text
stringlengths
28
881k
from pathlib import PathNEWLINENEWLINEimport pytestNEWLINENEWLINEnplg = pytest.importorskip("ome_types._napari_plugin")NEWLINENEWLINEDATA = Path(__file__).parent / "data"NEWLINENEWLINENEWLINE@pytest.mark.parametrize("fname", DATA.iterdir(), ids=lambda x: x.stem)NEWLINEdef test_widget(fname, qtbot):NEWLINE if fname.stem in ("bad.ome", "timestampannotation.ome"):NEWLINE pytest.xfail()NEWLINE nplg.OMETree(str(fname))NEWLINE
# -*- coding: utf-8 -*-NEWLINEfrom __future__ import unicode_literalsNEWLINENEWLINEfrom django.db import migrations, modelsNEWLINENEWLINEimport wagtail.core.fieldsNEWLINENEWLINENEWLINEclass Migration(migrations.Migration):NEWLINENEWLINE dependencies = [("puput", "0001_initial")]NEWLINENEWLINE operations = [NEWLINE migrations.AlterField(NEWLINE model_name="blogpage",NEWLINE name="description",NEWLINE field=models.CharField(NEWLINE max_length=255,NEWLINE help_text="The blog description that will appear under the title.",NEWLINE verbose_name="Description",NEWLINE blank=True,NEWLINE ),NEWLINE ),NEWLINE migrations.AlterField(NEWLINE model_name="category",NEWLINE name="description",NEWLINE field=models.CharField(max_length=500, verbose_name="Description", blank=True),NEWLINE ),NEWLINE migrations.AlterField(NEWLINE model_name="category",NEWLINE name="name",NEWLINE field=models.CharField(max_length=80, unique=True, verbose_name="Category name"),NEWLINE ),NEWLINE migrations.AlterField(NEWLINE model_name="category",NEWLINE name="parent",NEWLINE field=models.ForeignKey(NEWLINE to="puput.Category",NEWLINE related_name="children",NEWLINE null=True,NEWLINE verbose_name="Parent category",NEWLINE blank=True,NEWLINE on_delete=models.SET_NULL,NEWLINE ),NEWLINE ),NEWLINE migrations.AlterField(NEWLINE model_name="entrypage",NEWLINE name="excerpt",NEWLINE field=wagtail.core.fields.RichTextField(NEWLINE help_text="Entry excerpt to be displayed on entries list. If this field is not filled, a truncate version of body text will be used.",NEWLINE verbose_name="excerpt",NEWLINE blank=True,NEWLINE ),NEWLINE ),NEWLINE ]NEWLINE
from __future__ import annotationsNEWLINENEWLINEimport subprocessNEWLINEimport sysNEWLINEfrom urllib.parse import ParseResultNEWLINENEWLINEimport requestsNEWLINENEWLINEimport murfeyNEWLINENEWLINENEWLINEdef check(api_base: ParseResult, install: bool = True, force: bool = False):NEWLINE """NEWLINE Verify that the current client version can run against the selected server.NEWLINE If the version number is outside the allowed range then this can triggerNEWLINE an update on the client, and in that case will terminate the process.NEWLINE """NEWLINE version_check_url = api_base._replace(NEWLINE path="/version", query=f"client_version={murfey.__version__}"NEWLINE )NEWLINE server_reply = requests.get(version_check_url.geturl())NEWLINE if server_reply.status_code != 200:NEWLINE raise ValueError(f"Server unreachable ({server_reply.status_code})")NEWLINE versions = server_reply.json()NEWLINE if not install:NEWLINE returnNEWLINE print(NEWLINE f"Murfey {murfey.__version__} connected to Murfey server {versions['server']}"NEWLINE )NEWLINE if versions["client-needs-update"] or versions["client-needs-downgrade"]:NEWLINE # Proceed with mandatory installationNEWLINE if versions["client-needs-update"]:NEWLINE print("This version of Murfey must be updated before continuing.")NEWLINE if versions["client-needs-downgrade"]:NEWLINE print(NEWLINE "This version of Murfey is too new for the server and must be downgraded before continuing."NEWLINE )NEWLINE result = install_murfey(api_base, versions["server"])NEWLINE if result:NEWLINE print("\nMurfey has been updated. Please restart Murfey")NEWLINE exit()NEWLINE else:NEWLINE exit("Error occurred while updating Murfey")NEWLINENEWLINE if versions["server"] != murfey.__version__:NEWLINE if force:NEWLINE result = install_murfey(api_base, versions["server"])NEWLINE if result:NEWLINE print("\nMurfey has been updated. Please restart Murfey")NEWLINE exit()NEWLINE else:NEWLINE exit("Error occurred while updating Murfey")NEWLINE else:NEWLINE print("An update is available, install with 'murfey update'.")NEWLINENEWLINENEWLINEdef install_murfey(api_base: ParseResult, version: str) -> bool:NEWLINE """Install a specific version of the Murfey client.NEWLINE Return 'true' on success and 'false' on error."""NEWLINENEWLINE assert api_base.hostname is not NoneNEWLINE result = subprocess.run(NEWLINE [NEWLINE sys.executable,NEWLINE "-mpip",NEWLINE "install",NEWLINE "--trusted-host",NEWLINE api_base.hostname,NEWLINE "-i",NEWLINE api_base._replace(path="/pypi", query="").geturl(),NEWLINE f"murfey[client]=={version}",NEWLINE ]NEWLINE )NEWLINE return result.returncode == 0NEWLINE
from django.conf import settingsNEWLINEfrom django.conf.urls.defaults import *NEWLINEfrom django.contrib import adminNEWLINEimport loggingNEWLINElog = logging.getLogger('satchmo_store.urls')NEWLINENEWLINE# discover all admin modules - if you override this for yourNEWLINE# own base URLs, you'll need to autodiscover there.NEWLINEadmin.autodiscover()NEWLINENEWLINEurlpatterns = getattr(settings, 'URLS', [])NEWLINENEWLINEadminpatterns = patterns('',NEWLINE (r'^admin/(.*)', admin.site.root),NEWLINE)NEWLINENEWLINEif urlpatterns:NEWLINE urlpatterns += adminpatternsNEWLINEelse:NEWLINE urlpatterns = adminpatternsNEWLINENEWLINE#The following is used to serve up local media files like imagesNEWLINEif getattr(settings, 'LOCAL_DEV', False):NEWLINE log.debug("Adding local serving of static files at: %s", settings.MEDIA_ROOT)NEWLINE baseurlregex = r'^static/(?P<path>.*)$' NEWLINE urlpatterns += patterns('',NEWLINE (baseurlregex, 'django.views.static.serve',NEWLINE {'document_root': settings.MEDIA_ROOT}),NEWLINE NEWLINE (r'^site_media/(.*)$', 'django.views.static.serve', NEWLINE {'document_root': settings.MEDIA_ROOT}), NEWLINE )NEWLINENEWLINENEWLINE
def test_fixture(postgresql_instance):NEWLINE assert hasattr(postgresql_instance, 'port')NEWLINE
#!/usr/bin/pythonNEWLINENEWLINE__author__ = 'vilelag'NEWLINENEWLINEimport osNEWLINEimport argparseNEWLINEimport subprocessNEWLINEfrom multiprocessing import PoolNEWLINEimport itertoolsNEWLINEfrom sklearn.decomposition import PCANEWLINEimport numpy as npNEWLINEimport matplotlib.pyplot as pltNEWLINEfrom numpy.linalg import matrix_rankNEWLINEimport shutilNEWLINEfrom matplotlib import cmNEWLINEfrom matplotlib import patheffectsNEWLINEfrom numpy.ma import masked_arrayNEWLINENEWLINENEWLINEdef create_parsers():NEWLINE #parser for the main programNEWLINE parser = argparse.ArgumentParser(description='PCA analysis and Rank analysis of all cases or only 'NEWLINE 'the successful cases.\n For examples check ./Tests/var_*/run_all.sh')NEWLINE parser.add_argument('-nocaw', metavar='[<int>]', nargs='?', default=0, type=int, const=1,NEWLINE help='If present all the cases in the <test_file> will be used in the PCA analysis')NEWLINE parser.add_argument('-caw', metavar='<compute-accuracy-w_exec>', default='./word2vec/compute-accuracy-w',NEWLINE help='Path to the compute-accuracy-w executable')NEWLINE parser.add_argument('-test', metavar='<test_file>', default='./word2vec/questions-words.txt',NEWLINE help='Use text data from <test_file> to test the model')NEWLINE parser .add_argument('-bin', metavar='<file.bin>',NEWLINE help='Word representation dictionary in binary mode', required=False)NEWLINE parser .add_argument('-text', metavar='<file.bin>', required=True,NEWLINE help='Word representation dictionary in "text" mode')NEWLINE parser .add_argument('-folder', metavar='<folder>', default='./pcaImages',NEWLINE help='Folder where all the generated images will be saved')NEWLINE parser.add_argument('-threads', metavar='<int>', nargs=1, default=[8], type=int,NEWLINE help='Use <int> threads (default 8)')NEWLINE parser.add_argument('-t', metavar='<int>', nargs=1, default=[30000], type=int,NEWLINE help='Threshold is used to reduce vocabulary of the model for fast approximate evaluation 'NEWLINE '(0 = off, otherwise typical value is 30000, default=30000)')NEWLINE parser.add_argument('-pdf', metavar='<int>', default=1, type=int,NEWLINE help='Decide if the generated tex will be transformed in a pdf (1 = On, else Off, Default: On)')NEWLINE return parserNEWLINENEWLINENEWLINEdef create_output_folder(directory):NEWLINE if not os.path.exists(directory):NEWLINE os.makedirs(directory)NEWLINENEWLINENEWLINEdef run_ca(ca, file, threshold, test):NEWLINE out = subprocess.check_output([ca, file, threshold], stdin=open(test, 'r'))NEWLINE return outNEWLINENEWLINENEWLINEdef analyse_log(log):NEWLINE classes = dict()NEWLINE results = dict()NEWLINE current_class = ''NEWLINE case = 1NEWLINE for line in log.splitlines()[:-1]:NEWLINE spt = line.split("\\;")NEWLINE # if len(line.split(":")) == 2 and line.split(":")[1] == '':NEWLINE if len(spt) == 1 and line[-1] == ':':NEWLINE current_class = line[:-1]NEWLINE elif len(spt) == 4:NEWLINE try:NEWLINE classes[current_class].append(spt)NEWLINE except KeyError:NEWLINE classes[current_class] = [spt]NEWLINE else:NEWLINE if case == 1:NEWLINE results[current_class] = [float(line.split(" ")[2])]NEWLINE case = 0NEWLINE else:NEWLINE tmp = line.split(" ")NEWLINE ta = float(tmp[2])NEWLINE sem = float(tmp[8])NEWLINE syn = float(tmp[14])NEWLINE results[current_class].extend([ta, sem, syn])NEWLINE case = 1NEWLINE return classes, resultsNEWLINENEWLINENEWLINEdef get_raw_classes(test):NEWLINE with open(test) as f:NEWLINE content = f.read().splitlines()NEWLINE classes = dict()NEWLINE current_class = ''NEWLINE for line in content:NEWLINE spt = line.split(' ')NEWLINE if len(spt) == 2 and spt[0] == ':':NEWLINE current_class = spt[-1]NEWLINE elif len(spt) == 4:NEWLINE spt = [x.upper() for x in spt]NEWLINE try:NEWLINE classes[current_class].append(spt)NEWLINE except KeyError:NEWLINE classes[current_class] = [spt]NEWLINE return classesNEWLINENEWLINENEWLINEdef read_bin_in_text_mode(path, threshold):NEWLINE with open(path) as f:NEWLINE content = f.read().splitlines()NEWLINE data = dict()NEWLINE words, size = content[0].split(' ')NEWLINE words = int(words)NEWLINE size = int(size)NEWLINENEWLINE if 0 < threshold < words:NEWLINE words = thresholdNEWLINE print wordsNEWLINE for i in range(1, words+1):NEWLINE temp = content[i].split(' ')NEWLINE data[temp[0].upper()] = np.asarray([float(x) for x in temp[1:-1]])NEWLINE # NormalizingNEWLINE data[temp[0].upper()] *= 1 / np.linalg.norm(data[temp[0].upper()])NEWLINENEWLINE return dataNEWLINENEWLINENEWLINEdef get_words_without_repetition(data):NEWLINE class_1 = []NEWLINE dic_words = dict()NEWLINE for i in [0, 2]:NEWLINE for datum in data:NEWLINE try:NEWLINE if dic_words[datum[i]+';'+datum[i+1]]:NEWLINE continueNEWLINE except KeyError:NEWLINE dic_words[datum[i]+';'+datum[i+1]] = TrueNEWLINE class_1.append([datum[i], datum[i+1]])NEWLINENEWLINE return class_1NEWLINENEWLINENEWLINEdef pca_analyse(atuple, confidence_interval=0.9):NEWLINE class_name, data = atupleNEWLINE data = get_words_without_repetition(data)NEWLINE class_representation = []NEWLINE for c in data:NEWLINE try:NEWLINE class_representation.append(wr[c[1]] - wr[c[0]])NEWLINE except KeyError:NEWLINE passNEWLINE class_representation = np.array(class_representation)NEWLINE pca = PCA(n_components=confidence_interval)NEWLINE pca.fit(class_representation)NEWLINENEWLINE return class_name, pca.n_components, len(data)NEWLINENEWLINENEWLINEdef generate_npc_figure(n_pc):NEWLINENEWLINE y = np.arange(len(n_pc))NEWLINENEWLINE names = tuple((e[0] for e in reversed(n_pc)))NEWLINE components = np.array([e[1] for e in reversed(n_pc)])NEWLINE comp_div_pair = np.array([float(e[1])/e[2] for e in reversed(n_pc)])NEWLINE # print n_pcNEWLINE # print comp_div_pairNEWLINENEWLINE fig, (ax0, ax1) = plt.subplots(1, 2, sharey=True, figsize=(18, 16))NEWLINENEWLINE ax0.barh(y, components, align='center', alpha=0.4)NEWLINE plt.yticks(y, names)NEWLINE ax0.set_xlabel("Number of components")NEWLINE ax0.set_title("Number of components required to get a confidence interval of 90%")NEWLINE ax0.grid()NEWLINENEWLINE ax1.barh(y, comp_div_pair, align='center', color='g', alpha=0.4)NEWLINE ax1.set_xlabel("Number of components / number of pairs")NEWLINE ax1.set_title("Number of components divided by number of pairs in the class")NEWLINE ax1.grid()NEWLINENEWLINE ax1.set_xlim([0, 1])NEWLINENEWLINE ax0.yaxis.set_ticks_position('left')NEWLINE ax0.xaxis.set_ticks_position('bottom')NEWLINE ax1.yaxis.set_ticks_position('left')NEWLINE ax1.xaxis.set_ticks_position('bottom')NEWLINENEWLINE plt.savefig(folder+'/ncomponents.png', bbox_inches='tight', transparent=False)NEWLINE plt.close()NEWLINENEWLINENEWLINEdef pca_analyse2(atuple, link=True):NEWLINENEWLINE class_name, data = atupleNEWLINE n_success = len(data)NEWLINE data = get_words_without_repetition(data)NEWLINE class_1 = []NEWLINE class_2 = []NEWLINE for c in data:NEWLINE try:NEWLINE t1 = wr[c[0]]NEWLINE except KeyError:NEWLINE t1 = NoneNEWLINE try:NEWLINE t2 = wr[c[1]]NEWLINE except KeyError:NEWLINE t2 = NoneNEWLINE if t1 is not None and t2 is not None:NEWLINE class_1.append(t1)NEWLINE class_2.append(t2)NEWLINENEWLINE class_1 = np.array(class_1)NEWLINE class_2 = np.array(class_2)NEWLINENEWLINE pca = PCA(n_components=2)NEWLINE pca2 = PCA(n_components=2)NEWLINENEWLINE X_1 = pca.fit(class_1).transform(class_1)NEWLINE X_2 = pca2.fit(class_2).transform(class_2)NEWLINE print class_nameNEWLINENEWLINE plt.figure(figsize=(16, 9))NEWLINENEWLINE plt.scatter(X_1[:, 0], X_1[:, 1], c='r', marker='o')NEWLINE plt.scatter(X_2[:, 0], X_2[:, 1], c='b', marker='^')NEWLINENEWLINE # creating links between data1 and data2NEWLINE if link:NEWLINE for i in range(len(X_1)):NEWLINE plt.plot([X_1[i][0], X_2[i][0]], [X_1[i][1], X_2[i][1]], c='gray')NEWLINENEWLINE plt.xlabel("1st PC")NEWLINE plt.ylabel("2nd PC")NEWLINE plt.title('PCA with 2 PC for {}'.format(class_name))NEWLINE plt.figtext(0.1, -0.01, "Number of success cases: {0:<5} Number of combinations: {1}\nFirst explained variance "NEWLINE "ration: {2}\nSecond explained variance ration: {3}".format(NEWLINE n_success, len(data), pca.explained_variance_ratio_, pca2.explained_variance_ratio_))NEWLINE plt.savefig(folder+'/'+class_name+'.png', bbox_inches='tight', transparent=False)NEWLINE plt.close()NEWLINENEWLINENEWLINEdef pca_analyse_all(all_tuples, confidence_interval=0.9):NEWLINE data = []NEWLINE for cn, datum in all_tuples:NEWLINE datum = get_words_without_repetition(datum)NEWLINE for el in datum:NEWLINE try:NEWLINE data.append(wr[el[1]] - wr[el[0]])NEWLINE except KeyError:NEWLINE passNEWLINENEWLINE data = np.array(data)NEWLINENEWLINE pca = PCA()NEWLINE pca.fit(data)NEWLINENEWLINE ci, n = 0, 0NEWLINE for var in pca.explained_variance_ratio_:NEWLINE ci += varNEWLINE n += 1NEWLINE if ci > confidence_interval:NEWLINE breakNEWLINENEWLINENEWLINE plt.figure(figsize=(16, 9))NEWLINE plt.plot(pca.explained_variance_ratio_)NEWLINE #adding confidence_interval vlineNEWLINE plt.axvline(x=n-1, c='k', linestyle='--')NEWLINE plt.xticks(list(plt.xticks()[0]) + [n-1])NEWLINE yl = plt.ylim()NEWLINE plt.annotate("Number of components\nto {0:.0%} of the distribution".format(confidence_interval),NEWLINE (n-1, (yl[1]-yl[0])/2), ((n-1)/2, (yl[1]-yl[0])/1.6), arrowprops=dict(arrowstyle='->'))NEWLINE plt.xlabel("Principal Component")NEWLINE plt.ylabel("Explained Variance Ratio")NEWLINE plt.title("Explained variance ratio for all the success data")NEWLINE plt.savefig(folder+'/evr_all.png', bbox_inches='tight', transparent=False)NEWLINE plt.close()NEWLINENEWLINENEWLINEdef pca_analyse_all_mean(all_tuples, confidence_interval=0.9):NEWLINENEWLINE data = []NEWLINE for cn, datum in all_tuples:NEWLINE tmp_data = []NEWLINE datum = get_words_without_repetition(datum)NEWLINE for el in datum:NEWLINE try:NEWLINE tmp_data.append(wr[el[1]] - wr[el[0]])NEWLINE except KeyError:NEWLINE passNEWLINE data.append(np.array(tmp_data).mean(axis=0))NEWLINE data = np.array(data)NEWLINENEWLINE pca = PCA()NEWLINE pca.fit(data)NEWLINENEWLINE ci, n = 0, 0NEWLINE for var in pca.explained_variance_ratio_:NEWLINE ci += varNEWLINE n += 1NEWLINE if ci > confidence_interval:NEWLINE breakNEWLINENEWLINENEWLINE plt.figure(figsize=(16, 9))NEWLINE plt.plot(pca.explained_variance_ratio_)NEWLINE #adding confidence_interval vlineNEWLINE plt.axvline(x=n-1, c='k', linestyle='--')NEWLINE plt.xticks(list(plt.xticks()[0]) + [n-1])NEWLINE yl = plt.ylim()NEWLINE plt.annotate("Number of components\nto {0:.0%} of the distribution".format(confidence_interval),NEWLINE (n-1, (yl[1]-yl[0])/2), ((n-1)/2, (yl[1]-yl[0])/1.6), arrowprops=dict(arrowstyle='->'))NEWLINE plt.xlabel("Principal Component")NEWLINE plt.ylabel("Explained Variance Ratio")NEWLINE plt.title("Explained variance ratio for the mean of each success in a test class")NEWLINE plt.figtext(0.1, -0.01, "Matrix rank: {0}".format(NEWLINE matrix_rank(data)))NEWLINE plt.savefig(folder+'/evr_mean_all.png', bbox_inches='tight', transparent=False)NEWLINE plt.close()NEWLINENEWLINENEWLINEdef pca_analyse_combination(data, confidence_interval=0.9):NEWLINENEWLINE data = get_words_without_repetition(data)NEWLINE class_1 = []NEWLINE for c in data:NEWLINE try:NEWLINE class_1.append(wr[c[1]] - wr[c[0]])NEWLINE except KeyError:NEWLINE passNEWLINE class_1 = np.array(class_1)NEWLINENEWLINE pca = PCA(n_components=confidence_interval)NEWLINENEWLINE pca.fit(class_1)NEWLINENEWLINE return pca.n_componentsNEWLINENEWLINENEWLINEdef rank_analyse_combination(data):NEWLINENEWLINE data = get_words_without_repetition(data)NEWLINE class_1 = []NEWLINE for c in data:NEWLINE try:NEWLINE class_1.append(wr[c[1]] - wr[c[0]])NEWLINE except KeyError:NEWLINE passNEWLINE class_1 = np.array(class_1)NEWLINENEWLINE rank = matrix_rank(class_1)NEWLINE return rankNEWLINENEWLINENEWLINEdef get_element(p_matrix, i, j):NEWLINE if i == j:NEWLINE return str(p_matrix[i][j])NEWLINE sum = p_matrix[i][i] + p_matrix[j][j]NEWLINE comb = p_matrix[i][j]NEWLINE if comb == sum:NEWLINE return str('\\cellcolor{{green!40}} {}'.format(comb))NEWLINE elif 0.9*sum < comb < 1.1*sum:NEWLINE return str('\\cellcolor{{yellow!40}} {}'.format(comb))NEWLINE elif 1.1*sum <= comb:NEWLINE return str('\\cellcolor{{orange!40}} {}'.format(comb))NEWLINE else: #comb <= 0.9*sumNEWLINE return str('\\cellcolor{{red!40}} {}'.format(comb))NEWLINENEWLINENEWLINEdef do_line(fd, p_matrix, class_names, i):NEWLINE if i == 0:NEWLINE t_str = ['&'] + [" \\textbf{{{}}} &".format(name) for name in class_names[:-1]] + \NEWLINE [' \\textbf{{{}}} \\\\ \\hline\n'.format(class_names[-1])]NEWLINE t_str = ''.join(t_str)NEWLINE else:NEWLINE t_str = ['\\textbf{{{}}} &'.format(class_names[i-1])] + [" {} &".format(get_element(p_matrix, i-1, j))NEWLINE for j in range(len(p_matrix)-1)] + \NEWLINE [' {} \\\\ \\hline\n'.format(get_element(p_matrix, i-1, len(p_matrix)-1))]NEWLINE t_str = ''.join(t_str)NEWLINE fd.write(t_str)NEWLINENEWLINENEWLINEdef generate_latex(class_names, class_names_bak, p_matrix, fname='overlaps'):NEWLINE fd = open(folder+"/{}.tex".format(fname), "w")NEWLINE fd.write("\\documentclass{report}\n")NEWLINE fd.write("\\usepackage{amsmath, amssymb, array, stackengine, subfig}\n")NEWLINE fd.write("\\usepackage[table]{xcolor}\n")NEWLINE fd.write("\\usepackage[top=2in, bottom=1.5in, left=1cm, right=1cm]{geometry}\n")NEWLINE c_width = '{:.3f}\\textwidth'.format(float(0.5)/(len(class_names)))NEWLINE fd.write("\\newcolumntype{{C}}{{>{{\\centering\\let\\newline\\\\\\arraybackslash\\hspace{{0pt}}}}m{{{}}}}}\n".format(NEWLINE c_width))NEWLINE fd.write("\\begin{document}\n")NEWLINENEWLINE # First tableNEWLINE fd.write('\\begin{tabular}{')NEWLINE tstr = ['|'] + ['C|']*(len(class_names)+1)NEWLINE tstr = ''.join(tstr)NEWLINE fd.write(tstr+'}\n')NEWLINE fd.write("\\hline\n")NEWLINE fd.write("\\multicolumn{{{}}}{{|c|}}{{\\textbf{{Number of required components to represent each combination}}}}"NEWLINE " \\\\ \\hline\n".format(len(class_names)+1))NEWLINE for i in range(len(class_names)+1):NEWLINE do_line(fd, p_matrix, class_names, i)NEWLINE fd.write('\\end{tabular}\n')NEWLINENEWLINE #Creating 'captions'NEWLINE fd.write("\\begin{figure}[h]\n")NEWLINE # First captionNEWLINE fd.write('\\belowbaseline[0pt]{\n\\subfloat{\n\\begin{tabular}{|c|l|}\n')NEWLINE fd.write('\\hline\n')NEWLINE fd.write('\\multicolumn{2}{|c|}{\\textbf{Label}} \\\\ \\hline\n')NEWLINE for i in range(len(class_names)):NEWLINE fd.write('\\textbf{{{}}} & {} \\\\ \\hline\n'.format(class_names[i], class_names_bak[i]))NEWLINE fd.write('\\end{tabular}\n}}\n')NEWLINE # Second captionNEWLINE fd.write('\\belowbaseline[0pt]{\n\\subfloat{\n')NEWLINE fd.write('\\begin{tabular}{|C|l|}\n\\hline\n')NEWLINE fd.write('\\multicolumn{2}{|c|}{\\textbf{Color Meaning}} \\\\ \\hline\n')NEWLINE fd.write(' & Class alone \\\\ \\hline\n')NEWLINE fd.write('\\cellcolor{green!40}& $Combination = Sum$ \\\\ \\hline\n')NEWLINE fd.write('\\cellcolor{yellow!40}& $0.9 Sum < Combination < 1.1 Sum$ \\\\ \\hline\n')NEWLINE fd.write('\\cellcolor{red!40}& $Combination \\leq 0.9 Sum$ \\\\ \\hline\n')NEWLINE fd.write('\\cellcolor{orange!40}& $Combination \\geq 1.1 Sum$ \\\\ \\hline\n')NEWLINE fd.write('\\end{tabular}\n}}\n')NEWLINE fd.write('\\end{figure}\n\n')NEWLINENEWLINE fd.write('\\end{document}\n')NEWLINE fd.close()NEWLINENEWLINENEWLINEdef generate_pdf(fname='overlaps'):NEWLINE subprocess.call(['pdflatex', '{0}/{1}.tex'.format(folder, fname)])NEWLINE #remove auxiliary filesNEWLINE os.remove('{0}.aux'.format(fname))NEWLINE os.remove('{0}.log'.format(fname))NEWLINE shutil.move('{}.pdf'.format(fname), '{0}/{1}.pdf'.format(folder, fname))NEWLINENEWLINENEWLINEdef analyse_combinations(classes, pool, n_pc, pdf, rank=True):NEWLINE combinations = [i for i in itertools.combinations(range(len(classes)), 2)]NEWLINE class_names = sorted(classes)NEWLINE parallel_list2 = [classes[class_names[k[0]]] + classes[class_names[k[1]]] for k in combinations]NEWLINENEWLINE # PCANEWLINE n_pc_comb = pool.map(pca_analyse_combination, parallel_list2)NEWLINE p_matrix = [[0]*len(class_names) for i in class_names]NEWLINE for i, comb in enumerate(combinations):NEWLINE p_matrix[comb[0]][comb[1]] = n_pc_comb[i]NEWLINE p_matrix[comb[1]][comb[0]] = n_pc_comb[i]NEWLINENEWLINE class_names_bak = class_namesNEWLINE class_names = [str(i) for i in range(len(class_names))]NEWLINE for i in range(len(class_names)):NEWLINE p_matrix[i][i] = n_pc[i][1]NEWLINENEWLINE title = "Number of required components to represent each combination divided by the sum of its elements " \NEWLINE "components' number"NEWLINE generate_combinations_img(class_names, class_names_bak, p_matrix, title, fname='pca_overlaps_img')NEWLINE generate_latex(class_names, class_names_bak, p_matrix, fname='pca_overlaps')NEWLINENEWLINE if pdf == 1:NEWLINE generate_pdf(fname='pca_overlaps')NEWLINENEWLINE # Matrix rankNEWLINE if rank:NEWLINE n_rk_comb = pool.map(rank_analyse_combination, parallel_list2)NEWLINENEWLINE parallel_list3 = [classes[class_names_bak[i]] for i in range(len(classes))]NEWLINE n_rk_comb_2 = pool.map(rank_analyse_combination, parallel_list3)NEWLINENEWLINENEWLINE p_matrix = [[0]*len(class_names) for i in class_names]NEWLINE for i, comb in enumerate(combinations):NEWLINE p_matrix[comb[0]][comb[1]] = n_rk_comb[i]NEWLINE p_matrix[comb[1]][comb[0]] = n_rk_comb[i]NEWLINENEWLINE for i in range(len(class_names)):NEWLINE p_matrix[i][i] = n_rk_comb_2[i]NEWLINENEWLINE title = "Matrix rank to represent each combination divided by the sum of its elements rank"NEWLINE generate_combinations_img(class_names, class_names_bak, p_matrix, title, fname='rank_overlaps_img')NEWLINE generate_latex(class_names, class_names_bak, p_matrix, fname='rank_overlaps')NEWLINE if pdf == 1:NEWLINE generate_pdf(fname='rank_overlaps')NEWLINENEWLINENEWLINEdef generate_combinations_img(class_names, class_names_bak, p_matrix, title, fname='overlaps_img'):NEWLINE a_size = len(p_matrix)NEWLINENEWLINE diff = np.zeros([a_size, a_size])NEWLINENEWLINE for i in xrange(a_size):NEWLINE for j in xrange(a_size):NEWLINE if i == j:NEWLINE passNEWLINE else:NEWLINE _sum = p_matrix[i][i] + p_matrix[j][j]NEWLINE comb = p_matrix[i][j]NEWLINE diff[i][j] = float(comb)/float(_sum)NEWLINENEWLINE fig = plt.figure(figsize=(16, 9))NEWLINE ax = fig.add_subplot(111)NEWLINENEWLINE diffa = masked_array(diff, diff != 0)NEWLINE diffb = masked_array(diff, diff == 0)NEWLINENEWLINE cax = ax.imshow(diffb, cmap=cm.winter, interpolation='None', origin='lower', aspect='auto')NEWLINE cba = plt.colorbar(cax, format='%.1f')NEWLINENEWLINE caxb = ax.imshow(diffa, cmap=cm.Reds, interpolation='None', origin='lower', aspect='auto')NEWLINENEWLINE plt.xticks(range(a_size))NEWLINE ax.set_xticklabels(class_names_bak)NEWLINE plt.xticks(rotation=80)NEWLINENEWLINE plt.yticks(range(a_size))NEWLINE ax.set_yticklabels(class_names_bak)NEWLINENEWLINE for i in xrange(a_size):NEWLINE for j in xrange(a_size):NEWLINE ax.text(j, i, '{0}/{1:.2f}'.format(p_matrix[i][j], diff[i][j]),NEWLINE size='medium', ha='center', va='center',NEWLINE path_effects=[patheffects.withSimplePatchShadow(shadow_rgbFace=(1, 1, 1))])NEWLINENEWLINE plt.title(title)NEWLINENEWLINENEWLINE # bar = fig.colorbar(cax, format='%.1f')NEWLINE plt.rc('text', usetex=True)NEWLINE cba.set_label('$\\frac{a_{i,j}}{a_{i,i}+a_{j,j}}$', fontsize=25, rotation=0, labelpad=40)NEWLINE plt.savefig(folder+'/'+fname, bbox_inches='tight', transparent=False)NEWLINE plt.close()NEWLINENEWLINENEWLINEdef main():NEWLINE global folderNEWLINE global wrNEWLINE parser = create_parsers()NEWLINE args = vars(parser.parse_args())NEWLINE caw = args['caw']NEWLINE test = args['test']NEWLINE bin = args['bin']NEWLINE text_bin = args['text']NEWLINE threads = args['threads'][0]NEWLINE threshold = str(args['t'][0])NEWLINE folder = args['folder']NEWLINE pdf = args['pdf']NEWLINE nocaw = args['nocaw']NEWLINENEWLINE create_output_folder(folder)NEWLINE if nocaw == 0:NEWLINE run_output = run_ca(caw, bin, threshold, test)NEWLINE classes, results = analyse_log(run_output)NEWLINE else:NEWLINE classes = get_raw_classes(test)NEWLINENEWLINE wr = read_bin_in_text_mode(text_bin, int(threshold))NEWLINENEWLINE parallel_list = [(k, classes[k]) for k in sorted(classes)]NEWLINENEWLINE pool = Pool(threads)NEWLINENEWLINE n_pc = pool.map(pca_analyse, parallel_list)NEWLINE generate_npc_figure(n_pc)NEWLINENEWLINE pool.map(pca_analyse2, parallel_list)NEWLINENEWLINE pca_analyse_all(parallel_list)NEWLINE pca_analyse_all_mean(parallel_list)NEWLINENEWLINE analyse_combinations(classes, pool, n_pc, pdf)NEWLINENEWLINENEWLINEfolder = ''NEWLINEwr = dict()NEWLINEmain()
import pkgutilNEWLINEimport insightsNEWLINEimport jsonNEWLINENEWLINE# from insights.client.config import InsightsConfigNEWLINEfrom insights.client.collection_rules import InsightsUploadConfNEWLINEfrom mock.mock import patch, MockNEWLINEfrom insights.specs.default import DefaultSpecsNEWLINEfrom insights.specs.sos_archive import SosSpecsNEWLINEfrom insights.client.map_components import (map_rm_conf_to_components,NEWLINE _search_uploader_json,NEWLINE _get_component_by_symbolic_name)NEWLINENEWLINEuploader_json_file = pkgutil.get_data(insights.__name__, "client/uploader_json_map.json")NEWLINEuploader_json = json.loads(uploader_json_file)NEWLINEdefault_specs = vars(DefaultSpecs).keys()NEWLINEsos_specs = vars(SosSpecs).keys()NEWLINENEWLINENEWLINE@patch('insights.client.collection_rules.InsightsUploadConf.load_redaction_file', Mock(return_value={'test': 'test'}))NEWLINE@patch('insights.client.collection_rules.InsightsUploadConf.get_rm_conf_old', Mock(return_value={'test': 'test'}))NEWLINE@patch('insights.client.collection_rules.map_rm_conf_to_components')NEWLINEdef test_called_when_core_collection_enabled(map_rm_conf_to_components):NEWLINE '''NEWLINE Verify that the function is called from get_rm_conf when core_collect=TrueNEWLINE '''NEWLINE upload_conf = InsightsUploadConf(Mock(core_collect=True))NEWLINE upload_conf.get_rm_conf()NEWLINE map_rm_conf_to_components.assert_called_once_with({'test': 'test'})NEWLINENEWLINENEWLINE@patch('insights.client.collection_rules.InsightsUploadConf.load_redaction_file', Mock(return_value={'test': 'test'}))NEWLINE@patch('insights.client.collection_rules.InsightsUploadConf.get_rm_conf_old', Mock(return_value={'test': 'test'}))NEWLINE@patch('insights.client.collection_rules.map_rm_conf_to_components')NEWLINEdef test_not_called_when_core_collection_disabled(map_rm_conf_to_components):NEWLINE '''NEWLINE Verify that the function is not called from get_rm_conf when core_collect=FalseNEWLINE '''NEWLINE upload_conf = InsightsUploadConf(Mock(core_collect=False))NEWLINE upload_conf.get_rm_conf()NEWLINE map_rm_conf_to_components.assert_not_called()NEWLINENEWLINENEWLINEdef test_get_component_by_symbolic_name():NEWLINE '''NEWLINE Verify that all symbolic names in uploader.json can be mappedNEWLINE to valid components as prescribed in the conversion functionNEWLINE '''NEWLINE # some specs have been removed for core release so because they eitherNEWLINE # A) do not appear in uploader.json, orNEWLINE # B) DO appear in uploader.json, but have no associated rulesNEWLINE # Filter out the (B) specs with this listNEWLINE skipped_specs = [NEWLINE 'ceph_osd_df',NEWLINE 'gluster_peer_status',NEWLINE 'gluster_v_status',NEWLINE 'heat_crontab',NEWLINE 'httpd_on_nfs',NEWLINE 'ls_usr_sbin',NEWLINE 'lvmconfig',NEWLINE 'nova_migration_uid',NEWLINE 'ntpq_pn',NEWLINE 'rabbitmq_queues',NEWLINE 'rhev_data_center',NEWLINE 'root_crontab',NEWLINE 'yum_list_installed',NEWLINE 'zdump_v',NEWLINE 'cni_podman_bridge_conf',NEWLINE 'cobbler_modules_conf',NEWLINE 'cobbler_settings',NEWLINE 'cpu_smt_control',NEWLINE 'cpu_vulns_meltdown',NEWLINE 'cpu_vulns_spectre_v1',NEWLINE 'cpu_vulns_spectre_v2',NEWLINE 'cpu_vulns_spec_store_bypass',NEWLINE 'docker_storage',NEWLINE 'freeipa_healthcheck_log',NEWLINE 'ironic_conf',NEWLINE 'octavia_conf',NEWLINE 'rhn_entitlement_cert_xml',NEWLINE 'rhn_hibernate_conf',NEWLINE 'rhn_schema_version',NEWLINE 'rhn_search_daemon_log',NEWLINE 'rhn_taskomatic_daemon_log',NEWLINE 'rhosp_release',NEWLINE 'secure',NEWLINE 'foreman_tasks_config',NEWLINE 'ssh_foreman_config',NEWLINE 'swift_conf',NEWLINE 'sys_kernel_sched_features',NEWLINE 'sysconfig_memcached',NEWLINE 'sysconfig_mongod',NEWLINE 'systemd_system_origin_accounting',NEWLINE 'tuned_conf',NEWLINE 'vdsm_conf',NEWLINE 'vdsm_id',NEWLINE 'neutron_ml2_conf',NEWLINE 'sap_host_profile',NEWLINE 'sched_rt_runtime_us',NEWLINE 'libvirtd_qemu_log',NEWLINE 'mlx4_port',NEWLINE 'qpid_stat_g',NEWLINE 'lsinitrd'NEWLINE ]NEWLINENEWLINE # first, make sure our list is proper and one of theseNEWLINE # are in the default specsNEWLINE for s in skipped_specs:NEWLINE assert s not in default_specsNEWLINENEWLINE for category in ['commands', 'files', 'globs']:NEWLINE for entry in uploader_json[category]:NEWLINE full_component = _get_component_by_symbolic_name(entry['symbolic_name'])NEWLINENEWLINE if full_component is None:NEWLINE # this entry should not be in core, so assert that it's missingNEWLINE assert entry['symbolic_name'] not in default_specsNEWLINE continueNEWLINENEWLINE module, shortname = full_component.rsplit('.', 1)NEWLINENEWLINE # filter out specs without associated rulesNEWLINE if shortname in skipped_specs:NEWLINE continueNEWLINENEWLINE if module == "insights.specs.default.DefaultSpecs":NEWLINE assert shortname in default_specsNEWLINE elif module == "insights.specs.sos_archive.SosSpecs":NEWLINE assert shortname in sos_specsNEWLINE else:NEWLINE # invalid module nameNEWLINE assert FalseNEWLINENEWLINENEWLINEdef test_search_uploader_json():NEWLINE '''NEWLINE Verify that all valid input from an uploader.json-based remove.confNEWLINE will return a symbolic nameNEWLINE '''NEWLINE for cmd in uploader_json['commands']:NEWLINE assert _search_uploader_json(['commands'], cmd['command'])NEWLINE assert _search_uploader_json(['commands'], cmd['symbolic_name'])NEWLINE for fil in uploader_json['files']:NEWLINE assert _search_uploader_json(['files', 'globs'], fil['file'])NEWLINE assert _search_uploader_json(['files', 'globs'], fil['symbolic_name'])NEWLINE for glb in uploader_json['globs']:NEWLINE assert _search_uploader_json(['files', 'globs'], glb['symbolic_name'])NEWLINENEWLINENEWLINEdef test_search_uploader_json_invalid():NEWLINE '''NEWLINE Verify that invalid input will return NoneNEWLINE '''NEWLINE assert _search_uploader_json(['commands'], 'random value') is NoneNEWLINE assert _search_uploader_json(['files', 'globs'], 'random value') is NoneNEWLINENEWLINENEWLINEdef test_search_uploader_json_globs_symbolic_only():NEWLINE '''NEWLINE Verify that globs are matched by symbolic name onlyNEWLINE '''NEWLINE for glb in uploader_json['globs']:NEWLINE assert _search_uploader_json(['files', 'globs'], glb['glob']) is NoneNEWLINENEWLINENEWLINEdef test_map_rm_conf_to_components_sym_names():NEWLINE '''NEWLINE Verify that all symbolic names in uploader.json result asNEWLINE components in the outputNEWLINE '''NEWLINE # commandsNEWLINE for cmd in uploader_json['commands']:NEWLINE # run each possible command through the functionNEWLINE sym_name = cmd['symbolic_name']NEWLINE rm_conf = {'commands': [sym_name]}NEWLINE # figure out the destination name should beNEWLINE spec_name = _get_component_by_symbolic_name(sym_name)NEWLINE new_rm_conf = map_rm_conf_to_components(rm_conf)NEWLINE # commands should be empty, components should have 1 itemNEWLINE assert len(new_rm_conf['commands']) == 0NEWLINE assert len(new_rm_conf['components']) == 1NEWLINE assert new_rm_conf['components'][0] == spec_nameNEWLINENEWLINE # filesNEWLINE for fil in uploader_json['files']:NEWLINE # run each possible file through the functionNEWLINE sym_name = fil['symbolic_name']NEWLINE rm_conf = {'files': [sym_name]}NEWLINE # figure out the destination name should beNEWLINE spec_name = _get_component_by_symbolic_name(sym_name)NEWLINE new_rm_conf = map_rm_conf_to_components(rm_conf)NEWLINE # files should be empty, components should have 1 itemNEWLINE # except for these which cannot be mapped to specs.NEWLINE # in which case, components empty and these remain in filesNEWLINE if sym_name in ['grub2_efi_grubenv',NEWLINE 'grub2_grubenv',NEWLINE 'redhat_access_proactive_log']:NEWLINE assert len(new_rm_conf['files']) == 1NEWLINE assert new_rm_conf['files'][0] == sym_nameNEWLINE assert len(new_rm_conf['components']) == 0NEWLINE else:NEWLINE assert len(new_rm_conf['files']) == 0NEWLINE assert len(new_rm_conf['components']) == 1NEWLINE assert new_rm_conf['components'][0] == spec_nameNEWLINENEWLINE # globsNEWLINE for glb in uploader_json['globs']:NEWLINE # run each possible glob through the functionNEWLINE sym_name = glb['symbolic_name']NEWLINE rm_conf = {'files': [sym_name]}NEWLINE # figure out the destination name should beNEWLINE spec_name = _get_component_by_symbolic_name(sym_name)NEWLINE new_rm_conf = map_rm_conf_to_components(rm_conf)NEWLINE # files should be empty, components should have 1 itemNEWLINE assert len(new_rm_conf['files']) == 0NEWLINE assert len(new_rm_conf['components']) == 1NEWLINE assert new_rm_conf['components'][0] == spec_nameNEWLINENEWLINENEWLINEdef test_map_rm_conf_to_components_raw_cmds_files():NEWLINE '''NEWLINE Verify that all raw files/commands in uploader.json result asNEWLINE components in the outputNEWLINE '''NEWLINE # commandsNEWLINE for cmd in uploader_json['commands']:NEWLINE # run each possible command through the functionNEWLINE rm_conf = {'commands': [cmd['command']]}NEWLINE sym_name = cmd['symbolic_name']NEWLINE # figure out the destination name should beNEWLINE spec_name = _get_component_by_symbolic_name(sym_name)NEWLINE new_rm_conf = map_rm_conf_to_components(rm_conf)NEWLINE # commands should be empty, components should have 1 itemNEWLINE assert len(new_rm_conf['commands']) == 0NEWLINE assert len(new_rm_conf['components']) == 1NEWLINE assert new_rm_conf['components'][0] == spec_nameNEWLINENEWLINE # filesNEWLINE for fil in uploader_json['files']:NEWLINE # run each possible file through the functionNEWLINE rm_conf = {'files': [fil['file']]}NEWLINE sym_name = fil['symbolic_name']NEWLINE # figure out the destination name should beNEWLINE spec_name = _get_component_by_symbolic_name(sym_name)NEWLINE new_rm_conf = map_rm_conf_to_components(rm_conf)NEWLINE # files should be empty, components should have 1 itemNEWLINE # except for these which cannot be mapped to specs.NEWLINE # in which case, components empty and these remain in filesNEWLINE if fil['file'] in ['/boot/efi/EFI/redhat/grubenv',NEWLINE '/boot/grub2/grubenv',NEWLINE '/var/log/redhat_access_proactive/redhat_access_proactive.log']:NEWLINE assert len(new_rm_conf['files']) == 1NEWLINE assert new_rm_conf['files'][0] == fil['file']NEWLINE assert len(new_rm_conf['components']) == 0NEWLINE else:NEWLINE assert len(new_rm_conf['files']) == 0NEWLINE assert len(new_rm_conf['components']) == 1NEWLINE assert new_rm_conf['components'][0] == spec_nameNEWLINENEWLINENEWLINEdef test_map_rm_conf_to_components_invalid():NEWLINE '''NEWLINE Verify that matching commands/files are mapped to componentsNEWLINE '''NEWLINE rm_conf = {'commands': ['random', 'value'], 'files': ['other', 'invalid', 'data']}NEWLINE new_rm_conf = map_rm_conf_to_components(rm_conf)NEWLINE # rm_conf should be unchangedNEWLINE assert len(new_rm_conf['commands']) == 2NEWLINE assert len(new_rm_conf['files']) == 3NEWLINE assert len(new_rm_conf['components']) == 0NEWLINE assert new_rm_conf['commands'] == rm_conf['commands']NEWLINE assert new_rm_conf['files'] == rm_conf['files']NEWLINENEWLINENEWLINE@patch('insights.client.map_components._search_uploader_json')NEWLINEdef test_rm_conf_empty(_search_uploader_json):NEWLINE '''NEWLINE Verify the function returns rm_conf unchanged if calledNEWLINE with an empty dict or NoneNEWLINE '''NEWLINE rm_conf = {}NEWLINE new_rm_conf = map_rm_conf_to_components(rm_conf)NEWLINE _search_uploader_json.assert_not_called()NEWLINE assert new_rm_conf == {}NEWLINENEWLINE rm_conf = NoneNEWLINE new_rm_conf = map_rm_conf_to_components(rm_conf)NEWLINE _search_uploader_json.assert_not_called()NEWLINE assert new_rm_conf is NoneNEWLINENEWLINENEWLINE@patch('insights.client.map_components.logger.warning')NEWLINEdef test_log_long_key(logger_warning):NEWLINE '''NEWLINE Verify the conversion table is logged with properNEWLINE spacing, wrapping, and unconverted specs are not loggedNEWLINE '''NEWLINE rm_conf = {'commands': ["/usr/bin/find /etc/origin/node /etc/origin/master /etc/pki /etc/ipa -type f -exec /usr/bin/openssl x509 -noout -enddate -in '{}' \\; -exec echo 'FileName= {}' \\;",NEWLINE "/usr/bin/md5sum /etc/pki/product/69.pem"],NEWLINE 'files': ["/etc/sysconfig/virt-who",NEWLINE "/etc/yum.repos.d/fedora-cisco-openh264.repo",NEWLINE "krb5_conf_d"]}NEWLINE map_rm_conf_to_components(rm_conf)NEWLINE logger_warning.assert_any_call("- /usr/bin/find /etc/origin/node => certificates_enddate\n /etc/origin/master /etc/pki /etc/ipa -type f\n -exec /usr/bin/openssl x509 -noout -enddate -in\n '{}' \\; -exec echo 'FileName= {}' \\;")NEWLINE logger_warning.assert_any_call("- /usr/bin/md5sum /etc/pki/product/69.pem => md5chk_files")NEWLINE logger_warning.assert_any_call("- /etc/sysconfig/virt-who => sysconfig_virt_who")NEWLINE logger_warning.assert_any_call("- krb5_conf_d => krb5")NEWLINENEWLINENEWLINE@patch('insights.client.map_components.logger.warning')NEWLINEdef test_log_short_key(logger_warning):NEWLINE '''NEWLINE Verify the conversion table is logged without wrapping or spacing when keyNEWLINE is shortNEWLINE '''NEWLINE rm_conf = {'commands': ["ss_tupna"]}NEWLINE map_rm_conf_to_components(rm_conf)NEWLINE logger_warning.assert_any_call("If possible, commands and files specified in the blacklist configuration will be converted to Insights component specs that will be disabled as needed.")NEWLINENEWLINENEWLINEdef test_components_added():NEWLINE '''NEWLINE Verify that the resulting component list isNEWLINE an aggregation of the current list and the conversion resultsNEWLINE with no duplicates.NEWLINE '''NEWLINE rm_conf = {'commands': ["/usr/bin/md5sum /etc/pki/product/69.pem"],NEWLINE 'components': ["insights.specs.default.DefaultSpecs.sysconfig_virt_who"]}NEWLINE results = map_rm_conf_to_components(rm_conf)NEWLINENEWLINE assert results == {'commands': [],NEWLINE 'files': [],NEWLINE 'components': ["insights.specs.default.DefaultSpecs.sysconfig_virt_who",NEWLINE "insights.specs.default.DefaultSpecs.md5chk_files"]}NEWLINE
from django.contrib import adminNEWLINENEWLINEfrom guardian.admin import GuardedModelAdminNEWLINEfrom userena.utils import get_profile_modelNEWLINENEWLINEtry:NEWLINE admin.site.unregister(get_profile_model())NEWLINEexcept admin.sites.NotRegistered:NEWLINE passNEWLINENEWLINEadmin.site.register(get_profile_model(), GuardedModelAdmin)NEWLINE
import sysNEWLINEimport osNEWLINEimport filecmpNEWLINEimport importlibNEWLINEimport datetimeNEWLINEimport commonNEWLINENEWLINEpath = os.path.abspath('.')NEWLINEsys.path.append(path)NEWLINENEWLINEdomain = 'maaseuduntulevaisuus'NEWLINEurl = 'http://www.maaseuduntulevaisuus.fi/maatalous/eu-s%C3%A4%C3%A4st%C3%A4%C3%A4-suorista-tuista-1-37-prosenttia-kriisien-varalle-1.161757'NEWLINENEWLINEout = 'test/parser_out.txt'NEWLINEmodule = importlib.import_module( 'sites.' + domain )NEWLINEd = module.parse(url)NEWLINENEWLINEclass TestParser:NEWLINENEWLINE @classmethodNEWLINE def setup_class(cls):NEWLINE common.initialise_file( out, d )NEWLINENEWLINE def test_file_exists(self):NEWLINE common.file_exists(out)NEWLINENEWLINE def test_file_not_empty(self):NEWLINE common.file_not_empty(out)NEWLINENEWLINE def test_file_contents_match(self):NEWLINE common.file_contents_match(domain, out)NEWLINENEWLINE def test_dictionary_created(self):NEWLINE common.dictionary_created(d)NEWLINENEWLINE def test_dictionary_contains_right_keys(self):NEWLINE common.dictionary_contains_right_keys(d)NEWLINENEWLINE def test_dictionary_values_correct_type(self):NEWLINE common.dictionary_values_correct_type(d)NEWLINE
import numpy as npNEWLINEimport pandas as pdNEWLINEimport osNEWLINEimport datetimeNEWLINEimport requestsNEWLINENEWLINEfrom huey.models import Buoy, BuoyRealtimeWaveDetail, BuoyRawSpectralWaveDataNEWLINENEWLINEdef import_buoy_realtime_wave_detail(db_session):NEWLINE station_id = "46025"NEWLINE buoy = db_session.query(Buoy).filter(Buoy.station_id == station_id).first()NEWLINE latest_ob = db_session.query(BuoyRealtimeWaveDetail).filter(BuoyRealtimeWaveDetail.buoy_id == buoy.NEWLINEid ).order_by(BuoyRealtimeWaveDetail.ts.desc()).first()NEWLINENEWLINE realtime_url = f"https://www.ndbc.noaa.gov/data/realtime2/{station_id}.spec"NEWLINE df = pd.read_csv(realtime_url, delim_whitespace=True)NEWLINE df = df.replace('MM', np.NaN)NEWLINENEWLINE # skip first row which is headerNEWLINE for (index, row) in df[1:].iterrows():NEWLINENEWLINE ob = BuoyRealtimeWaveDetail.from_pd_row(row)NEWLINE ob.buoy = buoyNEWLINENEWLINE if (latest_ob is None or ob.ts > latest_ob.ts):NEWLINE print(f"inserting observation for date: {ob.ts}")NEWLINE db_session.add(ob)NEWLINE else:NEWLINE print(f"observation for date: {ob.ts} already present, skipping.")NEWLINE breakNEWLINENEWLINE db_session.commit()NEWLINE print("import complete")NEWLINENEWLINEdef import_buoy_raw_spectral_wave_data(db_session):NEWLINE station_id = "46025"NEWLINE buoy = db_session.query(Buoy).filter(Buoy.station_id == station_id).first()NEWLINE latest_ob = db_session.query(BuoyRawSpectralWaveData).filter(BuoyRawSpectralWaveData.buoy_id == buoy.id ).order_by(BuoyRawSpectralWaveData.ts.desc()).first()NEWLINENEWLINE raw_spec_url = f"https://www.ndbc.noaa.gov/data/realtime2/{station_id}.data_spec"NEWLINE response = requests.get(raw_spec_url)NEWLINE data = response.textNEWLINENEWLINE # skip first row which is headerNEWLINE for line in data.splitlines()[1:]:NEWLINE NEWLINE ob = BuoyRawSpectralWaveData.from_data_line(line)NEWLINE ob.buoy = buoyNEWLINENEWLINE if (latest_ob is None or ob.ts > latest_ob.ts):NEWLINE print(f"inserting observation for date: {ob.ts}")NEWLINE db_session.add(ob)NEWLINE else:NEWLINE print(f"observation for date: {ob.ts} already present, skipping.")NEWLINE breakNEWLINENEWLINE db_session.commit()NEWLINE print("import complete")NEWLINE
# BGP SP Topology APIsNEWLINE# Author: Naveena Suvarna (naveen.suvarna@broadcom.com)NEWLINENEWLINEimport copyNEWLINENEWLINEfrom spytest import st, utils, putilsNEWLINEfrom spytest.dicts import SpyTestDictNEWLINEimport apis.routing.ip as ipapiNEWLINEimport apis.routing.bgp as bgpapiNEWLINEimport apis.system.interface as ifapiNEWLINEfrom spytest.tgen.tg import tgen_obj_dictNEWLINEimport BGP.bgplib as bgplibNEWLINENEWLINEsp_topo = SpyTestDict()NEWLINEbgp_topo = SpyTestDict()NEWLINENEWLINENEWLINEclass BGPSP:NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_topology_data_present():NEWLINE if not sp_topo['dut_list'] or len(sp_topo['dut_list']) == 0 :NEWLINE return FalseNEWLINE return TrueNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_dut_present(dut):NEWLINE if dut in sp_topo['dut_list'] :NEWLINE return TrueNEWLINE if dut in sp_topo['tg_list'] :NEWLINE return TrueNEWLINE return FalseNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_dut_list_present(dut_name_list = []):NEWLINENEWLINE if not dut_name_list or len(dut_name_list) == 0 :NEWLINE return FalseNEWLINE for dut_name in dut_name_list:NEWLINE if dut_name not in sp_topo['dut_list'] :NEWLINE return FalseNEWLINE return TrueNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_get_dut_count():NEWLINE return len (sp_topo['dut_list'])NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_get_dut_list():NEWLINE return copy.deepcopy(sp_topo['dut_list'])NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_get_dut_from_device(device_name):NEWLINENEWLINE for dut in sp_topo['dut_list'] :NEWLINE if device_name == sp_topo[dut]['device'] :NEWLINE st.log("BGP SP - DUT device {} is dut {}".format(device_name, dut))NEWLINE return dutNEWLINE for dut in sp_topo['tg_list'] :NEWLINE if device_name == sp_topo[dut]['device'] :NEWLINE st.log("BGP SP - TG device {} is dut {}".format(device_name, dut))NEWLINE return dutNEWLINE st.log("BGP SP - device {} not in dut list".format(device_name))NEWLINE return ""NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_get_dut_device(dut):NEWLINENEWLINE if dut in sp_topo['dut_list'] :NEWLINE return sp_topo[dut]['device']NEWLINE return ''NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_get_tg_list():NEWLINE return copy.deepcopy(sp_topo['tg_list'])NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_dut_is_tg(dut):NEWLINENEWLINE if dut in sp_topo['tg_list'] :NEWLINE if dut in sp_topo.keys() :NEWLINE if sp_topo[dut]['type'] == 'TG' :NEWLINE return TrueNEWLINE return FalseNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_valid_link_type(link_type):NEWLINENEWLINE if link_type == "ETH" :NEWLINE return TrueNEWLINE if link_type == "LBK" :NEWLINE return TrueNEWLINE return FalseNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_dut_link_present(dut, link_name):NEWLINENEWLINE if not BGPSP.bgp_sp_dut_present(dut) :NEWLINE st.log("BGP SP - Link dut {} not in dut list".format(dut))NEWLINE return FalseNEWLINENEWLINE if link_name not in sp_topo[dut]['intf'].keys():NEWLINE return FalseNEWLINENEWLINE return TrueNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_link_present(link_name):NEWLINENEWLINE if not link_name or link_name == '' :NEWLINE return FalseNEWLINE for dut in BGPSP.bgp_sp_get_dut_list():NEWLINE if link_name in sp_topo[dut]['intf'].keys():NEWLINE return TrueNEWLINE for dut in BGPSP.bgp_sp_get_tg_list():NEWLINE if link_name in sp_topo[dut]['intf'].keys():NEWLINE return TrueNEWLINE return FalseNEWLINENEWLINENEWLINE """ UNUSED AND USES UNDEFINED VARIABLENEWLINE @staticmethodNEWLINE def bgp_sp_link_list_present(link_name_list = []):NEWLINENEWLINE if not link_name_list or len(link_name_list) == 0 :NEWLINE return FalseNEWLINENEWLINE topo_links = sp_topo[dut]['intf'].keys()NEWLINENEWLINE for link_name in link_name_list:NEWLINE if link_name not in topo_links :NEWLINE return FalseNEWLINE return TrueNEWLINE """NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_dut_get_all_links(dut):NEWLINENEWLINE if not BGPSP.bgp_sp_dut_present(dut):NEWLINE return []NEWLINENEWLINE link_name_list = []NEWLINE for link_name, link_data in sp_topo[dut]['intf'].items():NEWLINE if link_data['type'] == 'LBK' :NEWLINE continueNEWLINE link_name_list.append(link_name)NEWLINENEWLINE return copy.deepcopy(link_name_list)NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_get_link_dut_interface(dut, link_name):NEWLINENEWLINE if BGPSP.bgp_sp_dut_link_present(dut, link_name):NEWLINE if_data = sp_topo[dut]['intf'][link_name]NEWLINE if 'if' in if_data.keys():NEWLINE return if_data['if']NEWLINENEWLINE return ''NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_dut_link_connected(dut, link_name):NEWLINENEWLINE if BGPSP.bgp_sp_dut_link_present(dut, link_name):NEWLINE if_data = sp_topo[dut]['intf'][link_name]NEWLINE if 'rmt_dut' in if_data.keys():NEWLINE if 'rmt_link' in if_data.keys():NEWLINE return TrueNEWLINENEWLINE return FalseNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_dut_get_remote_dut(dut, link_name):NEWLINENEWLINE if BGPSP.bgp_sp_dut_link_present(dut, link_name):NEWLINE if_data = sp_topo[dut]['intf'][link_name]NEWLINE if 'rmt_dut' in if_data.keys():NEWLINE return sp_topo[dut]['intf'][link_name]['rmt_dut']NEWLINENEWLINE return ''NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_dut_get_remote_link(dut, link_name):NEWLINENEWLINE if BGPSP.bgp_sp_dut_link_present(dut, link_name):NEWLINE if_data = sp_topo[dut]['intf'][link_name]NEWLINE if 'rmt_dut' in if_data.keys():NEWLINE if 'rmt_link' in if_data.keys():NEWLINE return sp_topo[dut]['intf'][link_name]['rmt_link']NEWLINENEWLINE return ''NEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_is_tg_connected_link(dut, link_name):NEWLINENEWLINE rmt_dut = BGPSP.bgp_sp_dut_get_remote_dut(dut, link_name)NEWLINE if rmt_dut == '' :NEWLINE return FalseNEWLINENEWLINE if BGPSP.bgp_sp_dut_is_tg(rmt_dut):NEWLINE return TrueNEWLINENEWLINE return FalseNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_dut_get_tg_connected_links(dut):NEWLINENEWLINE if not BGPSP.bgp_sp_dut_present(dut):NEWLINE return []NEWLINENEWLINE link_name_list = []NEWLINE for link_name, link_data in sp_topo[dut]['intf'].items():NEWLINE if 'rmt_dut' in link_data.keys():NEWLINE rmt_dut = link_data['rmt_dut']NEWLINE if BGPSP.bgp_sp_dut_is_tg(rmt_dut):NEWLINE link_name_list.append(link_name)NEWLINENEWLINE return link_name_listNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_dut_get_tg_connected_link_data(dut, link_name):NEWLINENEWLINE if not BGPSP.bgp_sp_is_tg_connected_link(dut, link_name):NEWLINE return {}NEWLINENEWLINE link_data = sp_topo[dut]['intf'][link_name]NEWLINE rmt_dut = link_data['rmt_dut']NEWLINE if BGPSP.bgp_sp_dut_is_tg(rmt_dut):NEWLINE return copy.deepcopy(link_data)NEWLINENEWLINE return {}NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_dut_get_connected_first_link(from_dut, to_dut):NEWLINENEWLINE if not BGPSP.bgp_sp_dut_present(from_dut):NEWLINE return ''NEWLINENEWLINE if not BGPSP.bgp_sp_dut_present(to_dut):NEWLINE return ''NEWLINENEWLINE for link_name, link_data in sp_topo[from_dut]['intf'].items():NEWLINE if 'rmt_dut' in link_data.keys():NEWLINE if link_data['rmt_dut'] == to_dut :NEWLINE if 'rmt_link' in link_data.keys():NEWLINE return link_nameNEWLINENEWLINE return ''NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_dut_get_connected_links(from_dut, to_dut):NEWLINENEWLINE if not BGPSP.bgp_sp_dut_present(from_dut):NEWLINE return []NEWLINENEWLINE if not BGPSP.bgp_sp_dut_present(to_dut):NEWLINE return []NEWLINENEWLINE link_name_list = []NEWLINE for link_name, link_data in sp_topo[from_dut]['intf'].items():NEWLINE if 'rmt_dut' in link_data.keys():NEWLINE if link_data['rmt_dut'] == to_dut :NEWLINE if 'rmt_link' in link_data.keys():NEWLINE link_name_list.append(link_name)NEWLINENEWLINE return link_name_listNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_dut_link_connected_to_each_other(from_dut, from_link, to_dut, to_link):NEWLINENEWLINE if not BGPSP.bgp_sp_dut_link_connected(from_dut, from_link):NEWLINE return FalseNEWLINENEWLINE if not BGPSP.bgp_sp_dut_link_connected(to_dut, to_link):NEWLINE return FalseNEWLINENEWLINE from_if_info = sp_topo[from_dut]['intf'][from_link]NEWLINE to_if_info = sp_topo[to_dut]['intf'][to_link]NEWLINENEWLINE if from_if_info['rmt_dut'] != to_dut:NEWLINE return FalseNEWLINE if to_if_info['rmt_dut'] != from_dut:NEWLINE return FalseNEWLINE if from_if_info['rmt_link'] != to_link:NEWLINE return FalseNEWLINE if to_if_info['rmt_link'] == from_link :NEWLINE return FalseNEWLINENEWLINE return TrueNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_get_unused_dut_interface(dut):NEWLINENEWLINE if not BGPSP.bgp_sp_dut_present(dut):NEWLINE st.log("BGP SP - not present in {}".format(dut))NEWLINE return ''NEWLINENEWLINE dut_if_list = []NEWLINE for _, link_data in sp_topo[dut]['intf'].items():NEWLINE if 'if' in link_data.keys():NEWLINE dut_if_list.append(link_data['if'])NEWLINENEWLINE if_idx = 80NEWLINE while if_idx < 100:NEWLINE if_name = "Ethernet{}".format(if_idx)NEWLINE if if_name not in dut_if_list :NEWLINE st.log("BGP SP - Found unused interface {} in dut {}".format(if_name, dut))NEWLINE return copy.deepcopy(if_name)NEWLINE if_idx += 4NEWLINENEWLINE st.log("BGP SP - No unused interfaces in {}".format(dut))NEWLINE return ''NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_addr_family_valid(addr_family):NEWLINENEWLINE if addr_family != 'ipv4' and addr_family != 'ipv6' :NEWLINE st.log("BGP SP - Invalid address family {}".format(addr_family))NEWLINE return FalseNEWLINE return TrueNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_get_address_family_list(addr_family):NEWLINENEWLINE addr_family_list = []NEWLINE if addr_family == 'ipv4' or addr_family == 'all':NEWLINE addr_family_list.append('ipv4')NEWLINE if addr_family == 'ipv6' or addr_family == 'all':NEWLINE addr_family_list.append('ipv6')NEWLINE return addr_family_listNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_ip_prefix_to_route_prefix(prefix, addr_family):NEWLINENEWLINE route_prefix = prefixNEWLINENEWLINE if not BGPSP.bgp_sp_addr_family_valid(addr_family) :NEWLINE st.log("BGP SP - Invalid address family {}".format(addr_family))NEWLINE return route_prefixNEWLINENEWLINE if addr_family == 'ipv6' :NEWLINE temp_prefix = prefix.partition(":0/")NEWLINE if temp_prefix and len(temp_prefix) == 3 and temp_prefix[1] == ":0/" :NEWLINE route_prefix = "{}:/{}".format(temp_prefix[0], temp_prefix[2])NEWLINENEWLINE return route_prefixNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_ip_prefix_list_to_route_prefix_list(prefix_list, addr_family):NEWLINENEWLINE route_prefix_list = []NEWLINENEWLINE if not BGPSP.bgp_sp_addr_family_valid(addr_family) :NEWLINE st.log("BGP SP - Invalid address family {}".format(addr_family))NEWLINE return route_prefix_listNEWLINENEWLINE for prefix in prefix_list :NEWLINE route_prefix = BGPSP.bgp_sp_ip_prefix_to_route_prefix(prefix, addr_family)NEWLINE if route_prefix != '':NEWLINE route_prefix_list.append(route_prefix)NEWLINENEWLINE #st.log("BGP SP - route_prefix list {}".format(route_prefix_list))NEWLINE return copy.deepcopy(route_prefix_list)NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_dut_ip_link_present(dut, link_name, addr_family):NEWLINENEWLINE if not BGPSP.bgp_sp_addr_family_valid(addr_family) :NEWLINE st.log("BGP SP - Invalid address family {}".format(addr_family))NEWLINE return FalseNEWLINENEWLINE if BGPSP.bgp_sp_dut_link_present(dut, link_name):NEWLINE if link_name in sp_topo[dut][addr_family]['link'].keys():NEWLINE return TrueNEWLINENEWLINE return FalseNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_dut_get_ip_link(dut, link_name, addr_family):NEWLINENEWLINE if not BGPSP.bgp_sp_addr_family_valid(addr_family) :NEWLINE st.log("BGP SP - Invalid address family {}".format(addr_family))NEWLINE return {}NEWLINENEWLINE if BGPSP.bgp_sp_dut_link_present(dut, link_name):NEWLINE if link_name in sp_topo[dut][addr_family]['link'].keys():NEWLINE ip_data = sp_topo[dut][addr_family]['link'][link_name]NEWLINE return copy.deepcopy(ip_data)NEWLINENEWLINE return {}NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_dut_link_has_ip(dut, link_name, addr_family):NEWLINENEWLINE if not BGPSP.bgp_sp_addr_family_valid(addr_family) :NEWLINE st.log("BGP SP - Invalid address family {}".format(addr_family))NEWLINE return FalseNEWLINENEWLINE if BGPSP.bgp_sp_dut_link_present(dut, link_name):NEWLINE if link_name in sp_topo[dut][addr_family]['link'].keys():NEWLINE ip_data = sp_topo[dut][addr_family]['link'][link_name]NEWLINE if 'ip' in ip_data.keys():NEWLINE return TrueNEWLINENEWLINE st.log("BGP SP - {} {} doesnot have ip address".format(dut, link_name))NEWLINE return FalseNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_dut_get_link_local_ip(dut, link_name, addr_family):NEWLINENEWLINE if not BGPSP.bgp_sp_addr_family_valid(addr_family) :NEWLINE st.log("BGP SP - Invalid address family {}".format(addr_family))NEWLINE return FalseNEWLINENEWLINE st.log("BGP SP - Find local ip {} {} {}".format(dut, link_name, addr_family))NEWLINE if BGPSP.bgp_sp_dut_link_present(dut, link_name):NEWLINE if link_name in sp_topo[dut][addr_family]['link'].keys():NEWLINE ip_data = sp_topo[dut][addr_family]['link'][link_name]NEWLINE if 'ip' in ip_data.keys():NEWLINE return ip_data['ip']NEWLINENEWLINE st.log("BGP SP - {} {} doesnot have local ip address".format(dut, link_name))NEWLINE return ""NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_dut_get_link_remote_ip(dut, link_name, addr_family):NEWLINENEWLINE if not BGPSP.bgp_sp_addr_family_valid(addr_family) :NEWLINE st.log("BGP SP - Invalid address family {}".format(addr_family))NEWLINE return FalseNEWLINENEWLINE if BGPSP.bgp_sp_dut_link_present(dut, link_name):NEWLINE if link_name in sp_topo[dut][addr_family]['link'].keys():NEWLINE ip_data = sp_topo[dut][addr_family]['link'][link_name]NEWLINE if 'rmt_ip' in ip_data.keys():NEWLINE return ip_data['rmt_ip']NEWLINENEWLINE st.log("BGP SP - {} {} doesnot have local remote address".format(dut, link_name))NEWLINE return ""NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_get_dut_loopback_ip(dut, lpbk_num, addr_family):NEWLINENEWLINE if not BGPSP.bgp_sp_addr_family_valid(addr_family) :NEWLINE st.log("BGP SP - Invalid address family {}".format(addr_family))NEWLINE return ""NEWLINENEWLINE link_name = "{}L{}".format(dut, lpbk_num)NEWLINENEWLINE if not BGPSP.bgp_sp_dut_link_present(dut, link_name):NEWLINE st.log("BGP SP - Link {} not in intf list".format(link_name))NEWLINE return ''NEWLINENEWLINE if link_name in sp_topo[dut][addr_family]['link'].keys():NEWLINE ip_data = sp_topo[dut][addr_family]['link'][link_name]NEWLINE if 'ip' not in ip_data.keys():NEWLINE st.log("BGP SP - {} doesnt have ip address".format(link_name))NEWLINE return ''NEWLINENEWLINE return ip_data['ip']NEWLINENEWLINE return ''NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_get_dut_loopback_ip_list(dut, addr_family):NEWLINENEWLINE if not BGPSP.bgp_sp_addr_family_valid(addr_family) :NEWLINE return []NEWLINENEWLINE if not BGPSP.bgp_sp_dut_present(dut):NEWLINE st.log("BGP SP - Dut {} not present".format(dut))NEWLINE return []NEWLINENEWLINE lpbk_ip_list = []NEWLINE for _, ip_data in sp_topo[dut][addr_family]['link'].items():NEWLINE if ip_data['type'] == 'LBK' :NEWLINE if 'ip' in ip_data.keys():NEWLINE lpbk_ip_list.append(ip_data['ip'])NEWLINENEWLINE return copy.deepcopy(lpbk_ip_list)NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_get_loopback_ip_in_dut_list(dut_list=[], addr_family='ipv4'):NEWLINENEWLINE if not BGPSP.bgp_sp_addr_family_valid(addr_family) :NEWLINE return []NEWLINENEWLINE lpbk_ip_list = []NEWLINENEWLINE for dut in dut_list:NEWLINE if not BGPSP.bgp_sp_dut_present(dut):NEWLINE continueNEWLINENEWLINE for _, ip_data in sp_topo[dut][addr_family]['link'].items():NEWLINE if ip_data['type'] == 'LBK' :NEWLINE if 'ip' in ip_data.keys():NEWLINE if ip_data['ip'] not in lpbk_ip_list:NEWLINE lpbk_ip_list.append(ip_data['ip'])NEWLINENEWLINE return copy.deepcopy(lpbk_ip_list)NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_get_dut_ip_address_list(dut, addr_family, vrf='default'):NEWLINENEWLINE if not BGPSP.bgp_sp_addr_family_valid(addr_family) :NEWLINE return []NEWLINENEWLINE if not BGPSP.bgp_sp_dut_present(dut):NEWLINE st.log("BGP SP - Dut {} not present".format(dut))NEWLINE return []NEWLINENEWLINE ip_addr_list = []NEWLINE for _, ip_data in sp_topo[dut][addr_family]['link'].items():NEWLINE if 'ip' in ip_data.keys():NEWLINE ip_addr_list.append(ip_data['ip'])NEWLINENEWLINE st.log("BGP SP - Dut {} has host ip {}".format(dut, ip_addr_list))NEWLINE return copy.deepcopy(ip_addr_list)NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_get_dut_static_network_prefixes(dut, addr_family):NEWLINENEWLINE if not BGPSP.bgp_sp_dut_present(dut):NEWLINE st.log("BGP SP - Dut {} not present".format(dut))NEWLINE return []NEWLINENEWLINE if not BGPSP.bgp_sp_addr_family_valid(addr_family):NEWLINE return []NEWLINENEWLINE snw_list = []NEWLINE for prefix, snw_data in sp_topo[dut][addr_family]['static_nw'].items() :NEWLINE prefix_subnet = "{}/{}".format(prefix, snw_data['subnet'])NEWLINE snw_list.append(prefix_subnet)NEWLINENEWLINE return copy.deepcopy(snw_list)NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_get_dut_static_route_prefixes(dut, addr_family):NEWLINENEWLINE if not BGPSP.bgp_sp_dut_present(dut):NEWLINE st.log("BGP SP - Dut {} not present".format(dut))NEWLINE return []NEWLINENEWLINE if not BGPSP.bgp_sp_addr_family_valid(addr_family):NEWLINE return []NEWLINENEWLINE srtp_list = []NEWLINE for prefix, rt_data in sp_topo[dut][addr_family]['static_rt'].items() :NEWLINE prefix_subnet = "{}/{}".format(prefix, rt_data['subnet'])NEWLINE srtp_list.append(prefix_subnet)NEWLINENEWLINE return copy.deepcopy(srtp_list)NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_get_dut_null_nhop_static_route_prefixes(dut, addr_family):NEWLINENEWLINE if not BGPSP.bgp_sp_dut_present(dut):NEWLINE st.log("BGP SP - Dut {} not present".format(dut))NEWLINE return []NEWLINENEWLINE if not BGPSP.bgp_sp_addr_family_valid(addr_family):NEWLINE return []NEWLINENEWLINE srtp_list = []NEWLINE for prefix, rt_data in sp_topo[dut][addr_family]['static_rt'].items() :NEWLINE if rt_data['nexthop'] == 'Null0' :NEWLINE prefix_subnet = "{}/{}".format(prefix, rt_data['subnet'])NEWLINE srtp_list.append(prefix_subnet)NEWLINENEWLINE return copy.deepcopy(srtp_list)NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_get_dut_static_route_prefix_data_list(dut, addr_family):NEWLINENEWLINE if not BGPSP.bgp_sp_dut_present(dut):NEWLINE st.log("BGP SP - Dut {} not present".format(dut))NEWLINE return {}NEWLINENEWLINE if not BGPSP.bgp_sp_addr_family_valid(addr_family):NEWLINE return {}NEWLINENEWLINE srtp_data_list = {}NEWLINE for prefix, rt_data in sp_topo[dut][addr_family]['static_rt'].items() :NEWLINE srtp_data_list.update({prefix: rt_data})NEWLINENEWLINE return copy.deepcopy(srtp_data_list)NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_find_linear_topo_in_dut_list(dut_list=[], start_dut='', node_limit=0, save_path='yes'):NEWLINENEWLINE st.log("BGP SP - Find Linear Topo in Dut list {} length {}".format(dut_list, node_limit))NEWLINE sp_topo_dut_list = BGPSP.bgp_sp_get_dut_list()NEWLINENEWLINE found_path = {}NEWLINE found_path['found'] = FalseNEWLINENEWLINE if not dut_list or len(dut_list) == 0 :NEWLINE dut_list = sp_topo_dut_listNEWLINE else :NEWLINE for dut in dut_list :NEWLINE if dut not in sp_topo_dut_list :NEWLINE st.log("Dut {} not in Topo dut lidt {}".format(dut, sp_topo_dut_list))NEWLINE return found_pathNEWLINENEWLINE if start_dut and start_dut != '' :NEWLINE if start_dut not in dut_list :NEWLINE st.log("Start dut {} not in dut list {}".format(start_dut, dut_list))NEWLINE return found_pathNEWLINENEWLINE if node_limit <= 0 :NEWLINE length_limit = len (dut_list)NEWLINE else :NEWLINE length_limit = node_limitNEWLINENEWLINE st.log("Modified Dut list {} length_limit {}".format(dut_list, length_limit))NEWLINENEWLINE longest_path = []NEWLINENEWLINE for dut in dut_list :NEWLINENEWLINE if start_dut and start_dut != '' and start_dut != dut :NEWLINE continueNEWLINENEWLINE if BGPSP.bgp_sp_dut_is_tg(dut) :NEWLINE continueNEWLINENEWLINE st.log(" Starting dut {} ".format(dut))NEWLINENEWLINE sp_topo_stack = []NEWLINE sp_topo_path = []NEWLINE sp_topo_stack.append(dut)NEWLINENEWLINE while sp_topo_stack and len(sp_topo_stack) :NEWLINENEWLINE st.log(" sp stack {}".format(sp_topo_stack))NEWLINE st.log(" sp path {}".format(sp_topo_path))NEWLINENEWLINE curr_dut = sp_topo_stack.pop()NEWLINE sp_topo_path.append(curr_dut)NEWLINENEWLINE leaf_dut = TrueNEWLINE for _, link_data in sp_topo[curr_dut]['intf'].items():NEWLINE if 'rmt_dut' in link_data.keys():NEWLINE next_dut = link_data['rmt_dut']NEWLINENEWLINE if BGPSP.bgp_sp_dut_is_tg(next_dut):NEWLINE continueNEWLINENEWLINE if next_dut in sp_topo_path :NEWLINE continueNEWLINENEWLINE if next_dut not in dut_list :NEWLINE continueNEWLINENEWLINE if next_dut not in sp_topo_stack :NEWLINE sp_topo_stack.append(next_dut)NEWLINENEWLINE leaf_dut = FalseNEWLINENEWLINE if len(sp_topo_path) == length_limit :NEWLINE leaf_dut = TrueNEWLINENEWLINE if leaf_dut is True :NEWLINE st.log(" Linear found Dut {} ".format(curr_dut))NEWLINE st.log(" Linear found sp path {} ".format(sp_topo_path))NEWLINE st.log(" Linear found longest path {} ".format(longest_path))NEWLINENEWLINE if len(longest_path) < len(sp_topo_path) :NEWLINE if node_limit > 0 :NEWLINE if len(sp_topo_path) <= length_limit :NEWLINE longest_path = copy.deepcopy(sp_topo_path)NEWLINE st.log(" New longest path set as curr new linear path")NEWLINE else :NEWLINE longest_path = copy.deepcopy(sp_topo_path)NEWLINE st.log(" New longest path set as curr new linear path")NEWLINENEWLINE if len(longest_path) >= length_limit :NEWLINE st.log(" Path length limit provided {} and reached".format(length_limit))NEWLINE breakNEWLINENEWLINE sp_topo_path.pop()NEWLINENEWLINENEWLINE if len(longest_path) == length_limit :NEWLINE breakNEWLINENEWLINE st.log("BGP SP - Longest path len {} with path {}".format(len(longest_path), longest_path))NEWLINENEWLINE path_length = len(longest_path)NEWLINE found_path['found'] = True if path_length else FalseNEWLINENEWLINE path_length = len(longest_path)NEWLINE found_path['found'] = True if path_length else FalseNEWLINE found_path['dut_list'] = []NEWLINE found_path['segment'] = {}NEWLINE found_path['segment_count'] = 0NEWLINE found_path['type'] = 'Linear'NEWLINENEWLINE if found_path['found'] :NEWLINE for dut in longest_path :NEWLINE found_path['dut_list'].append(dut)NEWLINENEWLINE from_dut = longest_path[0]NEWLINE found_path['start_dut'] = from_dutNEWLINE dut_idx = 1NEWLINE while dut_idx < path_length :NEWLINE to_dut = longest_path[dut_idx]NEWLINE segt_link_idx = 0NEWLINE for link_name, link_data in sp_topo[from_dut]['intf'].items():NEWLINE if 'rmt_dut' in link_data.keys():NEWLINE if link_data['rmt_dut'] == to_dut :NEWLINENEWLINE rmt_link = link_data['rmt_link']NEWLINE segt_link = { 'lcl_dut' : from_dut, 'lcl_link': link_name,NEWLINE 'rmt_dut' : to_dut, 'rmt_link' : rmt_link }NEWLINENEWLINE if segt_link_idx == 0 : found_path['segment'][dut_idx - 1] = {}NEWLINE found_path['segment'][dut_idx - 1].update({ segt_link_idx: segt_link})NEWLINENEWLINE if segt_link_idx == 0:NEWLINE found_path['segment_count'] += 1NEWLINE segt_link_idx += 1NEWLINE #st.log(" Path node {} is {}".format(dut_idx - 1, segt_link))NEWLINE from_dut = to_dutNEWLINE dut_idx += 1NEWLINENEWLINE if save_path == 'yes' :NEWLINE sp_topo['subtopo']['linear'] = copy.deepcopy(found_path)NEWLINENEWLINE BGPSP.bgp_sp_show_topo_path(found_path)NEWLINE return found_pathNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_dut_get_saved_linear_topo():NEWLINE return copy.deepcopy(sp_topo['subtopo']['linear'])NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_find_ring_topo_in_dut_list(dut_list=[], start_dut='', node_limit=0, save_path='yes'):NEWLINENEWLINE st.log("BGP SP - Find Linear Topo in Dut list {} length {}".format(dut_list, node_limit))NEWLINE sp_topo_dut_list = BGPSP.bgp_sp_get_dut_list()NEWLINENEWLINE found_path = {}NEWLINE found_path['found'] = FalseNEWLINENEWLINE if not dut_list or len(dut_list) == 0 :NEWLINE dut_list = sp_topo_dut_listNEWLINE else :NEWLINE for dut in dut_list :NEWLINE if dut not in sp_topo_dut_list :NEWLINE st.log("Dut {} not in Topo dut lidt {}".format(dut, sp_topo_dut_list))NEWLINE return found_pathNEWLINENEWLINE if start_dut and start_dut != '' :NEWLINE if start_dut not in dut_list :NEWLINE st.log("Start dut {} not in dut list {}".format(start_dut, dut_list))NEWLINE return found_pathNEWLINENEWLINE if node_limit <= 0 :NEWLINE length_limit = len(dut_list) + 1NEWLINE else :NEWLINE length_limit = node_limit + 1NEWLINENEWLINE st.log("Modified Dut list {} length_limit {}".format(dut_list, length_limit))NEWLINENEWLINE longest_path = []NEWLINE loop_count = 0NEWLINENEWLINE for dut in dut_list :NEWLINENEWLINE if length_limit <= 3 :NEWLINE breakNEWLINENEWLINE if start_dut and start_dut != '' and start_dut != dut :NEWLINE continueNEWLINENEWLINE if BGPSP.bgp_sp_dut_is_tg(dut) :NEWLINE continueNEWLINENEWLINE st.log(" Starting at dut {} with longest path {}.".format(dut, longest_path))NEWLINENEWLINE sp_topo_stack = []NEWLINE sp_topo_path = []NEWLINE sp_topo_stack.append(dut)NEWLINENEWLINE while sp_topo_stack and len(sp_topo_stack) :NEWLINENEWLINE loop_count += 1NEWLINE if loop_count > 100 :NEWLINE breakNEWLINENEWLINE st.log(" sp stack {}".format(sp_topo_stack))NEWLINE st.log(" sp path {}".format(sp_topo_path))NEWLINENEWLINE curr_dut = sp_topo_stack.pop()NEWLINE sp_topo_path.append(curr_dut)NEWLINENEWLINE st.log(" modified sp path {}".format(sp_topo_path))NEWLINENEWLINE leaf_dut = TrueNEWLINE ring_found = FalseNEWLINENEWLINE for link_name, link_data in sp_topo[curr_dut]['intf'].items():NEWLINE if 'rmt_dut' in link_data.keys():NEWLINE next_dut = link_data['rmt_dut']NEWLINENEWLINE if next_dut == dut :NEWLINE ring_found = TrueNEWLINENEWLINE if BGPSP.bgp_sp_dut_is_tg(next_dut):NEWLINE continueNEWLINENEWLINE if next_dut not in dut_list :NEWLINE continueNEWLINENEWLINE if next_dut in sp_topo_path :NEWLINE continueNEWLINENEWLINE if next_dut not in sp_topo_stack :NEWLINE sp_topo_stack.append(next_dut)NEWLINENEWLINE leaf_dut = FalseNEWLINENEWLINE if ring_found :NEWLINE st.log(" Ring found Dut {} ".format(curr_dut))NEWLINE st.log(" Ring found sp path {} ".format(sp_topo_path))NEWLINE st.log(" Ring found longest path {} ".format(longest_path))NEWLINENEWLINE if len(sp_topo_path) > 2 :NEWLINENEWLINE sp_topo_path.append(dut)NEWLINENEWLINE st.log(" new ring sp path {} ".format(sp_topo_path))NEWLINE st.log(" ring longest path {} ".format(longest_path))NEWLINENEWLINE if len(longest_path) < len(sp_topo_path) :NEWLINE if node_limit > 0 :NEWLINE if len(sp_topo_path) <= length_limit :NEWLINE longest_path = copy.deepcopy(sp_topo_path)NEWLINE st.log(" New longest path set as curr new ring sp path")NEWLINE else :NEWLINE longest_path = copy.deepcopy(sp_topo_path)NEWLINE st.log(" New longest path set as curr new ring sp path")NEWLINENEWLINE if len(longest_path) >= length_limit :NEWLINE st.log(" Path length limit provided {} and reached".format(length_limit))NEWLINE breakNEWLINENEWLINE sp_topo_path.pop()NEWLINENEWLINE if leaf_dut is True :NEWLINE sp_topo_path.pop()NEWLINENEWLINE if len(longest_path) == length_limit :NEWLINE breakNEWLINENEWLINE st.log("BGP SP - Longest path len {} with path {}".format(len(longest_path), longest_path))NEWLINENEWLINE path_length = len(longest_path)NEWLINE found_path['found'] = True if path_length else FalseNEWLINE found_path['dut_list'] = []NEWLINE found_path['segment'] = {}NEWLINE found_path['segment_count'] = 0NEWLINE found_path['type'] = 'Ring'NEWLINENEWLINE if found_path['found'] :NEWLINE for dut in longest_path :NEWLINE found_path['dut_list'].append(dut)NEWLINENEWLINE from_dut = longest_path[0]NEWLINE found_path['start_dut'] = from_dutNEWLINE dut_idx = 1NEWLINE while dut_idx < path_length :NEWLINE to_dut = longest_path[dut_idx]NEWLINE segt_link_idx = 0NEWLINE for link_name, link_data in sp_topo[from_dut]['intf'].items():NEWLINE if 'rmt_dut' in link_data.keys():NEWLINE if link_data['rmt_dut'] == to_dut :NEWLINENEWLINE rmt_link = link_data['rmt_link']NEWLINE segt_link = { 'lcl_dut' : from_dut, 'lcl_link': link_name,NEWLINE 'rmt_dut' : to_dut, 'rmt_link' : rmt_link }NEWLINENEWLINE if segt_link_idx == 0 : found_path['segment'][dut_idx - 1] = {}NEWLINE found_path['segment'][dut_idx - 1].update({ segt_link_idx: segt_link})NEWLINENEWLINE if segt_link_idx == 0:NEWLINE found_path['segment_count'] += 1NEWLINE segt_link_idx += 1NEWLINE #st.log(" Path node {} is {}".format(dut_idx - 1, segt_link))NEWLINENEWLINE from_dut = to_dutNEWLINE dut_idx += 1NEWLINE found_path['dut_list'].pop()NEWLINENEWLINE if save_path == 'yes' :NEWLINE sp_topo['subtopo']['ring'] = copy.deepcopy(found_path)NEWLINENEWLINE BGPSP.bgp_sp_show_topo_path(found_path)NEWLINE return found_pathNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_dut_get_saved_ring_topo():NEWLINE return copy.deepcopy(sp_topo['subtopo']['ring'])NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_find_star_topo_in_dut_list(dut_list=[], core_dut = "", path_spoke_limit=0, save_path='yes'):NEWLINENEWLINE st.log("BGP SP - Find Star Topo in Dut list {} length {}".format(dut_list, path_spoke_limit))NEWLINE sp_topo_dut_list = BGPSP.bgp_sp_get_dut_list()NEWLINENEWLINE found_path = {}NEWLINE found_path['found'] = FalseNEWLINENEWLINE if not dut_list or len(dut_list) == 0 :NEWLINE dut_list = sp_topo_dut_listNEWLINE else :NEWLINE for dut in dut_list :NEWLINE if dut not in sp_topo_dut_list :NEWLINE st.log("Dut {} not in Topo dut list {}".format(dut, sp_topo_dut_list))NEWLINE return found_pathNEWLINENEWLINE if core_dut and core_dut != '' :NEWLINE if core_dut not in dut_list :NEWLINE st.log("Core dute {} not in dut list {}".format(core_dut, dut_list))NEWLINE return found_pathNEWLINENEWLINE if path_spoke_limit <= 0 :NEWLINE spoke_limit = len (dut_list)NEWLINE else :NEWLINE spoke_limit = path_spoke_limitNEWLINENEWLINE st.log("Modified Dut list {} length_limit {}".format(dut_list, spoke_limit))NEWLINENEWLINE largest_star = []NEWLINENEWLINE for dut in dut_list :NEWLINENEWLINE if core_dut and core_dut != '' and core_dut != dut :NEWLINE continueNEWLINENEWLINE if BGPSP.bgp_sp_dut_is_tg(dut) :NEWLINE continueNEWLINENEWLINE st.log(" Starting dut {} ".format(dut))NEWLINENEWLINE sp_topo_path = []NEWLINE sp_topo_path.append(dut)NEWLINENEWLINE excl_list = list(dut_list)NEWLINE excl_list.remove(dut)NEWLINENEWLINE for next_dut in excl_list :NEWLINENEWLINE st.log(" sp path {}".format(sp_topo_path))NEWLINENEWLINE #leaf_dut = TrueNEWLINE for link_name, link_data in sp_topo[dut]['intf'].items():NEWLINE if 'rmt_dut' in link_data.keys():NEWLINE rmt_dut = link_data['rmt_dut']NEWLINENEWLINE if rmt_dut != next_dut :NEWLINE continueNEWLINENEWLINE sp_topo_path.append(next_dut)NEWLINE breakNEWLINENEWLINE if len(largest_star) < len(sp_topo_path) :NEWLINE largest_star = sp_topo_pathNEWLINENEWLINE path_spoke_count = len(largest_star) - 1NEWLINE if path_spoke_limit > 0 :NEWLINE if path_spoke_count == path_spoke_limit :NEWLINE st.log(" Path spoke limit provided {} and reached".format(path_spoke_limit))NEWLINE breakNEWLINE else :NEWLINE if path_spoke_count == spoke_limit :NEWLINE st.log(" Path max possible spoke {} reached".format(spoke_limit))NEWLINE breakNEWLINENEWLINE st.log("BGP SP - {} Star with nodes {}".format(len(largest_star), largest_star))NEWLINENEWLINE path_length = len(largest_star)NEWLINENEWLINE found_path['found'] = True if path_length else FalseNEWLINE found_path['dut_list'] = []NEWLINE found_path['segment'] = {}NEWLINE found_path['segment_count'] = 0NEWLINE found_path['type'] = 'Star'NEWLINENEWLINE if found_path['found'] :NEWLINENEWLINE for dut in largest_star :NEWLINE found_path['dut_list'].append(dut)NEWLINENEWLINE from_dut = largest_star[0]NEWLINE found_path['start_dut'] = from_dutNEWLINENEWLINE dut_idx = 1NEWLINE while dut_idx < path_length :NEWLINE to_dut = largest_star[dut_idx]NEWLINE segt_link_idx = 0NEWLINE for link_name, link_data in sp_topo[from_dut]['intf'].items():NEWLINE if 'rmt_dut' in link_data.keys():NEWLINE if link_data['rmt_dut'] == to_dut :NEWLINE rmt_link = link_data['rmt_link']NEWLINE segt_link = { 'lcl_dut' : from_dut, 'lcl_link': link_name,NEWLINE 'rmt_dut' : to_dut, 'rmt_link' : rmt_link }NEWLINENEWLINE if segt_link_idx == 0 : found_path['segment'][dut_idx - 1] = {}NEWLINE found_path['segment'][dut_idx - 1].update({ segt_link_idx: segt_link})NEWLINENEWLINE if segt_link_idx == 0:NEWLINE found_path['segment_count'] += 1NEWLINE segt_link_idx += 1NEWLINE #st.log(" Path node {} is {}".format(dut_idx - 1, segt_link))NEWLINENEWLINE dut_idx += 1NEWLINENEWLINE if save_path == 'yes' :NEWLINE sp_topo['subtopo']['star'] = copy.deepcopy(found_path)NEWLINENEWLINE BGPSP.bgp_sp_show_topo_path(found_path)NEWLINE return found_pathNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_dut_get_saved_star_topo():NEWLINE return copy.deepcopy(sp_topo['subtopo']['star'])NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_find_spine_leaf_topo_in_dut_list(spine_list=[], leaf_list=[], save_path='yes'):NEWLINENEWLINE st.log("BGP SP - Find Spine Leaf paths in {} and {}.".format(spine_list, leaf_list))NEWLINE sp_topo_dut_list = BGPSP.bgp_sp_get_dut_list()NEWLINENEWLINE found_path = {}NEWLINE found_path['found'] = FalseNEWLINENEWLINE for dut in spine_list:NEWLINE if dut not in sp_topo_dut_list:NEWLINE st.log("Spine dut {} not in topo dut list {}".format(dut, sp_topo_dut_list))NEWLINE return found_pathNEWLINENEWLINE for dut in leaf_list:NEWLINE if dut not in sp_topo_dut_list:NEWLINE st.log("Leaf dut {} not in topo dut list {}".format(dut, sp_topo_dut_list))NEWLINE return found_pathNEWLINENEWLINE for dut in spine_list:NEWLINE if dut in leaf_list:NEWLINE st.log("Dut {} in both spine and leaf list {}".format(dut, spine_list))NEWLINE return found_pathNEWLINENEWLINE found_path['spine_list'] = spine_listNEWLINE found_path['leaf_list'] = leaf_listNEWLINE found_path['dut_list'] = []NEWLINE found_path['spine_path'] = {}NEWLINE found_path['type'] = 'SpineLeaf'NEWLINENEWLINE for spine_dut in spine_list :NEWLINENEWLINE dut_list = copy.deepcopy(leaf_list)NEWLINE dut_list.append(spine_dut)NEWLINENEWLINE spine_path = BGPSP.bgp_sp_find_star_topo_in_dut_list(dut_list, spine_dut, save_path='no')NEWLINENEWLINE st.log("Spine Leaf paths from {} is {}.\n".format(spine_dut, spine_path))NEWLINENEWLINE if spine_path['found'] :NEWLINE found_path['found'] = TrueNEWLINENEWLINE if spine_dut not in found_path['dut_list']:NEWLINE found_path['dut_list'].append(spine_dut)NEWLINENEWLINE for leaf_dut in spine_path['dut_list']:NEWLINE if leaf_dut not in found_path['dut_list']:NEWLINE found_path['dut_list'].append(leaf_dut)NEWLINENEWLINE spine_path = copy.deepcopy(spine_path)NEWLINE found_path['spine_path'].update({ spine_dut : spine_path })NEWLINENEWLINE if save_path == 'yes' :NEWLINE sp_topo['subtopo']['spine_leaf'] = copy.deepcopy(found_path)NEWLINENEWLINE st.log("BGP SP - Spine Leaf paths {}\n".format(found_path))NEWLINE return found_pathNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_dut_get_saved_spine_leaf_topo():NEWLINE return copy.deepcopy(sp_topo['subtopo']['spine_leaf'])NEWLINENEWLINENEWLINE """ UNUSED AND CALLS UNDEFINED FUNCTIONNEWLINE @staticmethodNEWLINE def bgp_sp_dut_get_connected_ip_links(from_dut, to_dut, addr_family):NEWLINENEWLINE ip_link_list = []NEWLINE if not BGPSP.bgp_sp_addr_family_valid(addr_family):NEWLINE return ip_link_listNEWLINENEWLINE link_name_list = bgp_sp_dut_get_connected_link_names(from_dut, to_dut)NEWLINE if not link_name_list or len(link_name_list) == 0 :NEWLINE return ip_link_listNEWLINENEWLINE ip_link_list = []NEWLINE for link_name in link_name_list:NEWLINE if link_name in sp_topo[dut][addr_family]['link'].keys():NEWLINE ip_data = sp_topo[dut][addr_family]['link'][link_name]NEWLINE if 'rmt_dut' in ip_data.keys():NEWLINE if 'rmt_link' in ip_data.keys():NEWLINE if ip_data['rmt_dut'] == to_dut :NEWLINE ip_link_list.append(link_name)NEWLINENEWLINE return ip_link_listNEWLINE """NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_add_del_dut(dut, device_name, device_type='DUT', add='yes'):NEWLINENEWLINE action_str = "Add" if add == 'yes' else 'Delete'NEWLINENEWLINE if add == 'yes' :NEWLINENEWLINE if BGPSP.bgp_sp_dut_present(dut):NEWLINE st.log("BGP SP - device {} exists as dut {}".format(device_name, dut))NEWLINE return FalseNEWLINENEWLINE dut2 = BGPSP.bgp_sp_get_dut_from_device(device_name)NEWLINE if dut2 != "" and dut != dut2 :NEWLINE st.log("BGP SP - device {} exists as dut {}".format(device_name, dut2))NEWLINE return FalseNEWLINENEWLINE st.log("BGP SP - {} {} {} {}".format(action_str, device_type, dut, device_name))NEWLINE if device_type == 'DUT' :NEWLINE sp_topo['dut_list'].append(dut)NEWLINE sp_topo['dut_list'].sort()NEWLINE else :NEWLINE sp_topo['tg_list'].append(dut)NEWLINE sp_topo['tg_list'].sort()NEWLINENEWLINE sp_topo[dut] = {}NEWLINE sp_topo[dut]['type'] = device_typeNEWLINE sp_topo[dut]['device'] = device_nameNEWLINE sp_topo[dut]['intf'] = {}NEWLINE sp_topo[dut]['nwoctet'] = 0NEWLINE sp_topo[dut]['vrf'] = {}NEWLINENEWLINE sp_topo[dut]['ipv4'] = {}NEWLINE sp_topo[dut]['ipv4']['static_nw'] = {}NEWLINE sp_topo[dut]['ipv4']['static_rt'] = {}NEWLINE sp_topo[dut]['ipv4']['link'] = {}NEWLINE sp_topo[dut]['ipv4']['nwoctet'] = 0NEWLINENEWLINE sp_topo[dut]['ipv6'] = {}NEWLINE sp_topo[dut]['ipv6']['static_nw'] = {}NEWLINE sp_topo[dut]['ipv6']['static_rt'] = {}NEWLINE sp_topo[dut]['ipv6']['link'] = {}NEWLINE sp_topo[dut]['ipv6']['nwoctet'] = 0NEWLINENEWLINE return TrueNEWLINENEWLINE else :NEWLINENEWLINE if not BGPSP.bgp_sp_dut_present(dut):NEWLINE st.log("BGP SP - dut doesnt exists {}".format(dut))NEWLINE return FalseNEWLINENEWLINE if device_name != '' and device_name != sp_topo[dut]['device']:NEWLINE st.log("BGP SP - device {} isnot dut {}".format(device_name, dut))NEWLINE return FalseNEWLINENEWLINE device_name = sp_topo[dut]['device']NEWLINENEWLINE if len(sp_topo[dut]['intf']) != 0 :NEWLINE st.log("BGP SP - device {} {} interface exists".format(device_name, dut))NEWLINE return FalseNEWLINENEWLINE st.log("BGP SP - Deleting device {} {} ".format(device_name, dut))NEWLINE del sp_topo[dut]NEWLINE if device_type == 'DUT' :NEWLINE del sp_topo['dut_list'][dut]NEWLINE sp_topo['dut_list'].sort()NEWLINE else :NEWLINE del sp_topo['tg_list'][dut]NEWLINE sp_topo['tg_list'].sort()NEWLINENEWLINE return TrueNEWLINENEWLINE #st.log("BGP SP - Dut {} FAILED".format(action_str))NEWLINE #return FalseNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_add_del_link(dut, link_type, link_name, intf_name, add='yes'):NEWLINENEWLINE action_str = "Add" if add == 'yes' else 'Delete'NEWLINE st.log("BGP SP - Link {} for {} {}".format(action_str, dut, link_name))NEWLINENEWLINE if not BGPSP.bgp_sp_dut_present(dut):NEWLINE st.log("BGP SP - Dut {} doesnt exist".format(dut))NEWLINE return FalseNEWLINENEWLINE if not BGPSP.bgp_sp_valid_link_type(link_type):NEWLINE st.log("BGP SP - Invalid intface type {}".format(link_type))NEWLINE return FalseNEWLINENEWLINE if dut == "" or link_name=="" or intf_name == "" :NEWLINE st.log("BGP SP - Invalid dut {} or link {} or intf {}".format(dut, link_name, intf_name))NEWLINE return FalseNEWLINENEWLINE if add == 'yes' :NEWLINE if BGPSP.bgp_sp_dut_link_present(dut, link_name):NEWLINE st.log("BGP SP - dut {} link {} already present".format(dut, link_name))NEWLINE return FalseNEWLINENEWLINE if_data = { 'if': intf_name, 'type': link_type }NEWLINE sp_topo[dut]['intf'].update({link_name : if_data })NEWLINENEWLINE return TrueNEWLINENEWLINE else:NEWLINE if not BGPSP.bgp_sp_dut_link_present(dut, link_name):NEWLINE st.log("BGP SP - dut {} doesnt have intf {}".format(dut, link_name))NEWLINE return FalseNEWLINENEWLINE if BGPSP.bgp_sp_dut_link_connected(dut, link_name):NEWLINE st.log("BGP SP - dut {} link {} connected".format(dut, link_name))NEWLINE return FalseNEWLINENEWLINE if BGPSP.bgp_sp_dut_link_has_ip(dut, link_name, 'ipv4'):NEWLINE st.log("BGP SP - dut {} link {} has ipv4 addr".format(dut, link_name))NEWLINE return FalseNEWLINENEWLINE if BGPSP.bgp_sp_dut_link_has_ip(dut, link_name, 'ipv6'):NEWLINE st.log("BGP SP - dut {} link {} has ipv6 addr".format(dut, link_name))NEWLINE return FalseNEWLINENEWLINE st.log("BGP SP - dut {} deleting link {}".format(dut, link_name))NEWLINE del sp_topo[dut]['intf'][link_name]NEWLINE return TrueNEWLINENEWLINE #st.log("BGP SP - Link {} FAILED".format(action_str))NEWLINE #return FalseNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_connect_links(from_dut, from_link, to_dut, to_link, add='yes'):NEWLINENEWLINE action_str = "Add" if add == 'yes' else 'Delete'NEWLINE st.log("BGP SP - Link connect {} for {} {}".format(action_str, from_link, to_link))NEWLINENEWLINE if not BGPSP.bgp_sp_dut_link_present(from_dut, from_link):NEWLINE st.log("BGP SP - dut {} link {} not present".format(from_dut, from_link))NEWLINE return FalseNEWLINENEWLINE if not BGPSP.bgp_sp_dut_link_present(to_dut, to_link):NEWLINE st.log("BGP SP - dut {} link {} not present".format(to_dut, to_link))NEWLINE return FalseNEWLINENEWLINE if add == 'yes' :NEWLINENEWLINE if BGPSP.bgp_sp_dut_link_connected(from_dut, from_link):NEWLINE st.log("BGP SP - dut {} link {} already connected".format(from_dut, from_link))NEWLINE return FalseNEWLINENEWLINE if BGPSP.bgp_sp_dut_link_connected(to_dut, to_link):NEWLINE st.log("BGP SP - dut {} link {} already connected".format(to_dut, to_link))NEWLINE return FalseNEWLINENEWLINE sp_topo[from_dut]['intf'][from_link].update({'rmt_dut': to_dut})NEWLINE sp_topo[from_dut]['intf'][from_link].update({'rmt_link': to_link})NEWLINENEWLINE sp_topo[to_dut]['intf'][to_link].update({'rmt_dut': from_dut})NEWLINE sp_topo[to_dut]['intf'][to_link].update({'rmt_link': from_link})NEWLINENEWLINE if BGPSP.bgp_sp_dut_link_connected(from_dut, from_link):NEWLINE st.log("BGP SP - {} {} {} {} connected".format(from_dut, from_link, to_dut, to_link))NEWLINE return TrueNEWLINENEWLINE else:NEWLINENEWLINE if not BGPSP.bgp_sp_dut_link_connected_to_each_other(from_dut, from_link, to_dut, to_link):NEWLINE st.log("BGP SP - {} {} {} {} not connected".format(from_dut, from_link, to_dut, to_link))NEWLINE return FalseNEWLINENEWLINE del sp_topo[from_dut]['intf'][from_link]['rmt_dut']NEWLINE del sp_topo[from_dut]['intf'][from_link]['rmt_link']NEWLINE del sp_topo[to_dut]['intf'][to_link]['rmt_dut']NEWLINE del sp_topo[to_dut]['intf'][to_link]['rmt_link']NEWLINENEWLINE st.log("BGP SP - {} {} {} {} disconnected".format(from_dut, from_link, to_dut, to_link))NEWLINE return TrueNEWLINENEWLINE return FalseNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_add_del_link_ip(dut, link_name, ip_addr, subnet, rmt_ip, addr_family, add='yes'):NEWLINENEWLINE action_str = "Add" if add == 'yes' else 'Delete'NEWLINE st.log("BGP SP - Link ip {} for {} {} {}".format(action_str, dut, link_name, ip_addr))NEWLINENEWLINE if not BGPSP.bgp_sp_dut_link_connected(dut, link_name):NEWLINE st.log("BGP SP - {} link not in connected state".format(link_name))NEWLINENEWLINE if add == 'yes' :NEWLINENEWLINE if BGPSP.bgp_sp_dut_ip_link_present(dut, link_name, addr_family) :NEWLINE st.log("BGP SP - {} {} already has {} address".format(dut, link_name, addr_family))NEWLINE return FalseNEWLINENEWLINE if_data = sp_topo[dut]['intf'][link_name]NEWLINE ip_data = { "ip": ip_addr, "subnet": subnet, "if": if_data['if'], 'type': if_data['type']}NEWLINENEWLINE if 'rmt_dut' in if_data.keys():NEWLINE ip_data.update({'rmt_dut': if_data['rmt_dut']})NEWLINE ip_data.update({'rmt_link': if_data['rmt_link']})NEWLINENEWLINE if rmt_ip and rmt_ip != "":NEWLINE ip_data.update({'rmt_ip': rmt_ip})NEWLINENEWLINE sp_topo[dut][addr_family]['link'].update({link_name: ip_data})NEWLINENEWLINE #st.log("BGP SP - Added IP link {} {}".format(link_name, ip_data))NEWLINE return TrueNEWLINENEWLINE else:NEWLINENEWLINE if not BGPSP.bgp_sp_dut_ip_link_present(dut, link_name, addr_family) :NEWLINE st.log("BGP SP - {} {} does not exist".format(dut, link_name))NEWLINE return TrueNEWLINENEWLINE #if_data = sp_topo[dut]['intf'][link_name]NEWLINE #ip_data = sp_topo[dut][addr_family]['link'][link_name]NEWLINENEWLINE del sp_topo[dut][addr_family]['link'][link_name]NEWLINENEWLINE #st.log("BGP SP - Deleted IP link {} {}".format(link_name, ip_data))NEWLINE return TrueNEWLINENEWLINE #st.log("BGP SP - Link ip {} FAILED".format(action_str))NEWLINE #return FalseNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_connect_all_ip_links():NEWLINENEWLINE st.log("BGP SP - IP link connect all")NEWLINENEWLINE nbr_visited = {}NEWLINE for dut in sp_topo['dut_list']:NEWLINE nbr_visited[dut] = FalseNEWLINENEWLINE addr_family_list = BGPSP.bgp_sp_get_address_family_list("all")NEWLINENEWLINE dut_list = BGPSP.bgp_sp_get_dut_list()NEWLINE dut_list += BGPSP.bgp_sp_get_tg_list()NEWLINENEWLINE for lcl_dut in dut_list:NEWLINE for lcl_link, link_data in sp_topo[lcl_dut]['intf'].items():NEWLINE if 'rmt_dut' in link_data.keys():NEWLINE rmt_dut = link_data['rmt_dut']NEWLINE rmt_link = link_data['rmt_link']NEWLINENEWLINE for afmly in addr_family_list:NEWLINE if lcl_link in sp_topo[lcl_dut][afmly]['link'].keys():NEWLINE if rmt_link in sp_topo[rmt_dut][afmly]['link'].keys():NEWLINENEWLINE lcl_ip = sp_topo[lcl_dut][afmly]['link'][lcl_link]['ip']NEWLINE rmt_ip = sp_topo[rmt_dut][afmly]['link'][rmt_link]['ip']NEWLINENEWLINE sp_topo[lcl_dut][afmly]['link'][lcl_link].update({'rmt_link': rmt_link})NEWLINE sp_topo[lcl_dut][afmly]['link'][lcl_link].update({'rmt_dut': rmt_dut})NEWLINE sp_topo[lcl_dut][afmly]['link'][lcl_link].update({'rmt_ip': rmt_ip})NEWLINENEWLINE sp_topo[rmt_dut][afmly]['link'][rmt_link].update({'rmt_link': lcl_link})NEWLINE sp_topo[rmt_dut][afmly]['link'][rmt_link].update({'rmt_dut': lcl_dut})NEWLINE sp_topo[rmt_dut][afmly]['link'][rmt_link].update({'rmt_ip': lcl_ip})NEWLINENEWLINE nbr_visited[lcl_dut] = TrueNEWLINENEWLINE return TrueNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_add_del_dut_static_network_prefix(dut, prefix, subnet, addr_family, add='yes'):NEWLINENEWLINE action_str = "Add" if add == 'yes' else 'Delete'NEWLINE st.log("BGP SP - Static nw {} for {} {}".format(action_str, dut, prefix))NEWLINENEWLINE if not BGPSP.bgp_sp_dut_present(dut):NEWLINE st.log("BGP SP - Dut {} not present".format(dut))NEWLINE return FalseNEWLINENEWLINE if not BGPSP.bgp_sp_addr_family_valid(addr_family):NEWLINE return FalseNEWLINENEWLINE if add == 'yes' :NEWLINE snw_data = {'subnet': subnet}NEWLINE sp_topo[dut][addr_family]['static_nw'].update({prefix: snw_data})NEWLINE else :NEWLINE if prefix in sp_topo[dut][addr_family]['static_nw']:NEWLINE del sp_topo[dut][addr_family]['static_nw'][prefix]NEWLINENEWLINE return TrueNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_add_del_dut_static_route_prefix(dut, prefix, subnet, next_hop, addr_family, add='yes'):NEWLINENEWLINE action_str = "Add" if add == 'yes' else 'Delete'NEWLINE st.log("BGP SP - {} Static route {} pfx {} nhop {}.".format(action_str, dut, prefix, next_hop))NEWLINENEWLINE if not BGPSP.bgp_sp_dut_present(dut):NEWLINE st.log("BGP SP - Dut {} not present".format(dut))NEWLINE return FalseNEWLINENEWLINE if not BGPSP.bgp_sp_addr_family_valid(addr_family):NEWLINE return FalseNEWLINENEWLINE if add == 'yes' :NEWLINE strt_data = {'nexthop' : next_hop , 'subnet': subnet}NEWLINE sp_topo[dut][addr_family]['static_rt'].update({prefix: strt_data})NEWLINE else :NEWLINE if prefix in sp_topo[dut][addr_family]['static_rt'].keys():NEWLINE del sp_topo[dut][addr_family]['static_rt'][prefix]NEWLINENEWLINE return TrueNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_add_del_dut_network_num(dut, nw_num, addr_family, add='yes'):NEWLINENEWLINE action_str = "Add" if add == 'yes' else 'Delete'NEWLINE st.log("BGP SP - Nw num {} for {} {}".format(action_str, dut, nw_num))NEWLINENEWLINE if not BGPSP.bgp_sp_dut_present(dut):NEWLINE st.log("BGP SP - Dut {} not present".format(dut))NEWLINE return FalseNEWLINENEWLINE if not BGPSP.bgp_sp_addr_family_valid(addr_family):NEWLINE return FalseNEWLINENEWLINE if add == 'yes' :NEWLINE sp_topo[dut][addr_family]['nwoctet'] = nw_numNEWLINE else :NEWLINE sp_topo[dut][addr_family]['nwoctet'] = 0NEWLINENEWLINE return TrueNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_add_del_link_address_octate(link_name, addr_oct_list=[], add='yes'):NEWLINENEWLINE action_str = "Add" if add == 'yes' else 'Delete'NEWLINE st.log("BGP SP - Addr octate {} for {} {}".format(action_str, link_name, addr_oct_list))NEWLINENEWLINE if add == 'yes' :NEWLINE sp_topo['network'].update({link_name: addr_oct_list})NEWLINE else :NEWLINE if link_name in sp_topo['network'].keys():NEWLINE del sp_topo['network'][link_name]NEWLINENEWLINE return TrueNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_bgp_verify_routes_in_dut_list(dut_list=[], route_list=[], addr_family='ipv4', present='yes'):NEWLINENEWLINE st.log("BGP SP - verify route list routes in list of duts")NEWLINENEWLINE if not BGPSP.bgp_sp_addr_family_valid(addr_family):NEWLINE st.log("BGP SP - Invalid address family {}".format(addr_family))NEWLINE return FalseNEWLINENEWLINE if len(dut_list) == 0 :NEWLINE st.log("BGP SP - Dut list List empty")NEWLINE return FalseNEWLINENEWLINE if len(route_list) == 0 :NEWLINE st.log("BGP SP - Route List empty")NEWLINE if present == 'yes' :NEWLINE return TrueNEWLINE else :NEWLINE return FalseNEWLINENEWLINE for dut in dut_list:NEWLINE tb_dut = BGPSP.bgp_sp_get_dut_device(dut)NEWLINENEWLINE result = bgpapi.verify_ip_bgp_route_network_list(tb_dut, addr_family, route_list)NEWLINE if present == 'yes' :NEWLINE if not result :NEWLINE st.log("BGP SP - {} doesnot have routes {} - failed result".format(dut, route_list))NEWLINE return FalseNEWLINE else :NEWLINE st.log("BGP SP - {} has routes {}".format(dut, route_list))NEWLINE else :NEWLINE if result :NEWLINE st.log("BGP SP - {} has routes {} - failed result".format(dut, route_list))NEWLINE return FalseNEWLINE else :NEWLINE st.log("BGP SP - {} doesnot have routes {}".format(dut, route_list))NEWLINENEWLINE if present == 'yes' :NEWLINE st.log("BGP SP - {} has routes {} - Success".format(dut_list, route_list))NEWLINE else:NEWLINE st.log("BGP SP - {} doesnot have routes {} - Success".format(dut_list, route_list))NEWLINENEWLINE return TrueNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_bgp_verify_static_route(dut_list=[], afmly_list=[], present='yes'):NEWLINENEWLINE st.log("BGP SP - verify every has other network due to root reflection")NEWLINE for dut in dut_list:NEWLINE other_dut_list = copy.deepcopy(dut_list)NEWLINE other_dut_list.remove(dut)NEWLINENEWLINE for afmly in afmly_list:NEWLINE #strt_prefix_list = BGPSP.bgp_sp_get_dut_static_route_prefixes(dut, afmly)NEWLINE strt_prefix_list = BGPSP.bgp_sp_get_dut_null_nhop_static_route_prefixes(dut, afmly)NEWLINE strt_prefix_list = BGPSP.bgp_sp_ip_prefix_list_to_route_prefix_list(strt_prefix_list, afmly)NEWLINENEWLINE st.log("BGP SP - {} static route prefixes {}".format(dut, strt_prefix_list))NEWLINENEWLINE result = BGPSP.bgp_sp_bgp_verify_routes_in_dut_list(other_dut_list, strt_prefix_list, afmly, present=present)NEWLINE if not result :NEWLINE st.log("BGP SP - Static route check FAILED")NEWLINE return FalseNEWLINENEWLINE st.log("BGP SP - Static route check Passed")NEWLINE return TrueNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_get_matching_entries(entries=[], match=None):NEWLINE matched_entries = utils.filter_and_select(entries, None, match)NEWLINE if not matched_entries:NEWLINE st.log("\nBGP SP no match {} in\n {}\n".format(match, entries))NEWLINE else :NEWLINE st.log("\nBGP SP Matched {} entries\n {}\n".format(match, matched_entries))NEWLINE return matched_entriesNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_entries_are_matching(entries=[], match=None):NEWLINE matched_entries = BGPSP.bgp_sp_get_matching_entries(entries, match)NEWLINE if not matched_entries:NEWLINE return FalseNEWLINE return TrueNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_get_matching_bgp_ip_routes(dut, route_prefix_list=[], addr_family='ipv4'):NEWLINENEWLINE matched_entries = []NEWLINE tb_dut = BGPSP.bgp_sp_get_dut_device(dut)NEWLINE show_output = bgpapi.show_ip_bgp_route(tb_dut, family=addr_family)NEWLINE #st.log("\nBGP SP ip bgp route \n {}\n".format(show_output))NEWLINENEWLINE if not route_prefix_list :NEWLINE return show_outputNEWLINENEWLINE for route_prefix in route_prefix_list:NEWLINE match = {'network': route_prefix}NEWLINE entries = utils.filter_and_select(show_output, None, match)NEWLINE #st.log("\nBGP SP filtered entries \n {}\n".format(entries))NEWLINE if entries:NEWLINE matched_entries += entriesNEWLINE else :NEWLINE if len(matched_entries) :NEWLINE st.log("BGP SP - Few entries dont match")NEWLINE return []NEWLINENEWLINE #st.log("\nBGP SP route_prefixes Matched entries {}\n".format(matched_entries))NEWLINE return matched_entriesNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_bgp_ip_route_is_matching(dut, route_prefix_list=[], addr_family='ipv4', match=None):NEWLINENEWLINE matched_entries = BGPSP.bgp_sp_get_matching_bgp_ip_routes(dut, route_prefix_list, addr_family)NEWLINE if not matched_entries :NEWLINE return FalseNEWLINENEWLINE if not match:NEWLINE return TrueNEWLINENEWLINE result = BGPSP.bgp_sp_entries_are_matching(matched_entries, match)NEWLINE return resultNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_bgp_ip_route_is_selected(dut, route_prefix_list=[], addr_family='ipv4', match=None):NEWLINENEWLINE matched_entries = BGPSP.bgp_sp_get_matching_bgp_ip_routes(dut, route_prefix_list, addr_family)NEWLINE if not matched_entries :NEWLINE return FalseNEWLINENEWLINE match_selected ={'status_code': '*>'}NEWLINE selected_entries = BGPSP.bgp_sp_get_matching_entries(matched_entries, match_selected)NEWLINE #if not matched_entries:NEWLINE #return FalseNEWLINENEWLINE if not match:NEWLINE return TrueNEWLINENEWLINE result = BGPSP.bgp_sp_entries_are_matching(selected_entries, match)NEWLINE return resultNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_bgp_ip_routes_matching(dut_list=[], route_prefix_list=[], addr_family='ipv4', match=None):NEWLINENEWLINE fail_result_list = []NEWLINE for dut in dut_list :NEWLINE matched_entries = BGPSP.bgp_sp_get_matching_bgp_ip_routes(dut, route_prefix_list, addr_family)NEWLINE if not matched_entries :NEWLINE st.log("BGP SP - {} doesnt have all routes to {}".format(dut, route_prefix_list))NEWLINE fail_result = "BGP SP - {} doesnt have all matching routes ".format(dut)NEWLINE fail_result_list.append(fail_result)NEWLINE continueNEWLINENEWLINE if not match:NEWLINE continueNEWLINENEWLINE result = BGPSP.bgp_sp_entries_are_matching(matched_entries, match)NEWLINE if not result :NEWLINE st.log("BGP SP - {} routes do not match condition {}".format(dut, match))NEWLINE fail_result = "BGP SP - {} routes dont match route condition".format(dut)NEWLINE fail_result_list.append(fail_result)NEWLINE continueNEWLINENEWLINE if len(fail_result_list):NEWLINE st.log("BGP SP - Dut List {}".format(dut_list))NEWLINE st.log("BGP SP - Route Prefix {}".format(route_prefix_list))NEWLINE st.log("BGP SP - Match condition {}".format(match))NEWLINE for fail_result in fail_result_list:NEWLINE st.log("{}".format(fail_result))NEWLINE st.log("BGP SP - IP routes not matching")NEWLINE return FalseNEWLINENEWLINE st.log("BGP SP - IP routes matching")NEWLINE return TrueNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_bgp_ip_routes_not_matching(dut_list=[], route_prefix_list=[], addr_family='ipv4', match=None):NEWLINENEWLINE result = BGPSP.bgp_sp_bgp_ip_routes_matching(dut_list, route_prefix_list, addr_family, match)NEWLINE if result :NEWLINE return FalseNEWLINE else :NEWLINE return TrueNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_dut_verify_bgp_ip_routes(dut, route_prefix_list=[], addr_family='ipv4', match=None):NEWLINENEWLINE if not BGPSP.bgp_sp_dut_present(dut):NEWLINE st.log("Dut {} not present".format(dut))NEWLINE return FalseNEWLINENEWLINE matched_entries = BGPSP.bgp_sp_get_matching_bgp_ip_routes(dut, route_prefix_list, addr_family)NEWLINE if not matched_entries :NEWLINE st.log("BGP SP - {} doesnt have all routes {}".format(dut, route_prefix_list))NEWLINE return FalseNEWLINENEWLINE if match:NEWLINE result = BGPSP.bgp_sp_entries_are_matching(matched_entries, match)NEWLINE if not result :NEWLINE st.log("BGP SP - {} routes do not match condition {}".format(dut, match))NEWLINE return FalseNEWLINENEWLINE st.log("BGP SP - {} IP routes matching".format(dut))NEWLINE return TrueNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_verify_bgp_ip_routes(dut_list, route_prefix_list=[], addr_family='ipv4', match=None, threaded_run=True):NEWLINENEWLINE st.log("BGP SP - Verify that {} has BGP routes {}".format(dut_list,route_prefix_list))NEWLINENEWLINE result = TrueNEWLINENEWLINE dut_list = list(dut_list) if isinstance(dut_list, list) else [dut_list]NEWLINE if not dut_list or len(dut_list) < 2: threaded_run = FalseNEWLINENEWLINE dut_thread = []NEWLINE fail_result_list = []NEWLINENEWLINE for dut in dut_list :NEWLINE dut_result = TrueNEWLINE if threaded_run:NEWLINE dut_thread.append([BGPSP.bgp_sp_dut_verify_bgp_ip_routes, dut, route_prefix_list, addr_family, match])NEWLINE else :NEWLINE dut_result = BGPSP.bgp_sp_dut_verify_bgp_ip_routes(dut, route_prefix_list, addr_family, match)NEWLINENEWLINE if not dut_result:NEWLINE result = FalseNEWLINE st.log("BGP SP - {} routes do not match condition {}".format(dut, match))NEWLINE fail_result = "BGP SP - {} routes dont match route condition".format(dut)NEWLINE fail_result_list.append(fail_result)NEWLINE breakNEWLINENEWLINE if threaded_run:NEWLINE [out, exceptions] = putils.exec_all(bgplib.fast_start, dut_thread)NEWLINE st.log("BGP SP - BGP Route match Threaded Run result {}".format([out, exceptions]))NEWLINE if False in out : result = FalseNEWLINENEWLINE if not result or len(fail_result_list):NEWLINE st.log("BGP SP - Dut List {}".format(dut_list))NEWLINE st.log("BGP SP - Route Prefix {}".format(route_prefix_list))NEWLINE st.log("BGP SP - Match condition {}".format(match))NEWLINE for fail_result in fail_result_list:NEWLINE st.log("{}".format(fail_result))NEWLINE st.log("BGP SP - IP routes not matching")NEWLINE return FalseNEWLINENEWLINE st.log("BGP SP - IP routes matching")NEWLINE return TrueNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_verify_no_bgp_ip_routes(dut_list, route_prefix_list=[], addr_family='ipv4', match=None, threaded_run=True):NEWLINENEWLINE result = BGPSP.bgp_sp_verify_bgp_ip_routes(dut_list, route_prefix_list, addr_family, match, threaded_run)NEWLINE if not result :NEWLINE result = TrueNEWLINE else :NEWLINE result = FalseNEWLINE return resultNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_find_tb_connected_link(lcl_dut, lcl_if, rmt_tb, rmt_if):NEWLINENEWLINE connected_link = { 'connected': False,NEWLINE 'lcl_dut' : lcl_dut,NEWLINE 'lcl_tb' : '',NEWLINE 'lcl_link': '',NEWLINE 'lcl_if' : lcl_if,NEWLINE 'rmt_dut' : '',NEWLINE 'rmt_tb' : rmt_tb,NEWLINE 'rmt_link': '',NEWLINE 'rmt_if' : rmt_if }NEWLINENEWLINE connected_link['lcl_tb'] = BGPSP.bgp_sp_get_dut_device(lcl_dut)NEWLINE if connected_link['lcl_tb'] == '' :NEWLINE st.log("BGP SP - No lcl_tb, Link NOT connected {}".format(connected_link))NEWLINE return connected_linkNEWLINENEWLINE connected_link['rmt_dut'] = BGPSP.bgp_sp_get_dut_from_device(rmt_tb)NEWLINE if connected_link['rmt_dut'] == '' :NEWLINE st.log("BGP SP - No rmt dut, Link NOT connected {}".format(connected_link))NEWLINE return connected_linkNEWLINENEWLINE tb_vars = st.get_testbed_vars()NEWLINE tb_vars_keys = tb_vars.keys()NEWLINENEWLINE for port_idx in range(1,20) :NEWLINE link_name = "{}{}P{}".format(connected_link['lcl_dut'],NEWLINE connected_link['rmt_dut'], port_idx)NEWLINE if link_name in tb_vars_keys :NEWLINE temp_lcl_if = tb_vars[link_name]NEWLINE if temp_lcl_if == lcl_if :NEWLINE connected_link['lcl_link'] = link_nameNEWLINE breakNEWLINENEWLINE for port_idx in range(1,20) :NEWLINE link_name = "{}{}P{}".format(connected_link['rmt_dut'],NEWLINE connected_link['lcl_dut'], port_idx)NEWLINE if link_name in tb_vars_keys :NEWLINE temp_rmt_if = tb_vars[link_name]NEWLINE if temp_rmt_if == rmt_if :NEWLINE connected_link['rmt_link'] = link_nameNEWLINE breakNEWLINENEWLINE if connected_link['lcl_link'] != '' and connected_link['rmt_link'] != '' :NEWLINE connected_link['connected'] = TrueNEWLINE st.log("BGP SP - Link connected {}".format(connected_link))NEWLINE return copy.deepcopy(connected_link)NEWLINENEWLINE st.log("BGP SP - Link NOT connected {}".format(connected_link))NEWLINE return {'connected': False }NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_setup_testbed_topology(per_node_nw='no', nw_ip_octet='10'):NEWLINE st.banner("BGP SP - BUILD TOPOLOGY - START")NEWLINE tb_vars = st.get_testbed_vars()NEWLINE tb_var_keys = tb_vars.keys()NEWLINE st.log("TestBed Vars => {}\n".format(tb_vars))NEWLINENEWLINE sub_nw_idx = 32NEWLINE sp_topo['dut_list'] = []NEWLINE sp_topo['tg_list'] = []NEWLINE sp_topo['dut_map'] = {}NEWLINE sp_topo['tg_map'] = {}NEWLINE sp_topo['network'] = {}NEWLINE sp_topo['subtopo'] = {}NEWLINE sp_topo['subtopo']['linear'] = { 'found': False }NEWLINE sp_topo['subtopo']['ring'] = { 'found': False }NEWLINE sp_topo['subtopo']['star'] = {'found': False}NEWLINE sp_topo['subtopo']['spine_leaf'] = {'found': False}NEWLINENEWLINENEWLINE tb_dut_count = len(tb_vars.dut_list)NEWLINE for dut_idx in range(1, tb_dut_count+1) :NEWLINE dut = "D{}".format(dut_idx)NEWLINE if dut in tb_var_keys :NEWLINE sp_topo['dut_map'][dut] = tb_vars[dut]NEWLINENEWLINE tb_tg_count = len(tb_vars.tgen_list)NEWLINE for tg_idx in range(1, tb_tg_count+1) :NEWLINE tgen = "T{}".format(tg_idx)NEWLINE if tgen in tb_var_keys :NEWLINE sp_topo['tg_map'][tgen] = tb_vars[tgen]NEWLINENEWLINE st.log("BGP SP - Testbed Dut List {}".format(sp_topo['dut_map']))NEWLINE st.log("BGP SP - Testbed Tgen List {}".format(sp_topo['tg_map']))NEWLINENEWLINE dut_idx = 0NEWLINE for dut, tb_dut_name in sp_topo['dut_map'].items():NEWLINENEWLINE dut_idx += 1NEWLINENEWLINE result = BGPSP.bgp_sp_add_del_dut(dut, tb_dut_name, add='yes')NEWLINE if not result:NEWLINE st.log("BGP SP - Dut {} add {} FAILED".format(dut, tb_dut_name))NEWLINENEWLINE if per_node_nw == 'no' :NEWLINE nw_ipv4_octet = nw_ip_octetNEWLINE else :NEWLINE nw_ipv4_octet = int(nw_ip_octet) + dut_idxNEWLINENEWLINE BGPSP.bgp_sp_add_del_dut_network_num(dut, nw_ipv4_octet, 'ipv4', 'yes')NEWLINE nw_ipv6_octet = "97{}".format(nw_ipv4_octet)NEWLINE BGPSP.bgp_sp_add_del_dut_network_num(dut, nw_ipv6_octet, 'ipv6', 'yes')NEWLINENEWLINENEWLINE for dut, tb_dut_name in sp_topo['tg_map'].items():NEWLINENEWLINE dut_idx += 1NEWLINENEWLINE result = BGPSP.bgp_sp_add_del_dut(dut, tb_dut_name, device_type='TG', add='yes')NEWLINE if not result:NEWLINE st.log("BGP SP - TG Dut {} add {} FAILED".format(dut, tb_dut_name))NEWLINENEWLINE if per_node_nw == 'no' :NEWLINE nw_ipv4_octet = nw_ip_octetNEWLINE else :NEWLINE nw_ipv4_octet = int(nw_ip_octet) + dut_idxNEWLINENEWLINE BGPSP.bgp_sp_add_del_dut_network_num(dut, nw_ipv4_octet, 'ipv4', 'yes')NEWLINE nw_ipv6_octet = "97{}".format(nw_ipv4_octet)NEWLINE BGPSP.bgp_sp_add_del_dut_network_num(dut, nw_ipv6_octet, 'ipv6', 'yes')NEWLINENEWLINENEWLINE sp_topo['dut_list'].sort()NEWLINE sp_topo['tg_list'].sort()NEWLINE #st.log("SP topo after dut add:\n{}\n".format(sp_topo))NEWLINENEWLINE for from_dut_idx, from_dut in enumerate(sp_topo['dut_list'], start = 1):NEWLINENEWLINE for count in range(0,2):NEWLINE intf_name = "Loopback{}".format(count)NEWLINE link_name = "{}L{}".format(from_dut, count)NEWLINENEWLINE result = BGPSP.bgp_sp_add_del_link(from_dut, 'LBK', link_name, intf_name, add='yes')NEWLINE if not result:NEWLINE st.log("Loopback interface {} add FAILED".format(link_name))NEWLINENEWLINE nwoct4 = "{}".format(sp_topo[from_dut]['ipv4']['nwoctet'])NEWLINE nwoct3 = 8NEWLINE nwoct2 = count + 1NEWLINENEWLINE lo_ip = "{}.{}.{}.{}".format(nwoct4, nwoct3, nwoct2, from_dut_idx)NEWLINE result = BGPSP.bgp_sp_add_del_link_ip(from_dut, link_name, lo_ip, 32, "", 'ipv4', add='yes')NEWLINE if not result:NEWLINE st.log("Loopback interface IPv4 {} add FAILED".format(link_name))NEWLINENEWLINE lo_ip = "{}:{}{}:{}{}::{}".format(nwoct4, from_dut_idx, nwoct3, nwoct2, count+1, from_dut_idx)NEWLINE result = BGPSP.bgp_sp_add_del_link_ip(from_dut, link_name, lo_ip, 128, "", 'ipv6', add='yes')NEWLINE if not result:NEWLINE st.log("Loopback interface IPv6 {} add FAILED".format(link_name))NEWLINENEWLINE addr_oct_list = [nwoct4, nwoct3, nwoct2, from_dut_idx]NEWLINE BGPSP.bgp_sp_add_del_link_address_octate(link_name, addr_oct_list, add='yes')NEWLINENEWLINE #st.log("SP topo after dut loopback add :\n{}\n".format(sp_topo))NEWLINENEWLINE lcl_dut = from_dutNEWLINE lcl_tb = BGPSP.bgp_sp_get_dut_device(lcl_dut)NEWLINENEWLINE dut_links = st.get_dut_links(lcl_tb)NEWLINE tg_links = st.get_tg_links(lcl_tb)NEWLINENEWLINE dut_all_links = dut_links + tg_linksNEWLINE st.log("BGP SP - Dut {} links {}".format(lcl_dut, dut_all_links))NEWLINENEWLINE for link_idx, link in enumerate(dut_all_links , start = 1):NEWLINENEWLINE link_data = BGPSP.bgp_sp_find_tb_connected_link(lcl_dut, link[0], link[1], link[2])NEWLINE if not link_data['connected'] :NEWLINE continueNEWLINENEWLINE rmt_dut = link_data['rmt_dut']NEWLINE #rmt_tb = link_data['rmt_tb']NEWLINENEWLINE lcl_if = link_data['lcl_if']NEWLINE rmt_if = link_data['rmt_if']NEWLINENEWLINE lcl_link = link_data['lcl_link']NEWLINE rmt_link = link_data['rmt_link']NEWLINENEWLINE BGPSP.bgp_sp_add_del_link(lcl_dut, 'ETH', lcl_link, lcl_if, add='yes')NEWLINENEWLINE if BGPSP.bgp_sp_dut_is_tg(rmt_dut) :NEWLINE BGPSP.bgp_sp_add_del_link(rmt_dut, 'ETH', rmt_link, rmt_if, add='yes')NEWLINENEWLINE if BGPSP.bgp_sp_dut_link_present(rmt_dut, rmt_link):NEWLINE BGPSP.bgp_sp_connect_links(lcl_dut, lcl_link, rmt_dut, rmt_link)NEWLINENEWLINE if lcl_link in sp_topo['network'].keys() :NEWLINE nwoct4 = sp_topo['network'][lcl_link][0]NEWLINE nwoct3 = sp_topo['network'][lcl_link][1]NEWLINE nwoct2 = sp_topo['network'][lcl_link][2]NEWLINE elif rmt_link in sp_topo['network'].keys():NEWLINE nwoct4 = sp_topo['network'][rmt_link][0]NEWLINE nwoct3 = sp_topo['network'][rmt_link][1]NEWLINE nwoct2 = sp_topo['network'][rmt_link][2]NEWLINE else :NEWLINE nwoct4 = "{}".format(sp_topo[lcl_dut]['ipv4']['nwoctet'])NEWLINE nwoct3 = sub_nw_idxNEWLINE sub_nw_idx += 2NEWLINE nwoct2 = link_idx #from_dut_idxNEWLINENEWLINE if link_data['lcl_dut'] < link_data['rmt_dut'] :NEWLINE lcl_host_num = 1NEWLINE rmt_host_num = 2NEWLINE else:NEWLINE lcl_host_num = 2NEWLINE rmt_host_num = 1NEWLINENEWLINE lcl_ip = "{}.{}.{}.{}".format(nwoct4, nwoct3, nwoct2, lcl_host_num)NEWLINE rmt_ip = "{}.{}.{}.{}".format(nwoct4, nwoct3, nwoct2, rmt_host_num)NEWLINENEWLINE BGPSP.bgp_sp_add_del_link_ip(lcl_dut, lcl_link, lcl_ip, 24, rmt_ip, 'ipv4', add='yes')NEWLINENEWLINE if BGPSP.bgp_sp_dut_is_tg(rmt_dut) :NEWLINE BGPSP.bgp_sp_add_del_link_ip(rmt_dut, rmt_link, rmt_ip, 24, lcl_ip, 'ipv4', add='yes')NEWLINENEWLINE lcl_ip = "{}:{}:{}::{}".format(nwoct4, nwoct3, nwoct2, lcl_host_num)NEWLINE rmt_ip = "{}:{}:{}::{}".format(nwoct4, nwoct3, nwoct2, rmt_host_num)NEWLINENEWLINE BGPSP.bgp_sp_add_del_link_ip(lcl_dut, lcl_link, lcl_ip, 64, rmt_ip, 'ipv6', add='yes')NEWLINENEWLINE if BGPSP.bgp_sp_dut_is_tg(rmt_dut) :NEWLINE BGPSP.bgp_sp_add_del_link_ip(rmt_dut, rmt_link, rmt_ip, 64, lcl_ip, 'ipv6', add='yes')NEWLINENEWLINE addr_oct_list = [nwoct4, nwoct3, nwoct2, lcl_host_num]NEWLINE BGPSP.bgp_sp_add_del_link_address_octate(lcl_link, addr_oct_list, add='yes')NEWLINENEWLINE if BGPSP.bgp_sp_dut_is_tg(rmt_dut) :NEWLINE BGPSP.bgp_sp_add_del_link_address_octate(rmt_link, addr_oct_list, add='yes')NEWLINENEWLINENEWLINE #st.log("SP topo after {} interface add :\n{}\n".format(from_dut, sp_topo))NEWLINENEWLINE for count in range(1,3):NEWLINE link_name = "{}N{}".format(from_dut, count)NEWLINE nwoct4 = 216NEWLINE nwoct3 = 50 + countNEWLINE nwoct2 = from_dut_idxNEWLINENEWLINE st_nw = "{}.{}.{}.{}".format(nwoct4, nwoct3, nwoct2, 0)NEWLINE BGPSP.bgp_sp_add_del_dut_static_network_prefix(from_dut, st_nw, 24, 'ipv4', add='yes')NEWLINENEWLINE st_nw = "{}:{}:{}::{}".format(nwoct4, nwoct3, nwoct2, 0)NEWLINE BGPSP.bgp_sp_add_del_dut_static_network_prefix(from_dut, st_nw, 86, 'ipv6', add='yes')NEWLINENEWLINE addr_oct_list = [nwoct4, nwoct3, nwoct2, 0]NEWLINE BGPSP.bgp_sp_add_del_link_address_octate(link_name, addr_oct_list, add='yes')NEWLINENEWLINE for count in range(1,2):NEWLINE link_name = "{}RN{}".format(from_dut, count)NEWLINE nwoct4 = 209NEWLINE nwoct3 = 90 + countNEWLINE nwoct2 = from_dut_idxNEWLINE next_hop = "Null0"NEWLINENEWLINE st_rt = "{}.{}.{}.{}".format(nwoct4, nwoct3, nwoct2, 0)NEWLINE BGPSP.bgp_sp_add_del_dut_static_route_prefix(from_dut, st_rt, 24, next_hop, 'ipv4', add='yes')NEWLINENEWLINE st_rt = "{}:{}:{}::{}".format(nwoct4, nwoct3, nwoct2, 0)NEWLINE BGPSP.bgp_sp_add_del_dut_static_route_prefix(from_dut, st_rt, 64, next_hop, 'ipv6', add='yes')NEWLINENEWLINE addr_oct_list = [nwoct4, nwoct3, nwoct2, 0]NEWLINE BGPSP.bgp_sp_add_del_link_address_octate(link_name, addr_oct_list, add='yes')NEWLINENEWLINE for count in range(1,2):NEWLINE link_name = "{}RS{}".format(from_dut, count)NEWLINE nwoct4 = 208NEWLINE nwoct3 = 80 + countNEWLINE nwoct2 = from_dut_idxNEWLINENEWLINE st_rt = "{}.{}.{}.{}".format(nwoct4, nwoct3, nwoct2, 0)NEWLINE #next_hop = BGPSP.bgp_sp_get_dut_loopback_ip(from_dut, 0, 'ipv4')NEWLINE next_hop = BGPSP.bgp_sp_get_unused_dut_interface(from_dut)NEWLINE BGPSP.bgp_sp_add_del_dut_static_route_prefix(from_dut, st_rt, 24, next_hop, 'ipv4', add='yes')NEWLINENEWLINE st_rt = "{}:{}:{}::{}".format(nwoct4, nwoct3, nwoct2, 0)NEWLINE #next_hop = BGPSP.bgp_sp_get_dut_loopback_ip(from_dut, 0, 'ipv6')NEWLINE next_hop = BGPSP.bgp_sp_get_unused_dut_interface(from_dut)NEWLINE BGPSP.bgp_sp_add_del_dut_static_route_prefix(from_dut, st_rt, 64, next_hop, 'ipv6', add='yes')NEWLINENEWLINE addr_oct_list = [nwoct4, nwoct3, nwoct2, 0]NEWLINE BGPSP.bgp_sp_add_del_link_address_octate(link_name, addr_oct_list, add='yes')NEWLINENEWLINE #st.log("SP topo for {} :\n{}\n".format(from_dut, sp_topo))NEWLINENEWLINE #st.log("SP topo at testbed topobuild complete:\n{}\n".format(sp_topo))NEWLINENEWLINE BGPSP.bgp_sp_connect_all_ip_links()NEWLINENEWLINE BGPSP.bgp_sp_show_dut_topo_data()NEWLINENEWLINE st.banner("BGP SP - BUILD TOPOLOGY - END")NEWLINENEWLINE return TrueNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_clear_testbed_topology(per_node_nw='no', nw_ip_octet='10'):NEWLINE sp_topo.clear()NEWLINE bgp_topo.clear()NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_test_topo_present(topo_path=None, dut_count=None, segment_count=None):NEWLINENEWLINE if dut_count :NEWLINE if BGPSP.bgp_sp_get_dut_count() < dut_count :NEWLINE st.log("BGP SP - Test case needs minimum {} duts in testbed".format(dut_count))NEWLINE return FalseNEWLINENEWLINE if not topo_path :NEWLINE st.log("BGP SP - Testbed Topology path is Null")NEWLINE return FalseNEWLINENEWLINE if 'found' not in topo_path.keys() :NEWLINE st.log("BGP SP - Invalid Path")NEWLINE return FalseNEWLINENEWLINE if not topo_path['found'] :NEWLINE st.log("BGP SP - Required Topology path not found")NEWLINE return FalseNEWLINENEWLINE if segment_count :NEWLINE if topo_path['segment_count'] < segment_count :NEWLINE st.log("BGP SP - Test case needs minimum {} segments in Topology path".format(segment_count))NEWLINE return FalseNEWLINENEWLINE return TrueNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_show_dut_topo_data(dut_list = []):NEWLINENEWLINE if not dut_list :NEWLINE dut_list = BGPSP.bgp_sp_get_dut_list()NEWLINE dut_list += BGPSP.bgp_sp_get_tg_list()NEWLINENEWLINE st.log("\n")NEWLINE st.log("BGP SP - Dut List: {}".format(sp_topo['dut_list']))NEWLINE st.log("BGP SP - Dut Dev Map: {}".format(sp_topo['dut_map']))NEWLINE st.log("BGP SP - TG List: {}".format(sp_topo['tg_list']))NEWLINE st.log("BGP SP - TG Dev Map: {}".format(sp_topo['tg_map']))NEWLINENEWLINE for dut in dut_list:NEWLINE if not BGPSP.bgp_sp_dut_present(dut) :NEWLINE continueNEWLINENEWLINE st.log("\n")NEWLINE st.log("BGP SP - Dut {} {} {}".format(dut, sp_topo[dut]['type'], sp_topo[dut]['device']))NEWLINENEWLINE for intf, intf_data in sp_topo[dut]['intf'].items():NEWLINE st.log(" Intf {} {}".format(intf, intf_data))NEWLINENEWLINE for link, link_data in sp_topo[dut]['ipv4']['link'].items():NEWLINE st.log(" Ipv4 Link {} {}".format(link, link_data))NEWLINE for link, link_data in sp_topo[dut]['ipv6']['link'].items():NEWLINE st.log(" Ipv6 Link {} {}".format(link, link_data))NEWLINENEWLINE for stnw, stnw_data in sp_topo[dut]['ipv4']['static_nw'].items():NEWLINE st.log(" Static Ipv4 Nw {} {}".format(stnw, stnw_data))NEWLINE for stnw, stnw_data in sp_topo[dut]['ipv6']['static_nw'].items():NEWLINE st.log(" Static IPv6 Nw {} {}".format(stnw, stnw_data))NEWLINENEWLINE for strt, strt_data in sp_topo[dut]['ipv4']['static_rt'].items():NEWLINE st.log(" Static Ipv4 Route {} {}".format(strt, strt_data))NEWLINE for strt, strt_data in sp_topo[dut]['ipv6']['static_rt'].items():NEWLINE st.log(" Static IPv6 Route {} {}".format(strt, strt_data))NEWLINENEWLINE st.log(" Ipv4 Network Octates {}".format(sp_topo[dut]['ipv4']['nwoctet']))NEWLINE st.log(" IPv6 Network Octates {}".format(sp_topo[dut]['ipv6']['nwoctet']))NEWLINENEWLINE st.log("\n")NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_show_topo_path(path):NEWLINENEWLINE if not path :NEWLINE st.log("BGP SP - Path Null")NEWLINE returnNEWLINENEWLINE if 'type' not in path.keys():NEWLINE st.log("BGP SP - Path Type Not found")NEWLINE returnNEWLINENEWLINE if 'found' not in path.keys():NEWLINE st.log("BGP SP - Path Invalid")NEWLINE returnNEWLINENEWLINE path_found = "Found" if path['found'] else "Not Found"NEWLINENEWLINE st.log("BGP SP - {} Topo Path {}".format(path['type'], path_found))NEWLINE if not path['found'] : returnNEWLINENEWLINE st.log(" Dut List: {}".format(path['dut_list']))NEWLINE st.log(" Segt Count: {}".format(path['segment_count']))NEWLINE for segt_idx, segt_data in path['segment'].items():NEWLINE st.log(" Segment-{}: ".format(segt_idx))NEWLINE for link_idx, link_data in segt_data.items():NEWLINE st.log(" Link-{}: {}".format(link_idx, link_data))NEWLINE st.log("\n")NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_show_dut_if_cmd_logs(dut):NEWLINE tb_dut = BGPSP.bgp_sp_get_dut_device(dut)NEWLINE st.show(tb_dut, "show ip interface")NEWLINE st.show(tb_dut, "show ipv6 interface")NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_show_dut_route_cmd_logs(dut):NEWLINE tb_dut = BGPSP.bgp_sp_get_dut_device(dut)NEWLINE st.vtysh_show(tb_dut, "show ip route")NEWLINE st.vtysh_show(tb_dut, "show ipv6 route")NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_show_dut_bgp_cmd_logs(dut):NEWLINE tb_dut = BGPSP.bgp_sp_get_dut_device(dut)NEWLINE st.vtysh_config(tb_dut, "do show running-config bgp")NEWLINE st.vtysh_show(tb_dut, "show ip bgp summary")NEWLINE st.vtysh_show(tb_dut, "show bgp ipv4")NEWLINE st.vtysh_show(tb_dut, "show bgp ipv6")NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_show_dut_cmd_logs(dut):NEWLINE BGPSP.bgp_sp_show_dut_if_cmd_logs(dut)NEWLINE BGPSP.bgp_sp_show_dut_route_cmd_logs(dut)NEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_show_dut_bgp_running_config(dut_list=[]):NEWLINE for dut in dut_list :NEWLINE tb_dut = BGPSP.bgp_sp_get_dut_device(dut)NEWLINE st.vtysh_config(tb_dut, "do show running-config bgp")NEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_loopback_interface_config_unconfig(config='yes', vrf='default', threaded_run=True):NEWLINE """NEWLINENEWLINE :param config:NEWLINE :param vrf:NEWLINE :return:NEWLINE """NEWLINE action_str = 'Config' if config == 'yes' else 'Unconfig'NEWLINE st.banner("{}uring LOOPBACK Interface on all nodes.".format(action_str))NEWLINENEWLINE result = TrueNEWLINE #threaded_run = TrueNEWLINENEWLINE dut_list = BGPSP.bgp_sp_get_dut_list() #+ BGPSP.bgp_sp_get_tg_list()NEWLINE dut_thread = []NEWLINENEWLINE for dut in dut_list :NEWLINE tb_dut = sp_topo[dut]['device']NEWLINE lpbk_if_data = {}NEWLINENEWLINE if BGPSP.bgp_sp_dut_is_tg(dut) :NEWLINE st.log("BGP SP - TG {} Loopback config not done for now".format(dut))NEWLINE continueNEWLINENEWLINE for _, link_data in sp_topo[dut]['intf'].items():NEWLINE if link_data['type'] != 'LBK':NEWLINE continueNEWLINENEWLINE if_name = link_data['if']NEWLINE lpbk_if_data[if_name] = 'default'NEWLINENEWLINENEWLINE loopback_names = list(lpbk_if_data.keys())NEWLINE if threaded_run:NEWLINE dut_thread.append(putils.ExecAllFunc(ipapi.config_loopback_interfaces, tb_dut, loopback_name=loopback_names, config=config))NEWLINE else :NEWLINE result = ipapi.config_loopback_interfaces(tb_dut, loopback_name=loopback_names, config=config)NEWLINE if not result :NEWLINE st.log("{}uring {} loopback interfaces FAILED".format(action_str, dut))NEWLINE return FalseNEWLINENEWLINE if threaded_run:NEWLINE [out, exceptions] = putils.exec_all(bgplib.fast_start, dut_thread)NEWLINE st.log("BGP SP - Threaded Run result {}".format([out, exceptions]))NEWLINE if False in out : result = FalseNEWLINENEWLINE return resultNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_loopback_address_config_unconfig(config='yes', vrf='default', addr_family='all', threaded_run=True, debug_run=False):NEWLINE """NEWLINENEWLINE :param config:NEWLINE :param vrf:NEWLINE :param addr_family:NEWLINE :return:NEWLINE """NEWLINE action_str = 'Config' if config == 'yes' else 'Unconfig'NEWLINE st.banner("{}uring LOOPBACK Addresses on all nodes.".format(action_str))NEWLINENEWLINE if not BGPSP.bgp_sp_topology_data_present() :NEWLINE st.log("BGP SP Topology data not available")NEWLINE st.log("SP topo:\n{}\n".format(sp_topo))NEWLINE return FalseNEWLINENEWLINE #threaded_run = TrueNEWLINE #debug_run = FalseNEWLINE result = TrueNEWLINE config = 'add' if config == 'yes' else 'remove'NEWLINENEWLINE addr_family_list = BGPSP.bgp_sp_get_address_family_list(addr_family)NEWLINE dut_thread = []NEWLINENEWLINE dut_list = BGPSP.bgp_sp_get_dut_list() #+ BGPSP.bgp_sp_get_tg_list()NEWLINENEWLINE for dut in dut_list :NEWLINE tb_dut = sp_topo[dut]['device']NEWLINE if_data_list = []NEWLINENEWLINE if BGPSP.bgp_sp_dut_is_tg(dut) :NEWLINE st.log("BGP SP - TG {} Loopback IP config not done for now".format(dut))NEWLINE continueNEWLINENEWLINE for afmly in addr_family_list:NEWLINE for _, link_data in sp_topo[dut][afmly]['link'].items():NEWLINE if link_data['type'] != 'LBK':NEWLINE continueNEWLINENEWLINE lpbk_if = link_data['if']NEWLINE lpbk_ip = link_data['ip']NEWLINE subnet = link_data['subnet']NEWLINENEWLINE if_data_list.append({'name': lpbk_if, 'ip': lpbk_ip, 'subnet': subnet, 'family': afmly })NEWLINE st.log("{}uring {} Loopback {}:{} {} {} ".format(action_str, afmly, dut, tb_dut, lpbk_if, lpbk_ip))NEWLINENEWLINE if threaded_run:NEWLINE dut_thread.append([ipapi.config_unconfig_interface_ip_addresses, tb_dut, if_data_list, config])NEWLINE else :NEWLINE result = ipapi.config_unconfig_interface_ip_addresses(tb_dut, if_data_list, config=config)NEWLINE if not result:NEWLINE BGPSP.bgp_sp_show_dut_cmd_logs(dut)NEWLINE st.log("{}uring {} loopback address FAILED".format(action_str, dut))NEWLINE return FalseNEWLINENEWLINE if debug_run:NEWLINE BGPSP.bgp_sp_show_dut_if_cmd_logs(dut)NEWLINENEWLINE if threaded_run:NEWLINE [out, exceptions] = putils.exec_all(bgplib.fast_start, dut_thread)NEWLINE st.log("BGP SP - Threaded Run result {}".format([out, exceptions]))NEWLINE if False in out : result = FalseNEWLINENEWLINE return resultNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_interface_address_all_config_unconfig(config='yes', vrf='default', addr_family='all', threaded_run=True, debug_run=False):NEWLINE """NEWLINENEWLINE :param config:NEWLINE :param vrf:NEWLINE :param addr_family:NEWLINE :return:NEWLINE """NEWLINENEWLINE action_str = 'Config' if config == 'yes' else 'Unconfig'NEWLINE st.banner("{}uring Interface Addresses on all nodes.".format(action_str))NEWLINENEWLINE if not BGPSP.bgp_sp_topology_data_present() :NEWLINE st.log("BGP SP Topology data not available")NEWLINE st.log("SP topo:\n{}\n".format(sp_topo))NEWLINE return FalseNEWLINENEWLINE #threaded_run = TrueNEWLINE #debug_run = FalseNEWLINE result = TrueNEWLINENEWLINE config = 'add' if config == 'yes' else 'remove'NEWLINENEWLINE addr_family_list = BGPSP.bgp_sp_get_address_family_list(addr_family)NEWLINE dut_thread = []NEWLINENEWLINE dut_list = BGPSP.bgp_sp_get_dut_list()NEWLINENEWLINE for dut in dut_list :NEWLINE tb_dut = sp_topo[dut]['device']NEWLINENEWLINE if_data_list = []NEWLINENEWLINE for afmly in addr_family_list:NEWLINE for link_name, link_data in sp_topo[dut][afmly]['link'].items():NEWLINE if link_data['type'] == 'LBK':NEWLINE continueNEWLINENEWLINE link_ip = link_data['ip']NEWLINE link_if = link_data['if']NEWLINE subnet = link_data['subnet']NEWLINENEWLINE if_data_list.append({'name': link_if, 'ip': link_ip, 'subnet': subnet, 'family':afmly })NEWLINENEWLINE st.log("{}uring {} Interface {}:{} {}:{} {} ".format(action_str, afmly, dut,NEWLINE tb_dut, link_name, link_if, link_ip))NEWLINENEWLINE if threaded_run:NEWLINE dut_thread.append([ipapi.config_unconfig_interface_ip_addresses, tb_dut, if_data_list, config])NEWLINE else :NEWLINE result = ipapi.config_unconfig_interface_ip_addresses(tb_dut, if_data_list, config=config)NEWLINE if not result:NEWLINE BGPSP.bgp_sp_show_dut_cmd_logs(dut)NEWLINE st.log("{}uring {} Interface address FAILED".format(action_str, dut))NEWLINE return FalseNEWLINENEWLINE if debug_run:NEWLINE BGPSP.bgp_sp_show_dut_if_cmd_logs(dut)NEWLINENEWLINE if threaded_run:NEWLINE [out, exceptions] = putils.exec_all(bgplib.fast_start, dut_thread)NEWLINE st.log("BGP SP - Threaded Run result {}".format([out, exceptions]))NEWLINE if False in out : result = FalseNEWLINENEWLINE return resultNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_tg_interface_ip_all_config_unconfig(config='yes', vrf='default', addr_family='all', threaded_run=True):NEWLINE """NEWLINENEWLINE :param config:NEWLINE :param vrf:NEWLINE :param addr_family:NEWLINE :return:NEWLINE """NEWLINENEWLINE action_str = 'Config' if config == 'yes' else 'Unconfig'NEWLINE st.banner("{}uring Interface Addresses on all TGENs.".format(action_str))NEWLINENEWLINE if not BGPSP.bgp_sp_topology_data_present() :NEWLINE st.log("BGP SP Topology data not available")NEWLINE st.log("SP topo:\n{}\n".format(sp_topo))NEWLINE return FalseNEWLINENEWLINE result = TrueNEWLINE #threaded_run = TrueNEWLINE dut_thread = []NEWLINENEWLINE dut_list = BGPSP.bgp_sp_get_tg_list()NEWLINENEWLINE for dut in dut_list :NEWLINE tb_dut = sp_topo[dut]['device']NEWLINE tg = tgen_obj_dict[tb_dut]NEWLINENEWLINE for link_name, link_data in sp_topo[dut]['intf'].items():NEWLINE if link_data['type'] == 'LBK':NEWLINE continueNEWLINENEWLINE tb_if = link_data['if']NEWLINE tg_port_handle = tg.get_port_handle(tb_if)NEWLINENEWLINE if config == 'yes' :NEWLINE st.log("\n")NEWLINE st.log("BGP SP - Resetting TG port {} {}".format(tb_dut, tb_if))NEWLINE tg.tg_traffic_control(action="reset", port_handle=tg_port_handle)NEWLINE st.log("\n")NEWLINENEWLINE if threaded_run:NEWLINE dut_thread.append([BGPSP.bgp_sp_tg_link_ip_config_unconfig, dut, link_name, addr_family, vrf, config])NEWLINE else :NEWLINE result = BGPSP.bgp_sp_tg_link_ip_config_unconfig(dut, link_name, addr_family, vrf, config=config)NEWLINE if not result:NEWLINE BGPSP.bgp_sp_show_dut_cmd_logs(dut)NEWLINE st.log("{}uring TG {} Interface address FAILED".format(action_str, dut))NEWLINENEWLINE if threaded_run:NEWLINE [out, exceptions] = putils.exec_all(bgplib.fast_start, dut_thread)NEWLINE st.log("BGP SP - Threaded Run result {}".format([out, exceptions]))NEWLINE if False in out : result = FalseNEWLINENEWLINE return resultNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_dut_link_ip_config_unconfig(dut, link_name, addr_family='all', vrf='default', config='yes'):NEWLINENEWLINE action_str = 'Config' if config == 'yes' else 'Unconfig'NEWLINE st.log("{}uring Interface Addresses on TG link.".format(action_str))NEWLINENEWLINE result = TrueNEWLINE addr_family_list = BGPSP.bgp_sp_get_address_family_list(addr_family)NEWLINENEWLINE if not BGPSP.bgp_sp_dut_link_present(dut, link_name) :NEWLINE st.log("BGP SP - Dut {} link {} not present".format(dut, link_name))NEWLINE return FalseNEWLINENEWLINE tb_dut = sp_topo[dut]['device']NEWLINE #link_data = sp_topo[dut]['intf'][link_name]NEWLINE #tb_if = link_data['if']NEWLINENEWLINE for afmly in addr_family_list:NEWLINENEWLINE if link_name not in sp_topo[dut][afmly]['link'].keys():NEWLINE st.log("BGP SP - {} {} {} address not assigned".format(dut, link_name, afmly))NEWLINE continueNEWLINENEWLINE ip_data = sp_topo[dut][afmly]['link'][link_name]NEWLINENEWLINE link_ip = ip_data['ip']NEWLINE link_if = ip_data['if']NEWLINE #rmt_ip = ip_data['rmt_ip']NEWLINE subnet = ip_data['subnet']NEWLINENEWLINE st.log("{}uring {} Interface {} {}:{} {} ".format(action_str, afmly,NEWLINE tb_dut, link_name, link_if, link_ip))NEWLINENEWLINE result = ipapi.config_ip_addr_interface(tb_dut, link_if, link_ip, subnet, afmly, config)NEWLINENEWLINE if not result:NEWLINE BGPSP.bgp_sp_show_dut_cmd_logs(dut)NEWLINE st.log("{}uring {} Interface address FAILED".format(action_str, dut))NEWLINE breakNEWLINENEWLINE return resultNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_tg_link_ip_config_unconfig(dut, link_name, addr_family='all', vrf='default', config='yes'):NEWLINENEWLINE action_str = 'Config' if config == 'yes' else 'Unconfig'NEWLINE st.log("{}uring Interface Addresses on TG link.".format(action_str))NEWLINENEWLINE result = TrueNEWLINENEWLINE addr_family_list = BGPSP.bgp_sp_get_address_family_list(addr_family)NEWLINENEWLINE if not BGPSP.bgp_sp_dut_link_present(dut, link_name) :NEWLINE st.log("BGP SP - Dut {} link {} not present".format(dut, link_name))NEWLINE return FalseNEWLINENEWLINE tb_dut = sp_topo[dut]['device']NEWLINE link_data = sp_topo[dut]['intf'][link_name]NEWLINE tb_if = link_data['if']NEWLINENEWLINE tg = tgen_obj_dict[tb_dut]NEWLINE tg_port_handle = tg.get_port_handle(tb_if)NEWLINENEWLINE for afmly in addr_family_list:NEWLINENEWLINE if link_name not in sp_topo[dut][afmly]['link'].keys():NEWLINE st.log("BGP SP - {} {} {} address not assigned".format(dut, link_name, afmly))NEWLINE continueNEWLINENEWLINE ip_data = sp_topo[dut][afmly]['link'][link_name]NEWLINENEWLINE link_ip = ip_data['ip']NEWLINE link_if = ip_data['if']NEWLINE rmt_ip = ip_data['rmt_ip']NEWLINE subnet = ip_data['subnet']NEWLINENEWLINE st.log("{}uring {} Interface {} {}:{} {} ".format(action_str, afmly,NEWLINE tb_dut, link_name, link_if, link_ip))NEWLINENEWLINE if config =='yes' :NEWLINE if afmly == 'ipv4':NEWLINE tg_result = tg.tg_interface_config(port_handle=tg_port_handle, mode='config',NEWLINE intf_ip_addr=link_ip,NEWLINE gateway=rmt_ip, arp_send_req='1')NEWLINE else:NEWLINE tg_result = tg.tg_interface_config(port_handle=tg_port_handle, mode='config',NEWLINE ipv6_intf_addr=link_ip,NEWLINE ipv6_prefix_length=subnet,NEWLINE ipv6_gateway=rmt_ip, arp_send_req='1')NEWLINENEWLINE st.log("BGP SP - Port ip config tg api result = {}".format(tg_result))NEWLINENEWLINE if 'handle' in tg_result.keys():NEWLINE sp_topo[dut][afmly]['link'][link_name]['tg_handle'] = tg_result['handle']NEWLINE else :NEWLINE result = FalseNEWLINE breakNEWLINENEWLINE else :NEWLINE handle = ''NEWLINE if 'tg_handle' in ip_data.keys():NEWLINE handle = ip_data['tg_handle']NEWLINENEWLINE if handle == '' :NEWLINE st.log("BGP SP - {} {} {} tg handle invalid".format(dut, link_name, afmly))NEWLINE continueNEWLINENEWLINE if afmly == 'ipv4':NEWLINE tg_result = tg.tg_interface_config(port_handle=tg_port_handle, handle=handle, mode='destroy')NEWLINE else:NEWLINE tg_result = tg.tg_interface_config(port_handle=tg_port_handle, handle=handle, mode='destroy')NEWLINENEWLINE st.log("BGP SP - Port ip Unconfig tg api result = {}".format(tg_result))NEWLINENEWLINE sp_topo[dut][afmly]['link'][link_name]['tg_handle'] = ''NEWLINENEWLINE if not result:NEWLINE BGPSP.bgp_sp_show_dut_cmd_logs(dut)NEWLINE st.log("{}uring TG {} Interface address FAILED".format(action_str, dut))NEWLINENEWLINE return resultNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_static_route_config_unconfig(config='yes', vrf='default', addr_family='all', threaded_run=True, debug_run=False):NEWLINE """NEWLINENEWLINE :param config:NEWLINE :param vrf:NEWLINE :param addr_family:NEWLINE :return:NEWLINE """NEWLINE action_str = 'Config' if config == 'yes' else 'Unconfig'NEWLINE st.banner("{}uring Static Route on all nodes.".format(action_str))NEWLINENEWLINE if not BGPSP.bgp_sp_topology_data_present() :NEWLINE st.log("BGP SP Topology data not available")NEWLINE st.log("SP topo:\n{}\n".format(sp_topo))NEWLINE return FalseNEWLINENEWLINE #threaded_run = TrueNEWLINE #debug_run = FalseNEWLINE result = TrueNEWLINE config = 'add' if config == 'yes' else 'remove'NEWLINENEWLINE addr_family_list = BGPSP.bgp_sp_get_address_family_list(addr_family)NEWLINE #thread_info = {'ipv4': [], 'ipv6': []}NEWLINE dut_thread = []NEWLINENEWLINE for dut in sp_topo['dut_list'] :NEWLINE tb_dut = sp_topo[dut]['device']NEWLINE rt_data_list = []NEWLINENEWLINE for afmly in addr_family_list:NEWLINENEWLINE for prefix, strt_data in sp_topo[dut][afmly]['static_rt'].items():NEWLINENEWLINE nexthop = strt_data['nexthop']NEWLINE subnet = strt_data['subnet']NEWLINE rt_data_list.append({ 'ip': prefix, 'subnet': subnet, 'nexthop': nexthop, 'family': afmly })NEWLINENEWLINE st.log("{}uring {} Static route {}:{} pfx {} nh {} .".format(action_str, afmly, dut, tb_dut, prefix, nexthop))NEWLINENEWLINE '''NEWLINE prefix_sn = "{}/{}".format(prefix, subnet)NEWLINE if config == 'add':NEWLINE if threaded_run:NEWLINE thread_info[afmly].append([ipapi.create_static_route, tb_dut, nexthop, prefix_sn, 'vtysh', afmly])NEWLINE else:NEWLINE result = ipapi.create_static_route(tb_dut, nexthop, prefix_sn, 'vtysh', afmly)NEWLINE else:NEWLINE if threaded_run:NEWLINE thread_info[afmly].append([ipapi.delete_static_route, tb_dut, nexthop, prefix_sn, afmly, 'vtysh'])NEWLINE else:NEWLINE result = ipapi.delete_static_route(tb_dut, nexthop, prefix_sn, afmly, 'vtysh')NEWLINE result = TrueNEWLINE '''NEWLINENEWLINE if threaded_run:NEWLINE dut_thread.append([ipapi.config_unconfig_static_routes, tb_dut, rt_data_list, "vtysh", config])NEWLINE else :NEWLINE result = ipapi.config_unconfig_static_routes(tb_dut, rt_data_list, shell="vtysh", config=config)NEWLINE if not result:NEWLINE BGPSP.bgp_sp_show_dut_cmd_logs(dut)NEWLINE st.log("{}uring {} Static route FAILED".format(action_str, dut))NEWLINE return FalseNEWLINENEWLINE if debug_run:NEWLINE BGPSP.bgp_sp_show_dut_route_cmd_logs(dut)NEWLINENEWLINE if threaded_run:NEWLINE [out, exceptions] = putils.exec_all(bgplib.fast_start, dut_thread)NEWLINE st.log("BGP SP - Threaded Run result {}".format([out, exceptions]))NEWLINE if False in out : result = FalseNEWLINENEWLINE return resultNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_dut_interface_address_ping_test(dut, vrf='default', addr_family='all', ping_count=3):NEWLINENEWLINE st.log("BGP SP - {} interface IP address Ping test".format(dut))NEWLINENEWLINE #debug_run = FalseNEWLINE result = TrueNEWLINENEWLINE if not BGPSP.bgp_sp_dut_present(dut):NEWLINE st.log("BGP SP - Dut {} not present".format(dut))NEWLINE return FalseNEWLINENEWLINE tb_dut = BGPSP.bgp_sp_get_dut_device(dut)NEWLINE BGPSP.bgp_sp_show_dut_route_cmd_logs(dut)NEWLINENEWLINE addr_family_list = BGPSP.bgp_sp_get_address_family_list(addr_family)NEWLINENEWLINE for afmly in addr_family_list:NEWLINE for link_name, link_data in sp_topo[dut][afmly]['link'].items():NEWLINE if link_data['type'] == 'LBK' :NEWLINE continueNEWLINE if 'rmt_ip' not in link_data.keys():NEWLINE continueNEWLINENEWLINE if BGPSP.bgp_sp_is_tg_connected_link(dut, link_name):NEWLINE st.log("Not Trying Pinf test for TG connected link {}".format(link_name))NEWLINE continue #only for nowNEWLINENEWLINE lcl_ip = link_data['ip']NEWLINE rmt_ip = link_data['rmt_ip']NEWLINE st.log("Pingtest for {} {} {} --{}-> {} ".format(afmly, tb_dut, lcl_ip, link_name, rmt_ip))NEWLINENEWLINE if not ipapi.ping(tb_dut, rmt_ip, family=afmly, count=ping_count):NEWLINE st.log("Ping FAILED for {} {} {} --{}-> {} ".format(afmly, tb_dut, lcl_ip, link_name, rmt_ip))NEWLINE st.log("ERROR Dut {} Ping to {} FAILED ".format(tb_dut, rmt_ip))NEWLINE result = FalseNEWLINE breakNEWLINENEWLINE if not result:NEWLINE st.log("{} Ping Test FAILED".format(dut))NEWLINE BGPSP.bgp_sp_show_dut_cmd_logs(dut)NEWLINE return FalseNEWLINENEWLINE return resultNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_interface_address_ping_test(vrf='default', addr_family='all', ping_count=3):NEWLINE """NEWLINENEWLINE :param config:NEWLINE :param vrf:NEWLINE :param addr_family:NEWLINE :return:NEWLINE """NEWLINENEWLINE st.log("BGP SP network Ping test for interface IP addressess")NEWLINENEWLINE if not BGPSP.bgp_sp_topology_data_present() :NEWLINE st.log("BGP SP Topology data not available")NEWLINE st.log("SP topo:\n{}\n".format(sp_topo))NEWLINE return FalseNEWLINENEWLINE threaded_run = TrueNEWLINE result = TrueNEWLINE dut_thread = []NEWLINENEWLINE dut_list = BGPSP.bgp_sp_get_dut_list()NEWLINENEWLINE if not dut_list or len(dut_list) < 2: threaded_run = FalseNEWLINENEWLINE for dut in dut_list :NEWLINE if threaded_run:NEWLINE dut_thread.append([BGPSP.bgp_sp_dut_interface_address_ping_test, dut, vrf, addr_family, ping_count])NEWLINE else :NEWLINE result = BGPSP.bgp_sp_dut_interface_address_ping_test(dut, vrf, addr_family, ping_count)NEWLINENEWLINE if not result:NEWLINE BGPSP.bgp_sp_show_dut_if_cmd_logs(dut)NEWLINE st.log("BGP SP - Ping Test Failed for {}".format(dut))NEWLINE breakNEWLINENEWLINE if threaded_run:NEWLINE [out, exceptions] = putils.exec_all(bgplib.fast_start, dut_thread)NEWLINE st.log("BGP SP - Ping Test Threaded Run result {}".format([out, exceptions]))NEWLINE if False in out : result = FalseNEWLINENEWLINE if not result:NEWLINE st.log("BGP SP - Interface Ping Test FAILED")NEWLINENEWLINE return resultNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_dut_interface_shut_noshut(dut, link_name, shut='yes'):NEWLINENEWLINE action_str = "Shut down" if shut == 'yes' else 'Startup'NEWLINENEWLINE tb_dut = BGPSP.bgp_sp_get_dut_device(dut)NEWLINE tb_intf = BGPSP.bgp_sp_get_link_dut_interface(dut, link_name)NEWLINENEWLINE if tb_dut == '' or tb_intf == '' :NEWLINE st.log("BGP SP - tb dut {} or if {} empty".format(tb_dut, tb_intf))NEWLINE return FalseNEWLINENEWLINE st.log("BGP SP - {} {} {}".format(action_str, dut, link_name))NEWLINENEWLINE if shut == 'yes':NEWLINE result = ifapi.interface_shutdown(tb_dut, tb_intf)NEWLINE else :NEWLINE result = ifapi.interface_noshutdown(tb_dut, tb_intf)NEWLINENEWLINE if not result :NEWLINE st.log("BGP SP - {} {} {} Failed".format(action_str, dut, link_name))NEWLINENEWLINE return resultNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_config_ip_topology_on_testbed():NEWLINE st.banner("BGP SP Base Class Pre CONFIG - START")NEWLINE BGPSP.bgp_sp_loopback_interface_config_unconfig(config='yes', vrf='default')NEWLINE BGPSP.bgp_sp_loopback_address_config_unconfig(config='yes', addr_family='all')NEWLINE BGPSP.bgp_sp_interface_address_all_config_unconfig(config='yes', addr_family='all')NEWLINE BGPSP.bgp_sp_static_route_config_unconfig(config='yes', addr_family='all')NEWLINE st.banner("BGP SP Base Class Pre CONFIG - END")NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_unconfig_ip_topology_on_testbed():NEWLINE st.banner("BGP SP Base Class Pre CONFIG CLEANUP - START")NEWLINE BGPSP.bgp_sp_static_route_config_unconfig('no')NEWLINE BGPSP.bgp_sp_interface_address_all_config_unconfig(config='no')NEWLINE BGPSP.bgp_sp_loopback_address_config_unconfig(config='no')NEWLINE BGPSP.bgp_sp_loopback_interface_config_unconfig(config='no')NEWLINE st.banner("BGP SP Base Class Pre CONFIG CLEANUP - END")NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_bgp_configured(dut, vrf='default'):NEWLINENEWLINE if dut not in bgp_topo.keys():NEWLINE return FalseNEWLINENEWLINE if vrf not in bgp_topo[dut].keys():NEWLINE return FalseNEWLINENEWLINE if bgp_topo[dut][vrf]['asn'] == 0 :NEWLINE return FalseNEWLINENEWLINE if bgp_topo[dut][vrf]['asn'] == '0' :NEWLINE return FalseNEWLINENEWLINE if bgp_topo[dut][vrf]['asn'] == '' :NEWLINE return FalseNEWLINENEWLINE return TrueNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_get_bgp_asn(dut, vrf='default'):NEWLINENEWLINE if not BGPSP.bgp_sp_bgp_configured(dut, vrf):NEWLINE return 0NEWLINENEWLINE return int(bgp_topo[dut][vrf]['asn'])NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_bgp_asn_match(dut, asn = 0, vrf='default'):NEWLINENEWLINE if not BGPSP.bgp_sp_bgp_configured(dut, vrf):NEWLINE return 0NEWLINENEWLINE bgp_asn = BGPSP.bgp_sp_get_bgp_asn(dut, vrf)NEWLINENEWLINE if bgp_asn == asn :NEWLINE return TrueNEWLINENEWLINE return FalseNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_is_ip_bgp_neigbour(dut, nbr_ip, addr_family, vrf='default'):NEWLINENEWLINE if not BGPSP.bgp_sp_addr_family_valid(addr_family):NEWLINE return FalseNEWLINENEWLINE if not BGPSP.bgp_sp_bgp_configured(dut, vrf):NEWLINE return FalseNEWLINENEWLINE if nbr_ip in bgp_topo[dut][vrf][addr_family]['nbr'].keys():NEWLINE return TrueNEWLINENEWLINE return FalseNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_get_bgp_neigbour_ip_list(dut, addr_family, vrf='default'):NEWLINENEWLINE if not BGPSP.bgp_sp_addr_family_valid(addr_family):NEWLINE return []NEWLINENEWLINE if not BGPSP.bgp_sp_bgp_configured(dut, vrf):NEWLINE return []NEWLINENEWLINE nbr_ip_list = []NEWLINE for nbr_ip in bgp_topo[dut][vrf][addr_family]['nbr'].keys():NEWLINE nbr_ip_list.append(nbr_ip)NEWLINENEWLINE return copy.deepcopy(nbr_ip_list)NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_get_bgp_neigbour_list(dut, addr_family, vrf='default'):NEWLINENEWLINE if not BGPSP.bgp_sp_addr_family_valid(addr_family):NEWLINE return {}NEWLINENEWLINE if not BGPSP.bgp_sp_bgp_configured(dut, vrf):NEWLINE return {}NEWLINENEWLINE nbr_ip_data_list = {}NEWLINE for nbr_ip, nbr_data in bgp_topo[dut][vrf][addr_family]['nbr'].items():NEWLINE nbr_ip_data_list.update( { nbr_ip: nbr_data} )NEWLINENEWLINE return copy.deepcopy(nbr_ip_data_list)NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_get_bgp_neigbour_ip_between_duts(from_dut, to_dut, addr_family, from_vrf='default', to_vrf='default'):NEWLINENEWLINE if not BGPSP.bgp_sp_addr_family_valid(addr_family):NEWLINE return []NEWLINENEWLINE from_asn = BGPSP.bgp_sp_get_bgp_asn(from_dut, from_vrf)NEWLINE to_asn = BGPSP.bgp_sp_get_bgp_asn(to_dut, to_vrf)NEWLINE to_dut_ip_list = BGPSP.bgp_sp_get_dut_ip_address_list(to_dut, addr_family, vrf=to_vrf)NEWLINENEWLINE if from_asn == 0 or to_asn == 0 :NEWLINE return []NEWLINENEWLINE nbr_ip_list = []NEWLINE for nbr_ip, nbr_data in bgp_topo[from_dut][from_vrf][addr_family]['nbr'].items():NEWLINE if nbr_data['rmt_asn'] == to_asn :NEWLINE if nbr_ip in to_dut_ip_list :NEWLINE nbr_ip_list.append(nbr_ip)NEWLINENEWLINE return copy.deepcopy(nbr_ip_list)NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_get_bgp_network_prefix_list(dut, addr_family, vrf='default'):NEWLINENEWLINE if not BGPSP.bgp_sp_addr_family_valid(addr_family):NEWLINE return {}NEWLINENEWLINE if not BGPSP.bgp_sp_bgp_configured(dut, vrf):NEWLINE return {}NEWLINENEWLINE nbr_nwip_list = {}NEWLINE for prefix, subnet in bgp_topo[dut][vrf][addr_family]['network'].items():NEWLINE nbr_nwip_list.update( {prefix: subnet} )NEWLINENEWLINE return copy.deepcopy(nbr_nwip_list)NEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_bgp_config_unconfig(dut, local_asn, router_id='', vrf='default', config='yes', cli_type=""):NEWLINE """NEWLINENEWLINE :param dutNEWLINE :param local_asn:NEWLINE :param vrf:NEWLINE :param configNEWLINE :return:NEWLINE """NEWLINE action_str = 'Config' if config == 'yes' else 'Unconfig'NEWLINE st.log("{}uring BGP router.".format(action_str))NEWLINENEWLINE if not BGPSP.bgp_sp_topology_data_present() :NEWLINE st.log("BGP SP Topology data not available")NEWLINE return FalseNEWLINENEWLINE if not BGPSP.bgp_sp_dut_present(dut):NEWLINE st.log("BGP SP - Dut {} doesnt exist".format(dut))NEWLINE return FalseNEWLINENEWLINE if not local_asn :NEWLINE st.log("BGP SP - local asn not provided ")NEWLINE return FalseNEWLINENEWLINE result = TrueNEWLINENEWLINE if dut not in bgp_topo.keys():NEWLINE if config != 'yes' :NEWLINE st.log("BGP SP - {} BGP dut doesnt exist".format(dut))NEWLINE return FalseNEWLINE bgp_topo[dut] = {}NEWLINENEWLINE if vrf not in bgp_topo[dut].keys():NEWLINE if config != 'yes' :NEWLINE st.log("BGP SP - {} vrf {} BGP router doesnt exist".format(dut, vrf))NEWLINE return TrueNEWLINENEWLINE bgp_topo[dut][vrf] = {}NEWLINE bgp_topo[dut][vrf]['asn'] = int(local_asn)NEWLINE bgp_topo[dut][vrf]['rtrid'] = '0'NEWLINE bgp_topo[dut][vrf]['ipv4']={}NEWLINE bgp_topo[dut][vrf]['ipv4']['nbr']={}NEWLINE bgp_topo[dut][vrf]['ipv4']['unicast']={}NEWLINE bgp_topo[dut][vrf]['ipv4']['network'] = {}NEWLINE bgp_topo[dut][vrf]['ipv6']={}NEWLINE bgp_topo[dut][vrf]['ipv6']['nbr']={}NEWLINE bgp_topo[dut][vrf]['ipv6']['unicast']={}NEWLINE bgp_topo[dut][vrf]['ipv6']['network'] = {}NEWLINENEWLINE if bgp_topo[dut][vrf]['asn'] != 0 :NEWLINE if bgp_topo[dut][vrf]['asn'] != local_asn:NEWLINE st.log("BGP SP - bgp asns {} {} dont match".format(bgp_topo[dut][vrf]['asn'], local_asn))NEWLINE return FalseNEWLINENEWLINE tb_dut = BGPSP.bgp_sp_get_dut_device(dut)NEWLINENEWLINE if config == 'yes' :NEWLINENEWLINE if not router_id or router_id == '' :NEWLINE router_id = BGPSP.bgp_sp_get_dut_loopback_ip(dut, 0, 'ipv4')NEWLINENEWLINE st.log("BGP SP - {} vrf {} Configuring BGP with as {}".format(dut, vrf, local_asn))NEWLINENEWLINE result = bgpapi.config_bgp_router(tb_dut, local_asn, router_id=router_id, keep_alive=30, hold=60, config='yes')NEWLINE if not result :NEWLINE st.log("BGP SP - {} vrf {} Configuring BGP with as {} FAILED".format(dut, vrf, local_asn))NEWLINE return FalseNEWLINENEWLINE bgp_topo[dut][vrf]['asn'] = int(local_asn)NEWLINE bgp_topo[dut][vrf]['ipv4']['rtr_id'] = router_idNEWLINENEWLINE bgpapi.config_bgp_default(tb_dut, local_asn, 'ipv4-unicast', config='no', cli_type=cli_type)NEWLINENEWLINE else :NEWLINENEWLINE st.log("BGP SP - {} vrf {} Unconfiguring BGP with as {}".format(dut, vrf, local_asn))NEWLINENEWLINE result = bgpapi.config_bgp_router(tb_dut, local_asn, config='no')NEWLINE if not result :NEWLINE st.log("BGP SP - {} vrf {} UnConfiguring BGP with as {} FAILED".format(dut, vrf, local_asn))NEWLINE return FalseNEWLINENEWLINE del bgp_topo[dut][vrf]NEWLINENEWLINE #st.log("BGP SP - Bgp topo after {} router bgpn: {}".format(action_str, bgp_topo))NEWLINE return resultNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_dut_bgp_redistribute_connected_config_unconfig(dut, addr_family='all', tr_type='unicast', vrf='default', config='yes'):NEWLINENEWLINE action_str = 'Config' if config == 'yes' else 'Unconfig'NEWLINE st.log("{}uring BGP redistribute connected route on {}".format(action_str, dut))NEWLINENEWLINE if not BGPSP.bgp_sp_dut_present(dut):NEWLINE st.log("Dut {} not present".format(dut))NEWLINE return FalseNEWLINENEWLINE result = TrueNEWLINE afmly_list = BGPSP.bgp_sp_get_address_family_list(addr_family)NEWLINENEWLINE tb_dut = BGPSP.bgp_sp_get_dut_device(dut)NEWLINE dut_asn = BGPSP.bgp_sp_get_bgp_asn(dut, vrf)NEWLINENEWLINE if dut_asn == 0 :NEWLINE st.log("BGP SP - BGP bot configured in dut {}".format(dut))NEWLINE return FalseNEWLINENEWLINE for afmly in afmly_list:NEWLINE bgpapi.config_address_family_redistribute(tb_dut, dut_asn, afmly, tr_type, "connected", config=config)NEWLINENEWLINE return resultNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_bgp_redistribute_connected_config_unconfig(dut_list, addr_family='all', tr_type='unicast', vrf='default', config='yes'):NEWLINENEWLINE action_str = 'Config' if config == 'yes' else 'Unconfig'NEWLINE st.log("{}uring BGP redistribute connected route ".format(action_str))NEWLINENEWLINE result = TrueNEWLINE threaded_run = TrueNEWLINE dut_thread = []NEWLINENEWLINE dut_list = list(dut_list) if isinstance(dut_list, list) else [dut_list]NEWLINE if not dut_list or len(dut_list) < 2: threaded_run = FalseNEWLINENEWLINE for dut in dut_list :NEWLINE if threaded_run:NEWLINE dut_thread.append([BGPSP.bgp_sp_dut_bgp_redistribute_connected_config_unconfig,NEWLINE dut, addr_family, tr_type, vrf, config])NEWLINE else :NEWLINE result = BGPSP.bgp_sp_dut_bgp_redistribute_connected_config_unconfig(NEWLINE dut, addr_family, tr_type, vrf, config)NEWLINENEWLINE if not result:NEWLINE st.log("BGP SP - Redistribute connected at {} failed".format(dut))NEWLINE breakNEWLINENEWLINE if threaded_run:NEWLINE [out, exceptions] = putils.exec_all(bgplib.fast_start, dut_thread)NEWLINE st.log("BGP SP - Redistribute connected Threaded Run result {}".format([out, exceptions]))NEWLINE if False in out : result = FalseNEWLINENEWLINE if not result:NEWLINE st.log("BGP SP - {}uring Redistribute connected Static FAILED".format(action_str))NEWLINENEWLINE return resultNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_dut_bgp_redistribute_static_config_unconfig(dut, addr_family='all', tr_type='unicast', vrf='default', config='yes'):NEWLINENEWLINE action_str = 'Config' if config == 'yes' else 'Unconfig'NEWLINE st.log("{}uring BGP redistribute static route on {}".format(action_str, dut))NEWLINENEWLINE if not BGPSP.bgp_sp_dut_present(dut):NEWLINE st.log("Dut {} not present".format(dut))NEWLINE return FalseNEWLINENEWLINE result = TrueNEWLINE afmly_list = BGPSP.bgp_sp_get_address_family_list(addr_family)NEWLINE tb_dut = BGPSP.bgp_sp_get_dut_device(dut)NEWLINENEWLINE dut_asn = BGPSP.bgp_sp_get_bgp_asn(dut, vrf)NEWLINE if dut_asn == 0 :NEWLINE st.log("BGP SP - BGP bot configured in dut {}".format(dut))NEWLINE return FalseNEWLINENEWLINE for afmly in afmly_list:NEWLINE bgpapi.config_address_family_redistribute(tb_dut, dut_asn, afmly, tr_type, "static", config=config)NEWLINENEWLINE return resultNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_bgp_redistribute_static_config_unconfig(dut_list, addr_family='all', tr_type='unicast', vrf='default', config='yes'):NEWLINENEWLINE action_str = 'Config' if config == 'yes' else 'Unconfig'NEWLINE st.log("{}uring BGP redistribute static route ".format(action_str))NEWLINENEWLINE result = TrueNEWLINE threaded_run = TrueNEWLINE dut_thread = []NEWLINENEWLINE dut_list = list(dut_list) if isinstance(dut_list, list) else [dut_list]NEWLINE if not dut_list or len(dut_list) < 2: threaded_run = FalseNEWLINENEWLINE for dut in dut_list :NEWLINE if threaded_run:NEWLINE dut_thread.append([BGPSP.bgp_sp_dut_bgp_redistribute_static_config_unconfig,NEWLINE dut, addr_family, tr_type, vrf, config])NEWLINE else :NEWLINE result = BGPSP.bgp_sp_dut_bgp_redistribute_static_config_unconfig(NEWLINE dut, addr_family, tr_type, vrf, config)NEWLINENEWLINE if not result:NEWLINE st.log("BGP SP - Redistribute static at {} failed".format(dut))NEWLINE breakNEWLINENEWLINE if threaded_run:NEWLINE [out, exceptions] = putils.exec_all(bgplib.fast_start, dut_thread)NEWLINE st.log("BGP SP - Redistribute Static Threaded Run result {}".format([out, exceptions]))NEWLINE if False in out : result = FalseNEWLINENEWLINE if not result:NEWLINE st.log("BGP SP - {}uring Redistribute Static FAILED".format(action_str))NEWLINENEWLINE return resultNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_dut_bgp_network_advertise_config_unconfig(dut, network_list=[], addr_family='ipv4', vrf='default', config='yes', cli_type=""):NEWLINENEWLINE action_str = 'Config' if config == 'yes' else 'Unconfig'NEWLINE st.log("{}uring BGP network advertise on {}".format(action_str, dut))NEWLINENEWLINE if not BGPSP.bgp_sp_dut_present(dut):NEWLINE st.log("Dut {} not present".format(dut))NEWLINE return FalseNEWLINENEWLINE if not BGPSP.bgp_sp_addr_family_valid(addr_family) :NEWLINE st.log("BGP SP - Invalid address family {}".format(addr_family))NEWLINE return FalseNEWLINENEWLINE result = TrueNEWLINE tb_dut = BGPSP.bgp_sp_get_dut_device(dut)NEWLINENEWLINE dut_asn = BGPSP.bgp_sp_get_bgp_asn(dut, vrf)NEWLINE if dut_asn == 0 :NEWLINE st.log("BGP SP - BGP bot configured in dut {}".format(dut))NEWLINE return FalseNEWLINE check_flag = True if config == "yes" else FalseNEWLINE for network_ip in network_list:NEWLINE result = bgpapi.config_bgp_network_advertise(tb_dut, dut_asn, network_ip, route_map='',NEWLINE addr_family=addr_family, config=config, cli_type=cli_type, network_import_check=check_flag)NEWLINENEWLINE return resultNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_bgp_network_advertise_config_unconfig(dut_list, network_list=[], addr_family='ipv4', vrf='default', config='yes'):NEWLINENEWLINE action_str = 'Config' if config == 'yes' else 'Unconfig'NEWLINE st.log("{}uring BGP network advertise ".format(action_str))NEWLINENEWLINE result = TrueNEWLINE threaded_run = TrueNEWLINE dut_thread = []NEWLINENEWLINE dut_list = list(dut_list) if isinstance(dut_list, list) else [dut_list]NEWLINE if not dut_list or len(dut_list) < 2: threaded_run = FalseNEWLINENEWLINE for dut in dut_list :NEWLINE if threaded_run:NEWLINE dut_thread.append([BGPSP.bgp_sp_dut_bgp_network_advertise_config_unconfig,NEWLINE dut, network_list, addr_family, vrf, config])NEWLINE else :NEWLINE result = BGPSP.bgp_sp_dut_bgp_network_advertise_config_unconfig(NEWLINE dut, network_list, addr_family, vrf, config)NEWLINENEWLINE if not result:NEWLINE st.log("BGP SP - Network advertise at {} failed".format(dut))NEWLINE breakNEWLINENEWLINE if threaded_run:NEWLINE [out, exceptions] = putils.exec_all(bgplib.fast_start, dut_thread)NEWLINE st.log("BGP SP - Network advertise Threaded Run result {}".format([out, exceptions]))NEWLINE if False in out : result = FalseNEWLINENEWLINE if not result:NEWLINE st.log("BGP SP - {}uring Network advertise FAILED".format(action_str))NEWLINENEWLINE return resultNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_bgp_deterministic_med_config_unconfig(dut_list, vrf='default', config='yes'):NEWLINENEWLINE action_str = 'Config' if config == 'yes' else 'Unconfig'NEWLINE st.log("{}uring BGP deterministic Med".format(action_str))NEWLINENEWLINE result = TrueNEWLINE threaded_run = TrueNEWLINE dut_thread = []NEWLINENEWLINE dut_list = list(dut_list) if isinstance(dut_list, list) else [dut_list]NEWLINE if not dut_list or len(dut_list) < 2: threaded_run = FalseNEWLINENEWLINE for dut in dut_list :NEWLINE tb_dut = BGPSP.bgp_sp_get_dut_device(dut)NEWLINE dut_asn = BGPSP.bgp_sp_get_bgp_asn(dut, vrf)NEWLINENEWLINE if dut_asn == 0 :NEWLINE st.log("BGP SP - BGP not configured in dut {}".format(dut))NEWLINE return FalseNEWLINENEWLINE if threaded_run:NEWLINE dut_thread.append([bgpapi.config_bgp_deterministic_med, tb_dut, dut_asn, config])NEWLINE else :NEWLINE result = bgpapi.config_bgp_deterministic_med(tb_dut, dut_asn, config=config)NEWLINENEWLINE if not result:NEWLINE st.log("BGP SP - deterministic med at {} failed".format(dut))NEWLINE breakNEWLINENEWLINE if threaded_run:NEWLINE [out, exceptions] = putils.exec_all(bgplib.fast_start, dut_thread)NEWLINE st.log("BGP SP - Deterministic med Threaded Run result {}".format([out, exceptions]))NEWLINE if False in out : result = FalseNEWLINENEWLINE if not result:NEWLINE st.log("BGP SP - {}uring Deterministic med FAILED".format(action_str))NEWLINENEWLINE return resultNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_bgp_compare_med_config_unconfig(dut_list, vrf='default', config='yes'):NEWLINENEWLINE action_str = 'Config' if config == 'yes' else 'Unconfig'NEWLINE st.log("{}uring BGP Always compare Med".format(action_str))NEWLINENEWLINE result = TrueNEWLINE threaded_run = TrueNEWLINE dut_thread = []NEWLINENEWLINE dut_list = list(dut_list) if isinstance(dut_list, list) else [dut_list]NEWLINE if not dut_list or len(dut_list) < 2: threaded_run = FalseNEWLINENEWLINE for dut in dut_list :NEWLINE tb_dut = BGPSP.bgp_sp_get_dut_device(dut)NEWLINE dut_asn = BGPSP.bgp_sp_get_bgp_asn(dut, vrf)NEWLINENEWLINE if dut_asn == 0 :NEWLINE st.log("BGP SP - BGP not configured in dut {}".format(dut))NEWLINE return FalseNEWLINENEWLINE if threaded_run:NEWLINE dut_thread.append([bgpapi.config_bgp_always_compare_med, tb_dut, dut_asn, config])NEWLINE else :NEWLINE result = bgpapi.config_bgp_always_compare_med(tb_dut, dut_asn, config=config)NEWLINENEWLINE if not result:NEWLINE st.log("BGP SP - compare med at {} failed".format(dut))NEWLINE breakNEWLINENEWLINE if threaded_run:NEWLINE [out, exceptions] = putils.exec_all(bgplib.fast_start, dut_thread)NEWLINE st.log("BGP SP - compare med Threaded Run result {}".format([out, exceptions]))NEWLINE if False in out : result = FalseNEWLINENEWLINE if not result:NEWLINE st.log("BGP SP - {}uring Always compare med FAILED".format(action_str))NEWLINENEWLINE return resultNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_bgp_ctoc_reflection_config_unconfig(dut_list, vrf='default', config='yes', cli_type=""):NEWLINENEWLINE action_str = 'Config' if config == 'yes' else 'Unconfig'NEWLINE st.log("{}uring BGP Client to Client Route Reflection".format(action_str))NEWLINENEWLINE result = TrueNEWLINE threaded_run = TrueNEWLINE dut_thread = []NEWLINENEWLINE dut_list = list(dut_list) if isinstance(dut_list, list) else [dut_list]NEWLINE if not dut_list or len(dut_list) < 2: threaded_run = FalseNEWLINENEWLINE for dut in dut_list :NEWLINE tb_dut = BGPSP.bgp_sp_get_dut_device(dut)NEWLINE dut_asn = BGPSP.bgp_sp_get_bgp_asn(dut, vrf)NEWLINENEWLINE if dut_asn == 0 :NEWLINE st.log("BGP SP - BGP not configured in dut {}".format(dut))NEWLINE return FalseNEWLINENEWLINE if threaded_run:NEWLINE dut_thread.append([bgpapi.create_bgp_client_to_client_reflection, tb_dut, dut_asn, config, cli_type])NEWLINE else :NEWLINE result = bgpapi.create_bgp_client_to_client_reflection(tb_dut, dut_asn, config=config, cli_type= cli_type)NEWLINENEWLINE if not result:NEWLINE st.log("BGP SP - Client to Client RR at {} failed".format(dut))NEWLINE breakNEWLINENEWLINE if threaded_run:NEWLINE [out, exceptions] = putils.exec_all(bgplib.fast_start, dut_thread)NEWLINE st.log("BGP SP - Client to Client RR Threaded Run result {}".format([out, exceptions]))NEWLINE if False in out : result = FalseNEWLINENEWLINE if not result:NEWLINE st.log("BGP SP - {}uring Client to Client RR FAILED".format(action_str))NEWLINENEWLINE return resultNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_bgp_neighbor_route_reflector_config_unconfig(dut, nbr_list=[], addr_family='ipv4', vrf='default', config='yes', cli_type="vtysh"):NEWLINENEWLINE action_str = 'Config' if config == 'yes' else 'Unconfig'NEWLINE st.log("{}uring BGP Neighbor Route Reflector clients ".format(action_str))NEWLINENEWLINE result = TrueNEWLINENEWLINE tb_dut = BGPSP.bgp_sp_get_dut_device(dut)NEWLINE dut_asn = BGPSP.bgp_sp_get_bgp_asn(dut, vrf)NEWLINENEWLINE if dut_asn == 0 :NEWLINE st.log("BGP SP - dut {} doesnt have bgp configured".format(dut))NEWLINE return FalseNEWLINENEWLINE if len(nbr_list) != 0:NEWLINE if not BGPSP.bgp_sp_addr_family_valid(addr_family) :NEWLINE st.log("BGP SP - Invalid address family {}".format(addr_family))NEWLINE return FalseNEWLINENEWLINE afmly_list = BGPSP.bgp_sp_get_address_family_list(addr_family)NEWLINENEWLINE for afmly in afmly_list :NEWLINE dut_nbr_list = BGPSP.bgp_sp_get_bgp_neigbour_ip_list(dut, afmly, vrf=vrf)NEWLINE if len(nbr_list) == 0 :NEWLINE rr_nbr_list = dut_nbr_listNEWLINE else :NEWLINE rr_nbr_list = nbr_listNEWLINENEWLINE for nbr_ip in rr_nbr_list :NEWLINE if nbr_ip not in dut_nbr_list :NEWLINE st.log("BGP SP - nbr {} not in ngr list {} Failed".format(nbr_ip, dut_nbr_list))NEWLINE continueNEWLINENEWLINE st.log("BGP SP - {}uring {} route-reflector-client {}.".format(action_str, dut, nbr_ip))NEWLINE result = bgpapi.create_bgp_route_reflector_client(tb_dut, dut_asn, afmly, nbr_ip, config=config)NEWLINE if not result :NEWLINE st.log("BGP SP - Configuring client reflection on {} {} bgp {} Failed".format(dut, afmly, dut_asn))NEWLINE breakNEWLINENEWLINE return resultNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_route_map_config_unconfig(dut, rmap_name, condition='permit', sequence='', config='yes', **kwargs):NEWLINENEWLINE cli_type = st.get_ui_type(dut, cli_type="")NEWLINE # cli_type = "vtysh" if cli_type in ['click', "vtysh"] else cli_typeNEWLINE # cli_type = "vtysh" if cli_type in ["rest-patch", "rest-put"] else cli_typeNEWLINE cli_type = "vtysh" if cli_type in ['click', "vtysh"] else ("klish" if cli_type in ["rest-patch", "rest-put"] else cli_type)NEWLINE action_str = 'Config' if config == 'yes' else 'Unconfig'NEWLINE st.log("{}uring route map".format(action_str))NEWLINENEWLINE result = TrueNEWLINE tb_dut = BGPSP.bgp_sp_get_dut_device(dut)NEWLINENEWLINE no_params = True if not kwargs else FalseNEWLINE cfg_action = "no" if config == 'no' else ""NEWLINE cmd_str = ''NEWLINENEWLINE if rmap_name == '' :NEWLINE st.log("BGP SP - Routemap name must")NEWLINE return FalseNEWLINENEWLINE if no_params :NEWLINE if config == 'yes' :NEWLINE if sequence == '' :NEWLINE st.log("BGP SP - Sequence value for rmap must")NEWLINE return FalseNEWLINE else :NEWLINE if condition == '':NEWLINE st.log("BGP SP - routemap condition permit/deny is must")NEWLINE return FalseNEWLINE else :NEWLINE cmd_str = "route-map {} {} {}".format(rmap_name, condition, sequence)NEWLINENEWLINE elif config == 'no' :NEWLINE if sequence == '' :NEWLINE cmd_str = "no route-map {}".format(rmap_name)NEWLINE else :NEWLINE if condition == '':NEWLINE st.log("BGP SP - routemap condition permit/deny is must")NEWLINE return FalseNEWLINE else :NEWLINE cmd_str = "no route-map {} {} {}".format(rmap_name, condition, sequence)NEWLINENEWLINE if no_params :NEWLINE #st.log("BGP SP - Route Map cmd without params is\n{}\n".format(cmd_str))NEWLINE st.config(tb_dut, cmd_str, type= cli_type)NEWLINE result = TrueNEWLINE return resultNEWLINENEWLINE if condition == '':NEWLINE st.log("BGP SP - routemap condition permit/deny is must")NEWLINE return FalseNEWLINENEWLINE cmd_str = "route-map {} {} {}".format(rmap_name, condition, sequence)NEWLINENEWLINE if 'metric' in kwargs :NEWLINE metric = kwargs['metric']NEWLINE cmd_str += "\n {} set metric {} ".format(cfg_action, metric)NEWLINENEWLINE if 'community' in kwargs :NEWLINE community = kwargs['metric']NEWLINE cmd_str += "\n {} set community {} ".format(cfg_action, community)NEWLINENEWLINE #st.log("BGP SP - Route Map cmd is \n{}\n".format(cmd_str))NEWLINE st.config(tb_dut, cmd_str, type= cli_type)NEWLINE return resultNEWLINENEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_bgp_nexthop_self_config_unconfig(dut_list=[], addr_family='all', vrf='default', force='no', config='yes'):NEWLINENEWLINE action_str = 'Config' if config == 'yes' else 'Unconfig'NEWLINE st.log("{}uring BGP nexthop self ".format(action_str))NEWLINENEWLINE result = TrueNEWLINE afmly_list = BGPSP.bgp_sp_get_address_family_list(addr_family)NEWLINENEWLINE for dut in dut_list :NEWLINE tb_dut = BGPSP.bgp_sp_get_dut_device(dut)NEWLINE dut_asn = BGPSP.bgp_sp_get_bgp_asn(dut, vrf)NEWLINENEWLINE if dut_asn == 0 :NEWLINE st.log("BGP SP - BGP not configured on dut {}".format(dut))NEWLINE continueNEWLINENEWLINE for afmly in afmly_list :NEWLINE dut_nbr_list = BGPSP.bgp_sp_get_bgp_neigbour_ip_list(dut, afmly, vrf=vrf)NEWLINE for bgp_nbr in dut_nbr_list :NEWLINE st.log("BGP SP - {}uring {} nexthop self {}.".format(action_str, dut, bgp_nbr))NEWLINE result = bgpapi.create_bgp_next_hop_self(tb_dut, dut_asn, afmly, bgp_nbr, force, config=config)NEWLINE if not result :NEWLINE st.log("BGP SP - Configuring nexthop self on {} {} bgp {} Failed".format(dut, afmly, dut_asn))NEWLINE breakNEWLINE else :NEWLINE if config == 'yes' :NEWLINE bgp_topo[dut][vrf][afmly]['nbr'][bgp_nbr].update({'nh_self': True})NEWLINE else :NEWLINE del bgp_topo[dut][vrf][afmly]['nbr'][bgp_nbr]['nh_self']NEWLINENEWLINE return resultNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_bgp_neighbor_route_map_config_unconfig(dut, nbr_list, route_map, direction, addr_family, vrf='default', config='yes'):NEWLINENEWLINE action_str = 'Config' if config == 'yes' else 'Unconfig'NEWLINE st.log("{}uring BGP neighbor route map".format(action_str))NEWLINENEWLINE result = TrueNEWLINE if not BGPSP.bgp_sp_addr_family_valid(addr_family) :NEWLINE st.log("BGP SP - Invalid address family {}".format(addr_family))NEWLINE return FalseNEWLINENEWLINE if direction != 'in' and direction != 'out' :NEWLINE st.log("BGP SP - Invalid rmap direction {}".format(direction))NEWLINE return FalseNEWLINENEWLINE tb_dut = BGPSP.bgp_sp_get_dut_device(dut)NEWLINE dut_asn = BGPSP.bgp_sp_get_bgp_asn(dut, vrf)NEWLINENEWLINE if dut_asn == 0 :NEWLINE st.log("BGP SP - dut {} doesnt have bgp configured".format(dut))NEWLINE return FalseNEWLINENEWLINE dut_nbr_list = BGPSP.bgp_sp_get_bgp_neigbour_ip_list(dut, addr_family, vrf=vrf)NEWLINENEWLINE for nbr_ip in nbr_list :NEWLINE if nbr_ip in dut_nbr_list :NEWLINE bgpapi.config_bgp(dut=tb_dut, local_as=dut_asn, neighbor= nbr_ip,NEWLINE addr_family=addr_family, config_type_list =["routeMap"],NEWLINE routeMap=route_map, diRection= direction, config = config)NEWLINENEWLINE result = TrueNEWLINE if result :NEWLINE if config == 'yes':NEWLINE if direction == 'out' :NEWLINE bgp_topo[dut][vrf][addr_family]['nbr'][nbr_ip].update({'route_map_out': route_map})NEWLINE if direction == 'in' :NEWLINE bgp_topo[dut][vrf][addr_family]['nbr'][nbr_ip].update({'route_map_in': route_map})NEWLINE else :NEWLINE if direction == 'out' :NEWLINE if "route_map_out" in bgp_topo[dut][vrf][addr_family]['nbr'][nbr_ip]:NEWLINE del bgp_topo[dut][vrf][addr_family]['nbr'][nbr_ip]['route_map_out']NEWLINE if direction == 'in' :NEWLINE if "route_map_in" in bgp_topo[dut][vrf][addr_family]['nbr'][nbr_ip]:NEWLINE del bgp_topo[dut][vrf][addr_family]['nbr'][nbr_ip]['route_map_in']NEWLINENEWLINE return resultNEWLINENEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_bgp_neighbor_config_unconfig(dut, nbr_ip, nbr_asn, addr_family, vrf='default', config='yes', cli_type=""):NEWLINE """NEWLINENEWLINE :param dutNEWLINE :param nbr_ip:NEWLINE :param nbr_asn:NEWLINE :param addr_familyNEWLINE :param vrfNEWLINE :param configNEWLINE :return:NEWLINE """NEWLINENEWLINE action_str = 'Config' if config == 'yes' else 'Unconfig'NEWLINE st.log("{}uring BGP neighbor ".format(action_str))NEWLINENEWLINE if not BGPSP.bgp_sp_topology_data_present() :NEWLINE st.log("BGP SP Topology data not available")NEWLINE st.log("SP topo:\n{}\n".format(sp_topo))NEWLINE return FalseNEWLINENEWLINE if not nbr_ip or not nbr_asn :NEWLINE st.log("BGP SP - nbr_ip or asn not provided ")NEWLINE return FalseNEWLINENEWLINE if not BGPSP.bgp_sp_addr_family_valid(addr_family):NEWLINE return FalseNEWLINENEWLINE result = TrueNEWLINENEWLINE if dut not in bgp_topo.keys():NEWLINE st.log("BGP SP - {} BGP dut not configured".format(dut))NEWLINE return FalseNEWLINENEWLINE if vrf not in bgp_topo[dut].keys():NEWLINE st.log("BGP SP - {} BGP on vrf {} not configured".format(dut, vrf))NEWLINE return FalseNEWLINENEWLINE tb_dut = BGPSP.bgp_sp_get_dut_device(dut)NEWLINENEWLINE lcl_asn = bgp_topo[dut][vrf]['asn']NEWLINE if lcl_asn == 0 :NEWLINE st.log("BGP SP - {} {} BGP lcl asn not set".format(dut, vrf))NEWLINE return FalseNEWLINENEWLINE if config == 'yes' :NEWLINENEWLINE if nbr_ip in bgp_topo[dut][vrf][addr_family]['nbr'].keys():NEWLINENEWLINE st.log("BGP SP - {} vrf {} BGP nbr {} exists".format(dut, vrf, nbr_ip))NEWLINENEWLINE nbr_data = bgp_topo[dut][vrf][addr_family]['nbr'][nbr_ip]NEWLINE if nbr_data['rmt_asn'] != nbr_asn :NEWLINE st.log("BGP SP - {} vrf {} BGP nbr {} rmt asns {} wont match".format(dut, vrf, nbr_ip, nbr_asn))NEWLINE return FalseNEWLINENEWLINE result = TrueNEWLINE bgp_topo[dut][vrf][addr_family]['nbr'][nbr_ip].update({'nbr_ip' : nbr_ip})NEWLINENEWLINE else :NEWLINE st.log("BGP SP - {} vrf {} Configuring BGP nbr {} asn {}".format(dut, vrf, nbr_ip, nbr_asn))NEWLINENEWLINE result = bgpapi.config_bgp_neighbor(tb_dut, lcl_asn, nbr_ip, nbr_asn, addr_family, 3, 9, config='yes', cli_type=cli_type, connect_retry=1)NEWLINE if not result:NEWLINE st.log("BGP SP - {} vrf {} Configuring BGP nbr {} asin {} FAILED".format(dut, vrf, nbr_ip, nbr_asn))NEWLINE return FalseNEWLINENEWLINE nbr_data = {'lcl_asn': lcl_asn, 'rmt_asn': nbr_asn, 'rmt_ip': nbr_ip }NEWLINE bgp_topo[dut][vrf][addr_family]['nbr'].update({nbr_ip : nbr_data})NEWLINE else :NEWLINENEWLINE if nbr_ip not in bgp_topo[dut][vrf][addr_family]['nbr'].keys():NEWLINE st.log("BGP SP - {} vrf {} BGP nbr {} doesnt exists".format(dut, vrf, nbr_ip))NEWLINE return FalseNEWLINENEWLINE st.log("BGP SP - {} vrf {} UnConfiguring BGP nbr {} asn {} ".format(dut, vrf, nbr_ip, nbr_asn))NEWLINENEWLINE result = bgpapi.config_bgp_neighbor(tb_dut, lcl_asn, nbr_ip, nbr_asn, addr_family, config='no', cli_type=cli_type)NEWLINE if not result:NEWLINE st.log("BGP SP - {} vrf {} UnConfiguring BGP nbr {} asn {} FAILED".format(dut, vrf, nbr_ip, nbr_asn))NEWLINENEWLINE del bgp_topo[dut][vrf][addr_family]['nbr'][nbr_ip]NEWLINENEWLINE #st.log("BGP SP - Bgp topo after {} router bgp nbr: {}".format(action_str, bgp_topo))NEWLINE return resultNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_bgp_neighbor_segment_config_unconfig(segment_data={}, addr_family='all', config='yes'):NEWLINENEWLINE action_str = 'Config' if config == 'yes' else 'Unconfig'NEWLINE st.log("{}uring Bgp segment".format(action_str))NEWLINE st.log("Input BGP Segment data : {}".format(segment_data))NEWLINENEWLINE result = TrueNEWLINE threaded_run = FalseNEWLINE if config != 'yes' : threaded_run = TrueNEWLINENEWLINE lcl_dut = segment_data['lcl_dut']NEWLINE lcl_asn = segment_data['lcl_asn']NEWLINE rmt_dut = segment_data['rmt_dut']NEWLINE rmt_asn = segment_data['rmt_asn']NEWLINENEWLINE if 'lcl_vrf' in segment_data.keys():NEWLINE lcl_vrf = segment_data['lcl_vrf']NEWLINE else:NEWLINE lcl_vrf ='default'NEWLINENEWLINE if 'rmt_vrf' in segment_data.keys():NEWLINE rmt_vrf = segment_data['rmt_vrf']NEWLINE else:NEWLINE rmt_vrf ='default'NEWLINENEWLINE if 'lcl_link' in segment_data.keys():NEWLINE link = segment_data['lcl_link']NEWLINE else:NEWLINE link ='none'NEWLINENEWLINE st.log("BGP SP - {}uring bgp nbr {}:{}--{}--{}:{}".format(NEWLINE action_str, lcl_dut, lcl_asn,NEWLINE link, rmt_asn, rmt_dut))NEWLINENEWLINENEWLINE for _ in range(0,1) :NEWLINENEWLINE #ibgp_session = True if lcl_asn == rmt_asn else FalseNEWLINENEWLINE if not BGPSP.bgp_sp_dut_present(lcl_dut) :NEWLINE st.log("BGP SP - Dut {} not in topology list ".format(lcl_dut))NEWLINE result = FalseNEWLINE breakNEWLINENEWLINE if not BGPSP.bgp_sp_dut_present(rmt_dut) :NEWLINE st.log("BGP SP - Dut {} not in topology list ".format(rmt_dut))NEWLINE result = FalseNEWLINE breakNEWLINENEWLINE addr_family_list = BGPSP.bgp_sp_get_address_family_list(addr_family)NEWLINE link_list = BGPSP.bgp_sp_dut_get_connected_links(lcl_dut, rmt_dut)NEWLINENEWLINE if not link_list or len(link_list) == 0 :NEWLINE st.log("BGP SP - no links available between {} {}".format(lcl_dut, rmt_dut))NEWLINENEWLINE bgp_configured = FalseNEWLINENEWLINE for afmly in addr_family_list:NEWLINE lcl_ip = ''NEWLINE rmt_ip = ''NEWLINE link_name = ''NEWLINENEWLINE if link == 'none' :NEWLINE lcl_ip = BGPSP.bgp_sp_get_dut_loopback_ip(lcl_dut, 0, afmly)NEWLINE rmt_ip = BGPSP.bgp_sp_get_dut_loopback_ip(rmt_dut, 0, afmly)NEWLINE elif link == 'any' :NEWLINE if len(link_list) == 0 :NEWLINE st.log("BGP SP - No link present between {} {}".format(lcl_dut, rmt_dut))NEWLINE lcl_ip = BGPSP.bgp_sp_get_dut_loopback_ip(lcl_dut, 0, afmly)NEWLINE rmt_ip = BGPSP.bgp_sp_get_dut_loopback_ip(rmt_dut, 0, afmly)NEWLINE else :NEWLINE link_name = link_list[0]NEWLINE else :NEWLINE if link not in link_list :NEWLINE st.log("BGP SP - Link {} not present between {} {}".format(link, lcl_dut, rmt_dut))NEWLINE result = FalseNEWLINE breakNEWLINENEWLINE link_name = linkNEWLINENEWLINE lcl_ip = BGPSP.bgp_sp_dut_get_link_local_ip(lcl_dut, link_name, afmly)NEWLINE rmt_ip = BGPSP.bgp_sp_dut_get_link_remote_ip(lcl_dut, link_name, afmly)NEWLINENEWLINE if lcl_ip == '' or rmt_ip == '' :NEWLINE st.log("BGP SP - {} Link {} no have lcl/rmt {} {} ip assigned".format(afmly, link, lcl_ip, rmt_ip))NEWLINE continueNEWLINE #return FalseNEWLINENEWLINE if not bgp_configured :NEWLINENEWLINE bgp_configured = TrueNEWLINENEWLINE dut_thread = []NEWLINENEWLINE if config == 'yes' :NEWLINE if not BGPSP.bgp_sp_bgp_configured(lcl_dut, lcl_vrf):NEWLINE st.log("BGP SP - {} BGP on vrf {} not configured".format(lcl_dut, lcl_vrf))NEWLINENEWLINE if threaded_run:NEWLINE dut_thread.append([BGPSP.bgp_sp_bgp_config_unconfig,NEWLINE lcl_dut, lcl_asn, '', lcl_vrf, config])NEWLINE else :NEWLINE result = BGPSP.bgp_sp_bgp_config_unconfig(NEWLINE lcl_dut, lcl_asn, router_id='', vrf=lcl_vrf, config=config)NEWLINENEWLINE if not result :NEWLINE st.log("BGP SP - bgp config for {} {} FAILED".format(lcl_dut, lcl_asn))NEWLINE result = FalseNEWLINE breakNEWLINENEWLINE if not BGPSP.bgp_sp_bgp_configured(rmt_dut, rmt_vrf) :NEWLINE st.log("BGP SP - {} BGP on vrf {} not configured".format(rmt_dut, rmt_vrf))NEWLINENEWLINENEWLINE if threaded_run:NEWLINE dut_thread.append([BGPSP.bgp_sp_bgp_config_unconfig,NEWLINE rmt_dut, rmt_asn, '', rmt_vrf, config])NEWLINE else :NEWLINE result = BGPSP.bgp_sp_bgp_config_unconfig(NEWLINE rmt_dut, rmt_asn, router_id='', vrf=rmt_vrf, config=config)NEWLINENEWLINE if not result :NEWLINE st.log("BGP SP - bgp config for {} {} FAILED".format(rmt_dut, rmt_asn))NEWLINE result = FalseNEWLINE breakNEWLINENEWLINE if threaded_run:NEWLINE [out, exceptions] = putils.exec_all(bgplib.fast_start, dut_thread)NEWLINE st.log("BGP SP - Bgp config Threaded Run result {}".format([out, exceptions]))NEWLINE if False in out : result = FalseNEWLINENEWLINE if not result :NEWLINE st.log("BGP SP - Neighbor BGP config FAILED")NEWLINE return FalseNEWLINENEWLINENEWLINE dut_thread = []NEWLINENEWLINE if threaded_run:NEWLINE dut_thread.append([BGPSP.bgp_sp_bgp_neighbor_config_unconfig,NEWLINE lcl_dut, rmt_ip, rmt_asn, afmly, lcl_vrf, config])NEWLINE else :NEWLINE result = BGPSP.bgp_sp_bgp_neighbor_config_unconfig(NEWLINE lcl_dut, rmt_ip, rmt_asn, afmly, vrf=lcl_vrf, config=config)NEWLINENEWLINE if not result :NEWLINE st.log("BGP SP - bgp nbr config for {} {} {} {} FAILED".format(lcl_dut, rmt_ip, rmt_asn, afmly))NEWLINE result = FalseNEWLINE breakNEWLINENEWLINE if threaded_run:NEWLINE dut_thread.append([BGPSP.bgp_sp_bgp_neighbor_config_unconfig,NEWLINE rmt_dut, lcl_ip, lcl_asn, afmly, rmt_vrf, config])NEWLINE else :NEWLINE result = BGPSP.bgp_sp_bgp_neighbor_config_unconfig(NEWLINE rmt_dut, lcl_ip, lcl_asn, afmly, vrf=rmt_vrf, config=config)NEWLINENEWLINE if not result :NEWLINE st.log("BGP SP - bgp nbr config for {} {} {} {} FAILED".format(rmt_dut, lcl_ip, lcl_asn, afmly))NEWLINE result = FalseNEWLINE breakNEWLINENEWLINE if threaded_run:NEWLINE [out, exceptions] = putils.exec_all(bgplib.fast_start, dut_thread)NEWLINE st.log("BGP SP - Bgp Neighbor config Threaded Run result {}".format([out, exceptions]))NEWLINE if False in out : result = FalseNEWLINENEWLINE if not result :NEWLINE breakNEWLINENEWLINE if not bgp_configured :NEWLINE result = FalseNEWLINE breakNEWLINENEWLINE result_str = "Success" if result else "FAILED"NEWLINENEWLINE st.log("BGP SP - {}uring bgp nbr {}:{}--{}--{}:{} {}".format(NEWLINE action_str, lcl_dut, lcl_asn,NEWLINE link, rmt_asn, rmt_dut, result_str))NEWLINE return resultNEWLINENEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_bgp_asn_map_config_unconfig(dut_asn_map={}, config='yes', vrf='default', addr_family='all', max_adjacency='all', cli_type="vtysh", debug_run=False):NEWLINE """NEWLINENEWLINE :param dut_asn_mapNEWLINE :param config:NEWLINE :param vrf:NEWLINE :param addr_familyNEWLINE :param max_adjacencyNEWLINE :return:NEWLINE """NEWLINE action_str = 'Config' if config == 'yes' else 'Unconfig'NEWLINE st.log("{}uring list of bgp AS nodes.".format(action_str))NEWLINENEWLINE if not BGPSP.bgp_sp_topology_data_present() :NEWLINE st.log("BGP SP Topology data not available")NEWLINE st.log("SP topo:\n{}\n".format(sp_topo))NEWLINE return FalseNEWLINENEWLINE if not dut_asn_map :NEWLINE st.log("BGP SP DUT to AS Map not provided ")NEWLINE st.log("dut_asn_map:\n{}\n".format(dut_asn_map))NEWLINE return FalseNEWLINENEWLINE #threaded_run = FalseNEWLINE #debug_run = FalseNEWLINE result = TrueNEWLINENEWLINE addr_family_list = BGPSP.bgp_sp_get_address_family_list(addr_family)NEWLINE dut_asn_map = {k: dut_asn_map[k] for k in sorted(dut_asn_map)}NEWLINE adj_limit = 10 if max_adjacency == 'all' else int(max_adjacency)NEWLINENEWLINE st.log("BGP Dut Asn map: {}".format(dut_asn_map))NEWLINENEWLINE for dut, as_num in dut_asn_map.items():NEWLINE if dut not in sp_topo['dut_list']:NEWLINE st.log("BGP SP - Dut {} not in BGP SP topology {}".format(dut, sp_topo['dut_list']))NEWLINE return FalseNEWLINENEWLINE nbr_count = {}NEWLINE nbr_visited = {}NEWLINE for dut, as_num in dut_asn_map.items():NEWLINE nbr_visited[dut] = FalseNEWLINENEWLINE result = BGPSP.bgp_sp_bgp_config_unconfig(dut, as_num, router_id='', vrf=vrf, config=config, cli_type=cli_type)NEWLINE if not result :NEWLINE st.log("BGP SP - bgp config for {} {} FAILED".format(dut, as_num))NEWLINE return FalseNEWLINENEWLINE for dut, lcl_asn in dut_asn_map.items():NEWLINE #tb_dut = sp_topo[dut]['device']NEWLINENEWLINE for link_name, link_data in sp_topo[dut]['intf'].items():NEWLINENEWLINE if link_data['type'] == 'LBK':NEWLINE continueNEWLINENEWLINE rmt_dut = link_data['rmt_dut']NEWLINE if rmt_dut not in dut_asn_map.keys():NEWLINE continueNEWLINENEWLINE if nbr_visited[rmt_dut] :NEWLINE continueNEWLINENEWLINE rmt_asn = dut_asn_map[rmt_dut]NEWLINENEWLINE from_node_adj = "{}{}".format(dut, rmt_dut)NEWLINE if from_node_adj not in nbr_count.keys():NEWLINE nbr_count[from_node_adj] = 0NEWLINENEWLINE to_node_adj = "{}{}".format(dut, rmt_dut)NEWLINE if to_node_adj not in nbr_count.keys():NEWLINE nbr_count[to_node_adj] = 0NEWLINENEWLINE if nbr_count[from_node_adj] >= adj_limit :NEWLINE continueNEWLINENEWLINE if nbr_count[to_node_adj] >= adj_limit :NEWLINE continueNEWLINENEWLINE nbr_added = FalseNEWLINE for afmly in addr_family_list:NEWLINE if link_name in sp_topo[dut][afmly]['link'].keys():NEWLINENEWLINE ip_data = sp_topo[dut][afmly]['link'][link_name]NEWLINENEWLINE if 'rmt_ip' in ip_data.keys() :NEWLINENEWLINE lcl_ip = ip_data['ip']NEWLINE rmt_ip = ip_data['rmt_ip']NEWLINENEWLINE result = BGPSP.bgp_sp_bgp_neighbor_config_unconfig(dut, rmt_ip, rmt_asn, afmly, vrf=vrf, config=config, cli_type=cli_type)NEWLINE if not result :NEWLINE st.log("BGP SP - bgp nbr config for {} {} {} {} FAILED".format(dut, rmt_ip, rmt_asn, afmly))NEWLINE return FalseNEWLINENEWLINE result = BGPSP.bgp_sp_bgp_neighbor_config_unconfig(rmt_dut, lcl_ip, lcl_asn, afmly, vrf=vrf, config=config, cli_type=cli_type)NEWLINE if not result :NEWLINE st.log("BGP SP - bgp nbr config for {} {} {} {} FAILED".format(rmt_dut, lcl_ip, lcl_asn, afmly))NEWLINE return FalseNEWLINENEWLINE nbr_added = TrueNEWLINENEWLINE if nbr_added :NEWLINE nbr_count[to_node_adj] += 1NEWLINE nbr_count[from_node_adj] += 1NEWLINENEWLINE nbr_visited[dut] = TrueNEWLINENEWLINE if debug_run:NEWLINE BGPSP.bgp_sp_show_dut_bgp_cmd_logs(dut)NEWLINENEWLINE return resultNEWLINENEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_clear_bgp(dut_list, addr_family='all'):NEWLINENEWLINE if len(dut_list) == 0:NEWLINE dut_list = sp_topo['dut_list']NEWLINENEWLINE st.log("BGP SP - Clearing BGP sessions {}".format(dut_list))NEWLINENEWLINE result = TrueNEWLINE threaded_run = TrueNEWLINE dut_thread = []NEWLINENEWLINE dut_list = list(dut_list) if isinstance(dut_list, list) else [dut_list]NEWLINE if not dut_list or len(dut_list) < 2: threaded_run = FalseNEWLINENEWLINE addr_family_list = BGPSP.bgp_sp_get_address_family_list(addr_family)NEWLINENEWLINE for afmly in addr_family_list:NEWLINE dut_thread = []NEWLINE for dut in dut_list :NEWLINE if dut not in bgp_topo.keys():NEWLINE continueNEWLINENEWLINE if BGPSP.bgp_sp_dut_is_tg(dut) :NEWLINE continueNEWLINENEWLINE tb_dut = sp_topo[dut]['device']NEWLINENEWLINE st.log("BGP SP - clearing {} bgp on {}".format(afmly , dut))NEWLINE if threaded_run:NEWLINE if afmly == 'ipv4' :NEWLINE dut_thread.append([bgpapi.clear_ip_bgp_vtysh, tb_dut])NEWLINE else :NEWLINE dut_thread.append([bgpapi.clear_ipv6_bgp_vtysh, tb_dut])NEWLINE else :NEWLINE if afmly == 'ipv4' :NEWLINE bgpapi.clear_ip_bgp_vtysh(tb_dut)NEWLINE else :NEWLINE bgpapi.clear_ipv6_bgp_vtysh(tb_dut)NEWLINENEWLINE if threaded_run :NEWLINE [out, exceptions] = putils.exec_all(bgplib.fast_start, dut_thread)NEWLINE st.log("BGP SP - Clear BGP Threaded Run result {}".format([out, exceptions]))NEWLINE if False in out : result = FalseNEWLINENEWLINE return resultNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_cleanup_bgp_routers(dut_list = [], threaded_run=True):NEWLINENEWLINE if len(dut_list) == 0:NEWLINE dut_list = sp_topo['dut_list']NEWLINENEWLINE st.log("BGP SP - Unconfiguring BGP routers {}".format(dut_list))NEWLINENEWLINE result = TrueNEWLINE #threaded_run = TrueNEWLINE device_list = []NEWLINE dut_thread = []NEWLINENEWLINE for dut in dut_list :NEWLINE if dut not in bgp_topo.keys():NEWLINE st.log("BGP SP - BGP not in topo..force deleting bgp router on {}".format(dut))NEWLINENEWLINE tb_dut = sp_topo[dut]['device']NEWLINE if not BGPSP.bgp_sp_dut_is_tg(dut) :NEWLINE device_list.append(tb_dut)NEWLINE dut_thread.append([bgpapi.unconfig_router_bgp, tb_dut])NEWLINENEWLINE if dut in bgp_topo.keys():NEWLINE del bgp_topo[dut]NEWLINENEWLINE if not device_list : return TrueNEWLINENEWLINE st.log("BGP SP - clearing bgp on {}".format(device_list))NEWLINENEWLINE if threaded_run :NEWLINE [out, exceptions] = putils.exec_all(bgplib.fast_start, dut_thread)NEWLINE st.log("BGP SP - Threaded Run result {}".format([out, exceptions]))NEWLINE if False in out : result = FalseNEWLINE else :NEWLINE result = bgpapi.cleanup_router_bgp(device_list)NEWLINENEWLINE return resultNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_dut_verify_all_bgp_sessions(dut, addr_family='all', state='up'):NEWLINENEWLINE st.log("BGP SP - Verify Bgp session {} on {}.".format(state, dut))NEWLINENEWLINE if not BGPSP.bgp_sp_dut_present(dut):NEWLINE st.log("Dut {} not present".format(dut))NEWLINE return FalseNEWLINENEWLINE if not bgp_topo[dut] :NEWLINE st.log("BGP SP - BGP not configured in {}".format(dut))NEWLINE return FalseNEWLINENEWLINE result = TrueNEWLINE tb_dut = BGPSP.bgp_sp_get_dut_device(dut)NEWLINENEWLINE addr_family_list = BGPSP.bgp_sp_get_address_family_list(addr_family)NEWLINENEWLINE vrf_list = list(bgp_topo[dut].keys())NEWLINENEWLINE for vrf in vrf_list :NEWLINE for afmly in addr_family_list:NEWLINE nbr_list = bgp_topo[dut][vrf][afmly]['nbr'].keys()NEWLINENEWLINE loop_flag = 0NEWLINE for iter in range(6):NEWLINE result_flag = 0NEWLINE result = bgpapi.verify_bgp_summary(tb_dut, family=afmly, neighbor=nbr_list, state='Established')NEWLINE if result :NEWLINE if state == 'down' :NEWLINE st.log("BGP SP - BGP session not down for nghbor {}".format(nbr_list))NEWLINE BGPSP.bgp_sp_show_dut_route_cmd_logs(dut)NEWLINE #breakNEWLINE result_flag = 1NEWLINENEWLINE if not result :NEWLINE if state == 'up' :NEWLINE st.log("BGP SP - BGP session not up for nghbor {}".format(nbr_list))NEWLINE BGPSP.bgp_sp_show_dut_route_cmd_logs(dut)NEWLINE #breakNEWLINE result_flag = 1NEWLINENEWLINE if result_flag == 0:NEWLINE loop_flag = 0NEWLINE breakNEWLINE else:NEWLINE loop_flag = 1NEWLINE st.wait(10, "Waiting or the connectios establishement")NEWLINENEWLINE if loop_flag == 1:NEWLINE breakNEWLINENEWLINE if not result :NEWLINE breakNEWLINENEWLINE result_str = "Success" if result else "Failed"NEWLINE st.log("BGP SP - BGP Session {} check {}".format(state, result_str))NEWLINENEWLINE return resultNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_verify_all_bgp_sessions(dut_list=[], addr_family='all', state='up', threaded_run=True):NEWLINE """NEWLINENEWLINE :param config:NEWLINE :param vrf:NEWLINE :param addr_family:NEWLINE :return:NEWLINE """NEWLINENEWLINE if len(dut_list) == 0:NEWLINE dut_list = BGPSP.bgp_sp_get_dut_list()NEWLINENEWLINE st.log("BGP SP - Verify {} Bgp Session {} on {}.".format(addr_family, state, dut_list))NEWLINENEWLINE result = TrueNEWLINE dut_thread = []NEWLINENEWLINE dut_list = list(dut_list) if isinstance(dut_list, list) else [dut_list]NEWLINE if not dut_list or len(dut_list) < 2: threaded_run = FalseNEWLINENEWLINE for dut in dut_list :NEWLINENEWLINE dut_result = TrueNEWLINE if threaded_run:NEWLINE dut_thread.append([BGPSP.bgp_sp_dut_verify_all_bgp_sessions, dut, addr_family, state])NEWLINE else :NEWLINE dut_result = BGPSP.bgp_sp_dut_verify_all_bgp_sessions(dut, addr_family, state)NEWLINENEWLINE if not dut_result:NEWLINE result = FalseNEWLINE st.log("BGP SP - BGP session test at {} failed".format(dut))NEWLINENEWLINE if threaded_run:NEWLINE [out, exceptions] = putils.exec_all(bgplib.fast_start, dut_thread)NEWLINE st.log("BGP SP - BGP session test Threaded Run result {}".format([out, exceptions]))NEWLINE if False in out : result = FalseNEWLINENEWLINE result_str = "Success" if result else "Failed"NEWLINE st.log("BGP SP - BGP Session {} check {}".format(state, result_str))NEWLINENEWLINE return resultNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_linear_topo_bgp_config_unconfig(sess_type='eBGP', addr_family='all', ring='no', config='yes'):NEWLINENEWLINE action_str = 'Config' if config == 'yes' else 'Unconfig'NEWLINE topology = "Linear" if ring == 'no' else "Ring"NEWLINE st.banner("{}uring {} topo {} session".format(action_str, topology, sess_type))NEWLINENEWLINE if BGPSP.bgp_sp_get_dut_count() < 2 :NEWLINE st.log("BGP SP - Testbed doesnt have two duts")NEWLINE st.report_fail("test_case_passed")NEWLINE return FalseNEWLINENEWLINE if config == 'yes' :NEWLINE if ring == 'no' :NEWLINE dut_linear_path = BGPSP.bgp_sp_find_linear_topo_in_dut_list()NEWLINE else :NEWLINE dut_linear_path = BGPSP.bgp_sp_find_ring_topo_in_dut_list()NEWLINE else :NEWLINE if ring == 'no' :NEWLINE dut_linear_path = BGPSP.bgp_sp_dut_get_saved_linear_topo()NEWLINE else :NEWLINE dut_linear_path = BGPSP.bgp_sp_dut_get_saved_ring_topo()NEWLINENEWLINE BGPSP.bgp_sp_show_topo_path(dut_linear_path)NEWLINENEWLINE if not dut_linear_path['found'] :NEWLINE st.log("BGP SP - Get linear path Failed")NEWLINE st.log("BGP SP - {} topo {} session test FAILED".format(sess_type, topology))NEWLINE st.report_fail("test_case_failed")NEWLINE return FalseNEWLINENEWLINE dut_list = dut_linear_path['dut_list']NEWLINE path_segts = dut_linear_path['segment']NEWLINENEWLINE result = TrueNEWLINE base_asn = 65001NEWLINE asn_index = 0NEWLINENEWLINE segment_count = len(path_segts)NEWLINENEWLINE form_ring_session = FalseNEWLINE if segment_count >= 2 and ring == 'yes' :NEWLINE form_ring_session = TrueNEWLINENEWLINE for segt_idx, segt_data_links in path_segts.items():NEWLINENEWLINE segt_data = segt_data_links[0]NEWLINENEWLINE if form_ring_session and segt_idx == (segment_count - 1):NEWLINE # last node and first node segmentNEWLINE lcl_asn = base_asn + asn_indexNEWLINE rmt_asn = path_segts[0]['lcl_asn']NEWLINENEWLINE elif sess_type == 'iBGP' :NEWLINE # all node i bgpNEWLINE lcl_asn = base_asnNEWLINE rmt_asn = base_asnNEWLINENEWLINE elif sess_type == 'eBGP' :NEWLINE # all node ebgpNEWLINE lcl_asn = base_asn + asn_indexNEWLINE asn_index += 1NEWLINE rmt_asn = base_asn + asn_indexNEWLINENEWLINE elif sess_type == 'eBGPiBGPeBGP' :NEWLINE # N--e--N--i--N--e--N...NEWLINE lcl_asn = base_asn + asn_indexNEWLINE curr_sess = segt_idx % 3NEWLINE if curr_sess == 0 or curr_sess == 2: #0-e 1=i 2=eNEWLINE asn_index += 1NEWLINE rmt_asn = base_asn + asn_indexNEWLINENEWLINE elif sess_type == 'eBGPiBGPiBGP' :NEWLINE # N--e--N--i--N--i--N--i--N ...all iNEWLINE lcl_asn = base_asn + asn_indexNEWLINE if segt_idx == 0:NEWLINE asn_index += 1NEWLINE rmt_asn = base_asn + asn_indexNEWLINENEWLINE elif sess_type == 'eBGPeBGPiBGP' :NEWLINE # N--e--N--e--N--i--N--i--N ...all iNEWLINE lcl_asn = base_asn + asn_indexNEWLINE if segt_idx <= 1:NEWLINE asn_index += 1NEWLINE rmt_asn = base_asn + asn_indexNEWLINENEWLINE elif sess_type == 'iBGPeBGPiBGP' :NEWLINE # N--i--N--e--N--i--N--i--N ...all iNEWLINE lcl_asn = base_asn + asn_indexNEWLINE if segt_idx == 1:NEWLINE asn_index += 1NEWLINE rmt_asn = base_asn + asn_indexNEWLINENEWLINE else :NEWLINE st.log("BGP SP - Invalid BGP session Type passed {}".format(sess_type))NEWLINE return FalseNEWLINENEWLINE segt_data.update({'lcl_asn': lcl_asn})NEWLINE segt_data.update({'rmt_asn': rmt_asn})NEWLINENEWLINE result = BGPSP.bgp_sp_bgp_neighbor_segment_config_unconfig(segt_data, addr_family, config=config)NEWLINE if not result :NEWLINE breakNEWLINENEWLINE if result and config == 'yes':NEWLINE st.wait(3)NEWLINE result = BGPSP.bgp_sp_verify_all_bgp_sessions(dut_list, addr_family='all')NEWLINE if not result :NEWLINE st.log("BGP SP - Linear topo session {} check Failed".format(sess_type))NEWLINENEWLINE result_str = "Success" if result else "Failed"NEWLINE st.banner("BGP SP - {}uring {} topo {} session {}".format(action_str, topology, sess_type, result_str))NEWLINENEWLINE return resultNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_star_topo_bgp_config_unconfig(bgp_asn=65008, sess_type='eBGP', addr_family='all', config='yes'):NEWLINENEWLINE action_str = 'Config' if config == 'yes' else 'Unconfig'NEWLINE st.banner("{}uring Star topology {} session".format(action_str, sess_type))NEWLINENEWLINE if BGPSP.bgp_sp_get_dut_count() < 3 :NEWLINE st.log("BGP SP - Testbed doesnt have minimum 3 duts")NEWLINE st.report_fail("test_case_passed")NEWLINE return FalseNEWLINENEWLINE if config == 'yes' :NEWLINE dut_star_path = BGPSP.bgp_sp_find_star_topo_in_dut_list([],'', 0)NEWLINE else :NEWLINE dut_star_path = BGPSP.bgp_sp_dut_get_saved_star_topo()NEWLINE BGPSP.bgp_sp_show_topo_path(dut_star_path)NEWLINENEWLINE if not dut_star_path['found'] :NEWLINE st.log("BGP SP - Get Star path Failed")NEWLINE st.report_fail("test_case_failed")NEWLINE return FalseNEWLINENEWLINE dut_list = dut_star_path['dut_list']NEWLINE path_segts = dut_star_path['segment']NEWLINENEWLINE result = TrueNEWLINE if len(path_segts) < 2 :NEWLINE st.log("BGP SP - Testbed doesnt have 3 connected nodes")NEWLINE st.report_fail("test_case_failed")NEWLINE return FalseNEWLINENEWLINE core_asn = bgp_asnNEWLINE spoke_end_as = bgp_asnNEWLINE for _, segt_data_links in path_segts.items():NEWLINENEWLINE segt_data = segt_data_links[0]NEWLINENEWLINE if sess_type == 'eBGP' :NEWLINE spoke_end_as += 1NEWLINENEWLINE segt_data.update({'lcl_asn': core_asn})NEWLINE segt_data.update({'rmt_asn': spoke_end_as})NEWLINENEWLINE result = BGPSP.bgp_sp_bgp_neighbor_segment_config_unconfig(segt_data, addr_family, config=config)NEWLINE if not result :NEWLINE breakNEWLINENEWLINE if result and config == 'yes':NEWLINE st.wait(3)NEWLINE result = BGPSP.bgp_sp_verify_all_bgp_sessions(dut_list, addr_family='all')NEWLINE if not result :NEWLINE st.log("BGP SP - Star topology {} session check Failed".format(sess_type))NEWLINENEWLINE result_str = "Success" if result else "Failed"NEWLINE st.banner("BGP SP - {}uring Star topology {} session {}".format(action_str, sess_type, result_str))NEWLINENEWLINE return resultNEWLINENEWLINENEWLINE @staticmethodNEWLINE def bgp_sp_spine_leaf_bgp_config_unconfig(spine_asn=65001, leaf_asn=65003, addr_family='all', config='yes', cli_type="vtysh"):NEWLINENEWLINE action_str = 'Config' if config == 'yes' else 'Unconfig'NEWLINE st.banner("{}uring Spine Leaf BGP session".format(action_str))NEWLINENEWLINE topo_dut_count = BGPSP.bgp_sp_get_dut_count()NEWLINE if topo_dut_count < 2 :NEWLINE st.log("BGP SP - Testbed doesnt have minimum 2 duts")NEWLINE st.report_fail("test_case_passed")NEWLINE return FalseNEWLINENEWLINE topo_dut_list = BGPSP.bgp_sp_get_dut_list()NEWLINENEWLINE st.log("BGP SP - dut count {} list {}".format(topo_dut_count, topo_dut_list))NEWLINENEWLINE spine_list = []NEWLINE leaf_list = []NEWLINE dut_mid_index = topo_dut_count / 2NEWLINE dut_idx = 1NEWLINENEWLINE for dut in topo_dut_list:NEWLINE if dut_idx <= dut_mid_index :NEWLINE spine_list.append(dut)NEWLINE else :NEWLINE leaf_list.append(dut)NEWLINE dut_idx += 1NEWLINENEWLINE st.log("BGP SP - Spine List {} Leaf list {}".format(spine_list, leaf_list))NEWLINENEWLINE if config == 'yes' :NEWLINE spine_leaf_path = BGPSP.bgp_sp_find_spine_leaf_topo_in_dut_list(spine_list, leaf_list, save_path='yes')NEWLINE else :NEWLINE spine_leaf_path = BGPSP.bgp_sp_dut_get_saved_spine_leaf_topo()NEWLINENEWLINE st.log("BGP SP - Leaf Spine Path {}".format(spine_leaf_path))NEWLINENEWLINE spine_leaf_session_count = 0NEWLINENEWLINE for spine_dut, spine_path in spine_leaf_path['spine_path'].items():NEWLINENEWLINE st.log("BGP SP - Spine Path \n")NEWLINE BGPSP.bgp_sp_show_topo_path(spine_path)NEWLINENEWLINE if not spine_path['found'] :NEWLINE st.log("BGP SP - Spine {} doesnot have any leafs connected".format(spine_dut))NEWLINE continueNEWLINENEWLINE dut_list = spine_path['dut_list']NEWLINE path_segts = spine_path['segment']NEWLINENEWLINE result = TrueNEWLINE if len(path_segts) < 1 :NEWLINE st.log("BGP SP - Spine {} doesnt have connected leafs".format(spine_dut))NEWLINE continueNEWLINENEWLINE for _, segt_data_links in path_segts.items():NEWLINE segt_data = segt_data_links[0]NEWLINE segt_data.update({'lcl_asn': spine_asn})NEWLINE segt_data.update({'rmt_asn': leaf_asn})NEWLINENEWLINE result = BGPSP.bgp_sp_bgp_neighbor_segment_config_unconfig(segt_data, addr_family, config=config)NEWLINE if not result :NEWLINE breakNEWLINENEWLINE spine_leaf_session_count += 1NEWLINENEWLINE if result and spine_leaf_session_count < 1 :NEWLINE #result = FalseNEWLINE st.log("BGP SP - Zero spine leaf sessions")NEWLINE return FalseNEWLINENEWLINE if result and config == 'yes' :NEWLINE st.wait(3)NEWLINE result = BGPSP.bgp_sp_verify_all_bgp_sessions(dut_list, addr_family='all')NEWLINE if not result :NEWLINE st.log("BGP SP - Spine Leaf BGP session check Failed")NEWLINENEWLINE result_str = "Success" if result else "Failed"NEWLINE st.banner("BGP SP - {}uring Spine Leaf BGP session {}".format(action_str, result_str))NEWLINENEWLINE return resultNEWLINENEWLINENEWLINE
# Licensed to the Apache Software Foundation (ASF) under oneNEWLINE# or more contributor license agreements. See the NOTICE fileNEWLINE# distributed with this work for additional informationNEWLINE# regarding copyright ownership. The ASF licenses this fileNEWLINE# to you under the Apache License, Version 2.0 (theNEWLINE# "License"); you may not use this file except in complianceNEWLINE# with the License. You may obtain a copy of the License atNEWLINE#NEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing,NEWLINE# software distributed under the License is distributed on anNEWLINE# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANYNEWLINE# KIND, either express or implied. See the License for theNEWLINE# specific language governing permissions and limitationsNEWLINE# under the License.NEWLINENEWLINEfrom aliyunsdkcore.request import RpcRequestNEWLINEfrom aliyunsdkvpc.endpoint import endpoint_dataNEWLINENEWLINEclass DescribeSslVpnServersRequest(RpcRequest):NEWLINENEWLINE def __init__(self):NEWLINE RpcRequest.__init__(self, 'Vpc', '2016-04-28', 'DescribeSslVpnServers','vpc')NEWLINE if hasattr(self, "endpoint_map"):NEWLINE setattr(self, "endpoint_map", endpoint_data.getEndpointMap())NEWLINE if hasattr(self, "endpoint_regional"):NEWLINE setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional())NEWLINENEWLINENEWLINE def get_ResourceOwnerId(self):NEWLINE return self.get_query_params().get('ResourceOwnerId')NEWLINENEWLINE def set_ResourceOwnerId(self,ResourceOwnerId):NEWLINE self.add_query_param('ResourceOwnerId',ResourceOwnerId)NEWLINENEWLINE def get_PageNumber(self):NEWLINE return self.get_query_params().get('PageNumber')NEWLINENEWLINE def set_PageNumber(self,PageNumber):NEWLINE self.add_query_param('PageNumber',PageNumber)NEWLINENEWLINE def get_SslVpnServerId(self):NEWLINE return self.get_query_params().get('SslVpnServerId')NEWLINENEWLINE def set_SslVpnServerId(self,SslVpnServerId):NEWLINE self.add_query_param('SslVpnServerId',SslVpnServerId)NEWLINENEWLINE def get_PageSize(self):NEWLINE return self.get_query_params().get('PageSize')NEWLINENEWLINE def set_PageSize(self,PageSize):NEWLINE self.add_query_param('PageSize',PageSize)NEWLINENEWLINE def get_ResourceOwnerAccount(self):NEWLINE return self.get_query_params().get('ResourceOwnerAccount')NEWLINENEWLINE def set_ResourceOwnerAccount(self,ResourceOwnerAccount):NEWLINE self.add_query_param('ResourceOwnerAccount',ResourceOwnerAccount)NEWLINENEWLINE def get_OwnerAccount(self):NEWLINE return self.get_query_params().get('OwnerAccount')NEWLINENEWLINE def set_OwnerAccount(self,OwnerAccount):NEWLINE self.add_query_param('OwnerAccount',OwnerAccount)NEWLINENEWLINE def get_VpnGatewayId(self):NEWLINE return self.get_query_params().get('VpnGatewayId')NEWLINENEWLINE def set_VpnGatewayId(self,VpnGatewayId):NEWLINE self.add_query_param('VpnGatewayId',VpnGatewayId)NEWLINENEWLINE def get_OwnerId(self):NEWLINE return self.get_query_params().get('OwnerId')NEWLINENEWLINE def set_OwnerId(self,OwnerId):NEWLINE self.add_query_param('OwnerId',OwnerId)NEWLINENEWLINE def get_Name(self):NEWLINE return self.get_query_params().get('Name')NEWLINENEWLINE def set_Name(self,Name):NEWLINE self.add_query_param('Name',Name)
from hp_model import operationNEWLINEimport matplotlib.pyplot as pltNEWLINENEWLINENEWLINEinit = 0NEWLINEstate = 0NEWLINEi = 0NEWLINENEWLINEcp1 = []NEWLINEcp2 = []NEWLINEerp = []NEWLINEpu = []NEWLINEefflist = []NEWLINElast_state = 0NEWLINEtemperature = []NEWLINEstate_list = []NEWLINEQ_list = []NEWLINEwhile 1:NEWLINE if i >= 30:NEWLINE state = 0NEWLINE state_list.append(state)NEWLINE last_q = initNEWLINE Q, P_total, COP, P, eff, T, current_q = operation(state, last_q, 'Heater')NEWLINE cp1.append(P[0])NEWLINE cp2.append(P[1])NEWLINE erp.append(P[2])NEWLINE pu.append(P[3])NEWLINE efflist.append(eff)NEWLINE temperature.append(T)NEWLINE Q_list.append(current_q)NEWLINE i += 1NEWLINE init = QNEWLINE last_state = stateNEWLINE state = 100NEWLINE if i == 50:NEWLINE breakNEWLINENEWLINEplt.figure()NEWLINEplt.plot(cp1, label='cp1')NEWLINEplt.plot(cp2, label='cp2')NEWLINEplt.plot(erp, label='erp')NEWLINEplt.plot(pu, label='pu')NEWLINEplt.legend()NEWLINEplt.xlabel('Minutes')NEWLINEplt.ylabel('Power')NEWLINEplt.show()NEWLINENEWLINEplt.figure()NEWLINEplt.plot(efflist)NEWLINEplt.xlabel('Minutes')NEWLINEplt.ylabel('Efficiency')NEWLINEplt.show()NEWLINENEWLINEplt.figure()NEWLINEplt.plot(temperature)NEWLINEplt.xlabel('Minutes')NEWLINEplt.ylabel('Temperature')NEWLINEplt.show()NEWLINENEWLINEplt.figure()NEWLINEplt.plot(state_list)NEWLINEplt.xlabel('Minutes')NEWLINEplt.ylabel('State')NEWLINEplt.show()NEWLINENEWLINEplt.figure()NEWLINEplt.plot(Q_list)NEWLINEplt.xlabel('Minutes')NEWLINEplt.ylabel('Q')NEWLINEplt.show()NEWLINENEWLINEprint("Thermal input to the Room: %10.3f" % Q + "\n",NEWLINE "Total power consumption: %10.3f" % P_total + "\n",NEWLINE "Energy efficiency of heat pump: %10.3f" % COP)NEWLINE
n,m=map(int,input().split())NEWLINES=set(range(1,m+1))NEWLINEfor i in range(n):NEWLINE K,*A=map(int,input().split())NEWLINE S&=set(A)NEWLINEprint(len(S))
# Copyright 2020 - 2021 MONAI ConsortiumNEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINENEWLINEfrom monai.transforms import AddChanneld, Compose, LoadImaged, ScaleIntensityRanged, SpacingdNEWLINENEWLINEfrom monailabel.interfaces.tasks.infer import InferTask, InferTypeNEWLINEfrom monailabel.scribbles.transforms import (NEWLINE ApplyCRFOptimisationd,NEWLINE ApplyGraphCutOptimisationd,NEWLINE ApplyISegGraphCutPostProcd,NEWLINE ApplySimpleCRFOptimisationd,NEWLINE MakeISegUnaryd,NEWLINE SoftenProbSoftmax,NEWLINE)NEWLINEfrom monailabel.transform.post import BoundingBoxd, RestoredNEWLINENEWLINEfrom segmentation_spleen_scribbles.lib.transforms import MakeMIDeepEGDUnarydNEWLINENEWLINEclass SpleenPostProc(InferTask):NEWLINE """NEWLINE Defines a generic post processing task for Spleen segmentation.NEWLINE """NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE dimension,NEWLINE description,NEWLINE intensity_range=(-300, 200, 0.0, 1.0, True),NEWLINE pix_dim=(2.5, 2.5, 5.0),NEWLINE ):NEWLINE super().__init__(NEWLINE path=None, network=None, labels=None, type=InferType.SCRIBBLES, dimension=dimension, description=descriptionNEWLINE )NEWLINE self.intensity_range = intensity_rangeNEWLINE self.pix_dim = pix_dimNEWLINENEWLINE def pre_transforms(self):NEWLINE return [NEWLINE LoadImaged(keys=["image", "logits", "label"]),NEWLINE AddChanneld(keys=["image", "label"]),NEWLINE # at the moment optimisers are bottleneck taking a long time,NEWLINE # therefore scaling non-isotropic with big spacingNEWLINE Spacingd(keys=["image", "logits", "label"], pixdim=self.pix_dim, mode=["bilinear", "bilinear", "nearest"]),NEWLINE ScaleIntensityRanged(NEWLINE keys="image",NEWLINE a_min=self.intensity_range[0],NEWLINE a_max=self.intensity_range[1],NEWLINE b_min=self.intensity_range[2],NEWLINE b_max=self.intensity_range[3],NEWLINE clip=self.intensity_range[4],NEWLINE ),NEWLINE ]NEWLINENEWLINE def post_transforms(self):NEWLINE return [NEWLINE Restored(keys="pred", ref_image="image"),NEWLINE BoundingBoxd(keys="pred", result="result", bbox="bbox"),NEWLINE ]NEWLINENEWLINE def inferer(self):NEWLINE raise NotImplementedError("inferer not implemented in base post proc class")NEWLINENEWLINENEWLINEclass SpleenISegCRF(SpleenPostProc):NEWLINE """NEWLINE Defines ISeg+CRF based post processing task for Spleen segmentation from the following paper:NEWLINENEWLINE Wang, Guotai, et al. "Interactive medical image segmentation using deep learning with image-specific fine tuning."NEWLINE IEEE transactions on medical imaging 37.7 (2018): 1562-1573. (preprint: https://arxiv.org/pdf/1710.04043.pdf)NEWLINENEWLINE This task takes as input 1) original image volume 2) logits from model and 3) scribbles from userNEWLINE indicating corrections for initial segmentation from model. User-scribbles are incorporated usingNEWLINE Equation 7 on page 4 of the paper.NEWLINENEWLINE MONAI's CRF layer is used to optimise Equation 5 from the paper, where unaries come from Equation 7NEWLINE and pairwise is the original input volume.NEWLINE """NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE dimension=3,NEWLINE description="A post processing step with ISeg + MONAI's CRF for Spleen segmentation",NEWLINE intensity_range=(-300, 200, 0.0, 1.0, True),NEWLINE pix_dim=(2.5, 2.5, 5.0),NEWLINE ):NEWLINE super().__init__(dimension, description, intensity_range, pix_dim)NEWLINENEWLINE def pre_transforms(self):NEWLINE return [NEWLINE LoadImaged(keys=["image", "logits", "label"]),NEWLINE AddChanneld(keys=["image", "label"]),NEWLINE # at the moment optimisers are bottleneck taking a long time,NEWLINE # therefore scaling non-isotropic with big spacingNEWLINE Spacingd(keys=["image", "logits", "label"], pixdim=self.pix_dim, mode=["bilinear", "bilinear", "nearest"]),NEWLINE ScaleIntensityRanged(NEWLINE keys="image",NEWLINE a_min=self.intensity_range[0],NEWLINE a_max=self.intensity_range[1],NEWLINE b_min=self.intensity_range[2],NEWLINE b_max=self.intensity_range[3],NEWLINE clip=self.intensity_range[4],NEWLINE ),NEWLINE SoftenProbSoftmax(logits="logits", prob="prob"),NEWLINE ]NEWLINENEWLINE def inferer(self):NEWLINE return Compose(NEWLINE [NEWLINE # unary term makerNEWLINE MakeISegUnaryd(NEWLINE image="image",NEWLINE logits="prob",NEWLINE scribbles="label",NEWLINE unary="unary",NEWLINE scribbles_bg_label=2,NEWLINE scribbles_fg_label=3,NEWLINE ),NEWLINE # optimiserNEWLINE ApplyCRFOptimisationd(unary="unary", pairwise="image", post_proc_label="pred", device="cuda"),NEWLINE ]NEWLINE )NEWLINENEWLINENEWLINEclass SpleenISegGraphCut(SpleenPostProc):NEWLINE """NEWLINE Defines ISeg+GraphCut based post processing task for Spleen segmentation from the following paper:NEWLINENEWLINE Wang, Guotai, et al. "Interactive medical image segmentation using deep learning with image-specific fine tuning."NEWLINE IEEE transactions on medical imaging 37.7 (2018): 1562-1573. (preprint: https://arxiv.org/pdf/1710.04043.pdf)NEWLINENEWLINE This task takes as input 1) original image volume 2) logits from model and 3) scribbles from userNEWLINE indicating corrections for initial segmentation from model. User-scribbles are incorporated usingNEWLINE Equation 7 on page 4 of the paper.NEWLINENEWLINE SimpleCRF's GraphCut MaxFlow is used to optimise Equation 5 from the paper,NEWLINE where unaries come from Equation 7 and pairwise is the original input volume.NEWLINE """NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE dimension=3,NEWLINE description="A post processing step with ISeg + SimpleCRF's GraphCut for Spleen segmentation",NEWLINE intensity_range=(-300, 200, 0.0, 1.0, True),NEWLINE pix_dim=(2.5, 2.5, 5.0),NEWLINE ):NEWLINE super().__init__(dimension, description, intensity_range, pix_dim)NEWLINENEWLINE def inferer(self):NEWLINE return Compose(NEWLINE [NEWLINE # unary term makerNEWLINE MakeISegUnaryd(NEWLINE image="image",NEWLINE logits="logits",NEWLINE scribbles="label",NEWLINE unary="unary",NEWLINE scribbles_bg_label=2,NEWLINE scribbles_fg_label=3,NEWLINE ),NEWLINE # optimiserNEWLINE ApplyGraphCutOptimisationd(NEWLINE unary="unary",NEWLINE pairwise="image",NEWLINE post_proc_label="pred",NEWLINE lamda=5.0,NEWLINE sigma=0.01,NEWLINE ),NEWLINE ]NEWLINE )NEWLINENEWLINENEWLINEclass SpleenMIDeepSeg(SpleenPostProc):NEWLINE """NEWLINE MIDeepSeg: https://arxiv.org/pdf/2104.12166.pdfNEWLINENEWLINE TODO: detailed descriptionNEWLINE """NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE dimension=3,NEWLINE description="A post processing step with MIDeepSeg + SimpleCRF's GraphCut for Spleen segmentation",NEWLINE intensity_range=(-300, 200, 0.0, 1.0, True),NEWLINE pix_dim=(2.5, 2.5, 5.0),NEWLINE ):NEWLINE super().__init__(dimension, description, intensity_range, pix_dim)NEWLINENEWLINE def inferer(self):NEWLINE return Compose(NEWLINE [NEWLINE # unary term makerNEWLINE MakeMIDeepEGDUnaryd(NEWLINE image="image",NEWLINE logits="logits",NEWLINE scribbles="label",NEWLINE unary = "unary",NEWLINE tau = 1.0,NEWLINE scribbles_bg_label = 2,NEWLINE scribbles_fg_label = 3,NEWLINE ),NEWLINE # MakeISegUnaryd(NEWLINE # image="image",NEWLINE # logits="logits",NEWLINE # scribbles="label",NEWLINE # unary="unary",NEWLINE # scribbles_bg_label=2,NEWLINE # scribbles_fg_label=3,NEWLINE # ),NEWLINE # optimiserNEWLINE ApplyGraphCutOptimisationd(NEWLINE unary="unary",NEWLINE pairwise="image",NEWLINE post_proc_label="pred",NEWLINE lamda=5.0,NEWLINE sigma=0.1,NEWLINE ),NEWLINE ]NEWLINE )NEWLINENEWLINENEWLINEclass SpleenInteractiveGraphCut(SpleenPostProc):NEWLINE """NEWLINE Defines ISeg+GraphCut based post processing task for Spleen segmentation from the following paper:NEWLINENEWLINE Wang, Guotai, et al. "Interactive medical image segmentation using deep learning with image-specific fine tuning."NEWLINE IEEE transactions on medical imaging 37.7 (2018): 1562-1573. (preprint: https://arxiv.org/pdf/1710.04043.pdf)NEWLINENEWLINE This task takes as input 1) original image volume 2) logits from model and 3) scribbles from userNEWLINE indicating corrections for initial segmentation from model. User-scribbles are incorporated usingNEWLINE Equation 7 on page 4 of the paper.NEWLINENEWLINE SimpleCRF's interactive GraphCut MaxFlow is used to optimise Equation 5 from the paper,NEWLINE where unaries come from Equation 7 and pairwise is the original input volume.NEWLINE """NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE dimension=3,NEWLINE description="A post processing step with SimpleCRF's Interactive ISeg GraphCut for Spleen segmentation",NEWLINE intensity_range=(-300, 200, 0.0, 1.0, True),NEWLINE pix_dim=(2.5, 2.5, 5.0),NEWLINE ):NEWLINE super().__init__(dimension, description, intensity_range, pix_dim)NEWLINENEWLINE def inferer(self):NEWLINE return Compose(NEWLINE [NEWLINE ApplyISegGraphCutPostProcd(NEWLINE image="image",NEWLINE logits="logits",NEWLINE scribbles="label",NEWLINE post_proc_label="pred",NEWLINE scribbles_bg_label=2,NEWLINE scribbles_fg_label=3,NEWLINE lamda=10.0,NEWLINE sigma=15.0,NEWLINE ),NEWLINE ]NEWLINE )NEWLINENEWLINENEWLINEclass SpleenISegSimpleCRF(SpleenPostProc):NEWLINE """NEWLINE Defines ISeg+SimpleCRF's CRF based post processing task for Spleen segmentation from the following paper:NEWLINENEWLINE Wang, Guotai, et al. "Interactive medical image segmentation using deep learning with image-specific fine tuning."NEWLINE IEEE transactions on medical imaging 37.7 (2018): 1562-1573. (preprint: https://arxiv.org/pdf/1710.04043.pdf)NEWLINENEWLINE This task takes as input 1) original image volume 2) logits from model and 3) scribbles from userNEWLINE indicating corrections for initial segmentation from model. User-scribbles are incorporated usingNEWLINE Equation 7 on page 4 of the paper.NEWLINENEWLINE SimpleCRF's CRF is used to optimise Equation 5 from the paper,NEWLINE where unaries come from Equation 7 and pairwise is the original input volume.NEWLINE """NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE dimension=3,NEWLINE description="A post processing step with ISeg + SimpleCRF's CRF for Spleen segmentation",NEWLINE intensity_range=(-300, 200, 0.0, 1.0, True),NEWLINE pix_dim=(2.5, 2.5, 5.0),NEWLINE ):NEWLINE super().__init__(dimension, description, intensity_range, pix_dim)NEWLINENEWLINE def inferer(self):NEWLINE return Compose(NEWLINE [NEWLINE # unary term makerNEWLINE MakeISegUnaryd(NEWLINE image="image",NEWLINE logits="logits",NEWLINE scribbles="label",NEWLINE unary="unary",NEWLINE scribbles_bg_label=2,NEWLINE scribbles_fg_label=3,NEWLINE ),NEWLINE # optimiserNEWLINE ApplySimpleCRFOptimisationd(NEWLINE unary="unary",NEWLINE pairwise="image",NEWLINE post_proc_label="pred",NEWLINE ),NEWLINE ]NEWLINE )NEWLINE
#!/usr/bin/pythonNEWLINENEWLINE__author__ = 'vilelag'NEWLINENEWLINEimport osNEWLINEimport argparseNEWLINEimport subprocessNEWLINEfrom multiprocessing import PoolNEWLINEimport itertoolsNEWLINEfrom sklearn.decomposition import PCANEWLINEimport numpy as npNEWLINEimport matplotlib.pyplot as pltNEWLINEfrom numpy.linalg import matrix_rankNEWLINEimport shutilNEWLINEfrom matplotlib import cmNEWLINEfrom matplotlib import patheffectsNEWLINEfrom numpy.ma import masked_arrayNEWLINENEWLINENEWLINEdef create_parsers():NEWLINE #parser for the main programNEWLINE parser = argparse.ArgumentParser(description='PCA analysis and Rank analysis of all cases or only 'NEWLINE 'the successful cases.\n For examples check ./Tests/var_*/run_all.sh')NEWLINE parser.add_argument('-nocaw', metavar='[<int>]', nargs='?', default=0, type=int, const=1,NEWLINE help='If present all the cases in the <test_file> will be used in the PCA analysis')NEWLINE parser.add_argument('-caw', metavar='<compute-accuracy-w_exec>', default='./word2vec/compute-accuracy-w',NEWLINE help='Path to the compute-accuracy-w executable')NEWLINE parser.add_argument('-test', metavar='<test_file>', default='./word2vec/questions-words.txt',NEWLINE help='Use text data from <test_file> to test the model')NEWLINE parser .add_argument('-bin', metavar='<file.bin>',NEWLINE help='Word representation dictionary in binary mode', required=False)NEWLINE parser .add_argument('-text', metavar='<file.bin>', required=True,NEWLINE help='Word representation dictionary in "text" mode')NEWLINE parser .add_argument('-folder', metavar='<folder>', default='./pcaImages',NEWLINE help='Folder where all the generated images will be saved')NEWLINE parser.add_argument('-threads', metavar='<int>', nargs=1, default=[8], type=int,NEWLINE help='Use <int> threads (default 8)')NEWLINE parser.add_argument('-t', metavar='<int>', nargs=1, default=[30000], type=int,NEWLINE help='Threshold is used to reduce vocabulary of the model for fast approximate evaluation 'NEWLINE '(0 = off, otherwise typical value is 30000, default=30000)')NEWLINE parser.add_argument('-pdf', metavar='<int>', default=1, type=int,NEWLINE help='Decide if the generated tex will be transformed in a pdf (1 = On, else Off, Default: On)')NEWLINE return parserNEWLINENEWLINENEWLINEdef create_output_folder(directory):NEWLINE if not os.path.exists(directory):NEWLINE os.makedirs(directory)NEWLINENEWLINENEWLINEdef run_ca(ca, file, threshold, test):NEWLINE out = subprocess.check_output([ca, file, threshold], stdin=open(test, 'r'))NEWLINE return outNEWLINENEWLINENEWLINEdef analyse_log(log):NEWLINE classes = dict()NEWLINE results = dict()NEWLINE current_class = ''NEWLINE case = 1NEWLINE for line in log.splitlines()[:-1]:NEWLINE spt = line.split("\\;")NEWLINE # if len(line.split(":")) == 2 and line.split(":")[1] == '':NEWLINE if len(spt) == 1 and line[-1] == ':':NEWLINE current_class = line[:-1]NEWLINE elif len(spt) == 4:NEWLINE try:NEWLINE classes[current_class].append(spt)NEWLINE except KeyError:NEWLINE classes[current_class] = [spt]NEWLINE else:NEWLINE if case == 1:NEWLINE results[current_class] = [float(line.split(" ")[2])]NEWLINE case = 0NEWLINE else:NEWLINE tmp = line.split(" ")NEWLINE ta = float(tmp[2])NEWLINE sem = float(tmp[8])NEWLINE syn = float(tmp[14])NEWLINE results[current_class].extend([ta, sem, syn])NEWLINE case = 1NEWLINE return classes, resultsNEWLINENEWLINENEWLINEdef get_raw_classes(test):NEWLINE with open(test) as f:NEWLINE content = f.read().splitlines()NEWLINE classes = dict()NEWLINE current_class = ''NEWLINE for line in content:NEWLINE spt = line.split(' ')NEWLINE if len(spt) == 2 and spt[0] == ':':NEWLINE current_class = spt[-1]NEWLINE elif len(spt) == 4:NEWLINE spt = [x.upper() for x in spt]NEWLINE try:NEWLINE classes[current_class].append(spt)NEWLINE except KeyError:NEWLINE classes[current_class] = [spt]NEWLINE return classesNEWLINENEWLINENEWLINEdef read_bin_in_text_mode(path, threshold):NEWLINE with open(path) as f:NEWLINE content = f.read().splitlines()NEWLINE data = dict()NEWLINE words, size = content[0].split(' ')NEWLINE words = int(words)NEWLINE size = int(size)NEWLINENEWLINE if 0 < threshold < words:NEWLINE words = thresholdNEWLINE print wordsNEWLINE for i in range(1, words+1):NEWLINE temp = content[i].split(' ')NEWLINE data[temp[0].upper()] = np.asarray([float(x) for x in temp[1:-1]])NEWLINE # NormalizingNEWLINE data[temp[0].upper()] *= 1 / np.linalg.norm(data[temp[0].upper()])NEWLINENEWLINE return dataNEWLINENEWLINENEWLINEdef get_words_without_repetition(data):NEWLINE class_1 = []NEWLINE dic_words = dict()NEWLINE for i in [0, 2]:NEWLINE for datum in data:NEWLINE try:NEWLINE if dic_words[datum[i]+';'+datum[i+1]]:NEWLINE continueNEWLINE except KeyError:NEWLINE dic_words[datum[i]+';'+datum[i+1]] = TrueNEWLINE class_1.append([datum[i], datum[i+1]])NEWLINENEWLINE return class_1NEWLINENEWLINENEWLINEdef pca_analyse(atuple, confidence_interval=0.9):NEWLINE class_name, data = atupleNEWLINE data = get_words_without_repetition(data)NEWLINE class_representation = []NEWLINE for c in data:NEWLINE try:NEWLINE class_representation.append(wr[c[1]] - wr[c[0]])NEWLINE except KeyError:NEWLINE passNEWLINE class_representation = np.array(class_representation)NEWLINE pca = PCA(n_components=confidence_interval)NEWLINE pca.fit(class_representation)NEWLINENEWLINE return class_name, pca.n_components, len(data)NEWLINENEWLINENEWLINEdef generate_npc_figure(n_pc):NEWLINENEWLINE y = np.arange(len(n_pc))NEWLINENEWLINE names = tuple((e[0] for e in reversed(n_pc)))NEWLINE components = np.array([e[1] for e in reversed(n_pc)])NEWLINE comp_div_pair = np.array([float(e[1])/e[2] for e in reversed(n_pc)])NEWLINE # print n_pcNEWLINE # print comp_div_pairNEWLINENEWLINE fig, (ax0, ax1) = plt.subplots(1, 2, sharey=True, figsize=(18, 16))NEWLINENEWLINE ax0.barh(y, components, align='center', alpha=0.4)NEWLINE plt.yticks(y, names)NEWLINE ax0.set_xlabel("Number of components")NEWLINE ax0.set_title("Number of components required to get a confidence interval of 90%")NEWLINE ax0.grid()NEWLINENEWLINE ax1.barh(y, comp_div_pair, align='center', color='g', alpha=0.4)NEWLINE ax1.set_xlabel("Number of components / number of pairs")NEWLINE ax1.set_title("Number of components divided by number of pairs in the class")NEWLINE ax1.grid()NEWLINENEWLINE ax1.set_xlim([0, 1])NEWLINENEWLINE ax0.yaxis.set_ticks_position('left')NEWLINE ax0.xaxis.set_ticks_position('bottom')NEWLINE ax1.yaxis.set_ticks_position('left')NEWLINE ax1.xaxis.set_ticks_position('bottom')NEWLINENEWLINE plt.savefig(folder+'/ncomponents.png', bbox_inches='tight', transparent=False)NEWLINE plt.close()NEWLINENEWLINENEWLINEdef pca_analyse2(atuple, link=True):NEWLINENEWLINE class_name, data = atupleNEWLINE n_success = len(data)NEWLINE data = get_words_without_repetition(data)NEWLINE class_1 = []NEWLINE class_2 = []NEWLINE for c in data:NEWLINE try:NEWLINE t1 = wr[c[0]]NEWLINE except KeyError:NEWLINE t1 = NoneNEWLINE try:NEWLINE t2 = wr[c[1]]NEWLINE except KeyError:NEWLINE t2 = NoneNEWLINE if t1 is not None and t2 is not None:NEWLINE class_1.append(t1)NEWLINE class_2.append(t2)NEWLINENEWLINE class_1 = np.array(class_1)NEWLINE class_2 = np.array(class_2)NEWLINENEWLINE pca = PCA(n_components=2)NEWLINE pca2 = PCA(n_components=2)NEWLINENEWLINE X_1 = pca.fit(class_1).transform(class_1)NEWLINE X_2 = pca2.fit(class_2).transform(class_2)NEWLINE print class_nameNEWLINENEWLINE plt.figure(figsize=(16, 9))NEWLINENEWLINE plt.scatter(X_1[:, 0], X_1[:, 1], c='r', marker='o')NEWLINE plt.scatter(X_2[:, 0], X_2[:, 1], c='b', marker='^')NEWLINENEWLINE # creating links between data1 and data2NEWLINE if link:NEWLINE for i in range(len(X_1)):NEWLINE plt.plot([X_1[i][0], X_2[i][0]], [X_1[i][1], X_2[i][1]], c='gray')NEWLINENEWLINE plt.xlabel("1st PC")NEWLINE plt.ylabel("2nd PC")NEWLINE plt.title('PCA with 2 PC for {}'.format(class_name))NEWLINE plt.figtext(0.1, -0.01, "Number of success cases: {0:<5} Number of combinations: {1}\nFirst explained variance "NEWLINE "ration: {2}\nSecond explained variance ration: {3}".format(NEWLINE n_success, len(data), pca.explained_variance_ratio_, pca2.explained_variance_ratio_))NEWLINE plt.savefig(folder+'/'+class_name+'.png', bbox_inches='tight', transparent=False)NEWLINE plt.close()NEWLINENEWLINENEWLINEdef pca_analyse_all(all_tuples, confidence_interval=0.9):NEWLINE data = []NEWLINE for cn, datum in all_tuples:NEWLINE datum = get_words_without_repetition(datum)NEWLINE for el in datum:NEWLINE try:NEWLINE data.append(wr[el[1]] - wr[el[0]])NEWLINE except KeyError:NEWLINE passNEWLINENEWLINE data = np.array(data)NEWLINENEWLINE pca = PCA()NEWLINE pca.fit(data)NEWLINENEWLINE ci, n = 0, 0NEWLINE for var in pca.explained_variance_ratio_:NEWLINE ci += varNEWLINE n += 1NEWLINE if ci > confidence_interval:NEWLINE breakNEWLINENEWLINENEWLINE plt.figure(figsize=(16, 9))NEWLINE plt.plot(pca.explained_variance_ratio_)NEWLINE #adding confidence_interval vlineNEWLINE plt.axvline(x=n-1, c='k', linestyle='--')NEWLINE plt.xticks(list(plt.xticks()[0]) + [n-1])NEWLINE yl = plt.ylim()NEWLINE plt.annotate("Number of components\nto {0:.0%} of the distribution".format(confidence_interval),NEWLINE (n-1, (yl[1]-yl[0])/2), ((n-1)/2, (yl[1]-yl[0])/1.6), arrowprops=dict(arrowstyle='->'))NEWLINE plt.xlabel("Principal Component")NEWLINE plt.ylabel("Explained Variance Ratio")NEWLINE plt.title("Explained variance ratio for all the success data")NEWLINE plt.savefig(folder+'/evr_all.png', bbox_inches='tight', transparent=False)NEWLINE plt.close()NEWLINENEWLINENEWLINEdef pca_analyse_all_mean(all_tuples, confidence_interval=0.9):NEWLINENEWLINE data = []NEWLINE for cn, datum in all_tuples:NEWLINE tmp_data = []NEWLINE datum = get_words_without_repetition(datum)NEWLINE for el in datum:NEWLINE try:NEWLINE tmp_data.append(wr[el[1]] - wr[el[0]])NEWLINE except KeyError:NEWLINE passNEWLINE data.append(np.array(tmp_data).mean(axis=0))NEWLINE data = np.array(data)NEWLINENEWLINE pca = PCA()NEWLINE pca.fit(data)NEWLINENEWLINE ci, n = 0, 0NEWLINE for var in pca.explained_variance_ratio_:NEWLINE ci += varNEWLINE n += 1NEWLINE if ci > confidence_interval:NEWLINE breakNEWLINENEWLINENEWLINE plt.figure(figsize=(16, 9))NEWLINE plt.plot(pca.explained_variance_ratio_)NEWLINE #adding confidence_interval vlineNEWLINE plt.axvline(x=n-1, c='k', linestyle='--')NEWLINE plt.xticks(list(plt.xticks()[0]) + [n-1])NEWLINE yl = plt.ylim()NEWLINE plt.annotate("Number of components\nto {0:.0%} of the distribution".format(confidence_interval),NEWLINE (n-1, (yl[1]-yl[0])/2), ((n-1)/2, (yl[1]-yl[0])/1.6), arrowprops=dict(arrowstyle='->'))NEWLINE plt.xlabel("Principal Component")NEWLINE plt.ylabel("Explained Variance Ratio")NEWLINE plt.title("Explained variance ratio for the mean of each success in a test class")NEWLINE plt.figtext(0.1, -0.01, "Matrix rank: {0}".format(NEWLINE matrix_rank(data)))NEWLINE plt.savefig(folder+'/evr_mean_all.png', bbox_inches='tight', transparent=False)NEWLINE plt.close()NEWLINENEWLINENEWLINEdef pca_analyse_combination(data, confidence_interval=0.9):NEWLINENEWLINE data = get_words_without_repetition(data)NEWLINE class_1 = []NEWLINE for c in data:NEWLINE try:NEWLINE class_1.append(wr[c[1]] - wr[c[0]])NEWLINE except KeyError:NEWLINE passNEWLINE class_1 = np.array(class_1)NEWLINENEWLINE pca = PCA(n_components=confidence_interval)NEWLINENEWLINE pca.fit(class_1)NEWLINENEWLINE return pca.n_componentsNEWLINENEWLINENEWLINEdef rank_analyse_combination(data):NEWLINENEWLINE data = get_words_without_repetition(data)NEWLINE class_1 = []NEWLINE for c in data:NEWLINE try:NEWLINE class_1.append(wr[c[1]] - wr[c[0]])NEWLINE except KeyError:NEWLINE passNEWLINE class_1 = np.array(class_1)NEWLINENEWLINE rank = matrix_rank(class_1)NEWLINE return rankNEWLINENEWLINENEWLINEdef get_element(p_matrix, i, j):NEWLINE if i == j:NEWLINE return str(p_matrix[i][j])NEWLINE sum = p_matrix[i][i] + p_matrix[j][j]NEWLINE comb = p_matrix[i][j]NEWLINE if comb == sum:NEWLINE return str('\\cellcolor{{green!40}} {}'.format(comb))NEWLINE elif 0.9*sum < comb < 1.1*sum:NEWLINE return str('\\cellcolor{{yellow!40}} {}'.format(comb))NEWLINE elif 1.1*sum <= comb:NEWLINE return str('\\cellcolor{{orange!40}} {}'.format(comb))NEWLINE else: #comb <= 0.9*sumNEWLINE return str('\\cellcolor{{red!40}} {}'.format(comb))NEWLINENEWLINENEWLINEdef do_line(fd, p_matrix, class_names, i):NEWLINE if i == 0:NEWLINE t_str = ['&'] + [" \\textbf{{{}}} &".format(name) for name in class_names[:-1]] + \NEWLINE [' \\textbf{{{}}} \\\\ \\hline\n'.format(class_names[-1])]NEWLINE t_str = ''.join(t_str)NEWLINE else:NEWLINE t_str = ['\\textbf{{{}}} &'.format(class_names[i-1])] + [" {} &".format(get_element(p_matrix, i-1, j))NEWLINE for j in range(len(p_matrix)-1)] + \NEWLINE [' {} \\\\ \\hline\n'.format(get_element(p_matrix, i-1, len(p_matrix)-1))]NEWLINE t_str = ''.join(t_str)NEWLINE fd.write(t_str)NEWLINENEWLINENEWLINEdef generate_latex(class_names, class_names_bak, p_matrix, fname='overlaps'):NEWLINE fd = open(folder+"/{}.tex".format(fname), "w")NEWLINE fd.write("\\documentclass{report}\n")NEWLINE fd.write("\\usepackage{amsmath, amssymb, array, stackengine, subfig}\n")NEWLINE fd.write("\\usepackage[table]{xcolor}\n")NEWLINE fd.write("\\usepackage[top=2in, bottom=1.5in, left=1cm, right=1cm]{geometry}\n")NEWLINE c_width = '{:.3f}\\textwidth'.format(float(0.5)/(len(class_names)))NEWLINE fd.write("\\newcolumntype{{C}}{{>{{\\centering\\let\\newline\\\\\\arraybackslash\\hspace{{0pt}}}}m{{{}}}}}\n".format(NEWLINE c_width))NEWLINE fd.write("\\begin{document}\n")NEWLINENEWLINE # First tableNEWLINE fd.write('\\begin{tabular}{')NEWLINE tstr = ['|'] + ['C|']*(len(class_names)+1)NEWLINE tstr = ''.join(tstr)NEWLINE fd.write(tstr+'}\n')NEWLINE fd.write("\\hline\n")NEWLINE fd.write("\\multicolumn{{{}}}{{|c|}}{{\\textbf{{Number of required components to represent each combination}}}}"NEWLINE " \\\\ \\hline\n".format(len(class_names)+1))NEWLINE for i in range(len(class_names)+1):NEWLINE do_line(fd, p_matrix, class_names, i)NEWLINE fd.write('\\end{tabular}\n')NEWLINENEWLINE #Creating 'captions'NEWLINE fd.write("\\begin{figure}[h]\n")NEWLINE # First captionNEWLINE fd.write('\\belowbaseline[0pt]{\n\\subfloat{\n\\begin{tabular}{|c|l|}\n')NEWLINE fd.write('\\hline\n')NEWLINE fd.write('\\multicolumn{2}{|c|}{\\textbf{Label}} \\\\ \\hline\n')NEWLINE for i in range(len(class_names)):NEWLINE fd.write('\\textbf{{{}}} & {} \\\\ \\hline\n'.format(class_names[i], class_names_bak[i]))NEWLINE fd.write('\\end{tabular}\n}}\n')NEWLINE # Second captionNEWLINE fd.write('\\belowbaseline[0pt]{\n\\subfloat{\n')NEWLINE fd.write('\\begin{tabular}{|C|l|}\n\\hline\n')NEWLINE fd.write('\\multicolumn{2}{|c|}{\\textbf{Color Meaning}} \\\\ \\hline\n')NEWLINE fd.write(' & Class alone \\\\ \\hline\n')NEWLINE fd.write('\\cellcolor{green!40}& $Combination = Sum$ \\\\ \\hline\n')NEWLINE fd.write('\\cellcolor{yellow!40}& $0.9 Sum < Combination < 1.1 Sum$ \\\\ \\hline\n')NEWLINE fd.write('\\cellcolor{red!40}& $Combination \\leq 0.9 Sum$ \\\\ \\hline\n')NEWLINE fd.write('\\cellcolor{orange!40}& $Combination \\geq 1.1 Sum$ \\\\ \\hline\n')NEWLINE fd.write('\\end{tabular}\n}}\n')NEWLINE fd.write('\\end{figure}\n\n')NEWLINENEWLINE fd.write('\\end{document}\n')NEWLINE fd.close()NEWLINENEWLINENEWLINEdef generate_pdf(fname='overlaps'):NEWLINE subprocess.call(['pdflatex', '{0}/{1}.tex'.format(folder, fname)])NEWLINE #remove auxiliary filesNEWLINE os.remove('{0}.aux'.format(fname))NEWLINE os.remove('{0}.log'.format(fname))NEWLINE shutil.move('{}.pdf'.format(fname), '{0}/{1}.pdf'.format(folder, fname))NEWLINENEWLINENEWLINEdef analyse_combinations(classes, pool, n_pc, pdf, rank=True):NEWLINE combinations = [i for i in itertools.combinations(range(len(classes)), 2)]NEWLINE class_names = sorted(classes)NEWLINE parallel_list2 = [classes[class_names[k[0]]] + classes[class_names[k[1]]] for k in combinations]NEWLINENEWLINE # PCANEWLINE n_pc_comb = pool.map(pca_analyse_combination, parallel_list2)NEWLINE p_matrix = [[0]*len(class_names) for i in class_names]NEWLINE for i, comb in enumerate(combinations):NEWLINE p_matrix[comb[0]][comb[1]] = n_pc_comb[i]NEWLINE p_matrix[comb[1]][comb[0]] = n_pc_comb[i]NEWLINENEWLINE class_names_bak = class_namesNEWLINE class_names = [str(i) for i in range(len(class_names))]NEWLINE for i in range(len(class_names)):NEWLINE p_matrix[i][i] = n_pc[i][1]NEWLINENEWLINE title = "Number of required components to represent each combination divided by the sum of its elements " \NEWLINE "components' number"NEWLINE generate_combinations_img(class_names, class_names_bak, p_matrix, title, fname='pca_overlaps_img')NEWLINE generate_latex(class_names, class_names_bak, p_matrix, fname='pca_overlaps')NEWLINENEWLINE if pdf == 1:NEWLINE generate_pdf(fname='pca_overlaps')NEWLINENEWLINE # Matrix rankNEWLINE if rank:NEWLINE n_rk_comb = pool.map(rank_analyse_combination, parallel_list2)NEWLINENEWLINE parallel_list3 = [classes[class_names_bak[i]] for i in range(len(classes))]NEWLINE n_rk_comb_2 = pool.map(rank_analyse_combination, parallel_list3)NEWLINENEWLINENEWLINE p_matrix = [[0]*len(class_names) for i in class_names]NEWLINE for i, comb in enumerate(combinations):NEWLINE p_matrix[comb[0]][comb[1]] = n_rk_comb[i]NEWLINE p_matrix[comb[1]][comb[0]] = n_rk_comb[i]NEWLINENEWLINE for i in range(len(class_names)):NEWLINE p_matrix[i][i] = n_rk_comb_2[i]NEWLINENEWLINE title = "Matrix rank to represent each combination divided by the sum of its elements rank"NEWLINE generate_combinations_img(class_names, class_names_bak, p_matrix, title, fname='rank_overlaps_img')NEWLINE generate_latex(class_names, class_names_bak, p_matrix, fname='rank_overlaps')NEWLINE if pdf == 1:NEWLINE generate_pdf(fname='rank_overlaps')NEWLINENEWLINENEWLINEdef generate_combinations_img(class_names, class_names_bak, p_matrix, title, fname='overlaps_img'):NEWLINE a_size = len(p_matrix)NEWLINENEWLINE diff = np.zeros([a_size, a_size])NEWLINENEWLINE for i in xrange(a_size):NEWLINE for j in xrange(a_size):NEWLINE if i == j:NEWLINE passNEWLINE else:NEWLINE _sum = p_matrix[i][i] + p_matrix[j][j]NEWLINE comb = p_matrix[i][j]NEWLINE diff[i][j] = float(comb)/float(_sum)NEWLINENEWLINE fig = plt.figure(figsize=(16, 9))NEWLINE ax = fig.add_subplot(111)NEWLINENEWLINE diffa = masked_array(diff, diff != 0)NEWLINE diffb = masked_array(diff, diff == 0)NEWLINENEWLINE cax = ax.imshow(diffb, cmap=cm.winter, interpolation='None', origin='lower', aspect='auto')NEWLINE cba = plt.colorbar(cax, format='%.1f')NEWLINENEWLINE caxb = ax.imshow(diffa, cmap=cm.Reds, interpolation='None', origin='lower', aspect='auto')NEWLINENEWLINE plt.xticks(range(a_size))NEWLINE ax.set_xticklabels(class_names_bak)NEWLINE plt.xticks(rotation=80)NEWLINENEWLINE plt.yticks(range(a_size))NEWLINE ax.set_yticklabels(class_names_bak)NEWLINENEWLINE for i in xrange(a_size):NEWLINE for j in xrange(a_size):NEWLINE ax.text(j, i, '{0}/{1:.2f}'.format(p_matrix[i][j], diff[i][j]),NEWLINE size='medium', ha='center', va='center',NEWLINE path_effects=[patheffects.withSimplePatchShadow(shadow_rgbFace=(1, 1, 1))])NEWLINENEWLINE plt.title(title)NEWLINENEWLINENEWLINE # bar = fig.colorbar(cax, format='%.1f')NEWLINE plt.rc('text', usetex=True)NEWLINE cba.set_label('$\\frac{a_{i,j}}{a_{i,i}+a_{j,j}}$', fontsize=25, rotation=0, labelpad=40)NEWLINE plt.savefig(folder+'/'+fname, bbox_inches='tight', transparent=False)NEWLINE plt.close()NEWLINENEWLINENEWLINEdef main():NEWLINE global folderNEWLINE global wrNEWLINE parser = create_parsers()NEWLINE args = vars(parser.parse_args())NEWLINE caw = args['caw']NEWLINE test = args['test']NEWLINE bin = args['bin']NEWLINE text_bin = args['text']NEWLINE threads = args['threads'][0]NEWLINE threshold = str(args['t'][0])NEWLINE folder = args['folder']NEWLINE pdf = args['pdf']NEWLINE nocaw = args['nocaw']NEWLINENEWLINE create_output_folder(folder)NEWLINE if nocaw == 0:NEWLINE run_output = run_ca(caw, bin, threshold, test)NEWLINE classes, results = analyse_log(run_output)NEWLINE else:NEWLINE classes = get_raw_classes(test)NEWLINENEWLINE wr = read_bin_in_text_mode(text_bin, int(threshold))NEWLINENEWLINE parallel_list = [(k, classes[k]) for k in sorted(classes)]NEWLINENEWLINE pool = Pool(threads)NEWLINENEWLINE n_pc = pool.map(pca_analyse, parallel_list)NEWLINE generate_npc_figure(n_pc)NEWLINENEWLINE pool.map(pca_analyse2, parallel_list)NEWLINENEWLINE pca_analyse_all(parallel_list)NEWLINE pca_analyse_all_mean(parallel_list)NEWLINENEWLINE analyse_combinations(classes, pool, n_pc, pdf)NEWLINENEWLINENEWLINEfolder = ''NEWLINEwr = dict()NEWLINEmain()
# Copyright 2019 The meson development teamNEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINENEWLINE"""Abstractions to simplify compilers that implement an MSVC compatibleNEWLINEinterface.NEWLINE"""NEWLINENEWLINEimport abcNEWLINEimport osNEWLINEimport typing as TNEWLINENEWLINEfrom ... import mesonlibNEWLINEfrom ... import mlogNEWLINENEWLINEif T.TYPE_CHECKING:NEWLINE from ...environment import EnvironmentNEWLINENEWLINEvs32_instruction_set_args = {NEWLINE 'mmx': ['/arch:SSE'], # There does not seem to be a flag just for MMXNEWLINE 'sse': ['/arch:SSE'],NEWLINE 'sse2': ['/arch:SSE2'],NEWLINE 'sse3': ['/arch:AVX'], # VS leaped from SSE2 directly to AVX.NEWLINE 'sse41': ['/arch:AVX'],NEWLINE 'sse42': ['/arch:AVX'],NEWLINE 'avx': ['/arch:AVX'],NEWLINE 'avx2': ['/arch:AVX2'],NEWLINE 'neon': None,NEWLINE} # T.Dicst[str, T.Optional[T.List[str]]]NEWLINENEWLINE# The 64 bit compiler defaults to /arch:avx.NEWLINEvs64_instruction_set_args = {NEWLINE 'mmx': ['/arch:AVX'],NEWLINE 'sse': ['/arch:AVX'],NEWLINE 'sse2': ['/arch:AVX'],NEWLINE 'sse3': ['/arch:AVX'],NEWLINE 'ssse3': ['/arch:AVX'],NEWLINE 'sse41': ['/arch:AVX'],NEWLINE 'sse42': ['/arch:AVX'],NEWLINE 'avx': ['/arch:AVX'],NEWLINE 'avx2': ['/arch:AVX2'],NEWLINE 'neon': None,NEWLINE} # T.Dicst[str, T.Optional[T.List[str]]]NEWLINENEWLINEmsvc_buildtype_args = {NEWLINE 'plain': [],NEWLINE 'debug': ["/ZI", "/Ob0", "/Od", "/RTC1"],NEWLINE 'debugoptimized': ["/Zi", "/Ob1"],NEWLINE 'release': ["/Ob2", "/Gw"],NEWLINE 'minsize': ["/Zi", "/Gw"],NEWLINE 'custom': [],NEWLINE} # type: T.Dict[str, T.List[str]]NEWLINENEWLINE# Clang-cl doesn't have /ZI, and /Zi and /Z7 do the same thingNEWLINE# quoting the docs (https://clang.llvm.org/docs/MSVCCompatibility.html):NEWLINE#NEWLINE# Clang emits relatively complete CodeView debug information if /Z7 or /Zi isNEWLINE# passed. Microsoft’s link.exe will transform the CodeView debug informationNEWLINE# into a PDBNEWLINEclangcl_buildtype_args = msvc_buildtype_args.copy()NEWLINEclangcl_buildtype_args['debug'] = ['/Zi', '/Ob0', '/Od', '/RTC1']NEWLINENEWLINEmsvc_optimization_args = {NEWLINE '0': [],NEWLINE 'g': ['/O0'],NEWLINE '1': ['/O1'],NEWLINE '2': ['/O2'],NEWLINE '3': ['/O2'],NEWLINE 's': ['/O1'], # Implies /Os.NEWLINE} # type: T.Dict[str, T.List[str]]NEWLINENEWLINEmsvc_debug_args = {NEWLINE False: [],NEWLINE True: [] # Fixme!NEWLINE} # type: T.Dict[bool, T.List[str]]NEWLINENEWLINENEWLINEclass VisualStudioLikeCompiler(metaclass=abc.ABCMeta):NEWLINENEWLINE """A common interface for all compilers implementing an MSVC-styleNEWLINE interface.NEWLINENEWLINE A number of compilers attempt to mimic MSVC, with varying levels ofNEWLINE success, such as Clang-CL and ICL (the Intel C/C++ Compiler for Windows).NEWLINE This class implements as much common logic as possible.NEWLINE """NEWLINENEWLINE std_warn_args = ['/W3']NEWLINE std_opt_args = ['/O2']NEWLINE # XXX: this is copied in this patch only to avoid circular dependenciesNEWLINE #ignore_libs = unixy_compiler_internal_libsNEWLINE ignore_libs = ('m', 'c', 'pthread', 'dl', 'rt', 'execinfo')NEWLINE internal_libs = ()NEWLINENEWLINE crt_args = {NEWLINE 'none': [],NEWLINE 'md': ['/MD'],NEWLINE 'mdd': ['/MDd'],NEWLINE 'mt': ['/MT'],NEWLINE 'mtd': ['/MTd'],NEWLINE } # type: T.Dict[str, T.List[str]]NEWLINENEWLINE # /showIncludes is needed for build dependency tracking in NinjaNEWLINE # See: https://ninja-build.org/manual.html#_depsNEWLINE always_args = ['/nologo', '/showIncludes']NEWLINE warn_args = {NEWLINE '0': ['/W1'],NEWLINE '1': ['/W2'],NEWLINE '2': ['/W3'],NEWLINE '3': ['/W4'],NEWLINE } # type: T.Dict[str, T.List[str]]NEWLINENEWLINE INVOKES_LINKER = FalseNEWLINENEWLINE def __init__(self, target: str):NEWLINE self.base_options = ['b_pch', 'b_ndebug', 'b_vscrt'] # FIXME add lto, pgo and the likeNEWLINE self.target = targetNEWLINE self.is_64 = ('x64' in target) or ('x86_64' in target)NEWLINE # do some canonicalization of target machineNEWLINE if 'x86_64' in target:NEWLINE self.machine = 'x64'NEWLINE elif '86' in target:NEWLINE self.machine = 'x86'NEWLINE else:NEWLINE self.machine = targetNEWLINE self.linker.machine = self.machineNEWLINENEWLINE # Override CCompiler.get_always_argsNEWLINE def get_always_args(self) -> T.List[str]:NEWLINE return self.always_argsNEWLINENEWLINE def get_pch_suffix(self) -> str:NEWLINE return 'pch'NEWLINENEWLINE def get_pch_name(self, header: str) -> str:NEWLINE chopped = os.path.basename(header).split('.')[:-1]NEWLINE chopped.append(self.get_pch_suffix())NEWLINE pchname = '.'.join(chopped)NEWLINE return pchnameNEWLINENEWLINE def get_pch_base_name(self, header: str) -> str:NEWLINE # This needs to be implemented by inherting classesNEWLINE raise NotImplementedErrorNEWLINENEWLINE def get_pch_use_args(self, pch_dir: str, header: str) -> T.List[str]:NEWLINE base = self.get_pch_base_name(header)NEWLINE pchname = self.get_pch_name(header)NEWLINE return ['/FI' + base, '/Yu' + base, '/Fp' + os.path.join(pch_dir, pchname)]NEWLINENEWLINE def get_preprocess_only_args(self) -> T.List[str]:NEWLINE return ['/EP']NEWLINENEWLINE def get_compile_only_args(self) -> T.List[str]:NEWLINE return ['/c']NEWLINENEWLINE def get_no_optimization_args(self) -> T.List[str]:NEWLINE return ['/Od']NEWLINENEWLINE def get_output_args(self, target: str) -> T.List[str]:NEWLINE if target.endswith('.exe'):NEWLINE return ['/Fe' + target]NEWLINE return ['/Fo' + target]NEWLINENEWLINE def get_optimization_args(self, optimization_level: str) -> T.List[str]:NEWLINE return msvc_optimization_args[optimization_level]NEWLINENEWLINE def get_debug_args(self, is_debug: bool) -> T.List[str]:NEWLINE return msvc_debug_args[is_debug]NEWLINENEWLINE def get_dependency_gen_args(self, outtarget: str, outfile: str) -> T.List[str]:NEWLINE return []NEWLINENEWLINE def linker_to_compiler_args(self, args: T.List[str]) -> T.List[str]:NEWLINE return ['/link'] + argsNEWLINENEWLINE def get_gui_app_args(self, value: bool) -> T.List[str]:NEWLINE # the default is for the linker to guess the subsystem based on presenceNEWLINE # of main or WinMain symbols, so always be explicitNEWLINE if value:NEWLINE return ['/SUBSYSTEM:WINDOWS']NEWLINE else:NEWLINE return ['/SUBSYSTEM:CONSOLE']NEWLINENEWLINE def get_pic_args(self) -> T.List[str]:NEWLINE return [] # PIC is handled by the loader on WindowsNEWLINENEWLINE def gen_vs_module_defs_args(self, defsfile: str) -> T.List[str]:NEWLINE if not isinstance(defsfile, str):NEWLINE raise RuntimeError('Module definitions file should be str')NEWLINE # With MSVC, DLLs only export symbols that are explicitly exported,NEWLINE # so if a module defs file is specified, we use that to export symbolsNEWLINE return ['/DEF:' + defsfile]NEWLINENEWLINE def gen_pch_args(self, header: str, source: str, pchname: str) -> T.Tuple[str, T.List[str]]:NEWLINE objname = os.path.splitext(pchname)[0] + '.obj'NEWLINE return objname, ['/Yc' + header, '/Fp' + pchname, '/Fo' + objname]NEWLINENEWLINE def openmp_flags(self) -> T.List[str]:NEWLINE return ['/openmp']NEWLINENEWLINE # FIXME, no idea what these should be.NEWLINE def thread_flags(self, env: 'Environment') -> T.List[str]:NEWLINE return []NEWLINENEWLINE @classmethodNEWLINE def unix_args_to_native(cls, args: T.List[str]) -> T.List[str]:NEWLINE result = []NEWLINE for i in args:NEWLINE # -mms-bitfields is specific to MinGW-GCCNEWLINE # -pthread is only valid for GCCNEWLINE if i in ('-mms-bitfields', '-pthread'):NEWLINE continueNEWLINE if i.startswith('-LIBPATH:'):NEWLINE i = '/LIBPATH:' + i[9:]NEWLINE elif i.startswith('-L'):NEWLINE i = '/LIBPATH:' + i[2:]NEWLINE # Translate GNU-style -lfoo library name to the import libraryNEWLINE elif i.startswith('-l'):NEWLINE name = i[2:]NEWLINE if name in cls.ignore_libs:NEWLINE # With MSVC, these are provided by the C runtime which isNEWLINE # linked in by defaultNEWLINE continueNEWLINE else:NEWLINE i = name + '.lib'NEWLINE elif i.startswith('-isystem'):NEWLINE # just use /I for -isystem system include path sNEWLINE if i.startswith('-isystem='):NEWLINE i = '/I' + i[9:]NEWLINE else:NEWLINE i = '/I' + i[8:]NEWLINE elif i.startswith('-idirafter'):NEWLINE # same as -isystem, but appends the path insteadNEWLINE if i.startswith('-idirafter='):NEWLINE i = '/I' + i[11:]NEWLINE else:NEWLINE i = '/I' + i[10:]NEWLINE # -pthread in link flags is only used on LinuxNEWLINE elif i == '-pthread':NEWLINE continueNEWLINE result.append(i)NEWLINE return resultNEWLINENEWLINE @classmethodNEWLINE def native_args_to_unix(cls, args: T.List[str]) -> T.List[str]:NEWLINE result = []NEWLINE for arg in args:NEWLINE if arg.startswith(('/LIBPATH:', '-LIBPATH:')):NEWLINE result.append('-L' + arg[9:])NEWLINE elif arg.endswith(('.a', '.lib')) and not os.path.isabs(arg):NEWLINE result.append('-l' + arg)NEWLINE else:NEWLINE result.append(arg)NEWLINE return resultNEWLINENEWLINE def get_werror_args(self) -> T.List[str]:NEWLINE return ['/WX']NEWLINENEWLINE def get_include_args(self, path: str, is_system: bool) -> T.List[str]:NEWLINE if path == '':NEWLINE path = '.'NEWLINE # msvc does not have a concept of system header dirs.NEWLINE return ['-I' + path]NEWLINENEWLINE def compute_parameters_with_absolute_paths(self, parameter_list: T.List[str], build_dir: str) -> T.List[str]:NEWLINE for idx, i in enumerate(parameter_list):NEWLINE if i[:2] == '-I' or i[:2] == '/I':NEWLINE parameter_list[idx] = i[:2] + os.path.normpath(os.path.join(build_dir, i[2:]))NEWLINE elif i[:9] == '/LIBPATH:':NEWLINE parameter_list[idx] = i[:9] + os.path.normpath(os.path.join(build_dir, i[9:]))NEWLINENEWLINE return parameter_listNEWLINENEWLINE # Visual Studio is special. It ignores some arguments it does notNEWLINE # understand and you can't tell it to error out on those.NEWLINE # http://stackoverflow.com/questions/15259720/how-can-i-make-the-microsoft-c-compiler-treat-unknown-flags-as-errors-rather-tNEWLINE def has_arguments(self, args: T.List[str], env: 'Environment', code, mode: str) -> T.Tuple[bool, bool]:NEWLINE warning_text = '4044' if mode == 'link' else '9002'NEWLINE with self._build_wrapper(code, env, extra_args=args, mode=mode) as p:NEWLINE if p.returncode != 0:NEWLINE return False, p.cachedNEWLINE return not(warning_text in p.stde or warning_text in p.stdo), p.cachedNEWLINENEWLINE def get_compile_debugfile_args(self, rel_obj: str, pch: bool = False) -> T.List[str]:NEWLINE pdbarr = rel_obj.split('.')[:-1]NEWLINE pdbarr += ['pdb']NEWLINE args = ['/Fd' + '.'.join(pdbarr)]NEWLINE return argsNEWLINENEWLINE def get_instruction_set_args(self, instruction_set: str) -> T.Optional[T.List[str]]:NEWLINE if self.is_64:NEWLINE return vs64_instruction_set_args.get(instruction_set, None)NEWLINE return vs32_instruction_set_args.get(instruction_set, None)NEWLINENEWLINE def _calculate_toolset_version(self, version: int) -> T.Optional[str]:NEWLINE if version < 1310:NEWLINE return '7.0'NEWLINE elif version < 1400:NEWLINE return '7.1' # (Visual Studio 2003)NEWLINE elif version < 1500:NEWLINE return '8.0' # (Visual Studio 2005)NEWLINE elif version < 1600:NEWLINE return '9.0' # (Visual Studio 2008)NEWLINE elif version < 1700:NEWLINE return '10.0' # (Visual Studio 2010)NEWLINE elif version < 1800:NEWLINE return '11.0' # (Visual Studio 2012)NEWLINE elif version < 1900:NEWLINE return '12.0' # (Visual Studio 2013)NEWLINE elif version < 1910:NEWLINE return '14.0' # (Visual Studio 2015)NEWLINE elif version < 1920:NEWLINE return '14.1' # (Visual Studio 2017)NEWLINE elif version < 1930:NEWLINE return '14.2' # (Visual Studio 2019)NEWLINE mlog.warning('Could not find toolset for version {!r}'.format(self.version))NEWLINE return NoneNEWLINENEWLINE def get_toolset_version(self) -> T.Optional[str]:NEWLINE # See boost/config/compiler/visualc.cpp for up to date mappingNEWLINE try:NEWLINE version = int(''.join(self.version.split('.')[0:2]))NEWLINE except ValueError:NEWLINE return NoneNEWLINE return self._calculate_toolset_version(version)NEWLINENEWLINE def get_default_include_dirs(self) -> T.List[str]:NEWLINE if 'INCLUDE' not in os.environ:NEWLINE return []NEWLINE return os.environ['INCLUDE'].split(os.pathsep)NEWLINENEWLINE def get_crt_compile_args(self, crt_val: str, buildtype: str) -> T.List[str]:NEWLINE if crt_val in self.crt_args:NEWLINE return self.crt_args[crt_val]NEWLINE assert(crt_val == 'from_buildtype')NEWLINE # Match what build type flags used to do.NEWLINE if buildtype == 'plain':NEWLINE return []NEWLINE elif buildtype == 'debug':NEWLINE return self.crt_args['mdd']NEWLINE elif buildtype == 'debugoptimized':NEWLINE return self.crt_args['md']NEWLINE elif buildtype == 'release':NEWLINE return self.crt_args['md']NEWLINE elif buildtype == 'minsize':NEWLINE return self.crt_args['md']NEWLINE else:NEWLINE assert(buildtype == 'custom')NEWLINE raise mesonlib.EnvironmentException('Requested C runtime based on buildtype, but buildtype is "custom".')NEWLINENEWLINE def has_func_attribute(self, name: str, env: 'Environment') -> T.Tuple[bool, bool]:NEWLINE # MSVC doesn't have __attribute__ like Clang and GCC do, so just returnNEWLINE # false without compiling anythingNEWLINE return name in ['dllimport', 'dllexport'], FalseNEWLINENEWLINE def get_argument_syntax(self) -> str:NEWLINE return 'msvc'NEWLINENEWLINENEWLINEclass MSVCCompiler(VisualStudioLikeCompiler):NEWLINENEWLINE """Spcific to the Microsoft Compilers."""NEWLINENEWLINE def __init__(self, target: str):NEWLINE super().__init__(target)NEWLINE self.id = 'msvc'NEWLINENEWLINE def get_compile_debugfile_args(self, rel_obj: str, pch: bool = False) -> T.List[str]:NEWLINE args = super().get_compile_debugfile_args(rel_obj, pch)NEWLINE # When generating a PDB file with PCH, all compile commands writeNEWLINE # to the same PDB file. Hence, we need to serialize the PDBNEWLINE # writes using /FS since we do parallel builds. This slows down theNEWLINE # build obviously, which is why we only do this when PCH is on.NEWLINE # This was added in Visual Studio 2013 (MSVC 18.0). Before that it wasNEWLINE # always on: https://msdn.microsoft.com/en-us/library/dn502518.aspxNEWLINE if pch and mesonlib.version_compare(self.version, '>=18.0'):NEWLINE args = ['/FS'] + argsNEWLINE return argsNEWLINENEWLINE def get_instruction_set_args(self, instruction_set: str) -> T.Optional[T.List[str]]:NEWLINE if self.version.split('.')[0] == '16' and instruction_set == 'avx':NEWLINE # VS documentation says that this exists and should work, butNEWLINE # it does not. The headers do not contain AVX intrinsicsNEWLINE # and they can not be called.NEWLINE return NoneNEWLINE return super().get_instruction_set_args(instruction_set)NEWLINENEWLINE def get_buildtype_args(self, buildtype: str) -> T.List[str]:NEWLINE args = msvc_buildtype_args[buildtype]NEWLINE if mesonlib.version_compare(self.version, '<18.0'):NEWLINE args = [arg for arg in args if arg != '/Gw']NEWLINE return argsNEWLINENEWLINE def get_pch_base_name(self, header: str) -> str:NEWLINE return os.path.basename(header)NEWLINENEWLINENEWLINEclass ClangClCompiler(VisualStudioLikeCompiler):NEWLINENEWLINE """Spcific to Clang-CL."""NEWLINENEWLINE def __init__(self, target: str):NEWLINE super().__init__(target)NEWLINE self.id = 'clang-cl'NEWLINENEWLINE def has_arguments(self, args: T.List[str], env: 'Environment', code, mode: str) -> T.Tuple[bool, bool]:NEWLINE if mode != 'link':NEWLINE args = args + ['-Werror=unknown-argument']NEWLINE return super().has_arguments(args, env, code, mode)NEWLINENEWLINE def get_toolset_version(self) -> T.Optional[str]:NEWLINE # XXX: what is the right thing to do here?NEWLINE return '14.1'NEWLINENEWLINE def get_pch_base_name(self, header: str) -> str:NEWLINE return headerNEWLINENEWLINE def get_buildtype_args(self, buildtype: str) -> T.List[str]:NEWLINE return clangcl_buildtype_args[buildtype]NEWLINE
# coding=utf-8NEWLINE# *** WARNING: this file was generated by the Kulado Terraform Bridge (tfgen) Tool. ***NEWLINE# *** Do not edit by hand unless you're certain you know what you are doing! ***NEWLINENEWLINEimport jsonNEWLINEimport warningsNEWLINEimport kuladoNEWLINEimport kulado.runtimeNEWLINEfrom .. import utilities, tablesNEWLINENEWLINEclass NetworkPacketCapture(kulado.CustomResource):NEWLINE filters: kulado.Output[list]NEWLINE """NEWLINE One or more `filter` blocks as defined below. Changing this forces a new resource to be created.NEWLINE """NEWLINE maximum_bytes_per_packet: kulado.Output[float]NEWLINE """NEWLINE The number of bytes captured per packet. The remaining bytes are truncated. Defaults to `0` (Entire Packet Captured). Changing this forces a new resource to be created.NEWLINE """NEWLINE maximum_bytes_per_session: kulado.Output[float]NEWLINE """NEWLINE Maximum size of the capture in Bytes. Defaults to `1073741824` (1GB). Changing this forces a new resource to be created.NEWLINE """NEWLINE maximum_capture_duration: kulado.Output[float]NEWLINE """NEWLINE The maximum duration of the capture session in seconds. Defaults to `18000` (5 hours). Changing this forces a new resource to be created.NEWLINE """NEWLINE name: kulado.Output[str]NEWLINE """NEWLINE The name to use for this Network Packet Capture. Changing this forces a new resource to be created.NEWLINE """NEWLINE network_watcher_name: kulado.Output[str]NEWLINE """NEWLINE The name of the Network Watcher. Changing this forces a new resource to be created.NEWLINE """NEWLINE resource_group_name: kulado.Output[str]NEWLINE """NEWLINE The name of the resource group in which the Network Watcher exists. Changing this forces a new resource to be created.NEWLINE """NEWLINE storage_location: kulado.Output[dict]NEWLINE """NEWLINE A `storage_location` block as defined below. Changing this forces a new resource to be created.NEWLINE """NEWLINE target_resource_id: kulado.Output[str]NEWLINE """NEWLINE The ID of the Resource to capture packets from. Changing this forces a new resource to be created.NEWLINE """NEWLINE def __init__(__self__, resource_name, opts=None, filters=None, maximum_bytes_per_packet=None, maximum_bytes_per_session=None, maximum_capture_duration=None, name=None, network_watcher_name=None, resource_group_name=None, storage_location=None, target_resource_id=None, __name__=None, __opts__=None):NEWLINE """NEWLINE Configures Network Packet Capturing against a Virtual Machine using a Network Watcher.NEWLINE NEWLINE :param str resource_name: The name of the resource.NEWLINE :param kulado.ResourceOptions opts: Options for the resource.NEWLINE :param kulado.Input[list] filters: One or more `filter` blocks as defined below. Changing this forces a new resource to be created.NEWLINE :param kulado.Input[float] maximum_bytes_per_packet: The number of bytes captured per packet. The remaining bytes are truncated. Defaults to `0` (Entire Packet Captured). Changing this forces a new resource to be created.NEWLINE :param kulado.Input[float] maximum_bytes_per_session: Maximum size of the capture in Bytes. Defaults to `1073741824` (1GB). Changing this forces a new resource to be created.NEWLINE :param kulado.Input[float] maximum_capture_duration: The maximum duration of the capture session in seconds. Defaults to `18000` (5 hours). Changing this forces a new resource to be created.NEWLINE :param kulado.Input[str] name: The name to use for this Network Packet Capture. Changing this forces a new resource to be created.NEWLINE :param kulado.Input[str] network_watcher_name: The name of the Network Watcher. Changing this forces a new resource to be created.NEWLINE :param kulado.Input[str] resource_group_name: The name of the resource group in which the Network Watcher exists. Changing this forces a new resource to be created.NEWLINE :param kulado.Input[dict] storage_location: A `storage_location` block as defined below. Changing this forces a new resource to be created.NEWLINE :param kulado.Input[str] target_resource_id: The ID of the Resource to capture packets from. Changing this forces a new resource to be created.NEWLINENEWLINE > This content is derived from https://github.com/terraform-providers/terraform-provider-azurerm/blob/master/website/docs/r/network_packet_capture.html.markdown.NEWLINE """NEWLINE if __name__ is not None:NEWLINE warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning)NEWLINE resource_name = __name__NEWLINE if __opts__ is not None:NEWLINE warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning)NEWLINE opts = __opts__NEWLINE if not resource_name:NEWLINE raise TypeError('Missing resource name argument (for URN creation)')NEWLINE if not isinstance(resource_name, str):NEWLINE raise TypeError('Expected resource name to be a string')NEWLINE if opts and not isinstance(opts, kulado.ResourceOptions):NEWLINE raise TypeError('Expected resource options to be a ResourceOptions instance')NEWLINENEWLINE __props__ = dict()NEWLINENEWLINE __props__['filters'] = filtersNEWLINENEWLINE __props__['maximum_bytes_per_packet'] = maximum_bytes_per_packetNEWLINENEWLINE __props__['maximum_bytes_per_session'] = maximum_bytes_per_sessionNEWLINENEWLINE __props__['maximum_capture_duration'] = maximum_capture_durationNEWLINENEWLINE __props__['name'] = nameNEWLINENEWLINE if network_watcher_name is None:NEWLINE raise TypeError("Missing required property 'network_watcher_name'")NEWLINE __props__['network_watcher_name'] = network_watcher_nameNEWLINENEWLINE if resource_group_name is None:NEWLINE raise TypeError("Missing required property 'resource_group_name'")NEWLINE __props__['resource_group_name'] = resource_group_nameNEWLINENEWLINE if storage_location is None:NEWLINE raise TypeError("Missing required property 'storage_location'")NEWLINE __props__['storage_location'] = storage_locationNEWLINENEWLINE if target_resource_id is None:NEWLINE raise TypeError("Missing required property 'target_resource_id'")NEWLINE __props__['target_resource_id'] = target_resource_idNEWLINENEWLINE super(NetworkPacketCapture, __self__).__init__(NEWLINE 'azure:network/networkPacketCapture:NetworkPacketCapture',NEWLINE resource_name,NEWLINE __props__,NEWLINE opts)NEWLINENEWLINENEWLINE def translate_output_property(self, prop):NEWLINE return tables._CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or propNEWLINENEWLINE def translate_input_property(self, prop):NEWLINE return tables._SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or propNEWLINENEWLINE
# Copyright 2021 University College London. All Rights Reserved.NEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINE# ==============================================================================NEWLINE"""Keras objects registry.NEWLINENEWLINEKeras Declarative maintains its own object registry. There are a few differencesNEWLINEwith respect to the Keras registry:NEWLINENEWLINE * It includes non-serializable objects such as callbacks.NEWLINE * It does not prepend package prefixes to object names.NEWLINE * It supports objects of type `ObjectConfig` as identifiers.NEWLINE"""NEWLINENEWLINEimport inspectNEWLINENEWLINEimport tensorflow as tfNEWLINENEWLINEfrom keras_declarative import config as config_moduleNEWLINEfrom keras_declarative import hyperparamsNEWLINEfrom keras_declarative import predicatesNEWLINEfrom keras_declarative import utilNEWLINENEWLINENEWLINEdef get_list(get_fn):NEWLINE """Returns a function that retrieves a list of objects.NEWLINENEWLINE Args:NEWLINE get_fn: The get function to be used for individual identifiers.NEWLINENEWLINE Returns:NEWLINE A function that retrieves an object or a list of objects.NEWLINE """NEWLINE def get_list_fn(identifier):NEWLINE """Retrieves a list of objects.NEWLINENEWLINE Args:NEWLINE identifier: An object identifier. Must be a string, a dictionary, anNEWLINE `ObjectConfig` or `None`.NEWLINENEWLINE Returns:NEWLINE A list of Keras objects as class instances.NEWLINE """NEWLINE if isinstance(identifier, list):NEWLINE return [get_fn(ident) for ident in identifier]NEWLINE return get_fn(identifier)NEWLINE return get_list_fnNEWLINENEWLINENEWLINEdef get_nest(get_fn):NEWLINE """Returns a function that retrieves a nested structure of objects.NEWLINENEWLINE Nests include lists and dictionaries.NEWLINENEWLINE Args:NEWLINE get_fn: The get function to be used for individual identifiers.NEWLINENEWLINE Returns:NEWLINE A function that retrieves an object or a list of objects.NEWLINE """NEWLINE def get_nest_fn(identifier):NEWLINE """Retrieves a nested structure of objects.NEWLINENEWLINE Args:NEWLINE identifier: An object identifier. Must be a string, a dictionary, anNEWLINE `ObjectConfig` or `None`.NEWLINENEWLINE Returns:NEWLINE A list of Keras objects as class instances.NEWLINE """NEWLINE if isinstance(identifier, hyperparams.ParamsDict):NEWLINE identifier = identifier.as_dict()NEWLINE def _parse_nest(nest):NEWLINE if is_object_config(nest):NEWLINE return get_fn(nest)NEWLINE if isinstance(nest, dict):NEWLINE return {key: _parse_nest(value) for key, value in nest.items()}NEWLINE if isinstance(nest, list):NEWLINE return [_parse_nest(value) for value in nest]NEWLINE return get_fn(nest)NEWLINE return _parse_nest(identifier)NEWLINE return get_nest_fnNEWLINENEWLINENEWLINEdef get_callback(identifier):NEWLINE """Retrieve a Keras callback as a class instance.NEWLINENEWLINE Args:NEWLINE identifier: A callback identifier. Must be a string, a dictionary, anNEWLINE `ObjectConfig` or `None`.NEWLINENEWLINE Returns:NEWLINE A Keras callback as a class instance.NEWLINE """NEWLINE return _get(identifier, _CALLBACK_OBJECTS, 'callback')NEWLINENEWLINENEWLINEdef get_layer(identifier):NEWLINE """Retrieve a Keras layer as a class instance.NEWLINENEWLINE Args:NEWLINE identifier: A layer identifier. Must be a string, a dictionary, anNEWLINE `ObjectConfig` or `None`.NEWLINENEWLINE Returns:NEWLINE A Keras layer as a class instance.NEWLINE """NEWLINE return _get(identifier, _LAYER_OBJECTS, 'layer')NEWLINENEWLINENEWLINEdef get_loss(identifier):NEWLINE """Retrieve a Keras loss as a class instance.NEWLINENEWLINE Args:NEWLINE identifier: A loss identifier. Must be a string, a dictionary, anNEWLINE `ObjectConfig` or `None`.NEWLINENEWLINE Returns:NEWLINE A Keras loss as a class instance.NEWLINE """NEWLINE return _get(identifier, _LOSS_OBJECTS, 'loss')NEWLINENEWLINENEWLINEdef get_metric(identifier):NEWLINE """Retrieve a Keras metric as a class instance.NEWLINENEWLINE Args:NEWLINE identifier: A metric identifier. Must be a string, a dictionary, anNEWLINE `ObjectConfig` or `None`.NEWLINENEWLINE Returns:NEWLINE A Keras metric as a class instance.NEWLINE """NEWLINE return _get(identifier, _METRIC_OBJECTS, 'metric')NEWLINENEWLINENEWLINEdef get_optimizer(identifier):NEWLINE """Retrieve a Keras optimizer as a class instance.NEWLINENEWLINE Args:NEWLINE identifier: An optimizer identifier. Must be a string, a dictionary, anNEWLINE `ObjectConfig` or `None`.NEWLINENEWLINE Returns:NEWLINE A Keras optimizer as a class instance.NEWLINE """NEWLINE return _get(identifier, _OPTIMIZER_OBJECTS, 'optimizer')NEWLINENEWLINENEWLINEdef get_predicate(identifier):NEWLINE """Retrieve a predicate as a class instance.NEWLINENEWLINE Args:NEWLINE identifier: A predicate identifier. Must be a string, a dictionary, anNEWLINE `ObjectConfig` or `None`.NEWLINENEWLINE Returns:NEWLINE A predicate as a class instance.NEWLINE """NEWLINE return _get(identifier, _PREDICATE_OBJECTS, 'predicate')NEWLINENEWLINENEWLINEdef get_strategy(identifier):NEWLINE """Retrieve a TF distribution strategy as a class instance.NEWLINENEWLINE Args:NEWLINE identifier: A strategy identifier. Must be a string, a dictionary, anNEWLINE `ObjectConfig` or `None`.NEWLINENEWLINE Returns:NEWLINE A TF distribution strategy as a class instance.NEWLINE """NEWLINE return _get(identifier, _STRATEGY_OBJECTS, 'strategy')NEWLINENEWLINENEWLINEdef _get(identifier, objects, objtype):NEWLINE """Retrieve an object as a class instance.NEWLINENEWLINE Args:NEWLINE identifier: An object identifier. Must be a string, a dictionary, anNEWLINE `ObjectConfig` or `None`.NEWLINE objects: A dictionary with the registered objects.NEWLINE objtype: A string with the type of object being retrieved. This is only usedNEWLINE to format error messages.NEWLINENEWLINE Returns:NEWLINE An instance of the object identified by `identifier`.NEWLINENEWLINE Raises:NEWLINE ValueError: If the identifier is invalid.NEWLINE RuntimeError: If an error occurs while initializing the object.NEWLINE """NEWLINE # If object is an external object, don't try to resolve it.NEWLINE if isinstance(identifier, util.ExternalObject):NEWLINE return identifierNEWLINENEWLINE if isinstance(identifier, config_module.ObjectConfig):NEWLINE identifier = identifier.as_dict()NEWLINENEWLINE if not identifier: # Might be `None` or an empty dict.NEWLINE return NoneNEWLINENEWLINE class_name, config = class_and_config_for_serialized_object(identifier)NEWLINENEWLINE if class_name not in objects:NEWLINE raise ValueError(f"No known {objtype} with name: {class_name}")NEWLINE obj = objects[class_name]NEWLINENEWLINE try:NEWLINE return obj(**config)NEWLINE except Exception as e:NEWLINE raise RuntimeError(NEWLINE f"An error occurred while initializing {class_name} with parameters: "NEWLINE f"{config}") from eNEWLINENEWLINENEWLINEdef class_and_config_for_serialized_object(identifier):NEWLINE """Returns the class name and config for a serialized object.NEWLINENEWLINE Args:NEWLINE identifier: An object identifier. Must be a string, a dictionary or anNEWLINE `ObjectConfig`.NEWLINENEWLINE Returns:NEWLINE A tuple containing the class name and its keyword arguments.NEWLINENEWLINE Raises:NEWLINE ValueError: If the identifier is invalid.NEWLINE """NEWLINE if isinstance(identifier, config_module.ObjectConfig):NEWLINE identifier = identifier.as_dict()NEWLINENEWLINE if isinstance(identifier, str):NEWLINE class_name, config = identifier, {}NEWLINENEWLINE elif isinstance(identifier, dict):NEWLINE if 'class_name' not in identifier or 'config' not in identifier:NEWLINE raise ValueError(NEWLINE f"Invalid identifier: {identifier}. Value is not a valid "NEWLINE f"configuration dictionary.")NEWLINE class_name = identifier['class_name']NEWLINE config = identifier['config']NEWLINENEWLINE else:NEWLINE raise ValueError(NEWLINE f"Invalid identifier: {identifier}. Value must be a string, a "NEWLINE f"dictionary or an `ObjectConfig`.")NEWLINENEWLINE return class_name, configNEWLINENEWLINENEWLINEdef is_object_config(config):NEWLINE """Check if input is a valid object configuration dict.NEWLINENEWLINE Args:NEWLINE config: The object to check.NEWLINENEWLINE Returns:NEWLINE True if input is a valid object configuration dict, false otherwise.NEWLINE """NEWLINE # A str or None are valid object configs.NEWLINE if isinstance(config, (str, type(None))):NEWLINE return TrueNEWLINENEWLINE # Otherwise, must be a dict or an object of type `ParamsDict`.NEWLINE if not isinstance(config, (dict, hyperparams.ParamsDict)):NEWLINE return FalseNEWLINENEWLINE # If a dict, must have two keys: class_name and config.NEWLINE d = config.as_dict() if isinstance(config, hyperparams.ParamsDict) else configNEWLINE if set(d.keys()) != {'class_name', 'config'}:NEWLINE return FalseNEWLINENEWLINE return TrueNEWLINENEWLINENEWLINEdef _find_objects(modules, objtype):NEWLINE """Finds objects of a certain type on the given modules.NEWLINENEWLINE Args:NEWLINE modules: A list of modules to search for objects.NEWLINE objtype: The type of objects to be searched for.NEWLINENEWLINE Returns:NEWLINE A dictionary containing the found objects.NEWLINE """NEWLINE objects = {}NEWLINE for module in modules:NEWLINE members = inspect.getmembers(module)NEWLINE for name, value in members:NEWLINE if inspect.isclass(value) and issubclass(value, objtype):NEWLINE objects[name] = valueNEWLINE return objectsNEWLINENEWLINENEWLINE_CALLBACK_MODULES = [NEWLINE tf.keras.callbacksNEWLINE]NEWLINENEWLINE_LAYER_MODULES = [NEWLINE tf.keras.layersNEWLINE]NEWLINENEWLINE_LOSS_MODULES = [NEWLINE tf.keras.losses,NEWLINE]NEWLINENEWLINE_METRIC_MODULES = [NEWLINE tf.keras.metrics,NEWLINE]NEWLINENEWLINE_OPTIMIZER_MODULES = [NEWLINE tf.keras.optimizersNEWLINE]NEWLINENEWLINE_PREDICATE_MODULES = [NEWLINE predicatesNEWLINE]NEWLINENEWLINE_STRATEGY_MODULES = [NEWLINE tf.distributeNEWLINE]NEWLINENEWLINENEWLINE# Try to discover objects from TensorFlow MRI, if it is installed.NEWLINEtry:NEWLINE import tensorflow_mri as tfmriNEWLINE _CALLBACK_MODULES.append(tfmri.callbacks)NEWLINE _LAYER_MODULES.extend([tfmri.layers])NEWLINE _LOSS_MODULES.append(tfmri.losses)NEWLINE _METRIC_MODULES.append(tfmri.metrics)NEWLINEexcept ImportError:NEWLINE passNEWLINENEWLINENEWLINE# Try to discover objects from TF Playground, if it is installed.NEWLINEtry:NEWLINE import tf_playground as tfpgNEWLINE _CALLBACK_MODULES.append(tfpg.callbacks)NEWLINE _LAYER_MODULES.append(tfpg.layers)NEWLINE _LOSS_MODULES.append(tfpg.losses)NEWLINE _METRIC_MODULES.append(tfpg.metrics)NEWLINEexcept ImportError:NEWLINE passNEWLINENEWLINENEWLINE_CALLBACK_OBJECTS = NoneNEWLINE_LAYER_OBJECTS = NoneNEWLINE_LOSS_OBJECTS = NoneNEWLINE_METRIC_OBJECTS = NoneNEWLINE_OPTIMIZER_OBJECTS = NoneNEWLINE_PREDICATE_OBJECTS = NoneNEWLINE_STRATEGY_OBJECTS = NoneNEWLINENEWLINENEWLINEdef discover_objects(custom_modules=None):NEWLINE """Discover Keras objects.NEWLINENEWLINE By default, this function searches for Keras objects in core TensorFlow andNEWLINE TensorFlow MRI (if installed).NEWLINENEWLINE Args:NEWLINE custom_modules: A list of custom modules to be searched for Keras objects.NEWLINE """NEWLINE global _CALLBACK_OBJECTSNEWLINE global _LAYER_OBJECTSNEWLINE global _LOSS_OBJECTSNEWLINE global _METRIC_OBJECTSNEWLINE global _OPTIMIZER_OBJECTSNEWLINE global _PREDICATE_OBJECTSNEWLINE global _STRATEGY_OBJECTSNEWLINENEWLINE custom_modules = custom_modules or []NEWLINENEWLINE _CALLBACK_OBJECTS = _find_objects(_CALLBACK_MODULES + custom_modules,NEWLINE tf.keras.callbacks.Callback)NEWLINENEWLINE _LAYER_OBJECTS = _find_objects(_LAYER_MODULES + custom_modules,NEWLINE tf.keras.layers.Layer)NEWLINENEWLINE _LOSS_OBJECTS = _find_objects(_LOSS_MODULES + custom_modules,NEWLINE tf.keras.losses.Loss)NEWLINENEWLINE _METRIC_OBJECTS = _find_objects(_METRIC_MODULES + custom_modules,NEWLINE tf.keras.metrics.Metric)NEWLINENEWLINE _OPTIMIZER_OBJECTS = _find_objects(_OPTIMIZER_MODULES + custom_modules,NEWLINE tf.keras.optimizers.Optimizer)NEWLINENEWLINE _PREDICATE_OBJECTS = _find_objects(_PREDICATE_MODULES, predicates.Predicate)NEWLINENEWLINE _STRATEGY_OBJECTS = _find_objects(_STRATEGY_MODULES, tf.distribute.Strategy)NEWLINENEWLINEdiscover_objects()NEWLINE
from django.shortcuts import renderNEWLINEfrom property.views import hot_propertiesNEWLINEfrom property.models import PropertyNEWLINENEWLINENEWLINEdef index(request, *args, **kwargs):NEWLINE context = {NEWLINE 'carousel_property_list': hot_properties(4),NEWLINE 'hot_property_list': hot_properties(4),NEWLINE 'recommended_property_list': hot_properties(4)NEWLINE }NEWLINE return render(request, 'index.html', context)NEWLINENEWLINENEWLINEdef about(request, *args, **kwargs):NEWLINE return render(request, 'about.html')NEWLINENEWLINENEWLINEdef blog(request, *args, **kwargs):NEWLINE return render(request, 'blog.html')NEWLINE
# pylint: disable=missing-docstringNEWLINEimport osNEWLINENEWLINEfrom resolwe.test import ProcessTestCase, tag_process, with_docker_executorNEWLINENEWLINENEWLINEclass ArchiverProcessTestCase(ProcessTestCase):NEWLINENEWLINE def setUp(self):NEWLINE super().setUp()NEWLINE self.files_path = os.path.abspath(os.path.join(os.path.dirname(__file__), 'files'))NEWLINENEWLINE @with_docker_executorNEWLINE @tag_process('archiver')NEWLINE def test_archiver(self):NEWLINE with self.preparation_stage():NEWLINE binary = self.run_process('upload-file', {'src': 'file binary'})NEWLINE image = self.run_process('upload-image-file', {'src': 'file image.png'})NEWLINE tab = self.run_process('upload-tab-file', {'src': 'file tab.txt'})NEWLINENEWLINE archive = self.run_process('archiver', {NEWLINE 'data': [binary.id, image.id, tab.id],NEWLINE 'fields': ['file']})NEWLINENEWLINE self.assertFileExists(archive, 'archive')NEWLINE
# Copyright 2017 Battelle Energy Alliance, LLCNEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINE"""NEWLINECreated on Feb. 16 2018NEWLINENEWLINE@author: wangcNEWLINE"""NEWLINE#for future compatibility with Python 3--------------------------------------------------------------NEWLINEfrom __future__ import division, print_function, unicode_literals, absolute_importNEWLINEimport warningsNEWLINEwarnings.simplefilter('default',DeprecationWarning)NEWLINE#End compatibility block for Python 3----------------------------------------------------------------NEWLINENEWLINE#External Modules------------------------------------------------------------------------------------NEWLINEimport mathNEWLINEimport scipyNEWLINEimport numpy as npNEWLINEimport astNEWLINEimport scipy.spatial.distance as spatialDistanceNEWLINE#External Modules End--------------------------------------------------------------------------------NEWLINENEWLINE#Internal Modules------------------------------------------------------------------------------------NEWLINEfrom .Metric import MetricNEWLINEfrom utils import utils, InputDataNEWLINE#Internal Modules End--------------------------------------------------------------------------------NEWLINENEWLINEclass ScipyMetric(Metric):NEWLINE """NEWLINE ScipyMetric metrics which can be employed for both pointSets and historySetsNEWLINE """NEWLINE availMetrics = {}NEWLINE # Distance functions between two numeric vectorsNEWLINE availMetrics['paired_distance'] = {}NEWLINE availMetrics['paired_distance']['braycurtis'] = spatialDistance.braycurtisNEWLINE availMetrics['paired_distance']['canberra'] = spatialDistance.canberraNEWLINE availMetrics['paired_distance']['correlation'] = spatialDistance.correlationNEWLINE availMetrics['paired_distance']['minkowski'] = spatialDistance.minkowskiNEWLINE # Distance functions between two boolean vectorsNEWLINE availMetrics['boolean'] = {}NEWLINE availMetrics['boolean']['rogerstanimoto'] = spatialDistance.rogerstanimotoNEWLINE availMetrics['boolean']['dice'] = spatialDistance.diceNEWLINE availMetrics['boolean']['hamming'] = spatialDistance.hammingNEWLINE availMetrics['boolean']['jaccard'] = spatialDistance.jaccardNEWLINE availMetrics['boolean']['kulsinski'] = spatialDistance.kulsinskiNEWLINE availMetrics['boolean']['russellrao'] = spatialDistance.russellraoNEWLINE availMetrics['boolean']['sokalmichener'] = spatialDistance.sokalmichenerNEWLINE availMetrics['boolean']['sokalsneath'] = spatialDistance.sokalsneathNEWLINE availMetrics['boolean']['yule'] = spatialDistance.yuleNEWLINENEWLINE @classmethodNEWLINE def getInputSpecification(cls):NEWLINE """NEWLINE Method to get a reference to a class that specifies the input data forNEWLINE class cls.NEWLINE @ In, cls, the class for which we are retrieving the specificationNEWLINE @ Out, inputSpecification, InputData.ParameterInput, class to use forNEWLINE specifying input of cls.NEWLINE """NEWLINE inputSpecification = super(ScipyMetric, cls).getInputSpecification()NEWLINE inputSpecification.addSub(InputData.parameterInputFactory("metricType",contentType=InputData.StringType),quantity=InputData.Quantity.one)NEWLINE inputSpecification.addSub(InputData.parameterInputFactory("w",contentType=InputData.FloatListType),quantity=InputData.Quantity.zero_to_one)NEWLINE inputSpecification.addSub(InputData.parameterInputFactory("p",contentType=InputData.FloatType),quantity=InputData.Quantity.zero_to_one)NEWLINENEWLINE return inputSpecificationNEWLINENEWLINE def __init__(self):NEWLINE """NEWLINE ConstructorNEWLINE @ In, NoneNEWLINE @ Out, NoneNEWLINE """NEWLINE Metric.__init__(self)NEWLINE # The type of given metric, None or List of two elements, first element should be in availMetrics.keys()NEWLINE # and sencond element should be in availMetrics.values()[firstElement].keys()NEWLINE self.metricType = NoneNEWLINENEWLINE def _localReadMoreXML(self,xmlNode):NEWLINE """NEWLINE Method that reads the portion of the xml input that belongs to this specialized classNEWLINE and initialize internal parametersNEWLINE @ In, xmlNode, xml.etree.Element, Xml element nodeNEWLINE @ Out, NoneNEWLINE """NEWLINE self.distParams = {}NEWLINE paramInput = ScipyMetric.getInputSpecification()()NEWLINE paramInput.parseNode(xmlNode)NEWLINE for child in paramInput.subparts:NEWLINE if child.getName() == "metricType":NEWLINE self.metricType = list(elem.strip() for elem in child.value.split('|'))NEWLINE if len(self.metricType) != 2:NEWLINE self.raiseAnError(IOError, "Metric type: '", child.value, "' is not correct, please check the user manual for the correct metric type!")NEWLINE else:NEWLINE self.distParams[child.getName()] = child.valueNEWLINENEWLINE if self.metricType[0] not in self.__class__.availMetrics.keys() or self.metricType[1] not in self.__class__.availMetrics[self.metricType[0]].keys():NEWLINE self.raiseAnError(IOError, "Metric '", self.name, "' with metricType '", self.metricType[0], "|", self.metricType[1], "' is not valid!")NEWLINENEWLINE def __evaluateLocal__(self, x, y, weights = None, axis = 0, **kwargs):NEWLINE """NEWLINE This method computes difference between two points x and y based on given metricNEWLINE @ In, x, 1-D numpy.ndarray, array containing data of x.NEWLINE @ In, y, 1-D numpy.ndarray, array containing data of y.NEWLINE @ In, weights, array_like (numpy.array or list), optional, weights associated the metric methodNEWLINE @ In, axis, integer, optional, default is 0, not used in this metricNEWLINE @ In, kwargs, dict, dictionary of parameters characteristic of each metricNEWLINE @ Out, value, float, metric resultNEWLINE """NEWLINE if isinstance(x,np.ndarray) and isinstance(y,np.ndarray):NEWLINE assert(x.shape == y.shape, "Input data x, y should have the same shape!")NEWLINE # TODO: weights are supported in scipy.spatial.distance for many distance metrics in v1.0.0NEWLINE # when we switch to scipy 1.0.0, we can enable weights in our metrics calculationsNEWLINE sv = str(scipy.__version__).split('.')NEWLINE if int(sv[0]) > 0:NEWLINE if weights is not None and 'w' not in self.distParams.keys():NEWLINE self.distParams['w'] = weightsNEWLINE # FIXME: In Scipy version 1.1.0, the function scipy.spatial.distance.canberra andNEWLINE # scipy.spatial.distance.sokalmichener will accept the weights, and the calculated results fromNEWLINE # these functions will affected by the normalization of the weights. The following is disabled forNEWLINE # this purpose --- wangc July 17, 2018NEWLINE # For future development, please pay attention to canberra, minkowski, and sokalmichener metricsNEWLINE #if 'w' in self.distParams.keys():NEWLINE # Normalized weights, since methods exist in Scipy are using unnormalized weightsNEWLINE #self.distParams['w'] = np.asarray(self.distParams['w'])/np.sum(self.distParams['w'])NEWLINE else:NEWLINE if 'w' in self.distParams.keys():NEWLINE self.raiseAWarning("Weights will not be used, since weights provided with key word 'w' is not supported for your current version of scipy!")NEWLINE self.distParams.pop('w')NEWLINE dictTemp = utils.mergeDictionaries(kwargs, self.distParams)NEWLINE try:NEWLINE value = self.__class__.availMetrics[self.metricType[0]][self.metricType[1]](x, y, **dictTemp)NEWLINE except TypeError as e:NEWLINE self.raiseAWarning('There are some unexpected keyword arguments found in Metric with type', self.metricType[1])NEWLINE self.raiseAnError(TypeError, 'Input parameters error: \n', str(e), '\n')NEWLINE else:NEWLINE self.raiseAnError(IOError, "Input data type is not correct!")NEWLINENEWLINE return valueNEWLINE
# Copyright (c) Chris Choy (chrischoy@ai.stanford.edu) and Wei Dong (weidong@andrew.cmu.edu)NEWLINE#NEWLINE# Please cite the following papers if you use any part of the code.NEWLINE# - Christopher Choy, Wei Dong, Vladlen Koltun, Deep Global Registration, CVPR 2020NEWLINE# - Christopher Choy, Jaesik Park, Vladlen Koltun, Fully Convolutional Geometric Features, ICCV 2019NEWLINE# - Christopher Choy, JunYoung Gwak, Silvio Savarese, 4D Spatio-Temporal ConvNets: Minkowski Convolutional Neural Networks, CVPR 2019NEWLINE# Run with python -m scripts.test_3dmatch_refactorNEWLINEimport osNEWLINEimport sysNEWLINEimport mathNEWLINEimport loggingNEWLINEimport open3d as o3dNEWLINEimport numpy as npNEWLINEimport timeNEWLINEimport torchNEWLINEimport copyNEWLINENEWLINEsys.path.append('.')NEWLINEimport MinkowskiEngine as MENEWLINEfrom config import get_configNEWLINEfrom model import load_modelNEWLINENEWLINEfrom dataloader.data_loaders import ThreeDMatchTrajectoryDatasetNEWLINEfrom core.knn import find_knn_gpuNEWLINEfrom core.deep_global_registration import DeepGlobalRegistrationNEWLINENEWLINEfrom util.timer import TimerNEWLINEfrom util.pointcloud import make_open3d_point_cloudNEWLINENEWLINEo3d.utility.set_verbosity_level(o3d.utility.VerbosityLevel.Warning)NEWLINEch = logging.StreamHandler(sys.stdout)NEWLINElogging.getLogger().setLevel(logging.INFO)NEWLINElogging.basicConfig(format='%(asctime)s %(message)s',NEWLINE datefmt='%m/%d %H:%M:%S',NEWLINE handlers=[ch])NEWLINENEWLINE# CriteriaNEWLINEdef rte_rre(T_pred, T_gt, rte_thresh, rre_thresh, eps=1e-16):NEWLINE if T_pred is None:NEWLINE return np.array([0, np.inf, np.inf])NEWLINENEWLINE rte = np.linalg.norm(T_pred[:3, 3] - T_gt[:3, 3])NEWLINE rre = np.arccos(NEWLINE np.clip((np.trace(T_pred[:3, :3].T @ T_gt[:3, :3]) - 1) / 2, -1 + eps,NEWLINE 1 - eps)) * 180 / math.piNEWLINE return np.array([rte < rte_thresh and rre < rre_thresh, rte, rre])NEWLINENEWLINENEWLINEdef analyze_stats(stats, mask, method_names):NEWLINE mask = (mask > 0).squeeze(1)NEWLINE stats = stats[:, mask, :]NEWLINENEWLINE print('Total result mean')NEWLINE for i, method_name in enumerate(method_names):NEWLINE print(method_name)NEWLINE print("Reg Recall; Mean TE; Mean RE; Mean Time; --; Mean Precision; Mean Recall")NEWLINE print(stats[i].mean(0))NEWLINENEWLINE print('Total successful result mean')NEWLINE for i, method_name in enumerate(method_names):NEWLINE sel = stats[i][:, 0] > 0NEWLINE sel_stats = stats[i][sel]NEWLINE print(method_name)NEWLINE print("Success Rate; Mean TE; Mean RE; Mean Time; --; Mean Precision; Mean Recall")NEWLINE print(sel_stats.mean(0))NEWLINENEWLINENEWLINEdef create_pcd(xyz, color):NEWLINE # n x 3NEWLINE n = xyz.shape[0]NEWLINE pcd = o3d.geometry.PointCloud()NEWLINE pcd.points = o3d.utility.Vector3dVector(xyz)NEWLINE pcd.colors = o3d.utility.Vector3dVector(np.tile(color, (n, 1)))NEWLINE pcd.estimate_normals(NEWLINE search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.1, max_nn=30))NEWLINE return pcdNEWLINENEWLINENEWLINEdef draw_geometries_flip(pcds):NEWLINE pcds_transform = []NEWLINE flip_transform = [[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]]NEWLINE for pcd in pcds:NEWLINE pcd_temp = copy.deepcopy(pcd)NEWLINE pcd_temp.transform(flip_transform)NEWLINE pcds_transform.append(pcd_temp)NEWLINE o3d.visualization.draw_geometries(pcds_transform)NEWLINENEWLINENEWLINEdef evaluate(methods, method_names, data_loader, config, debug=False):NEWLINENEWLINE tot_num_data = len(data_loader.dataset)NEWLINE data_loader_iter = iter(data_loader)NEWLINENEWLINE # Accumulate success, rre, rte, time, sidNEWLINE mask = np.zeros((tot_num_data, 1)).astype(int)NEWLINE stats = np.zeros((len(methods), tot_num_data, 7))NEWLINENEWLINE dataset = data_loader.datasetNEWLINE subset_names = open(dataset.DATA_FILES[dataset.phase]).read().split()NEWLINENEWLINE total_safe_guard = 0NEWLINE for batch_idx in range(tot_num_data):NEWLINE batch = data_loader_iter.next()NEWLINENEWLINE # Skip too sparse point cloudsNEWLINE sname, xyz0, xyz1, trans = batch[0]NEWLINENEWLINE sid = subset_names.index(sname)NEWLINE T_gt = np.linalg.inv(trans)NEWLINENEWLINE NEWLINE for i, method in enumerate(methods):NEWLINE start = time.time()NEWLINE T, precision, recall, outlier_rejection_time, safe_guard = method.register(xyz0, xyz1, T_gt=T_gt)NEWLINE end = time.time()NEWLINE total_safe_guard += safe_guardNEWLINENEWLINE # VisualizeNEWLINE if debug:NEWLINE print(method_names[i])NEWLINE pcd0 = create_pcd(xyz0, np.array([1, 0.706, 0]))NEWLINE pcd1 = create_pcd(xyz1, np.array([0, 0.651, 0.929]))NEWLINENEWLINE pcd0.transform(T)NEWLINE draw_geometries_flip([pcd0, pcd1])NEWLINE pcd0.transform(np.linalg.inv(T))NEWLINENEWLINE stats[i, batch_idx, :3] = rte_rre(T, T_gt, config.success_rte_thresh,NEWLINE config.success_rre_thresh)NEWLINE stats[i, batch_idx, 3] = outlier_rejection_time # not including feature extraction time.NEWLINE stats[i, batch_idx, 4] = safe_guardNEWLINE stats[i, batch_idx, 5] = precisionNEWLINE stats[i, batch_idx, 6] = recallNEWLINE mask[batch_idx] = 1NEWLINE if stats[i, batch_idx, 0] == 0:NEWLINE print(f"{method_names[i]}: failed")NEWLINENEWLINE if batch_idx % 10 == 9:NEWLINE print('Summary {} / {}'.format(batch_idx, tot_num_data))NEWLINE print(f"Safe guard number: {total_safe_guard} / {batch_idx}")NEWLINE analyze_stats(stats, mask, method_names)NEWLINENEWLINE NEWLINE # Save resultsNEWLINE print(f"Total safe guard ratio: {total_safe_guard} / {tot_num_data}")NEWLINE filename = f'3dmatch-stats_{method.__class__.__name__}' + '_noicp_fpfh'NEWLINE if os.path.isdir(config.out_dir):NEWLINE out_file = os.path.join(config.out_dir, filename)NEWLINE else:NEWLINE out_file = filename # save it on the current directoryNEWLINE print(f'Saving the stats to {out_file}')NEWLINE np.savez(out_file, stats=stats, names=method_names)NEWLINE analyze_stats(stats, mask, method_names)NEWLINENEWLINE # Analysis per sceneNEWLINE for i, method in enumerate(methods):NEWLINE print(f'Scene-wise mean {method}')NEWLINE scene_vals = np.zeros((len(subset_names), 3))NEWLINE for sid, sname in enumerate(subset_names):NEWLINE curr_scene = stats[i, :, 4] == sidNEWLINE scene_vals[sid] = (stats[i, curr_scene, :3]).mean(0)NEWLINENEWLINE print('All scenes')NEWLINE print(scene_vals)NEWLINE print('Scene average')NEWLINE print(scene_vals.mean(0))NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE config = get_config()NEWLINE print(config)NEWLINENEWLINE dgr = DeepGlobalRegistration(config)NEWLINENEWLINE methods = [dgr]NEWLINE method_names = ['DGR']NEWLINENEWLINE dset = ThreeDMatchTrajectoryDataset(phase='test',NEWLINE transform=None,NEWLINE random_scale=False,NEWLINE random_rotation=False,NEWLINE config=config)NEWLINENEWLINE data_loader = torch.utils.data.DataLoader(dset,NEWLINE batch_size=1,NEWLINE shuffle=False,NEWLINE num_workers=10,NEWLINE collate_fn=lambda x: x,NEWLINE pin_memory=False,NEWLINE drop_last=True)NEWLINENEWLINE evaluate(methods, method_names, data_loader, config, debug=False)NEWLINE
_base_ = [NEWLINE '../_base_/models/cascade_mask_rcnn_swin_fpn.py',NEWLINE '../_base_/datasets/coco_instance.py',NEWLINE '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py'NEWLINE]NEWLINENEWLINEmodel = dict(NEWLINE backbone=dict(NEWLINE embed_dim=96,NEWLINE depths=[2, 2, 18, 2],NEWLINE num_heads=[3, 6, 12, 24],NEWLINE window_size=7,NEWLINE ape=False,NEWLINE drop_path_rate=0.2,NEWLINE patch_norm=True,NEWLINE use_checkpoint=FalseNEWLINE ),NEWLINE neck=dict(in_channels=[96, 192, 384, 768]),NEWLINE roi_head=dict(NEWLINE bbox_head=[NEWLINE dict(NEWLINE type='ConvFCBBoxHead',NEWLINE num_shared_convs=4,NEWLINE num_shared_fcs=1,NEWLINE in_channels=256,NEWLINE conv_out_channels=256,NEWLINE fc_out_channels=1024,NEWLINE roi_feat_size=7,NEWLINE num_classes=4,NEWLINE bbox_coder=dict(NEWLINE type='DeltaXYWHBBoxCoder',NEWLINE target_means=[0., 0., 0., 0.],NEWLINE target_stds=[0.1, 0.1, 0.2, 0.2]),NEWLINE reg_class_agnostic=False,NEWLINE reg_decoded_bbox=True,NEWLINE norm_cfg=dict(type='SyncBN', requires_grad=True),NEWLINE loss_cls=dict(NEWLINE type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0),NEWLINE loss_bbox=dict(type='GIoULoss', loss_weight=10.0)),NEWLINE dict(NEWLINE type='ConvFCBBoxHead',NEWLINE num_shared_convs=4,NEWLINE num_shared_fcs=1,NEWLINE in_channels=256,NEWLINE conv_out_channels=256,NEWLINE fc_out_channels=1024,NEWLINE roi_feat_size=7,NEWLINE num_classes=4,NEWLINE bbox_coder=dict(NEWLINE type='DeltaXYWHBBoxCoder',NEWLINE target_means=[0., 0., 0., 0.],NEWLINE target_stds=[0.05, 0.05, 0.1, 0.1]),NEWLINE reg_class_agnostic=False,NEWLINE reg_decoded_bbox=True,NEWLINE norm_cfg=dict(type='SyncBN', requires_grad=True),NEWLINE loss_cls=dict(NEWLINE type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0),NEWLINE loss_bbox=dict(type='GIoULoss', loss_weight=10.0)),NEWLINE dict(NEWLINE type='ConvFCBBoxHead',NEWLINE num_shared_convs=4,NEWLINE num_shared_fcs=1,NEWLINE in_channels=256,NEWLINE conv_out_channels=256,NEWLINE fc_out_channels=1024,NEWLINE roi_feat_size=7,NEWLINE num_classes=4,NEWLINE bbox_coder=dict(NEWLINE type='DeltaXYWHBBoxCoder',NEWLINE target_means=[0., 0., 0., 0.],NEWLINE target_stds=[0.033, 0.033, 0.067, 0.067]),NEWLINE reg_class_agnostic=False,NEWLINE reg_decoded_bbox=True,NEWLINE norm_cfg=dict(type='SyncBN', requires_grad=True),NEWLINE loss_cls=dict(NEWLINE type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0),NEWLINE loss_bbox=dict(type='GIoULoss', loss_weight=10.0))NEWLINE ]))NEWLINENEWLINEimg_norm_cfg = dict(NEWLINE mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)NEWLINENEWLINE# augmentation strategy originates from DETR / Sparse RCNNNEWLINEtrain_pipeline = [NEWLINE dict(type='LoadImageFromFile'),NEWLINE dict(type='LoadAnnotations', with_bbox=True),NEWLINE dict(type='RandomFlip', flip_ratio=0.5),NEWLINE dict(type='AutoAugment',NEWLINE policies=[NEWLINE [NEWLINE dict(type='Resize',NEWLINE img_scale=[(320, 320), (384, 384), (448, 448),NEWLINE (512, 512), (576, 576)],NEWLINE multiscale_mode='value',NEWLINE keep_ratio=True)NEWLINE ],NEWLINE [NEWLINE dict(type='Resize',NEWLINE img_scale=[(320, 320), (576, 576)],NEWLINE multiscale_mode='value',NEWLINE keep_ratio=True),NEWLINE dict(type='RandomCrop',NEWLINE crop_type='absolute_range',NEWLINE crop_size=(320, 320),NEWLINE allow_negative_crop=True),NEWLINE dict(type='Resize',NEWLINE img_scale=[(320, 320), (384, 384), (448, 448),NEWLINE (512, 512), (576, 576)],NEWLINE multiscale_mode='value',NEWLINE override=True,NEWLINE keep_ratio=True)NEWLINE ]NEWLINE ]),NEWLINE dict(type='Normalize', **img_norm_cfg),NEWLINE dict(type='Pad', size_divisor=32),NEWLINE dict(type='DefaultFormatBundle'),NEWLINE dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels', 'gt_masks']),NEWLINE]NEWLINEdata = dict(train=dict(pipeline=train_pipeline))NEWLINENEWLINEoptimizer = dict(_delete_=True, type='AdamW', lr=0.0001, betas=(0.9, 0.999), weight_decay=0.05,NEWLINE paramwise_cfg=dict(custom_keys={'absolute_pos_embed': dict(decay_mult=0.),NEWLINE 'relative_position_bias_table': dict(decay_mult=0.),NEWLINE 'norm': dict(decay_mult=0.)}))NEWLINElr_config = dict(step=[16, 22])NEWLINErunner = dict(type='EpochBasedRunnerAmp', max_epochs=12)NEWLINENEWLINE# do not use mmdet version fp16NEWLINEfp16 = NoneNEWLINEoptimizer_config = dict(NEWLINE type="DistOptimizerHook",NEWLINE update_interval=1,NEWLINE grad_clip=None,NEWLINE coalesce=True,NEWLINE bucket_size_mb=-1,NEWLINE use_fp16=True,NEWLINE)NEWLINE
import networkxNEWLINEimport reNEWLINEfrom konlpy.tag import Mecab,OktNEWLINEimport mathNEWLINEimport pandas as pdNEWLINEfrom tqdm import tqdmNEWLINENEWLINE# Textrank 요약NEWLINEclass TextRank:NEWLINE def __init__(self, **kargs):NEWLINE self.graph = NoneNEWLINE self.window = kargs.get('window', 5)NEWLINE self.coef = kargs.get('coef', 1.0)NEWLINE self.threshold = kargs.get('threshold', 0.005)NEWLINE self.dictCount = {}NEWLINE self.dictBiCount = {}NEWLINE self.dictNear = {}NEWLINE self.nTotal = 0NEWLINENEWLINE def clean_text(self,texts):NEWLINE law = re.sub(r'\【이유\】', '', texts) # remove startNEWLINE law = re.sub(r'\【이 유\】', '', law) # remove startNEWLINE law = re.sub(r'[@%\\*=()/~#&\+á?\xc3\xa1\-\|\:\;\!\-\,\_\~\$\'\"\[\]]', '', law) # remove punctuationNEWLINE law = re.sub(r'\d\.', '', law) # remove number with punctuationNEWLINE law = re.sub(r'\d+', '', law) # remove numberNEWLINE law = re.sub(r'[①②③④⑤⑥⑦]', '', law) # remove numberNEWLINE return lawNEWLINENEWLINE def loadSents(self, sentenceIter, tokenizer=Okt()):NEWLINE def similarity(a, b):NEWLINE n = len(a.intersection(b))NEWLINE return n / float(len(a) + len(b) - n) / (math.log(len(a) + 1) * math.log(len(b) + 1))NEWLINENEWLINE if not tokenizer: rgxSplitter = re.compile('[\\s.,:;-?!()"\']+')NEWLINE sentSet = []NEWLINE for sent in filter(None, sentenceIter):NEWLINE if type(sent) == str:NEWLINE if tokenizer:NEWLINE s = set(filter(None, tokenizer(sent)))NEWLINE else:NEWLINE s = set(filter(None, rgxSplitter.split(sent)))NEWLINE else:NEWLINE s = set(sent)NEWLINE # 해당 문장을 토크나이저로 자른 형태들, 2보다 작다면 이는 여기서 NNG, NN, VV, VA을 포함하는 요소가 아예 없거나 하나밖에 없다는 뜻NEWLINE if len(s) < 2: continueNEWLINE self.dictCount[len(self.dictCount)] = sentNEWLINE sentSet.append(s)NEWLINE # sentSet : {('아버지', 'NNG'), ('식당', 'NNG')} 등의 형태로 문장의 토큰들을 저장한 곳NEWLINENEWLINE # 모든 문장의 조합에 대해서 similarity 계산 후 dicBiCount에 저장NEWLINE for i in range(len(self.dictCount)):NEWLINE for j in range(i + 1, len(self.dictCount)):NEWLINE s = similarity(sentSet[i], sentSet[j])NEWLINE if s < self.threshold: continueNEWLINE self.dictBiCount[i, j] = sNEWLINENEWLINE def build(self):NEWLINE self.graph = networkx.Graph()NEWLINE self.graph.add_nodes_from(self.dictCount.keys())NEWLINE for (a, b), n in self.dictBiCount.items():NEWLINE self.graph.add_edge(a, b, weight=n * self.coef + (1 - self.coef))NEWLINENEWLINE def rank(self):NEWLINE return networkx.pagerank(self.graph, weight='weight')NEWLINENEWLINE def summarize(self, ratio=0.333):NEWLINE r = self.rank()NEWLINE ks = sorted(r, key=r.get, reverse=True)NEWLINE score = int(len(r)*ratio)NEWLINENEWLINE # 문장 수NEWLINE if score < 3 :NEWLINE score = len(r)NEWLINE elif score >= 3:NEWLINE score = 3NEWLINE else:NEWLINE passNEWLINENEWLINENEWLINE ks = ks[:score]NEWLINE return ' '.join(map(lambda k: self.dictCount[k], sorted(ks)))NEWLINENEWLINE def law_to_list(self,data):NEWLINE clean_law=self.clean_text(data)NEWLINE line_law=clean_law.split('.')NEWLINE df_line = pd.DataFrame(line_law)NEWLINE df_line.columns=['original']NEWLINE df_line['length'] = df_line['original'].apply(lambda x: len(x))NEWLINE df_line.drop(df_line.loc[df_line['length'] <= 1].index, inplace=True)NEWLINE df_line.reset_index(drop=True, inplace=True)NEWLINE return df_lineNEWLINENEWLINENEWLINE def predict(self,data_path):NEWLINE # data = pd.read_csv(data_path, sep='\t')NEWLINE data = pd.read_csv(data_path)NEWLINE summary=[]NEWLINE tagger=Okt()NEWLINE data=data.iloc[:10,:]NEWLINE for i in tqdm(range(0,len(data))):NEWLINE self.dictCount = {}NEWLINE self.dictBiCount = {}NEWLINE self.dictNear = {}NEWLINE self.nTotal = 0NEWLINENEWLINE text=data['article_original'][i]NEWLINE l_list=self.law_to_list(text)NEWLINE stopword = set([('있', 'VV'), ('하', 'VV'), ('되', 'VV')])NEWLINE # print(l_list['original'])NEWLINE self.loadSents(l_list['original'],NEWLINE lambda sent: filter(NEWLINE lambda x: x not in stopword and x[1] in (NEWLINE 'NNG', 'NNP', 'VV', 'VA', 'Noun', 'verb', 'Adjective'),NEWLINE tagger.pos(sent))) # 명사 ,명사 ,동사,NEWLINE self.build()NEWLINE self.rank()NEWLINE final=self.summarize(0.3)NEWLINE rate=0.3NEWLINE while final=='' and rate <=1:NEWLINE final=self.summarize(rate)NEWLINE rate += 0.2NEWLINE # print(final[:100])NEWLINE # summary.append({NEWLINE # "origin" : text,NEWLINE # "origin_sum": data.iloc[i, 0],NEWLINE # 'textrank_sum' : final,NEWLINE # })NEWLINE summary.append(final)NEWLINE # return pd.DataFrame(summary)NEWLINE data['textrank_sum'] = summaryNEWLINE return dataNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINEif __name__=='__main__':NEWLINE tr = TextRank()NEWLINE data = tr.fit(df.iloc[10, 1])['original']NEWLINE tagger = Okt()NEWLINE stopword = set([('있', 'VV'), ('하', 'VV'), ('되', 'VV')])NEWLINE tr.loadSents(data,NEWLINE lambda sent: filter(NEWLINE lambda x: x not in stopword and x[1] in ('NNG', 'NNP', 'VV', 'VA', 'Noun', 'verb', 'Adjective'),NEWLINE tagger.pos(sent))) # 명사 ,명사 ,동사,NEWLINENEWLINE tr.build()NEWLINE ranks = tr.rank()NEWLINE tr.summarize(0.3)NEWLINE
# -*- coding=utf-8 -*-NEWLINEfrom __future__ import absolute_import, print_functionNEWLINENEWLINEimport loggingNEWLINEimport operatorNEWLINEimport platformNEWLINEimport sysNEWLINEfrom collections import defaultdictNEWLINENEWLINEimport attrNEWLINEimport sixNEWLINEfrom packaging.version import VersionNEWLINENEWLINEfrom ..compat import Path, lru_cacheNEWLINEfrom ..environment import ASDF_DATA_DIR, MYPY_RUNNING, PYENV_ROOT, SYSTEM_ARCHNEWLINEfrom ..exceptions import InvalidPythonVersionNEWLINEfrom ..utils import (NEWLINE RE_MATCHER,NEWLINE _filter_none,NEWLINE ensure_path,NEWLINE expand_paths,NEWLINE get_python_version,NEWLINE guess_company,NEWLINE is_in_path,NEWLINE looks_like_python,NEWLINE optional_instance_of,NEWLINE parse_asdf_version_order,NEWLINE parse_pyenv_version_order,NEWLINE parse_python_version,NEWLINE path_is_pythoncore,NEWLINE unnest,NEWLINE)NEWLINEfrom .mixins import BaseFinder, BasePathNEWLINENEWLINEif MYPY_RUNNING:NEWLINE from typing import (NEWLINE DefaultDict,NEWLINE Optional,NEWLINE Callable,NEWLINE Generator,NEWLINE Any,NEWLINE Union,NEWLINE Tuple,NEWLINE List,NEWLINE Dict,NEWLINE Type,NEWLINE TypeVar,NEWLINE Iterator,NEWLINE overload,NEWLINE )NEWLINE from .path import PathEntryNEWLINE from .._vendor.pep514tools.environment import EnvironmentNEWLINEelse:NEWLINENEWLINE def overload(f):NEWLINE return fNEWLINENEWLINENEWLINElogger = logging.getLogger(__name__)NEWLINENEWLINENEWLINE@attr.s(slots=True)NEWLINEclass PythonFinder(BaseFinder, BasePath):NEWLINE root = attr.ib(default=None, validator=optional_instance_of(Path), type=Path)NEWLINE # should come before versions, because its value is used in versions's default initializer.NEWLINE #: Whether to ignore any paths which raise exceptions and are not actually pythonNEWLINE ignore_unsupported = attr.ib(default=True, type=bool)NEWLINE #: Glob path for python versions off of the root directoryNEWLINE version_glob_path = attr.ib(default="versions/*", type=str)NEWLINE #: The function to use to sort version order when returning an ordered verion setNEWLINE sort_function = attr.ib(default=None) # type: CallableNEWLINE #: The root locations used for discoveryNEWLINE roots = attr.ib(default=attr.Factory(defaultdict), type=defaultdict)NEWLINE #: List of paths discovered during searchNEWLINE paths = attr.ib(type=list)NEWLINE #: shim directoryNEWLINE shim_dir = attr.ib(default="shims", type=str)NEWLINE #: Versions discovered in the specified pathsNEWLINE _versions = attr.ib(default=attr.Factory(defaultdict), type=defaultdict)NEWLINE _pythons = attr.ib(default=attr.Factory(defaultdict), type=defaultdict)NEWLINENEWLINE def __del__(self):NEWLINE # type: () -> NoneNEWLINE self._versions = defaultdict()NEWLINE self._pythons = defaultdict()NEWLINE self.roots = defaultdict()NEWLINE self.paths = []NEWLINENEWLINE @propertyNEWLINE def expanded_paths(self):NEWLINE # type: () -> GeneratorNEWLINE return (NEWLINE path for path in unnest(p for p in self.versions.values()) if path is not NoneNEWLINE )NEWLINENEWLINE @propertyNEWLINE def is_pyenv(self):NEWLINE # type: () -> boolNEWLINE return is_in_path(str(self.root), PYENV_ROOT)NEWLINENEWLINE @propertyNEWLINE def is_asdf(self):NEWLINE # type: () -> boolNEWLINE return is_in_path(str(self.root), ASDF_DATA_DIR)NEWLINENEWLINE def get_version_order(self):NEWLINE # type: () -> List[Path]NEWLINE version_paths = [NEWLINE pNEWLINE for p in self.root.glob(self.version_glob_path)NEWLINE if not (p.parent.name == "envs" or p.name == "envs")NEWLINE ]NEWLINE versions = {v.name: v for v in version_paths}NEWLINE version_order = [] # type: List[Path]NEWLINE if self.is_pyenv:NEWLINE version_order = [NEWLINE versions[v] for v in parse_pyenv_version_order() if v in versionsNEWLINE ]NEWLINE elif self.is_asdf:NEWLINE version_order = [NEWLINE versions[v] for v in parse_asdf_version_order() if v in versionsNEWLINE ]NEWLINE for version in version_order:NEWLINE if version in version_paths:NEWLINE version_paths.remove(version)NEWLINE if version_order:NEWLINE version_order += version_pathsNEWLINE else:NEWLINE version_order = version_pathsNEWLINE return version_orderNEWLINENEWLINE def get_bin_dir(self, base):NEWLINE # type: (Union[Path, str]) -> PathNEWLINE if isinstance(base, six.string_types):NEWLINE base = Path(base)NEWLINE return base / "bin"NEWLINENEWLINE @classmethodNEWLINE def version_from_bin_dir(cls, entry):NEWLINE # type: (PathEntry) -> Optional[PathEntry]NEWLINE py_version = NoneNEWLINE py_version = next(iter(entry.find_all_python_versions()), None)NEWLINE return py_versionNEWLINENEWLINE def _iter_version_bases(self):NEWLINE # type: () -> Iterator[Tuple[Path, PathEntry]]NEWLINE from .path import PathEntryNEWLINENEWLINE for p in self.get_version_order():NEWLINE bin_dir = self.get_bin_dir(p)NEWLINE if bin_dir.exists() and bin_dir.is_dir():NEWLINE entry = PathEntry.create(NEWLINE path=bin_dir.absolute(), only_python=False, name=p.name, is_root=TrueNEWLINE )NEWLINE self.roots[p] = entryNEWLINE yield (p, entry)NEWLINENEWLINE def _iter_versions(self):NEWLINE # type: () -> Iterator[Tuple[Path, PathEntry, Tuple]]NEWLINE for base_path, entry in self._iter_version_bases():NEWLINE version = NoneNEWLINE version_entry = NoneNEWLINE try:NEWLINE version = PythonVersion.parse(entry.name)NEWLINE except (ValueError, InvalidPythonVersion):NEWLINE version_entry = next(iter(entry.find_all_python_versions()), None)NEWLINE if version is None:NEWLINE if not self.ignore_unsupported:NEWLINE raiseNEWLINE continueNEWLINE if version_entry is not None:NEWLINE version = version_entry.py_version.as_dict()NEWLINE except Exception:NEWLINE if not self.ignore_unsupported:NEWLINE raiseNEWLINE logger.warning(NEWLINE "Unsupported Python version %r, ignoring...",NEWLINE base_path.name,NEWLINE exc_info=True,NEWLINE )NEWLINE continueNEWLINE if version is not None:NEWLINE version_tuple = (NEWLINE version.get("major"),NEWLINE version.get("minor"),NEWLINE version.get("patch"),NEWLINE version.get("is_prerelease"),NEWLINE version.get("is_devrelease"),NEWLINE version.get("is_debug"),NEWLINE )NEWLINE yield (base_path, entry, version_tuple)NEWLINENEWLINE @propertyNEWLINE def versions(self):NEWLINE # type: () -> DefaultDict[Tuple, PathEntry]NEWLINE if not self._versions:NEWLINE for base_path, entry, version_tuple in self._iter_versions():NEWLINE self._versions[version_tuple] = entryNEWLINE return self._versionsNEWLINENEWLINE def _iter_pythons(self):NEWLINE # type: () -> IteratorNEWLINE for path, entry, version_tuple in self._iter_versions():NEWLINE if path.as_posix() in self._pythons:NEWLINE yield self._pythons[path.as_posix()]NEWLINE elif version_tuple not in self.versions:NEWLINE for python in entry.find_all_python_versions():NEWLINE yield pythonNEWLINE else:NEWLINE yield self.versions[version_tuple]NEWLINENEWLINE @paths.defaultNEWLINE def get_paths(self):NEWLINE # type: () -> List[PathEntry]NEWLINE _paths = [base for _, base in self._iter_version_bases()]NEWLINE return _pathsNEWLINENEWLINE @propertyNEWLINE def pythons(self):NEWLINE # type: () -> DefaultDict[str, PathEntry]NEWLINE if not self._pythons:NEWLINE from .path import PathEntryNEWLINENEWLINE self._pythons = defaultdict(PathEntry) # type: DefaultDict[str, PathEntry]NEWLINE for python in self._iter_pythons():NEWLINE python_path = python.path.as_posix() # type: ignoreNEWLINE self._pythons[python_path] = pythonNEWLINE return self._pythonsNEWLINENEWLINE @pythons.setterNEWLINE def pythons(self, value):NEWLINE # type: (DefaultDict[str, PathEntry]) -> NoneNEWLINE self._pythons = valueNEWLINENEWLINE def get_pythons(self):NEWLINE # type: () -> DefaultDict[str, PathEntry]NEWLINE return self.pythonsNEWLINENEWLINE @overloadNEWLINE @classmethodNEWLINE def create(cls, root, sort_function, version_glob_path=None, ignore_unsupported=True):NEWLINE # type: (str, Callable, Optional[str], bool) -> PythonFinderNEWLINE root = ensure_path(root)NEWLINE if not version_glob_path:NEWLINE version_glob_path = "versions/*"NEWLINE return cls(NEWLINE root=root,NEWLINE path=root,NEWLINE ignore_unsupported=ignore_unsupported, # type: ignoreNEWLINE sort_function=sort_function,NEWLINE version_glob_path=version_glob_path,NEWLINE )NEWLINENEWLINE def find_all_python_versions(NEWLINE self,NEWLINE major=None, # type: Optional[Union[str, int]]NEWLINE minor=None, # type: Optional[int]NEWLINE patch=None, # type: Optional[int]NEWLINE pre=None, # type: Optional[bool]NEWLINE dev=None, # type: Optional[bool]NEWLINE arch=None, # type: Optional[str]NEWLINE name=None, # type: Optional[str]NEWLINE ):NEWLINE # type: (...) -> List[PathEntry]NEWLINE """Search for a specific python version on the path. Return all copiesNEWLINENEWLINE :param major: Major python version to search for.NEWLINE :type major: intNEWLINE :param int minor: Minor python version to search for, defaults to NoneNEWLINE :param int patch: Patch python version to search for, defaults to NoneNEWLINE :param bool pre: Search for prereleases (default None) - prioritize releases if NoneNEWLINE :param bool dev: Search for devreleases (default None) - prioritize releases if NoneNEWLINE :param str arch: Architecture to include, e.g. '64bit', defaults to NoneNEWLINE :param str name: The name of a python version, e.g. ``anaconda3-5.3.0``NEWLINE :return: A list of :class:`~pythonfinder.models.PathEntry` instances matching the version requested.NEWLINE :rtype: List[:class:`~pythonfinder.models.PathEntry`]NEWLINE """NEWLINENEWLINE call_method = "find_all_python_versions" if self.is_dir else "find_python_version"NEWLINE sub_finder = operator.methodcaller(NEWLINE call_method, major, minor, patch, pre, dev, arch, nameNEWLINE )NEWLINE if not any([major, minor, patch, name]):NEWLINE pythons = [NEWLINE next(iter(py for py in base.find_all_python_versions()), None)NEWLINE for _, base in self._iter_version_bases()NEWLINE ]NEWLINE else:NEWLINE pythons = [sub_finder(path) for path in self.paths]NEWLINE pythons = expand_paths(pythons, True)NEWLINE version_sort = operator.attrgetter("as_python.version_sort")NEWLINE paths = [NEWLINE p for p in sorted(pythons, key=version_sort, reverse=True) if p is not NoneNEWLINE ]NEWLINE return pathsNEWLINENEWLINE def find_python_version(NEWLINE self,NEWLINE major=None, # type: Optional[Union[str, int]]NEWLINE minor=None, # type: Optional[int]NEWLINE patch=None, # type: Optional[int]NEWLINE pre=None, # type: Optional[bool]NEWLINE dev=None, # type: Optional[bool]NEWLINE arch=None, # type: Optional[str]NEWLINE name=None, # type: Optional[str]NEWLINE ):NEWLINE # type: (...) -> Optional[PathEntry]NEWLINE """Search or self for the specified Python version and return the first match.NEWLINENEWLINE :param major: Major version number.NEWLINE :type major: intNEWLINE :param int minor: Minor python version to search for, defaults to NoneNEWLINE :param int patch: Patch python version to search for, defaults to NoneNEWLINE :param bool pre: Search for prereleases (default None) - prioritize releases if NoneNEWLINE :param bool dev: Search for devreleases (default None) - prioritize releases if NoneNEWLINE :param str arch: Architecture to include, e.g. '64bit', defaults to NoneNEWLINE :param str name: The name of a python version, e.g. ``anaconda3-5.3.0``NEWLINE :returns: A :class:`~pythonfinder.models.PathEntry` instance matching the version requested.NEWLINE """NEWLINENEWLINE sub_finder = operator.methodcaller(NEWLINE "find_python_version", major, minor, patch, pre, dev, arch, nameNEWLINE )NEWLINE version_sort = operator.attrgetter("as_python.version_sort")NEWLINE unnested = [sub_finder(self.roots[path]) for path in self.roots]NEWLINE unnested = [NEWLINE pNEWLINE for p in unnestedNEWLINE if p is not None and p.is_python and p.as_python is not NoneNEWLINE ]NEWLINE paths = sorted(list(unnested), key=version_sort, reverse=True)NEWLINE return next(iter(p for p in paths if p is not None), None)NEWLINENEWLINE def which(self, name):NEWLINE # type: (str) -> Optional[PathEntry]NEWLINE """Search in this path for an executable.NEWLINENEWLINE :param executable: The name of an executable to search for.NEWLINE :type executable: strNEWLINE :returns: :class:`~pythonfinder.models.PathEntry` instance.NEWLINE """NEWLINENEWLINE matches = (p.which(name) for p in self.paths)NEWLINE non_empty_match = next(iter(m for m in matches if m is not None), None)NEWLINE return non_empty_matchNEWLINENEWLINENEWLINE@attr.s(slots=True)NEWLINEclass PythonVersion(object):NEWLINE major = attr.ib(default=0, type=int)NEWLINE minor = attr.ib(default=None) # type: Optional[int]NEWLINE patch = attr.ib(default=None) # type: Optional[int]NEWLINE is_prerelease = attr.ib(default=False, type=bool)NEWLINE is_postrelease = attr.ib(default=False, type=bool)NEWLINE is_devrelease = attr.ib(default=False, type=bool)NEWLINE is_debug = attr.ib(default=False, type=bool)NEWLINE version = attr.ib(default=None) # type: VersionNEWLINE architecture = attr.ib(default=None) # type: Optional[str]NEWLINE comes_from = attr.ib(default=None) # type: Optional[PathEntry]NEWLINE executable = attr.ib(default=None) # type: Optional[str]NEWLINE company = attr.ib(default=None) # type: Optional[str]NEWLINE name = attr.ib(default=None, type=str)NEWLINENEWLINE def __getattribute__(self, key):NEWLINE result = super(PythonVersion, self).__getattribute__(key)NEWLINE if key in ["minor", "patch"] and result is None:NEWLINE executable = None # type: Optional[str]NEWLINE if self.executable:NEWLINE executable = self.executableNEWLINE elif self.comes_from:NEWLINE executable = self.comes_from.path.as_posix()NEWLINE if executable is not None:NEWLINE if not isinstance(executable, six.string_types):NEWLINE executable = executable.as_posix()NEWLINE instance_dict = self.parse_executable(executable)NEWLINE for k in instance_dict.keys():NEWLINE try:NEWLINE super(PythonVersion, self).__getattribute__(k)NEWLINE except AttributeError:NEWLINE continueNEWLINE else:NEWLINE setattr(self, k, instance_dict[k])NEWLINE result = instance_dict.get(key)NEWLINE return resultNEWLINENEWLINE @propertyNEWLINE def version_sort(self):NEWLINE # type: () -> Tuple[int, int, Optional[int], int, int]NEWLINE """NEWLINE A tuple for sorting against other instances of the same class.NEWLINENEWLINE Returns a tuple of the python version but includes points for core python,NEWLINE non-dev, and non-prerelease versions. So released versions will have 2 pointsNEWLINE for this value. E.g. ``(1, 3, 6, 6, 2)`` is a release, ``(1, 3, 6, 6, 1)`` is aNEWLINE prerelease, ``(1, 3, 6, 6, 0)`` is a dev release, and ``(1, 3, 6, 6, 3)`` is aNEWLINE postrelease. ``(0, 3, 7, 3, 2)`` represents a non-core python release, e.g. byNEWLINE a repackager of python like Continuum.NEWLINE """NEWLINE company_sort = 1 if (self.company and self.company == "PythonCore") else 0NEWLINE release_sort = 2NEWLINE if self.is_postrelease:NEWLINE release_sort = 3NEWLINE elif self.is_prerelease:NEWLINE release_sort = 1NEWLINE elif self.is_devrelease:NEWLINE release_sort = 0NEWLINE elif self.is_debug:NEWLINE release_sort = 1NEWLINE return (NEWLINE company_sort,NEWLINE self.major,NEWLINE self.minor,NEWLINE self.patch if self.patch else 0,NEWLINE release_sort,NEWLINE )NEWLINENEWLINE @propertyNEWLINE def version_tuple(self):NEWLINE # type: () -> Tuple[int, Optional[int], Optional[int], bool, bool, bool]NEWLINE """NEWLINE Provides a version tuple for using as a dictionary key.NEWLINENEWLINE :return: A tuple describing the python version meetadata contained.NEWLINE :rtype: tupleNEWLINE """NEWLINENEWLINE return (NEWLINE self.major,NEWLINE self.minor,NEWLINE self.patch,NEWLINE self.is_prerelease,NEWLINE self.is_devrelease,NEWLINE self.is_debug,NEWLINE )NEWLINENEWLINE def matches(NEWLINE self,NEWLINE major=None, # type: Optional[int]NEWLINE minor=None, # type: Optional[int]NEWLINE patch=None, # type: Optional[int]NEWLINE pre=False, # type: boolNEWLINE dev=False, # type: boolNEWLINE arch=None, # type: Optional[str]NEWLINE debug=False, # type: boolNEWLINE python_name=None, # type: Optional[str]NEWLINE ):NEWLINE # type: (...) -> boolNEWLINE result = FalseNEWLINE if arch:NEWLINE own_arch = self.get_architecture()NEWLINE if arch.isdigit():NEWLINE arch = "{0}bit".format(arch)NEWLINE if (NEWLINE (major is None or self.major and self.major == major)NEWLINE and (minor is None or self.minor and self.minor == minor)NEWLINE and (patch is None or self.patch and self.patch == patch)NEWLINE and (pre is None or self.is_prerelease == pre)NEWLINE and (dev is None or self.is_devrelease == dev)NEWLINE and (arch is None or own_arch == arch)NEWLINE and (debug is None or self.is_debug == debug)NEWLINE and (NEWLINE python_name is NoneNEWLINE or (python_name and self.name)NEWLINE and (self.name == python_name or self.name.startswith(python_name))NEWLINE )NEWLINE ):NEWLINE result = TrueNEWLINE return resultNEWLINENEWLINE def as_major(self):NEWLINE # type: () -> PythonVersionNEWLINE self_dict = attr.asdict(self, recurse=False, filter=_filter_none).copy()NEWLINE self_dict.update({"minor": None, "patch": None})NEWLINE return self.create(**self_dict)NEWLINENEWLINE def as_minor(self):NEWLINE # type: () -> PythonVersionNEWLINE self_dict = attr.asdict(self, recurse=False, filter=_filter_none).copy()NEWLINE self_dict.update({"patch": None})NEWLINE return self.create(**self_dict)NEWLINENEWLINE def as_dict(self):NEWLINE # type: () -> Dict[str, Union[int, bool, Version, None]]NEWLINE return {NEWLINE "major": self.major,NEWLINE "minor": self.minor,NEWLINE "patch": self.patch,NEWLINE "is_prerelease": self.is_prerelease,NEWLINE "is_postrelease": self.is_postrelease,NEWLINE "is_devrelease": self.is_devrelease,NEWLINE "is_debug": self.is_debug,NEWLINE "version": self.version,NEWLINE "company": self.company,NEWLINE }NEWLINENEWLINE def update_metadata(self, metadata):NEWLINE # type: (Dict[str, Union[str, int, Version]]) -> NoneNEWLINE """NEWLINE Update the metadata on the current :class:`pythonfinder.models.python.PythonVersion`NEWLINENEWLINE Given a parsed version dictionary from :func:`pythonfinder.utils.parse_python_version`,NEWLINE update the instance variables of the current version instance to reflect the newlyNEWLINE supplied values.NEWLINE """NEWLINENEWLINE for key in metadata:NEWLINE try:NEWLINE _ = getattr(self, key)NEWLINE except AttributeError:NEWLINE continueNEWLINE else:NEWLINE setattr(self, key, metadata[key])NEWLINENEWLINE @classmethodNEWLINE @lru_cache(maxsize=1024)NEWLINE def parse(cls, version):NEWLINE # type: (str) -> Dict[str, Union[str, int, Version]]NEWLINE """NEWLINE Parse a valid version string into a dictionaryNEWLINENEWLINE Raises:NEWLINE ValueError -- Unable to parse version stringNEWLINE ValueError -- Not a valid python versionNEWLINE TypeError -- NoneType or unparseable type passed inNEWLINENEWLINE :param str version: A valid version stringNEWLINE :return: A dictionary with metadata about the specified python version.NEWLINE :rtype: dictNEWLINE """NEWLINENEWLINE if version is None:NEWLINE raise TypeError("Must pass a value to parse!")NEWLINE version_dict = parse_python_version(str(version))NEWLINE if not version_dict:NEWLINE raise ValueError("Not a valid python version: %r" % version)NEWLINE return version_dictNEWLINENEWLINE def get_architecture(self):NEWLINE # type: () -> strNEWLINE if self.architecture:NEWLINE return self.architectureNEWLINE arch = NoneNEWLINE if self.comes_from is not None:NEWLINE arch, _ = platform.architecture(self.comes_from.path.as_posix())NEWLINE elif self.executable is not None:NEWLINE arch, _ = platform.architecture(self.executable)NEWLINE if arch is None:NEWLINE arch, _ = platform.architecture(sys.executable)NEWLINE self.architecture = archNEWLINE return self.architectureNEWLINENEWLINE @classmethodNEWLINE def from_path(cls, path, name=None, ignore_unsupported=True, company=None):NEWLINE # type: (Union[str, PathEntry], Optional[str], bool, Optional[str]) -> PythonVersionNEWLINE """NEWLINE Parses a python version from a system path.NEWLINENEWLINE Raises:NEWLINE ValueError -- Not a valid python pathNEWLINENEWLINE :param path: A string or :class:`~pythonfinder.models.path.PathEntry`NEWLINE :type path: str or :class:`~pythonfinder.models.path.PathEntry` instanceNEWLINE :param str name: Name of the python distribution in questionNEWLINE :param bool ignore_unsupported: Whether to ignore or error on unsupported paths.NEWLINE :param Optional[str] company: The company or vendor packaging the distribution.NEWLINE :return: An instance of a PythonVersion.NEWLINE :rtype: :class:`~pythonfinder.models.python.PythonVersion`NEWLINE """NEWLINENEWLINE from .path import PathEntryNEWLINENEWLINE if not isinstance(path, PathEntry):NEWLINE path = PathEntry.create(path, is_root=False, only_python=True, name=name)NEWLINE from ..environment import IGNORE_UNSUPPORTEDNEWLINENEWLINE ignore_unsupported = ignore_unsupported or IGNORE_UNSUPPORTEDNEWLINE path_name = getattr(path, "name", path.path.name) # strNEWLINE if not path.is_python:NEWLINE if not (ignore_unsupported or IGNORE_UNSUPPORTED):NEWLINE raise ValueError("Not a valid python path: %s" % path.path)NEWLINE try:NEWLINE instance_dict = cls.parse(path_name)NEWLINE except Exception:NEWLINE instance_dict = cls.parse_executable(path.path.absolute().as_posix())NEWLINE else:NEWLINE if instance_dict.get("minor") is None and looks_like_python(path.path.name):NEWLINE instance_dict = cls.parse_executable(path.path.absolute().as_posix())NEWLINENEWLINE if (NEWLINE not isinstance(instance_dict.get("version"), Version)NEWLINE and not ignore_unsupportedNEWLINE ):NEWLINE raise ValueError("Not a valid python path: %s" % path)NEWLINE if instance_dict.get("patch") is None:NEWLINE instance_dict = cls.parse_executable(path.path.absolute().as_posix())NEWLINE if name is None:NEWLINE name = path_nameNEWLINE if company is None:NEWLINE company = guess_company(path.path.as_posix())NEWLINE instance_dict.update(NEWLINE {"comes_from": path, "name": name, "executable": path.path.as_posix()}NEWLINE )NEWLINE return cls(**instance_dict) # type: ignoreNEWLINENEWLINE @classmethodNEWLINE @lru_cache(maxsize=1024)NEWLINE def parse_executable(cls, path):NEWLINE # type: (str) -> Dict[str, Optional[Union[str, int, Version]]]NEWLINE result_dict = {} # type: Dict[str, Optional[Union[str, int, Version]]]NEWLINE result_version = None # type: Optional[str]NEWLINE if path is None:NEWLINE raise TypeError("Must pass a valid path to parse.")NEWLINE if not isinstance(path, six.string_types):NEWLINE path = path.as_posix()NEWLINE # if not looks_like_python(path):NEWLINE # raise ValueError("Path %r does not look like a valid python path" % path)NEWLINE try:NEWLINE result_version = get_python_version(path)NEWLINE except Exception:NEWLINE raise ValueError("Not a valid python path: %r" % path)NEWLINE if result_version is None:NEWLINE raise ValueError("Not a valid python path: %s" % path)NEWLINE result_dict = cls.parse(result_version.strip())NEWLINE return result_dictNEWLINENEWLINE @classmethodNEWLINE def from_windows_launcher(cls, launcher_entry, name=None, company=None):NEWLINE # type: (Environment, Optional[str], Optional[str]) -> PythonVersionNEWLINE """Create a new PythonVersion instance from a Windows Launcher EntryNEWLINENEWLINE :param launcher_entry: A python launcher environment object.NEWLINE :param Optional[str] name: The name of the distribution.NEWLINE :param Optional[str] company: The name of the distributing company.NEWLINE :return: An instance of a PythonVersion.NEWLINE :rtype: :class:`~pythonfinder.models.python.PythonVersion`NEWLINE """NEWLINENEWLINE from .path import PathEntryNEWLINENEWLINE creation_dict = cls.parse(launcher_entry.info.version)NEWLINE base_path = ensure_path(launcher_entry.info.install_path.__getattr__(""))NEWLINE default_path = base_path / "python.exe"NEWLINE if not default_path.exists():NEWLINE default_path = base_path / "Scripts" / "python.exe"NEWLINE exe_path = ensure_path(NEWLINE getattr(launcher_entry.info.install_path, "executable_path", default_path)NEWLINE )NEWLINE company = getattr(launcher_entry, "company", guess_company(exe_path.as_posix()))NEWLINE creation_dict.update(NEWLINE {NEWLINE "architecture": getattr(NEWLINE launcher_entry.info, "sys_architecture", SYSTEM_ARCHNEWLINE ),NEWLINE "executable": exe_path,NEWLINE "name": name,NEWLINE "company": company,NEWLINE }NEWLINE )NEWLINE py_version = cls.create(**creation_dict)NEWLINE comes_from = PathEntry.create(exe_path, only_python=True, name=name)NEWLINE py_version.comes_from = comes_fromNEWLINE py_version.name = comes_from.nameNEWLINE return py_versionNEWLINENEWLINE @classmethodNEWLINE def create(cls, **kwargs):NEWLINE # type: (...) -> PythonVersionNEWLINE if "architecture" in kwargs:NEWLINE if kwargs["architecture"].isdigit():NEWLINE kwargs["architecture"] = "{0}bit".format(kwargs["architecture"])NEWLINE return cls(**kwargs)NEWLINENEWLINENEWLINE@attr.sNEWLINEclass VersionMap(object):NEWLINE versions = attr.ib(NEWLINE factory=defaultdictNEWLINE ) # type: DefaultDict[Tuple[int, Optional[int], Optional[int], bool, bool, bool], List[PathEntry]]NEWLINENEWLINE def add_entry(self, entry):NEWLINE # type: (...) -> NoneNEWLINE version = entry.as_python # type: PythonVersionNEWLINE if version:NEWLINE _ = self.versions[version.version_tuple]NEWLINE paths = {p.path for p in self.versions.get(version.version_tuple, [])}NEWLINE if entry.path not in paths:NEWLINE self.versions[version.version_tuple].append(entry)NEWLINENEWLINE def merge(self, target):NEWLINE # type: (VersionMap) -> NoneNEWLINE for version, entries in target.versions.items():NEWLINE if version not in self.versions:NEWLINE self.versions[version] = entriesNEWLINE else:NEWLINE current_entries = {NEWLINE p.pathNEWLINE for p in self.versions[version] # type: ignoreNEWLINE if version in self.versionsNEWLINE }NEWLINE new_entries = {p.path for p in entries}NEWLINE new_entries -= current_entriesNEWLINE self.versions[version].extend(NEWLINE [e for e in entries if e.path in new_entries]NEWLINE )NEWLINE
# coding: utf-8NEWLINENEWLINE"""NEWLINE convertapiNEWLINENEWLINE Convert API lets you effortlessly convert file formats and types. # noqa: E501NEWLINENEWLINE OpenAPI spec version: v1NEWLINE NEWLINE Generated by: https://github.com/swagger-api/swagger-codegen.gitNEWLINE"""NEWLINENEWLINENEWLINEimport pprintNEWLINEimport re # noqa: F401NEWLINENEWLINEimport sixNEWLINENEWLINENEWLINEclass SetFormFieldValue(object):NEWLINE """NOTE: This class is auto generated by the swagger code generator program.NEWLINENEWLINE Do not edit the class manually.NEWLINE """NEWLINENEWLINE """NEWLINE Attributes:NEWLINE swagger_types (dict): The key is attribute nameNEWLINE and the value is attribute type.NEWLINE attribute_map (dict): The key is attribute nameNEWLINE and the value is json key in definition.NEWLINE """NEWLINE swagger_types = {NEWLINE 'field_name': 'str',NEWLINE 'text_value': 'str',NEWLINE 'checkbox_value': 'bool',NEWLINE 'combo_box_selected_index': 'int'NEWLINE }NEWLINENEWLINE attribute_map = {NEWLINE 'field_name': 'FieldName',NEWLINE 'text_value': 'TextValue',NEWLINE 'checkbox_value': 'CheckboxValue',NEWLINE 'combo_box_selected_index': 'ComboBoxSelectedIndex'NEWLINE }NEWLINENEWLINE def __init__(self, field_name=None, text_value=None, checkbox_value=None, combo_box_selected_index=None): # noqa: E501NEWLINE """SetFormFieldValue - a model defined in Swagger""" # noqa: E501NEWLINENEWLINE self._field_name = NoneNEWLINE self._text_value = NoneNEWLINE self._checkbox_value = NoneNEWLINE self._combo_box_selected_index = NoneNEWLINE self.discriminator = NoneNEWLINENEWLINE if field_name is not None:NEWLINE self.field_name = field_nameNEWLINE if text_value is not None:NEWLINE self.text_value = text_valueNEWLINE if checkbox_value is not None:NEWLINE self.checkbox_value = checkbox_valueNEWLINE if combo_box_selected_index is not None:NEWLINE self.combo_box_selected_index = combo_box_selected_indexNEWLINENEWLINE @propertyNEWLINE def field_name(self):NEWLINE """Gets the field_name of this SetFormFieldValue. # noqa: E501NEWLINENEWLINE Name of the field to set; you can call /convert/edit/pdf/form/get-fields to enumerate field names in a form # noqa: E501NEWLINENEWLINE :return: The field_name of this SetFormFieldValue. # noqa: E501NEWLINE :rtype: strNEWLINE """NEWLINE return self._field_nameNEWLINENEWLINE @field_name.setterNEWLINE def field_name(self, field_name):NEWLINE """Sets the field_name of this SetFormFieldValue.NEWLINENEWLINE Name of the field to set; you can call /convert/edit/pdf/form/get-fields to enumerate field names in a form # noqa: E501NEWLINENEWLINE :param field_name: The field_name of this SetFormFieldValue. # noqa: E501NEWLINE :type: strNEWLINE """NEWLINENEWLINE self._field_name = field_nameNEWLINENEWLINE @propertyNEWLINE def text_value(self):NEWLINE """Gets the text_value of this SetFormFieldValue. # noqa: E501NEWLINENEWLINE For fields of type Text, the text value to put into the field # noqa: E501NEWLINENEWLINE :return: The text_value of this SetFormFieldValue. # noqa: E501NEWLINE :rtype: strNEWLINE """NEWLINE return self._text_valueNEWLINENEWLINE @text_value.setterNEWLINE def text_value(self, text_value):NEWLINE """Sets the text_value of this SetFormFieldValue.NEWLINENEWLINE For fields of type Text, the text value to put into the field # noqa: E501NEWLINENEWLINE :param text_value: The text_value of this SetFormFieldValue. # noqa: E501NEWLINE :type: strNEWLINE """NEWLINENEWLINE self._text_value = text_valueNEWLINENEWLINE @propertyNEWLINE def checkbox_value(self):NEWLINE """Gets the checkbox_value of this SetFormFieldValue. # noqa: E501NEWLINENEWLINE For fields of type Checkbox, the value to put into the field # noqa: E501NEWLINENEWLINE :return: The checkbox_value of this SetFormFieldValue. # noqa: E501NEWLINE :rtype: boolNEWLINE """NEWLINE return self._checkbox_valueNEWLINENEWLINE @checkbox_value.setterNEWLINE def checkbox_value(self, checkbox_value):NEWLINE """Sets the checkbox_value of this SetFormFieldValue.NEWLINENEWLINE For fields of type Checkbox, the value to put into the field # noqa: E501NEWLINENEWLINE :param checkbox_value: The checkbox_value of this SetFormFieldValue. # noqa: E501NEWLINE :type: boolNEWLINE """NEWLINENEWLINE self._checkbox_value = checkbox_valueNEWLINENEWLINE @propertyNEWLINE def combo_box_selected_index(self):NEWLINE """Gets the combo_box_selected_index of this SetFormFieldValue. # noqa: E501NEWLINENEWLINE For fields of type ComboBox; specifies the selected index of the combo box selection # noqa: E501NEWLINENEWLINE :return: The combo_box_selected_index of this SetFormFieldValue. # noqa: E501NEWLINE :rtype: intNEWLINE """NEWLINE return self._combo_box_selected_indexNEWLINENEWLINE @combo_box_selected_index.setterNEWLINE def combo_box_selected_index(self, combo_box_selected_index):NEWLINE """Sets the combo_box_selected_index of this SetFormFieldValue.NEWLINENEWLINE For fields of type ComboBox; specifies the selected index of the combo box selection # noqa: E501NEWLINENEWLINE :param combo_box_selected_index: The combo_box_selected_index of this SetFormFieldValue. # noqa: E501NEWLINE :type: intNEWLINE """NEWLINENEWLINE self._combo_box_selected_index = combo_box_selected_indexNEWLINENEWLINE def to_dict(self):NEWLINE """Returns the model properties as a dict"""NEWLINE result = {}NEWLINENEWLINE for attr, _ in six.iteritems(self.swagger_types):NEWLINE value = getattr(self, attr)NEWLINE if isinstance(value, list):NEWLINE result[attr] = list(map(NEWLINE lambda x: x.to_dict() if hasattr(x, "to_dict") else x,NEWLINE valueNEWLINE ))NEWLINE elif hasattr(value, "to_dict"):NEWLINE result[attr] = value.to_dict()NEWLINE elif isinstance(value, dict):NEWLINE result[attr] = dict(map(NEWLINE lambda item: (item[0], item[1].to_dict())NEWLINE if hasattr(item[1], "to_dict") else item,NEWLINE value.items()NEWLINE ))NEWLINE else:NEWLINE result[attr] = valueNEWLINE if issubclass(SetFormFieldValue, dict):NEWLINE for key, value in self.items():NEWLINE result[key] = valueNEWLINENEWLINE return resultNEWLINENEWLINE def to_str(self):NEWLINE """Returns the string representation of the model"""NEWLINE return pprint.pformat(self.to_dict())NEWLINENEWLINE def __repr__(self):NEWLINE """For `print` and `pprint`"""NEWLINE return self.to_str()NEWLINENEWLINE def __eq__(self, other):NEWLINE """Returns true if both objects are equal"""NEWLINE if not isinstance(other, SetFormFieldValue):NEWLINE return FalseNEWLINENEWLINE return self.__dict__ == other.__dict__NEWLINENEWLINE def __ne__(self, other):NEWLINE """Returns true if both objects are not equal"""NEWLINE return not self == otherNEWLINE
import jsonNEWLINEimport os.pathNEWLINENEWLINEclass Inventory:NEWLINE pets = {}NEWLINENEWLINE def __init__(self) -> None:NEWLINE self.load()NEWLINENEWLINE def add(self, key , qty):NEWLINE q = 0NEWLINE if key in self.pets: # test to make sure key existNEWLINE v = self.pets[key]NEWLINE q = v + qtyNEWLINE else:NEWLINE q = qtyNEWLINE self.pets[key] = qNEWLINE print(f'Added {qty} {key}: total = {self.pets[key]}')NEWLINE NEWLINENEWLINE def remove(self, key, qty):NEWLINE if key in self.pets: # test to make sure key existNEWLINE v = self.pets[key]NEWLINE q = v - qtyNEWLINE if q < 0:NEWLINE q = 0NEWLINE self.pets[key] = qNEWLINE print(f'Removed {qty} {key}: total = {self.pets[key]}')NEWLINENEWLINE def display(self):NEWLINE for key, value in self.pets.items(): # For loop iterating the dictionaryNEWLINE print(f'The key {key} = value {value}')NEWLINENEWLINE def load(self):NEWLINE if not os.path.exists('inventory.txt'):NEWLINE print('Skipping , nothing to load')NEWLINE returnNEWLINE print('Loading data from invnetory')NEWLINE with open('inventory.txt', 'r') as f:NEWLINE self.pets = json.load(f)NEWLINE print('loaded')NEWLINENEWLINE def save(self):NEWLINE print('Saving in Inventory')NEWLINE with open('inventory.txt', 'w') as f: # with is autoclosableNEWLINE json.dump(self.pets, f)NEWLINE print('Saved')NEWLINENEWLINEdef main():NEWLINE inv = Inventory()NEWLINE while True:NEWLINE action = input('Actions: Add, remove, list, save ,exit')NEWLINE if action == 'add' or action == 'remove':NEWLINE key = input('Enter the animal: ')NEWLINE qty = int(input('Enter the qty:'))NEWLINE if action == 'add':NEWLINE inv.add(key, qty)NEWLINE if action == 'remove':NEWLINE inv.remove(key, qty)NEWLINE if action == 'exit':NEWLINE breakNEWLINE if action == 'list':NEWLINE inv.display()NEWLINE if action == 'save':NEWLINE inv.save()NEWLINE inv.save()NEWLINEif __name__ == '__main__':NEWLINE main()
# encoding: utf8NEWLINEfrom __future__ import unicode_literalsNEWLINENEWLINENEWLINESTOP_WORDS = set("""NEWLINEà às acerca adeus agora ainda algmas algo algumas alguns ali além ambos anoNEWLINEanos antes ao aos apenas apoio apontar após aquela aquelas aquele aqueles aquiNEWLINEaquilo area área as assim através atrás até aíNEWLINENEWLINEbaixo bastante bem bom breveNEWLINENEWLINEcada caminho catorze cedo cento certamente certeza cima cinco coisa com comoNEWLINEcomprido conhecido conselho contra corrente custa cáNEWLINENEWLINEda daquela daquele dar das de debaixo demais dentro depois desde desligadoNEWLINEdessa desse desta deste deve devem deverá dez dezanove dezasseis dezasseteNEWLINEdezoito dia diante direita diz dizem dizer do dois dos doze duas dá dão dúvidaNEWLINENEWLINEé ela elas ele eles em embora enquanto entre então era és essa essas esse essesNEWLINEesta estado estar estará estas estava este estes esteve estive estivemosNEWLINEestiveram estiveste estivestes estou está estás estão eu exemploNEWLINENEWLINEfalta fará favor faz fazeis fazem fazemos fazer fazes fazia faço fez fim finalNEWLINEfoi fomos for fora foram forma foste fostes fuiNEWLINENEWLINEgeral grande grandes grupoNEWLINENEWLINEhoje horas háNEWLINENEWLINEiniciar inicio ir irá isso ista iste isto jáNEWLINENEWLINElado ligado local logo longe lugar láNEWLINENEWLINEmaior maioria maiorias mais mal mas me meio menor menos meses mesmo meu meusNEWLINEmil minha minhas momento muito muitos máximo mêsNEWLINENEWLINEna nada naquela naquele nas nem nenhuma nessa nesse nesta neste no noite nomeNEWLINEnos nossa nossas nosso nossos nova nove novo novos num numa nunca não nível nósNEWLINEnúmeroNEWLINENEWLINEobra obrigada obrigado oitava oitavo oito onde ontem onze os ou outra outrasNEWLINEoutro outrosNEWLINENEWLINEpara parece parte partir pegar pela pelas pelo pelos perto pessoas pode podemNEWLINEpoder poderá podia ponto pontos por porque porquê posição possivelmente possoNEWLINEpossível pouca pouco povo primeira primeiro promeiro próprio próximo puderamNEWLINEpôde põe põemNEWLINENEWLINEqual qualquer quando quanto quarta quarto quatro que quem quer quero questãoNEWLINEquieto quinta quinto quinze quê relaçãoNEWLINENEWLINEsabe saber se segunda segundo sei seis sem sempre ser seria sete seu seus sextaNEWLINEsexto sim sistema sob sobre sois somente somos sou sua suas são sétima sétimoNEWLINENEWLINEtal talvez também tanto tarde te tem temos tempo tendes tenho tens tentarNEWLINEtentaram tente tentei ter terceira terceiro teu teus teve tipo tive tivemosNEWLINEtiveram tiveste tivestes toda todas todo todos trabalhar trabalho treze três tuNEWLINEtua tuas tudo tão têmNEWLINENEWLINEúltimo um uma umas uns usa usarNEWLINENEWLINEvai vais valor veja vem vens ver verdade verdadeiro vez vezes viagem vindoNEWLINEvinte você vocês vos vossa vossas vosso vossos vários vão vêm vósNEWLINENEWLINEzeroNEWLINE""".split())NEWLINE
# Copyright 2014-2015 Robert Jordens <jordens@gmail.com>NEWLINE#NEWLINE# This file is part of redpid.NEWLINE#NEWLINE# redpid is free software: you can redistribute it and/or modifyNEWLINE# it under the terms of the GNU General Public License as published byNEWLINE# the Free Software Foundation, either version 3 of the License, orNEWLINE# (at your option) any later version.NEWLINE#NEWLINE# redpid is distributed in the hope that it will be useful,NEWLINE# but WITHOUT ANY WARRANTY; without even the implied warranty ofNEWLINE# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See theNEWLINE# GNU General Public License for more details.NEWLINE#NEWLINE# You should have received a copy of the GNU General Public LicenseNEWLINE# along with redpid. If not, see <http://www.gnu.org/licenses/>.NEWLINENEWLINEfrom functools import reduceNEWLINEfrom operator import or_NEWLINENEWLINEfrom migen import *NEWLINEfrom misoc.interconnect import csr_bus, wishboneNEWLINENEWLINENEWLINEsys_layout = [NEWLINE ("rstn", 1, DIR_M_TO_S),NEWLINE ("clk", 1, DIR_M_TO_S),NEWLINE ("addr", 32, DIR_M_TO_S),NEWLINE ("wdata", 32, DIR_M_TO_S),NEWLINE ("sel", 4, DIR_M_TO_S),NEWLINE ("wen", 1, DIR_M_TO_S),NEWLINE ("ren", 1, DIR_M_TO_S),NEWLINE ("rdata", 32, DIR_S_TO_M),NEWLINE ("err", 1, DIR_S_TO_M),NEWLINE ("ack", 1, DIR_S_TO_M),NEWLINE]NEWLINENEWLINENEWLINEaxi_layout = [NEWLINE ("arvalid", 1),NEWLINE ("awvalid", 1),NEWLINE ("bready", 1),NEWLINE ("rready", 1),NEWLINE ("wlast", 1),NEWLINE ("wvalid", 1),NEWLINE ("arid", 12),NEWLINE ("awid", 12),NEWLINE ("wid", 12),NEWLINE ("arburst", 2),NEWLINE ("arlock", 2),NEWLINE ("arsize", 3),NEWLINE ("awburst", 2),NEWLINE ("awlock", 2),NEWLINE ("awsize", 3),NEWLINE ("arprot", 3),NEWLINE ("awprot", 3),NEWLINE ("araddr", 32),NEWLINE ("awaddr", 32),NEWLINE ("wdata", 32),NEWLINE ("arcache", 4),NEWLINE ("arlen", 4),NEWLINE ("arqos", 4),NEWLINE ("awcache", 4),NEWLINE ("awlen", 4),NEWLINE ("awqos", 4),NEWLINE ("wstrb", 4),NEWLINE ("aclk", 1),NEWLINE ("arready", 1),NEWLINE ("awready", 1),NEWLINE ("bvalid", 1),NEWLINE ("rlast", 1),NEWLINE ("rvalid", 1),NEWLINE ("wready", 1),NEWLINE ("bid", 12),NEWLINE ("rid", 12),NEWLINE ("bresp", 2),NEWLINE ("rresp", 2),NEWLINE ("rdata", 32),NEWLINE ("arstn", 1),NEWLINE]NEWLINENEWLINENEWLINEclass PitayaPS(Module):NEWLINE def __init__(self, cpu):NEWLINE self.fclk = Signal(4)NEWLINE self.frstn = Signal(4)NEWLINENEWLINE ###NEWLINENEWLINE self.submodules.axi = Axi2Sys()NEWLINE axi = self.axi.axiNEWLINE self.comb += [NEWLINE axi.aclk.eq(self.fclk[0]),NEWLINE axi.arstn.eq(self.frstn[0]),NEWLINE ]NEWLINENEWLINE self.specials += Instance("system_processing_system7_0_0",NEWLINE io_MIO=cpu.mio,NEWLINENEWLINE io_PS_CLK=cpu.ps_clk,NEWLINE io_PS_PORB=cpu.ps_porb,NEWLINE io_PS_SRSTB=cpu.ps_srstb,NEWLINENEWLINE io_DDR_Addr=cpu.DDR_addr,NEWLINE io_DDR_BankAddr=cpu.DDR_ba,NEWLINE io_DDR_CAS_n=cpu.DDR_cas_n,NEWLINE io_DDR_Clk_n=cpu.DDR_ck_n,NEWLINE io_DDR_Clk=cpu.DDR_ck_p,NEWLINE io_DDR_CKE=cpu.DDR_cke,NEWLINE io_DDR_CS_n=cpu.DDR_cs_n,NEWLINE io_DDR_DM=cpu.DDR_dm,NEWLINE io_DDR_DQ=cpu.DDR_dq,NEWLINE io_DDR_DQS_n=cpu.DDR_dqs_n,NEWLINE io_DDR_DQS=cpu.DDR_dqs_p,NEWLINE io_DDR_ODT=cpu.DDR_odt,NEWLINE io_DDR_RAS_n=cpu.DDR_ras_n,NEWLINE io_DDR_DRSTB=cpu.DDR_reset_n,NEWLINE io_DDR_WEB=cpu.DDR_we_n,NEWLINE io_DDR_VRN=cpu.ddr_vrn,NEWLINE io_DDR_VRP=cpu.ddr_vrp,NEWLINENEWLINE o_FCLK_CLK0=self.fclk[0],NEWLINE o_FCLK_CLK1=self.fclk[1],NEWLINE o_FCLK_CLK2=self.fclk[2],NEWLINE o_FCLK_CLK3=self.fclk[3],NEWLINE o_FCLK_RESET0_N=self.frstn[0],NEWLINE o_FCLK_RESET1_N=self.frstn[1],NEWLINE o_FCLK_RESET2_N=self.frstn[2],NEWLINE o_FCLK_RESET3_N=self.frstn[3],NEWLINENEWLINE i_M_AXI_GP0_ACLK=axi.aclk,NEWLINE o_M_AXI_GP0_ARVALID=axi.arvalid,NEWLINE o_M_AXI_GP0_AWVALID=axi.awvalid,NEWLINE o_M_AXI_GP0_BREADY=axi.bready,NEWLINE o_M_AXI_GP0_RREADY=axi.rready,NEWLINE o_M_AXI_GP0_WLAST=axi.wlast,NEWLINE o_M_AXI_GP0_WVALID=axi.wvalid,NEWLINE o_M_AXI_GP0_ARID=axi.arid,NEWLINE o_M_AXI_GP0_AWID=axi.awid,NEWLINE o_M_AXI_GP0_WID=axi.wid,NEWLINE o_M_AXI_GP0_ARBURST=axi.arburst,NEWLINE o_M_AXI_GP0_ARLOCK=axi.arlock,NEWLINE o_M_AXI_GP0_ARSIZE=axi.arsize,NEWLINE o_M_AXI_GP0_AWBURST=axi.awburst,NEWLINE o_M_AXI_GP0_AWLOCK=axi.awlock,NEWLINE o_M_AXI_GP0_AWSIZE=axi.awsize,NEWLINE o_M_AXI_GP0_ARPROT=axi.arprot,NEWLINE o_M_AXI_GP0_AWPROT=axi.awprot,NEWLINE o_M_AXI_GP0_ARADDR=axi.araddr,NEWLINE o_M_AXI_GP0_AWADDR=axi.awaddr,NEWLINE o_M_AXI_GP0_WDATA=axi.wdata,NEWLINE o_M_AXI_GP0_ARCACHE=axi.arcache,NEWLINE o_M_AXI_GP0_ARLEN=axi.arlen,NEWLINE o_M_AXI_GP0_ARQOS=axi.arqos,NEWLINE o_M_AXI_GP0_AWCACHE=axi.awcache,NEWLINE o_M_AXI_GP0_AWLEN=axi.awlen,NEWLINE o_M_AXI_GP0_AWQOS=axi.awqos,NEWLINE o_M_AXI_GP0_WSTRB=axi.wstrb,NEWLINE i_M_AXI_GP0_ARREADY=axi.arready,NEWLINE i_M_AXI_GP0_AWREADY=axi.awready,NEWLINE i_M_AXI_GP0_BVALID=axi.bvalid,NEWLINE i_M_AXI_GP0_RLAST=axi.rlast,NEWLINE i_M_AXI_GP0_RVALID=axi.rvalid,NEWLINE i_M_AXI_GP0_WREADY=axi.wready,NEWLINE i_M_AXI_GP0_BID=axi.bid,NEWLINE i_M_AXI_GP0_RID=axi.rid,NEWLINE i_M_AXI_GP0_BRESP=axi.bresp,NEWLINE i_M_AXI_GP0_RRESP=axi.rresp,NEWLINE i_M_AXI_GP0_RDATA=axi.rdata,NEWLINENEWLINE i_SPI0_SS_I=0,NEWLINE #i_SPI0_SS_I=spi.ss_i,NEWLINE #o_SPI0_SS_O=spi.ss_o,NEWLINE #o_SPI0_SS_T=spi.ss_t,NEWLINE #o_SPI0_SS1_O=spi.ss1_o,NEWLINE #o_SPI0_SS2_O=spi.ss2_o,NEWLINE i_SPI0_SCLK_I=0,NEWLINE #i_SPI0_SCLK_I=spi.sclk_i,NEWLINE #o_SPI0_SCLK_O=spi.sclk_o,NEWLINE #o_SPI0_SCLK_T=spi.sclk_t,NEWLINE i_SPI0_MOSI_I=0,NEWLINE #i_SPI0_MOSI_I=spi.mosi_i,NEWLINE #o_SPI0_MOSI_O=spi.mosi_o,NEWLINE #o_SPI0_MOSI_T=spi.mosi_t,NEWLINE i_SPI0_MISO_I=0,NEWLINE #i_SPI0_MISO_I=spi.miso_i,NEWLINE #o_SPI0_MISO_O=spi.miso_o,NEWLINE #o_SPI0_MISO_T=spi.miso_t,NEWLINENEWLINE i_USB0_VBUS_PWRFAULT=0,NEWLINE )NEWLINENEWLINENEWLINEclass Axi2Sys(Module):NEWLINE def __init__(self):NEWLINE self.sys = Record(sys_layout)NEWLINE self.axi = Record(axi_layout)NEWLINENEWLINE ###NEWLINENEWLINE self.comb += [NEWLINE self.sys.clk.eq(self.axi.aclk),NEWLINE self.sys.rstn.eq(self.axi.arstn)NEWLINE ]NEWLINENEWLINE self.specials += Instance("axi_slave",NEWLINE p_AXI_DW=32,NEWLINE p_AXI_AW=32,NEWLINE p_AXI_IW=12,NEWLINENEWLINE i_axi_clk_i=self.axi.aclk,NEWLINE i_axi_rstn_i=self.axi.arstn,NEWLINENEWLINE i_axi_awid_i=self.axi.awid,NEWLINE i_axi_awaddr_i=self.axi.awaddr,NEWLINE i_axi_awlen_i=self.axi.awlen,NEWLINE i_axi_awsize_i=self.axi.awsize,NEWLINE i_axi_awburst_i=self.axi.awburst,NEWLINE i_axi_awlock_i=self.axi.awlock,NEWLINE i_axi_awcache_i=self.axi.awcache,NEWLINE i_axi_awprot_i=self.axi.awprot,NEWLINE i_axi_awvalid_i=self.axi.awvalid,NEWLINE o_axi_awready_o=self.axi.awready,NEWLINENEWLINE i_axi_wid_i=self.axi.wid,NEWLINE i_axi_wdata_i=self.axi.wdata,NEWLINE i_axi_wstrb_i=self.axi.wstrb,NEWLINE i_axi_wlast_i=self.axi.wlast,NEWLINE i_axi_wvalid_i=self.axi.wvalid,NEWLINE o_axi_wready_o=self.axi.wready,NEWLINENEWLINE o_axi_bid_o=self.axi.bid,NEWLINE o_axi_bresp_o=self.axi.bresp,NEWLINE o_axi_bvalid_o=self.axi.bvalid,NEWLINE i_axi_bready_i=self.axi.bready,NEWLINENEWLINE i_axi_arid_i=self.axi.arid,NEWLINE i_axi_araddr_i=self.axi.araddr,NEWLINE i_axi_arlen_i=self.axi.arlen,NEWLINE i_axi_arsize_i=self.axi.arsize,NEWLINE i_axi_arburst_i=self.axi.arburst,NEWLINE i_axi_arlock_i=self.axi.arlock,NEWLINE i_axi_arcache_i=self.axi.arcache,NEWLINE i_axi_arprot_i=self.axi.arprot,NEWLINE i_axi_arvalid_i=self.axi.arvalid,NEWLINE o_axi_arready_o=self.axi.arready,NEWLINENEWLINE o_axi_rid_o=self.axi.rid,NEWLINE o_axi_rdata_o=self.axi.rdata,NEWLINE o_axi_rresp_o=self.axi.rresp,NEWLINE o_axi_rlast_o=self.axi.rlast,NEWLINE o_axi_rvalid_o=self.axi.rvalid,NEWLINE i_axi_rready_i=self.axi.rready,NEWLINENEWLINE o_sys_addr_o=self.sys.addr,NEWLINE o_sys_wdata_o=self.sys.wdata,NEWLINE o_sys_sel_o=self.sys.sel,NEWLINE o_sys_wen_o=self.sys.wen,NEWLINE o_sys_ren_o=self.sys.ren,NEWLINE i_sys_rdata_i=self.sys.rdata,NEWLINE i_sys_err_i=self.sys.err,NEWLINE i_sys_ack_i=self.sys.ack,NEWLINE )NEWLINENEWLINENEWLINEclass SysInterconnect(Module):NEWLINE def __init__(self, master, *slaves):NEWLINE cs = Signal(max=len(slaves))NEWLINE self.comb += cs.eq(master.addr[20:23])NEWLINE rets = []NEWLINE for i, s in enumerate(slaves):NEWLINE sel = Signal()NEWLINE self.comb += [NEWLINE sel.eq(cs == i),NEWLINE s.clk.eq(master.clk),NEWLINE s.rstn.eq(master.rstn),NEWLINE s.addr.eq(master.addr),NEWLINE s.wdata.eq(master.wdata),NEWLINE s.sel.eq(master.sel),NEWLINE s.wen.eq(sel & master.wen),NEWLINE s.ren.eq(sel & master.ren),NEWLINE ]NEWLINE ret = Cat(s.err, s.ack, s.rdata)NEWLINE rets.append(Replicate(sel, len(ret)) & ret)NEWLINE self.comb += Cat(master.err, master.ack, master.rdata).eq(NEWLINE reduce(or_, rets))NEWLINENEWLINENEWLINEclass Sys2Wishbone(Module):NEWLINE def __init__(self):NEWLINE self.wishbone = wb = wishbone.Interface()NEWLINE self.sys = sys = Record(sys_layout)NEWLINENEWLINE ###NEWLINENEWLINE sys2 = Record(sys_layout)NEWLINENEWLINE self.specials += Instance("bus_clk_bridge",NEWLINE i_sys_clk_i=sys.clk, i_sys_rstn_i=sys.rstn,NEWLINE i_sys_addr_i=sys.addr, i_sys_wdata_i=sys.wdata,NEWLINE i_sys_sel_i=sys.sel, i_sys_wen_i=sys.wen,NEWLINE i_sys_ren_i=sys.ren, o_sys_rdata_o=sys.rdata,NEWLINE o_sys_err_o=sys.err, o_sys_ack_o=sys.ack,NEWLINENEWLINE i_clk_i=ClockSignal(), i_rstn_i=~ResetSignal(),NEWLINE o_addr_o=sys2.addr, o_wen_o=sys2.wen, o_ren_o=sys2.ren,NEWLINE o_wdata_o=sys2.wdata, i_rdata_i=sys2.rdata,NEWLINE i_err_i=sys2.err, i_ack_i=sys2.ackNEWLINE )NEWLINE self.sync += [NEWLINE If(sys2.ren | sys2.wen,NEWLINE wb.cyc.eq(1),NEWLINE wb.adr.eq(sys2.addr[2:]),NEWLINE wb.we.eq(sys2.wen),NEWLINE wb.dat_w.eq(sys2.wdata)NEWLINE ).Elif(wb.ack,NEWLINE wb.cyc.eq(0)NEWLINE )NEWLINE ]NEWLINE self.comb += [NEWLINE wb.stb.eq(wb.cyc),NEWLINE sys2.rdata.eq(wb.dat_r),NEWLINE sys2.ack.eq(wb.ack),NEWLINE sys2.err.eq(wb.err)NEWLINE ]NEWLINENEWLINENEWLINEclass SysCDC(Module):NEWLINE def __init__(self, cd_target="sys"):NEWLINE self.source = Record(sys_layout)NEWLINE self.target = Record(sys_layout)NEWLINENEWLINE self.specials += Instance("bus_clk_bridge",NEWLINE i_sys_clk_i=self.source.clk, i_sys_rstn_i=self.source.rstn,NEWLINE i_sys_addr_i=self.source.addr, i_sys_wdata_i=self.source.wdata,NEWLINE i_sys_sel_i=self.source.sel, i_sys_wen_i=self.source.wen,NEWLINE i_sys_ren_i=self.source.ren, o_sys_rdata_o=self.source.rdata,NEWLINE o_sys_err_o=self.source.err, o_sys_ack_o=self.source.ack,NEWLINENEWLINE i_clk_i=self.target.clk, i_rstn_i=self.target.rstn,NEWLINE o_addr_o=self.target.addr, o_wdata_o=self.target.wdata,NEWLINE o_wen_o=self.target.wen,NEWLINE o_ren_o=self.target.ren, i_rdata_i=self.target.rdata,NEWLINE i_err_i=self.target.err, i_ack_i=self.target.ackNEWLINE )NEWLINE self.comb += [NEWLINE self.target.clk.eq(ClockSignal(cd_target)),NEWLINE self.target.rstn.eq(~ResetSignal(cd_target))NEWLINE ]NEWLINENEWLINENEWLINEclass Sys2CSR(Module):NEWLINE def __init__(self):NEWLINE self.csr = csr_bus.Interface()NEWLINE self.sys = Record(sys_layout)NEWLINENEWLINE ###NEWLINENEWLINE stb = Signal()NEWLINE self.sync += [NEWLINE stb.eq(self.sys.wen | self.sys.ren),NEWLINE self.csr.adr.eq(self.sys.addr[2:]),NEWLINE self.csr.we.eq(self.sys.wen),NEWLINE self.csr.dat_w.eq(self.sys.wdata),NEWLINE self.sys.ack.eq(stb),NEWLINE self.sys.rdata.eq(self.csr.dat_r)NEWLINE ]NEWLINE
# Author: Nathan Trouvain at 27/09/2021 <nathan.trouvain@inria.fr>NEWLINE# Licence: MIT LicenseNEWLINE# Copyright: Xavier Hinaut (2018) <xavier.hinaut@inria.fr>NEWLINEimport numpy as npNEWLINENEWLINEfrom ...node import NodeNEWLINEfrom ...utils.validation import add_bias, check_vectorNEWLINENEWLINENEWLINEdef _initialize_readout(NEWLINE readout, x=None, y=None, init_func=None, bias_init=None, bias=TrueNEWLINE):NEWLINENEWLINE if x is not None:NEWLINENEWLINE in_dim = x.shape[1]NEWLINENEWLINE if readout.output_dim is not None:NEWLINE out_dim = readout.output_dimNEWLINE elif y is not None:NEWLINE out_dim = y.shape[1]NEWLINE else:NEWLINE raise RuntimeError(NEWLINE f"Impossible to initialize {readout.name}: "NEWLINE f"output dimension was not specified at "NEWLINE f"creation, and no teacher vector was given."NEWLINE )NEWLINENEWLINE readout.set_input_dim(in_dim)NEWLINE readout.set_output_dim(out_dim)NEWLINENEWLINE if callable(init_func):NEWLINE W = init_func(in_dim, out_dim, dtype=readout.dtype)NEWLINE elif isinstance(init_func, np.ndarray):NEWLINE W = (NEWLINE check_vector(init_func, caller=readout)NEWLINE .reshape(readout.input_dim, readout.output_dim)NEWLINE .astype(readout.dtype)NEWLINE )NEWLINE else:NEWLINE raise ValueError(NEWLINE f"Data type {type(init_func)} not "NEWLINE f"understood for matrix initializer "NEWLINE f"'Wout'. It should be an array or "NEWLINE f"a callable returning an array."NEWLINE )NEWLINENEWLINE if bias:NEWLINE if callable(bias_init):NEWLINE bias = bias_init(1, out_dim, dtype=readout.dtype)NEWLINE elif isinstance(bias_init, np.ndarray):NEWLINE bias = (NEWLINE check_vector(bias_init)NEWLINE .reshape(1, readout.output_dim)NEWLINE .astype(readout.dtype)NEWLINE )NEWLINE else:NEWLINE raise ValueError(NEWLINE f"Data type {type(bias_init)} not "NEWLINE f"understood for matrix initializer "NEWLINE f"'bias'. It should be an array or "NEWLINE f"a callable returning an array."NEWLINE )NEWLINE else:NEWLINE bias = np.zeros((1, out_dim), dtype=readout.dtype)NEWLINENEWLINE readout.set_param("Wout", W)NEWLINE readout.set_param("bias", bias)NEWLINENEWLINENEWLINEdef _prepare_inputs_for_learning(X=None, Y=None, bias=True, allow_reshape=False):NEWLINE if X is not None:NEWLINENEWLINE if bias:NEWLINE X = add_bias(X)NEWLINE if not isinstance(X, np.ndarray):NEWLINE X = np.vstack(X)NEWLINENEWLINE X = check_vector(X, allow_reshape=allow_reshape)NEWLINENEWLINE if Y is not None:NEWLINENEWLINE if not isinstance(Y, np.ndarray):NEWLINE Y = np.vstack(Y)NEWLINENEWLINE Y = check_vector(Y, allow_reshape=allow_reshape)NEWLINENEWLINE return X, YNEWLINENEWLINENEWLINEdef readout_forward(node: Node, x):NEWLINE return (node.Wout.T @ x.reshape(-1, 1) + node.bias.T).TNEWLINENEWLINENEWLINEdef _assemble_wout(Wout, bias, has_bias=True):NEWLINE wo = WoutNEWLINE if has_bias:NEWLINE wo = np.r_[bias, wo]NEWLINE return woNEWLINENEWLINENEWLINEdef _split_and_save_wout(node, wo):NEWLINE if node.input_bias:NEWLINE Wout, bias = wo[1:, :], wo[0, :][np.newaxis, :]NEWLINE node.set_param("Wout", Wout)NEWLINE node.set_param("bias", bias)NEWLINE else:NEWLINE node.set_param("Wout", wo)NEWLINENEWLINENEWLINEdef _compute_error(node, x, y=None):NEWLINE """Error between target and prediction."""NEWLINE prediction = node.state()NEWLINE error = prediction - yNEWLINE return error, x.TNEWLINE
import argparseNEWLINEimport osNEWLINEimport os.path as ospNEWLINENEWLINEimport cv2NEWLINEimport numpy as npNEWLINENEWLINENEWLINEdef flow_to_img(raw_flow, bound=20.):NEWLINE """Convert flow to gray image.NEWLINENEWLINE Args:NEWLINE raw_flow (np.ndarray[float]): Estimated flow with the shape (w, h).NEWLINE bound (float): Bound for the flow-to-image normalization. Default: 20.NEWLINENEWLINE Returns:NEWLINE np.ndarray[uint8]: The result list of np.ndarray[uint8], with shapeNEWLINE (w, h).NEWLINE """NEWLINE flow = np.clip(raw_flow, -bound, bound)NEWLINE flow += boundNEWLINE flow *= (255 / float(2 * bound))NEWLINE flow = flow.astype(np.uint8)NEWLINE return flowNEWLINENEWLINENEWLINEdef generate_flow(frames, method='tvl1'):NEWLINE """Estimate flow with given frames.NEWLINENEWLINE Args:NEWLINE frames (list[np.ndarray[uint8]]): List of rgb frames, with shapeNEWLINE (w, h, 3).NEWLINE method (str): Use which method to generate flow. Options are 'tvl1'NEWLINE and 'farneback'. Default: 'tvl1'.NEWLINENEWLINE Returns:NEWLINE list[np.ndarray[float]]: The result list of np.ndarray[float], withNEWLINE shape (w, h, 2).NEWLINE """NEWLINE assert method in ['tvl1', 'farneback']NEWLINE gray_frames = [cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) for frame in frames]NEWLINENEWLINE if method == 'tvl1':NEWLINE tvl1 = cv2.optflow.DualTVL1OpticalFlow_create()NEWLINENEWLINE def op(x, y):NEWLINE return tvl1.calc(x, y, None)NEWLINE elif method == 'farneback':NEWLINENEWLINE def op(x, y):NEWLINE return cv2.calcOpticalFlowFarneback(x, y, None, 0.5, 3, 15, 3, 5,NEWLINE 1.2, 0)NEWLINENEWLINE gray_st = gray_frames[:-1]NEWLINE gray_ed = gray_frames[1:]NEWLINENEWLINE flow = [op(x, y) for x, y in zip(gray_st, gray_ed)]NEWLINE return flowNEWLINENEWLINENEWLINEdef extract_dense_flow(path,NEWLINE dest,NEWLINE bound=20.,NEWLINE save_rgb=False,NEWLINE start_idx=0,NEWLINE rgb_tmpl='img_{:05d}.jpg',NEWLINE flow_tmpl='{}_{:05d}.jpg',NEWLINE method='tvl1'):NEWLINE """Extract dense flow given video or frames, save them as gray-scaleNEWLINE images.NEWLINENEWLINE Args:NEWLINE path (str): Location of the input video.NEWLINE dest (str): The directory to store the extracted flow images.NEWLINE bound (float): Bound for the flow-to-image normalization. Default: 20.NEWLINE save_rgb (bool): Save extracted RGB frames. Default: False.NEWLINE start_idx (int): The starting frame index if use frames as input, theNEWLINE first image is path.format(start_idx). Default: 0.NEWLINE rgb_tmpl (str): The template of RGB frame names, Default:NEWLINE 'img_{:05d}.jpg'.NEWLINE flow_tmpl (str): The template of Flow frame names, Default:NEWLINE '{}_{:05d}.jpg'.NEWLINE method (str): Use which method to generate flow. Options are 'tvl1'NEWLINE and 'farneback'. Default: 'tvl1'.NEWLINE """NEWLINENEWLINE frames = []NEWLINE assert osp.exists(path)NEWLINE video = cv2.VideoCapture(path)NEWLINE flag, f = video.read()NEWLINE while flag:NEWLINE frames.append(f)NEWLINE flag, f = video.read()NEWLINENEWLINE flow = generate_flow(frames, method=method)NEWLINENEWLINE flow_x = [flow_to_img(x[:, :, 0], bound) for x in flow]NEWLINE flow_y = [flow_to_img(x[:, :, 1], bound) for x in flow]NEWLINENEWLINE if not osp.exists(dest):NEWLINE os.system('mkdir -p ' + dest)NEWLINE flow_x_names = [NEWLINE osp.join(dest, flow_tmpl.format('x', ind + start_idx))NEWLINE for ind in range(len(flow_x))NEWLINE ]NEWLINE flow_y_names = [NEWLINE osp.join(dest, flow_tmpl.format('y', ind + start_idx))NEWLINE for ind in range(len(flow_y))NEWLINE ]NEWLINENEWLINE num_frames = len(flow)NEWLINE for i in range(num_frames):NEWLINE cv2.imwrite(flow_x_names[i], flow_x[i])NEWLINE cv2.imwrite(flow_y_names[i], flow_y[i])NEWLINENEWLINE if save_rgb:NEWLINE img_names = [NEWLINE osp.join(dest, rgb_tmpl.format(ind + start_idx))NEWLINE for ind in range(len(frames))NEWLINE ]NEWLINE for frame, name in zip(frames, img_names):NEWLINE cv2.imwrite(name, frame)NEWLINENEWLINENEWLINEdef parse_args():NEWLINE parser = argparse.ArgumentParser(description='Extract flow and RGB images')NEWLINE parser.add_argument(NEWLINE '--input',NEWLINE help='videos for frame extraction, can be'NEWLINE 'single video or a video list, the video list should be a txt file 'NEWLINE 'and just consists of filenames without directories')NEWLINE parser.add_argument(NEWLINE '--prefix',NEWLINE default='',NEWLINE help='the prefix of input 'NEWLINE 'videos, used when input is a video list')NEWLINE parser.add_argument(NEWLINE '--dest',NEWLINE default='',NEWLINE help='the destination to save 'NEWLINE 'extracted frames')NEWLINE parser.add_argument(NEWLINE '--save-rgb', action='store_true', help='also save 'NEWLINE 'rgb frames')NEWLINE parser.add_argument(NEWLINE '--rgb-tmpl',NEWLINE default='img_{:05d}.jpg',NEWLINE help='template filename of rgb frames')NEWLINE parser.add_argument(NEWLINE '--flow-tmpl',NEWLINE default='{}_{:05d}.jpg',NEWLINE help='template filename of flow frames')NEWLINE parser.add_argument(NEWLINE '--start-idx',NEWLINE type=int,NEWLINE default=1,NEWLINE help='the start 'NEWLINE 'index of extracted frames')NEWLINE parser.add_argument(NEWLINE '--method',NEWLINE default='tvl1',NEWLINE help='use which method to 'NEWLINE 'generate flow')NEWLINE parser.add_argument(NEWLINE '--bound', type=float, default=20, help='maximum of 'NEWLINE 'optical flow')NEWLINENEWLINE args = parser.parse_args()NEWLINE return argsNEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE args = parse_args()NEWLINE if args.input.endswith('.txt'):NEWLINE lines = open(args.input).readlines()NEWLINE lines = [x.strip() for x in lines]NEWLINE videos = [osp.join(args.prefix, x) for x in lines]NEWLINE dests = [osp.join(args.dest, x.split('.')[0]) for x in lines]NEWLINE for video, dest in zip(videos, dests):NEWLINE extract_dense_flow(video, dest, args.bound, args.save_rgb,NEWLINE args.start_idx, args.rgb_tmpl, args.flow_tmpl,NEWLINE args.method)NEWLINE else:NEWLINE extract_dense_flow(args.input, args.dest, args.bound, args.save_rgb,NEWLINE args.start_idx, args.rgb_tmpl, args.flow_tmpl,NEWLINE args.method)NEWLINE
from dataclasses import dataclassNEWLINENEWLINENEWLINE@dataclassNEWLINEclass UserEntity:NEWLINE id: intNEWLINE username: strNEWLINE email: strNEWLINENEWLINE def get_id(self):NEWLINE return self.idNEWLINENEWLINE def get_user_id(self):NEWLINE return self.idNEWLINENEWLINE @propertyNEWLINE def is_authenticated(self):NEWLINE return TrueNEWLINENEWLINE @propertyNEWLINE def is_active(self):NEWLINE return TrueNEWLINENEWLINE @propertyNEWLINE def is_anonymous(self):NEWLINE return self.id is NoneNEWLINENEWLINE @classmethodNEWLINE def from_dict(cls, a_dict=None, **kwargs):NEWLINE if a_dict is None:NEWLINE a_dict = kwargsNEWLINENEWLINE return cls(**a_dict)NEWLINENEWLINE def to_dict(self):NEWLINE return dict(id=self.id, username=self.username, email=self.email)NEWLINE
"""NEWLINEImplementation of custom solvers: advection equation with forward-time, backward-space; Burgers' equation withNEWLINEMacCormack scheme and Korteweg-de Vries equation with Zabusky and Kruska scheme.NEWLINE"""NEWLINEimport numpy as npNEWLINEimport matplotlib.pyplot as pltNEWLINEimport matplotlib as mplNEWLINEimport sympy as spNEWLINEimport warningsNEWLINENEWLINENEWLINE# enable pgf printing of solution plotNEWLINEmpl.use("pgf")NEWLINEpgf_with_custom_preamble = {NEWLINE "font.family": "serif", # use serif/main font for text elementsNEWLINE "pgf.rcfonts": False,NEWLINE "text.usetex": True, # use inline math for ticksNEWLINE}NEWLINEmpl.rcParams.update(pgf_with_custom_preamble)NEWLINENEWLINENEWLINEclass FDgrid:NEWLINE """NEWLINE Class for initialization of the calculation domain and data storage;NEWLINE handles an arbitrary number of ghost cells 'n_ghost'NEWLINE """NEWLINE def __init__(self, x_nodes, n_t, x_min, x_max, u_max_convection, cfl, n_ghost):NEWLINE """NEWLINE Initializes the calculation domainNEWLINENEWLINE :param x_nodes: Number of points in domain OmegaNEWLINE :param n_t: Total number of time steps including IC t = 0NEWLINE :param x_min: left bound of OmegaNEWLINE :param x_max: right bound of OmegaNEWLINE :param u_max_convection: convection speed to calculate dt from cflNEWLINE :param cfl: cfl number of ICNEWLINE :param n_ghost: number of ghost cells for periodic BC needed by scheme (1 for advection and Burgers; 2 for KdV)NEWLINE """NEWLINENEWLINE self.n_x = x_nodes + n_ghost * 2 # ghost nodes at both sidesNEWLINE self.x_nodes = x_nodesNEWLINE self.n_t = n_tNEWLINE self.x_min = x_minNEWLINE self.x_max = x_maxNEWLINE self.n_ghost = n_ghostNEWLINE self.i_ghost_r = x_nodes + n_ghost # index of leftmost ghost node at right boundaryNEWLINE self.i_ghost_l = n_ghost - 1 # index of rightmost ghost node at left boundaryNEWLINE self.dx = (x_max - x_min) / x_nodes # save spatial widthNEWLINE self.dt = (cfl*self.dx)/u_max_convection # set dt according to desired cfl numberNEWLINE self.t_max = self.dt * (n_t - 1) # t = 0 is initial conditionNEWLINE self.grid = np.zeros((self.n_x, n_t), dtype=np.float64) # initialize array to store simulation resultsNEWLINENEWLINE def fill_BC(self, i_time):NEWLINE """fills ghost cells with periodic boundary conditions"""NEWLINE vect_to_set = np.zeros(self.n_x)NEWLINE # copies the data within the domain to a vectorNEWLINE vect_to_set[self.i_ghost_l + 1: self.i_ghost_r] = self.grid[self.i_ghost_l + 1: self.i_ghost_r, i_time]NEWLINE vect_to_set = set_periodic_BC(self, vect_to_set) # sets periodic BCs for vectorNEWLINE self.grid[:, i_time] = vect_to_set # copies filled vector back onto the gridNEWLINENEWLINENEWLINEdef set_periodic_BC(domain, vect):NEWLINE """Helper function called from 'fill_BC' to set the periodic BCs for arbitrary number of ghost cells"""NEWLINE for i in range(domain.n_ghost): # set all values for ghost cells, starting from left for both sidesNEWLINE # value of left ghost cell is value of most right real cellNEWLINE # leftmost left node is to be n_ghost nodes left of the leftmost right ghost nodeNEWLINE vect[i] = vect[domain.i_ghost_r - domain.n_ghost + i] # set left boundary elementNEWLINE # leftmost right ghost node is first real left nodeNEWLINE vect[domain.i_ghost_r + i] = vect[i + domain.n_ghost] # right boundaryNEWLINE return vectNEWLINENEWLINENEWLINEdef solve(x_nodes, n_t, initial_cond, equation, x_min=0., x_max=1., cfl=0.1, a=1., manufactured=False, s=None):NEWLINE """NEWLINENEWLINE :param x_nodes: Number of points in domain OmegaNEWLINE :param n_t: Total number of time steps including IC t = 0NEWLINE :param initial_cond: Numpy array containing the values of the IC; Dimension is x_nodesNEWLINE :param equation: String of equation to be solvedNEWLINE :param x_min: left bound of Omega (default=0.0)NEWLINE :param x_max: right bound of Omega (default=1.0)NEWLINE :param cfl: desired cfl number of IC (default=0.1)NEWLINE :param a: Advection speed; Only used if 'equation' == 'Advection' (default=1.0)NEWLINE :param manufactured: Whether the Method of Manufactured solution is to be calculated (forcing 's' will be applied)NEWLINE (default=False)NEWLINE :param s: Forcing Function of MMS (default=None)NEWLINE :return: FDgrid object containing the simulation results in FDgrid.grid and information about the discretizationNEWLINE """NEWLINENEWLINE # set up calculation domain:NEWLINE if equation == 'Advection':NEWLINE u_max_convection = aNEWLINE if a < 0.: warnings.warn('FTBS only implemented for a > 0: solver will not be stable')NEWLINE else: # for nonlinear equations: calculate maximum convection speed in cfl from initial conditionsNEWLINE u_max_convection = np.max(np.abs(initial_cond))NEWLINE n_ghost = 1 # for FTBS and MacCormackNEWLINE if equation == 'KdV':NEWLINE n_ghost = 2NEWLINE domain = FDgrid(x_nodes, n_t, x_min, x_max, u_max_convection, cfl, n_ghost) # initializes calculation domainNEWLINE domain.grid[domain.i_ghost_l + 1:domain.i_ghost_r, 0] = initial_cond # set ICNEWLINE domain.fill_BC(0) # sets ghost cells for ICNEWLINENEWLINE # initialize sympy variables to process forcing term used in MMSNEWLINE x_values = np.arange(x_min, x_max, domain.dx) # for evaluation of forcing functionNEWLINE x = sp.symbols('x')NEWLINE t = sp.symbols('t')NEWLINENEWLINE if equation == 'Advection': # solve advection u_t + a u_x = 0 using FTBSNEWLINE for i_t in range(1, n_t):NEWLINE for i_x in range(domain.i_ghost_l + 1, domain.i_ghost_r): # iterate domain without ghost cellsNEWLINE # FTBS for a > 0:NEWLINE # u_i^n+1 = u_i^n - cfl (u_i^n - u_i-1^n) ; cfl = a * t / dxNEWLINE domain.grid[i_x, i_t] = domain.grid[i_x, i_t - 1] - cfl * \NEWLINE (domain.grid[i_x, i_t - 1] - domain.grid[i_x - 1, i_t - 1])NEWLINE if manufactured: # add forcing from MMSNEWLINE time = (i_t - 1) * domain.dt # to evaluate source term for current time stepNEWLINE domain.grid[domain.i_ghost_l + 1:domain.i_ghost_r, i_t] += domain.dt * calculate_forcing_manufactured(NEWLINE x_values, x, t, s, time)NEWLINE domain.fill_BC(i_t)NEWLINENEWLINE elif equation == 'Burgers':NEWLINE # solve Burgers equation u_t + g_x = 0 ; g = u^2/2 using 2nd order scheme in time and space of Mac CormackNEWLINE u_predictor = np.zeros(domain.n_x) # initialize saving of predictor stepNEWLINE for i_t in range(1, n_t):NEWLINE time = (i_t - 1) * domain.dt # time for evaluation source termNEWLINENEWLINE # prediction step:NEWLINE for i_x in range(domain.i_ghost_l + 1, domain.i_ghost_r): # iterate domain without ghost cellsNEWLINE # u_i^n+1_pred = u_i^n - dt/dx(g_i+1^n - g_i^n)NEWLINE u_predictor[i_x] = domain.grid[i_x, i_t - 1] - (domain.dt / domain.dx) *\NEWLINE (0.5 * domain.grid[i_x + 1, i_t - 1] ** 2 - 0.5 * domain.grid[i_x, i_t - 1] ** 2)NEWLINE if manufactured: # add forcing from MMSNEWLINE u_predictor[domain.i_ghost_l + 1:domain.i_ghost_r] += domain.dt * calculate_forcing_manufactured(NEWLINE x_values, x, t, s, time)NEWLINE # set periodic BC for predictor; MacCormack only needs a single ghost cellNEWLINE u_predictor[domain.i_ghost_l] = u_predictor[domain.i_ghost_r - 1]NEWLINE u_predictor[domain.i_ghost_r] = u_predictor[domain.i_ghost_l + 1]NEWLINENEWLINE # correction step:NEWLINE for i_x in range(domain.i_ghost_l + 1, domain.i_ghost_r): # iterate domain without ghost cellsNEWLINE # u_i^n+1 = u_i^n - 0.5*(dt/dx) * ((g_i+1^n - g_i^n) + (g_i^n_pred - g_i-1^n_pred))NEWLINE domain.grid[i_x, i_t] = domain.grid[i_x, i_t - 1] - 0.5 * (domain.dt/domain.dx) * \NEWLINE ((0.5 * domain.grid[i_x + 1, i_t - 1] ** 2 - 0.5 * domain.grid[i_x, i_t - 1] ** 2) +NEWLINE (0.5 * u_predictor[i_x] ** 2 - 0.5 * u_predictor[i_x - 1] ** 2))NEWLINE if manufactured: # forcing needs to be evaluated at intermediate stepNEWLINE domain.grid[domain.i_ghost_l + 1:domain.i_ghost_r, i_t] += domain.dt * calculate_forcing_manufactured(NEWLINE x_values, x, t, s, time + 0.5*domain.dt)NEWLINENEWLINE domain.fill_BC(i_t)NEWLINENEWLINE elif equation == 'KdV':NEWLINE # solve KdV u_x + 6*uu_x + u_xxx = 0 using the explicit 2nd order scheme in space and time of Zabusky and KruskaNEWLINENEWLINE # use forward time scheme in first time step to generate data to use for central time steppingNEWLINE for i_x in range(domain.i_ghost_l + 1, domain.i_ghost_r):NEWLINE # u_j^k+1 = u_j^k - (dt/dx)*(u_j+1^k + u_j^k + u_j-1^k) * (u_j+1^k - u_j-1^k) -NEWLINE # 0.5 * dt/dx**3 * (u_j+2^k - 2 * u_j+1^k + 2 * u_j-1^k - u_j-2^k)NEWLINE domain.grid[i_x, 1] = domain.grid[i_x, 0] - (domain.dt/domain.dx) * (domain.grid[i_x + 1, 0] +NEWLINE domain.grid[i_x, 0] + domain.grid[i_x - 1, 0]) * 0.5 * (domain.grid[i_x + 1, 0]NEWLINE - domain.grid[i_x - 1, 0]) - 0.5 * (domain.dt / domain.dx ** 3) * \NEWLINE (domain.grid[i_x + 2, 0] - 2. * domain.grid[i_x + 1, 0] + 2. * domain.grid[i_x - 1, 0]NEWLINE - domain.grid[i_x - 2, 0])NEWLINE if manufactured: # add forcing for MMSNEWLINE domain.grid[domain.i_ghost_l + 1:domain.i_ghost_r, 1] += domain.dt * calculate_forcing_manufactured(NEWLINE x_values, x, t, s, 0.)NEWLINE domain.fill_BC(1)NEWLINENEWLINE # central time stepping from now onNEWLINE for i_t in range(2, n_t):NEWLINENEWLINE for i_x in range(domain.i_ghost_l + 1, domain.i_ghost_r):NEWLINE # u_j^k+1 = u_j^k-1 - 2 * (dt/dx) * (u_j+1^k + u_j^k + u_j-1^k) * (u_j+1^k - u_j-1^k) - dt / dx**3 *NEWLINE # (u_j+2^k - 2 * u_j+1^k + 2 * u_j-1^k - u_j-2^k)NEWLINE domain.grid[i_x, i_t] = domain.grid[i_x, i_t - 2] - 2. * (domain.dt / domain.dx) * \NEWLINE (domain.grid[i_x + 1, i_t - 1] + domain.grid[i_x, i_t - 1] +NEWLINE domain.grid[i_x - 1, i_t - 1]) * (domain.grid[i_x + 1, i_t - 1] -NEWLINE domain.grid[i_x - 1, i_t - 1]) - (domain.dt / (domain.dx ** 3)) * \NEWLINE (domain.grid[i_x + 2, i_t - 1] - 2. * domain.grid[i_x + 1, i_t - 1] +NEWLINE 2. * domain.grid[i_x - 1, i_t - 1] - domain.grid[i_x - 2, i_t - 1])NEWLINE if manufactured: # add forcing for MMSNEWLINE time = (i_t - 1) * domain.dtNEWLINE domain.grid[domain.i_ghost_l + 1:domain.i_ghost_r, i_t] += 2. * domain.dt * \NEWLINE calculate_forcing_manufactured(x_values, x, t, s, time)NEWLINE domain.fill_BC(i_t)NEWLINENEWLINE else: raise Exception('Equation not implemented! (or typo)')NEWLINENEWLINE return domainNEWLINENEWLINENEWLINEdef calculate_forcing_manufactured(x_values, x, t, s, time):NEWLINE """Calculates the forcing term for MMS from the source term; directly depends on time"""NEWLINE lam_s = sp.lambdify(x, s.subs({t: time}), modules=['numpy'])NEWLINE return lam_s(x_values)NEWLINENEWLINENEWLINEdef visualize(domain):NEWLINE """Function to plot the first and last time step of a simulation; to check if everything worked as expected"""NEWLINE tn = np.arange(0., domain.n_t * domain.dt, domain.dt) # array with all timestampsNEWLINE xn = np.arange(domain.x_min, domain.x_max, domain.dx) # array with all x_valuesNEWLINENEWLINE fig = plt.figure(figsize=(5., 3.3))NEWLINE colorlist = [(0., 101 / 256., 189 / 256., 1.), (227/256., 114/256., 34/256., 1.)]NEWLINENEWLINE for index, i in enumerate([0, domain.n_t-1]): # plot IC and last time stepNEWLINE subfig = fig.add_subplot(1, 1, 1)NEWLINE label = 't = ' + str(round(tn[i], 2))NEWLINE subfig.plot(xn, domain.grid[domain.i_ghost_l + 1:domain.i_ghost_r, i], label=label, color=colorlist[index])NEWLINE subfig.legend()NEWLINENEWLINE plt.xlabel('$x$')NEWLINE plt.ylabel('$u(x, t)$')NEWLINE plt.title('Time evolution of solution')NEWLINENEWLINE plt.savefig('transport-equation.png')NEWLINE plt.savefig('transport-equation.pgf')NEWLINE
import jsonNEWLINEimport osNEWLINEimport csvNEWLINEimport reNEWLINEimport pandas as pdNEWLINEimport pickleNEWLINEimport collectionsNEWLINEimport subprocessNEWLINENEWLINENEWLINEimport sdi_utils.gensolution as gsNEWLINEimport sdi_utils.set_logging as slogNEWLINEimport sdi_utils.textfield_parser as tfpNEWLINEimport sdi_utils.tprogress as tpNEWLINENEWLINENEWLINENEWLINEtry:NEWLINE apiNEWLINEexcept NameError:NEWLINE class api:NEWLINENEWLINE queue = list()NEWLINE class Message:NEWLINE def __init__(self, body=None, attributes=""):NEWLINE self.body = bodyNEWLINE self.attributes = attributesNEWLINENEWLINE def send(port, msg):NEWLINE if port == outports[1]['name'] :NEWLINE api.queue.append(msg)NEWLINE if port == outports[0]['name'] :NEWLINE #print(msg)NEWLINE passNEWLINENEWLINE def set_config(config):NEWLINE api.config = configNEWLINENEWLINE class config:NEWLINE ## Meta dataNEWLINE config_params = dict()NEWLINE tags = {'sdi_utils': '','pandas': ''}NEWLINE version = "0.1.0"NEWLINE operator_name = "word_frequency"NEWLINE operator_description = "Word Frequency"NEWLINE operator_description_long = "Calculates word frequency"NEWLINE add_readme = dict()NEWLINENEWLINE debug_mode = TrueNEWLINE config_params['debug_mode'] = {'title': 'Debug mode',NEWLINE 'description': 'Sending debug level information to log port',NEWLINE 'type': 'boolean'}NEWLINENEWLINE word_types = 'PROPN'NEWLINE config_params['word_types'] = {'title': 'Word types',NEWLINE 'description': 'Setting word type selection for delete',NEWLINE 'type': 'string'}NEWLINENEWLINE language_filter = 'None'NEWLINE config_params['language_filter'] = {'title': 'Language filter', 'description': 'Filter for languages of media.',NEWLINE 'type': 'string'}NEWLINENEWLINENEWLINEdef process(msg):NEWLINENEWLINE att_dict = msg.attributesNEWLINENEWLINE logger, log_stream = slog.set_logging('word_regex', api.config.debug_mode)NEWLINE logger.info("Main Process started. Logging level: {}".format(logger.level))NEWLINE time_monitor = tp.progress()NEWLINENEWLINE df = msg.bodyNEWLINENEWLINE if not isinstance(df, pd.DataFrame) or df.empty:NEWLINE logger.warning('Empty dataframe, no output send!')NEWLINE api.send(outports[0]['name'], log_stream.getvalue())NEWLINE api.send(outports[2]['name'], api.Message(attributes=att_dict, body=df))NEWLINE return 0NEWLINENEWLINE df['count'] = df['count'].astype('int32')NEWLINENEWLINE # word typeNEWLINE word_types = tfp.read_list(api.config.word_types)NEWLINE if word_types :NEWLINE df = df.loc[df['type'].isin(word_types)]NEWLINENEWLINE # Language filterNEWLINE language_filter = tfp.read_list(api.config.language_filter)NEWLINE if language_filter :NEWLINE df = df.loc[df['language'].isin(language_filter)]NEWLINENEWLINE df = df.groupby(['language','type','word'])['count'].agg('sum').reset_index()NEWLINENEWLINE api.send(outports[1]['name'], api.Message(attributes=att_dict, body=df))NEWLINE api.send(outports[0]['name'],log_stream.getvalue())NEWLINENEWLINENEWLINEinports = [{'name': 'words', 'type': 'message.DataFrame', "description": "Message table."}]NEWLINEoutports = [{'name': 'log', 'type': 'string', "description": "Logging data"}, \NEWLINE {'name': 'data', 'type': 'message.DataFrame', "description": "Table after regex"}]NEWLINENEWLINE#api.set_port_callback(inports[0]['name'], process)NEWLINENEWLINENEWLINEdef test_operator():NEWLINENEWLINE config = api.configNEWLINE config.debug_mode = TrueNEWLINE config.test_mode = FalseNEWLINE config.language_filter = 'None'NEWLINE config.word_types = 'None'NEWLINE api.set_config(config)NEWLINENEWLINE doc_file = '/Users/Shared/data/onlinemedia/data/word_extraction.csv'NEWLINE df = pd.read_csv(doc_file,sep=',',nrows=10000000)NEWLINE msg = api.Message(attributes={'file': {'path': doc_file},'format':'pandas'}, body=df)NEWLINE process(msg)NEWLINENEWLINE out_file = '/Users/Shared/data/onlinemedia/data/word_freq_test.csv'NEWLINE df_list = [d.body for d in api.queue]NEWLINE pd.concat(df_list).to_csv(out_file,index=False)NEWLINENEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE #test_operator()NEWLINENEWLINE if True :NEWLINE subprocess.run(["rm",'-r','/Users/d051079/OneDrive - SAP SE/GitHub/di_textanalysis/solution/operators/textanalysis_' + api.config.version])NEWLINE gs.gensolution(os.path.realpath(__file__), api.config, inports, outports)NEWLINE solution_name = api.config.operator_name+'_'+api.config.versionNEWLINE subprocess.run(["vctl", "solution", "bundle", '/Users/d051079/OneDrive - SAP SE/GitHub/di_textanalysis/solution/operators/textanalysis_' + api.config.version,\NEWLINE "-t", solution_name])NEWLINE subprocess.run(["mv", solution_name+'.zip', '../../../solution/operators'])NEWLINENEWLINENEWLINENEWLINENEWLINE
#!/usr/bin/env python3NEWLINENEWLINE# do lxc list --format=json swift-runwayNEWLINE# ...and delete themNEWLINENEWLINENEWLINE# while it would be cool if this worked, it doesn't and the docs are badNEWLINE# https://linuxcontainers.org/lxc/documentation/#pythonNEWLINE# import lxcNEWLINE# for defined in (True, False):NEWLINE# for active in (True, False):NEWLINE# x = lxc.list_containers(active=active, defined=defined)NEWLINE# print(x, '=> lxc.list_containers(active=%s, defined=%s)' % (active, defined))NEWLINENEWLINENEWLINEimport argparseNEWLINEimport globNEWLINEimport jsonNEWLINEimport osNEWLINEimport reNEWLINEimport shlexNEWLINEimport shutilNEWLINEimport subprocessNEWLINEimport sysNEWLINENEWLINENEWLINEdef parse_profiles_list(cli_output):NEWLINE profiles = []NEWLINE lines = cli_output.split('\n')NEWLINE for line in lines:NEWLINE result = re.match('(^\|\s{1}|^)([\w-]+)', line)NEWLINE if result is not None:NEWLINE profiles.append(result.group(2))NEWLINE return profilesNEWLINENEWLINENEWLINEif os.geteuid() != 0:NEWLINE print('must be run as root')NEWLINE sys.exit(1)NEWLINENEWLINEDEFAULT_PREFIX = 'swift-runway-'NEWLINEparser = argparse.ArgumentParser()NEWLINEparser.add_argument('-a', '--all', action='store_true', default=False,NEWLINE help="Delete everything")NEWLINENEWLINEparser.add_argument('-p', '--prefix', default=None,NEWLINE help="Prefix to look for when deleting. Default: "NEWLINE "'{}'".format(DEFAULT_PREFIX))NEWLINENEWLINEargs = parser.parse_args()NEWLINENEWLINEdelete_everything = args.allNEWLINEprefix = args.prefixNEWLINEif prefix is None:NEWLINE prefix_was_provided = FalseNEWLINE prefix = DEFAULT_PREFIXNEWLINEelse:NEWLINE prefix_was_provided = TrueNEWLINENEWLINEVOLUME_GROUP = 'swift-runway-vg01'NEWLINENEWLINElist_command = 'lxc list --format=json'NEWLINEp = subprocess.run(shlex.split(list_command), stdout=subprocess.PIPE)NEWLINENEWLINEcontainers = json.loads(p.stdout.decode())NEWLINEto_delete = [x['name'] for x in containers if x['name'].startswith(prefix)]NEWLINENEWLINEif to_delete:NEWLINE delete_command = 'lxc delete --force %s' % ' '.join(to_delete)NEWLINE p = subprocess.run(shlex.split(delete_command))NEWLINE print('%d containers deleted' % len(to_delete))NEWLINEelse:NEWLINE print('No containers to delete')NEWLINENEWLINE# delete associated lvm volumesNEWLINEtry:NEWLINENEWLINE if prefix_was_provided:NEWLINE lvlist = glob.glob('/dev/%s/%s*' % (VOLUME_GROUP, prefix))NEWLINE else:NEWLINE # We'll delete all the lvm volumes if a prefix was not providedNEWLINE lvlist = glob.glob('/dev/%s/*' % VOLUME_GROUP)NEWLINEexcept FileNotFoundError:NEWLINE print('No volumes to delete')NEWLINEelse:NEWLINE num_deleted = 0NEWLINE for logical_volume in lvlist:NEWLINE delete_command = 'lvremove --yes %s' % logical_volumeNEWLINE try:NEWLINE p = subprocess.run(NEWLINE shlex.split(delete_command),NEWLINE stdout=subprocess.PIPE,NEWLINE stderr=subprocess.PIPE,NEWLINE universal_newlines=True,NEWLINE check=True)NEWLINE except subprocess.CalledProcessError as err:NEWLINE print('Error deleting %s:\n%s' % (logical_volume,NEWLINE err.stderr.rstrip()),NEWLINE file=sys.stderr)NEWLINE else:NEWLINE num_deleted += 1NEWLINE else:NEWLINE print('%d volumes deleted' % num_deleted)NEWLINENEWLINE# delete associated lxc profilesNEWLINEprofile_list_command = 'lxc profile list'NEWLINEp = subprocess.run(shlex.split(profile_list_command), stdout=subprocess.PIPE)NEWLINEto_delete = []NEWLINEfor line in p.stdout.decode().split('\n'):NEWLINE parts = line.split('|')NEWLINE try:NEWLINE profile_name = parts[1].strip()NEWLINE if profile_name.startswith(prefix):NEWLINE to_delete.append(profile_name)NEWLINE except IndexError:NEWLINE passNEWLINEif to_delete:NEWLINE for profile in to_delete:NEWLINE delete_command = 'lxc profile delete %s' % profileNEWLINE p = subprocess.run(shlex.split(delete_command))NEWLINE print('%d profiles deleted' % len(to_delete))NEWLINEelse:NEWLINE print('No profiles to delete')NEWLINENEWLINE# delete container working spacesNEWLINEfor dirname in os.listdir('guest_workspaces'):NEWLINE if dirname == 'README':NEWLINE continueNEWLINE dirname = 'guest_workspaces/' + dirnameNEWLINE shutil.rmtree(dirname)NEWLINENEWLINE# delete snapshotted container imagesNEWLINEimages_to_delete = []NEWLINEimage_list_command = 'lxc image list description="Created by swift runway"'NEWLINEp = subprocess.run(shlex.split(image_list_command), stdout=subprocess.PIPE)NEWLINEfor line in p.stdout.decode().split('\n'):NEWLINE if "Created by swift runway" in line:NEWLINE parts = line.split('|')NEWLINE fingerprint = parts[2].strip()NEWLINE alias = parts[1].strip()NEWLINE # If we're not deleting everything, we ONLY delete images whose aliasNEWLINE # starts with the given prefix.NEWLINE if delete_everything or (alias != "" and alias.startswith(prefix)):NEWLINE images_to_delete.append(fingerprint)NEWLINEif images_to_delete:NEWLINE print('Deleting %d images' % len(images_to_delete))NEWLINE image_delete_command = 'lxc image delete %s' % ' '.join(images_to_delete)NEWLINE p = subprocess.run(shlex.split(image_delete_command))NEWLINEelse:NEWLINE print('No images to delete')NEWLINE
# Copyright (c) 2015 Jaime van Kessel, Ultimaker B.V.NEWLINE# The PostProcessingPlugin is released under the terms of the AGPLv3 or higher.NEWLINEfrom PyQt5.QtCore import QObject, pyqtProperty, pyqtSignal, pyqtSlotNEWLINENEWLINEfrom UM.PluginRegistry import PluginRegistryNEWLINEfrom UM.Resources import ResourcesNEWLINEfrom UM.Application import ApplicationNEWLINEfrom UM.Extension import ExtensionNEWLINEfrom UM.Logger import LoggerNEWLINENEWLINEimport configparser #The script lists are stored in metadata as serialised config files.NEWLINEimport io #To allow configparser to write to a string.NEWLINEimport os.pathNEWLINEimport pkgutilNEWLINEimport sysNEWLINEimport importlib.utilNEWLINENEWLINEfrom UM.i18n import i18nCatalogNEWLINEi18n_catalog = i18nCatalog("cura")NEWLINENEWLINENEWLINE## The post processing plugin is an Extension type plugin that enables pre-written scripts to post process generatedNEWLINE# g-code files.NEWLINEclass PostProcessingPlugin(QObject, Extension):NEWLINE def __init__(self, parent = None):NEWLINE super().__init__(parent)NEWLINE self.addMenuItem(i18n_catalog.i18n("Modify G-Code"), self.showPopup)NEWLINE self._view = NoneNEWLINENEWLINE # Loaded scripts are all scripts that can be usedNEWLINE self._loaded_scripts = {}NEWLINE self._script_labels = {}NEWLINENEWLINE # Script list contains instances of scripts in loaded_scripts.NEWLINE # There can be duplicates, which will be executed in sequence.NEWLINE self._script_list = []NEWLINE self._selected_script_index = -1NEWLINENEWLINE Application.getInstance().getOutputDeviceManager().writeStarted.connect(self.execute)NEWLINE Application.getInstance().globalContainerStackChanged.connect(self._onGlobalContainerStackChanged) #When the current printer changes, update the list of scripts.NEWLINE Application.getInstance().mainWindowChanged.connect(self._createView) #When the main window is created, create the view so that we can display the post-processing icon if necessary.NEWLINENEWLINE selectedIndexChanged = pyqtSignal()NEWLINE @pyqtProperty("QVariant", notify = selectedIndexChanged)NEWLINE def selectedScriptDefinitionId(self):NEWLINE try:NEWLINE return self._script_list[self._selected_script_index].getDefinitionId()NEWLINE except:NEWLINE return ""NEWLINENEWLINE @pyqtProperty("QVariant", notify=selectedIndexChanged)NEWLINE def selectedScriptStackId(self):NEWLINE try:NEWLINE return self._script_list[self._selected_script_index].getStackId()NEWLINE except:NEWLINE return ""NEWLINENEWLINE ## Execute all post-processing scripts on the gcode.NEWLINE def execute(self, output_device):NEWLINE scene = Application.getInstance().getController().getScene()NEWLINE # If the scene does not have a gcode, do nothingNEWLINE if not hasattr(scene, "gcode_dict"):NEWLINE returnNEWLINE gcode_dict = getattr(scene, "gcode_dict")NEWLINE if not gcode_dict:NEWLINE returnNEWLINENEWLINE # get gcode list for the active build plateNEWLINE active_build_plate_id = Application.getInstance().getMultiBuildPlateModel().activeBuildPlateNEWLINE gcode_list = gcode_dict[active_build_plate_id]NEWLINE if not gcode_list:NEWLINE returnNEWLINENEWLINE if ";POSTPROCESSED" not in gcode_list[0]:NEWLINE for script in self._script_list:NEWLINE try:NEWLINE gcode_list = script.execute(gcode_list)NEWLINE except Exception:NEWLINE Logger.logException("e", "Exception in post-processing script.")NEWLINE if len(self._script_list): # Add comment to g-code if any changes were made.NEWLINE gcode_list[0] += ";POSTPROCESSED\n"NEWLINE gcode_dict[active_build_plate_id] = gcode_listNEWLINE setattr(scene, "gcode_dict", gcode_dict)NEWLINE else:NEWLINE Logger.log("e", "Already post processed")NEWLINENEWLINE @pyqtSlot(int)NEWLINE def setSelectedScriptIndex(self, index):NEWLINE self._selected_script_index = indexNEWLINE self.selectedIndexChanged.emit()NEWLINENEWLINE @pyqtProperty(int, notify = selectedIndexChanged)NEWLINE def selectedScriptIndex(self):NEWLINE return self._selected_script_indexNEWLINENEWLINE @pyqtSlot(int, int)NEWLINE def moveScript(self, index, new_index):NEWLINE if new_index < 0 or new_index > len(self._script_list) - 1:NEWLINE return # nothing needs to be doneNEWLINE else:NEWLINE # Magical switch code.NEWLINE self._script_list[new_index], self._script_list[index] = self._script_list[index], self._script_list[new_index]NEWLINE self.scriptListChanged.emit()NEWLINE self.selectedIndexChanged.emit() #Ensure that settings are updatedNEWLINE self._propertyChanged()NEWLINENEWLINE ## Remove a script from the active script list by index.NEWLINE @pyqtSlot(int)NEWLINE def removeScriptByIndex(self, index):NEWLINE self._script_list.pop(index)NEWLINE if len(self._script_list) - 1 < self._selected_script_index:NEWLINE self._selected_script_index = len(self._script_list) - 1NEWLINE self.scriptListChanged.emit()NEWLINE self.selectedIndexChanged.emit() # Ensure that settings are updatedNEWLINE self._propertyChanged()NEWLINENEWLINE ## Load all scripts from all paths where scripts can be found.NEWLINE #NEWLINE # This should probably only be done on init.NEWLINE def loadAllScripts(self):NEWLINE if self._loaded_scripts: #Already loaded.NEWLINE returnNEWLINENEWLINE #The PostProcessingPlugin path is for built-in scripts.NEWLINE #The Resources path is where the user should store custom scripts.NEWLINE #The Preferences path is legacy, where the user may previously have stored scripts.NEWLINE for root in [PluginRegistry.getInstance().getPluginPath("PostProcessingPlugin"), Resources.getStoragePath(Resources.Resources), Resources.getStoragePath(Resources.Preferences)]:NEWLINE path = os.path.join(root, "scripts")NEWLINE if not os.path.isdir(path):NEWLINE try:NEWLINE os.makedirs(path)NEWLINE except OSError:NEWLINE Logger.log("w", "Unable to create a folder for scripts: " + path)NEWLINE continueNEWLINENEWLINE self.loadScripts(path)NEWLINENEWLINE ## Load all scripts from provided path.NEWLINE # This should probably only be done on init.NEWLINE # \param path Path to check for scripts.NEWLINE def loadScripts(self, path):NEWLINE ## Load all scripts in the scripts foldersNEWLINE scripts = pkgutil.iter_modules(path = [path])NEWLINE for loader, script_name, ispkg in scripts:NEWLINE # Iterate over all scripts.NEWLINE if script_name not in sys.modules:NEWLINE try:NEWLINE spec = importlib.util.spec_from_file_location(__name__ + "." + script_name, os.path.join(path, script_name + ".py"))NEWLINE loaded_script = importlib.util.module_from_spec(spec)NEWLINE spec.loader.exec_module(loaded_script)NEWLINE sys.modules[script_name] = loaded_script #TODO: This could be a security risk. Overwrite any module with a user-provided name?NEWLINENEWLINE loaded_class = getattr(loaded_script, script_name)NEWLINE temp_object = loaded_class()NEWLINE Logger.log("d", "Begin loading of script: %s", script_name)NEWLINE try:NEWLINE setting_data = temp_object.getSettingData()NEWLINE if "name" in setting_data and "key" in setting_data:NEWLINE self._script_labels[setting_data["key"]] = setting_data["name"]NEWLINE self._loaded_scripts[setting_data["key"]] = loaded_classNEWLINE else:NEWLINE Logger.log("w", "Script %s.py has no name or key", script_name)NEWLINE self._script_labels[script_name] = script_nameNEWLINE self._loaded_scripts[script_name] = loaded_classNEWLINE except AttributeError:NEWLINE Logger.log("e", "Script %s.py is not a recognised script type. Ensure it inherits Script", script_name)NEWLINE except NotImplementedError:NEWLINE Logger.log("e", "Script %s.py has no implemented settings", script_name)NEWLINE except Exception as e:NEWLINE Logger.logException("e", "Exception occurred while loading post processing plugin: {error_msg}".format(error_msg = str(e)))NEWLINENEWLINE loadedScriptListChanged = pyqtSignal()NEWLINE @pyqtProperty("QVariantList", notify = loadedScriptListChanged)NEWLINE def loadedScriptList(self):NEWLINE return sorted(list(self._loaded_scripts.keys()))NEWLINENEWLINE @pyqtSlot(str, result = str)NEWLINE def getScriptLabelByKey(self, key):NEWLINE return self._script_labels[key]NEWLINENEWLINE scriptListChanged = pyqtSignal()NEWLINE @pyqtProperty("QVariantList", notify = scriptListChanged)NEWLINE def scriptList(self):NEWLINE script_list = [script.getSettingData()["key"] for script in self._script_list]NEWLINE return script_listNEWLINENEWLINE @pyqtSlot(str)NEWLINE def addScriptToList(self, key):NEWLINE Logger.log("d", "Adding script %s to list.", key)NEWLINE new_script = self._loaded_scripts[key]()NEWLINE self._script_list.append(new_script)NEWLINE self.setSelectedScriptIndex(len(self._script_list) - 1)NEWLINE self.scriptListChanged.emit()NEWLINE self._propertyChanged()NEWLINENEWLINE ## When the global container stack is changed, swap out the list of activeNEWLINE # scripts.NEWLINE def _onGlobalContainerStackChanged(self):NEWLINE self.loadAllScripts()NEWLINE new_stack = Application.getInstance().getGlobalContainerStack()NEWLINE self._script_list.clear()NEWLINE if not new_stack.getMetaDataEntry("post_processing_scripts"): #Missing or empty.NEWLINE self.scriptListChanged.emit() #Even emit this if it didn't change. We want it to write the empty list to the stack's metadata.NEWLINE returnNEWLINENEWLINE self._script_list.clear()NEWLINE scripts_list_strs = new_stack.getMetaDataEntry("post_processing_scripts")NEWLINE for script_str in scripts_list_strs.split("\n"): #Encoded config files should never contain three newlines in a row. At most 2, just before section headers.NEWLINE if not script_str: #There were no scripts in this one (or a corrupt file caused more than 3 consecutive newlines here).NEWLINE continueNEWLINE script_str = script_str.replace("\\n", "\n").replace("\\\\", "\\") #Unescape escape sequences.NEWLINE script_parser = configparser.ConfigParser(interpolation = None)NEWLINE script_parser.optionxform = str #Don't transform the setting keys as they are case-sensitive.NEWLINE script_parser.read_string(script_str)NEWLINE for script_name, settings in script_parser.items(): #There should only be one, really! Otherwise we can't guarantee the order or allow multiple uses of the same script.NEWLINE if script_name == "DEFAULT": #ConfigParser always has a DEFAULT section, but we don't fill it. Ignore this one.NEWLINE continueNEWLINE if script_name not in self._loaded_scripts: #Don't know this post-processing plug-in.NEWLINE Logger.log("e", "Unknown post-processing script {script_name} was encountered in this global stack.".format(script_name = script_name))NEWLINE continueNEWLINE new_script = self._loaded_scripts[script_name]()NEWLINE for setting_key, setting_value in settings.items(): #Put all setting values into the script.NEWLINE new_script._instance.setProperty(setting_key, "value", setting_value)NEWLINE self._script_list.append(new_script)NEWLINENEWLINE self.setSelectedScriptIndex(0)NEWLINE self.scriptListChanged.emit()NEWLINENEWLINE @pyqtSlot()NEWLINE def writeScriptsToStack(self):NEWLINE script_list_strs = []NEWLINE for script in self._script_list:NEWLINE parser = configparser.ConfigParser(interpolation = None) #We'll encode the script as a config with one section. The section header is the key and its values are the settings.NEWLINE parser.optionxform = str #Don't transform the setting keys as they are case-sensitive.NEWLINE script_name = script.getSettingData()["key"]NEWLINE parser.add_section(script_name)NEWLINE for key in script.getSettingData()["settings"]:NEWLINE value = script.getSettingValueByKey(key)NEWLINE parser[script_name][key] = str(value)NEWLINE serialized = io.StringIO() #ConfigParser can only write to streams. Fine.NEWLINE parser.write(serialized)NEWLINE serialized.seek(0)NEWLINE script_str = serialized.read()NEWLINE script_str = script_str.replace("\\", "\\\\").replace("\n", "\\n") #Escape newlines because configparser sees those as section delimiters.NEWLINE script_list_strs.append(script_str)NEWLINENEWLINE script_list_strs = "\n".join(script_list_strs) #ConfigParser should never output three newlines in a row when serialised, so it's a safe delimiter.NEWLINENEWLINE global_stack = Application.getInstance().getGlobalContainerStack()NEWLINE if "post_processing_scripts" not in global_stack.getMetaData():NEWLINE global_stack.addMetaDataEntry("post_processing_scripts", "")NEWLINE Application.getInstance().getGlobalContainerStack().setMetaDataEntry("post_processing_scripts", script_list_strs)NEWLINENEWLINE ## Creates the view used by show popup. The view is saved because of the fairly aggressive garbage collection.NEWLINE def _createView(self):NEWLINE Logger.log("d", "Creating post processing plugin view.")NEWLINENEWLINE self.loadAllScripts()NEWLINENEWLINE # Create the plugin dialog componentNEWLINE path = os.path.join(PluginRegistry.getInstance().getPluginPath("PostProcessingPlugin"), "PostProcessingPlugin.qml")NEWLINE self._view = Application.getInstance().createQmlComponent(path, {"manager": self})NEWLINE Logger.log("d", "Post processing view created.")NEWLINENEWLINE # Create the save button componentNEWLINE Application.getInstance().addAdditionalComponent("saveButton", self._view.findChild(QObject, "postProcessingSaveAreaButton"))NEWLINENEWLINE ## Show the (GUI) popup of the post processing plugin.NEWLINE def showPopup(self):NEWLINE if self._view is None:NEWLINE self._createView()NEWLINE self._view.show()NEWLINENEWLINE ## Property changed: trigger re-sliceNEWLINE # To do this we use the global container stack propertyChanged.NEWLINE # Re-slicing is necessary for setting changes in this plugin, because the changesNEWLINE # are applied only once per "fresh" gcodeNEWLINE def _propertyChanged(self):NEWLINE global_container_stack = Application.getInstance().getGlobalContainerStack()NEWLINE global_container_stack.propertyChanged.emit("post_processing_plugin", "value")NEWLINENEWLINENEWLINE
from django.core.management.base import BaseCommand, CommandErrorNEWLINEfrom ._offences import OffenceScraperNEWLINEfrom ....api import modelsNEWLINEimport pprintNEWLINENEWLINEclass Command(BaseCommand):NEWLINE help = 'Scrapes offences'NEWLINENEWLINE def add_arguments(self, parser):NEWLINE passNEWLINENEWLINE def handle(self, *args, **options):NEWLINE scraper = OffenceScraper()NEWLINE offences = scraper.get_offences(5)NEWLINE for offence in offences:NEWLINE model, _created = models.Offence.objects.update_or_create(offence_name=offence["name"], defaults = {"effective_from": offence["effective_date"]})NEWLINE self.stdout.write(self.style.SUCCESS(model))NEWLINE pprint.pprint(offence, indent=4)NEWLINENEWLINE self.stdout.write(self.style.SUCCESS('Command has run successfully'))NEWLINE
"""NEWLINE@author: Junguang JiangNEWLINE@contact: JiangJunguang1123@outlook.comNEWLINE"""NEWLINEimport randomNEWLINEimport timeNEWLINEimport warningsNEWLINEimport sysNEWLINEimport argparseNEWLINEimport shutilNEWLINEimport os.path as ospNEWLINENEWLINEimport torchNEWLINEimport torch.nn as nnNEWLINEimport torch.backends.cudnn as cudnnNEWLINEfrom torch.optim import SGDNEWLINEfrom torch.optim.lr_scheduler import LambdaLRNEWLINEfrom torch.utils.data import DataLoaderNEWLINEimport torch.nn.functional as FNEWLINENEWLINEsys.path.append('../../..')NEWLINEfrom common.modules.classifier import ClassifierNEWLINEfrom common.utils.data import ForeverDataIteratorNEWLINEfrom common.utils.metric import accuracy, ConfusionMatrixNEWLINEfrom common.utils.meter import AverageMeter, ProgressMeterNEWLINEfrom common.utils.logger import CompleteLoggerNEWLINEfrom common.utils.analysis import collect_feature, tsne, a_distanceNEWLINENEWLINEsys.path.append('.')NEWLINEimport utilsNEWLINENEWLINEdevice = torch.device("cuda" if torch.cuda.is_available() else "cpu")NEWLINENEWLINENEWLINEdef main(args: argparse.Namespace):NEWLINE logger = CompleteLogger(args.log, args.phase)NEWLINE print(args)NEWLINENEWLINE if args.seed is not None:NEWLINE random.seed(args.seed)NEWLINE torch.manual_seed(args.seed)NEWLINE cudnn.deterministic = TrueNEWLINE warnings.warn('You have chosen to seed training. 'NEWLINE 'This will turn on the CUDNN deterministic setting, 'NEWLINE 'which can slow down your training considerably! 'NEWLINE 'You may see unexpected behavior when restarting 'NEWLINE 'from checkpoints.')NEWLINENEWLINE cudnn.benchmark = TrueNEWLINENEWLINE # Data loading codeNEWLINE # Data loading codeNEWLINE train_transform = utils.get_train_transform(args.train_resizing, random_horizontal_flip=True, random_color_jitter=False)NEWLINE val_transform = utils.get_val_transform(args.val_resizing)NEWLINE print("train_transform: ", train_transform)NEWLINE print("val_transform: ", val_transform)NEWLINENEWLINE train_source_dataset, _, val_dataset, test_dataset, num_classes, args.class_names = \NEWLINE utils.get_dataset(args.data, args.root, args.source, args.target, train_transform, val_transform)NEWLINE train_source_loader = DataLoader(train_source_dataset, batch_size=args.batch_size,NEWLINE shuffle=True, num_workers=args.workers, drop_last=True)NEWLINE val_loader = DataLoader(val_dataset, batch_size=args.batch_size, shuffle=False, num_workers=args.workers)NEWLINE test_loader = DataLoader(test_dataset, batch_size=args.batch_size, shuffle=False, num_workers=args.workers)NEWLINENEWLINE train_source_iter = ForeverDataIterator(train_source_loader)NEWLINENEWLINE # create modelNEWLINE print("=> using pre-trained model '{}'".format(args.arch))NEWLINE backbone = utils.get_model(args.arch)NEWLINE pool_layer = nn.Identity() if args.no_pool else NoneNEWLINE classifier = Classifier(backbone, num_classes, pool_layer=pool_layer).to(device)NEWLINENEWLINE # define optimizer and lr schedulerNEWLINE optimizer = SGD(classifier.get_parameters(), args.lr, momentum=args.momentum, weight_decay=args.wd, nesterov=True)NEWLINE lr_scheduler = LambdaLR(optimizer, lambda x: args.lr * (1. + args.lr_gamma * float(x)) ** (-args.lr_decay))NEWLINENEWLINE # analysis the modelNEWLINE if args.phase == 'analysis':NEWLINE # using shuffled val loaderNEWLINE val_loader = DataLoader(val_dataset, batch_size=args.batch_size, shuffle=True, num_workers=args.workers)NEWLINE # extract features from both domainsNEWLINE feature_extractor = nn.Sequential(classifier.backbone, classifier.pool_layer, classifier.bottleneck).to(device)NEWLINE source_feature = collect_feature(train_source_loader, feature_extractor, device)NEWLINE target_feature = collect_feature(val_loader, feature_extractor, device)NEWLINE # plot t-SNENEWLINE tSNE_filename = osp.join(logger.visualize_directory, 'TSNE.png')NEWLINE tsne.visualize(source_feature, target_feature, tSNE_filename)NEWLINE print("Saving t-SNE to", tSNE_filename)NEWLINE # calculate A-distance, which is a measure for distribution discrepancyNEWLINE A_distance = a_distance.calculate(source_feature, target_feature, device)NEWLINE print("A-distance =", A_distance)NEWLINE returnNEWLINENEWLINE if args.phase == 'test':NEWLINE acc1 = validate(test_loader, classifier, args)NEWLINE print(acc1)NEWLINE returnNEWLINENEWLINE # start trainingNEWLINE best_h_score = 0.NEWLINE for epoch in range(args.epochs):NEWLINE # train for one epochNEWLINE train(train_source_iter, classifier, optimizer,NEWLINE lr_scheduler, epoch, args)NEWLINENEWLINE # evaluate on validation setNEWLINE h_score = validate(val_loader, classifier, args)NEWLINENEWLINE # remember best acc@1 and save checkpointNEWLINE torch.save(classifier.state_dict(), logger.get_checkpoint_path('latest'))NEWLINE if h_score > best_h_score:NEWLINE shutil.copy(logger.get_checkpoint_path('latest'), logger.get_checkpoint_path('best'))NEWLINE best_h_score = max(h_score, best_h_score)NEWLINENEWLINE print("best_h_score = {:3.1f}".format(best_h_score))NEWLINENEWLINE # evaluate on test setNEWLINE classifier.load_state_dict(torch.load(logger.get_checkpoint_path('best')))NEWLINE h_score = validate(test_loader, classifier, args)NEWLINE print("test_h_score = {:3.1f}".format(h_score))NEWLINENEWLINE logger.close()NEWLINENEWLINENEWLINEdef train(train_source_iter: ForeverDataIterator, model: Classifier, optimizer: SGD,NEWLINE lr_scheduler: LambdaLR, epoch: int, args: argparse.Namespace):NEWLINE batch_time = AverageMeter('Time', ':4.2f')NEWLINE data_time = AverageMeter('Data', ':3.1f')NEWLINE losses = AverageMeter('Loss', ':3.2f')NEWLINE cls_accs = AverageMeter('Cls Acc', ':3.1f')NEWLINENEWLINE progress = ProgressMeter(NEWLINE args.iters_per_epoch,NEWLINE [batch_time, data_time, losses, cls_accs],NEWLINE prefix="Epoch: [{}]".format(epoch))NEWLINENEWLINE # switch to train modeNEWLINE model.train()NEWLINENEWLINE end = time.time()NEWLINE for i in range(args.iters_per_epoch):NEWLINE x_s, labels_s = next(train_source_iter)NEWLINE x_s = x_s.to(device)NEWLINE labels_s = labels_s.to(device)NEWLINENEWLINE # measure data loading timeNEWLINE data_time.update(time.time() - end)NEWLINENEWLINE # compute outputNEWLINE y_s, f_s = model(x_s)NEWLINENEWLINE cls_loss = F.cross_entropy(y_s, labels_s)NEWLINE loss = cls_lossNEWLINENEWLINE cls_acc = accuracy(y_s, labels_s)[0]NEWLINENEWLINE losses.update(loss.item(), x_s.size(0))NEWLINE cls_accs.update(cls_acc.item(), x_s.size(0))NEWLINENEWLINE # compute gradient and do SGD stepNEWLINE optimizer.zero_grad()NEWLINE loss.backward()NEWLINE optimizer.step()NEWLINE lr_scheduler.step()NEWLINENEWLINE # measure elapsed timeNEWLINE batch_time.update(time.time() - end)NEWLINE end = time.time()NEWLINENEWLINE if i % args.print_freq == 0:NEWLINE progress.display(i)NEWLINENEWLINENEWLINEdef validate(val_loader: DataLoader, model: Classifier, args: argparse.Namespace) -> float:NEWLINE batch_time = AverageMeter('Time', ':6.3f')NEWLINE classes = val_loader.dataset.classesNEWLINE confmat = ConfusionMatrix(len(classes))NEWLINE progress = ProgressMeter(NEWLINE len(val_loader),NEWLINE [batch_time],NEWLINE prefix='Test: ')NEWLINENEWLINE # switch to evaluate modeNEWLINE model.eval()NEWLINENEWLINE with torch.no_grad():NEWLINE end = time.time()NEWLINE for i, (images, target) in enumerate(val_loader):NEWLINE images = images.to(device)NEWLINE target = target.to(device)NEWLINENEWLINE # compute outputNEWLINE output = model(images)NEWLINE softmax_output = F.softmax(output, dim=1)NEWLINE softmax_output[:, -1] = args.thresholdNEWLINENEWLINE # measure accuracy and record lossNEWLINE confmat.update(target, softmax_output.argmax(1))NEWLINENEWLINE # measure elapsed timeNEWLINE batch_time.update(time.time() - end)NEWLINE end = time.time()NEWLINENEWLINE if i % args.print_freq == 0:NEWLINE progress.display(i)NEWLINENEWLINE acc_global, accs, iu = confmat.compute()NEWLINE all_acc = torch.mean(accs).item() * 100NEWLINE known = torch.mean(accs[:-1]).item() * 100NEWLINE unknown = accs[-1].item() * 100NEWLINE h_score = 2 * known * unknown / (known + unknown)NEWLINE if args.per_class_eval:NEWLINE print(confmat.format(classes))NEWLINE print(' * All {all:.3f} Known {known:.3f} Unknown {unknown:.3f} H-score {h_score:.3f}'NEWLINE .format(all=all_acc, known=known, unknown=unknown, h_score=h_score))NEWLINENEWLINE return h_scoreNEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE parser = argparse.ArgumentParser(description='Source Only for Openset Domain Adaptation')NEWLINE # dataset parametersNEWLINE parser.add_argument('root', metavar='DIR',NEWLINE help='root path of dataset')NEWLINE parser.add_argument('-d', '--data', metavar='DATA', default='Office31', choices=utils.get_dataset_names(),NEWLINE help='dataset: ' + ' | '.join(utils.get_dataset_names()) +NEWLINE ' (default: Office31)')NEWLINE parser.add_argument('-s', '--source', help='source domain')NEWLINE parser.add_argument('-t', '--target', help='target domain')NEWLINE parser.add_argument('--train-resizing', type=str, default='default')NEWLINE parser.add_argument('--val-resizing', type=str, default='default')NEWLINE # model parametersNEWLINE parser.add_argument('-a', '--arch', metavar='ARCH', default='resnet18',NEWLINE choices=utils.get_model_names(),NEWLINE help='backbone architecture: ' +NEWLINE ' | '.join(utils.get_model_names()) +NEWLINE ' (default: resnet18)')NEWLINE parser.add_argument('--no-pool', action='store_true',NEWLINE help='no pool layer after the feature extractor.')NEWLINE parser.add_argument('--threshold', default=0.8, type=float,NEWLINE help='When class confidence is less than the given threshold, 'NEWLINE 'model will output "unknown" (default: 0.5)')NEWLINE # training parametersNEWLINE parser.add_argument('-b', '--batch-size', default=32, type=int,NEWLINE metavar='N',NEWLINE help='mini-batch size (default: 32)')NEWLINE parser.add_argument('--lr', '--learning-rate', default=0.001, type=float,NEWLINE metavar='LR', help='initial learning rate', dest='lr')NEWLINE parser.add_argument('--lr-gamma', default=0.0003, type=float, help='parameter for lr scheduler')NEWLINE parser.add_argument('--lr-decay', default=0.75, type=float, help='parameter for lr scheduler')NEWLINE parser.add_argument('--momentum', default=0.9, type=float, metavar='M',NEWLINE help='momentum')NEWLINE parser.add_argument('--wd', '--weight-decay', default=0.0005, type=float,NEWLINE metavar='W', help='weight decay (default: 5e-4)')NEWLINE parser.add_argument('-j', '--workers', default=2, type=int, metavar='N',NEWLINE help='number of data loading workers (default: 4)')NEWLINE parser.add_argument('--epochs', default=20, type=int, metavar='N',NEWLINE help='number of total epochs to run')NEWLINE parser.add_argument('-i', '--iters-per-epoch', default=500, type=int,NEWLINE help='Number of iterations per epoch')NEWLINE parser.add_argument('-p', '--print-freq', default=100, type=int,NEWLINE metavar='N', help='print frequency (default: 100)')NEWLINE parser.add_argument('--seed', default=None, type=int,NEWLINE help='seed for initializing training. ')NEWLINE parser.add_argument('--per-class-eval', action='store_true',NEWLINE help='whether output per-class accuracy during evaluation')NEWLINE parser.add_argument("--log", type=str, default='src_only',NEWLINE help="Where to save logs, checkpoints and debugging images.")NEWLINE parser.add_argument("--phase", type=str, default='train', choices=['train', 'test', 'analysis'],NEWLINE help="When phase is 'test', only test the model."NEWLINE "When phase is 'analysis', only analysis the model.")NEWLINE args = parser.parse_args()NEWLINE main(args)NEWLINENEWLINE
from rt_utils.rtstruct import RTStructNEWLINEimport pytestNEWLINEimport osNEWLINEfrom rt_utils import RTStructBuilderNEWLINENEWLINE@pytest.fixture()NEWLINEdef series_path() -> str:NEWLINE return get_and_test_series_path('mock_data')NEWLINENEWLINE@pytest.fixture()NEWLINEdef new_rtstruct() -> RTStruct:NEWLINE return get_rtstruct('mock_data')NEWLINENEWLINE@pytest.fixture()NEWLINEdef oriented_series_path() -> RTStruct:NEWLINE return get_and_test_series_path('oriented_data')NEWLINENEWLINE@pytest.fixture()NEWLINEdef oriented_rtstruct() -> RTStruct:NEWLINE return get_rtstruct('oriented_data')NEWLINENEWLINE@pytest.fixture()NEWLINEdef one_slice_series_path() -> RTStruct:NEWLINE return get_and_test_series_path('one_slice_data')NEWLINENEWLINE@pytest.fixture()NEWLINEdef one_slice_rtstruct() -> RTStruct:NEWLINE return get_rtstruct('one_slice_data')NEWLINENEWLINEdef get_rtstruct(dirname) -> RTStruct:NEWLINE path = get_and_test_series_path(dirname)NEWLINE rtstruct = RTStructBuilder.create_new(path)NEWLINE return rtstructNEWLINENEWLINEdef get_and_test_series_path(dirname) -> str:NEWLINE series_path = os.path.join(os.path.dirname(__file__), dirname)NEWLINE assert os.path.exists(series_path)NEWLINE return series_pathNEWLINE
from math import ceilNEWLINENEWLINEimport numpy as npNEWLINEfrom numpy.testing import assert_array_equalNEWLINEimport pytestNEWLINENEWLINEfrom sklearn.ensemble import StackingClassifierNEWLINEfrom sklearn.exceptions import NotFittedErrorNEWLINEfrom sklearn.neighbors import KNeighborsClassifierNEWLINEfrom sklearn.svm import SVCNEWLINEfrom sklearn.model_selection import train_test_splitNEWLINEfrom sklearn.datasets import load_iris, make_blobsNEWLINEfrom sklearn.metrics import accuracy_scoreNEWLINENEWLINEfrom sklearn.semi_supervised import SelfTrainingClassifierNEWLINENEWLINE# Author: Oliver Rausch <rauscho@ethz.ch>NEWLINE# License: BSD 3 clauseNEWLINENEWLINE# load the iris dataset and randomly permute itNEWLINEiris = load_iris()NEWLINEX_train, X_test, y_train, y_test = train_test_split(NEWLINE iris.data, iris.target, random_state=0NEWLINE)NEWLINENEWLINEn_labeled_samples = 50NEWLINENEWLINEy_train_missing_labels = y_train.copy()NEWLINEy_train_missing_labels[n_labeled_samples:] = -1NEWLINEmapping = {0: "A", 1: "B", 2: "C", -1: "-1"}NEWLINEy_train_missing_strings = np.vectorize(mapping.get)(y_train_missing_labels).astype(NEWLINE objectNEWLINE)NEWLINEy_train_missing_strings[y_train_missing_labels == -1] = -1NEWLINENEWLINENEWLINEdef test_missing_predict_proba():NEWLINE # Check that an error is thrown if predict_proba is not implementedNEWLINE base_estimator = SVC(probability=False, gamma="scale")NEWLINE self_training = SelfTrainingClassifier(base_estimator)NEWLINENEWLINE with pytest.raises(ValueError, match=r"base_estimator \(SVC\) should"):NEWLINE self_training.fit(X_train, y_train_missing_labels)NEWLINENEWLINENEWLINEdef test_none_classifier():NEWLINE st = SelfTrainingClassifier(None)NEWLINE with pytest.raises(ValueError, match="base_estimator cannot be None"):NEWLINE st.fit(X_train, y_train_missing_labels)NEWLINENEWLINENEWLINE@pytest.mark.parametrize("max_iter, threshold", [(-1, 1.0), (-100, -2), (-10, 10)])NEWLINEdef test_invalid_params(max_iter, threshold):NEWLINE # Test negative iterationsNEWLINE base_estimator = SVC(gamma="scale", probability=True)NEWLINE st = SelfTrainingClassifier(base_estimator, max_iter=max_iter)NEWLINE with pytest.raises(ValueError, match="max_iter must be >= 0 or None"):NEWLINE st.fit(X_train, y_train)NEWLINENEWLINE base_estimator = SVC(gamma="scale", probability=True)NEWLINE st = SelfTrainingClassifier(base_estimator, threshold=threshold)NEWLINE with pytest.raises(ValueError, match="threshold must be in"):NEWLINE st.fit(X_train, y_train)NEWLINENEWLINENEWLINEdef test_invalid_params_selection_crit():NEWLINE st = SelfTrainingClassifier(KNeighborsClassifier(), criterion="foo")NEWLINENEWLINE with pytest.raises(ValueError, match="criterion must be either"):NEWLINE st.fit(X_train, y_train)NEWLINENEWLINENEWLINEdef test_warns_k_best():NEWLINE st = SelfTrainingClassifier(KNeighborsClassifier(), criterion="k_best", k_best=1000)NEWLINE with pytest.warns(UserWarning, match="k_best is larger than"):NEWLINE st.fit(X_train, y_train_missing_labels)NEWLINENEWLINE assert st.termination_condition_ == "all_labeled"NEWLINENEWLINENEWLINE@pytest.mark.parametrize(NEWLINE "base_estimator",NEWLINE [KNeighborsClassifier(), SVC(gamma="scale", probability=True, random_state=0)],NEWLINE)NEWLINE@pytest.mark.parametrize("selection_crit", ["threshold", "k_best"])NEWLINEdef test_classification(base_estimator, selection_crit):NEWLINE # Check classification for various parameter settings.NEWLINE # Also assert that predictions for strings and numerical labels are equal.NEWLINE # Also test for multioutput classificationNEWLINE threshold = 0.75NEWLINE max_iter = 10NEWLINE st = SelfTrainingClassifier(NEWLINE base_estimator, max_iter=max_iter, threshold=threshold, criterion=selection_critNEWLINE )NEWLINE st.fit(X_train, y_train_missing_labels)NEWLINE pred = st.predict(X_test)NEWLINE proba = st.predict_proba(X_test)NEWLINENEWLINE st_string = SelfTrainingClassifier(NEWLINE base_estimator, max_iter=max_iter, criterion=selection_crit, threshold=thresholdNEWLINE )NEWLINE st_string.fit(X_train, y_train_missing_strings)NEWLINE pred_string = st_string.predict(X_test)NEWLINE proba_string = st_string.predict_proba(X_test)NEWLINENEWLINE assert_array_equal(np.vectorize(mapping.get)(pred), pred_string)NEWLINE assert_array_equal(proba, proba_string)NEWLINENEWLINE assert st.termination_condition_ == st_string.termination_condition_NEWLINE # Check consistency between labeled_iter, n_iter and max_iterNEWLINE labeled = y_train_missing_labels != -1NEWLINE # assert that labeled samples have labeled_iter = 0NEWLINE assert_array_equal(st.labeled_iter_ == 0, labeled)NEWLINE # assert that labeled samples do not change label during trainingNEWLINE assert_array_equal(y_train_missing_labels[labeled], st.transduction_[labeled])NEWLINENEWLINE # assert that the max of the iterations is less than the total amount ofNEWLINE # iterationsNEWLINE assert np.max(st.labeled_iter_) <= st.n_iter_ <= max_iterNEWLINE assert np.max(st_string.labeled_iter_) <= st_string.n_iter_ <= max_iterNEWLINENEWLINE # check shapesNEWLINE assert st.labeled_iter_.shape == st.transduction_.shapeNEWLINE assert st_string.labeled_iter_.shape == st_string.transduction_.shapeNEWLINENEWLINENEWLINEdef test_k_best():NEWLINE st = SelfTrainingClassifier(NEWLINE KNeighborsClassifier(n_neighbors=1),NEWLINE criterion="k_best",NEWLINE k_best=10,NEWLINE max_iter=None,NEWLINE )NEWLINE y_train_only_one_label = np.copy(y_train)NEWLINE y_train_only_one_label[1:] = -1NEWLINE n_samples = y_train.shape[0]NEWLINENEWLINE n_expected_iter = ceil((n_samples - 1) / 10)NEWLINE st.fit(X_train, y_train_only_one_label)NEWLINE assert st.n_iter_ == n_expected_iterNEWLINENEWLINE # Check labeled_iter_NEWLINE assert np.sum(st.labeled_iter_ == 0) == 1NEWLINE for i in range(1, n_expected_iter):NEWLINE assert np.sum(st.labeled_iter_ == i) == 10NEWLINE assert np.sum(st.labeled_iter_ == n_expected_iter) == (n_samples - 1) % 10NEWLINE assert st.termination_condition_ == "all_labeled"NEWLINENEWLINENEWLINEdef test_sanity_classification():NEWLINE base_estimator = SVC(gamma="scale", probability=True)NEWLINE base_estimator.fit(X_train[n_labeled_samples:], y_train[n_labeled_samples:])NEWLINENEWLINE st = SelfTrainingClassifier(base_estimator)NEWLINE st.fit(X_train, y_train_missing_labels)NEWLINENEWLINE pred1, pred2 = base_estimator.predict(X_test), st.predict(X_test)NEWLINE assert not np.array_equal(pred1, pred2)NEWLINE score_supervised = accuracy_score(base_estimator.predict(X_test), y_test)NEWLINE score_self_training = accuracy_score(st.predict(X_test), y_test)NEWLINENEWLINE assert score_self_training > score_supervisedNEWLINENEWLINENEWLINEdef test_none_iter():NEWLINE # Check that the all samples were labeled after a 'reasonable' number ofNEWLINE # iterations.NEWLINE st = SelfTrainingClassifier(KNeighborsClassifier(), threshold=0.55, max_iter=None)NEWLINE st.fit(X_train, y_train_missing_labels)NEWLINENEWLINE assert st.n_iter_ < 10NEWLINE assert st.termination_condition_ == "all_labeled"NEWLINENEWLINENEWLINE@pytest.mark.parametrize(NEWLINE "base_estimator",NEWLINE [KNeighborsClassifier(), SVC(gamma="scale", probability=True, random_state=0)],NEWLINE)NEWLINE@pytest.mark.parametrize("y", [y_train_missing_labels, y_train_missing_strings])NEWLINEdef test_zero_iterations(base_estimator, y):NEWLINE # Check classification for zero iterations.NEWLINE # Fitting a SelfTrainingClassifier with zero iterations should give theNEWLINE # same results as fitting a supervised classifier.NEWLINE # This also asserts that string arrays work as expected.NEWLINENEWLINE clf1 = SelfTrainingClassifier(base_estimator, max_iter=0)NEWLINENEWLINE clf1.fit(X_train, y)NEWLINENEWLINE clf2 = base_estimator.fit(X_train[:n_labeled_samples], y[:n_labeled_samples])NEWLINENEWLINE assert_array_equal(clf1.predict(X_test), clf2.predict(X_test))NEWLINE assert clf1.termination_condition_ == "max_iter"NEWLINENEWLINENEWLINEdef test_prefitted_throws_error():NEWLINE # Test that passing a pre-fitted classifier and calling predict throws anNEWLINE # errorNEWLINE knn = KNeighborsClassifier()NEWLINE knn.fit(X_train, y_train)NEWLINE st = SelfTrainingClassifier(knn)NEWLINE with pytest.raises(NEWLINE NotFittedError,NEWLINE match="This SelfTrainingClassifier instance is not fitted yet",NEWLINE ):NEWLINE st.predict(X_train)NEWLINENEWLINENEWLINE@pytest.mark.parametrize("max_iter", range(1, 5))NEWLINEdef test_labeled_iter(max_iter):NEWLINE # Check that the amount of datapoints labeled in iteration 0 is equal toNEWLINE # the amount of labeled datapoints we passed.NEWLINE st = SelfTrainingClassifier(KNeighborsClassifier(), max_iter=max_iter)NEWLINENEWLINE st.fit(X_train, y_train_missing_labels)NEWLINE amount_iter_0 = len(st.labeled_iter_[st.labeled_iter_ == 0])NEWLINE assert amount_iter_0 == n_labeled_samplesNEWLINE # Check that the max of the iterations is less than the total amount ofNEWLINE # iterationsNEWLINE assert np.max(st.labeled_iter_) <= st.n_iter_ <= max_iterNEWLINENEWLINENEWLINEdef test_no_unlabeled():NEWLINE # Test that training on a fully labeled dataset produces the same resultsNEWLINE # as training the classifier by itself.NEWLINE knn = KNeighborsClassifier()NEWLINE knn.fit(X_train, y_train)NEWLINE st = SelfTrainingClassifier(knn)NEWLINE with pytest.warns(UserWarning, match="y contains no unlabeled samples"):NEWLINE st.fit(X_train, y_train)NEWLINE assert_array_equal(knn.predict(X_test), st.predict(X_test))NEWLINE # Assert that all samples were labeled in iteration 0 (since there were noNEWLINE # unlabeled samples).NEWLINE assert np.all(st.labeled_iter_ == 0)NEWLINE assert st.termination_condition_ == "all_labeled"NEWLINENEWLINENEWLINEdef test_early_stopping():NEWLINE svc = SVC(gamma="scale", probability=True)NEWLINE st = SelfTrainingClassifier(svc)NEWLINE X_train_easy = [[1], [0], [1], [0.5]]NEWLINE y_train_easy = [1, 0, -1, -1]NEWLINE # X = [[0.5]] cannot be predicted on with a high confidence, so trainingNEWLINE # stops earlyNEWLINE st.fit(X_train_easy, y_train_easy)NEWLINE assert st.n_iter_ == 1NEWLINE assert st.termination_condition_ == "no_change"NEWLINENEWLINENEWLINEdef test_strings_dtype():NEWLINE clf = SelfTrainingClassifier(KNeighborsClassifier())NEWLINE X, y = make_blobs(n_samples=30, random_state=0, cluster_std=0.1)NEWLINE labels_multiclass = ["one", "two", "three"]NEWLINENEWLINE y_strings = np.take(labels_multiclass, y)NEWLINENEWLINE with pytest.raises(ValueError, match="dtype"):NEWLINE clf.fit(X, y_strings)NEWLINENEWLINENEWLINE@pytest.mark.parametrize("verbose", [True, False])NEWLINEdef test_verbose(capsys, verbose):NEWLINE clf = SelfTrainingClassifier(KNeighborsClassifier(), verbose=verbose)NEWLINE clf.fit(X_train, y_train_missing_labels)NEWLINENEWLINE captured = capsys.readouterr()NEWLINENEWLINE if verbose:NEWLINE assert "iteration" in captured.outNEWLINE else:NEWLINE assert "iteration" not in captured.outNEWLINENEWLINENEWLINEdef test_verbose_k_best(capsys):NEWLINE st = SelfTrainingClassifier(NEWLINE KNeighborsClassifier(n_neighbors=1),NEWLINE criterion="k_best",NEWLINE k_best=10,NEWLINE verbose=True,NEWLINE max_iter=None,NEWLINE )NEWLINENEWLINE y_train_only_one_label = np.copy(y_train)NEWLINE y_train_only_one_label[1:] = -1NEWLINE n_samples = y_train.shape[0]NEWLINENEWLINE n_expected_iter = ceil((n_samples - 1) / 10)NEWLINE st.fit(X_train, y_train_only_one_label)NEWLINENEWLINE captured = capsys.readouterr()NEWLINENEWLINE msg = "End of iteration {}, added {} new labels."NEWLINE for i in range(1, n_expected_iter):NEWLINE assert msg.format(i, 10) in captured.outNEWLINENEWLINE assert msg.format(n_expected_iter, (n_samples - 1) % 10) in captured.outNEWLINENEWLINENEWLINEdef test_k_best_selects_best():NEWLINE # Tests that the labels added by st really are the 10 best labels.NEWLINE svc = SVC(gamma="scale", probability=True, random_state=0)NEWLINE st = SelfTrainingClassifier(svc, criterion="k_best", max_iter=1, k_best=10)NEWLINE has_label = y_train_missing_labels != -1NEWLINE st.fit(X_train, y_train_missing_labels)NEWLINENEWLINE got_label = ~has_label & (st.transduction_ != -1)NEWLINENEWLINE svc.fit(X_train[has_label], y_train_missing_labels[has_label])NEWLINE pred = svc.predict_proba(X_train[~has_label])NEWLINE max_proba = np.max(pred, axis=1)NEWLINENEWLINE most_confident_svc = X_train[~has_label][np.argsort(max_proba)[-10:]]NEWLINE added_by_st = X_train[np.where(got_label)].tolist()NEWLINENEWLINE for row in most_confident_svc.tolist():NEWLINE assert row in added_by_stNEWLINENEWLINENEWLINEdef test_base_estimator_meta_estimator():NEWLINE # Check that a meta-estimator relying on an estimator implementingNEWLINE # `predict_proba` will work even if it does expose this method before beingNEWLINE # fitted.NEWLINE # Non-regression test for:NEWLINE # https://github.com/scikit-learn/scikit-learn/issues/19119NEWLINENEWLINE base_estimator = StackingClassifier(NEWLINE estimators=[NEWLINE ("svc_1", SVC(probability=True)),NEWLINE ("svc_2", SVC(probability=True)),NEWLINE ],NEWLINE final_estimator=SVC(probability=True),NEWLINE cv=2,NEWLINE )NEWLINENEWLINE # make sure that the `base_estimator` does not expose `predict_proba`NEWLINE # without being fittedNEWLINE assert not hasattr(base_estimator, "predict_proba")NEWLINENEWLINE clf = SelfTrainingClassifier(base_estimator=base_estimator)NEWLINE clf.fit(X_train, y_train_missing_labels)NEWLINE clf.predict_proba(X_test)NEWLINE
#!/usr/bin/env pythonNEWLINE#NEWLINE# Copyright (c) 2017 Amazon.com, Inc. or its affiliates. All RightsNEWLINE# Reserved.NEWLINE#NEWLINE# Additional copyrights may followNEWLINE#NEWLINENEWLINEimport osNEWLINEimport sysNEWLINEimport reNEWLINEimport argparseNEWLINEimport loggingNEWLINEimport timeNEWLINEimport shlexNEWLINEimport shutilNEWLINEimport requestsNEWLINEimport BuilderUtilsNEWLINENEWLINENEWLINE_cov_filename = 'coverity_tools.tgz'NEWLINENEWLINEdef run_coverity_internal(logger, build_root, source_tarball, config):NEWLINE # read the token fileNEWLINE file = open(config['token_file'], 'r')NEWLINE token = file.readline().rstrip('\n')NEWLINENEWLINE # get the toolNEWLINE if not os.path.isdir(config['tool_dir']):NEWLINE os.makedirs(config['tool_dir'])NEWLINE os.chdir(config['tool_dir'])NEWLINE timestamp = 0NEWLINE if os.path.exists(_cov_filename):NEWLINE timestamp = os.stat(_cov_filename).st_mtimeNEWLINE if (timestamp + (24 * 3600)) > int(time.time()):NEWLINE logger.debug('Reusing existing tarball')NEWLINE else:NEWLINE logger.debug('Downloading %s' % (config['tool_url']))NEWLINE # As of 9 Aug 2021, this file is 2+GB. Downloading it allNEWLINE # into a Python script and then writing it out to disk is notNEWLINE # a good idea on our limited resources AWS VM (meaning: itNEWLINE # brings the VM to a crawl). FromNEWLINE # https://stackoverflow.com/questions/38969164/coverity-scan-for-projects-outside-github,NEWLINE # we can use a command line tool to download, instead. It'sNEWLINE # not very Pythonic, but it doesn't bring our VM to its knees.NEWLINE cmd = [NEWLINE 'wget',NEWLINE config["tool_url"],NEWLINE '--post-data',NEWLINE f'token={token}&project={config["project_name"]}',NEWLINE '-O',NEWLINE _cov_filenameNEWLINE ]NEWLINE BuilderUtils.logged_call(cmd,NEWLINE log_file=os.path.join(build_root, 'coverity-tools-download-output.txt'))NEWLINENEWLINE # make sure we have a build rootNEWLINE if not os.path.isdir(build_root):NEWLINE os.makedirs(build_root)NEWLINE os.chdir(build_root)NEWLINENEWLINE # The name of the top-level directory in the tarball changes everyNEWLINE # time Coverity releases a new version of the tool. So searchNEWLINE # around and hope we find something.NEWLINE logger.debug('Expanding ' + _cov_filename)NEWLINE BuilderUtils.logged_call(['tar', 'xf', os.path.join(config['tool_dir'], _cov_filename)],NEWLINE log_file=os.path.join(build_root, 'coverity-tools-untar-output.txt'))NEWLINE cov_path=''NEWLINE for file in os.listdir(build_root):NEWLINE if file.startswith('cov-'):NEWLINE cov_path = os.path.join(build_root, file, 'bin')NEWLINE breakNEWLINE logger.debug('Found Coverity path %s' % (cov_path))NEWLINENEWLINE child_env = os.environ.copy()NEWLINE child_env['PATH'] = cov_path + ':' + child_env['PATH']NEWLINENEWLINE logger.debug('Extracting build tarball: %s' % (source_tarball))NEWLINE BuilderUtils.logged_call(['tar', 'xf', source_tarball],NEWLINE log_file=os.path.join(build_root, 'coverity-source-untar-output.txt'))NEWLINENEWLINE # guess the directory based on the tarball name. Don't worryNEWLINE # about the exception, because we want out in that case anyway...NEWLINE build_version = re.search('^' + config['project_prefix'] + '-(.*)\.tar\..*$',NEWLINE os.path.basename(source_tarball)).group(1)NEWLINE srcdir = config['project_prefix'] + '-' + build_versionNEWLINE os.chdir(srcdir)NEWLINENEWLINE logger.debug('coverity configure')NEWLINE args = ['./configure']NEWLINE if 'configure_args' in config:NEWLINE args.extend(shlex.split(config['configure_args']))NEWLINE BuilderUtils.logged_call(args, env=child_env,NEWLINE log_file=os.path.join(build_root, 'coverity-configure-output.txt'))NEWLINENEWLINE logger.debug('coverity build')NEWLINE args = ['cov-build', '--dir', 'cov-int', 'make']NEWLINE if 'make_args' in config:NEWLINE args.extend(shlex.split(config['make_args']))NEWLINE BuilderUtils.logged_call(args, env=child_env,NEWLINE log_file=os.path.join(build_root, 'coverity-make-output.txt'))NEWLINENEWLINE logger.debug('bundling results')NEWLINE results_tarball = os.path.join(build_root, 'analyzed.tar.bz2')NEWLINE BuilderUtils.logged_call(['tar', 'jcf', results_tarball, 'cov-int'],NEWLINE log_file=os.path.join(build_root, 'coverity-results-tar-output.txt'))NEWLINENEWLINE logger.debug('submitting results')NEWLINE url = 'https://scan.coverity.com/builds?project=' + config['project_name']NEWLINE files = { 'file': open(results_tarball, 'rb') }NEWLINE values = { 'email' : config['email'],NEWLINE 'version' : build_version,NEWLINE 'description' : 'nightly-master',NEWLINE 'token' : token }NEWLINE r = requests.post(url, files=files, data=values)NEWLINE r.raise_for_status()NEWLINENEWLINENEWLINEdef run_coverity(logger, build_root, source_tarball, config):NEWLINE """Run coverity test and submit resultsNEWLINENEWLINE Run Coverity test and submit results to their server. Can be runNEWLINE either standalone (with a tarball as a target) or integrated intoNEWLINE the Builder class.NEWLINENEWLINE """NEWLINE cwd = os.getcwd()NEWLINE try:NEWLINE run_coverity_internal(logger, build_root, source_tarball, config)NEWLINE finally:NEWLINE os.chdir(cwd)NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE config = { 'tool_url' : 'https://scan.coverity.com/download/cxx/linux64',NEWLINE 'log_level' : 'INFO' }NEWLINENEWLINE parser = argparse.ArgumentParser(description='Coverity submission script for Open MPI related projects')NEWLINE parser.add_argument('--log-level', help='Log level.', type=str,NEWLINE choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'])NEWLINE parser.add_argument('--build-root',NEWLINE help='Directory to use as base of build tree.',NEWLINE type=str)NEWLINE parser.add_argument('--source-tarball',NEWLINE help='Tarball to submit for analysis',NEWLINE type=str)NEWLINE parser.add_argument('--tool-dir',NEWLINE help='Directory in which to store downloaded tool (for reuse)',NEWLINE type=str)NEWLINE parser.add_argument('--tool-url',NEWLINE help='URL for downloading Coverity tool',NEWLINE type=str)NEWLINE parser.add_argument('--project-name',NEWLINE help='Coverity project name',NEWLINE type=str)NEWLINE parser.add_argument('--project-prefix',NEWLINE help='prefix of the tarball directory',NEWLINE type=str)NEWLINE parser.add_argument('--token-file',NEWLINE help='File containing the Coverity token for project',NEWLINE type=str)NEWLINE parser.add_argument('--configure-args',NEWLINE help='Configuration arguments for source tarball',NEWLINE type=str)NEWLINE parser.add_argument('--make-args',NEWLINE help='Build arguments for source tarball',NEWLINE type=str)NEWLINE parser.add_argument('--email',NEWLINE help='Coverity submission email address',NEWLINE type=str)NEWLINENEWLINE for key, value in vars(parser.parse_args()).iteritems():NEWLINE if not value == None:NEWLINE config[key] = valueNEWLINENEWLINE logging.basicConfig()NEWLINE logger = logging.getLogger()NEWLINE logger.setLevel(config['log_level'])NEWLINENEWLINE run_coverity(logger, config['build_root'], config['source_tarball'], config)NEWLINE
import jsonNEWLINEimport osNEWLINEimport csvNEWLINEimport reNEWLINEimport pandas as pdNEWLINEimport pickleNEWLINEimport collectionsNEWLINEimport subprocessNEWLINENEWLINENEWLINEimport sdi_utils.gensolution as gsNEWLINEimport sdi_utils.set_logging as slogNEWLINEimport sdi_utils.textfield_parser as tfpNEWLINEimport sdi_utils.tprogress as tpNEWLINENEWLINENEWLINENEWLINEtry:NEWLINE apiNEWLINEexcept NameError:NEWLINE class api:NEWLINENEWLINE queue = list()NEWLINE class Message:NEWLINE def __init__(self, body=None, attributes=""):NEWLINE self.body = bodyNEWLINE self.attributes = attributesNEWLINENEWLINE def send(port, msg):NEWLINE if port == outports[1]['name'] :NEWLINE api.queue.append(msg)NEWLINE if port == outports[0]['name'] :NEWLINE #print(msg)NEWLINE passNEWLINENEWLINE def set_config(config):NEWLINE api.config = configNEWLINENEWLINE class config:NEWLINE ## Meta dataNEWLINE config_params = dict()NEWLINE tags = {'sdi_utils': '','pandas': ''}NEWLINE version = "0.1.0"NEWLINE operator_name = "word_frequency"NEWLINE operator_description = "Word Frequency"NEWLINE operator_description_long = "Calculates word frequency"NEWLINE add_readme = dict()NEWLINENEWLINE debug_mode = TrueNEWLINE config_params['debug_mode'] = {'title': 'Debug mode',NEWLINE 'description': 'Sending debug level information to log port',NEWLINE 'type': 'boolean'}NEWLINENEWLINE word_types = 'PROPN'NEWLINE config_params['word_types'] = {'title': 'Word types',NEWLINE 'description': 'Setting word type selection for delete',NEWLINE 'type': 'string'}NEWLINENEWLINE language_filter = 'None'NEWLINE config_params['language_filter'] = {'title': 'Language filter', 'description': 'Filter for languages of media.',NEWLINE 'type': 'string'}NEWLINENEWLINENEWLINEdef process(msg):NEWLINENEWLINE att_dict = msg.attributesNEWLINENEWLINE logger, log_stream = slog.set_logging('word_regex', api.config.debug_mode)NEWLINE logger.info("Main Process started. Logging level: {}".format(logger.level))NEWLINE time_monitor = tp.progress()NEWLINENEWLINE df = msg.bodyNEWLINENEWLINE if not isinstance(df, pd.DataFrame) or df.empty:NEWLINE logger.warning('Empty dataframe, no output send!')NEWLINE api.send(outports[0]['name'], log_stream.getvalue())NEWLINE api.send(outports[2]['name'], api.Message(attributes=att_dict, body=df))NEWLINE return 0NEWLINENEWLINE df['count'] = df['count'].astype('int32')NEWLINENEWLINE # word typeNEWLINE word_types = tfp.read_list(api.config.word_types)NEWLINE if word_types :NEWLINE df = df.loc[df['type'].isin(word_types)]NEWLINENEWLINE # Language filterNEWLINE language_filter = tfp.read_list(api.config.language_filter)NEWLINE if language_filter :NEWLINE df = df.loc[df['language'].isin(language_filter)]NEWLINENEWLINE df = df.groupby(['language','type','word'])['count'].agg('sum').reset_index()NEWLINENEWLINE api.send(outports[1]['name'], api.Message(attributes=att_dict, body=df))NEWLINE api.send(outports[0]['name'],log_stream.getvalue())NEWLINENEWLINENEWLINEinports = [{'name': 'words', 'type': 'message.DataFrame', "description": "Message table."}]NEWLINEoutports = [{'name': 'log', 'type': 'string', "description": "Logging data"}, \NEWLINE {'name': 'data', 'type': 'message.DataFrame', "description": "Table after regex"}]NEWLINENEWLINE#api.set_port_callback(inports[0]['name'], process)NEWLINENEWLINENEWLINEdef test_operator():NEWLINENEWLINE config = api.configNEWLINE config.debug_mode = TrueNEWLINE config.test_mode = FalseNEWLINE config.language_filter = 'None'NEWLINE config.word_types = 'None'NEWLINE api.set_config(config)NEWLINENEWLINE doc_file = '/Users/Shared/data/onlinemedia/data/word_extraction.csv'NEWLINE df = pd.read_csv(doc_file,sep=',',nrows=10000000)NEWLINE msg = api.Message(attributes={'file': {'path': doc_file},'format':'pandas'}, body=df)NEWLINE process(msg)NEWLINENEWLINE out_file = '/Users/Shared/data/onlinemedia/data/word_freq_test.csv'NEWLINE df_list = [d.body for d in api.queue]NEWLINE pd.concat(df_list).to_csv(out_file,index=False)NEWLINENEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE #test_operator()NEWLINENEWLINE if True :NEWLINE subprocess.run(["rm",'-r','/Users/d051079/OneDrive - SAP SE/GitHub/di_textanalysis/solution/operators/textanalysis_' + api.config.version])NEWLINE gs.gensolution(os.path.realpath(__file__), api.config, inports, outports)NEWLINE solution_name = api.config.operator_name+'_'+api.config.versionNEWLINE subprocess.run(["vctl", "solution", "bundle", '/Users/d051079/OneDrive - SAP SE/GitHub/di_textanalysis/solution/operators/textanalysis_' + api.config.version,\NEWLINE "-t", solution_name])NEWLINE subprocess.run(["mv", solution_name+'.zip', '../../../solution/operators'])NEWLINENEWLINENEWLINENEWLINENEWLINE
import osNEWLINEimport shutilNEWLINEimport unittestNEWLINEfrom xbrr.edinet.client.document_client import DocumentClientNEWLINEfrom xbrr.edinet.reader.doc import DocNEWLINENEWLINENEWLINEclass TestDoc(unittest.TestCase):NEWLINENEWLINE @classmethodNEWLINE def setUpClass(cls):NEWLINE cls._dir = os.path.join(os.path.dirname(__file__), "../data")NEWLINE client = DocumentClient()NEWLINE cls.root_dir = client.get_xbrl("S100FGR9", save_dir=cls._dir,NEWLINE expand_level="dir")NEWLINE cls.doc = Doc(root_dir=cls.root_dir, xbrl_kind="public")NEWLINENEWLINE @classmethodNEWLINE def tearDownClass(cls):NEWLINE shutil.rmtree(cls.root_dir)NEWLINENEWLINE def test_doc(self):NEWLINE doc = self.docNEWLINENEWLINE self.assertGreater(len(doc.xsd.find_all("element")), 0)NEWLINE self.assertGreater(len(doc.cal.find_all("calculationLink")), 0)NEWLINE self.assertGreater(len(doc.def_.find_all("definitionArc")), 0)NEWLINE self.assertGreater(len(doc.lab.find_all("labelLink")), 0)NEWLINE self.assertGreater(len(doc.lab_en.find_all("labelLink")), 0)NEWLINE self.assertGreater(len(doc.pre.find_all("presentationLink")), 0)NEWLINE self.assertTrue(doc.man.find("manifest"))NEWLINENEWLINE def test_find_xsduri(self):NEWLINE doc = self.docNEWLINE self.assertEqual(doc.find_xsduri("http://disclosure.edinet-fsa.go.jp/taxonomy/jpcrp/2018-02-28/jpcrp_cor"),NEWLINE "http://disclosure.edinet-fsa.go.jp/taxonomy/jpcrp/2018-02-28/jpcrp_cor_2018-02-28.xsd")NEWLINENEWLINE self.assertEqual(doc.find_xsduri("http://disclosure.edinet-fsa.go.jp/jpcrp030000/asr/001/E01726-000/2018-12-31/01/2019-03-27"),NEWLINE "jpcrp030000-asr-001_E01726-000_2018-12-31_01_2019-03-27.xsd")NEWLINE self.assertEqual(doc.find_xsduri("local"),NEWLINE "jpcrp030000-asr-001_E01726-000_2018-12-31_01_2019-03-27.xsd")NEWLINENEWLINE def test_find_laburi(self):NEWLINE doc = self.docNEWLINE self.assertEqual(doc.find_laburi('local', 'lab'), "jpcrp030000-asr-001_E01726-000_2018-12-31_01_2019-03-27_lab.xml")NEWLINE self.assertEqual(doc.find_laburi('jpcrp030000-asr-001_E01726-000_2018-12-31_01_2019-03-27.xsd', 'lab'), "jpcrp030000-asr-001_E01726-000_2018-12-31_01_2019-03-27_lab.xml")NEWLINENEWLINE self.assertEqual(doc.find_laburi(doc.find_xsduri('http://disclosure.edinet-fsa.go.jp/taxonomy/jpcrp/2018-02-28/jpcrp_cor'), 'lab'), NEWLINE "http://disclosure.edinet-fsa.go.jp/taxonomy/jpcrp/2018-02-28/label/jpcrp_2018-02-28_lab.xml")NEWLINE
# Copyright (c) 2021 Benjamin Holt -- MIT LicenseNEWLINENEWLINEfrom setuptools import setupNEWLINENEWLINEfrom allgit import _versionNEWLINE#####NEWLINENEWLINENEWLINE#####NEWLINEwith open("README.md", "r") as f:NEWLINE long_description = f.read()NEWLINENEWLINEsetup(NEWLINE name="allgit",NEWLINE version=_version,NEWLINE description="""Powerful "git multiplexer" for easily working with many repositories""",NEWLINE long_description=long_description, # FIXME: Do something better than just dumping the whole readmeNEWLINE long_description_content_type="text/markdown",NEWLINE url="https://github.com/inventhouse/allgit",NEWLINE author="Benjamin Holt",NEWLINE license="MIT",NEWLINE py_modules=["allgit"],NEWLINE entry_points={NEWLINE "console_scripts": [NEWLINE "allgit=allgit:main",NEWLINE ],NEWLINE },NEWLINE classifiers=[NEWLINE "Development Status :: 5 - Production/Stable",NEWLINE "Environment :: Console",NEWLINE "Intended Audience :: Developers",NEWLINE "Operating System :: Unix",NEWLINE "License :: OSI Approved :: MIT License",NEWLINE "Natural Language :: English",NEWLINE "Programming Language :: Python :: 3.6",NEWLINE "Topic :: Software Development :: Version Control",NEWLINE ],NEWLINE keywords="git",NEWLINE)NEWLINE#####NEWLINE
# -*- coding: utf-8 -*-NEWLINE# Generated by Django 1.9 on 2016-01-14 10:38NEWLINEfrom __future__ import unicode_literalsNEWLINENEWLINEfrom django.db import migrations, modelsNEWLINENEWLINENEWLINEclass Migration(migrations.Migration):NEWLINENEWLINE initial = TrueNEWLINENEWLINE dependencies = [NEWLINE ]NEWLINENEWLINE operations = [NEWLINE migrations.CreateModel(NEWLINE name='Article',NEWLINE fields=[NEWLINE ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),NEWLINE ('heading_one', models.CharField(max_length=500)),NEWLINE ('question', models.CharField(blank=True, max_length=200)),NEWLINE ('h1_paragraph_one', models.TextField(blank=True)),NEWLINE ('h1_paragraph_two', models.TextField(blank=True)),NEWLINE ('h1_paragraph_three', models.TextField(blank=True)),NEWLINE ('answer', models.CharField(blank=True, max_length=200)),NEWLINE ('h1_paragraph_four', models.TextField(blank=True)),NEWLINE ('h1_paragraph_five', models.TextField(blank=True)),NEWLINE ('h1_paragraph_six', models.TextField(blank=True)),NEWLINE ('h1_paragraph_seven', models.TextField(blank=True)),NEWLINE ('h1_paragraph_eight', models.TextField(blank=True)),NEWLINE ('h1_paragraph_nine', models.TextField(blank=True)),NEWLINE ('h1_paragraph_ten', models.TextField(blank=True)),NEWLINE ('image_one', models.ImageField(upload_to='')),NEWLINE ('heading_two', models.CharField(max_length=500)),NEWLINE ('sub_heading_two', models.CharField(blank=True, max_length=200)),NEWLINE ('h2_paragraph_one', models.TextField(blank=True)),NEWLINE ('h2_paragraph_two', models.TextField(blank=True)),NEWLINE ('h2_paragraph_three', models.TextField(blank=True)),NEWLINE ('h2_paragraph_four', models.TextField(blank=True)),NEWLINE ('h2_paragraph_five', models.TextField(blank=True)),NEWLINE ('h2_paragraph_six', models.TextField(blank=True)),NEWLINE ('h2_paragraph_seven', models.TextField(blank=True)),NEWLINE ('h2_paragraph_eight', models.TextField(blank=True)),NEWLINE ('h2_paragraph_nine', models.TextField(blank=True)),NEWLINE ('h2_paragraph_ten', models.TextField(blank=True)),NEWLINE ('image_two', models.ImageField(upload_to='')),NEWLINE ('heading_three', models.CharField(max_length=500)),NEWLINE ('sub_heading_three', models.CharField(blank=True, max_length=200)),NEWLINE ('h3_paragraph_one', models.TextField(blank=True)),NEWLINE ('h3_paragraph_two', models.TextField(blank=True)),NEWLINE ('h3_paragraph_three', models.TextField(blank=True)),NEWLINE ('h3_paragraph_four', models.TextField(blank=True)),NEWLINE ('h3_paragraph_five', models.TextField(blank=True)),NEWLINE ('h3_paragraph_six', models.TextField(blank=True)),NEWLINE ('h3_paragraph_seven', models.TextField(blank=True)),NEWLINE ('h3_paragraph_eight', models.TextField(blank=True)),NEWLINE ('h3_paragraph_nine', models.TextField(blank=True)),NEWLINE ('h3_paragraph_ten', models.TextField(blank=True)),NEWLINE ('image_three', models.ImageField(upload_to='')),NEWLINE ('heading_four', models.CharField(max_length=500)),NEWLINE ('sub_heading_four', models.CharField(blank=True, max_length=200)),NEWLINE ('h4_paragraph_one', models.TextField(blank=True)),NEWLINE ('h4_paragraph_two', models.TextField(blank=True)),NEWLINE ('h4_paragraph_three', models.TextField(blank=True)),NEWLINE ('h4_paragraph_four', models.TextField(blank=True)),NEWLINE ('h4_paragraph_five', models.TextField(blank=True)),NEWLINE ('h4_paragraph_six', models.TextField(blank=True)),NEWLINE ('h4_paragraph_seven', models.TextField(blank=True)),NEWLINE ('h4_paragraph_eight', models.TextField(blank=True)),NEWLINE ('h4_paragraph_nine', models.TextField(blank=True)),NEWLINE ('h4_paragraph_ten', models.TextField(blank=True)),NEWLINE ('image_four', models.ImageField(upload_to='')),NEWLINE ('heading_five', models.CharField(max_length=500)),NEWLINE ('sub_heading_five', models.CharField(blank=True, max_length=200)),NEWLINE ('h5_paragraph_one', models.TextField(blank=True)),NEWLINE ('h5_paragraph_two', models.TextField(blank=True)),NEWLINE ('h5_paragraph_three', models.TextField(blank=True)),NEWLINE ('h5_paragraph_four', models.TextField(blank=True)),NEWLINE ('h5_paragraph_five', models.TextField(blank=True)),NEWLINE ('h5_paragraph_six', models.TextField(blank=True)),NEWLINE ('h5_paragraph_seven', models.TextField(blank=True)),NEWLINE ('h5_paragraph_eight', models.TextField(blank=True)),NEWLINE ('h5_paragraph_nine', models.TextField(blank=True)),NEWLINE ('h5_paragraph_ten', models.TextField(blank=True)),NEWLINE ('image_five', models.ImageField(upload_to='')),NEWLINE ('heading_six', models.CharField(max_length=500)),NEWLINE ('sub_heading_six', models.CharField(blank=True, max_length=200)),NEWLINE ('h6_paragraph_one', models.TextField(blank=True)),NEWLINE ('h6_paragraph_two', models.TextField(blank=True)),NEWLINE ('h6_paragraph_three', models.TextField(blank=True)),NEWLINE ('h6_paragraph_four', models.TextField(blank=True)),NEWLINE ('h6_paragraph_five', models.TextField(blank=True)),NEWLINE ('h6_paragraph_six', models.TextField(blank=True)),NEWLINE ('h6_paragraph_seven', models.TextField(blank=True)),NEWLINE ('h6_paragraph_eight', models.TextField(blank=True)),NEWLINE ('h6_paragraph_nine', models.TextField(blank=True)),NEWLINE ('h6_paragraph_ten', models.TextField(blank=True)),NEWLINE ('image_six', models.ImageField(upload_to='')),NEWLINE ('pub_date', models.DateTimeField(auto_now_add=True, verbose_name='Date Published')),NEWLINE ],NEWLINE ),NEWLINE ]NEWLINE
from datetime import datetimeNEWLINENEWLINEdef convert_to_datetime(line):NEWLINE '''Extract date and time from a line of text, return as a datetime object.'''NEWLINE NEWLINE # Find the part of the string that contains the information about time.NEWLINE date_string = line.split()[1]NEWLINE date = datetime.strptime(date_string, "%Y-%m-%dT%H:%M:%S")NEWLINE return dateNEWLINENEWLINEdef time_between_shutdowns(loglines):NEWLINE '''TODO 2:NEWLINE Extract shutdown events ("Shutdown initiated") from loglines and calculate the NEWLINE timedelta between the first and last one. NEWLINE Return this datetime.timedelta object.'''NEWLINE NEWLINE datetimes_from_log = [convert_to_datetime(line) for line in loglines if line.startswith('INFO')]NEWLINE return datetimes_from_log[-1] - datetimes_from_log[0]NEWLINE
"""Tests the plotting function developed as part of 2E"""NEWLINENEWLINE# ImportsNEWLINEfrom floodsystem.plot import plot_water_levelsNEWLINEfrom floodsystem.datafetcher import fetch_measure_levelsNEWLINEimport datetimeNEWLINEfrom floodsystem.station import MonitoringStationNEWLINENEWLINEfictional_station = MonitoringStation("station_id", "measure_id",NEWLINE "Line at y=1 and y=9, and a line that goes diagonally from 0 to 10 across 11 days",NEWLINE "coord", [1, 9], "made up river", "New Madeupville")NEWLINENEWLINEdates = []NEWLINEfor i in range(11):NEWLINE date = datetime.date(2022, 1, 11-i)NEWLINE dates.append(date)NEWLINE # remember that the actual dates go backwards!NEWLINENEWLINElevels = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]NEWLINENEWLINEplot_water_levels(fictional_station, dates, levels)NEWLINENEWLINE#print("Check that this forms a Z shape, that all three lines are plotted, and that the graph has a legend and title")
from setuptools import setupNEWLINENEWLINENEWLINEsetup(NEWLINE name="Flask-Simple-Registration",NEWLINE version="0.1",NEWLINE url="http://github.com/mtrichardson/flask-simple-registration",NEWLINE license="MIT",NEWLINE author="Michael Richardson",NEWLINE author_email="michael@mtrichardson.com",NEWLINE description="Very basic registration support for Flask.",NEWLINE packages=["flaskext"],NEWLINE namespace_packages=["flaskext"],NEWLINE zip_safe=False,NEWLINE install_requires=["setuptools", "Flask", "Flask-SQLAlchemy", "Flask-WTF"]NEWLINE)NEWLINE
# -*- coding:utf-8 -*-NEWLINE# adapted from https://www.itread01.com/content/1527482333.htmlNEWLINENEWLINEimport loggingNEWLINEimport sysNEWLINENEWLINEreload(sys) # reload 才能調用 setdefaultencoding 方法NEWLINEsys.setdefaultencoding('utf-8') # 設置 'utf-8'NEWLINENEWLINENEWLINE# from cfg import configNEWLINENEWLINEclass TimeTool(object):NEWLINE def __init__(self):NEWLINE handler = logging.StreamHandler()NEWLINE formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')NEWLINE handler.setFormatter(formatter)NEWLINE self.logger = logging.getLogger("HistoryReader")NEWLINE self.logger.addHandler(handler)NEWLINE # self.logger.setLevel(config.LOG_LEVEL)NEWLINE self.Nanosecond = 1NEWLINE self.Microsecond = 1000 * self.NanosecondNEWLINE self.Millisecond = 1000 * self.MicrosecondNEWLINE self.Second = 1000 * self.MillisecondNEWLINE self.Minute = 60 * self.SecondNEWLINE self.Hour = 60 * self.MinuteNEWLINE self.unitMap = {NEWLINE "ns": int(self.Nanosecond),NEWLINE "us": int(self.Microsecond),NEWLINE "μs": int(self.Microsecond), # U+00B5 = micro symbolNEWLINE "μs": int(self.Microsecond), # U+03BC = Greek letter muNEWLINE "ms": int(self.Millisecond),NEWLINE "s": int(self.Second),NEWLINE "m": int(self.Minute),NEWLINE "h": int(self.Hour),NEWLINE }NEWLINE passNEWLINENEWLINE def leadingInt(self, s):NEWLINE x, rem, err = int(0), str(""), "time: bad [0-9]*"NEWLINE i = 0NEWLINE while i < len(s):NEWLINE c = s[i]NEWLINE if c < '0' or c > '9':NEWLINE breakNEWLINE # print xNEWLINE if x > (1 << 63 - 1) / 10:NEWLINE # print "x > (1 << 63-1)/10 => %s > %s" %(x, (1 << 63-1)/10)NEWLINE return 0, "", errNEWLINE x = x * 10 + int(c) - int('0')NEWLINE if x < 0:NEWLINE # print "x < 0 => %s < 0" %(x)NEWLINE return 0, "", errNEWLINE i += 1NEWLINE return x, s[i:], NoneNEWLINENEWLINE def leadingFraction(self, s):NEWLINE x, scale, rem = int(0), float(1), ""NEWLINE i, overflow = 0, FalseNEWLINE while i < len(s):NEWLINE c = s[i]NEWLINE if c < '0' or c > '9':NEWLINE breakNEWLINE if overflow:NEWLINE continueNEWLINE if x > (1 << 63 - 1) / 10:NEWLINE overflow = TrueNEWLINE continueNEWLINE y = x * 10 + int(c) - int('0')NEWLINE if y < 0:NEWLINE overflow = TrueNEWLINE continueNEWLINE x = yNEWLINE scale *= 10NEWLINE i += 1NEWLINE return x, scale, s[i:]NEWLINENEWLINE """NEWLINE 將小時,分鐘,轉換為秒NEWLINE 比如: 5m 轉換為 300秒;5m20s 轉換為320秒NEWLINE time 單位支持:"ns", "us" (or "μs"), "ms", "s", "m", "h"NEWLINE """NEWLINENEWLINE def ParseDuration(self, s):NEWLINE if s == "" or len(s) < 1:NEWLINE return 0NEWLINENEWLINE orig = sNEWLINE neg = FalseNEWLINE d = float(0)NEWLINENEWLINE if s != "":NEWLINE if s[0] == "-" or s[0] == "+":NEWLINE neg = s[0] == "-"NEWLINE s = s[1:]NEWLINENEWLINE if s == "0" or s == "":NEWLINE return 0NEWLINENEWLINE while s != "":NEWLINE v, f, scale = int(0), int(0), float(1)NEWLINENEWLINE # print "S: %s" %sNEWLINE # the next character must be [0-9.]NEWLINE if not (s[0] == "." or '0' <= s[0] and s[0] <= '9'):NEWLINE self.logger.error("time1: invalid duration %s, s:%s" % (orig, s))NEWLINE return 0NEWLINENEWLINE # Consume [0-9]*NEWLINE pl = len(s)NEWLINE v, s, err = self.leadingInt(s)NEWLINE if err != None:NEWLINE self.logger.error("time2, invalid duration %s" % orig)NEWLINE return 0NEWLINE pre = pl != len(s)NEWLINENEWLINE # consume (\.[0-9]*)?NEWLINE post = FalseNEWLINE if s != "" and s[0] == ".":NEWLINE s = s[1:]NEWLINE pl = len(s)NEWLINE f, scale, s = self.leadingFraction(s)NEWLINE post = pl != len(s)NEWLINE if not pre and not post:NEWLINE self.logger.error("time3, invalid duration %s" % orig)NEWLINE return 0NEWLINENEWLINE # Consume unit.NEWLINE i = 0NEWLINE while i < len(s):NEWLINE c = s[i]NEWLINE if c == '.' or '0' <= c and c <= '9':NEWLINE breakNEWLINE i += 1NEWLINE if i == 0:NEWLINE self.logger.error("time4: unkonw unit in duration: %s" % orig)NEWLINE return 0NEWLINE # print "s:%s, i:%s, s[:i]:%s" %(s, i, s[:i])NEWLINE u = s[:i]NEWLINE s = s[i:]NEWLINE if not self.unitMap.has_key(u):NEWLINE self.logger.error("time5: unknow unit %s in duration %s" % (u, orig))NEWLINE return 0NEWLINE unit = self.unitMap[u]NEWLINE if v > (1 << 63 - 1) / unit:NEWLINE self.logger.error("time6: invalid duration %s" % orig)NEWLINE return 0NEWLINE v *= unitNEWLINE if f > 0:NEWLINE v += int(float(f) * (float(unit) / scale))NEWLINE if v < 0:NEWLINE self.logger.error("time7: invalid duration %s" % orig)NEWLINE return 0NEWLINE d += vNEWLINE if d < 0:NEWLINE self.logger.error("time8: invalid duration %s" % orig)NEWLINE return 0NEWLINENEWLINE if neg:NEWLINE d = -dNEWLINE return float(d)NEWLINENEWLINENEWLINEif __name__ == "__main__":NEWLINE from sys import argvNEWLINENEWLINE tools = TimeTool()NEWLINE # s = tools.ParseDuration("1m20.123s")NEWLINE s = tools.ParseDuration(argv[1])NEWLINE print(s / tools.Second)
#!/usr/bin/env python3NEWLINENEWLINE"""Unit tests for Mininet Topologies in mininet_test_topo"""NEWLINENEWLINEfrom unittest import TestCase, mainNEWLINENEWLINEfrom clib.config_generator import FaucetFakeOFTopoGeneratorNEWLINENEWLINENEWLINEclass FaucetTopoTest(TestCase):NEWLINE """Tests for Faucet test suite mininet Topo class generator"""NEWLINENEWLINE serial = 0NEWLINENEWLINE START_PORT = 5NEWLINE PORT_ORDER = [0, 1, 2, 3]NEWLINENEWLINE class FakeExtendedHost:NEWLINE """Fake class for a mininet extended host"""NEWLINENEWLINE def get_serialno(self, *_args, **_kwargs):NEWLINE """"Return mock serial number"""NEWLINE self.serial += 1NEWLINE return self.serialNEWLINENEWLINE def test_port_order(self):NEWLINE """Test port order extension & port order option"""NEWLINE port_order = [3, 2, 1, 0]NEWLINE extended = FaucetFakeOFTopoGenerator.extend_port_order(port_order, max_length=8)NEWLINE self.assertEqual(extended, [3, 2, 1, 0, 7, 6, 5, 4])NEWLINE port_order = [1, 2, 3, 4, 0]NEWLINE extended = FaucetFakeOFTopoGenerator.extend_port_order(port_order, max_length=10)NEWLINE self.assertEqual(extended, [1, 2, 3, 4, 0, 6, 7, 8, 9, 5])NEWLINE host_links = {0: [0], 1: [1]}NEWLINE host_vlans = {0: 0, 1: 0}NEWLINE switch_links = [(0, 1)]NEWLINE link_vlans = {(0, 1): [0]}NEWLINE port_order = [3, 2, 1, 0]NEWLINE expected_ports = [self.START_PORT + port for port in port_order]NEWLINE topo = FaucetFakeOFTopoGenerator(NEWLINE '', '', '',NEWLINE 2, False,NEWLINE host_links, host_vlans, switch_links, link_vlans,NEWLINE start_port=self.START_PORT, port_order=port_order,NEWLINE get_serialno=self.get_serialno)NEWLINE s1_name = topo.switches_by_id[0]NEWLINE s1_ports = list(topo.ports[s1_name].keys())NEWLINE self.assertEqual(s1_ports, expected_ports[:2])NEWLINE s2_name = topo.switches_by_id[1]NEWLINE s2_ports = list(topo.ports[s2_name].keys())NEWLINE self.assertEqual(s2_ports, expected_ports[:2])NEWLINENEWLINE def test_start_port(self):NEWLINE """Test the topology start port parameter option"""NEWLINE start_port = 55NEWLINE host_links = {0: [0], 1: [1]}NEWLINE host_vlans = {0: 0, 1: 0}NEWLINE switch_links = [(0, 1)]NEWLINE link_vlans = {(0, 1): [0]}NEWLINE port_order = [3, 2, 1, 0]NEWLINE expected_ports = [start_port + port for port in port_order]NEWLINE topo = FaucetFakeOFTopoGenerator(NEWLINE '', '', '',NEWLINE 2, False,NEWLINE host_links, host_vlans, switch_links, link_vlans,NEWLINE start_port=start_port, port_order=port_order,NEWLINE get_serialno=self.get_serialno)NEWLINE s1_name, s2_name = topo.switches_by_id.values()NEWLINE h1_name, h2_name = topo.hosts_by_id.values()NEWLINE self.assertEqual(topo.ports[s1_name][expected_ports[0]][0], s2_name)NEWLINE self.assertEqual(topo.ports[s2_name][expected_ports[0]][0], s1_name)NEWLINE self.assertEqual(topo.ports[s1_name][expected_ports[1]][0], h1_name)NEWLINE self.assertEqual(topo.ports[s2_name][expected_ports[1]][0], h2_name)NEWLINENEWLINE def test_hw_build(self):NEWLINE """Test the topology is built with hardware requirements"""NEWLINE host_links = {0: [0], 1: [1]}NEWLINE host_vlans = {0: 0, 1: 0}NEWLINE switch_links = [(0, 1)]NEWLINE link_vlans = {(0, 1): [0]}NEWLINE hw_dpid = 0x123NEWLINE hw_ports = {1: 'p1', 2: 'p2', 3: 'p3', 4: 'p4', 5: 'p5', 6: 'p6'}NEWLINE topo = FaucetFakeOFTopoGenerator(NEWLINE '', '', '',NEWLINE 2, False,NEWLINE host_links, host_vlans, switch_links, link_vlans,NEWLINE hw_dpid=hw_dpid, hw_ports=hw_ports,NEWLINE start_port=self.START_PORT, port_order=self.PORT_ORDER,NEWLINE get_serialno=self.get_serialno)NEWLINE self.assertEqual(topo.dpids_by_id[0], hw_dpid)NEWLINE self.assertEqual(list(topo.ports[topo.switches_by_id[0]].keys()), [1, 2])NEWLINENEWLINE def test_no_links(self):NEWLINE """Test single switch topology"""NEWLINE host_links = {0: [0]}NEWLINE host_vlans = {0: 0}NEWLINE switch_links = {}NEWLINE link_vlans = {}NEWLINE topo = FaucetFakeOFTopoGenerator(NEWLINE '', '', '',NEWLINE 2, False,NEWLINE host_links, host_vlans, switch_links, link_vlans,NEWLINE start_port=self.START_PORT, port_order=self.PORT_ORDER,NEWLINE get_serialno=self.get_serialno)NEWLINE self.assertEqual(len(topo.hosts()), 1)NEWLINE self.assertEqual(len(topo.switches()), 1)NEWLINE self.assertEqual(len(topo.links()), 1)NEWLINE host_name = topo.hosts_by_id[0]NEWLINE switch_name = topo.switches_by_id[0]NEWLINE self.assertEqual((switch_name, host_name), topo.links()[0])NEWLINENEWLINE def test_build(self):NEWLINE """Test the topology is built correctly"""NEWLINE host_links = {0: [0], 1: [1]}NEWLINE host_vlans = {0: 0, 1: [0, 1]}NEWLINE switch_links = [(0, 1), (0, 1), (0, 1)]NEWLINE link_vlans = {(0, 1): [0, 1]}NEWLINE topo = FaucetFakeOFTopoGenerator(NEWLINE '', '', '',NEWLINE 2, False,NEWLINE host_links, host_vlans, switch_links, link_vlans,NEWLINE start_port=self.START_PORT, port_order=self.PORT_ORDER,NEWLINE get_serialno=self.get_serialno)NEWLINE self.assertEqual(len(topo.dpids_by_id), 2)NEWLINE self.assertEqual(len(topo.hosts_by_id), 2)NEWLINE self.assertEqual(len(topo.switches_by_id), 2)NEWLINE _, host_port_maps, link_port_maps = topo.create_port_maps()NEWLINE self.assertEqual(len(link_port_maps[(0, 1)]), 3)NEWLINE self.assertEqual(len(host_port_maps[0]), 1)NEWLINE self.assertEqual(len(host_port_maps[1]), 1)NEWLINE host0, host1 = topo.hosts_by_id.values()NEWLINE dp0, dp1 = topo.switches_by_id.values()NEWLINE links = topo.links()NEWLINE self.assertIn((dp0, host0), links)NEWLINE self.assertIn((dp1, host1), links)NEWLINE self.assertIn((dp0, dp1), links)NEWLINE self.assertEqual(links.count((dp0, dp1)), 3)NEWLINENEWLINE def test_host_options(self):NEWLINE """Test the topology correctly provides mininet host options"""NEWLINE host_options = {NEWLINE 0: {'inNamespace': True, 'ip': '127.0.0.1'},NEWLINE 1: {'cls': self.FakeExtendedHost}}NEWLINE host_links = {0: [0], 1: [0]}NEWLINE host_vlans = {0: 0, 1: None}NEWLINE switch_links = []NEWLINE link_vlans = {}NEWLINE topo = FaucetFakeOFTopoGenerator(NEWLINE '', '', '',NEWLINE 2, False,NEWLINE host_links, host_vlans, switch_links, link_vlans,NEWLINE host_options=host_options,NEWLINE start_port=self.START_PORT, port_order=self.PORT_ORDER,NEWLINE get_serialno=self.get_serialno)NEWLINE for host_id, opts in host_options.items():NEWLINE info = topo.nodeInfo(topo.hosts_by_id[host_id])NEWLINE for key, value in opts.items():NEWLINE self.assertIn(key, info)NEWLINE self.assertEqual(value, info[key])NEWLINENEWLINE def test_link_port_map(self):NEWLINE """Test correctly generated link port map"""NEWLINE host_links = {0: [0], 1: [1]}NEWLINE host_vlans = {0: 0, 1: 0}NEWLINE switch_links = [(0, 1), (0, 1), (1, 2)]NEWLINE link_vlans = {edge: None for edge in switch_links}NEWLINE topo = FaucetFakeOFTopoGenerator(NEWLINE '', '', '',NEWLINE 2, False,NEWLINE host_links, host_vlans, switch_links, link_vlans,NEWLINE start_port=self.START_PORT, port_order=self.PORT_ORDER,NEWLINE get_serialno=self.get_serialno)NEWLINE link_port_maps = topo._create_link_port_map()NEWLINE self.assertEqual(NEWLINE link_port_maps,NEWLINE {(0, 1): [5, 6], (1, 0): [5, 6], (1, 2): [7], (2, 1): [5]})NEWLINENEWLINE def test_host_port_map(self):NEWLINE """Test correctly generated host port map"""NEWLINE host_links = {0: [0, 2], 1: [1]}NEWLINE host_vlans = {0: 0, 1: 0}NEWLINE switch_links = [(0, 1), (0, 1), (1, 2)]NEWLINE link_vlans = {edge: None for edge in switch_links}NEWLINE topo = FaucetFakeOFTopoGenerator(NEWLINE '', '', '',NEWLINE 2, False,NEWLINE host_links, host_vlans, switch_links, link_vlans,NEWLINE start_port=self.START_PORT, port_order=self.PORT_ORDER,NEWLINE get_serialno=self.get_serialno)NEWLINE host_port_maps = topo._create_host_port_map()NEWLINE self.assertEqual(NEWLINE host_port_maps,NEWLINE {0: {0: [7], 2: [6]}, 1: {1: [8]}})NEWLINENEWLINENEWLINEif __name__ == "__main__":NEWLINE main()NEWLINE
#!/usr/bin/env pythonNEWLINE# encoding: utf-8NEWLINENEWLINEname = "Intra_R_Add_Exo_scission/training"NEWLINEshortDesc = "Kinetics used to train group additivity values"NEWLINElongDesc = """NEWLINEPut kinetic parameters for reactions to use as a training set for fittingNEWLINEgroup additivity values in this file.NEWLINE"""NEWLINENEWLINE
import pytestNEWLINEfrom numerous.engine.model.external_mappings import ExternalMappingElementNEWLINENEWLINEfrom numerous.utils.data_loader import InMemoryDataLoaderNEWLINEfrom pytest import approxNEWLINENEWLINEfrom numerous.engine.model.external_mappings.interpolation_type import InterpolationTypeNEWLINEfrom numerous.engine.model import ModelNEWLINEfrom numerous.engine.simulation import SimulationNEWLINENEWLINEfrom numerous.engine.system import Subsystem, ConnectorItem, Item, ConnectorTwoWayNEWLINEfrom numerous import EquationBase, EquationNEWLINEfrom numerous.engine.simulation.solvers.base_solver import solver_typesNEWLINEfrom tests.test_equations import TestEq_ground, Test_Eq, TestEq_inputNEWLINENEWLINENEWLINE@pytest.fixture(autouse=True)NEWLINEdef run_before_and_after_tests():NEWLINE import shutilNEWLINE shutil.rmtree('./tmp', ignore_errors=True)NEWLINE yieldNEWLINENEWLINENEWLINE@pytest.fixtureNEWLINEdef test_eq1():NEWLINE class TestEq1(EquationBase):NEWLINE def __init__(self, P=10):NEWLINE super().__init__(tag='example_1')NEWLINE self.add_parameter('P', P)NEWLINE self.add_state('T1', 0)NEWLINE self.add_state('T2', 0)NEWLINE self.add_state('T3', 0)NEWLINE self.add_state('T4', 0)NEWLINE # self.add_parameter('T_4', 0)NEWLINE self.add_constant('TG', 10)NEWLINE self.add_constant('R1', 10)NEWLINE self.add_constant('R2', 5)NEWLINE self.add_constant('R3', 3)NEWLINE self.add_constant('RG', 2)NEWLINENEWLINE @Equation()NEWLINE def eval(self, scope):NEWLINE scope.T1_dot = scope.P - (scope.T1 - scope.T2) / scope.R1NEWLINE scope.T2_dot = (scope.T1 - scope.T2) / scope.R1 - (scope.T2 - scope.T3) / scope.R2NEWLINE scope.T3_dot = (scope.T2 - scope.T3) / scope.R2 - (scope.T3 - scope.T4) / scope.R3NEWLINE scope.T4_dot = (scope.T3 - scope.T4) / scope.R3 - (scope.T4 - scope.TG) / scope.RGNEWLINENEWLINE return TestEq1(P=100)NEWLINENEWLINENEWLINE@pytest.fixtureNEWLINEdef simple_item(test_eq1):NEWLINE class T1(Item):NEWLINE def __init__(self, tag):NEWLINE super().__init__(tag)NEWLINENEWLINE t1 = self.create_namespace('t1')NEWLINENEWLINE t1.add_equations([test_eq1])NEWLINENEWLINE return T1('test_item')NEWLINENEWLINENEWLINE@pytest.fixtureNEWLINEdef ms1(simple_item):NEWLINE class S1(Subsystem):NEWLINE def __init__(self, tag):NEWLINE super().__init__(tag)NEWLINE self.register_items([simple_item])NEWLINENEWLINE return S1('S1')NEWLINENEWLINENEWLINE@pytest.fixtureNEWLINEdef ms2():NEWLINE class I(Item):NEWLINE def __init__(self, tag, P, T, R):NEWLINE super().__init__(tag)NEWLINENEWLINE t1 = self.create_namespace('t1')NEWLINE t1.add_equations([TestEq_input(P=P, T=T, R=R)])NEWLINENEWLINE class T(Item):NEWLINE def __init__(self, tag, T, R):NEWLINE super().__init__(tag)NEWLINENEWLINE t1 = self.create_namespace('t1')NEWLINE t1.add_equations([Test_Eq(T=T, R=R)])NEWLINENEWLINE class G(Item):NEWLINE def __init__(self, tag, TG, RG):NEWLINE super().__init__(tag)NEWLINENEWLINE t1 = self.create_namespace('t1')NEWLINE t1.add_equations([TestEq_ground(TG=TG, RG=RG)])NEWLINENEWLINE class S2(Subsystem):NEWLINE def __init__(self, tag):NEWLINE super().__init__(tag)NEWLINENEWLINE input = I('1', P=100, T=0, R=10)NEWLINE item1 = T('2', T=0, R=5)NEWLINE item2 = T('3', T=0, R=3)NEWLINE item3 = T('4', T=0, R=2)NEWLINE ## RG is redundant we use item3.R as a last value of R in a chainNEWLINE ground = G('5', TG=10, RG=2)NEWLINENEWLINE input.t1.T_o.add_mapping(item1.t1.T)NEWLINENEWLINE # item1.bind(input=input, output=item2)NEWLINENEWLINE item1.t1.R_i.add_mapping(input.t1.R)NEWLINE item1.t1.T_i.add_mapping(input.t1.T)NEWLINE item1.t1.T_o.add_mapping(item2.t1.T)NEWLINE # t_0 = item1.t1.T_oNEWLINE # item1.t1.T_o = item2.t1.TNEWLINENEWLINE item2.t1.R_i.add_mapping(item1.t1.R)NEWLINE item2.t1.T_i.add_mapping(item1.t1.T)NEWLINE item2.t1.T_o.add_mapping(item3.t1.T)NEWLINENEWLINE item3.t1.R_i.add_mapping(item2.t1.R)NEWLINE item3.t1.T_i.add_mapping(item2.t1.T)NEWLINE item3.t1.T_o.add_mapping(ground.t1.T)NEWLINENEWLINE self.register_items([input, item1, item2, item3, ground])NEWLINENEWLINE return S2('S2')NEWLINENEWLINENEWLINE@pytest.fixtureNEWLINEdef ms3():NEWLINE class I(ConnectorItem):NEWLINE def __init__(self, tag, P, T, R):NEWLINE super(I, self).__init__(tag)NEWLINENEWLINE self.create_binding('output')NEWLINENEWLINE t1 = self.create_namespace('t1')NEWLINENEWLINE t1.add_equations([TestEq_input(P=P, T=T, R=R)])NEWLINE ##this line has to be after t1.add_equations since t1 inside output is created thereNEWLINE self.output.t1.create_variable(name='T')NEWLINE t1.T_o = self.output.t1.TNEWLINENEWLINE class T(ConnectorTwoWay):NEWLINE def __init__(self, tag, T, R):NEWLINE super().__init__(tag, side1_name='input', side2_name='output')NEWLINENEWLINE t1 = self.create_namespace('t1')NEWLINE t1.add_equations([Test_Eq(T=T, R=R)])NEWLINENEWLINE t1.R_i = self.input.t1.RNEWLINE t1.T_i = self.input.t1.TNEWLINENEWLINE ##we ask for variable TNEWLINE t1.T_o = self.output.t1.TNEWLINENEWLINE class G(Item):NEWLINE def __init__(self, tag, TG, RG):NEWLINE super().__init__(tag)NEWLINENEWLINE t1 = self.create_namespace('t1')NEWLINE t1.add_equations([TestEq_ground(TG=TG, RG=RG)])NEWLINENEWLINE # ##since we asked for variable T in binding we have to create variable T and map it to TGNEWLINE # t1.create_variable('T')NEWLINE # t1.T = t1.TGNEWLINENEWLINE class S3(Subsystem):NEWLINE def __init__(self, tag):NEWLINE super().__init__(tag)NEWLINENEWLINE input = I('1', P=100, T=0, R=10)NEWLINE item1 = T('2', T=0, R=5)NEWLINE item2 = T('3', T=0, R=3)NEWLINE item3 = T('4', T=0, R=2)NEWLINE ## RG is redundant we use item3.R as a last value of R in a chainNEWLINE ground = G('5', TG=10, RG=2)NEWLINENEWLINE input.bind(output=item1)NEWLINENEWLINE item1.bind(input=input, output=item2)NEWLINENEWLINE item2.bind(input=item1, output=item3)NEWLINE item3.bind(input=item2, output=ground)NEWLINENEWLINE self.register_items([input, item1, item2, item3, ground])NEWLINENEWLINE return S3('S3')NEWLINENEWLINENEWLINE@pytest.mark.parametrize("solver", solver_types)NEWLINE@pytest.mark.parametrize("use_llvm", [True, False])NEWLINEdef test_model_var_referencing(ms1, solver, use_llvm):NEWLINE m1 = Model(ms1, use_llvm=use_llvm)NEWLINE s1 = Simulation(m1, t_start=0, t_stop=1000, num=10, solver_type=solver)NEWLINE s1.solve()NEWLINE assert approx(list(m1.states_as_vector[::-1]), rel=0.01) == [2010, 1010, 510, 210]NEWLINENEWLINENEWLINE@pytest.mark.parametrize("solver", solver_types)NEWLINE@pytest.mark.skip(reason="Functionality not implemented in current version")NEWLINEdef test_model_save_only_aliases(ms3, solver):NEWLINE of = OutputFilter(only_aliases=True)NEWLINE m1 = Model(ms3, historian_filter=of)NEWLINE s1 = Simulation(m1, t_start=0, t_stop=1000, num=10, solver_type=solver)NEWLINE s1.solve()NEWLINE assert m1.historian_df.emptyNEWLINENEWLINENEWLINE@pytest.mark.parametrize("solver", solver_types)NEWLINE@pytest.mark.skip(reason="Functionality not implemented in current version")NEWLINEdef test_model_save_only_aliases2(ms3, solver):NEWLINE of = OutputFilter(only_aliases=True)NEWLINE m1 = Model(ms3, historian_filter=of)NEWLINE item = m1.search_items('2')[0]NEWLINE columns_number = 0NEWLINE for i, var in enumerate(item.get_variables()):NEWLINE var[0].alias = str(i)NEWLINE columns_number += 1NEWLINENEWLINE s1 = Simulation(m1, t_start=0, t_stop=1000, num=10, solver_type=solver)NEWLINE s1.solve()NEWLINE assert m1.historian_df.columns.size == columns_numberNEWLINENEWLINENEWLINEdef test_1_item_model(ms1):NEWLINE m1 = Model(ms1)NEWLINE item = m1.search_items('test_item')[0]NEWLINE assert item.t1.P.value == 100NEWLINENEWLINENEWLINE@pytest.mark.parametrize("solver", solver_types)NEWLINE@pytest.mark.parametrize("use_llvm", [True, False])NEWLINEdef test_callback_step_item_model(ms3, solver, use_llvm):NEWLINE def action(time, variables):NEWLINE if int(time) == 119:NEWLINE raise ValueError("Overflow of state. time:119")NEWLINENEWLINE def condition(time, states):NEWLINE return 500 - states['S3.3.t1.T']NEWLINENEWLINE def action2(time, variables):NEWLINE if int(time) == 118:NEWLINE raise ValueError("Overflow of state. time:119")NEWLINENEWLINE def condition2(time, states):NEWLINE return 500 - states['S3.3.t1.T']NEWLINENEWLINE m1 = Model(ms3, use_llvm=use_llvm)NEWLINE m1.add_event("simple", condition, action)NEWLINE m1.add_event("simple2", condition2, action2)NEWLINE s1 = Simulation(m1, t_start=0, t_stop=1000, num=100, solver_type=solver)NEWLINE with pytest.raises(ValueError, match=r".*time:119.*"):NEWLINE s1.solve()NEWLINENEWLINENEWLINEdef test_add_item_twice_with_same_tag(ms2):NEWLINE class Item_(Item):NEWLINE def __init__(self, tag):NEWLINE super().__init__(tag)NEWLINENEWLINE with pytest.raises(ValueError, match=r".*already registered in system.*"):NEWLINE ms2.register_items([Item_('1')])NEWLINENEWLINENEWLINE@pytest.mark.parametrize("solver", solver_types)NEWLINE@pytest.mark.parametrize("use_llvm", [True, False])NEWLINEdef test_chain_item_model(ms2, solver, use_llvm):NEWLINE m1 = Model(ms2, use_llvm=use_llvm)NEWLINE s1 = Simulation(m1, t_start=0, t_stop=1000, num=10, solver_type=solver)NEWLINE s1.solve()NEWLINE assert approx(m1.states_as_vector, rel=0.01) == [2010, 1010, 510, 210]NEWLINENEWLINENEWLINE@pytest.mark.parametrize("solver", solver_types)NEWLINE@pytest.mark.parametrize("use_llvm", [True, False])NEWLINEdef test_chain_item_binding_model_nested(ms3, solver, use_llvm):NEWLINE ms4 = Subsystem('new_s')NEWLINE ms4.register_item(ms3)NEWLINE m1 = Model(ms4, use_llvm=use_llvm)NEWLINE s1 = Simulation(m1, t_start=0, t_stop=1000, num=10, solver_type=solver)NEWLINE s1.solve()NEWLINE assert approx(m1.states_as_vector, rel=0.01) == [2010, 1010, 510, 210]NEWLINENEWLINENEWLINE@pytest.mark.parametrize("solver", solver_types)NEWLINE@pytest.mark.parametrize("use_llvm", [True, False])NEWLINEdef test_chain_item_binding_model_nested2(ms3, solver, use_llvm):NEWLINE ms4 = Subsystem('new_s4')NEWLINE ms4.register_item(ms3)NEWLINE ms5 = Subsystem('new_s5')NEWLINE ms5.register_item(ms3)NEWLINE ms6 = Subsystem('new_s6')NEWLINE ms6.register_item(ms4)NEWLINE ms6.register_item(ms5)NEWLINE ms7 = Subsystem('new_s7')NEWLINE ms7.register_item(ms6)NEWLINE m1 = Model(ms7, use_llvm=use_llvm)NEWLINE s1 = Simulation(m1, t_start=0, t_stop=1000, num=100, solver_type=solver)NEWLINE s1.solve()NEWLINE assert len(m1.path_variables) == 50NEWLINE assert len(m1.variables) == 25NEWLINE assert approx(m1.states_as_vector, rel=0.01) == [2010, 1010, 510, 210]NEWLINENEWLINENEWLINE@pytest.mark.parametrize("solver", solver_types)NEWLINE@pytest.mark.parametrize("use_llvm", [True, False])NEWLINEdef test_chain_item_binding_model(ms3, solver, use_llvm):NEWLINE m1 = Model(ms3, use_llvm=use_llvm)NEWLINE s1 = Simulation(m1, t_start=0, t_stop=1000, num=100, solver_type=solver)NEWLINE s1.solve()NEWLINE assert approx(m1.states_as_vector, rel=0.01) == [2010, 1010, 510, 210]NEWLINENEWLINENEWLINEclass StaticDataTest(EquationBase, Item):NEWLINE def __init__(self, tag="tm"):NEWLINE super(StaticDataTest, self).__init__(tag)NEWLINENEWLINE ##will map to variable with the same path in external dataframe/datasourceNEWLINE self.add_parameter('T1', 0)NEWLINE self.add_parameter('T2', 0)NEWLINE self.add_parameter('T_i1', 0)NEWLINE self.add_parameter('T_i2', 0)NEWLINE mechanics = self.create_namespace('test_nm')NEWLINE mechanics.add_equations([self])NEWLINENEWLINE @Equation()NEWLINE def eval(self, scope):NEWLINE scope.T_i1 = scope.T1NEWLINE scope.T_i2 = scope.T2NEWLINENEWLINENEWLINEclass StaticDataSystem(Subsystem):NEWLINE def __init__(self, tag, n=1):NEWLINE super().__init__(tag)NEWLINE o_s = []NEWLINE for i in range(n):NEWLINE o = StaticDataTest('tm' + str(i))NEWLINE o_s.append(o)NEWLINE # Register the items to the subsystem to make it recognize them.NEWLINE self.register_items(o_s)NEWLINENEWLINENEWLINE@pytest.mark.parametrize("solver", solver_types)NEWLINE@pytest.mark.parametrize("use_llvm", [True, False])NEWLINEdef test_external_data(solver, use_llvm):NEWLINE external_mappings = []NEWLINENEWLINE import pandas as pdNEWLINE import numpy as npNEWLINENEWLINE data = {'time': np.arange(100),NEWLINE 'Dew Point Temperature {C}': np.arange(100) + 1,NEWLINE 'Dry Bulb Temperature {C}': np.arange(100) + 2,NEWLINE }NEWLINENEWLINE df = pd.DataFrame(data, columns=['time', 'Dew Point Temperature {C}', 'Dry Bulb Temperature {C}'])NEWLINE index_to_timestep_mapping = 'time'NEWLINE index_to_timestep_mapping_start = 0NEWLINE dataframe_aliases = {NEWLINE 'system_external.tm0.test_nm.T1': ("Dew Point Temperature {C}", InterpolationType.PIESEWISE),NEWLINE 'system_external.tm0.test_nm.T2': ('Dry Bulb Temperature {C}', InterpolationType.PIESEWISE)NEWLINE }NEWLINE external_mappings.append(ExternalMappingElementNEWLINE ("inmemory", index_to_timestep_mapping, index_to_timestep_mapping_start, 1,NEWLINE dataframe_aliases))NEWLINE data_loader = InMemoryDataLoader(df)NEWLINE s = Simulation(NEWLINE Model(StaticDataSystem('system_external', n=1), use_llvm=use_llvm, external_mappings=external_mappings,NEWLINE data_loader=data_loader),NEWLINE t_start=0, t_stop=100.0, num=100, num_inner=100, max_step=.1, solver_type=solverNEWLINE )NEWLINE s.solve()NEWLINE assert approx(np.array(s.model.historian_df['system_external.tm0.test_nm.T_i1'])[1:]) == np.arange(101)[1:]NEWLINE assert approx(np.array(s.model.historian_df['system_external.tm0.test_nm.T_i2'])[1:]) == np.arange(101)[1:] + 1NEWLINENEWLINENEWLINE@pytest.mark.parametrize("solver", solver_types)NEWLINE@pytest.mark.parametrize("use_llvm", [True, False])NEWLINEdef test_static_system(solver, use_llvm):NEWLINE import numpy as npNEWLINE s = Simulation(NEWLINE Model(StaticDataSystem('system_static', n=1), use_llvm=use_llvm),NEWLINE t_start=0, t_stop=100.0, num=100, num_inner=100, max_step=.1, solver_type=solverNEWLINE )NEWLINE s.solve()NEWLINE assert approx(np.array(s.model.historian_df['system_static.tm0.test_nm.T_i1'])[1:]) == np.repeat(0, (100))NEWLINE assert approx(np.array(s.model.historian_df['system_static.tm0.test_nm.T_i2'])[1:]) == np.repeat(0, (100))NEWLINE
# coding=utf-8NEWLINE# --------------------------------------------------------------------------NEWLINE# Copyright (c) Microsoft Corporation. All rights reserved.NEWLINE# Licensed under the MIT License. See License.txt in the project root for license information.NEWLINE# Code generated by Microsoft (R) AutoRest Code Generator.NEWLINE# Changes may cause incorrect behavior and will be lost if the code is regenerated.NEWLINE# --------------------------------------------------------------------------NEWLINENEWLINEimport datetimeNEWLINEfrom typing import Dict, List, Optional, UnionNEWLINENEWLINEfrom azure.core.exceptions import HttpResponseErrorNEWLINEimport msrest.serializationNEWLINENEWLINEfrom ._monitor_management_client_enums import *NEWLINENEWLINENEWLINEclass AutoscaleErrorResponse(msrest.serialization.Model):NEWLINE """Describes the format of Error response.NEWLINENEWLINE Variables are only populated by the server, and will be ignored when sending a request.NEWLINENEWLINE :ivar error: The error object.NEWLINE :vartype error:NEWLINE ~$(python-base-namespace).v2021_05_01_preview.models.AutoscaleErrorResponseErrorNEWLINE :ivar system_data: The system metadata related to the response.NEWLINE :vartype system_data: ~$(python-base-namespace).v2021_05_01_preview.models.SystemDataNEWLINE """NEWLINENEWLINE _validation = {NEWLINE 'system_data': {'readonly': True},NEWLINE }NEWLINENEWLINE _attribute_map = {NEWLINE 'error': {'key': 'error', 'type': 'AutoscaleErrorResponseError'},NEWLINE 'system_data': {'key': 'systemData', 'type': 'SystemData'},NEWLINE }NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE *,NEWLINE error: Optional["AutoscaleErrorResponseError"] = None,NEWLINE **kwargsNEWLINE ):NEWLINE """NEWLINE :keyword error: The error object.NEWLINE :paramtype error:NEWLINE ~$(python-base-namespace).v2021_05_01_preview.models.AutoscaleErrorResponseErrorNEWLINE """NEWLINE super(AutoscaleErrorResponse, self).__init__(**kwargs)NEWLINE self.error = errorNEWLINE self.system_data = NoneNEWLINENEWLINENEWLINEclass AutoscaleErrorResponseError(msrest.serialization.Model):NEWLINE """The error object.NEWLINENEWLINE :ivar code: One of a server-defined set of error codes.NEWLINE :vartype code: strNEWLINE :ivar message: A human-readable representation of the error.NEWLINE :vartype message: strNEWLINE :ivar target: The target of the particular error.NEWLINE :vartype target: strNEWLINE :ivar details: A human-readable representation of the error's details.NEWLINE :vartype details: strNEWLINE """NEWLINENEWLINE _attribute_map = {NEWLINE 'code': {'key': 'code', 'type': 'str'},NEWLINE 'message': {'key': 'message', 'type': 'str'},NEWLINE 'target': {'key': 'target', 'type': 'str'},NEWLINE 'details': {'key': 'details', 'type': 'str'},NEWLINE }NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE *,NEWLINE code: Optional[str] = None,NEWLINE message: Optional[str] = None,NEWLINE target: Optional[str] = None,NEWLINE details: Optional[str] = None,NEWLINE **kwargsNEWLINE ):NEWLINE """NEWLINE :keyword code: One of a server-defined set of error codes.NEWLINE :paramtype code: strNEWLINE :keyword message: A human-readable representation of the error.NEWLINE :paramtype message: strNEWLINE :keyword target: The target of the particular error.NEWLINE :paramtype target: strNEWLINE :keyword details: A human-readable representation of the error's details.NEWLINE :paramtype details: strNEWLINE """NEWLINE super(AutoscaleErrorResponseError, self).__init__(**kwargs)NEWLINE self.code = codeNEWLINE self.message = messageNEWLINE self.target = targetNEWLINE self.details = detailsNEWLINENEWLINENEWLINEclass AutoscaleNotification(msrest.serialization.Model):NEWLINE """Autoscale notification.NEWLINENEWLINE Variables are only populated by the server, and will be ignored when sending a request.NEWLINENEWLINE All required parameters must be populated in order to send to Azure.NEWLINENEWLINE :ivar operation: the operation associated with the notification and its value must be "scale".NEWLINE Has constant value: "Scale".NEWLINE :vartype operation: strNEWLINE :ivar email: the email notification.NEWLINE :vartype email: ~$(python-base-namespace).v2021_05_01_preview.models.EmailNotificationNEWLINE :ivar webhooks: the collection of webhook notifications.NEWLINE :vartype webhooks:NEWLINE list[~$(python-base-namespace).v2021_05_01_preview.models.WebhookNotification]NEWLINE """NEWLINENEWLINE _validation = {NEWLINE 'operation': {'required': True, 'constant': True},NEWLINE }NEWLINENEWLINE _attribute_map = {NEWLINE 'operation': {'key': 'operation', 'type': 'str'},NEWLINE 'email': {'key': 'email', 'type': 'EmailNotification'},NEWLINE 'webhooks': {'key': 'webhooks', 'type': '[WebhookNotification]'},NEWLINE }NEWLINENEWLINE operation = "Scale"NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE *,NEWLINE email: Optional["EmailNotification"] = None,NEWLINE webhooks: Optional[List["WebhookNotification"]] = None,NEWLINE **kwargsNEWLINE ):NEWLINE """NEWLINE :keyword email: the email notification.NEWLINE :paramtype email: ~$(python-base-namespace).v2021_05_01_preview.models.EmailNotificationNEWLINE :keyword webhooks: the collection of webhook notifications.NEWLINE :paramtype webhooks:NEWLINE list[~$(python-base-namespace).v2021_05_01_preview.models.WebhookNotification]NEWLINE """NEWLINE super(AutoscaleNotification, self).__init__(**kwargs)NEWLINE self.email = emailNEWLINE self.webhooks = webhooksNEWLINENEWLINENEWLINEclass AutoscaleProfile(msrest.serialization.Model):NEWLINE """Autoscale profile.NEWLINENEWLINE All required parameters must be populated in order to send to Azure.NEWLINENEWLINE :ivar name: Required. the name of the profile.NEWLINE :vartype name: strNEWLINE :ivar capacity: Required. the number of instances that can be used during this profile.NEWLINE :vartype capacity: ~$(python-base-namespace).v2021_05_01_preview.models.ScaleCapacityNEWLINE :ivar rules: Required. the collection of rules that provide the triggers and parameters for theNEWLINE scaling action. A maximum of 10 rules can be specified.NEWLINE :vartype rules: list[~$(python-base-namespace).v2021_05_01_preview.models.ScaleRule]NEWLINE :ivar fixed_date: the specific date-time for the profile. This element is not used if theNEWLINE Recurrence element is used.NEWLINE :vartype fixed_date: ~$(python-base-namespace).v2021_05_01_preview.models.TimeWindowNEWLINE :ivar recurrence: the repeating times at which this profile begins. This element is not used ifNEWLINE the FixedDate element is used.NEWLINE :vartype recurrence: ~$(python-base-namespace).v2021_05_01_preview.models.RecurrenceNEWLINE """NEWLINENEWLINE _validation = {NEWLINE 'name': {'required': True},NEWLINE 'capacity': {'required': True},NEWLINE 'rules': {'required': True},NEWLINE }NEWLINENEWLINE _attribute_map = {NEWLINE 'name': {'key': 'name', 'type': 'str'},NEWLINE 'capacity': {'key': 'capacity', 'type': 'ScaleCapacity'},NEWLINE 'rules': {'key': 'rules', 'type': '[ScaleRule]'},NEWLINE 'fixed_date': {'key': 'fixedDate', 'type': 'TimeWindow'},NEWLINE 'recurrence': {'key': 'recurrence', 'type': 'Recurrence'},NEWLINE }NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE *,NEWLINE name: str,NEWLINE capacity: "ScaleCapacity",NEWLINE rules: List["ScaleRule"],NEWLINE fixed_date: Optional["TimeWindow"] = None,NEWLINE recurrence: Optional["Recurrence"] = None,NEWLINE **kwargsNEWLINE ):NEWLINE """NEWLINE :keyword name: Required. the name of the profile.NEWLINE :paramtype name: strNEWLINE :keyword capacity: Required. the number of instances that can be used during this profile.NEWLINE :paramtype capacity: ~$(python-base-namespace).v2021_05_01_preview.models.ScaleCapacityNEWLINE :keyword rules: Required. the collection of rules that provide the triggers and parameters forNEWLINE the scaling action. A maximum of 10 rules can be specified.NEWLINE :paramtype rules: list[~$(python-base-namespace).v2021_05_01_preview.models.ScaleRule]NEWLINE :keyword fixed_date: the specific date-time for the profile. This element is not used if theNEWLINE Recurrence element is used.NEWLINE :paramtype fixed_date: ~$(python-base-namespace).v2021_05_01_preview.models.TimeWindowNEWLINE :keyword recurrence: the repeating times at which this profile begins. This element is not usedNEWLINE if the FixedDate element is used.NEWLINE :paramtype recurrence: ~$(python-base-namespace).v2021_05_01_preview.models.RecurrenceNEWLINE """NEWLINE super(AutoscaleProfile, self).__init__(**kwargs)NEWLINE self.name = nameNEWLINE self.capacity = capacityNEWLINE self.rules = rulesNEWLINE self.fixed_date = fixed_dateNEWLINE self.recurrence = recurrenceNEWLINENEWLINENEWLINEclass AutoscaleSettingResource(msrest.serialization.Model):NEWLINE """The autoscale setting resource.NEWLINENEWLINE Variables are only populated by the server, and will be ignored when sending a request.NEWLINENEWLINE All required parameters must be populated in order to send to Azure.NEWLINENEWLINE :ivar id: Azure resource Id.NEWLINE :vartype id: strNEWLINE :ivar name: Azure resource name.NEWLINE :vartype name: strNEWLINE :ivar type: Azure resource type.NEWLINE :vartype type: strNEWLINE :ivar location: Required. Resource location.NEWLINE :vartype location: strNEWLINE :ivar tags: A set of tags. Gets or sets a list of key value pairs that describe the resource.NEWLINE These tags can be used in viewing and grouping this resource (across resource groups). ANEWLINE maximum of 15 tags can be provided for a resource. Each tag must have a key no greater inNEWLINE length than 128 characters and a value no greater in length than 256 characters.NEWLINE :vartype tags: dict[str, str]NEWLINE :ivar system_data: The system metadata related to the response.NEWLINE :vartype system_data: ~$(python-base-namespace).v2021_05_01_preview.models.SystemDataNEWLINE :ivar profiles: Required. the collection of automatic scaling profiles that specify differentNEWLINE scaling parameters for different time periods. A maximum of 20 profiles can be specified.NEWLINE :vartype profiles: list[~$(python-base-namespace).v2021_05_01_preview.models.AutoscaleProfile]NEWLINE :ivar notifications: the collection of notifications.NEWLINE :vartype notifications:NEWLINE list[~$(python-base-namespace).v2021_05_01_preview.models.AutoscaleNotification]NEWLINE :ivar enabled: the enabled flag. Specifies whether automatic scaling is enabled for theNEWLINE resource. The default value is 'true'.NEWLINE :vartype enabled: boolNEWLINE :ivar predictive_autoscale_policy: the predictive autoscale policy mode.NEWLINE :vartype predictive_autoscale_policy:NEWLINE ~$(python-base-namespace).v2021_05_01_preview.models.PredictiveAutoscalePolicyNEWLINE :ivar name_properties_name: the name of the autoscale setting.NEWLINE :vartype name_properties_name: strNEWLINE :ivar target_resource_uri: the resource identifier of the resource that the autoscale settingNEWLINE should be added to.NEWLINE :vartype target_resource_uri: strNEWLINE :ivar target_resource_location: the location of the resource that the autoscale setting shouldNEWLINE be added to.NEWLINE :vartype target_resource_location: strNEWLINE """NEWLINENEWLINE _validation = {NEWLINE 'id': {'readonly': True},NEWLINE 'name': {'readonly': True},NEWLINE 'type': {'readonly': True},NEWLINE 'location': {'required': True},NEWLINE 'system_data': {'readonly': True},NEWLINE 'profiles': {'required': True, 'max_items': 20, 'min_items': 0},NEWLINE }NEWLINENEWLINE _attribute_map = {NEWLINE 'id': {'key': 'id', 'type': 'str'},NEWLINE 'name': {'key': 'name', 'type': 'str'},NEWLINE 'type': {'key': 'type', 'type': 'str'},NEWLINE 'location': {'key': 'location', 'type': 'str'},NEWLINE 'tags': {'key': 'tags', 'type': '{str}'},NEWLINE 'system_data': {'key': 'systemData', 'type': 'SystemData'},NEWLINE 'profiles': {'key': 'properties.profiles', 'type': '[AutoscaleProfile]'},NEWLINE 'notifications': {'key': 'properties.notifications', 'type': '[AutoscaleNotification]'},NEWLINE 'enabled': {'key': 'properties.enabled', 'type': 'bool'},NEWLINE 'predictive_autoscale_policy': {'key': 'properties.predictiveAutoscalePolicy', 'type': 'PredictiveAutoscalePolicy'},NEWLINE 'name_properties_name': {'key': 'properties.name', 'type': 'str'},NEWLINE 'target_resource_uri': {'key': 'properties.targetResourceUri', 'type': 'str'},NEWLINE 'target_resource_location': {'key': 'properties.targetResourceLocation', 'type': 'str'},NEWLINE }NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE *,NEWLINE location: str,NEWLINE profiles: List["AutoscaleProfile"],NEWLINE tags: Optional[Dict[str, str]] = None,NEWLINE notifications: Optional[List["AutoscaleNotification"]] = None,NEWLINE enabled: Optional[bool] = True,NEWLINE predictive_autoscale_policy: Optional["PredictiveAutoscalePolicy"] = None,NEWLINE name_properties_name: Optional[str] = None,NEWLINE target_resource_uri: Optional[str] = None,NEWLINE target_resource_location: Optional[str] = None,NEWLINE **kwargsNEWLINE ):NEWLINE """NEWLINE :keyword location: Required. Resource location.NEWLINE :paramtype location: strNEWLINE :keyword tags: A set of tags. Gets or sets a list of key value pairs that describe theNEWLINE resource. These tags can be used in viewing and grouping this resource (across resourceNEWLINE groups). A maximum of 15 tags can be provided for a resource. Each tag must have a key noNEWLINE greater in length than 128 characters and a value no greater in length than 256 characters.NEWLINE :paramtype tags: dict[str, str]NEWLINE :keyword profiles: Required. the collection of automatic scaling profiles that specifyNEWLINE different scaling parameters for different time periods. A maximum of 20 profiles can beNEWLINE specified.NEWLINE :paramtype profiles:NEWLINE list[~$(python-base-namespace).v2021_05_01_preview.models.AutoscaleProfile]NEWLINE :keyword notifications: the collection of notifications.NEWLINE :paramtype notifications:NEWLINE list[~$(python-base-namespace).v2021_05_01_preview.models.AutoscaleNotification]NEWLINE :keyword enabled: the enabled flag. Specifies whether automatic scaling is enabled for theNEWLINE resource. The default value is 'true'.NEWLINE :paramtype enabled: boolNEWLINE :keyword predictive_autoscale_policy: the predictive autoscale policy mode.NEWLINE :paramtype predictive_autoscale_policy:NEWLINE ~$(python-base-namespace).v2021_05_01_preview.models.PredictiveAutoscalePolicyNEWLINE :keyword name_properties_name: the name of the autoscale setting.NEWLINE :paramtype name_properties_name: strNEWLINE :keyword target_resource_uri: the resource identifier of the resource that the autoscaleNEWLINE setting should be added to.NEWLINE :paramtype target_resource_uri: strNEWLINE :keyword target_resource_location: the location of the resource that the autoscale settingNEWLINE should be added to.NEWLINE :paramtype target_resource_location: strNEWLINE """NEWLINE super(AutoscaleSettingResource, self).__init__(**kwargs)NEWLINE self.id = NoneNEWLINE self.name = NoneNEWLINE self.type = NoneNEWLINE self.location = locationNEWLINE self.tags = tagsNEWLINE self.system_data = NoneNEWLINE self.profiles = profilesNEWLINE self.notifications = notificationsNEWLINE self.enabled = enabledNEWLINE self.predictive_autoscale_policy = predictive_autoscale_policyNEWLINE self.name_properties_name = name_properties_nameNEWLINE self.target_resource_uri = target_resource_uriNEWLINE self.target_resource_location = target_resource_locationNEWLINENEWLINENEWLINEclass AutoscaleSettingResourceCollection(msrest.serialization.Model):NEWLINE """Represents a collection of autoscale setting resources.NEWLINENEWLINE All required parameters must be populated in order to send to Azure.NEWLINENEWLINE :ivar value: Required. the values for the autoscale setting resources.NEWLINE :vartype value:NEWLINE list[~$(python-base-namespace).v2021_05_01_preview.models.AutoscaleSettingResource]NEWLINE :ivar next_link: URL to get the next set of results.NEWLINE :vartype next_link: strNEWLINE """NEWLINENEWLINE _validation = {NEWLINE 'value': {'required': True},NEWLINE }NEWLINENEWLINE _attribute_map = {NEWLINE 'value': {'key': 'value', 'type': '[AutoscaleSettingResource]'},NEWLINE 'next_link': {'key': 'nextLink', 'type': 'str'},NEWLINE }NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE *,NEWLINE value: List["AutoscaleSettingResource"],NEWLINE next_link: Optional[str] = None,NEWLINE **kwargsNEWLINE ):NEWLINE """NEWLINE :keyword value: Required. the values for the autoscale setting resources.NEWLINE :paramtype value:NEWLINE list[~$(python-base-namespace).v2021_05_01_preview.models.AutoscaleSettingResource]NEWLINE :keyword next_link: URL to get the next set of results.NEWLINE :paramtype next_link: strNEWLINE """NEWLINE super(AutoscaleSettingResourceCollection, self).__init__(**kwargs)NEWLINE self.value = valueNEWLINE self.next_link = next_linkNEWLINENEWLINENEWLINEclass AutoscaleSettingResourcePatch(msrest.serialization.Model):NEWLINE """The autoscale setting object for patch operations.NEWLINENEWLINE :ivar tags: A set of tags. Resource tags.NEWLINE :vartype tags: dict[str, str]NEWLINE :ivar profiles: the collection of automatic scaling profiles that specify different scalingNEWLINE parameters for different time periods. A maximum of 20 profiles can be specified.NEWLINE :vartype profiles: list[~$(python-base-namespace).v2021_05_01_preview.models.AutoscaleProfile]NEWLINE :ivar notifications: the collection of notifications.NEWLINE :vartype notifications:NEWLINE list[~$(python-base-namespace).v2021_05_01_preview.models.AutoscaleNotification]NEWLINE :ivar enabled: the enabled flag. Specifies whether automatic scaling is enabled for theNEWLINE resource. The default value is 'true'.NEWLINE :vartype enabled: boolNEWLINE :ivar predictive_autoscale_policy: the predictive autoscale policy mode.NEWLINE :vartype predictive_autoscale_policy:NEWLINE ~$(python-base-namespace).v2021_05_01_preview.models.PredictiveAutoscalePolicyNEWLINE :ivar name: the name of the autoscale setting.NEWLINE :vartype name: strNEWLINE :ivar target_resource_uri: the resource identifier of the resource that the autoscale settingNEWLINE should be added to.NEWLINE :vartype target_resource_uri: strNEWLINE :ivar target_resource_location: the location of the resource that the autoscale setting shouldNEWLINE be added to.NEWLINE :vartype target_resource_location: strNEWLINE """NEWLINENEWLINE _validation = {NEWLINE 'profiles': {'max_items': 20, 'min_items': 0},NEWLINE }NEWLINENEWLINE _attribute_map = {NEWLINE 'tags': {'key': 'tags', 'type': '{str}'},NEWLINE 'profiles': {'key': 'properties.profiles', 'type': '[AutoscaleProfile]'},NEWLINE 'notifications': {'key': 'properties.notifications', 'type': '[AutoscaleNotification]'},NEWLINE 'enabled': {'key': 'properties.enabled', 'type': 'bool'},NEWLINE 'predictive_autoscale_policy': {'key': 'properties.predictiveAutoscalePolicy', 'type': 'PredictiveAutoscalePolicy'},NEWLINE 'name': {'key': 'properties.name', 'type': 'str'},NEWLINE 'target_resource_uri': {'key': 'properties.targetResourceUri', 'type': 'str'},NEWLINE 'target_resource_location': {'key': 'properties.targetResourceLocation', 'type': 'str'},NEWLINE }NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE *,NEWLINE tags: Optional[Dict[str, str]] = None,NEWLINE profiles: Optional[List["AutoscaleProfile"]] = None,NEWLINE notifications: Optional[List["AutoscaleNotification"]] = None,NEWLINE enabled: Optional[bool] = True,NEWLINE predictive_autoscale_policy: Optional["PredictiveAutoscalePolicy"] = None,NEWLINE name: Optional[str] = None,NEWLINE target_resource_uri: Optional[str] = None,NEWLINE target_resource_location: Optional[str] = None,NEWLINE **kwargsNEWLINE ):NEWLINE """NEWLINE :keyword tags: A set of tags. Resource tags.NEWLINE :paramtype tags: dict[str, str]NEWLINE :keyword profiles: the collection of automatic scaling profiles that specify different scalingNEWLINE parameters for different time periods. A maximum of 20 profiles can be specified.NEWLINE :paramtype profiles:NEWLINE list[~$(python-base-namespace).v2021_05_01_preview.models.AutoscaleProfile]NEWLINE :keyword notifications: the collection of notifications.NEWLINE :paramtype notifications:NEWLINE list[~$(python-base-namespace).v2021_05_01_preview.models.AutoscaleNotification]NEWLINE :keyword enabled: the enabled flag. Specifies whether automatic scaling is enabled for theNEWLINE resource. The default value is 'true'.NEWLINE :paramtype enabled: boolNEWLINE :keyword predictive_autoscale_policy: the predictive autoscale policy mode.NEWLINE :paramtype predictive_autoscale_policy:NEWLINE ~$(python-base-namespace).v2021_05_01_preview.models.PredictiveAutoscalePolicyNEWLINE :keyword name: the name of the autoscale setting.NEWLINE :paramtype name: strNEWLINE :keyword target_resource_uri: the resource identifier of the resource that the autoscaleNEWLINE setting should be added to.NEWLINE :paramtype target_resource_uri: strNEWLINE :keyword target_resource_location: the location of the resource that the autoscale settingNEWLINE should be added to.NEWLINE :paramtype target_resource_location: strNEWLINE """NEWLINE super(AutoscaleSettingResourcePatch, self).__init__(**kwargs)NEWLINE self.tags = tagsNEWLINE self.profiles = profilesNEWLINE self.notifications = notificationsNEWLINE self.enabled = enabledNEWLINE self.predictive_autoscale_policy = predictive_autoscale_policyNEWLINE self.name = nameNEWLINE self.target_resource_uri = target_resource_uriNEWLINE self.target_resource_location = target_resource_locationNEWLINENEWLINENEWLINEclass Resource(msrest.serialization.Model):NEWLINE """Common fields that are returned in the response for all Azure Resource Manager resources.NEWLINENEWLINE Variables are only populated by the server, and will be ignored when sending a request.NEWLINENEWLINE :ivar id: Fully qualified resource ID for the resource. Ex -NEWLINE /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.NEWLINE :vartype id: strNEWLINE :ivar name: The name of the resource.NEWLINE :vartype name: strNEWLINE :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" orNEWLINE "Microsoft.Storage/storageAccounts".NEWLINE :vartype type: strNEWLINE """NEWLINENEWLINE _validation = {NEWLINE 'id': {'readonly': True},NEWLINE 'name': {'readonly': True},NEWLINE 'type': {'readonly': True},NEWLINE }NEWLINENEWLINE _attribute_map = {NEWLINE 'id': {'key': 'id', 'type': 'str'},NEWLINE 'name': {'key': 'name', 'type': 'str'},NEWLINE 'type': {'key': 'type', 'type': 'str'},NEWLINE }NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE **kwargsNEWLINE ):NEWLINE """NEWLINE """NEWLINE super(Resource, self).__init__(**kwargs)NEWLINE self.id = NoneNEWLINE self.name = NoneNEWLINE self.type = NoneNEWLINENEWLINENEWLINEclass DiagnosticSettingsCategoryResource(Resource):NEWLINE """The diagnostic settings category resource.NEWLINENEWLINE Variables are only populated by the server, and will be ignored when sending a request.NEWLINENEWLINE :ivar id: Fully qualified resource ID for the resource. Ex -NEWLINE /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.NEWLINE :vartype id: strNEWLINE :ivar name: The name of the resource.NEWLINE :vartype name: strNEWLINE :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" orNEWLINE "Microsoft.Storage/storageAccounts".NEWLINE :vartype type: strNEWLINE :ivar system_data: The system metadata related to this resource.NEWLINE :vartype system_data: ~$(python-base-namespace).v2021_05_01_preview.models.SystemDataNEWLINE :ivar category_type: The type of the diagnostic settings category. Possible values include:NEWLINE "Metrics", "Logs".NEWLINE :vartype category_type: str orNEWLINE ~$(python-base-namespace).v2021_05_01_preview.models.CategoryTypeNEWLINE :ivar category_groups: the collection of what category groups are supported.NEWLINE :vartype category_groups: list[str]NEWLINE """NEWLINENEWLINE _validation = {NEWLINE 'id': {'readonly': True},NEWLINE 'name': {'readonly': True},NEWLINE 'type': {'readonly': True},NEWLINE 'system_data': {'readonly': True},NEWLINE }NEWLINENEWLINE _attribute_map = {NEWLINE 'id': {'key': 'id', 'type': 'str'},NEWLINE 'name': {'key': 'name', 'type': 'str'},NEWLINE 'type': {'key': 'type', 'type': 'str'},NEWLINE 'system_data': {'key': 'systemData', 'type': 'SystemData'},NEWLINE 'category_type': {'key': 'properties.categoryType', 'type': 'str'},NEWLINE 'category_groups': {'key': 'properties.categoryGroups', 'type': '[str]'},NEWLINE }NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE *,NEWLINE category_type: Optional[Union[str, "CategoryType"]] = None,NEWLINE category_groups: Optional[List[str]] = None,NEWLINE **kwargsNEWLINE ):NEWLINE """NEWLINE :keyword category_type: The type of the diagnostic settings category. Possible values include:NEWLINE "Metrics", "Logs".NEWLINE :paramtype category_type: str orNEWLINE ~$(python-base-namespace).v2021_05_01_preview.models.CategoryTypeNEWLINE :keyword category_groups: the collection of what category groups are supported.NEWLINE :paramtype category_groups: list[str]NEWLINE """NEWLINE super(DiagnosticSettingsCategoryResource, self).__init__(**kwargs)NEWLINE self.system_data = NoneNEWLINE self.category_type = category_typeNEWLINE self.category_groups = category_groupsNEWLINENEWLINENEWLINEclass DiagnosticSettingsCategoryResourceCollection(msrest.serialization.Model):NEWLINE """Represents a collection of diagnostic setting category resources.NEWLINENEWLINE :ivar value: The collection of diagnostic settings category resources.NEWLINE :vartype value:NEWLINE list[~$(python-base-namespace).v2021_05_01_preview.models.DiagnosticSettingsCategoryResource]NEWLINE """NEWLINENEWLINE _attribute_map = {NEWLINE 'value': {'key': 'value', 'type': '[DiagnosticSettingsCategoryResource]'},NEWLINE }NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE *,NEWLINE value: Optional[List["DiagnosticSettingsCategoryResource"]] = None,NEWLINE **kwargsNEWLINE ):NEWLINE """NEWLINE :keyword value: The collection of diagnostic settings category resources.NEWLINE :paramtype value:NEWLINE list[~$(python-base-namespace).v2021_05_01_preview.models.DiagnosticSettingsCategoryResource]NEWLINE """NEWLINE super(DiagnosticSettingsCategoryResourceCollection, self).__init__(**kwargs)NEWLINE self.value = valueNEWLINENEWLINENEWLINEclass DiagnosticSettingsResource(Resource):NEWLINE """The diagnostic setting resource.NEWLINENEWLINE Variables are only populated by the server, and will be ignored when sending a request.NEWLINENEWLINE :ivar id: Fully qualified resource ID for the resource. Ex -NEWLINE /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.NEWLINE :vartype id: strNEWLINE :ivar name: The name of the resource.NEWLINE :vartype name: strNEWLINE :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" orNEWLINE "Microsoft.Storage/storageAccounts".NEWLINE :vartype type: strNEWLINE :ivar system_data: The system metadata related to this resource.NEWLINE :vartype system_data: ~$(python-base-namespace).v2021_05_01_preview.models.SystemDataNEWLINE :ivar storage_account_id: The resource ID of the storage account to which you would like toNEWLINE send Diagnostic Logs.NEWLINE :vartype storage_account_id: strNEWLINE :ivar service_bus_rule_id: The service bus rule Id of the diagnostic setting. This is here toNEWLINE maintain backwards compatibility.NEWLINE :vartype service_bus_rule_id: strNEWLINE :ivar event_hub_authorization_rule_id: The resource Id for the event hub authorization rule.NEWLINE :vartype event_hub_authorization_rule_id: strNEWLINE :ivar event_hub_name: The name of the event hub. If none is specified, the default event hubNEWLINE will be selected.NEWLINE :vartype event_hub_name: strNEWLINE :ivar metrics: The list of metric settings.NEWLINE :vartype metrics: list[~$(python-base-namespace).v2021_05_01_preview.models.MetricSettings]NEWLINE :ivar logs: The list of logs settings.NEWLINE :vartype logs: list[~$(python-base-namespace).v2021_05_01_preview.models.LogSettings]NEWLINE :ivar workspace_id: The full ARM resource ID of the Log Analytics workspace to which you wouldNEWLINE like to send Diagnostic Logs. Example:NEWLINE /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2.NEWLINE :vartype workspace_id: strNEWLINE :ivar marketplace_partner_id: The full ARM resource ID of the Marketplace resource to which youNEWLINE would like to send Diagnostic Logs.NEWLINE :vartype marketplace_partner_id: strNEWLINE :ivar log_analytics_destination_type: A string indicating whether the export to Log AnalyticsNEWLINE should use the default destination type, i.e. AzureDiagnostics, or use a destination typeNEWLINE constructed as follows: :code:`<normalized service identity>`_:code:`<normalized categoryNEWLINE name>`. Possible values are: Dedicated and null (null is default.).NEWLINE :vartype log_analytics_destination_type: strNEWLINE """NEWLINENEWLINE _validation = {NEWLINE 'id': {'readonly': True},NEWLINE 'name': {'readonly': True},NEWLINE 'type': {'readonly': True},NEWLINE 'system_data': {'readonly': True},NEWLINE }NEWLINENEWLINE _attribute_map = {NEWLINE 'id': {'key': 'id', 'type': 'str'},NEWLINE 'name': {'key': 'name', 'type': 'str'},NEWLINE 'type': {'key': 'type', 'type': 'str'},NEWLINE 'system_data': {'key': 'systemData', 'type': 'SystemData'},NEWLINE 'storage_account_id': {'key': 'properties.storageAccountId', 'type': 'str'},NEWLINE 'service_bus_rule_id': {'key': 'properties.serviceBusRuleId', 'type': 'str'},NEWLINE 'event_hub_authorization_rule_id': {'key': 'properties.eventHubAuthorizationRuleId', 'type': 'str'},NEWLINE 'event_hub_name': {'key': 'properties.eventHubName', 'type': 'str'},NEWLINE 'metrics': {'key': 'properties.metrics', 'type': '[MetricSettings]'},NEWLINE 'logs': {'key': 'properties.logs', 'type': '[LogSettings]'},NEWLINE 'workspace_id': {'key': 'properties.workspaceId', 'type': 'str'},NEWLINE 'marketplace_partner_id': {'key': 'properties.marketplacePartnerId', 'type': 'str'},NEWLINE 'log_analytics_destination_type': {'key': 'properties.logAnalyticsDestinationType', 'type': 'str'},NEWLINE }NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE *,NEWLINE storage_account_id: Optional[str] = None,NEWLINE service_bus_rule_id: Optional[str] = None,NEWLINE event_hub_authorization_rule_id: Optional[str] = None,NEWLINE event_hub_name: Optional[str] = None,NEWLINE metrics: Optional[List["MetricSettings"]] = None,NEWLINE logs: Optional[List["LogSettings"]] = None,NEWLINE workspace_id: Optional[str] = None,NEWLINE marketplace_partner_id: Optional[str] = None,NEWLINE log_analytics_destination_type: Optional[str] = None,NEWLINE **kwargsNEWLINE ):NEWLINE """NEWLINE :keyword storage_account_id: The resource ID of the storage account to which you would like toNEWLINE send Diagnostic Logs.NEWLINE :paramtype storage_account_id: strNEWLINE :keyword service_bus_rule_id: The service bus rule Id of the diagnostic setting. This is hereNEWLINE to maintain backwards compatibility.NEWLINE :paramtype service_bus_rule_id: strNEWLINE :keyword event_hub_authorization_rule_id: The resource Id for the event hub authorization rule.NEWLINE :paramtype event_hub_authorization_rule_id: strNEWLINE :keyword event_hub_name: The name of the event hub. If none is specified, the default event hubNEWLINE will be selected.NEWLINE :paramtype event_hub_name: strNEWLINE :keyword metrics: The list of metric settings.NEWLINE :paramtype metrics: list[~$(python-base-namespace).v2021_05_01_preview.models.MetricSettings]NEWLINE :keyword logs: The list of logs settings.NEWLINE :paramtype logs: list[~$(python-base-namespace).v2021_05_01_preview.models.LogSettings]NEWLINE :keyword workspace_id: The full ARM resource ID of the Log Analytics workspace to which youNEWLINE would like to send Diagnostic Logs. Example:NEWLINE /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2.NEWLINE :paramtype workspace_id: strNEWLINE :keyword marketplace_partner_id: The full ARM resource ID of the Marketplace resource to whichNEWLINE you would like to send Diagnostic Logs.NEWLINE :paramtype marketplace_partner_id: strNEWLINE :keyword log_analytics_destination_type: A string indicating whether the export to LogNEWLINE Analytics should use the default destination type, i.e. AzureDiagnostics, or use a destinationNEWLINE type constructed as follows: :code:`<normalized service identity>`_:code:`<normalized categoryNEWLINE name>`. Possible values are: Dedicated and null (null is default.).NEWLINE :paramtype log_analytics_destination_type: strNEWLINE """NEWLINE super(DiagnosticSettingsResource, self).__init__(**kwargs)NEWLINE self.system_data = NoneNEWLINE self.storage_account_id = storage_account_idNEWLINE self.service_bus_rule_id = service_bus_rule_idNEWLINE self.event_hub_authorization_rule_id = event_hub_authorization_rule_idNEWLINE self.event_hub_name = event_hub_nameNEWLINE self.metrics = metricsNEWLINE self.logs = logsNEWLINE self.workspace_id = workspace_idNEWLINE self.marketplace_partner_id = marketplace_partner_idNEWLINE self.log_analytics_destination_type = log_analytics_destination_typeNEWLINENEWLINENEWLINEclass DiagnosticSettingsResourceCollection(msrest.serialization.Model):NEWLINE """Represents a collection of alert rule resources.NEWLINENEWLINE :ivar value: The collection of diagnostic settings resources;.NEWLINE :vartype value:NEWLINE list[~$(python-base-namespace).v2021_05_01_preview.models.DiagnosticSettingsResource]NEWLINE """NEWLINENEWLINE _attribute_map = {NEWLINE 'value': {'key': 'value', 'type': '[DiagnosticSettingsResource]'},NEWLINE }NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE *,NEWLINE value: Optional[List["DiagnosticSettingsResource"]] = None,NEWLINE **kwargsNEWLINE ):NEWLINE """NEWLINE :keyword value: The collection of diagnostic settings resources;.NEWLINE :paramtype value:NEWLINE list[~$(python-base-namespace).v2021_05_01_preview.models.DiagnosticSettingsResource]NEWLINE """NEWLINE super(DiagnosticSettingsResourceCollection, self).__init__(**kwargs)NEWLINE self.value = valueNEWLINENEWLINENEWLINEclass EmailNotification(msrest.serialization.Model):NEWLINE """Email notification of an autoscale event.NEWLINENEWLINE :ivar send_to_subscription_administrator: a value indicating whether to send email toNEWLINE subscription administrator.NEWLINE :vartype send_to_subscription_administrator: boolNEWLINE :ivar send_to_subscription_co_administrators: a value indicating whether to send email toNEWLINE subscription co-administrators.NEWLINE :vartype send_to_subscription_co_administrators: boolNEWLINE :ivar custom_emails: the custom e-mails list. This value can be null or empty, in which caseNEWLINE this attribute will be ignored.NEWLINE :vartype custom_emails: list[str]NEWLINE """NEWLINENEWLINE _attribute_map = {NEWLINE 'send_to_subscription_administrator': {'key': 'sendToSubscriptionAdministrator', 'type': 'bool'},NEWLINE 'send_to_subscription_co_administrators': {'key': 'sendToSubscriptionCoAdministrators', 'type': 'bool'},NEWLINE 'custom_emails': {'key': 'customEmails', 'type': '[str]'},NEWLINE }NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE *,NEWLINE send_to_subscription_administrator: Optional[bool] = False,NEWLINE send_to_subscription_co_administrators: Optional[bool] = False,NEWLINE custom_emails: Optional[List[str]] = None,NEWLINE **kwargsNEWLINE ):NEWLINE """NEWLINE :keyword send_to_subscription_administrator: a value indicating whether to send email toNEWLINE subscription administrator.NEWLINE :paramtype send_to_subscription_administrator: boolNEWLINE :keyword send_to_subscription_co_administrators: a value indicating whether to send email toNEWLINE subscription co-administrators.NEWLINE :paramtype send_to_subscription_co_administrators: boolNEWLINE :keyword custom_emails: the custom e-mails list. This value can be null or empty, in which caseNEWLINE this attribute will be ignored.NEWLINE :paramtype custom_emails: list[str]NEWLINE """NEWLINE super(EmailNotification, self).__init__(**kwargs)NEWLINE self.send_to_subscription_administrator = send_to_subscription_administratorNEWLINE self.send_to_subscription_co_administrators = send_to_subscription_co_administratorsNEWLINE self.custom_emails = custom_emailsNEWLINENEWLINENEWLINEclass ErrorResponse(msrest.serialization.Model):NEWLINE """Describes the format of Error response.NEWLINENEWLINE :ivar code: Error code.NEWLINE :vartype code: strNEWLINE :ivar message: Error message indicating why the operation failed.NEWLINE :vartype message: strNEWLINE """NEWLINENEWLINE _attribute_map = {NEWLINE 'code': {'key': 'code', 'type': 'str'},NEWLINE 'message': {'key': 'message', 'type': 'str'},NEWLINE }NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE *,NEWLINE code: Optional[str] = None,NEWLINE message: Optional[str] = None,NEWLINE **kwargsNEWLINE ):NEWLINE """NEWLINE :keyword code: Error code.NEWLINE :paramtype code: strNEWLINE :keyword message: Error message indicating why the operation failed.NEWLINE :paramtype message: strNEWLINE """NEWLINE super(ErrorResponse, self).__init__(**kwargs)NEWLINE self.code = codeNEWLINE self.message = messageNEWLINENEWLINENEWLINEclass LogSettings(msrest.serialization.Model):NEWLINE """Part of MultiTenantDiagnosticSettings. Specifies the settings for a particular log.NEWLINENEWLINE All required parameters must be populated in order to send to Azure.NEWLINENEWLINE :ivar category: Name of a Diagnostic Log category for a resource type this setting is appliedNEWLINE to. To obtain the list of Diagnostic Log categories for a resource, first perform a GETNEWLINE diagnostic settings operation.NEWLINE :vartype category: strNEWLINE :ivar category_group: Name of a Diagnostic Log category group for a resource type this settingNEWLINE is applied to. To obtain the list of Diagnostic Log categories for a resource, first perform aNEWLINE GET diagnostic settings operation.NEWLINE :vartype category_group: strNEWLINE :ivar enabled: Required. a value indicating whether this log is enabled.NEWLINE :vartype enabled: boolNEWLINE :ivar retention_policy: the retention policy for this log.NEWLINE :vartype retention_policy: ~$(python-base-namespace).v2021_05_01_preview.models.RetentionPolicyNEWLINE """NEWLINENEWLINE _validation = {NEWLINE 'enabled': {'required': True},NEWLINE }NEWLINENEWLINE _attribute_map = {NEWLINE 'category': {'key': 'category', 'type': 'str'},NEWLINE 'category_group': {'key': 'categoryGroup', 'type': 'str'},NEWLINE 'enabled': {'key': 'enabled', 'type': 'bool'},NEWLINE 'retention_policy': {'key': 'retentionPolicy', 'type': 'RetentionPolicy'},NEWLINE }NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE *,NEWLINE enabled: bool,NEWLINE category: Optional[str] = None,NEWLINE category_group: Optional[str] = None,NEWLINE retention_policy: Optional["RetentionPolicy"] = None,NEWLINE **kwargsNEWLINE ):NEWLINE """NEWLINE :keyword category: Name of a Diagnostic Log category for a resource type this setting isNEWLINE applied to. To obtain the list of Diagnostic Log categories for a resource, first perform a GETNEWLINE diagnostic settings operation.NEWLINE :paramtype category: strNEWLINE :keyword category_group: Name of a Diagnostic Log category group for a resource type thisNEWLINE setting is applied to. To obtain the list of Diagnostic Log categories for a resource, firstNEWLINE perform a GET diagnostic settings operation.NEWLINE :paramtype category_group: strNEWLINE :keyword enabled: Required. a value indicating whether this log is enabled.NEWLINE :paramtype enabled: boolNEWLINE :keyword retention_policy: the retention policy for this log.NEWLINE :paramtype retention_policy:NEWLINE ~$(python-base-namespace).v2021_05_01_preview.models.RetentionPolicyNEWLINE """NEWLINE super(LogSettings, self).__init__(**kwargs)NEWLINE self.category = categoryNEWLINE self.category_group = category_groupNEWLINE self.enabled = enabledNEWLINE self.retention_policy = retention_policyNEWLINENEWLINENEWLINEclass ManagementGroupDiagnosticSettingsResource(Resource):NEWLINE """The management group diagnostic setting resource.NEWLINENEWLINE Variables are only populated by the server, and will be ignored when sending a request.NEWLINENEWLINE :ivar id: Fully qualified resource ID for the resource. Ex -NEWLINE /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.NEWLINE :vartype id: strNEWLINE :ivar name: The name of the resource.NEWLINE :vartype name: strNEWLINE :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" orNEWLINE "Microsoft.Storage/storageAccounts".NEWLINE :vartype type: strNEWLINE :ivar system_data: The system metadata related to this resource.NEWLINE :vartype system_data: ~$(python-base-namespace).v2021_05_01_preview.models.SystemDataNEWLINE :ivar storage_account_id: The resource ID of the storage account to which you would like toNEWLINE send Diagnostic Logs.NEWLINE :vartype storage_account_id: strNEWLINE :ivar service_bus_rule_id: The service bus rule Id of the diagnostic setting. This is here toNEWLINE maintain backwards compatibility.NEWLINE :vartype service_bus_rule_id: strNEWLINE :ivar event_hub_authorization_rule_id: The resource Id for the event hub authorization rule.NEWLINE :vartype event_hub_authorization_rule_id: strNEWLINE :ivar event_hub_name: The name of the event hub. If none is specified, the default event hubNEWLINE will be selected.NEWLINE :vartype event_hub_name: strNEWLINE :ivar logs: The list of logs settings.NEWLINE :vartype logs:NEWLINE list[~$(python-base-namespace).v2021_05_01_preview.models.ManagementGroupLogSettings]NEWLINE :ivar workspace_id: The full ARM resource ID of the Log Analytics workspace to which you wouldNEWLINE like to send Diagnostic Logs. Example:NEWLINE /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2.NEWLINE :vartype workspace_id: strNEWLINE :ivar marketplace_partner_id: The full ARM resource ID of the Marketplace resource to which youNEWLINE would like to send Diagnostic Logs.NEWLINE :vartype marketplace_partner_id: strNEWLINE """NEWLINENEWLINE _validation = {NEWLINE 'id': {'readonly': True},NEWLINE 'name': {'readonly': True},NEWLINE 'type': {'readonly': True},NEWLINE 'system_data': {'readonly': True},NEWLINE }NEWLINENEWLINE _attribute_map = {NEWLINE 'id': {'key': 'id', 'type': 'str'},NEWLINE 'name': {'key': 'name', 'type': 'str'},NEWLINE 'type': {'key': 'type', 'type': 'str'},NEWLINE 'system_data': {'key': 'systemData', 'type': 'SystemData'},NEWLINE 'storage_account_id': {'key': 'properties.storageAccountId', 'type': 'str'},NEWLINE 'service_bus_rule_id': {'key': 'properties.serviceBusRuleId', 'type': 'str'},NEWLINE 'event_hub_authorization_rule_id': {'key': 'properties.eventHubAuthorizationRuleId', 'type': 'str'},NEWLINE 'event_hub_name': {'key': 'properties.eventHubName', 'type': 'str'},NEWLINE 'logs': {'key': 'properties.logs', 'type': '[ManagementGroupLogSettings]'},NEWLINE 'workspace_id': {'key': 'properties.workspaceId', 'type': 'str'},NEWLINE 'marketplace_partner_id': {'key': 'properties.marketplacePartnerId', 'type': 'str'},NEWLINE }NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE *,NEWLINE storage_account_id: Optional[str] = None,NEWLINE service_bus_rule_id: Optional[str] = None,NEWLINE event_hub_authorization_rule_id: Optional[str] = None,NEWLINE event_hub_name: Optional[str] = None,NEWLINE logs: Optional[List["ManagementGroupLogSettings"]] = None,NEWLINE workspace_id: Optional[str] = None,NEWLINE marketplace_partner_id: Optional[str] = None,NEWLINE **kwargsNEWLINE ):NEWLINE """NEWLINE :keyword storage_account_id: The resource ID of the storage account to which you would like toNEWLINE send Diagnostic Logs.NEWLINE :paramtype storage_account_id: strNEWLINE :keyword service_bus_rule_id: The service bus rule Id of the diagnostic setting. This is hereNEWLINE to maintain backwards compatibility.NEWLINE :paramtype service_bus_rule_id: strNEWLINE :keyword event_hub_authorization_rule_id: The resource Id for the event hub authorization rule.NEWLINE :paramtype event_hub_authorization_rule_id: strNEWLINE :keyword event_hub_name: The name of the event hub. If none is specified, the default event hubNEWLINE will be selected.NEWLINE :paramtype event_hub_name: strNEWLINE :keyword logs: The list of logs settings.NEWLINE :paramtype logs:NEWLINE list[~$(python-base-namespace).v2021_05_01_preview.models.ManagementGroupLogSettings]NEWLINE :keyword workspace_id: The full ARM resource ID of the Log Analytics workspace to which youNEWLINE would like to send Diagnostic Logs. Example:NEWLINE /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2.NEWLINE :paramtype workspace_id: strNEWLINE :keyword marketplace_partner_id: The full ARM resource ID of the Marketplace resource to whichNEWLINE you would like to send Diagnostic Logs.NEWLINE :paramtype marketplace_partner_id: strNEWLINE """NEWLINE super(ManagementGroupDiagnosticSettingsResource, self).__init__(**kwargs)NEWLINE self.system_data = NoneNEWLINE self.storage_account_id = storage_account_idNEWLINE self.service_bus_rule_id = service_bus_rule_idNEWLINE self.event_hub_authorization_rule_id = event_hub_authorization_rule_idNEWLINE self.event_hub_name = event_hub_nameNEWLINE self.logs = logsNEWLINE self.workspace_id = workspace_idNEWLINE self.marketplace_partner_id = marketplace_partner_idNEWLINENEWLINENEWLINEclass ManagementGroupDiagnosticSettingsResourceCollection(msrest.serialization.Model):NEWLINE """Represents a collection of management group diagnostic settings resources.NEWLINENEWLINE :ivar value: The collection of management group diagnostic settings resources.NEWLINE :vartype value:NEWLINE list[~$(python-base-namespace).v2021_05_01_preview.models.ManagementGroupDiagnosticSettingsResource]NEWLINE """NEWLINENEWLINE _attribute_map = {NEWLINE 'value': {'key': 'value', 'type': '[ManagementGroupDiagnosticSettingsResource]'},NEWLINE }NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE *,NEWLINE value: Optional[List["ManagementGroupDiagnosticSettingsResource"]] = None,NEWLINE **kwargsNEWLINE ):NEWLINE """NEWLINE :keyword value: The collection of management group diagnostic settings resources.NEWLINE :paramtype value:NEWLINE list[~$(python-base-namespace).v2021_05_01_preview.models.ManagementGroupDiagnosticSettingsResource]NEWLINE """NEWLINE super(ManagementGroupDiagnosticSettingsResourceCollection, self).__init__(**kwargs)NEWLINE self.value = valueNEWLINENEWLINENEWLINEclass ManagementGroupLogSettings(msrest.serialization.Model):NEWLINE """Part of Management Group diagnostic setting. Specifies the settings for a particular log.NEWLINENEWLINE All required parameters must be populated in order to send to Azure.NEWLINENEWLINE :ivar category: Name of a Management Group Diagnostic Log category for a resource type thisNEWLINE setting is applied to.NEWLINE :vartype category: strNEWLINE :ivar category_group: Name of a Management Group Diagnostic Log category group for a resourceNEWLINE type this setting is applied to.NEWLINE :vartype category_group: strNEWLINE :ivar enabled: Required. a value indicating whether this log is enabled.NEWLINE :vartype enabled: boolNEWLINE """NEWLINENEWLINE _validation = {NEWLINE 'enabled': {'required': True},NEWLINE }NEWLINENEWLINE _attribute_map = {NEWLINE 'category': {'key': 'category', 'type': 'str'},NEWLINE 'category_group': {'key': 'categoryGroup', 'type': 'str'},NEWLINE 'enabled': {'key': 'enabled', 'type': 'bool'},NEWLINE }NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE *,NEWLINE enabled: bool,NEWLINE category: Optional[str] = None,NEWLINE category_group: Optional[str] = None,NEWLINE **kwargsNEWLINE ):NEWLINE """NEWLINE :keyword category: Name of a Management Group Diagnostic Log category for a resource type thisNEWLINE setting is applied to.NEWLINE :paramtype category: strNEWLINE :keyword category_group: Name of a Management Group Diagnostic Log category group for aNEWLINE resource type this setting is applied to.NEWLINE :paramtype category_group: strNEWLINE :keyword enabled: Required. a value indicating whether this log is enabled.NEWLINE :paramtype enabled: boolNEWLINE """NEWLINE super(ManagementGroupLogSettings, self).__init__(**kwargs)NEWLINE self.category = categoryNEWLINE self.category_group = category_groupNEWLINE self.enabled = enabledNEWLINENEWLINENEWLINEclass MetricSettings(msrest.serialization.Model):NEWLINE """Part of MultiTenantDiagnosticSettings. Specifies the settings for a particular metric.NEWLINENEWLINE All required parameters must be populated in order to send to Azure.NEWLINENEWLINE :ivar time_grain: the timegrain of the metric in ISO8601 format.NEWLINE :vartype time_grain: ~datetime.timedeltaNEWLINE :ivar category: Name of a Diagnostic Metric category for a resource type this setting isNEWLINE applied to. To obtain the list of Diagnostic metric categories for a resource, first perform aNEWLINE GET diagnostic settings operation.NEWLINE :vartype category: strNEWLINE :ivar enabled: Required. a value indicating whether this category is enabled.NEWLINE :vartype enabled: boolNEWLINE :ivar retention_policy: the retention policy for this category.NEWLINE :vartype retention_policy: ~$(python-base-namespace).v2021_05_01_preview.models.RetentionPolicyNEWLINE """NEWLINENEWLINE _validation = {NEWLINE 'enabled': {'required': True},NEWLINE }NEWLINENEWLINE _attribute_map = {NEWLINE 'time_grain': {'key': 'timeGrain', 'type': 'duration'},NEWLINE 'category': {'key': 'category', 'type': 'str'},NEWLINE 'enabled': {'key': 'enabled', 'type': 'bool'},NEWLINE 'retention_policy': {'key': 'retentionPolicy', 'type': 'RetentionPolicy'},NEWLINE }NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE *,NEWLINE enabled: bool,NEWLINE time_grain: Optional[datetime.timedelta] = None,NEWLINE category: Optional[str] = None,NEWLINE retention_policy: Optional["RetentionPolicy"] = None,NEWLINE **kwargsNEWLINE ):NEWLINE """NEWLINE :keyword time_grain: the timegrain of the metric in ISO8601 format.NEWLINE :paramtype time_grain: ~datetime.timedeltaNEWLINE :keyword category: Name of a Diagnostic Metric category for a resource type this setting isNEWLINE applied to. To obtain the list of Diagnostic metric categories for a resource, first perform aNEWLINE GET diagnostic settings operation.NEWLINE :paramtype category: strNEWLINE :keyword enabled: Required. a value indicating whether this category is enabled.NEWLINE :paramtype enabled: boolNEWLINE :keyword retention_policy: the retention policy for this category.NEWLINE :paramtype retention_policy:NEWLINE ~$(python-base-namespace).v2021_05_01_preview.models.RetentionPolicyNEWLINE """NEWLINE super(MetricSettings, self).__init__(**kwargs)NEWLINE self.time_grain = time_grainNEWLINE self.category = categoryNEWLINE self.enabled = enabledNEWLINE self.retention_policy = retention_policyNEWLINENEWLINENEWLINEclass MetricTrigger(msrest.serialization.Model):NEWLINE """The trigger that results in a scaling action.NEWLINENEWLINE All required parameters must be populated in order to send to Azure.NEWLINENEWLINE :ivar metric_name: Required. the name of the metric that defines what the rule monitors.NEWLINE :vartype metric_name: strNEWLINE :ivar metric_namespace: the namespace of the metric that defines what the rule monitors.NEWLINE :vartype metric_namespace: strNEWLINE :ivar metric_resource_uri: Required. the resource identifier of the resource the rule monitors.NEWLINE :vartype metric_resource_uri: strNEWLINE :ivar metric_resource_location: the location of the resource the rule monitors.NEWLINE :vartype metric_resource_location: strNEWLINE :ivar time_grain: Required. the granularity of metrics the rule monitors. Must be one of theNEWLINE predefined values returned from metric definitions for the metric. Must be between 12 hours andNEWLINE 1 minute.NEWLINE :vartype time_grain: ~datetime.timedeltaNEWLINE :ivar statistic: Required. the metric statistic type. How the metrics from multiple instancesNEWLINE are combined. Possible values include: "Average", "Min", "Max", "Sum", "Count".NEWLINE :vartype statistic: str orNEWLINE ~$(python-base-namespace).v2021_05_01_preview.models.MetricStatisticTypeNEWLINE :ivar time_window: Required. the range of time in which instance data is collected. This valueNEWLINE must be greater than the delay in metric collection, which can vary from resource-to-resource.NEWLINE Must be between 12 hours and 5 minutes.NEWLINE :vartype time_window: ~datetime.timedeltaNEWLINE :ivar time_aggregation: Required. time aggregation type. How the data that is collected shouldNEWLINE be combined over time. The default value is Average. Possible values include: "Average",NEWLINE "Minimum", "Maximum", "Total", "Count", "Last".NEWLINE :vartype time_aggregation: str orNEWLINE ~$(python-base-namespace).v2021_05_01_preview.models.TimeAggregationTypeNEWLINE :ivar operator: Required. the operator that is used to compare the metric data and theNEWLINE threshold. Possible values include: "Equals", "NotEquals", "GreaterThan", "GreaterThanOrEqual",NEWLINE "LessThan", "LessThanOrEqual".NEWLINE :vartype operator: str orNEWLINE ~$(python-base-namespace).v2021_05_01_preview.models.ComparisonOperationTypeNEWLINE :ivar threshold: Required. the threshold of the metric that triggers the scale action.NEWLINE :vartype threshold: floatNEWLINE :ivar dimensions: List of dimension conditions. For example:NEWLINE [{"DimensionName":"AppName","Operator":"Equals","Values":["App1"]},{"DimensionName":"Deployment","Operator":"Equals","Values":["default"]}].NEWLINE :vartype dimensions:NEWLINE list[~$(python-base-namespace).v2021_05_01_preview.models.ScaleRuleMetricDimension]NEWLINE :ivar divide_per_instance: a value indicating whether metric should divide per instance.NEWLINE :vartype divide_per_instance: boolNEWLINE """NEWLINENEWLINE _validation = {NEWLINE 'metric_name': {'required': True},NEWLINE 'metric_resource_uri': {'required': True},NEWLINE 'time_grain': {'required': True},NEWLINE 'statistic': {'required': True},NEWLINE 'time_window': {'required': True},NEWLINE 'time_aggregation': {'required': True},NEWLINE 'operator': {'required': True},NEWLINE 'threshold': {'required': True},NEWLINE }NEWLINENEWLINE _attribute_map = {NEWLINE 'metric_name': {'key': 'metricName', 'type': 'str'},NEWLINE 'metric_namespace': {'key': 'metricNamespace', 'type': 'str'},NEWLINE 'metric_resource_uri': {'key': 'metricResourceUri', 'type': 'str'},NEWLINE 'metric_resource_location': {'key': 'metricResourceLocation', 'type': 'str'},NEWLINE 'time_grain': {'key': 'timeGrain', 'type': 'duration'},NEWLINE 'statistic': {'key': 'statistic', 'type': 'str'},NEWLINE 'time_window': {'key': 'timeWindow', 'type': 'duration'},NEWLINE 'time_aggregation': {'key': 'timeAggregation', 'type': 'str'},NEWLINE 'operator': {'key': 'operator', 'type': 'str'},NEWLINE 'threshold': {'key': 'threshold', 'type': 'float'},NEWLINE 'dimensions': {'key': 'dimensions', 'type': '[ScaleRuleMetricDimension]'},NEWLINE 'divide_per_instance': {'key': 'dividePerInstance', 'type': 'bool'},NEWLINE }NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE *,NEWLINE metric_name: str,NEWLINE metric_resource_uri: str,NEWLINE time_grain: datetime.timedelta,NEWLINE statistic: Union[str, "MetricStatisticType"],NEWLINE time_window: datetime.timedelta,NEWLINE time_aggregation: Union[str, "TimeAggregationType"],NEWLINE operator: Union[str, "ComparisonOperationType"],NEWLINE threshold: float,NEWLINE metric_namespace: Optional[str] = None,NEWLINE metric_resource_location: Optional[str] = None,NEWLINE dimensions: Optional[List["ScaleRuleMetricDimension"]] = None,NEWLINE divide_per_instance: Optional[bool] = None,NEWLINE **kwargsNEWLINE ):NEWLINE """NEWLINE :keyword metric_name: Required. the name of the metric that defines what the rule monitors.NEWLINE :paramtype metric_name: strNEWLINE :keyword metric_namespace: the namespace of the metric that defines what the rule monitors.NEWLINE :paramtype metric_namespace: strNEWLINE :keyword metric_resource_uri: Required. the resource identifier of the resource the ruleNEWLINE monitors.NEWLINE :paramtype metric_resource_uri: strNEWLINE :keyword metric_resource_location: the location of the resource the rule monitors.NEWLINE :paramtype metric_resource_location: strNEWLINE :keyword time_grain: Required. the granularity of metrics the rule monitors. Must be one of theNEWLINE predefined values returned from metric definitions for the metric. Must be between 12 hours andNEWLINE 1 minute.NEWLINE :paramtype time_grain: ~datetime.timedeltaNEWLINE :keyword statistic: Required. the metric statistic type. How the metrics from multipleNEWLINE instances are combined. Possible values include: "Average", "Min", "Max", "Sum", "Count".NEWLINE :paramtype statistic: str orNEWLINE ~$(python-base-namespace).v2021_05_01_preview.models.MetricStatisticTypeNEWLINE :keyword time_window: Required. the range of time in which instance data is collected. ThisNEWLINE value must be greater than the delay in metric collection, which can vary fromNEWLINE resource-to-resource. Must be between 12 hours and 5 minutes.NEWLINE :paramtype time_window: ~datetime.timedeltaNEWLINE :keyword time_aggregation: Required. time aggregation type. How the data that is collectedNEWLINE should be combined over time. The default value is Average. Possible values include: "Average",NEWLINE "Minimum", "Maximum", "Total", "Count", "Last".NEWLINE :paramtype time_aggregation: str orNEWLINE ~$(python-base-namespace).v2021_05_01_preview.models.TimeAggregationTypeNEWLINE :keyword operator: Required. the operator that is used to compare the metric data and theNEWLINE threshold. Possible values include: "Equals", "NotEquals", "GreaterThan", "GreaterThanOrEqual",NEWLINE "LessThan", "LessThanOrEqual".NEWLINE :paramtype operator: str orNEWLINE ~$(python-base-namespace).v2021_05_01_preview.models.ComparisonOperationTypeNEWLINE :keyword threshold: Required. the threshold of the metric that triggers the scale action.NEWLINE :paramtype threshold: floatNEWLINE :keyword dimensions: List of dimension conditions. For example:NEWLINE [{"DimensionName":"AppName","Operator":"Equals","Values":["App1"]},{"DimensionName":"Deployment","Operator":"Equals","Values":["default"]}].NEWLINE :paramtype dimensions:NEWLINE list[~$(python-base-namespace).v2021_05_01_preview.models.ScaleRuleMetricDimension]NEWLINE :keyword divide_per_instance: a value indicating whether metric should divide per instance.NEWLINE :paramtype divide_per_instance: boolNEWLINE """NEWLINE super(MetricTrigger, self).__init__(**kwargs)NEWLINE self.metric_name = metric_nameNEWLINE self.metric_namespace = metric_namespaceNEWLINE self.metric_resource_uri = metric_resource_uriNEWLINE self.metric_resource_location = metric_resource_locationNEWLINE self.time_grain = time_grainNEWLINE self.statistic = statisticNEWLINE self.time_window = time_windowNEWLINE self.time_aggregation = time_aggregationNEWLINE self.operator = operatorNEWLINE self.threshold = thresholdNEWLINE self.dimensions = dimensionsNEWLINE self.divide_per_instance = divide_per_instanceNEWLINENEWLINENEWLINEclass PredictiveAutoscalePolicy(msrest.serialization.Model):NEWLINE """The parameters for enabling predictive autoscale.NEWLINENEWLINE All required parameters must be populated in order to send to Azure.NEWLINENEWLINE :ivar scale_mode: Required. the predictive autoscale mode. Possible values include: "Disabled",NEWLINE "ForecastOnly", "Enabled".NEWLINE :vartype scale_mode: str orNEWLINE ~$(python-base-namespace).v2021_05_01_preview.models.PredictiveAutoscalePolicyScaleModeNEWLINE :ivar scale_look_ahead_time: the amount of time to specify by which instances are launched inNEWLINE advance. It must be between 1 minute and 60 minutes in ISO 8601 format.NEWLINE :vartype scale_look_ahead_time: ~datetime.timedeltaNEWLINE """NEWLINENEWLINE _validation = {NEWLINE 'scale_mode': {'required': True},NEWLINE }NEWLINENEWLINE _attribute_map = {NEWLINE 'scale_mode': {'key': 'scaleMode', 'type': 'str'},NEWLINE 'scale_look_ahead_time': {'key': 'scaleLookAheadTime', 'type': 'duration'},NEWLINE }NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE *,NEWLINE scale_mode: Union[str, "PredictiveAutoscalePolicyScaleMode"],NEWLINE scale_look_ahead_time: Optional[datetime.timedelta] = None,NEWLINE **kwargsNEWLINE ):NEWLINE """NEWLINE :keyword scale_mode: Required. the predictive autoscale mode. Possible values include:NEWLINE "Disabled", "ForecastOnly", "Enabled".NEWLINE :paramtype scale_mode: str orNEWLINE ~$(python-base-namespace).v2021_05_01_preview.models.PredictiveAutoscalePolicyScaleModeNEWLINE :keyword scale_look_ahead_time: the amount of time to specify by which instances are launchedNEWLINE in advance. It must be between 1 minute and 60 minutes in ISO 8601 format.NEWLINE :paramtype scale_look_ahead_time: ~datetime.timedeltaNEWLINE """NEWLINE super(PredictiveAutoscalePolicy, self).__init__(**kwargs)NEWLINE self.scale_mode = scale_modeNEWLINE self.scale_look_ahead_time = scale_look_ahead_timeNEWLINENEWLINENEWLINEclass PredictiveResponse(msrest.serialization.Model):NEWLINE """The response to a metrics query.NEWLINENEWLINE :ivar timespan: The timespan for which the data was retrieved. Its value consists of twoNEWLINE datetimes concatenated, separated by '/'. This may be adjusted in the future and returned backNEWLINE from what was originally requested.NEWLINE :vartype timespan: strNEWLINE :ivar interval: The interval (window size) for which the metric data was returned in. This mayNEWLINE be adjusted in the future and returned back from what was originally requested. This is notNEWLINE present if a metadata request was made.NEWLINE :vartype interval: ~datetime.timedeltaNEWLINE :ivar metric_name: The metrics being queried.NEWLINE :vartype metric_name: strNEWLINE :ivar target_resource_id: resource of the predictive metric.NEWLINE :vartype target_resource_id: strNEWLINE :ivar data: the value of the collection.NEWLINE :vartype data: list[~$(python-base-namespace).v2021_05_01_preview.models.PredictiveValue]NEWLINE """NEWLINENEWLINE _attribute_map = {NEWLINE 'timespan': {'key': 'timespan', 'type': 'str'},NEWLINE 'interval': {'key': 'interval', 'type': 'duration'},NEWLINE 'metric_name': {'key': 'metricName', 'type': 'str'},NEWLINE 'target_resource_id': {'key': 'targetResourceId', 'type': 'str'},NEWLINE 'data': {'key': 'data', 'type': '[PredictiveValue]'},NEWLINE }NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE *,NEWLINE timespan: Optional[str] = None,NEWLINE interval: Optional[datetime.timedelta] = None,NEWLINE metric_name: Optional[str] = None,NEWLINE target_resource_id: Optional[str] = None,NEWLINE data: Optional[List["PredictiveValue"]] = None,NEWLINE **kwargsNEWLINE ):NEWLINE """NEWLINE :keyword timespan: The timespan for which the data was retrieved. Its value consists of twoNEWLINE datetimes concatenated, separated by '/'. This may be adjusted in the future and returned backNEWLINE from what was originally requested.NEWLINE :paramtype timespan: strNEWLINE :keyword interval: The interval (window size) for which the metric data was returned in. ThisNEWLINE may be adjusted in the future and returned back from what was originally requested. This isNEWLINE not present if a metadata request was made.NEWLINE :paramtype interval: ~datetime.timedeltaNEWLINE :keyword metric_name: The metrics being queried.NEWLINE :paramtype metric_name: strNEWLINE :keyword target_resource_id: resource of the predictive metric.NEWLINE :paramtype target_resource_id: strNEWLINE :keyword data: the value of the collection.NEWLINE :paramtype data: list[~$(python-base-namespace).v2021_05_01_preview.models.PredictiveValue]NEWLINE """NEWLINE super(PredictiveResponse, self).__init__(**kwargs)NEWLINE self.timespan = timespanNEWLINE self.interval = intervalNEWLINE self.metric_name = metric_nameNEWLINE self.target_resource_id = target_resource_idNEWLINE self.data = dataNEWLINENEWLINENEWLINEclass PredictiveValue(msrest.serialization.Model):NEWLINE """Represents a predictive metric value in the given bucket.NEWLINENEWLINE All required parameters must be populated in order to send to Azure.NEWLINENEWLINE :ivar time_stamp: Required. the timestamp for the metric value in ISO 8601 format.NEWLINE :vartype time_stamp: ~datetime.datetimeNEWLINE :ivar value: Required. Predictive value in this time bucket.NEWLINE :vartype value: floatNEWLINE """NEWLINENEWLINE _validation = {NEWLINE 'time_stamp': {'required': True},NEWLINE 'value': {'required': True},NEWLINE }NEWLINENEWLINE _attribute_map = {NEWLINE 'time_stamp': {'key': 'timeStamp', 'type': 'iso-8601'},NEWLINE 'value': {'key': 'value', 'type': 'float'},NEWLINE }NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE *,NEWLINE time_stamp: datetime.datetime,NEWLINE value: float,NEWLINE **kwargsNEWLINE ):NEWLINE """NEWLINE :keyword time_stamp: Required. the timestamp for the metric value in ISO 8601 format.NEWLINE :paramtype time_stamp: ~datetime.datetimeNEWLINE :keyword value: Required. Predictive value in this time bucket.NEWLINE :paramtype value: floatNEWLINE """NEWLINE super(PredictiveValue, self).__init__(**kwargs)NEWLINE self.time_stamp = time_stampNEWLINE self.value = valueNEWLINENEWLINENEWLINEclass Recurrence(msrest.serialization.Model):NEWLINE """The repeating times at which this profile begins. This element is not used if the FixedDate element is used.NEWLINENEWLINE All required parameters must be populated in order to send to Azure.NEWLINENEWLINE :ivar frequency: Required. the recurrence frequency. How often the schedule profile should takeNEWLINE effect. This value must be Week, meaning each week will have the same set of profiles. ForNEWLINE example, to set a daily schedule, set **schedule** to every day of the week. The frequencyNEWLINE property specifies that the schedule is repeated weekly. Possible values include: "None",NEWLINE "Second", "Minute", "Hour", "Day", "Week", "Month", "Year".NEWLINE :vartype frequency: str orNEWLINE ~$(python-base-namespace).v2021_05_01_preview.models.RecurrenceFrequencyNEWLINE :ivar schedule: Required. the scheduling constraints for when the profile begins.NEWLINE :vartype schedule: ~$(python-base-namespace).v2021_05_01_preview.models.RecurrentScheduleNEWLINE """NEWLINENEWLINE _validation = {NEWLINE 'frequency': {'required': True},NEWLINE 'schedule': {'required': True},NEWLINE }NEWLINENEWLINE _attribute_map = {NEWLINE 'frequency': {'key': 'frequency', 'type': 'str'},NEWLINE 'schedule': {'key': 'schedule', 'type': 'RecurrentSchedule'},NEWLINE }NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE *,NEWLINE frequency: Union[str, "RecurrenceFrequency"],NEWLINE schedule: "RecurrentSchedule",NEWLINE **kwargsNEWLINE ):NEWLINE """NEWLINE :keyword frequency: Required. the recurrence frequency. How often the schedule profile shouldNEWLINE take effect. This value must be Week, meaning each week will have the same set of profiles. ForNEWLINE example, to set a daily schedule, set **schedule** to every day of the week. The frequencyNEWLINE property specifies that the schedule is repeated weekly. Possible values include: "None",NEWLINE "Second", "Minute", "Hour", "Day", "Week", "Month", "Year".NEWLINE :paramtype frequency: str orNEWLINE ~$(python-base-namespace).v2021_05_01_preview.models.RecurrenceFrequencyNEWLINE :keyword schedule: Required. the scheduling constraints for when the profile begins.NEWLINE :paramtype schedule: ~$(python-base-namespace).v2021_05_01_preview.models.RecurrentScheduleNEWLINE """NEWLINE super(Recurrence, self).__init__(**kwargs)NEWLINE self.frequency = frequencyNEWLINE self.schedule = scheduleNEWLINENEWLINENEWLINEclass RecurrentSchedule(msrest.serialization.Model):NEWLINE """The scheduling constraints for when the profile begins.NEWLINENEWLINE All required parameters must be populated in order to send to Azure.NEWLINENEWLINE :ivar time_zone: Required. the timezone for the hours of the profile. Some examples of validNEWLINE time zones are: Dateline Standard Time, UTC-11, Hawaiian Standard Time, Alaskan Standard Time,NEWLINE Pacific Standard Time (Mexico), Pacific Standard Time, US Mountain Standard Time, MountainNEWLINE Standard Time (Mexico), Mountain Standard Time, Central America Standard Time, Central StandardNEWLINE Time, Central Standard Time (Mexico), Canada Central Standard Time, SA Pacific Standard Time,NEWLINE Eastern Standard Time, US Eastern Standard Time, Venezuela Standard Time, Paraguay StandardNEWLINE Time, Atlantic Standard Time, Central Brazilian Standard Time, SA Western Standard Time,NEWLINE Pacific SA Standard Time, Newfoundland Standard Time, E. South America Standard Time, ArgentinaNEWLINE Standard Time, SA Eastern Standard Time, Greenland Standard Time, Montevideo Standard Time,NEWLINE Bahia Standard Time, UTC-02, Mid-Atlantic Standard Time, Azores Standard Time, Cape VerdeNEWLINE Standard Time, Morocco Standard Time, UTC, GMT Standard Time, Greenwich Standard Time, W.NEWLINE Europe Standard Time, Central Europe Standard Time, Romance Standard Time, Central EuropeanNEWLINE Standard Time, W. Central Africa Standard Time, Namibia Standard Time, Jordan Standard Time,NEWLINE GTB Standard Time, Middle East Standard Time, Egypt Standard Time, Syria Standard Time, E.NEWLINE Europe Standard Time, South Africa Standard Time, FLE Standard Time, Turkey Standard Time,NEWLINE Israel Standard Time, Kaliningrad Standard Time, Libya Standard Time, Arabic Standard Time,NEWLINE Arab Standard Time, Belarus Standard Time, Russian Standard Time, E. Africa Standard Time, IranNEWLINE Standard Time, Arabian Standard Time, Azerbaijan Standard Time, Russia Time Zone 3, MauritiusNEWLINE Standard Time, Georgian Standard Time, Caucasus Standard Time, Afghanistan Standard Time, WestNEWLINE Asia Standard Time, Ekaterinburg Standard Time, Pakistan Standard Time, India Standard Time,NEWLINE Sri Lanka Standard Time, Nepal Standard Time, Central Asia Standard Time, Bangladesh StandardNEWLINE Time, N. Central Asia Standard Time, Myanmar Standard Time, SE Asia Standard Time, North AsiaNEWLINE Standard Time, China Standard Time, North Asia East Standard Time, Singapore Standard Time, W.NEWLINE Australia Standard Time, Taipei Standard Time, Ulaanbaatar Standard Time, Tokyo Standard Time,NEWLINE Korea Standard Time, Yakutsk Standard Time, Cen. Australia Standard Time, AUS Central StandardNEWLINE Time, E. Australia Standard Time, AUS Eastern Standard Time, West Pacific Standard Time,NEWLINE Tasmania Standard Time, Magadan Standard Time, Vladivostok Standard Time, Russia Time Zone 10,NEWLINE Central Pacific Standard Time, Russia Time Zone 11, New Zealand Standard Time, UTC+12, FijiNEWLINE Standard Time, Kamchatka Standard Time, Tonga Standard Time, Samoa Standard Time, Line IslandsNEWLINE Standard Time.NEWLINE :vartype time_zone: strNEWLINE :ivar days: Required. the collection of days that the profile takes effect on. Possible valuesNEWLINE are Sunday through Saturday.NEWLINE :vartype days: list[str]NEWLINE :ivar hours: Required. A collection of hours that the profile takes effect on. Values supportedNEWLINE are 0 to 23 on the 24-hour clock (AM/PM times are not supported).NEWLINE :vartype hours: list[int]NEWLINE :ivar minutes: Required. A collection of minutes at which the profile takes effect at.NEWLINE :vartype minutes: list[int]NEWLINE """NEWLINENEWLINE _validation = {NEWLINE 'time_zone': {'required': True},NEWLINE 'days': {'required': True},NEWLINE 'hours': {'required': True},NEWLINE 'minutes': {'required': True},NEWLINE }NEWLINENEWLINE _attribute_map = {NEWLINE 'time_zone': {'key': 'timeZone', 'type': 'str'},NEWLINE 'days': {'key': 'days', 'type': '[str]'},NEWLINE 'hours': {'key': 'hours', 'type': '[int]'},NEWLINE 'minutes': {'key': 'minutes', 'type': '[int]'},NEWLINE }NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE *,NEWLINE time_zone: str,NEWLINE days: List[str],NEWLINE hours: List[int],NEWLINE minutes: List[int],NEWLINE **kwargsNEWLINE ):NEWLINE """NEWLINE :keyword time_zone: Required. the timezone for the hours of the profile. Some examples of validNEWLINE time zones are: Dateline Standard Time, UTC-11, Hawaiian Standard Time, Alaskan Standard Time,NEWLINE Pacific Standard Time (Mexico), Pacific Standard Time, US Mountain Standard Time, MountainNEWLINE Standard Time (Mexico), Mountain Standard Time, Central America Standard Time, Central StandardNEWLINE Time, Central Standard Time (Mexico), Canada Central Standard Time, SA Pacific Standard Time,NEWLINE Eastern Standard Time, US Eastern Standard Time, Venezuela Standard Time, Paraguay StandardNEWLINE Time, Atlantic Standard Time, Central Brazilian Standard Time, SA Western Standard Time,NEWLINE Pacific SA Standard Time, Newfoundland Standard Time, E. South America Standard Time, ArgentinaNEWLINE Standard Time, SA Eastern Standard Time, Greenland Standard Time, Montevideo Standard Time,NEWLINE Bahia Standard Time, UTC-02, Mid-Atlantic Standard Time, Azores Standard Time, Cape VerdeNEWLINE Standard Time, Morocco Standard Time, UTC, GMT Standard Time, Greenwich Standard Time, W.NEWLINE Europe Standard Time, Central Europe Standard Time, Romance Standard Time, Central EuropeanNEWLINE Standard Time, W. Central Africa Standard Time, Namibia Standard Time, Jordan Standard Time,NEWLINE GTB Standard Time, Middle East Standard Time, Egypt Standard Time, Syria Standard Time, E.NEWLINE Europe Standard Time, South Africa Standard Time, FLE Standard Time, Turkey Standard Time,NEWLINE Israel Standard Time, Kaliningrad Standard Time, Libya Standard Time, Arabic Standard Time,NEWLINE Arab Standard Time, Belarus Standard Time, Russian Standard Time, E. Africa Standard Time, IranNEWLINE Standard Time, Arabian Standard Time, Azerbaijan Standard Time, Russia Time Zone 3, MauritiusNEWLINE Standard Time, Georgian Standard Time, Caucasus Standard Time, Afghanistan Standard Time, WestNEWLINE Asia Standard Time, Ekaterinburg Standard Time, Pakistan Standard Time, India Standard Time,NEWLINE Sri Lanka Standard Time, Nepal Standard Time, Central Asia Standard Time, Bangladesh StandardNEWLINE Time, N. Central Asia Standard Time, Myanmar Standard Time, SE Asia Standard Time, North AsiaNEWLINE Standard Time, China Standard Time, North Asia East Standard Time, Singapore Standard Time, W.NEWLINE Australia Standard Time, Taipei Standard Time, Ulaanbaatar Standard Time, Tokyo Standard Time,NEWLINE Korea Standard Time, Yakutsk Standard Time, Cen. Australia Standard Time, AUS Central StandardNEWLINE Time, E. Australia Standard Time, AUS Eastern Standard Time, West Pacific Standard Time,NEWLINE Tasmania Standard Time, Magadan Standard Time, Vladivostok Standard Time, Russia Time Zone 10,NEWLINE Central Pacific Standard Time, Russia Time Zone 11, New Zealand Standard Time, UTC+12, FijiNEWLINE Standard Time, Kamchatka Standard Time, Tonga Standard Time, Samoa Standard Time, Line IslandsNEWLINE Standard Time.NEWLINE :paramtype time_zone: strNEWLINE :keyword days: Required. the collection of days that the profile takes effect on. PossibleNEWLINE values are Sunday through Saturday.NEWLINE :paramtype days: list[str]NEWLINE :keyword hours: Required. A collection of hours that the profile takes effect on. ValuesNEWLINE supported are 0 to 23 on the 24-hour clock (AM/PM times are not supported).NEWLINE :paramtype hours: list[int]NEWLINE :keyword minutes: Required. A collection of minutes at which the profile takes effect at.NEWLINE :paramtype minutes: list[int]NEWLINE """NEWLINE super(RecurrentSchedule, self).__init__(**kwargs)NEWLINE self.time_zone = time_zoneNEWLINE self.days = daysNEWLINE self.hours = hoursNEWLINE self.minutes = minutesNEWLINENEWLINENEWLINEclass RetentionPolicy(msrest.serialization.Model):NEWLINE """Specifies the retention policy for the log.NEWLINENEWLINE All required parameters must be populated in order to send to Azure.NEWLINENEWLINE :ivar enabled: Required. a value indicating whether the retention policy is enabled.NEWLINE :vartype enabled: boolNEWLINE :ivar days: Required. the number of days for the retention in days. A value of 0 will retainNEWLINE the events indefinitely.NEWLINE :vartype days: intNEWLINE """NEWLINENEWLINE _validation = {NEWLINE 'enabled': {'required': True},NEWLINE 'days': {'required': True, 'minimum': 0},NEWLINE }NEWLINENEWLINE _attribute_map = {NEWLINE 'enabled': {'key': 'enabled', 'type': 'bool'},NEWLINE 'days': {'key': 'days', 'type': 'int'},NEWLINE }NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE *,NEWLINE enabled: bool,NEWLINE days: int,NEWLINE **kwargsNEWLINE ):NEWLINE """NEWLINE :keyword enabled: Required. a value indicating whether the retention policy is enabled.NEWLINE :paramtype enabled: boolNEWLINE :keyword days: Required. the number of days for the retention in days. A value of 0 will retainNEWLINE the events indefinitely.NEWLINE :paramtype days: intNEWLINE """NEWLINE super(RetentionPolicy, self).__init__(**kwargs)NEWLINE self.enabled = enabledNEWLINE self.days = daysNEWLINENEWLINENEWLINEclass ScaleAction(msrest.serialization.Model):NEWLINE """The parameters for the scaling action.NEWLINENEWLINE All required parameters must be populated in order to send to Azure.NEWLINENEWLINE :ivar direction: Required. the scale direction. Whether the scaling action increases orNEWLINE decreases the number of instances. Possible values include: "None", "Increase", "Decrease".NEWLINE :vartype direction: str or ~$(python-base-namespace).v2021_05_01_preview.models.ScaleDirectionNEWLINE :ivar type: Required. the type of action that should occur when the scale rule fires. PossibleNEWLINE values include: "ChangeCount", "PercentChangeCount", "ExactCount", "ServiceAllowedNextValue".NEWLINE :vartype type: str or ~$(python-base-namespace).v2021_05_01_preview.models.ScaleTypeNEWLINE :ivar value: the number of instances that are involved in the scaling action. This value mustNEWLINE be 1 or greater. The default value is 1.NEWLINE :vartype value: strNEWLINE :ivar cooldown: Required. the amount of time to wait since the last scaling action before thisNEWLINE action occurs. It must be between 1 week and 1 minute in ISO 8601 format.NEWLINE :vartype cooldown: ~datetime.timedeltaNEWLINE """NEWLINENEWLINE _validation = {NEWLINE 'direction': {'required': True},NEWLINE 'type': {'required': True},NEWLINE 'cooldown': {'required': True},NEWLINE }NEWLINENEWLINE _attribute_map = {NEWLINE 'direction': {'key': 'direction', 'type': 'str'},NEWLINE 'type': {'key': 'type', 'type': 'str'},NEWLINE 'value': {'key': 'value', 'type': 'str'},NEWLINE 'cooldown': {'key': 'cooldown', 'type': 'duration'},NEWLINE }NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE *,NEWLINE direction: Union[str, "ScaleDirection"],NEWLINE type: Union[str, "ScaleType"],NEWLINE cooldown: datetime.timedelta,NEWLINE value: Optional[str] = "1",NEWLINE **kwargsNEWLINE ):NEWLINE """NEWLINE :keyword direction: Required. the scale direction. Whether the scaling action increases orNEWLINE decreases the number of instances. Possible values include: "None", "Increase", "Decrease".NEWLINE :paramtype direction: str orNEWLINE ~$(python-base-namespace).v2021_05_01_preview.models.ScaleDirectionNEWLINE :keyword type: Required. the type of action that should occur when the scale rule fires.NEWLINE Possible values include: "ChangeCount", "PercentChangeCount", "ExactCount",NEWLINE "ServiceAllowedNextValue".NEWLINE :paramtype type: str or ~$(python-base-namespace).v2021_05_01_preview.models.ScaleTypeNEWLINE :keyword value: the number of instances that are involved in the scaling action. This valueNEWLINE must be 1 or greater. The default value is 1.NEWLINE :paramtype value: strNEWLINE :keyword cooldown: Required. the amount of time to wait since the last scaling action beforeNEWLINE this action occurs. It must be between 1 week and 1 minute in ISO 8601 format.NEWLINE :paramtype cooldown: ~datetime.timedeltaNEWLINE """NEWLINE super(ScaleAction, self).__init__(**kwargs)NEWLINE self.direction = directionNEWLINE self.type = typeNEWLINE self.value = valueNEWLINE self.cooldown = cooldownNEWLINENEWLINENEWLINEclass ScaleCapacity(msrest.serialization.Model):NEWLINE """The number of instances that can be used during this profile.NEWLINENEWLINE All required parameters must be populated in order to send to Azure.NEWLINENEWLINE :ivar minimum: Required. the minimum number of instances for the resource.NEWLINE :vartype minimum: strNEWLINE :ivar maximum: Required. the maximum number of instances for the resource. The actual maximumNEWLINE number of instances is limited by the cores that are available in the subscription.NEWLINE :vartype maximum: strNEWLINE :ivar default: Required. the number of instances that will be set if metrics are not availableNEWLINE for evaluation. The default is only used if the current instance count is lower than theNEWLINE default.NEWLINE :vartype default: strNEWLINE """NEWLINENEWLINE _validation = {NEWLINE 'minimum': {'required': True},NEWLINE 'maximum': {'required': True},NEWLINE 'default': {'required': True},NEWLINE }NEWLINENEWLINE _attribute_map = {NEWLINE 'minimum': {'key': 'minimum', 'type': 'str'},NEWLINE 'maximum': {'key': 'maximum', 'type': 'str'},NEWLINE 'default': {'key': 'default', 'type': 'str'},NEWLINE }NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE *,NEWLINE minimum: str,NEWLINE maximum: str,NEWLINE default: str,NEWLINE **kwargsNEWLINE ):NEWLINE """NEWLINE :keyword minimum: Required. the minimum number of instances for the resource.NEWLINE :paramtype minimum: strNEWLINE :keyword maximum: Required. the maximum number of instances for the resource. The actualNEWLINE maximum number of instances is limited by the cores that are available in the subscription.NEWLINE :paramtype maximum: strNEWLINE :keyword default: Required. the number of instances that will be set if metrics are notNEWLINE available for evaluation. The default is only used if the current instance count is lower thanNEWLINE the default.NEWLINE :paramtype default: strNEWLINE """NEWLINE super(ScaleCapacity, self).__init__(**kwargs)NEWLINE self.minimum = minimumNEWLINE self.maximum = maximumNEWLINE self.default = defaultNEWLINENEWLINENEWLINEclass ScaleRule(msrest.serialization.Model):NEWLINE """A rule that provide the triggers and parameters for the scaling action.NEWLINENEWLINE All required parameters must be populated in order to send to Azure.NEWLINENEWLINE :ivar metric_trigger: Required. the trigger that results in a scaling action.NEWLINE :vartype metric_trigger: ~$(python-base-namespace).v2021_05_01_preview.models.MetricTriggerNEWLINE :ivar scale_action: Required. the parameters for the scaling action.NEWLINE :vartype scale_action: ~$(python-base-namespace).v2021_05_01_preview.models.ScaleActionNEWLINE """NEWLINENEWLINE _validation = {NEWLINE 'metric_trigger': {'required': True},NEWLINE 'scale_action': {'required': True},NEWLINE }NEWLINENEWLINE _attribute_map = {NEWLINE 'metric_trigger': {'key': 'metricTrigger', 'type': 'MetricTrigger'},NEWLINE 'scale_action': {'key': 'scaleAction', 'type': 'ScaleAction'},NEWLINE }NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE *,NEWLINE metric_trigger: "MetricTrigger",NEWLINE scale_action: "ScaleAction",NEWLINE **kwargsNEWLINE ):NEWLINE """NEWLINE :keyword metric_trigger: Required. the trigger that results in a scaling action.NEWLINE :paramtype metric_trigger: ~$(python-base-namespace).v2021_05_01_preview.models.MetricTriggerNEWLINE :keyword scale_action: Required. the parameters for the scaling action.NEWLINE :paramtype scale_action: ~$(python-base-namespace).v2021_05_01_preview.models.ScaleActionNEWLINE """NEWLINE super(ScaleRule, self).__init__(**kwargs)NEWLINE self.metric_trigger = metric_triggerNEWLINE self.scale_action = scale_actionNEWLINENEWLINENEWLINEclass ScaleRuleMetricDimension(msrest.serialization.Model):NEWLINE """Specifies an auto scale rule metric dimension.NEWLINENEWLINE All required parameters must be populated in order to send to Azure.NEWLINENEWLINE :ivar dimension_name: Required. Name of the dimension.NEWLINE :vartype dimension_name: strNEWLINE :ivar operator: Required. the dimension operator. Only 'Equals' and 'NotEquals' are supported.NEWLINE 'Equals' being equal to any of the values. 'NotEquals' being not equal to all of the values.NEWLINE Possible values include: "Equals", "NotEquals".NEWLINE :vartype operator: str orNEWLINE ~$(python-base-namespace).v2021_05_01_preview.models.ScaleRuleMetricDimensionOperationTypeNEWLINE :ivar values: Required. list of dimension values. For example: ["App1","App2"].NEWLINE :vartype values: list[str]NEWLINE """NEWLINENEWLINE _validation = {NEWLINE 'dimension_name': {'required': True},NEWLINE 'operator': {'required': True},NEWLINE 'values': {'required': True},NEWLINE }NEWLINENEWLINE _attribute_map = {NEWLINE 'dimension_name': {'key': 'DimensionName', 'type': 'str'},NEWLINE 'operator': {'key': 'Operator', 'type': 'str'},NEWLINE 'values': {'key': 'Values', 'type': '[str]'},NEWLINE }NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE *,NEWLINE dimension_name: str,NEWLINE operator: Union[str, "ScaleRuleMetricDimensionOperationType"],NEWLINE values: List[str],NEWLINE **kwargsNEWLINE ):NEWLINE """NEWLINE :keyword dimension_name: Required. Name of the dimension.NEWLINE :paramtype dimension_name: strNEWLINE :keyword operator: Required. the dimension operator. Only 'Equals' and 'NotEquals' areNEWLINE supported. 'Equals' being equal to any of the values. 'NotEquals' being not equal to all of theNEWLINE values. Possible values include: "Equals", "NotEquals".NEWLINE :paramtype operator: str orNEWLINE ~$(python-base-namespace).v2021_05_01_preview.models.ScaleRuleMetricDimensionOperationTypeNEWLINE :keyword values: Required. list of dimension values. For example: ["App1","App2"].NEWLINE :paramtype values: list[str]NEWLINE """NEWLINE super(ScaleRuleMetricDimension, self).__init__(**kwargs)NEWLINE self.dimension_name = dimension_nameNEWLINE self.operator = operatorNEWLINE self.values = valuesNEWLINENEWLINENEWLINEclass SubscriptionDiagnosticSettingsResource(Resource):NEWLINE """The subscription diagnostic setting resource.NEWLINENEWLINE Variables are only populated by the server, and will be ignored when sending a request.NEWLINENEWLINE :ivar id: Fully qualified resource ID for the resource. Ex -NEWLINE /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.NEWLINE :vartype id: strNEWLINE :ivar name: The name of the resource.NEWLINE :vartype name: strNEWLINE :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" orNEWLINE "Microsoft.Storage/storageAccounts".NEWLINE :vartype type: strNEWLINE :ivar system_data: The system metadata related to this resource.NEWLINE :vartype system_data: ~$(python-base-namespace).v2021_05_01_preview.models.SystemDataNEWLINE :ivar storage_account_id: The resource ID of the storage account to which you would like toNEWLINE send Diagnostic Logs.NEWLINE :vartype storage_account_id: strNEWLINE :ivar service_bus_rule_id: The service bus rule Id of the diagnostic setting. This is here toNEWLINE maintain backwards compatibility.NEWLINE :vartype service_bus_rule_id: strNEWLINE :ivar event_hub_authorization_rule_id: The resource Id for the event hub authorization rule.NEWLINE :vartype event_hub_authorization_rule_id: strNEWLINE :ivar event_hub_name: The name of the event hub. If none is specified, the default event hubNEWLINE will be selected.NEWLINE :vartype event_hub_name: strNEWLINE :ivar logs: The list of logs settings.NEWLINE :vartype logs:NEWLINE list[~$(python-base-namespace).v2021_05_01_preview.models.SubscriptionLogSettings]NEWLINE :ivar workspace_id: The full ARM resource ID of the Log Analytics workspace to which you wouldNEWLINE like to send Diagnostic Logs. Example:NEWLINE /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2.NEWLINE :vartype workspace_id: strNEWLINE :ivar marketplace_partner_id: The full ARM resource ID of the Marketplace resource to which youNEWLINE would like to send Diagnostic Logs.NEWLINE :vartype marketplace_partner_id: strNEWLINE """NEWLINENEWLINE _validation = {NEWLINE 'id': {'readonly': True},NEWLINE 'name': {'readonly': True},NEWLINE 'type': {'readonly': True},NEWLINE 'system_data': {'readonly': True},NEWLINE }NEWLINENEWLINE _attribute_map = {NEWLINE 'id': {'key': 'id', 'type': 'str'},NEWLINE 'name': {'key': 'name', 'type': 'str'},NEWLINE 'type': {'key': 'type', 'type': 'str'},NEWLINE 'system_data': {'key': 'systemData', 'type': 'SystemData'},NEWLINE 'storage_account_id': {'key': 'properties.storageAccountId', 'type': 'str'},NEWLINE 'service_bus_rule_id': {'key': 'properties.serviceBusRuleId', 'type': 'str'},NEWLINE 'event_hub_authorization_rule_id': {'key': 'properties.eventHubAuthorizationRuleId', 'type': 'str'},NEWLINE 'event_hub_name': {'key': 'properties.eventHubName', 'type': 'str'},NEWLINE 'logs': {'key': 'properties.logs', 'type': '[SubscriptionLogSettings]'},NEWLINE 'workspace_id': {'key': 'properties.workspaceId', 'type': 'str'},NEWLINE 'marketplace_partner_id': {'key': 'properties.marketplacePartnerId', 'type': 'str'},NEWLINE }NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE *,NEWLINE storage_account_id: Optional[str] = None,NEWLINE service_bus_rule_id: Optional[str] = None,NEWLINE event_hub_authorization_rule_id: Optional[str] = None,NEWLINE event_hub_name: Optional[str] = None,NEWLINE logs: Optional[List["SubscriptionLogSettings"]] = None,NEWLINE workspace_id: Optional[str] = None,NEWLINE marketplace_partner_id: Optional[str] = None,NEWLINE **kwargsNEWLINE ):NEWLINE """NEWLINE :keyword storage_account_id: The resource ID of the storage account to which you would like toNEWLINE send Diagnostic Logs.NEWLINE :paramtype storage_account_id: strNEWLINE :keyword service_bus_rule_id: The service bus rule Id of the diagnostic setting. This is hereNEWLINE to maintain backwards compatibility.NEWLINE :paramtype service_bus_rule_id: strNEWLINE :keyword event_hub_authorization_rule_id: The resource Id for the event hub authorization rule.NEWLINE :paramtype event_hub_authorization_rule_id: strNEWLINE :keyword event_hub_name: The name of the event hub. If none is specified, the default event hubNEWLINE will be selected.NEWLINE :paramtype event_hub_name: strNEWLINE :keyword logs: The list of logs settings.NEWLINE :paramtype logs:NEWLINE list[~$(python-base-namespace).v2021_05_01_preview.models.SubscriptionLogSettings]NEWLINE :keyword workspace_id: The full ARM resource ID of the Log Analytics workspace to which youNEWLINE would like to send Diagnostic Logs. Example:NEWLINE /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2.NEWLINE :paramtype workspace_id: strNEWLINE :keyword marketplace_partner_id: The full ARM resource ID of the Marketplace resource to whichNEWLINE you would like to send Diagnostic Logs.NEWLINE :paramtype marketplace_partner_id: strNEWLINE """NEWLINE super(SubscriptionDiagnosticSettingsResource, self).__init__(**kwargs)NEWLINE self.system_data = NoneNEWLINE self.storage_account_id = storage_account_idNEWLINE self.service_bus_rule_id = service_bus_rule_idNEWLINE self.event_hub_authorization_rule_id = event_hub_authorization_rule_idNEWLINE self.event_hub_name = event_hub_nameNEWLINE self.logs = logsNEWLINE self.workspace_id = workspace_idNEWLINE self.marketplace_partner_id = marketplace_partner_idNEWLINENEWLINENEWLINEclass SubscriptionDiagnosticSettingsResourceCollection(msrest.serialization.Model):NEWLINE """Represents a collection of subscription diagnostic settings resources.NEWLINENEWLINE :ivar value: The collection of subscription diagnostic settings resources.NEWLINE :vartype value:NEWLINE list[~$(python-base-namespace).v2021_05_01_preview.models.SubscriptionDiagnosticSettingsResource]NEWLINE """NEWLINENEWLINE _attribute_map = {NEWLINE 'value': {'key': 'value', 'type': '[SubscriptionDiagnosticSettingsResource]'},NEWLINE }NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE *,NEWLINE value: Optional[List["SubscriptionDiagnosticSettingsResource"]] = None,NEWLINE **kwargsNEWLINE ):NEWLINE """NEWLINE :keyword value: The collection of subscription diagnostic settings resources.NEWLINE :paramtype value:NEWLINE list[~$(python-base-namespace).v2021_05_01_preview.models.SubscriptionDiagnosticSettingsResource]NEWLINE """NEWLINE super(SubscriptionDiagnosticSettingsResourceCollection, self).__init__(**kwargs)NEWLINE self.value = valueNEWLINENEWLINENEWLINEclass SubscriptionLogSettings(msrest.serialization.Model):NEWLINE """Part of Subscription diagnostic setting. Specifies the settings for a particular log.NEWLINENEWLINE All required parameters must be populated in order to send to Azure.NEWLINENEWLINE :ivar category: Name of a Subscription Diagnostic Log category for a resource type this settingNEWLINE is applied to.NEWLINE :vartype category: strNEWLINE :ivar category_group: Name of a Subscription Diagnostic Log category group for a resource typeNEWLINE this setting is applied to.NEWLINE :vartype category_group: strNEWLINE :ivar enabled: Required. a value indicating whether this log is enabled.NEWLINE :vartype enabled: boolNEWLINE """NEWLINENEWLINE _validation = {NEWLINE 'enabled': {'required': True},NEWLINE }NEWLINENEWLINE _attribute_map = {NEWLINE 'category': {'key': 'category', 'type': 'str'},NEWLINE 'category_group': {'key': 'categoryGroup', 'type': 'str'},NEWLINE 'enabled': {'key': 'enabled', 'type': 'bool'},NEWLINE }NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE *,NEWLINE enabled: bool,NEWLINE category: Optional[str] = None,NEWLINE category_group: Optional[str] = None,NEWLINE **kwargsNEWLINE ):NEWLINE """NEWLINE :keyword category: Name of a Subscription Diagnostic Log category for a resource type thisNEWLINE setting is applied to.NEWLINE :paramtype category: strNEWLINE :keyword category_group: Name of a Subscription Diagnostic Log category group for a resourceNEWLINE type this setting is applied to.NEWLINE :paramtype category_group: strNEWLINE :keyword enabled: Required. a value indicating whether this log is enabled.NEWLINE :paramtype enabled: boolNEWLINE """NEWLINE super(SubscriptionLogSettings, self).__init__(**kwargs)NEWLINE self.category = categoryNEWLINE self.category_group = category_groupNEWLINE self.enabled = enabledNEWLINENEWLINENEWLINEclass SystemData(msrest.serialization.Model):NEWLINE """Metadata pertaining to creation and last modification of the resource.NEWLINENEWLINE :ivar created_by: The identity that created the resource.NEWLINE :vartype created_by: strNEWLINE :ivar created_by_type: The type of identity that created the resource. Possible values include:NEWLINE "User", "Application", "ManagedIdentity", "Key".NEWLINE :vartype created_by_type: str orNEWLINE ~$(python-base-namespace).v2021_05_01_preview.models.CreatedByTypeNEWLINE :ivar created_at: The timestamp of resource creation (UTC).NEWLINE :vartype created_at: ~datetime.datetimeNEWLINE :ivar last_modified_by: The identity that last modified the resource.NEWLINE :vartype last_modified_by: strNEWLINE :ivar last_modified_by_type: The type of identity that last modified the resource. PossibleNEWLINE values include: "User", "Application", "ManagedIdentity", "Key".NEWLINE :vartype last_modified_by_type: str orNEWLINE ~$(python-base-namespace).v2021_05_01_preview.models.CreatedByTypeNEWLINE :ivar last_modified_at: The timestamp of resource last modification (UTC).NEWLINE :vartype last_modified_at: ~datetime.datetimeNEWLINE """NEWLINENEWLINE _attribute_map = {NEWLINE 'created_by': {'key': 'createdBy', 'type': 'str'},NEWLINE 'created_by_type': {'key': 'createdByType', 'type': 'str'},NEWLINE 'created_at': {'key': 'createdAt', 'type': 'iso-8601'},NEWLINE 'last_modified_by': {'key': 'lastModifiedBy', 'type': 'str'},NEWLINE 'last_modified_by_type': {'key': 'lastModifiedByType', 'type': 'str'},NEWLINE 'last_modified_at': {'key': 'lastModifiedAt', 'type': 'iso-8601'},NEWLINE }NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE *,NEWLINE created_by: Optional[str] = None,NEWLINE created_by_type: Optional[Union[str, "CreatedByType"]] = None,NEWLINE created_at: Optional[datetime.datetime] = None,NEWLINE last_modified_by: Optional[str] = None,NEWLINE last_modified_by_type: Optional[Union[str, "CreatedByType"]] = None,NEWLINE last_modified_at: Optional[datetime.datetime] = None,NEWLINE **kwargsNEWLINE ):NEWLINE """NEWLINE :keyword created_by: The identity that created the resource.NEWLINE :paramtype created_by: strNEWLINE :keyword created_by_type: The type of identity that created the resource. Possible valuesNEWLINE include: "User", "Application", "ManagedIdentity", "Key".NEWLINE :paramtype created_by_type: str orNEWLINE ~$(python-base-namespace).v2021_05_01_preview.models.CreatedByTypeNEWLINE :keyword created_at: The timestamp of resource creation (UTC).NEWLINE :paramtype created_at: ~datetime.datetimeNEWLINE :keyword last_modified_by: The identity that last modified the resource.NEWLINE :paramtype last_modified_by: strNEWLINE :keyword last_modified_by_type: The type of identity that last modified the resource. PossibleNEWLINE values include: "User", "Application", "ManagedIdentity", "Key".NEWLINE :paramtype last_modified_by_type: str orNEWLINE ~$(python-base-namespace).v2021_05_01_preview.models.CreatedByTypeNEWLINE :keyword last_modified_at: The timestamp of resource last modification (UTC).NEWLINE :paramtype last_modified_at: ~datetime.datetimeNEWLINE """NEWLINE super(SystemData, self).__init__(**kwargs)NEWLINE self.created_by = created_byNEWLINE self.created_by_type = created_by_typeNEWLINE self.created_at = created_atNEWLINE self.last_modified_by = last_modified_byNEWLINE self.last_modified_by_type = last_modified_by_typeNEWLINE self.last_modified_at = last_modified_atNEWLINENEWLINENEWLINEclass TimeWindow(msrest.serialization.Model):NEWLINE """A specific date-time for the profile.NEWLINENEWLINE All required parameters must be populated in order to send to Azure.NEWLINENEWLINE :ivar time_zone: the timezone of the start and end times for the profile. Some examples ofNEWLINE valid time zones are: Dateline Standard Time, UTC-11, Hawaiian Standard Time, Alaskan StandardNEWLINE Time, Pacific Standard Time (Mexico), Pacific Standard Time, US Mountain Standard Time,NEWLINE Mountain Standard Time (Mexico), Mountain Standard Time, Central America Standard Time, CentralNEWLINE Standard Time, Central Standard Time (Mexico), Canada Central Standard Time, SA PacificNEWLINE Standard Time, Eastern Standard Time, US Eastern Standard Time, Venezuela Standard Time,NEWLINE Paraguay Standard Time, Atlantic Standard Time, Central Brazilian Standard Time, SA WesternNEWLINE Standard Time, Pacific SA Standard Time, Newfoundland Standard Time, E. South America StandardNEWLINE Time, Argentina Standard Time, SA Eastern Standard Time, Greenland Standard Time, MontevideoNEWLINE Standard Time, Bahia Standard Time, UTC-02, Mid-Atlantic Standard Time, Azores Standard Time,NEWLINE Cape Verde Standard Time, Morocco Standard Time, UTC, GMT Standard Time, Greenwich StandardNEWLINE Time, W. Europe Standard Time, Central Europe Standard Time, Romance Standard Time, CentralNEWLINE European Standard Time, W. Central Africa Standard Time, Namibia Standard Time, Jordan StandardNEWLINE Time, GTB Standard Time, Middle East Standard Time, Egypt Standard Time, Syria Standard Time,NEWLINE E. Europe Standard Time, South Africa Standard Time, FLE Standard Time, Turkey Standard Time,NEWLINE Israel Standard Time, Kaliningrad Standard Time, Libya Standard Time, Arabic Standard Time,NEWLINE Arab Standard Time, Belarus Standard Time, Russian Standard Time, E. Africa Standard Time, IranNEWLINE Standard Time, Arabian Standard Time, Azerbaijan Standard Time, Russia Time Zone 3, MauritiusNEWLINE Standard Time, Georgian Standard Time, Caucasus Standard Time, Afghanistan Standard Time, WestNEWLINE Asia Standard Time, Ekaterinburg Standard Time, Pakistan Standard Time, India Standard Time,NEWLINE Sri Lanka Standard Time, Nepal Standard Time, Central Asia Standard Time, Bangladesh StandardNEWLINE Time, N. Central Asia Standard Time, Myanmar Standard Time, SE Asia Standard Time, North AsiaNEWLINE Standard Time, China Standard Time, North Asia East Standard Time, Singapore Standard Time, W.NEWLINE Australia Standard Time, Taipei Standard Time, Ulaanbaatar Standard Time, Tokyo Standard Time,NEWLINE Korea Standard Time, Yakutsk Standard Time, Cen. Australia Standard Time, AUS Central StandardNEWLINE Time, E. Australia Standard Time, AUS Eastern Standard Time, West Pacific Standard Time,NEWLINE Tasmania Standard Time, Magadan Standard Time, Vladivostok Standard Time, Russia Time Zone 10,NEWLINE Central Pacific Standard Time, Russia Time Zone 11, New Zealand Standard Time, UTC+12, FijiNEWLINE Standard Time, Kamchatka Standard Time, Tonga Standard Time, Samoa Standard Time, Line IslandsNEWLINE Standard Time.NEWLINE :vartype time_zone: strNEWLINE :ivar start: Required. the start time for the profile in ISO 8601 format.NEWLINE :vartype start: ~datetime.datetimeNEWLINE :ivar end: Required. the end time for the profile in ISO 8601 format.NEWLINE :vartype end: ~datetime.datetimeNEWLINE """NEWLINENEWLINE _validation = {NEWLINE 'start': {'required': True},NEWLINE 'end': {'required': True},NEWLINE }NEWLINENEWLINE _attribute_map = {NEWLINE 'time_zone': {'key': 'timeZone', 'type': 'str'},NEWLINE 'start': {'key': 'start', 'type': 'iso-8601'},NEWLINE 'end': {'key': 'end', 'type': 'iso-8601'},NEWLINE }NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE *,NEWLINE start: datetime.datetime,NEWLINE end: datetime.datetime,NEWLINE time_zone: Optional[str] = None,NEWLINE **kwargsNEWLINE ):NEWLINE """NEWLINE :keyword time_zone: the timezone of the start and end times for the profile. Some examples ofNEWLINE valid time zones are: Dateline Standard Time, UTC-11, Hawaiian Standard Time, Alaskan StandardNEWLINE Time, Pacific Standard Time (Mexico), Pacific Standard Time, US Mountain Standard Time,NEWLINE Mountain Standard Time (Mexico), Mountain Standard Time, Central America Standard Time, CentralNEWLINE Standard Time, Central Standard Time (Mexico), Canada Central Standard Time, SA PacificNEWLINE Standard Time, Eastern Standard Time, US Eastern Standard Time, Venezuela Standard Time,NEWLINE Paraguay Standard Time, Atlantic Standard Time, Central Brazilian Standard Time, SA WesternNEWLINE Standard Time, Pacific SA Standard Time, Newfoundland Standard Time, E. South America StandardNEWLINE Time, Argentina Standard Time, SA Eastern Standard Time, Greenland Standard Time, MontevideoNEWLINE Standard Time, Bahia Standard Time, UTC-02, Mid-Atlantic Standard Time, Azores Standard Time,NEWLINE Cape Verde Standard Time, Morocco Standard Time, UTC, GMT Standard Time, Greenwich StandardNEWLINE Time, W. Europe Standard Time, Central Europe Standard Time, Romance Standard Time, CentralNEWLINE European Standard Time, W. Central Africa Standard Time, Namibia Standard Time, Jordan StandardNEWLINE Time, GTB Standard Time, Middle East Standard Time, Egypt Standard Time, Syria Standard Time,NEWLINE E. Europe Standard Time, South Africa Standard Time, FLE Standard Time, Turkey Standard Time,NEWLINE Israel Standard Time, Kaliningrad Standard Time, Libya Standard Time, Arabic Standard Time,NEWLINE Arab Standard Time, Belarus Standard Time, Russian Standard Time, E. Africa Standard Time, IranNEWLINE Standard Time, Arabian Standard Time, Azerbaijan Standard Time, Russia Time Zone 3, MauritiusNEWLINE Standard Time, Georgian Standard Time, Caucasus Standard Time, Afghanistan Standard Time, WestNEWLINE Asia Standard Time, Ekaterinburg Standard Time, Pakistan Standard Time, India Standard Time,NEWLINE Sri Lanka Standard Time, Nepal Standard Time, Central Asia Standard Time, Bangladesh StandardNEWLINE Time, N. Central Asia Standard Time, Myanmar Standard Time, SE Asia Standard Time, North AsiaNEWLINE Standard Time, China Standard Time, North Asia East Standard Time, Singapore Standard Time, W.NEWLINE Australia Standard Time, Taipei Standard Time, Ulaanbaatar Standard Time, Tokyo Standard Time,NEWLINE Korea Standard Time, Yakutsk Standard Time, Cen. Australia Standard Time, AUS Central StandardNEWLINE Time, E. Australia Standard Time, AUS Eastern Standard Time, West Pacific Standard Time,NEWLINE Tasmania Standard Time, Magadan Standard Time, Vladivostok Standard Time, Russia Time Zone 10,NEWLINE Central Pacific Standard Time, Russia Time Zone 11, New Zealand Standard Time, UTC+12, FijiNEWLINE Standard Time, Kamchatka Standard Time, Tonga Standard Time, Samoa Standard Time, Line IslandsNEWLINE Standard Time.NEWLINE :paramtype time_zone: strNEWLINE :keyword start: Required. the start time for the profile in ISO 8601 format.NEWLINE :paramtype start: ~datetime.datetimeNEWLINE :keyword end: Required. the end time for the profile in ISO 8601 format.NEWLINE :paramtype end: ~datetime.datetimeNEWLINE """NEWLINE super(TimeWindow, self).__init__(**kwargs)NEWLINE self.time_zone = time_zoneNEWLINE self.start = startNEWLINE self.end = endNEWLINENEWLINENEWLINEclass WebhookNotification(msrest.serialization.Model):NEWLINE """Webhook notification of an autoscale event.NEWLINENEWLINE :ivar service_uri: the service address to receive the notification.NEWLINE :vartype service_uri: strNEWLINE :ivar properties: a property bag of settings. This value can be empty.NEWLINE :vartype properties: dict[str, str]NEWLINE """NEWLINENEWLINE _attribute_map = {NEWLINE 'service_uri': {'key': 'serviceUri', 'type': 'str'},NEWLINE 'properties': {'key': 'properties', 'type': '{str}'},NEWLINE }NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE *,NEWLINE service_uri: Optional[str] = None,NEWLINE properties: Optional[Dict[str, str]] = None,NEWLINE **kwargsNEWLINE ):NEWLINE """NEWLINE :keyword service_uri: the service address to receive the notification.NEWLINE :paramtype service_uri: strNEWLINE :keyword properties: a property bag of settings. This value can be empty.NEWLINE :paramtype properties: dict[str, str]NEWLINE """NEWLINE super(WebhookNotification, self).__init__(**kwargs)NEWLINE self.service_uri = service_uriNEWLINE self.properties = propertiesNEWLINE
_base_ = './mask_rcnn_r101_fpn_1x_coco.py'NEWLINEmodel = dict(NEWLINE pretrained='open-mmlab://resnext101_32x4d',NEWLINE backbone=dict(NEWLINE type='ResNeXt',NEWLINE depth=101,NEWLINE groups=32,NEWLINE base_width=4,NEWLINE num_stages=4,NEWLINE out_indices=(0, 1, 2, 3),NEWLINE frozen_stages=1,NEWLINE norm_cfg=dict(type='BN', requires_grad=True),NEWLINE style='pytorch'))NEWLINE
"""Program to draw Mandelbrot fractals: the graphical user interface.NEWLINENEWLINEAuthor: Lars van den Haak and Tom VerhoeffNEWLINENEWLINECopyright (c) 2020 - Eindhoven University of Technology, The NetherlandsNEWLINENEWLINEThis software is made available under the terms of the MIT License.NEWLINENEWLINE* Contributor 1: Harry VerspagenNEWLINE* TU/e ID number 1: 1484575NEWLINE* Contributor 2: Sander DebetsNEWLINE* TU/e ID number 2: 1252402NEWLINE* Date: 04-05-2020NEWLINE"""NEWLINEfrom PIL import Image, ImageTk # type: ignoreNEWLINEimport tkinter as tkNEWLINEfrom mandel import *NEWLINEfrom typing import CallableNEWLINENEWLINENEWLINEdef squares(px: int, py: int, c1: Color = GREEN, c2: Color = BLUE) -> Color:NEWLINE """Colors the screen in squares of 20 pixelsNEWLINENEWLINE :param: px: pixel x-coordinateNEWLINE :param: py: pixel y-coordinateNEWLINE :param: c1: Color of the first type of squareNEWLINE :param: c2: Color of the second type of squareNEWLINE :return: Color for the input pixelNEWLINE """NEWLINE if px // 20 % 2 == py // 20 % 2:NEWLINE c = c1NEWLINE else:NEWLINE c = c2NEWLINE return cNEWLINENEWLINENEWLINEclass GUI:NEWLINE """A class where we make our Graphical User Interface based on TkInterNEWLINE """NEWLINE def __init__(self) -> None:NEWLINE self.image = NoneNEWLINE self.window = tk.Tk()NEWLINE self.canvas = tk.Label(self.window, image=None)NEWLINE self.canvas.pack(side="bottom", fill="both", expand="yes")NEWLINENEWLINENEWLINEdef make_image(gui: GUI, colorize: Callable[[int, int], Color] = squares) -> None:NEWLINE """Puts an image on screen created by a functionNEWLINENEWLINE :param: gui: An instance from the GUI classNEWLINE :param: colorize: A function that gives a color to each pixelNEWLINE """NEWLINE img = Image.new('RGB', (600, 600))NEWLINE for x in range(0, 600):NEWLINE for y in range(0, 600):NEWLINE img.putpixel((x, y), colorize(x, y))NEWLINENEWLINE tkimg = ImageTk.PhotoImage(img)NEWLINE # Save the image to the gui class, otherwise it gets garbage collectedNEWLINE gui.image = tkimgNEWLINE canvas = gui.canvasNEWLINENEWLINE canvas.configure(image=tkimg)NEWLINE canvas.pack(side="bottom", fill="both", expand="yes")NEWLINE
from __future__ import unicode_literalsNEWLINEfrom django.db import modelsNEWLINE#from django.utils import timezoneNEWLINEfrom accounts.models import UserNEWLINENEWLINE NEWLINE# 계산 객체 생성NEWLINEclass Inference(models.Model):NEWLINE author = models.ForeignKey(User, NEWLINE null = True, # DB에 null 저장을 허용(탈퇴 퇴출 등).NEWLINE blank= False, # 입력 창에서는 반드시 author가 존재해야함.NEWLINE on_delete=models.SET_NULL)NEWLINE title = models.CharField(max_length=200)NEWLINE memo = models.TextField(blank = True, null = True)NEWLINENEWLINE input_data = models.FileField(upload_to='list/files/%Y/%m/%d/', blank = True)NEWLINENEWLINE output_data = models.FileField(upload_to='list/files/%Y/%m/%d/', blank = True, null = True)NEWLINENEWLINE output_text = models.CharField(max_length=200,NEWLINE blank = True,NEWLINE null = True)NEWLINENEWLINE thumbnail = models.ImageField(u'썸네일', NEWLINE upload_to='%Y/%m/%d', blank=True, null=True)NEWLINE created_at = models.DateTimeField(auto_now_add = True)NEWLINE updated_at = models.DateTimeField(auto_now = True)NEWLINENEWLINE def __str__(self):NEWLINE return f'[{self.pk}] {self.title} :: {self.author}'
from setuptools import setup, find_packagesNEWLINENEWLINENEWLINEsetup(NEWLINE name='zeit.find',NEWLINE version='3.0.10.dev0',NEWLINE author='gocept, Zeit Online',NEWLINE author_email='zon-backend@zeit.de',NEWLINE url='http://www.zeit.de/',NEWLINE description="vivi UI for querying elastic search",NEWLINE packages=find_packages('src'),NEWLINE package_dir={'': 'src'},NEWLINE include_package_data=True,NEWLINE zip_safe=False,NEWLINE license='BSD',NEWLINE namespace_packages=['zeit'],NEWLINE install_requires=[NEWLINE 'gocept.httpserverlayer',NEWLINE 'gocept.selenium',NEWLINE 'grokcore.component',NEWLINE 'plone.testing',NEWLINE 'setuptools',NEWLINE 'zc.iso8601',NEWLINE 'zeit.cms >= 3.12.0.dev0',NEWLINE 'zeit.content.image',NEWLINE 'zeit.retresco >= 1.31.0.dev0',NEWLINE ],NEWLINE entry_points={NEWLINE 'fanstatic.libraries': [NEWLINE 'zeit_find=zeit.find.browser.resources:lib',NEWLINE ],NEWLINE 'console_scripts': [NEWLINE 'search-elastic=zeit.find.cli:search_elastic',NEWLINE ],NEWLINE },NEWLINE)NEWLINE
from pyspark import SparkFilesNEWLINEfrom pyspark.sql import SparkSession, DataFrameWriterNEWLINEfrom pyspark.sql.functions import when, isnull, col, explode, splitNEWLINENEWLINEimport osNEWLINENEWLINEdef analyze(ss, json_file):NEWLINE print('Calculating hourly activities')NEWLINE df = ss.read.json(json_file)NEWLINE try:NEWLINE df = df.select('*', explode(split('date', ', ')))NEWLINE except:NEWLINE print('** No "data" field found in HourlyActivity file input **')NEWLINE exit(-1)NEWLINE ip = os.getenv('POSTGRES_IP')NEWLINE url = "jdbc:postgresql://" + ip + "/hiddengems_db"NEWLINE table = "checkins"NEWLINE mode = "overwrite"NEWLINE properties = {NEWLINE "user": "postgres", NEWLINE "password": "password", NEWLINE "driver": "org.postgresql.Driver"NEWLINE }NEWLINE try:NEWLINE df = df.drop(col('date')).withColumnRenamed('col','date')NEWLINE except:NEWLINE print('** Warning: The file provided in HourlyActivity does not have the correct schema. **')NEWLINE exit(-1)NEWLINE NEWLINE df.write.jdbc(url, table, mode, properties)
# -*- coding: utf-8 -*-NEWLINEfrom tests import HangulizeTestCaseNEWLINEfrom hangulize.langs.aze import AzerbaijaniNEWLINENEWLINENEWLINEclass AzerbaijaniTestCase(HangulizeTestCase):NEWLINENEWLINE lang = Azerbaijani()NEWLINENEWLINE def test_people(self):NEWLINE self.assert_examples({NEWLINE u'Namiq Abdullayev': u'나미크 아브둘라예프',NEWLINE u'Qəmər Almaszadə': u'게메르 알마스자데',NEWLINE u'Heydər Əliyev': u'헤이데르 엘리예프',NEWLINE u'İlham Əliyev': u'일함 엘리예프',NEWLINE u'Hüseyn Ərəblinski': u'휘세인 에레블린스키',NEWLINE u'Rəşid Behbudov': u'레시트 베흐부도프',NEWLINE u'Bülbül': u'뷜뷜',NEWLINE u'Cəfər Cabbarlı': u'제페르 자발르',NEWLINE u'Vaqif Cavadov': u'바기프 자바도프',NEWLINE u'Hüseyn Cavid': u'휘세인 자비트',NEWLINE u'Füzuli': u'퓌줄리',NEWLINE u'Üzeyir Hacıbəyov': u'위제이르 하즈베요프',NEWLINE u'Mehdi Hüseynzadə': u'메흐디 휘세인자데',NEWLINE u'Kərim Kərimov': u'케림 케리모프',NEWLINE u'Fərid Mansurov': u'페리트 만수로프',NEWLINE u'Elnur Məmmədli': u'엘누르 멤메들리',NEWLINE u'Məhəmməd Mövlazadə': u'메헴메트 뫼블라자데',NEWLINE u'Əzizə Mustafazadə': u'에지제 무스타파자데',NEWLINE u'Vaqif Mustafazadə': u'바기프 무스타파자데',NEWLINE u'Mikayıl Müşfiq': u'미카이을 뮈슈피크',NEWLINE u'Xurşidbanu Natəvan': u'후르시드바누 나테반',NEWLINE u'Hüseyn xan Naxçıvanski': u'휘세인 한 나흐츠반스키',NEWLINE u'Nəriman Nərimanov': u'네리만 네리마노프',NEWLINE u'İmadəddin Nəsimi': u'이마데딘 네시미',NEWLINE u'Mir-Möhsün Nəvvab': u'미르뫼흐쉰 네바프',NEWLINE u'Ramil Quliyev': u'라밀 굴리예프',NEWLINE u'Nigar Rəfibəyli': u'니가르 레피베일리',NEWLINE u'Artur Rəsizadə': u'아르투르 레시자데',NEWLINE u'Məhəmməd Əmin Rəsulzadə': u'메헴메트 에민 레술자데',NEWLINE u'Süleyman Rüstəm': u'쉴레이만 뤼스템',NEWLINE u'Rəsul Rza': u'레술 르자',NEWLINE u'Rəşad Sadıqov': u'레샤트 사드고프',NEWLINE u'Məmməd ağa Şahtaxtinski': u'멤메트 아가 샤흐타흐틴스키',NEWLINE u'Məhəmmədhüseyn Şəhriyar': u'메헴메트휘세인 셰흐리야르',NEWLINE u'Nigar Şıxlinskaya': u'니가르 시으흘린스카야',NEWLINE u'Zeynalabdin Tağıyev': u'제이날라브딘 타그예프',NEWLINE u'Aysel Teymurzadə': u'아이셀 테이무르자데',NEWLINE u'Səməd Vurğun': u'세메트 부르군',NEWLINE u'Fətəli xan Xoyski': u'페텔리 한 호이스키',NEWLINE })NEWLINENEWLINE def test_places(self):NEWLINE self.assert_examples({NEWLINE u'Abşeron': u'압셰론',NEWLINE u'Ağdam': u'아그담',NEWLINE u'Azərbaycan': u'아제르바이잔',NEWLINE u'Bakı': u'바크',NEWLINE u'Gəncə': u'겐제',NEWLINE u'İçəri Şəhər': u'이체리 셰헤르',NEWLINE u'Lənkəran': u'렌케란',NEWLINE u'Mingəçevir': u'민게체비르',NEWLINE u'Naftalan': u'나프탈란',NEWLINE u'Naxçıvan': u'나흐츠반',NEWLINE u'Qəbələ': u'게벨레',NEWLINE u'Qobustan': u'고부스탄',NEWLINE u'Salyan': u'살리안',NEWLINE u'Sumqayıt': u'숨가이으트',NEWLINE u'Şəki': u'셰키',NEWLINE u'Şəmkir': u'솀키르',NEWLINE u'Şirvan': u'시르반',NEWLINE u'Talış': u'탈르슈',NEWLINE u'Tovuz': u'토부스',NEWLINE u'Xaçmaz': u'하치마스',NEWLINE u'Xınalıq': u'흐날르크',NEWLINE u'Xırdalan': u'흐르달란',NEWLINE u'Yevlax': u'예블라흐',NEWLINE u'Zaqatala': u'자가탈라',NEWLINE })NEWLINENEWLINE def test_others(self):NEWLINE self.assert_examples({NEWLINE u'jurnal': u'주르날',NEWLINE })NEWLINE
"""add tagsNEWLINENEWLINERevision ID: 42f99b73b077NEWLINERevises: e59c406395d2NEWLINECreate Date: 2017-02-02 16:08:12.273221NEWLINENEWLINE"""NEWLINEfrom alembic import opNEWLINEimport sqlalchemy as saNEWLINENEWLINENEWLINE# revision identifiers, used by Alembic.NEWLINErevision = '42f99b73b077'NEWLINEdown_revision = 'e59c406395d2'NEWLINEbranch_labels = NoneNEWLINEdepends_on = NoneNEWLINENEWLINENEWLINEdef upgrade():NEWLINE # ### commands auto generated by Alembic - please adjust! ###NEWLINE op.create_table('tags',NEWLINE sa.Column('id', sa.Integer(), nullable=False),NEWLINE sa.Column('name', sa.Unicode(), nullable=False),NEWLINE sa.PrimaryKeyConstraint('id'),NEWLINE sa.UniqueConstraint('name')NEWLINE )NEWLINE op.create_table('tag_assignments',NEWLINE sa.Column('id', sa.Integer(), nullable=False),NEWLINE sa.Column('tag_id', sa.Integer(), nullable=False),NEWLINE sa.Column('collection_id', sa.Integer(), nullable=False),NEWLINE sa.ForeignKeyConstraint(['collection_id'], ['collections.id'], ondelete='CASCADE'),NEWLINE sa.ForeignKeyConstraint(['tag_id'], ['tags.id'], ondelete='CASCADE'),NEWLINE sa.PrimaryKeyConstraint('id'),NEWLINE sa.UniqueConstraint('tag_id', 'collection_id', name='uq_tag_assignments_name_collection_id')NEWLINE )NEWLINE # ### end Alembic commands ###NEWLINENEWLINENEWLINEdef downgrade():NEWLINE # ### commands auto generated by Alembic - please adjust! ###NEWLINE op.drop_table('tag_assignments')NEWLINE op.drop_table('tags')NEWLINE # ### end Alembic commands ###NEWLINE
from setuptools import setupNEWLINENEWLINEinstall_requires = [NEWLINE 'social-auth-app-django',NEWLINE]NEWLINENEWLINE# copy from `python-social-auth` social-core/setup.pyNEWLINEsocial_core_extras_require={NEWLINE 'openidconnect': ['python-jose>=3.0.0'],NEWLINE 'saml': ['python3-saml>=1.2.1'],NEWLINE 'azuread': ['cryptography>=2.1.1'],NEWLINE 'all': [NEWLINE 'python-jose>=3.0.0', NEWLINE 'python3-saml>=1.2.1', NEWLINE 'cryptography>=2.1.1',NEWLINE ]NEWLINE}NEWLINENEWLINEREADME = 'file README.md'NEWLINEwith open("README.md") as readme:NEWLINE README = readme.read()NEWLINENEWLINEsetup(NEWLINE name="saleor-social-auth",NEWLINE version="0.1.0",NEWLINE description="Social auth plugin (wx, alipay & etc.) for Saleor",NEWLINE long_description=README,NEWLINE long_description_content_type="text/markdown",NEWLINE url="https://github.com/ace-han/social_auth",NEWLINE author="Ace Han",NEWLINE author_email="ace.jl.han@gmail.com",NEWLINE license="MIT",NEWLINE classifiers=[NEWLINE "License :: OSI Approved :: MIT License",NEWLINE "Programming Language :: Python :: 3",NEWLINE "Programming Language :: Python :: 3.9",NEWLINE "Operating System :: OS Independent",NEWLINE ],NEWLINE packages=["social_auth"],NEWLINE package_dir={"social_auth": "social_auth"},NEWLINE install_requires=install_requires,NEWLINE extras_require=social_core_extras_require,NEWLINE zip_safe=True,NEWLINE entry_points={NEWLINE "saleor.plugins": ["social_auth = social_auth.plugin:SocialAuthPlugin"]NEWLINE },NEWLINE)NEWLINE
import osNEWLINEimport sysNEWLINEimport timeNEWLINEimport torchNEWLINEimport utilsNEWLINEimport loggingNEWLINEimport argparseNEWLINEimport torch.nn as nnNEWLINEimport torch.utilsNEWLINENEWLINEfrom adaptive_augmentor import AdaAugNEWLINEfrom networks import get_modelNEWLINEfrom networks.projection import ProjectionNEWLINEfrom dataset import get_num_class, get_dataloaders, get_label_name, get_dataset_dimensionNEWLINEfrom config import get_warmup_configNEWLINEfrom warmup_scheduler import GradualWarmupSchedulerNEWLINENEWLINEparser = argparse.ArgumentParser("ada_aug")NEWLINEparser.add_argument('--dataroot', type=str, default='./', help='location of the data corpus')NEWLINEparser.add_argument('--dataset', type=str, default='cifar10', help='name of dataset')NEWLINEparser.add_argument('--train_portion', type=float, default=0.5, help='portion of training data')NEWLINEparser.add_argument('--batch_size', type=int, default=96, help='batch size')NEWLINEparser.add_argument('--num_workers', type=int, default=0, help="num_workers")NEWLINEparser.add_argument('--learning_rate', type=float, default=0.025, help='init learning rate')NEWLINEparser.add_argument('--learning_rate_min', type=float, default=0.0001, help='min learning rate')NEWLINEparser.add_argument('--momentum', type=float, default=0.9, help='momentum')NEWLINEparser.add_argument('--weight_decay', type=float, default=3e-4, help='weight decay')NEWLINEparser.add_argument('--grad_clip', type=float, default=5, help='gradient clipping')NEWLINEparser.add_argument('--use_cuda', type=bool, default=True, help="use cuda default True")NEWLINEparser.add_argument('--gpu', type=int, default=0, help='gpu device id')NEWLINEparser.add_argument('--use_parallel', action='store_true', default=False, help="use data parallel default False")NEWLINEparser.add_argument('--model_name', type=str, default='wresnet40_2', help="model name")NEWLINEparser.add_argument('--model_path', type=str, default='saved_models', help='path to save the model')NEWLINEparser.add_argument('--cutout', action='store_true', default=False, help='use cutout')NEWLINEparser.add_argument('--cutout_length', type=int, default=16, help='cutout length')NEWLINEparser.add_argument('--drop_path_prob', type=float, default=0.2, help='drop path probability')NEWLINEparser.add_argument('--epochs', type=int, default=600, help='number of training epochs')NEWLINEparser.add_argument('--report_freq', type=float, default=50, help='report frequency')NEWLINEparser.add_argument('--save', type=str, default='EXP', help='experiment name')NEWLINEparser.add_argument('--seed', type=int, default=0, help='seed')NEWLINEparser.add_argument('--search_dataset', type=str, default='./', help='search dataset name')NEWLINEparser.add_argument('--gf_model_name', type=str, default='./', help='gf_model name')NEWLINEparser.add_argument('--gf_model_path', type=str, default='./', help='gf_model path')NEWLINEparser.add_argument('--h_model_path', type=str, default='./', help='h_model path')NEWLINEparser.add_argument('--k_ops', type=int, default=1, help="number of augmentation applied during training")NEWLINEparser.add_argument('--delta', type=float, default=0.3, help="degree of perturbation in magnitude")NEWLINEparser.add_argument('--temperature', type=float, default=1.0, help="temperature")NEWLINEparser.add_argument('--n_proj_layer', type=int, default=0, help="number of additional hidden layer in augmentation policy projection")NEWLINEparser.add_argument('--n_proj_hidden', type=int, default=128, help="number of hidden units in augmentation policy projection layers")NEWLINEparser.add_argument('--restore_path', type=str, default='./', help='restore model path')NEWLINEparser.add_argument('--restore', action='store_true', default=False, help='restore model default False')NEWLINENEWLINEargs = parser.parse_args()NEWLINEdebug = True if args.save == "debug" else FalseNEWLINEargs.save = '{}-{}'.format(time.strftime("%Y%m%d-%H%M%S"), args.save)NEWLINEif debug:NEWLINE args.save = os.path.join('debug', args.save)NEWLINEelse:NEWLINE args.save = os.path.join('eval', args.dataset, args.save)NEWLINEutils.create_exp_dir(args.save)NEWLINElog_format = '%(asctime)s %(message)s'NEWLINElogging.basicConfig(stream=sys.stdout, level=logging.INFO,NEWLINE format=log_format, datefmt='%m/%d %I:%M:%S %p')NEWLINEfh = logging.FileHandler(os.path.join(args.save, 'log.txt'))NEWLINEfh.setFormatter(logging.Formatter(log_format))NEWLINElogging.getLogger().addHandler(fh)NEWLINENEWLINENEWLINEdef main():NEWLINE if not torch.cuda.is_available():NEWLINE logging.info('no gpu device available')NEWLINE sys.exit(1)NEWLINENEWLINE torch.cuda.set_device(args.gpu)NEWLINE utils.reproducibility(args.seed)NEWLINE logging.info('gpu device = %d' % args.gpu)NEWLINE logging.info("args = %s", args)NEWLINENEWLINE # dataset settingsNEWLINE n_class = get_num_class(args.dataset)NEWLINE class2label = get_label_name(args.dataset, args.dataroot)NEWLINE train_queue, valid_queue, _, test_queue = get_dataloaders(NEWLINE args.dataset, args.batch_size, args.num_workers,NEWLINE args.dataroot, args.cutout, args.cutout_length,NEWLINE split=args.train_portion, split_idx=0, target_lb=-1,NEWLINE search=True)NEWLINENEWLINE logging.info(f'Dataset: {args.dataset}')NEWLINE logging.info(f' |total: {len(train_queue.dataset)}')NEWLINE logging.info(f' |train: {len(train_queue)*args.batch_size}')NEWLINE logging.info(f' |valid: {len(valid_queue)*args.batch_size}')NEWLINENEWLINE # task model settingsNEWLINE task_model = get_model(model_name=args.model_name,NEWLINE num_class=n_class,NEWLINE use_cuda=True, data_parallel=False)NEWLINE logging.info("param size = %fMB", utils.count_parameters_in_MB(task_model))NEWLINENEWLINE # task optimization settingsNEWLINE optimizer = torch.optim.SGD(NEWLINE task_model.parameters(),NEWLINE args.learning_rate,NEWLINE momentum=args.momentum,NEWLINE weight_decay=args.weight_decay,NEWLINE nesterov=TrueNEWLINE )NEWLINENEWLINE scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(NEWLINE optimizer, float(args.epochs), eta_min=args.learning_rate_min)NEWLINENEWLINE m, e = get_warmup_config(args.dataset)NEWLINE scheduler = GradualWarmupScheduler(NEWLINE optimizer,NEWLINE multiplier=m,NEWLINE total_epoch=e,NEWLINE after_scheduler=scheduler)NEWLINE logging.info(f'Optimizer: SGD, scheduler: CosineAnnealing, warmup: {m}/{e}')NEWLINE criterion = nn.CrossEntropyLoss()NEWLINE criterion = criterion.cuda()NEWLINENEWLINE # restore settingNEWLINE if args.restore:NEWLINE trained_epoch = utils.restore_ckpt(task_model, optimizer, scheduler, args.restore_path, location=args.gpu) + 1NEWLINE n_epoch = args.epochs - trained_epochNEWLINE logging.info(f'Restoring model from {args.restore_path}, starting from epoch {trained_epoch}')NEWLINE else:NEWLINE trained_epoch = 0NEWLINE n_epoch = args.epochsNEWLINENEWLINE # load trained adaaug sub modelsNEWLINE search_n_class = get_num_class(args.search_dataset)NEWLINE gf_model = get_model(model_name=args.gf_model_name,NEWLINE num_class=search_n_class,NEWLINE use_cuda=True, data_parallel=False)NEWLINENEWLINE h_model = Projection(in_features=gf_model.fc.in_features,NEWLINE n_layers=args.n_proj_layer,NEWLINE n_hidden=args.n_proj_hidden).cuda()NEWLINENEWLINE utils.load_model(gf_model, f'{args.gf_model_path}/gf_weights.pt', location=args.gpu)NEWLINE utils.load_model(h_model, f'{args.h_model_path}/h_weights.pt', location=args.gpu)NEWLINENEWLINE for param in gf_model.parameters():NEWLINE param.requires_grad = FalseNEWLINENEWLINE for param in h_model.parameters():NEWLINE param.requires_grad = FalseNEWLINENEWLINE after_transforms = train_queue.dataset.after_transformsNEWLINE adaaug_config = {'sampling': 'prob',NEWLINE 'k_ops': args.k_ops,NEWLINE 'delta': args.delta,NEWLINE 'temp': args.temperature,NEWLINE 'search_d': get_dataset_dimension(args.search_dataset),NEWLINE 'target_d': get_dataset_dimension(args.dataset)}NEWLINENEWLINE adaaug = AdaAug(after_transforms=after_transforms,NEWLINE n_class=search_n_class,NEWLINE gf_model=gf_model,NEWLINE h_model=h_model,NEWLINE save_dir=args.save,NEWLINE config=adaaug_config)NEWLINENEWLINE # start trainingNEWLINE for i_epoch in range(n_epoch):NEWLINE epoch = trained_epoch + i_epochNEWLINE lr = scheduler.get_last_lr()[0]NEWLINE logging.info('epoch %d lr %e', epoch, lr)NEWLINENEWLINE train_acc, train_obj = train(NEWLINE train_queue, task_model, criterion, optimizer, epoch, args.grad_clip, adaaug)NEWLINE logging.info('train_acc %f', train_acc)NEWLINENEWLINE valid_acc, valid_obj, _, _ = infer(valid_queue, task_model, criterion)NEWLINE logging.info('valid_acc %f', valid_acc)NEWLINENEWLINE scheduler.step()NEWLINENEWLINE if epoch % args.report_freq == 0:NEWLINE test_acc, test_obj, test_acc5, _ = infer(test_queue, task_model, criterion)NEWLINE logging.info('test_acc %f %f', test_acc, test_acc5)NEWLINENEWLINE utils.save_ckpt(task_model, optimizer, scheduler, epoch,NEWLINE os.path.join(args.save, 'weights.pt'))NEWLINENEWLINE adaaug.save_history(class2label)NEWLINE figure = adaaug.plot_history()NEWLINE test_acc, test_obj, test_acc5, _ = infer(test_queue, task_model, criterion)NEWLINENEWLINE logging.info('test_acc %f %f', test_acc, test_acc5)NEWLINE logging.info(f'save to {args.save}')NEWLINENEWLINENEWLINEdef train(train_queue, model, criterion, optimizer, epoch, grad_clip, adaaug):NEWLINE objs = utils.AvgrageMeter()NEWLINE top1 = utils.AvgrageMeter()NEWLINE top5 = utils.AvgrageMeter()NEWLINENEWLINE for step, (input, target) in enumerate(train_queue):NEWLINE target = target.cuda(non_blocking=True)NEWLINENEWLINE # get augmented training data from adaaugNEWLINE aug_images = adaaug(input, mode='exploit')NEWLINE model.train()NEWLINE optimizer.zero_grad()NEWLINE logits = model(aug_images)NEWLINE loss = criterion(logits, target)NEWLINE loss.backward()NEWLINE nn.utils.clip_grad_norm_(model.parameters(), grad_clip)NEWLINE optimizer.step()NEWLINENEWLINE prec1, prec5 = utils.accuracy(logits, target, topk=(1, 5))NEWLINE n = input.size(0)NEWLINE objs.update(loss.detach().item(), n)NEWLINE top1.update(prec1.detach().item(), n)NEWLINE top5.update(prec5.detach().item(), n)NEWLINENEWLINE global_step = step + epoch * len(train_queue)NEWLINE if global_step % args.report_freq == 0:NEWLINE logging.info('train %03d %e %f %f', global_step, objs.avg, top1.avg, top5.avg)NEWLINENEWLINE # log the policyNEWLINE if step == 0:NEWLINE adaaug.add_history(input, target)NEWLINENEWLINE return top1.avg, objs.avgNEWLINENEWLINENEWLINEdef infer(valid_queue, model, criterion):NEWLINE objs = utils.AvgrageMeter()NEWLINE top1 = utils.AvgrageMeter()NEWLINE top5 = utils.AvgrageMeter()NEWLINE model.eval()NEWLINE with torch.no_grad():NEWLINE for input, target in valid_queue:NEWLINE input = input.cuda()NEWLINE target = target.cuda(non_blocking=True)NEWLINENEWLINE logits = model(input)NEWLINE loss = criterion(logits, target)NEWLINENEWLINE prec1, prec5 = utils.accuracy(logits, target, topk=(1, 5))NEWLINE n = input.size(0)NEWLINE objs.update(loss.detach().item(), n)NEWLINE top1.update(prec1.detach().item(), n)NEWLINE top5.update(prec5.detach().item(), n)NEWLINENEWLINE return top1.avg, objs.avg, top5.avg, objs.avgNEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE main()NEWLINE
import osNEWLINEfrom PyQt5 import QtCore, QtWidgetsNEWLINEfrom .ui.MainWindow import Ui_MainWindowNEWLINEfrom .ui.about import Ui_Form as Ui_aboutWindowNEWLINEfrom .ui.input import Ui_Form as Ui_inputWindowNEWLINEfrom .ui.help import Ui_Form as Ui_helpWindowNEWLINEimport pyqtgraph as pgNEWLINEimport pyqtgraph.exportersNEWLINEimport matplotlib.pyplot as pltNEWLINEfrom .fit import *NEWLINEimport configparserNEWLINENEWLINElanguage_path = os.path.realpath(__file__)[:-6] + "language\\"NEWLINENEWLINENEWLINEclass Mainwindow(QtWidgets.QMainWindow, Ui_MainWindow):NEWLINE def __init__(self, parent=None, rawVariables=None):NEWLINE super(Mainwindow, self).__init__(parent)NEWLINE self.setupUi(self)NEWLINE self.show()NEWLINENEWLINE # 设置图像框NEWLINE self.graphWidget = pg.PlotWidget()NEWLINE self.gridLayout_3.addWidget(self.graphWidget)NEWLINE self.graphWidget.setBackground('w')NEWLINE self.graphWidget.showGrid(x=True, y=True)NEWLINE self.Xlabel = NoneNEWLINE self.Ylabel = NoneNEWLINENEWLINE # 设置帮助、关于以及输入窗口,以及设置各种信号的连接NEWLINE self.rawVariables = rawVariablesNEWLINE self.showvars()NEWLINE self.aboutwindow = Aboutwindow()NEWLINE self.helpwindow = Helpwindow()NEWLINE self.inputwindow_title = Inputwindow()NEWLINE self.inputwindow_title.pushButton.clicked.connect(self.inputtitleback)NEWLINE self.inputwindow_xlabel = Inputwindow()NEWLINE self.inputwindow_xlabel.pushButton.clicked.connect(self.inputXlabelback)NEWLINE self.inputwindow_ylabel = Inputwindow()NEWLINE self.inputwindow_ylabel.pushButton.clicked.connect(self.inputYlabelback)NEWLINE self.signalchannels()NEWLINENEWLINE # 设置拟合选项comboBoxNEWLINE self.comboBox_3.setCurrentIndex(4)NEWLINE self.stackedWidget.setCurrentIndex(4)NEWLINE self.findcombo = {'0': [self.lineEdit_2, self.lineEdit_3, self.textEdit_2], '1': self.comboBox_5,NEWLINE '2': self.comboBox_6, '3': self.comboBox_7, '4': self.comboBox_4, '5': self.comboBox_8,NEWLINE '6': [self.comboBox_9, self.comboBox_10], '7': self.comboBox_11}NEWLINE self.findlabel = {'1': self.label_11, '2': self.label_13, '3': self.label_15, '5': self.label_19,NEWLINE '6': self.label_22, '7': self.label_26}NEWLINENEWLINE # 设置翻译NEWLINE self.translator = QtCore.QTranslator()NEWLINE config = configparser.ConfigParser()NEWLINE config.read(os.path.expanduser('~') + '\curvefitting.ini')NEWLINE self.language = config['DEFAULT'].get('language', "en")NEWLINE if self.language == 'en':NEWLINE self.translate("en", nomatter=True)NEWLINE else:NEWLINE self.action_English.setIconVisibleInMenu(False)NEWLINENEWLINE # 自动拟合的设置NEWLINE if config['DEFAULT'].get('autofit', "False") == "False":NEWLINE self.autofit = FalseNEWLINE self.action_12.setIconVisibleInMenu(False)NEWLINE else:NEWLINE self.autofit = TrueNEWLINE self.checkBox.setChecked(True)NEWLINENEWLINE def signalchannels(self):NEWLINE # 各种信号槽的搭建NEWLINE self.comboBox.currentIndexChanged.connect(self.plot)NEWLINE self.comboBox.currentIndexChanged.connect(self.renew_xylabel)NEWLINE self.comboBox_2.currentIndexChanged.connect(self.plot)NEWLINE self.comboBox_2.currentIndexChanged.connect(self.renew_xylabel)NEWLINE self.pushButton.clicked.connect(self.goodfit)NEWLINE self.checkBox.stateChanged.connect(self.setCheckBox)NEWLINE self.pushButton_2.setDisabled(True)NEWLINE self.pushButton_4.clicked.connect(self.printfigure)NEWLINE self.action_3.triggered.connect(self.printfigure)NEWLINE self.pushButton_5.clicked.connect(self.savefigure)NEWLINE self.action_7.triggered.connect(self.savefigure)NEWLINE self.action_5.triggered.connect(self.close)NEWLINE self.action_Chinese.triggered.connect(lambda: self.translate("zh_CN"))NEWLINE self.action_English.triggered.connect(lambda: self.translate("en"))NEWLINE self.action_11.triggered.connect(self.aboutwindow.show)NEWLINE self.action_10.triggered.connect(self.helpwindow.show)NEWLINE self.action_12.triggered.connect(self.action_autofit)NEWLINE self.action_8.triggered.connect(self.inputtitle)NEWLINE self.actionX.triggered.connect(self.inputXlabel)NEWLINE self.actionY.triggered.connect(self.inputYlabel)NEWLINE self.action.triggered.connect(self.clear)NEWLINE self.pushButton_2.clicked.connect(self.stopfitting)NEWLINE self.comboBox_3.currentIndexChanged.connect(self.showfitoption)NEWLINE self.comboBox_5.currentIndexChanged.connect(self.showfunction)NEWLINE self.comboBox_6.currentIndexChanged.connect(self.showfunction)NEWLINE self.comboBox_7.currentIndexChanged.connect(self.showfunction)NEWLINE self.comboBox_8.currentIndexChanged.connect(self.showfunction)NEWLINE self.comboBox_9.currentIndexChanged.connect(self.showfunction)NEWLINE self.comboBox_10.currentIndexChanged.connect(self.showfunction)NEWLINE self.comboBox_11.currentIndexChanged.connect(self.showfunction)NEWLINE self.pushButton_3.clicked.connect(self.printresult)NEWLINE self.action_2.triggered.connect(self.printresult)NEWLINENEWLINE def translate(self, language, nomatter=False):NEWLINE if (self.language != language) or nomatter:NEWLINE self.translator.load(language_path + "MainWindow_{}.qm".format(language))NEWLINE _app = QtWidgets.QApplication.instance()NEWLINE _app.installTranslator(self.translator)NEWLINE self.retranslateUi(self)NEWLINE self.aboutwindow.translate(language)NEWLINE self.helpwindow.translate(language)NEWLINE self.inputwindow_title.translate(language)NEWLINE self.inputwindow_xlabel.translate(language)NEWLINE self.inputwindow_ylabel.translate(language)NEWLINE self.language = languageNEWLINE if language == "en":NEWLINE self.action_English.setIconVisibleInMenu(True)NEWLINE self.action_Chinese.setIconVisibleInMenu(False)NEWLINE elif language == "zh_CN":NEWLINE self.action_English.setIconVisibleInMenu(False)NEWLINE self.action_Chinese.setIconVisibleInMenu(True)NEWLINENEWLINE def showvars(self):NEWLINE # 负责筛选合适的变量,并显示在comboBox中NEWLINE keys_ = list(self.rawVariables.keys())NEWLINE variables = []NEWLINE for i_ in keys_:NEWLINE if not i_.startswith('_') and str(type(self.rawVariables[i_]))[8:-2] in ['int', 'float', 'list', 'tuple',NEWLINE 'numpy.ndarray'] \NEWLINE and not i_ in ['In', 'variables']:NEWLINE variables.append(i_)NEWLINE del i_, keys_NEWLINE text1 = self.comboBox.currentText()NEWLINE text2 = self.comboBox_2.currentText()NEWLINE self.comboBox.clear()NEWLINE self.comboBox_2.clear()NEWLINE self.comboBox.addItems(variables)NEWLINE self.comboBox_2.addItems(variables)NEWLINE self.comboBox.setCurrentText(text1)NEWLINE self.comboBox_2.setCurrentText(text2)NEWLINENEWLINE def plot(self):NEWLINE # 绘制散点图NEWLINE text1 = self.comboBox.currentText()NEWLINE text2 = self.comboBox_2.currentText()NEWLINE try:NEWLINE x, y = eval(text1, self.rawVariables), eval(text2, self.rawVariables)NEWLINE if type(x) != type(y):NEWLINE self.messege(NEWLINE "无法绘制!\nX与Y的数据类型不同" if self.language == "zh_CN" else "Cannot plot!\nX and Y have different data types")NEWLINE elif len(x) != len(y):NEWLINE self.messege(NEWLINE "无法绘制!\nX与Y的维度不同" if self.language == "zh_CN" else "Cannot plot!\nX and Y have different dimensions")NEWLINE else:NEWLINE self.graphWidget.clear()NEWLINE scatter = pg.ScatterPlotItem(pen=pg.mkPen(width=1, color='k'), symbol='o', size=4)NEWLINE self.graphWidget.addItem(scatter)NEWLINE pos = [{'pos': [x[i], y[i]]} for i in range(len(x))]NEWLINE scatter.setData(pos)NEWLINENEWLINE if self.autofit:NEWLINE self.goodfit()NEWLINE except Exception as e:NEWLINE self.messege(repr(e))NEWLINENEWLINE def messege(self, e):NEWLINE msg_box = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, 'Warning', e)NEWLINE msg_box.exec_()NEWLINENEWLINE def setCheckBox(self):NEWLINE # checkBox状态发生变化时进行的设置NEWLINE combos = (self.comboBox_3, self.comboBox_4, self.comboBox_5, self.comboBox_6, self.comboBox_7,NEWLINE self.comboBox_8, self.comboBox_9, self.comboBox_10, self.comboBox_11)NEWLINE if self.checkBox.isChecked():NEWLINE self.autofit = TrueNEWLINE self.plot()NEWLINE self.pushButton.setDisabled(True)NEWLINE self.pushButton_2.setDisabled(True)NEWLINE for combo in combos:NEWLINE combo.currentIndexChanged.connect(self.plot)NEWLINE self.action_12.setIconVisibleInMenu(True)NEWLINE else:NEWLINE self.autofit = FalseNEWLINE self.pushButton.setDisabled(False)NEWLINE for combo in combos:NEWLINE combo.currentIndexChanged.disconnect(self.plot)NEWLINE self.action_12.setIconVisibleInMenu(False)NEWLINENEWLINE def findfitmod(self):NEWLINE # 生成fit输入参数NEWLINE index = self.comboBox_3.currentIndex()NEWLINE if index == 0:NEWLINE edits = self.findcombo['0']NEWLINE value = [edits[0].text(), edits[1].text(), edits[2].toPlainText()]NEWLINE elif index == 6:NEWLINE value = [i.currentIndex() for i in self.findcombo['6']]NEWLINE elif index == 8:NEWLINE value = 0NEWLINE else:NEWLINE value = self.findcombo[str(index)].currentIndex()NEWLINE self.fitmod = (index, value)NEWLINENEWLINE def goodfit(self):NEWLINE # 拟合接口函数NEWLINE if not self.autofit:NEWLINE self.pushButton.setDisabled(True)NEWLINE self.plot()NEWLINE self.pushButton_2.setDisabled(False)NEWLINE self.text1 = self.comboBox.currentText()NEWLINE self.text2 = self.comboBox_2.currentText()NEWLINENEWLINE try:NEWLINE self.findfitmod()NEWLINE self.x, self.y = eval(self.text1, self.rawVariables), eval(self.text2, self.rawVariables)NEWLINENEWLINE # 激发线程NEWLINE self.workthread = WorkThread([self])NEWLINE self.workthread.trigger.connect(self.goodfitback)NEWLINE self.workthread.start()NEWLINE except Exception as e:NEWLINE self.messege(repr(e))NEWLINENEWLINE def goodfitback(self):NEWLINE # 把fit操作放在一个线程里,结束后触发的恢复按钮状态的操作NEWLINE if self.successfit:NEWLINE try:NEWLINE pen = pg.mkPen(color='b', width=4)NEWLINE xx = (self.x.min(), self.x.max())NEWLINE self.graphWidget.plot(np.linspace(xx[0], xx[1], 200),NEWLINE self.p(np.linspace(xx[0], xx[1], 200), *self.para),NEWLINE name=self.lineEdit.text(), pen=pen)NEWLINENEWLINE self.textEdit.setText("")NEWLINE text = give_reflect(self.x, self.y, self.p, self.para, self.para_names, self.fitmod, self.language)NEWLINE for i in text:NEWLINE self.textEdit.append(i)NEWLINE except Exception as e:NEWLINE self.messege(repr(e))NEWLINE else:NEWLINE self.messege(self.e)NEWLINE if not self.autofit:NEWLINE self.pushButton.setDisabled(False)NEWLINE self.pushButton_2.setDisabled(True)NEWLINENEWLINE def stopfitting(self):NEWLINE # 停止拟合NEWLINE self.workthread.terminate()NEWLINE self.workthread.wait()NEWLINE if not self.autofit:NEWLINE self.pushButton.setDisabled(False)NEWLINE self.pushButton_2.setDisabled(True)NEWLINENEWLINE def showfitoption(self):NEWLINE # 将stackedWidget与相应拟合模式相绑定NEWLINE self.stackedWidget.setCurrentIndex(self.comboBox_3.currentIndex())NEWLINENEWLINE def showfunction(self):NEWLINE # 设置label为表示当前方程的字符串NEWLINE self.findfitmod()NEWLINE text = show_function(self.fitmod)[7:]NEWLINE label = self.findlabel[str(self.fitmod[0])]NEWLINE label.setToolTip(text)NEWLINE room = int(label.width() / 5.5)NEWLINE if len(text) > room:NEWLINE text = text[:room - 4] + '...'NEWLINE label.setText(text)NEWLINENEWLINE def printresult(self):NEWLINE # 输出拟合结果NEWLINE if self.fitmod[0] == 0:NEWLINE text_func = "f({}) = ".format(self.fitmod[1][1]) + self.fitmod[1][2]NEWLINE else:NEWLINE text_func = show_function(self.fitmod)NEWLINE if self.fitmod[0] == 4:NEWLINE for i in range(self.fitmod[1] + 2):NEWLINE text_func = text_func.replace("p{}".format(i + 1), str(round(self.p[self.fitmod[1] + 1 - i], 2)))NEWLINE else:NEWLINE for i in range(len(self.para)):NEWLINE text_func = text_func.replace(self.para_names[i], str(round(self.para[i], 2)))NEWLINE print(text_func)NEWLINENEWLINE def printfigure(self):NEWLINE try:NEWLINE if self.language == "zh_CN":NEWLINE plt.rcParams['font.sans-serif'] = 'SimHei'NEWLINE plt.rcParams['axes.unicode_minus'] = FalseNEWLINE xx = (self.x.min(), self.x.max())NEWLINE plt.plot(np.linspace(xx[0], xx[1], 200), self.p(np.linspace(xx[0], xx[1], 200), *self.para))NEWLINE plt.scatter(self.x, self.y, c='k')NEWLINE plt.gcf().set_facecolor(np.ones(3) * 240 / 255)NEWLINE plt.grid()NEWLINE if self.Xlabel:NEWLINE self.text1 = self.XlabelNEWLINE if self.Ylabel:NEWLINE self.text2 = self.YlabelNEWLINE plt.legend([self.lineEdit.text(), "{} vs. {}".format(self.text2, self.text1)])NEWLINE plt.title(self.lineEdit.text())NEWLINE plt.xlabel(self.text1)NEWLINE plt.ylabel(self.text2)NEWLINE plt.show()NEWLINE except Exception as e:NEWLINE self.messege(repr(e))NEWLINENEWLINE def savefigure(self):NEWLINE fileName, fileType = QtWidgets.QFileDialog.getSaveFileName(self,NEWLINE "保存文件" if self.language == "zh_CN" else "Save file",NEWLINE os.getcwd(),NEWLINE "Portable Network Graphics(*.png);;Joint Photographic Group(*.jpg);;All Files(*)")NEWLINE if fileName:NEWLINE ex = pyqtgraph.exporters.ImageExporter(self.graphWidget.plotItem)NEWLINE ex.parameters()['width'] = 2000NEWLINE ex.export(fileName)NEWLINENEWLINE def action_autofit(self):NEWLINE if self.checkBox.isChecked():NEWLINE self.checkBox.setChecked(False)NEWLINE self.action_12.setIconVisibleInMenu(False)NEWLINE else:NEWLINE self.checkBox.setChecked(True)NEWLINE self.action_12.setIconVisibleInMenu(True)NEWLINENEWLINE def closeEvent(self, event):NEWLINE config = configparser.ConfigParser()NEWLINE config['DEFAULT'] = {"language": self.language, "autofit": str(self.checkBox.isChecked())}NEWLINE with open(os.path.expanduser('~') + '\curvefitting.ini', 'w') as configfile:NEWLINE config.write(configfile)NEWLINE event.accept()NEWLINENEWLINE def inputtitle(self):NEWLINE self.inputwindow_title.lineEdit.setText(self.lineEdit.text())NEWLINE self.inputwindow_title.show()NEWLINENEWLINE def inputtitleback(self):NEWLINE title = self.inputwindow_title.inputvalueNEWLINE if title:NEWLINE self.lineEdit.setText(title)NEWLINENEWLINE def inputXlabel(self):NEWLINE if self.Xlabel:NEWLINE self.inputwindow_xlabel.lineEdit.setText(self.Xlabel)NEWLINE else:NEWLINE self.inputwindow_xlabel.lineEdit.setText(self.comboBox.currentText())NEWLINE self.inputwindow_xlabel.show()NEWLINENEWLINE def inputXlabelback(self):NEWLINE xlabel = self.inputwindow_xlabel.inputvalueNEWLINE if xlabel:NEWLINE self.Xlabel = xlabelNEWLINENEWLINE def inputYlabel(self):NEWLINE if self.Ylabel:NEWLINE self.inputwindow_ylabel.lineEdit.setText(self.Ylabel)NEWLINE else:NEWLINE self.inputwindow_ylabel.lineEdit.setText(self.comboBox_2.currentText())NEWLINE self.inputwindow_ylabel.show()NEWLINENEWLINE def inputYlabelback(self):NEWLINE ylabel = self.inputwindow_ylabel.inputvalueNEWLINE if ylabel:NEWLINE self.Ylabel = ylabelNEWLINENEWLINE def renew_xylabel(self):NEWLINE self.Xlabel = NoneNEWLINE self.Ylabel = NoneNEWLINENEWLINE def clear(self):NEWLINE self.comboBox.setCurrentIndex(0)NEWLINE self.comboBox_2.setCurrentIndex(0)NEWLINE self.comboBox_3.setCurrentIndex(0)NEWLINE self.comboBox_4.setCurrentIndex(0)NEWLINE self.graphWidget.clear()NEWLINE self.renew_xylabel()NEWLINE self.translate(self.language, nomatter=True)NEWLINE del self.x, self.y, self.p, self.text1, self.text2NEWLINENEWLINENEWLINEclass WorkThread(QtCore.QThread):NEWLINE # 专为拟合而生的线程NEWLINE trigger = QtCore.pyqtSignal()NEWLINENEWLINE def __init__(self, myui):NEWLINE super(WorkThread, self).__init__()NEWLINE [self.ui] = myuiNEWLINENEWLINE def run(self):NEWLINE self.ui.successfit = FalseNEWLINE try:NEWLINE self.ui.p, self.ui.para, self.ui.para_names = fit(self.ui.x, self.ui.y, mod=self.ui.fitmod)NEWLINE except Exception as e:NEWLINE self.ui.e = repr(e)NEWLINE else:NEWLINE self.ui.successfit = TrueNEWLINE self.trigger.emit()NEWLINENEWLINENEWLINEclass Aboutwindow(QtWidgets.QWidget, Ui_aboutWindow):NEWLINE def __init__(self, parent=None):NEWLINE super(Aboutwindow, self).__init__(parent)NEWLINE self.setupUi(self)NEWLINE self.translator = QtCore.QTranslator()NEWLINENEWLINE def translate(self, language):NEWLINE self.translator.load(language_path + "about_{}.qm".format(language))NEWLINE _app = QtWidgets.QApplication.instance()NEWLINE _app.installTranslator(self.translator)NEWLINE self.retranslateUi(self)NEWLINENEWLINENEWLINEclass Helpwindow(QtWidgets.QWidget, Ui_helpWindow):NEWLINE def __init__(self, parent=None):NEWLINE super(Helpwindow, self).__init__(parent)NEWLINE self.setupUi(self)NEWLINE self.translator = QtCore.QTranslator()NEWLINENEWLINE def translate(self, language):NEWLINE self.translator.load(language_path + "help_{}.qm".format(language))NEWLINE _app = QtWidgets.QApplication.instance()NEWLINE _app.installTranslator(self.translator)NEWLINE self.retranslateUi(self)NEWLINENEWLINENEWLINEclass Inputwindow(QtWidgets.QWidget, Ui_inputWindow):NEWLINE def __init__(self, parent=None):NEWLINE super(Inputwindow, self).__init__(parent)NEWLINE self.setupUi(self)NEWLINE self.translator = QtCore.QTranslator()NEWLINE self.inputvalue = NoneNEWLINE self.pushButton.clicked.connect(self.OK)NEWLINE self.pushButton_2.clicked.connect(self.close)NEWLINENEWLINE def OK(self):NEWLINE self.inputvalue = self.lineEdit.text()NEWLINE self.close()NEWLINENEWLINE def translate(self, language):NEWLINE self.translator.load(language_path + "input_{}.qm".format(language))NEWLINE _app = QtWidgets.QApplication.instance()NEWLINE _app.installTranslator(self.translator)NEWLINE self.retranslateUi(self)NEWLINE
from os import pathNEWLINEfrom typing import Optional, TupleNEWLINEimport tarfileNEWLINEimport torchNEWLINEfrom pytorch_lightning import LightningDataModuleNEWLINEfrom torch.utils.data import ConcatDataset, DataLoader, Dataset, random_splitNEWLINEfrom torchvision.datasets import MNISTNEWLINEfrom torchvision.transforms import transformsNEWLINEimport numpy as npNEWLINEimport pandas as pdNEWLINEfrom pathlib import PathNEWLINEfrom survae.datasets.tabular.utils import get_data_pathNEWLINEimport osNEWLINENEWLINENEWLINEclass UCIDataModule(LightningDataModule):NEWLINE """NEWLINE Example of LightningDataModule for MNIST dataset.NEWLINENEWLINE A DataModule implements 5 key methods:NEWLINE - prepare_data (things to do on 1 GPU/TPU, not on every GPU/TPU in distributed mode)NEWLINE - setup (things to do on every accelerator in distributed mode)NEWLINE - train_dataloader (the training dataloader)NEWLINE - val_dataloader (the validation dataloader(s))NEWLINE - test_dataloader (the test dataloader(s))NEWLINENEWLINE This allows you to share a full dataset without explaining how to download,NEWLINE split, transform and process the data.NEWLINENEWLINE Read the docs:NEWLINE https://pytorch-lightning.readthedocs.io/en/latest/extensions/datamodules.htmlNEWLINE """NEWLINENEWLINE url = "https://zenodo.org/record/1161203/files/data.tar.gz?download=1"NEWLINE uci_folder = "uci_maf"NEWLINE uci_file = "data.tar.gz"NEWLINE raw_folder = NoneNEWLINE raw_file = NoneNEWLINENEWLINE def __init__(NEWLINE self,NEWLINE data_dir: str = get_data_path(),NEWLINE download_data: bool = True,NEWLINE ):NEWLINE super().__init__()NEWLINENEWLINE self.data_dir = data_dirNEWLINE self.download_data = download_dataNEWLINENEWLINE def prepare_data(self):NEWLINE """Download data if needed. This method is called only from a single GPU.NEWLINE Do not use it to assign state (self.x = y)."""NEWLINE if not self._check_download():NEWLINE if self.download_data:NEWLINE self.download()NEWLINE else:NEWLINE raise RuntimeError(NEWLINE "Dataset not found." + " You can use download=True to download it"NEWLINE )NEWLINENEWLINE if not self._check_raw():NEWLINE self.extract()NEWLINENEWLINE @propertyNEWLINE def raw_uci_data_path(self):NEWLINE return os.path.join(self.data_dir, self.uci_folder, self.uci_file)NEWLINENEWLINE @propertyNEWLINE def raw_data_path(self):NEWLINE return os.path.join(self.data_dir, self.raw_folder, self.raw_file)NEWLINENEWLINE def _check_download(self):NEWLINE return os.path.exists(self.raw_uci_data_path)NEWLINENEWLINE def download(self):NEWLINE """Download the data if it doesn't exist in parent_folder already."""NEWLINE from six.moves import urllibNEWLINENEWLINE if not os.path.exists(os.path.join(self.data_dir, self.uci_folder)):NEWLINE os.makedirs(os.path.join(self.data_dir, self.uci_folder))NEWLINENEWLINE print("Downloading", self.uci_file)NEWLINE urllib.request.urlretrieve(self.url, self.raw_uci_data_path)NEWLINE print("Completed")NEWLINENEWLINE def _check_raw(self):NEWLINE return os.path.exists(self.raw_data_path)NEWLINENEWLINE def extract(self):NEWLINENEWLINE print("Extracting data...")NEWLINE tar = tarfile.open(self.raw_uci_data_path)NEWLINE tar.extractall(os.path.join(self.data_dir, self.uci_folder))NEWLINE tar.close()NEWLINE print("Completed!")NEWLINE
from ingest.api.ingestapi import IngestApiNEWLINEfrom ingest.exporter.bundle import BundleService, BundleNEWLINEfrom ingest.exporter.metadata import MetadataServiceNEWLINEfrom ingest.exporter.staging import StagingServiceNEWLINENEWLINENEWLINEclass SubmissionEnvelopeParseException(Exception):NEWLINE passNEWLINENEWLINENEWLINEclass SubmissionEnvelope:NEWLINENEWLINE def __init__(self, uuid, staging_area_uuid):NEWLINE self.uuid = uuidNEWLINE self.staging_area_uuid = staging_area_uuidNEWLINENEWLINE @staticmethodNEWLINE def from_dict(source: dict):NEWLINE try:NEWLINE uuid = source['uuid']['uuid']NEWLINE staging_area_uuid = source['stagingDetails']['stagingAreaUuid']['uuid']NEWLINE return SubmissionEnvelope(uuid, staging_area_uuid)NEWLINE except (KeyError, TypeError) as e:NEWLINE raise SubmissionEnvelopeParseException(e)NEWLINENEWLINENEWLINEclass Exporter:NEWLINENEWLINE def __init__(self, ingest_api: IngestApi, metadata_service: MetadataService,NEWLINE staging_service: StagingService, bundle_service: BundleService):NEWLINE self.ingest_api = ingest_apiNEWLINE self.metadata_service = metadata_serviceNEWLINE self.staging_service = staging_serviceNEWLINE self.bundle_service = bundle_serviceNEWLINENEWLINE def export_update(self, submission_source: dict, bundle_uuid: str, metadata_urls: list,NEWLINE update_version: str):NEWLINE bundle = self.bundle_service.fetch(bundle_uuid)NEWLINE submission = SubmissionEnvelope.from_dict(submission_source)NEWLINE staging_details = self._apply_metadata_updates(bundle, metadata_urls,NEWLINE submission.staging_area_uuid)NEWLINE bundle.update_version(update_version)NEWLINE self.bundle_service.update(bundle, staging_details)NEWLINE manifest = bundle.generate_manifest(submission.uuid)NEWLINE self.ingest_api.create_bundle_manifest(manifest)NEWLINENEWLINE def _apply_metadata_updates(self, bundle: Bundle, metadata_urls, staging_area_uuid):NEWLINE staging_details = []NEWLINE for url in metadata_urls:NEWLINE metadata_resource = self.metadata_service.fetch_resource(url)NEWLINE staging_info = self.staging_service.stage_metadata(staging_area_uuid, metadata_resource)NEWLINE staging_details.append(staging_info)NEWLINE bundle.update_file(metadata_resource)NEWLINE return staging_detailsNEWLINE
import osNEWLINEimport timeNEWLINEimport pprintNEWLINEimport argparseNEWLINEimport torchNEWLINEimport numpy as npNEWLINEimport pickleNEWLINEimport utilsNEWLINEimport csvNEWLINENEWLINEfrom model.hidden import HiddenNEWLINEfrom noise_layers.noiser import NoiserNEWLINEfrom average_meter import AverageMeterNEWLINENEWLINENEWLINEdef write_validation_loss(file_name, losses_accu, experiment_name, epoch, write_header=False):NEWLINE with open(file_name, 'a', newline='') as csvfile:NEWLINE writer = csv.writer(csvfile)NEWLINE if write_header:NEWLINE row_to_write = ['experiment_name', 'epoch'] + [loss_name.strip() for loss_name in losses_accu.keys()]NEWLINE writer.writerow(row_to_write)NEWLINE row_to_write = [experiment_name, epoch] + ['{:.4f}'.format(loss_avg.avg) for loss_avg in losses_accu.values()]NEWLINE writer.writerow(row_to_write)NEWLINENEWLINENEWLINEdef main():NEWLINE # device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')NEWLINE device = torch.device('cpu')NEWLINENEWLINE parser = argparse.ArgumentParser(description='Training of HiDDeN nets')NEWLINE # parser.add_argument('--size', '-s', default=128, type=int, help='The size of the images (images are square so this is height and width).')NEWLINE parser.add_argument('--data-dir', '-d', required=True, type=str, help='The directory where the data is stored.')NEWLINE parser.add_argument('--runs_root', '-r', default=os.path.join('.', 'experiments'), type=str,NEWLINE help='The root folder where data about experiments are stored.')NEWLINE parser.add_argument('--batch-size', '-b', default=1, type=int, help='Validation batch size.')NEWLINENEWLINE args = parser.parse_args()NEWLINE print_each = 25NEWLINENEWLINE completed_runs = [o for o in os.listdir(args.runs_root)NEWLINE if os.path.isdir(os.path.join(args.runs_root, o)) and o != 'no-noise-defaults']NEWLINENEWLINE print(completed_runs)NEWLINENEWLINE write_csv_header = TrueNEWLINE for run_name in completed_runs:NEWLINE current_run = os.path.join(args.runs_root, run_name)NEWLINE print(f'Run folder: {current_run}')NEWLINE options_file = os.path.join(current_run, 'options-and-config.pickle')NEWLINE train_options, hidden_config, noise_config = utils.load_options(options_file)NEWLINE train_options.train_folder = os.path.join(args.data_dir, 'val')NEWLINE train_options.validation_folder = os.path.join(args.data_dir, 'val')NEWLINE train_options.batch_size = args.batch_sizeNEWLINE checkpoint, chpt_file_name = utils.load_last_checkpoint(os.path.join(current_run, 'checkpoints'))NEWLINE print(f'Loaded checkpoint from file {chpt_file_name}')NEWLINENEWLINE noiser = Noiser(noise_config)NEWLINE model = Hidden(hidden_config, device, noiser, tb_logger=None)NEWLINE utils.model_from_checkpoint(model, checkpoint)NEWLINENEWLINE print('Model loaded successfully. Starting validation run...')NEWLINE _, val_data = utils.get_data_loaders(hidden_config, train_options)NEWLINE file_count = len(val_data.dataset)NEWLINE if file_count % train_options.batch_size == 0:NEWLINE steps_in_epoch = file_count // train_options.batch_sizeNEWLINE else:NEWLINE steps_in_epoch = file_count // train_options.batch_size + 1NEWLINENEWLINE losses_accu = {}NEWLINE step = 0NEWLINE for image, _ in val_data:NEWLINE step += 1NEWLINE image = image.to(device)NEWLINE message = torch.Tensor(np.random.choice([0, 1], (image.shape[0], hidden_config.message_length))).to(device)NEWLINE losses, (encoded_images, noised_images, decoded_messages) = model.validate_on_batch([image, message],NEWLINE set_eval_mode=True)NEWLINE if not losses_accu: # dict is empty, initializeNEWLINE for name in losses:NEWLINE losses_accu[name] = AverageMeter()NEWLINE for name, loss in losses.items():NEWLINE losses_accu[name].update(loss)NEWLINE if step % print_each == 0 or step == steps_in_epoch:NEWLINE print(f'Step {step}/{steps_in_epoch}')NEWLINE utils.print_progress(losses_accu)NEWLINE print('-' * 40)NEWLINENEWLINE # utils.print_progress(losses_accu)NEWLINE write_validation_loss(os.path.join(args.runs_root, 'validation_run.csv'), losses_accu, run_name,NEWLINE checkpoint['epoch'],NEWLINE write_header=write_csv_header)NEWLINE write_csv_header = FalseNEWLINENEWLINE # train(model, device, hidden_config, train_options, this_run_folder, tb_logger)NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE main()
#!/usr/bin/env python3NEWLINENEWLINE"""NEWLINEusage: steps.py [-h] [--after AFTER] [--before BEFORE] [--tz TZ]NEWLINE [--output OUTPUT] [--account ACCOUNT] [--password PASSWORD]NEWLINE [--subaccount SUBACCOUNT]NEWLINE FLOWNEWLINENEWLINECreates a CSV file of steps within engagements in a Twilio Studio flow, forNEWLINEthe given time period, for the purposes of analyzing paths through an IVR. NEWLINENEWLINEpositional arguments:NEWLINE FLOW Flow SIDNEWLINENEWLINEoptional arguments:NEWLINE -h, --help show this help message and exitNEWLINE --after AFTER yyyy-mm-dd [HH:MM[:SS]]; time defaults to 00:00:00NEWLINE (default: None)NEWLINE --before BEFORE, -b BEFORENEWLINE yyyy-mm-dd [HH:MM[:SS]]; time defaults to 00:00:00NEWLINE (default: None)NEWLINE --tz TZ, -t TZ Time zone name (default: UTC)NEWLINE --output OUTPUT, -o OUTPUTNEWLINE Output file; defaults to terminal (default: None)NEWLINE --account ACCOUNT, -a ACCOUNTNEWLINE Account SID; if not given, value of environmentNEWLINE variable TWILIO_ACCOUNT_SID (default: None)NEWLINE --password PASSWORD, -p PASSWORDNEWLINE Auth token; if not given, value of environmentNEWLINE variable TWILIO_AUTH_TOKEN (default: None)NEWLINE --subaccount SUBACCOUNT, -s SUBACCOUNTNEWLINE If present, subaccount to use (default: None)NEWLINE"""NEWLINENEWLINENEWLINEimport osNEWLINEimport sysNEWLINEfrom datetime import datetimeNEWLINEfrom pytz import timezone, UnknownTimeZoneErrorNEWLINEimport beginNEWLINEfrom twilio.base.exceptions import TwilioRestExceptionNEWLINEfrom twilio.rest import ClientNEWLINENEWLINENEWLINEdef get_datetime(dt_string, tz):NEWLINE """Converts a date/time string into a datetime object with the given time zone."""NEWLINE try:NEWLINE dt = datetime.strptime(dt_string, '%Y-%m-%d')NEWLINE except ValueError:NEWLINE try:NEWLINE dt = datetime.strptime(dt_string, '%Y-%m-%d %H:%M')NEWLINE except ValueError:NEWLINE dt = datetime.strptime(dt_string, '%Y-%m-%d %H:%M:%S')NEWLINE NEWLINE return tz.localize(dt)NEWLINENEWLINENEWLINE@begin.startNEWLINEdef main(NEWLINE flow: "Flow SID",NEWLINE after: "yyyy-mm-dd [HH:MM[:SS]]; time defaults to 00:00:00" = None,NEWLINE before: "yyyy-mm-dd [HH:MM[:SS]]; time defaults to 00:00:00" = None,NEWLINE tz: "Time zone name" = "UTC",NEWLINE output: "Output file; defaults to terminal" = None,NEWLINE account: "Account SID; if not given, value of environment variable TWILIO_ACCOUNT_SID" = None,NEWLINE password: "Auth token; if not given, value of environment variable TWILIO_AUTH_TOKEN" = None,NEWLINE subaccount: "If present, subaccount to use" = NoneNEWLINE ):NEWLINE """NEWLINE Creates a CSV file of steps within engagements in a Twilio Studio flow, for the given time period,NEWLINE for the purposes of analyzing paths through an IVR. NEWLINE """NEWLINE if not flow:NEWLINE sys.exit("Error: no Flow SID")NEWLINENEWLINE try:NEWLINE account = account or os.environ['TWILIO_ACCOUNT_SID']NEWLINE password = password or os.environ['TWILIO_AUTH_TOKEN']NEWLINE except KeyError:NEWLINE sys.exit("Error: missing environment variable TWILIO_ACCOUNT_SID and/or TWILIO_AUTH_TOKEN")NEWLINENEWLINE try:NEWLINE tz = timezone(tz)NEWLINE except UnknownTimeZoneError:NEWLINE sys.exit("Invalid timezone: {}".format(tz))NEWLINE NEWLINE try:NEWLINE after = get_datetime(after, tz) if after else NoneNEWLINE except ValueError:NEWLINE sys.exit("Invalid date/time: {}".format(after))NEWLINENEWLINE try:NEWLINE before = get_datetime(before, tz) if before else NoneNEWLINE except ValueError:NEWLINE sys.exit("Invalid date/time: {}".format(before))NEWLINENEWLINE if after and before and after > before:NEWLINE sys.exit("Error: end date/time is before start date/time")NEWLINENEWLINE client = Client(account, password, subaccount)NEWLINENEWLINE # Grab the flow instance.NEWLINE try:NEWLINE flow = client.studio.flows.get(flow).fetch()NEWLINE except TwilioRestException:NEWLINE sys.exit("Error: unable to get Flow {}".format(flow))NEWLINENEWLINE def in_range(engagement):NEWLINE """Does the engagement fall between after and before?"""NEWLINE if after and engagement.date_created < after:NEWLINE return FalseNEWLINE if before and engagement.date_created >= before:NEWLINE return FalseNEWLINE return TrueNEWLINE NEWLINE engagements = filter(in_range, flow.engagements.list())NEWLINENEWLINE output = open(output, 'w') if output else sys.stdoutNEWLINE print("Date/Time,Engagement SID,Contact Address,Step,Event,Next Step", file=output)NEWLINENEWLINE for engagement in engagements:NEWLINE steps = engagement.steps.list()NEWLINE for step in steps:NEWLINE print("{},{},{},{},{},{}".format(NEWLINE step.date_created,NEWLINE engagement.sid,NEWLINE engagement.contact_channel_address,NEWLINE step.transitioned_from,NEWLINE step.name,NEWLINE step.transitioned_toNEWLINE ), file=output)NEWLINENEWLINE output.close()NEWLINE
from flask import request,gNEWLINEfrom . import apiNEWLINEfrom .. import dbNEWLINEfrom ..models import Agent,AgentGroupNEWLINEfrom ..decorators import json, paginateNEWLINEfrom ..utils import random_strNEWLINEimport datetimeNEWLINENEWLINENEWLINE@api.route('/agents/<string:id>', methods=['GET'])NEWLINE@jsonNEWLINEdef get_agent(id):NEWLINE userId = g.user.id;NEWLINE print("userId",userId)NEWLINE return Agent.query.filter(Agent.id==id).filter(Agent.user_id == userId).one();NEWLINENEWLINE@api.route('/agents/<string:id>', methods=['PUT','POST'])NEWLINE@jsonNEWLINEdef update_agent(id):NEWLINE """update agent info."""NEWLINE form = request.formNEWLINE ip = form['ip']NEWLINE host_name = form['host_name']NEWLINE agent = Agent.query.get_or_404(id);NEWLINE agent.ip =ip;NEWLINE agent.host_name = host_name;NEWLINE agent.status = 1;NEWLINE db.session.commit();NEWLINE return {}NEWLINENEWLINE@api.route('/agents/key', methods=['GET'])NEWLINE@jsonNEWLINEdef getAgentKey():NEWLINE """return a user's agent key to install."""NEWLINE userId = g.user.id;NEWLINE temp_agent = Agent.query.filter(Agent.user_id == userId).filter(Agent.status==-1).one_or_none()NEWLINE if temp_agent is None :NEWLINE now = datetime.datetime.now()NEWLINE agent = Agent(id=random_str(8),user_id=userId,create_time=now,update_time=now,status=-1)NEWLINE baseGroup =AgentGroup.query.filter(AgentGroup.user_id==agent.user_id).filter(AgentGroup.name=='all').one_or_none();NEWLINE if baseGroup is None:NEWLINE baseGroup = AgentGroup(name='all',user_id=agent.user_id,sid="%d@%s"%(agent.user_id,random_str(8)))NEWLINE db.session.add(baseGroup)NEWLINE agent.default_group_sid = baseGroup.sidNEWLINE db.session.add(agent)NEWLINE db.session.commit()NEWLINE return agentNEWLINE return temp_agentNEWLINE NEWLINE
from rlkit.core import loggerNEWLINEfrom rlkit.core.timer import timerNEWLINEfrom rlkit.data_management.online_vae_replay_buffer import \NEWLINE OnlineVaeRelabelingBufferNEWLINEfrom rlkit.data_management.shared_obs_dict_replay_buffer \NEWLINE import SharedObsDictRelabelingBufferNEWLINEimport rlkit.torch.vae.vae_schedules as vae_schedulesNEWLINEfrom rlkit.misc.eval_util import create_stats_ordered_dictNEWLINEfrom rlkit.torch.torch_rl_algorithm import (NEWLINE TorchBatchRLAlgorithm,NEWLINE)NEWLINEimport rlkit.torch.pytorch_util as ptuNEWLINEfrom torch.multiprocessing import Process, PipeNEWLINEfrom threading import ThreadNEWLINEimport numpy as npNEWLINEfrom rlkit.core.logging import add_prefixNEWLINENEWLINEclass OnlineVaeAlgorithm(TorchBatchRLAlgorithm):NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE vae,NEWLINE vae_trainer,NEWLINE *base_args,NEWLINE vae_save_period=1,NEWLINE vae_training_schedule=vae_schedules.never_train,NEWLINE oracle_data=False,NEWLINE parallel_vae_train=True,NEWLINE vae_min_num_steps_before_training=0,NEWLINE uniform_dataset=None,NEWLINE **base_kwargsNEWLINE ):NEWLINE super().__init__(*base_args, **base_kwargs)NEWLINE assert isinstance(self.replay_buffer, OnlineVaeRelabelingBuffer)NEWLINE self.vae = vaeNEWLINE self.vae_trainer = vae_trainerNEWLINE self.vae_trainer.model = self.vaeNEWLINE self.vae_save_period = vae_save_periodNEWLINE self.vae_training_schedule = vae_training_scheduleNEWLINE self.oracle_data = oracle_dataNEWLINENEWLINE self.parallel_vae_train = parallel_vae_trainNEWLINE self.vae_min_num_steps_before_training = vae_min_num_steps_before_trainingNEWLINE self.uniform_dataset = uniform_datasetNEWLINENEWLINE self._vae_training_process = NoneNEWLINE self._update_subprocess_vae_thread = NoneNEWLINE self._vae_conn_pipe = NoneNEWLINENEWLINE def _end_epoch(self):NEWLINE timer.start_timer('vae training')NEWLINE self._train_vae(self.epoch)NEWLINE timer.stop_timer('vae training')NEWLINE super()._end_epoch()NEWLINENEWLINE def _get_diagnostics(self):NEWLINE vae_log = self._get_vae_diagnostics().copy()NEWLINE vae_log.update(super()._get_diagnostics())NEWLINE return vae_logNEWLINENEWLINE def to(self, device):NEWLINE self.vae.to(device)NEWLINE super().to(device)NEWLINENEWLINE """NEWLINE VAE-specific CodeNEWLINE """NEWLINE def _train_vae(self, epoch):NEWLINE if self.parallel_vae_train and self._vae_training_process is None:NEWLINE self.init_vae_training_subprocess()NEWLINE should_train, amount_to_train = self.vae_training_schedule(epoch)NEWLINE rl_start_epoch = int(self.min_num_steps_before_training / (NEWLINE self.num_expl_steps_per_train_loop * self.num_train_loops_per_epochNEWLINE ))NEWLINE if should_train: # or epoch <= (rl_start_epoch - 1):NEWLINE if self.parallel_vae_train:NEWLINE assert self._vae_training_process.is_alive()NEWLINE # Make sure the last vae update has finished before startingNEWLINE # another oneNEWLINE if self._update_subprocess_vae_thread is not None:NEWLINE self._update_subprocess_vae_thread.join()NEWLINE self._update_subprocess_vae_thread = Thread(NEWLINE target=OnlineVaeAlgorithm.update_vae_in_training_subprocess,NEWLINE args=(self, epoch, ptu.device)NEWLINE )NEWLINE self._update_subprocess_vae_thread.start()NEWLINE self._vae_conn_pipe.send((amount_to_train, epoch))NEWLINE else:NEWLINE _train_vae(NEWLINE self.vae_trainer,NEWLINE epoch,NEWLINE self.replay_buffer,NEWLINE amount_to_trainNEWLINE )NEWLINE self.replay_buffer.refresh_latents(epoch)NEWLINE _test_vae(NEWLINE self.vae_trainer,NEWLINE epoch,NEWLINE self.replay_buffer,NEWLINE vae_save_period=self.vae_save_period,NEWLINE uniform_dataset=self.uniform_dataset,NEWLINE )NEWLINENEWLINE def _get_vae_diagnostics(self):NEWLINE return add_prefix(NEWLINE self.vae_trainer.get_diagnostics(),NEWLINE prefix='vae_trainer/',NEWLINE )NEWLINENEWLINE def _cleanup(self):NEWLINE if self.parallel_vae_train:NEWLINE self._vae_conn_pipe.close()NEWLINE self._vae_training_process.terminate()NEWLINENEWLINE def init_vae_training_subprocess(self):NEWLINE assert isinstance(self.replay_buffer, SharedObsDictRelabelingBuffer)NEWLINENEWLINE self._vae_conn_pipe, process_pipe = Pipe()NEWLINE self._vae_training_process = Process(NEWLINE target=subprocess_train_vae_loop,NEWLINE args=(NEWLINE process_pipe,NEWLINE self.vae,NEWLINE self.vae.state_dict(),NEWLINE self.replay_buffer,NEWLINE self.replay_buffer.get_mp_info(),NEWLINE ptu.device,NEWLINE )NEWLINE )NEWLINE self._vae_training_process.start()NEWLINE self._vae_conn_pipe.send(self.vae_trainer)NEWLINENEWLINE def update_vae_in_training_subprocess(self, epoch, device):NEWLINE self.vae.__setstate__(self._vae_conn_pipe.recv())NEWLINE self.vae.to(device)NEWLINE _test_vae(NEWLINE self.vae_trainer,NEWLINE epoch,NEWLINE self.replay_buffer,NEWLINE vae_save_period=self.vae_save_period,NEWLINE uniform_dataset=self.uniform_dataset,NEWLINE )NEWLINENEWLINENEWLINEdef _train_vae(vae_trainer, epoch, replay_buffer, batches=50, oracle_data=False):NEWLINE for b in range(batches):NEWLINE batch = replay_buffer.random_vae_training_data(vae_trainer.batch_size, epoch)NEWLINE vae_trainer.train_batch(NEWLINE epoch,NEWLINE batch,NEWLINE )NEWLINE # replay_buffer.train_dynamics_model(batches=batches)NEWLINENEWLINEdef _test_vae(vae_trainer, epoch, replay_buffer, batches=10, vae_save_period=1, uniform_dataset=None):NEWLINE save_imgs = epoch % vae_save_period == 0NEWLINE log_fit_skew_stats = replay_buffer._prioritize_vae_samples and uniform_dataset is not NoneNEWLINE if uniform_dataset is not None:NEWLINE replay_buffer.log_loss_under_uniform(uniform_dataset, vae_trainer.batch_size, rl_logger=vae_trainer.vae_logger_stats_for_rl)NEWLINE for b in range(batches):NEWLINE batch = replay_buffer.random_vae_training_data(vae_trainer.batch_size, epoch)NEWLINE vae_trainer.test_batch(NEWLINE epoch,NEWLINE batch,NEWLINE )NEWLINE if save_imgs:NEWLINE vae_trainer.dump_samples(epoch)NEWLINE vae_trainer.dump_reconstructions(epoch)NEWLINE if log_fit_skew_stats:NEWLINE vae_trainer.dump_best_reconstruction(epoch)NEWLINE vae_trainer.dump_worst_reconstruction(epoch)NEWLINE vae_trainer.dump_sampling_histogram(epoch, batch_size=vae_trainer.batch_size)NEWLINE if uniform_dataset is not None:NEWLINE vae_trainer.dump_uniform_imgs_and_reconstructions(dataset=uniform_dataset, epoch=epoch)NEWLINENEWLINENEWLINEdef subprocess_train_vae_loop(NEWLINE conn_pipe,NEWLINE vae,NEWLINE vae_params,NEWLINE replay_buffer,NEWLINE mp_info,NEWLINE device,NEWLINE):NEWLINE """NEWLINE The observations and next_observations of the replay buffer are stored inNEWLINE shared memory. This loop waits until the parent signals to start vaeNEWLINE training, trains and sends the vae back, and then refreshes the latents.NEWLINE Refreshing latents in the subprocess reflects in the main process as wellNEWLINE since the latents are in shared memory. Since this is does asynchronously,NEWLINE it is possible for the main process to see half the latents updated and halfNEWLINE not.NEWLINE """NEWLINE ptu.device = deviceNEWLINE vae_trainer = conn_pipe.recv()NEWLINE vae.load_state_dict(vae_params)NEWLINE vae.to(device)NEWLINE vae_trainer.set_vae(vae)NEWLINE replay_buffer.init_from_mp_info(mp_info)NEWLINE replay_buffer.env.vae = vaeNEWLINE while True:NEWLINE amount_to_train, epoch = conn_pipe.recv()NEWLINE _train_vae(vae_trainer, replay_buffer, epoch, amount_to_train)NEWLINE conn_pipe.send(vae_trainer.model.__getstate__())NEWLINE replay_buffer.refresh_latents(epoch)NEWLINE
# -------------------------------------------------------------------------NEWLINE# Copyright (c) Microsoft Corporation. All rights reserved.NEWLINE# Licensed under the MIT License. See License.txt in the project root forNEWLINE# license information.NEWLINE# --------------------------------------------------------------------------NEWLINENEWLINEimport inspectNEWLINEimport reNEWLINEimport sixNEWLINEimport sysNEWLINEimport tracebackNEWLINEimport warningsNEWLINEimport numpy as npNEWLINEfrom onnx import onnx_pb as onnx_protoNEWLINEfrom onnxconverter_common.onnx_ops import __dict__ as dict_apply_operationNEWLINEfrom ..proto import TensorProtoNEWLINEfrom ..proto.onnx_helper_modified import (NEWLINE make_node, ValueInfoProto, make_tensor, make_attributeNEWLINE)NEWLINEfrom .interface import ModelContainerNEWLINEfrom .utils import get_domainNEWLINENEWLINENEWLINEdef _get_operation_list():NEWLINE """NEWLINE Investigates this module to extract all ONNX functionsNEWLINE which needs to be converted with these functions.NEWLINE """NEWLINE regs = [re.compile("container.add_node[(]'([A-Z][a-zA-Z0-9]*)', "NEWLINE "\\[?input_name"),NEWLINE re.compile("container.add_node[(]'([A-Z][a-zA-Z0-9]*)', "NEWLINE "\\[\\]"),NEWLINE re.compile("container.add_node[(]'([A-Z][a-zA-Z0-9]*)', "NEWLINE "inputs"),NEWLINE re.compile("scope, '([A-Z][a-zA-Z0-9]*)', \\[?input_name"),NEWLINE re.compile("op_type = '([A-Z][a-zA-Z0-9]*)'")]NEWLINE res = {}NEWLINE for k, v in dict_apply_operation.items():NEWLINE if k.startswith("apply_") and callable(v):NEWLINE found = NoneNEWLINE source = inspect.getsource(v)NEWLINE for reg in regs:NEWLINE g = reg.search(source)NEWLINE if g:NEWLINE found = g.groups()[0]NEWLINE breakNEWLINE if found is None:NEWLINE warnings.warn("Unable to find an ONNX name in function "NEWLINE "'{0}', source=\n{1}".format(k, source))NEWLINE res[found] = vNEWLINE return resNEWLINENEWLINENEWLINEdef _build_options(model, defined_options, default_values):NEWLINE opts = {} if default_values is None else default_valuesNEWLINE if defined_options is not None:NEWLINE opts.update(defined_options.get(type(model), {}))NEWLINE opts.update(defined_options.get(id(model), {}))NEWLINE return optsNEWLINENEWLINENEWLINE_apply_operation_specific = _get_operation_list()NEWLINENEWLINENEWLINEclass RawModelContainerNode(object):NEWLINE """NEWLINE This node is the carrier of the model we want to convert.NEWLINE It provides an abstract layer so that our parsingNEWLINE framework can work with models generated by different tools.NEWLINE """NEWLINENEWLINE def __init__(self, raw_model, dtype):NEWLINE """NEWLINE :param raw_model: *scikit-learn* model to convertNEWLINE """NEWLINE self._raw_model = raw_modelNEWLINE self.dtype = dtypeNEWLINE if dtype == np.float32:NEWLINE self.proto_dtype = onnx_proto.TensorProto.FLOATNEWLINE elif dtype == np.float64:NEWLINE self.proto_dtype = onnx_proto.TensorProto.DOUBLENEWLINE elif dtype == np.int64:NEWLINE self.proto_dtype = onnx_proto.TensorProto.INT64NEWLINE else:NEWLINE raise ValueError("dtype should be either np.float32, "NEWLINE "np.float64, np.int64.")NEWLINENEWLINE @propertyNEWLINE def raw_model(self):NEWLINE return self._raw_modelNEWLINENEWLINE @propertyNEWLINE def input_names(self):NEWLINE """NEWLINE This function should return a list of strings. Each stringNEWLINE corresponds to an input variable name.NEWLINE :return: a list of stringNEWLINE """NEWLINE raise NotImplementedError()NEWLINENEWLINE @propertyNEWLINE def output_names(self):NEWLINE """NEWLINE This function should return a list of strings. Each stringNEWLINE corresponds to an output variable name.NEWLINE :return: a list of stringNEWLINE """NEWLINE raise NotImplementedError()NEWLINENEWLINENEWLINEclass SklearnModelContainerNode(RawModelContainerNode):NEWLINE """NEWLINE Main container for one *scikit-learn* model.NEWLINE Every converter adds nodes to an existing containerNEWLINE which is converted into a *ONNX* graph by an instance ofNEWLINE :class:`Topology <skl2onnx.common._topology.Topology>`.NEWLINE """NEWLINENEWLINE def __init__(self, sklearn_model, dtype):NEWLINE super(SklearnModelContainerNode, self).__init__(sklearn_model, dtype)NEWLINE # Scikit-learn models have no input and output specified,NEWLINE # so we create them and store them in this container.NEWLINE self._inputs = []NEWLINE self._outputs = []NEWLINENEWLINE @propertyNEWLINE def input_names(self):NEWLINE return [variable.raw_name for variable in self._inputs]NEWLINENEWLINE @propertyNEWLINE def output_names(self):NEWLINE return [variable.raw_name for variable in self._outputs]NEWLINENEWLINE def add_input(self, variable):NEWLINE # The order of adding variables matters. The final model'sNEWLINE # input names are sequentially added as this listNEWLINE if variable not in self._inputs:NEWLINE self._inputs.append(variable)NEWLINENEWLINE def add_output(self, variable):NEWLINE # The order of adding variables matters. The final model'sNEWLINE # output names are sequentially added as this listNEWLINE if variable not in self._outputs:NEWLINE self._outputs.append(variable)NEWLINENEWLINENEWLINEclass ModelComponentContainer(ModelContainer):NEWLINE """NEWLINE In the conversion phase, this class is used to collect all materialsNEWLINE required to build an *ONNX* *GraphProto*, which is encapsulated in aNEWLINE *ONNX* *ModelProto*.NEWLINE """NEWLINENEWLINE def __init__(self, target_opset, options=None, dtype=None):NEWLINE """NEWLINE :param target_opset: number, for example, 7 for *ONNX 1.2*, andNEWLINE 8 for *ONNX 1.3*.NEWLINE :param dtype: float type to be used for every float coefficientNEWLINE :param options: see :ref:`l-conv-options`NEWLINE """NEWLINE if dtype is None:NEWLINE raise ValueError("dtype must be specified, it should be either "NEWLINE "np.float32 or np.float64.")NEWLINE # Inputs of ONNX graph. They are ValueInfoProto in ONNX.NEWLINE self.inputs = []NEWLINE # Outputs of ONNX graph. They are ValueInfoProto in ONNX.NEWLINE self.outputs = []NEWLINE # ONNX tensors (type: TensorProto). They are initializers ofNEWLINE # ONNX GraphProto.NEWLINE self.initializers = []NEWLINE # Intermediate variables in ONNX computational graph. They areNEWLINE # ValueInfoProto in ONNX.NEWLINE self.value_info = []NEWLINE # ONNX nodes (type: NodeProto) used to define computationNEWLINE # structureNEWLINE self.nodes = []NEWLINE # ONNX operators' domain-version pair set. They will be addedNEWLINE # into opset_import field in the final ONNX model.NEWLINE self.node_domain_version_pair_sets = set()NEWLINE # The targeted ONNX operator set (referred to as opset) thatNEWLINE # matches the ONNX version.NEWLINE self.target_opset = target_opsetNEWLINE # Additional options given to converters.NEWLINE self.options = optionsNEWLINENEWLINE self.dtype = dtypeNEWLINE if dtype == np.float32:NEWLINE self.proto_dtype = onnx_proto.TensorProto.FLOATNEWLINE elif dtype == np.float64:NEWLINE self.proto_dtype = onnx_proto.TensorProto.DOUBLENEWLINE elif dtype == np.int64:NEWLINE self.proto_dtype = onnx_proto.TensorProto.INT64NEWLINE else:NEWLINE raise ValueError("dtype should be either np.float32, "NEWLINE "np.float64, np.int64.")NEWLINENEWLINE def __str__(self):NEWLINE """NEWLINE Shows internal information.NEWLINE """NEWLINE rows = []NEWLINE if self.inputs:NEWLINE rows.append("INPUTS")NEWLINE for inp in self.inputs:NEWLINE rows.append(NEWLINE " " + str(inp).replace(" ", "").replace("\n", " "))NEWLINE if self.outputs:NEWLINE rows.append("OUTPUTS")NEWLINE for out in self.outputs:NEWLINE rows.append(NEWLINE " " + str(out).replace(" ", "").replace("\n", " "))NEWLINE if self.initializers:NEWLINE rows.append("INITIALIZERS")NEWLINE for ini in self.initializers:NEWLINE rows.append(NEWLINE " " + str(ini).replace(" ", "").replace("\n", " "))NEWLINE if self.value_info:NEWLINE rows.append("NODES")NEWLINE for val in self.value_info:NEWLINE rows.append(NEWLINE " " + str(val).replace(" ", "").replace("\n", " "))NEWLINE if self.nodes:NEWLINE rows.append("PROTO")NEWLINE for nod in self.nodes:NEWLINE rows.append(NEWLINE " " + str(nod).replace(" ", "").replace("\n", " "))NEWLINE return "\n".join(rows)NEWLINENEWLINE def _make_value_info(self, variable):NEWLINE value_info = ValueInfoProto()NEWLINE value_info.name = variable.full_nameNEWLINE value_info.type.CopyFrom(variable.type.to_onnx_type())NEWLINE if variable.type.doc_string:NEWLINE value_info.doc_string = variable.type.doc_stringNEWLINE return value_infoNEWLINENEWLINE def add_input(self, variable):NEWLINE """NEWLINE Adds our *Variable* object defined _parser.py into the the inputNEWLINE list of the final ONNX model.NEWLINENEWLINE :param variable: The Variable object to be addedNEWLINE """NEWLINE self.inputs.append(self._make_value_info(variable))NEWLINENEWLINE def add_output(self, variable):NEWLINE """NEWLINE Adds our *Variable* object defined *_parser.py* into the theNEWLINE output list of the final ONNX model.NEWLINENEWLINE :param variable: The Variable object to be addedNEWLINE """NEWLINE self.outputs.append(self._make_value_info(variable))NEWLINENEWLINE def add_initializer(self, name, onnx_type, shape, content, can_cast=True):NEWLINE """NEWLINE Adds a *TensorProto* into the initializer list of the finalNEWLINE ONNX model.NEWLINENEWLINE :param name: Variable name in the produced ONNX model.NEWLINE :param onnx_type: Element types allowed in ONNX tensor, e.g.,NEWLINE TensorProto.FLOAT and TensorProto.STRING.NEWLINE :param shape: Tensor shape, a list of integers.NEWLINE :param content: Flattened tensor values (i.e., a float listNEWLINE or a float array).NEWLINE :param can_cast: the method can take the responsabilityNEWLINE to cast the constantNEWLINE :return: created tensorNEWLINE """NEWLINE if (can_cast and isinstance(content, np.ndarray) andNEWLINE onnx_type in (TensorProto.FLOAT, TensorProto.DOUBLE) andNEWLINE onnx_type != self.proto_dtype):NEWLINE content = content.astype(self.dtype)NEWLINE onnx_type = self.proto_dtypeNEWLINENEWLINE if isinstance(content, TensorProto):NEWLINE tensor = TensorProto()NEWLINE tensor.data_type = content.data_typeNEWLINE tensor.name = nameNEWLINE tensor.raw_data = content.raw_dataNEWLINE tensor.dims.extend(content.dims)NEWLINE elif shape is None:NEWLINE tensor = make_attribute(name, content)NEWLINE else:NEWLINE if any(d is None for d in shape):NEWLINE raise ValueError('Shape of initializer cannot contain None')NEWLINE tensor = make_tensor(name, onnx_type, shape, content)NEWLINE self.initializers.append(tensor)NEWLINE return tensorNEWLINENEWLINE def add_value_info(self, variable):NEWLINE self.value_info.append(self._make_value_info(variable))NEWLINENEWLINE def _check_operator(self, op_type):NEWLINE """NEWLINE Checks that if *op_type* is one of the operators defined inNEWLINE :mod:`skl2onnx.common._apply_container`, then it was calledNEWLINE from a function defined in this submodule by lookingNEWLINE into the callstack. The test is enabled for *python >= 3.6*.NEWLINE """NEWLINE if (op_type in _apply_operation_specific andNEWLINE sys.version_info[:2] >= (3, 6)):NEWLINE tb = traceback.extract_stack()NEWLINE operation = []NEWLINE fct = _apply_operation_specific[op_type]NEWLINE skl2 = FalseNEWLINE for b in tb:NEWLINE if "_apply_operation" in b.filename and b.name == fct.__name__:NEWLINE operation.append(b)NEWLINE if not skl2 and "skl2onnx" in b.filename:NEWLINE skl2 = TrueNEWLINE if skl2 and len(operation) == 0:NEWLINE raise RuntimeError(NEWLINE "Operator '{0}' should be added with function "NEWLINE "'{1}' in submodule _apply_operation.".format(NEWLINE op_type, fct.__name__))NEWLINENEWLINE def add_node(self, op_type, inputs, outputs, op_domain='', op_version=1,NEWLINE name=None, **attrs):NEWLINE """NEWLINE Adds a *NodeProto* into the node list of the final ONNX model.NEWLINE If the input operator's domain-version information cannot beNEWLINE found in our domain-version pool (a Python set), we may add it.NEWLINENEWLINE :param op_type: A string (e.g., Pool and Conv) indicating theNEWLINE type of the NodeProtoNEWLINE :param inputs: A list of strings. They are the input variables'NEWLINE names of the considered NodeProtoNEWLINE :param outputs: A list of strings. They are the outputNEWLINE variables' names of the considered NodeProtoNEWLINE :param op_domain: The domain name (e.g., ai.onnx.ml) of theNEWLINE operator we are trying to add.NEWLINE :param op_version: The version number (e.g., 0 and 1) of theNEWLINE operator we are trying to add.NEWLINE :param name: name of the node, this name cannot be emptyNEWLINE :param attrs: A Python dictionary. Keys and values areNEWLINE attributes' names and attributes' values,NEWLINE respectively.NEWLINE """NEWLINE if name is None or not isinstance(NEWLINE name, str) or name == '':NEWLINE name = "N%d" % len(self.nodes)NEWLINE existing_names = set(n.name for n in self.nodes)NEWLINE if name in existing_names:NEWLINE name += "-N%d" % len(self.nodes)NEWLINENEWLINE if op_domain is None:NEWLINE op_domain = get_domain()NEWLINE self._check_operator(op_type)NEWLINENEWLINE if isinstance(inputs, (six.string_types, six.text_type)):NEWLINE inputs = [inputs]NEWLINE if isinstance(outputs, (six.string_types, six.text_type)):NEWLINE outputs = [outputs]NEWLINE if not isinstance(inputs, list) or not all(NEWLINE isinstance(s, (six.string_types, six.text_type))NEWLINE for s in inputs):NEWLINE type_list = ','.join(list(str(type(s)) for s in inputs))NEWLINE raise ValueError('Inputs must be a list of string but get [%s]'NEWLINE % type_list)NEWLINE if (not isinstance(outputs, list) orNEWLINE not all(isinstance(s, (six.string_types, six.text_type))NEWLINE for s in outputs)):NEWLINE type_list = ','.join(list(str(type(s)) for s in outputs))NEWLINE raise ValueError('Outputs must be a list of string but get [%s]'NEWLINE % type_list)NEWLINE upd = {}NEWLINE for k, v in attrs.items():NEWLINE if v is None:NEWLINE raise ValueError('Failed to create ONNX node. Undefined 'NEWLINE 'attribute pair (%s, %s) found' % (k, v))NEWLINE if (isinstance(v, np.ndarray) andNEWLINE v.dtype in (np.float32, np.float64) andNEWLINE v.dtype != self.dtype):NEWLINE upd[k] = v.astype(self.dtype)NEWLINENEWLINE if upd:NEWLINE attrs.update(upd)NEWLINE try:NEWLINE node = make_node(op_type, inputs, outputs, name=name, **attrs)NEWLINE except ValueError as e:NEWLINE raise ValueError("Unable to create node '{}' with name='{}'."NEWLINE "".format(op_type, name)) from eNEWLINE node.domain = op_domainNEWLINENEWLINE self.node_domain_version_pair_sets.add((op_domain, op_version))NEWLINE self.nodes.append(node)NEWLINE if (self.target_opset is not None andNEWLINE op_version is not None andNEWLINE op_version > self.target_opset):NEWLINE raise RuntimeError(NEWLINE "Opset number {} is higher than targeted opset {} for "NEWLINE "node '{}'.".format(NEWLINE op_version, self.target_opset, node.op_type))NEWLINENEWLINE def get_options(self, model, default_values=None):NEWLINE """NEWLINE Returns additional options for a model.NEWLINE It first looks by class then by id (``id(model)``).NEWLINE :param model: model being convertedNEWLINE :param default_values: default options (it is modified byNEWLINE the function)NEWLINE :return: dictionaryNEWLINE """NEWLINE return _build_options(model, self.options, default_values)NEWLINE
# title.pyNEWLINENEWLINEimport htmlNEWLINEimport reNEWLINENEWLINEfrom bobbit.utils import strip_htmlNEWLINENEWLINE# MetadataNEWLINENEWLINENAME = 'title'NEWLINEENABLE = TrueNEWLINEPATTERN = r'.*(?P<url>http[^\s]+).*'NEWLINEUSAGE = '''Usage: <url>NEWLINELooks up title of URL.NEWLINEExample:NEWLINE > http://www.insidehighered.com/quicktakes/2019/06/24/uc-santa-cruz-removes-catholic-mission-bellNEWLINE Title: UC Santa Cruz Removes Catholic Mission BellNEWLINE'''NEWLINENEWLINE# ConstantsNEWLINENEWLINEBLACKLIST = []NEWLINEAVOID_EXTENSIONS = ('.gif', '.jpg', '.mkv', '.mov', '.mp4', '.png')NEWLINENEWLINE# CommandNEWLINENEWLINEasync def title(bot, message, url=None):NEWLINE if message.channel in BLACKLIST or \NEWLINE any(url.lower().endswith(extension) for extension in AVOID_EXTENSIONS):NEWLINE returnNEWLINENEWLINE async with bot.http_client.get(url) as response:NEWLINE try:NEWLINE text = (await response.text()).replace('\n', ' ')NEWLINE html_title = re.findall(r'<title[^>]*>([^<]+)</title>', text)[0]NEWLINE response = bot.client.format_text(NEWLINE '{color}{green}Title{color}: {bold}{title}{bold}',NEWLINE title = strip_html(html.unescape(html_title)).strip()NEWLINE )NEWLINE except (IndexError, ValueError):NEWLINE returnNEWLINENEWLINE return message.with_body(response)NEWLINENEWLINE# RegisterNEWLINENEWLINEdef register(bot):NEWLINE global BLACKLISTNEWLINENEWLINE config = bot.config.load_module_config('title')NEWLINE BLACKLIST = config.get('blacklist', BLACKLIST)NEWLINENEWLINE if config.get('disabled', False):NEWLINE return []NEWLINENEWLINE return (NEWLINE ('command', PATTERN, title),NEWLINE )NEWLINENEWLINE# vim: set sts=4 sw=4 ts=8 expandtab ft=python:NEWLINE
# -*- coding: utf-8 -*-NEWLINENEWLINEfrom django.core import validatorsNEWLINEfrom django.utils.deconstruct import deconstructibleNEWLINEfrom django.utils.translation import ungettext_lazyNEWLINENEWLINEfrom collectionfield.converter import CollectionConverterNEWLINENEWLINENEWLINEclass ItemValidatorMixin(object):NEWLINENEWLINE def __call__(self, value):NEWLINE validate = super(ItemValidatorMixin, self).__call__NEWLINE for item in value:NEWLINE validate(item)NEWLINENEWLINENEWLINE@deconstructibleNEWLINEclass ConvertedMaxLengthValidator(validators.MaxLengthValidator):NEWLINENEWLINE def __init__(self, limit_value, collection_type, item_type, sort,NEWLINE unique_items, delimiter, **kwargs):NEWLINE self.collection_type = collection_typeNEWLINE self.item_type = item_typeNEWLINE self.sort = sortNEWLINE self.unique_items = unique_itemsNEWLINE self.delimiter = delimiterNEWLINE super(ConvertedMaxLengthValidator, self).__init__(NEWLINE limit_value, **kwargsNEWLINE )NEWLINENEWLINE def clean(self, value):NEWLINE return super(ConvertedMaxLengthValidator, self).clean(NEWLINE CollectionConverter(NEWLINE collection_type=self.collection_type,NEWLINE item_type=self.item_type,NEWLINE sort=self.sort,NEWLINE unique_items=self.unique_items,NEWLINE delimiter=self.delimiterNEWLINE ).dump(value)NEWLINE )NEWLINENEWLINE def __eq__(self, other):NEWLINE return (NEWLINE isinstance(other, self.__class__) andNEWLINE self.limit_value == other.limit_value andNEWLINE self.message == other.message andNEWLINE self.code == other.code andNEWLINE self.collection_type == other.collection_type andNEWLINE self.item_type == other.item_type andNEWLINE self.sort == other.sort andNEWLINE self.unique_items == other.unique_items andNEWLINE self.delimiter == other.delimiterNEWLINE )NEWLINENEWLINENEWLINE@deconstructibleNEWLINEclass MaxItemsValidator(validators.MaxLengthValidator):NEWLINE message = ungettext_lazy(NEWLINE singular=(NEWLINE 'Ensure this value has at most %(limit_value)d item 'NEWLINE '(it has %(show_value)d).'NEWLINE ),NEWLINE plural=(NEWLINE 'Ensure this value has at most %(limit_value)d items 'NEWLINE '(it has %(show_value)d).'NEWLINE ),NEWLINE number='limit_value'NEWLINE )NEWLINE code = 'max_items'NEWLINENEWLINENEWLINE# Predefined item validators:NEWLINENEWLINE@deconstructibleNEWLINEclass ItemRegexValidator(ItemValidatorMixin, validators.RegexValidator):NEWLINE passNEWLINENEWLINENEWLINE@deconstructibleNEWLINEclass ItemURLValidator(ItemValidatorMixin, validators.URLValidator):NEWLINE passNEWLINENEWLINENEWLINE@deconstructibleNEWLINEclass ItemEmailValidator(ItemValidatorMixin, validators.EmailValidator):NEWLINE passNEWLINENEWLINENEWLINE@deconstructibleNEWLINEclass ItemMinValueValidator(ItemValidatorMixin, validators.MinValueValidator):NEWLINE passNEWLINENEWLINENEWLINE@deconstructibleNEWLINEclass ItemMaxValueValidator(ItemValidatorMixin, validators.MaxValueValidator):NEWLINE passNEWLINENEWLINENEWLINE@deconstructibleNEWLINEclass ItemMinLengthValidator(ItemValidatorMixin,NEWLINE validators.MinLengthValidator):NEWLINE passNEWLINENEWLINENEWLINE@deconstructibleNEWLINEclass ItemMaxLengthValidator(ItemValidatorMixin,NEWLINE validators.MaxLengthValidator):NEWLINE passNEWLINE
from rest_framework.status import HTTP_404_NOT_FOUNDNEWLINENEWLINENEWLINEERROR_GRID_DOES_NOT_EXIST = (NEWLINE "ERROR_GRID_DOES_NOT_EXIST",NEWLINE HTTP_404_NOT_FOUND,NEWLINE "The requested grid view does not exist.",NEWLINE)NEWLINE
from ast import BitAndNEWLINEimport importlibNEWLINEfrom cmath import cos, exp, log, log10, pi, sinNEWLINEimport matplotlib.pyplot as mpltNEWLINENEWLINE##################### ##################### #####################NEWLINE##################### ##################### #####################NEWLINENEWLINETWOPI = 2.0 * piNEWLINENEWLINEfs = 44100.0NEWLINEdt = 1.0 / fsNEWLINENEWLINEBW = 0.01NEWLINENEWLINEfc = 200.0NEWLINEbandwidth = 8000.0NEWLINEfc2 = fc + bandwidthNEWLINENEWLINEfc /= fsNEWLINEwc = TWOPI * fcNEWLINENEWLINEfc2 /= fsNEWLINEwc2 = TWOPI * fc2NEWLINENEWLINEmax = int( 4.0 / BW )NEWLINEmax += 1NEWLINENEWLINEprint( "kernelLength = ", max )NEWLINENEWLINEmiddle = int( max * 0.5 )NEWLINENEWLINE##################### NEWLINENEWLINEh = [0.0] * max NEWLINEw = [0.0] * maxNEWLINEtaps = [0.0] * maxNEWLINEx = [0.0] * maxNEWLINENEWLINE##################### NEWLINENEWLINEsum = 0NEWLINEi = 0NEWLINEfor n in range(-middle, middle):NEWLINENEWLINE nm = n + middleNEWLINENEWLINE w[i] = 0.42 - (0.5 * cos((TWOPI*i) / max)) + (0.08 * cos(((2.0*TWOPI) * i) / max))NEWLINENEWLINE if n == 0:NEWLINE h[nm] = (2.0 * fc2) - (2.0 * fc)NEWLINE else:NEWLINE h[nm] = (sin(wc2 * n)/(pi * n)) - (sin(wc * n)/(pi * n))NEWLINE NEWLINE h[nm] *= w[i] NEWLINE i += 1NEWLINENEWLINENEWLINE##################### ##################### #####################NEWLINE##################### ##################### #####################NEWLINENEWLINEnumberOfSeconds = 0.15NEWLINEsimulationLength = int( numberOfSeconds * fs )NEWLINENEWLINEsineSweepData = [0.0] * simulationLengthNEWLINENEWLINEstartFrequency = 1.0NEWLINEendFrequency = 20000.0NEWLINENEWLINET = numberOfSecondsNEWLINEtempOne = TWOPI * startFrequency * TNEWLINEtempTwo = TWOPI * endFrequency * TNEWLINEtempThree = log( tempTwo / tempOne )NEWLINEtempFour = tempOne / tempThreeNEWLINENEWLINEtime = 0.0NEWLINEfor i in range( 0, simulationLength ):NEWLINE sineSweepData[ i ] = sin( tempFour * (exp((time / T) * tempThree) - 1.0) )NEWLINE time += dtNEWLINENEWLINENEWLINE##################### ##################### #####################NEWLINE##################### ##################### #####################NEWLINENEWLINEconvolvedOutput = [0.0] * simulationLengthNEWLINEtemporary = [0.0] * maxNEWLINENEWLINExIndex = 0NEWLINEnewest = 0NEWLINENEWLINEfor i in range( 0, simulationLength ):NEWLINENEWLINE if newest == max:NEWLINE newest = 0NEWLINE NEWLINE temporary[ newest ] = sineSweepData[ i ]NEWLINE xIndex = newestNEWLINENEWLINE accum = 0.0NEWLINE kernel = 0.0NEWLINE for j in range( 0, max ):NEWLINENEWLINE accum += h[ j ] * temporary[ xIndex ]NEWLINE kernel += h[ j ]NEWLINENEWLINE xIndex -= 1NEWLINE if xIndex == -1:NEWLINE xIndex = max - 1NEWLINENEWLINE convolvedOutput[i] = accumNEWLINE newest += 1NEWLINE NEWLINE##################### ##################### #####################NEWLINE##################### ##################### #####################NEWLINENEWLINEfig, (ax1, ax2, ax3) = mplt.subplots(3)NEWLINENEWLINEax1.axis([ 0, max, -1.0, 1.0 ])NEWLINEax1.plot( h )NEWLINENEWLINEax2.axis([ 0, simulationLength, -1.1, 1.1])NEWLINEax2.plot( sineSweepData )NEWLINENEWLINEax3.axis([ 0, simulationLength, -1.1, 1.1])NEWLINEax3.plot( convolvedOutput )NEWLINENEWLINEmplt.show()
#!/usr/bin/env pythonNEWLINE#NEWLINE# Copyright (c) 2017 Amazon.com, Inc. or its affiliates. All RightsNEWLINE# Reserved.NEWLINE#NEWLINE# Additional copyrights may followNEWLINE#NEWLINENEWLINEimport osNEWLINEimport sysNEWLINEimport reNEWLINEimport argparseNEWLINEimport loggingNEWLINEimport timeNEWLINEimport shlexNEWLINEimport shutilNEWLINEimport requestsNEWLINEimport BuilderUtilsNEWLINENEWLINENEWLINE_cov_filename = 'coverity_tools.tgz'NEWLINENEWLINEdef run_coverity_internal(logger, build_root, source_tarball, config):NEWLINE # read the token fileNEWLINE file = open(config['token_file'], 'r')NEWLINE token = file.readline().rstrip('\n')NEWLINENEWLINE # get the toolNEWLINE if not os.path.isdir(config['tool_dir']):NEWLINE os.makedirs(config['tool_dir'])NEWLINE os.chdir(config['tool_dir'])NEWLINE timestamp = 0NEWLINE if os.path.exists(_cov_filename):NEWLINE timestamp = os.stat(_cov_filename).st_mtimeNEWLINE if (timestamp + (24 * 3600)) > int(time.time()):NEWLINE logger.debug('Reusing existing tarball')NEWLINE else:NEWLINE logger.debug('Downloading %s' % (config['tool_url']))NEWLINE # As of 9 Aug 2021, this file is 2+GB. Downloading it allNEWLINE # into a Python script and then writing it out to disk is notNEWLINE # a good idea on our limited resources AWS VM (meaning: itNEWLINE # brings the VM to a crawl). FromNEWLINE # https://stackoverflow.com/questions/38969164/coverity-scan-for-projects-outside-github,NEWLINE # we can use a command line tool to download, instead. It'sNEWLINE # not very Pythonic, but it doesn't bring our VM to its knees.NEWLINE cmd = [NEWLINE 'wget',NEWLINE config["tool_url"],NEWLINE '--post-data',NEWLINE f'token={token}&project={config["project_name"]}',NEWLINE '-O',NEWLINE _cov_filenameNEWLINE ]NEWLINE BuilderUtils.logged_call(cmd,NEWLINE log_file=os.path.join(build_root, 'coverity-tools-download-output.txt'))NEWLINENEWLINE # make sure we have a build rootNEWLINE if not os.path.isdir(build_root):NEWLINE os.makedirs(build_root)NEWLINE os.chdir(build_root)NEWLINENEWLINE # The name of the top-level directory in the tarball changes everyNEWLINE # time Coverity releases a new version of the tool. So searchNEWLINE # around and hope we find something.NEWLINE logger.debug('Expanding ' + _cov_filename)NEWLINE BuilderUtils.logged_call(['tar', 'xf', os.path.join(config['tool_dir'], _cov_filename)],NEWLINE log_file=os.path.join(build_root, 'coverity-tools-untar-output.txt'))NEWLINE cov_path=''NEWLINE for file in os.listdir(build_root):NEWLINE if file.startswith('cov-'):NEWLINE cov_path = os.path.join(build_root, file, 'bin')NEWLINE breakNEWLINE logger.debug('Found Coverity path %s' % (cov_path))NEWLINENEWLINE child_env = os.environ.copy()NEWLINE child_env['PATH'] = cov_path + ':' + child_env['PATH']NEWLINENEWLINE logger.debug('Extracting build tarball: %s' % (source_tarball))NEWLINE BuilderUtils.logged_call(['tar', 'xf', source_tarball],NEWLINE log_file=os.path.join(build_root, 'coverity-source-untar-output.txt'))NEWLINENEWLINE # guess the directory based on the tarball name. Don't worryNEWLINE # about the exception, because we want out in that case anyway...NEWLINE build_version = re.search('^' + config['project_prefix'] + '-(.*)\.tar\..*$',NEWLINE os.path.basename(source_tarball)).group(1)NEWLINE srcdir = config['project_prefix'] + '-' + build_versionNEWLINE os.chdir(srcdir)NEWLINENEWLINE logger.debug('coverity configure')NEWLINE args = ['./configure']NEWLINE if 'configure_args' in config:NEWLINE args.extend(shlex.split(config['configure_args']))NEWLINE BuilderUtils.logged_call(args, env=child_env,NEWLINE log_file=os.path.join(build_root, 'coverity-configure-output.txt'))NEWLINENEWLINE logger.debug('coverity build')NEWLINE args = ['cov-build', '--dir', 'cov-int', 'make']NEWLINE if 'make_args' in config:NEWLINE args.extend(shlex.split(config['make_args']))NEWLINE BuilderUtils.logged_call(args, env=child_env,NEWLINE log_file=os.path.join(build_root, 'coverity-make-output.txt'))NEWLINENEWLINE logger.debug('bundling results')NEWLINE results_tarball = os.path.join(build_root, 'analyzed.tar.bz2')NEWLINE BuilderUtils.logged_call(['tar', 'jcf', results_tarball, 'cov-int'],NEWLINE log_file=os.path.join(build_root, 'coverity-results-tar-output.txt'))NEWLINENEWLINE logger.debug('submitting results')NEWLINE url = 'https://scan.coverity.com/builds?project=' + config['project_name']NEWLINE files = { 'file': open(results_tarball, 'rb') }NEWLINE values = { 'email' : config['email'],NEWLINE 'version' : build_version,NEWLINE 'description' : 'nightly-master',NEWLINE 'token' : token }NEWLINE r = requests.post(url, files=files, data=values)NEWLINE r.raise_for_status()NEWLINENEWLINENEWLINEdef run_coverity(logger, build_root, source_tarball, config):NEWLINE """Run coverity test and submit resultsNEWLINENEWLINE Run Coverity test and submit results to their server. Can be runNEWLINE either standalone (with a tarball as a target) or integrated intoNEWLINE the Builder class.NEWLINENEWLINE """NEWLINE cwd = os.getcwd()NEWLINE try:NEWLINE run_coverity_internal(logger, build_root, source_tarball, config)NEWLINE finally:NEWLINE os.chdir(cwd)NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE config = { 'tool_url' : 'https://scan.coverity.com/download/cxx/linux64',NEWLINE 'log_level' : 'INFO' }NEWLINENEWLINE parser = argparse.ArgumentParser(description='Coverity submission script for Open MPI related projects')NEWLINE parser.add_argument('--log-level', help='Log level.', type=str,NEWLINE choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'])NEWLINE parser.add_argument('--build-root',NEWLINE help='Directory to use as base of build tree.',NEWLINE type=str)NEWLINE parser.add_argument('--source-tarball',NEWLINE help='Tarball to submit for analysis',NEWLINE type=str)NEWLINE parser.add_argument('--tool-dir',NEWLINE help='Directory in which to store downloaded tool (for reuse)',NEWLINE type=str)NEWLINE parser.add_argument('--tool-url',NEWLINE help='URL for downloading Coverity tool',NEWLINE type=str)NEWLINE parser.add_argument('--project-name',NEWLINE help='Coverity project name',NEWLINE type=str)NEWLINE parser.add_argument('--project-prefix',NEWLINE help='prefix of the tarball directory',NEWLINE type=str)NEWLINE parser.add_argument('--token-file',NEWLINE help='File containing the Coverity token for project',NEWLINE type=str)NEWLINE parser.add_argument('--configure-args',NEWLINE help='Configuration arguments for source tarball',NEWLINE type=str)NEWLINE parser.add_argument('--make-args',NEWLINE help='Build arguments for source tarball',NEWLINE type=str)NEWLINE parser.add_argument('--email',NEWLINE help='Coverity submission email address',NEWLINE type=str)NEWLINENEWLINE for key, value in vars(parser.parse_args()).iteritems():NEWLINE if not value == None:NEWLINE config[key] = valueNEWLINENEWLINE logging.basicConfig()NEWLINE logger = logging.getLogger()NEWLINE logger.setLevel(config['log_level'])NEWLINENEWLINE run_coverity(logger, config['build_root'], config['source_tarball'], config)NEWLINE
import torchNEWLINEfrom .base import BaseSchedulerNEWLINENEWLINENEWLINEclass TorchScheduler(BaseScheduler):NEWLINE def __init__(self, optimizer, name, priority=0, active=False, *args, **kwargs):NEWLINE super().__init__(active, priority)NEWLINE self.optimizer = optimizerNEWLINE self.scheduler = getattr(torch.optim.lr_scheduler,NEWLINE name)(optimizer=optimizer, *args, **kwargs)NEWLINENEWLINE def step(self, epoch):NEWLINE self.scheduler.step()NEWLINE
from service import ServiceScraper, ServiceSoundDetector, ServiceLanguageDetectorNEWLINENEWLINEif __name__ == "__main__":NEWLINE services = [ServiceScraper, ServiceSoundDetector, ServiceLanguageDetector]NEWLINENEWLINE for service in services:NEWLINE s = service()NEWLINE s.process()
class StatusAuditoria:NEWLINE CONCLUIDO = "OK"NEWLINE NAO_CONCLUIDO = "NOK"NEWLINE
from .tool.func import *NEWLINENEWLINEdef watch_list_2(conn, tool):NEWLINE curs = conn.cursor()NEWLINENEWLINE if tool == 'watch_list':NEWLINE div = load_lang("msg_whatchlist_lmt") + ' : 10 <hr class=\"main_hr\">'NEWLINE else:NEWLINE div = ''NEWLINENEWLINE ip = ip_check()NEWLINENEWLINE if ip_or_user(ip) != 0:NEWLINE return redirect('/login')NEWLINENEWLINENEWLINE curs.execute(db_change("delete from scan where user = ? and title = ''"), [ip])NEWLINE conn.commit()NEWLINENEWLINE if tool == 'watch_list':NEWLINE curs.execute(db_change("select title from scan where type = '' and user = ?"), [ip])NEWLINENEWLINE title_name = load_lang('watchlist')NEWLINE else:NEWLINE curs.execute(db_change("select title from scan where type = 'star' and user = ?"), [ip])NEWLINENEWLINE title_name = load_lang('star_doc')NEWLINENEWLINE data = curs.fetchall()NEWLINE for data_list in data:NEWLINE if tool == 'star_doc':NEWLINE curs.execute(db_change("select date from history where title = ? order by id + 0 desc limit 1"), [data_list[0]])NEWLINE get_data = curs.fetchall()NEWLINE if get_data:NEWLINE plus = '(' + get_data[0][0] + ') 'NEWLINE else:NEWLINE plus = ''NEWLINE else:NEWLINE plus = ''NEWLINENEWLINE div += '' + \NEWLINE '<li>' + \NEWLINE '<a href="/w/' + url_pas(data_list[0]) + '">' + data_list[0] + '</a> ' + \NEWLINE plus + \NEWLINE '<a href="/' + ('star_doc' if tool == 'star_doc' else 'watch_list') + '/' + url_pas(data_list[0]) + '">(' + load_lang('delete') + ')</a>' + \NEWLINE '</li>' + \NEWLINE ''NEWLINENEWLINE if data:NEWLINE div = '<ul>' + div + '</ul><hr class=\"main_hr\">'NEWLINENEWLINE div += '<a href="/manager/' + ('13' if tool == 'watch_list' else '16') + '">(' + load_lang('add') + ')</a>'NEWLINENEWLINE return easy_minify(flask.render_template(skin_check(),NEWLINE imp = [title_name, wiki_set(), custom(), other2([0, 0])],NEWLINE data = div,NEWLINE menu = [['user', load_lang('return')]]NEWLINE ))NEWLINE
# creating list out of dictionariesNEWLINENEWLINEpen_1 = {'color': 'black',NEWLINE 'price': '2.5',NEWLINE 'brand': 'faber castel'NEWLINE }NEWLINENEWLINEpen_2 = {'color': 'blue',NEWLINE 'price': '2.5',NEWLINE 'brand': 'faber castel'NEWLINE }NEWLINENEWLINEpen_3 = {'color': 'red',NEWLINE 'price': '2.5',NEWLINE 'brand': 'faber castel'NEWLINE }NEWLINENEWLINEall_pens = [pen_1, pen_2, pen_3]NEWLINENEWLINEprint(all_pens)
#! /usr/bin/env pythonNEWLINENEWLINE"""NEWLINEModule with functions for correcting bad pixels in cubes.NEWLINE"""NEWLINENEWLINENEWLINENEWLINE__author__ = 'Carlos Alberto Gomez Gonzalez, V. Christiaens'NEWLINE__all__ = ['frame_fix_badpix_isolated',NEWLINE 'cube_fix_badpix_isolated',NEWLINE 'cube_fix_badpix_annuli',NEWLINE 'cube_fix_badpix_clump']NEWLINENEWLINEimport numpy as npNEWLINEfrom skimage.draw import circle, ellipseNEWLINEfrom scipy.ndimage import median_filterNEWLINEfrom astropy.stats import sigma_clipped_statsNEWLINEfrom ..stats import sigma_filterNEWLINEfrom ..var import frame_center, get_annulus_segmentsNEWLINEfrom ..stats import clip_arrayNEWLINEfrom ..conf import timing, time_ini, ProgressbarNEWLINEfrom .cosmetics import approx_stellar_positionNEWLINENEWLINEimport warningsNEWLINEtry:NEWLINE from numba import njitNEWLINE no_numba = FalseNEWLINEexcept ImportError:NEWLINE msg = "Numba python bindings are missing."NEWLINE warnings.warn(msg, ImportWarning)NEWLINE no_numba = TrueNEWLINENEWLINEdef frame_fix_badpix_isolated(array, bpm_mask=None, sigma_clip=3, num_neig=5,NEWLINE size=5, protect_mask=False, radius=30,NEWLINE verbose=True):NEWLINE """ Corrects the bad pixels, marked in the bad pixel mask. The bad pixel isNEWLINE replaced by the median of the adjacent pixels. This function is very fastNEWLINE but works only with isolated (sparse) pixels.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE array : numpy ndarrayNEWLINE Input 2d array.NEWLINE bpm_mask : numpy ndarray, optionalNEWLINE Input bad pixel map. Zeros frame where the bad pixels have a value ofNEWLINE 1. If None is provided a bad pixel map will be created usingNEWLINE sigma clip statistics. NEWLINE sigma_clip : int, optionalNEWLINE In case no bad pixel mask is provided all the pixels above and belowNEWLINE sigma_clip*STDDEV will be marked as bad.NEWLINE num_neig : int, optionalNEWLINE The side of the square window around each pixel where the sigma clippedNEWLINE statistics are calculated (STDDEV and MEDIAN). If the value is equal toNEWLINE 0 then the statistics are computed in the whole frame.NEWLINE size : odd int, optionalNEWLINE The size the box (size x size) of adjacent pixels for the medianNEWLINE filter.NEWLINE protect_mask : bool, optionalNEWLINE If True a circular aperture at the center of the frames will beNEWLINE protected from any operation. With this we protect the star andNEWLINE vicinity.NEWLINE radius : int, optionalNEWLINE Radius of the circular aperture (at the center of the frames) for theNEWLINE protection mask.NEWLINE verbose : bool, optionalNEWLINE If True additional information will be printed.NEWLINENEWLINE ReturnNEWLINE ------NEWLINE frame : numpy ndarrayNEWLINE Frame with bad pixels corrected.NEWLINE """NEWLINE if array.ndim != 2:NEWLINE raise TypeError('Array is not a 2d array or single frame')NEWLINE if size % 2 == 0:NEWLINE raise TypeError('Size of the median blur kernel must be an odd integer')NEWLINENEWLINE if bpm_mask is not None:NEWLINE bpm_mask = bpm_mask.astype('bool')NEWLINENEWLINE if verbose: start = time_ini()NEWLINENEWLINE if num_neig > 0:NEWLINE neigh = TrueNEWLINE else:NEWLINE neigh = FalseNEWLINENEWLINE frame = array.copy()NEWLINE cy, cx = frame_center(frame)NEWLINE if bpm_mask is None:NEWLINE ind = clip_array(frame, sigma_clip, sigma_clip, neighbor=neigh,NEWLINE num_neighbor=num_neig, mad=True)NEWLINE bpm_mask = np.zeros_like(frame)NEWLINE bpm_mask[ind] = 1NEWLINE if protect_mask:NEWLINE cir = circle(cy, cx, radius)NEWLINE bpm_mask[cir] = 0NEWLINE bpm_mask = bpm_mask.astype('bool')NEWLINENEWLINE smoothed = median_filter(frame, size, mode='mirror')NEWLINE frame[np.where(bpm_mask)] = smoothed[np.where(bpm_mask)]NEWLINE array_out = frameNEWLINE count_bp = np.sum(bpm_mask)NEWLINE NEWLINE if verbose:NEWLINE msg = "/nDone replacing {} bad pixels using the median of neighbors"NEWLINE print(msg.format(count_bp))NEWLINE timing(start)NEWLINE return array_outNEWLINENEWLINENEWLINEdef cube_fix_badpix_isolated(array, bpm_mask=None, sigma_clip=3, num_neig=5, NEWLINE size=5, frame_by_frame=False, protect_mask=False, NEWLINE radius=30, verbose=True):NEWLINE """ Corrects the bad pixels, marked in the bad pixel mask. The bad pixel is NEWLINE replaced by the median of the adjacent pixels. This function is very fastNEWLINE but works only with isolated (sparse) pixels. NEWLINE NEWLINE ParametersNEWLINE ----------NEWLINE array : numpy ndarrayNEWLINE Input 3d array.NEWLINE bpm_mask : numpy ndarray, optionalNEWLINE Input bad pixel map. Zeros frame where the bad pixels have a value of 1.NEWLINE If None is provided a bad pixel map will be created per frame using NEWLINE sigma clip statistics.NEWLINE sigma_clip : int, optionalNEWLINE In case no bad pixel mask is provided all the pixels above and belowNEWLINE sigma_clip*STDDEV will be marked as bad. NEWLINE num_neig : int, optionalNEWLINE The side of the square window around each pixel where the sigma clippedNEWLINE statistics are calculated (STDDEV and MEDIAN). If the value is equal toNEWLINE 0 then the statistics are computed in the whole frame.NEWLINE size : odd int, optionalNEWLINE The size the box (size x size) of adjacent pixels for the median filter. NEWLINE frame_by_frame: bool, optionalNEWLINE Whether to correct bad pixels frame by frame in the cube. By default itNEWLINE is set to False; the bad pixels are computed on the mean frame of the NEWLINE stack (faster but not necessarily optimal).NEWLINE protect_mask : bool, optionalNEWLINE If True a circular aperture at the center of the frames will be NEWLINE protected from any operation. With this we protect the star and itsNEWLINE vicinity.NEWLINE radius : int, optional NEWLINE Radius of the circular aperture (at the center of the frames) for the NEWLINE protection mask.NEWLINE verbose : bool, optionalNEWLINE If True additional information will be printed.NEWLINE NEWLINE ReturnNEWLINE ------NEWLINE array_out : numpy ndarrayNEWLINE Cube with bad pixels corrected.NEWLINE """NEWLINE if array.ndim != 3:NEWLINE raise TypeError('Array is not a 3d array or cube')NEWLINE if size % 2 == 0:NEWLINE raise TypeError('Size of the median blur kernel must be an odd integer')NEWLINE NEWLINE if bpm_mask is not None:NEWLINE bpm_mask = bpm_mask.astype('bool')NEWLINE NEWLINE if verbose: start = time_ini()NEWLINE NEWLINE if num_neig > 0:NEWLINE neigh = TrueNEWLINE else:NEWLINE neigh = FalseNEWLINE NEWLINE cy, cx = frame_center(array[0])NEWLINE array_out = array.copy()NEWLINE n_frames = array.shape[0]NEWLINE count_bp = 0NEWLINE if frame_by_frame:NEWLINE for i in Progressbar(range(n_frames), desc="processing frames"):NEWLINE array_out[i] = frame_fix_badpix_isolated(array[i], bpm_mask=bpm_mask, NEWLINE sigma_clip=sigma_clip, NEWLINE num_neig=num_neig,NEWLINE size=size, NEWLINE protect_mask=protect_mask, NEWLINE radius=radius,NEWLINE verbose=False,NEWLINE debug=False)NEWLINE if verbose: NEWLINE bpm = np.where(array_out[i]!=array[i]) NEWLINE count_bp+=np.sum(np.ones_like(array_out[i])[bpm]) NEWLINE else: NEWLINE if bpm_mask is None:NEWLINE ind = clip_array(np.mean(array, axis=0), sigma_clip, sigma_clip,NEWLINE neighbor=neigh, num_neighbor=num_neig, mad=True)NEWLINE bpm_mask = np.zeros_like(array[0])NEWLINE bpm_mask[ind] = 1NEWLINE if protect_mask:NEWLINE cir = circle(cy, cx, radius)NEWLINE bpm_mask[cir] = 0NEWLINE bpm_mask = bpm_mask.astype('bool')NEWLINE NEWLINE for i in Progressbar(range(n_frames), desc="processing frames"):NEWLINE frame = array_out[i]NEWLINE smoothed = median_filter(frame, size, mode='mirror')NEWLINE frame[np.where(bpm_mask)] = smoothed[np.where(bpm_mask)]NEWLINE if verbose: NEWLINE count_bp+=np.sum(bpm_mask) NEWLINE NEWLINE if verbose: NEWLINE msg = "/nDone replacing {} bad pixels using the median of neighbors"NEWLINE print(msg.format(count_bp))NEWLINE timing(start)NEWLINE return array_outNEWLINENEWLINENEWLINEdef cube_fix_badpix_annuli(array, fwhm, cy=None, cx=None, sig=5., NEWLINE protect_psf=True, r_in_std=10, r_out_std=None, NEWLINE verbose=True, half_res_y=False, min_thr=None, NEWLINE max_thr=None, full_output=False):NEWLINE """NEWLINE Function to correct the bad pixels annulus per annulus (centered on the NEWLINE provided location of the star), in an input frame or cube.NEWLINE This function is MUCH FASTER than bp_clump_removal (about 20 times faster);NEWLINE hence to be prefered in all cases where there is only one bright source.NEWLINE The bad pixel values are replaced by: ann_median + ann_stddev*random_gauss;NEWLINE where ann_median is the median of the annulus, ann_stddev is the standard NEWLINE deviation in the annulus, and random_gauss is a random factor picked from a NEWLINE gaussian distribution centered on 0 and with variance 1.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE array : 3D or 2D array NEWLINE Input 3d cube or 2d image.NEWLINE fwhm: float or 1D arrayNEWLINE Vector containing the full width half maximum of the PSF in pixels, for NEWLINE each channel (cube_like); or single value (frame_like)NEWLINE cy, cx : None, float or 1D array, optionalNEWLINE If None: will use the barycentre of the image found by NEWLINE photutils.centroid_com()NEWLINE If floats: coordinates of the center, assumed to be the same in all NEWLINE frames if the input is a cube.NEWLINE If 1D arrays: they must be the same length as the 0th dimension of theNEWLINE input cube.NEWLINE sig: Float scalar, optionalNEWLINE Number of stddev above or below the median of the pixels in the same NEWLINE annulus, to consider a pixel as bad.NEWLINE protect_psf: bool, {True, False}, optionalNEWLINE Whether to protect a circular region centered on the star (1.8*fwhm NEWLINE radius) from any bpix corr. If False, there is a risk of modifying a NEWLINE centroid peak value if it is too "peaky"; but if True real bad pixels NEWLINE within the core are not corrected.NEWLINE r_in_std: float, optionalNEWLINE Inner radius in fwhm for the calculation of the standard NEWLINE deviation of the background - used for min threshold NEWLINE to consider bad pixels. Default: 10 FWHM.NEWLINE r_out_std: float or None, optionalNEWLINE Outer radius in fwhm for the calculation of the standard NEWLINE deviation of the background - used for min threshold NEWLINE to consider bad pixels. If set to None, the default will be to NEWLINE consider the largest annulus that fits within the frame.NEWLINE verbose: bool, {False, True}, optionalNEWLINE Whether to print out the number of bad pixels in each frame. NEWLINE half_res_y: bool, {True,False}, optionalNEWLINE Whether the input data have only half the angular resolution vertically NEWLINE compared to horizontally (e.g. SINFONI data).NEWLINE The algorithm will then correct the bad pixels every other row.NEWLINE min_thr, max_thr: {None,float}, optionalNEWLINE Any pixel whose value is lower (resp. larger) than this threshold will NEWLINE be automatically considered bad and hence sigma_filtered. If None, it NEWLINE is not used.NEWLINE full_output: bool, {False,True}, optionalNEWLINE Whether to return as well the cube of bad pixel maps and the cube of NEWLINE defined annuli.NEWLINENEWLINE Returns:NEWLINE --------NEWLINE obj_tmp: 2d or 3d array; the bad pixel corrected frame/cube.NEWLINE If full_output is set to True, it returns as well:NEWLINE bpix_map: 2d or 3d array; the bad pixel map or the cube of bpix mapsNEWLINE ann_frame_cumul: 2 or 3d array; the cube of defined annuliNEWLINE """NEWLINENEWLINE obj_tmp = array.copy()NEWLINE ndims = obj_tmp.ndimNEWLINE assert ndims == 2 or ndims == 3, "Object is not two or three dimensional.\n"NEWLINENEWLINE #thresholdsNEWLINE if min_thr is None:NEWLINE min_thr = np.amin(obj_tmp)-1NEWLINE if max_thr is None:NEWLINE max_thr = np.amax(obj_tmp)-1NEWLINENEWLINE def bp_removal_2d(obj_tmp, cy, cx, fwhm, sig, protect_psf, r_in_std,NEWLINE r_out_std, verbose):NEWLINENEWLINE n_x = obj_tmp.shape[1]NEWLINE n_y = obj_tmp.shape[0]NEWLINENEWLINE # Squash the frame if twice less resolved vertically than horizontallyNEWLINE if half_res_y:NEWLINE if n_y % 2 != 0:NEWLINE msg = 'The input frames do not have of an even number of rows. 'NEWLINE msg2 = 'Hence, you should not use option half_res_y = True'NEWLINE raise ValueError(msg+msg2)NEWLINE n_y = int(n_y/2)NEWLINE cy = int(cy/2)NEWLINE frame = obj_tmp.copy()NEWLINE obj_tmp = np.zeros([n_y,n_x])NEWLINE for yy in range(n_y):NEWLINE obj_tmp[yy] = frame[2*yy]NEWLINENEWLINE #1/ Stddev of background NEWLINE if r_in_std or r_out_std:NEWLINE r_in_std = min(r_in_std*fwhm,cx-2, cy-2,n_x-cx-2,n_y-cy-2)NEWLINE if r_out_std:NEWLINE r_out_std *= fwhmNEWLINE else:NEWLINE r_out_std = min(n_y-(cy+r_in_std), cy-r_in_std, NEWLINE n_x-(cx+r_in_std), cx-r_in_std)NEWLINE ceny, cenx = frame_center(obj_tmp)NEWLINE width = max(2,r_out_std-r_in_std)NEWLINE obj_tmp_crop = get_annulus_segments(obj_tmp, r_in_std, width, NEWLINE mode="val")NEWLINE else:NEWLINE obj_tmp_crop = obj_tmpNEWLINE _, _, stddev = sigma_clipped_stats(obj_tmp_crop, sigma=2.5)NEWLINENEWLINE #2/ Define each annulus, its median and stddevNEWLINE NEWLINE ymax = max(cy, n_y-cy)NEWLINE xmax = max(cx, n_x-cx)NEWLINE if half_res_y:NEWLINE ymax *= 2NEWLINE rmax = np.sqrt(ymax**2+xmax**2)NEWLINE # the annuli definition is optimized for Airy ringsNEWLINE ann_width = max(1.5, 0.5*fwhm) #0.61*fwhmNEWLINE nrad = int(rmax/ann_width)+1NEWLINE d_bord_max = max(n_y-cy, cy, n_x-cx, cx)NEWLINE if half_res_y:NEWLINE d_bord_max = max(2*(n_y-cy), 2*cy, n_x-cx, cx)NEWLINENEWLINE big_ell_frame = np.zeros_like(obj_tmp)NEWLINE sma_ell_frame = np.zeros_like(obj_tmp)NEWLINE ann_frame_cumul = np.zeros_like(obj_tmp)NEWLINE n_neig = np.zeros(nrad, dtype=np.int16)NEWLINE med_neig = np.zeros(nrad)NEWLINE std_neig = np.zeros(nrad)NEWLINE neighbours = np.zeros([nrad,n_y*n_x])NEWLINENEWLINE for rr in range(nrad):NEWLINE if rr > int(d_bord_max/ann_width):NEWLINE # just to merge farthest annuli with very few elements NEWLINE rr_big = nrad NEWLINE rr_sma = int(d_bord_max/ann_width)NEWLINE else: NEWLINE rr_big = rrNEWLINE rr_sma= rrNEWLINE if half_res_y:NEWLINE big_ell_idx = ellipse(cy=cy, cx=cx, NEWLINE r_radius=((rr_big+1)*ann_width)/2, NEWLINE c_radius=(rr_big+1)*ann_width, NEWLINE shape=(n_y,n_x))NEWLINE if rr != 0:NEWLINE small_ell_idx = ellipse(cy=cy, cx=cx, NEWLINE r_radius=(rr_sma*ann_width)/2, NEWLINE c_radius=rr_sma*ann_width, NEWLINE shape=(n_y,n_x))NEWLINE else:NEWLINE big_ell_idx = circle(cy, cx, radius=(rr_big+1)*ann_width,NEWLINE shape=(n_y,n_x))NEWLINE if rr != 0:NEWLINE small_ell_idx = circle(cy, cx, radius=rr_sma*ann_width, NEWLINE shape=(n_y,n_x))NEWLINE big_ell_frame[big_ell_idx] = 1NEWLINE if rr!=0: sma_ell_frame[small_ell_idx] = 1NEWLINE ann_frame = big_ell_frame - sma_ell_frameNEWLINE n_neig[rr] = ann_frame[np.where(ann_frame)].shape[0]NEWLINE neighbours[rr,:n_neig[rr]] = obj_tmp[np.where(ann_frame)]NEWLINE ann_frame_cumul[np.where(ann_frame)] = rrNEWLINENEWLINE # We delete iteratively max and min outliers in each annulus, NEWLINE # so that the annuli median and stddev are not corrupted by bpixsNEWLINE neigh = neighbours[rr,:n_neig[rr]]NEWLINE n_rm = 0NEWLINE n_pix_init = neigh.shape[0]NEWLINE while neigh.shape[0] >= np.amin(n_neig[rr]) and n_rm < n_pix_init/5:NEWLINE min_neigh = np.amin(neigh)NEWLINE if reject_outliers(neigh, min_neigh, m=5, stddev=stddev):NEWLINE min_idx = np.argmin(neigh)NEWLINE neigh = np.delete(neigh,min_idx)NEWLINE n_rm += 1NEWLINE else:NEWLINE max_neigh = np.amax(neigh)NEWLINE if reject_outliers(neigh, max_neigh, m=5, NEWLINE stddev=stddev):NEWLINE max_idx = np.argmax(neigh)NEWLINE neigh = np.delete(neigh,max_idx)NEWLINE n_rm += 1NEWLINE else: breakNEWLINE n_neig[rr] = neigh.shape[0]NEWLINE neighbours[rr,:n_neig[rr]] = neighNEWLINE neighbours[rr,n_neig[rr]:] = 0NEWLINE med_neig[rr] = np.median(neigh)NEWLINE std_neig[rr] = np.std(neigh)NEWLINE NEWLINE #3/ Create a tuple-array with coordinates of a circle of radius 1.8*fwhmNEWLINE # centered on the provided coordinates of the starNEWLINE if protect_psf:NEWLINE if half_res_y: NEWLINE circl_new = ellipse(cy, cx, r_radius=0.9*fwhm, NEWLINE c_radius=1.8*fwhm, shape=(n_y,n_x))NEWLINE else: NEWLINE circl_new = circle(cy, cx, radius=1.8*fwhm, NEWLINE shape=(n_y, n_x))NEWLINE else: circl_new = []NEWLINENEWLINE #4/ Loop on all pixels to check bpixNEWLINE bpix_map = np.zeros_like(obj_tmp)NEWLINE obj_tmp_corr = obj_tmp.copy()NEWLINE obj_tmp_corr, bpix_map = correct_ann_outliers(obj_tmp, ann_width, sig, NEWLINE med_neig, std_neig, cy, NEWLINE cx, min_thr, max_thr, NEWLINE stddev, half_res_y)NEWLINENEWLINE #5/ Count bpix and uncorrect if within the circleNEWLINE nbpix_tot = np.sum(bpix_map)NEWLINE nbpix_tbc = nbpix_tot - np.sum(bpix_map[circl_new])NEWLINE bpix_map[circl_new] = 0NEWLINE obj_tmp_corr[circl_new] = obj_tmp[circl_new]NEWLINE if verbose:NEWLINE print(nbpix_tot, ' bpix in total, and ', nbpix_tbc, ' corrected.')NEWLINENEWLINE # Unsquash all the framesNEWLINE if half_res_y:NEWLINE frame = obj_tmp_corr.copy()NEWLINE frame_bpix = bpix_map.copy()NEWLINE n_y = 2*n_yNEWLINE obj_tmp_corr = np.zeros([n_y,n_x])NEWLINE bpix_map = np.zeros([n_y,n_x])NEWLINE ann_frame = ann_frame_cumul.copy()NEWLINE ann_frame_cumul = np.zeros([n_y,n_x])NEWLINE for yy in range(n_y):NEWLINE obj_tmp_corr[yy] = frame[int(yy/2)]NEWLINE bpix_map[yy] = frame_bpix[int(yy/2)]NEWLINE ann_frame_cumul[yy] = ann_frame[int(yy/2)]NEWLINENEWLINE return obj_tmp_corr, bpix_map, ann_frame_cumulNEWLINENEWLINENEWLINENEWLINE if ndims == 2:NEWLINE if cy is None or cx is None:NEWLINE cen = approx_stellar_position([obj_tmp], fwhm)NEWLINE cy = cen[0,0]NEWLINE cx = cen[0,1]NEWLINE obj_tmp, bpix_map, ann_frame_cumul = bp_removal_2d(obj_tmp, cy, cx, NEWLINE fwhm, sig, NEWLINE protect_psf, NEWLINE r_in_std, r_out_std,NEWLINE verbose)NEWLINE if ndims == 3:NEWLINE n_z = obj_tmp.shape[0]NEWLINE bpix_map = np.zeros_like(obj_tmp)NEWLINE ann_frame_cumul = np.zeros_like(obj_tmp)NEWLINE if isinstance(fwhm, (int,float)):NEWLINE fwhm = [fwhm]*n_zNEWLINE if cy is None or cx is None:NEWLINE cen = approx_stellar_position(obj_tmp, fwhm)NEWLINE cy = cen[:,0]NEWLINE cx = cen[:,1]NEWLINE elif isinstance(cy, (float,int)) and isinstance(cx, (float,int)): NEWLINE cy = [cy]*n_zNEWLINE cx = [cx]*n_zNEWLINE for i in range(n_z):NEWLINE if verbose:NEWLINE print('************Frame # ', i,' *************')NEWLINE print('centroid assumed at coords:',cx[i],cy[i]) NEWLINE res_i = bp_removal_2d(obj_tmp[i], cy[i], cx[i], fwhm[i], sig,NEWLINE protect_psf, r_in_std, r_out_std, verbose)NEWLINE obj_tmp[i], bpix_map[i], ann_frame_cumul[i] = res_iNEWLINE NEWLINE if full_output:NEWLINE return obj_tmp, bpix_map, ann_frame_cumulNEWLINE else:NEWLINE return obj_tmpNEWLINENEWLINENEWLINEdef cube_fix_badpix_clump(array, bpm_mask=None, cy=None, cx=None, fwhm=4., NEWLINE sig=4., protect_psf=True, verbose=True, NEWLINE half_res_y=False, min_thr=None, max_nit=15, NEWLINE full_output=False):NEWLINE """NEWLINE Function to correct clumps of bad pixels. Very fast when a bad pixel map is NEWLINE provided. If a bad pixel map is not provided, the bad pixel clumps will be NEWLINE searched iteratively and replaced by the median of good neighbouring pixel NEWLINE values if enough of them. The size of the box is set by the closest odd NEWLINE integer larger than fwhm (to avoid accidentally replacing a companion).NEWLINENEWLINENEWLINENEWLINE ParametersNEWLINE ----------NEWLINE array : 3D or 2D array NEWLINE Input 3d cube or 2d image.NEWLINE bpix_map: 3D or 2D array, optNEWLINE Input bad pixel array. Should have same dimenstions as array. If notNEWLINE provided, the algorithm will attempt to identify bad pixel clumpsNEWLINE automatically.NEWLINE cy,cx : float or 1D array. optNEWLINE Vector with approximate y and x coordinates of the star for each channelNEWLINE (cube_like), or single 2-elements vector (frame_like). Should be NEWLINE provided if bpix_map is None and protect_psf set to True.NEWLINE fwhm: float or 1D array, optNEWLINE Vector containing the full width half maximum of the PSF in pixels, forNEWLINE each channel (cube_like); or single value (frame_like). Shouod be NEWLINE provided if bpix map is None.NEWLINE sig: float, optionalNEWLINE Value representing the number of "sigmas" above or below the "median" ofNEWLINE the neighbouring pixel, to consider a pixel as bad. See details on NEWLINE parameter "m" of function reject_outlier.NEWLINE protect_psf: bool, {True, False}, optionalNEWLINE True if you want to protect a circular region centered on the star NEWLINE (1.8*fwhm radius) from any bpix corr. If False, there is a risk to NEWLINE modify a psf peak value; but if True, real bpix within the core are NEWLINE not corrected.NEWLINE verbose: bool, {False,True}, optionalNEWLINE Whether to print the number of bad pixels and number of iterations NEWLINE required for each frame.NEWLINE half_res_y: bool, {True,False}, optionalNEWLINE Whether the input data has only half the angular resolution vertically NEWLINE compared to horizontally (e.g. the case of SINFONI data); in other wordsNEWLINE there are always 2 rows of pixels with exactly the same values.NEWLINE The algorithm will just consider every other row (hence making itNEWLINE twice faster), then apply the bad pixel correction on all rows.NEWLINE min_thr: float or None, optNEWLINE If provided, corresponds to a minimum absolute threshold below whichNEWLINE pixels are not considered bad (can be used to avoid the identificationNEWLINE of bad pixels within noise).NEWLINE max_nit: float, optionalNEWLINE Maximum number of iterations on a frame to correct bpix. Typically, it NEWLINE should be set to less than ny/2 or nx/2. This is a mean of precaution inNEWLINE case the algorithm gets stuck with 2 neighbouring pixels considered bpixNEWLINE alternately on two consecutively iterations hence leading to an infiniteNEWLINE loop (very very rare case).NEWLINE full_output: bool, {False,True}, optionalNEWLINE Whether to return as well the cube of bad pixel maps and the cube of NEWLINE defined annuli.NEWLINENEWLINE Returns:NEWLINE --------NEWLINE obj_tmp: 2d or 3d array; the bad pixel corrected frame/cube.NEWLINE If full_output is set to True, it returns as well:NEWLINE bpix_map: 2d or 3d array; the bad pixel map or the cube of bpix mapsNEWLINE """NEWLINENEWLINE obj_tmp = array.copy()NEWLINE ndims = obj_tmp.ndimNEWLINE assert ndims == 2 or ndims == 3, "Object is not two or three dimensional.\n"NEWLINENEWLINE if bpm_mask is not None:NEWLINE if bpm_mask.shape[-2:] != array.shape[-2:]:NEWLINE raise TypeError("Bad pixel map has wrong y/x dimensions.")NEWLINENEWLINE def bp_removal_2d(obj_tmp, cy, cx, fwhm, sig, protect_psf, min_thr, verbose): NEWLINE n_x = obj_tmp.shape[1]NEWLINE n_y = obj_tmp.shape[0]NEWLINENEWLINE if half_res_y:NEWLINE if n_y%2 != 0: NEWLINE msg = 'The input frames do not have of an even number of rows. 'NEWLINE msg2 = 'Hence, you should not use option half_res_y = True'NEWLINE raise ValueError(msg+msg2)NEWLINE n_y = int(n_y/2)NEWLINE frame = obj_tmp.copy()NEWLINE obj_tmp = np.zeros([n_y,n_x])NEWLINE for yy in range(n_y):NEWLINE obj_tmp[yy] = frame[2*yy]NEWLINE NEWLINE fwhm_round = int(round(fwhm))NEWLINE # This should reduce the chance to accidently correct a bright planet:NEWLINE if fwhm_round % 2 == 0:NEWLINE neighbor_box = max(3, fwhm_round+1) NEWLINE else:NEWLINE neighbor_box = max(3, fwhm_round)NEWLINE nneig = sum(np.arange(3, neighbor_box+2, 2))NEWLINENEWLINE NEWLINE #1/ Create a tuple-array with coordinates of a circle of radius 1.8*fwhmNEWLINE # centered on the approximate coordinates of the starNEWLINE if protect_psf:NEWLINE if half_res_y: NEWLINE circl_new = ellipse(int(cy/2), cx, r_radius=0.9*fwhm, NEWLINE c_radius=1.8*fwhm, shape=(n_y, n_x))NEWLINE else: circl_new = circle(cy, cx, radius=1.8*fwhm, NEWLINE shape=(n_y, n_x))NEWLINE else: circl_new = []NEWLINE NEWLINENEWLINE #3/ Create a bad pixel map, by detecting them with clip_arrayNEWLINE bp=clip_array(obj_tmp, sig, sig, out_good=False, neighbor=True,NEWLINE num_neighbor=neighbor_box, mad=True)NEWLINE bpix_map = np.zeros_like(obj_tmp) NEWLINE bpix_map[bp] = 1 NEWLINE nbpix_tot = np.sum(bpix_map)NEWLINE bpix_map[circl_new] = 0NEWLINE if min_thr is not None:NEWLINE bpix_map[np.where(np.abs(obj_tmp)<min_thr)] = 0NEWLINE nbpix_tbc = np.sum(bpix_map)NEWLINE bpix_map_cumul = np.zeros_like(bpix_map)NEWLINE bpix_map_cumul[:] = bpix_map[:]NEWLINE nit = 0NEWLINENEWLINE #4/ Loop over the bpix correction with sigma_filter, until 0 bpix leftNEWLINE while nbpix_tbc > 0 and nit < max_nit:NEWLINE nit = nit+1NEWLINE if verbose:NEWLINE print("Iteration {}: {} bpix in total, {} to be "NEWLINE "corrected".format(nit, nbpix_tot, nbpix_tbc))NEWLINE obj_tmp = sigma_filter(obj_tmp, bpix_map, neighbor_box=neighbor_box,NEWLINE min_neighbors=nneig, verbose=verbose)NEWLINE bp=clip_array(obj_tmp, sig, sig, out_good=False, neighbor=True,NEWLINE num_neighbor=neighbor_box, mad=True)NEWLINE bpix_map = np.zeros_like(obj_tmp) NEWLINE bpix_map[bp] = 1NEWLINE nbpix_tot = np.sum(bpix_map)NEWLINE bpix_map[circl_new] = 0NEWLINE if min_thr is not None:NEWLINE bpix_map[np.where(np.abs(obj_tmp)<min_thr)] = 0NEWLINE nbpix_tbc = np.sum(bpix_map)NEWLINE bpix_map_cumul = bpix_map_cumul+bpix_mapNEWLINENEWLINE if verbose:NEWLINE print('All bad pixels are corrected.')NEWLINE NEWLINE if half_res_y:NEWLINE frame = obj_tmp.copy()NEWLINE frame_bpix = bpix_map_cumul.copy()NEWLINE n_y = 2*n_yNEWLINE obj_tmp = np.zeros([n_y,n_x])NEWLINE bpix_map_cumul = np.zeros([n_y,n_x])NEWLINE for yy in range(n_y):NEWLINE obj_tmp[yy] = frame[int(yy/2)]NEWLINE bpix_map_cumul[yy] = frame_bpix[int(yy/2)]NEWLINENEWLINE return obj_tmp, bpix_map_cumulNEWLINENEWLINE if ndims == 2:NEWLINE if bpm_mask is None:NEWLINE if (cy is None or cx is None) and protect_psf:NEWLINE cen = approx_stellar_position([obj_tmp], fwhm)NEWLINE cy = cen[0,0]NEWLINE cx = cen[0,1]NEWLINE obj_tmp, bpix_map_cumul = bp_removal_2d(obj_tmp, cy, cx, fwhm, sig, NEWLINE protect_psf, min_thr, NEWLINE verbose)NEWLINE else:NEWLINE fwhm_round = int(round(fwhm))NEWLINE fwhm_round = fwhm_round+1-(fwhm_round%2) # make it oddNEWLINE neighbor_box = max(3, fwhm_round) # to not replace a companionNEWLINE nneig = sum(np.arange(3, neighbor_box+2, 2))NEWLINE obj_tmp = sigma_filter(obj_tmp, bpm_mask, neighbor_box, nneig, NEWLINE verbose)NEWLINE bpix_map_cumul = bpm_maskNEWLINE NEWLINE if ndims == 3:NEWLINE n_z = obj_tmp.shape[0]NEWLINE if bpm_mask is None:NEWLINE if cy is None or cx is None:NEWLINE cen = approx_stellar_position(obj_tmp, fwhm)NEWLINE cy = cen[:,0]NEWLINE cx = cen[:,1]NEWLINE elif isinstance(cy, (float,int)) and isinstance(cx, (float,int)): NEWLINE cy = [cy]*n_zNEWLINE cx = [cx]*n_zNEWLINE if isinstance(fwhm, (float,int)):NEWLINE fwhm = [fwhm]*n_zNEWLINE bpix_map_cumul = np.zeros_like(obj_tmp)NEWLINE for i in range(n_z):NEWLINE if verbose: print('************Frame # ', i,' *************')NEWLINE obj_tmp[i], bpix_map_cumul[i] = bp_removal_2d(obj_tmp[i], cy[i], NEWLINE cx[i], fwhm[i], sig, NEWLINE protect_psf, NEWLINE min_thr, verbose)NEWLINE else:NEWLINE if isinstance(fwhm, (float,int)):NEWLINE fwhm_round = int(round(fwhm))NEWLINE else:NEWLINE fwhm_round = int(np.median(fwhm))NEWLINE fwhm_round = fwhm_round+1-(fwhm_round%2) # make it oddNEWLINE neighbor_box = max(3, fwhm_round) # to not replace a companionNEWLINE nneig = sum(np.arange(3, neighbor_box+2, 2))NEWLINE for i in range(n_z):NEWLINE if verbose: print('************Frame # ', i,' *************')NEWLINE if bpm_mask.ndim == 3:NEWLINE bpm = bpm_mask[i]NEWLINE else:NEWLINE bpm = bpm_maskNEWLINE obj_tmp[i] = sigma_filter(obj_tmp[i], bpm, neighbor_box, NEWLINE nneig, verbose)NEWLINE bpix_map_cumul = bpm_maskNEWLINE NEWLINE if full_output:NEWLINE return obj_tmp, bpix_map_cumulNEWLINE else:NEWLINE return obj_tmpNEWLINE NEWLINE NEWLINEdef find_outliers(frame, sig_dist, in_bpix=None, stddev=None, neighbor_box=3,NEWLINE min_thr=None, mid_thr=None):NEWLINE """ Provides a bad pixel (or outlier) map for a given frame.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE frame: 2d array NEWLINE Input 2d image.NEWLINE sig_dist: floatNEWLINE Threshold used to discriminate good from bad neighbours, in terms of NEWLINE normalized distance to the median value of the set (see reject_outliers)NEWLINE in_bpix: 2d array, optionalNEWLINE Input bpix map (typically known from the previous iteration), to only NEWLINE look for bpix around those locations.NEWLINE neighbor_box: int, optionalNEWLINE The side of the square window around each pixel where the sigma and NEWLINE median are calculated for the bad pixel DETECTION and CORRECTION.NEWLINE min_thr: {None,float}, optionalNEWLINE Any pixel whose value is lower than this threshold (expressed in adu)NEWLINE will be automatically considered bad and hence sigma_filtered. If None,NEWLINE it is not used.NEWLINE mid_thr: {None, float}, optionalNEWLINE Pixels whose value is lower than this threshold (expressed in adu) willNEWLINE have its neighbours checked; if there is at max. 1 neighbour pixel whoseNEWLINE value is lower than mid_thr+(5*stddev), then the pixel is considered badNEWLINE (because it means it is a cold pixel in the middle of significant NEWLINE signal). If None, it is not used.NEWLINENEWLINE ReturnsNEWLINE -------NEWLINE bpix_map : numpy ndarrayNEWLINE Output cube with frames indicating the location of bad pixels"""NEWLINENEWLINE ndims = len(frame.shape)NEWLINE assert ndims == 2, "Object is not two dimensional.\n"NEWLINENEWLINE nx = frame.shape[1]NEWLINE ny = frame.shape[0]NEWLINE bpix_map = np.zeros_like(frame)NEWLINE if stddev is None: stddev = np.std(frame)NEWLINE half_box = int(neighbor_box/2)NEWLINE NEWLINE if in_bpix is None:NEWLINE for xx in range(nx):NEWLINE for yy in range(ny):NEWLINE #0/ Determine the box of neighbouring pixelsNEWLINE # half size of the box at the bottom of the pixelNEWLINE hbox_b = min(half_box, yy) NEWLINE # half size of the box at the top of the pixelNEWLINE hbox_t = min(half_box, ny-1-yy) NEWLINE # half size of the box to the left of the pixelNEWLINE hbox_l = min(half_box, xx)NEWLINE # half size of the box to the right of the pixel NEWLINE hbox_r = min(half_box, nx-1-xx) NEWLINE # but in case we are at an edge, we want to extend the box by NEWLINE # one row/column of px in the direction opposite to the edge:NEWLINE if yy > ny-1-half_box:NEWLINE hbox_b = hbox_b + (yy-(ny-1-half_box))NEWLINE elif yy < half_box:NEWLINE hbox_t = hbox_t+(half_box-yy)NEWLINE if xx > nx-1-half_box:NEWLINE hbox_l = hbox_l + (xx-(nx-1-half_box))NEWLINE elif xx < half_box:NEWLINE hbox_r = hbox_r+(half_box-xx)NEWLINENEWLINE #1/ list neighbouring pixels, >8 (NOT including pixel itself)NEWLINE neighbours = frame[yy-hbox_b:yy+hbox_t+1,NEWLINE xx-hbox_l:xx+hbox_r+1]NEWLINE idx_px = ([[hbox_b],[hbox_l]])NEWLINE flat_idx = np.ravel_multi_index(idx_px,(hbox_t+hbox_b+1,NEWLINE hbox_r+hbox_l+1))NEWLINE neighbours = np.delete(neighbours,flat_idx)NEWLINENEWLINE #2/ Det if central pixel is outlierNEWLINE test_result = reject_outliers(neighbours, frame[yy,xx], NEWLINE m=sig_dist, stddev=stddev, NEWLINE min_thr=min_thr, mid_thr=mid_thr)NEWLINENEWLINE #3/ Assign the value of the test to bpix_mapNEWLINE bpix_map[yy,xx] = test_resultNEWLINENEWLINE else:NEWLINE nb = int(np.sum(in_bpix)) # number of bad pixels at previous iterationNEWLINE wb = np.where(in_bpix) # pixels to checkNEWLINE bool_bpix= np.zeros_like(in_bpix)NEWLINE for n in range(nb):NEWLINE for yy in [max(0,wb[0][n]-half_box),wb[0][n],min(ny-1,wb[0][n]+half_box)]:NEWLINE for xx in [max(0,wb[1][n]-half_box),wb[1][n],min(ny-1,wb[1][n]+half_box)]:NEWLINE bool_bpix[yy,xx] = 1NEWLINE nb = int(np.sum(bool_bpix))# true number of px to check (including NEWLINE # neighbours of bpix from previous iteration)NEWLINE wb = np.where(bool_bpix) # true px to checkNEWLINE for n in range(nb):NEWLINE #0/ Determine the box of neighbouring pixelsNEWLINE # half size of the box at the bottom of the pixelNEWLINE hbox_b = min(half_box,wb[0][n])NEWLINE # half size of the box at the top of the pixel NEWLINE hbox_t = min(half_box,ny-1-wb[0][n])NEWLINE # half size of the box to the left of the pixelNEWLINE hbox_l = min(half_box,wb[1][n])NEWLINE # half size of the box to the right of the pixelNEWLINE hbox_r = min(half_box,nx-1-wb[1][n])NEWLINE # but in case we are at an edge, we want to extend the box by one NEWLINE # row/column of pixels in the direction opposite to the edge:NEWLINE if wb[0][n] > ny-1-half_box:NEWLINE hbox_b = hbox_b + (wb[0][n]-(ny-1-half_box))NEWLINE elif wb[0][n] < half_box:NEWLINE hbox_t = hbox_t+(half_box-wb[0][n])NEWLINE if wb[1][n] > nx-1-half_box:NEWLINE hbox_l = hbox_l + (wb[1][n]-(nx-1-half_box))NEWLINE elif wb[1][n] < half_box:NEWLINE hbox_r = hbox_r+(half_box-wb[1][n])NEWLINENEWLINE #1/ list neighbouring pixels, > 8, not including the pixel itselfNEWLINE neighbours = frame[wb[0][n]-hbox_b:wb[0][n]+hbox_t+1,NEWLINE wb[1][n]-hbox_l:wb[1][n]+hbox_r+1]NEWLINE c_idx_px = ([[hbox_b],[hbox_l]])NEWLINE flat_c_idx = np.ravel_multi_index(c_idx_px,(hbox_t+hbox_b+1,NEWLINE hbox_r+hbox_l+1))NEWLINE neighbours = np.delete(neighbours,flat_c_idx)NEWLINENEWLINE #2/ test if bpixNEWLINE test_result = reject_outliers(neighbours, frame[wb[0][n],wb[1][n]],NEWLINE m=sig_dist, stddev=stddev, NEWLINE min_thr=min_thr, mid_thr=mid_thr)NEWLINENEWLINE #3/ Assign the value of the test to bpix_mapNEWLINE bpix_map[wb[0][n],wb[1][n]] = test_resultNEWLINENEWLINENEWLINE return bpix_mapNEWLINE NEWLINE NEWLINENEWLINEdef reject_outliers(data, test_value, m=5., stddev=None, debug=False):NEWLINE """ Function to reject outliers from a set.NEWLINE Instead of the classic standard deviation criterion (e.g. 5-sigma), the NEWLINE discriminant is determined as follow:NEWLINE - for each value in data, an absolute distance to the median of data isNEWLINE computed and put in a new array "d" (of same size as data)NEWLINE - scaling each element of "d" by the median value of "d" gives the absoluteNEWLINE distances "s" of each elementNEWLINE - each "s" is then compared to "m" (parameter): if s < m, we have a good NEWLINE neighbour, otherwise we have an outlier. A specific value test_value is NEWLINE tested as outlier.NEWLINENEWLINE Parameters:NEWLINE -----------NEWLINE data: numpy ndarrayNEWLINE Input array with respect to which either a test_value or the central a NEWLINE value of data is determined to be an outlier or notNEWLINE test_value: floatNEWLINE Value to be tested as an outlier in the context of the input array dataNEWLINE m: float, optionalNEWLINE Criterion used to test if test_value is or pixels of data are outlier(s)NEWLINE (similar to the number of "sigma" in std_dev statistics)NEWLINE stddev: float, optional (but strongly recommended)NEWLINE Global std dev of the non-PSF part of the considered frame. It is neededNEWLINE as a reference to know the typical variation of the noise, and hence NEWLINE avoid detecting outliers out of very close pixel values. If the 9 pixelsNEWLINE of data happen to be very uniform in values at some location, the NEWLINE departure in value of only one pixel could make it appear as a bad NEWLINE pixel. If stddev is not provided, the stddev of data is used (not NEWLINE recommended).NEWLINENEWLINE Returns:NEWLINE --------NEWLINE test_result: 0 or 1NEWLINE 0 if test_value is not an outlier. 1 otherwise. NEWLINE """NEWLINENEWLINE if no_numba:NEWLINE def _reject_outliers(data, test_value, m=5., stddev=None, debug=False):NEWLINE if stddev is None:NEWLINE stddev = np.std(data)NEWLINE NEWLINE med = np.median(data)NEWLINE d = np.abs(data - med)NEWLINE mdev = np.median(d)NEWLINE if debug:NEWLINE print("data = ", data)NEWLINE print("median(data)= ", np.median(data))NEWLINE print("d = ", d)NEWLINE print("mdev = ", mdev)NEWLINE print("stddev(box) = ", np.std(data))NEWLINE print("stddev(frame) = ", stddev)NEWLINE print("max(d) = ", np.max(d))NEWLINE NEWLINE if max(np.max(d),np.abs(test_value-med)) > stddev:NEWLINE mdev = mdev if mdev>stddev else stddevNEWLINE s = d/mdevNEWLINE if debug:NEWLINE print("s =", s)NEWLINE test = np.abs((test_value-np.median(data))/mdev)NEWLINE if debug:NEWLINE print("test =", test)NEWLINE else:NEWLINE if test < m:NEWLINE test_result = 0NEWLINE else:NEWLINE test_result = 1NEWLINE else:NEWLINE test_result = 0NEWLINE NEWLINE return test_resultNEWLINE return _reject_outliers(data, test_value, m=5., stddev=None, NEWLINE debug=debug)NEWLINE else:NEWLINE @njitNEWLINE def _reject_outliers(data, test_value, m=5.,stddev=None):NEWLINE if stddev is None:NEWLINE stddev = np.std(data)NEWLINE NEWLINE med = np.median(data)NEWLINE d = data.copy()NEWLINE d_flat = d.flatten()NEWLINE for i in range(d_flat.shape[0]):NEWLINE d_flat[i] = np.abs(data.flatten()[i] - med)NEWLINE mdev = np.median(d_flat)NEWLINE if max(np.max(d),np.abs(test_value-med)) > stddev:NEWLINE test = np.abs((test_value-med)/mdev)NEWLINE if test < m:NEWLINE test_result = 0NEWLINE else:NEWLINE test_result = 1NEWLINE else:NEWLINE test_result = 0NEWLINE NEWLINE return test_resultNEWLINE NEWLINE return _reject_outliers(data, test_value, m=5.,stddev=None)NEWLINENEWLINE NEWLINEdef correct_ann_outliers(obj_tmp, ann_width, sig, med_neig, std_neig, cy, cx, NEWLINE min_thr, max_thr, rand_arr, stddev, half_res_y=False):NEWLINE """ Function to correct outliers in concentric annuli.NEWLINENEWLINE Parameters:NEWLINE -----------NEWLINE obj_tmp: numpy ndarrayNEWLINE Input array with respect to which either a test_value or the central a NEWLINE value of data is determined to be an outlier or notNEWLINE ann_width: floatNEWLINE Width of concenrtric annuli in pixels.NEWLINE sig: floatNEWLINE Number of sigma to consider a pixel intensity as an outlier.NEWLINE med_neig, std_neig: 1d arraysNEWLINE Median and standard deviation of good pixel intensities in each annulus NEWLINE cy, cx: floatsNEWLINE Coordinates of the center of the concentric annuli.NEWLINE min_thr, max_thr: {None,float}NEWLINE Any pixel whose value is lower (resp. larger) than this threshold will NEWLINE be automatically considered bad and hence sigma_filtered. If None, it NEWLINE is not used.NEWLINE stddev: floatNEWLINE Global std dev of the non-PSF part of the considered frame. It is neededNEWLINE as a reference to know the typical variation of the noise, and hence NEWLINE avoid detecting outliers out of very close pixel values. If the 9 pixelsNEWLINE of data happen to be very uniform in values at some location, the NEWLINE departure in value of only one pixel could make it appear as a bad NEWLINE pixel. If stddev is not provided, the stddev of data is used (not NEWLINE recommended).NEWLINE half_res_y: bool, {True,False}, optionalNEWLINE Whether the input data have only half the angular resolution vertically NEWLINE compared to horizontally (e.g. SINFONI data).NEWLINE The algorithm will then correct the bad pixels every other row.NEWLINENEWLINE Returns:NEWLINE --------NEWLINE obj_tmp_corr: np.arrayNEWLINE Array with corrected outliers.NEWLINE bpix_map: np.arrayNEWLINE Boolean array with location of outliers.NEWLINE """ NEWLINE NEWLINE if no_numba: NEWLINE def _correct_ann_outliers(obj_tmp, ann_width, sig, med_neig, std_neig, NEWLINE cy, cx, min_thr, max_thr, rand_arr, stddev, NEWLINE half_res_y=False): NEWLINE n_y, n_x = obj_tmp.shapeNEWLINE rand_arr = 2*(np.random.rand((n_y, n_x))-0.5)NEWLINE obj_tmp_corr = obj_tmp.copy()NEWLINE bpix_map = np.zeros([n_y,n_x])NEWLINE for yy in range(n_y):NEWLINE for xx in range(n_x):NEWLINE if half_res_y:NEWLINE rad = np.sqrt((2*(cy-yy))**2+(cx-xx)**2)NEWLINE else:NEWLINE rad = np.sqrt((cy-yy)**2+(cx-xx)**2)NEWLINE rr = int(rad/ann_width)NEWLINE dev = max(stddev,min(std_neig[rr],med_neig[rr]))NEWLINE NEWLINE # check min_thrNEWLINE if obj_tmp[yy,xx] < min_thr:NEWLINE bpix_map[yy,xx] = 1NEWLINE obj_tmp_corr[yy,xx] = med_neig[rr] + \NEWLINE np.sqrt(np.abs(med_neig[rr]))*rand_arr[yy,xx]NEWLINE NEWLINE # check max_thrNEWLINE elif obj_tmp[yy,xx] > max_thr:NEWLINE bpix_map[yy,xx] = 1NEWLINE obj_tmp_corr[yy,xx] = med_neig[rr] + \NEWLINE np.sqrt(np.abs(med_neig[rr]))*rand_arr[yy,xx]NEWLINE NEWLINE elif (obj_tmp[yy,xx] < med_neig[rr]-sig*dev or NEWLINE obj_tmp[yy,xx] > med_neig[rr]+sig*dev):NEWLINE bpix_map[yy,xx] = 1NEWLINE obj_tmp_corr[yy,xx] = med_neig[rr] + \NEWLINE np.sqrt(np.abs(med_neig[rr]))*rand_arr[yy,xx]NEWLINE return obj_tmp_corr, bpix_mapNEWLINE else:NEWLINE @njit NEWLINE def _correct_ann_outliers(obj_tmp, ann_width, sig, med_neig, std_neig, NEWLINE cy, cx, min_thr, max_thr, rand_arr, stddev, NEWLINE half_res_y=False): NEWLINE n_y, n_x = obj_tmp.shapeNEWLINE rand_arr = 2*(np.random.rand((n_y, n_x))-0.5)NEWLINE obj_tmp_corr = obj_tmp.copy()NEWLINE bpix_map = np.zeros([n_y,n_x])NEWLINE for yy in range(n_y):NEWLINE for xx in range(n_x):NEWLINE if half_res_y:NEWLINE rad = np.sqrt((2*(cy-yy))**2+(cx-xx)**2)NEWLINE else:NEWLINE rad = np.sqrt((cy-yy)**2+(cx-xx)**2)NEWLINE rr = int(rad/ann_width)NEWLINE dev = max(stddev,min(std_neig[rr],med_neig[rr]))NEWLINE NEWLINE # check min_thrNEWLINE if obj_tmp[yy,xx] < min_thr:NEWLINE bpix_map[yy,xx] = 1NEWLINE obj_tmp_corr[yy,xx] = med_neig[rr] + \NEWLINE np.sqrt(np.abs(med_neig[rr]))*rand_arr[yy,xx]NEWLINE NEWLINE # check max_thrNEWLINE elif obj_tmp[yy,xx] > max_thr:NEWLINE bpix_map[yy,xx] = 1NEWLINE obj_tmp_corr[yy,xx] = med_neig[rr] + \NEWLINE np.sqrt(np.abs(med_neig[rr]))*rand_arr[yy,xx]NEWLINE NEWLINE elif (obj_tmp[yy,xx] < med_neig[rr]-sig*dev or NEWLINE obj_tmp[yy,xx] > med_neig[rr]+sig*dev):NEWLINE bpix_map[yy,xx] = 1NEWLINE obj_tmp_corr[yy,xx] = med_neig[rr] + \NEWLINE np.sqrt(np.abs(med_neig[rr]))*rand_arr[yy,xx]NEWLINE return obj_tmp_corr, bpix_mapNEWLINE NEWLINE return _correct_ann_outliers(obj_tmp, ann_width, sig, med_neig, std_neig, NEWLINE cy, cx, min_thr, max_thr, rand_arr, stddev, NEWLINE half_res_y=False)
from flask_script import Manager, ShellNEWLINEimport osNEWLINENEWLINEfrom app import create_appNEWLINENEWLINEapp = create_app(os.getenv('APP_SETTINGS'))NEWLINEmanager = Manager(app)NEWLINENEWLINENEWLINEdef make_shell_context():NEWLINE return dict(app=app)NEWLINENEWLINEmanager.add_command("shell", Shell(make_context=make_shell_context()))NEWLINENEWLINEif __name__ == '__main__':NEWLINE manager.run()
#!/usr/bin/env python3NEWLINENEWLINEimport argparseNEWLINENEWLINEfrom utils import (NEWLINE load_yaml, load_wordset, sorted_items, get_morphgnt, parse_verse_ranges)NEWLINENEWLINEargparser = argparse.ArgumentParser()NEWLINEargparser.add_argument("verses", help="verses to cover (e.g. 'John 18:1-11')")NEWLINEargparser.add_argument("--exclude", help="exclusion list file")NEWLINEargparser.add_argument(NEWLINE "--existing", dest="headwords", help="existing headword file")NEWLINEargparser.add_argument(NEWLINE "--lexicon", dest="lexemes",NEWLINE default="../morphological-lexicon/lexemes.yaml",NEWLINE help="path to morphological-lexicon lexemes.yaml file "NEWLINE "(defaults to ../morphological-lexicon/lexemes.yaml)")NEWLINEargparser.add_argument(NEWLINE "--sblgnt", dest="sblgnt_dir", default="../sblgnt",NEWLINE help="path to MorphGNT sblgnt directory (defaults to ../sblgnt)")NEWLINENEWLINEargs = argparser.parse_args()NEWLINENEWLINEverses = parse_verse_ranges(args.verses)NEWLINENEWLINEif args.exclude:NEWLINE exclusions = load_wordset(args.exclude)NEWLINEelse:NEWLINE exclusions = set()NEWLINENEWLINElexemes = load_yaml(args.lexemes)NEWLINENEWLINEif args.headwords:NEWLINE headwords = load_yaml(args.headwords)NEWLINEelse:NEWLINE headwords = {}NEWLINENEWLINENEWLINEfor entry in get_morphgnt(verses, args.sblgnt_dir):NEWLINE if entry[0] == "WORD":NEWLINE lexeme = entry[8]NEWLINE if lexeme not in exclusions and lexeme not in headwords:NEWLINE pos = entry[2]NEWLINE if pos in ["N-", "A-"]:NEWLINE if "full-citation-form" in lexemes[lexeme]:NEWLINE headword = lexemes[lexeme]["full-citation-form"]NEWLINE else:NEWLINE headword = lexemes[lexeme]["danker-entry"]NEWLINE headwords[lexeme] = headwordNEWLINENEWLINEfor lexeme, headword in sorted_items(headwords):NEWLINE print("{}: {}".format(lexeme, headword))NEWLINE
#!/usr/bin/env python3NEWLINENEWLINEimport reNEWLINENEWLINENEWLINEdef parse(line):NEWLINE m = re.match(r'(.*) (\d+),(\d+) through (\d+),(\d+)', line)NEWLINE if m:NEWLINE op = m.group(1)NEWLINE p0 = [int(m.group(2)), int(m.group(3))]NEWLINE p1 = [int(m.group(4)), int(m.group(5))]NEWLINENEWLINE return op, p0, p1NEWLINENEWLINENEWLINEdef part1(filename):NEWLINE with open(filename) as f:NEWLINE lines = f.readlines()NEWLINENEWLINE grid = [[0] * 1000 for _ in range(1000)]NEWLINENEWLINE for line in lines:NEWLINE op, p0, p1 = parse(line)NEWLINE for i in range(p0[0], p1[0] + 1):NEWLINE for j in range(p0[1], p1[1] + 1):NEWLINE if op == 'turn on':NEWLINE grid[i][j] = 1NEWLINE elif op == 'turn off':NEWLINE grid[i][j] = 0NEWLINE elif op == 'toggle':NEWLINE grid[i][j] = int(not grid[i][j])NEWLINENEWLINE count = 0NEWLINE for i in range(1000):NEWLINE for j in range(1000):NEWLINE if grid[i][j] == 1:NEWLINE count += 1NEWLINENEWLINE print(count)NEWLINENEWLINENEWLINEdef part2(filename):NEWLINE with open(filename) as f:NEWLINE lines = f.readlines()NEWLINENEWLINE grid = [[0] * 1000 for _ in range(1000)]NEWLINENEWLINE for line in lines:NEWLINE op, p0, p1 = parse(line)NEWLINE for i in range(p0[0], p1[0] + 1):NEWLINE for j in range(p0[1], p1[1] + 1):NEWLINE if op == 'turn on':NEWLINE grid[i][j] += 1NEWLINE elif op == 'turn off':NEWLINE grid[i][j] = max(0, grid[i][j] - 1)NEWLINE elif op == 'toggle':NEWLINE grid[i][j] += 2NEWLINENEWLINE count = 0NEWLINE for i in range(1000):NEWLINE for j in range(1000):NEWLINE count += grid[i][j]NEWLINENEWLINE print(count)NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE part1('day06input.txt')NEWLINE part2('day06input.txt')
# Generated by Django 3.0 on 2020-04-21 20:13NEWLINENEWLINEfrom django.db import migrations, modelsNEWLINEimport django.db.models.deletionNEWLINENEWLINENEWLINEclass Migration(migrations.Migration):NEWLINENEWLINE initial = TrueNEWLINENEWLINE dependencies = [NEWLINE ]NEWLINENEWLINE operations = [NEWLINE migrations.CreateModel(NEWLINE name='Hospital',NEWLINE fields=[NEWLINE ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),NEWLINE ('name', models.CharField(max_length=254, verbose_name='Nome')),NEWLINE ('city', models.CharField(max_length=254, verbose_name='Cidade')),NEWLINE ('phonenumber', models.CharField(max_length=16, verbose_name='Telefone')),NEWLINE ('email', models.EmailField(max_length=254, verbose_name='E-mail')),NEWLINE ],NEWLINE ),NEWLINE migrations.CreateModel(NEWLINE name='Patient',NEWLINE fields=[NEWLINE ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),NEWLINE ('name', models.CharField(max_length=254, verbose_name='Nome')),NEWLINE ('birthday', models.DateField(verbose_name='Data de Nascimento')),NEWLINE ('airways', models.CharField(choices=[('VM', 'Ventilação Mecânica'), ('AA', 'Ar Ambiente'), ('VNI', 'Ventilação não Invasiva')], default='AA', max_length=24, verbose_name='Vias Aéreas')),NEWLINE ('status', models.CharField(choices=[('S', 'Suspeito'), ('C', 'Confirmado'), ('D', 'Descartado')], default='S', max_length=10, verbose_name='Status COVID')),NEWLINE ('hospitalization_date', models.DateField(verbose_name='Data de Internação')),NEWLINE ('departure_date', models.DateField(verbose_name='Data de Saída')),NEWLINE ('cns', models.CharField(blank=True, default='', max_length=30, verbose_name='Carteira Nacional do SUS')),NEWLINE ('sisreg', models.CharField(blank=True, default='', max_length=30, verbose_name='Número no sistema Sisreg')),NEWLINE ('departure_reason', models.CharField(choices=[('A', 'Alta'), ('O', 'Óbito')], default='A', max_length=5, verbose_name='Motivo da Saída')),NEWLINE ('hospital', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='hospitals.Hospital', verbose_name='Hospital')),NEWLINE ],NEWLINE ),NEWLINE ]NEWLINE
"""NEWLINECopyright (c) 2018-2020 Intel CorporationNEWLINENEWLINELicensed under the Apache License, Version 2.0 (the "License");NEWLINEyou may not use this file except in compliance with the License.NEWLINEYou may obtain a copy of the License atNEWLINENEWLINE http://www.apache.org/licenses/LICENSE-2.0NEWLINENEWLINEUnless required by applicable law or agreed to in writing, softwareNEWLINEdistributed under the License is distributed on an "AS IS" BASIS,NEWLINEWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINESee the License for the specific language governing permissions andNEWLINElimitations under the License.NEWLINE"""NEWLINENEWLINEfrom .postprocessing_executor import PostprocessingExecutor, PostprocessorNEWLINENEWLINEfrom .filter import (NEWLINE FilterPostprocessor,NEWLINENEWLINE FilterByHeightRange,NEWLINE FilterByLabels,NEWLINE FilterByMinConfidence,NEWLINE FilterEmpty,NEWLINE FilterByVisibility,NEWLINE FilterByAspectRatioNEWLINE)NEWLINENEWLINEfrom .cast_to_int import CastToIntNEWLINEfrom .clip_boxes import ClipBoxesNEWLINEfrom .nms import NMS, SoftNMSNEWLINEfrom .resize_prediction_boxes import ResizePredictionBoxesNEWLINEfrom .faster_rcnn_postprocessing_resize import FRCNNPostprocessingBboxResizeNEWLINEfrom .correct_yolo_v2_boxes import CorrectYoloV2BoxesNEWLINEfrom .resize_segmentation_mask import ResizeSegmentationMaskNEWLINEfrom .encode_segmentation_mask import EncodeSegMaskNEWLINEfrom .shift import Shift, ShiftLabelsNEWLINEfrom .normalize_landmarks_points import NormalizeLandmarksPointsNEWLINEfrom .clip_points import ClipPointsNEWLINEfrom .extend_segmentation_mask import ExtendSegmentationMaskNEWLINEfrom .zoom_segmentation_mask import ZoomSegMaskNEWLINEfrom .crop_segmentation_mask import CropSegmentationMask, CropOrPadSegmentationMaskNEWLINEfrom .clip_segmentation_mask import ClipSegmentationMaskNEWLINEfrom .normalize_boxes import NormalizeBoxesNEWLINEfrom .brats_postprocessing import SegmentationPredictionResample, TransformBratsPredictionNEWLINEfrom .extract_answers_tokens import ExtractSQUADPrediction, ExtractSQUADPredictionBiDAFNEWLINEfrom .translate_3d_poses import Translate3dPosesNEWLINEfrom .normalize_recomendation import MinMaxNormalizeRecommendation, SigmoidNormalizeRecommendationNEWLINEfrom .align_prediction_depth_map import AlignDepthNEWLINEfrom .resize_prediction_depth_map import ResizeDepthMapNEWLINEfrom .resize_super_resolution import ResizeSuperResolutionNEWLINEfrom .resize_style_transfer import ResizeStyleTransferNEWLINEfrom .crop_ground_truth_image import CropGTImage, CornerCropGTImageNEWLINEfrom .resize import ResizeNEWLINEfrom .to_gray_scale_ref_image import RGB2GRAYAnnotation, BGR2GRAYAnnotationNEWLINEfrom .remove_repeats import RemoveRepeatTokensNEWLINEfrom .tokens_to_lower_case import TokensToLowerCaseNEWLINEfrom .super_resolution_image_recovery import SRImageRecovery, ColorizationLABRecoveryNEWLINEfrom .argmax_segmentation_mask import ArgMaxSegmentationMaskNEWLINEfrom .normalize_salient_map import SalientMapNormalizerNEWLINENEWLINENEWLINE__all__ = [NEWLINE 'Postprocessor',NEWLINE 'PostprocessingExecutor',NEWLINENEWLINE 'FilterPostprocessor',NEWLINE 'FilterByHeightRange',NEWLINE 'FilterByLabels',NEWLINE 'FilterByMinConfidence',NEWLINE 'FilterEmpty',NEWLINE 'FilterByVisibility',NEWLINE 'FilterByAspectRatio',NEWLINENEWLINE 'CastToInt',NEWLINE 'ClipBoxes',NEWLINE 'NMS',NEWLINE 'SoftNMS',NEWLINE 'ResizePredictionBoxes',NEWLINE 'FRCNNPostprocessingBboxResize',NEWLINE 'CorrectYoloV2Boxes',NEWLINE 'NormalizeBoxes',NEWLINENEWLINE 'ResizeSegmentationMask',NEWLINE 'EncodeSegMask',NEWLINE 'Shift',NEWLINE 'ShiftLabels',NEWLINE 'ExtendSegmentationMask',NEWLINE 'ZoomSegMask',NEWLINE 'CropSegmentationMask',NEWLINE 'ClipSegmentationMask',NEWLINE 'ArgMaxSegmentationMask',NEWLINENEWLINE 'SegmentationPredictionResample',NEWLINE 'TransformBratsPrediction',NEWLINENEWLINE 'NormalizeLandmarksPoints',NEWLINENEWLINE 'ExtractSQUADPrediction',NEWLINE 'ExtractSQUADPredictionBiDAF',NEWLINENEWLINE 'Translate3dPoses',NEWLINENEWLINE 'SigmoidNormalizeRecommendation',NEWLINE 'MinMaxNormalizeRecommendation',NEWLINENEWLINE 'MinMaxNormalizeRecommendation',NEWLINENEWLINE 'AlignDepth',NEWLINE 'ResizeDepthMap',NEWLINENEWLINE 'ResizeSuperResolution',NEWLINE 'ResizeStyleTransfer',NEWLINE 'RGB2GRAYAnnotation',NEWLINE 'BGR2GRAYAnnotation',NEWLINENEWLINE 'CropGTImage',NEWLINE 'CornerCropGTImage',NEWLINENEWLINE 'Resize',NEWLINENEWLINE 'RemoveRepeatTokens',NEWLINE 'TokensToLowerCase',NEWLINENEWLINE 'SRImageRecovery',NEWLINE 'ColorizationLABRecovery',NEWLINENEWLINE 'SalientMapNormalizer'NEWLINE]NEWLINE
import socketNEWLINEimport selectNEWLINENEWLINEHEADER_LENGTH = 10NEWLINENEWLINEIP = "127.0.0.1"NEWLINEPORT = 1234NEWLINENEWLINENEWLINEserver_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)NEWLINENEWLINEserver_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)NEWLINEserver_socket.bind((IP, PORT))NEWLINENEWLINE# Fazendo o servidor listar as conexõesNEWLINEserver_socket.listen()NEWLINENEWLINEsockets_list = [server_socket]NEWLINENEWLINE# Lista de clientes conectados - socket usa cabeçalho e nome como dadosNEWLINEclients = {}NEWLINENEWLINEprint(f'Listening for connections on {IP}:{PORT}...')NEWLINENEWLINEdef receive_message(client_socket):NEWLINENEWLINE try:NEWLINENEWLINE # Recebe o cabeçalho contendo o tamanho da mensagemNEWLINE message_header = client_socket.recv(HEADER_LENGTH)NEWLINENEWLINE # Se houver o recebimento da mensagem, fecha-se a conexãoNEWLINE if not len(message_header):NEWLINE return FalseNEWLINENEWLINE # Convertendo cabeçalho para um valor inteiroNEWLINE message_length = int(message_header.decode('utf-8').strip())NEWLINENEWLINE # Retornando o objeto da mensagem de cabaçalho e os dados da mensagemNEWLINE return {'header': message_header, 'data': client_socket.recv(message_length)}NEWLINENEWLINE except:NEWLINENEWLINE # Em caso de erro:NEWLINE return FalseNEWLINENEWLINEwhile True:NEWLINENEWLINE NEWLINE read_sockets, _, exception_sockets = select.select(sockets_list, [], sockets_list)NEWLINENEWLINENEWLINE # Iterate over notified socketsNEWLINE for notified_socket in read_sockets:NEWLINENEWLINE # Se a notificação do socket é um servidor socket - nova conexão, aceitaNEWLINE if notified_socket == server_socket:NEWLINENEWLINE NEWLINE client_socket, client_address = server_socket.accept()NEWLINENEWLINE NEWLINE user = receive_message(client_socket)NEWLINENEWLINE NEWLINE if user is False:NEWLINE continueNEWLINENEWLINE NEWLINE sockets_list.append(client_socket)NEWLINENEWLINE NEWLINE clients[client_socket] = userNEWLINENEWLINE print('Accepted new connection from {}:{}, username: {}'.format(*client_address, user['data'].decode('utf-8')))NEWLINENEWLINE # Se o socket existente estiver enviando uma mensagem NEWLINE else:NEWLINENEWLINE # Recebendo a mensagemNEWLINE message = receive_message(notified_socket)NEWLINENEWLINE # Se falso, cliente é desconectadoNEWLINE if message is False:NEWLINE print('Closed connection from: {}'.format(clients[notified_socket]['data'].decode('utf-8')))NEWLINENEWLINE # Removendo da lista de socketsNEWLINE sockets_list.remove(notified_socket)NEWLINENEWLINE # Removendo da lista de usuáriosNEWLINE del clients[notified_socket]NEWLINENEWLINE continueNEWLINENEWLINE # Passando o usuário que enviou a mensagemNEWLINE user = clients[notified_socket]NEWLINENEWLINE print(f'Received message from {user["data"].decode("utf-8")}: {message["data"].decode("utf-8")}')NEWLINENEWLINE NEWLINE for client_socket in clients:NEWLINENEWLINE NEWLINE if client_socket != notified_socket:NEWLINENEWLINE # Usuário e respectiva mensagemNEWLINE client_socket.send(user['header'] + user['data'] + message['header'] + message['data'])NEWLINENEWLINE # Exceções NEWLINE for notified_socket in exception_sockets:NEWLINENEWLINE # Remove da lista de socketsNEWLINE sockets_list.remove(notified_socket)NEWLINENEWLINE # Remove da lista de usuáriosNEWLINE del clients[notified_socket]
# _*_ coding: utf-8 _*_NEWLINE"""NEWLINE Swagger 配置NEWLINE"""NEWLINEimport osNEWLINEfrom collections import namedtupleNEWLINENEWLINEVERSION = "0.1.0" # 项目版本NEWLINENEWLINE# is_dev_mode = os.path.exists('app/config/dev_setting.py') # 'development' & 'product' (开发环境 or 生产环境)NEWLINENEWLINEis_dev_mode = TrueNEWLINENEWLINEEXTERNAL_URL = '182.92.242.32:8020' # 外部(云服务器)地址NEWLINEINTERNAL_URL = '0.0.0.0:8020' # 内部(本地)地址NEWLINESERVER_URL = INTERNAL_URL if is_dev_mode else EXTERNAL_URLNEWLINENEWLINEEXTERNAL_SCHEMES = ["https", "http"] # 外部(云服务器)支持 https 和 http 协议NEWLINEINTERNAL_SCHEMES = ["http"] # 内部只支持httpNEWLINESERVER_SCHEMES = INTERNAL_SCHEMES if is_dev_mode else EXTERNAL_SCHEMESNEWLINENEWLINESWAGGER_TAGS = [] # 在'/app/api/__init__.py'中create_blueprint_list设置NEWLINESWAGGER = {NEWLINE "swagger_version": "2.0",NEWLINE "info": {NEWLINE "title": "金峰项目: API文档",NEWLINE "version": VERSION,NEWLINE "description": "描述暂无",NEWLINE "contact": {NEWLINE "responsibleOrganization": "TaleCeres",NEWLINE "responsibleDeveloper": "董冬伟",NEWLINE "email": "bodanli159951@163.com",NEWLINE "url": "http://51anquan.com"NEWLINE },NEWLINE "termsOfService": "http://51anquan.com"NEWLINE },NEWLINE "host": SERVER_URL, # "api.ivinetrue.com",NEWLINE "basePath": "/", # base bash for blueprint registrationNEWLINE "tags": SWAGGER_TAGS, # 在'/app/api/v1/__init__.py'定义NEWLINE "schemes": SERVER_SCHEMES,NEWLINE "operationId": "getmyData",NEWLINE "securityDefinitions": {NEWLINE 'basicAuth': {NEWLINE 'type': 'basic'NEWLINE }NEWLINE }NEWLINE}NEWLINENEWLINE# SWAGGER的安全访问方式NEWLINEspecs_security = [NEWLINE {NEWLINE "basicAuth": []NEWLINE }NEWLINE]NEWLINENEWLINE# all api by module(version)NEWLINE# 可以控制Swagger API文档的显示顺序NEWLINEALL_RP_API_LIST= \NEWLINE ['cms.admin', 'cms.group', 'cms.auth',NEWLINE 'cms.user', 'cms.cdkey', 'cms.agent', 'cms.company',NEWLINE 'cms.project', 'cms.device_category', 'cms.device'] +\NEWLINE ['v1.token', 'v1.user', 'v1.cdkey', 'v1.device', 'v1.project', 'v1.alarm', 'v1.device', 'v1.job', 'v1.statement']NEWLINENEWLINE# 所有endpoint的meta信息NEWLINEEP_META = {}NEWLINEEP_INFO_LIST = []NEWLINEEP_INFOS = {}NEWLINENEWLINE# 权限组(必须存在于数据库, 项目启动后自动导入)NEWLINEGroup = namedtuple('group', ['name', 'info', 'id'])NEWLINEAUTH_GROUPS = {NEWLINE # System 系统(金峰)NEWLINE # 'SYS_SUPER': Group('系统超级管理员', '', ''),NEWLINE 'SYS_ADMIN': Group('系统管理员', '', ''),NEWLINE # Company 企业NEWLINE 'CO_SUPER': Group('企业超级管理员', '', ''),NEWLINE 'CO_ADMIN': Group('企业管理员', '', ''),NEWLINE 'CO_PROJECT': Group('项目管理员', '', ''),NEWLINE 'CO_OPERATE': Group('运维管理员', '', ''),NEWLINE 'CO_USER': Group('普通员工', '', ''),NEWLINE # Agent 代理商NEWLINE 'AGENT': Group('代理商', '', ''),NEWLINE # Guest 访客NEWLINE 'GUEST': Group('访客', '', '')NEWLINE}NEWLINENEWLINE# tokenNEWLINEtmp_token = 'eyJhbGciOiJIUzUxMiIsImlhdCI6MTU4Mzk3NjE5NCwiZXhwIjoxNTg2NTY4MTk0fQ.eyJ1aWQiOiI1ZTY4NDQ4YTQ1YjY5YzdiNzc5MGIyYzYiLCJ0eXBlIjoxMDEsInNjb3BlIjoiU3lzU3VwZXJTY29wZSJ9.BM487QjEFINNKxrTgcd0YDoVvLuFJpVBjTlc3smzQ1wm1amSGYU1EaiLearM5SKtQEiugdWil03Wnj9H5Rkclw'NEWLINENEWLINEfrom app.libs.schedule_task import per_hour_statistics, per_day_statisticsNEWLINENEWLINEJOBS = [NEWLINE {NEWLINE "id": "per_hour_statistics",NEWLINE "func": per_hour_statistics,NEWLINE "trigger": {NEWLINE "type": "cron",NEWLINE "hour": "*"NEWLINE },NEWLINE "replace_existing": TrueNEWLINE },NEWLINE {NEWLINE "id": "per_day_statistics",NEWLINE "func": per_day_statistics,NEWLINE "trigger": {NEWLINE "type": "cron",NEWLINE "day": "*"NEWLINE },NEWLINE "replace_existing": TrueNEWLINE }NEWLINE]NEWLINE
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.NEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINE# ==============================================================================NEWLINE"""Tests for the cost analyzer."""NEWLINENEWLINEfrom __future__ import absolute_importNEWLINEfrom __future__ import divisionNEWLINEfrom __future__ import print_functionNEWLINENEWLINEfrom tensorflow.python.framework import constant_opNEWLINEfrom tensorflow.python.framework import meta_graphNEWLINEfrom tensorflow.python.framework import opsNEWLINEfrom tensorflow.python.framework import test_utilNEWLINEfrom tensorflow.python.grappler import model_analyzerNEWLINEfrom tensorflow.python.ops import math_opsNEWLINEfrom tensorflow.python.platform import testNEWLINENEWLINENEWLINEclass PyWrapOptimizeGraphTest(test.TestCase):NEWLINENEWLINE @test_util.run_deprecated_v1NEWLINE def testBasic(self):NEWLINE """Make sure arguments can be passed correctly."""NEWLINE a = constant_op.constant([10, 11], name="a")NEWLINE b = constant_op.constant([10], name="b")NEWLINE c = math_ops.add(a, b, name="c")NEWLINE d = math_ops.add_n([a, c], name="d")NEWLINE train_op = ops.get_collection_ref(ops.GraphKeys.TRAIN_OP)NEWLINE train_op.append(d)NEWLINE mg = meta_graph.create_meta_graph_def(graph=ops.get_default_graph())NEWLINENEWLINE report = model_analyzer.GenerateModelReport(mg)NEWLINENEWLINE # Check the report headersNEWLINE self.assertTrue(b"a [Const]" in report)NEWLINE self.assertTrue(b"a [Const]" in report)NEWLINE self.assertTrue(b"c [Add]" in report)NEWLINE self.assertTrue(b"d [AddN]" in report)NEWLINENEWLINE # Also print the report to make it easier to debugNEWLINE print("{}".format(report))NEWLINENEWLINE @test_util.run_deprecated_v1NEWLINE def testDebugMode(self):NEWLINE """Make sure arguments can be passed correctly."""NEWLINE a = constant_op.constant([10, 11], name="a")NEWLINE b = constant_op.constant([10], name="b")NEWLINE c = math_ops.add(a, b, name="c")NEWLINE train_op = ops.get_collection_ref(ops.GraphKeys.TRAIN_OP)NEWLINE train_op.append(c)NEWLINE mg = meta_graph.create_meta_graph_def(graph=ops.get_default_graph())NEWLINENEWLINE report = model_analyzer.GenerateModelReport(mg, debug=True)NEWLINENEWLINE # Check the report headersNEWLINE self.assertTrue(b"input 0 (int32) has known value" in report)NEWLINE self.assertTrue(b"input 1 (int32) has known value" in report)NEWLINENEWLINE # Also print the report to make it easier to debugNEWLINE print("{}".format(report))NEWLINENEWLINENEWLINEif __name__ == "__main__":NEWLINE test.main()NEWLINE
import pendulumNEWLINEfrom dagster.core.scheduler.job import JobStatusNEWLINEfrom dagster_graphql.test.utils import (NEWLINE execute_dagster_graphql,NEWLINE infer_repository_selector,NEWLINE infer_schedule_selector,NEWLINE main_repo_location_name,NEWLINE main_repo_name,NEWLINE)NEWLINENEWLINEGET_SCHEDULES_QUERY = """NEWLINEquery SchedulesQuery($repositorySelector: RepositorySelector!) {NEWLINE schedulesOrError(repositorySelector: $repositorySelector) {NEWLINE __typenameNEWLINE ... on PythonError {NEWLINE messageNEWLINE stackNEWLINE }NEWLINE ... on Schedules {NEWLINE results {NEWLINE nameNEWLINE cronScheduleNEWLINE pipelineNameNEWLINE solidSelectionNEWLINE modeNEWLINE executionTimezoneNEWLINE }NEWLINE }NEWLINE }NEWLINE}NEWLINE"""NEWLINENEWLINEGET_SCHEDULE_QUERY = """NEWLINEquery getSchedule($scheduleSelector: ScheduleSelector!, $ticksAfter: Float) {NEWLINE scheduleOrError(scheduleSelector: $scheduleSelector) {NEWLINE __typenameNEWLINE ... on PythonError {NEWLINE messageNEWLINE stackNEWLINE }NEWLINE ... on Schedule {NEWLINE nameNEWLINE partitionSet {NEWLINE nameNEWLINE }NEWLINE executionTimezoneNEWLINE futureTicks(limit: 3, cursor: $ticksAfter) {NEWLINE results {NEWLINE timestampNEWLINE }NEWLINE cursorNEWLINE }NEWLINE }NEWLINE }NEWLINE}NEWLINE"""NEWLINENEWLINERECONCILE_SCHEDULER_STATE_QUERY = """NEWLINEmutation(NEWLINE $repositorySelector: RepositorySelector!NEWLINE) {NEWLINE reconcileSchedulerState(NEWLINE repositorySelector: $repositorySelector,NEWLINE ) {NEWLINE ... on PythonError {NEWLINE messageNEWLINE stackNEWLINE }NEWLINE ... on ReconcileSchedulerStateSuccess {NEWLINE messageNEWLINE }NEWLINE }NEWLINE}NEWLINE"""NEWLINENEWLINENEWLINESTART_SCHEDULES_QUERY = """NEWLINEmutation(NEWLINE $scheduleSelector: ScheduleSelector!NEWLINE) {NEWLINE startSchedule(NEWLINE scheduleSelector: $scheduleSelector,NEWLINE ) {NEWLINE ... on PythonError {NEWLINE messageNEWLINE classNameNEWLINE stackNEWLINE }NEWLINE ... on ScheduleStateResult {NEWLINE scheduleState {NEWLINE idNEWLINE statusNEWLINE }NEWLINE }NEWLINE }NEWLINE}NEWLINE"""NEWLINENEWLINENEWLINESTOP_SCHEDULES_QUERY = """NEWLINEmutation(NEWLINE $scheduleOriginId: String!NEWLINE) {NEWLINE stopRunningSchedule(NEWLINE scheduleOriginId: $scheduleOriginId,NEWLINE ) {NEWLINE ... on PythonError {NEWLINE messageNEWLINE classNameNEWLINE stackNEWLINE }NEWLINE ... on ScheduleStateResult {NEWLINE scheduleState {NEWLINE idNEWLINE statusNEWLINE }NEWLINE }NEWLINE }NEWLINE}NEWLINE"""NEWLINENEWLINENEWLINEdef default_execution_params():NEWLINE return {NEWLINE "runConfigData": {"intermediate_storage": {"filesystem": None}},NEWLINE "selector": {"name": "no_config_pipeline", "solidSelection": None},NEWLINE "mode": "default",NEWLINE }NEWLINENEWLINENEWLINEdef test_get_schedule_definitions_for_repository(graphql_context):NEWLINE selector = infer_repository_selector(graphql_context)NEWLINE result = execute_dagster_graphql(NEWLINE graphql_context, GET_SCHEDULES_QUERY, variables={"repositorySelector": selector},NEWLINE )NEWLINENEWLINE assert result.dataNEWLINE assert result.data["schedulesOrError"]NEWLINE assert result.data["schedulesOrError"]["__typename"] == "Schedules"NEWLINENEWLINE external_repository = graphql_context.get_repository_location(NEWLINE main_repo_location_name()NEWLINE ).get_repository(main_repo_name())NEWLINENEWLINE results = result.data["schedulesOrError"]["results"]NEWLINE assert len(results) == len(external_repository.get_external_schedules())NEWLINENEWLINE for schedule in results:NEWLINE if schedule["name"] == "timezone_schedule":NEWLINE assert schedule["executionTimezone"] == "US/Central"NEWLINENEWLINENEWLINEdef test_start_and_stop_schedule(graphql_context):NEWLINE external_repository = graphql_context.get_repository_location(NEWLINE main_repo_location_name()NEWLINE ).get_repository(main_repo_name())NEWLINE graphql_context.instance.reconcile_scheduler_state(external_repository)NEWLINENEWLINE schedule_selector = infer_schedule_selector(NEWLINE graphql_context, "no_config_pipeline_hourly_schedule"NEWLINE )NEWLINENEWLINE # Start a single scheduleNEWLINE start_result = execute_dagster_graphql(NEWLINE graphql_context, START_SCHEDULES_QUERY, variables={"scheduleSelector": schedule_selector},NEWLINE )NEWLINE assert start_result.data["startSchedule"]["scheduleState"]["status"] == JobStatus.RUNNING.valueNEWLINENEWLINE schedule_origin_id = start_result.data["startSchedule"]["scheduleState"]["id"]NEWLINENEWLINE # Stop a single scheduleNEWLINE stop_result = execute_dagster_graphql(NEWLINE graphql_context, STOP_SCHEDULES_QUERY, variables={"scheduleOriginId": schedule_origin_id},NEWLINE )NEWLINE assert (NEWLINE stop_result.data["stopRunningSchedule"]["scheduleState"]["status"]NEWLINE == JobStatus.STOPPED.valueNEWLINE )NEWLINENEWLINENEWLINEdef test_get_single_schedule_definition(graphql_context):NEWLINE context = graphql_contextNEWLINE instance = context.instanceNEWLINENEWLINE instance.reconcile_scheduler_state(NEWLINE external_repository=context.get_repository_location(NEWLINE main_repo_location_name()NEWLINE ).get_repository(main_repo_name()),NEWLINE )NEWLINENEWLINE schedule_selector = infer_schedule_selector(context, "partition_based_multi_mode_decorator")NEWLINENEWLINE result = execute_dagster_graphql(NEWLINE context, GET_SCHEDULE_QUERY, variables={"scheduleSelector": schedule_selector}NEWLINE )NEWLINENEWLINE assert result.dataNEWLINENEWLINE assert result.data["scheduleOrError"]["__typename"] == "Schedule"NEWLINE assert result.data["scheduleOrError"]["partitionSet"]NEWLINE assert result.data["scheduleOrError"]["executionTimezone"] == pendulum.now().timezone.nameNEWLINENEWLINE future_ticks = result.data["scheduleOrError"]["futureTicks"]NEWLINE assert future_ticksNEWLINE assert len(future_ticks["results"]) == 3NEWLINENEWLINE schedule_selector = infer_schedule_selector(context, "timezone_schedule")NEWLINENEWLINE future_ticks_start_time = pendulum.create(2019, 2, 27, tz="US/Central").timestamp()NEWLINENEWLINE result = execute_dagster_graphql(NEWLINE context,NEWLINE GET_SCHEDULE_QUERY,NEWLINE variables={"scheduleSelector": schedule_selector, "ticksAfter": future_ticks_start_time},NEWLINE )NEWLINENEWLINE assert result.dataNEWLINE assert result.data["scheduleOrError"]["__typename"] == "Schedule"NEWLINE assert result.data["scheduleOrError"]["executionTimezone"] == "US/Central"NEWLINENEWLINE future_ticks = result.data["scheduleOrError"]["futureTicks"]NEWLINE assert future_ticksNEWLINE assert len(future_ticks["results"]) == 3NEWLINE timestamps = [future_tick["timestamp"] for future_tick in future_ticks["results"]]NEWLINENEWLINE assert timestamps == [NEWLINE pendulum.create(2019, 2, 27, tz="US/Central").timestamp(),NEWLINE pendulum.create(2019, 2, 28, tz="US/Central").timestamp(),NEWLINE pendulum.create(2019, 3, 1, tz="US/Central").timestamp(),NEWLINE ]NEWLINENEWLINE cursor = future_ticks["cursor"]NEWLINENEWLINE assert future_ticks["cursor"] == (pendulum.create(2019, 3, 1, tz="US/Central").timestamp() + 1)NEWLINENEWLINE result = execute_dagster_graphql(NEWLINE context,NEWLINE GET_SCHEDULE_QUERY,NEWLINE variables={"scheduleSelector": schedule_selector, "ticksAfter": cursor},NEWLINE )NEWLINENEWLINE future_ticks = result.data["scheduleOrError"]["futureTicks"]NEWLINENEWLINE assert future_ticksNEWLINE assert len(future_ticks["results"]) == 3NEWLINE timestamps = [future_tick["timestamp"] for future_tick in future_ticks["results"]]NEWLINENEWLINE assert timestamps == [NEWLINE pendulum.create(2019, 3, 2, tz="US/Central").timestamp(),NEWLINE pendulum.create(2019, 3, 3, tz="US/Central").timestamp(),NEWLINE pendulum.create(2019, 3, 4, tz="US/Central").timestamp(),NEWLINE ]NEWLINE
"""NEWLINEResults for test_glm.py.NEWLINENEWLINEHard-coded from R or Stata. Note that some of the remaining discrepancy vs.NEWLINEStata may be because Stata uses ML by default unless you specifically ask forNEWLINEIRLS.NEWLINE"""NEWLINEimport osNEWLINENEWLINEimport numpy as npNEWLINEimport pandas as pdNEWLINENEWLINEfrom statsmodels.api import add_constantNEWLINEfrom statsmodels.genmod.tests.results import glm_test_residsNEWLINENEWLINE# Test PrecisionsNEWLINEDECIMAL_4 = 4NEWLINEDECIMAL_3 = 3NEWLINEDECIMAL_2 = 2NEWLINEDECIMAL_1 = 1NEWLINEDECIMAL_0 = 0NEWLINENEWLINENEWLINEclass Longley(object):NEWLINE """NEWLINE Longley used for TestGlmGaussianNEWLINENEWLINE Results are from Stata and R.NEWLINE """NEWLINE def __init__(self):NEWLINENEWLINE self.resids = np.array([NEWLINE [267.34002976, 267.34002976, 267.34002976,NEWLINE 267.34002976, 267.34002976],NEWLINE [-94.0139424, -94.0139424, -94.0139424, -94.0139424,NEWLINE -94.0139424],NEWLINE [46.28716776, 46.28716776, 46.28716776, 46.28716776,NEWLINE 46.28716776],NEWLINE [-410.11462193, -410.11462193, -410.11462193, -410.11462193,NEWLINE -410.11462193],NEWLINE [309.71459076, 309.71459076, 309.71459076, 309.71459076,NEWLINE 309.71459076],NEWLINE [-249.31121533, -249.31121533, -249.31121533, -249.31121533,NEWLINE -249.31121533],NEWLINE [-164.0489564, -164.0489564, -164.0489564, -164.0489564,NEWLINE -164.0489564],NEWLINE [-13.18035687, -13.18035687, -13.18035687, -13.18035687,NEWLINE -13.18035687],NEWLINE [14.3047726, 14.3047726, 14.3047726, 14.3047726,NEWLINE 14.3047726],NEWLINE [455.39409455, 455.39409455, 455.39409455, 455.39409455,NEWLINE 455.39409455],NEWLINE [-17.26892711, -17.26892711, -17.26892711, -17.26892711,NEWLINE -17.26892711],NEWLINE [-39.05504252, -39.05504252, -39.05504252, -39.05504252,NEWLINE -39.05504252],NEWLINE [-155.5499736, -155.5499736, -155.5499736, -155.5499736,NEWLINE -155.5499736],NEWLINE [-85.67130804, -85.67130804, -85.67130804, -85.67130804,NEWLINE -85.67130804],NEWLINE [341.93151396, 341.93151396, 341.93151396, 341.93151396,NEWLINE 341.93151396],NEWLINE [-206.75782519, -206.75782519, -206.75782519, -206.75782519,NEWLINE -206.75782519]])NEWLINE self.null_deviance = 185008826 # taken from R.NEWLINE self.params = np.array([NEWLINE 1.50618723e+01, -3.58191793e-02,NEWLINE -2.02022980e+00, -1.03322687e+00, -5.11041057e-02,NEWLINE 1.82915146e+03, -3.48225863e+06])NEWLINE self.bse = np.array([NEWLINE 8.49149258e+01, 3.34910078e-02, 4.88399682e-01,NEWLINE 2.14274163e-01, 2.26073200e-01,NEWLINE 4.55478499e+02, 8.90420384e+05])NEWLINE self.aic_R = 235.23486961695903 # R adds 2 for dof to AICNEWLINE self.aic_Stata = 14.57717943930524 # stata divides by nobsNEWLINE self.deviance = 836424.0555058046 # from RNEWLINE self.scale = 92936.006167311629NEWLINE self.llf = -109.61743480847952NEWLINE self.null_deviance = 185008826 # taken from R. Rpy bugNEWLINENEWLINE self.bic_Stata = 836399.1760177979 # no bic in R?NEWLINE self.df_model = 6NEWLINE self.df_resid = 9NEWLINENEWLINE # TODO: taken from Stata; not available in sm yetNEWLINE self.chi2 = 1981.711859508729NEWLINENEWLINE self.prsquared = 0.90NEWLINE self.prsquared_cox_snell = 1.00NEWLINENEWLINE # self.pearson_chi2 = 836424.1293162981 # from Stata (?)NEWLINE self.fittedvalues = np.array([NEWLINE 60055.659970240202, 61216.013942398131,NEWLINE 60124.71283224225, 61597.114621930756, 62911.285409240052,NEWLINE 63888.31121532945, 65153.048956395127, 63774.180356866214,NEWLINE 66004.695227399934, 67401.605905447621,NEWLINE 68186.268927114084, 66552.055042522494,NEWLINE 68810.549973595422, 69649.67130804155, 68989.068486039061,NEWLINE 70757.757825193927])NEWLINENEWLINENEWLINEclass GaussianLog(object):NEWLINE """NEWLINE Uses generated data. These results are from R and Stata.NEWLINE """NEWLINE def __init__(self):NEWLINE self.resids = np.array([NEWLINE [3.20800000e-04, 3.20800000e-04,NEWLINE 8.72100000e-04, 3.20800000e-04, 3.20800000e-04],NEWLINE [8.12100000e-04, 8.12100000e-04, 2.16350000e-03,NEWLINE 8.12100000e-04, 8.12100000e-04],NEWLINE [-2.94800000e-04, -2.94800000e-04, -7.69700000e-04,NEWLINE -2.94800000e-04, -2.94800000e-04],NEWLINE [1.40190000e-03, 1.40190000e-03, 3.58560000e-03,NEWLINE 1.40190000e-03, 1.40190000e-03],NEWLINE [-2.30910000e-03, -2.30910000e-03, -5.78490000e-03,NEWLINE -2.30910000e-03, -2.30910000e-03],NEWLINE [1.10380000e-03, 1.10380000e-03, 2.70820000e-03,NEWLINE 1.10380000e-03, 1.10380000e-03],NEWLINE [-5.14000000e-06, -5.14000000e-06, -1.23000000e-05,NEWLINE -5.14000000e-06, -5.14000000e-06],NEWLINE [-1.65500000e-04, -1.65500000e-04, -3.89200000e-04,NEWLINE -1.65500000e-04, -1.65500000e-04],NEWLINE [-7.55400000e-04, -7.55400000e-04, -1.73870000e-03,NEWLINE -7.55400000e-04, -7.55400000e-04],NEWLINE [-1.39800000e-04, -1.39800000e-04, -3.14800000e-04,NEWLINE -1.39800000e-04, -1.39800000e-04],NEWLINE [-7.17000000e-04, -7.17000000e-04, -1.58000000e-03,NEWLINE -7.17000000e-04, -7.17000000e-04],NEWLINE [-1.12200000e-04, -1.12200000e-04, -2.41900000e-04,NEWLINE -1.12200000e-04, -1.12200000e-04],NEWLINE [3.22100000e-04, 3.22100000e-04, 6.79000000e-04,NEWLINE 3.22100000e-04, 3.22100000e-04],NEWLINE [-3.78000000e-05, -3.78000000e-05, -7.79000000e-05,NEWLINE -3.78000000e-05, -3.78000000e-05],NEWLINE [5.54500000e-04, 5.54500000e-04, 1.11730000e-03,NEWLINE 5.54500000e-04, 5.54500000e-04],NEWLINE [3.38400000e-04, 3.38400000e-04, 6.66300000e-04,NEWLINE 3.38400000e-04, 3.38400000e-04],NEWLINE [9.72000000e-05, 9.72000000e-05, 1.87000000e-04,NEWLINE 9.72000000e-05, 9.72000000e-05],NEWLINE [-7.92900000e-04, -7.92900000e-04, -1.49070000e-03,NEWLINE -7.92900000e-04, -7.92900000e-04],NEWLINE [3.33000000e-04, 3.33000000e-04, 6.11500000e-04,NEWLINE 3.33000000e-04, 3.33000000e-04],NEWLINE [-8.35300000e-04, -8.35300000e-04, -1.49790000e-03,NEWLINE -8.35300000e-04, -8.35300000e-04],NEWLINE [-3.99700000e-04, -3.99700000e-04, -6.99800000e-04,NEWLINE -3.99700000e-04, -3.99700000e-04],NEWLINE [1.41300000e-04, 1.41300000e-04, 2.41500000e-04,NEWLINE 1.41300000e-04, 1.41300000e-04],NEWLINE [-8.50700000e-04, -8.50700000e-04, -1.41920000e-03,NEWLINE -8.50700000e-04, -8.50700000e-04],NEWLINE [1.43000000e-06, 1.43000000e-06, 2.33000000e-06,NEWLINE 1.43000000e-06, 1.43000000e-06],NEWLINE [-9.12000000e-05, -9.12000000e-05, -1.44900000e-04,NEWLINE -9.12000000e-05, -9.12000000e-05],NEWLINE [6.75500000e-04, 6.75500000e-04, 1.04650000e-03,NEWLINE 6.75500000e-04, 6.75500000e-04],NEWLINE [3.97900000e-04, 3.97900000e-04, 6.01100000e-04,NEWLINE 3.97900000e-04, 3.97900000e-04],NEWLINE [1.07000000e-05, 1.07000000e-05, 1.57000000e-05,NEWLINE 1.07000000e-05, 1.07000000e-05],NEWLINE [-8.15200000e-04, -8.15200000e-04, -1.17060000e-03,NEWLINE -8.15200000e-04, -8.15200000e-04],NEWLINE [-8.46400000e-04, -8.46400000e-04, -1.18460000e-03,NEWLINE -8.46400000e-04, -8.46400000e-04],NEWLINE [9.91200000e-04, 9.91200000e-04, 1.35180000e-03,NEWLINE 9.91200000e-04, 9.91200000e-04],NEWLINE [-5.07400000e-04, -5.07400000e-04, -6.74200000e-04,NEWLINE -5.07400000e-04, -5.07400000e-04],NEWLINE [1.08520000e-03, 1.08520000e-03, 1.40450000e-03,NEWLINE 1.08520000e-03, 1.08520000e-03],NEWLINE [9.56100000e-04, 9.56100000e-04, 1.20500000e-03,NEWLINE 9.56100000e-04, 9.56100000e-04],NEWLINE [1.87500000e-03, 1.87500000e-03, 2.30090000e-03,NEWLINE 1.87500000e-03, 1.87500000e-03],NEWLINE [-1.93920000e-03, -1.93920000e-03, -2.31650000e-03,NEWLINE -1.93920000e-03, -1.93920000e-03],NEWLINE [8.16000000e-04, 8.16000000e-04, 9.48700000e-04,NEWLINE 8.16000000e-04, 8.16000000e-04],NEWLINE [1.01520000e-03, 1.01520000e-03, 1.14860000e-03,NEWLINE 1.01520000e-03, 1.01520000e-03],NEWLINE [1.04150000e-03, 1.04150000e-03, 1.14640000e-03,NEWLINE 1.04150000e-03, 1.04150000e-03],NEWLINE [-3.88200000e-04, -3.88200000e-04, -4.15600000e-04,NEWLINE -3.88200000e-04, -3.88200000e-04],NEWLINE [9.95900000e-04, 9.95900000e-04, 1.03690000e-03,NEWLINE 9.95900000e-04, 9.95900000e-04],NEWLINE [-6.82800000e-04, -6.82800000e-04, -6.91200000e-04,NEWLINE -6.82800000e-04, -6.82800000e-04],NEWLINE [-8.11400000e-04, -8.11400000e-04, -7.98500000e-04,NEWLINE -8.11400000e-04, -8.11400000e-04],NEWLINE [-1.79050000e-03, -1.79050000e-03, -1.71250000e-03,NEWLINE -1.79050000e-03, -1.79050000e-03],NEWLINE [6.10000000e-04, 6.10000000e-04, 5.66900000e-04,NEWLINE 6.10000000e-04, 6.10000000e-04],NEWLINE [2.52600000e-04, 2.52600000e-04, 2.28100000e-04,NEWLINE 2.52600000e-04, 2.52600000e-04],NEWLINE [-8.62500000e-04, -8.62500000e-04, -7.56400000e-04,NEWLINE -8.62500000e-04, -8.62500000e-04],NEWLINE [-3.47300000e-04, -3.47300000e-04, -2.95800000e-04,NEWLINE -3.47300000e-04, -3.47300000e-04],NEWLINE [-7.79000000e-05, -7.79000000e-05, -6.44000000e-05,NEWLINE -7.79000000e-05, -7.79000000e-05],NEWLINE [6.72000000e-04, 6.72000000e-04, 5.39400000e-04,NEWLINE 6.72000000e-04, 6.72000000e-04],NEWLINE [-3.72100000e-04, -3.72100000e-04, -2.89900000e-04,NEWLINE -3.72100000e-04, -3.72100000e-04],NEWLINE [-1.22900000e-04, -1.22900000e-04, -9.29000000e-05,NEWLINE -1.22900000e-04, -1.22900000e-04],NEWLINE [-1.63470000e-03, -1.63470000e-03, -1.19900000e-03,NEWLINE -1.63470000e-03, -1.63470000e-03],NEWLINE [2.64400000e-04, 2.64400000e-04, 1.88100000e-04,NEWLINE 2.64400000e-04, 2.64400000e-04],NEWLINE [1.79230000e-03, 1.79230000e-03, 1.23650000e-03,NEWLINE 1.79230000e-03, 1.79230000e-03],NEWLINE [-1.40500000e-04, -1.40500000e-04, -9.40000000e-05,NEWLINE -1.40500000e-04, -1.40500000e-04],NEWLINE [-2.98500000e-04, -2.98500000e-04, -1.93600000e-04,NEWLINE -2.98500000e-04, -2.98500000e-04],NEWLINE [-9.33100000e-04, -9.33100000e-04, -5.86400000e-04,NEWLINE -9.33100000e-04, -9.33100000e-04],NEWLINE [9.11200000e-04, 9.11200000e-04, 5.54900000e-04,NEWLINE 9.11200000e-04, 9.11200000e-04],NEWLINE [-1.31840000e-03, -1.31840000e-03, -7.77900000e-04,NEWLINE -1.31840000e-03, -1.31840000e-03],NEWLINE [-1.30200000e-04, -1.30200000e-04, -7.44000000e-05,NEWLINE -1.30200000e-04, -1.30200000e-04],NEWLINE [9.09300000e-04, 9.09300000e-04, 5.03200000e-04,NEWLINE 9.09300000e-04, 9.09300000e-04],NEWLINE [-2.39500000e-04, -2.39500000e-04, -1.28300000e-04,NEWLINE -2.39500000e-04, -2.39500000e-04],NEWLINE [7.15300000e-04, 7.15300000e-04, 3.71000000e-04,NEWLINE 7.15300000e-04, 7.15300000e-04],NEWLINE [5.45000000e-05, 5.45000000e-05, 2.73000000e-05,NEWLINE 5.45000000e-05, 5.45000000e-05],NEWLINE [2.85310000e-03, 2.85310000e-03, 1.38600000e-03,NEWLINE 2.85310000e-03, 2.85310000e-03],NEWLINE [4.63400000e-04, 4.63400000e-04, 2.17800000e-04,NEWLINE 4.63400000e-04, 4.63400000e-04],NEWLINE [2.80900000e-04, 2.80900000e-04, 1.27700000e-04,NEWLINE 2.80900000e-04, 2.80900000e-04],NEWLINE [5.42000000e-05, 5.42000000e-05, 2.38000000e-05,NEWLINE 5.42000000e-05, 5.42000000e-05],NEWLINE [-3.62300000e-04, -3.62300000e-04, -1.54000000e-04,NEWLINE -3.62300000e-04, -3.62300000e-04],NEWLINE [-1.11900000e-03, -1.11900000e-03, -4.59800000e-04,NEWLINE -1.11900000e-03, -1.11900000e-03],NEWLINE [1.28900000e-03, 1.28900000e-03, 5.11900000e-04,NEWLINE 1.28900000e-03, 1.28900000e-03],NEWLINE [-1.40820000e-03, -1.40820000e-03, -5.40400000e-04,NEWLINE -1.40820000e-03, -1.40820000e-03],NEWLINE [-1.69300000e-04, -1.69300000e-04, -6.28000000e-05,NEWLINE -1.69300000e-04, -1.69300000e-04],NEWLINE [-1.03620000e-03, -1.03620000e-03, -3.71000000e-04,NEWLINE -1.03620000e-03, -1.03620000e-03],NEWLINE [1.49150000e-03, 1.49150000e-03, 5.15800000e-04,NEWLINE 1.49150000e-03, 1.49150000e-03],NEWLINE [-7.22000000e-05, -7.22000000e-05, -2.41000000e-05,NEWLINE -7.22000000e-05, -7.22000000e-05],NEWLINE [5.49000000e-04, 5.49000000e-04, 1.76900000e-04,NEWLINE 5.49000000e-04, 5.49000000e-04],NEWLINE [-2.12320000e-03, -2.12320000e-03, -6.60400000e-04,NEWLINE -2.12320000e-03, -2.12320000e-03],NEWLINE [7.84000000e-06, 7.84000000e-06, 2.35000000e-06,NEWLINE 7.84000000e-06, 7.84000000e-06],NEWLINE [1.15580000e-03, 1.15580000e-03, 3.34700000e-04,NEWLINE 1.15580000e-03, 1.15580000e-03],NEWLINE [4.83400000e-04, 4.83400000e-04, 1.35000000e-04,NEWLINE 4.83400000e-04, 4.83400000e-04],NEWLINE [-5.26100000e-04, -5.26100000e-04, -1.41700000e-04,NEWLINE -5.26100000e-04, -5.26100000e-04],NEWLINE [-1.75100000e-04, -1.75100000e-04, -4.55000000e-05,NEWLINE -1.75100000e-04, -1.75100000e-04],NEWLINE [-1.84600000e-03, -1.84600000e-03, -4.62100000e-04,NEWLINE -1.84600000e-03, -1.84600000e-03],NEWLINE [2.07200000e-04, 2.07200000e-04, 5.00000000e-05,NEWLINE 2.07200000e-04, 2.07200000e-04],NEWLINE [-8.54700000e-04, -8.54700000e-04, -1.98700000e-04,NEWLINE -8.54700000e-04, -8.54700000e-04],NEWLINE [-9.20000000e-05, -9.20000000e-05, -2.06000000e-05,NEWLINE -9.20000000e-05, -9.20000000e-05],NEWLINE [5.35700000e-04, 5.35700000e-04, 1.15600000e-04,NEWLINE 5.35700000e-04, 5.35700000e-04],NEWLINE [-7.67300000e-04, -7.67300000e-04, -1.59400000e-04,NEWLINE -7.67300000e-04, -7.67300000e-04],NEWLINE [-1.79710000e-03, -1.79710000e-03, -3.59500000e-04,NEWLINE -1.79710000e-03, -1.79710000e-03],NEWLINE [1.10910000e-03, 1.10910000e-03, 2.13500000e-04,NEWLINE 1.10910000e-03, 1.10910000e-03],NEWLINE [-5.53800000e-04, -5.53800000e-04, -1.02600000e-04,NEWLINE -5.53800000e-04, -5.53800000e-04],NEWLINE [7.48000000e-04, 7.48000000e-04, 1.33400000e-04,NEWLINE 7.48000000e-04, 7.48000000e-04],NEWLINE [4.23000000e-04, 4.23000000e-04, 7.26000000e-05,NEWLINE 4.23000000e-04, 4.23000000e-04],NEWLINE [-3.16400000e-04, -3.16400000e-04, -5.22000000e-05,NEWLINE -3.16400000e-04, -3.16400000e-04],NEWLINE [-6.63200000e-04, -6.63200000e-04, -1.05200000e-04,NEWLINE -6.63200000e-04, -6.63200000e-04],NEWLINE [1.33540000e-03, 1.33540000e-03, 2.03700000e-04,NEWLINE 1.33540000e-03, 1.33540000e-03],NEWLINE [-7.81200000e-04, -7.81200000e-04, -1.14600000e-04,NEWLINE -7.81200000e-04, -7.81200000e-04],NEWLINE [1.67880000e-03, 1.67880000e-03, 2.36600000e-04,NEWLINE 1.67880000e-03, 1.67880000e-03]])NEWLINENEWLINE self.null_deviance = 56.691617808182208NEWLINE self.params = np.array([NEWLINE 9.99964386e-01, -1.99896965e-02, -1.00027232e-04])NEWLINE self.bse = np.array([1.42119293e-04, 1.20276468e-05, 1.87347682e-07])NEWLINE self.aic_R = -1103.8187213072656 # adds 2 for dof for scaleNEWLINENEWLINE self.aic_Stata = -11.05818072104212 # divides by nobs for e(aic)NEWLINE self.deviance = 8.68876986288542e-05NEWLINE self.scale = 8.9574946938163984e-07 # from R but e(phi) in StataNEWLINE self.llf = 555.9093606536328NEWLINE self.bic_Stata = -446.7014211525822NEWLINE self.df_model = 2NEWLINE self.df_resid = 97NEWLINE self.chi2 = 33207648.86501769 # from Stata not in smNEWLINE self.fittedvalues = np.array([NEWLINE 2.7181850213327747, 2.664122305869506,NEWLINE 2.6106125414084405, 2.5576658143523567, 2.5052916730829535,NEWLINE 2.4534991313100165, 2.4022966718815781, 2.3516922510411282,NEWLINE 2.3016933031175575, 2.2523067456332542, 2.2035389848154616,NEWLINE 2.1553959214958001, 2.107882957382607, 2.0610050016905817,NEWLINE 2.0147664781120667, 1.969171332114154, 1.9242230385457144,NEWLINE 1.8799246095383746, 1.8362786026854092, 1.7932871294825108,NEWLINE 1.7509518640143886, 1.7092740518711942, 1.6682545192788105,NEWLINE 1.6278936824271399, 1.5881915569806042, 1.5491477677552221,NEWLINE 1.5107615585467538, 1.4730318020945796, 1.4359570101661721,NEWLINE 1.3995353437472129, 1.3637646233226499, 1.3286423392342188,NEWLINE 1.2941656621002184, 1.2603314532836074, 1.2271362753947765,NEWLINE 1.1945764028156565, 1.162647832232141, 1.1313462931621328,NEWLINE 1.1006672584668622, 1.0706059548334832, 1.0411573732173065,NEWLINE 1.0123162792324054, 0.98407722347970683, 0.95643455180206194,NEWLINE 0.92938241545618494, 0.90291478119174029, 0.87702544122826565,NEWLINE 0.85170802312101246, 0.82695599950720078, 0.80276269772458597,NEWLINE 0.77912130929465073, 0.75602489926313921, 0.73346641539106316,NEWLINE 0.71143869718971686, 0.68993448479364294, 0.66894642766589496,NEWLINE 0.64846709313034534, 0.62848897472617915, 0.60900450038011367,NEWLINE 0.5900060403922629, 0.57148591523195513, 0.55343640314018494,NEWLINE 0.5358497475357491, 0.51871816422248385, 0.50203384839536769,NEWLINE 0.48578898144361343, 0.46997573754920047, 0.45458629007964013,NEWLINE 0.4396128177740814, 0.42504751072218311, 0.41088257613548018,NEWLINE 0.39711024391126759, 0.38372277198930843, 0.37071245150195081,NEWLINE 0.35807161171849949, 0.34579262478494655, 0.33386791026040569,NEWLINE 0.32228993945183393, 0.31105123954884056, 0.30014439756060574,NEWLINE 0.28956206405712448, 0.27929695671718968, 0.26934186368570684,NEWLINE 0.25968964674310463, 0.25033324428976694, 0.24126567414856051,NEWLINE 0.23248003618867552, 0.22396951477412205, 0.21572738104035141,NEWLINE 0.20774699500257574, 0.20002180749946474, 0.19254536197598673,NEWLINE 0.18531129610924435, 0.17831334328122878, 0.17154533390247831,NEWLINE 0.16500119659068577, 0.15867495920834204, 0.15256074976354628,NEWLINE 0.14665279717814039, 0.14094543192735109])NEWLINENEWLINENEWLINEclass GaussianInverse(object):NEWLINE """NEWLINE This test uses generated data. Results are from R and Stata.NEWLINE """NEWLINE def __init__(self):NEWLINE self.resids = np.array([NEWLINE [-5.15300000e-04, -5.15300000e-04,NEWLINE 5.14800000e-04, -5.15300000e-04, -5.15300000e-04],NEWLINE [-2.12500000e-04, -2.12500000e-04, 2.03700000e-04,NEWLINE -2.12500000e-04, -2.12500000e-04],NEWLINE [-1.71400000e-04, -1.71400000e-04, 1.57200000e-04,NEWLINE -1.71400000e-04, -1.71400000e-04],NEWLINE [1.94020000e-03, 1.94020000e-03, -1.69710000e-03,NEWLINE 1.94020000e-03, 1.94020000e-03],NEWLINE [-6.81100000e-04, -6.81100000e-04, 5.66900000e-04,NEWLINE -6.81100000e-04, -6.81100000e-04],NEWLINE [1.21370000e-03, 1.21370000e-03, -9.58800000e-04,NEWLINE 1.21370000e-03, 1.21370000e-03],NEWLINE [-1.51090000e-03, -1.51090000e-03, 1.13070000e-03,NEWLINE -1.51090000e-03, -1.51090000e-03],NEWLINE [3.21500000e-04, 3.21500000e-04, -2.27400000e-04,NEWLINE 3.21500000e-04, 3.21500000e-04],NEWLINE [-3.18500000e-04, -3.18500000e-04, 2.12600000e-04,NEWLINE -3.18500000e-04, -3.18500000e-04],NEWLINE [3.75600000e-04, 3.75600000e-04, -2.36300000e-04,NEWLINE 3.75600000e-04, 3.75600000e-04],NEWLINE [4.82300000e-04, 4.82300000e-04, -2.85500000e-04,NEWLINE 4.82300000e-04, 4.82300000e-04],NEWLINE [-1.41870000e-03, -1.41870000e-03, 7.89300000e-04,NEWLINE -1.41870000e-03, -1.41870000e-03],NEWLINE [6.75000000e-05, 6.75000000e-05, -3.52000000e-05,NEWLINE 6.75000000e-05, 6.75000000e-05],NEWLINE [4.06300000e-04, 4.06300000e-04, -1.99100000e-04,NEWLINE 4.06300000e-04, 4.06300000e-04],NEWLINE [-3.61500000e-04, -3.61500000e-04, 1.66000000e-04,NEWLINE -3.61500000e-04, -3.61500000e-04],NEWLINE [-2.97400000e-04, -2.97400000e-04, 1.28000000e-04,NEWLINE -2.97400000e-04, -2.97400000e-04],NEWLINE [-9.32700000e-04, -9.32700000e-04, 3.75800000e-04,NEWLINE -9.32700000e-04, -9.32700000e-04],NEWLINE [1.16270000e-03, 1.16270000e-03, -4.38500000e-04,NEWLINE 1.16270000e-03, 1.16270000e-03],NEWLINE [6.77900000e-04, 6.77900000e-04, -2.39200000e-04,NEWLINE 6.77900000e-04, 6.77900000e-04],NEWLINE [-1.29330000e-03, -1.29330000e-03, 4.27000000e-04,NEWLINE -1.29330000e-03, -1.29330000e-03],NEWLINE [2.24500000e-04, 2.24500000e-04, -6.94000000e-05,NEWLINE 2.24500000e-04, 2.24500000e-04],NEWLINE [1.05510000e-03, 1.05510000e-03, -3.04900000e-04,NEWLINE 1.05510000e-03, 1.05510000e-03],NEWLINE [2.50400000e-04, 2.50400000e-04, -6.77000000e-05,NEWLINE 2.50400000e-04, 2.50400000e-04],NEWLINE [4.08600000e-04, 4.08600000e-04, -1.03400000e-04,NEWLINE 4.08600000e-04, 4.08600000e-04],NEWLINE [-1.67610000e-03, -1.67610000e-03, 3.96800000e-04,NEWLINE -1.67610000e-03, -1.67610000e-03],NEWLINE [7.47600000e-04, 7.47600000e-04, -1.65700000e-04,NEWLINE 7.47600000e-04, 7.47600000e-04],NEWLINE [2.08200000e-04, 2.08200000e-04, -4.32000000e-05,NEWLINE 2.08200000e-04, 2.08200000e-04],NEWLINE [-8.00800000e-04, -8.00800000e-04, 1.55700000e-04,NEWLINE -8.00800000e-04, -8.00800000e-04],NEWLINE [5.81200000e-04, 5.81200000e-04, -1.05900000e-04,NEWLINE 5.81200000e-04, 5.81200000e-04],NEWLINE [1.00980000e-03, 1.00980000e-03, -1.72400000e-04,NEWLINE 1.00980000e-03, 1.00980000e-03],NEWLINE [2.77400000e-04, 2.77400000e-04, -4.44000000e-05,NEWLINE 2.77400000e-04, 2.77400000e-04],NEWLINE [-5.02800000e-04, -5.02800000e-04, 7.55000000e-05,NEWLINE -5.02800000e-04, -5.02800000e-04],NEWLINE [2.69800000e-04, 2.69800000e-04, -3.80000000e-05,NEWLINE 2.69800000e-04, 2.69800000e-04],NEWLINE [2.01300000e-04, 2.01300000e-04, -2.67000000e-05,NEWLINE 2.01300000e-04, 2.01300000e-04],NEWLINE [-1.19690000e-03, -1.19690000e-03, 1.48900000e-04,NEWLINE -1.19690000e-03, -1.19690000e-03],NEWLINE [-6.94200000e-04, -6.94200000e-04, 8.12000000e-05,NEWLINE -6.94200000e-04, -6.94200000e-04],NEWLINE [5.65500000e-04, 5.65500000e-04, -6.22000000e-05,NEWLINE 5.65500000e-04, 5.65500000e-04],NEWLINE [4.93100000e-04, 4.93100000e-04, -5.10000000e-05,NEWLINE 4.93100000e-04, 4.93100000e-04],NEWLINE [3.25000000e-04, 3.25000000e-04, -3.17000000e-05,NEWLINE 3.25000000e-04, 3.25000000e-04],NEWLINE [-7.70200000e-04, -7.70200000e-04, 7.07000000e-05,NEWLINE -7.70200000e-04, -7.70200000e-04],NEWLINE [2.58000000e-05, 2.58000000e-05, -2.23000000e-06,NEWLINE 2.58000000e-05, 2.58000000e-05],NEWLINE [-1.52800000e-04, -1.52800000e-04, 1.25000000e-05,NEWLINE -1.52800000e-04, -1.52800000e-04],NEWLINE [4.52000000e-05, 4.52000000e-05, -3.48000000e-06,NEWLINE 4.52000000e-05, 4.52000000e-05],NEWLINE [-6.83900000e-04, -6.83900000e-04, 4.97000000e-05,NEWLINE -6.83900000e-04, -6.83900000e-04],NEWLINE [-7.77600000e-04, -7.77600000e-04, 5.34000000e-05,NEWLINE -7.77600000e-04, -7.77600000e-04],NEWLINE [1.03170000e-03, 1.03170000e-03, -6.70000000e-05,NEWLINE 1.03170000e-03, 1.03170000e-03],NEWLINE [1.20000000e-03, 1.20000000e-03, -7.37000000e-05,NEWLINE 1.20000000e-03, 1.20000000e-03],NEWLINE [-7.71600000e-04, -7.71600000e-04, 4.48000000e-05,NEWLINE -7.71600000e-04, -7.71600000e-04],NEWLINE [-3.37000000e-04, -3.37000000e-04, 1.85000000e-05,NEWLINE -3.37000000e-04, -3.37000000e-04],NEWLINE [1.19880000e-03, 1.19880000e-03, -6.25000000e-05,NEWLINE 1.19880000e-03, 1.19880000e-03],NEWLINE [-1.54610000e-03, -1.54610000e-03, 7.64000000e-05,NEWLINE -1.54610000e-03, -1.54610000e-03],NEWLINE [9.11600000e-04, 9.11600000e-04, -4.27000000e-05,NEWLINE 9.11600000e-04, 9.11600000e-04],NEWLINE [-4.70800000e-04, -4.70800000e-04, 2.09000000e-05,NEWLINE -4.70800000e-04, -4.70800000e-04],NEWLINE [-1.21550000e-03, -1.21550000e-03, 5.13000000e-05,NEWLINE -1.21550000e-03, -1.21550000e-03],NEWLINE [1.09160000e-03, 1.09160000e-03, -4.37000000e-05,NEWLINE 1.09160000e-03, 1.09160000e-03],NEWLINE [-2.72000000e-04, -2.72000000e-04, 1.04000000e-05,NEWLINE -2.72000000e-04, -2.72000000e-04],NEWLINE [-7.84500000e-04, -7.84500000e-04, 2.84000000e-05,NEWLINE -7.84500000e-04, -7.84500000e-04],NEWLINE [1.53330000e-03, 1.53330000e-03, -5.28000000e-05,NEWLINE 1.53330000e-03, 1.53330000e-03],NEWLINE [-1.84450000e-03, -1.84450000e-03, 6.05000000e-05,NEWLINE -1.84450000e-03, -1.84450000e-03],NEWLINE [1.68550000e-03, 1.68550000e-03, -5.26000000e-05,NEWLINE 1.68550000e-03, 1.68550000e-03],NEWLINE [-3.06100000e-04, -3.06100000e-04, 9.10000000e-06,NEWLINE -3.06100000e-04, -3.06100000e-04],NEWLINE [1.00950000e-03, 1.00950000e-03, -2.86000000e-05,NEWLINE 1.00950000e-03, 1.00950000e-03],NEWLINE [5.22000000e-04, 5.22000000e-04, -1.41000000e-05,NEWLINE 5.22000000e-04, 5.22000000e-04],NEWLINE [-2.18000000e-05, -2.18000000e-05, 5.62000000e-07,NEWLINE -2.18000000e-05, -2.18000000e-05],NEWLINE [-7.80600000e-04, -7.80600000e-04, 1.92000000e-05,NEWLINE -7.80600000e-04, -7.80600000e-04],NEWLINE [6.81400000e-04, 6.81400000e-04, -1.60000000e-05,NEWLINE 6.81400000e-04, 6.81400000e-04],NEWLINE [-1.43800000e-04, -1.43800000e-04, 3.23000000e-06,NEWLINE -1.43800000e-04, -1.43800000e-04],NEWLINE [7.76000000e-04, 7.76000000e-04, -1.66000000e-05,NEWLINE 7.76000000e-04, 7.76000000e-04],NEWLINE [2.54900000e-04, 2.54900000e-04, -5.22000000e-06,NEWLINE 2.54900000e-04, 2.54900000e-04],NEWLINE [5.77500000e-04, 5.77500000e-04, -1.13000000e-05,NEWLINE 5.77500000e-04, 5.77500000e-04],NEWLINE [7.58100000e-04, 7.58100000e-04, -1.42000000e-05,NEWLINE 7.58100000e-04, 7.58100000e-04],NEWLINE [-8.31000000e-04, -8.31000000e-04, 1.49000000e-05,NEWLINE -8.31000000e-04, -8.31000000e-04],NEWLINE [-2.10340000e-03, -2.10340000e-03, 3.62000000e-05,NEWLINE -2.10340000e-03, -2.10340000e-03],NEWLINE [-8.89900000e-04, -8.89900000e-04, 1.47000000e-05,NEWLINE -8.89900000e-04, -8.89900000e-04],NEWLINE [1.08570000e-03, 1.08570000e-03, -1.71000000e-05,NEWLINE 1.08570000e-03, 1.08570000e-03],NEWLINE [-1.88600000e-04, -1.88600000e-04, 2.86000000e-06,NEWLINE -1.88600000e-04, -1.88600000e-04],NEWLINE [9.10000000e-05, 9.10000000e-05, -1.32000000e-06,NEWLINE 9.10000000e-05, 9.10000000e-05],NEWLINE [1.07700000e-03, 1.07700000e-03, -1.50000000e-05,NEWLINE 1.07700000e-03, 1.07700000e-03],NEWLINE [9.04100000e-04, 9.04100000e-04, -1.21000000e-05,NEWLINE 9.04100000e-04, 9.04100000e-04],NEWLINE [-2.20000000e-04, -2.20000000e-04, 2.83000000e-06,NEWLINE -2.20000000e-04, -2.20000000e-04],NEWLINE [-1.64030000e-03, -1.64030000e-03, 2.02000000e-05,NEWLINE -1.64030000e-03, -1.64030000e-03],NEWLINE [2.20600000e-04, 2.20600000e-04, -2.62000000e-06,NEWLINE 2.20600000e-04, 2.20600000e-04],NEWLINE [-2.78300000e-04, -2.78300000e-04, 3.17000000e-06,NEWLINE -2.78300000e-04, -2.78300000e-04],NEWLINE [-4.93000000e-04, -4.93000000e-04, 5.40000000e-06,NEWLINE -4.93000000e-04, -4.93000000e-04],NEWLINE [-1.85000000e-04, -1.85000000e-04, 1.95000000e-06,NEWLINE -1.85000000e-04, -1.85000000e-04],NEWLINE [-7.64000000e-04, -7.64000000e-04, 7.75000000e-06,NEWLINE -7.64000000e-04, -7.64000000e-04],NEWLINE [7.79600000e-04, 7.79600000e-04, -7.61000000e-06,NEWLINE 7.79600000e-04, 7.79600000e-04],NEWLINE [2.88400000e-04, 2.88400000e-04, -2.71000000e-06,NEWLINE 2.88400000e-04, 2.88400000e-04],NEWLINE [1.09370000e-03, 1.09370000e-03, -9.91000000e-06,NEWLINE 1.09370000e-03, 1.09370000e-03],NEWLINE [3.07000000e-04, 3.07000000e-04, -2.68000000e-06,NEWLINE 3.07000000e-04, 3.07000000e-04],NEWLINE [-8.76000000e-04, -8.76000000e-04, 7.37000000e-06,NEWLINE -8.76000000e-04, -8.76000000e-04],NEWLINE [-1.85300000e-04, -1.85300000e-04, 1.50000000e-06,NEWLINE -1.85300000e-04, -1.85300000e-04],NEWLINE [3.24700000e-04, 3.24700000e-04, -2.54000000e-06,NEWLINE 3.24700000e-04, 3.24700000e-04],NEWLINE [4.59600000e-04, 4.59600000e-04, -3.47000000e-06,NEWLINE 4.59600000e-04, 4.59600000e-04],NEWLINE [-2.73300000e-04, -2.73300000e-04, 1.99000000e-06,NEWLINE -2.73300000e-04, -2.73300000e-04],NEWLINE [1.32180000e-03, 1.32180000e-03, -9.29000000e-06,NEWLINE 1.32180000e-03, 1.32180000e-03],NEWLINE [-1.32620000e-03, -1.32620000e-03, 9.00000000e-06,NEWLINE -1.32620000e-03, -1.32620000e-03],NEWLINE [9.62000000e-05, 9.62000000e-05, -6.31000000e-07,NEWLINE 9.62000000e-05, 9.62000000e-05],NEWLINE [-6.04400000e-04, -6.04400000e-04, 3.83000000e-06,NEWLINE -6.04400000e-04, -6.04400000e-04],NEWLINE [-6.66300000e-04, -6.66300000e-04, 4.08000000e-06,NEWLINE -6.66300000e-04, -6.66300000e-04]])NEWLINE self.null_deviance = 6.8088354977561 # from R, Rpy bugNEWLINE self.params = np.array([1.00045997, 0.01991666, 0.00100126])NEWLINE self.bse = np.array([4.55214070e-04, 7.00529313e-05, 1.84478509e-06])NEWLINE self.aic_R = -1123.1528237643774NEWLINE self.aic_Stata = -11.25152876811373NEWLINE self.deviance = 7.1612915365488368e-05NEWLINE self.scale = 7.3827747608449547e-07NEWLINE self.llf = 565.57641188218872NEWLINE self.bic_Stata = -446.7014364279675NEWLINE self.df_model = 2NEWLINE self.df_resid = 97NEWLINE self.chi2 = 2704006.698904491NEWLINE self.fittedvalues = np.array([NEWLINE 0.99954024, 0.97906956, 0.95758077, 0.93526008, 0.91228657,NEWLINE 0.88882978, 0.8650479, 0.84108646, 0.81707757, 0.79313958,NEWLINE 0.76937709, 0.74588129, 0.72273051, 0.69999099, 0.67771773,NEWLINE 0.65595543, 0.63473944, 0.61409675, 0.59404691, 0.57460297,NEWLINE 0.55577231, 0.53755742, 0.51995663, 0.50296478, 0.48657379,NEWLINE 0.47077316, 0.4555505, 0.44089187, 0.42678213, 0.41320529,NEWLINE 0.40014475, 0.38758348, 0.37550428, 0.36388987, 0.35272306,NEWLINE 0.34198684, 0.33166446, 0.32173953, 0.31219604, 0.30301842,NEWLINE 0.29419156, 0.28570085, 0.27753216, 0.26967189, 0.26210695,NEWLINE 0.25482476, 0.24781324, 0.2410608, 0.23455636, 0.22828931,NEWLINE 0.22224947, 0.21642715, 0.21081306, 0.20539835, 0.20017455,NEWLINE 0.19513359, 0.19026777, 0.18556972, 0.18103243, 0.17664922,NEWLINE 0.1724137, 0.16831977, 0.16436164, 0.16053377, 0.15683086,NEWLINE 0.15324789, 0.14978003, 0.1464227, 0.14317153, 0.14002232,NEWLINE 0.13697109, 0.13401403, 0.1311475, 0.12836802, 0.12567228,NEWLINE 0.1230571, 0.12051944, 0.11805642, 0.11566526, 0.1133433,NEWLINE 0.11108802, 0.10889699, 0.10676788, 0.10469847, 0.10268664,NEWLINE 0.10073034, 0.09882763, 0.09697663, 0.09517555, 0.09342267,NEWLINE 0.09171634, 0.09005498, 0.08843707, 0.08686116, 0.08532585,NEWLINE 0.08382979, 0.0823717, 0.08095035, 0.07956453, 0.07821311])NEWLINENEWLINENEWLINEclass Star98(object):NEWLINE """NEWLINE Star98 class used with TestGlmBinomialNEWLINE """NEWLINE def __init__(self):NEWLINE self.params = (NEWLINE -0.0168150366, 0.0099254766, -0.0187242148,NEWLINE -0.0142385609, 0.2544871730, 0.2406936644, 0.0804086739,NEWLINE -1.9521605027, -0.3340864748, -0.1690221685, 0.0049167021,NEWLINE -0.0035799644, -0.0140765648, -0.0040049918, -0.0039063958,NEWLINE 0.0917143006, 0.0489898381, 0.0080407389, 0.0002220095,NEWLINE -0.0022492486, 2.9588779262)NEWLINE self.bse = (NEWLINE 4.339467e-04, 6.013714e-04, 7.435499e-04, 4.338655e-04,NEWLINE 2.994576e-02, 5.713824e-02, 1.392359e-02, 3.168109e-01,NEWLINE 6.126411e-02, 3.270139e-02, 1.253877e-03, 2.254633e-04,NEWLINE 1.904573e-03, 4.739838e-04, 9.623650e-04, 1.450923e-02,NEWLINE 7.451666e-03, 1.499497e-03, 2.988794e-05, 3.489838e-04,NEWLINE 1.546712e+00)NEWLINE self.null_deviance = 34345.3688931NEWLINE self.df_null = 302NEWLINE self.deviance = 4078.76541772NEWLINE self.df_resid = 282NEWLINE self.df_model = 20NEWLINE self.aic_R = 6039.22511799NEWLINE self.aic_Stata = 19.93143846737438NEWLINE self.bic_Stata = 2467.493504191302NEWLINE self.llf = -2998.61255899391 # from RNEWLINE self.llf_Stata = -2998.612927807218NEWLINE self.scale = 1.NEWLINE self.pearson_chi2 = 4051.921614NEWLINE self.prsquared = 0.8346NEWLINE self.prsquared_cox_snell = 1.0000NEWLINE self.resids = glm_test_resids.star98_residsNEWLINE self.fittedvalues = np.array([NEWLINE 0.5833118, 0.75144661, 0.50058272, 0.68534524, 0.32251021,NEWLINE 0.68693601, 0.33299827, 0.65624766, 0.49851481, 0.506736,NEWLINE 0.23954874, 0.86631452, 0.46432936, 0.44171873, 0.66797935,NEWLINE 0.73988491, 0.51966014, 0.42442446, 0.5649369, 0.59251634,NEWLINE 0.34798337, 0.56415024, 0.49974355, 0.3565539, 0.20752309,NEWLINE 0.18269097, 0.44932642, 0.48025128, 0.59965277, 0.58848671,NEWLINE 0.36264203, 0.33333196, 0.74253352, 0.5081886, 0.53421878,NEWLINE 0.56291445, 0.60205239, 0.29174423, 0.2954348, 0.32220414,NEWLINE 0.47977903, 0.23687535, 0.11776464, 0.1557423, 0.27854799,NEWLINE 0.22699533, 0.1819439, 0.32554433, 0.22681989, 0.15785389,NEWLINE 0.15268609, 0.61094772, 0.20743222, 0.51649059, 0.46502006,NEWLINE 0.41031788, 0.59523288, 0.65733285, 0.27835336, 0.2371213,NEWLINE 0.25137045, 0.23953942, 0.27854519, 0.39652413, 0.27023163,NEWLINE 0.61411863, 0.2212025, 0.42005842, 0.55940397, 0.35413774,NEWLINE 0.45724563, 0.57399437, 0.2168918, 0.58308738, 0.17181104,NEWLINE 0.49873249, 0.22832683, 0.14846056, 0.5028073, 0.24513863,NEWLINE 0.48202096, 0.52823155, 0.5086262, 0.46295993, 0.57869402,NEWLINE 0.78363217, 0.21144435, 0.2298366, 0.17954825, 0.32232586,NEWLINE 0.8343015, 0.56217006, 0.47367315, 0.52535649, 0.60350746,NEWLINE 0.43210701, 0.44712008, 0.35858239, 0.2521347, 0.19787004,NEWLINE 0.63256553, 0.51386532, 0.64997027, 0.13402072, 0.81756174,NEWLINE 0.74543642, 0.30825852, 0.23988707, 0.17273125, 0.27880599,NEWLINE 0.17395893, 0.32052828, 0.80467697, 0.18726218, 0.23842081,NEWLINE 0.19020381, 0.85835388, 0.58703615, 0.72415106, 0.64433695,NEWLINE 0.68766653, 0.32923663, 0.16352185, 0.38868816, 0.44980444,NEWLINE 0.74810044, 0.42973792, 0.53762581, 0.72714996, 0.61229484,NEWLINE 0.30267667, 0.24713253, 0.65086008, 0.48957265, 0.54955545,NEWLINE 0.5697156, 0.36406211, 0.48906545, 0.45919413, 0.4930565,NEWLINE 0.39785555, 0.5078719, 0.30159626, 0.28524393, 0.34687707,NEWLINE 0.22522042, 0.52947159, 0.29277287, 0.8585002, 0.60800389,NEWLINE 0.75830521, 0.35648175, 0.69508796, 0.45518355, 0.21567675,NEWLINE 0.39682985, 0.49042948, 0.47615798, 0.60588234, 0.62910299,NEWLINE 0.46005639, 0.71755165, 0.48852156, 0.47940661, 0.60128813,NEWLINE 0.16589699, 0.68512861, 0.46305199, 0.68832227, 0.7006721,NEWLINE 0.56564937, 0.51753941, 0.54261733, 0.56072214, 0.34545715,NEWLINE 0.30226104, 0.3572956, 0.40996287, 0.33517519, 0.36248407,NEWLINE 0.33937041, 0.34140691, 0.2627528, 0.29955161, 0.38581683,NEWLINE 0.24840026, 0.15414272, 0.40415991, 0.53936252, 0.52111887,NEWLINE 0.28060168, 0.45600958, 0.51110589, 0.43757523, 0.46891953,NEWLINE 0.39425249, 0.5834369, 0.55817308, 0.32051259, 0.43567448,NEWLINE 0.34134195, 0.43016545, 0.4885413, 0.28478325, 0.2650776,NEWLINE 0.46784606, 0.46265983, 0.42655938, 0.18972234, 0.60448491,NEWLINE 0.211896, 0.37886032, 0.50727577, 0.39782309, 0.50427121,NEWLINE 0.35882898, 0.39596807, 0.49160806, 0.35618002, 0.6819922,NEWLINE 0.36871093, 0.43079679, 0.67985516, 0.41270595, 0.68952767,NEWLINE 0.52587734, 0.32042126, 0.39120123, 0.56870985, 0.32962349,NEWLINE 0.32168989, 0.54076251, 0.4592907, 0.48480182, 0.4408386,NEWLINE 0.431178, 0.47078232, 0.55911605, 0.30331618, 0.50310393,NEWLINE 0.65036038, 0.45078895, 0.62354291, 0.56435463, 0.50034281,NEWLINE 0.52693538, 0.57217285, 0.49221472, 0.40707122, 0.44226533,NEWLINE 0.3475959, 0.54746396, 0.86385832, 0.48402233, 0.54313657,NEWLINE 0.61586824, 0.27097185, 0.69717808, 0.52156974, 0.50401189,NEWLINE 0.56724181, 0.6577178, 0.42732047, 0.44808396, 0.65435634,NEWLINE 0.54766225, 0.38160648, 0.49890847, 0.50879037, 0.5875452,NEWLINE 0.45101593, 0.5709704, 0.3175516, 0.39813159, 0.28305688,NEWLINE 0.40521062, 0.30120578, 0.26400428, 0.44205496, 0.40545798,NEWLINE 0.39366599, 0.55288196, 0.14104184, 0.17550155, 0.1949095,NEWLINE 0.40255144, 0.21016822, 0.09712017, 0.63151487, 0.25885514,NEWLINE 0.57323748, 0.61836898, 0.43268601, 0.67008878, 0.75801989,NEWLINE 0.50353406, 0.64222315, 0.29925757, 0.32592036, 0.39634977,NEWLINE 0.39582747, 0.41037006, 0.34174944])NEWLINENEWLINENEWLINEclass Lbw(object):NEWLINE '''NEWLINE The LBW data can be found hereNEWLINENEWLINE https://www.stata-press.com/data/r9/rmain.htmlNEWLINE '''NEWLINE def __init__(self):NEWLINE # data set up for data not in datasetsNEWLINE filename = os.path.join(os.path.dirname(os.path.abspath(__file__)),NEWLINE "stata_lbw_glm.csv")NEWLINENEWLINE data = pd.read_csv(filename)NEWLINE dummies = pd.get_dummies(data.race, prefix="race", drop_first=False)NEWLINE data = pd.concat([data, dummies], axis=1)NEWLINE self.endog = data.lowNEWLINE design = data[["age", "lwt", "race_black", "race_other", "smoke",NEWLINE "ptl", "ht", "ui"]]NEWLINE self.exog = add_constant(design, prepend=False)NEWLINE # Results for Canonical Logit LinkNEWLINE self.params = (NEWLINE -.02710031, -.01515082, 1.26264728,NEWLINE .86207916, .92334482, .54183656, 1.83251780,NEWLINE .75851348, .46122388)NEWLINE self.bse = (NEWLINE 0.036449917, 0.006925765, 0.526405169,NEWLINE 0.439146744, 0.400820976, 0.346246857, 0.691623875,NEWLINE 0.459373871, 1.204574885)NEWLINE self.aic_R = 219.447991133NEWLINE self.aic_Stata = 1.161100482182551NEWLINE self.deviance = 201.4479911325021NEWLINE self.scale = 1NEWLINE self.llf = -100.7239955662511NEWLINE self.chi2 = 25.65329337867037 # from Stata not used by smNEWLINE self.null_deviance = 234.671996193219NEWLINE self.bic_Stata = -742.0664715782335NEWLINE self.df_resid = 180NEWLINE self.df_model = 8NEWLINE self.df_null = 188NEWLINE self.pearson_chi2 = 182.023342493558NEWLINE self.resids = glm_test_resids.lbw_residsNEWLINE self.fittedvalues = np.array([NEWLINE 0.31217507, 0.12793027, 0.32119762, 0.48442686, 0.50853393,NEWLINE 0.24517662, 0.12755193, 0.33226988, 0.22013309, 0.26268069,NEWLINE 0.34729955, 0.18782188, 0.75404181, 0.54723527, 0.35016393,NEWLINE 0.35016393, 0.45824406, 0.25336683, 0.43087357, 0.23284101,NEWLINE 0.20146616, 0.24315597, 0.02725586, 0.22207692, 0.39800383,NEWLINE 0.05584178, 0.28403447, 0.06931188, 0.35371946, 0.3896279,NEWLINE 0.3896279, 0.47812002, 0.60043853, 0.07144772, 0.29995988,NEWLINE 0.17910031, 0.22773411, 0.22691015, 0.06221253, 0.2384528,NEWLINE 0.32633864, 0.05131047, 0.2954536, 0.07364416, 0.57241299,NEWLINE 0.57241299, 0.08272435, 0.23298882, 0.12658158, 0.58967487,NEWLINE 0.46989562, 0.22455631, 0.2348285, 0.29571887, 0.28212464,NEWLINE 0.31499013, 0.68340511, 0.14090647, 0.31448425, 0.28082972,NEWLINE 0.28082972, 0.24918728, 0.27018297, 0.08175784, 0.64808999,NEWLINE 0.38252574, 0.25550797, 0.09113411, 0.40736693, 0.32644055,NEWLINE 0.54367425, 0.29606968, 0.47028421, 0.39972155, 0.25079125,NEWLINE 0.09678472, 0.08807264, 0.27467837, 0.5675742, 0.045619,NEWLINE 0.10719293, 0.04826292, 0.23934092, 0.24179618, 0.23802197,NEWLINE 0.49196179, 0.31379451, 0.10605469, 0.04047396, 0.11620849,NEWLINE 0.09937016, 0.21822964, 0.29770265, 0.83912829, 0.25079125,NEWLINE 0.08548557, 0.06550308, 0.2046457, 0.2046457, 0.08110349,NEWLINE 0.13519643, 0.47862055, 0.38891913, 0.1383964, 0.26176764,NEWLINE 0.31594589, 0.11418612, 0.06324112, 0.28468594, 0.21663702,NEWLINE 0.03827107, 0.27237604, 0.20246694, 0.19042999, 0.15019447,NEWLINE 0.18759474, 0.12308435, 0.19700616, 0.11564002, 0.36595033,NEWLINE 0.07765727, 0.14119063, 0.13584627, 0.11012759, 0.10102472,NEWLINE 0.10002166, 0.07439288, 0.27919958, 0.12491598, 0.06774594,NEWLINE 0.72513764, 0.17714986, 0.67373352, 0.80679436, 0.52908941,NEWLINE 0.15695938, 0.49722003, 0.41970014, 0.62375224, 0.53695622,NEWLINE 0.25474238, 0.79135707, 0.2503871, 0.25352337, 0.33474211,NEWLINE 0.19308929, 0.24658944, 0.25495092, 0.30867144, 0.41240259,NEWLINE 0.59412526, 0.16811226, 0.48282791, 0.36566756, 0.09279325,NEWLINE 0.75337353, 0.57128885, 0.52974123, 0.44548504, 0.77748843,NEWLINE 0.3224082, 0.40054277, 0.29522468, 0.19673553, 0.73781774,NEWLINE 0.57680312, 0.44545573, 0.30242355, 0.38720223, 0.16632904,NEWLINE 0.30804092, 0.56385194, 0.60012179, 0.48324821, 0.24636345,NEWLINE 0.26153216, 0.2348285, 0.29023669, 0.41011454, 0.36472083,NEWLINE 0.65922069, 0.30476903, 0.09986775, 0.70658332, 0.30713075,NEWLINE 0.36096386, 0.54962701, 0.71996086, 0.6633756])NEWLINENEWLINENEWLINEclass Scotvote(object):NEWLINE """NEWLINE Scotvot class is used with TestGlmGamma.NEWLINE """NEWLINE def __init__(self):NEWLINE self.params = (NEWLINE 4.961768e-05, 2.034423e-03, -7.181429e-05, 1.118520e-04,NEWLINE -1.467515e-07, -5.186831e-04, -2.42717498e-06, -1.776527e-02)NEWLINE self.bse = (NEWLINE 1.621577e-05, 5.320802e-04, 2.711664e-05, 4.057691e-05,NEWLINE 1.236569e-07, 2.402534e-04, 7.460253e-07, 1.147922e-02)NEWLINE self.null_deviance = 0.536072NEWLINE self.df_null = 31NEWLINE self.deviance = 0.087388516417NEWLINE self.df_resid = 24NEWLINE self.df_model = 7NEWLINE self.aic_R = 182.947045954721NEWLINE self.aic_Stata = 10.72212NEWLINE self.bic_Stata = -83.09027NEWLINE self.llf = -163.5539382 # from Stata, same as ours with scale = 1NEWLINE # self.llf = -82.47352 # Very close to ours as isNEWLINE self.scale = 0.003584283NEWLINE self.pearson_chi2 = .0860228056NEWLINE self.prsquared = 0.429NEWLINE self.prsquared_cox_snell = 0.97971NEWLINE self.resids = glm_test_resids.scotvote_residsNEWLINE self.fittedvalues = np.array([NEWLINE 57.80431482, 53.2733447, 50.56347993, 58.33003783,NEWLINE 70.46562169, 56.88801284, 66.81878401, 66.03410393,NEWLINE 57.92937473, 63.23216907, 53.9914785, 61.28993391,NEWLINE 64.81036393, 63.47546816, 60.69696114, 74.83508176,NEWLINE 56.56991106, 72.01804172, 64.35676519, 52.02445881,NEWLINE 64.24933079, 71.15070332, 45.73479688, 54.93318588,NEWLINE 66.98031261, 52.02479973, 56.18413736, 58.12267471,NEWLINE 67.37947398, 60.49162862, 73.82609217, 69.61515621])NEWLINENEWLINENEWLINEclass Cancer(object):NEWLINE '''NEWLINE The Cancer data can be found hereNEWLINENEWLINE https://www.stata-press.com/data/r10/rmain.htmlNEWLINE '''NEWLINE def __init__(self):NEWLINE filename = os.path.join(os.path.dirname(os.path.abspath(__file__)),NEWLINE "stata_cancer_glm.csv")NEWLINE data = np.recfromcsv(open(filename, 'rb'))NEWLINE self.endog = data.studytimeNEWLINE dummies = pd.get_dummies(pd.Series(data.drug, dtype="category"),NEWLINE drop_first=True)NEWLINE design = np.column_stack((data.age, dummies)).astype(float)NEWLINE self.exog = add_constant(design, prepend=False)NEWLINENEWLINENEWLINEclass CancerLog(Cancer):NEWLINE """NEWLINE CancerLog is used TestGlmGammaLogNEWLINE """NEWLINE def __init__(self):NEWLINE super(CancerLog, self).__init__()NEWLINENEWLINE self.resids = np.array([NEWLINE [-8.52598100e-01, -1.45739100e+00, -3.92408100e+01,NEWLINE -1.41526900e+00, -5.78417200e+00],NEWLINE [-8.23683800e-01, -1.35040200e+00, -2.64957500e+01,NEWLINE -1.31777000e+00, -4.67162900e+00],NEWLINE [-7.30450400e-01, -1.07754600e+00, -4.02136400e+01,NEWLINE -1.06208800e+00, -5.41978500e+00],NEWLINE [-7.04471600e-01, -1.01441500e+00, -7.25951500e+01,NEWLINE -1.00172900e+00, -7.15130900e+00],NEWLINE [-5.28668000e-01, -6.68617300e-01, -3.80758100e+01,NEWLINE -6.65304600e-01, -4.48658700e+00],NEWLINE [-2.28658500e-01, -2.48859700e-01, -6.14913600e+00,NEWLINE -2.48707200e-01, -1.18577100e+00],NEWLINE [-1.93939400e-01, -2.08119900e-01, -7.46226500e+00,NEWLINE -2.08031700e-01, -1.20300800e+00],NEWLINE [-3.55635700e-01, -4.09525000e-01, -2.14132500e+01,NEWLINE -4.08815100e-01, -2.75958600e+00],NEWLINE [-5.73360000e-02, -5.84700000e-02, -4.12946200e+00,NEWLINE -5.84681000e-02, -4.86586900e-01],NEWLINE [3.09828000e-02, 3.06685000e-02, 1.86551100e+00,NEWLINE 3.06682000e-02, 2.40413800e-01],NEWLINE [-2.11924300e-01, -2.29071300e-01, -2.18386100e+01,NEWLINE -2.28953000e-01, -2.15130900e+00],NEWLINE [-3.10989000e-01, -3.50739300e-01, -4.19249500e+01,NEWLINE -3.50300400e-01, -3.61084500e+00],NEWLINE [-9.22250000e-03, -9.25100000e-03, -1.13679700e+00,NEWLINE -9.25100000e-03, -1.02392100e-01],NEWLINE [2.39402500e-01, 2.22589700e-01, 1.88577300e+01,NEWLINE 2.22493500e-01, 2.12475600e+00],NEWLINE [3.35166000e-02, 3.31493000e-02, 4.51842400e+00,NEWLINE 3.31489000e-02, 3.89155400e-01],NEWLINE [8.49829400e-01, 6.85180200e-01, 3.57627500e+01,NEWLINE 6.82689900e-01, 5.51291500e+00],NEWLINE [4.12934200e-01, 3.66785200e-01, 4.65392600e+01,NEWLINE 3.66370400e-01, 4.38379500e+00],NEWLINE [4.64148400e-01, 4.07123200e-01, 6.25726500e+01,NEWLINE 4.06561900e-01, 5.38915500e+00],NEWLINE [1.71104600e+00, 1.19474800e+00, 1.12676500e+02,NEWLINE 1.18311900e+00, 1.38850500e+01],NEWLINE [1.26571800e+00, 9.46389000e-01, 1.30431000e+02,NEWLINE 9.40244600e-01, 1.28486900e+01],NEWLINE [-3.48532600e-01, -3.99988300e-01, -2.95638100e+01,NEWLINE -3.99328600e-01, -3.20997700e+00],NEWLINE [-4.04340300e-01, -4.76960100e-01, -4.10254300e+01,NEWLINE -4.75818000e-01, -4.07286500e+00],NEWLINE [-4.92057900e-01, -6.08818300e-01, -9.34509600e+01,NEWLINE -6.06357200e-01, -6.78109700e+00],NEWLINE [-4.02876400e-01, -4.74878400e-01, -9.15226200e+01,NEWLINE -4.73751900e-01, -6.07225700e+00],NEWLINE [-5.15056700e-01, -6.46013300e-01, -2.19014600e+02,NEWLINE -6.43043500e-01, -1.06209700e+01],NEWLINE [-8.70423000e-02, -8.97043000e-02, -1.26361400e+01,NEWLINE -8.96975000e-02, -1.04875100e+00],NEWLINE [1.28362300e-01, 1.23247800e-01, 1.70383300e+01,NEWLINE 1.23231000e-01, 1.47887800e+00],NEWLINE [-2.39271900e-01, -2.61562100e-01, -9.30283300e+01,NEWLINE -2.61384400e-01, -4.71795100e+00],NEWLINE [7.37246500e-01, 6.08186000e-01, 6.25359600e+01,NEWLINE 6.06409700e-01, 6.79002300e+00],NEWLINE [-3.64110000e-02, -3.68626000e-02, -1.41565300e+01,NEWLINE -3.68621000e-02, -7.17951200e-01],NEWLINE [2.68833000e-01, 2.47933100e-01, 6.67934100e+01,NEWLINE 2.47801000e-01, 4.23748400e+00],NEWLINE [5.96389600e-01, 5.07237700e-01, 1.13265500e+02,NEWLINE 5.06180100e-01, 8.21890300e+00],NEWLINE [1.98218000e-02, 1.96923000e-02, 1.00820900e+01,NEWLINE 1.96923000e-02, 4.47040700e-01],NEWLINE [7.74936000e-01, 6.34305300e-01, 2.51883900e+02,NEWLINE 6.32303700e-01, 1.39711800e+01],NEWLINE [-7.63925100e-01, -1.16591700e+00, -4.93461700e+02,NEWLINE -1.14588000e+00, -1.94156600e+01],NEWLINE [-6.23771700e-01, -8.41174800e-01, -4.40679600e+02,NEWLINE -8.34266300e-01, -1.65796100e+01],NEWLINE [-1.63272900e-01, -1.73115100e-01, -6.73975900e+01,NEWLINE -1.73064800e-01, -3.31725800e+00],NEWLINE [-4.28562500e-01, -5.11932900e-01, -4.73787800e+02,NEWLINE -5.10507400e-01, -1.42494800e+01],NEWLINE [8.00693000e-02, 7.80269000e-02, 3.95353400e+01,NEWLINE 7.80226000e-02, 1.77920500e+00],NEWLINE [-2.13674400e-01, -2.31127400e-01, -2.15987000e+02,NEWLINE -2.31005700e-01, -6.79344600e+00],NEWLINE [-1.63544000e-02, -1.64444000e-02, -1.05642100e+01,NEWLINE -1.64444000e-02, -4.15657600e-01],NEWLINE [2.04900500e-01, 1.92372100e-01, 1.10651300e+02,NEWLINE 1.92309400e-01, 4.76156600e+00],NEWLINE [-1.94758900e-01, -2.09067700e-01, -2.35484100e+02,NEWLINE -2.08978200e-01, -6.77219400e+00],NEWLINE [3.16727400e-01, 2.88367800e-01, 1.87065600e+02,NEWLINE 2.88162100e-01, 7.69732400e+00],NEWLINE [6.24234900e-01, 5.27632500e-01, 2.57678500e+02,NEWLINE 5.26448400e-01, 1.26827400e+01],NEWLINE [8.30241100e-01, 6.72002100e-01, 2.86513700e+02,NEWLINE 6.69644800e-01, 1.54232100e+01],NEWLINE [6.55140000e-03, 6.53710000e-03, 7.92130700e+00,NEWLINE 6.53710000e-03, 2.27805800e-01],NEWLINE [3.41595200e-01, 3.08985000e-01, 2.88667600e+02,NEWLINE 3.08733300e-01, 9.93012900e+00]])NEWLINE self.null_deviance = 27.92207137420696 # From R (bug in rpy)NEWLINE self.params = np.array([NEWLINE -0.04477778, 0.57437126, 1.05210726, 4.64604002])NEWLINE self.bse = np.array([0.0147328, 0.19694727, 0.19772507, 0.83534671])NEWLINENEWLINE self.aic_R = 331.89022395372069NEWLINENEWLINE self.aic_Stata = 7.403608467857651NEWLINE self.deviance = 16.174635536991005NEWLINE self.scale = 0.31805268736385695NEWLINENEWLINE # self.llf = -160.94511197686035 # From RNEWLINE self.llf = -173.6866032285836 # from StaaNEWLINE self.bic_Stata = -154.1582089453923 # from StataNEWLINE self.df_model = 3NEWLINE self.df_resid = 44NEWLINE self.chi2 = 36.77821448266359 # from Stata not in smNEWLINENEWLINE self.fittedvalues = np.array([NEWLINE 6.78419193, 5.67167253, 7.41979002, 10.15123371,NEWLINE 8.48656317, 5.18582263, 6.20304079, 7.75958258,NEWLINE 8.48656317, 7.75958258, 10.15123371, 11.61071755,NEWLINE 11.10228357, 8.87520908, 11.61071755, 6.48711178,NEWLINE 10.61611394, 11.61071755, 8.11493609, 10.15123371,NEWLINE 9.21009116, 10.07296716, 13.78112366, 15.07225103,NEWLINE 20.62079147, 12.04881666, 11.5211983, 19.71780584,NEWLINE 9.21009116, 19.71780584, 15.76249142, 13.78112366,NEWLINE 22.55271436, 18.02872842, 25.41575239, 26.579678,NEWLINE 20.31745227, 33.24937131, 22.22095589, 31.79337946,NEWLINE 25.41575239, 23.23857437, 34.77204095, 24.30279515,NEWLINE 20.31745227, 18.57700761, 34.77204095, 29.06987768])NEWLINENEWLINENEWLINEclass CancerIdentity(Cancer):NEWLINE """NEWLINE CancerIdentity is used with TestGlmGammaIdentityNEWLINE """NEWLINE def __init__(self):NEWLINE super(CancerIdentity, self).__init__()NEWLINENEWLINE self.resids = np.array([NEWLINE [-8.52598100e-01, -1.45739100e+00, -3.92408100e+01,NEWLINE -1.41526900e+00, -5.78417200e+00],NEWLINE [-8.23683800e-01, -1.35040200e+00, -2.64957500e+01,NEWLINE -1.31777000e+00, -4.67162900e+00],NEWLINE [-7.30450400e-01, -1.07754600e+00, -4.02136400e+01,NEWLINE -1.06208800e+00, -5.41978500e+00],NEWLINE [-7.04471600e-01, -1.01441500e+00, -7.25951500e+01,NEWLINE -1.00172900e+00, -7.15130900e+00],NEWLINE [-5.28668000e-01, -6.68617300e-01, -3.80758100e+01,NEWLINE -6.65304600e-01, -4.48658700e+00],NEWLINE [-2.28658500e-01, -2.48859700e-01, -6.14913600e+00,NEWLINE -2.48707200e-01, -1.18577100e+00],NEWLINE [-1.93939400e-01, -2.08119900e-01, -7.46226500e+00,NEWLINE -2.08031700e-01, -1.20300800e+00],NEWLINE [-3.55635700e-01, -4.09525000e-01, -2.14132500e+01,NEWLINE -4.08815100e-01, -2.75958600e+00],NEWLINE [-5.73360000e-02, -5.84700000e-02, -4.12946200e+00,NEWLINE -5.84681000e-02, -4.86586900e-01],NEWLINE [3.09828000e-02, 3.06685000e-02, 1.86551100e+00,NEWLINE 3.06682000e-02, 2.40413800e-01],NEWLINE [-2.11924300e-01, -2.29071300e-01, -2.18386100e+01,NEWLINE -2.28953000e-01, -2.15130900e+00],NEWLINE [-3.10989000e-01, -3.50739300e-01, -4.19249500e+01,NEWLINE -3.50300400e-01, -3.61084500e+00],NEWLINE [-9.22250000e-03, -9.25100000e-03, -1.13679700e+00,NEWLINE -9.25100000e-03, -1.02392100e-01],NEWLINE [2.39402500e-01, 2.22589700e-01, 1.88577300e+01,NEWLINE 2.22493500e-01, 2.12475600e+00],NEWLINE [3.35166000e-02, 3.31493000e-02, 4.51842400e+00,NEWLINE 3.31489000e-02, 3.89155400e-01],NEWLINE [8.49829400e-01, 6.85180200e-01, 3.57627500e+01,NEWLINE 6.82689900e-01, 5.51291500e+00],NEWLINE [4.12934200e-01, 3.66785200e-01, 4.65392600e+01,NEWLINE 3.66370400e-01, 4.38379500e+00],NEWLINE [4.64148400e-01, 4.07123200e-01, 6.25726500e+01,NEWLINE 4.06561900e-01, 5.38915500e+00],NEWLINE [1.71104600e+00, 1.19474800e+00, 1.12676500e+02,NEWLINE 1.18311900e+00, 1.38850500e+01],NEWLINE [1.26571800e+00, 9.46389000e-01, 1.30431000e+02,NEWLINE 9.40244600e-01, 1.28486900e+01],NEWLINE [-3.48532600e-01, -3.99988300e-01, -2.95638100e+01,NEWLINE -3.99328600e-01, -3.20997700e+00],NEWLINE [-4.04340300e-01, -4.76960100e-01, -4.10254300e+01,NEWLINE -4.75818000e-01, -4.07286500e+00],NEWLINE [-4.92057900e-01, -6.08818300e-01, -9.34509600e+01,NEWLINE -6.06357200e-01, -6.78109700e+00],NEWLINE [-4.02876400e-01, -4.74878400e-01, -9.15226200e+01,NEWLINE -4.73751900e-01, -6.07225700e+00],NEWLINE [-5.15056700e-01, -6.46013300e-01, -2.19014600e+02,NEWLINE -6.43043500e-01, -1.06209700e+01],NEWLINE [-8.70423000e-02, -8.97043000e-02, -1.26361400e+01,NEWLINE -8.96975000e-02, -1.04875100e+00],NEWLINE [1.28362300e-01, 1.23247800e-01, 1.70383300e+01,NEWLINE 1.23231000e-01, 1.47887800e+00],NEWLINE [-2.39271900e-01, -2.61562100e-01, -9.30283300e+01,NEWLINE -2.61384400e-01, -4.71795100e+00],NEWLINE [7.37246500e-01, 6.08186000e-01, 6.25359600e+01,NEWLINE 6.06409700e-01, 6.79002300e+00],NEWLINE [-3.64110000e-02, -3.68626000e-02, -1.41565300e+01,NEWLINE -3.68621000e-02, -7.17951200e-01],NEWLINE [2.68833000e-01, 2.47933100e-01, 6.67934100e+01,NEWLINE 2.47801000e-01, 4.23748400e+00],NEWLINE [5.96389600e-01, 5.07237700e-01, 1.13265500e+02,NEWLINE 5.06180100e-01, 8.21890300e+00],NEWLINE [1.98218000e-02, 1.96923000e-02, 1.00820900e+01,NEWLINE 1.96923000e-02, 4.47040700e-01],NEWLINE [7.74936000e-01, 6.34305300e-01, 2.51883900e+02,NEWLINE 6.32303700e-01, 1.39711800e+01],NEWLINE [-7.63925100e-01, -1.16591700e+00, -4.93461700e+02,NEWLINE -1.14588000e+00, -1.94156600e+01],NEWLINE [-6.23771700e-01, -8.41174800e-01, -4.40679600e+02,NEWLINE -8.34266300e-01, -1.65796100e+01],NEWLINE [-1.63272900e-01, -1.73115100e-01, -6.73975900e+01,NEWLINE -1.73064800e-01, -3.31725800e+00],NEWLINE [-4.28562500e-01, -5.11932900e-01, -4.73787800e+02,NEWLINE -5.10507400e-01, -1.42494800e+01],NEWLINE [8.00693000e-02, 7.80269000e-02, 3.95353400e+01,NEWLINE 7.80226000e-02, 1.77920500e+00],NEWLINE [-2.13674400e-01, -2.31127400e-01, -2.15987000e+02,NEWLINE -2.31005700e-01, -6.79344600e+00],NEWLINE [-1.63544000e-02, -1.64444000e-02, -1.05642100e+01,NEWLINE -1.64444000e-02, -4.15657600e-01],NEWLINE [2.04900500e-01, 1.92372100e-01, 1.10651300e+02,NEWLINE 1.92309400e-01, 4.76156600e+00],NEWLINE [-1.94758900e-01, -2.09067700e-01, -2.35484100e+02,NEWLINE -2.08978200e-01, -6.77219400e+00],NEWLINE [3.16727400e-01, 2.88367800e-01, 1.87065600e+02,NEWLINE 2.88162100e-01, 7.69732400e+00],NEWLINE [6.24234900e-01, 5.27632500e-01, 2.57678500e+02,NEWLINE 5.26448400e-01, 1.26827400e+01],NEWLINE [8.30241100e-01, 6.72002100e-01, 2.86513700e+02,NEWLINE 6.69644800e-01, 1.54232100e+01],NEWLINE [6.55140000e-03, 6.53710000e-03, 7.92130700e+00,NEWLINE 6.53710000e-03, 2.27805800e-01],NEWLINE [3.41595200e-01, 3.08985000e-01, 2.88667600e+02,NEWLINE 3.08733300e-01, 9.93012900e+00]])NEWLINENEWLINE self.params = np.array([NEWLINE -0.5369833, 6.47296332, 16.20336802, 38.96617431])NEWLINE self.bse = np.array([NEWLINE 0.13341238, 2.1349966, 3.87411875, 8.19235553])NEWLINENEWLINE self.aic_R = 328.39209118952965NEWLINENEWLINE # TODO: the below will failNEWLINE self.aic_Stata = 7.381090276021671NEWLINE self.deviance = 15.093762327607557NEWLINE self.scale = 0.29512089119443752NEWLINE self.null_deviance = 27.92207137420696 # from R bug in RPyNEWLINE # NOTE: our scale is Stata's dispers_p (pearson?)NEWLINE # TODO: if scale is analagous to Stata's dispersion, then this might beNEWLINE # where the discrepancies come from?NEWLINE # self.llf = -159.19604559476483 # From RNEWLINE self.llf = -173.1461666245201 # From StataNEWLINE self.bic_Stata = -155.2390821535193NEWLINE self.df_model = 3NEWLINE self.df_resid = 44NEWLINE self.chi2 = 51.56632068622578NEWLINE self.fittedvalues = np.array([NEWLINE 6.21019277, 4.06225956,NEWLINE 7.28415938, 11.04304251,NEWLINE 8.89510929, 2.98829295, 5.13622616, 7.82114268,NEWLINE 8.89510929, 7.82114268, 11.04304251, 12.65399242,NEWLINE 12.11700911, 9.43209259, 12.65399242, 5.67320947,NEWLINE 11.58002581, 12.65399242, 8.35812599, 11.04304251,NEWLINE 9.46125627, 10.53522287, 14.294106, 15.36807261,NEWLINE 19.12695574, 12.68315609, 12.14617279, 18.58997243,NEWLINE 9.46125627, 18.58997243, 15.90505591, 14.294106,NEWLINE 20.20092234, 17.51600582, 25.63546061, 26.17244391,NEWLINE 22.95054409, 28.85736043, 24.0245107, 28.32037713,NEWLINE 25.63546061, 24.561494, 29.39434374, 25.09847731,NEWLINE 22.95054409, 21.87657748, 29.39434374, 27.24641052])NEWLINENEWLINENEWLINEclass Cpunish(object):NEWLINE '''NEWLINE The following are from the R script in models.datasets.cpunishNEWLINE Slightly different than published results, but should be correctNEWLINE Probably due to rounding in cleaning?NEWLINE '''NEWLINE def __init__(self):NEWLINE self.params = (NEWLINE 2.611017e-04, 7.781801e-02, -9.493111e-02, 2.969349e-01,NEWLINE 2.301183e+00, -1.872207e+01, -6.801480e+00)NEWLINE self.bse = (NEWLINE 5.187132e-05, 7.940193e-02, 2.291926e-02, 4.375164e-01,NEWLINE 4.283826e-01, 4.283961e+00, 4.146850e+00)NEWLINE self.null_deviance = 136.57281747225NEWLINE self.df_null = 16NEWLINE self.deviance = 18.591641759528944NEWLINE self.df_resid = 10NEWLINE self.df_model = 6NEWLINE self.aic_R = 77.8546573896503 # same as StataNEWLINE self.aic_Stata = 4.579685683305706NEWLINE self.bic_Stata = -9.740492454486446NEWLINE self.chi2 = 128.8021169250578 # from Stata not in smNEWLINE self.llf = -31.92732869482515NEWLINE self.scale = 1NEWLINE self.pearson_chi2 = 24.75374835NEWLINE self.resids = glm_test_resids.cpunish_residsNEWLINE self.fittedvalues = np.array([NEWLINE 35.2263655, 8.1965744, 1.3118966,NEWLINE 3.6862982, 2.0823003, 1.0650316, 1.9260424, 2.4171405,NEWLINE 1.8473219, 2.8643241, 3.1211989, 3.3382067, 2.5269969,NEWLINE 0.8972542, 0.9793332, 0.5346209, 1.9790936])NEWLINENEWLINENEWLINEclass Cpunish_offset(Cpunish):NEWLINE '''NEWLINE Same model as Cpunish but with offset of 100. Many things do not change.NEWLINE '''NEWLINE def __init__(self):NEWLINE super(Cpunish_offset, self).__init__()NEWLINENEWLINE self.params = (NEWLINE -1.140665e+01, 2.611017e-04, 7.781801e-02,NEWLINE -9.493111e-02, 2.969349e-01, 2.301183e+00,NEWLINE -1.872207e+01)NEWLINE self.bse = (NEWLINE 4.147e+00, 5.187e-05, 7.940e-02, 2.292e-02,NEWLINE 4.375e-01, 4.284e-01, 4.284e+00)NEWLINENEWLINENEWLINEclass InvGauss(object):NEWLINE '''NEWLINE UsefNEWLINENEWLINE Data was generated by Hardin and Hilbe using Stata.NEWLINE Note only the first 5000 observations are used becauseNEWLINE the models code currently uses np.eye.NEWLINE '''NEWLINE # FIXME: do something with the commented-out code belowNEWLINE # np.random.seed(54321)NEWLINE # x1 = np.abs(stats.norm.ppf((np.random.random(5000))))NEWLINE # x2 = np.abs(stats.norm.ppf((np.random.random(5000))))NEWLINE # X = np.column_stack((x1, x2))NEWLINE # X = add_constant(X)NEWLINE # params = np.array([.5, -.25, 1])NEWLINE # eta = np.dot(X, params)NEWLINE # mu = 1/np.sqrt(eta)NEWLINE # sigma = .5NEWLINE # This is not correct. Errors need to be normally distributedNEWLINE # But Y needs to be Inverse Gaussian, so we could build it upNEWLINE # by throwing out data?NEWLINE # Refs:NEWLINE # * Lai (2009) Generating inverse Gaussian random variates byNEWLINE # approximationNEWLINE # * Atkinson (1982) The simulation of generalized inverse gaussianNEWLINE # and hyperbolic random variables seems to be the canonical refNEWLINE # Y = np.dot(X, params) + np.random.wald(mu, sigma, 1000)NEWLINE # model = GLM(Y, X, family=models.family.InverseGaussian(link=\NEWLINE # models.family.links.identity()))NEWLINENEWLINE def __init__(self):NEWLINE # set up data #NEWLINE filename = os.path.join(os.path.dirname(os.path.abspath(__file__)),NEWLINE "inv_gaussian.csv")NEWLINE with open(filename, 'r') as fd:NEWLINE data = np.genfromtxt(fd, delimiter=",", dtype=float)[1:]NEWLINE self.endog = data[:5000, 0]NEWLINE self.exog = data[:5000, 1:]NEWLINE self.exog = add_constant(self.exog, prepend=False)NEWLINENEWLINE # ResultsNEWLINE # NOTE: loglikelihood difference in R vs. Stata vs. ModelsNEWLINE # is the same situation as gammaNEWLINE self.params = (0.4519770, -0.2508288, 1.0359574)NEWLINE self.bse = (0.03148291, 0.02237211, 0.03429943)NEWLINE self.null_deviance = 1520.673165475461NEWLINE self.df_null = 4999NEWLINE self.deviance = 1423.943980407997NEWLINE self.df_resid = 4997NEWLINE self.df_model = 2NEWLINE self.aic_R = 5059.41911646446NEWLINE self.aic_Stata = 1.552280060977946NEWLINE self.bic_Stata = -41136.47039418921NEWLINE self.llf = -3877.700354 # Stata is same as ours with scale set to 1NEWLINE # self.llf = -2525.70955823223 # from R, close to oursNEWLINE self.scale = 0.2867266359127567NEWLINE self.pearson_chi2 = 1432.771536NEWLINE self.resids = glm_test_resids.invgauss_residsNEWLINE self.fittedvalues = np.array([NEWLINE 1.0404339, 0.96831526, 0.81265833, 0.9958362, 1.05433442,NEWLINE 1.09866137, 0.95548191, 1.38082105, 0.98942888, 0.96521958,NEWLINE 1.02684056, 0.91412576, 0.91492102, 0.92639676, 0.96763425,NEWLINE 0.80250852, 0.85281816, 0.90962261, 0.95550299, 0.86386815,NEWLINE 0.94760134, 0.94269533, 0.98960509, 0.84787252, 0.78949111,NEWLINE 0.76873582, 0.98933453, 0.95105574, 0.8489395, 0.88962971,NEWLINE 0.84856357, 0.88567313, 0.84505405, 0.84626147, 0.77250421,NEWLINE 0.90175601, 1.15436378, 0.98375558, 0.83539542, 0.82845381,NEWLINE 0.90703971, 0.85546165, 0.96707286, 0.84127197, 0.82096543,NEWLINE 1.1311227, 0.87617029, 0.91194419, 1.05125511, 0.95330314,NEWLINE 0.75556148, 0.82573228, 0.80424982, 0.83800144, 0.8203644,NEWLINE 0.84423807, 0.98348433, 0.93165089, 0.83968706, 0.79256287,NEWLINE 1.0302839, 0.90982028, 0.99471562, 0.70931825, 0.85471721,NEWLINE 1.02668021, 1.11308301, 0.80497105, 1.02708486, 1.07671424,NEWLINE 0.821108, 0.86373486, 0.99104964, 1.06840593, 0.94947784,NEWLINE 0.80982122, 0.95778065, 1.0254212, 1.03480946, 0.83942363,NEWLINE 1.17194944, 0.91772559, 0.92368795, 1.10410916, 1.12558875,NEWLINE 1.11290791, 0.87816503, 1.04299294, 0.89631173, 1.02093004,NEWLINE 0.86331723, 1.13134858, 1.01807861, 0.98441692, 0.72567667,NEWLINE 1.42760495, 0.78987436, 0.72734482, 0.81750166, 0.86451854,NEWLINE 0.90564264, 0.81022323, 0.98720325, 0.98263709, 0.99364823,NEWLINE 0.7264445, 0.81632452, 0.7627845, 1.10726938, 0.79195664,NEWLINE 0.86836774, 1.01558149, 0.82673675, 0.99529548, 0.97155636,NEWLINE 0.980696, 0.85460503, 1.00460782, 0.77395244, 0.81229831,NEWLINE 0.94078297, 1.05910564, 0.95921954, 0.97841172, 0.93093166,NEWLINE 0.93009865, 0.89888111, 1.18714408, 0.98964763, 1.03388898,NEWLINE 1.67554215, 0.82998876, 1.34100687, 0.86766346, 0.96392316,NEWLINE 0.91371033, 0.76589296, 0.92329051, 0.82560326, 0.96758148,NEWLINE 0.8412995, 1.02550678, 0.74911108, 0.8751611, 1.01389312,NEWLINE 0.87865556, 1.24095868, 0.90678261, 0.85973204, 1.05617845,NEWLINE 0.94163038, 0.88087351, 0.95699844, 0.86083491, 0.89669384,NEWLINE 0.78646825, 1.0014202, 0.82399199, 1.05313139, 1.06458324,NEWLINE 0.88501766, 1.19043294, 0.8458026, 1.00231535, 0.72464305,NEWLINE 0.94790753, 0.7829744, 1.1953009, 0.85574035, 0.95433052,NEWLINE 0.96341484, 0.91362908, 0.94097713, 0.87273804, 0.81126399,NEWLINE 0.72715262, 0.85526116, 0.76015834, 0.8403826, 0.9831501,NEWLINE 1.17104665, 0.78862494, 1.01054909, 0.91511601, 1.0990797,NEWLINE 0.91352124, 1.13671162, 0.98793866, 1.0300545, 1.04490115,NEWLINE 0.85778231, 0.94824343, 1.14510618, 0.81305136, 0.88085051,NEWLINE 0.94743792, 0.94875465, 0.96206997, 0.94493612, 0.93547218,NEWLINE 1.09212018, 0.86934651, 0.90532353, 1.07066001, 1.26197714,NEWLINE 0.93858662, 0.9685039, 0.7946546, 1.03052031, 0.75395899,NEWLINE 0.87527062, 0.82156476, 0.949774, 1.01000235, 0.82613526,NEWLINE 1.0224591, 0.91529149, 0.91608832, 1.09418385, 0.8228272,NEWLINE 1.06337472, 1.05533176, 0.93513063, 1.00055806, 0.95474743,NEWLINE 0.91329368, 0.88711836, 0.95584926, 0.9825458, 0.74954073,NEWLINE 0.96964967, 0.88779583, 0.95321846, 0.95390055, 0.95369029,NEWLINE 0.94326714, 1.31881201, 0.71512263, 0.84526602, 0.92323824,NEWLINE 1.01993108, 0.85155992, 0.81416851, 0.98749128, 1.00034192,NEWLINE 0.98763473, 1.05974138, 1.05912658, 0.89772172, 0.97905626,NEWLINE 1.1534306, 0.92304181, 1.16450278, 0.7142307, 0.99846981,NEWLINE 0.79861247, 0.73939835, 0.93776385, 1.0072242, 0.89159707,NEWLINE 1.05514263, 1.05254569, 0.81005146, 0.95179784, 1.00278795,NEWLINE 1.04910398, 0.88427798, 0.74394266, 0.92941178, 0.83622845,NEWLINE 0.84064958, 0.93426956, 1.03619314, 1.22439347, 0.73510451,NEWLINE 0.82997071, 0.90828036, 0.80866989, 1.34078212, 0.85079169,NEWLINE 0.88346039, 0.76871666, 0.96763454, 0.66936914, 0.94175741,NEWLINE 0.97127617, 1.00844382, 0.83449557, 0.88095564, 1.17711652,NEWLINE 1.0547188, 1.04525593, 0.93817487, 0.77978294, 1.36143199,NEWLINE 1.16127997, 1.03792952, 1.03151637, 0.83837387, 0.94326066,NEWLINE 1.0054787, 0.99656841, 1.05575689, 0.97641643, 0.85108163,NEWLINE 0.82631589, 0.77407305, 0.90566132, 0.91308164, 0.95560906,NEWLINE 1.04523011, 1.03773723, 0.97378685, 0.83999133, 1.06926871,NEWLINE 1.01073982, 0.9804959, 1.06473061, 1.25315673, 0.969175,NEWLINE 0.63443508, 0.84574684, 1.06031239, 0.93834605, 1.01784925,NEWLINE 0.93488249, 0.80240225, 0.88757274, 0.9224097, 0.99158962,NEWLINE 0.87412592, 0.76418199, 0.78044069, 1.03117412, 0.82042521,NEWLINE 1.10272129, 1.09673757, 0.89626935, 1.01678612, 0.84911824,NEWLINE 0.95821431, 0.99169558, 0.86853864, 0.92172772, 0.94046199,NEWLINE 0.89750517, 1.09599258, 0.92387291, 1.07770118, 0.98831383,NEWLINE 0.86352396, 0.83079533, 0.94431185, 1.12424626, 1.02553104,NEWLINE 0.8357513, 0.97019669, 0.76816092, 1.34011343, 0.86489527,NEWLINE 0.82156358, 1.25529129, 0.86820218, 0.96970237, 0.85850546,NEWLINE 0.97429559, 0.84826078, 1.02498396, 0.72478517, 0.993497,NEWLINE 0.76918521, 0.91079198, 0.80988325, 0.75431095, 1.02918073,NEWLINE 0.88884197, 0.82625507, 0.78564563, 0.91505355, 0.88896863,NEWLINE 0.85882361, 0.81538316, 0.67656235, 0.8564822, 0.82473022,NEWLINE 0.92928331, 0.98068415, 0.82605685, 1.0150412, 1.00631678,NEWLINE 0.92405101, 0.88909552, 0.94873568, 0.87657342, 0.8280683,NEWLINE 0.77596382, 0.96598811, 0.78922426, 0.87637606, 0.98698735,NEWLINE 0.92207026, 0.71487846, 1.03845478, 0.70749745, 1.08603388,NEWLINE 0.92697779, 0.86470448, 0.70119494, 1.00596847, 0.91426549,NEWLINE 1.05318838, 0.79621712, 0.96169742, 0.88053405, 0.98963934,NEWLINE 0.94152997, 0.88413591, 0.75035344, 0.86007123, 0.83713514,NEWLINE 0.91234911, 0.79562744, 0.84099675, 1.0334279, 1.00272243,NEWLINE 0.95359383, 0.84292969, 0.94234155, 0.90190899, 0.97302022,NEWLINE 1.1009829, 1.0148975, 0.99082987, 0.75916515, 0.9204784,NEWLINE 0.94477378, 1.01108683, 1.00038149, 0.9259798, 1.19400436,NEWLINE 0.80191877, 0.79565851, 0.81865924, 0.79003506, 0.8995508,NEWLINE 0.73137983, 0.88336018, 0.7855268, 1.04478073, 0.90857981,NEWLINE 1.16076951, 0.76096486, 0.90004113, 0.83819665, 0.95295365,NEWLINE 1.09911441, 0.78498197, 0.95094991, 0.94333419, 0.95131688,NEWLINE 0.82961049, 1.08001761, 1.06426458, 0.94291798, 1.04381938,NEWLINE 0.90380364, 0.74060138, 0.98701862, 0.72250236, 0.86125293,NEWLINE 0.76488061, 0.9858051, 0.98099677, 0.96849209, 0.90053351,NEWLINE 0.88469597, 0.80688516, 1.06396217, 1.02446023, 0.911863,NEWLINE 0.98837746, 0.91102987, 0.92810392, 1.13526335, 1.00419541,NEWLINE 1.00866175, 0.74352261, 0.91051641, 0.81868428, 0.93538014,NEWLINE 0.87822651, 0.93278572, 1.0356074, 1.25158731, 0.98372647,NEWLINE 0.81335741, 1.06441863, 0.80305786, 0.95201148, 0.90283451,NEWLINE 1.17319519, 0.8984894, 0.88911288, 0.91474736, 0.94512294,NEWLINE 0.92956283, 0.86682085, 1.08937227, 0.94825713, 0.9787145,NEWLINE 1.16747163, 0.80863682, 0.98314119, 0.91052823, 0.80913225,NEWLINE 0.78503169, 0.78751737, 1.08932193, 0.86859845, 0.96847458,NEWLINE 0.93468839, 1.10769915, 1.1769249, 0.84916138, 1.00556408,NEWLINE 0.84508585, 0.92617942, 0.93985886, 1.17303268, 0.81172495,NEWLINE 0.93482682, 1.04082486, 1.03209348, 0.97220394, 0.90274672,NEWLINE 0.93686291, 0.91116431, 1.14814563, 0.83279158, 0.95853283,NEWLINE 1.0261179, 0.95779432, 0.86995883, 0.78164915, 0.89946906,NEWLINE 0.9194465, 0.97919367, 0.92719039, 0.89063569, 0.80847805,NEWLINE 0.81192101, 0.75044535, 0.86819023, 1.03420014, 0.8899434,NEWLINE 0.94899544, 0.9860773, 1.10047297, 1.00243849, 0.82153972,NEWLINE 1.14289945, 0.8604684, 0.87187524, 1.00415032, 0.78460709,NEWLINE 0.86319884, 0.92818335, 1.08892111, 1.06841003, 1.00735918,NEWLINE 1.20775251, 0.72613554, 1.25768191, 1.08573511, 0.89671127,NEWLINE 0.91259535, 1.01414208, 0.87422903, 0.82720677, 0.9568079,NEWLINE 1.00450416, 0.91043845, 0.84095709, 1.08010574, 0.69848293,NEWLINE 0.90769214, 0.94713501, 1.14808251, 1.0605676, 1.21734482,NEWLINE 0.78578521, 1.01516235, 0.94330326, 0.98363817, 0.99650084,NEWLINE 0.74280796, 0.96227123, 0.95741454, 1.00980406, 0.93468092,NEWLINE 1.10098591, 1.18175828, 0.8553791, 0.81713219, 0.82912143,NEWLINE 0.87599518, 1.15006511, 1.03151163, 0.8751847, 1.15701331,NEWLINE 0.73394166, 0.91426368, 0.96953458, 1.13901709, 0.83028721,NEWLINE 1.15742641, 0.9395442, 0.98118552, 0.89585426, 0.74147117,NEWLINE 0.8902096, 1.00212097, 0.97665858, 0.92624514, 0.98006601,NEWLINE 0.9507215, 1.00889825, 1.2406772, 0.88768719, 0.76587533,NEWLINE 1.0081044, 0.89608494, 1.00083526, 0.85594415, 0.76425576,NEWLINE 1.0286636, 1.13570272, 0.82020405, 0.81961271, 1.04586579,NEWLINE 1.26560245, 0.89721521, 1.19324037, 0.948205, 0.79414261,NEWLINE 0.85157002, 0.95155101, 0.91969239, 0.87699126, 1.03452982,NEWLINE 0.97093572, 1.14355781, 0.85088592, 0.79032079, 0.84521733,NEWLINE 0.99547581, 0.87593455, 0.8776799, 1.05531013, 0.94557017,NEWLINE 0.91538439, 0.79679863, 1.03398557, 0.88379021, 0.98850319,NEWLINE 1.05833423, 0.90055078, 0.92267584, 0.76273738, 0.98222632,NEWLINE 0.86392524, 0.78242646, 1.19417739, 0.89159895, 0.97565002,NEWLINE 0.85818308, 0.85334266, 1.85008011, 0.87199282, 0.77873231,NEWLINE 0.78036174, 0.96023918, 0.91574121, 0.89217979, 1.16421151,NEWLINE 1.29817786, 1.18683283, 0.96096225, 0.89964569, 1.00401442,NEWLINE 0.80758845, 0.89458758, 0.7994919, 0.85889356, 0.73147252,NEWLINE 0.7777221, 0.9148438, 0.72388117, 0.91134001, 1.0892724,NEWLINE 1.01736424, 0.86503014, 0.77344917, 1.04515616, 1.06677211,NEWLINE 0.93421936, 0.8821777, 0.91860774, 0.96381507, 0.70913689,NEWLINE 0.82354748, 1.12416046, 0.85989778, 0.90588737, 1.22832895,NEWLINE 0.65955579, 0.93828405, 0.88946418, 0.92152859, 0.83168025,NEWLINE 0.93346887, 0.96456078, 0.9039245, 1.03598695, 0.78405559,NEWLINE 1.21739525, 0.79019383, 0.84034646, 1.00273203, 0.96356393,NEWLINE 0.948103, 0.90279217, 1.0187839, 0.91630508, 1.15965854,NEWLINE 0.84203423, 0.98803156, 0.91604459, 0.90986512, 0.93384826,NEWLINE 0.76687038, 0.96251902, 0.80648134, 0.77336547, 0.85720164,NEWLINE 0.9351947, 0.88004728, 0.91083961, 1.06225829, 0.90230812,NEWLINE 0.72383932, 0.8343425, 0.8850996, 1.19037918, 0.93595522,NEWLINE 0.85061223, 0.84330949, 0.82397482, 0.92075047, 0.86129584,NEWLINE 0.99296756, 0.84912251, 0.8569699, 0.75252201, 0.80591772,NEWLINE 1.03902954, 1.04379139, 0.87360195, 0.97452318, 0.93240609,NEWLINE 0.85406409, 1.11717394, 0.95758536, 0.82772817, 0.67947416,NEWLINE 0.85957788, 0.93731268, 0.90349227, 0.79464185, 0.99148637,NEWLINE 0.8461071, 0.95399991, 1.04320664, 0.87290871, 0.96780849,NEWLINE 0.99467159, 0.96421545, 0.80174643, 0.86475812, 0.74421362,NEWLINE 0.85230296, 0.89891758, 0.77589592, 0.98331957, 0.87387233,NEWLINE 0.92023388, 1.03037742, 0.83796515, 1.0296667, 0.85891747,NEWLINE 1.02239978, 0.90958406, 1.09731875, 0.8032638, 0.84482057,NEWLINE 0.8233118, 0.86184709, 0.93105929, 0.99443502, 0.77442109,NEWLINE 0.98367982, 0.95786272, 0.81183444, 1.0526009, 0.86993018,NEWLINE 0.985886, 0.92016756, 1.00847155, 1.2309469, 0.97732206,NEWLINE 0.83074957, 0.87406987, 0.95268492, 0.94189139, 0.87056443,NEWLINE 1.0135018, 0.93051004, 1.5170931, 0.80948763, 0.83737473,NEWLINE 1.05461331, 0.97501633, 1.01449333, 0.79760056, 1.05756482,NEWLINE 0.97300884, 0.92674035, 0.8933763, 0.91624084, 1.13127607,NEWLINE 0.88115305, 0.9351562, 0.91430431, 1.11668229, 1.10000526,NEWLINE 0.88171963, 0.74914744, 0.94610698, 1.13841497, 0.90551414,NEWLINE 0.89773592, 1.01696097, 0.85096063, 0.80935471, 0.68458106,NEWLINE 1.2718979, 0.93550219, 0.96071403, 0.75434294, 0.95112257,NEWLINE 1.16233368, 0.73664915, 1.02195777, 1.07487625, 0.8937445,NEWLINE 0.78006023, 0.89588994, 1.16354892, 1.02629448, 0.89208642,NEWLINE 1.02088244, 0.85385355, 0.88586061, 0.94571704, 0.89710576,NEWLINE 0.95191525, 0.99819848, 0.97117841, 1.13899808, 0.88414949,NEWLINE 0.90938883, 1.02937917, 0.92936684, 0.87323594, 0.8384819,NEWLINE 0.87766945, 1.05869911, 0.91028734, 0.969953, 1.11036647,NEWLINE 0.94996802, 1.01305483, 1.03697568, 0.9750155, 1.04537837,NEWLINE 0.9314676, 0.86589798, 1.17446667, 1.02564533, 0.82088708,NEWLINE 0.96481845, 0.86148642, 0.79174298, 1.18029919, 0.82132544,NEWLINE 0.92193776, 1.03669516, 0.96637464, 0.83725933, 0.88776321,NEWLINE 1.08395861, 0.91255709, 0.96884738, 0.89840008, 0.91168146,NEWLINE 0.99652569, 0.95693101, 0.83144932, 0.99886503, 1.02819927,NEWLINE 0.95273533, 0.95959945, 1.08515986, 0.70269432, 0.79529303,NEWLINE 0.93355669, 0.92597539, 1.0745695, 0.87949758, 0.86133964,NEWLINE 0.95653873, 1.09161425, 0.91402143, 1.13895454, 0.89384443,NEWLINE 1.16281703, 0.8427015, 0.7657266, 0.92724079, 0.95383649,NEWLINE 0.86820891, 0.78942366, 1.11752711, 0.97902686, 0.87425286,NEWLINE 0.83944794, 1.12576718, 0.9196059, 0.89844835, 1.10874172,NEWLINE 1.00396783, 0.9072041, 1.63580253, 0.98327489, 0.68564426,NEWLINE 1.01007087, 0.92746473, 1.01328833, 0.99584546, 0.86381679,NEWLINE 1.0082541, 0.85414132, 0.87620981, 1.22461203, 1.03935516,NEWLINE 0.86457326, 0.95165828, 0.84762138, 0.83080254, 0.84715241,NEWLINE 0.80323344, 1.09282941, 1.00902453, 1.02834261, 1.09810743,NEWLINE 0.86560231, 1.31568763, 1.03754782, 0.81298745, 1.14500629,NEWLINE 0.87364384, 0.89928367, 0.96118471, 0.83321743, 0.90590461,NEWLINE 0.98739499, 0.79408399, 1.18513754, 1.05619307, 0.99920088,NEWLINE 1.04347259, 1.07689022, 1.24916765, 0.74246274, 0.90949597,NEWLINE 0.87077335, 0.81233276, 1.05403934, 0.98333063, 0.77689527,NEWLINE 0.93181907, 0.98853585, 0.80700332, 0.89570662, 0.97102475,NEWLINE 0.69178123, 0.72950409, 0.89661719, 0.84821737, 0.8724469,NEWLINE 0.96453177, 0.9690018, 0.87132764, 0.91711564, 1.79521288,NEWLINE 0.75894855, 0.90733112, 0.86565687, 0.90433268, 0.83412618,NEWLINE 1.26779628, 1.06999114, 0.73181364, 0.90334838, 0.86634581,NEWLINE 0.76999285, 1.55403008, 0.74712547, 0.84702579, 0.72396203,NEWLINE 0.82292773, 0.73633208, 0.90524618, 0.9954355, 0.85076517,NEWLINE 0.96097585, 1.21655611, 0.77658146, 0.81026686, 1.07540173,NEWLINE 0.94219623, 0.97472554, 0.72422803, 0.85055855, 0.85905477,NEWLINE 1.17391419, 0.87644114, 1.03573284, 1.16647944, 0.87810532,NEWLINE 0.89134419, 0.83531593, 0.93448128, 1.04967869, 1.00110843,NEWLINE 0.936784, 1.00143426, 0.79714807, 0.82656251, 0.95057309,NEWLINE 0.93821813, 0.93469098, 0.99825205, 0.95384714, 1.07063008,NEWLINE 0.97603699, 0.816668, 0.98286184, 0.86061483, 0.88166732,NEWLINE 0.93730982, 0.77633837, 0.87671549, 0.99192439, 0.86452825,NEWLINE 0.95880282, 0.7098419, 1.12717149, 1.16707939, 0.84854333,NEWLINE 0.87486963, 0.9255293, 1.06534197, 0.9888494, 1.09931069,NEWLINE 1.21859221, 0.97489537, 0.82508579, 1.14868922, 0.98076133,NEWLINE 0.85524084, 0.69042079, 0.93012936, 0.96908499, 0.94284892,NEWLINE 0.80114327, 0.919846, 0.95753354, 1.04536666, 0.77109284,NEWLINE 0.99942571, 0.79004323, 0.91820045, 0.97665489, 0.64689716,NEWLINE 0.89444405, 0.96106598, 0.74196857, 0.92905294, 0.70500318,NEWLINE 0.95074586, 0.98518665, 1.0794044, 1.00364488, 0.96710486,NEWLINE 0.92429638, 0.94383006, 1.12554253, 0.95199191, 0.87380738,NEWLINE 0.72183594, 0.94453761, 0.98663804, 0.68247366, 1.02761427,NEWLINE 0.93255355, 0.85264705, 1.00341417, 1.07765999, 0.97396039,NEWLINE 0.90770805, 0.82750901, 0.73824542, 1.24491161, 0.83152629,NEWLINE 0.78656996, 0.99062838, 0.98276905, 0.98291014, 1.12795903,NEWLINE 0.98742704, 0.9579893, 0.80451701, 0.87198344, 1.24746127,NEWLINE 0.95839155, 1.11708725, 0.97113877, 0.7721646, 0.95781621,NEWLINE 0.67069168, 1.05509376, 0.96071852, 0.99768666, 0.83008521,NEWLINE 0.9156695, 0.86314088, 1.23081412, 1.14723685, 0.8007289,NEWLINE 0.81590842, 1.31857558, 0.7753396, 1.11091566, 1.03560198,NEWLINE 1.01837739, 0.94882818, 0.82551111, 0.93188019, 0.99532255,NEWLINE 0.93848495, 0.77764975, 0.85192319, 0.79913938, 0.99495229,NEWLINE 0.96122733, 1.13845155, 0.95846389, 0.8891543, 0.97979531,NEWLINE 0.87167192, 0.88119611, 0.79655111, 0.9298217, 0.96399321,NEWLINE 1.02005428, 1.06936503, 0.86948022, 1.02560548, 0.9149464,NEWLINE 0.83797207, 0.86175383, 0.92455994, 0.89218435, 0.81546463,NEWLINE 0.98488771, 0.92784833, 0.87895608, 0.93366386, 1.17487238,NEWLINE 0.79088952, 0.9237694, 0.76389869, 0.931953, 0.76272078,NEWLINE 1.00304977, 0.86612561, 0.87870143, 0.93808276, 1.12489343,NEWLINE 1.00668791, 0.88027101, 0.88845209, 0.88574216, 0.84284514,NEWLINE 0.96594357, 0.94363002, 0.78245367, 0.92941326, 0.99622557,NEWLINE 0.83812683, 0.77901691, 0.9588432, 0.82057415, 0.95178868,NEWLINE 1.01904651, 0.97598844, 0.99369336, 1.12041918, 1.19432836,NEWLINE 0.91709572, 0.94645855, 0.93656587, 0.68754669, 0.80869784,NEWLINE 0.86704186, 0.83033797, 0.71892193, 0.97549489, 1.12150683,NEWLINE 0.76214802, 1.08564181, 0.84677802, 0.68080207, 1.03577057,NEWLINE 1.07937239, 0.6773357, 1.0279076, 0.89945816, 0.97765439,NEWLINE 0.91322633, 0.92490964, 0.92693575, 1.12297137, 0.81825246,NEWLINE 0.87598377, 1.11873032, 0.83472799, 1.21424495, 1.02318444,NEWLINE 1.01563195, 1.05663193, 0.82533918, 0.88766496, 0.95906474,NEWLINE 0.90738779, 0.93509534, 1.06658145, 1.00231797, 1.3131534,NEWLINE 0.88839464, 1.081006, 0.866936, 0.89030904, 0.91197562,NEWLINE 0.73449761, 0.95767806, 1.03407868, 0.79812826, 1.10555445,NEWLINE 0.85610722, 0.87420881, 1.04251375, 1.14286242, 1.00025972,NEWLINE 0.83742693, 1.11116502, 0.97424809, 0.92059325, 0.93958773,NEWLINE 0.80386755, 0.6881267, 0.88620708, 1.01715536, 1.12403581,NEWLINE 0.91078992, 0.81101399, 1.17271429, 1.09980447, 0.86063042,NEWLINE 0.80805811, 0.87988444, 0.97398188, 0.91808966, 0.90676805,NEWLINE 0.80042891, 0.84060789, 0.9710147, 1.00012669, 1.04805667,NEWLINE 0.66912164, 0.96111694, 0.86948596, 0.9056999, 1.01489333,NEWLINE 1.27876763, 0.873881, 0.98276702, 0.95553234, 0.82877996,NEWLINE 0.79697623, 0.77015376, 0.8234212, 1.13394959, 0.96244655,NEWLINE 1.06516156, 0.82743856, 1.02931842, 0.78093489, 1.01322256,NEWLINE 1.00348929, 0.9408142, 1.06495299, 0.8599522, 0.81640723,NEWLINE 0.81505589, 1.02506487, 0.91148383, 1.11134309, 0.83992234,NEWLINE 0.82982074, 0.9721429, 0.98897262, 1.01815004, 0.87838456,NEWLINE 0.80573592, 1.103707, 0.97326218, 1.08921236, 1.2638062,NEWLINE 0.83142563, 1.16028769, 0.86701564, 1.15610014, 0.98303722,NEWLINE 0.87138463, 0.75281511, 1.07715535, 0.91526065, 1.08769832,NEWLINE 0.83598308, 1.03580956, 0.9390066, 0.78544378, 1.03635836,NEWLINE 0.7974467, 0.99273331, 0.89639711, 0.9250066, 1.14323824,NEWLINE 0.9783478, 1.15460639, 0.94265587, 1.09317654, 0.78585439,NEWLINE 0.99523323, 0.95104776, 0.85582572, 0.96100168, 0.9131529,NEWLINE 0.86496966, 0.72414589, 1.05142704, 0.85570039, 0.98217968,NEWLINE 0.99031168, 1.01867086, 0.96781667, 0.98581487, 1.00415938,NEWLINE 1.0339337, 1.13987579, 1.14205543, 0.83393745, 0.96348647,NEWLINE 0.91895164, 0.77055293, 1.0053723, 0.93168993, 1.00332386,NEWLINE 1.04195993, 1.11933891, 0.87439883, 0.87156457, 0.96050419,NEWLINE 0.72718399, 1.13546762, 0.89614816, 0.85081037, 0.8831463,NEWLINE 0.76370482, 0.99582951, 1.01844155, 1.08611311, 1.15832217,NEWLINE 1.17551069, 0.97057262, 0.95163548, 0.98310701, 0.65874788,NEWLINE 0.9655409, 0.85675853, 1.34637286, 0.93779619, 1.0005791,NEWLINE 0.88104966, 1.14530829, 0.93687034, 1.01472112, 1.62464726,NEWLINE 0.84652357, 0.84639676, 0.87513324, 0.94837881, 0.85425129,NEWLINE 0.89820401, 0.94906277, 0.97796792, 0.98969445, 0.8036801,NEWLINE 1.03936478, 0.95898918, 0.82919938, 1.29609354, 0.97833841,NEWLINE 0.86862799, 0.88040491, 0.8741178, 0.80617278, 0.95983882,NEWLINE 0.9752235, 0.84292828, 0.9327284, 0.93297136, 1.06255543,NEWLINE 0.88756716, 1.13601403, 0.72311518, 0.95250034, 0.95369843,NEWLINE 1.02562728, 0.74354691, 0.78463923, 0.88720818, 1.07763289,NEWLINE 0.94502062, 0.81170329, 0.96516347, 0.76884811, 0.84169312,NEWLINE 0.83752837, 1.1487847, 1.04311868, 0.78128663, 0.74604211,NEWLINE 0.96488513, 1.1722513, 0.91661948, 1.06642815, 0.92185781,NEWLINE 0.93289001, 0.65208625, 0.75734648, 0.99580571, 1.21871511,NEWLINE 0.96316283, 1.06093093, 0.7914337, 0.90494572, 0.79235327,NEWLINE 0.90771769, 0.91355145, 0.98754767, 0.88938619, 0.89503537,NEWLINE 0.82764566, 0.77267065, 0.81520031, 0.90423926, 0.94289609,NEWLINE 0.88678376, 1.03209085, 0.81319963, 0.91600997, 0.81608666,NEWLINE 0.72429125, 0.95585073, 1.14039309, 1.00326452, 0.99629944,NEWLINE 0.95647901, 0.8927127, 0.96558599, 0.86305195, 1.0366906,NEWLINE 0.90494731, 0.95148458, 1.11229696, 1.17059748, 0.74867876,NEWLINE 0.99621909, 0.94246499, 0.82403515, 0.92144961, 0.93209989,NEWLINE 0.9705427, 0.97915309, 0.92431525, 0.7589944, 0.75208652,NEWLINE 0.89375154, 0.78820016, 1.24061454, 1.08031776, 0.88364539,NEWLINE 0.86909794, 0.98635253, 0.97620372, 1.24278282, 1.01146474,NEWLINE 0.93726261, 0.94411536, 1.08344492, 0.75389972, 1.09979822,NEWLINE 0.84271329, 1.16616317, 0.88177625, 0.8451345, 0.91355741,NEWLINE 0.99833789, 0.86172172, 0.87076203, 0.83743078, 0.99771528,NEWLINE 1.0469295, 0.87952668, 1.04362453, 0.96350831, 0.95744466,NEWLINE 0.84284283, 0.8773066, 0.85984544, 1.00589365, 0.88069101,NEWLINE 1.02331332, 1.06616241, 0.78475212, 1.02296979, 0.81480926,NEWLINE 1.09008244, 0.71435844, 0.79655626, 1.09824162, 0.87785428,NEWLINE 1.18020492, 0.99852432, 0.79028362, 0.80081103, 1.10940685,NEWLINE 1.08752313, 0.90673214, 0.84978348, 0.69466992, 0.77497046,NEWLINE 0.83074014, 0.87865947, 0.78890395, 0.7925195, 0.99749611,NEWLINE 0.91430636, 0.87863864, 0.95392862, 0.91430684, 0.97358575,NEWLINE 0.87999755, 0.88234274, 0.71682337, 1.09723693, 0.71907671,NEWLINE 0.97487202, 0.71792963, 0.88374828, 0.73386811, 0.9315647,NEWLINE 1.05020628, 0.99128682, 0.71831173, 1.07119604, 1.02028122,NEWLINE 1.04696848, 0.93335813, 1.04275931, 0.72181913, 0.8837163,NEWLINE 0.90283411, 0.96642474, 0.89851984, 0.8397063, 0.91185676,NEWLINE 1.00573193, 0.88430729, 0.7738957, 1.07361285, 0.92617819,NEWLINE 0.64251751, 1.05229257, 0.73378537, 1.08270418, 0.99490809,NEWLINE 1.13634433, 1.11979997, 1.03383516, 1.00661234, 1.05778729,NEWLINE 1.05977357, 1.13779694, 0.91237075, 1.04866775, 0.9163203,NEWLINE 0.93152436, 0.83607634, 1.13426049, 1.26438419, 0.93515536,NEWLINE 0.92181847, 0.86558905, 1.01985742, 1.44095931, 0.92256398,NEWLINE 0.83369288, 0.93369164, 0.8243758, 0.98278708, 0.80512458,NEWLINE 1.02092014, 0.73575074, 1.2214659, 0.85391033, 0.97617313,NEWLINE 0.82054292, 1.04792993, 0.93961791, 1.01145014, 0.89301558,NEWLINE 0.93167504, 0.88221321, 1.23543354, 0.97023998, 1.00197517,NEWLINE 0.85394662, 0.89426495, 0.81344186, 1.08242456, 0.76253284,NEWLINE 1.00642867, 0.76685541, 1.01487961, 0.84028343, 0.87979545,NEWLINE 0.92796937, 0.99796437, 1.28844084, 1.02827514, 1.03663144,NEWLINE 0.83164521, 0.95644234, 0.77797914, 0.96748275, 1.09139879,NEWLINE 0.84329253, 0.9539873, 0.80094065, 1.13771172, 0.91557533,NEWLINE 0.93370323, 0.79977904, 1.02721929, 1.16292026, 0.92976802,NEWLINE 0.85806865, 0.97824974, 1.02721582, 0.82773004, 0.9297126,NEWLINE 0.93769842, 1.14995068, 1.02895292, 0.90307101, 0.85918303,NEWLINE 1.14903979, 1.0344768, 0.7502627, 1.27452448, 1.12150928,NEWLINE 0.87274005, 1.09807041, 0.98634666, 1.03086907, 0.94743667,NEWLINE 0.91145542, 1.04395791, 0.83396016, 0.94783374, 0.96693806,NEWLINE 0.88864359, 0.93400675, 1.08563936, 0.78599906, 0.92142347,NEWLINE 1.15487344, 1.19946426, 0.92729226, 0.83333347, 0.90837637,NEWLINE 0.89191831, 1.0581614, 0.85162688, 1.10081699, 0.98295351,NEWLINE 0.86684217, 1.00867408, 0.95966205, 0.73170785, 1.3207658,NEWLINE 0.87988622, 0.82869937, 0.9620586, 0.71668579, 1.04105616,NEWLINE 0.71415591, 1.30198958, 0.81934393, 0.86731955, 0.99773712,NEWLINE 0.99943609, 0.87678188, 1.01650692, 0.73917494, 0.92077402,NEWLINE 0.98322263, 0.90623212, 0.88261034, 1.12798871, 0.84698889,NEWLINE 0.85312827, 0.91214965, 0.8778361, 0.99621569, 0.94155734,NEWLINE 0.66441342, 0.85925635, 0.98064691, 0.97107172, 0.96438785,NEWLINE 0.95670408, 0.87601389, 0.9388234, 0.91165254, 1.14769638,NEWLINE 0.99856344, 0.84391431, 0.94850194, 0.93754548, 0.86398937,NEWLINE 0.95090327, 1.07959765, 1.16684297, 0.82354834, 0.93165852,NEWLINE 0.91422292, 1.14872038, 0.87050113, 0.92322683, 1.04111597,NEWLINE 0.87780005, 0.94602618, 1.10071675, 0.88412438, 0.91286998,NEWLINE 0.9045216, 0.91750005, 0.98647095, 1.10986959, 0.98912028,NEWLINE 1.01565645, 0.93891294, 0.97696431, 0.91186476, 0.77363533,NEWLINE 1.00075969, 0.89608139, 0.99828964, 0.87239569, 0.87540604,NEWLINE 0.76152791, 0.82501538, 0.91656546, 0.74389243, 1.07923575,NEWLINE 1.00241137, 1.05628365, 1.04407879, 0.90048788, 1.1134027,NEWLINE 0.89745966, 0.96534, 0.71151925, 0.91798511, 0.7337992,NEWLINE 0.83636115, 0.75279928, 0.95570185, 0.89073922, 0.90307955,NEWLINE 0.8030445, 0.84374939, 0.89769981, 0.99002578, 1.01849373,NEWLINE 0.92436541, 0.79675699, 1.03910383, 1.07487895, 0.8906169,NEWLINE 0.97729004, 0.97284392, 0.76338988, 0.82756432, 1.12289431,NEWLINE 0.9582901, 0.97160038, 0.90141331, 0.83271234, 1.16065947,NEWLINE 0.90605662, 1.13389282, 0.8557889, 0.77149889, 0.9462268,NEWLINE 0.95908887, 1.03399986, 0.92795031, 0.73529029, 0.93630494,NEWLINE 0.96730298, 1.05490026, 0.93313995, 0.96980639, 0.9177592,NEWLINE 0.95483326, 0.85262905, 0.95170479, 0.9601628, 0.94878173,NEWLINE 0.87627934, 1.00561764, 0.83441231, 0.90890643, 0.97177858,NEWLINE 1.26394809, 0.80773622, 0.72205262, 0.87692143, 1.01842034,NEWLINE 0.98128171, 1.10776014, 0.94400422, 0.92697961, 0.79523284,NEWLINE 0.8609763, 0.96303262, 1.17190075, 1.01259271, 1.04973619,NEWLINE 0.94837034, 0.86592734, 0.85908444, 1.14914962, 0.98113587,NEWLINE 1.03070712, 0.89916573, 0.90618114, 0.93223156, 0.96031901,NEWLINE 0.94162334, 0.98908438, 0.95170104, 0.95056422, 0.81782932,NEWLINE 0.81770133, 1.32039255, 1.28822384, 0.82916292, 1.01626284,NEWLINE 0.97537737, 0.83235746, 0.78645733, 0.77916206, 0.93591612,NEWLINE 0.8469273, 0.74309279, 0.91331015, 1.11240033, 1.41018987,NEWLINE 0.95320314, 0.95807535, 0.89382722, 0.9259679, 0.92570222,NEWLINE 0.84567759, 0.82332966, 0.98371126, 1.00248628, 0.72107053,NEWLINE 1.09687436, 0.78399705, 0.85224803, 0.92151262, 0.85618586,NEWLINE 0.88485527, 0.954487, 0.86659146, 1.12800711, 0.93019359,NEWLINE 0.91388385, 0.95298992, 0.96834137, 0.90256791, 1.01222062,NEWLINE 0.84883116, 1.01234642, 0.91135106, 0.83362478, 0.94928359,NEWLINE 0.82247066, 0.7671973, 0.85663382, 0.88838144, 0.92491567,NEWLINE 0.88698604, 0.87485584, 1.08494606, 0.96431031, 1.06243095,NEWLINE 1.14062212, 1.02081623, 0.72229471, 0.82390737, 0.86599633,NEWLINE 0.95284398, 0.87238315, 1.02818071, 0.98462575, 0.81992808,NEWLINE 1.01207538, 1.0081178, 0.88458825, 1.01726135, 0.97708359,NEWLINE 0.79820777, 1.06081843, 0.97028599, 0.95203124, 1.00482088,NEWLINE 0.71764193, 0.88115767, 0.90628038, 0.97304174, 0.77015983,NEWLINE 1.06109546, 0.89575454, 0.94824633, 0.93822134, 0.98048549,NEWLINE 0.812265, 0.95744328, 0.79087999, 1.0222571, 0.89100453,NEWLINE 1.03590214, 0.92699983, 0.86840126, 0.99455198, 0.87912973,NEWLINE 0.93506231, 0.80706147, 0.89931563, 0.7861299, 0.89253527,NEWLINE 0.90052785, 0.82420191, 0.97042004, 1.03249619, 0.92354267,NEWLINE 0.80482118, 0.9007601, 0.80123508, 0.82285143, 0.88105118,NEWLINE 1.03519622, 0.8620259, 0.96447485, 0.80399664, 1.00324939,NEWLINE 0.96317193, 0.83260244, 0.98561657, 0.88445103, 0.70777743,NEWLINE 0.81608832, 0.98073402, 1.1206105, 0.69903403, 0.84353026,NEWLINE 0.9064964, 0.97055276, 0.82747966, 0.85400205, 1.01205886,NEWLINE 0.85324973, 0.90899616, 0.92797575, 0.94646632, 0.89358892,NEWLINE 0.7981183, 0.96559671, 0.88352248, 1.09804477, 0.79152196,NEWLINE 1.1054838, 0.93272283, 0.96165854, 0.8899703, 0.8792494,NEWLINE 0.74563326, 0.85371604, 0.87760912, 0.87184716, 0.92049887,NEWLINE 0.99459292, 0.93699011, 0.90492494, 1.12981885, 1.10621082,NEWLINE 0.91391466, 1.05207781, 1.13395097, 0.87022945, 0.93165871,NEWLINE 0.89083332, 0.99584874, 0.98626911, 1.13885184, 1.17350384,NEWLINE 0.93294232, 0.79602714, 0.93670114, 1.09726582, 1.05378961,NEWLINE 0.9457279, 1.03257053, 1.11349021, 0.80111296, 0.96415105,NEWLINE 0.99447221, 0.75745769, 0.77537636, 0.83860967, 0.90122484,NEWLINE 0.78850128, 1.19877642, 0.91190085, 0.80851919, 0.79484738,NEWLINE 0.93093657, 0.87619908, 1.22781715, 0.89734952, 0.8678127,NEWLINE 0.76177975, 0.82089769, 0.89288915, 1.01603179, 0.95279916,NEWLINE 0.84037366, 0.99962719, 0.84298093, 0.77234882, 0.99876963,NEWLINE 1.01856707, 1.2133211, 0.73822878, 0.83465671, 1.08879938,NEWLINE 0.8878534, 1.24133317, 0.89264527, 0.83938655, 1.03853109,NEWLINE 0.9842176, 0.94257497, 0.98282054, 0.90632313, 0.75810741,NEWLINE 1.02540204, 0.86648513, 0.98430307, 0.84561701, 1.13483974,NEWLINE 1.12446434, 1.00220923, 1.23248603, 0.98999724, 0.81980761,NEWLINE 0.91334393, 0.92831557, 1.16798373, 0.8888053, 0.9319632,NEWLINE 0.89206108, 0.86764558, 0.69337981, 0.9021983, 1.09931186,NEWLINE 1.15290804, 0.62304114, 1.1205393, 1.27030677, 1.12718725,NEWLINE 0.93002501, 0.83367301, 0.96589068, 0.86578968, 0.79204086,NEWLINE 0.85124905, 0.89121046, 0.96406141, 0.99249204, 0.93363878,NEWLINE 1.11258502, 0.92020983, 1.16020824, 0.99075915, 0.73994574,NEWLINE 0.9335638, 0.97410789, 1.00029038, 1.43611904, 0.93089581,NEWLINE 0.94758878, 0.84808364, 0.92192819, 1.0249259, 0.69529827,NEWLINE 0.94629021, 0.7330735, 1.07902207, 0.93022729, 0.77375973,NEWLINE 0.95019291, 0.92333668, 0.81483081, 0.78044978, 0.85101115,NEWLINE 0.88859716, 0.88720344, 0.89291167, 1.10372601, 0.91132273,NEWLINE 1.04156844, 0.94867703, 0.83546241, 0.84227545, 0.97043199,NEWLINE 0.73281541, 0.74512501, 0.9128489, 0.99223543, 0.7319106,NEWLINE 0.93065507, 1.07907995, 0.86895295, 0.84344015, 0.89394039,NEWLINE 0.88802964, 1.00580322, 1.04286883, 0.82233574, 1.0279258,NEWLINE 0.97550628, 1.03867605, 1.10231813, 0.9642628, 0.91684874,NEWLINE 1.11066089, 0.99439688, 0.88595489, 0.88725073, 0.78921585,NEWLINE 0.80397616, 0.71088468, 0.98316478, 0.72820659, 0.96964036,NEWLINE 1.03825415, 1.01438989, 1.02763769, 1.29949298, 1.06450406,NEWLINE 0.86198627, 0.85588074, 0.90445183, 1.01268187, 0.87927487,NEWLINE 0.9263951, 0.93582126, 0.88738294, 1.20707424, 0.92887657,NEWLINE 0.97891062, 0.92893689, 0.84846424, 0.96287008, 0.99565057,NEWLINE 0.93483385, 1.21357183, 0.82369562, 0.65144728, 1.11249654,NEWLINE 0.7785981, 0.88248898, 0.8953217, 0.95884666, 0.77538093,NEWLINE 0.82272417, 0.91073072, 1.17185169, 0.99645708, 0.88693463,NEWLINE 0.90293325, 0.93368474, 0.87575633, 1.01924242, 0.80011545,NEWLINE 0.99762674, 0.75834671, 0.91952152, 0.86754419, 0.81073894,NEWLINE 0.8880299, 0.74868718, 0.99979109, 0.90652154, 0.92463566,NEWLINE 0.93894041, 0.92370595, 0.88766357, 1.04614978, 1.77193759,NEWLINE 0.85480724, 0.85208602, 0.96154559, 0.95832935, 0.84210613,NEWLINE 0.9604567, 0.88597666, 1.0010723, 0.91890105, 1.10529207,NEWLINE 0.91123688, 0.88466788, 1.09759195, 0.8946647, 0.78066485,NEWLINE 1.04376296, 1.02951755, 0.88455241, 0.99284282, 0.82423576,NEWLINE 0.80612213, 0.80915541, 0.9482253, 0.8887192, 0.86163309,NEWLINE 0.891385, 0.84850622, 1.03353375, 1.09248204, 1.05337218,NEWLINE 0.85927317, 0.89167858, 1.04868715, 0.92933249, 1.1177299,NEWLINE 0.99846776, 0.82418972, 0.86041965, 0.88015748, 0.89785813,NEWLINE 0.85997945, 0.97102367, 0.86679181, 1.00848475, 0.9091588,NEWLINE 0.92565039, 0.84019067, 0.86978485, 1.21977681, 1.14920817,NEWLINE 1.05177219, 0.84202905, 0.85356083, 1.01379321, 0.93364219,NEWLINE 1.01999942, 0.85906744, 0.98178266, 0.87218886, 0.93983742,NEWLINE 0.79713053, 1.01123331, 0.86551625, 0.81983929, 0.86782985,NEWLINE 0.86735664, 1.43316935, 0.8490094, 0.99909103, 0.85715326,NEWLINE 0.89452366, 1.08380518, 0.74686847, 1.62233058, 0.81046611,NEWLINE 0.83563461, 0.96925792, 0.82863186, 0.87147202, 0.92609558,NEWLINE 0.8879082, 0.93933353, 0.90043906, 0.81677055, 0.78016427,NEWLINE 0.68871014, 0.83329967, 0.81570171, 0.89780443, 0.81337668,NEWLINE 1.00772749, 0.96220158, 0.90035459, 1.06031906, 0.85832752,NEWLINE 0.93636203, 0.96336629, 0.94686138, 0.98499419, 0.87223701,NEWLINE 0.96079992, 0.81302793, 0.99287479, 0.99369685, 1.21897038,NEWLINE 0.94547481, 0.80785132, 1.02033902, 0.93270741, 0.90386512,NEWLINE 1.05290969, 1.08873223, 0.81226537, 0.87185463, 0.96283379,NEWLINE 0.95065022, 1.07603824, 1.22279786, 0.83749284, 0.93504869,NEWLINE 0.93554565, 0.95255889, 0.96665227, 0.92370811, 0.76627742,NEWLINE 1.14267254, 0.98268052, 1.10017739, 0.79569048, 0.86494449,NEWLINE 1.17939799, 0.80655859, 0.76799971, 1.0018905, 0.83051793,NEWLINE 1.37419036, 1.10424623, 0.93729691, 0.99655914, 0.94900303,NEWLINE 1.157402, 0.93397459, 0.8133195, 0.8592273, 1.024661,NEWLINE 0.83708977, 1.06537435, 0.93561942, 1.00402051, 0.68981047,NEWLINE 0.92807172, 0.72192097, 1.232419, 0.97080757, 0.90350598,NEWLINE 0.95122672, 1.04663207, 0.79080723, 0.8421381, 1.01956925,NEWLINE 0.93307897, 0.88011784, 0.78674974, 0.97537097, 0.7582792,NEWLINE 0.85704507, 0.97683858, 0.7739793, 0.96245444, 0.99506991,NEWLINE 0.76853035, 0.90875698, 0.97951121, 0.93350388, 1.16380858,NEWLINE 0.8154485, 1.16902243, 0.98644779, 0.969998, 0.73120517,NEWLINE 1.19059456, 0.85953661, 0.99193867, 0.88144929, 0.99254885,NEWLINE 1.02956121, 0.90689455, 0.89494433, 0.85625065, 0.86227273,NEWLINE 0.99830845, 0.97635222, 0.83420327, 1.02359646, 0.93694813,NEWLINE 0.88462353, 0.97040788, 1.02543309, 0.91904348, 1.2527365,NEWLINE 0.82235812, 0.92026753, 0.93935859, 0.88919482, 1.00405208,NEWLINE 1.06835782, 1.34738363, 0.97831176, 0.92053317, 1.09692339,NEWLINE 0.86156677, 1.02455351, 1.25572326, 0.89721167, 0.95787106,NEWLINE 0.85059479, 0.92044416, 0.99210399, 0.94334232, 0.76604642,NEWLINE 0.8239008, 0.70790815, 1.06013034, 1.12729012, 0.88584074,NEWLINE 0.91995677, 0.82002708, 0.91612106, 0.86556894, 0.88014564,NEWLINE 0.95764757, 0.96559535, 0.97882426, 0.70725389, 0.9273384,NEWLINE 0.86511581, 0.85436928, 1.26804081, 1.02018914, 0.95359667,NEWLINE 0.89336753, 0.91851577, 0.78166458, 1.02673106, 1.01340992,NEWLINE 1.34916703, 0.77389899, 1.12009884, 0.94523179, 0.87991868,NEWLINE 0.82919239, 0.98198121, 0.83653977, 0.91748611, 1.0642761,NEWLINE 0.86964263, 0.86304793, 1.11500797, 0.7234409, 1.00464282,NEWLINE 1.01835251, 0.73389264, 0.88471293, 0.85754755, 1.05383962,NEWLINE 0.73121546, 0.85445808, 0.768308, 0.81396206, 1.01261272,NEWLINE 0.76696225, 1.01770784, 0.76742866, 0.98390583, 0.96277488,NEWLINE 0.87998292, 0.85264282, 1.12704234, 0.79612317, 0.92206712,NEWLINE 1.09846877, 0.99874997, 0.87707457, 1.03404785, 1.00726392,NEWLINE 0.91613763, 0.74242708, 0.80247702, 0.90702146, 0.81638055,NEWLINE 0.78507729, 1.00066404, 0.84687328, 0.76488847, 0.89697089,NEWLINE 0.82524207, 0.84940145, 1.022041, 0.75856559, 1.15434195,NEWLINE 1.09781849, 0.93256477, 0.96021119, 1.00796782, 0.88193493,NEWLINE 0.87902107, 0.82245196, 1.04739362, 1.133521, 0.82969043,NEWLINE 1.01007529, 1.07135903, 0.981338, 0.86178089, 0.77930618,NEWLINE 0.82512349, 1.2017057, 1.30452154, 1.12652148, 1.03670177,NEWLINE 0.90631643, 0.74222362, 0.84452965, 0.86366363, 0.79192948,NEWLINE 1.10288297, 0.9554774, 1.00912465, 0.95545229, 0.93584303,NEWLINE 0.91604017, 0.91681165, 0.76792072, 1.66615421, 0.99044246,NEWLINE 1.05068209, 0.88197497, 0.91153792, 0.82702508, 0.95182748,NEWLINE 1.05320356, 0.8466656, 1.01676717, 0.65881123, 1.02589358,NEWLINE 1.03902555, 1.00199915, 1.03022137, 0.93427176, 0.94600332,NEWLINE 0.94594696, 0.86465228, 0.91241272, 0.72232997, 0.93380167,NEWLINE 1.1960032, 0.87463367, 0.78428202, 0.88088, 0.97202961,NEWLINE 0.99425528, 0.89567214, 0.84908979, 0.81004889, 0.85484368,NEWLINE 0.68478631, 0.96563032, 0.78298607, 0.71894276, 0.88632131,NEWLINE 0.8885966, 0.99235811, 0.84002222, 0.91265424, 0.91999157,NEWLINE 0.89786651, 1.18062511, 0.92378385, 0.82501238, 1.09009807,NEWLINE 0.96787582, 1.12456979, 0.86339677, 0.8786218, 0.89865768,NEWLINE 1.02943564, 0.98886502, 0.97135566, 0.95914954, 1.05080931,NEWLINE 0.76554446, 0.80142172, 0.99661393, 1.14749469, 0.93695459,NEWLINE 0.95769957, 1.00811373, 1.00352699, 0.98747546, 0.99436785,NEWLINE 1.10256609, 0.84366101, 0.85931876, 0.90745126, 1.04928733,NEWLINE 0.84499693, 1.14018589, 1.2337188, 0.90516077, 0.84991869,NEWLINE 0.72984467, 0.9729476, 0.97483938, 0.88626286, 1.02838695,NEWLINE 0.89750089, 0.80324802, 1.40726294, 0.91149383, 0.86837826,NEWLINE 1.21798148, 0.96459285, 0.71897535, 0.76230781, 0.88042964,NEWLINE 0.8205186, 1.0517869, 0.74269565, 0.98278109, 1.1454159,NEWLINE 1.03806052, 0.75238659, 0.94224089, 0.94931526, 1.24018529,NEWLINE 0.99048689, 0.88108251, 0.81008694, 0.95443294, 0.99975781,NEWLINE 0.83336879, 0.74422074, 0.87934792, 0.81994499, 0.98684546,NEWLINE 0.82176924, 0.91652824, 0.77571479, 0.77039071, 0.9951089,NEWLINE 0.92896121, 0.96234268, 1.00295341, 1.01455466, 0.75014075,NEWLINE 0.95568202, 0.80995874, 1.24671334, 0.89480962, 0.81300194,NEWLINE 0.76967074, 0.92514927, 0.89610963, 0.97441759, 1.19354494,NEWLINE 0.87041262, 0.97344039, 0.88983828, 0.91614149, 0.85782814,NEWLINE 0.78403196, 0.96665254, 0.91000054, 0.78641804, 0.96920714,NEWLINE 0.89670528, 0.79247817, 1.04189638, 0.86777037, 1.18686087,NEWLINE 0.79506403, 0.92389297, 0.76211023, 0.93617759, 0.91879446,NEWLINE 0.8207635, 0.78984486, 0.93005953, 0.78743101, 0.9814347,NEWLINE 0.94882561, 0.9577075, 0.81121566, 1.01025446, 0.90587214,NEWLINE 0.94842798, 0.8811194, 1.01942816, 0.94698308, 0.92603676,NEWLINE 0.86119014, 0.97543551, 0.84730649, 0.77552262, 0.97536054,NEWLINE 0.96944817, 0.8736804, 0.86809673, 0.98134953, 1.16303105,NEWLINE 0.81534447, 1.35930512, 0.83221293, 0.94136243, 0.76926289,NEWLINE 1.05844282, 0.87783288, 0.78921971, 0.84360428, 0.78722128,NEWLINE 1.00022607, 0.96779519, 0.95891975, 0.91900001, 1.07307813,NEWLINE 1.03713093, 0.96257742, 0.90363152, 0.88729834, 0.91929215,NEWLINE 1.00508255, 0.80838454, 0.92165553, 0.94513005, 0.95429071,NEWLINE 0.80829571, 0.79531708, 1.01317347, 0.75337253, 0.85965134,NEWLINE 0.77014567, 0.77680991, 0.77158741, 0.88882588, 0.91466414,NEWLINE 0.82815897, 0.80251251, 1.04901425, 1.03386161, 1.3267075,NEWLINE 1.12457236, 0.8267327, 0.89313417, 0.85992512, 0.93482733,NEWLINE 0.83456348, 0.87991138, 0.8110149, 0.77913188, 0.89391799,NEWLINE 0.73646974, 0.87038816, 0.99533506, 0.90744083, 0.98175496,NEWLINE 1.17458551, 0.86718975, 0.93125366, 0.76131575, 0.90419708,NEWLINE 0.95122171, 0.97531776, 1.05955142, 0.94714906, 0.79360281,NEWLINE 1.02765349, 0.85192628, 0.84680852, 0.85470655, 0.94950982,NEWLINE 0.75868699, 0.89731933, 1.00736877, 1.05171121, 0.73336848,NEWLINE 0.97323586, 0.9848978, 1.27418684, 0.83954394, 0.73979357,NEWLINE 1.06785996, 0.97832832, 0.7903268, 0.76600605, 0.94906446,NEWLINE 0.81383465, 0.83620612, 1.00573379, 0.86359645, 0.9962139,NEWLINE 0.98779432, 1.13793814, 1.02764992, 0.9070168, 0.81340349,NEWLINE 0.94807089, 0.90499083, 0.83805736, 0.99623054, 0.91875275,NEWLINE 0.95603557, 0.93156095, 0.83858677, 1.03667466, 1.01436655,NEWLINE 0.85551979, 0.76227045, 0.84743986, 0.88487423, 0.93800365,NEWLINE 0.8984666, 0.92600404, 0.89230381, 1.34625848, 1.10026015,NEWLINE 0.9314026, 0.82450724, 1.0299575, 0.98494286, 1.07564492,NEWLINE 0.96565301, 0.89677015, 1.15236174, 0.85476951, 1.00169288,NEWLINE 0.90520725, 1.06235248, 1.04267637, 0.8311949, 0.82017897,NEWLINE 0.81635968, 0.97246582, 0.84554172, 0.85409644, 1.18006461,NEWLINE 0.96488389, 0.69228637, 0.97812108, 0.91764623, 0.86250551,NEWLINE 0.91067775, 1.04692847, 0.94594707, 1.04351374, 0.9861303,NEWLINE 0.92192581, 0.835444, 0.84362223, 1.13770705, 0.8075574,NEWLINE 1.02260109, 1.13786456, 0.80862839, 0.89291687, 0.90278047,NEWLINE 1.11613951, 1.29900454, 1.5622857, 0.70999772, 0.99692653,NEWLINE 0.89109939, 0.77506441, 0.86054356, 0.99498141, 0.84222293,NEWLINE 0.95213508, 0.91438286, 0.89305591, 0.9716793, 0.88609491,NEWLINE 1.00275797, 0.90086022, 0.75336995, 1.1572679, 0.75952094,NEWLINE 0.89203313, 0.82115965, 0.81459913, 1.02943406, 0.67063452,NEWLINE 1.08707079, 0.92139483, 0.89855103, 0.89910955, 1.07169531,NEWLINE 0.93684641, 0.84893365, 1.08659966, 1.43385982, 0.94788914,NEWLINE 0.95277539, 0.94709274, 1.08412066, 0.90274516, 0.85147284,NEWLINE 0.89327944, 0.92176174, 0.83820774, 0.90981839, 0.82303984,NEWLINE 0.95189716, 0.95154905, 0.73628819, 1.18956148, 1.20224654,NEWLINE 0.97666968, 1.08057375, 0.90369444, 0.98589538, 0.81426873,NEWLINE 0.75127684, 0.93200745, 0.833666, 0.79532088, 0.91965037,NEWLINE 0.99540522, 0.75449668, 0.85698312, 0.79328453, 0.94667443,NEWLINE 0.7637764, 0.77203985, 0.73841377, 0.98587851, 1.34642268,NEWLINE 0.78002774, 1.04356217, 1.02266882, 1.08936378, 0.9794388,NEWLINE 1.07623423, 0.78069571, 1.12194495, 0.8072132, 0.91672662,NEWLINE 1.36102062, 0.86933509, 1.15282756, 1.06219505, 0.80295502,NEWLINE 1.00999033, 0.69418333, 0.93678452, 1.13002256, 0.91465628,NEWLINE 0.73558316, 1.1302073, 0.85856238, 0.89450543, 1.11812369,NEWLINE 0.75891878, 0.66859534, 0.97445338, 0.82210227, 0.76292085,NEWLINE 0.79289499, 1.04380135, 0.95586226, 0.87480096, 0.81244036,NEWLINE 0.86097575, 0.84111811, 0.85369732, 0.99160655, 0.90911501,NEWLINE 0.81315845, 0.74037745, 1.04369233, 1.03535223, 1.18886682,NEWLINE 0.87092491, 0.93562683, 0.92555142, 0.95268616, 0.9653025,NEWLINE 0.93447525, 0.9043932, 1.25701034, 1.10354218, 0.96588129,NEWLINE 0.94717991, 0.97010307, 0.78264501, 0.80991731, 0.98540974,NEWLINE 0.83174886, 0.66966351, 1.01747376, 1.21553117, 0.80527296,NEWLINE 1.06556826, 1.00870321, 1.03316522, 0.88994006, 0.89092714,NEWLINE 0.94119254, 0.83930854, 1.01500087, 1.03581272, 0.97608081,NEWLINE 1.11919255, 1.16586474, 0.85064102, 1.06070274, 1.00679658,NEWLINE 0.75848826, 0.97969353, 0.94834777, 1.64970724, 0.82448941,NEWLINE 1.02236919, 0.95252025, 0.98638842, 0.89094895, 0.95522527,NEWLINE 0.91533774, 0.83716951, 0.92612154, 0.8662328, 0.9675949,NEWLINE 0.96758398, 0.84309291, 0.95071171, 1.0165785, 0.96628063,NEWLINE 1.00096151, 0.83175371, 0.79063043, 0.97371271, 0.76009001,NEWLINE 1.02409279, 0.97232166, 0.8480577, 0.8982739, 0.9959743,NEWLINE 0.96604729, 0.8681602, 0.99850841, 0.96162481, 1.01259965,NEWLINE 0.98580061, 0.82751273, 0.90469122, 0.98254028, 0.78012425,NEWLINE 0.87023012, 0.96830515, 0.9415831, 0.8591063, 0.82961507,NEWLINE 0.89166083, 0.88509907, 0.95987837, 1.12356244, 0.71406404,NEWLINE 0.99047619, 0.93735587, 0.80540831, 1.0024624, 0.95179491,NEWLINE 0.83602101, 0.90343297, 0.90510417, 0.96477126, 0.79995299,NEWLINE 0.93123762, 0.73763362, 1.0619498, 0.80929865, 0.86110233,NEWLINE 0.84552556, 0.9943, 0.97085623, 0.75751174, 0.9201456,NEWLINE 1.02268858, 0.9642899, 0.79078558, 1.03160502, 0.85200219,NEWLINE 1.02246639, 1.08771483, 0.81997868, 0.82499763, 0.92767703,NEWLINE 1.06700018, 0.7882174, 0.7789828, 0.89096139, 0.73155973,NEWLINE 1.01717651, 0.91889525, 0.93256065, 0.84716063, 1.00965969,NEWLINE 0.74505112, 0.80104245, 0.76003901, 0.96662605, 0.96594583,NEWLINE 1.04571121, 0.97700878, 0.85461917, 0.9150222, 0.89110471,NEWLINE 1.11183096, 0.98143747, 1.02346975, 0.9059266, 1.00771483,NEWLINE 0.96336096, 0.93783898, 0.90545613, 1.10404183, 0.75297691,NEWLINE 0.92548654, 0.79889783, 0.88177552, 0.93896814, 0.87309811,NEWLINE 0.80691061, 0.89725699, 1.16586955, 0.98948281, 0.94524894,NEWLINE 0.86085608, 0.76716851, 0.85362573, 1.09936882, 0.9328761,NEWLINE 0.74819673, 0.94331186, 0.81077304, 0.88610499, 1.01452015,NEWLINE 0.91513953, 0.92846128, 0.93539081, 0.8946682, 0.9270336,NEWLINE 0.96673629, 0.9897488, 1.11891899, 0.87551585, 0.85854576,NEWLINE 1.13458763, 1.11450768, 0.79887951, 1.091154, 1.04180374,NEWLINE 0.79252573, 0.90484245, 0.94221016, 0.95721137, 0.86776103,NEWLINE 0.97167404, 0.83404166, 0.94634038, 0.98907413, 0.92321459,NEWLINE 1.03547804, 0.79660212, 0.94870239, 0.70027204, 0.79841059,NEWLINE 0.92563393, 1.4385341, 0.8331731, 0.844816, 0.97851389,NEWLINE 1.24048695, 0.83765698, 0.83600835, 1.13901283, 1.05994936,NEWLINE 0.84292427, 0.86759056, 0.9272156, 0.77375499, 0.99972839,NEWLINE 0.95570976, 0.97879539, 0.95528351, 0.84555495, 0.95296134,NEWLINE 0.87469056, 0.78862024, 0.793795, 0.8516853, 0.92816818,NEWLINE 1.02492208, 0.8037345, 0.95481283, 0.75138828, 0.72110948,NEWLINE 1.36815666, 0.9661646, 0.81651816, 0.87764538, 0.97397297,NEWLINE 0.99845266, 0.77433798, 0.9266279, 1.92493013, 1.07588789,NEWLINE 0.90412593, 1.03165475, 1.00826548, 0.75500744, 0.87198881,NEWLINE 0.86871262, 0.97854606, 0.80954477, 0.84130266, 0.89674826,NEWLINE 1.43926644, 0.74873088, 1.01894282, 0.93606154, 1.08241489,NEWLINE 0.76626357, 0.97434747, 0.82824599, 1.00267494, 0.97168761,NEWLINE 1.06433173, 1.22741978, 1.46998419, 0.9521923, 0.98276685,NEWLINE 0.92422781, 1.14241216, 1.13339577, 1.05586816, 1.04923068,NEWLINE 0.83364505, 0.98007268, 0.94322393, 0.84310173, 1.03481955,NEWLINE 1.18281181, 0.79807678, 0.840274, 1.00344058, 1.09442855,NEWLINE 0.88033836, 0.86189964, 1.1395012, 1.18808865, 0.78667714,NEWLINE 1.09323293, 0.81511099, 0.95830848, 0.99637275, 0.9146258,NEWLINE 0.96358155, 0.79048719, 0.80395604, 1.00828722, 0.92872342,NEWLINE 0.98789363, 0.96720252, 0.80541021, 0.73697557, 0.86692999,NEWLINE 0.86795696, 1.1516694, 0.95911714, 1.13981603, 1.02002866,NEWLINE 0.90808456, 0.94208296, 0.93691739, 0.87653118, 0.72824225,NEWLINE 0.78177906, 1.2139146, 0.83405505, 0.91764545, 0.83318595,NEWLINE 0.77930256, 0.86499397, 0.95599882, 0.73850016, 0.9630604,NEWLINE 0.97913407, 1.1790714, 0.94994057, 1.04379512, 0.80815459,NEWLINE 1.16560205, 0.97486893, 1.02780804, 1.10633754, 0.78679252,NEWLINE 0.94643528, 1.19999119, 0.98621069, 0.8899674, 0.89235261,NEWLINE 0.8728921, 0.77089094, 0.8492628, 0.86905159, 0.90741875,NEWLINE 0.81065291, 0.91208596, 1.04616696, 1.24291958, 0.98628605,NEWLINE 0.99751975, 0.83249612, 0.96343385, 0.77862866, 0.72381238,NEWLINE 1.17384381, 1.06013687, 0.73460652, 1.09554763, 0.82015886,NEWLINE 0.90862905, 0.89037104, 0.7866143, 0.8570287, 0.75061334,NEWLINE 0.94950855, 0.8091383, 1.04055212, 0.96679573, 0.78338675,NEWLINE 0.75968533, 1.00495071, 0.6491633, 1.02802735, 1.00725883,NEWLINE 0.89333988, 0.87539291, 0.99374251, 1.10241119, 1.14935785,NEWLINE 0.9369769, 0.84772646, 1.05024743, 0.97411124, 0.76972352,NEWLINE 0.92161017, 0.88689841, 0.78598549, 0.93400036, 1.14699647,NEWLINE 0.98636563, 0.93051079, 1.00131515, 0.82749213, 0.96665447,NEWLINE 0.84457933, 0.95172036, 0.86372572, 0.97034285, 0.99877807,NEWLINE 0.8724721, 0.86281118, 0.96253742, 1.13485439, 1.03410559,NEWLINE 0.83113167, 1.02644607, 1.0669284, 0.947969, 1.13373538,NEWLINE 0.85495039, 1.15829218, 0.72662405, 0.81755747, 0.78381403,NEWLINE 0.84360371, 1.10945791, 0.80215303, 0.8861351, 0.97484684,NEWLINE 1.02996282, 0.86219328, 0.95675062, 1.10753315, 0.92496918,NEWLINE 0.79323289, 0.76891191, 0.93106762, 0.94523682, 0.9534338,NEWLINE 0.8954424, 0.81732651, 1.00443776, 0.96178195, 0.89727229,NEWLINE 0.88917552, 0.88660003, 0.941933, 1.03900381, 0.75262915,NEWLINE 0.94265862, 0.84472046, 1.09834757, 0.81516259, 0.90865634,NEWLINE 0.9582531, 0.99819053, 0.8815072, 0.92425525, 0.79085083,NEWLINE 0.98173446, 0.95199169, 0.71653726, 1.11863725, 0.97855807,NEWLINE 0.87873181, 1.37925403, 0.8085008, 1.40027689, 0.79367826,NEWLINE 0.82070449, 0.87039383, 0.95896081, 0.75617612, 1.3196712,NEWLINE 0.9335008, 0.9461447, 1.0838461, 0.83347962, 0.69558254,NEWLINE 0.92358528, 0.99423247, 0.94884494, 0.75094955, 0.90429063,NEWLINE 1.13740548, 0.89354463, 1.13094104, 1.7373979, 0.87808028,NEWLINE 0.72820621, 1.02995089, 0.80134468, 0.97511989, 0.93823103,NEWLINE 0.98097787, 0.73179813, 0.93764192, 1.04399599, 0.95644709,NEWLINE 0.80476939, 0.87463727, 0.83220517, 0.76978546, 0.97056432,NEWLINE 1.1693819, 1.0368387, 0.98606478, 1.03538075, 0.88253058,NEWLINE 0.91105775, 0.93745618, 0.80272442, 0.77045021, 0.8482449,NEWLINE 1.04505306, 0.90427753, 0.706451, 1.02687396, 0.82931474,NEWLINE 1.24255717, 0.91343217, 0.8692726, 0.98422894, 0.82142068,NEWLINE 0.86854354, 0.77715916, 0.94490329, 0.97686366, 1.05198512,NEWLINE 0.888989, 1.09252847, 0.8034292, 1.04727187, 0.87246831,NEWLINE 0.89474556, 1.06031526, 0.93056174, 0.7747956, 0.87772054,NEWLINE 1.1183045, 0.78938083, 0.82019511, 0.82553273, 1.04324276,NEWLINE 0.7676436, 0.68914756, 0.88400598, 0.79611901, 0.77011016,NEWLINE 0.76727015, 0.84523666, 1.09972447, 1.03942974, 1.07322466,NEWLINE 1.01079248, 1.03469338, 0.90450148, 0.87367007, 0.88432601,NEWLINE 0.85312482, 0.7328442, 1.12256832, 0.8837547, 0.81023384,NEWLINE 0.87068285, 0.94466637, 1.13236695, 0.95958423, 0.8099625,NEWLINE 1.07509372, 1.03306035, 0.99385633, 1.06433672, 1.07385915,NEWLINE 0.92709455, 1.03502217, 0.88961476, 0.8307198, 0.98819038,NEWLINE 1.09916368, 0.8919766, 0.90349117, 0.97554616, 0.98376763,NEWLINE 0.89285893, 0.99941071, 1.16078972, 0.66336693, 1.16389515,NEWLINE 1.10395069, 1.20381952, 0.98928899, 1.17155389, 0.81707565,NEWLINE 0.82903836, 0.95892646, 0.8437454, 0.79017432, 0.81562954,NEWLINE 0.65169124, 0.87950793, 0.9017879, 0.82160564, 0.87079127,NEWLINE 0.88100146, 1.00783979, 0.84102603, 1.16817499, 0.97697533,NEWLINE 0.89115235, 0.77254376, 0.7679024, 0.97093775, 1.13881665,NEWLINE 0.90348632, 1.14654277, 1.08625707, 0.98787902, 1.49057495,NEWLINE 0.99639001, 0.97623973, 0.74807856, 0.76656108, 0.79095998,NEWLINE 1.04583503, 0.95124469, 0.90228738, 1.03129265, 1.02663212,NEWLINE 0.67704952, 0.95335397, 1.01726294, 0.78765385, 0.91140255,NEWLINE 1.04097119, 0.71881619, 1.14572601, 0.79708798, 1.07104057,NEWLINE 0.95925248, 0.72556831, 0.92256392, 1.08702165, 0.95977251,NEWLINE 0.99670254, 0.95276505, 1.15268752, 0.68215678, 1.05573208,NEWLINE 0.89672437, 0.89396611, 1.01814905, 0.81969778, 0.74390457,NEWLINE 1.20909881, 0.82388701, 1.00574083, 1.01348114, 1.01492015,NEWLINE 0.94759788, 0.99758684, 1.19912008, 0.92749943, 1.16660441,NEWLINE 0.97646538, 0.8189475, 0.97464158, 1.01050799, 0.94368665,NEWLINE 0.70995047, 0.94469581, 1.02534612, 1.3513094, 0.88081968,NEWLINE 1.00576693, 0.9695495, 1.0549135, 1.29993316, 0.91050559,NEWLINE 0.95543198, 1.02161725, 0.76895773, 1.03685293, 0.88201449,NEWLINE 0.90345561, 1.02793048, 1.00267831, 0.84653161, 0.9217411,NEWLINE 0.94666576, 0.94946561, 0.77482488, 0.94358305, 0.89779666,NEWLINE 1.01462131, 1.05829923, 1.13217729, 1.12260175, 0.89810828,NEWLINE 0.96305689, 0.90466377, 0.8091617, 0.93070824, 1.03997521,NEWLINE 1.04076373, 0.95858477, 0.94382748, 0.7585222, 1.22890096,NEWLINE 0.97300529, 0.87424719, 0.90435141, 0.91894865, 0.97819677,NEWLINE 0.80300175, 1.03729016, 1.19305569, 0.81633791, 0.7930351,NEWLINE 0.8141721, 0.86764479, 0.89207142, 0.89691482, 0.86243171,NEWLINE 0.91184679, 0.94284352, 1.01357831, 1.03806277, 0.92000143,NEWLINE 0.91018767, 0.90555137, 0.89089532, 1.3530331, 0.96933587,NEWLINE 0.82350429, 0.71549154, 1.13399156, 0.87838533, 0.99177078,NEWLINE 0.93296992, 1.43078263, 0.90278792, 0.85789581, 0.93531789,NEWLINE 0.84948314, 0.95778101, 0.80962713, 0.88865859, 1.15297165,NEWLINE 0.85695093, 0.88601982, 0.96665296, 0.9320964, 1.04193558,NEWLINE 1.006005, 0.78939639, 0.79344784, 0.87012624, 0.8532022,NEWLINE 0.93351167, 0.91705323, 0.74384626, 0.84219843, 0.78265573,NEWLINE 1.07759963, 1.0236098, 1.00202257, 1.18687122, 1.00869294,NEWLINE 0.8809502, 0.76397598, 0.81845324, 0.97439912, 1.10466318,NEWLINE 1.10678275, 0.96692316, 0.84120323, 1.13151276, 0.72574077,NEWLINE 0.82457571, 0.8179266, 1.01118196, 0.84303742, 0.86255339,NEWLINE 1.03927791, 0.82302701, 1.03586066, 0.75785864, 0.9186558,NEWLINE 0.97139449, 0.92424514, 1.00415659, 1.08544681, 0.80940032,NEWLINE 0.9073428, 0.83621672, 1.04027879, 0.79447936, 0.94829305,NEWLINE 1.16176292, 1.11185195, 0.88652664, 0.98676451, 0.89310091,NEWLINE 0.72272527, 0.79963233, 0.94651986, 0.91540761, 1.0498236,NEWLINE 0.84938647, 1.15539602, 1.03118991, 0.86565049, 0.77764016,NEWLINE 0.77866522, 0.78008955, 0.89062575, 0.81285464, 0.92554114,NEWLINE 1.08747324, 0.84338687, 0.76746516, 0.99205474, 0.86649541,NEWLINE 0.97586166, 0.9721711, 1.14895298, 1.04659345, 1.0605085,NEWLINE 1.06392238, 1.08286448, 0.93612266, 0.82545354, 0.84305431,NEWLINE 0.83650404, 1.11073704, 0.91760695, 0.83281572, 0.84244131,NEWLINE 1.05843708, 0.94695861, 0.95469608, 0.96038612, 0.81373042,NEWLINE 0.94943303, 1.00824522, 0.86416102, 0.87121008, 1.04208739,NEWLINE 0.81171276, 1.12798927, 0.99122576, 0.80626996, 1.07103151,NEWLINE 0.99809277, 1.08490135, 0.9441509, 0.98766371, 1.33205139,NEWLINE 0.92145678, 0.88112784, 0.9297591, 1.17549838, 0.8481953,NEWLINE 0.96359948, 0.98478935, 0.77028684, 0.86408555, 0.92863805,NEWLINE 0.94593549, 0.78705212, 1.1923026, 0.9983487, 0.99152533,NEWLINE 0.95313678, 1.01847515, 1.05728959, 0.88009142, 1.00351951,NEWLINE 1.00549552, 0.81671365, 0.90545602, 0.77895202, 0.82217088,NEWLINE 0.94838645, 0.85928327, 0.90729044, 0.92975916, 0.91946285,NEWLINE 0.80537364, 1.11885357, 0.84691232, 0.85356231, 0.85102988,NEWLINE 1.06499659, 1.0242127, 0.91245632, 0.83131215, 0.72151085,NEWLINE 0.9295769, 0.89549018, 0.87914839, 0.93541175, 0.97319188,NEWLINE 0.791944, 1.08008186, 0.79549907, 0.90967683, 0.80506028,NEWLINE 1.1206821, 0.91258859, 1.24855319, 0.96112955, 1.14305514,NEWLINE 0.79327927, 0.84209204, 0.94494251, 0.89573237, 1.0571304,NEWLINE 0.94504292, 0.84446547, 0.92060829, 0.82347072, 0.86280426,NEWLINE 0.85516098, 0.78649432, 0.89522516, 0.94529795, 0.90322825,NEWLINE 0.9616288, 0.77439126, 1.0130917, 0.84021262, 0.97337238,NEWLINE 0.93206526, 0.93809914, 0.87626441, 0.92706652, 0.86819358,NEWLINE 0.74060652, 0.84046045, 0.94130171, 0.92537388, 0.80485074,NEWLINE 0.81633347, 0.76401825, 0.81300784, 0.8052467, 1.27234895,NEWLINE 0.92674704, 1.12106762, 0.91743016, 0.94694287, 0.87309918,NEWLINE 0.99163895, 0.83777703, 0.89713459, 0.88208343, 0.90205904,NEWLINE 0.9708827, 0.94965009, 0.81446019, 0.89512677, 0.97025135,NEWLINE 1.02314481, 0.88399736, 1.01059963, 0.86193889, 0.94621507,NEWLINE 0.97334837, 0.90122433, 0.71015398, 1.17491792, 1.13869784,NEWLINE 1.03908735, 0.85480742, 0.98971408, 1.04147459, 0.85170846,NEWLINE 0.94861439, 0.7778831, 0.73445723, 0.89587488, 0.88627975,NEWLINE 0.98253057, 0.86159356, 1.06559385, 0.90852704, 0.86562284,NEWLINE 0.92122779, 0.98233847, 0.94989946, 0.97171474, 0.92428639,NEWLINE 1.03712828, 0.88170861, 0.86802004, 0.79670394, 0.85606075,NEWLINE 1.09636421, 0.85048902, 0.99393971, 1.10510884, 0.80515088,NEWLINE 0.95559246, 0.96803475, 0.98115871, 0.94603995, 0.8654312,NEWLINE 0.90759845, 0.9010954, 0.77979965, 0.83322032, 0.8485444,NEWLINE 0.89217626, 0.78817966, 1.03815705, 0.84076982, 0.93362471,NEWLINE 1.06173045, 0.82612852, 0.8336989, 0.93943901, 0.91775212,NEWLINE 1.00501856, 1.04269442, 0.93195426, 0.78377288, 1.03372915,NEWLINE 0.8415154, 1.02888978, 0.93202174, 0.78683383, 0.85106996,NEWLINE 0.9724203, 0.93409182, 0.97876305, 1.17153649, 0.9434591,NEWLINE 0.81361398, 1.09554602, 1.48193137, 0.96349931, 0.93586569,NEWLINE 1.0210303, 0.88980694, 0.88890459, 1.05330284, 1.09511186,NEWLINE 0.91202441, 0.78753378, 0.98074421, 1.04268892, 1.14265114,NEWLINE 0.86482628, 0.87233851, 1.18915875, 0.82556032, 0.87461473,NEWLINE 1.08396187, 0.69206719, 0.88113605, 0.96951674, 0.89248729,NEWLINE 0.909926, 0.82966779, 0.8261611, 0.9551228, 0.79879533,NEWLINE 1.09416042, 1.01020839, 1.04133795, 1.09654304, 0.84060693,NEWLINE 1.02612223, 1.00177693, 0.90510435, 1.2091018, 1.03290288,NEWLINE 0.80529305, 0.74332311, 1.04728164, 1.04647891, 0.83707027,NEWLINE 0.81648396, 1.07180239, 0.7926372, 0.99855278, 1.16851397,NEWLINE 0.94566149, 0.75612408, 0.94975744, 0.92924923, 1.03215206,NEWLINE 0.82394984, 0.84142091, 0.88028348, 1.11036047, 0.82451341,NEWLINE 0.83694112, 0.84207459, 0.94095384, 1.00173733, 1.10241786,NEWLINE 0.86609134, 0.86859604, 1.1211537, 0.84188088, 0.89023025,NEWLINE 0.99062899, 0.96828743, 0.80106184, 0.86745454, 0.99013196,NEWLINE 0.91838615, 0.86400837, 0.95679525, 0.78893711, 1.03753175,NEWLINE 0.97177648, 0.88685941, 0.9441012, 0.69289996, 0.84219432,NEWLINE 1.01050959, 0.83578317, 0.79907595, 1.21281139, 0.91613925,NEWLINE 1.00202544, 0.95293036, 0.84583258, 0.84574886, 0.76470341,NEWLINE 1.23606485, 1.10063291, 0.93852084, 0.97201415, 0.68523403,NEWLINE 0.94560108, 0.81903039, 1.14332074, 0.80914367, 1.46398921,NEWLINE 0.85155227, 1.41106313, 0.85740937, 0.91107708, 0.9003576,NEWLINE 0.94132363, 0.85710825, 0.74805485, 1.2521402, 0.95307547,NEWLINE 0.94274593, 0.86732331, 0.83850172, 0.96835288, 1.09443821,NEWLINE 0.68532627, 0.84736457, 1.06989165, 0.81424504, 1.02942437,NEWLINE 0.80255995, 0.89258275, 0.93560962, 1.04192911, 1.13498644,NEWLINE 1.24409985, 0.93295415, 1.08360355, 1.16468059, 0.81482388,NEWLINE 0.92387137, 1.07508578, 0.86564567, 1.0142773, 0.86143907,NEWLINE 0.91214944, 0.9757589, 0.90588817, 0.74168224, 0.91222552,NEWLINE 0.96119617, 0.95431519, 0.78080736, 1.0327991, 1.05112022,NEWLINE 0.92761155, 1.0183631, 0.73188757, 0.85617225, 0.93341155,NEWLINE 0.95106173, 0.9481304, 0.92996766, 1.08092599, 0.96485228,NEWLINE 0.97964284, 0.94224551, 1.00654477, 1.01367565, 0.89785325,NEWLINE 0.80725703, 0.7495798, 0.78240339, 1.04479122, 0.88200252,NEWLINE 1.0664992, 1.05951775, 0.82508097, 0.81201381, 0.81860218,NEWLINE 1.07561763, 1.02830358, 0.87348993, 1.0081337, 0.87470565,NEWLINE 1.45597242, 0.77540871, 0.8036279, 0.80514427, 0.92688461,NEWLINE 0.88152328, 1.56288788, 0.87251203, 0.92808414, 1.03548911,NEWLINE 0.65226699, 0.81243827, 1.03103554, 1.11995602, 0.78956176,NEWLINE 0.96734427, 0.91600861, 0.8246106, 1.09390498, 0.98187349,NEWLINE 0.8919928, 0.98746862, 0.96298125, 0.93854424, 0.83060031,NEWLINE 0.74692856, 0.99757209, 0.78888849, 1.17517182, 1.06657933,NEWLINE 1.1244446, 0.93608433, 0.88898472, 0.96823218, 0.87496056,NEWLINE 0.81776683, 0.98863687, 0.82962648, 1.02395766, 0.99622674,NEWLINE 1.07138771, 0.86669915, 0.98172208, 0.8787271, 0.86125353,NEWLINE 0.79554881, 0.93382729, 1.00706175, 1.08386454, 0.69664542,NEWLINE 0.77316657, 0.79978147, 0.80764736, 0.9969375, 0.83554928,NEWLINE 0.91017317, 0.95323454, 1.29872357, 1.08851275, 1.01673108,NEWLINE 0.79536208, 0.84878371, 0.95165619, 0.87733936, 0.86319684,NEWLINE 0.96758495, 0.87763237, 0.95094713, 1.00143077, 1.0596993,NEWLINE 1.27278299, 0.82281481, 0.89765404, 0.94538181, 0.88161857,NEWLINE 0.77679456, 0.84274277, 0.89864342, 0.98705162, 0.95456512,NEWLINE 0.92712401, 0.77427128, 1.03292269, 0.87034158, 1.24316113,NEWLINE 0.98278702, 1.17325118, 1.18863971, 0.88678137, 0.90389731,NEWLINE 1.01740421, 0.80228624, 0.97742223, 0.82741518, 0.8359407,NEWLINE 0.7177401, 1.02297899, 0.81896048, 0.77127181, 0.83328601,NEWLINE 0.96939523, 0.94073198, 0.90356023, 1.12355064, 1.12811114,NEWLINE 0.92403138, 1.05423548, 0.70827734, 0.95891358, 0.89898027,NEWLINE 1.02318421, 0.93775375, 0.8245529, 0.80604304, 0.77555283,NEWLINE 0.92112699, 0.85662169, 0.92725859, 0.93599147, 0.78971931,NEWLINE 0.8337306, 0.93775212, 0.91025099, 0.75308822, 0.95391173,NEWLINE 0.96840576, 0.8394416, 0.89087015, 0.73703219, 0.97812386,NEWLINE 0.8787356, 0.93985266, 0.96406021, 0.88666152, 0.89242745,NEWLINE 0.97900374, 0.85697634, 0.8795755, 0.78581812, 0.87138735,NEWLINE 0.74602994, 0.96158936, 0.84529806, 0.85333232, 1.06116542,NEWLINE 1.05929382, 1.09720986, 1.28959453, 0.91541148, 0.87657407,NEWLINE 1.06514793, 0.8668096, 1.07325125, 0.85009534, 0.95542191,NEWLINE 0.86977409, 0.96249874, 0.97715908, 0.89360331, 0.98859647,NEWLINE 0.67560717, 0.90213348, 1.12051182, 0.99684949, 0.9863559,NEWLINE 1.32246221, 0.84632664, 0.89707447, 1.00486846, 0.90843649,NEWLINE 1.02399424, 0.97899017, 0.95693977, 0.8384806, 0.93927435,NEWLINE 0.79153251, 1.08694094, 1.01785553, 0.99674552, 0.898566,NEWLINE 0.94116882, 0.95224977, 0.99859129, 0.81125029, 0.85985586,NEWLINE 1.14418875, 0.96306241, 1.31398561, 0.77961419, 1.01958366,NEWLINE 0.9575668, 0.771084, 1.04473363, 1.01569517, 1.04560744,NEWLINE 0.9648178, 0.93466398, 1.09313672, 0.90349389, 1.00193114,NEWLINE 0.79991514, 0.91102351, 0.9795356, 0.89285193, 1.04898573,NEWLINE 0.93031782, 0.95087069, 1.15644699, 0.91155375, 0.93005986,NEWLINE 0.70098757, 0.82751625, 0.85462106, 1.34969332, 0.93382692,NEWLINE 1.05558387, 1.25417819, 1.0546501, 1.05217032, 0.86031346,NEWLINE 1.00864463, 0.73592482, 1.01899722, 1.00462831, 0.96882832,NEWLINE 0.81334751, 1.05102745, 0.82288113, 1.05798623, 0.77971966,NEWLINE 1.38584414, 1.0248193, 0.78951056, 0.76171823, 0.78407227,NEWLINE 1.14808104, 0.97890501, 0.99870905, 0.96006489, 0.78442704,NEWLINE 0.99315422, 0.83653213, 0.95210661, 0.97233777, 0.78140495,NEWLINE 0.95996216, 0.76318841, 0.82333311, 0.87123204, 0.79531258,NEWLINE 0.82681452, 1.00492217, 0.93549261, 1.00240153, 1.02086339,NEWLINE 1.00424549, 0.87437775, 0.84675564, 0.98014462, 0.77262117,NEWLINE 1.02620976, 0.91162462, 1.0275041, 1.1475431, 0.78167746,NEWLINE 0.86273856, 0.84499552, 0.99712362, 0.9694771, 0.94523806,NEWLINE 0.8450763, 0.93068519, 1.29362523, 1.0249628, 1.05522183,NEWLINE 1.13433408, 1.06981137, 0.85666419, 0.98203234, 0.75867592,NEWLINE 0.8844762, 0.89708521, 0.75482121, 0.80137918, 0.90412883,NEWLINE 0.88815714, 1.11497471, 0.77441965, 0.93853353, 0.8962444,NEWLINE 0.83055142, 0.99776183, 0.92581583, 0.78783745, 0.90934299,NEWLINE 0.81136457, 0.99000726, 0.9669203, 1.2890399, 1.01923088,NEWLINE 1.11076459, 1.01331706, 1.02470946, 0.92950448, 1.10298478,NEWLINE 1.03723287, 1.09129035, 0.95138186, 0.85764624, 0.86606803,NEWLINE 0.8141785, 1.0129293, 0.93267714, 0.95663734, 1.01940702,NEWLINE 0.8072268, 1.0707215, 0.90482063, 1.01546955, 0.84018308,NEWLINE 0.95938216, 0.96454054, 0.93114659, 1.09705112, 0.88720628,NEWLINE 0.81067916, 0.82667413, 0.89494027, 0.9173495, 0.73326273,NEWLINE 1.00209461, 0.9560545, 1.09126364, 0.95709908, 0.81314274,NEWLINE 0.8274943, 1.37605062, 0.99097917, 1.02221806, 0.90277482,NEWLINE 1.01611791, 0.79663017, 1.16686882, 1.19669266, 0.88366356,NEWLINE 0.77661102, 0.73467145, 1.15438391, 0.91439204, 0.78280849,NEWLINE 1.07238853, 1.03588797, 1.0438292, 0.75935005, 0.76200114,NEWLINE 0.81603429, 0.74402367, 1.1171573, 0.90227791, 0.94762351,NEWLINE 0.92462278, 0.8847803, 1.1343863, 0.8662186, 1.00410699,NEWLINE 1.05008842, 0.94783969, 0.89555844, 0.98278045, 0.80396855,NEWLINE 1.00483139, 0.82540491, 0.83284354, 0.93132265, 0.91191039,NEWLINE 0.95753995, 1.18260689, 0.84124197, 0.87429189, 0.67617592,NEWLINE 0.89495946, 0.92898357, 1.10528183, 1.06994417, 0.82259834,NEWLINE 0.74746328, 0.99070832, 1.07386274, 0.84007203, 0.89720099,NEWLINE 0.9670094, 1.02728082, 0.78001838, 0.97709347, 0.90602469,NEWLINE 1.49985196, 0.80256976, 1.05905677, 0.98298874, 0.94679703,NEWLINE 0.94305923, 0.98720786, 0.82091251, 0.91644161, 0.79576881,NEWLINE 0.98942172, 0.92974761, 0.99307545, 0.86959859, 0.88549807,NEWLINE 1.09246144, 0.87265047, 1.01449921, 0.74353851, 0.95029192,NEWLINE 0.94385304, 0.84779449, 1.00690543, 0.79727923, 0.92285822,NEWLINE 0.83164749, 1.06508941, 1.09757529, 0.9059649, 0.9146043,NEWLINE 0.74474669, 0.71306438, 0.77989422, 0.84965464, 0.9424323,NEWLINE 0.82492634, 0.85076686, 1.01110574, 1.01445751, 0.87929754,NEWLINE 0.8773275, 0.72314196, 0.92285502, 1.18173931, 0.86460799,NEWLINE 0.91795108, 1.16580482, 0.79880497, 0.72734786, 0.97579653,NEWLINE 0.76967834, 0.97543732, 1.04996964, 1.16439594, 1.08656546,NEWLINE 1.15644902, 0.98333436, 1.24374723, 0.95810117, 0.8488915,NEWLINE 1.06288523, 0.99055893, 0.75517736, 0.95856183, 0.85574796,NEWLINE 1.00426506, 1.25275675, 0.92735225, 0.83351314, 0.90216604,NEWLINE 0.87996386, 1.13312875, 1.00891523, 0.76513657, 0.85659621,NEWLINE 0.91142459, 1.05893495, 0.92253051, 0.87153684, 1.03190013,NEWLINE 0.92160845, 1.01768282, 0.80590054, 1.05172907, 0.92758177,NEWLINE 0.86902046, 0.93927127, 0.80389584, 0.96016014, 0.9720314,NEWLINE 0.93255573, 0.85792534, 0.97826842, 0.80506149, 0.97170364,NEWLINE 1.08397772, 1.01866333, 1.18898045, 1.02855427, 0.94848891,NEWLINE 0.94336541, 0.93119013, 0.92907817, 1.11806635, 0.88409637,NEWLINE 0.88809707, 1.06735612, 0.98447974, 0.88816438, 1.00099784,NEWLINE 0.92443453, 1.00325146, 0.86977836, 0.84621801, 0.92361073,NEWLINE 0.85573903, 0.77309241, 0.86717528, 1.19892035, 1.07497019,NEWLINE 1.02178857, 0.8718756, 0.90646803, 0.92912096, 1.04538692,NEWLINE 0.95245707, 0.99698525, 0.94583199, 0.92537599, 0.86720487,NEWLINE 0.89927054, 0.86111792, 0.94401208, 1.01130191, 1.03759681,NEWLINE 0.8177749, 1.07784373, 0.79823294, 1.00839713, 1.39409602,NEWLINE 0.87146241, 1.21218822, 0.84895926, 1.01742432, 0.8044077,NEWLINE 0.78632084, 1.07751744, 1.13147508, 0.90268302, 0.90024653,NEWLINE 0.92072578, 0.87763264, 1.00736787, 0.90978808, 0.90895492,NEWLINE 0.90766826, 0.98956566, 0.92075658, 0.77613105, 0.93815569,NEWLINE 0.95455546, 1.00607757, 0.82187828, 0.94197599, 0.867015,NEWLINE 0.90709762, 0.75604815, 0.91312261, 0.9286002, 0.74623204,NEWLINE 0.87368702, 0.83879278, 0.92224793, 0.81676402, 0.90355168,NEWLINE 0.92762955, 0.91784037, 0.82273304, 0.75947806, 0.92687078,NEWLINE 0.87971276, 1.15037445, 0.86707445, 0.8611453, 0.91921763,NEWLINE 1.07088129, 1.05150864, 1.02162325, 0.90305964, 0.99912687,NEWLINE 0.87693204, 0.6186911, 0.95526533, 1.15975655, 1.00061222,NEWLINE 0.74608861, 0.954568, 0.84965574, 0.79177899, 0.9741051,NEWLINE 1.0119514, 0.79147502, 0.81367071, 0.87757421, 1.01270813,NEWLINE 0.86044808, 0.9689615, 0.9577413, 0.79480242, 0.76073002,NEWLINE 0.83131288, 0.96379259, 0.84679732, 0.82508685, 0.89977283,NEWLINE 0.86766439, 1.12231836, 0.93058445, 1.04584181, 0.88838751,NEWLINE 0.96615893, 0.98731619, 1.05517799, 1.02860493, 0.98881473,NEWLINE 0.85210319, 0.91497438, 0.9275787, 0.97456134, 0.9011687,NEWLINE 0.69417417, 0.89661214, 0.79038577, 1.08118303, 1.0509366,NEWLINE 0.97813138, 0.85714945, 0.97330329, 0.83611871, 0.99772489,NEWLINE 0.83591193, 0.75592677, 0.85392601, 1.02734573, 0.72404609,NEWLINE 0.83534547, 0.91630472, 0.88463459, 1.12044562, 1.10991104,NEWLINE 0.96047701, 1.12342573, 0.72046647, 0.96852239, 0.89605698,NEWLINE 0.98310243, 0.92300659, 0.87794646, 0.83109321, 1.43297752,NEWLINE 0.80609029, 0.8692251, 0.90254649, 0.81647796, 1.07521371,NEWLINE 1.03942973, 0.96156488, 1.25225334, 1.0265727, 0.9518054,NEWLINE 0.87765718, 1.15552582, 0.79577766, 0.66849239, 0.87236017,NEWLINE 1.03437641, 0.98567811, 0.78463682, 1.09573491, 0.89858959,NEWLINE 0.94056747, 1.16075317, 1.06296054, 0.85844006, 0.95475376,NEWLINE 0.67038747, 0.7924646, 0.94009167, 0.88282093, 0.97711174,NEWLINE 0.9209607, 1.03230176, 0.99981312, 1.12345314, 1.11705968,NEWLINE 1.02453864, 0.91724212, 0.98337942, 0.89195196, 0.83800177,NEWLINE 0.95044243, 0.76543521, 0.8613025, 0.83907753, 0.69333275,NEWLINE 0.84411739, 0.68621941, 0.9847701, 1.13328481, 1.1432074,NEWLINE 0.97156328, 0.86464461, 0.74258211, 0.97319505, 1.11453917,NEWLINE 0.87344741, 0.91382664, 1.01635943, 1.38708812, 0.81377942,NEWLINE 1.3828856, 0.74476285, 0.86657537, 1.1216954, 0.91008346,NEWLINE 0.800862, 0.98356936, 0.92409916, 1.13970543, 0.97547004,NEWLINE 0.99385865, 1.16476579, 0.78678084, 1.003947, 0.81491463,NEWLINE 1.19724322, 0.9173622, 0.93274116, 0.80047839, 0.86798029,NEWLINE 0.9433708, 0.82376832, 1.01726905, 0.81914971, 0.73290844])NEWLINENEWLINENEWLINEclass Medpar1(object):NEWLINE '''NEWLINE The medpar1 data can be found here.NEWLINENEWLINE https://www.stata-press.com/data/hh2/medpar1NEWLINE '''NEWLINE def __init__(self):NEWLINE filename = os.path.join(os.path.dirname(os.path.abspath(__file__)),NEWLINE "stata_medpar1_glm.csv")NEWLINE data = pd.read_csv(filename).to_records()NEWLINE self.endog = data.losNEWLINE dummies = pd.get_dummies(data.admitype, prefix="race", drop_first=True)NEWLINE design = np.column_stack((data.codes, dummies)).astype(float)NEWLINE self.exog = add_constant(design, prepend=False)NEWLINENEWLINENEWLINEclass InvGaussLog(Medpar1):NEWLINE """NEWLINE InvGaussLog is used with TestGlmInvgaussLogNEWLINE """NEWLINE def __init__(self):NEWLINE super(InvGaussLog, self).__init__()NEWLINE filename = os.path.join(os.path.dirname(os.path.abspath(__file__)),NEWLINE "medparlogresids.csv")NEWLINE self.resids = pd.read_csv(filename, sep=',', header=None).valuesNEWLINE self.null_deviance = 335.1539777981053 # from R, Rpy bugNEWLINE self.params = np.array([0.09927544, -0.19161722, 1.05712336])NEWLINE self.bse = np.array([0.00600728, 0.02632126, 0.04915765])NEWLINE self.aic_R = 18545.836421595981NEWLINE self.aic_Stata = 6.619000588187141NEWLINE self.deviance = 304.27188306012789NEWLINE self.scale = 0.10240599519220173NEWLINE # self.llf = -9268.9182107979905 # from RNEWLINE self.llf = -12162.72308108797 # from Stata, big rounding diff with RNEWLINE self.bic_Stata = -29849.51723280784NEWLINE self.chi2 = 398.5465213008323 # from Stata not in smNEWLINE self.df_model = 2NEWLINE self.df_resid = 3673NEWLINE self.fittedvalues = np.array([NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 5.76642001,NEWLINE 7.03292237, 7.03292237, 6.36826384, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 5.76642001, 7.03292237,NEWLINE 5.22145448, 7.03292237, 5.22145448, 4.72799187, 4.72799187,NEWLINE 7.03292237, 7.03292237, 6.36826384, 7.03292237, 5.76642001,NEWLINE 7.03292237, 4.28116479, 7.03292237, 7.03292237, 7.03292237,NEWLINE 5.76642001, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 3.87656588, 7.03292237, 7.03292237, 4.28116479,NEWLINE 7.03292237, 7.03292237, 4.72799187, 7.03292237, 7.03292237,NEWLINE 7.03292237, 5.22145448, 6.36826384, 6.36826384, 4.28116479,NEWLINE 4.72799187, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 5.22145448, 7.03292237, 7.03292237, 6.36826384, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 5.76642001, 6.36826384,NEWLINE 6.36826384, 5.22145448, 7.03292237, 7.03292237, 7.03292237,NEWLINE 5.76642001, 7.03292237, 7.03292237, 3.87656588, 5.76642001,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 5.22145448, 5.22145448, 7.03292237, 6.36826384, 7.03292237,NEWLINE 7.03292237, 7.03292237, 4.72799187, 7.03292237, 6.36826384,NEWLINE 7.03292237, 6.36826384, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 5.22145448, 6.36826384, 5.22145448,NEWLINE 7.03292237, 7.03292237, 4.72799187, 5.76642001, 7.03292237,NEWLINE 4.72799187, 6.36826384, 3.87656588, 7.03292237, 7.03292237,NEWLINE 5.22145448, 5.22145448, 6.36826384, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 6.36826384, 4.28116479,NEWLINE 7.03292237, 6.36826384, 6.36826384, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 6.36826384, 7.03292237,NEWLINE 6.36826384, 7.03292237, 7.03292237, 6.36826384, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 5.76642001,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 5.76642001,NEWLINE 7.03292237, 7.03292237, 6.36826384, 3.87656588, 7.03292237,NEWLINE 7.03292237, 5.22145448, 7.03292237, 5.76642001, 4.28116479,NEWLINE 5.76642001, 6.36826384, 6.36826384, 7.03292237, 7.03292237,NEWLINE 5.76642001, 7.03292237, 7.03292237, 4.28116479, 7.03292237,NEWLINE 6.36826384, 7.03292237, 6.36826384, 7.03292237, 5.22145448,NEWLINE 7.03292237, 4.28116479, 4.72799187, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 6.36826384,NEWLINE 7.03292237, 4.28116479, 5.22145448, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 4.28116479, 7.03292237, 7.03292237,NEWLINE 7.03292237, 6.36826384, 5.76642001, 7.03292237, 7.03292237,NEWLINE 7.03292237, 4.72799187, 7.03292237, 6.36826384, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 6.36826384, 7.03292237,NEWLINE 6.36826384, 7.03292237, 6.36826384, 4.28116479, 5.76642001,NEWLINE 5.22145448, 6.36826384, 6.36826384, 7.03292237, 7.03292237,NEWLINE 7.03292237, 6.36826384, 7.03292237, 7.03292237, 6.36826384,NEWLINE 5.76642001, 7.03292237, 5.22145448, 5.76642001, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 6.36826384, 7.03292237,NEWLINE 4.28116479, 7.03292237, 5.22145448, 7.03292237, 6.36826384,NEWLINE 5.76642001, 4.28116479, 4.28116479, 7.03292237, 6.36826384,NEWLINE 7.03292237, 7.03292237, 7.03292237, 6.36826384, 4.28116479,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 5.22145448,NEWLINE 7.03292237, 7.03292237, 7.03292237, 5.22145448, 7.03292237,NEWLINE 5.76642001, 7.03292237, 4.72799187, 4.28116479, 6.36826384,NEWLINE 5.76642001, 7.03292237, 7.03292237, 7.03292237, 5.22145448,NEWLINE 7.03292237, 7.03292237, 7.03292237, 6.36826384, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 6.36826384, 7.03292237,NEWLINE 3.87656588, 4.72799187, 7.03292237, 7.03292237, 7.03292237,NEWLINE 4.72799187, 7.03292237, 7.03292237, 6.36826384, 7.03292237,NEWLINE 7.03292237, 6.36826384, 3.87656588, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 4.28116479, 7.03292237, 6.36826384,NEWLINE 7.03292237, 5.22145448, 5.22145448, 6.36826384, 7.03292237,NEWLINE 6.36826384, 6.36826384, 7.03292237, 4.28116479, 7.03292237,NEWLINE 7.03292237, 7.03292237, 5.22145448, 6.36826384, 7.03292237,NEWLINE 3.87656588, 6.36826384, 5.22145448, 5.76642001, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 4.28116479, 7.03292237,NEWLINE 5.22145448, 7.03292237, 6.36826384, 5.22145448, 4.72799187,NEWLINE 7.03292237, 7.03292237, 7.03292237, 4.72799187, 6.36826384,NEWLINE 7.03292237, 6.36826384, 5.76642001, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 5.22145448, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 3.87656588, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 4.72799187, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 6.36826384, 7.03292237, 7.03292237,NEWLINE 6.36826384, 7.03292237, 6.36826384, 7.03292237, 5.22145448,NEWLINE 6.36826384, 7.03292237, 6.36826384, 7.03292237, 6.36826384,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 3.87656588,NEWLINE 7.03292237, 7.03292237, 7.03292237, 6.36826384, 7.03292237,NEWLINE 7.03292237, 6.36826384, 7.03292237, 7.03292237, 6.36826384,NEWLINE 5.76642001, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 5.76642001, 7.03292237, 6.36826384, 7.03292237, 7.03292237,NEWLINE 7.03292237, 3.87656588, 7.03292237, 6.36826384, 6.36826384,NEWLINE 4.72799187, 5.76642001, 6.36826384, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 3.87656588, 5.22145448, 4.72799187,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 4.72799187, 6.36826384,NEWLINE 7.03292237, 7.03292237, 5.76642001, 7.03292237, 6.36826384,NEWLINE 7.03292237, 7.03292237, 7.03292237, 5.76642001, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 6.36826384,NEWLINE 7.03292237, 5.22145448, 5.76642001, 7.03292237, 5.76642001,NEWLINE 6.36826384, 5.76642001, 5.76642001, 7.03292237, 5.76642001,NEWLINE 7.03292237, 7.03292237, 7.03292237, 4.72799187, 6.36826384,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 6.36826384, 7.03292237, 6.36826384, 7.03292237, 4.72799187,NEWLINE 7.03292237, 7.03292237, 4.28116479, 6.36826384, 3.87656588,NEWLINE 7.03292237, 3.5102043, 7.03292237, 7.03292237, 5.76642001,NEWLINE 5.22145448, 7.03292237, 5.76642001, 4.28116479, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 5.76642001, 4.72799187,NEWLINE 7.03292237, 6.36826384, 7.03292237, 5.22145448, 7.03292237,NEWLINE 4.72799187, 7.03292237, 7.03292237, 7.03292237, 5.22145448,NEWLINE 5.22145448, 4.72799187, 7.03292237, 6.36826384, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 4.28116479, 7.03292237, 7.03292237, 7.03292237, 5.76642001,NEWLINE 6.36826384, 7.03292237, 7.03292237, 5.76642001, 7.03292237,NEWLINE 7.03292237, 6.36826384, 4.72799187, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 4.72799187, 5.76642001, 7.03292237, 5.76642001,NEWLINE 6.36826384, 7.03292237, 7.03292237, 7.03292237, 4.72799187,NEWLINE 7.03292237, 7.03292237, 7.03292237, 5.76642001, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 6.36826384, 7.03292237, 7.03292237, 5.76642001, 6.36826384,NEWLINE 4.72799187, 7.03292237, 7.03292237, 7.03292237, 5.76642001,NEWLINE 7.03292237, 6.36826384, 5.22145448, 5.76642001, 4.72799187,NEWLINE 7.03292237, 7.03292237, 7.03292237, 6.36826384, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 5.22145448, 7.03292237, 7.03292237,NEWLINE 6.36826384, 7.03292237, 7.03292237, 5.76642001, 7.03292237,NEWLINE 7.03292237, 7.03292237, 6.36826384, 7.03292237, 5.22145448,NEWLINE 7.03292237, 7.03292237, 7.03292237, 5.76642001, 7.03292237,NEWLINE 6.36826384, 6.36826384, 7.03292237, 5.76642001, 7.03292237,NEWLINE 6.36826384, 7.03292237, 7.03292237, 7.03292237, 4.72799187,NEWLINE 5.22145448, 7.03292237, 3.87656588, 5.76642001, 6.36826384,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 6.36826384, 7.03292237, 7.03292237,NEWLINE 4.72799187, 7.03292237, 6.36826384, 7.03292237, 4.28116479,NEWLINE 7.03292237, 7.03292237, 5.76642001, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 4.72799187, 6.36826384, 3.87656588, 7.03292237, 7.03292237,NEWLINE 6.36826384, 4.72799187, 4.28116479, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 3.87656588, 7.03292237, 7.03292237, 7.03292237,NEWLINE 3.87656588, 7.03292237, 7.03292237, 6.36826384, 7.03292237,NEWLINE 7.03292237, 6.36826384, 7.03292237, 7.03292237, 3.87656588,NEWLINE 7.03292237, 4.72799187, 5.22145448, 5.22145448, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 6.36826384, 7.03292237,NEWLINE 7.03292237, 6.36826384, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 5.22145448, 5.22145448, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 4.72799187, 6.36826384, 5.76642001,NEWLINE 5.76642001, 6.36826384, 7.03292237, 7.03292237, 7.03292237,NEWLINE 6.36826384, 7.03292237, 7.03292237, 6.36826384, 7.03292237,NEWLINE 7.03292237, 4.72799187, 7.03292237, 5.76642001, 7.03292237,NEWLINE 7.03292237, 7.03292237, 4.72799187, 4.28116479, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 5.76642001,NEWLINE 7.03292237, 5.76642001, 7.03292237, 7.03292237, 7.03292237,NEWLINE 5.22145448, 7.03292237, 7.03292237, 7.03292237, 5.22145448,NEWLINE 6.36826384, 7.03292237, 7.03292237, 6.36826384, 6.36826384,NEWLINE 7.03292237, 7.03292237, 5.76642001, 7.03292237, 5.22145448,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 4.72799187, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 4.28116479,NEWLINE 7.03292237, 6.36826384, 7.03292237, 5.76642001, 4.28116479,NEWLINE 5.76642001, 7.03292237, 3.87656588, 7.03292237, 7.03292237,NEWLINE 7.03292237, 3.5102043, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 5.76642001, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 5.76642001, 5.76642001, 5.76642001, 7.03292237,NEWLINE 7.03292237, 6.36826384, 7.03292237, 6.36826384, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 5.76642001, 7.03292237, 4.28116479, 6.36826384,NEWLINE 5.76642001, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 6.36826384, 5.22145448,NEWLINE 7.03292237, 7.03292237, 7.03292237, 5.76642001, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 6.36826384, 7.03292237,NEWLINE 7.03292237, 5.76642001, 7.03292237, 7.03292237, 7.03292237,NEWLINE 6.36826384, 6.36826384, 7.03292237, 7.03292237, 6.36826384,NEWLINE 7.03292237, 7.03292237, 7.03292237, 6.36826384, 7.03292237,NEWLINE 7.03292237, 7.03292237, 5.22145448, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 3.5102043, 7.03292237, 7.03292237,NEWLINE 7.03292237, 3.87656588, 6.36826384, 5.76642001, 7.03292237,NEWLINE 7.03292237, 6.36826384, 4.72799187, 7.03292237, 7.03292237,NEWLINE 5.76642001, 7.03292237, 3.87656588, 5.22145448, 6.36826384,NEWLINE 4.28116479, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 6.36826384,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 6.36826384,NEWLINE 7.03292237, 5.22145448, 6.36826384, 6.36826384, 7.03292237,NEWLINE 6.36826384, 7.03292237, 7.03292237, 7.03292237, 5.22145448,NEWLINE 7.03292237, 6.36826384, 7.03292237, 7.03292237, 4.72799187,NEWLINE 7.03292237, 7.03292237, 7.03292237, 6.36826384, 6.36826384,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 6.36826384, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 3.5102043, 7.03292237, 5.22145448,NEWLINE 5.22145448, 7.03292237, 6.36826384, 7.03292237, 4.72799187,NEWLINE 7.03292237, 7.03292237, 7.03292237, 4.72799187, 7.03292237,NEWLINE 5.76642001, 7.03292237, 3.87656588, 7.03292237, 5.22145448,NEWLINE 3.87656588, 4.72799187, 6.36826384, 5.76642001, 7.03292237,NEWLINE 6.36826384, 7.03292237, 4.28116479, 5.76642001, 7.03292237,NEWLINE 7.03292237, 7.03292237, 5.22145448, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 4.28116479, 6.36826384, 7.03292237, 7.03292237,NEWLINE 7.03292237, 5.76642001, 6.36826384, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 3.5102043, 4.72799187, 7.03292237, 4.28116479, 7.03292237,NEWLINE 4.72799187, 7.03292237, 5.22145448, 5.76642001, 5.76642001,NEWLINE 3.87656588, 5.76642001, 5.22145448, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 5.22145448, 6.36826384,NEWLINE 7.03292237, 7.03292237, 7.03292237, 5.22145448, 7.03292237,NEWLINE 7.03292237, 7.03292237, 5.22145448, 7.03292237, 7.03292237,NEWLINE 6.36826384, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 4.28116479,NEWLINE 4.72799187, 7.03292237, 7.03292237, 6.36826384, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 6.36826384, 7.03292237, 7.03292237, 6.36826384,NEWLINE 6.36826384, 5.76642001, 7.03292237, 5.76642001, 6.36826384,NEWLINE 7.03292237, 7.03292237, 7.03292237, 5.76642001, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 5.22145448, 7.03292237, 7.03292237, 5.76642001, 6.36826384,NEWLINE 5.76642001, 7.03292237, 7.03292237, 6.36826384, 7.03292237,NEWLINE 4.72799187, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 6.36826384, 5.76642001, 6.36826384, 4.72799187,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 4.72799187,NEWLINE 7.03292237, 6.36826384, 7.03292237, 5.22145448, 7.03292237,NEWLINE 7.03292237, 6.36826384, 7.03292237, 5.76642001, 6.36826384,NEWLINE 5.76642001, 7.03292237, 7.03292237, 7.03292237, 6.36826384,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 4.72799187, 7.03292237, 5.22145448, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 4.72799187, 6.36826384, 7.03292237,NEWLINE 7.03292237, 6.36826384, 7.03292237, 5.76642001, 5.22145448,NEWLINE 7.03292237, 7.03292237, 7.03292237, 5.22145448, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 4.28116479,NEWLINE 5.76642001, 7.03292237, 4.28116479, 7.03292237, 6.36826384,NEWLINE 7.03292237, 7.03292237, 4.28116479, 7.03292237, 7.03292237,NEWLINE 6.36826384, 3.87656588, 3.5102043, 6.36826384, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 5.76642001,NEWLINE 7.03292237, 4.72799187, 5.76642001, 7.03292237, 7.03292237,NEWLINE 3.87656588, 7.03292237, 7.03292237, 7.03292237, 4.28116479,NEWLINE 7.03292237, 7.03292237, 7.03292237, 5.76642001, 5.76642001,NEWLINE 7.03292237, 6.36826384, 5.76642001, 7.03292237, 6.36826384,NEWLINE 5.76642001, 7.03292237, 5.76642001, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 4.28116479, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 4.72799187, 5.76642001, 6.36826384, 6.36826384,NEWLINE 7.03292237, 7.03292237, 7.03292237, 5.76642001, 4.28116479,NEWLINE 7.03292237, 5.76642001, 4.72799187, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 5.76642001,NEWLINE 6.36826384, 6.36826384, 7.03292237, 7.03292237, 6.36826384,NEWLINE 3.87656588, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 3.5102043, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 6.36826384, 7.03292237, 7.03292237,NEWLINE 7.03292237, 4.72799187, 7.03292237, 6.36826384, 4.72799187,NEWLINE 4.72799187, 7.03292237, 5.76642001, 7.03292237, 7.03292237,NEWLINE 7.03292237, 6.36826384, 4.28116479, 7.03292237, 7.03292237,NEWLINE 7.03292237, 5.76642001, 7.03292237, 7.03292237, 7.03292237,NEWLINE 4.72799187, 7.03292237, 7.03292237, 6.36826384, 5.22145448,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 5.22145448, 7.03292237, 7.03292237, 6.36826384,NEWLINE 7.03292237, 7.03292237, 5.22145448, 7.03292237, 6.36826384,NEWLINE 6.36826384, 7.03292237, 6.36826384, 7.03292237, 7.03292237,NEWLINE 7.03292237, 6.36826384, 6.36826384, 7.03292237, 4.72799187,NEWLINE 4.28116479, 4.72799187, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 4.28116479,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 6.36826384, 4.28116479, 4.28116479, 7.03292237, 5.22145448,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 6.36826384, 7.03292237, 7.03292237, 7.03292237,NEWLINE 5.76642001, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 4.72799187, 7.03292237,NEWLINE 3.87656588, 7.03292237, 4.72799187, 7.03292237, 7.03292237,NEWLINE 7.03292237, 5.22145448, 7.03292237, 4.28116479, 7.03292237,NEWLINE 7.03292237, 4.72799187, 5.22145448, 7.03292237, 7.03292237,NEWLINE 7.03292237, 6.36826384, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 6.36826384, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 5.76642001, 5.22145448,NEWLINE 7.03292237, 7.03292237, 3.87656588, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 4.72799187, 6.36826384,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 4.28116479, 7.03292237, 7.03292237, 7.03292237, 5.76642001,NEWLINE 7.03292237, 5.22145448, 4.72799187, 7.03292237, 7.03292237,NEWLINE 7.03292237, 6.36826384, 5.76642001, 7.03292237, 5.76642001,NEWLINE 7.03292237, 4.28116479, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 5.76642001, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 5.76642001,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 5.76642001, 7.03292237, 3.87656588,NEWLINE 6.36826384, 5.76642001, 7.03292237, 4.28116479, 7.03292237,NEWLINE 5.76642001, 5.22145448, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 6.36826384, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 5.76642001, 7.03292237, 7.03292237, 7.03292237, 3.5102043,NEWLINE 7.03292237, 7.03292237, 7.03292237, 6.36826384, 7.03292237,NEWLINE 7.03292237, 4.28116479, 4.72799187, 6.36826384, 7.03292237,NEWLINE 7.03292237, 4.28116479, 5.76642001, 7.03292237, 7.03292237,NEWLINE 7.03292237, 4.28116479, 7.03292237, 7.03292237, 5.22145448,NEWLINE 6.36826384, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 4.72799187,NEWLINE 7.03292237, 5.22145448, 6.36826384, 7.03292237, 6.36826384,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 5.22145448,NEWLINE 7.03292237, 7.03292237, 5.22145448, 7.03292237, 6.36826384,NEWLINE 7.03292237, 7.03292237, 5.76642001, 7.03292237, 7.03292237,NEWLINE 3.5102043, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 6.36826384, 7.03292237,NEWLINE 7.03292237, 5.76642001, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 6.36826384,NEWLINE 4.72799187, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 6.36826384, 7.03292237, 6.36826384, 4.72799187, 5.22145448,NEWLINE 5.76642001, 7.03292237, 6.36826384, 6.36826384, 7.03292237,NEWLINE 6.36826384, 7.03292237, 5.22145448, 4.72799187, 5.76642001,NEWLINE 6.36826384, 7.03292237, 7.03292237, 5.76642001, 5.22145448,NEWLINE 7.03292237, 6.36826384, 3.87656588, 6.36826384, 7.03292237,NEWLINE 5.76642001, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 3.5102043, 7.03292237, 7.03292237, 7.03292237,NEWLINE 5.22145448, 7.03292237, 6.36826384, 7.03292237, 6.36826384,NEWLINE 7.03292237, 6.36826384, 5.22145448, 7.03292237, 7.03292237,NEWLINE 7.03292237, 6.36826384, 6.36826384, 7.03292237, 7.03292237,NEWLINE 6.36826384, 4.72799187, 7.03292237, 5.22145448, 7.03292237,NEWLINE 4.72799187, 7.03292237, 4.28116479, 7.03292237, 7.03292237,NEWLINE 6.36826384, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 4.28116479, 6.36826384, 7.03292237, 3.87656588, 7.03292237,NEWLINE 7.03292237, 7.03292237, 6.36826384, 7.03292237, 7.03292237,NEWLINE 7.03292237, 6.36826384, 7.03292237, 5.22145448, 7.03292237,NEWLINE 7.03292237, 5.76642001, 6.36826384, 7.03292237, 4.72799187,NEWLINE 7.03292237, 7.03292237, 5.22145448, 7.03292237, 3.5102043,NEWLINE 6.36826384, 6.36826384, 7.03292237, 6.36826384, 7.03292237,NEWLINE 5.22145448, 6.36826384, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 5.76642001, 4.28116479, 7.03292237, 7.03292237,NEWLINE 4.72799187, 4.72799187, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 5.76642001, 7.03292237, 5.76642001,NEWLINE 4.28116479, 7.03292237, 4.28116479, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 3.5102043, 7.03292237, 5.22145448,NEWLINE 7.03292237, 6.36826384, 7.03292237, 6.36826384, 7.03292237,NEWLINE 4.72799187, 7.03292237, 7.03292237, 4.72799187, 3.5102043,NEWLINE 3.17846635, 3.87656588, 5.22145448, 6.36826384, 7.03292237,NEWLINE 4.28116479, 7.03292237, 7.03292237, 6.36826384, 7.03292237,NEWLINE 6.36826384, 7.03292237, 7.03292237, 5.76642001, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 4.72799187, 7.03292237,NEWLINE 7.03292237, 7.03292237, 5.76642001, 7.03292237, 3.5102043,NEWLINE 7.03292237, 7.03292237, 5.22145448, 6.36826384, 3.87656588,NEWLINE 4.72799187, 7.03292237, 7.03292237, 3.87656588, 7.03292237,NEWLINE 6.36826384, 7.03292237, 6.36826384, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 4.72799187, 7.03292237,NEWLINE 7.03292237, 6.36826384, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 5.76642001, 7.03292237, 4.28116479, 7.03292237,NEWLINE 7.03292237, 7.03292237, 4.72799187, 6.36826384, 6.36826384,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 6.36826384, 4.72799187, 6.36826384, 7.03292237, 7.03292237,NEWLINE 5.22145448, 7.03292237, 5.76642001, 7.03292237, 7.03292237,NEWLINE 7.03292237, 5.76642001, 7.03292237, 6.36826384, 6.36826384,NEWLINE 7.03292237, 7.03292237, 6.36826384, 7.03292237, 5.22145448,NEWLINE 7.03292237, 5.22145448, 5.22145448, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 4.72799187, 4.28116479, 7.03292237, 6.36826384, 7.03292237,NEWLINE 5.76642001, 7.03292237, 7.03292237, 7.03292237, 4.72799187,NEWLINE 7.03292237, 5.76642001, 7.03292237, 4.72799187, 7.03292237,NEWLINE 7.03292237, 4.72799187, 5.76642001, 6.36826384, 7.03292237,NEWLINE 4.28116479, 6.36826384, 7.03292237, 6.36826384, 5.76642001,NEWLINE 7.03292237, 4.28116479, 5.22145448, 4.72799187, 7.03292237,NEWLINE 7.03292237, 6.36826384, 5.22145448, 7.03292237, 5.76642001,NEWLINE 7.03292237, 7.03292237, 7.03292237, 6.36826384, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 4.28116479, 7.03292237,NEWLINE 6.36826384, 5.22145448, 5.76642001, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 6.36826384, 7.03292237, 7.03292237,NEWLINE 5.22145448, 7.03292237, 7.03292237, 6.36826384, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 4.28116479,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 6.36826384, 7.03292237, 7.03292237, 7.03292237,NEWLINE 6.36826384, 7.03292237, 4.72799187, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 5.22145448, 6.36826384, 7.03292237,NEWLINE 5.76642001, 5.76642001, 7.03292237, 7.03292237, 7.03292237,NEWLINE 4.28116479, 7.03292237, 5.76642001, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 6.36826384, 7.03292237,NEWLINE 7.03292237, 7.03292237, 3.87656588, 6.36826384, 6.36826384,NEWLINE 5.22145448, 7.03292237, 5.22145448, 7.03292237, 7.03292237,NEWLINE 7.03292237, 4.28116479, 7.03292237, 3.87656588, 7.03292237,NEWLINE 7.03292237, 5.22145448, 6.36826384, 4.72799187, 7.03292237,NEWLINE 7.03292237, 7.03292237, 6.36826384, 7.03292237, 5.76642001,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 5.22145448,NEWLINE 4.28116479, 7.03292237, 6.36826384, 7.03292237, 7.03292237,NEWLINE 5.76642001, 5.22145448, 5.76642001, 7.03292237, 4.28116479,NEWLINE 7.03292237, 7.03292237, 4.72799187, 6.36826384, 7.03292237,NEWLINE 4.72799187, 5.76642001, 7.03292237, 7.03292237, 6.36826384,NEWLINE 6.36826384, 5.76642001, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 4.72799187, 7.03292237, 6.36826384,NEWLINE 7.03292237, 4.72799187, 4.72799187, 5.76642001, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 4.72799187,NEWLINE 7.03292237, 7.03292237, 7.03292237, 6.36826384, 7.03292237,NEWLINE 5.76642001, 7.03292237, 4.72799187, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 6.36826384, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 6.36826384, 7.03292237,NEWLINE 3.5102043, 6.36826384, 5.22145448, 7.03292237, 5.22145448,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 4.72799187, 7.03292237, 6.36826384, 7.03292237, 7.03292237,NEWLINE 7.03292237, 6.36826384, 7.03292237, 7.03292237, 7.03292237,NEWLINE 6.36826384, 4.72799187, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 6.36826384, 7.03292237, 5.76642001, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 5.22145448, 4.72799187,NEWLINE 7.03292237, 7.03292237, 7.03292237, 4.28116479, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 3.87656588, 7.03292237,NEWLINE 5.22145448, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 3.5102043, 7.03292237, 6.36826384, 7.03292237, 7.03292237,NEWLINE 7.03292237, 4.72799187, 7.03292237, 7.03292237, 4.28116479,NEWLINE 6.36826384, 7.03292237, 5.22145448, 7.03292237, 7.03292237,NEWLINE 5.76642001, 7.03292237, 7.03292237, 7.03292237, 5.76642001,NEWLINE 4.72799187, 7.03292237, 4.72799187, 6.36826384, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 6.36826384, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 3.87656588, 5.22145448, 7.03292237, 7.03292237,NEWLINE 6.36826384, 4.28116479, 7.03292237, 5.76642001, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 3.87656588, 6.36826384, 7.03292237,NEWLINE 7.03292237, 5.76642001, 7.03292237, 5.22145448, 7.03292237,NEWLINE 5.76642001, 4.72799187, 7.03292237, 7.03292237, 6.36826384,NEWLINE 7.03292237, 7.03292237, 7.03292237, 6.36826384, 5.76642001,NEWLINE 5.22145448, 7.03292237, 5.76642001, 6.36826384, 4.28116479,NEWLINE 7.03292237, 4.72799187, 3.87656588, 5.22145448, 7.03292237,NEWLINE 6.36826384, 5.76642001, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 6.36826384, 5.76642001, 6.36826384, 7.03292237,NEWLINE 5.76642001, 7.03292237, 5.76642001, 5.22145448, 3.87656588,NEWLINE 5.76642001, 6.36826384, 7.03292237, 5.22145448, 6.36826384,NEWLINE 5.22145448, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 6.36826384, 7.03292237, 5.76642001, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 4.72799187, 5.76642001, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 4.72799187,NEWLINE 7.03292237, 7.03292237, 7.03292237, 6.36826384, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 5.22145448, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 3.5102043,NEWLINE 3.87656588, 7.03292237, 4.72799187, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 3.87656588,NEWLINE 5.22145448, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 5.76642001, 7.03292237, 7.03292237, 7.03292237,NEWLINE 4.28116479, 7.03292237, 4.72799187, 4.72799187, 7.03292237,NEWLINE 6.36826384, 5.76642001, 7.03292237, 4.28116479, 7.03292237,NEWLINE 7.03292237, 7.03292237, 5.76642001, 7.03292237, 7.03292237,NEWLINE 5.76642001, 5.22145448, 7.03292237, 4.72799187, 7.03292237,NEWLINE 4.28116479, 5.76642001, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 4.28116479, 7.03292237,NEWLINE 7.03292237, 7.03292237, 5.22145448, 5.22145448, 7.03292237,NEWLINE 7.03292237, 7.03292237, 5.76642001, 6.36826384, 7.03292237,NEWLINE 7.03292237, 5.22145448, 7.03292237, 7.03292237, 5.76642001,NEWLINE 5.22145448, 7.03292237, 7.03292237, 7.03292237, 3.87656588,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 5.76642001, 7.03292237, 6.36826384,NEWLINE 7.03292237, 7.03292237, 7.03292237, 6.36826384, 6.36826384,NEWLINE 7.03292237, 7.03292237, 7.03292237, 4.28116479, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 3.5102043,NEWLINE 7.03292237, 7.03292237, 7.03292237, 5.76642001, 4.28116479,NEWLINE 5.22145448, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 6.36826384, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 5.76642001, 6.36826384, 7.03292237,NEWLINE 5.22145448, 5.76642001, 5.76642001, 7.03292237, 7.03292237,NEWLINE 5.22145448, 7.03292237, 7.03292237, 5.22145448, 6.36826384,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 5.22145448,NEWLINE 6.36826384, 5.22145448, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 5.22145448, 7.03292237, 5.76642001, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 4.72799187, 7.03292237,NEWLINE 7.03292237, 7.03292237, 6.36826384, 4.72799187, 5.22145448,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 6.36826384, 7.03292237, 7.03292237, 5.76642001, 6.36826384,NEWLINE 7.03292237, 7.03292237, 7.03292237, 6.36826384, 7.03292237,NEWLINE 4.72799187, 3.87656588, 7.03292237, 7.03292237, 4.72799187,NEWLINE 7.03292237, 7.03292237, 6.36826384, 7.03292237, 5.22145448,NEWLINE 7.03292237, 7.03292237, 7.03292237, 3.87656588, 5.76642001,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 5.76642001,NEWLINE 5.22145448, 7.03292237, 6.36826384, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 5.76642001,NEWLINE 5.76642001, 7.03292237, 5.76642001, 3.87656588, 6.36826384,NEWLINE 7.03292237, 7.03292237, 7.03292237, 6.36826384, 5.76642001,NEWLINE 5.22145448, 7.03292237, 5.22145448, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 5.22145448, 4.72799187,NEWLINE 7.03292237, 6.36826384, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 7.03292237, 7.03292237, 5.22145448, 6.36826384,NEWLINE 7.03292237, 7.03292237, 3.17846635, 5.76642001, 7.03292237,NEWLINE 3.5102043, 7.03292237, 7.03292237, 7.03292237, 3.87656588,NEWLINE 7.03292237, 6.36826384, 6.36826384, 7.03292237, 5.22145448,NEWLINE 7.03292237, 7.03292237, 7.03292237, 7.03292237, 7.03292237,NEWLINE 7.03292237, 4.28116479, 6.36826384, 7.03292237, 6.36826384,NEWLINE 4.72799187, 7.03292237, 7.03292237, 5.22145448, 4.28116479,NEWLINE 7.03292237, 6.36826384, 7.03292237, 4.72799187, 5.76642001,NEWLINE 6.36826384, 5.22145448, 7.03292237, 7.03292237, 7.03292237,NEWLINE 6.36826384, 7.03292237, 7.03292237, 3.87656588, 7.03292237,NEWLINE 4.72799187, 7.03292237, 3.53462742, 4.76088805, 5.25778406,NEWLINE 4.31095206, 5.80654132, 5.80654132, 5.80654132, 5.80654132,NEWLINE 5.80654132, 5.25778406, 5.25778406, 5.80654132, 5.80654132,NEWLINE 3.90353806, 5.25778406, 4.31095206, 5.80654132, 5.25778406,NEWLINE 3.53462742, 2.89810483, 5.80654132, 5.25778406, 5.80654132,NEWLINE 2.89810483, 5.80654132, 5.25778406, 3.53462742, 4.76088805,NEWLINE 5.80654132, 3.20058132, 5.80654132, 5.80654132, 4.76088805,NEWLINE 5.80654132, 3.53462742, 3.53462742, 5.80654132, 5.80654132,NEWLINE 5.80654132, 4.76088805, 5.80654132, 4.76088805, 3.90353806,NEWLINE 5.80654132, 3.53462742, 5.80654132, 2.6242144, 3.20058132,NEWLINE 5.80654132, 5.80654132, 3.90353806, 3.20058132, 5.80654132,NEWLINE 5.80654132, 5.80654132, 5.80654132, 5.80654132, 5.80654132,NEWLINE 2.89810483, 5.80654132, 5.80654132, 3.90353806, 3.53462742,NEWLINE 4.31095206, 5.80654132, 5.80654132, 4.76088805, 5.80654132,NEWLINE 3.53462742, 5.80654132, 4.76088805, 2.89810483, 5.25778406,NEWLINE 4.31095206, 5.80654132, 4.31095206, 5.80654132, 5.80654132,NEWLINE 4.76088805, 4.31095206, 5.80654132, 5.80654132, 5.80654132,NEWLINE 5.80654132, 5.80654132, 4.76088805, 5.80654132, 5.25778406,NEWLINE 5.25778406, 5.80654132, 5.80654132, 3.53462742, 5.80654132,NEWLINE 3.53462742, 5.80654132, 4.31095206, 5.80654132, 5.80654132,NEWLINE 5.25778406, 5.80654132, 3.20058132, 5.80654132, 5.80654132,NEWLINE 3.20058132, 3.90353806, 5.80654132, 5.80654132, 5.25778406,NEWLINE 3.53462742, 3.20058132, 5.80654132, 4.31095206, 5.80654132,NEWLINE 5.80654132, 5.80654132, 3.20058132, 5.80654132, 5.80654132,NEWLINE 5.80654132, 5.80654132, 4.31095206, 5.80654132, 3.90353806,NEWLINE 5.80654132, 4.31095206, 4.31095206, 5.80654132, 4.76088805,NEWLINE 3.90353806, 3.90353806, 4.76088805, 3.90353806, 5.80654132,NEWLINE 5.80654132, 5.80654132, 5.80654132, 5.80654132, 5.80654132,NEWLINE 5.80654132, 5.25778406, 3.53462742, 5.80654132, 3.53462742,NEWLINE 5.80654132, 5.80654132, 5.80654132, 2.89810483, 5.80654132,NEWLINE 5.80654132, 5.80654132, 5.80654132, 4.76088805, 4.76088805,NEWLINE 5.80654132, 2.89810483, 5.80654132, 4.76088805, 5.80654132,NEWLINE 5.80654132, 4.31095206, 3.20058132, 5.80654132, 4.76088805,NEWLINE 5.80654132, 2.89810483, 2.89810483, 5.25778406, 3.90353806,NEWLINE 5.80654132, 5.80654132, 5.25778406, 5.80654132, 5.80654132,NEWLINE 3.90353806, 5.80654132, 5.25778406, 4.76088805, 5.80654132,NEWLINE 2.89810483, 5.25778406, 5.80654132, 5.80654132, 4.31095206,NEWLINE 5.25778406, 5.80654132, 5.80654132, 5.80654132, 5.80654132,NEWLINE 2.89810483, 5.80654132, 3.53462742, 3.90353806, 5.25778406,NEWLINE 5.80654132, 3.20058132, 2.89810483, 5.80654132, 4.31095206,NEWLINE 5.80654132, 3.53462742, 5.25778406, 4.76088805, 5.80654132,NEWLINE 3.53462742, 3.90353806, 5.80654132, 3.20058132, 5.80654132,NEWLINE 5.80654132, 3.53462742, 5.25778406, 4.76088805, 4.76088805,NEWLINE 5.80654132, 5.80654132, 2.89810483, 3.20058132, 5.80654132,NEWLINE 5.80654132, 5.80654132, 5.80654132, 5.25778406, 5.25778406,NEWLINE 5.80654132, 5.80654132, 4.76088805, 5.80654132, 4.31095206,NEWLINE 5.25778406, 5.80654132, 4.31095206, 4.31095206, 5.80654132,NEWLINE 5.80654132, 3.53462742, 4.76088805, 3.53462742, 4.76088805,NEWLINE 4.31095206, 5.80654132, 3.90353806, 5.80654132, 4.76088805,NEWLINE 5.80654132, 5.80654132, 5.80654132, 4.31095206, 3.90353806,NEWLINE 5.80654132, 4.76088805, 4.76088805, 3.53462742, 5.80654132,NEWLINE 5.80654132, 5.25778406, 3.53462742, 3.20058132, 3.53462742,NEWLINE 3.90353806, 5.80654132, 4.31095206, 4.76088805, 5.80654132,NEWLINE 5.80654132, 5.80654132, 3.90353806, 4.76088805, 2.89810483,NEWLINE 5.80654132, 5.80654132, 5.80654132, 4.76088805, 5.25778406,NEWLINE 5.80654132, 5.80654132, 5.80654132, 5.80654132, 5.80654132,NEWLINE 5.80654132, 5.80654132, 3.90353806, 5.25778406, 4.76088805,NEWLINE 5.80654132, 4.76088805, 3.90353806, 5.80654132, 5.80654132,NEWLINE 4.76088805, 5.80654132, 5.25778406, 5.80654132, 2.89810483,NEWLINE 5.80654132, 5.25778406, 3.90353806, 3.90353806, 5.80654132,NEWLINE 5.25778406, 3.53462742, 5.80654132, 4.76088805, 5.25778406,NEWLINE 5.80654132, 3.90353806, 4.31095206, 5.80654132, 5.25778406,NEWLINE 3.90353806, 3.53462742, 5.25778406, 2.89810483, 5.80654132,NEWLINE 3.53462742, 4.76088805, 4.31095206, 5.80654132, 5.80654132,NEWLINE 5.80654132, 5.80654132, 5.80654132, 3.90353806, 5.80654132,NEWLINE 4.31095206, 5.80654132, 5.80654132, 5.25778406, 5.80654132,NEWLINE 5.80654132, 5.80654132, 5.80654132, 5.25778406, 5.25778406,NEWLINE 5.80654132, 5.25778406, 5.80654132, 5.80654132, 5.80654132,NEWLINE 5.80654132, 5.25778406, 4.31095206, 5.80654132, 5.25778406,NEWLINE 5.80654132, 5.25778406, 5.80654132, 5.80654132, 5.80654132,NEWLINE 5.80654132, 4.31095206, 5.25778406, 3.53462742, 2.89810483,NEWLINE 5.80654132, 5.80654132, 3.20058132, 5.80654132, 4.31095206,NEWLINE 5.80654132, 5.80654132, 5.80654132, 5.80654132, 3.90353806,NEWLINE 3.90353806, 3.90353806, 5.80654132, 5.80654132, 5.80654132,NEWLINE 5.80654132, 4.76088805, 3.20058132, 4.31095206, 5.80654132,NEWLINE 3.90353806, 5.80654132, 5.80654132, 5.80654132, 5.80654132,NEWLINE 5.80654132, 3.90353806, 5.80654132, 5.80654132, 5.80654132,NEWLINE 5.80654132, 3.90353806, 5.80654132, 3.90353806, 3.53462742,NEWLINE 5.80654132, 4.76088805, 5.80654132, 5.80654132, 5.80654132,NEWLINE 5.80654132, 5.80654132, 5.80654132, 5.80654132, 5.80654132,NEWLINE 4.76088805, 5.25778406, 5.80654132, 5.80654132, 5.80654132,NEWLINE 5.80654132, 5.80654132, 5.80654132, 5.80654132, 5.25778406,NEWLINE 3.53462742, 5.25778406, 5.80654132, 3.53462742, 5.80654132,NEWLINE 3.90353806, 5.80654132, 5.80654132, 5.80654132, 3.90353806,NEWLINE 3.20058132, 5.80654132, 5.80654132, 3.90353806, 5.80654132,NEWLINE 5.80654132, 5.80654132, 5.80654132, 5.80654132, 5.80654132,NEWLINE 5.80654132, 5.80654132, 5.80654132, 5.80654132, 5.80654132,NEWLINE 5.80654132, 5.80654132, 3.53462742, 5.80654132, 5.80654132,NEWLINE 5.80654132, 5.80654132, 3.53462742, 5.25778406, 3.90353806,NEWLINE 5.80654132, 4.76088805, 4.76088805, 3.90353806, 5.80654132,NEWLINE 5.80654132, 4.31095206, 2.89810483, 5.80654132, 5.80654132,NEWLINE 3.90353806, 5.80654132, 3.53462742, 3.90353806, 5.80654132,NEWLINE 5.80654132, 4.76088805, 5.80654132, 4.31095206, 5.25778406,NEWLINE 5.25778406, 3.20058132, 3.53462742, 5.80654132, 4.31095206,NEWLINE 5.80654132, 4.76088805, 3.90353806, 4.76088805, 4.76088805,NEWLINE 5.80654132, 5.80654132, 5.25778406, 3.90353806, 5.80654132,NEWLINE 5.80654132, 5.80654132, 5.80654132, 5.80654132, 5.80654132,NEWLINE 5.80654132, 3.53462742, 4.31095206, 3.90353806, 4.76088805,NEWLINE 4.31095206, 3.53462742, 3.90353806, 5.80654132, 5.80654132,NEWLINE 5.80654132, 5.80654132, 3.20058132, 5.80654132, 5.80654132,NEWLINE 5.80654132, 5.80654132, 5.80654132, 3.90353806, 4.76088805,NEWLINE 5.25778406, 3.53462742, 3.20058132, 5.80654132, 3.90353806,NEWLINE 5.80654132, 3.53462742, 5.80654132, 5.80654132, 3.90353806,NEWLINE 5.80654132, 3.90353806, 5.80654132, 5.80654132, 5.80654132,NEWLINE 5.80654132, 4.76088805, 3.90353806, 4.76088805, 5.25778406,NEWLINE 2.89810483, 5.80654132, 4.31095206, 5.80654132, 4.76088805,NEWLINE 5.80654132, 5.25778406, 5.80654132, 5.80654132, 5.80654132,NEWLINE 3.53462742, 2.89810483, 5.80654132, 5.80654132, 5.80654132,NEWLINE 3.90353806, 4.76088805, 5.80654132, 5.25778406, 4.76088805,NEWLINE 5.25778406, 5.80654132, 5.80654132, 5.25778406, 5.80654132,NEWLINE 5.80654132, 5.80654132, 2.89810483, 5.25778406, 5.80654132,NEWLINE 5.80654132, 4.76088805, 4.76088805, 5.25778406, 5.80654132,NEWLINE 5.80654132, 4.31095206, 3.20058132, 3.53462742, 5.80654132,NEWLINE 5.80654132, 5.80654132, 5.80654132, 5.80654132, 5.25778406,NEWLINE 5.80654132, 5.80654132, 3.90353806, 4.76088805, 5.80654132,NEWLINE 3.53462742, 5.80654132, 5.25778406, 2.89810483, 5.80654132,NEWLINE 5.25778406, 5.80654132, 5.80654132, 5.80654132, 5.25778406,NEWLINE 5.80654132, 5.80654132, 5.80654132, 5.80654132, 5.80654132,NEWLINE 5.80654132, 4.31095206, 5.80654132, 3.20058132, 5.80654132,NEWLINE 5.25778406, 4.76088805, 5.25778406, 5.80654132, 4.76088805,NEWLINE 5.80654132, 3.90353806, 4.31095206, 5.80654132, 5.80654132,NEWLINE 5.80654132, 5.80654132, 5.25778406, 5.80654132, 3.90353806,NEWLINE 4.76088805, 3.90353806, 5.80654132, 3.53462742, 5.80654132,NEWLINE 5.80654132, 5.80654132, 5.80654132, 3.53462742, 5.80654132,NEWLINE 4.76088805, 5.80654132, 5.80654132, 5.80654132, 5.80654132,NEWLINE 5.80654132, 5.80654132, 5.80654132, 5.80654132, 3.90353806,NEWLINE 2.6242144, 5.80654132, 5.80654132, 5.80654132, 5.80654132,NEWLINE 4.76088805, 5.80654132, 3.53462742, 5.80654132, 5.80654132,NEWLINE 3.90353806, 5.80654132, 5.80654132, 5.80654132, 5.80654132,NEWLINE 5.80654132, 5.80654132, 3.20058132, 3.20058132, 5.80654132,NEWLINE 5.80654132, 5.80654132, 3.90353806, 5.80654132, 5.25778406,NEWLINE 4.31095206, 5.25778406, 4.31095206, 4.31095206, 4.76088805,NEWLINE 5.80654132, 4.76088805, 5.80654132, 3.53462742, 5.80654132,NEWLINE 5.80654132, 5.80654132, 5.80654132, 5.80654132, 3.20058132,NEWLINE 5.80654132, 3.90353806, 5.80654132, 4.76088805, 5.80654132,NEWLINE 3.90353806, 5.80654132, 5.80654132, 5.80654132, 5.80654132,NEWLINE 5.80654132, 5.25778406, 5.80654132, 4.31095206, 5.25778406,NEWLINE 4.31095206, 5.80654132, 3.90353806, 5.80654132, 3.53462742,NEWLINE 5.25778406, 5.80654132, 5.80654132, 4.31095206, 3.90353806,NEWLINE 3.53462742, 5.80654132, 5.80654132, 5.80654132, 4.31095206,NEWLINE 5.80654132, 5.80654132, 5.25778406, 4.76088805, 4.31095206,NEWLINE 3.20058132, 5.80654132, 3.53462742, 3.20058132, 5.80654132,NEWLINE 5.80654132, 3.20058132, 3.20058132, 5.80654132, 4.31095206,NEWLINE 4.31095206, 5.80654132, 5.80654132, 3.90353806, 3.90353806,NEWLINE 3.53462742, 5.80654132, 3.90353806, 3.53462742, 5.80654132,NEWLINE 3.90353806, 5.25778406, 5.80654132, 3.53462742, 5.80654132,NEWLINE 5.25778406, 5.80654132, 4.31095206, 3.90353806, 5.80654132,NEWLINE 5.80654132, 4.31095206, 5.25778406, 5.80654132, 5.80654132,NEWLINE 5.80654132, 5.80654132, 5.80654132, 5.80654132, 5.25778406,NEWLINE 3.20058132, 5.25778406, 2.89810483, 3.90353806, 5.80654132,NEWLINE 3.53462742, 5.80654132, 5.25778406, 5.80654132, 2.89810483,NEWLINE 5.80654132, 5.80654132, 5.80654132, 5.80654132, 3.20058132,NEWLINE 5.80654132, 5.25778406, 3.53462742, 4.31095206, 4.76088805,NEWLINE 3.90353806, 5.80654132, 5.80654132, 5.25778406, 3.90353806,NEWLINE 4.76088805, 4.31095206, 5.80654132, 5.80654132, 5.80654132,NEWLINE 5.80654132, 5.80654132, 3.90353806, 5.80654132, 5.80654132,NEWLINE 5.80654132, 5.80654132, 5.80654132, 5.80654132, 5.25778406,NEWLINE 3.53462742, 5.80654132, 5.80654132, 5.25778406, 5.80654132,NEWLINE 3.20058132, 5.80654132, 4.76088805, 5.80654132, 4.76088805,NEWLINE 5.80654132, 5.25778406, 5.80654132, 5.80654132, 5.80654132,NEWLINE 5.80654132, 5.25778406, 2.89810483, 5.80654132, 5.80654132,NEWLINE 2.89810483, 3.53462742, 5.80654132, 5.80654132, 2.89810483,NEWLINE 4.31095206, 3.53462742, 4.31095206, 5.80654132, 5.80654132,NEWLINE 5.80654132, 5.80654132, 5.80654132, 5.80654132, 4.31095206,NEWLINE 4.76088805, 5.25778406, 5.80654132, 5.80654132, 5.80654132,NEWLINE 5.80654132, 5.25778406, 3.90353806, 5.80654132, 5.25778406,NEWLINE 5.80654132, 2.89810483, 2.89810483, 5.80654132, 3.53462742,NEWLINE 5.80654132, 3.53462742, 5.80654132, 4.31095206, 2.89810483,NEWLINE 5.80654132, 5.80654132, 2.89810483, 4.76088805, 5.80654132,NEWLINE 5.80654132, 3.20058132, 5.80654132, 3.90353806, 5.80654132,NEWLINE 5.80654132, 3.20058132, 3.90353806, 4.76088805, 4.76088805,NEWLINE 5.80654132, 3.90353806, 4.31095206, 5.80654132, 4.31095206,NEWLINE 5.80654132, 3.20058132, 4.31095206, 4.76088805, 3.53462742,NEWLINE 5.80654132, 5.80654132, 3.53462742, 3.53462742, 3.53462742,NEWLINE 5.80654132, 5.80654132, 3.90353806, 3.90353806, 3.20058132,NEWLINE 5.80654132, 5.80654132, 2.89810483, 3.90353806, 5.80654132,NEWLINE 2.89810483, 3.53462742, 3.53462742, 4.31095206, 5.80654132,NEWLINE 3.53462742, 5.80654132, 5.80654132, 5.80654132, 5.80654132,NEWLINE 5.80654132, 5.80654132, 5.25778406, 5.80654132, 5.80654132,NEWLINE 5.80654132, 5.80654132, 5.80654132, 5.80654132, 5.80654132,NEWLINE 5.80654132, 4.76088805, 5.80654132, 5.80654132, 4.76088805,NEWLINE 5.80654132, 5.80654132, 4.76088805, 4.76088805, 5.80654132,NEWLINE 5.25778406, 4.31095206, 5.80654132, 4.76088805, 3.90353806,NEWLINE 4.31095206, 5.80654132, 2.89810483, 4.31095206, 5.25778406,NEWLINE 5.80654132, 5.80654132, 5.80654132, 5.80654132, 3.20058132,NEWLINE 5.25778406, 5.80654132, 4.76088805, 5.80654132, 4.31095206,NEWLINE 5.80654132, 5.80654132, 4.76088805, 4.31095206, 5.80654132,NEWLINE 5.80654132, 5.80654132, 5.80654132, 5.80654132, 4.31095206,NEWLINE 4.31095206, 3.20058132, 4.76088805, 5.80654132, 3.20058132,NEWLINE 3.20058132, 5.80654132, 3.90353806, 5.25778406, 3.20058132,NEWLINE 4.76088805, 3.20058132, 3.53462742, 4.76088805, 5.80654132,NEWLINE 5.80654132, 4.31095206, 4.76088805, 5.80654132, 4.31095206,NEWLINE 5.80654132, 4.76088805, 4.31095206, 2.89810483, 5.80654132,NEWLINE 5.80654132, 5.80654132, 4.76088805, 5.80654132, 5.80654132,NEWLINE 5.80654132, 5.80654132, 4.76088805, 5.25778406, 4.31095206,NEWLINE 5.80654132, 3.90353806, 3.53462742, 4.76088805, 5.80654132,NEWLINE 4.31095206, 5.80654132, 5.80654132, 3.20058132, 5.80654132,NEWLINE 5.25778406, 5.80654132, 5.80654132, 5.80654132, 3.53462742,NEWLINE 2.6242144, 5.80654132, 5.80654132, 3.53462742, 5.25778406,NEWLINE 3.90353806, 5.80654132, 2.89810483, 5.80654132, 3.90353806,NEWLINE 5.80654132, 5.80654132, 3.90353806, 2.89810483, 5.80654132,NEWLINE 4.76088805, 4.31095206, 5.80654132, 5.25778406, 5.80654132,NEWLINE 5.80654132, 4.31095206, 5.80654132, 5.80654132, 5.80654132,NEWLINE 3.90353806, 4.76088805, 5.80654132, 4.76088805, 5.80654132,NEWLINE 4.76088805, 3.53462742, 3.90353806, 5.80654132, 5.80654132,NEWLINE 5.80654132, 5.25778406, 5.80654132, 5.80654132, 5.25778406,NEWLINE 5.80654132, 5.80654132, 5.80654132, 5.80654132, 5.80654132,NEWLINE 5.80654132, 5.80654132, 5.80654132, 5.80654132, 5.80654132,NEWLINE 3.53462742, 3.53462742, 3.90353806, 5.80654132, 4.31095206,NEWLINE 3.53462742, 5.80654132, 4.76088805, 4.76088805, 3.20058132,NEWLINE 3.90353806, 5.80654132, 5.25778406, 5.80654132, 5.80654132,NEWLINE 5.80654132, 5.80654132, 4.31095206, 5.25778406, 4.31095206,NEWLINE 5.80654132, 3.20058132, 5.80654132, 4.31095206, 4.31095206,NEWLINE 4.76088805, 5.80654132, 4.76088805, 4.31095206, 5.80654132,NEWLINE 5.25778406, 3.53462742, 3.53462742, 5.25778406, 5.80654132,NEWLINE 3.90353806, 5.25778406, 4.31095206, 4.31095206, 3.53462742,NEWLINE 5.80654132, 3.90353806, 5.80654132, 5.80654132, 4.76088805,NEWLINE 5.25778406, 3.20058132, 3.90353806, 5.80654132, 5.25778406,NEWLINE 5.80654132, 5.80654132, 5.25778406, 5.80654132, 4.31095206,NEWLINE 5.25778406, 4.76088805, 5.80654132, 5.80654132, 5.25778406,NEWLINE 3.53462742, 5.80654132, 5.80654132, 5.80654132, 5.25778406,NEWLINE 5.25778406, 5.80654132, 3.20058132, 5.80654132, 5.80654132,NEWLINE 3.53462742, 5.80654132, 5.80654132, 5.80654132, 4.31095206,NEWLINE 5.80654132, 4.76088805, 5.80654132, 5.80654132, 5.80654132,NEWLINE 3.90353806, 4.31095206, 5.25778406, 5.80654132, 3.53462742,NEWLINE 3.90353806, 5.25778406, 4.31095206, 5.80654132, 5.25778406,NEWLINE 5.25778406, 2.89810483, 5.80654132, 5.80654132, 5.80654132,NEWLINE 5.80654132, 5.80654132, 5.25778406, 5.80654132, 4.76088805,NEWLINE 5.80654132, 5.80654132, 5.80654132, 4.31095206, 5.80654132,NEWLINE 3.20058132, 3.90353806, 5.80654132, 5.80654132, 5.25778406,NEWLINE 5.80654132, 5.80654132, 5.80654132, 5.80654132, 5.80654132,NEWLINE 5.80654132, 5.80654132, 2.6242144, 5.80654132, 3.90353806,NEWLINE 5.25778406, 4.76088805, 5.80654132, 5.80654132, 3.90353806,NEWLINE 5.80654132, 3.53462742, 2.89810483, 5.80654132, 3.53462742,NEWLINE 2.89810483, 4.76088805, 5.80654132, 5.80654132, 5.80654132,NEWLINE 4.31095206, 5.80654132, 4.76088805, 3.90353806, 2.89810483,NEWLINE 4.76088805, 5.80654132, 2.6242144, 3.53462742, 4.31095206,NEWLINE 5.25778406, 5.25778406, 3.20058132, 4.31095206, 4.31095206,NEWLINE 3.20058132, 4.31095206, 5.25778406, 4.31095206, 5.25778406,NEWLINE 3.90353806, 4.31095206, 5.80654132, 5.80654132, 5.80654132,NEWLINE 5.80654132, 3.90353806, 5.80654132, 5.80654132, 5.80654132,NEWLINE 4.31095206, 5.80654132, 5.80654132, 5.80654132, 3.90353806,NEWLINE 5.25778406, 3.90353806, 4.31095206, 4.76088805, 3.90353806,NEWLINE 5.80654132, 5.80654132, 5.80654132, 2.89810483, 5.80654132,NEWLINE 5.80654132, 5.80654132, 5.80654132, 5.80654132, 5.80654132,NEWLINE 5.80654132, 3.90353806, 3.20058132, 5.25778406, 4.76088805,NEWLINE 5.25778406])NEWLINENEWLINENEWLINEclass InvGaussIdentity(Medpar1):NEWLINE """NEWLINE Accuracy is different for R vs Stata ML vs Stata IRLS, we are close.NEWLINE """NEWLINE def __init__(self):NEWLINE super(InvGaussIdentity, self).__init__()NEWLINE self.params = np.array([0.44538838, -1.05872706, 2.83947966])NEWLINE self.bse = np.array([0.02586783, 0.13830023, 0.20834864])NEWLINE filename = os.path.join(os.path.dirname(os.path.abspath(__file__)),NEWLINE "igaussident_resids.csv")NEWLINE self.resids = pd.read_csv(filename, sep=',', header=None).valuesNEWLINE self.null_deviance = 335.1539777981053 # from R, Rpy bugNEWLINE self.df_null = 3675NEWLINE self.deviance = 305.33661191013988NEWLINE self.df_resid = 3673NEWLINE self.df_model = 2NEWLINE self.aic_R = 18558.677276882016NEWLINE self.aic_Stata = 6.619290231464371NEWLINE self.bic_Stata = -29848.45250412075NEWLINE self.llf_stata = -12163.25544543151NEWLINE self.chi2 = 567.1229375785638 # in Stata not smNEWLINE # self.llf = -9275.3386384410078 # from RNEWLINE self.llf = -12163.25545 # from Stata, big diff with RNEWLINE self.scale = 0.10115387793455666NEWLINE self.pearson_chi2 = 371.5346609292967 # deviance_p in StataNEWLINE self.fittedvalues = np.array([NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 5.9571983,NEWLINE 6.84797506, 6.84797506, 6.40258668, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 5.9571983, 6.84797506,NEWLINE 5.51180993, 6.84797506, 5.51180993, 5.06642155, 5.06642155,NEWLINE 6.84797506, 6.84797506, 6.40258668, 6.84797506, 5.9571983,NEWLINE 6.84797506, 4.62103317, 6.84797506, 6.84797506, 6.84797506,NEWLINE 5.9571983, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 4.17564479, 6.84797506, 6.84797506, 4.62103317,NEWLINE 6.84797506, 6.84797506, 5.06642155, 6.84797506, 6.84797506,NEWLINE 6.84797506, 5.51180993, 6.40258668, 6.40258668, 4.62103317,NEWLINE 5.06642155, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 5.51180993, 6.84797506, 6.84797506, 6.40258668, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 5.9571983, 6.40258668,NEWLINE 6.40258668, 5.51180993, 6.84797506, 6.84797506, 6.84797506,NEWLINE 5.9571983, 6.84797506, 6.84797506, 4.17564479, 5.9571983,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 5.51180993, 5.51180993, 6.84797506, 6.40258668, 6.84797506,NEWLINE 6.84797506, 6.84797506, 5.06642155, 6.84797506, 6.40258668,NEWLINE 6.84797506, 6.40258668, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 5.51180993, 6.40258668, 5.51180993,NEWLINE 6.84797506, 6.84797506, 5.06642155, 5.9571983, 6.84797506,NEWLINE 5.06642155, 6.40258668, 4.17564479, 6.84797506, 6.84797506,NEWLINE 5.51180993, 5.51180993, 6.40258668, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.40258668, 4.62103317,NEWLINE 6.84797506, 6.40258668, 6.40258668, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.40258668, 6.84797506,NEWLINE 6.40258668, 6.84797506, 6.84797506, 6.40258668, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 5.9571983,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 5.9571983,NEWLINE 6.84797506, 6.84797506, 6.40258668, 4.17564479, 6.84797506,NEWLINE 6.84797506, 5.51180993, 6.84797506, 5.9571983, 4.62103317,NEWLINE 5.9571983, 6.40258668, 6.40258668, 6.84797506, 6.84797506,NEWLINE 5.9571983, 6.84797506, 6.84797506, 4.62103317, 6.84797506,NEWLINE 6.40258668, 6.84797506, 6.40258668, 6.84797506, 5.51180993,NEWLINE 6.84797506, 4.62103317, 5.06642155, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.40258668,NEWLINE 6.84797506, 4.62103317, 5.51180993, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 4.62103317, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.40258668, 5.9571983, 6.84797506, 6.84797506,NEWLINE 6.84797506, 5.06642155, 6.84797506, 6.40258668, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.40258668, 6.84797506,NEWLINE 6.40258668, 6.84797506, 6.40258668, 4.62103317, 5.9571983,NEWLINE 5.51180993, 6.40258668, 6.40258668, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.40258668, 6.84797506, 6.84797506, 6.40258668,NEWLINE 5.9571983, 6.84797506, 5.51180993, 5.9571983, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.40258668, 6.84797506,NEWLINE 4.62103317, 6.84797506, 5.51180993, 6.84797506, 6.40258668,NEWLINE 5.9571983, 4.62103317, 4.62103317, 6.84797506, 6.40258668,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.40258668, 4.62103317,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 5.51180993,NEWLINE 6.84797506, 6.84797506, 6.84797506, 5.51180993, 6.84797506,NEWLINE 5.9571983, 6.84797506, 5.06642155, 4.62103317, 6.40258668,NEWLINE 5.9571983, 6.84797506, 6.84797506, 6.84797506, 5.51180993,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.40258668, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.40258668, 6.84797506,NEWLINE 4.17564479, 5.06642155, 6.84797506, 6.84797506, 6.84797506,NEWLINE 5.06642155, 6.84797506, 6.84797506, 6.40258668, 6.84797506,NEWLINE 6.84797506, 6.40258668, 4.17564479, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 4.62103317, 6.84797506, 6.40258668,NEWLINE 6.84797506, 5.51180993, 5.51180993, 6.40258668, 6.84797506,NEWLINE 6.40258668, 6.40258668, 6.84797506, 4.62103317, 6.84797506,NEWLINE 6.84797506, 6.84797506, 5.51180993, 6.40258668, 6.84797506,NEWLINE 4.17564479, 6.40258668, 5.51180993, 5.9571983, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 4.62103317, 6.84797506,NEWLINE 5.51180993, 6.84797506, 6.40258668, 5.51180993, 5.06642155,NEWLINE 6.84797506, 6.84797506, 6.84797506, 5.06642155, 6.40258668,NEWLINE 6.84797506, 6.40258668, 5.9571983, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 5.51180993, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 4.17564479, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 5.06642155, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.40258668, 6.84797506, 6.84797506,NEWLINE 6.40258668, 6.84797506, 6.40258668, 6.84797506, 5.51180993,NEWLINE 6.40258668, 6.84797506, 6.40258668, 6.84797506, 6.40258668,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 4.17564479,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.40258668, 6.84797506,NEWLINE 6.84797506, 6.40258668, 6.84797506, 6.84797506, 6.40258668,NEWLINE 5.9571983, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 5.9571983, 6.84797506, 6.40258668, 6.84797506, 6.84797506,NEWLINE 6.84797506, 4.17564479, 6.84797506, 6.40258668, 6.40258668,NEWLINE 5.06642155, 5.9571983, 6.40258668, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 4.17564479, 5.51180993, 5.06642155,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 5.06642155, 6.40258668,NEWLINE 6.84797506, 6.84797506, 5.9571983, 6.84797506, 6.40258668,NEWLINE 6.84797506, 6.84797506, 6.84797506, 5.9571983, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.40258668,NEWLINE 6.84797506, 5.51180993, 5.9571983, 6.84797506, 5.9571983,NEWLINE 6.40258668, 5.9571983, 5.9571983, 6.84797506, 5.9571983,NEWLINE 6.84797506, 6.84797506, 6.84797506, 5.06642155, 6.40258668,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.40258668, 6.84797506, 6.40258668, 6.84797506, 5.06642155,NEWLINE 6.84797506, 6.84797506, 4.62103317, 6.40258668, 4.17564479,NEWLINE 6.84797506, 3.73025641, 6.84797506, 6.84797506, 5.9571983,NEWLINE 5.51180993, 6.84797506, 5.9571983, 4.62103317, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 5.9571983, 5.06642155,NEWLINE 6.84797506, 6.40258668, 6.84797506, 5.51180993, 6.84797506,NEWLINE 5.06642155, 6.84797506, 6.84797506, 6.84797506, 5.51180993,NEWLINE 5.51180993, 5.06642155, 6.84797506, 6.40258668, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 4.62103317, 6.84797506, 6.84797506, 6.84797506, 5.9571983,NEWLINE 6.40258668, 6.84797506, 6.84797506, 5.9571983, 6.84797506,NEWLINE 6.84797506, 6.40258668, 5.06642155, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 5.06642155, 5.9571983, 6.84797506, 5.9571983,NEWLINE 6.40258668, 6.84797506, 6.84797506, 6.84797506, 5.06642155,NEWLINE 6.84797506, 6.84797506, 6.84797506, 5.9571983, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.40258668, 6.84797506, 6.84797506, 5.9571983, 6.40258668,NEWLINE 5.06642155, 6.84797506, 6.84797506, 6.84797506, 5.9571983,NEWLINE 6.84797506, 6.40258668, 5.51180993, 5.9571983, 5.06642155,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.40258668, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 5.51180993, 6.84797506, 6.84797506,NEWLINE 6.40258668, 6.84797506, 6.84797506, 5.9571983, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.40258668, 6.84797506, 5.51180993,NEWLINE 6.84797506, 6.84797506, 6.84797506, 5.9571983, 6.84797506,NEWLINE 6.40258668, 6.40258668, 6.84797506, 5.9571983, 6.84797506,NEWLINE 6.40258668, 6.84797506, 6.84797506, 6.84797506, 5.06642155,NEWLINE 5.51180993, 6.84797506, 4.17564479, 5.9571983, 6.40258668,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.40258668, 6.84797506, 6.84797506,NEWLINE 5.06642155, 6.84797506, 6.40258668, 6.84797506, 4.62103317,NEWLINE 6.84797506, 6.84797506, 5.9571983, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 5.06642155, 6.40258668, 4.17564479, 6.84797506, 6.84797506,NEWLINE 6.40258668, 5.06642155, 4.62103317, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 4.17564479, 6.84797506, 6.84797506, 6.84797506,NEWLINE 4.17564479, 6.84797506, 6.84797506, 6.40258668, 6.84797506,NEWLINE 6.84797506, 6.40258668, 6.84797506, 6.84797506, 4.17564479,NEWLINE 6.84797506, 5.06642155, 5.51180993, 5.51180993, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.40258668, 6.84797506,NEWLINE 6.84797506, 6.40258668, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 5.51180993, 5.51180993, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 5.06642155, 6.40258668, 5.9571983,NEWLINE 5.9571983, 6.40258668, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.40258668, 6.84797506, 6.84797506, 6.40258668, 6.84797506,NEWLINE 6.84797506, 5.06642155, 6.84797506, 5.9571983, 6.84797506,NEWLINE 6.84797506, 6.84797506, 5.06642155, 4.62103317, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 5.9571983,NEWLINE 6.84797506, 5.9571983, 6.84797506, 6.84797506, 6.84797506,NEWLINE 5.51180993, 6.84797506, 6.84797506, 6.84797506, 5.51180993,NEWLINE 6.40258668, 6.84797506, 6.84797506, 6.40258668, 6.40258668,NEWLINE 6.84797506, 6.84797506, 5.9571983, 6.84797506, 5.51180993,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 5.06642155, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 4.62103317,NEWLINE 6.84797506, 6.40258668, 6.84797506, 5.9571983, 4.62103317,NEWLINE 5.9571983, 6.84797506, 4.17564479, 6.84797506, 6.84797506,NEWLINE 6.84797506, 3.73025641, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 5.9571983, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 5.9571983, 5.9571983, 5.9571983, 6.84797506,NEWLINE 6.84797506, 6.40258668, 6.84797506, 6.40258668, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 5.9571983, 6.84797506, 4.62103317, 6.40258668,NEWLINE 5.9571983, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.40258668, 5.51180993,NEWLINE 6.84797506, 6.84797506, 6.84797506, 5.9571983, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.40258668, 6.84797506,NEWLINE 6.84797506, 5.9571983, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.40258668, 6.40258668, 6.84797506, 6.84797506, 6.40258668,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.40258668, 6.84797506,NEWLINE 6.84797506, 6.84797506, 5.51180993, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 3.73025641, 6.84797506, 6.84797506,NEWLINE 6.84797506, 4.17564479, 6.40258668, 5.9571983, 6.84797506,NEWLINE 6.84797506, 6.40258668, 5.06642155, 6.84797506, 6.84797506,NEWLINE 5.9571983, 6.84797506, 4.17564479, 5.51180993, 6.40258668,NEWLINE 4.62103317, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.40258668,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.40258668,NEWLINE 6.84797506, 5.51180993, 6.40258668, 6.40258668, 6.84797506,NEWLINE 6.40258668, 6.84797506, 6.84797506, 6.84797506, 5.51180993,NEWLINE 6.84797506, 6.40258668, 6.84797506, 6.84797506, 5.06642155,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.40258668, 6.40258668,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.40258668, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 3.73025641, 6.84797506, 5.51180993,NEWLINE 5.51180993, 6.84797506, 6.40258668, 6.84797506, 5.06642155,NEWLINE 6.84797506, 6.84797506, 6.84797506, 5.06642155, 6.84797506,NEWLINE 5.9571983, 6.84797506, 4.17564479, 6.84797506, 5.51180993,NEWLINE 4.17564479, 5.06642155, 6.40258668, 5.9571983, 6.84797506,NEWLINE 6.40258668, 6.84797506, 4.62103317, 5.9571983, 6.84797506,NEWLINE 6.84797506, 6.84797506, 5.51180993, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 4.62103317, 6.40258668, 6.84797506, 6.84797506,NEWLINE 6.84797506, 5.9571983, 6.40258668, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 3.73025641, 5.06642155, 6.84797506, 4.62103317, 6.84797506,NEWLINE 5.06642155, 6.84797506, 5.51180993, 5.9571983, 5.9571983,NEWLINE 4.17564479, 5.9571983, 5.51180993, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 5.51180993, 6.40258668,NEWLINE 6.84797506, 6.84797506, 6.84797506, 5.51180993, 6.84797506,NEWLINE 6.84797506, 6.84797506, 5.51180993, 6.84797506, 6.84797506,NEWLINE 6.40258668, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 4.62103317,NEWLINE 5.06642155, 6.84797506, 6.84797506, 6.40258668, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.40258668, 6.84797506, 6.84797506, 6.40258668,NEWLINE 6.40258668, 5.9571983, 6.84797506, 5.9571983, 6.40258668,NEWLINE 6.84797506, 6.84797506, 6.84797506, 5.9571983, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 5.51180993, 6.84797506, 6.84797506, 5.9571983, 6.40258668,NEWLINE 5.9571983, 6.84797506, 6.84797506, 6.40258668, 6.84797506,NEWLINE 5.06642155, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.40258668, 5.9571983, 6.40258668, 5.06642155,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 5.06642155,NEWLINE 6.84797506, 6.40258668, 6.84797506, 5.51180993, 6.84797506,NEWLINE 6.84797506, 6.40258668, 6.84797506, 5.9571983, 6.40258668,NEWLINE 5.9571983, 6.84797506, 6.84797506, 6.84797506, 6.40258668,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 5.06642155, 6.84797506, 5.51180993, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 5.06642155, 6.40258668, 6.84797506,NEWLINE 6.84797506, 6.40258668, 6.84797506, 5.9571983, 5.51180993,NEWLINE 6.84797506, 6.84797506, 6.84797506, 5.51180993, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 4.62103317,NEWLINE 5.9571983, 6.84797506, 4.62103317, 6.84797506, 6.40258668,NEWLINE 6.84797506, 6.84797506, 4.62103317, 6.84797506, 6.84797506,NEWLINE 6.40258668, 4.17564479, 3.73025641, 6.40258668, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 5.9571983,NEWLINE 6.84797506, 5.06642155, 5.9571983, 6.84797506, 6.84797506,NEWLINE 4.17564479, 6.84797506, 6.84797506, 6.84797506, 4.62103317,NEWLINE 6.84797506, 6.84797506, 6.84797506, 5.9571983, 5.9571983,NEWLINE 6.84797506, 6.40258668, 5.9571983, 6.84797506, 6.40258668,NEWLINE 5.9571983, 6.84797506, 5.9571983, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 4.62103317, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 5.06642155, 5.9571983, 6.40258668, 6.40258668,NEWLINE 6.84797506, 6.84797506, 6.84797506, 5.9571983, 4.62103317,NEWLINE 6.84797506, 5.9571983, 5.06642155, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 5.9571983,NEWLINE 6.40258668, 6.40258668, 6.84797506, 6.84797506, 6.40258668,NEWLINE 4.17564479, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 3.73025641, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.40258668, 6.84797506, 6.84797506,NEWLINE 6.84797506, 5.06642155, 6.84797506, 6.40258668, 5.06642155,NEWLINE 5.06642155, 6.84797506, 5.9571983, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.40258668, 4.62103317, 6.84797506, 6.84797506,NEWLINE 6.84797506, 5.9571983, 6.84797506, 6.84797506, 6.84797506,NEWLINE 5.06642155, 6.84797506, 6.84797506, 6.40258668, 5.51180993,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 5.51180993, 6.84797506, 6.84797506, 6.40258668,NEWLINE 6.84797506, 6.84797506, 5.51180993, 6.84797506, 6.40258668,NEWLINE 6.40258668, 6.84797506, 6.40258668, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.40258668, 6.40258668, 6.84797506, 5.06642155,NEWLINE 4.62103317, 5.06642155, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 4.62103317,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.40258668, 4.62103317, 4.62103317, 6.84797506, 5.51180993,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.40258668, 6.84797506, 6.84797506, 6.84797506,NEWLINE 5.9571983, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 5.06642155, 6.84797506,NEWLINE 4.17564479, 6.84797506, 5.06642155, 6.84797506, 6.84797506,NEWLINE 6.84797506, 5.51180993, 6.84797506, 4.62103317, 6.84797506,NEWLINE 6.84797506, 5.06642155, 5.51180993, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.40258668, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.40258668, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 5.9571983, 5.51180993,NEWLINE 6.84797506, 6.84797506, 4.17564479, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 5.06642155, 6.40258668,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 4.62103317, 6.84797506, 6.84797506, 6.84797506, 5.9571983,NEWLINE 6.84797506, 5.51180993, 5.06642155, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.40258668, 5.9571983, 6.84797506, 5.9571983,NEWLINE 6.84797506, 4.62103317, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 5.9571983, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 5.9571983,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 5.9571983, 6.84797506, 4.17564479,NEWLINE 6.40258668, 5.9571983, 6.84797506, 4.62103317, 6.84797506,NEWLINE 5.9571983, 5.51180993, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.40258668, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 5.9571983, 6.84797506, 6.84797506, 6.84797506, 3.73025641,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.40258668, 6.84797506,NEWLINE 6.84797506, 4.62103317, 5.06642155, 6.40258668, 6.84797506,NEWLINE 6.84797506, 4.62103317, 5.9571983, 6.84797506, 6.84797506,NEWLINE 6.84797506, 4.62103317, 6.84797506, 6.84797506, 5.51180993,NEWLINE 6.40258668, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 5.06642155,NEWLINE 6.84797506, 5.51180993, 6.40258668, 6.84797506, 6.40258668,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 5.51180993,NEWLINE 6.84797506, 6.84797506, 5.51180993, 6.84797506, 6.40258668,NEWLINE 6.84797506, 6.84797506, 5.9571983, 6.84797506, 6.84797506,NEWLINE 3.73025641, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.40258668, 6.84797506,NEWLINE 6.84797506, 5.9571983, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.40258668,NEWLINE 5.06642155, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.40258668, 6.84797506, 6.40258668, 5.06642155, 5.51180993,NEWLINE 5.9571983, 6.84797506, 6.40258668, 6.40258668, 6.84797506,NEWLINE 6.40258668, 6.84797506, 5.51180993, 5.06642155, 5.9571983,NEWLINE 6.40258668, 6.84797506, 6.84797506, 5.9571983, 5.51180993,NEWLINE 6.84797506, 6.40258668, 4.17564479, 6.40258668, 6.84797506,NEWLINE 5.9571983, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 3.73025641, 6.84797506, 6.84797506, 6.84797506,NEWLINE 5.51180993, 6.84797506, 6.40258668, 6.84797506, 6.40258668,NEWLINE 6.84797506, 6.40258668, 5.51180993, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.40258668, 6.40258668, 6.84797506, 6.84797506,NEWLINE 6.40258668, 5.06642155, 6.84797506, 5.51180993, 6.84797506,NEWLINE 5.06642155, 6.84797506, 4.62103317, 6.84797506, 6.84797506,NEWLINE 6.40258668, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 4.62103317, 6.40258668, 6.84797506, 4.17564479, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.40258668, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.40258668, 6.84797506, 5.51180993, 6.84797506,NEWLINE 6.84797506, 5.9571983, 6.40258668, 6.84797506, 5.06642155,NEWLINE 6.84797506, 6.84797506, 5.51180993, 6.84797506, 3.73025641,NEWLINE 6.40258668, 6.40258668, 6.84797506, 6.40258668, 6.84797506,NEWLINE 5.51180993, 6.40258668, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 5.9571983, 4.62103317, 6.84797506, 6.84797506,NEWLINE 5.06642155, 5.06642155, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 5.9571983, 6.84797506, 5.9571983,NEWLINE 4.62103317, 6.84797506, 4.62103317, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 3.73025641, 6.84797506, 5.51180993,NEWLINE 6.84797506, 6.40258668, 6.84797506, 6.40258668, 6.84797506,NEWLINE 5.06642155, 6.84797506, 6.84797506, 5.06642155, 3.73025641,NEWLINE 3.28486804, 4.17564479, 5.51180993, 6.40258668, 6.84797506,NEWLINE 4.62103317, 6.84797506, 6.84797506, 6.40258668, 6.84797506,NEWLINE 6.40258668, 6.84797506, 6.84797506, 5.9571983, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 5.06642155, 6.84797506,NEWLINE 6.84797506, 6.84797506, 5.9571983, 6.84797506, 3.73025641,NEWLINE 6.84797506, 6.84797506, 5.51180993, 6.40258668, 4.17564479,NEWLINE 5.06642155, 6.84797506, 6.84797506, 4.17564479, 6.84797506,NEWLINE 6.40258668, 6.84797506, 6.40258668, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 5.06642155, 6.84797506,NEWLINE 6.84797506, 6.40258668, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 5.9571983, 6.84797506, 4.62103317, 6.84797506,NEWLINE 6.84797506, 6.84797506, 5.06642155, 6.40258668, 6.40258668,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.40258668, 5.06642155, 6.40258668, 6.84797506, 6.84797506,NEWLINE 5.51180993, 6.84797506, 5.9571983, 6.84797506, 6.84797506,NEWLINE 6.84797506, 5.9571983, 6.84797506, 6.40258668, 6.40258668,NEWLINE 6.84797506, 6.84797506, 6.40258668, 6.84797506, 5.51180993,NEWLINE 6.84797506, 5.51180993, 5.51180993, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 5.06642155, 4.62103317, 6.84797506, 6.40258668, 6.84797506,NEWLINE 5.9571983, 6.84797506, 6.84797506, 6.84797506, 5.06642155,NEWLINE 6.84797506, 5.9571983, 6.84797506, 5.06642155, 6.84797506,NEWLINE 6.84797506, 5.06642155, 5.9571983, 6.40258668, 6.84797506,NEWLINE 4.62103317, 6.40258668, 6.84797506, 6.40258668, 5.9571983,NEWLINE 6.84797506, 4.62103317, 5.51180993, 5.06642155, 6.84797506,NEWLINE 6.84797506, 6.40258668, 5.51180993, 6.84797506, 5.9571983,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.40258668, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 4.62103317, 6.84797506,NEWLINE 6.40258668, 5.51180993, 5.9571983, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.40258668, 6.84797506, 6.84797506,NEWLINE 5.51180993, 6.84797506, 6.84797506, 6.40258668, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 4.62103317,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.40258668, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.40258668, 6.84797506, 5.06642155, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 5.51180993, 6.40258668, 6.84797506,NEWLINE 5.9571983, 5.9571983, 6.84797506, 6.84797506, 6.84797506,NEWLINE 4.62103317, 6.84797506, 5.9571983, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.40258668, 6.84797506,NEWLINE 6.84797506, 6.84797506, 4.17564479, 6.40258668, 6.40258668,NEWLINE 5.51180993, 6.84797506, 5.51180993, 6.84797506, 6.84797506,NEWLINE 6.84797506, 4.62103317, 6.84797506, 4.17564479, 6.84797506,NEWLINE 6.84797506, 5.51180993, 6.40258668, 5.06642155, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.40258668, 6.84797506, 5.9571983,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 5.51180993,NEWLINE 4.62103317, 6.84797506, 6.40258668, 6.84797506, 6.84797506,NEWLINE 5.9571983, 5.51180993, 5.9571983, 6.84797506, 4.62103317,NEWLINE 6.84797506, 6.84797506, 5.06642155, 6.40258668, 6.84797506,NEWLINE 5.06642155, 5.9571983, 6.84797506, 6.84797506, 6.40258668,NEWLINE 6.40258668, 5.9571983, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 5.06642155, 6.84797506, 6.40258668,NEWLINE 6.84797506, 5.06642155, 5.06642155, 5.9571983, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 5.06642155,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.40258668, 6.84797506,NEWLINE 5.9571983, 6.84797506, 5.06642155, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.40258668, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.40258668, 6.84797506,NEWLINE 3.73025641, 6.40258668, 5.51180993, 6.84797506, 5.51180993,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 5.06642155, 6.84797506, 6.40258668, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.40258668, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.40258668, 5.06642155, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.40258668, 6.84797506, 5.9571983, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 5.51180993, 5.06642155,NEWLINE 6.84797506, 6.84797506, 6.84797506, 4.62103317, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 4.17564479, 6.84797506,NEWLINE 5.51180993, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 3.73025641, 6.84797506, 6.40258668, 6.84797506, 6.84797506,NEWLINE 6.84797506, 5.06642155, 6.84797506, 6.84797506, 4.62103317,NEWLINE 6.40258668, 6.84797506, 5.51180993, 6.84797506, 6.84797506,NEWLINE 5.9571983, 6.84797506, 6.84797506, 6.84797506, 5.9571983,NEWLINE 5.06642155, 6.84797506, 5.06642155, 6.40258668, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.40258668, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 4.17564479, 5.51180993, 6.84797506, 6.84797506,NEWLINE 6.40258668, 4.62103317, 6.84797506, 5.9571983, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 4.17564479, 6.40258668, 6.84797506,NEWLINE 6.84797506, 5.9571983, 6.84797506, 5.51180993, 6.84797506,NEWLINE 5.9571983, 5.06642155, 6.84797506, 6.84797506, 6.40258668,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.40258668, 5.9571983,NEWLINE 5.51180993, 6.84797506, 5.9571983, 6.40258668, 4.62103317,NEWLINE 6.84797506, 5.06642155, 4.17564479, 5.51180993, 6.84797506,NEWLINE 6.40258668, 5.9571983, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.40258668, 5.9571983, 6.40258668, 6.84797506,NEWLINE 5.9571983, 6.84797506, 5.9571983, 5.51180993, 4.17564479,NEWLINE 5.9571983, 6.40258668, 6.84797506, 5.51180993, 6.40258668,NEWLINE 5.51180993, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.40258668, 6.84797506, 5.9571983, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 5.06642155, 5.9571983, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 5.06642155,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.40258668, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 5.51180993, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 3.73025641,NEWLINE 4.17564479, 6.84797506, 5.06642155, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 4.17564479,NEWLINE 5.51180993, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 5.9571983, 6.84797506, 6.84797506, 6.84797506,NEWLINE 4.62103317, 6.84797506, 5.06642155, 5.06642155, 6.84797506,NEWLINE 6.40258668, 5.9571983, 6.84797506, 4.62103317, 6.84797506,NEWLINE 6.84797506, 6.84797506, 5.9571983, 6.84797506, 6.84797506,NEWLINE 5.9571983, 5.51180993, 6.84797506, 5.06642155, 6.84797506,NEWLINE 4.62103317, 5.9571983, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 4.62103317, 6.84797506,NEWLINE 6.84797506, 6.84797506, 5.51180993, 5.51180993, 6.84797506,NEWLINE 6.84797506, 6.84797506, 5.9571983, 6.40258668, 6.84797506,NEWLINE 6.84797506, 5.51180993, 6.84797506, 6.84797506, 5.9571983,NEWLINE 5.51180993, 6.84797506, 6.84797506, 6.84797506, 4.17564479,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 5.9571983, 6.84797506, 6.40258668,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.40258668, 6.40258668,NEWLINE 6.84797506, 6.84797506, 6.84797506, 4.62103317, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 3.73025641,NEWLINE 6.84797506, 6.84797506, 6.84797506, 5.9571983, 4.62103317,NEWLINE 5.51180993, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.40258668, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 5.9571983, 6.40258668, 6.84797506,NEWLINE 5.51180993, 5.9571983, 5.9571983, 6.84797506, 6.84797506,NEWLINE 5.51180993, 6.84797506, 6.84797506, 5.51180993, 6.40258668,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 5.51180993,NEWLINE 6.40258668, 5.51180993, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 5.51180993, 6.84797506, 5.9571983, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 5.06642155, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.40258668, 5.06642155, 5.51180993,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.40258668, 6.84797506, 6.84797506, 5.9571983, 6.40258668,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.40258668, 6.84797506,NEWLINE 5.06642155, 4.17564479, 6.84797506, 6.84797506, 5.06642155,NEWLINE 6.84797506, 6.84797506, 6.40258668, 6.84797506, 5.51180993,NEWLINE 6.84797506, 6.84797506, 6.84797506, 4.17564479, 5.9571983,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 5.9571983,NEWLINE 5.51180993, 6.84797506, 6.40258668, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 5.9571983,NEWLINE 5.9571983, 6.84797506, 5.9571983, 4.17564479, 6.40258668,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.40258668, 5.9571983,NEWLINE 5.51180993, 6.84797506, 5.51180993, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 5.51180993, 5.06642155,NEWLINE 6.84797506, 6.40258668, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 6.84797506, 6.84797506, 5.51180993, 6.40258668,NEWLINE 6.84797506, 6.84797506, 3.28486804, 5.9571983, 6.84797506,NEWLINE 3.73025641, 6.84797506, 6.84797506, 6.84797506, 4.17564479,NEWLINE 6.84797506, 6.40258668, 6.40258668, 6.84797506, 5.51180993,NEWLINE 6.84797506, 6.84797506, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.84797506, 4.62103317, 6.40258668, 6.84797506, 6.40258668,NEWLINE 5.06642155, 6.84797506, 6.84797506, 5.51180993, 4.62103317,NEWLINE 6.84797506, 6.40258668, 6.84797506, 5.06642155, 5.9571983,NEWLINE 6.40258668, 5.51180993, 6.84797506, 6.84797506, 6.84797506,NEWLINE 6.40258668, 6.84797506, 6.84797506, 4.17564479, 6.84797506,NEWLINE 5.06642155, 6.84797506, 3.56230611, 4.89847125, 5.34385962,NEWLINE 4.45308287, 5.789248, 5.789248, 5.789248, 5.789248,NEWLINE 5.789248, 5.34385962, 5.34385962, 5.789248, 5.789248,NEWLINE 4.00769449, 5.34385962, 4.45308287, 5.789248, 5.34385962,NEWLINE 3.56230611, 2.67152936, 5.789248, 5.34385962, 5.789248,NEWLINE 2.67152936, 5.789248, 5.34385962, 3.56230611, 4.89847125,NEWLINE 5.789248, 3.11691773, 5.789248, 5.789248, 4.89847125,NEWLINE 5.789248, 3.56230611, 3.56230611, 5.789248, 5.789248,NEWLINE 5.789248, 4.89847125, 5.789248, 4.89847125, 4.00769449,NEWLINE 5.789248, 3.56230611, 5.789248, 2.22614098, 3.11691773,NEWLINE 5.789248, 5.789248, 4.00769449, 3.11691773, 5.789248,NEWLINE 5.789248, 5.789248, 5.789248, 5.789248, 5.789248,NEWLINE 2.67152936, 5.789248, 5.789248, 4.00769449, 3.56230611,NEWLINE 4.45308287, 5.789248, 5.789248, 4.89847125, 5.789248,NEWLINE 3.56230611, 5.789248, 4.89847125, 2.67152936, 5.34385962,NEWLINE 4.45308287, 5.789248, 4.45308287, 5.789248, 5.789248,NEWLINE 4.89847125, 4.45308287, 5.789248, 5.789248, 5.789248,NEWLINE 5.789248, 5.789248, 4.89847125, 5.789248, 5.34385962,NEWLINE 5.34385962, 5.789248, 5.789248, 3.56230611, 5.789248,NEWLINE 3.56230611, 5.789248, 4.45308287, 5.789248, 5.789248,NEWLINE 5.34385962, 5.789248, 3.11691773, 5.789248, 5.789248,NEWLINE 3.11691773, 4.00769449, 5.789248, 5.789248, 5.34385962,NEWLINE 3.56230611, 3.11691773, 5.789248, 4.45308287, 5.789248,NEWLINE 5.789248, 5.789248, 3.11691773, 5.789248, 5.789248,NEWLINE 5.789248, 5.789248, 4.45308287, 5.789248, 4.00769449,NEWLINE 5.789248, 4.45308287, 4.45308287, 5.789248, 4.89847125,NEWLINE 4.00769449, 4.00769449, 4.89847125, 4.00769449, 5.789248,NEWLINE 5.789248, 5.789248, 5.789248, 5.789248, 5.789248,NEWLINE 5.789248, 5.34385962, 3.56230611, 5.789248, 3.56230611,NEWLINE 5.789248, 5.789248, 5.789248, 2.67152936, 5.789248,NEWLINE 5.789248, 5.789248, 5.789248, 4.89847125, 4.89847125,NEWLINE 5.789248, 2.67152936, 5.789248, 4.89847125, 5.789248,NEWLINE 5.789248, 4.45308287, 3.11691773, 5.789248, 4.89847125,NEWLINE 5.789248, 2.67152936, 2.67152936, 5.34385962, 4.00769449,NEWLINE 5.789248, 5.789248, 5.34385962, 5.789248, 5.789248,NEWLINE 4.00769449, 5.789248, 5.34385962, 4.89847125, 5.789248,NEWLINE 2.67152936, 5.34385962, 5.789248, 5.789248, 4.45308287,NEWLINE 5.34385962, 5.789248, 5.789248, 5.789248, 5.789248,NEWLINE 2.67152936, 5.789248, 3.56230611, 4.00769449, 5.34385962,NEWLINE 5.789248, 3.11691773, 2.67152936, 5.789248, 4.45308287,NEWLINE 5.789248, 3.56230611, 5.34385962, 4.89847125, 5.789248,NEWLINE 3.56230611, 4.00769449, 5.789248, 3.11691773, 5.789248,NEWLINE 5.789248, 3.56230611, 5.34385962, 4.89847125, 4.89847125,NEWLINE 5.789248, 5.789248, 2.67152936, 3.11691773, 5.789248,NEWLINE 5.789248, 5.789248, 5.789248, 5.34385962, 5.34385962,NEWLINE 5.789248, 5.789248, 4.89847125, 5.789248, 4.45308287,NEWLINE 5.34385962, 5.789248, 4.45308287, 4.45308287, 5.789248,NEWLINE 5.789248, 3.56230611, 4.89847125, 3.56230611, 4.89847125,NEWLINE 4.45308287, 5.789248, 4.00769449, 5.789248, 4.89847125,NEWLINE 5.789248, 5.789248, 5.789248, 4.45308287, 4.00769449,NEWLINE 5.789248, 4.89847125, 4.89847125, 3.56230611, 5.789248,NEWLINE 5.789248, 5.34385962, 3.56230611, 3.11691773, 3.56230611,NEWLINE 4.00769449, 5.789248, 4.45308287, 4.89847125, 5.789248,NEWLINE 5.789248, 5.789248, 4.00769449, 4.89847125, 2.67152936,NEWLINE 5.789248, 5.789248, 5.789248, 4.89847125, 5.34385962,NEWLINE 5.789248, 5.789248, 5.789248, 5.789248, 5.789248,NEWLINE 5.789248, 5.789248, 4.00769449, 5.34385962, 4.89847125,NEWLINE 5.789248, 4.89847125, 4.00769449, 5.789248, 5.789248,NEWLINE 4.89847125, 5.789248, 5.34385962, 5.789248, 2.67152936,NEWLINE 5.789248, 5.34385962, 4.00769449, 4.00769449, 5.789248,NEWLINE 5.34385962, 3.56230611, 5.789248, 4.89847125, 5.34385962,NEWLINE 5.789248, 4.00769449, 4.45308287, 5.789248, 5.34385962,NEWLINE 4.00769449, 3.56230611, 5.34385962, 2.67152936, 5.789248,NEWLINE 3.56230611, 4.89847125, 4.45308287, 5.789248, 5.789248,NEWLINE 5.789248, 5.789248, 5.789248, 4.00769449, 5.789248,NEWLINE 4.45308287, 5.789248, 5.789248, 5.34385962, 5.789248,NEWLINE 5.789248, 5.789248, 5.789248, 5.34385962, 5.34385962,NEWLINE 5.789248, 5.34385962, 5.789248, 5.789248, 5.789248,NEWLINE 5.789248, 5.34385962, 4.45308287, 5.789248, 5.34385962,NEWLINE 5.789248, 5.34385962, 5.789248, 5.789248, 5.789248,NEWLINE 5.789248, 4.45308287, 5.34385962, 3.56230611, 2.67152936,NEWLINE 5.789248, 5.789248, 3.11691773, 5.789248, 4.45308287,NEWLINE 5.789248, 5.789248, 5.789248, 5.789248, 4.00769449,NEWLINE 4.00769449, 4.00769449, 5.789248, 5.789248, 5.789248,NEWLINE 5.789248, 4.89847125, 3.11691773, 4.45308287, 5.789248,NEWLINE 4.00769449, 5.789248, 5.789248, 5.789248, 5.789248,NEWLINE 5.789248, 4.00769449, 5.789248, 5.789248, 5.789248,NEWLINE 5.789248, 4.00769449, 5.789248, 4.00769449, 3.56230611,NEWLINE 5.789248, 4.89847125, 5.789248, 5.789248, 5.789248,NEWLINE 5.789248, 5.789248, 5.789248, 5.789248, 5.789248,NEWLINE 4.89847125, 5.34385962, 5.789248, 5.789248, 5.789248,NEWLINE 5.789248, 5.789248, 5.789248, 5.789248, 5.34385962,NEWLINE 3.56230611, 5.34385962, 5.789248, 3.56230611, 5.789248,NEWLINE 4.00769449, 5.789248, 5.789248, 5.789248, 4.00769449,NEWLINE 3.11691773, 5.789248, 5.789248, 4.00769449, 5.789248,NEWLINE 5.789248, 5.789248, 5.789248, 5.789248, 5.789248,NEWLINE 5.789248, 5.789248, 5.789248, 5.789248, 5.789248,NEWLINE 5.789248, 5.789248, 3.56230611, 5.789248, 5.789248,NEWLINE 5.789248, 5.789248, 3.56230611, 5.34385962, 4.00769449,NEWLINE 5.789248, 4.89847125, 4.89847125, 4.00769449, 5.789248,NEWLINE 5.789248, 4.45308287, 2.67152936, 5.789248, 5.789248,NEWLINE 4.00769449, 5.789248, 3.56230611, 4.00769449, 5.789248,NEWLINE 5.789248, 4.89847125, 5.789248, 4.45308287, 5.34385962,NEWLINE 5.34385962, 3.11691773, 3.56230611, 5.789248, 4.45308287,NEWLINE 5.789248, 4.89847125, 4.00769449, 4.89847125, 4.89847125,NEWLINE 5.789248, 5.789248, 5.34385962, 4.00769449, 5.789248,NEWLINE 5.789248, 5.789248, 5.789248, 5.789248, 5.789248,NEWLINE 5.789248, 3.56230611, 4.45308287, 4.00769449, 4.89847125,NEWLINE 4.45308287, 3.56230611, 4.00769449, 5.789248, 5.789248,NEWLINE 5.789248, 5.789248, 3.11691773, 5.789248, 5.789248,NEWLINE 5.789248, 5.789248, 5.789248, 4.00769449, 4.89847125,NEWLINE 5.34385962, 3.56230611, 3.11691773, 5.789248, 4.00769449,NEWLINE 5.789248, 3.56230611, 5.789248, 5.789248, 4.00769449,NEWLINE 5.789248, 4.00769449, 5.789248, 5.789248, 5.789248,NEWLINE 5.789248, 4.89847125, 4.00769449, 4.89847125, 5.34385962,NEWLINE 2.67152936, 5.789248, 4.45308287, 5.789248, 4.89847125,NEWLINE 5.789248, 5.34385962, 5.789248, 5.789248, 5.789248,NEWLINE 3.56230611, 2.67152936, 5.789248, 5.789248, 5.789248,NEWLINE 4.00769449, 4.89847125, 5.789248, 5.34385962, 4.89847125,NEWLINE 5.34385962, 5.789248, 5.789248, 5.34385962, 5.789248,NEWLINE 5.789248, 5.789248, 2.67152936, 5.34385962, 5.789248,NEWLINE 5.789248, 4.89847125, 4.89847125, 5.34385962, 5.789248,NEWLINE 5.789248, 4.45308287, 3.11691773, 3.56230611, 5.789248,NEWLINE 5.789248, 5.789248, 5.789248, 5.789248, 5.34385962,NEWLINE 5.789248, 5.789248, 4.00769449, 4.89847125, 5.789248,NEWLINE 3.56230611, 5.789248, 5.34385962, 2.67152936, 5.789248,NEWLINE 5.34385962, 5.789248, 5.789248, 5.789248, 5.34385962,NEWLINE 5.789248, 5.789248, 5.789248, 5.789248, 5.789248,NEWLINE 5.789248, 4.45308287, 5.789248, 3.11691773, 5.789248,NEWLINE 5.34385962, 4.89847125, 5.34385962, 5.789248, 4.89847125,NEWLINE 5.789248, 4.00769449, 4.45308287, 5.789248, 5.789248,NEWLINE 5.789248, 5.789248, 5.34385962, 5.789248, 4.00769449,NEWLINE 4.89847125, 4.00769449, 5.789248, 3.56230611, 5.789248,NEWLINE 5.789248, 5.789248, 5.789248, 3.56230611, 5.789248,NEWLINE 4.89847125, 5.789248, 5.789248, 5.789248, 5.789248,NEWLINE 5.789248, 5.789248, 5.789248, 5.789248, 4.00769449,NEWLINE 2.22614098, 5.789248, 5.789248, 5.789248, 5.789248,NEWLINE 4.89847125, 5.789248, 3.56230611, 5.789248, 5.789248,NEWLINE 4.00769449, 5.789248, 5.789248, 5.789248, 5.789248,NEWLINE 5.789248, 5.789248, 3.11691773, 3.11691773, 5.789248,NEWLINE 5.789248, 5.789248, 4.00769449, 5.789248, 5.34385962,NEWLINE 4.45308287, 5.34385962, 4.45308287, 4.45308287, 4.89847125,NEWLINE 5.789248, 4.89847125, 5.789248, 3.56230611, 5.789248,NEWLINE 5.789248, 5.789248, 5.789248, 5.789248, 3.11691773,NEWLINE 5.789248, 4.00769449, 5.789248, 4.89847125, 5.789248,NEWLINE 4.00769449, 5.789248, 5.789248, 5.789248, 5.789248,NEWLINE 5.789248, 5.34385962, 5.789248, 4.45308287, 5.34385962,NEWLINE 4.45308287, 5.789248, 4.00769449, 5.789248, 3.56230611,NEWLINE 5.34385962, 5.789248, 5.789248, 4.45308287, 4.00769449,NEWLINE 3.56230611, 5.789248, 5.789248, 5.789248, 4.45308287,NEWLINE 5.789248, 5.789248, 5.34385962, 4.89847125, 4.45308287,NEWLINE 3.11691773, 5.789248, 3.56230611, 3.11691773, 5.789248,NEWLINE 5.789248, 3.11691773, 3.11691773, 5.789248, 4.45308287,NEWLINE 4.45308287, 5.789248, 5.789248, 4.00769449, 4.00769449,NEWLINE 3.56230611, 5.789248, 4.00769449, 3.56230611, 5.789248,NEWLINE 4.00769449, 5.34385962, 5.789248, 3.56230611, 5.789248,NEWLINE 5.34385962, 5.789248, 4.45308287, 4.00769449, 5.789248,NEWLINE 5.789248, 4.45308287, 5.34385962, 5.789248, 5.789248,NEWLINE 5.789248, 5.789248, 5.789248, 5.789248, 5.34385962,NEWLINE 3.11691773, 5.34385962, 2.67152936, 4.00769449, 5.789248,NEWLINE 3.56230611, 5.789248, 5.34385962, 5.789248, 2.67152936,NEWLINE 5.789248, 5.789248, 5.789248, 5.789248, 3.11691773,NEWLINE 5.789248, 5.34385962, 3.56230611, 4.45308287, 4.89847125,NEWLINE 4.00769449, 5.789248, 5.789248, 5.34385962, 4.00769449,NEWLINE 4.89847125, 4.45308287, 5.789248, 5.789248, 5.789248,NEWLINE 5.789248, 5.789248, 4.00769449, 5.789248, 5.789248,NEWLINE 5.789248, 5.789248, 5.789248, 5.789248, 5.34385962,NEWLINE 3.56230611, 5.789248, 5.789248, 5.34385962, 5.789248,NEWLINE 3.11691773, 5.789248, 4.89847125, 5.789248, 4.89847125,NEWLINE 5.789248, 5.34385962, 5.789248, 5.789248, 5.789248,NEWLINE 5.789248, 5.34385962, 2.67152936, 5.789248, 5.789248,NEWLINE 2.67152936, 3.56230611, 5.789248, 5.789248, 2.67152936,NEWLINE 4.45308287, 3.56230611, 4.45308287, 5.789248, 5.789248,NEWLINE 5.789248, 5.789248, 5.789248, 5.789248, 4.45308287,NEWLINE 4.89847125, 5.34385962, 5.789248, 5.789248, 5.789248,NEWLINE 5.789248, 5.34385962, 4.00769449, 5.789248, 5.34385962,NEWLINE 5.789248, 2.67152936, 2.67152936, 5.789248, 3.56230611,NEWLINE 5.789248, 3.56230611, 5.789248, 4.45308287, 2.67152936,NEWLINE 5.789248, 5.789248, 2.67152936, 4.89847125, 5.789248,NEWLINE 5.789248, 3.11691773, 5.789248, 4.00769449, 5.789248,NEWLINE 5.789248, 3.11691773, 4.00769449, 4.89847125, 4.89847125,NEWLINE 5.789248, 4.00769449, 4.45308287, 5.789248, 4.45308287,NEWLINE 5.789248, 3.11691773, 4.45308287, 4.89847125, 3.56230611,NEWLINE 5.789248, 5.789248, 3.56230611, 3.56230611, 3.56230611,NEWLINE 5.789248, 5.789248, 4.00769449, 4.00769449, 3.11691773,NEWLINE 5.789248, 5.789248, 2.67152936, 4.00769449, 5.789248,NEWLINE 2.67152936, 3.56230611, 3.56230611, 4.45308287, 5.789248,NEWLINE 3.56230611, 5.789248, 5.789248, 5.789248, 5.789248,NEWLINE 5.789248, 5.789248, 5.34385962, 5.789248, 5.789248,NEWLINE 5.789248, 5.789248, 5.789248, 5.789248, 5.789248,NEWLINE 5.789248, 4.89847125, 5.789248, 5.789248, 4.89847125,NEWLINE 5.789248, 5.789248, 4.89847125, 4.89847125, 5.789248,NEWLINE 5.34385962, 4.45308287, 5.789248, 4.89847125, 4.00769449,NEWLINE 4.45308287, 5.789248, 2.67152936, 4.45308287, 5.34385962,NEWLINE 5.789248, 5.789248, 5.789248, 5.789248, 3.11691773,NEWLINE 5.34385962, 5.789248, 4.89847125, 5.789248, 4.45308287,NEWLINE 5.789248, 5.789248, 4.89847125, 4.45308287, 5.789248,NEWLINE 5.789248, 5.789248, 5.789248, 5.789248, 4.45308287,NEWLINE 4.45308287, 3.11691773, 4.89847125, 5.789248, 3.11691773,NEWLINE 3.11691773, 5.789248, 4.00769449, 5.34385962, 3.11691773,NEWLINE 4.89847125, 3.11691773, 3.56230611, 4.89847125, 5.789248,NEWLINE 5.789248, 4.45308287, 4.89847125, 5.789248, 4.45308287,NEWLINE 5.789248, 4.89847125, 4.45308287, 2.67152936, 5.789248,NEWLINE 5.789248, 5.789248, 4.89847125, 5.789248, 5.789248,NEWLINE 5.789248, 5.789248, 4.89847125, 5.34385962, 4.45308287,NEWLINE 5.789248, 4.00769449, 3.56230611, 4.89847125, 5.789248,NEWLINE 4.45308287, 5.789248, 5.789248, 3.11691773, 5.789248,NEWLINE 5.34385962, 5.789248, 5.789248, 5.789248, 3.56230611,NEWLINE 2.22614098, 5.789248, 5.789248, 3.56230611, 5.34385962,NEWLINE 4.00769449, 5.789248, 2.67152936, 5.789248, 4.00769449,NEWLINE 5.789248, 5.789248, 4.00769449, 2.67152936, 5.789248,NEWLINE 4.89847125, 4.45308287, 5.789248, 5.34385962, 5.789248,NEWLINE 5.789248, 4.45308287, 5.789248, 5.789248, 5.789248,NEWLINE 4.00769449, 4.89847125, 5.789248, 4.89847125, 5.789248,NEWLINE 4.89847125, 3.56230611, 4.00769449, 5.789248, 5.789248,NEWLINE 5.789248, 5.34385962, 5.789248, 5.789248, 5.34385962,NEWLINE 5.789248, 5.789248, 5.789248, 5.789248, 5.789248,NEWLINE 5.789248, 5.789248, 5.789248, 5.789248, 5.789248,NEWLINE 3.56230611, 3.56230611, 4.00769449, 5.789248, 4.45308287,NEWLINE 3.56230611, 5.789248, 4.89847125, 4.89847125, 3.11691773,NEWLINE 4.00769449, 5.789248, 5.34385962, 5.789248, 5.789248,NEWLINE 5.789248, 5.789248, 4.45308287, 5.34385962, 4.45308287,NEWLINE 5.789248, 3.11691773, 5.789248, 4.45308287, 4.45308287,NEWLINE 4.89847125, 5.789248, 4.89847125, 4.45308287, 5.789248,NEWLINE 5.34385962, 3.56230611, 3.56230611, 5.34385962, 5.789248,NEWLINE 4.00769449, 5.34385962, 4.45308287, 4.45308287, 3.56230611,NEWLINE 5.789248, 4.00769449, 5.789248, 5.789248, 4.89847125,NEWLINE 5.34385962, 3.11691773, 4.00769449, 5.789248, 5.34385962,NEWLINE 5.789248, 5.789248, 5.34385962, 5.789248, 4.45308287,NEWLINE 5.34385962, 4.89847125, 5.789248, 5.789248, 5.34385962,NEWLINE 3.56230611, 5.789248, 5.789248, 5.789248, 5.34385962,NEWLINE 5.34385962, 5.789248, 3.11691773, 5.789248, 5.789248,NEWLINE 3.56230611, 5.789248, 5.789248, 5.789248, 4.45308287,NEWLINE 5.789248, 4.89847125, 5.789248, 5.789248, 5.789248,NEWLINE 4.00769449, 4.45308287, 5.34385962, 5.789248, 3.56230611,NEWLINE 4.00769449, 5.34385962, 4.45308287, 5.789248, 5.34385962,NEWLINE 5.34385962, 2.67152936, 5.789248, 5.789248, 5.789248,NEWLINE 5.789248, 5.789248, 5.34385962, 5.789248, 4.89847125,NEWLINE 5.789248, 5.789248, 5.789248, 4.45308287, 5.789248,NEWLINE 3.11691773, 4.00769449, 5.789248, 5.789248, 5.34385962,NEWLINE 5.789248, 5.789248, 5.789248, 5.789248, 5.789248,NEWLINE 5.789248, 5.789248, 2.22614098, 5.789248, 4.00769449,NEWLINE 5.34385962, 4.89847125, 5.789248, 5.789248, 4.00769449,NEWLINE 5.789248, 3.56230611, 2.67152936, 5.789248, 3.56230611,NEWLINE 2.67152936, 4.89847125, 5.789248, 5.789248, 5.789248,NEWLINE 4.45308287, 5.789248, 4.89847125, 4.00769449, 2.67152936,NEWLINE 4.89847125, 5.789248, 2.22614098, 3.56230611, 4.45308287,NEWLINE 5.34385962, 5.34385962, 3.11691773, 4.45308287, 4.45308287,NEWLINE 3.11691773, 4.45308287, 5.34385962, 4.45308287, 5.34385962,NEWLINE 4.00769449, 4.45308287, 5.789248, 5.789248, 5.789248,NEWLINE 5.789248, 4.00769449, 5.789248, 5.789248, 5.789248,NEWLINE 4.45308287, 5.789248, 5.789248, 5.789248, 4.00769449,NEWLINE 5.34385962, 4.00769449, 4.45308287, 4.89847125, 4.00769449,NEWLINE 5.789248, 5.789248, 5.789248, 2.67152936, 5.789248,NEWLINE 5.789248, 5.789248, 5.789248, 5.789248, 5.789248,NEWLINE 5.789248, 4.00769449, 3.11691773, 5.34385962, 4.89847125,NEWLINE 5.34385962])NEWLINENEWLINENEWLINEclass Committee(object):NEWLINE def __init__(self):NEWLINE self.resids = np.array([NEWLINE [-5.04950800e-01, -6.29721800e-01, -8.35499100e+01,NEWLINE -1.30628500e+00, -6.62028600e+00],NEWLINE [-2.34152200e-01, -2.55423500e-01, -2.16830700e+02,NEWLINE -7.58866000e-01, -7.18370200e+00],NEWLINE [1.02423700e+00, 7.98775800e-01, 4.83736300e+02,NEWLINE 2.50351500e+00, 2.25135300e+01],NEWLINE [-2.85061700e-01, -3.17796600e-01, -7.04115100e+04,NEWLINE -2.37991800e+00, -1.41745600e+02],NEWLINE [2.09902500e-01, 1.96787700e-01, 2.24751400e+03,NEWLINE 9.51945500e-01, 2.17724200e+01],NEWLINE [-4.03483500e-01, -4.75741500e-01, -1.95633600e+04,NEWLINE -2.63502600e+00, -8.89461400e+01],NEWLINE [-1.64413400e-01, -1.74401100e-01, -1.73310300e+04,NEWLINE -1.16235500e+00, -5.34213500e+01],NEWLINE [-4.29607700e-01, -5.13466700e-01, -5.30037000e+03,NEWLINE -2.24496200e+00, -4.78260300e+01],NEWLINE [3.23713000e-01, 2.94184600e-01, 4.11079400e+03,NEWLINE 1.48684400e+00, 3.65598400e+01],NEWLINE [1.50367200e-01, 1.43429400e-01, 7.28532100e+03,NEWLINE 8.85542900e-01, 3.31355000e+01],NEWLINE [4.21288600e-01, 3.73428000e-01, 1.37315700e+03,NEWLINE 1.52133200e+00, 2.41570200e+01],NEWLINE [4.50658700e-01, 3.96586700e-01, 1.70146900e+03,NEWLINE 1.66177900e+00, 2.78032600e+01],NEWLINE [2.43537500e-01, 2.26174000e-01, 3.18402300e+03,NEWLINE 1.13656200e+00, 2.79073400e+01],NEWLINE [1.05182900e+00, 8.16205400e-01, 6.00135200e+03,NEWLINE 3.89079700e+00, 7.97131300e+01],NEWLINE [-5.54450300e-01, -7.12749000e-01, -2.09485200e+03,NEWLINE -2.45496500e+00, -3.42189900e+01],NEWLINE [-6.05750600e-01, -8.06411100e-01, -2.74738200e+02,NEWLINE -1.90774400e+00, -1.30510500e+01],NEWLINE [-3.41215700e-01, -3.90244600e-01, -6.31138000e+02,NEWLINE -1.27022900e+00, -1.47600100e+01],NEWLINE [2.21898500e-01, 2.07328700e-01, 6.91135800e+02,NEWLINE 8.16876400e-01, 1.24392900e+01],NEWLINE [2.45592500e-01, 2.26639200e-01, 1.99250600e-01,NEWLINE 2.57948300e-01, 2.74723700e-01],NEWLINE [-7.58952600e-01, -1.15300800e+00, -2.56739000e+02,NEWLINE -2.40716600e+00, -1.41474200e+01]])NEWLINE self.null_deviance = 27.81104693643434 # from R, Rpy bugNEWLINE self.params = np.array([NEWLINE -0.0268147, 1.25103364, 2.91070663,NEWLINE -0.34799563, 0.00659808, -0.31303026, -6.44847076])NEWLINE self.bse = np.array([NEWLINE 1.99956263e-02, 4.76820254e-01,NEWLINE 6.48362654e-01, 4.17956107e-01, 1.41512690e-03, 1.07770186e-01,NEWLINE 1.99557656e+00])NEWLINE self.aic_R = 216.66573352377935NEWLINE self.aic_Stata = 10.83328660860436NEWLINE self.deviance = 5.615520158267981NEWLINE self.scale = 0.38528595746569905NEWLINE self.llf = -101.33286676188968 # from RNEWLINE self.llf_Stata = -101.3328660860436 # same as RNEWLINE self.bic_Stata = -33.32900074962649NEWLINE self.chi2 = 5.008550263545408NEWLINE self.df_model = 6NEWLINE self.df_resid = 13NEWLINE self.fittedvalues = np.array([NEWLINE 12.62019383, 30.18289514, 21.48377849, 496.74068604,NEWLINE 103.23024673, 219.94693494, 324.4301163, 110.82526477,NEWLINE 112.44244488, 219.86056381, 56.84399998, 61.19840382,NEWLINE 114.09290269, 75.29071944, 61.21994387, 21.05130889,NEWLINE 42.75939828, 55.56133536, 0.72532053, 18.14664665])NEWLINENEWLINENEWLINEclass Wfs(object):NEWLINE """NEWLINE Wfs used for TestGlmPoissonOffsetNEWLINENEWLINE Results are from Stata and R.NEWLINE """NEWLINE def __init__(self):NEWLINENEWLINE self.resids = glm_test_resids.wfs_residsNEWLINE self.null_deviance = 3731.85161919 # from RNEWLINE self.params = [NEWLINE .9969348, 1.3693953, 1.6137574, 1.7849111, 1.9764051,NEWLINE .11241858, .15166023, .02297282, -.10127377, -.31014953,NEWLINE -.11709716]NEWLINE self.bse = [NEWLINE .0527437, .0510688, .0511949, .0512138, .0500341,NEWLINE .0324963, .0283292, .0226563, .0309871, .0552107, .0549118]NEWLINE self.aic_R = 522.14215776 # R adds 2 for dof to AICNEWLINE self.aic_Stata = 7.459173652869477 # stata divides by nobsNEWLINE # self.deviance = 70.6652992116034 # from StataNEWLINE self.deviance = 70.665301270867 # from RNEWLINE self.scale = 1.0NEWLINE self.llf = -250.0710778504317 # from Stata, ours with scale=1NEWLINE self.bic_Stata = -179.9959200693088 # no bic in R?NEWLINE self.df_model = 10NEWLINE self.df_resid = 59NEWLINENEWLINE # TODO: taken from Stata; not available in sm yetNEWLINE self.chi2 = 2699.138063147485NEWLINENEWLINE self.fittedvalues = [NEWLINE 7.11599, 19.11356, 33.76075, 33.26743, 11.94399,NEWLINE 27.49849, 35.07923, 37.22563, 64.18037, 108.0408,NEWLINE 100.0948, 35.67896, 24.10508, 73.99577, 52.2802,NEWLINE 38.88975, 35.06507, 102.1198, 107.251, 41.53885,NEWLINE 196.3685, 335.8434, 205.3413, 43.20131, 41.98048,NEWLINE 96.65113, 63.2286, 30.78585, 70.46306, 172.2402,NEWLINE 102.5898, 43.06099, 358.273, 549.8983, 183.958,NEWLINE 26.87062, 62.53445, 141.687, 52.47494, 13.10253,NEWLINE 114.9587, 214.803, 90.33611, 18.32685, 592.5995,NEWLINE 457.4376, 140.9273, 3.812064, 111.3119, 97.62744,NEWLINE 57.48056, 19.43552, 130.4872, 151.7268, 69.67963,NEWLINE 13.04879, 721.728, 429.2136, 128.2132, 9.04735,NEWLINE 301.7067, 177.3487, 46.40818, 4.707507, 330.4211,NEWLINE 330.7497, 84.38604, 1456.757, 451.005, 67.51025]NEWLINENEWLINENEWLINEclass CpunishTweediePower15(object):NEWLINE """NEWLINE # From RNEWLINE setwd('c:/workspace')NEWLINE data <- read.csv('cpunish.csv', sep=",")NEWLINENEWLINE library(statmod)NEWLINE library(tweedie)NEWLINENEWLINE summary(glm(EXECUTIONS ~ INCOME + SOUTH - 1,NEWLINE family=tweedie(var.power=1.5, link.power=1),NEWLINE data=data))NEWLINE """NEWLINE def __init__(self):NEWLINENEWLINE resid_resp = [NEWLINE 28.90498242, 0.5714367394, 4.3135711827, -3.7417822942,NEWLINE -4.9544111888, 0.4666602184, 0.0747051827, -6.114236142,NEWLINE -1.0048540116, -6.9747602544, -0.7626907093,NEWLINE -0.5688093336, -6.9845579527, -1.1594503855,NEWLINE -0.6365453438, -0.3994222036, -0.732355528]NEWLINE resid_dev = [NEWLINE 3.83881147757395, 0.113622743768915, 2.01981988071128,NEWLINE -0.938107751845672, -1.29607304923555, 0.316205676540778,NEWLINE 0.045273675744568, -1.69968893354602, -0.699080227540624,NEWLINE -2.1707839733642, -0.568738719015137, -0.451266938413727,NEWLINE -2.17218106358745, -0.774613533242944, -0.493831656345955,NEWLINE -0.336453094366771, -0.551210030548659]NEWLINE resid_pear = [NEWLINE 6.02294407053171, 0.115516970886608, 2.9148208139849,NEWLINE -0.806210703943481, -1.04601155367613, 0.338668788938945,NEWLINE 0.045708693925888, -1.27176471794657, -0.5964031365026,NEWLINE -1.46974255264233, -0.498557360800493,NEWLINE -0.405777068096011, -1.47045242302365, -0.65086941662954,NEWLINE -0.439928270112046, -0.310433407220704,NEWLINE -0.485001313250992]NEWLINE resid_work = [NEWLINE 28.9049727916181, 0.571427719513967, 4.31357425907762,NEWLINE -3.74179256698823, -4.9544210736226, 0.466663015515745,NEWLINE 0.0747086948013966, -6.114245735344, -1.00485035431368,NEWLINE -6.97477010217068, -0.76268749374494, -0.568806471745149,NEWLINE -6.98456778258272, -1.15944644619981, -0.636542358439925,NEWLINE -0.399419650775458, -0.732352367853816]NEWLINE self.resid_response = resid_respNEWLINE self.resid_deviance = resid_devNEWLINE self.resid_pearson = resid_pearNEWLINE self.resid_working = resid_workNEWLINE # self.null_deviance = 3731.85161919 # N/ANEWLINE self.params = [0.0000471043, 6.4721324886]NEWLINE self.bse = [0.0000246888, 3.5288126173]NEWLINE # self.aic_R = 522.14215776 # R adds 2 for dof to AICNEWLINE # self.aic_Stata = 7.459173652869477 # stata divides by nobsNEWLINE # self.deviance = 70.6652992116034 # from StataNEWLINE self.deviance = 36.087307138233 # from RNEWLINE # self.scale = 1.0NEWLINE # self.llf = -250.0710778504317 # from Stata, ours with scale=1NEWLINE # self.bic_Stata = -179.9959200693088 # no bic in R?NEWLINE self.df_model = 1NEWLINE self.df_resid = 15NEWLINENEWLINE # TODO: taken from Stata; not available in sm yetNEWLINE # self.chi2 = 2699.138063147485NEWLINENEWLINE self.fittedvalues = [NEWLINE 8.09501758000751, 8.42856326056927,NEWLINE 1.68642881732415, 7.74178229423817,NEWLINE 7.95441118875248, 1.53333978161934,NEWLINE 1.92529481734232, 8.11423614202829,NEWLINE 2.00485401159015, 7.97476025442155,NEWLINE 1.76269070926448, 1.56880933358418,NEWLINE 7.98455795270665, 2.15945038549266,NEWLINE 1.63654534384372, 1.39942220361664,NEWLINE 1.73235552803559]NEWLINENEWLINENEWLINEclass CpunishTweediePower2(object):NEWLINE """NEWLINE # From RNEWLINE setwd('c:/workspace')NEWLINE data <- read.csv('cpunish.csv', sep=",")NEWLINENEWLINE library(statmod)NEWLINE library(tweedie)NEWLINENEWLINE summary(glm(EXECUTIONS ~ INCOME + SOUTH - 1,NEWLINE family=tweedie(var.power=2, link.power=1),NEWLINE data=data))NEWLINE """NEWLINE def __init__(self):NEWLINE resid_resp = [NEWLINE 28.9397568116168, 0.605199215492085, 4.30845487128123,NEWLINE -3.7059362524505, -4.91921022348665, 0.46200835064931,NEWLINE 0.068864196242604, -6.07952005594693, -1.01093636580438,NEWLINE -6.9396210244365, -0.768038385056284, -0.573568809339664,NEWLINE -6.94944844711606, -1.16600175635393, -0.641510318056987,NEWLINE -0.403667790321936, -0.737611172529194]NEWLINE resid_dev = [NEWLINE 2.03295746713119, 0.0704291140028282, 1.60058476017728,NEWLINE -0.591230836989137, -0.836067997150736, 0.274690511542166,NEWLINE 0.0352446721149477, -1.13465831620614, -0.625909330466303,NEWLINE -1.5477830210949, -0.520517540529698, -0.421531194473357,NEWLINE -1.54848147513823, -0.684927882583903, -0.45784673829438,NEWLINE -0.320960880764019, -0.505992145923248]NEWLINE resid_pear = [NEWLINE 3.59043221590711, 0.0720921473930558, 2.54705286789752,NEWLINE -0.480919661289957, -0.621174344999372,NEWLINE 0.300397177607798, 0.0356599448410699,NEWLINE -0.752460543924524, -0.502719222246499,NEWLINE -0.874049404005278, -0.434401419984914,NEWLINE -0.364501892726482, -0.874205109115113,NEWLINE -0.538319857282425, -0.390804925805356,NEWLINE -0.287580717535275, -0.424497254731367]NEWLINE resid_work = [NEWLINE 28.9397568116168, 0.605199215492085, 4.30845487128123,NEWLINE -3.7059362524505, -4.91921022348665, 0.46200835064931,NEWLINE 0.068864196242604, -6.07952005594693, -1.01093636580438,NEWLINE -6.9396210244365, -0.768038385056284, -0.573568809339664,NEWLINE -6.94944844711606, -1.16600175635393, -0.641510318056987,NEWLINE -0.403667790321936, -0.737611172529194]NEWLINE self.resid_response = resid_respNEWLINE self.resid_deviance = resid_devNEWLINE self.resid_pearson = resid_pearNEWLINE self.resid_working = resid_workNEWLINE # self.null_deviance = 3731.85161919 # N/ANEWLINE self.params = [4.72472244209477e-05, 6.43243456540827]NEWLINE self.bse = [1.86839521185429e-05, 3.83231672422612]NEWLINE # self.aic_R = 522.14215776 # R adds 2 for dof to AICNEWLINE # self.aic_Stata = 7.459173652869477 # stata divides by nobsNEWLINE # self.deviance = 70.6652992116034 # from StataNEWLINE self.deviance = 15.7840685407599 # from RNEWLINE # self.scale = 1.0NEWLINE # self.llf = -250.0710778504317 # from Stata, ours with scale=1NEWLINE # self.bic_Stata = -179.9959200693088 # no bic in R?NEWLINE self.df_model = 1NEWLINE self.df_resid = 15NEWLINENEWLINE # TODO: taken from Stata; not available in sm yetNEWLINE # self.chi2 = 2699.138063147485NEWLINENEWLINE self.fittedvalues = [NEWLINE 8.06024318838318, 8.39480078450791,NEWLINE 1.69154512871877, 7.7059362524505,NEWLINE 7.91921022348665, 1.53799164935069,NEWLINE 1.9311358037574, 8.07952005594693,NEWLINE 2.01093636580438, 7.9396210244365,NEWLINE 1.76803838505628, 1.57356880933966,NEWLINE 7.94944844711606, 2.16600175635393,NEWLINE 1.64151031805699, 1.40366779032194,NEWLINE 1.73761117252919]NEWLINENEWLINENEWLINEclass CpunishTweedieLog1(object):NEWLINE """NEWLINE # From RNEWLINE setwd('c:/workspace')NEWLINE data <- read.csv('cpunish.csv', sep=",")NEWLINENEWLINE library(statmod)NEWLINE library(tweedie)NEWLINENEWLINE summary(glm(EXECUTIONS ~ INCOME + SOUTH - 1,NEWLINE family=tweedie(var.power=1, link.power=0),NEWLINE data=data))NEWLINE """NEWLINE def __init__(self):NEWLINE resid_resp = [NEWLINE 28.7231009386298, -0.307318358456484, 4.19015460156576,NEWLINE -3.30975297068573, -4.87746969906705, 0.285041779927669,NEWLINE 0.0315071085472043, -6.33304532673002, -1.02436294926752,NEWLINE -6.9340610414309, -0.859055122126197, -0.736490247380883,NEWLINE -6.96145354225969, -1.13750232106315, -0.778363801217565,NEWLINE -0.636042191521576, -0.839322392162821]NEWLINE resid_dev = [NEWLINE 7.30513948467594, -0.101296157943519, 2.44987904003561,NEWLINE -1.34021826264378, -1.99062116973315, 0.212014827300475,NEWLINE 0.0223969676885324, -2.63775728156667, -0.798884085657077,NEWLINE -3.11862021596631, -0.691356293575324, -0.607658243497501,NEWLINE -3.12628915913493, -0.869326536299756, -0.636663290048755,NEWLINE -0.536212950673418, -0.67812263418512]NEWLINE resid_pear = [NEWLINE 9.98383729954486, -0.100734032611758, 3.11465040934513,NEWLINE -1.22417704160631, -1.73780566805242, 0.217661565866984,NEWLINE 0.0224564769560215, -2.19386916576256,NEWLINE -0.719962160947025, -2.46172701579962,NEWLINE -0.630049829146329, -0.558895774299477,NEWLINE -2.4671965358931, -0.778034748813176,NEWLINE -0.583676657782738, -0.497265896656757,NEWLINE -0.61887064145702]NEWLINE resid_work = [NEWLINE 3.47027319357873, -0.0330190014589175, 2.31520029566659,NEWLINE -0.452785885372436, -0.619167053050639,NEWLINE 0.166209168591668, 0.0160057009522403,NEWLINE -0.759991705123147, -0.506017436072008,NEWLINE -0.873961141113221, -0.46209233491888,NEWLINE -0.424125760851072, -0.874394795536774,NEWLINE -0.532164250702372, -0.437685360377137,NEWLINE -0.388768819543728, -0.456321521305397]NEWLINE self.resid_response = resid_respNEWLINE self.resid_deviance = resid_devNEWLINE self.resid_working = resid_workNEWLINE self.resid_pearson = resid_pearNEWLINE # self.null_deviance = 3731.85161919 # N/ANEWLINE self.params = [1.65700638623525e-05, 1.54257997850499]NEWLINE self.bse = [1.81044999017907e-05, 0.725739640176733]NEWLINE # self.aic_R = 522.14215776 # R adds 2 for dof to AICNEWLINE # self.aic_Stata = 7.459173652869477 # stata divides by nobsNEWLINE # self.deviance = 70.6652992116034 # from StataNEWLINE self.deviance = 95.0325613464258 # from RNEWLINE # self.scale = 1.0NEWLINE # self.llf = -250.0710778504317 # from Stata, ours with scale=1NEWLINE # self.bic_Stata = -179.9959200693088 # no bic in R?NEWLINE self.df_model = 1NEWLINE self.df_resid = 15NEWLINENEWLINE # TODO: taken from Stata; not available in sm yetNEWLINE # self.chi2 = 2699.138063147485NEWLINENEWLINE self.fittedvalues = [NEWLINE 8.27689906137016, 9.30731835845648,NEWLINE 1.80984539843424, 7.30975297068573,NEWLINE 7.87746969906705, 1.71495822007233,NEWLINE 1.9684928914528, 8.33304532673002,NEWLINE 2.02436294926752, 7.9340610414309,NEWLINE 1.8590551221262, 1.73649024738088,NEWLINE 7.96145354225969, 2.13750232106315,NEWLINE 1.77836380121756, 1.63604219152158,NEWLINE 1.83932239216282]NEWLINENEWLINENEWLINEclass FairTweedieLog15(object):NEWLINE """NEWLINE # From RNEWLINE setwd('c:/workspace')NEWLINE data <- read.csv('fair.csv', sep=",")NEWLINENEWLINE library(statmod)NEWLINE library(tweedie)NEWLINENEWLINE model <- glm(affairs ~ rate_marriage + age + yrs_married -1, data=data,NEWLINE family=tweedie(var.power=1.5, link.power = 0))NEWLINE r <- resid(model, type='response')NEWLINE paste(as.character(r[1:17]), collapse=",")NEWLINE r <- resid(model, type='deviance')NEWLINE paste(as.character(r[1:17]), collapse=",")NEWLINE r <- resid(model, type='pearson')NEWLINE paste(as.character(r[1:17]), collapse=",")NEWLINE r <- resid(model, type='working')NEWLINE paste(as.character(r[1:17]), collapse=",")NEWLINE paste(as.character(model$coefficients[1:17]), collapse=",")NEWLINE s <- summary(model)NEWLINE paste(as.character(sqrt(diag(s$cov.scaled))), collapse=",")NEWLINE s$devianceNEWLINE paste(as.character(model$fitted.values[1:17]), collapse=",")NEWLINE """NEWLINE def __init__(self):NEWLINE resid_resp = [NEWLINE -0.997868449815039, 2.69283106662728, 0.677397439981157,NEWLINE 0.220024942629269, 4.30244966465517, 4.12917275616972,NEWLINE 0.669303122309246, 1.64321562230925, 3.73361710426128,NEWLINE 0.271937359562684, 1.70030700747884, 1.55430573164611,NEWLINE -0.263723852468304, 1.51263973164611, 2.75223392654071,NEWLINE 0.310487741565721, 1.28077676333896, -0.722602160018842]NEWLINE resid_dev = [NEWLINE -1.40274708439925, 2.48476334070913, 0.722690630291423,NEWLINE 0.333179337353702, 4.00781035212304, 3.33344591331998,NEWLINE 1.51543361886727, 2.82502498800952, 2.2795411865605,NEWLINE 0.245239170945663, 0.993721205729013, 1.74920359743562,NEWLINE -0.363141475997386, 1.71412357710318, 2.57445879456298,NEWLINE 0.279858474280908, 1.22953362433333, -1.84397406923697]NEWLINE resid_pear = [NEWLINE -0.923380371255914, 4.28706294677515, 0.864309147553743,NEWLINE 0.366063826152319, 9.17690493704408, 6.57783985712941,NEWLINE 2.39340023647571, 5.87607098775551, 3.55791152198837,NEWLINE 0.260052421285998, 1.21439278430259, 2.66470328868695,NEWLINE -0.327698246542009, 2.59327105694137, 4.53096038849505,NEWLINE 0.299198418236691, 1.6399313081981, -0.921987034618483]NEWLINE resid_work = [NEWLINE -0.899807800767353, 5.00583784559752, 0.937441759049674,NEWLINE 0.433762277766879, 11.8128959278604, 7.6822784352496,NEWLINE 3.65998654763585, 8.98568506862295, 3.50120010377224,NEWLINE 0.256207345500911, 1.08551656668241, 3.18923357641756,NEWLINE -0.352302468597673, 3.10374035363038, 5.35005901385941,NEWLINE 0.29552727652976, 1.78077778644209, -1]NEWLINE self.resid_response = resid_respNEWLINE self.resid_deviance = resid_devNEWLINE self.resid_working = resid_workNEWLINE self.resid_pearson = resid_pearNEWLINE # self.null_deviance = 3731.85161919 # N/ANEWLINE self.params = [NEWLINE -0.389168171340452, 0.0670222370664611, -0.0970852004566712]NEWLINE self.bse = [NEWLINE 0.0323435784513691, 0.0063805300018014, 0.00893580175352525]NEWLINE # self.aic_R = 522.14215776 # R adds 2 for dof to AICNEWLINE # self.aic_Stata = 7.459173652869477 # stata divides by nobsNEWLINE # self.deviance = 70.6652992116034 # from StataNEWLINE self.deviance = 20741.82 # from RNEWLINE # self.scale = 1.0NEWLINE # self.llf = -250.0710778504317 # from Stata, ours with scale=1NEWLINE # self.bic_Stata = -179.9959200693088 # no bic in R?NEWLINE self.df_model = 2NEWLINE self.df_resid = 6363NEWLINENEWLINE # TODO: taken from Stata; not available in sm yetNEWLINE # self.chi2 = 2699.138063147485NEWLINENEWLINE self.fittedvalues = [NEWLINE 1.10897954981504, 0.537938133372725,NEWLINE 0.722602160018842, 0.507247757370731,NEWLINE 0.364216335344828, 0.537493243830281,NEWLINE 0.182870377690754, 0.182870377690754,NEWLINE 1.06638209573872, 1.06139564043732,NEWLINE 1.56635749252116, 0.487360268353893,NEWLINE 0.748572252468304, 0.487360268353893,NEWLINE 0.514430573459285, 1.05062295843428,NEWLINE 0.71922323666104, 0.722602160018842]NEWLINE
'''NEWLINE Run the use case described onNEWLINE https://docs.google.com/document/d/16m74ZhD1_TpgmGH_RPTUGthIMCGNsxRhJOpucbDX_4E/edit?hl=en_USNEWLINE'''NEWLINEimport timeNEWLINEfrom nose.tools import eq_ as eqNEWLINEfrom nose.tools import with_setupNEWLINEfrom openmdao.gui.test.functional.pageobjects.openmdao_login import LoginPageObjectNEWLINENEWLINEimport setup_server_and_browserNEWLINENEWLINE@with_setup(setup_server_and_browser.setup_server, setup_server_and_browser.teardown_server)NEWLINEdef test_generator():NEWLINE for browser in setup_server_and_browser.browsers :NEWLINE for _test in [ _test_gui_demo_jan_2012, ]:NEWLINE yield _test, browserNEWLINENEWLINEdef _test_gui_demo_jan_2012(browser):NEWLINE gui_demo_jan_2012(browser)NEWLINENEWLINEdef gui_demo_jan_2012(browser):NEWLINENEWLINE ########## Login ##########NEWLINE login_page = LoginPageObject(browser, setup_server_and_browser.port)NEWLINE login_page.go_to()NEWLINE eq( "Login", login_page.page_title )NEWLINENEWLINE projects_page = login_page.login_successfully("herb", "herb" )NEWLINE eq( "Projects", projects_page.page_title )NEWLINE NEWLINE ########## New Project ##########NEWLINE new_project_page = projects_page.new_project()NEWLINE assert new_project_page.page_title.startswith( "New Project" )NEWLINE NEWLINE new_project_name = new_project_page.get_random_project_name()NEWLINE new_project_description = "A project generated by a test " \NEWLINE "script which automates the GUI demo posted in Jan 2012"NEWLINE new_project_version = "initial version"NEWLINE new_project_shared = TrueNEWLINE project_info_page = new_project_page.create_project(NEWLINE new_project_name,NEWLINE new_project_description, NEWLINE new_project_version, NEWLINE new_project_sharedNEWLINE )NEWLINENEWLINE project_info_page.assert_on_correct_page()NEWLINE eq( new_project_name, project_info_page.page_title )NEWLINENEWLINE ########## Go into Workspace ##########NEWLINE workspace_page = project_info_page.load_project_into_workspace()NEWLINE workspace_page.assert_on_correct_page()NEWLINENEWLINE ########## Assert initial state ##########NEWLINE # Check to see if Objects has "top" and "driver" elements.NEWLINE # There are two li tags with path values of "top" and "top.driver"NEWLINE # with the latter inside the former.NEWLINE # They are inside a div with an id of otreeNEWLINE object_names = workspace_page.get_objects_attribute("path")NEWLINE eq( sorted( object_names ), sorted( [ "top", "top.driver" ] ) )NEWLINENEWLINE # Structure tab should have Driver iconNEWLINE component_names = workspace_page.get_dataflow_component_names()NEWLINE eq( sorted( component_names ), sorted( [ "top" ] ) )NEWLINENEWLINE ########## New File ##########NEWLINE workspace_page.new_file( "plane.py", '''NEWLINEfrom openmdao.main.api import ComponentNEWLINEfrom openmdao.lib.datatypes.api import FloatNEWLINENEWLINEclass Plane(Component):NEWLINENEWLINE x1 = Float(0.0,iotype="in")NEWLINE x2 = Float(0.0,iotype="in")NEWLINE x3 = Float(0.0,iotype="in")NEWLINENEWLINE f_x = Float(0.0,iotype="out")NEWLINE'''NEWLINE )NEWLINE # Add paraboloid fileNEWLINE import openmdao.examples.simple.paraboloidNEWLINE file_path = openmdao.examples.simple.paraboloid.__file__NEWLINE if file_path.endswith( ".pyc" ):NEWLINE file_path = file_path[ :-1 ]NEWLINE workspace_page.add_file( file_path )NEWLINENEWLINE # import both filesNEWLINE workspace_page.import_from_file( "plane.py" )NEWLINE time.sleep(2)NEWLINE workspace_page.import_from_file( "paraboloid.py" )NEWLINENEWLINE workspace_page.objects_tab()NEWLINENEWLINE import pdb; pdb.set_trace()NEWLINENEWLINE # !!!!!! This next call is not working because the context menuNEWLINE # is not coming up. I have no idea why. Maybe because ofNEWLINE # the upgrade to Firefox 10 again?NEWLINE workspace_page.show_structure( "top" )NEWLINENEWLINE # drag over Plane and ParaboloidNEWLINE workspace_page.add_library_item_to_structure( "Plane", "plane" )NEWLINE workspace_page.add_library_item_to_structure( "Paraboloid", "paraboloid" )NEWLINENEWLINE # Check to see if in the object tree, under the top, there should beNEWLINE # driverNEWLINE # paraboloidNEWLINE # planeNEWLINENEWLINE # Click on paraboloid in the object treeNEWLINENEWLINE # under the Properties tab on the right there should be fieldsNEWLINE # for editing the inputs and outputs for the paraboloidNEWLINENEWLINE # link the y input of paraboloid with the f_xy output of planeNEWLINENEWLINE # in the Strucure pane, the inputs come in the top of the iconsNEWLINE # and outputs on the rightNEWLINE # link output of plane to input of paraboloid using drag and dropNEWLINENEWLINE # Opens up the link editor window/divNEWLINENEWLINE # Drag f_x on the left to y on the rightNEWLINENEWLINE # close the link editor windowNEWLINENEWLINE # Structure diagram should show thisNEWLINENEWLINE # put in some values for planeNEWLINE # x1 = 5NEWLINE # x2 = 15NEWLINE # x3 = 12NEWLINENEWLINE # go to Workflow tabNEWLINENEWLINE # drag and drop plane and paraboloid from object tree into top iconNEWLINENEWLINE # save the projectNEWLINENEWLINE # click on plane in object tree so properties are displayedNEWLINE # in Properties tabNEWLINENEWLINE # Context click on paraboloid and select PropertiesNEWLINE # to bring up the windowNEWLINENEWLINE # Run the ProjectNEWLINENEWLINE # The properties in the two areas should changeNEWLINE # f_x in plane is 103NEWLINE # y in paraboloid is 103NEWLINE # f_y in paraboloid is 21218NEWLINENEWLINE #### Now run through optimizerNEWLINENEWLINE # Get an optimizer over in LibrariesNEWLINE # openmdao.lib.drivers.conmindriver.CONMINdriverNEWLINE # drag it into the Structures area in a blank spaceNEWLINENEWLINE # name it driver - takes place of default driverNEWLINENEWLINE # re-drag plane and paraboloid into topNEWLINENEWLINE # Setup conmindriver ( not sure how you bring up theNEWLINE # editor for the driver ( double click on icon? )NEWLINENEWLINE # Click on Add ParameterNEWLINENEWLINE # In the New Parameter window that comes upNEWLINE # Target: plane.x3NEWLINE # Low: 5NEWLINE # High: 25NEWLINE # Click on OK to dismiss that windowNEWLINENEWLINE # Click on Objectives tabNEWLINENEWLINE # Click on Add Objective linkNEWLINENEWLINE # In the New ObjectiveNEWLINE # set to paraboloid.f_yNEWLINENEWLINE # Save projectNEWLINENEWLINE # Close the CONMIN editor windowNEWLINENEWLINE # Project -> RunNEWLINENEWLINE # Results changedNEWLINE # plane.x1 is 5NEWLINE # plane.x2 is 15NEWLINE # plane.x3 is 5NEWLINE # plane.f_x output is 75NEWLINE # paraboloid.y = 75NEWLINE # paraboloid.f_y = 11250NEWLINE NEWLINENEWLINE # Just to see what gets savedNEWLINE workspace_page.commit_project()NEWLINE NEWLINE projects_page_again = workspace_page.close_workspace()NEWLINENEWLINE login_page_again = projects_page_again.logout()NEWLINENEWLINE time.sleep(5)NEWLINE login_page_again.assert_on_correct_page()NEWLINE NEWLINE
from src.interfacing.ogs.connect import AuthenticationNEWLINEimport codecsNEWLINEimport sysNEWLINEimport osNEWLINEfrom time import sleepNEWLINENEWLINEdef loadList(pNameFile): NEWLINE iList = []NEWLINE with codecs.open(pNameFile, "r", "utf-8") as f:NEWLINE for line in f:NEWLINE iList.append(line)NEWLINE return iListNEWLINE NEWLINEif __name__ == "__main__":NEWLINE a = Authentication("Kuksu League", "", testing=False);NEWLINE NEWLINE iGroupNames = loadList("E:/Project/OGS/OGS-League/group_names.txt");NEWLINE fGroupIDs = codecs.open("E:/Project/OGS/OGS-League/group_ids.txt", "w", "utf-8");NEWLINE NEWLINE nGroups = len(iGroupNames);NEWLINE NEWLINE for i in range(nGroups):NEWLINE iGroupNames[i] = iGroupNames[i].replace("\r\n", "")NEWLINE iGroupNames[i] = iGroupNames[i].replace("\n", "")NEWLINE iTournament = a.post(['tournaments'],{NEWLINE "name":"Kuksu Main Title Tournament 9th Cycle - Group %s" % iGroupNames[i],NEWLINE "group":515,NEWLINE "tournament_type":"roundrobin",NEWLINE "description":"Kuksu Main Title Tournament 9th Cycle - Group %s" % iGroupNames[i],NEWLINE "board_size":19,NEWLINE "handicap":0, #default -1 for autoNEWLINE "time_start": "2015-12-01T00:00:00Z",NEWLINE "time_control_parameters":{NEWLINE "time_control":"fischer",NEWLINE "initial_time":604800,NEWLINE "max_time":604800,NEWLINE "time_increment":86400NEWLINE },NEWLINE "rules": "korean",NEWLINE "exclusivity": "invite", # open, group. defaultNEWLINE "exclude_provisional": False, # defaultNEWLINE "auto_start_on_max": True, # defaultNEWLINE "analysis_enabled": True, #defaultNEWLINE "settings":{NEWLINE "maximum_players":10,NEWLINE },NEWLINE "players_start": 10, #defaultNEWLINE "first_pairing_method": "slide", #slaughter, random, slide, strength . defaultNEWLINE "subsequent_pairing_method": "slide", # defaultNEWLINE "min_ranking":0,NEWLINE "max_ranking":36NEWLINE });NEWLINE NEWLINE print("Tournament %s with id %d created.\n" % (iGroupNames[i], iTournament["id"]));NEWLINE fGroupIDs.writelines("%d\n" % iTournament["id"]);NEWLINE sleep(2);NEWLINE NEWLINE fGroupIDs.close();NEWLINE NEWLINE#a.put(['tournaments', 12650], {"description":"Test Test"});NEWLINENEWLINE# tourney id 7370NEWLINE"""NEWLINEiTournament = a.post(['tournaments'],{NEWLINE "id":12650,NEWLINE "name":"Test Tournament 2",NEWLINE "group":515,NEWLINE "tournament_type":"roundrobin",NEWLINE "description":"<b>Test 3</b>",NEWLINE "board_size":19,NEWLINE "handicap":0, #default -1 for autoNEWLINE "time_start": "2015-12-01T00:00:00Z",NEWLINE "time_control_parameters":{NEWLINE "time_control":"fischer",NEWLINE "initial_time":604800,NEWLINE "max_time":604800,NEWLINE "time_increment":86400NEWLINE },NEWLINE "rules": "korean",NEWLINE "exclusivity": "invite", # open, group. defaultNEWLINE "exclude_provisional": False, # defaultNEWLINE "auto_start_on_max": True, # defaultNEWLINE "analysis_enabled": True, #defaultNEWLINE "settings":{NEWLINE "maximum_players":10,NEWLINE },NEWLINE "players_start": 6, #defaultNEWLINE "first_pairing_method": "slide", #slaughter, random, slide, strength . defaultNEWLINE "subsequent_pairing_method": "slide", # defaultNEWLINE "min_ranking":0,NEWLINE "max_ranking":36NEWLINE});NEWLINENEWLINE#print("Hello");NEWLINEprint(iTournament["id"]);NEWLINE"""NEWLINE#print "Tournament %s is created." % iTournament["id"];NEWLINENEWLINE# r= a.post (['tournaments', 12642, 'players'], app_param= {"player_id":40318} )NEWLINE# print (r)NEWLINE
#!/usr/bin/env pythonNEWLINENEWLINE# for non-list/dict, CHANGE_TO -> variables replace previous valuesNEWLINE# for 'list' , ADD_TO -> append to listNEWLINE# EXCLUDE_FROM -> remove element from listNEWLINE# for 'dict' , REPLACE_WITH -> replace matching keys NEWLINE# as CHANGE_TO, ADD_TO or EXCLUDE_FROMNEWLINENEWLINEimport pprintNEWLINEimport argparseNEWLINEimport sysNEWLINEimport osNEWLINEimport errnoNEWLINEimport reNEWLINENEWLINEclass dryRun(Exception): passNEWLINENEWLINEclass ConfigParseError(dryRun):NEWLINE def __init__(self, msg, config_filename, orig_exc):NEWLINE self.config_filename = config_filenameNEWLINE self.orig_exc = orig_excNEWLINE Exception.__init__(self, msg)NEWLINENEWLINEclass CmdLine():NEWLINE def __init__(self, argvList):NEWLINE self.json_dir = '../json'NEWLINENEWLINE # env_name: '-e' [dev, qa, uat, prod, ...] NEWLINE # app_name:'-a' [ 'eq', ... ]NEWLINE # app_use: '-u' [ centos_6u6, rh_7.2, ...]NEWLINE # hw_name: '-m' [ hp_dl_360_gen9, hp_dl_360_gen10, ...]NEWLINE # dc_name: '-l' [ rfp, sec, lnd, ....]NEWLINE # host_name: '-n' NEWLINENEWLINE self.env_name = ''NEWLINE self.app_name = ''NEWLINE self.app_use = 'all'NEWLINE self.hw_name = ''NEWLINE self.dc_name = ''NEWLINE self.host_name = ''NEWLINENEWLINE # This is JSON configuration file name and key value to look in toNEWLINE self.configFile = ''NEWLINE self.configKey = ''NEWLINE self.c = {}NEWLINE self.d = []NEWLINENEWLINE self.parseCmdLine(argvList)NEWLINENEWLINE print(self.hw_name)NEWLINENEWLINE # Read YAML in to main_configNEWLINE self.main_config = self.read_config(self.configFile)NEWLINE NEWLINE #print(self.main_config)NEWLINENEWLINE # parse JSONNEWLINE self.parseJSON(self.main_config[self.configKey])NEWLINE self.d.append(self.configFile)NEWLINE print(self.d)NEWLINE dane=self.mergeJSON(self.d)NEWLINE pprint.pprint(dane)NEWLINE print('dane')NEWLINENEWLINE def writeJSON(self, filename, datastore):NEWLINE import jsonNEWLINE if filename:NEWLINE # Writing JSON dataNEWLINE with open(filename, 'w') as f:NEWLINE json.dump(datastore, f)NEWLINENEWLINE def readJSON(self, filename):NEWLINE import yamlNEWLINE ret_dict={}NEWLINENEWLINE if filename:NEWLINE # Read JSON dataNEWLINE with open(filename, 'r') as f:NEWLINE ret_dict=yaml.load(f)NEWLINE NEWLINE return(ret_dict)NEWLINENEWLINE def mergeJSON(self, read_list, ret_dict={}):NEWLINE if not read_list:NEWLINE return(ret_dict)NEWLINENEWLINE for j_data in read_list:NEWLINE # read JSONNEWLINE tmp_dict=self.readJSON(j_data)[j_data.split('/')[-1]]NEWLINENEWLINE if (tmp_dict.has_key('extends')):NEWLINE k_data=tmp_dict.pop('extends')NEWLINENEWLINE ret_dict.update(tmp_dict)NEWLINENEWLINE k=my_func(ret_dict)NEWLINENEWLINE ret_dict=kNEWLINENEWLINE print('KK')NEWLINE pprint.pprint(k)NEWLINE #print('KK-End')NEWLINE return(ret_dict) NEWLINE #ret_dict.update( my_func(tmp_dict) )NEWLINENEWLINENEWLINENEWLINE def parseCmdLine(self, cmdLine):NEWLINE parser = argparse.ArgumentParser(description="parse josn files")NEWLINE parser.add_argument('-m', action="store", dest="model")NEWLINE parser.add_argument('-n', action="store", dest="host_name")NEWLINE parser.add_argument('-u', action="store", dest="unix_os")NEWLINE parser.add_argument('-l', action="store", dest="location")NEWLINE parser.add_argument('-a', action="store", dest="app_name")NEWLINE parser.add_argument('-e', action="store", dest="env_name")NEWLINE parser.add_argument('-r', action='store_true', dest="run" )NEWLINE parser.add_argument('command', nargs='*', action="store")NEWLINENEWLINE args = parser.parse_args(cmdLine)NEWLINE NEWLINE if (not args.run):NEWLINE print(args.model)NEWLINE raise dryRunNEWLINENEWLINE # command validationNEWLINE NEWLINE self.hw_name = args.modelNEWLINENEWLINE self.configFile = os.path.join(self.json_dir, self.hw_name)NEWLINE self.configKey = '%s' % (self.hw_name)NEWLINE NEWLINE def read_config(self, config_filename):NEWLINE from yaml import loadNEWLINE from os.path import existsNEWLINENEWLINE if not exists(config_filename): returnNEWLINENEWLINE with open(config_filename) as f:NEWLINE try:NEWLINE return load(f)NEWLINE except ValueError as exc:NEWLINE msg = 'Error parsing %s:\n %s' % (config_filename, exc)NEWLINE raise ConfigParseError(msg, config_filename, exc)NEWLINENEWLINE def parseJSON(self, k):NEWLINE if not k.has_key('extends'):NEWLINE return(self.d)NEWLINENEWLINE for j in k.pop('extends'):NEWLINE m = self.read_config(self.json_dir +'/'+ j )[j]NEWLINE self.parseJSON(m)NEWLINE print( 'Applying ' + self.json_dir +'/'+ j )NEWLINE self.d.append(os.path.join(self.json_dir, j))NEWLINE#NEWLINEdef manage_list(v, nv, r="ADD_TO"):NEWLINE if (r in ['ADD_TO']):NEWLINE try:NEWLINE print('aaaa')NEWLINE print(v)NEWLINE print([x for x in nv if any(re.search(y, x) for y in v)])NEWLINE print(nv)NEWLINE print('bbbb')NEWLINE #v.extend([x for x in nv if not any(re.search(y, x) for y in v)])NEWLINE v.extend(nv)NEWLINE except TypeError as exc:NEWLINE v.extend(nv)NEWLINE NEWLINE if (r in ['EXCLUDE_FROM']):NEWLINE v=reduce(lambda x,y : filter(lambda z: z!=y,x),nv,v)NEWLINE return(v)NEWLINENEWLINEdef my_func(a):NEWLINE ret_dict={}NEWLINE done_key_list=[]NEWLINENEWLINE for k,v in a.iteritems():NEWLINE reserved_word=''NEWLINE if (len(k.split('_')) > 2):NEWLINE reserved_word='_'.join(k.split('_')[:2])NEWLINE if (reserved_word in [NEWLINE 'ADD_TO', NEWLINE 'EXCLUDE_FROM', NEWLINE 'REPLACE_WITH', NEWLINE 'CHANGE_TO'NEWLINE ]):NEWLINE var='_'.join(k.split('_')[2:])NEWLINE else:NEWLINE var=kNEWLINE else:NEWLINE var=kNEWLINE NEWLINE if (isinstance(v, list)):NEWLINE if (reserved_word in ['ADD_TO', 'EXCLUDE_FROM']):NEWLINE done_key_list.append('%s' % (var))NEWLINE print('%s: %s' % ('Done List', ', '.join(done_key_list)))NEWLINE NEWLINE # check ret_dict if var exists or use from previous dict NEWLINENEWLINE # empty listNEWLINE pv=[]NEWLINENEWLINE pprint.pprint(ret_dict)NEWLINE pprint.pprint(a)NEWLINE print(var)NEWLINE if (a.has_key(var)):NEWLINE pv=a[var]NEWLINE pprint.pprint(pv)NEWLINE pprint.pprint(v)NEWLINE print(reserved_word)NEWLINENEWLINE ret_dict[var]=manage_list(pv, v, reserved_word)NEWLINE NEWLINE else:NEWLINE if (var not in done_key_list):NEWLINE ret_dict[var]=vNEWLINE NEWLINE if (not isinstance(v, list) and not isinstance(v, dict)):NEWLINE if (reserved_word in ['REPLACE_WITH']):NEWLINE done_key_list.append(var)NEWLINE ret_dict[var]=a['%s_%s' % (reserved_word, var)]NEWLINE else:NEWLINE if (var not in done_key_list):NEWLINE ret_dict[var]=vNEWLINE NEWLINE if (isinstance(v, dict)):NEWLINE if (reserved_word in ['CHANGE_TO']):NEWLINE done_key_list.append(var)NEWLINE tmp_dict={}NEWLINENEWLINE for k1,v1 in v.iteritems():NEWLINE tmp_dict[k1]=v1NEWLINENEWLINE if (a.has_key(var)):NEWLINE for k1,v1 in a[var].iteritems():NEWLINE tmp_dict[k1]=v1NEWLINE NEWLINE ret_dict[var]=my_func(tmp_dict)NEWLINE else: NEWLINE if (var not in done_key_list):NEWLINE ret_dict[var]=vNEWLINE NEWLINE return(ret_dict)NEWLINENEWLINEu=CmdLine(sys.argv[1:])NEWLINENEWLINEprint('End')NEWLINEpprint.pprint(u.c)NEWLINE
from django.views.decorators.csrf import csrf_exemptNEWLINEfrom django.shortcuts import renderNEWLINEfrom django.http import JsonResponseNEWLINEfrom backend.models import users,interviewer,interviewee,hr,play,interview,position,applyNEWLINEfrom django.views.decorators.csrf import csrf_protectNEWLINEfrom django.db.models import QNEWLINEfrom datetime import datetimeNEWLINEimport timeNEWLINEimport smtplibNEWLINEfrom email.mime.text import MIMETextNEWLINEfrom email.header import HeaderNEWLINEfrom PIL import ImageNEWLINEfrom email.utils import formataddrNEWLINEimport urllib.requestNEWLINEimport randomNEWLINEimport osNEWLINENEWLINE@csrf_exemptNEWLINE#新建用户 get用户信息NEWLINEdef user(request):NEWLINE result = {'verdict': 'ok', 'message': 'successful!'}NEWLINE if request.method == 'POST':NEWLINE print(request.POST)NEWLINE username = request.POST['username']NEWLINE password = request.POST['password']NEWLINE email = request.POST['email']NEWLINE username = str(username)NEWLINE password = str(password)NEWLINE email = str(email)NEWLINE result['email'] = emailNEWLINE result['password'] = passwordNEWLINE result['username'] = usernameNEWLINE #return JsonResponse(result)NEWLINE userinfo = users.objects.filter(Q(email = email)|Q(username = username))NEWLINE print (userinfo)NEWLINE if userinfo:NEWLINE result['verdict'] = 'error'NEWLINE result['message'] = 'The email or username already exits!'NEWLINE else:NEWLINE user = users(username = username , password = password ,email = email)NEWLINENEWLINE iner = interviewer.objects.create()NEWLINE inee =interviewee.objects.create()NEWLINE ihr =hr.objects.create()NEWLINE user.save()NEWLINE print(iner.er_id)NEWLINE play.objects.create(user=user,er_id=iner,ee_id=inee,hr_id=ihr)NEWLINENEWLINE return JsonResponse(result)NEWLINE else :NEWLINE username = request.session.get('username','')NEWLINE userinfo = users.objects.filter(username=username)NEWLINE if userinfo:NEWLINE result['username'] = usernameNEWLINE result['email'] = str(list(userinfo.values('email'))[0]['email'])NEWLINE result['role'] = str(request.session["role"])NEWLINE #result['avatar'] = '/media/'+str(list(userinfo.values('avatar'))[0]['avatar'])NEWLINE else:NEWLINE result['verdict'] = 'error'NEWLINE result['message'] = 'Please log in first!'NEWLINE return JsonResponse(result)NEWLINENEWLINE#登录NEWLINE@csrf_exemptNEWLINEdef login(request):NEWLINE if request.method == 'POST':NEWLINE username = request.POST['username']NEWLINE password = request.POST['password']NEWLINE role = request.POST['role']NEWLINE role=int(role)NEWLINE result = {'verdict': 'ok', 'message': 'successful'}NEWLINE userinfo = users.objects.filter(username = username,password = password)NEWLINE if userinfo:NEWLINE request.session["username"] = usernameNEWLINE print("FUCK!!!!!!!!!!!!!!!!!!!!!!")NEWLINE print (request.session["username"])NEWLINE if role==0:NEWLINE request.session["role"] = 0NEWLINE elif role ==1:NEWLINE request.session["role"] = 1NEWLINE elif role == 2:NEWLINE request.session["role"] = 2NEWLINE else:NEWLINE result['verdict'] = 'error'NEWLINE result['message'] = 'Please select your role!'NEWLINE else:NEWLINE print ("login error!")NEWLINE result['verdict'] = 'error'NEWLINE result['message'] = 'The Username or Password is not correct.'NEWLINE return JsonResponse(result)NEWLINENEWLINE#登出NEWLINEdef logout(request):NEWLINE del request.session["username"]NEWLINE result = {'verdict':'ok','message':'successful'}NEWLINE return render(request, "login.html")NEWLINENEWLINENEWLINENEWLINE'''NEWLINEPOST 确定面试时间NEWLINE参数NEWLINEee_idNEWLINEtimeNEWLINEer_idNEWLINEpos_idNEWLINE返回NEWLINEverdictNEWLINEmessageNEWLINENEWLINEee_id pos_id ->apply_idNEWLINEer_id time ee_id apply_id => interviewNEWLINENEWLINEGET 得到面试时间NEWLINENEWLINE返回NEWLINEinterviews:NEWLINENEWLINE[ { "job_title": "Google SDE", "date": [y,mo,d] },NEWLINE { "job_title": "Amazon SDE", "date": [y,mo,d] ]NEWLINENEWLINEuser -> apply->interviewNEWLINENEWLINE'''NEWLINENEWLINENEWLINE@csrf_exemptNEWLINEdef interview_time(request):NEWLINE result = {'verdict': 'ok', 'message': 'successful!'}NEWLINE if request.method == 'POST':NEWLINE time = request.POST['time']NEWLINE interviewer_id=request.POST['er_id']NEWLINE interviewee_id=request.POST['ee_id']NEWLINE position_id = request.POST['pos_id']NEWLINE interviewee_id=int(interviewee_id)NEWLINE interviewer_id=int(interviewer_id)NEWLINE position_id=int(position_id)NEWLINENEWLINE iinterviewer=interviewer.objects.get(er_id=interviewer_id)NEWLINE iinterviewee=interviewee.objects.get(ee_id=interviewee_id)NEWLINE iposition=position.objects.get(position_id=position_id)NEWLINE iapply=apply.objects.get(ee_id=iinterviewee,position_id=iposition)NEWLINENEWLINE interview.objects.create(er_id=iinterviewer,ee_id =iinterviewee,apply_id=iapply,date=time)NEWLINE return JsonResponse(result)NEWLINENEWLINE if request.method == 'GET':NEWLINE interviews=[]NEWLINE username = request.session.get('username','')NEWLINE userinfo = users.objects.get(username=username)NEWLINE iplay =play.objects.get(user=userinfo)NEWLINE print (iplay.user.username)NEWLINE iapply=apply.objects.filter(ee_id=iplay.ee_id)NEWLINE for iiapply in iapply:NEWLINE iinterview=interview.objects.filter(apply_id=iiapply)NEWLINE for iiinterview in iinterview:NEWLINE ainterview={}NEWLINE ainterview["job_title"]=iiinterview.apply_id.position_id.jobNEWLINE ainterview["date"]=iiinterview.dateNEWLINE interviews.append(ainterview)NEWLINE result['interviews']=interviewsNEWLINE return JsonResponse(result)NEWLINENEWLINENEWLINENEWLINE@csrf_exemptNEWLINE#发布岗位NEWLINEdef release_job(request):NEWLINE result = {'verdict':'ok','message':'successful'}NEWLINE if request.method == 'POST':NEWLINE job = request.POST['job']NEWLINE job_description = request.POST['job_description']NEWLINE excepted_salary = request.POST['excepted_salary']NEWLINE location=request.POST['location']NEWLINENEWLINE result['job'] = jobNEWLINE result['job_description'] = job_descriptionNEWLINE result['excepted_salary'] = excepted_salaryNEWLINE result['location'] = locationNEWLINENEWLINE username = request.session.get('username','')NEWLINE userinfo = users.objects.get(username=username)NEWLINE if userinfo:NEWLINE print( userinfo.email)NEWLINE iplay=play.objects.get(user=userinfo)NEWLINE print (iplay.hr_id)NEWLINE position.objects.create(job=job,location=location,excepted_salary=excepted_salary,NEWLINE job_description=job_description,hr=iplay.hr_id)NEWLINE else:NEWLINE result['verdict'] = 'fail'NEWLINE result['message'] = "The hr don't exits!"NEWLINE return JsonResponse(result)NEWLINENEWLINENEWLINENEWLINENEWLINE# 返回面试状态NEWLINEdef get_interview_status(request):NEWLINE result = {'verdict':'ok','message':'successful'}NEWLINE if request.method == 'GET':NEWLINE interviews=[]NEWLINE username = request.session.get('username','')NEWLINE userinfo = users.objects.get(username=username)NEWLINE iplay =play.objects.get(user=userinfo)NEWLINE print (iplay.user.username)NEWLINE iapply=apply.objects.filter(ee_id=iplay.ee_id)NEWLINE for iiapply in iapply:NEWLINE iinterview=interview.objects.filter(apply_id=iiapply)NEWLINE for iiinterview in iinterview:NEWLINE ainterview={}NEWLINE ainterview["job_title"]=iiinterview.apply_id.position_id.jobNEWLINE ainterview["status"]=iiinterview.statusNEWLINE interviews.append(ainterview)NEWLINE result['interviews']=interviewsNEWLINE return JsonResponse(result)NEWLINENEWLINENEWLINENEWLINENEWLINE@csrf_exemptNEWLINE# 申请工作NEWLINEdef apply_job(request):NEWLINE if request.method == "POST":NEWLINE username = request.session.get('username','')NEWLINE pos_id = request.POST['pos_id']NEWLINE print (username)NEWLINE result = {'verdict':'error','message':'No resume!'}NEWLINE resume =request.FILES.get("resume", None) # 获取上传的文件,如果没有文件,则默认为NoneNEWLINE if not resume:NEWLINE return JsonResponse(result)NEWLINENEWLINE userinfo = users.objects.get(username=username)NEWLINENEWLINENEWLINE if userinfo:NEWLINE x= str(random.randint(1, 20000000))NEWLINE resume_path=os.path.join("media", username+x+resume.name)NEWLINENEWLINE iplay=play.objects.get(user=userinfo)NEWLINE ipos=position.objects.get(position_id=int(pos_id))NEWLINE apply.objects.create(resume_path=resume_path,ee_id=iplay.ee_id,position_id=ipos)NEWLINENEWLINENEWLINE destination = open(resume_path,'wb+') # 打开特定的文件进行二进制的写操作NEWLINE for chunk in resume.chunks(): # 分块写入文件NEWLINE destination.write(chunk)NEWLINE destination.close()NEWLINENEWLINE return render(request, "apply_job.html")NEWLINENEWLINENEWLINE@csrf_exemptNEWLINE# 得到简历的路径NEWLINEdef get_resume_url(request):NEWLINE result = {'verdict':'ok','message':'successful'}NEWLINE if request.method == "POST":NEWLINE iinterviewee = request.POST['ee_id']NEWLINE iposition = request.POST['pos_id']NEWLINE interviewee_obj=interviewee.objects.get(ee_id=iinterviewee)NEWLINE position_obj=position.objects.get(position_id=iposition)NEWLINE iapply=apply.objects.get(ee_id=interviewee_obj,position_id=position_obj)NEWLINE result["resume_url"]=iapply.resume_pathNEWLINE # print (result["resume_url"])NEWLINE return JsonResponse(result)NEWLINENEWLINENEWLINENEWLINENEWLINE# 得到工作信息NEWLINEdef get_job_information(request):NEWLINE result = {'verdict':'ok','message':'successful'}NEWLINE job_list=[]NEWLINE if request.method == "GET":NEWLINE positions=position.objects.all()NEWLINE for i in positions:NEWLINE job_list.append(i.becomedict())NEWLINE result["job_list"]=job_listNEWLINE return JsonResponse(result)NEWLINENEWLINENEWLINENEWLINENEWLINE@csrf_exemptNEWLINE# 所有申请者情况信息NEWLINEdef applicants_list(request):NEWLINE result = {'verdict':'ok','message':'successful'}NEWLINE if request.method == 'POST':NEWLINE result["page"]="1"NEWLINE jishuqi=0NEWLINE rows=[]NEWLINE jishuqi=apply.objects.all().count()NEWLINE applys=apply.objects.all()NEWLINE for app in applys:NEWLINE row={}NEWLINE row["applicant_id"]=app.ee_id.ee_idNEWLINE row["job_id"]=app.position_id.position_idNEWLINE iplay=play.objects.get(ee_id=app.ee_id)NEWLINE row["interviewer"]=iplay.user.username #面试者名字NEWLINE row["status"]=app.statusNEWLINENEWLINE iinterview=interview.objects.get(apply_id=app)NEWLINE iplay=play.objects.get(er_id=iinterview.er_id)NEWLINE row["name"]=iplay.user.username #面试官名字NEWLINE iinterview=interview.objects.get(apply_id=app)NEWLINE row["date"]=iinterview.date #面试时间NEWLINE rows.append(row)NEWLINENEWLINENEWLINE result["total"]=jishuqiNEWLINE result["records"]=jishuqiNEWLINE result["rows"]=rowsNEWLINE return JsonResponse(result)NEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE
# -*- coding: utf-8 -*-NEWLINEfrom __future__ import unicode_literalsNEWLINENEWLINEfrom django.db import migrations, modelsNEWLINEimport core.utilsNEWLINENEWLINENEWLINEclass Migration(migrations.Migration):NEWLINENEWLINE dependencies = [NEWLINE ('questions', '0007_auto_20151209_1526'),NEWLINE ]NEWLINENEWLINE operations = [NEWLINE migrations.AddField(NEWLINE model_name='quiz',NEWLINE name='image',NEWLINE field=models.ImageField(default=None, upload_to=core.utils.PathAndRename(b'quiz/'), null=True, verbose_name='Image', blank=True),NEWLINE ),NEWLINE ]NEWLINE
# -*- coding: utf-8 -*-NEWLINENEWLINE# Copyright (c) 2017 Ansible, Inc.NEWLINE# All Rights Reserved.NEWLINEimport osNEWLINEimport pytestNEWLINEfrom uuid import uuid4NEWLINEimport jsonNEWLINEimport yamlNEWLINEimport mockNEWLINENEWLINEfrom backports.tempfile import TemporaryDirectoryNEWLINEfrom django.conf import settingsNEWLINENEWLINEfrom rest_framework.exceptions import ParseErrorNEWLINENEWLINEfrom awx.main.utils import commonNEWLINENEWLINEfrom awx.main.models import (NEWLINE Job,NEWLINE AdHocCommand,NEWLINE InventoryUpdate,NEWLINE ProjectUpdate,NEWLINE SystemJob,NEWLINE WorkflowJobNEWLINE)NEWLINENEWLINENEWLINE@pytest.mark.parametrize('input_, output', [NEWLINE ({"foo": "bar"}, {"foo": "bar"}),NEWLINE ('{"foo": "bar"}', {"foo": "bar"}),NEWLINE ('---\nfoo: bar', {"foo": "bar"}),NEWLINE (4399, {}),NEWLINE])NEWLINEdef test_parse_yaml_or_json(input_, output):NEWLINE assert common.parse_yaml_or_json(input_) == outputNEWLINENEWLINENEWLINEdef test_recursive_vars_not_allowed():NEWLINE rdict = {}NEWLINE rdict['a'] = rdictNEWLINE # YAML dumper will use a tag to give recursive dataNEWLINE data = yaml.dump(rdict, default_flow_style=False)NEWLINE with pytest.raises(ParseError) as exc:NEWLINE common.parse_yaml_or_json(data, silent_failure=False)NEWLINE assert 'Circular reference detected' in str(exc)NEWLINENEWLINENEWLINEclass TestParserExceptions:NEWLINENEWLINE @staticmethodNEWLINE def json_error(data):NEWLINE try:NEWLINE json.loads(data)NEWLINE return NoneNEWLINE except Exception as e:NEWLINE return str(e)NEWLINENEWLINE @staticmethodNEWLINE def yaml_error(data):NEWLINE try:NEWLINE yaml.load(data)NEWLINE return NoneNEWLINE except Exception as e:NEWLINE return str(e)NEWLINENEWLINE def test_invalid_JSON_and_YAML(self):NEWLINE data = "{key:val"NEWLINE with pytest.raises(ParseError) as exc:NEWLINE common.parse_yaml_or_json(data, silent_failure=False)NEWLINE message = str(exc.value)NEWLINE assert "Cannot parse as" in messageNEWLINE assert self.json_error(data) in messageNEWLINE assert self.yaml_error(data) in messageNEWLINENEWLINE def test_invalid_vars_type(self):NEWLINE data = "[1, 2, 3]"NEWLINE with pytest.raises(ParseError) as exc:NEWLINE common.parse_yaml_or_json(data, silent_failure=False)NEWLINE message = str(exc.value)NEWLINE assert "Cannot parse as" in messageNEWLINE assert "Input type `list` is not a dictionary" in messageNEWLINENEWLINENEWLINEdef test_set_environ():NEWLINE key = str(uuid4())NEWLINE old_environ = os.environ.copy()NEWLINE with common.set_environ(**{key: 'bar'}):NEWLINE assert os.environ[key] == 'bar'NEWLINE assert set(os.environ.keys()) - set(old_environ.keys()) == set([key])NEWLINE assert os.environ == old_environNEWLINE assert key not in os.environNEWLINENEWLINENEWLINE# Cases relied on for scheduler dependent jobs listNEWLINE@pytest.mark.parametrize('model,name', [NEWLINE (Job, 'job'),NEWLINE (AdHocCommand, 'ad_hoc_command'),NEWLINE (InventoryUpdate, 'inventory_update'),NEWLINE (ProjectUpdate, 'project_update'),NEWLINE (SystemJob, 'system_job'),NEWLINE (WorkflowJob, 'workflow_job')NEWLINE])NEWLINEdef test_get_type_for_model(model, name):NEWLINE assert common.get_type_for_model(model) == nameNEWLINENEWLINENEWLINE@pytest.fixtureNEWLINEdef memoized_function(mocker, mock_cache):NEWLINE with mock.patch('awx.main.utils.common.get_memoize_cache', return_value=mock_cache):NEWLINE @common.memoize(track_function=True)NEWLINE def myfunction(key, value):NEWLINE if key not in myfunction.calls:NEWLINE myfunction.calls[key] = 0NEWLINENEWLINE myfunction.calls[key] += 1NEWLINENEWLINE if myfunction.calls[key] == 1:NEWLINE return valueNEWLINE else:NEWLINE return '%s called %s times' % (value, myfunction.calls[key])NEWLINE myfunction.calls = dict()NEWLINE return myfunctionNEWLINENEWLINENEWLINEdef test_memoize_track_function(memoized_function, mock_cache):NEWLINE assert memoized_function('scott', 'scotterson') == 'scotterson'NEWLINE assert mock_cache.get('myfunction') == {u'scott-scotterson': 'scotterson'}NEWLINE assert memoized_function('scott', 'scotterson') == 'scotterson'NEWLINENEWLINE assert memoized_function.calls['scott'] == 1NEWLINENEWLINE assert memoized_function('john', 'smith') == 'smith'NEWLINE assert mock_cache.get('myfunction') == {u'scott-scotterson': 'scotterson', u'john-smith': 'smith'}NEWLINE assert memoized_function('john', 'smith') == 'smith'NEWLINENEWLINE assert memoized_function.calls['john'] == 1NEWLINENEWLINENEWLINEdef test_memoize_delete(memoized_function, mock_cache):NEWLINE assert memoized_function('john', 'smith') == 'smith'NEWLINE assert memoized_function('john', 'smith') == 'smith'NEWLINE assert memoized_function.calls['john'] == 1NEWLINENEWLINE assert mock_cache.get('myfunction') == {u'john-smith': 'smith'}NEWLINENEWLINE with mock.patch('awx.main.utils.common.memoize_delete', side_effect=mock_cache.delete):NEWLINE common.memoize_delete('myfunction')NEWLINENEWLINE assert mock_cache.get('myfunction') is NoneNEWLINENEWLINE assert memoized_function('john', 'smith') == 'smith called 2 times'NEWLINE assert memoized_function.calls['john'] == 2NEWLINENEWLINENEWLINEdef test_memoize_parameter_error():NEWLINE @common.memoize(cache_key='foo', track_function=True)NEWLINE def fn():NEWLINE returnNEWLINENEWLINE with pytest.raises(common.IllegalArgumentError):NEWLINE fn()NEWLINENEWLINENEWLINEdef test_extract_ansible_vars():NEWLINE my_dict = {NEWLINE "foobar": "baz",NEWLINE "ansible_connetion_setting": "1928"NEWLINE }NEWLINE redacted, var_list = common.extract_ansible_vars(json.dumps(my_dict))NEWLINE assert var_list == set(['ansible_connetion_setting'])NEWLINE assert redacted == {"foobar": "baz"}NEWLINENEWLINENEWLINEdef test_get_custom_venv_choices():NEWLINE bundled_venv = os.path.join(settings.BASE_VENV_PATH, 'ansible', '')NEWLINE assert common.get_custom_venv_choices() == [bundled_venv]NEWLINENEWLINE with TemporaryDirectory(dir=settings.BASE_VENV_PATH, prefix='tmp') as temp_dir:NEWLINE os.makedirs(os.path.join(temp_dir, 'bin', 'activate'))NEWLINE assert sorted(common.get_custom_venv_choices()) == [NEWLINE bundled_venv,NEWLINE os.path.join(temp_dir, '')NEWLINE ]NEWLINENEWLINENEWLINEdef test_region_sorting():NEWLINE s = [('Huey', 'China1'),NEWLINE ('Dewey', 'UK1'),NEWLINE ('Lewie', 'US1'),NEWLINE ('All', 'All')]NEWLINE assert [x[1] for x in sorted(s, key=common.region_sorting)] == ['All', 'US1', 'China1', 'UK1']NEWLINE
import timeNEWLINEfrom importlib import import_moduleNEWLINENEWLINEfrom django.conf import settingsNEWLINEfrom django.contrib.sessions.backends.base import UpdateErrorNEWLINEfrom django.contrib.sessions.middleware import SessionMiddlewareNEWLINEfrom django.core.exceptions import SuspiciousOperationNEWLINEfrom django.utils.cache import patch_vary_headersNEWLINEfrom django.utils.http import http_dateNEWLINENEWLINENEWLINEclass SamlSessionMiddleware(SessionMiddleware):NEWLINE cookie_name = getattr(settings, 'SAML_SESSION_COOKIE_NAME', 'saml_session')NEWLINENEWLINE def process_request(self, request):NEWLINE session_key = request.COOKIES.get(self.cookie_name, None)NEWLINE request.saml_session = self.SessionStore(session_key)NEWLINENEWLINE def process_response(self, request, response):NEWLINE """NEWLINE If request.saml_session was modified, or if the configuration is to save theNEWLINE session every time, save the changes and set a session cookie or deleteNEWLINE the session cookie if the session has been emptied.NEWLINE """NEWLINE try:NEWLINE accessed = request.saml_session.accessedNEWLINE modified = request.saml_session.modifiedNEWLINE empty = request.saml_session.is_empty()NEWLINE except AttributeError:NEWLINE return responseNEWLINE # First check if we need to delete this cookie.NEWLINE # The session should be deleted only if the session is entirely empty.NEWLINE if self.cookie_name in request.COOKIES and empty:NEWLINE response.delete_cookie(NEWLINE self.cookie_name,NEWLINE path=settings.SESSION_COOKIE_PATH,NEWLINE domain=settings.SESSION_COOKIE_DOMAIN,NEWLINE samesite=None,NEWLINE )NEWLINE patch_vary_headers(response, ('Cookie',))NEWLINE else:NEWLINE if accessed:NEWLINE patch_vary_headers(response, ('Cookie',))NEWLINE # relies and the global oneNEWLINE if (modified or settings.SESSION_SAVE_EVERY_REQUEST) and not empty:NEWLINE if request.session.get_expire_at_browser_close():NEWLINE max_age = NoneNEWLINE expires = NoneNEWLINE else:NEWLINE max_age = getattr(request, self.cookie_name).get_expiry_age()NEWLINE expires_time = time.time() + max_ageNEWLINE expires = http_date(expires_time)NEWLINE # Save the session data and refresh the client cookie.NEWLINE # Skip session save for 500 responses, refs #3881.NEWLINE if response.status_code != 500:NEWLINE try:NEWLINE request.saml_session.save()NEWLINE except UpdateError:NEWLINE raise SuspiciousOperation(NEWLINE "The request's session was deleted before the "NEWLINE "request completed. The user may have logged "NEWLINE "out in a concurrent request, for example."NEWLINE )NEWLINE response.set_cookie(NEWLINE self.cookie_name,NEWLINE request.saml_session.session_key,NEWLINE max_age=max_age,NEWLINE expires=expires, domain=settings.SESSION_COOKIE_DOMAIN,NEWLINE path=settings.SESSION_COOKIE_PATH,NEWLINE secure=settings.SESSION_COOKIE_SECURE or None,NEWLINE httponly=settings.SESSION_COOKIE_HTTPONLY or None,NEWLINE samesite=NoneNEWLINE )NEWLINE return responseNEWLINE
"""NEWLINEThe MIT License (MIT)NEWLINENEWLINECopyright (c) 2015-present RapptzNEWLINENEWLINEPermission is hereby granted, free of charge, to any person obtaining aNEWLINEcopy of this software and associated documentation files (the "Software"),NEWLINEto deal in the Software without restriction, including without limitationNEWLINEthe rights to use, copy, modify, merge, publish, distribute, sublicense,NEWLINEand/or sell copies of the Software, and to permit persons to whom theNEWLINESoftware is furnished to do so, subject to the following conditions:NEWLINENEWLINEThe above copyright notice and this permission notice shall be included inNEWLINEall copies or substantial portions of the Software.NEWLINENEWLINETHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESSNEWLINEOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,NEWLINEFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THENEWLINEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERNEWLINELIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISINGNEWLINEFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHERNEWLINEDEALINGS IN THE SOFTWARE.NEWLINE"""NEWLINENEWLINEfrom __future__ import annotationsNEWLINENEWLINEimport asyncioNEWLINEimport datetimeNEWLINEimport loggingNEWLINEimport sysNEWLINEimport tracebackNEWLINEfrom typing import (NEWLINE Any,NEWLINE AsyncIterator,NEWLINE Callable,NEWLINE Coroutine,NEWLINE Dict,NEWLINE Generator,NEWLINE List,NEWLINE Optional,NEWLINE Sequence,NEWLINE TYPE_CHECKING,NEWLINE Tuple,NEWLINE Type,NEWLINE TypeVar,NEWLINE Union,NEWLINE)NEWLINENEWLINEimport aiohttpNEWLINENEWLINEfrom .user import User, ClientUserNEWLINEfrom .invite import InviteNEWLINEfrom .template import TemplateNEWLINEfrom .widget import WidgetNEWLINEfrom .guild import GuildNEWLINEfrom .emoji import EmojiNEWLINEfrom .channel import _threaded_channel_factory, PartialMessageableNEWLINEfrom .enums import ChannelTypeNEWLINEfrom .mentions import AllowedMentionsNEWLINEfrom .errors import *NEWLINEfrom .enums import StatusNEWLINEfrom .flags import ApplicationFlags, IntentsNEWLINEfrom .gateway import *NEWLINEfrom .activity import ActivityTypes, BaseActivity, create_activityNEWLINEfrom .voice_client import VoiceClientNEWLINEfrom .http import HTTPClientNEWLINEfrom .state import ConnectionStateNEWLINEfrom . import utilsNEWLINEfrom .utils import MISSING, time_snowflakeNEWLINEfrom .object import ObjectNEWLINEfrom .backoff import ExponentialBackoffNEWLINEfrom .webhook import WebhookNEWLINEfrom .appinfo import AppInfoNEWLINEfrom .ui.view import ViewNEWLINEfrom .stage_instance import StageInstanceNEWLINEfrom .threads import ThreadNEWLINEfrom .sticker import GuildSticker, StandardSticker, StickerPack, _sticker_factoryNEWLINENEWLINEif TYPE_CHECKING:NEWLINE from typing_extensions import SelfNEWLINE from types import TracebackTypeNEWLINE from .types.guild import Guild as GuildPayloadNEWLINE from .abc import SnowflakeTime, Snowflake, PrivateChannelNEWLINE from .guild import GuildChannelNEWLINE from .channel import DMChannelNEWLINE from .message import MessageNEWLINE from .member import MemberNEWLINE from .voice_client import VoiceProtocolNEWLINENEWLINE# fmt: offNEWLINE__all__ = (NEWLINE 'Client',NEWLINE)NEWLINE# fmt: onNEWLINENEWLINECoro = TypeVar('Coro', bound=Callable[..., Coroutine[Any, Any, Any]])NEWLINENEWLINE_log = logging.getLogger(__name__)NEWLINENEWLINENEWLINEclass _LoopSentinel:NEWLINE __slots__ = ()NEWLINENEWLINE def __getattr__(self, attr: str) -> None:NEWLINE msg = (NEWLINE 'loop attribute cannot be accessed in non-async contexts. 'NEWLINE 'Consider using either an asynchronous main function and passing it to asyncio.run or 'NEWLINE 'using asynchronous initialisation hooks such as Client.setup_hook'NEWLINE )NEWLINE raise AttributeError(msg)NEWLINENEWLINENEWLINE_loop: Any = _LoopSentinel()NEWLINENEWLINENEWLINEclass Client:NEWLINE r"""Represents a client connection that connects to Discord.NEWLINE This class is used to interact with the Discord WebSocket and API.NEWLINENEWLINE A number of options can be passed to the :class:`Client`.NEWLINENEWLINE ParametersNEWLINE -----------NEWLINE max_messages: Optional[:class:`int`]NEWLINE The maximum number of messages to store in the internal message cache.NEWLINE This defaults to ``1000``. Passing in ``None`` disables the message cache.NEWLINENEWLINE .. versionchanged:: 1.3NEWLINE Allow disabling the message cache and change the default size to ``1000``.NEWLINE proxy: Optional[:class:`str`]NEWLINE Proxy URL.NEWLINE proxy_auth: Optional[:class:`aiohttp.BasicAuth`]NEWLINE An object that represents proxy HTTP Basic Authorization.NEWLINE shard_id: Optional[:class:`int`]NEWLINE Integer starting at ``0`` and less than :attr:`.shard_count`.NEWLINE shard_count: Optional[:class:`int`]NEWLINE The total number of shards.NEWLINE application_id: :class:`int`NEWLINE The client's application ID.NEWLINE intents: :class:`Intents`NEWLINE The intents that you want to enable for the session. This is a way ofNEWLINE disabling and enabling certain gateway events from triggering and being sent.NEWLINE If not given, defaults to a regularly constructed :class:`Intents` class.NEWLINENEWLINE .. versionadded:: 1.5NEWLINE member_cache_flags: :class:`MemberCacheFlags`NEWLINE Allows for finer control over how the library caches members.NEWLINE If not given, defaults to cache as much as possible with theNEWLINE currently selected intents.NEWLINENEWLINE .. versionadded:: 1.5NEWLINE chunk_guilds_at_startup: :class:`bool`NEWLINE Indicates if :func:`.on_ready` should be delayed to chunk all guildsNEWLINE at start-up if necessary. This operation is incredibly slow for largeNEWLINE amounts of guilds. The default is ``True`` if :attr:`Intents.members`NEWLINE is ``True``.NEWLINENEWLINE .. versionadded:: 1.5NEWLINE status: Optional[:class:`.Status`]NEWLINE A status to start your presence with upon logging on to Discord.NEWLINE activity: Optional[:class:`.BaseActivity`]NEWLINE An activity to start your presence with upon logging on to Discord.NEWLINE allowed_mentions: Optional[:class:`AllowedMentions`]NEWLINE Control how the client handles mentions by default on every message sent.NEWLINENEWLINE .. versionadded:: 1.4NEWLINE heartbeat_timeout: :class:`float`NEWLINE The maximum numbers of seconds before timing out and restarting theNEWLINE WebSocket in the case of not receiving a HEARTBEAT_ACK. Useful ifNEWLINE processing the initial packets take too long to the point of disconnectingNEWLINE you. The default timeout is 60 seconds.NEWLINE guild_ready_timeout: :class:`float`NEWLINE The maximum number of seconds to wait for the GUILD_CREATE stream to end beforeNEWLINE preparing the member cache and firing READY. The default timeout is 2 seconds.NEWLINENEWLINE .. versionadded:: 1.4NEWLINE assume_unsync_clock: :class:`bool`NEWLINE Whether to assume the system clock is unsynced. This applies to the ratelimit handlingNEWLINE code. If this is set to ``True``, the default, then the library uses the time to resetNEWLINE a rate limit bucket given by Discord. If this is ``False`` then your system clock isNEWLINE used to calculate how long to sleep for. If this is set to ``False`` it is recommended toNEWLINE sync your system clock to Google's NTP server.NEWLINENEWLINE .. versionadded:: 1.3NEWLINE enable_debug_events: :class:`bool`NEWLINE Whether to enable events that are useful only for debugging gateway related information.NEWLINENEWLINE Right now this involves :func:`on_socket_raw_receive` and :func:`on_socket_raw_send`. IfNEWLINE this is ``False`` then those events will not be dispatched (due to performance considerations).NEWLINE To enable these events, this must be set to ``True``. Defaults to ``False``.NEWLINENEWLINE .. versionadded:: 2.0NEWLINE http_trace: :class:`aiohttp.TraceConfig`NEWLINE The trace configuration to use for tracking HTTP requests the library does using ``aiohttp``.NEWLINE This allows you to check requests the library is using. For more information, check theNEWLINE `aiohttp documentation <https://docs.aiohttp.org/en/stable/client_advanced.html#client-tracing>`_.NEWLINENEWLINE .. versionadded:: 2.0NEWLINENEWLINE AttributesNEWLINE -----------NEWLINE wsNEWLINE The websocket gateway the client is currently connected to. Could be ``None``.NEWLINE """NEWLINENEWLINE def __init__(self, **options: Any) -> None:NEWLINE self.loop: asyncio.AbstractEventLoop = _loopNEWLINE # self.ws is set in the connect methodNEWLINE self.ws: DiscordWebSocket = None # type: ignoreNEWLINE self._listeners: Dict[str, List[Tuple[asyncio.Future, Callable[..., bool]]]] = {}NEWLINE self.shard_id: Optional[int] = options.get('shard_id')NEWLINE self.shard_count: Optional[int] = options.get('shard_count')NEWLINENEWLINE proxy: Optional[str] = options.pop('proxy', None)NEWLINE proxy_auth: Optional[aiohttp.BasicAuth] = options.pop('proxy_auth', None)NEWLINE unsync_clock: bool = options.pop('assume_unsync_clock', True)NEWLINE http_trace: Optional[aiohttp.TraceConfig] = options.pop('http_trace', None)NEWLINE self.http: HTTPClient = HTTPClient(NEWLINE self.loop,NEWLINE proxy=proxy,NEWLINE proxy_auth=proxy_auth,NEWLINE unsync_clock=unsync_clock,NEWLINE http_trace=http_trace,NEWLINE )NEWLINENEWLINE self._handlers: Dict[str, Callable[..., None]] = {NEWLINE 'ready': self._handle_ready,NEWLINE }NEWLINENEWLINE self._hooks: Dict[str, Callable[..., Coroutine[Any, Any, Any]]] = {NEWLINE 'before_identify': self._call_before_identify_hook,NEWLINE }NEWLINENEWLINE self._enable_debug_events: bool = options.pop('enable_debug_events', False)NEWLINE self._connection: ConnectionState = self._get_state(**options)NEWLINE self._connection.shard_count = self.shard_countNEWLINE self._closed: bool = FalseNEWLINE self._ready: asyncio.Event = MISSINGNEWLINE self._connection._get_websocket = self._get_websocketNEWLINE self._connection._get_client = lambda: selfNEWLINENEWLINE if VoiceClient.warn_nacl:NEWLINE VoiceClient.warn_nacl = FalseNEWLINE _log.warning("PyNaCl is not installed, voice will NOT be supported")NEWLINENEWLINE async def __aenter__(self) -> Self:NEWLINE await self._async_setup_hook()NEWLINE return selfNEWLINENEWLINE async def __aexit__(NEWLINE self,NEWLINE exc_type: Optional[Type[BaseException]],NEWLINE exc_value: Optional[BaseException],NEWLINE traceback: Optional[TracebackType],NEWLINE ) -> None:NEWLINE if not self.is_closed():NEWLINE await self.close()NEWLINENEWLINE # internalsNEWLINENEWLINE def _get_websocket(self, guild_id: Optional[int] = None, *, shard_id: Optional[int] = None) -> DiscordWebSocket:NEWLINE return self.wsNEWLINENEWLINE def _get_state(self, **options: Any) -> ConnectionState:NEWLINE return ConnectionState(dispatch=self.dispatch, handlers=self._handlers, hooks=self._hooks, http=self.http, **options)NEWLINENEWLINE def _handle_ready(self) -> None:NEWLINE self._ready.set()NEWLINENEWLINE @propertyNEWLINE def latency(self) -> float:NEWLINE """:class:`float`: Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.NEWLINENEWLINE This could be referred to as the Discord WebSocket protocol latency.NEWLINE """NEWLINE ws = self.wsNEWLINE return float('nan') if not ws else ws.latencyNEWLINENEWLINE def is_ws_ratelimited(self) -> bool:NEWLINE """:class:`bool`: Whether the websocket is currently rate limited.NEWLINENEWLINE This can be useful to know when deciding whether you should query membersNEWLINE using HTTP or via the gateway.NEWLINENEWLINE .. versionadded:: 1.6NEWLINE """NEWLINE return FalseNEWLINENEWLINE @propertyNEWLINE def user(self) -> Optional[ClientUser]:NEWLINE """Optional[:class:`.ClientUser`]: Represents the connected client. ``None`` if not logged in."""NEWLINE return self._connection.userNEWLINENEWLINE @propertyNEWLINE def guilds(self) -> List[Guild]:NEWLINE """List[:class:`.Guild`]: The guilds that the connected client is a member of."""NEWLINE return self._connection.guildsNEWLINENEWLINE @propertyNEWLINE def emojis(self) -> List[Emoji]:NEWLINE """List[:class:`.Emoji`]: The emojis that the connected client has."""NEWLINE return self._connection.emojisNEWLINENEWLINE @propertyNEWLINE def stickers(self) -> List[GuildSticker]:NEWLINE """List[:class:`.GuildSticker`]: The stickers that the connected client has.NEWLINENEWLINE .. versionadded:: 2.0NEWLINE """NEWLINE return self._connection.stickersNEWLINENEWLINE @propertyNEWLINE def cached_messages(self) -> Sequence[Message]:NEWLINE """Sequence[:class:`.Message`]: Read-only list of messages the connected client has cached.NEWLINENEWLINE .. versionadded:: 1.1NEWLINE """NEWLINE return utils.SequenceProxy(self._connection._messages or [])NEWLINENEWLINE @propertyNEWLINE def private_channels(self) -> List[PrivateChannel]:NEWLINE """List[:class:`.abc.PrivateChannel`]: The private channels that the connected client is participating on.NEWLINENEWLINE .. note::NEWLINENEWLINE This returns only up to 128 most recent private channels due to an internal workingNEWLINE on how Discord deals with private channels.NEWLINE """NEWLINE return self._connection.private_channelsNEWLINENEWLINE @propertyNEWLINE def voice_clients(self) -> List[VoiceProtocol]:NEWLINE """List[:class:`.VoiceProtocol`]: Represents a list of voice connections.NEWLINENEWLINE These are usually :class:`.VoiceClient` instances.NEWLINE """NEWLINE return self._connection.voice_clientsNEWLINENEWLINE @propertyNEWLINE def application_id(self) -> Optional[int]:NEWLINE """Optional[:class:`int`]: The client's application ID.NEWLINENEWLINE If this is not passed via ``__init__`` then this is retrievedNEWLINE through the gateway when an event contains the data. UsuallyNEWLINE after :func:`~discord.on_connect` is called.NEWLINENEWLINE .. versionadded:: 2.0NEWLINE """NEWLINE return self._connection.application_idNEWLINENEWLINE @propertyNEWLINE def application_flags(self) -> ApplicationFlags:NEWLINE """:class:`~discord.ApplicationFlags`: The client's application flags.NEWLINENEWLINE .. versionadded:: 2.0NEWLINE """NEWLINE return self._connection.application_flagsNEWLINENEWLINE def is_ready(self) -> bool:NEWLINE """:class:`bool`: Specifies if the client's internal cache is ready for use."""NEWLINE return self._ready is not MISSING and self._ready.is_set()NEWLINENEWLINE async def _run_event(NEWLINE self,NEWLINE coro: Callable[..., Coroutine[Any, Any, Any]],NEWLINE event_name: str,NEWLINE *args: Any,NEWLINE **kwargs: Any,NEWLINE ) -> None:NEWLINE try:NEWLINE await coro(*args, **kwargs)NEWLINE except asyncio.CancelledError:NEWLINE passNEWLINE except Exception:NEWLINE try:NEWLINE await self.on_error(event_name, *args, **kwargs)NEWLINE except asyncio.CancelledError:NEWLINE passNEWLINENEWLINE def _schedule_event(NEWLINE self,NEWLINE coro: Callable[..., Coroutine[Any, Any, Any]],NEWLINE event_name: str,NEWLINE *args: Any,NEWLINE **kwargs: Any,NEWLINE ) -> asyncio.Task:NEWLINE wrapped = self._run_event(coro, event_name, *args, **kwargs)NEWLINE # Schedules the taskNEWLINE return self.loop.create_task(wrapped, name=f'discord.py: {event_name}')NEWLINENEWLINE def dispatch(self, event: str, *args: Any, **kwargs: Any) -> None:NEWLINE _log.debug('Dispatching event %s', event)NEWLINE method = 'on_' + eventNEWLINENEWLINE listeners = self._listeners.get(event)NEWLINE if listeners:NEWLINE removed = []NEWLINE for i, (future, condition) in enumerate(listeners):NEWLINE if future.cancelled():NEWLINE removed.append(i)NEWLINE continueNEWLINENEWLINE try:NEWLINE result = condition(*args)NEWLINE except Exception as exc:NEWLINE future.set_exception(exc)NEWLINE removed.append(i)NEWLINE else:NEWLINE if result:NEWLINE if len(args) == 0:NEWLINE future.set_result(None)NEWLINE elif len(args) == 1:NEWLINE future.set_result(args[0])NEWLINE else:NEWLINE future.set_result(args)NEWLINE removed.append(i)NEWLINENEWLINE if len(removed) == len(listeners):NEWLINE self._listeners.pop(event)NEWLINE else:NEWLINE for idx in reversed(removed):NEWLINE del listeners[idx]NEWLINENEWLINE try:NEWLINE coro = getattr(self, method)NEWLINE except AttributeError:NEWLINE passNEWLINE else:NEWLINE self._schedule_event(coro, method, *args, **kwargs)NEWLINENEWLINE async def on_error(self, event_method: str, *args: Any, **kwargs: Any) -> None:NEWLINE """|coro|NEWLINENEWLINE The default error handler provided by the client.NEWLINENEWLINE By default this prints to :data:`sys.stderr` however it could beNEWLINE overridden to have a different implementation.NEWLINE Check :func:`~discord.on_error` for more details.NEWLINE """NEWLINE print(f'Ignoring exception in {event_method}', file=sys.stderr)NEWLINE traceback.print_exc()NEWLINENEWLINE # hooksNEWLINENEWLINE async def _call_before_identify_hook(self, shard_id: Optional[int], *, initial: bool = False) -> None:NEWLINE # This hook is an internal hook that actually calls the public one.NEWLINE # It allows the library to have its own hook without stepping on theNEWLINE # toes of those who need to override their own hook.NEWLINE await self.before_identify_hook(shard_id, initial=initial)NEWLINENEWLINE async def before_identify_hook(self, shard_id: Optional[int], *, initial: bool = False) -> None:NEWLINE """|coro|NEWLINENEWLINE A hook that is called before IDENTIFYing a session. This is usefulNEWLINE if you wish to have more control over the synchronization of multipleNEWLINE IDENTIFYing clients.NEWLINENEWLINE The default implementation does nothing.NEWLINENEWLINE .. versionadded:: 1.4NEWLINENEWLINE ParametersNEWLINE ------------NEWLINE shard_id: :class:`int`NEWLINE The shard ID that requested being IDENTIFY'dNEWLINE initial: :class:`bool`NEWLINE Whether this IDENTIFY is the first initial IDENTIFY.NEWLINE """NEWLINENEWLINE passNEWLINENEWLINE async def _async_setup_hook(self) -> None:NEWLINE # Called whenever the client needs to initialise asyncio objects with a running loopNEWLINE loop = asyncio.get_running_loop()NEWLINE self.loop = loopNEWLINE self.http.loop = loopNEWLINE self._connection.loop = loopNEWLINE await self._connection.async_setup()NEWLINENEWLINE self._ready = asyncio.Event()NEWLINENEWLINE async def setup_hook(self) -> None:NEWLINE """|coro|NEWLINENEWLINE A coroutine to be called to setup the bot, by default this is blank.NEWLINENEWLINE To perform asynchronous setup after the bot is logged in but beforeNEWLINE it has connected to the Websocket, overwrite this coroutine.NEWLINENEWLINE This is only called once, in :meth:`login`, and will be called beforeNEWLINE any events are dispatched, making it a better solution than doing suchNEWLINE setup in the :func:`~discord.on_ready` event.NEWLINENEWLINE .. warning::NEWLINENEWLINE Since this is called *before* the websocket connection is made thereforeNEWLINE anything that waits for the websocket will deadlock, this includes thingsNEWLINE like :meth:`wait_for` and :meth:`wait_until_ready`.NEWLINENEWLINE .. versionadded:: 2.0NEWLINE """NEWLINE passNEWLINENEWLINE # login state managementNEWLINENEWLINE async def login(self, token: str) -> None:NEWLINE """|coro|NEWLINENEWLINE Logs in the client with the specified credentials andNEWLINE calls the :meth:`setup_hook`.NEWLINENEWLINENEWLINE ParametersNEWLINE -----------NEWLINE token: :class:`str`NEWLINE The authentication token. Do not prefix this token withNEWLINE anything as the library will do it for you.NEWLINENEWLINE RaisesNEWLINE ------NEWLINE LoginFailureNEWLINE The wrong credentials are passed.NEWLINE HTTPExceptionNEWLINE An unknown HTTP related error occurred,NEWLINE usually when it isn't 200 or the known incorrect credentialsNEWLINE passing status code.NEWLINE """NEWLINENEWLINE _log.info('logging in using static token')NEWLINENEWLINE await self._async_setup_hook()NEWLINENEWLINE data = await self.http.static_login(token.strip())NEWLINE self._connection.user = ClientUser(state=self._connection, data=data)NEWLINE await self.setup_hook()NEWLINENEWLINE async def connect(self, *, reconnect: bool = True) -> None:NEWLINE """|coro|NEWLINENEWLINE Creates a websocket connection and lets the websocket listenNEWLINE to messages from Discord. This is a loop that runs the entireNEWLINE event system and miscellaneous aspects of the library. ControlNEWLINE is not resumed until the WebSocket connection is terminated.NEWLINENEWLINE ParametersNEWLINE -----------NEWLINE reconnect: :class:`bool`NEWLINE If we should attempt reconnecting, either due to internetNEWLINE failure or a specific failure on Discord's part. CertainNEWLINE disconnects that lead to bad state will not be handled (such asNEWLINE invalid sharding payloads or bad tokens).NEWLINENEWLINE RaisesNEWLINE -------NEWLINE GatewayNotFoundNEWLINE If the gateway to connect to Discord is not found. Usually if thisNEWLINE is thrown then there is a Discord API outage.NEWLINE ConnectionClosedNEWLINE The websocket connection has been terminated.NEWLINE """NEWLINENEWLINE backoff = ExponentialBackoff()NEWLINE ws_params = {NEWLINE 'initial': True,NEWLINE 'shard_id': self.shard_id,NEWLINE }NEWLINE while not self.is_closed():NEWLINE try:NEWLINE coro = DiscordWebSocket.from_client(self, **ws_params)NEWLINE self.ws = await asyncio.wait_for(coro, timeout=60.0)NEWLINE ws_params['initial'] = FalseNEWLINE while True:NEWLINE await self.ws.poll_event()NEWLINE except ReconnectWebSocket as e:NEWLINE _log.info('Got a request to %s the websocket.', e.op)NEWLINE self.dispatch('disconnect')NEWLINE ws_params.update(sequence=self.ws.sequence, resume=e.resume, session=self.ws.session_id)NEWLINE continueNEWLINE except (NEWLINE OSError,NEWLINE HTTPException,NEWLINE GatewayNotFound,NEWLINE ConnectionClosed,NEWLINE aiohttp.ClientError,NEWLINE asyncio.TimeoutError,NEWLINE ) as exc:NEWLINENEWLINE self.dispatch('disconnect')NEWLINE if not reconnect:NEWLINE await self.close()NEWLINE if isinstance(exc, ConnectionClosed) and exc.code == 1000:NEWLINE # clean close, don't re-raise thisNEWLINE returnNEWLINE raiseNEWLINENEWLINE if self.is_closed():NEWLINE returnNEWLINENEWLINE # If we get connection reset by peer then try to RESUMENEWLINE if isinstance(exc, OSError) and exc.errno in (54, 10054):NEWLINE ws_params.update(sequence=self.ws.sequence, initial=False, resume=True, session=self.ws.session_id)NEWLINE continueNEWLINENEWLINE # We should only get this when an unhandled close code happens,NEWLINE # such as a clean disconnect (1000) or a bad state (bad token, no sharding, etc)NEWLINE # sometimes, discord sends us 1000 for unknown reasons so we should reconnectNEWLINE # regardless and rely on is_closed insteadNEWLINE if isinstance(exc, ConnectionClosed):NEWLINE if exc.code == 4014:NEWLINE raise PrivilegedIntentsRequired(exc.shard_id) from NoneNEWLINE if exc.code != 1000:NEWLINE await self.close()NEWLINE raiseNEWLINENEWLINE retry = backoff.delay()NEWLINE _log.exception("Attempting a reconnect in %.2fs", retry)NEWLINE await asyncio.sleep(retry)NEWLINE # Always try to RESUME the connectionNEWLINE # If the connection is not RESUME-able then the gateway will invalidate the session.NEWLINE # This is apparently what the official Discord client does.NEWLINE ws_params.update(sequence=self.ws.sequence, resume=True, session=self.ws.session_id)NEWLINENEWLINE async def close(self) -> None:NEWLINE """|coro|NEWLINENEWLINE Closes the connection to Discord.NEWLINE """NEWLINE if self._closed:NEWLINE returnNEWLINENEWLINE self._closed = TrueNEWLINENEWLINE for voice in self.voice_clients:NEWLINE try:NEWLINE await voice.disconnect(force=True)NEWLINE except Exception:NEWLINE # if an error happens during disconnects, disregard it.NEWLINE passNEWLINENEWLINE if self.ws is not None and self.ws.open:NEWLINE await self.ws.close(code=1000)NEWLINENEWLINE await self.http.close()NEWLINENEWLINE if self._ready is not MISSING:NEWLINE self._ready.clear()NEWLINENEWLINE self.loop = MISSINGNEWLINENEWLINE def clear(self) -> None:NEWLINE """Clears the internal state of the bot.NEWLINENEWLINE After this, the bot can be considered "re-opened", i.e. :meth:`is_closed`NEWLINE and :meth:`is_ready` both return ``False`` along with the bot's internalNEWLINE cache cleared.NEWLINE """NEWLINE self._closed = FalseNEWLINE self._ready.clear()NEWLINE self._connection.clear()NEWLINE self.http.recreate()NEWLINENEWLINE async def start(self, token: str, *, reconnect: bool = True) -> None:NEWLINE """|coro|NEWLINENEWLINE A shorthand coroutine for :meth:`login` + :meth:`connect`.NEWLINENEWLINE RaisesNEWLINE -------NEWLINE TypeErrorNEWLINE An unexpected keyword argument was received.NEWLINE """NEWLINE await self.login(token)NEWLINE await self.connect(reconnect=reconnect)NEWLINENEWLINE def run(self, *args: Any, **kwargs: Any) -> None:NEWLINE """A blocking call that abstracts away the event loopNEWLINE initialisation from you.NEWLINENEWLINE If you want more control over the event loop then thisNEWLINE function should not be used. Use :meth:`start` coroutineNEWLINE or :meth:`connect` + :meth:`login`.NEWLINENEWLINE Roughly Equivalent to: ::NEWLINENEWLINE try:NEWLINE asyncio.run(self.start(*args, **kwargs))NEWLINE except KeyboardInterrupt:NEWLINE returnNEWLINENEWLINE .. warning::NEWLINENEWLINE This function must be the last function to call due to the fact that itNEWLINE is blocking. That means that registration of events or anything beingNEWLINE called after this function call will not execute until it returns.NEWLINE """NEWLINENEWLINE async def runner():NEWLINE async with self:NEWLINE await self.start(*args, **kwargs)NEWLINENEWLINE try:NEWLINE asyncio.run(runner())NEWLINE except KeyboardInterrupt:NEWLINE # nothing to do hereNEWLINE # `asyncio.run` handles the loop cleanupNEWLINE # and `self.start` closes all sockets and the HTTPClient instance.NEWLINE returnNEWLINENEWLINE # propertiesNEWLINENEWLINE def is_closed(self) -> bool:NEWLINE """:class:`bool`: Indicates if the websocket connection is closed."""NEWLINE return self._closedNEWLINENEWLINE @propertyNEWLINE def activity(self) -> Optional[ActivityTypes]:NEWLINE """Optional[:class:`.BaseActivity`]: The activity being used uponNEWLINE logging in.NEWLINE """NEWLINE return create_activity(self._connection._activity, self._connection)NEWLINENEWLINE @activity.setterNEWLINE def activity(self, value: Optional[ActivityTypes]) -> None:NEWLINE if value is None:NEWLINE self._connection._activity = NoneNEWLINE elif isinstance(value, BaseActivity):NEWLINE # ConnectionState._activity is typehinted as ActivityPayload, we're passing Dict[str, Any]NEWLINE self._connection._activity = value.to_dict() # type: ignoreNEWLINE else:NEWLINE raise TypeError('activity must derive from BaseActivity.')NEWLINENEWLINE @propertyNEWLINE def status(self) -> Status:NEWLINE """:class:`.Status`:NEWLINE The status being used upon logging on to Discord.NEWLINENEWLINE .. versionadded: 2.0NEWLINE """NEWLINE if self._connection._status in set(state.value for state in Status):NEWLINE return Status(self._connection._status)NEWLINE return Status.onlineNEWLINENEWLINE @status.setterNEWLINE def status(self, value: Status) -> None:NEWLINE if value is Status.offline:NEWLINE self._connection._status = 'invisible'NEWLINE elif isinstance(value, Status):NEWLINE self._connection._status = str(value)NEWLINE else:NEWLINE raise TypeError('status must derive from Status.')NEWLINENEWLINE @propertyNEWLINE def allowed_mentions(self) -> Optional[AllowedMentions]:NEWLINE """Optional[:class:`~discord.AllowedMentions`]: The allowed mention configuration.NEWLINENEWLINE .. versionadded:: 1.4NEWLINE """NEWLINE return self._connection.allowed_mentionsNEWLINENEWLINE @allowed_mentions.setterNEWLINE def allowed_mentions(self, value: Optional[AllowedMentions]) -> None:NEWLINE if value is None or isinstance(value, AllowedMentions):NEWLINE self._connection.allowed_mentions = valueNEWLINE else:NEWLINE raise TypeError(f'allowed_mentions must be AllowedMentions not {value.__class__!r}')NEWLINENEWLINE @propertyNEWLINE def intents(self) -> Intents:NEWLINE """:class:`~discord.Intents`: The intents configured for this connection.NEWLINENEWLINE .. versionadded:: 1.5NEWLINE """NEWLINE return self._connection.intentsNEWLINENEWLINE # helpers/gettersNEWLINENEWLINE @propertyNEWLINE def users(self) -> List[User]:NEWLINE """List[:class:`~discord.User`]: Returns a list of all the users the bot can see."""NEWLINE return list(self._connection._users.values())NEWLINENEWLINE def get_channel(self, id: int, /) -> Optional[Union[GuildChannel, Thread, PrivateChannel]]:NEWLINE """Returns a channel or thread with the given ID.NEWLINENEWLINE .. versionchanged:: 2.0NEWLINENEWLINE ``id`` parameter is now positional-only.NEWLINENEWLINE ParametersNEWLINE -----------NEWLINE id: :class:`int`NEWLINE The ID to search for.NEWLINENEWLINE ReturnsNEWLINE --------NEWLINE Optional[Union[:class:`.abc.GuildChannel`, :class:`.Thread`, :class:`.abc.PrivateChannel`]]NEWLINE The returned channel or ``None`` if not found.NEWLINE """NEWLINE return self._connection.get_channel(id) # type: ignore - The cache contains all channel typesNEWLINENEWLINE def get_partial_messageable(self, id: int, *, type: Optional[ChannelType] = None) -> PartialMessageable:NEWLINE """Returns a partial messageable with the given channel ID.NEWLINENEWLINE This is useful if you have a channel_id but don't want to do an API callNEWLINE to send messages to it.NEWLINENEWLINE .. versionadded:: 2.0NEWLINENEWLINE ParametersNEWLINE -----------NEWLINE id: :class:`int`NEWLINE The channel ID to create a partial messageable for.NEWLINE type: Optional[:class:`.ChannelType`]NEWLINE The underlying channel type for the partial messageable.NEWLINENEWLINE ReturnsNEWLINE --------NEWLINE :class:`.PartialMessageable`NEWLINE The partial messageableNEWLINE """NEWLINE return PartialMessageable(state=self._connection, id=id, type=type)NEWLINENEWLINE def get_stage_instance(self, id: int, /) -> Optional[StageInstance]:NEWLINE """Returns a stage instance with the given stage channel ID.NEWLINENEWLINE .. versionadded:: 2.0NEWLINENEWLINE ParametersNEWLINE -----------NEWLINE id: :class:`int`NEWLINE The ID to search for.NEWLINENEWLINE ReturnsNEWLINE --------NEWLINE Optional[:class:`.StageInstance`]NEWLINE The stage instance or ``None`` if not found.NEWLINE """NEWLINE from .channel import StageChannelNEWLINENEWLINE channel = self._connection.get_channel(id)NEWLINENEWLINE if isinstance(channel, StageChannel):NEWLINE return channel.instanceNEWLINENEWLINE def get_guild(self, id: int, /) -> Optional[Guild]:NEWLINE """Returns a guild with the given ID.NEWLINENEWLINE .. versionchanged:: 2.0NEWLINENEWLINE ``id`` parameter is now positional-only.NEWLINENEWLINE ParametersNEWLINE -----------NEWLINE id: :class:`int`NEWLINE The ID to search for.NEWLINENEWLINE ReturnsNEWLINE --------NEWLINE Optional[:class:`.Guild`]NEWLINE The guild or ``None`` if not found.NEWLINE """NEWLINE return self._connection._get_guild(id)NEWLINENEWLINE def get_user(self, id: int, /) -> Optional[User]:NEWLINE """Returns a user with the given ID.NEWLINENEWLINE .. versionchanged:: 2.0NEWLINENEWLINE ``id`` parameter is now positional-only.NEWLINENEWLINE ParametersNEWLINE -----------NEWLINE id: :class:`int`NEWLINE The ID to search for.NEWLINENEWLINE ReturnsNEWLINE --------NEWLINE Optional[:class:`~discord.User`]NEWLINE The user or ``None`` if not found.NEWLINE """NEWLINE return self._connection.get_user(id)NEWLINENEWLINE def get_emoji(self, id: int, /) -> Optional[Emoji]:NEWLINE """Returns an emoji with the given ID.NEWLINENEWLINE .. versionchanged:: 2.0NEWLINENEWLINE ``id`` parameter is now positional-only.NEWLINENEWLINE ParametersNEWLINE -----------NEWLINE id: :class:`int`NEWLINE The ID to search for.NEWLINENEWLINE ReturnsNEWLINE --------NEWLINE Optional[:class:`.Emoji`]NEWLINE The custom emoji or ``None`` if not found.NEWLINE """NEWLINE return self._connection.get_emoji(id)NEWLINENEWLINE def get_sticker(self, id: int, /) -> Optional[GuildSticker]:NEWLINE """Returns a guild sticker with the given ID.NEWLINENEWLINE .. versionadded:: 2.0NEWLINENEWLINE .. note::NEWLINENEWLINE To retrieve standard stickers, use :meth:`.fetch_sticker`.NEWLINE or :meth:`.fetch_premium_sticker_packs`.NEWLINENEWLINE ReturnsNEWLINE --------NEWLINE Optional[:class:`.GuildSticker`]NEWLINE The sticker or ``None`` if not found.NEWLINE """NEWLINE return self._connection.get_sticker(id)NEWLINENEWLINE def get_all_channels(self) -> Generator[GuildChannel, None, None]:NEWLINE """A generator that retrieves every :class:`.abc.GuildChannel` the client can 'access'.NEWLINENEWLINE This is equivalent to: ::NEWLINENEWLINE for guild in client.guilds:NEWLINE for channel in guild.channels:NEWLINE yield channelNEWLINENEWLINE .. note::NEWLINENEWLINE Just because you receive a :class:`.abc.GuildChannel` does not mean thatNEWLINE you can communicate in said channel. :meth:`.abc.GuildChannel.permissions_for` shouldNEWLINE be used for that.NEWLINENEWLINE YieldsNEWLINE ------NEWLINE :class:`.abc.GuildChannel`NEWLINE A channel the client can 'access'.NEWLINE """NEWLINENEWLINE for guild in self.guilds:NEWLINE yield from guild.channelsNEWLINENEWLINE def get_all_members(self) -> Generator[Member, None, None]:NEWLINE """Returns a generator with every :class:`.Member` the client can see.NEWLINENEWLINE This is equivalent to: ::NEWLINENEWLINE for guild in client.guilds:NEWLINE for member in guild.members:NEWLINE yield memberNEWLINENEWLINE YieldsNEWLINE ------NEWLINE :class:`.Member`NEWLINE A member the client can see.NEWLINE """NEWLINE for guild in self.guilds:NEWLINE yield from guild.membersNEWLINENEWLINE # listeners/waitersNEWLINENEWLINE async def wait_until_ready(self) -> None:NEWLINE """|coro|NEWLINENEWLINE Waits until the client's internal cache is all ready.NEWLINENEWLINE .. warning::NEWLINENEWLINE Calling this inside :meth:`setup_hook` can lead to a deadlock.NEWLINE """NEWLINE if self._ready is not MISSING:NEWLINE await self._ready.wait()NEWLINENEWLINE def wait_for(NEWLINE self,NEWLINE event: str,NEWLINE *,NEWLINE check: Optional[Callable[..., bool]] = None,NEWLINE timeout: Optional[float] = None,NEWLINE ) -> Any:NEWLINE """|coro|NEWLINENEWLINE Waits for a WebSocket event to be dispatched.NEWLINENEWLINE This could be used to wait for a user to reply to a message,NEWLINE or to react to a message, or to edit a message in a self-containedNEWLINE way.NEWLINENEWLINE The ``timeout`` parameter is passed onto :func:`asyncio.wait_for`. By default,NEWLINE it does not timeout. Note that this does propagate theNEWLINE :exc:`asyncio.TimeoutError` for you in case of timeout and is provided forNEWLINE ease of use.NEWLINENEWLINE In case the event returns multiple arguments, a :class:`tuple` containing thoseNEWLINE arguments is returned instead. Please check theNEWLINE :ref:`documentation <discord-api-events>` for a list of events and theirNEWLINE parameters.NEWLINENEWLINE This function returns the **first event that meets the requirements**.NEWLINENEWLINE ExamplesNEWLINE ---------NEWLINENEWLINE Waiting for a user reply: ::NEWLINENEWLINE @client.eventNEWLINE async def on_message(message):NEWLINE if message.content.startswith('$greet'):NEWLINE channel = message.channelNEWLINE await channel.send('Say hello!')NEWLINENEWLINE def check(m):NEWLINE return m.content == 'hello' and m.channel == channelNEWLINENEWLINE msg = await client.wait_for('message', check=check)NEWLINE await channel.send(f'Hello {msg.author}!')NEWLINENEWLINE Waiting for a thumbs up reaction from the message author: ::NEWLINENEWLINE @client.eventNEWLINE async def on_message(message):NEWLINE if message.content.startswith('$thumb'):NEWLINE channel = message.channelNEWLINE await channel.send('Send me that \N{THUMBS UP SIGN} reaction, mate')NEWLINENEWLINE def check(reaction, user):NEWLINE return user == message.author and str(reaction.emoji) == '\N{THUMBS UP SIGN}'NEWLINENEWLINE try:NEWLINE reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)NEWLINE except asyncio.TimeoutError:NEWLINE await channel.send('\N{THUMBS DOWN SIGN}')NEWLINE else:NEWLINE await channel.send('\N{THUMBS UP SIGN}')NEWLINENEWLINENEWLINE ParametersNEWLINE ------------NEWLINE event: :class:`str`NEWLINE The event name, similar to the :ref:`event reference <discord-api-events>`,NEWLINE but without the ``on_`` prefix, to wait for.NEWLINE check: Optional[Callable[..., :class:`bool`]]NEWLINE A predicate to check what to wait for. The arguments must meet theNEWLINE parameters of the event being waited for.NEWLINE timeout: Optional[:class:`float`]NEWLINE The number of seconds to wait before timing out and raisingNEWLINE :exc:`asyncio.TimeoutError`.NEWLINENEWLINE RaisesNEWLINE -------NEWLINE asyncio.TimeoutErrorNEWLINE If a timeout is provided and it was reached.NEWLINENEWLINE ReturnsNEWLINE --------NEWLINE AnyNEWLINE Returns no arguments, a single argument, or a :class:`tuple` of multipleNEWLINE arguments that mirrors the parameters passed in theNEWLINE :ref:`event reference <discord-api-events>`.NEWLINE """NEWLINENEWLINE future = self.loop.create_future()NEWLINE if check is None:NEWLINENEWLINE def _check(*args):NEWLINE return TrueNEWLINENEWLINE check = _checkNEWLINENEWLINE ev = event.lower()NEWLINE try:NEWLINE listeners = self._listeners[ev]NEWLINE except KeyError:NEWLINE listeners = []NEWLINE self._listeners[ev] = listenersNEWLINENEWLINE listeners.append((future, check))NEWLINE return asyncio.wait_for(future, timeout)NEWLINENEWLINE # event registrationNEWLINENEWLINE def event(self, coro: Coro) -> Coro:NEWLINE """A decorator that registers an event to listen to.NEWLINENEWLINE You can find more info about the events on the :ref:`documentation below <discord-api-events>`.NEWLINENEWLINE The events must be a :ref:`coroutine <coroutine>`, if not, :exc:`TypeError` is raised.NEWLINENEWLINE ExampleNEWLINE ---------NEWLINENEWLINE .. code-block:: python3NEWLINENEWLINE @client.eventNEWLINE async def on_ready():NEWLINE print('Ready!')NEWLINENEWLINE RaisesNEWLINE --------NEWLINE TypeErrorNEWLINE The coroutine passed is not actually a coroutine.NEWLINE """NEWLINENEWLINE if not asyncio.iscoroutinefunction(coro):NEWLINE raise TypeError('event registered must be a coroutine function')NEWLINENEWLINE setattr(self, coro.__name__, coro)NEWLINE _log.debug('%s has successfully been registered as an event', coro.__name__)NEWLINE return coroNEWLINENEWLINE async def change_presence(NEWLINE self,NEWLINE *,NEWLINE activity: Optional[BaseActivity] = None,NEWLINE status: Optional[Status] = None,NEWLINE ) -> None:NEWLINE """|coro|NEWLINENEWLINE Changes the client's presence.NEWLINENEWLINE ExampleNEWLINE ---------NEWLINENEWLINE .. code-block:: python3NEWLINENEWLINE game = discord.Game("with the API")NEWLINE await client.change_presence(status=discord.Status.idle, activity=game)NEWLINENEWLINE .. versionchanged:: 2.0NEWLINE Removed the ``afk`` keyword-only parameter.NEWLINENEWLINE .. versionchanged:: 2.0NEWLINE This function will now raise :exc:`TypeError` instead ofNEWLINE ``InvalidArgument``.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE activity: Optional[:class:`.BaseActivity`]NEWLINE The activity being done. ``None`` if no currently active activity is done.NEWLINE status: Optional[:class:`.Status`]NEWLINE Indicates what status to change to. If ``None``, thenNEWLINE :attr:`.Status.online` is used.NEWLINENEWLINE RaisesNEWLINE ------NEWLINE TypeErrorNEWLINE If the ``activity`` parameter is not the proper type.NEWLINE """NEWLINENEWLINE if status is None:NEWLINE status_str = 'online'NEWLINE status = Status.onlineNEWLINE elif status is Status.offline:NEWLINE status_str = 'invisible'NEWLINE status = Status.offlineNEWLINE else:NEWLINE status_str = str(status)NEWLINENEWLINE await self.ws.change_presence(activity=activity, status=status_str)NEWLINENEWLINE for guild in self._connection.guilds:NEWLINE me = guild.meNEWLINE if me is None:NEWLINE continueNEWLINENEWLINE if activity is not None:NEWLINE me.activities = (activity,) # type: ignore - Type checker does not understand the downcast hereNEWLINE else:NEWLINE me.activities = ()NEWLINENEWLINE me.status = statusNEWLINENEWLINE # Guild stuffNEWLINENEWLINE async def fetch_guilds(NEWLINE self,NEWLINE *,NEWLINE limit: Optional[int] = 100,NEWLINE before: Optional[SnowflakeTime] = None,NEWLINE after: Optional[SnowflakeTime] = None,NEWLINE ) -> AsyncIterator[Guild]:NEWLINE """Retrieves an :term:`asynchronous iterator` that enables receiving your guilds.NEWLINENEWLINE .. note::NEWLINENEWLINE Using this, you will only receive :attr:`.Guild.owner`, :attr:`.Guild.icon`,NEWLINE :attr:`.Guild.id`, and :attr:`.Guild.name` per :class:`.Guild`.NEWLINENEWLINE .. note::NEWLINENEWLINE This method is an API call. For general usage, consider :attr:`guilds` instead.NEWLINENEWLINE ExamplesNEWLINE ---------NEWLINENEWLINE Usage ::NEWLINENEWLINE async for guild in client.fetch_guilds(limit=150):NEWLINE print(guild.name)NEWLINENEWLINE Flattening into a list ::NEWLINENEWLINE guilds = [guild async for guild in client.fetch_guilds(limit=150)]NEWLINE # guilds is now a list of Guild...NEWLINENEWLINE All parameters are optional.NEWLINENEWLINE ParametersNEWLINE -----------NEWLINE limit: Optional[:class:`int`]NEWLINE The number of guilds to retrieve.NEWLINE If ``None``, it retrieves every guild you have access to. Note, however,NEWLINE that this would make it a slow operation.NEWLINE Defaults to ``100``.NEWLINE before: Union[:class:`.abc.Snowflake`, :class:`datetime.datetime`]NEWLINE Retrieves guilds before this date or object.NEWLINE If a datetime is provided, it is recommended to use a UTC aware datetime.NEWLINE If the datetime is naive, it is assumed to be local time.NEWLINE after: Union[:class:`.abc.Snowflake`, :class:`datetime.datetime`]NEWLINE Retrieve guilds after this date or object.NEWLINE If a datetime is provided, it is recommended to use a UTC aware datetime.NEWLINE If the datetime is naive, it is assumed to be local time.NEWLINENEWLINE RaisesNEWLINE ------NEWLINE HTTPExceptionNEWLINE Getting the guilds failed.NEWLINENEWLINE YieldsNEWLINE --------NEWLINE :class:`.Guild`NEWLINE The guild with the guild data parsed.NEWLINE """NEWLINENEWLINE async def _before_strategy(retrieve, before, limit):NEWLINE before_id = before.id if before else NoneNEWLINE data = await self.http.get_guilds(retrieve, before=before_id)NEWLINENEWLINE if data:NEWLINE if limit is not None:NEWLINE limit -= len(data)NEWLINENEWLINE before = Object(id=int(data[-1]['id']))NEWLINENEWLINE return data, before, limitNEWLINENEWLINE async def _after_strategy(retrieve, after, limit):NEWLINE after_id = after.id if after else NoneNEWLINE data = await self.http.get_guilds(retrieve, after=after_id)NEWLINENEWLINE if data:NEWLINE if limit is not None:NEWLINE limit -= len(data)NEWLINENEWLINE after = Object(id=int(data[0]['id']))NEWLINENEWLINE return data, after, limitNEWLINENEWLINE if isinstance(before, datetime.datetime):NEWLINE before = Object(id=time_snowflake(before, high=False))NEWLINE if isinstance(after, datetime.datetime):NEWLINE after = Object(id=time_snowflake(after, high=True))NEWLINENEWLINE predicate: Optional[Callable[[GuildPayload], bool]] = NoneNEWLINE strategy, state = _before_strategy, beforeNEWLINENEWLINE if before and after:NEWLINE predicate = lambda m: int(m['id']) > after.idNEWLINE elif after:NEWLINE strategy, state = _after_strategy, afterNEWLINENEWLINE while True:NEWLINE retrieve = min(100 if limit is None else limit, 100)NEWLINE if retrieve < 1:NEWLINE returnNEWLINENEWLINE data, state, limit = await strategy(retrieve, state, limit)NEWLINENEWLINE # Terminate loop on next iteration; there's no data left after thisNEWLINE if len(data) < 100:NEWLINE limit = 0NEWLINENEWLINE if predicate:NEWLINE data = filter(predicate, data)NEWLINENEWLINE for raw_guild in data:NEWLINE yield Guild(state=self._connection, data=raw_guild)NEWLINENEWLINE async def fetch_template(self, code: Union[Template, str]) -> Template:NEWLINE """|coro|NEWLINENEWLINE Gets a :class:`.Template` from a discord.new URL or code.NEWLINENEWLINE ParametersNEWLINE -----------NEWLINE code: Union[:class:`.Template`, :class:`str`]NEWLINE The Discord Template Code or URL (must be a discord.new URL).NEWLINENEWLINE RaisesNEWLINE -------NEWLINE NotFoundNEWLINE The template is invalid.NEWLINE HTTPExceptionNEWLINE Getting the template failed.NEWLINENEWLINE ReturnsNEWLINE --------NEWLINE :class:`.Template`NEWLINE The template from the URL/code.NEWLINE """NEWLINE code = utils.resolve_template(code)NEWLINE data = await self.http.get_template(code)NEWLINE return Template(data=data, state=self._connection)NEWLINENEWLINE async def fetch_guild(self, guild_id: int, /, *, with_counts: bool = True) -> Guild:NEWLINE """|coro|NEWLINENEWLINE Retrieves a :class:`.Guild` from an ID.NEWLINENEWLINE .. note::NEWLINENEWLINE Using this, you will **not** receive :attr:`.Guild.channels`, :attr:`.Guild.members`,NEWLINE :attr:`.Member.activity` and :attr:`.Member.voice` per :class:`.Member`.NEWLINENEWLINE .. note::NEWLINENEWLINE This method is an API call. For general usage, consider :meth:`get_guild` instead.NEWLINENEWLINE .. versionchanged:: 2.0NEWLINENEWLINE ``guild_id`` parameter is now positional-only.NEWLINENEWLINENEWLINE ParametersNEWLINE -----------NEWLINE guild_id: :class:`int`NEWLINE The guild's ID to fetch from.NEWLINE with_counts: :class:`bool`NEWLINE Whether to include count information in the guild. This fills theNEWLINE :attr:`.Guild.approximate_member_count` and :attr:`.Guild.approximate_presence_count`NEWLINE attributes without needing any privileged intents. Defaults to ``True``.NEWLINENEWLINE .. versionadded:: 2.0NEWLINENEWLINE RaisesNEWLINE ------NEWLINE ForbiddenNEWLINE You do not have access to the guild.NEWLINE HTTPExceptionNEWLINE Getting the guild failed.NEWLINENEWLINE ReturnsNEWLINE --------NEWLINE :class:`.Guild`NEWLINE The guild from the ID.NEWLINE """NEWLINE data = await self.http.get_guild(guild_id, with_counts=with_counts)NEWLINE return Guild(data=data, state=self._connection)NEWLINENEWLINE async def create_guild(NEWLINE self,NEWLINE *,NEWLINE name: str,NEWLINE icon: bytes = MISSING,NEWLINE code: str = MISSING,NEWLINE ) -> Guild:NEWLINE """|coro|NEWLINENEWLINE Creates a :class:`.Guild`.NEWLINENEWLINE Bot accounts in more than 10 guilds are not allowed to create guilds.NEWLINENEWLINE .. versionchanged:: 2.0NEWLINE ``name`` and ``icon`` parameters are now keyword-only. The `region`` parameter has been removed.NEWLINENEWLINE .. versionchanged:: 2.0NEWLINE This function will now raise :exc:`ValueError` instead ofNEWLINE ``InvalidArgument``.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE name: :class:`str`NEWLINE The name of the guild.NEWLINE icon: Optional[:class:`bytes`]NEWLINE The :term:`py:bytes-like object` representing the icon. See :meth:`.ClientUser.edit`NEWLINE for more details on what is expected.NEWLINE code: :class:`str`NEWLINE The code for a template to create the guild with.NEWLINENEWLINE .. versionadded:: 1.4NEWLINENEWLINE RaisesNEWLINE ------NEWLINE HTTPExceptionNEWLINE Guild creation failed.NEWLINE ValueErrorNEWLINE Invalid icon image format given. Must be PNG or JPG.NEWLINENEWLINE ReturnsNEWLINE -------NEWLINE :class:`.Guild`NEWLINE The guild created. This is not the same guild that isNEWLINE added to cache.NEWLINE """NEWLINE if icon is not MISSING:NEWLINE icon_base64 = utils._bytes_to_base64_data(icon)NEWLINE else:NEWLINE icon_base64 = NoneNEWLINENEWLINE if code:NEWLINE data = await self.http.create_from_template(code, name, icon_base64)NEWLINE else:NEWLINE data = await self.http.create_guild(name, icon_base64)NEWLINE return Guild(data=data, state=self._connection)NEWLINENEWLINE async def fetch_stage_instance(self, channel_id: int, /) -> StageInstance:NEWLINE """|coro|NEWLINENEWLINE Gets a :class:`.StageInstance` for a stage channel id.NEWLINENEWLINE .. versionadded:: 2.0NEWLINENEWLINE ParametersNEWLINE -----------NEWLINE channel_id: :class:`int`NEWLINE The stage channel ID.NEWLINENEWLINE RaisesNEWLINE -------NEWLINE NotFoundNEWLINE The stage instance or channel could not be found.NEWLINE HTTPExceptionNEWLINE Getting the stage instance failed.NEWLINENEWLINE ReturnsNEWLINE --------NEWLINE :class:`.StageInstance`NEWLINE The stage instance from the stage channel ID.NEWLINE """NEWLINE data = await self.http.get_stage_instance(channel_id)NEWLINE guild = self.get_guild(int(data['guild_id']))NEWLINE # Guild can technically be None here but this is being explicitly silenced right now.NEWLINE return StageInstance(guild=guild, state=self._connection, data=data) # type: ignoreNEWLINENEWLINE # Invite managementNEWLINENEWLINE async def fetch_invite(NEWLINE self,NEWLINE url: Union[Invite, str],NEWLINE *,NEWLINE with_counts: bool = True,NEWLINE with_expiration: bool = True,NEWLINE scheduled_event_id: Optional[int] = None,NEWLINE ) -> Invite:NEWLINE """|coro|NEWLINENEWLINE Gets an :class:`.Invite` from a discord.gg URL or ID.NEWLINENEWLINE .. note::NEWLINENEWLINE If the invite is for a guild you have not joined, the guild and channelNEWLINE attributes of the returned :class:`.Invite` will be :class:`.PartialInviteGuild` andNEWLINE :class:`.PartialInviteChannel` respectively.NEWLINENEWLINE ParametersNEWLINE -----------NEWLINE url: Union[:class:`.Invite`, :class:`str`]NEWLINE The Discord invite ID or URL (must be a discord.gg URL).NEWLINE with_counts: :class:`bool`NEWLINE Whether to include count information in the invite. This fills theNEWLINE :attr:`.Invite.approximate_member_count` and :attr:`.Invite.approximate_presence_count`NEWLINE fields.NEWLINE with_expiration: :class:`bool`NEWLINE Whether to include the expiration date of the invite. This fills theNEWLINE :attr:`.Invite.expires_at` field.NEWLINENEWLINE .. versionadded:: 2.0NEWLINE scheduled_event_id: Optional[:class:`int`]NEWLINE The ID of the scheduled event this invite is for.NEWLINENEWLINE .. note::NEWLINENEWLINE It is not possible to provide a url that contains an ``event_id`` parameterNEWLINE when using this parameter.NEWLINENEWLINE .. versionadded:: 2.0NEWLINENEWLINE RaisesNEWLINE -------NEWLINE ValueErrorNEWLINE The url contains an ``event_id``, but ``scheduled_event_id`` has also been provided.NEWLINE NotFoundNEWLINE The invite has expired or is invalid.NEWLINE HTTPExceptionNEWLINE Getting the invite failed.NEWLINENEWLINE ReturnsNEWLINE --------NEWLINE :class:`.Invite`NEWLINE The invite from the URL/ID.NEWLINE """NEWLINENEWLINE resolved = utils.resolve_invite(url)NEWLINENEWLINE if scheduled_event_id and resolved.event:NEWLINE raise ValueError('Cannot specify scheduled_event_id and contain an event_id in the url.')NEWLINENEWLINE scheduled_event_id = scheduled_event_id or resolved.eventNEWLINENEWLINE data = await self.http.get_invite(NEWLINE resolved.code,NEWLINE with_counts=with_counts,NEWLINE with_expiration=with_expiration,NEWLINE guild_scheduled_event_id=scheduled_event_id,NEWLINE )NEWLINE return Invite.from_incomplete(state=self._connection, data=data)NEWLINENEWLINE async def delete_invite(self, invite: Union[Invite, str], /) -> None:NEWLINE """|coro|NEWLINENEWLINE Revokes an :class:`.Invite`, URL, or ID to an invite.NEWLINENEWLINE You must have the :attr:`~.Permissions.manage_channels` permission inNEWLINE the associated guild to do this.NEWLINENEWLINE .. versionchanged:: 2.0NEWLINENEWLINE ``invite`` parameter is now positional-only.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE invite: Union[:class:`.Invite`, :class:`str`]NEWLINE The invite to revoke.NEWLINENEWLINE RaisesNEWLINE -------NEWLINE ForbiddenNEWLINE You do not have permissions to revoke invites.NEWLINE NotFoundNEWLINE The invite is invalid or expired.NEWLINE HTTPExceptionNEWLINE Revoking the invite failed.NEWLINE """NEWLINENEWLINE resolved = utils.resolve_invite(invite)NEWLINE await self.http.delete_invite(resolved.code)NEWLINENEWLINE # Miscellaneous stuffNEWLINENEWLINE async def fetch_widget(self, guild_id: int, /) -> Widget:NEWLINE """|coro|NEWLINENEWLINE Gets a :class:`.Widget` from a guild ID.NEWLINENEWLINE .. note::NEWLINENEWLINE The guild must have the widget enabled to get this information.NEWLINENEWLINE .. versionchanged:: 2.0NEWLINENEWLINE ``guild_id`` parameter is now positional-only.NEWLINENEWLINE ParametersNEWLINE -----------NEWLINE guild_id: :class:`int`NEWLINE The ID of the guild.NEWLINENEWLINE RaisesNEWLINE -------NEWLINE ForbiddenNEWLINE The widget for this guild is disabled.NEWLINE HTTPExceptionNEWLINE Retrieving the widget failed.NEWLINENEWLINE ReturnsNEWLINE --------NEWLINE :class:`.Widget`NEWLINE The guild's widget.NEWLINE """NEWLINE data = await self.http.get_widget(guild_id)NEWLINENEWLINE return Widget(state=self._connection, data=data)NEWLINENEWLINE async def application_info(self) -> AppInfo:NEWLINE """|coro|NEWLINENEWLINE Retrieves the bot's application information.NEWLINENEWLINE RaisesNEWLINE -------NEWLINE HTTPExceptionNEWLINE Retrieving the information failed somehow.NEWLINENEWLINE ReturnsNEWLINE --------NEWLINE :class:`.AppInfo`NEWLINE The bot's application information.NEWLINE """NEWLINE data = await self.http.application_info()NEWLINE if 'rpc_origins' not in data:NEWLINE data['rpc_origins'] = NoneNEWLINE return AppInfo(self._connection, data)NEWLINENEWLINE async def fetch_user(self, user_id: int, /) -> User:NEWLINE """|coro|NEWLINENEWLINE Retrieves a :class:`~discord.User` based on their ID.NEWLINE You do not have to share any guilds with the user to get this information,NEWLINE however many operations do require that you do.NEWLINENEWLINE .. note::NEWLINENEWLINE This method is an API call. If you have :attr:`discord.Intents.members` and member cache enabled, consider :meth:`get_user` instead.NEWLINENEWLINE .. versionchanged:: 2.0NEWLINENEWLINE ``user_id`` parameter is now positional-only.NEWLINENEWLINE ParametersNEWLINE -----------NEWLINE user_id: :class:`int`NEWLINE The user's ID to fetch from.NEWLINENEWLINE RaisesNEWLINE -------NEWLINE NotFoundNEWLINE A user with this ID does not exist.NEWLINE HTTPExceptionNEWLINE Fetching the user failed.NEWLINENEWLINE ReturnsNEWLINE --------NEWLINE :class:`~discord.User`NEWLINE The user you requested.NEWLINE """NEWLINE data = await self.http.get_user(user_id)NEWLINE return User(state=self._connection, data=data)NEWLINENEWLINE async def fetch_channel(self, channel_id: int, /) -> Union[GuildChannel, PrivateChannel, Thread]:NEWLINE """|coro|NEWLINENEWLINE Retrieves a :class:`.abc.GuildChannel`, :class:`.abc.PrivateChannel`, or :class:`.Thread` with the specified ID.NEWLINENEWLINE .. note::NEWLINENEWLINE This method is an API call. For general usage, consider :meth:`get_channel` instead.NEWLINENEWLINE .. versionadded:: 1.2NEWLINENEWLINE .. versionchanged:: 2.0NEWLINENEWLINE ``channel_id`` parameter is now positional-only.NEWLINENEWLINE RaisesNEWLINE -------NEWLINE InvalidDataNEWLINE An unknown channel type was received from Discord.NEWLINE HTTPExceptionNEWLINE Retrieving the channel failed.NEWLINE NotFoundNEWLINE Invalid Channel ID.NEWLINE ForbiddenNEWLINE You do not have permission to fetch this channel.NEWLINENEWLINE ReturnsNEWLINE --------NEWLINE Union[:class:`.abc.GuildChannel`, :class:`.abc.PrivateChannel`, :class:`.Thread`]NEWLINE The channel from the ID.NEWLINE """NEWLINE data = await self.http.get_channel(channel_id)NEWLINENEWLINE factory, ch_type = _threaded_channel_factory(data['type'])NEWLINE if factory is None:NEWLINE raise InvalidData('Unknown channel type {type} for channel ID {id}.'.format_map(data))NEWLINENEWLINE if ch_type in (ChannelType.group, ChannelType.private):NEWLINE # the factory will be a DMChannel or GroupChannel hereNEWLINE channel = factory(me=self.user, data=data, state=self._connection) # type: ignoreNEWLINE else:NEWLINE # the factory can't be a DMChannel or GroupChannel hereNEWLINE guild_id = int(data['guild_id']) # type: ignoreNEWLINE guild = self.get_guild(guild_id) or Object(id=guild_id)NEWLINE # GuildChannels expect a Guild, we may be passing an ObjectNEWLINE channel = factory(guild=guild, state=self._connection, data=data) # type: ignoreNEWLINENEWLINE return channelNEWLINENEWLINE async def fetch_webhook(self, webhook_id: int, /) -> Webhook:NEWLINE """|coro|NEWLINENEWLINE Retrieves a :class:`.Webhook` with the specified ID.NEWLINENEWLINE .. versionchanged:: 2.0NEWLINENEWLINE ``webhook_id`` parameter is now positional-only.NEWLINENEWLINE RaisesNEWLINE --------NEWLINE HTTPExceptionNEWLINE Retrieving the webhook failed.NEWLINE NotFoundNEWLINE Invalid webhook ID.NEWLINE ForbiddenNEWLINE You do not have permission to fetch this webhook.NEWLINENEWLINE ReturnsNEWLINE ---------NEWLINE :class:`.Webhook`NEWLINE The webhook you requested.NEWLINE """NEWLINE data = await self.http.get_webhook(webhook_id)NEWLINE return Webhook.from_state(data, state=self._connection)NEWLINENEWLINE async def fetch_sticker(self, sticker_id: int, /) -> Union[StandardSticker, GuildSticker]:NEWLINE """|coro|NEWLINENEWLINE Retrieves a :class:`.Sticker` with the specified ID.NEWLINENEWLINE .. versionadded:: 2.0NEWLINENEWLINE RaisesNEWLINE --------NEWLINE HTTPExceptionNEWLINE Retrieving the sticker failed.NEWLINE NotFoundNEWLINE Invalid sticker ID.NEWLINENEWLINE ReturnsNEWLINE --------NEWLINE Union[:class:`.StandardSticker`, :class:`.GuildSticker`]NEWLINE The sticker you requested.NEWLINE """NEWLINE data = await self.http.get_sticker(sticker_id)NEWLINE cls, _ = _sticker_factory(data['type'])NEWLINE # The type checker is not smart enough to figure out the constructor is correctNEWLINE return cls(state=self._connection, data=data) # type: ignoreNEWLINENEWLINE async def fetch_premium_sticker_packs(self) -> List[StickerPack]:NEWLINE """|coro|NEWLINENEWLINE Retrieves all available premium sticker packs.NEWLINENEWLINE .. versionadded:: 2.0NEWLINENEWLINE RaisesNEWLINE -------NEWLINE HTTPExceptionNEWLINE Retrieving the sticker packs failed.NEWLINENEWLINE ReturnsNEWLINE ---------NEWLINE List[:class:`.StickerPack`]NEWLINE All available premium sticker packs.NEWLINE """NEWLINE data = await self.http.list_premium_sticker_packs()NEWLINE return [StickerPack(state=self._connection, data=pack) for pack in data['sticker_packs']]NEWLINENEWLINE async def create_dm(self, user: Snowflake) -> DMChannel:NEWLINE """|coro|NEWLINENEWLINE Creates a :class:`.DMChannel` with this user.NEWLINENEWLINE This should be rarely called, as this is done transparently for mostNEWLINE people.NEWLINENEWLINE .. versionadded:: 2.0NEWLINENEWLINE ParametersNEWLINE -----------NEWLINE user: :class:`~discord.abc.Snowflake`NEWLINE The user to create a DM with.NEWLINENEWLINE ReturnsNEWLINE -------NEWLINE :class:`.DMChannel`NEWLINE The channel that was created.NEWLINE """NEWLINE state = self._connectionNEWLINE found = state._get_private_channel_by_user(user.id)NEWLINE if found:NEWLINE return foundNEWLINENEWLINE data = await state.http.start_private_message(user.id)NEWLINE return state.add_dm_channel(data)NEWLINENEWLINE def add_view(self, view: View, *, message_id: Optional[int] = None) -> None:NEWLINE """Registers a :class:`~discord.ui.View` for persistent listening.NEWLINENEWLINE This method should be used for when a view is comprised of componentsNEWLINE that last longer than the lifecycle of the program.NEWLINENEWLINE .. versionadded:: 2.0NEWLINENEWLINE ParametersNEWLINE ------------NEWLINE view: :class:`discord.ui.View`NEWLINE The view to register for dispatching.NEWLINE message_id: Optional[:class:`int`]NEWLINE The message ID that the view is attached to. This is currently used toNEWLINE refresh the view's state during message update events. If not givenNEWLINE then message update events are not propagated for the view.NEWLINENEWLINE RaisesNEWLINE -------NEWLINE TypeErrorNEWLINE A view was not passed.NEWLINE ValueErrorNEWLINE The view is not persistent. A persistent view has no timeoutNEWLINE and all their components have an explicitly provided custom_id.NEWLINE """NEWLINENEWLINE if not isinstance(view, View):NEWLINE raise TypeError(f'expected an instance of View not {view.__class__!r}')NEWLINENEWLINE if not view.is_persistent():NEWLINE raise ValueError('View is not persistent. Items need to have a custom_id set and View must have no timeout')NEWLINENEWLINE self._connection.store_view(view, message_id)NEWLINENEWLINE @propertyNEWLINE def persistent_views(self) -> Sequence[View]:NEWLINE """Sequence[:class:`.View`]: A sequence of persistent views added to the client.NEWLINENEWLINE .. versionadded:: 2.0NEWLINE """NEWLINE return self._connection.persistent_viewsNEWLINE