text
stringlengths
28
881k
# -*- coding: utf-8 -*-NEWLINE# Generated by Django 1.11.20 on 2019-02-25 16:08NEWLINEfrom __future__ import unicode_literalsNEWLINENEWLINEimport django.contrib.postgres.fields.hstoreNEWLINEfrom django.db import migrations, modelsNEWLINENEWLINENEWLINEclass Migration(migrations.Migration):NEWLINENEWLINE dependencies = [("research", "0004_public_flag")]NEWLINENEWLINE operations = [NEWLINE migrations.CreateModel(NEWLINE name="Classification",NEWLINE fields=[NEWLINE (NEWLINE "id",NEWLINE models.AutoField(NEWLINE auto_created=True,NEWLINE primary_key=True,NEWLINE serialize=False,NEWLINE verbose_name="ID",NEWLINE ),NEWLINE ),NEWLINE ("name", django.contrib.postgres.fields.hstore.HStoreField()),NEWLINE ],NEWLINE options={"db_table": "research_classification", "managed": False},NEWLINE ),NEWLINE migrations.CreateModel(NEWLINE name="Education",NEWLINE fields=[NEWLINE (NEWLINE "id",NEWLINE models.AutoField(NEWLINE auto_created=True,NEWLINE primary_key=True,NEWLINE serialize=False,NEWLINE verbose_name="ID",NEWLINE ),NEWLINE ),NEWLINE ("name", django.contrib.postgres.fields.hstore.HStoreField()),NEWLINE ],NEWLINE options={"db_table": "research_education", "managed": False},NEWLINE ),NEWLINE migrations.CreateModel(NEWLINE name="Expertise",NEWLINE fields=[NEWLINE (NEWLINE "id",NEWLINE models.AutoField(NEWLINE auto_created=True,NEWLINE primary_key=True,NEWLINE serialize=False,NEWLINE verbose_name="ID",NEWLINE ),NEWLINE ),NEWLINE ("name", django.contrib.postgres.fields.hstore.HStoreField()),NEWLINE ],NEWLINE options={"db_table": "research_expertise", "managed": False},NEWLINE ),NEWLINE migrations.CreateModel(NEWLINE name="Knowledge",NEWLINE fields=[NEWLINE (NEWLINE "id",NEWLINE models.AutoField(NEWLINE auto_created=True,NEWLINE primary_key=True,NEWLINE serialize=False,NEWLINE verbose_name="ID",NEWLINE ),NEWLINE ),NEWLINE ("name", django.contrib.postgres.fields.hstore.HStoreField()),NEWLINE ],NEWLINE options={"db_table": "research_knowledge", "managed": False},NEWLINE ),NEWLINE migrations.CreateModel(NEWLINE name="Program",NEWLINE fields=[NEWLINE (NEWLINE "id",NEWLINE models.AutoField(NEWLINE auto_created=True,NEWLINE primary_key=True,NEWLINE serialize=False,NEWLINE verbose_name="ID",NEWLINE ),NEWLINE ),NEWLINE ("name", models.CharField(blank=True, max_length=256, null=True)),NEWLINE ("active", models.BooleanField()),NEWLINE ],NEWLINE options={"db_table": "research_program", "managed": False},NEWLINE ),NEWLINE migrations.CreateModel(NEWLINE name="PublicationAuthorship",NEWLINE fields=[NEWLINE (NEWLINE "id",NEWLINE models.AutoField(NEWLINE auto_created=True,NEWLINE primary_key=True,NEWLINE serialize=False,NEWLINE verbose_name="ID",NEWLINE ),NEWLINE ),NEWLINE ("name", django.contrib.postgres.fields.hstore.HStoreField()),NEWLINE ],NEWLINE options={"db_table": "research_publicationauthorship", "managed": False},NEWLINE ),NEWLINE migrations.CreateModel(NEWLINE name="PublicationOrganization",NEWLINE fields=[NEWLINE (NEWLINE "id",NEWLINE models.CharField(max_length=256, primary_key=True, serialize=False),NEWLINE ),NEWLINE ("assigned", models.DateTimeField(blank=True, null=True)),NEWLINE ],NEWLINE options={"db_table": "research_publicationorganization", "managed": False},NEWLINE ),NEWLINE ]NEWLINE
import argparseNEWLINEimport templateNEWLINENEWLINEparser = argparse.ArgumentParser(description='EDSR and MDSR')NEWLINENEWLINEparser.add_argument('--debug', action='store_true',NEWLINE help='Enables debug mode')NEWLINEparser.add_argument('--template', default='.',NEWLINE help='You can set various templates in option.py')NEWLINENEWLINE# Hardware specificationsNEWLINEparser.add_argument('--n_threads', type=int, default=6,NEWLINE help='number of threads for data loading')NEWLINEparser.add_argument('--cpu', action='store_true',NEWLINE help='use cpu only')NEWLINEparser.add_argument('--n_GPUs', type=int, default=1,NEWLINE help='number of GPUs')NEWLINEparser.add_argument('--seed', type=int, default=1,NEWLINE help='random seed')NEWLINENEWLINE# Data specificationsNEWLINEparser.add_argument('--dir_data', type=str, default='../../../dataset',NEWLINE help='dataset directory')NEWLINEparser.add_argument('--dir_demo', type=str, default='../test',NEWLINE help='demo image directory')NEWLINEparser.add_argument('--data_train', type=str, default='DIV2K',NEWLINE help='train dataset name')NEWLINEparser.add_argument('--data_test', type=str, default='DIV2K',NEWLINE help='test dataset name')NEWLINEparser.add_argument('--data_range', type=str, default='1-800/801-810',NEWLINE help='train/test data range')NEWLINEparser.add_argument('--ext', type=str, default='sep',NEWLINE help='dataset file extension')NEWLINEparser.add_argument('--scale', type=str, default='4',NEWLINE help='super resolution scale')NEWLINEparser.add_argument('--patch_size', type=int, default=192,NEWLINE help='output patch size')NEWLINEparser.add_argument('--rgb_range', type=int, default=255,NEWLINE help='maximum value of RGB')NEWLINEparser.add_argument('--n_colors', type=int, default=3,NEWLINE help='number of color channels to use')NEWLINEparser.add_argument('--chop', action='store_true',NEWLINE help='enable memory-efficient forward')NEWLINEparser.add_argument('--no_augment', action='store_true',NEWLINE help='do not use data augmentation')NEWLINENEWLINE# Inference time data augmentationNEWLINEparser.add_argument('--chop-size', type=int, nargs='+', default=[400],NEWLINE help='patch size at inference time')NEWLINEparser.add_argument('--shave-size', type=int, nargs='+', default=[10],NEWLINE help='shave size at inference time')NEWLINEparser.add_argument('--self_ensemble', action='store_true',NEWLINE help='use self-ensemble method for test')NEWLINEparser.add_argument('--guided_filtering', action='store_true',NEWLINE help='use guided image filter for test')NEWLINEparser.add_argument('--guided-radius', type=int, default=10,NEWLINE help='guided filter radius')NEWLINEparser.add_argument('--guided-eps', type=int, default=10,NEWLINE help='guided filter eps')NEWLINEparser.add_argument('--guided-type', type=str, default='RGB',NEWLINE help='guided image type')NEWLINE# Model specificationsNEWLINEparser.add_argument('--model', default='EDSR',NEWLINE help='model name')NEWLINENEWLINEparser.add_argument('--act', type=str, default='relu',NEWLINE help='activation function')NEWLINEparser.add_argument('--pre_train', type=str, default='',NEWLINE help='pre-trained model directory')NEWLINEparser.add_argument('--pre_optimizer', type=str, default='',NEWLINE help='pre-trained optimizer directory')NEWLINEparser.add_argument('--extend', type=str, default='.',NEWLINE help='pre-trained model directory')NEWLINEparser.add_argument('--n_resblocks', type=int, default=16,NEWLINE help='number of residual blocks')NEWLINEparser.add_argument('--n_feats', type=int, default=64,NEWLINE help='number of feature maps')NEWLINEparser.add_argument('--res_scale', type=float, default=1,NEWLINE help='residual scaling')NEWLINEparser.add_argument('--shift_mean', default=True,NEWLINE help='subtract pixel mean from the input')NEWLINEparser.add_argument('--dilation', action='store_true',NEWLINE help='use dilated convolution')NEWLINEparser.add_argument('--precision', type=str, default='single',NEWLINE choices=('single', 'half'),NEWLINE help='FP precision for test (single | half)')NEWLINENEWLINE# Option for Residual dense network (RDN)NEWLINEparser.add_argument('--G0', type=int, default=64,NEWLINE help='default number of filters. (Use in RDN)')NEWLINEparser.add_argument('--RDNkSize', type=int, default=3,NEWLINE help='default kernel size. (Use in RDN)')NEWLINEparser.add_argument('--RDNconfig', type=str, default='B',NEWLINE help='parameters config of RDN. (Use in RDN)')NEWLINENEWLINE# Option for Residual channel attention network (RCAN)NEWLINEparser.add_argument('--n_resgroups', type=int, default=10,NEWLINE help='number of residual groups')NEWLINEparser.add_argument('--reduction', type=int, default=16,NEWLINE help='number of feature maps reduction')NEWLINENEWLINE# Training specificationsNEWLINEparser.add_argument('--reset', action='store_true',NEWLINE help='reset the training')NEWLINEparser.add_argument('--test_every', type=int, default=1000,NEWLINE help='do test per every N batches')NEWLINEparser.add_argument('--test_epoch', type=int, default=0,NEWLINE help='do test per every N epochs, default is 0, training without testing')NEWLINEparser.add_argument('--load_log', type=str, default='loss',NEWLINE help='load log file to cal epoch number')NEWLINEparser.add_argument('--epochs', type=int, default=300,NEWLINE help='number of epochs to train')NEWLINEparser.add_argument('--batch_size', type=int, default=16,NEWLINE help='input batch size for training')NEWLINEparser.add_argument('--split_batch', type=int, default=1,NEWLINE help='split the batch into smaller chunks')NEWLINEparser.add_argument('--test_only', action='store_true',NEWLINE help='set this option to test the model')NEWLINEparser.add_argument('--gan_k', type=int, default=1,NEWLINE help='k value for adversarial loss')NEWLINENEWLINE# Optimization specificationsNEWLINEparser.add_argument('--lr', type=float, default=1e-4,NEWLINE help='learning rate')NEWLINEparser.add_argument('--decay', type=str, default='200',NEWLINE help='learning rate decay type')NEWLINEparser.add_argument('--gamma', type=float, default=0.5,NEWLINE help='learning rate decay factor for step decay')NEWLINEparser.add_argument('--optimizer', default='ADAM',NEWLINE choices=('SGD', 'ADAM', 'RMSprop'),NEWLINE help='optimizer to use (SGD | ADAM | RMSprop)')NEWLINEparser.add_argument('--momentum', type=float, default=0.9,NEWLINE help='SGD momentum')NEWLINEparser.add_argument('--betas', type=tuple, default=(0.9, 0.999),NEWLINE help='ADAM beta')NEWLINEparser.add_argument('--epsilon', type=float, default=1e-8,NEWLINE help='ADAM epsilon for numerical stability')NEWLINEparser.add_argument('--weight_decay', type=float, default=0,NEWLINE help='weight decay')NEWLINEparser.add_argument('--gclip', type=float, default=0,NEWLINE help='gradient clipping threshold (0 = no clipping)')NEWLINEparser.add_argument('--deep-supervision', default=False,NEWLINE help='if using deep supervision')NEWLINEparser.add_argument('--deep-supervision-factor', type=float, default=0.2,NEWLINE help='deep supervision factor')NEWLINE# Loss specificationsNEWLINEparser.add_argument('--loss', type=str, default='1*L1',NEWLINE help='loss function configuration')NEWLINEparser.add_argument('--skip_threshold', type=float, default='1e8',NEWLINE help='skipping batch that has large error')NEWLINEparser.add_argument('--l1-clip-min', type=float, default=0.0,NEWLINE help='torch.clamp(||sr-hr||, min, max)')NEWLINEparser.add_argument('--l1-clip-max', type=float, default=10.0,NEWLINE help='torch.clamp(||sr-hr||, min, max)')NEWLINENEWLINE# Log specificationsNEWLINEparser.add_argument('--save', type=str, default='test',NEWLINE help='file name to save')NEWLINEparser.add_argument('--load', type=str, default='',NEWLINE help='file name to load')NEWLINEparser.add_argument('--resume', type=int, default=0,NEWLINE help='resume from specific checkpoint')NEWLINEparser.add_argument('--save_models', action='store_true',NEWLINE help='save all intermediate models')NEWLINEparser.add_argument('--print_every', type=int, default=100,NEWLINE help='how many batches to wait before logging training status')NEWLINEparser.add_argument('--save_results', action='store_true',NEWLINE help='save output results')NEWLINEparser.add_argument('--save_gt', action='store_true',NEWLINE help='save low-resolution and high-resolution images together')NEWLINENEWLINEargs = parser.parse_args()NEWLINEtemplate.set_template(args)NEWLINENEWLINEargs.scale = list(map(lambda x: int(x), args.scale.split('+')))NEWLINEargs.data_train = args.data_train.split('+')NEWLINEargs.data_test = args.data_test.split('+')NEWLINENEWLINEif args.epochs == 0:NEWLINE args.epochs = 1e8NEWLINENEWLINEfor arg in vars(args):NEWLINE if vars(args)[arg] == 'True':NEWLINE vars(args)[arg] = TrueNEWLINE elif vars(args)[arg] == 'False':NEWLINE vars(args)[arg] = FalseNEWLINENEWLINE
# -*- coding: utf-8 -*-NEWLINE#NEWLINE# Copyright (C) 2005-2007 Christopher Lenz <cmlenz@gmx.de>NEWLINE# Copyright (C) 2007-2010 Edgewall SoftwareNEWLINE# All rights reserved.NEWLINE#NEWLINE# This software is licensed as described in the file COPYING, whichNEWLINE# you should have received as part of this distribution. The termsNEWLINE# are also available at http://bitten.edgewall.org/wiki/License.NEWLINENEWLINE"""Implementation of the Bitten web interface."""NEWLINENEWLINEimport posixpathNEWLINEimport reNEWLINEimport timeNEWLINEfrom StringIO import StringIONEWLINEfrom datetime import datetimeNEWLINENEWLINEimport pkg_resourcesNEWLINEfrom genshi.builder import tagNEWLINEfrom trac.attachment import AttachmentModule, AttachmentNEWLINEfrom trac.core import *NEWLINEfrom trac.config import OptionNEWLINEfrom trac.mimeview.api import ContextNEWLINEfrom trac.perm import PermissionErrorNEWLINEfrom trac.resource import Resource, get_resource_urlNEWLINEfrom trac.timeline import ITimelineEventProviderNEWLINEfrom trac.util import escape, pretty_timedelta, format_datetime, shorten_line, \NEWLINE Markup, arityNEWLINEfrom trac.util.datefmt import to_timestamp, to_datetime, utcNEWLINEfrom trac.util.html import htmlNEWLINEfrom trac.web import IRequestHandler, IRequestFilter, HTTPNotFoundNEWLINEfrom trac.web.chrome import INavigationContributor, ITemplateProvider, \NEWLINE add_link, add_stylesheet, add_ctxtnav, \NEWLINE prevnext_nav, add_script, add_warningNEWLINEfrom trac.versioncontrol import NoSuchChangeset, NoSuchNodeNEWLINEfrom trac.wiki import wiki_to_html, wiki_to_onelinerNEWLINEfrom bitten.api import ILogFormatter, IReportChartGenerator, IReportSummarizerNEWLINEfrom bitten.master import BuildMasterNEWLINEfrom bitten.model import BuildConfig, TargetPlatform, Build, BuildStep, \NEWLINE BuildLog, ReportNEWLINEfrom bitten.queue import collect_changesNEWLINEfrom bitten.util.repository import get_repos, get_chgset_resource, display_revNEWLINEfrom bitten.util import jsonNEWLINENEWLINE_status_label = {Build.PENDING: 'pending',NEWLINE Build.IN_PROGRESS: 'in progress',NEWLINE Build.SUCCESS: 'completed',NEWLINE Build.FAILURE: 'failed'}NEWLINE_status_title = {Build.PENDING: 'Pending',NEWLINE Build.IN_PROGRESS: 'In Progress',NEWLINE Build.SUCCESS: 'Success',NEWLINE Build.FAILURE: 'Failure'}NEWLINE_step_status_label = {BuildStep.SUCCESS: 'success',NEWLINE BuildStep.FAILURE: 'failed',NEWLINE BuildStep.IN_PROGRESS: 'in progress'}NEWLINENEWLINEdef _get_build_data(env, req, build, repos_name=None):NEWLINE chgset_url = ''NEWLINE if repos_name:NEWLINE chgset_resource = get_chgset_resource(env, repos_name, build.rev)NEWLINE chgset_url = get_resource_url(env, chgset_resource, req.href)NEWLINE platform = TargetPlatform.fetch(env, build.platform)NEWLINE data = {'id': build.id, 'name': build.slave, 'rev': build.rev,NEWLINE 'status': _status_label[build.status],NEWLINE 'platform': getattr(platform, 'name', 'unknown'),NEWLINE 'cls': _status_label[build.status].replace(' ', '-'),NEWLINE 'href': req.href.build(build.config, build.id),NEWLINE 'chgset_href': chgset_url}NEWLINE if build.started:NEWLINE data['started'] = format_datetime(build.started)NEWLINE data['started_delta'] = pretty_timedelta(build.started)NEWLINE data['duration'] = pretty_timedelta(build.started)NEWLINE if build.stopped:NEWLINE data['stopped'] = format_datetime(build.stopped)NEWLINE data['stopped_delta'] = pretty_timedelta(build.stopped)NEWLINE data['duration'] = pretty_timedelta(build.stopped, build.started)NEWLINE data['slave'] = {NEWLINE 'name': build.slave,NEWLINE 'ipnr': build.slave_info.get(Build.IP_ADDRESS),NEWLINE 'os_name': build.slave_info.get(Build.OS_NAME),NEWLINE 'os_family': build.slave_info.get(Build.OS_FAMILY),NEWLINE 'os_version': build.slave_info.get(Build.OS_VERSION),NEWLINE 'machine': build.slave_info.get(Build.MACHINE),NEWLINE 'processor': build.slave_info.get(Build.PROCESSOR)NEWLINE }NEWLINE return dataNEWLINENEWLINEdef _has_permission(perm, repos, path, rev=None, raise_error=False):NEWLINE if hasattr(repos, 'authz'):NEWLINE if not repos.authz.has_permission(path):NEWLINE if not raise_error:NEWLINE return FalseNEWLINE repos.authz.assert_permission(path)NEWLINE else:NEWLINE node = repos.get_node(path, rev)NEWLINE if not node.can_view(perm):NEWLINE if not raise_error:NEWLINE return FalseNEWLINE raise PermissionError('BROWSER_VIEW', node.resource)NEWLINE return TrueNEWLINENEWLINEclass BittenChrome(Component):NEWLINE """Provides the Bitten templates and static resources."""NEWLINENEWLINE implements(INavigationContributor, ITemplateProvider)NEWLINENEWLINE # INavigationContributor methodsNEWLINENEWLINE def get_active_navigation_item(self, req):NEWLINE passNEWLINENEWLINE def get_navigation_items(self, req):NEWLINE """Return the navigation item for access the build status overview fromNEWLINE the Trac navigation bar."""NEWLINE if 'BUILD_VIEW' in req.perm:NEWLINE status = ''NEWLINE if BuildMaster(self.env).quick_status:NEWLINE for config in BuildConfig.select(self.env,NEWLINE include_inactive=False):NEWLINE prev_rev = NoneNEWLINE for platform, rev, build in collect_changes(config, req.authname):NEWLINE if rev != prev_rev:NEWLINE if prev_rev is not None:NEWLINE breakNEWLINE prev_rev = revNEWLINE if build:NEWLINE build_data = _get_build_data(self.env, req, build)NEWLINE if build_data['status'] == 'failed':NEWLINE status='bittenfailed'NEWLINE breakNEWLINE if build_data['status'] == 'in progress':NEWLINE status='bitteninprogress'NEWLINE elif not status:NEWLINE if (build_data['status'] == 'completed'):NEWLINE status='bittencompleted'NEWLINE if not status:NEWLINE status='bittenpending'NEWLINE yield ('mainnav', 'build',NEWLINE tag.a('Build Status', href=req.href.build(), accesskey=5,NEWLINE class_=status))NEWLINENEWLINE # ITemplatesProvider methodsNEWLINENEWLINE def get_htdocs_dirs(self):NEWLINE """Return the directories containing static resources."""NEWLINE return [('bitten', pkg_resources.resource_filename(__name__, 'htdocs'))]NEWLINENEWLINE def get_templates_dirs(self):NEWLINE """Return the directories containing templates."""NEWLINE return [pkg_resources.resource_filename(__name__, 'templates')]NEWLINENEWLINENEWLINEclass BuildConfigController(Component):NEWLINE """Implements the web interface for build configurations."""NEWLINENEWLINE implements(IRequestHandler, IRequestFilter, INavigationContributor)NEWLINENEWLINE # Configuration optionsNEWLINENEWLINE chart_style = Option('bitten', 'chart_style', 'height: 220px; width: 220px;', doc=NEWLINE """Style attribute for charts. Mostly useful for setting the height and width.""")NEWLINENEWLINE # INavigationContributor methodsNEWLINENEWLINE def get_active_navigation_item(self, req):NEWLINE return 'build'NEWLINENEWLINE def get_navigation_items(self, req):NEWLINE return []NEWLINENEWLINE # IRequestHandler methodsNEWLINENEWLINE def match_request(self, req):NEWLINE match = re.match(r'/build(?:/([\w.-]+))?/?$', req.path_info)NEWLINE if match:NEWLINE if match.group(1):NEWLINE req.args['config'] = match.group(1)NEWLINE return TrueNEWLINENEWLINE def process_request(self, req):NEWLINE req.perm.require('BUILD_VIEW')NEWLINENEWLINE action = req.args.get('action')NEWLINE view = req.args.get('view')NEWLINE config = req.args.get('config')NEWLINENEWLINE if config:NEWLINE data = self._render_config(req, config)NEWLINE elif view == 'inprogress':NEWLINE data = self._render_inprogress(req)NEWLINE else:NEWLINE data = self._render_overview(req)NEWLINENEWLINE add_stylesheet(req, 'bitten/bitten.css')NEWLINE return 'bitten_config.html', data, NoneNEWLINENEWLINE # IRequestHandler methodsNEWLINENEWLINE def pre_process_request(self, req, handler):NEWLINE return handlerNEWLINENEWLINE def post_process_request(self, req, template, data, content_type):NEWLINE if template:NEWLINE add_stylesheet(req, 'bitten/bitten.css')NEWLINENEWLINE return template, data, content_typeNEWLINENEWLINE # Internal methodsNEWLINENEWLINE def _render_overview(self, req):NEWLINE data = {'title': 'Build Status'}NEWLINE show_all = FalseNEWLINE if req.args.get('show') == 'all':NEWLINE show_all = TrueNEWLINE data['show_all'] = show_allNEWLINENEWLINE configs = []NEWLINE for config in BuildConfig.select(self.env, include_inactive=show_all):NEWLINE repos_name, repos, repos_path = get_repos(self.env, config.path,NEWLINE req.authname)NEWLINE rev = config.max_rev or repos.youngest_revNEWLINE try:NEWLINE if not _has_permission(req.perm, repos, repos_path, rev=rev):NEWLINE continueNEWLINE except NoSuchNode:NEWLINE add_warning(req, "Configuration '%s' points to non-existing "NEWLINE "path '/%s' at revision '%s'. Configuration skipped." \NEWLINE % (config.name, config.path, rev))NEWLINE continueNEWLINENEWLINE description = config.descriptionNEWLINE if description:NEWLINE description = wiki_to_html(description, self.env, req)NEWLINENEWLINE platforms_data = []NEWLINE for platform in TargetPlatform.select(self.env, config=config.name):NEWLINE pd = { 'name': platform.name,NEWLINE 'id': platform.id,NEWLINE 'builds_pending': len(list(Build.select(self.env,NEWLINE config=config.name, status=Build.PENDING,NEWLINE platform=platform.id))),NEWLINE 'builds_inprogress': len(list(Build.select(self.env,NEWLINE config=config.name, status=Build.IN_PROGRESS,NEWLINE platform=platform.id)))NEWLINE }NEWLINE platforms_data.append(pd)NEWLINENEWLINE config_data = {NEWLINE 'name': config.name, 'label': config.label or config.name,NEWLINE 'active': config.active, 'path': config.path,NEWLINE 'description': description,NEWLINE 'builds_pending' : len(list(Build.select(self.env,NEWLINE config=config.name,NEWLINE status=Build.PENDING))),NEWLINE 'builds_inprogress' : len(list(Build.select(self.env,NEWLINE config=config.name,NEWLINE status=Build.IN_PROGRESS))),NEWLINE 'href': req.href.build(config.name),NEWLINE 'builds': [],NEWLINE 'platforms': platforms_dataNEWLINE }NEWLINE configs.append(config_data)NEWLINE if not config.active:NEWLINE continueNEWLINENEWLINE prev_rev = NoneNEWLINE for platform, rev, build in collect_changes(config, req.authname):NEWLINE if rev != prev_rev:NEWLINE if prev_rev is None:NEWLINE chgset = repos.get_changeset(rev)NEWLINE chgset_resource = get_chgset_resource(self.env, NEWLINE repos_name, rev)NEWLINE config_data['youngest_rev'] = {NEWLINE 'id': rev,NEWLINE 'href': get_resource_url(self.env, chgset_resource,NEWLINE req.href),NEWLINE 'display_rev': display_rev(repos, rev),NEWLINE 'author': chgset.author or 'anonymous',NEWLINE 'date': format_datetime(chgset.date),NEWLINE 'message': wiki_to_oneliner(NEWLINE shorten_line(chgset.message), self.env, req=req)NEWLINE }NEWLINE else:NEWLINE breakNEWLINE prev_rev = revNEWLINE if build:NEWLINE build_data = _get_build_data(self.env, req, build, repos_name)NEWLINE build_data['platform'] = platform.nameNEWLINE config_data['builds'].append(build_data)NEWLINE else:NEWLINE config_data['builds'].append({NEWLINE 'platform': platform.name, 'status': 'pending'NEWLINE })NEWLINENEWLINE data['configs'] = sorted(configs, key=lambda x:x['label'].lower())NEWLINE data['page_mode'] = 'overview'NEWLINENEWLINE in_progress_builds = Build.select(self.env, status=Build.IN_PROGRESS)NEWLINE pending_builds = Build.select(self.env, status=Build.PENDING)NEWLINENEWLINE data['builds_pending'] = len(list(pending_builds))NEWLINE data['builds_inprogress'] = len(list(in_progress_builds))NEWLINENEWLINE add_link(req, 'views', req.href.build(view='inprogress'),NEWLINE 'In Progress Builds')NEWLINE add_ctxtnav(req, 'In Progress Builds',NEWLINE req.href.build(view='inprogress'))NEWLINE return dataNEWLINENEWLINE def _render_inprogress(self, req):NEWLINE data = {'title': 'In Progress Builds',NEWLINE 'page_mode': 'view-inprogress'}NEWLINENEWLINE configs = []NEWLINE for config in BuildConfig.select(self.env, include_inactive=False):NEWLINE repos_name, repos, repos_path = get_repos(self.env, config.path,NEWLINE req.authname)NEWLINE rev = config.max_rev or repos.youngest_revNEWLINE try:NEWLINE if not _has_permission(req.perm, repos, repos_path, rev=rev):NEWLINE continueNEWLINE except NoSuchNode:NEWLINE add_warning(req, "Configuration '%s' points to non-existing "NEWLINE "path '/%s' at revision '%s'. Configuration skipped." \NEWLINE % (config.name, config.path, rev))NEWLINE continueNEWLINENEWLINE self.log.debug(config.name)NEWLINE if not config.active:NEWLINE continueNEWLINENEWLINE in_progress_builds = Build.select(self.env, config=config.name,NEWLINE status=Build.IN_PROGRESS)NEWLINENEWLINE current_builds = 0NEWLINE builds = []NEWLINE # sort correctly by revision.NEWLINE for build in sorted(in_progress_builds,NEWLINE cmp=lambda x, y: int(y.rev_time) - int(x.rev_time)):NEWLINE rev = build.revNEWLINE build_data = _get_build_data(self.env, req, build, repos_name)NEWLINE build_data['rev'] = revNEWLINE build_data['rev_href'] = build_data['chgset_href']NEWLINE platform = TargetPlatform.fetch(self.env, build.platform)NEWLINE build_data['platform'] = platform.nameNEWLINE build_data['steps'] = []NEWLINENEWLINE for step in BuildStep.select(self.env, build=build.id):NEWLINE build_data['steps'].append({NEWLINE 'name': step.name,NEWLINE 'description': step.description,NEWLINE 'duration': to_datetime(step.stopped or int(time.time()), utc) - \NEWLINE to_datetime(step.started, utc),NEWLINE 'status': _step_status_label[step.status],NEWLINE 'cls': _step_status_label[step.status].replace(' ', '-'),NEWLINE 'errors': step.errors,NEWLINE 'href': build_data['href'] + '#step_' + step.nameNEWLINE })NEWLINENEWLINE builds.append(build_data)NEWLINE current_builds += 1NEWLINENEWLINE if current_builds == 0:NEWLINE continueNEWLINENEWLINE description = config.descriptionNEWLINE if description:NEWLINE description = wiki_to_html(description, self.env, req)NEWLINE configs.append({NEWLINE 'name': config.name, 'label': config.label or config.name,NEWLINE 'active': config.active, 'path': config.path,NEWLINE 'description': description,NEWLINE 'href': req.href.build(config.name),NEWLINE 'builds': buildsNEWLINE })NEWLINENEWLINE data['configs'] = sorted(configs, key=lambda x:x['label'].lower())NEWLINE return dataNEWLINENEWLINE def _render_config(self, req, config_name):NEWLINENEWLINE config = BuildConfig.fetch(self.env, config_name)NEWLINE if not config:NEWLINE raise HTTPNotFound("Build configuration '%s' does not exist." \NEWLINE % config_name)NEWLINENEWLINE repos_name, repos, repos_path = get_repos(self.env, config.path,NEWLINE req.authname)NEWLINENEWLINE rev = config.max_rev or repos.youngest_revNEWLINE try:NEWLINE _has_permission(req.perm, repos, repos_path, rev=rev,NEWLINE raise_error=True)NEWLINE except NoSuchNode:NEWLINE raise TracError("Permission checking against repository path %s "NEWLINE "at revision %s failed." % (config.path, rev))NEWLINENEWLINE data = {'title': 'Build Configuration "%s"' \NEWLINE % config.label or config.name,NEWLINE 'page_mode': 'view_config'}NEWLINE add_link(req, 'up', req.href.build(), 'Build Status')NEWLINE description = config.descriptionNEWLINE if description:NEWLINE description = wiki_to_html(description, self.env, req)NEWLINENEWLINE pending_builds = list(Build.select(self.env,NEWLINE config=config.name, status=Build.PENDING))NEWLINE inprogress_builds = list(Build.select(self.env,NEWLINE config=config.name, status=Build.IN_PROGRESS))NEWLINENEWLINE min_chgset_url = ''NEWLINE if config.min_rev:NEWLINE min_chgset_resource = get_chgset_resource(self.env, repos_name,NEWLINE config.min_rev)NEWLINE min_chgset_url = get_resource_url(self.env, min_chgset_resource,NEWLINE req.href),NEWLINE max_chgset_url = ''NEWLINE if config.max_rev:NEWLINE max_chgset_resource = get_chgset_resource(self.env, repos_name,NEWLINE config.max_rev)NEWLINE max_chgset_url = get_resource_url(self.env, max_chgset_resource,NEWLINE req.href),NEWLINENEWLINE data['config'] = {NEWLINE 'name': config.name, 'label': config.label, 'path': config.path,NEWLINE 'min_rev': config.min_rev,NEWLINE 'min_rev_href': min_chgset_url,NEWLINE 'max_rev': config.max_rev,NEWLINE 'max_rev_href': max_chgset_url,NEWLINE 'active': config.active, 'description': description,NEWLINE 'browser_href': req.href.browser(config.path),NEWLINE 'builds_pending' : len(pending_builds),NEWLINE 'builds_inprogress' : len(inprogress_builds)NEWLINE }NEWLINENEWLINE context = Context.from_request(req, config.resource)NEWLINE data['context'] = contextNEWLINE data['config']['attachments'] = AttachmentModule(self.env).attachment_data(context)NEWLINENEWLINE platforms = list(TargetPlatform.select(self.env, config=config_name))NEWLINE data['config']['platforms'] = [NEWLINE { 'name': platform.name,NEWLINE 'id': platform.id,NEWLINE 'builds_pending': len(list(Build.select(self.env,NEWLINE config=config.name,NEWLINE status=Build.PENDING,NEWLINE platform=platform.id))),NEWLINE 'builds_inprogress': len(list(Build.select(self.env,NEWLINE config=config.name,NEWLINE status=Build.IN_PROGRESS,NEWLINE platform=platform.id)))NEWLINE }NEWLINE for platform in platformsNEWLINE ]NEWLINENEWLINE has_reports = FalseNEWLINE for report in Report.select(self.env, config=config.name):NEWLINE has_reports = TrueNEWLINE breakNEWLINENEWLINE if has_reports:NEWLINE chart_generators = []NEWLINE report_categories = list(self._report_categories_for_config(config))NEWLINE for generator in ReportChartController(self.env).generators:NEWLINE for category in generator.get_supported_categories():NEWLINE if category in report_categories:NEWLINE chart_generators.append({NEWLINE 'href': req.href.build(config.name, 'chart/' + category),NEWLINE 'category': category,NEWLINE 'style': self.config.get('bitten', 'chart_style'),NEWLINE })NEWLINE data['config']['charts'] = chart_generatorsNEWLINENEWLINE page = max(1, int(req.args.get('page', 1)))NEWLINE more = FalseNEWLINE data['page_number'] = pageNEWLINENEWLINE builds_per_page = 12 * len(platforms)NEWLINE idx = 0NEWLINE builds = {}NEWLINE revisions = []NEWLINE build_order = []NEWLINE for platform, rev, build in collect_changes(config,authname=req.authname):NEWLINE if idx >= page * builds_per_page:NEWLINE more = TrueNEWLINE breakNEWLINE elif idx >= (page - 1) * builds_per_page:NEWLINE if rev not in builds:NEWLINE revisions.append(rev)NEWLINE builds.setdefault(rev, {})NEWLINE chgset_resource = get_chgset_resource(self.env, repos_name, rev)NEWLINE builds[rev].setdefault('href', get_resource_url(self.env,NEWLINE chgset_resource, req.href))NEWLINE build_order.append((rev, repos.get_changeset(rev).date))NEWLINE builds[rev].setdefault('display_rev', display_rev(repos, rev))NEWLINE if build and build.status != Build.PENDING:NEWLINE build_data = _get_build_data(self.env, req, build)NEWLINE build_data['steps'] = []NEWLINE for step in BuildStep.select(self.env, build=build.id):NEWLINE build_data['steps'].append({NEWLINE 'name': step.name,NEWLINE 'description': step.description,NEWLINE 'duration': to_datetime(step.stopped or int(time.time()), utc) - \NEWLINE to_datetime(step.started, utc),NEWLINE 'status': _step_status_label[step.status],NEWLINE 'cls': _step_status_label[step.status].replace(' ', '-'),NEWLINENEWLINE 'errors': step.errors,NEWLINE 'href': build_data['href'] + '#step_' + step.nameNEWLINE })NEWLINE builds[rev][platform.id] = build_dataNEWLINE idx += 1NEWLINE data['config']['build_order'] = [r[0] for r in sorted(build_order,NEWLINE key=lambda x: x[1],NEWLINE reverse=True)]NEWLINE data['config']['builds'] = buildsNEWLINE data['config']['revisions'] = revisionsNEWLINENEWLINE if page > 1:NEWLINE if page == 2:NEWLINE prev_href = req.href.build(config.name)NEWLINE else:NEWLINE prev_href = req.href.build(config.name, page=page - 1)NEWLINE add_link(req, 'prev', prev_href, 'Previous Page')NEWLINE if more:NEWLINE next_href = req.href.build(config.name, page=page + 1)NEWLINE add_link(req, 'next', next_href, 'Next Page')NEWLINE if arity(prevnext_nav) == 4: # Trac 0.12 compat, see #450NEWLINE prevnext_nav(req, 'Previous Page', 'Next Page')NEWLINE else:NEWLINE prevnext_nav (req, 'Page')NEWLINE return dataNEWLINENEWLINE def _report_categories_for_config(self, config):NEWLINE """Yields the categories of reports that exist for active buildsNEWLINE of this configuration.NEWLINE """NEWLINENEWLINENEWLINE for (category, ) in self.env.db_query("""SELECT DISTINCT report.category as categoryNEWLINEFROM bitten_build AS buildNEWLINEJOIN bitten_report AS report ON (report.build=build.id)NEWLINEWHERE build.config=%s AND build.rev_time >= %s AND build.rev_time <= %s""",NEWLINE (config.name,NEWLINE config.min_rev_time(self.env),NEWLINE config.max_rev_time(self.env))):NEWLINE yield categoryNEWLINENEWLINENEWLINEclass BuildController(Component):NEWLINE """Renders the build page."""NEWLINE implements(INavigationContributor, IRequestHandler, ITimelineEventProvider)NEWLINENEWLINE log_formatters = ExtensionPoint(ILogFormatter)NEWLINE report_summarizers = ExtensionPoint(IReportSummarizer)NEWLINENEWLINE # INavigationContributor methodsNEWLINENEWLINE def get_active_navigation_item(self, req):NEWLINE return 'build'NEWLINENEWLINE def get_navigation_items(self, req):NEWLINE return []NEWLINENEWLINE # IRequestHandler methodsNEWLINENEWLINE def match_request(self, req):NEWLINE match = re.match(r'/build/([\w.-]+)/(\d+)', req.path_info)NEWLINE if match:NEWLINE if match.group(1):NEWLINE req.args['config'] = match.group(1)NEWLINE if match.group(2):NEWLINE req.args['id'] = match.group(2)NEWLINE return TrueNEWLINENEWLINE def process_request(self, req):NEWLINE req.perm.require('BUILD_VIEW')NEWLINENEWLINE build_id = int(req.args.get('id'))NEWLINE build = Build.fetch(self.env, build_id)NEWLINE if not build:NEWLINE raise HTTPNotFound("Build '%s' does not exist." \NEWLINE % build_id)NEWLINENEWLINE if req.method == 'POST':NEWLINE if req.args.get('action') == 'invalidate':NEWLINE self._do_invalidate(req, build)NEWLINE req.redirect(req.href.build(build.config, build.id))NEWLINENEWLINE add_link(req, 'up', req.href.build(build.config),NEWLINE 'Build Configuration')NEWLINE data = {'title': 'Build %s - %s' % (build_id,NEWLINE _status_title[build.status]),NEWLINE 'page_mode': 'view_build',NEWLINE 'build': {}}NEWLINE config = BuildConfig.fetch(self.env, build.config)NEWLINE data['build']['config'] = {NEWLINE 'name': config.label or config.name,NEWLINE 'href': req.href.build(config.name)NEWLINE }NEWLINENEWLINE context = Context.from_request(req, build.resource)NEWLINE data['context'] = contextNEWLINE data['build']['attachments'] = AttachmentModule(self.env).attachment_data(context)NEWLINENEWLINE formatters = []NEWLINE for formatter in self.log_formatters:NEWLINE formatters.append(formatter.get_formatter(req, build))NEWLINENEWLINE summarizers = {} # keyed by report typeNEWLINE for summarizer in self.report_summarizers:NEWLINE categories = summarizer.get_supported_categories()NEWLINE summarizers.update(dict([(cat, summarizer) for cat in categories]))NEWLINENEWLINE repos_name, repos, repos_path = get_repos(self.env, config.path,NEWLINE req.authname)NEWLINENEWLINE _has_permission(req.perm, repos, repos_path, rev=build.rev, raise_error=True)NEWLINENEWLINE data['build'].update(_get_build_data(self.env, req, build, repos_name))NEWLINE steps = []NEWLINE for step in BuildStep.select(self.env, build=build.id):NEWLINE steps.append({NEWLINE 'name': step.name, 'description': step.description,NEWLINE 'duration': pretty_timedelta(step.started, step.stopped or int(time.time())),NEWLINE 'status': _step_status_label[step.status],NEWLINE 'cls': _step_status_label[step.status].replace(' ', '-'),NEWLINE 'errors': step.errors,NEWLINE 'log': self._render_log(req, build, formatters, step),NEWLINE 'reports': self._render_reports(req, config, build, summarizers,NEWLINE step)NEWLINE })NEWLINE data['build']['steps'] = stepsNEWLINE data['build']['can_delete'] = ('BUILD_DELETE' in req.perm \NEWLINE and build.status != build.PENDING)NEWLINENEWLINE chgset = repos.get_changeset(build.rev)NEWLINE data['build']['chgset_author'] = chgset.authorNEWLINE data['build']['display_rev'] = display_rev(repos, build.rev)NEWLINENEWLINE add_script(req, 'common/js/folding.js')NEWLINE add_script(req, 'bitten/tabset.js')NEWLINE add_script(req, 'bitten/jquery.flot.js')NEWLINE add_stylesheet(req, 'bitten/bitten.css')NEWLINE return 'bitten_build.html', data, NoneNEWLINENEWLINE # ITimelineEventProvider methodsNEWLINENEWLINE def get_timeline_filters(self, req):NEWLINE if 'BUILD_VIEW' in req.perm:NEWLINE yield ('build', 'Builds')NEWLINENEWLINE def get_timeline_events(self, req, start, stop, filters):NEWLINE if 'build' not in filters:NEWLINE returnNEWLINENEWLINE # Attachments (will be rendered by attachment module)NEWLINE for event in AttachmentModule(self.env).get_timeline_events(NEWLINE req, Resource('build'), start, stop):NEWLINE yield eventNEWLINENEWLINE start = to_timestamp(start)NEWLINE stop = to_timestamp(stop)NEWLINENEWLINE add_stylesheet(req, 'bitten/bitten.css')NEWLINENEWLINE with self.env.db_query as db:NEWLINE cursor = db.cursor()NEWLINE cursor.execute("SELECT b.id,b.config,c.label,c.path, b.rev,p.name,"NEWLINE "b.stopped,b.status FROM bitten_build AS b"NEWLINE " INNER JOIN bitten_config AS c ON (c.name=b.config) "NEWLINE " INNER JOIN bitten_platform AS p ON (p.id=b.platform) "NEWLINE "WHERE b.stopped>=%s AND b.stopped<=%s "NEWLINE "AND b.status IN (%s, %s) ORDER BY b.stopped",NEWLINE (start, stop, Build.SUCCESS, Build.FAILURE))NEWLINENEWLINE event_kinds = {Build.SUCCESS: 'successbuild',NEWLINE Build.FAILURE: 'failedbuild'}NEWLINENEWLINE for id_, config, label, path, rev, platform, stopped, status in cursor:NEWLINE config_object = BuildConfig.fetch(self.env, config)NEWLINE repos_name, repos, repos_path = get_repos(self.env,NEWLINE config_object.path,NEWLINE req.authname)NEWLINE if not _has_permission(req.perm, repos, repos_path, rev=rev):NEWLINE continueNEWLINE errors = []NEWLINE if status == Build.FAILURE:NEWLINE for step in BuildStep.select(self.env, build=id_,NEWLINE status=BuildStep.FAILURE):NEWLINE errors += [(step.name, error) for errorNEWLINE in step.errors]NEWLINE yield (event_kinds[status], to_datetime(stopped, utc), None,NEWLINE (id_, config, label, display_rev(repos, rev), platform,NEWLINE status, errors))NEWLINENEWLINE def render_timeline_event(self, context, field, event):NEWLINE id_, config, label, rev, platform, status, errors = event[3]NEWLINENEWLINE if field == 'url':NEWLINE return context.href.build(config, id_)NEWLINENEWLINE elif field == 'title':NEWLINE return tag('Build of ', tag.em('%s [%s]' % (label, rev)),NEWLINE ' on %s %s' % (platform, _status_label[status]))NEWLINENEWLINE elif field == 'description':NEWLINE message = ''NEWLINE if context.req.args.get('format') == 'rss':NEWLINE if errors:NEWLINE buf = StringIO()NEWLINE prev_step = NoneNEWLINE for step, error in errors:NEWLINE if step != prev_step:NEWLINE if prev_step is not None:NEWLINE buf.write('</ul>')NEWLINE buf.write('<p>Step %s failed:</p><ul>' \NEWLINE % escape(step))NEWLINE prev_step = stepNEWLINE buf.write('<li>%s</li>' % escape(error))NEWLINE buf.write('</ul>')NEWLINE message = Markup(buf.getvalue())NEWLINE else:NEWLINE if errors:NEWLINE steps = []NEWLINE for step, error in errors:NEWLINE if step not in steps:NEWLINE steps.append(step)NEWLINE steps = [Markup('<em>%s</em>') % step for step in steps]NEWLINE if len(steps) < 2:NEWLINE message = steps[0]NEWLINE elif len(steps) == 2:NEWLINE message = Markup(' and ').join(steps)NEWLINE elif len(steps) > 2:NEWLINE message = Markup(', ').join(steps[:-1]) + ', and ' + \NEWLINE steps[-1]NEWLINE message = Markup('Step%s %s failed') % (NEWLINE len(steps) != 1 and 's' or '', message)NEWLINE return messageNEWLINENEWLINE # Internal methodsNEWLINENEWLINE def _do_invalidate(self, req, build):NEWLINE self.log.info('Invalidating build %d', build.id)NEWLINENEWLINE with self.env.db_transaction as db:NEWLINE for step in BuildStep.select(self.env, build=build.id):NEWLINE step.delete()NEWLINENEWLINE build.slave = NoneNEWLINE build.started = 0NEWLINE build.stopped = 0NEWLINE build.last_activity = 0NEWLINE build.status = Build.PENDINGNEWLINE build.slave_info = {}NEWLINE build.update()NEWLINENEWLINE Attachment.delete_all(self.env, 'build', build.resource.id)NEWLINENEWLINE #commitNEWLINENEWLINE req.redirect(req.href.build(build.config))NEWLINENEWLINE def _render_log(self, req, build, formatters, step):NEWLINE items = []NEWLINE for log in BuildLog.select(self.env, build=build.id, step=step.name):NEWLINE for level, message in log.messages:NEWLINE for format in formatters:NEWLINE message = format(step, log.generator, level, message)NEWLINE items.append({'level': level, 'message': message})NEWLINE return itemsNEWLINENEWLINE def _render_reports(self, req, config, build, summarizers, step):NEWLINE reports = []NEWLINE for report in Report.select(self.env, build=build.id, step=step.name):NEWLINE summarizer = summarizers.get(report.category)NEWLINE if summarizer:NEWLINE tmpl, data = summarizer.render_summary(req, config, build,NEWLINE step, report.category)NEWLINE reports.append({'category': report.category,NEWLINE 'template': tmpl, 'data': data})NEWLINE else:NEWLINE tmpl = data = NoneNEWLINE return reportsNEWLINENEWLINENEWLINEclass ReportChartController(Component):NEWLINE implements(IRequestHandler)NEWLINENEWLINE generators = ExtensionPoint(IReportChartGenerator)NEWLINENEWLINE # IRequestHandler methodsNEWLINE def match_request(self, req):NEWLINE match = re.match(r'/build/([\w.-]+)/chart/(\w+)', req.path_info)NEWLINE if match:NEWLINE req.args['config'] = match.group(1)NEWLINE req.args['category'] = match.group(2)NEWLINE return TrueNEWLINENEWLINE def process_request(self, req):NEWLINE category = req.args.get('category')NEWLINE config = BuildConfig.fetch(self.env, name=req.args.get('config'))NEWLINENEWLINE for generator in self.generators:NEWLINE if category in generator.get_supported_categories():NEWLINE tmpl, data = generator.generate_chart_data(req, config,NEWLINE category)NEWLINE breakNEWLINE else:NEWLINE raise TracError('Unknown report category "%s"' % category)NEWLINENEWLINE data['dumps'] = json.to_jsonNEWLINENEWLINE return tmpl, data, 'text/plain'NEWLINENEWLINENEWLINEclass SourceFileLinkFormatter(Component):NEWLINE """Detects references to files in the build log and renders them as linksNEWLINE to the repository browser.NEWLINE """NEWLINENEWLINE implements(ILogFormatter)NEWLINENEWLINE _fileref_re = re.compile(r'(?P<prefix>-[A-Za-z])?(?P<path>[\w.-]+(?:[\\/][\w.-]+)+)(?P<line>:\d+)?')NEWLINENEWLINE def get_formatter(self, req, build):NEWLINE """Return the log message formatter function."""NEWLINE config = BuildConfig.fetch(self.env, name=build.config)NEWLINE repos_name, repos, repos_path = get_repos(self.env, config.path,NEWLINE req.authname)NEWLINE href = req.href.browserNEWLINE cache = {}NEWLINENEWLINE def _replace(m):NEWLINE filepath = posixpath.normpath(m.group('path').replace('\\', '/'))NEWLINE if not cache.get(filepath) is True:NEWLINE parts = filepath.split('/')NEWLINE path = ''NEWLINE for part in parts:NEWLINE path = posixpath.join(path, part)NEWLINE if path not in cache:NEWLINE try:NEWLINE full_path = posixpath.join(config.path, path)NEWLINE full_path = posixpath.normpath(full_path)NEWLINE if full_path.startswith(config.path + "/") \NEWLINE or full_path == config.path:NEWLINE repos.get_node(full_path,NEWLINE build.rev)NEWLINE cache[path] = TrueNEWLINE else:NEWLINE cache[path] = FalseNEWLINE except TracError:NEWLINE cache[path] = FalseNEWLINE if cache[path] is False:NEWLINE return m.group(0)NEWLINE link = href(config.path, filepath)NEWLINE if m.group('line'):NEWLINE link += '#L' + m.group('line')[1:]NEWLINE return Markup(tag.a(m.group(0), href=link))NEWLINENEWLINE def _formatter(step, type, level, message):NEWLINE buf = []NEWLINE offset = 0NEWLINE for mo in self._fileref_re.finditer(message):NEWLINE start, end = mo.span()NEWLINE if start > offset:NEWLINE buf.append(message[offset:start])NEWLINE buf.append(_replace(mo))NEWLINE offset = endNEWLINE if offset < len(message):NEWLINE buf.append(message[offset:])NEWLINE return Markup("").join(buf)NEWLINENEWLINE return _formatterNEWLINE
from typing import ListNEWLINENEWLINEfrom bleak.backends.service import BleakGATTServiceNEWLINEfrom bleak.backends.bluezdbus.characteristic import BleakGATTCharacteristicBlueZDBusNEWLINENEWLINENEWLINEclass BleakGATTServiceBlueZDBus(BleakGATTService):NEWLINE """GATT Service implementation for the BlueZ DBus backend"""NEWLINENEWLINE def __init__(self, obj, path):NEWLINE super().__init__(obj)NEWLINE self.__characteristics = []NEWLINE self.__path = pathNEWLINENEWLINE @propertyNEWLINE def uuid(self) -> str:NEWLINE """The UUID to this service"""NEWLINE return self.obj["UUID"]NEWLINENEWLINE @propertyNEWLINE def characteristics(self) -> List[BleakGATTCharacteristicBlueZDBus]:NEWLINE """List of characteristics for this service"""NEWLINE return self.__characteristicsNEWLINENEWLINE def add_characteristic(self, characteristic: BleakGATTCharacteristicBlueZDBus):NEWLINE """Add a :py:class:`~BleakGATTCharacteristicBlueZDBus` to the service.NEWLINENEWLINE Should not be used by end user, but rather by `bleak` itself.NEWLINE """NEWLINE self.__characteristics.append(characteristic)NEWLINENEWLINE @propertyNEWLINE def path(self):NEWLINE """The DBus path. Mostly needed by `bleak`, not by end user"""NEWLINE return self.__pathNEWLINE
# """NEWLINE# This is the interface that allows for creating nested lists.NEWLINE# You should not implement it, or speculate about its implementationNEWLINE# """NEWLINE# class NestedInteger(object):NEWLINE# def isInteger(self):NEWLINE# """NEWLINE# @return True if this NestedInteger holds a single integer, rather than a nested list.NEWLINE# :rtype boolNEWLINE# """NEWLINE#NEWLINE# def getInteger(self):NEWLINE# """NEWLINE# @return the single integer that this NestedInteger holds, if it holds a single integerNEWLINE# Return None if this NestedInteger holds a nested listNEWLINE# :rtype intNEWLINE# """NEWLINE#NEWLINE# def getList(self):NEWLINE# """NEWLINE# @return the nested list that this NestedInteger holds, if it holds a nested listNEWLINE# Return None if this NestedInteger holds a single integerNEWLINE# :rtype List[NestedInteger]NEWLINE# """NEWLINENEWLINENEWLINENEWLINEfrom collections import dequeNEWLINE# Approach 1: Brite force ut not good for the interview. This approach, modifies the input listNEWLINEclass NestedIterator(object):NEWLINENEWLINE def __init__(self, nestedList):NEWLINE """NEWLINE Initialize your data structure here.NEWLINE :type nestedList: List[NestedInteger]NEWLINE """NEWLINE self.q = deque()NEWLINE self.flatten(nestedList)NEWLINENEWLINE def flatten(self, nestedList):NEWLINE for l in nestedList:NEWLINE if l.isInteger():NEWLINE self.q.append(l.getInteger())NEWLINE else:NEWLINE self.flatten(l.getList())NEWLINENEWLINE def next(self):NEWLINE """NEWLINE :rtype: intNEWLINE """NEWLINE return self.q.popleft()NEWLINENEWLINE def hasNext(self):NEWLINE """NEWLINE :rtype: boolNEWLINE """NEWLINE return len(self.q) > 0NEWLINENEWLINENEWLINENEWLINENEWLINE# Approach 2: This approach, doesn't modify the input list but depends on hasNext to be called, which is also not good and not the perfect implementation for the interviewNEWLINEclass NestedIterator:NEWLINE def __init__(self, nestedList: [NestedInteger]):NEWLINE print("nestedList: ", nestedList)NEWLINE self.__nestedList = nestedListNEWLINE self.__position = 0NEWLINE self.__lists = []NEWLINENEWLINE def next(self) -> int:NEWLINE integer = self.__nestedList[self.__position].getInteger()NEWLINE self.__position += 1NEWLINE print("------")NEWLINE print("integer: ", integer)NEWLINE print("self.__nestedList: ", self.__nestedList)NEWLINE print("self.__position: ", self.__position)NEWLINE print("self.__lists: ", self.__lists)NEWLINE return integerNEWLINENEWLINE def hasNext(self) -> bool:NEWLINE while not self.__isComplete():NEWLINE currNode = self.__nestedList[self.__position]NEWLINENEWLINE if currNode.isInteger():NEWLINE return TrueNEWLINE else:NEWLINE self.__position += 1NEWLINE self.__lists.append((self.__nestedList, self.__position))NEWLINE self.__position = 0NEWLINE self.__nestedList = currNode.getList()NEWLINENEWLINE if self.__isComplete() and not self.__listEmpty():NEWLINE self.__nestedList, self.__position = self.__lists.pop()NEWLINE return self.hasNext()NEWLINENEWLINE return FalseNEWLINENEWLINE def __listEmpty(self) -> bool:NEWLINE return len(self.__lists) == 0NEWLINENEWLINE def __isComplete(self) -> bool:NEWLINE return self.__position >= len(self.__nestedList)NEWLINENEWLINENEWLINENEWLINE# Most optimal and preferd approachNEWLINE# https://tinyurl.com/rotxca8NEWLINE# Debug the code to get a clear ideaNEWLINEclass NestedIterator(object):NEWLINENEWLINE def __init__(self, nestedList):NEWLINE self.nestedListStack = [[nestedList, 0]] # <list, current element index/position on the nested list>NEWLINENEWLINE # Here, next method does't have any dependency over hasNextNEWLINE def next(self):NEWLINE currentNestedListStack = self.nestedListStackNEWLINE nestedList, currentPositionIdx = currentNestedListStack[-1]NEWLINE currentNestedListStack[-1][NEWLINE 1] += 1 # updating currentPositionIdx by 1, since we are sending the current integer here, on next lineNEWLINE return nestedList[currentPositionIdx].getInteger()NEWLINENEWLINE def hasNext(self):NEWLINE currentNestedListStack = self.nestedListStackNEWLINE while currentNestedListStack:NEWLINE nestedList, currentPositionIdx = currentNestedListStack[-1]NEWLINE if currentPositionIdx == len(nestedList): # we are done with this nested list, let's pop it out.NEWLINE currentNestedListStack.pop()NEWLINE else:NEWLINE currentItem = nestedList[currentPositionIdx]NEWLINE if currentItem.isInteger():NEWLINE return TrueNEWLINE currentNestedListStack[-1][1] += 1 # incremets current nestedListStack indexNEWLINE currentNestedListStack.append([currentItem.getList(), 0])NEWLINE return FalseNEWLINENEWLINE# Your NestedIterator object will be instantiated and called as such:NEWLINE# i, v = NestedIterator(nestedList), []NEWLINE# while i.hasNext(): v.append(i.next())
from decimal import ROUND_HALF_EVENNEWLINENEWLINEimport moneyedNEWLINEfrom moneyed.localization import _sign, _formatNEWLINENEWLINE_sign("en_GB", moneyed.GBP, prefix="£")NEWLINENEWLINE_format(NEWLINE "en_GB",NEWLINE group_size=3,NEWLINE group_separator=",",NEWLINE decimal_point=".",NEWLINE positive_sign="",NEWLINE trailing_positive_sign="",NEWLINE negative_sign="-",NEWLINE trailing_negative_sign="",NEWLINE rounding_method=ROUND_HALF_EVEN,NEWLINE)NEWLINE
import osNEWLINEimport shutilNEWLINEimport subprocessNEWLINENEWLINEimport requestsNEWLINENEWLINEfrom koapy.utils.logging import get_loggerNEWLINEfrom koapy.utils.subprocess import quoteNEWLINENEWLINElogger = get_logger(__name__)NEWLINENEWLINEiss_file_encoding = "euc-kr"NEWLINENEWLINENEWLINEdef download_openapi_installer(filepath):NEWLINE url = "https://download.kiwoom.com/web/openapi/OpenAPISetup.exe"NEWLINE response = requests.get(url)NEWLINE with open(filepath, "wb") as f:NEWLINE f.write(response.content)NEWLINENEWLINENEWLINEdef prepare_issfile_for_install(filepath, target=None):NEWLINE iss_filedir = os.path.join(NEWLINE os.path.dirname(__file__),NEWLINE "../../backend/kiwoom_open_api_plus/data/scripts/",NEWLINE )NEWLINE iss_filename = "install.iss"NEWLINE iss_filepath = os.path.join(iss_filedir, iss_filename)NEWLINE shutil.copy(iss_filepath, filepath)NEWLINE if target is not None:NEWLINE with open(filepath, "r", encoding=iss_file_encoding) as f:NEWLINE lines = [line for line in f]NEWLINE for i, line in enumerate(lines):NEWLINE if line.startswith("szDir="):NEWLINE lines[i] = "szDir={}\n".format(target)NEWLINE breakNEWLINE with open(filepath, "w", encoding=iss_file_encoding) as f:NEWLINE for line in lines:NEWLINE f.write(line)NEWLINENEWLINENEWLINEdef prepare_issfile_for_uninstall(filepath, reboot=False):NEWLINE iss_filedir = os.path.join(NEWLINE os.path.dirname(__file__),NEWLINE "../../backend/kiwoom_open_api_plus/data/scripts/",NEWLINE )NEWLINE iss_filename = "uninstall.iss"NEWLINE iss_filepath = os.path.join(iss_filedir, iss_filename)NEWLINE shutil.copy(iss_filepath, filepath)NEWLINE if reboot:NEWLINE with open(filepath, "r", encoding=iss_file_encoding) as f:NEWLINE lines = [line for line in f]NEWLINE for i, line in enumerate(lines):NEWLINE if line.startswith("BootOption="):NEWLINE boot_option = 3NEWLINE lines[i] = "BootOption={}\n".format(boot_option)NEWLINE breakNEWLINE with open(filepath, "w", encoding=iss_file_encoding) as f:NEWLINE for line in lines:NEWLINE f.write(line)NEWLINENEWLINENEWLINEdef run_installer_with_issfile(installer, issfile, logfile=None, cwd=None):NEWLINE cmd = [quote(installer), "/s", "/f1{}".format(quote(issfile))]NEWLINE if logfile is not None:NEWLINE cmd.extend(["/f2{}".format(quote(logfile))])NEWLINE # should use shell=True in order not to escape quotes in argsNEWLINE logger.info("Running command: %s", " ".join(cmd))NEWLINE proc = subprocess.run(" ".join(cmd), shell=True, check=False, cwd=cwd)NEWLINE if proc.returncode < 0:NEWLINE raise subprocess.CalledProcessError(proc.returncode, " ".join(cmd))NEWLINE return proc.returncodeNEWLINE
class RenderContentBase():NEWLINE '''NEWLINE This defines the data common for all content type renderersNEWLINE '''NEWLINENEWLINE def __init__(self, question_bundle):NEWLINE self.question_list = question_bundle.splitlines()NEWLINENEWLINE self.close_tokens = ')」}>』'NEWLINE self.tokens = '(「{<『'NEWLINENEWLINE self.ts_reading ='('NEWLINE self.te_reading =')'NEWLINE self.ts_writing ='「'NEWLINE self.te_writing ='」'NEWLINE self.ts_furi = '『'NEWLINE self.te_furi = '』'NEWLINE self.ts_combo ='{'NEWLINE self.te_combo ='}'NEWLINE self.ts_bonus ='<'NEWLINE self.te_bonus ='>'NEWLINE self.split = '|'NEWLINE
# 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# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE#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 RpcRequestNEWLINEclass GetProjectRequest(RpcRequest):NEWLINENEWLINE def __init__(self):NEWLINE RpcRequest.__init__(self, 'CSB', '2017-11-18', 'GetProject')NEWLINE self.set_protocol_type('https');NEWLINENEWLINE def get_ProjectName(self):NEWLINE return self.get_query_params().get('ProjectName')NEWLINENEWLINE def set_ProjectName(self,ProjectName):NEWLINE self.add_query_param('ProjectName',ProjectName)NEWLINENEWLINE def get_CsbId(self):NEWLINE return self.get_query_params().get('CsbId')NEWLINENEWLINE def set_CsbId(self,CsbId):NEWLINE self.add_query_param('CsbId',CsbId)
import osNEWLINEimport timeNEWLINEfrom pathlib import PathNEWLINEimport loggingNEWLINENEWLINEimport casperlabs_clientNEWLINEfrom casperlabs_client.abi import ABINEWLINENEWLINEBASE_PATH = Path(os.path.dirname(os.path.abspath(__file__))).parentNEWLINEERC20_WASM = f"{BASE_PATH}/execution-engine/target/wasm32-unknown-unknown/release/erc20_smart_contract.wasm"NEWLINENEWLINENEWLINE# At the beginning of a serialized version of Rust's Vec<u8>, first 4 bytes represent the size of the vector.NEWLINE#NEWLINE# Balances are 33 bytes arrays where:NEWLINE# - the first byte is "01";NEWLINE# - the rest is 32 bytes of the account's public key.NEWLINE#NEWLINE# Allowances are 64 bytes arrays where:NEWLINE# - the first 32 bytes are token owner's public key;NEWLINE# - the second 32 bytes are token spender's public key.NEWLINE#NEWLINE# Decimal version of "21 00 00 00" is 33.NEWLINE# Decimal version of "40 00 00 00" is 64.NEWLINEBALANCE_KEY_SIZE_HEX = "21000000"NEWLINEALLOWANCE_KEY_SIZE_HEX = "40000000"NEWLINEBALANCE_BYTE = "01"NEWLINEPAYMENT_AMOUNT = 10 ** 7NEWLINENEWLINENEWLINEclass Node:NEWLINE def __init__(NEWLINE self,NEWLINE host,NEWLINE port=casperlabs_client.DEFAULT_PORT,NEWLINE port_internal=casperlabs_client.DEFAULT_INTERNAL_PORT,NEWLINE ):NEWLINE self.host = hostNEWLINE self.port = portNEWLINE self.port_internal = port_internalNEWLINE self.client = casperlabs_client.CasperLabsClient(NEWLINE host=self.host, port=port, port_internal=port_internalNEWLINE )NEWLINENEWLINENEWLINEclass Agent:NEWLINE """NEWLINE An account that will be used to call contracts.NEWLINE """NEWLINENEWLINE def __init__(self, name):NEWLINE self.name = nameNEWLINE logging.debug(f"Agent {str(self)}")NEWLINENEWLINE def __str__(self):NEWLINE return f"{self.name}: {self.public_key_hex}"NEWLINENEWLINE def on(self, node):NEWLINE """NEWLINE Bind agent to a node.NEWLINE """NEWLINE return BoundAgent(self, node)NEWLINENEWLINE @propertyNEWLINE def private_key(self):NEWLINE return f"{BASE_PATH}/hack/docker/keys/{self.name}/account-private.pem"NEWLINENEWLINE @propertyNEWLINE def public_key(self):NEWLINE return f"{BASE_PATH}/hack/docker/keys/{self.name}/account-public.pem"NEWLINENEWLINE @propertyNEWLINE def public_key_hex(self):NEWLINE with open(f"{BASE_PATH}/hack/docker/keys/{self.name}/account-id-hex") as f:NEWLINE return f.read().strip()NEWLINENEWLINENEWLINEclass BoundAgent:NEWLINE """NEWLINE An agent that is bound to a node. Can be used to call a contract or issue a query.NEWLINE """NEWLINENEWLINE def __init__(self, agent, node):NEWLINE self.agent = agentNEWLINE self.node = nodeNEWLINENEWLINE def call_contract(self, method, wait_for_processed=True):NEWLINE deploy_hash = method(self)NEWLINE if wait_for_processed:NEWLINE self.wait_for_deploy_processed(deploy_hash)NEWLINE return deploy_hashNEWLINENEWLINE def query(self, method):NEWLINE return method(self)NEWLINENEWLINE def transfer_clx(self, recipient_public_hex, amount, wait_for_processed=False):NEWLINE deploy_hash = self.node.client.transfer(NEWLINE recipient_public_hex,NEWLINE amount,NEWLINE payment_amount=PAYMENT_AMOUNT,NEWLINE from_addr=self.agent.public_key_hex,NEWLINE private_key=self.agent.private_key,NEWLINE )NEWLINE if wait_for_processed:NEWLINE self.wait_for_deploy_processed(deploy_hash)NEWLINE return deploy_hashNEWLINENEWLINE def wait_for_deploy_processed(self, deploy_hash, on_error_raise=True):NEWLINE result = NoneNEWLINE while True:NEWLINE result = self.node.client.showDeploy(deploy_hash)NEWLINE if result.status.state != 1: # PENDINGNEWLINE breakNEWLINE # result.status.state == PROCESSED (2)NEWLINE time.sleep(0.1)NEWLINE if on_error_raise:NEWLINE last_processing_result = result.processing_results[0]NEWLINE if last_processing_result.is_error:NEWLINE raise Exception(NEWLINE f"Deploy {deploy_hash} execution error: {last_processing_result.error_message}"NEWLINE )NEWLINENEWLINENEWLINEclass SmartContract:NEWLINE """NEWLINE Python interface for calling smart contracts.NEWLINE """NEWLINENEWLINE def __init__(self, file_name, methods):NEWLINE """NEWLINE :param file_name: Path to WASM file with smart contract.NEWLINE :param methods: Dictionary mapping contract methods toNEWLINE their signatures: names and types ofNEWLINE their parameters. See ERC20 for an example.NEWLINE """NEWLINE self.file_name = file_nameNEWLINE self.methods = methodsNEWLINENEWLINE def contract_hash_by_name(self, bound_agent, deployer, contract_name, block_hash):NEWLINE response = bound_agent.node.client.queryState(NEWLINE block_hash, key=deployer, path=contract_name, keyType="address"NEWLINE )NEWLINE return response.key.hash.hashNEWLINENEWLINE def __getattr__(self, name):NEWLINE return self.method(name)NEWLINENEWLINE def abi_encode_args(self, method_name, parameters, kwargs):NEWLINE args = [ABI.string_value("method", method_name)] + [NEWLINE parameters[p](p, kwargs[p]) for p in parametersNEWLINE ]NEWLINE return ABI.args(args)NEWLINENEWLINE def method(self, name):NEWLINE """NEWLINE Returns a function representing a smart contract's method.NEWLINENEWLINE The function returned can be called with keyword arguments matchingNEWLINE the smart contract's parameters and it will return a function thatNEWLINE accepts a BoundAgent and actually call the smart contract on a node.NEWLINENEWLINE :param name: name of the smart contract's methodNEWLINE """NEWLINE if name not in self.methods:NEWLINE raise Exception(f"unknown method {name}")NEWLINENEWLINE def callable_method(**kwargs):NEWLINE parameters = self.methods[name]NEWLINE if set(kwargs.keys()) != set(parameters.keys()):NEWLINE raise Exception(NEWLINE f"Arguments ({kwargs.keys()}) don't match parameters ({parameters.keys()}) of method {name}"NEWLINE )NEWLINE arguments = self.abi_encode_args(name, parameters, kwargs)NEWLINE arguments_string = f"{name}({','.join(f'{p}={type(kwargs[p]) == bytes and kwargs[p].hex() or kwargs[p]}' for p in parameters)})"NEWLINENEWLINE def deploy(bound_agent, **session_reference):NEWLINE kwargs = dict(NEWLINE public_key=bound_agent.agent.public_key,NEWLINE private_key=bound_agent.agent.private_key,NEWLINE payment_amount=PAYMENT_AMOUNT,NEWLINE session_args=arguments,NEWLINE )NEWLINE if session_reference:NEWLINE kwargs.update(session_reference)NEWLINE else:NEWLINE kwargs["session"] = self.file_nameNEWLINE logging.debug(f"Call {arguments_string}")NEWLINE # TODO: deploy will soon return just the deploy_hash onlyNEWLINE _, deploy_hash = bound_agent.node.client.deploy(**kwargs)NEWLINE deploy_hash = deploy_hash.hex()NEWLINE return deploy_hashNEWLINENEWLINE return deployNEWLINENEWLINE return callable_methodNEWLINENEWLINENEWLINEclass DeployedERC20:NEWLINE """NEWLINE Interface to an already deployed ERC20 smart contract.NEWLINE """NEWLINENEWLINE def __init__(self, erc20, token_hash, proxy_hash):NEWLINE """NEWLINE This constructor is not to be used directly, useNEWLINE DeployedERC20.create instead.NEWLINE """NEWLINE self.erc20 = erc20NEWLINE self.token_hash = token_hashNEWLINE self.proxy_hash = proxy_hashNEWLINENEWLINE @classmethodNEWLINE def create(cls, deployer: BoundAgent, token_name: str):NEWLINE """NEWLINE Returns DeployedERC20 object that provides interface toNEWLINE a deployed ERC20 smart contract.NEWLINE """NEWLINE erc20 = ERC20(token_name)NEWLINE block_hash = last_block_hash(deployer.node)NEWLINE return DeployedERC20(NEWLINE erc20,NEWLINE erc20.token_hash(deployer, deployer.agent.public_key_hex, block_hash),NEWLINE erc20.proxy_hash(deployer, deployer.agent.public_key_hex, block_hash),NEWLINE )NEWLINENEWLINE def balance(self, account_public_hex):NEWLINE """NEWLINE Returns function that can be passed a bound agent to returnNEWLINE the amount of ERC20 tokens deposited in the given account.NEWLINE """NEWLINENEWLINE def execute(bound_agent):NEWLINE key = f"{self.token_hash.hex()}:{BALANCE_KEY_SIZE_HEX}{BALANCE_BYTE}{account_public_hex}"NEWLINE block_hash_hex = last_block_hash(bound_agent.node)NEWLINE response = bound_agent.node.client.queryState(NEWLINE block_hash_hex, key=key, path="", keyType="local"NEWLINE )NEWLINE return int(response.big_int.value)NEWLINENEWLINE return executeNEWLINENEWLINE def transfer(self, sender_private_key, recipient_public_key_hex, amount):NEWLINE """NEWLINE Returns a function that can be passed a bound agent and transferNEWLINE given amount of ERC20 tokens from sender to recipient.NEWLINE """NEWLINENEWLINE def execute(bound_agent):NEWLINE return self.erc20.method("transfer")(NEWLINE erc20=self.token_hash,NEWLINE recipient=bytes.fromhex(recipient_public_key_hex),NEWLINE amount=amount,NEWLINE )(bound_agent, private_key=sender_private_key, session_hash=self.proxy_hash)NEWLINENEWLINE return executeNEWLINENEWLINENEWLINEclass ERC20(SmartContract):NEWLINE methods = {NEWLINE "deploy": {"token_name": ABI.string_value, "initial_balance": ABI.big_int},NEWLINE "transfer": {NEWLINE "erc20": ABI.bytes_value,NEWLINE "recipient": ABI.bytes_value,NEWLINE "amount": ABI.big_int,NEWLINE },NEWLINE "approve": {NEWLINE "erc20": ABI.bytes_value,NEWLINE "recipient": ABI.bytes_value,NEWLINE "amount": ABI.big_int,NEWLINE },NEWLINE "transfer_from": {NEWLINE "erc20": ABI.bytes_value,NEWLINE "owner": ABI.bytes_value,NEWLINE "recipient": ABI.bytes_value,NEWLINE "amount": ABI.big_int,NEWLINE },NEWLINE }NEWLINENEWLINE def __init__(self, token_name):NEWLINE super().__init__(ERC20_WASM, ERC20.methods)NEWLINE self.token_name = token_nameNEWLINE self.proxy_name = "erc20_proxy"NEWLINENEWLINE def abi_encode_args(self, method_name, parameters, kwargs):NEWLINE # When using proxy make sure that token_hash ('erc20') is the first argumentNEWLINE args = (NEWLINE [parameters[p](p, kwargs[p]) for p in parameters if p == "erc20"]NEWLINE + [ABI.string_value("method", method_name)]NEWLINE + [parameters[p](p, kwargs[p]) for p in parameters if p != "erc20"]NEWLINE )NEWLINE return ABI.args(args)NEWLINENEWLINE def proxy_hash(self, bound_agent, deployer_public_hex, block_hash):NEWLINE return self.contract_hash_by_name(NEWLINE bound_agent, deployer_public_hex, self.proxy_name, block_hashNEWLINE )NEWLINENEWLINE def token_hash(self, bound_agent, deployer_public_hex, block_hash):NEWLINE return self.contract_hash_by_name(NEWLINE bound_agent, deployer_public_hex, self.token_name, block_hashNEWLINE )NEWLINENEWLINE def deploy(self, initial_balance=None):NEWLINE def execute(bound_agent):NEWLINE deploy_hash = self.method("deploy")(NEWLINE token_name=self.token_name, initial_balance=initial_balanceNEWLINE )(bound_agent)NEWLINE return deploy_hashNEWLINENEWLINE return executeNEWLINENEWLINENEWLINEdef last_block_hash(node):NEWLINE return next(node.client.showBlocks(1)).summary.block_hash.hex()NEWLINE
"""NEWLINEMetric Learning for Kernel Regression (MLKR), Weinberger et al.,NEWLINENEWLINEMLKR is an algorithm for supervised metric learning, which learns a distanceNEWLINEfunction by directly minimising the leave-one-out regression error. ThisNEWLINEalgorithm can also be viewed as a supervised variation of PCA and can be usedNEWLINEfor dimensionality reduction and high dimensional data visualization.NEWLINE"""NEWLINEfrom __future__ import division, print_functionNEWLINEimport numpy as npNEWLINEfrom scipy.optimize import minimizeNEWLINEfrom scipy.spatial.distance import pdist, squareformNEWLINEfrom sklearn.decomposition import PCANEWLINEfrom sklearn.utils.validation import check_X_yNEWLINENEWLINEfrom .base_metric import BaseMetricLearnerNEWLINENEWLINEEPS = np.finfo(float).epsNEWLINENEWLINENEWLINEclass MLKR(BaseMetricLearner):NEWLINE """Metric Learning for Kernel Regression (MLKR)"""NEWLINE def __init__(self, num_dims=None, A0=None, epsilon=0.01, alpha=0.0001,NEWLINE max_iter=1000):NEWLINE """NEWLINE Initialize MLKR.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE num_dims : int, optionalNEWLINE Dimensionality of reduced space (defaults to dimension of X)NEWLINENEWLINE A0: array-like, optionalNEWLINE Initialization of transformation matrix. Defaults to PCA loadings.NEWLINENEWLINE epsilon: float, optionalNEWLINE Step size for congujate gradient descent.NEWLINENEWLINE alpha: float, optionalNEWLINE Stopping criterion for congujate gradient descent.NEWLINENEWLINE max_iter: int, optionalNEWLINE Cap on number of congugate gradient iterations.NEWLINE """NEWLINE self.num_dims = num_dimsNEWLINE self.A0 = A0NEWLINE self.epsilon = epsilonNEWLINE self.alpha = alphaNEWLINE self.max_iter = max_iterNEWLINENEWLINE def _process_inputs(self, X, y):NEWLINE self.X_, y = check_X_y(X, y)NEWLINE n, d = self.X_.shapeNEWLINE if y.shape[0] != n:NEWLINE raise ValueError('Data and label lengths mismatch: %d != %d'NEWLINE % (n, y.shape[0]))NEWLINENEWLINE A = self.A0NEWLINE m = self.num_dimsNEWLINE if m is None:NEWLINE m = dNEWLINE if A is None:NEWLINE # initialize to PCA transformation matrixNEWLINE # note: not the same as n_components=m !NEWLINE A = PCA().fit(X).components_.T[:m]NEWLINE elif A.shape != (m, d):NEWLINE raise ValueError('A0 needs shape (%d,%d) but got %s' % (NEWLINE m, d, A.shape))NEWLINE return self.X_, y, ANEWLINENEWLINE def fit(self, X, y):NEWLINE """NEWLINE Fit MLKR modelNEWLINENEWLINE Parameters:NEWLINE ----------NEWLINE X : (n x d) array of samplesNEWLINE y : (n) data labelsNEWLINE """NEWLINE X, y, A = self._process_inputs(X, y)NEWLINENEWLINE # note: this line takes (n*n*d) memory!NEWLINE # for larger datasets, we'll need to compute dX as we goNEWLINE dX = (X[None] - X[:, None]).reshape((-1, X.shape[1]))NEWLINENEWLINE res = minimize(_loss, A.ravel(), (X, y, dX), method='CG', jac=True,NEWLINE tol=self.alpha,NEWLINE options=dict(maxiter=self.max_iter, eps=self.epsilon))NEWLINE self.transformer_ = res.x.reshape(A.shape)NEWLINE self.n_iter_ = res.nitNEWLINE return selfNEWLINENEWLINE def transformer(self):NEWLINE return self.transformer_NEWLINENEWLINENEWLINEdef _loss(flatA, X, y, dX):NEWLINE A = flatA.reshape((-1, X.shape[1]))NEWLINE dist = pdist(X, metric='mahalanobis', VI=A.T.dot(A))NEWLINE K = squareform(np.exp(-dist**2))NEWLINE denom = np.maximum(K.sum(axis=0), EPS)NEWLINE yhat = K.dot(y) / denomNEWLINE ydiff = yhat - yNEWLINE cost = (ydiff**2).sum()NEWLINENEWLINE # also compute the gradientNEWLINE np.fill_diagonal(K, 1)NEWLINE W = 2 * K * (np.outer(ydiff, ydiff) / denom)NEWLINE # note: this is the part that the matlab impl drops to C forNEWLINE M = (dX.T * W.ravel()).dot(dX)NEWLINE grad = 2 * A.dot(M)NEWLINE return cost, grad.ravel()NEWLINE
"""Implements get optimizer method."""NEWLINEimport torchNEWLINENEWLINENEWLINEdef get_optimizer(optimizer):NEWLINE """Method to get optimizer from pytorch."""NEWLINE dir_optim = dir(torch.optim)NEWLINE opts = [o.lower() for o in dir_optim]NEWLINENEWLINE if isinstance(optimizer, str):NEWLINENEWLINE try:NEWLINE str_idx = opts.index(optimizer.lower())NEWLINE return getattr(torch.optim, dir_optim[str_idx])NEWLINE except ValueError:NEWLINE raise ValueError("Invalid optimizer string input - must match pytorch optimizer in torch.optim")NEWLINENEWLINE elif hasattr(optimizer, "step") and hasattr(optimizer, "zero_grad"):NEWLINENEWLINE return optimizerNEWLINENEWLINE else:NEWLINENEWLINE raise ValueError("Invalid optimizer input")NEWLINE
# coding=utf-8NEWLINE# Copyright 2018 The Tensor2Tensor Authors.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"""Library for training. See t2t_trainer.py."""NEWLINENEWLINEfrom __future__ import absolute_importNEWLINEfrom __future__ import divisionNEWLINEfrom __future__ import print_functionNEWLINENEWLINEimport osNEWLINEimport randomNEWLINEimport numpy as npNEWLINENEWLINEfrom tensor2tensor.utils import decodingNEWLINEfrom tensor2tensor.utils import devicesNEWLINEfrom tensor2tensor.utils import metrics_hookNEWLINEfrom tensor2tensor.utils import registryNEWLINEfrom tensor2tensor.utils import t2t_modelNEWLINENEWLINEimport tensorflow as tfNEWLINENEWLINEfrom tensorflow.core.protobuf import rewriter_config_pb2NEWLINEfrom tensorflow.python import debugNEWLINENEWLINENEWLINEdef next_checkpoint(model_dir, timeout_mins=120):NEWLINE """Yields successive checkpoints from model_dir."""NEWLINE last_ckpt = NoneNEWLINE while True:NEWLINE last_ckpt = tf.contrib.training.wait_for_new_checkpoint(NEWLINE model_dir, last_ckpt, seconds_to_sleep=60, timeout=60 * timeout_mins)NEWLINENEWLINE if last_ckpt is None:NEWLINE tf.logging.info(NEWLINE "Eval timeout: no new checkpoints within %dm" % timeout_mins)NEWLINE breakNEWLINENEWLINE yield last_ckptNEWLINENEWLINENEWLINEdef create_session_config(log_device_placement=False,NEWLINE enable_graph_rewriter=False,NEWLINE gpu_mem_fraction=0.95,NEWLINE use_tpu=False,NEWLINE inter_op_parallelism_threads=0,NEWLINE intra_op_parallelism_threads=0):NEWLINE """The TensorFlow Session config to use."""NEWLINE if use_tpu:NEWLINE graph_options = tf.GraphOptions()NEWLINE else:NEWLINE if enable_graph_rewriter:NEWLINE rewrite_options = rewriter_config_pb2.RewriterConfig()NEWLINE rewrite_options.layout_optimizer = rewriter_config_pb2.RewriterConfig.ONNEWLINE graph_options = tf.GraphOptions(rewrite_options=rewrite_options)NEWLINE else:NEWLINE graph_options = tf.GraphOptions(NEWLINE optimizer_options=tf.OptimizerOptions(NEWLINE opt_level=tf.OptimizerOptions.L1, do_function_inlining=False))NEWLINENEWLINE gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_mem_fraction)NEWLINENEWLINE config = tf.ConfigProto(NEWLINE allow_soft_placement=True,NEWLINE graph_options=graph_options,NEWLINE gpu_options=gpu_options,NEWLINE log_device_placement=log_device_placement,NEWLINE inter_op_parallelism_threads=inter_op_parallelism_threads,NEWLINE intra_op_parallelism_threads=intra_op_parallelism_threads)NEWLINE return configNEWLINENEWLINENEWLINEdef create_hparams(hparams_set,NEWLINE hparams_overrides_str="",NEWLINE data_dir=None,NEWLINE problem_name=None):NEWLINE """Create HParams with data_dir and problem hparams, if kwargs provided."""NEWLINE hparams = registry.hparams(hparams_set)NEWLINE if data_dir:NEWLINE hparams.add_hparam("data_dir", data_dir)NEWLINE if problem_name:NEWLINE add_problem_hparams(hparams, problem_name)NEWLINE if hparams_overrides_str:NEWLINE tf.logging.info("Overriding hparams in %s with %s", hparams_set,NEWLINE hparams_overrides_str)NEWLINE hparams = hparams.parse(hparams_overrides_str)NEWLINE return hparamsNEWLINENEWLINENEWLINEdef create_run_config(master="",NEWLINE model_dir=None,NEWLINE iterations_per_loop=1000,NEWLINE num_shards=8,NEWLINE log_device_placement=False,NEWLINE save_checkpoints_steps=1000,NEWLINE save_checkpoints_secs=None,NEWLINE keep_checkpoint_max=20,NEWLINE keep_checkpoint_every_n_hours=10000,NEWLINE num_gpus=1,NEWLINE gpu_order="",NEWLINE shard_to_cpu=False,NEWLINE num_async_replicas=1,NEWLINE enable_graph_rewriter=False,NEWLINE gpu_mem_fraction=0.95,NEWLINE no_data_parallelism=False,NEWLINE daisy_chain_variables=True,NEWLINE schedule="continuous_train_and_eval",NEWLINE worker_job="/job:localhost",NEWLINE worker_id=0,NEWLINE ps_replicas=0,NEWLINE ps_job="/job:ps",NEWLINE ps_gpu=0,NEWLINE random_seed=None,NEWLINE sync=False,NEWLINE tpu_infeed_sleep_secs=None,NEWLINE use_tpu=False,NEWLINE inter_op_parallelism_threads=0,NEWLINE log_step_count_steps=100,NEWLINE intra_op_parallelism_threads=0,NEWLINE tpu_config_extra_kwargs=None):NEWLINE """Create RunConfig, TPUConfig, and Parallelism object."""NEWLINE session_config = create_session_config(NEWLINE log_device_placement=log_device_placement,NEWLINE enable_graph_rewriter=enable_graph_rewriter,NEWLINE gpu_mem_fraction=gpu_mem_fraction,NEWLINE use_tpu=use_tpu,NEWLINE inter_op_parallelism_threads=inter_op_parallelism_threads,NEWLINE intra_op_parallelism_threads=intra_op_parallelism_threads)NEWLINE run_config_args = {NEWLINE "master": master,NEWLINE "evaluation_master": master,NEWLINE "model_dir": model_dir,NEWLINE "session_config": session_config,NEWLINE "save_summary_steps": 100,NEWLINE "save_checkpoints_steps": save_checkpoints_steps,NEWLINE "save_checkpoints_secs": save_checkpoints_secs,NEWLINE "keep_checkpoint_max": keep_checkpoint_max,NEWLINE "keep_checkpoint_every_n_hours": keep_checkpoint_every_n_hours,NEWLINE "tf_random_seed": random_seed,NEWLINE "log_step_count_steps": log_step_count_stepsNEWLINE }NEWLINE if save_checkpoints_secs:NEWLINE del run_config_args["save_checkpoints_steps"]NEWLINE run_config_cls = tf.contrib.learn.RunConfigNEWLINENEWLINE # If using TPU, use TPU RunConfig, add TPUConfig, and add additional argsNEWLINE if use_tpu:NEWLINE tpu_config_kwargs = {NEWLINE "iterations_per_loop": iterations_per_loop,NEWLINE "num_shards": num_shards,NEWLINE "per_host_input_for_training": True,NEWLINE "initial_infeed_sleep_secs": tpu_infeed_sleep_secs,NEWLINE }NEWLINE if tpu_config_extra_kwargs is not None:NEWLINE tpu_config_kwargs.update(tpu_config_extra_kwargs)NEWLINE run_config_cls = tf.contrib.tpu.RunConfigNEWLINE tpu_config = tf.contrib.tpu.TPUConfig(NEWLINE **tpu_config_kwargs)NEWLINE run_config_args["tpu_config"] = tpu_configNEWLINENEWLINE config = run_config_cls(**run_config_args)NEWLINENEWLINE # If not using TPU, add device info for data_parallelismNEWLINE config.use_tpu = use_tpuNEWLINE if not use_tpu:NEWLINE config.t2t_device_info = {NEWLINE "num_async_replicas": num_async_replicas,NEWLINE }NEWLINE config.data_parallelism = devices.data_parallelism(NEWLINE daisy_chain_variables=daisy_chain_variables,NEWLINE ps_replicas=ps_replicas,NEWLINE ps_job=ps_job,NEWLINE ps_gpu=ps_gpu,NEWLINE schedule=schedule,NEWLINE sync=sync,NEWLINE worker_gpu=num_gpus,NEWLINE worker_replicas=num_async_replicas,NEWLINE worker_id=worker_id,NEWLINE gpu_order=gpu_order,NEWLINE locally_shard_to_cpu=shard_to_cpu,NEWLINE worker_job=worker_job,NEWLINE no_data_parallelism=no_data_parallelism)NEWLINENEWLINE return configNEWLINENEWLINENEWLINEdef create_estimator(model_name,NEWLINE hparams,NEWLINE run_config,NEWLINE schedule="train_and_evaluate",NEWLINE decode_hparams=None,NEWLINE use_tpu=False):NEWLINE """Create a T2T Estimator."""NEWLINE model_fn = t2t_model.T2TModel.make_estimator_model_fn(NEWLINE model_name, hparams, decode_hparams=decode_hparams, use_tpu=use_tpu)NEWLINENEWLINE if use_tpu:NEWLINE problem = hparams.problemNEWLINE batch_size = (NEWLINE problem.tpu_batch_size_per_shard(hparams) *NEWLINE run_config.tpu_config.num_shards)NEWLINE if getattr(hparams, "mtf_mode", False):NEWLINE batch_size = problem.tpu_batch_size_per_shard(hparams)NEWLINE predict_batch_size = batch_sizeNEWLINE if decode_hparams and decode_hparams.batch_size:NEWLINE predict_batch_size = decode_hparams.batch_sizeNEWLINE estimator = tf.contrib.tpu.TPUEstimator(NEWLINE model_fn=model_fn,NEWLINE model_dir=run_config.model_dir,NEWLINE config=run_config,NEWLINE train_batch_size=batch_size,NEWLINE eval_batch_size=batch_size if "eval" in schedule else None,NEWLINE predict_batch_size=predict_batch_size)NEWLINE else:NEWLINE estimator = tf.estimator.Estimator(NEWLINE model_fn=model_fn, model_dir=run_config.model_dir, config=run_config)NEWLINE return estimatorNEWLINENEWLINENEWLINEdef create_hooks(use_tfdbg=False,NEWLINE use_dbgprofile=False,NEWLINE dbgprofile_kwargs=None,NEWLINE use_validation_monitor=False,NEWLINE validation_monitor_kwargs=None,NEWLINE use_early_stopping=False,NEWLINE early_stopping_kwargs=None):NEWLINE """Create train and eval hooks for Experiment."""NEWLINE train_hooks = []NEWLINE eval_hooks = []NEWLINENEWLINE if use_tfdbg:NEWLINE hook = debug.LocalCLIDebugHook()NEWLINE train_hooks.append(hook)NEWLINE eval_hooks.append(hook)NEWLINENEWLINE if use_dbgprofile:NEWLINE # Recorded traces can be visualized with chrome://tracing/NEWLINE # The memory/tensor lifetime is also profiledNEWLINE tf.logging.info("Using ProfilerHook")NEWLINE defaults = dict(save_steps=10, show_dataflow=True, show_memory=True)NEWLINE defaults.update(dbgprofile_kwargs)NEWLINE train_hooks.append(tf.train.ProfilerHook(**defaults))NEWLINENEWLINE if use_validation_monitor:NEWLINE tf.logging.info("Using ValidationMonitor")NEWLINE train_hooks.append(NEWLINE tf.contrib.learn.monitors.ValidationMonitor(NEWLINE hooks=eval_hooks, **validation_monitor_kwargs))NEWLINENEWLINE if use_early_stopping:NEWLINE tf.logging.info("Using EarlyStoppingHook")NEWLINE hook = metrics_hook.EarlyStoppingHook(**early_stopping_kwargs)NEWLINE # Adding to both training and eval so that eval aborts as wellNEWLINE train_hooks.append(hook)NEWLINE eval_hooks.append(hook)NEWLINENEWLINE return train_hooks, eval_hooksNEWLINENEWLINENEWLINEclass T2TExperiment(object):NEWLINE """Custom Experiment class for running distributed experiments."""NEWLINENEWLINE def __init__(self, estimator, hparams, train_spec, eval_spec,NEWLINE use_validation_monitor, decode_hparams=None):NEWLINE self._train_spec = train_specNEWLINE self._eval_spec = eval_specNEWLINE self._hparams = hparamsNEWLINE self._decode_hparams = decode_hparamsNEWLINE self._estimator = estimatorNEWLINE self._use_validation_monitor = use_validation_monitorNEWLINENEWLINE @propertyNEWLINE def estimator(self):NEWLINE return self._estimatorNEWLINENEWLINE @propertyNEWLINE def train_steps(self):NEWLINE return self._train_spec.max_stepsNEWLINENEWLINE @propertyNEWLINE def eval_steps(self):NEWLINE return self._eval_spec.stepsNEWLINENEWLINE def continuous_train_and_eval(self, continuous_eval_predicate_fn=None):NEWLINE del continuous_eval_predicate_fnNEWLINE tf.estimator.train_and_evaluate(self._estimator, self._train_spec,NEWLINE self._eval_spec)NEWLINE return self.evaluate()NEWLINENEWLINE def train_and_evaluate(self):NEWLINE if self._use_validation_monitor:NEWLINE tf.logging.warning("EvalSpec not provided. Estimator will not manage "NEWLINE "model evaluation. Assuming ValidationMonitor present "NEWLINE "in train_hooks.")NEWLINE self.train()NEWLINENEWLINE def train(self):NEWLINE self._estimator.train(NEWLINE self._train_spec.input_fn,NEWLINE hooks=self._train_spec.hooks,NEWLINE max_steps=self._train_spec.max_steps)NEWLINENEWLINE def evaluate(self):NEWLINE return self._estimator.evaluate(NEWLINE self._eval_spec.input_fn,NEWLINE steps=self._eval_spec.steps,NEWLINE hooks=self._eval_spec.hooks)NEWLINENEWLINE def evaluate_on_train_data(self):NEWLINE self._estimator.evaluate(NEWLINE self._train_spec.input_fn,NEWLINE steps=self._eval_spec.steps,NEWLINE hooks=self._eval_spec.hooks,NEWLINE name="eval_train")NEWLINENEWLINE def continuous_eval(self):NEWLINE """Evaluate until checkpoints stop being produced."""NEWLINE for _ in next_checkpoint(self._hparams.model_dir):NEWLINE self.evaluate()NEWLINENEWLINE def continuous_eval_on_train_data(self):NEWLINE """Evaluate on train data until checkpoints stop being produced."""NEWLINE for _ in next_checkpoint(self._hparams.model_dir):NEWLINE self.evaluate_on_train_data()NEWLINENEWLINE def test(self):NEWLINE """Perform 1 step of train and 2 step of eval."""NEWLINE if self._use_validation_monitor:NEWLINE return self.train_and_evaluate()NEWLINENEWLINE self._estimator.train(NEWLINE self._train_spec.input_fn, hooks=self._train_spec.hooks, max_steps=1)NEWLINENEWLINE self._estimator.evaluate(NEWLINE self._eval_spec.input_fn, steps=1, hooks=self._eval_spec.hooks)NEWLINENEWLINE def run_std_server(self):NEWLINE """Starts a TensorFlow server and joins the serving thread.NEWLINENEWLINE Typically used for parameter servers.NEWLINENEWLINE Raises:NEWLINE ValueError: if not enough information is available in the estimator'sNEWLINE config to create a server.NEWLINE """NEWLINE config = self._estimator.configNEWLINE if (not config.cluster_spec or not config.task_type or not config.master orNEWLINE config.task_id is None):NEWLINE raise ValueError("Could not start server; be sure to specify "NEWLINE "cluster_spec, task_type, master, and task in "NEWLINE "RunConfig or set the TF_CONFIG environment variable.")NEWLINE server = tf.train.Server(NEWLINE config.cluster_spec,NEWLINE job_name=config.task_type,NEWLINE task_index=config.task_id,NEWLINE config=config.tf_config,NEWLINE start=False)NEWLINE server.start()NEWLINE server.join()NEWLINENEWLINE def decode(self):NEWLINE """Decodes from dataset."""NEWLINE decoding.decode_from_dataset(self._estimator, self._hparams.problem.name,NEWLINE self._hparams, self._decode_hparams)NEWLINENEWLINE def continuous_decode(self):NEWLINE """Decode from dataset on new checkpoint."""NEWLINE for _ in next_checkpoint(self._hparams.model_dir):NEWLINE self.decode()NEWLINENEWLINENEWLINEdef create_experiment(NEWLINE run_config,NEWLINE hparams,NEWLINE model_name,NEWLINE problem_name,NEWLINE data_dir,NEWLINE train_steps,NEWLINE eval_steps,NEWLINE min_eval_frequency=2000,NEWLINE eval_throttle_seconds=600,NEWLINE schedule="train_and_evaluate",NEWLINE export=False,NEWLINE decode_hparams=None,NEWLINE use_tfdbg=False,NEWLINE use_dbgprofile=False,NEWLINE eval_early_stopping_steps=None,NEWLINE eval_early_stopping_metric=None,NEWLINE eval_early_stopping_metric_delta=None,NEWLINE eval_early_stopping_metric_minimize=True,NEWLINE autotune=False,NEWLINE use_tpu=False):NEWLINE """Create Experiment."""NEWLINE # HParamsNEWLINE hparams.add_hparam("model_dir", run_config.model_dir)NEWLINE hparams.add_hparam("data_dir", data_dir)NEWLINE hparams.add_hparam("train_steps", train_steps)NEWLINE hparams.add_hparam("eval_steps", eval_steps)NEWLINE hparams.add_hparam("schedule", schedule)NEWLINE add_problem_hparams(hparams, problem_name)NEWLINENEWLINE # EstimatorNEWLINE estimator = create_estimator(NEWLINE model_name,NEWLINE hparams,NEWLINE run_config,NEWLINE schedule=schedule,NEWLINE decode_hparams=decode_hparams,NEWLINE use_tpu=use_tpu)NEWLINENEWLINE # Input fns from ProblemNEWLINE problem = hparams.problemNEWLINE train_input_fn = problem.make_estimator_input_fn(tf.estimator.ModeKeys.TRAIN,NEWLINE hparams)NEWLINE eval_input_fn = problem.make_estimator_input_fn(tf.estimator.ModeKeys.EVAL,NEWLINE hparams)NEWLINENEWLINE # ExportNEWLINE if export:NEWLINE tf.logging.warn("Exporting from the trainer is deprecated. "NEWLINE "See serving/export.py.")NEWLINENEWLINE # HooksNEWLINE validation_monitor_kwargs = dict(NEWLINE input_fn=eval_input_fn,NEWLINE eval_steps=eval_steps,NEWLINE every_n_steps=min_eval_frequency,NEWLINE early_stopping_rounds=eval_early_stopping_steps,NEWLINE early_stopping_metric=eval_early_stopping_metric,NEWLINE early_stopping_metric_minimize=eval_early_stopping_metric_minimize)NEWLINE dbgprofile_kwargs = {"output_dir": run_config.model_dir}NEWLINE early_stopping_kwargs = dict(NEWLINE events_dir=os.path.join(run_config.model_dir, "eval_continuous"),NEWLINE tag=eval_early_stopping_metric,NEWLINE num_plateau_steps=eval_early_stopping_steps,NEWLINE plateau_decrease=eval_early_stopping_metric_minimize,NEWLINE plateau_delta=eval_early_stopping_metric_delta,NEWLINE every_n_steps=min_eval_frequency)NEWLINENEWLINE # In-process eval (and possible early stopping)NEWLINE if schedule == "continuous_train_and_eval" and min_eval_frequency:NEWLINE tf.logging.warn("ValidationMonitor only works with "NEWLINE "--schedule=train_and_evaluate")NEWLINE use_validation_monitor = (NEWLINE schedule == "train_and_evaluate" and min_eval_frequency)NEWLINE # Distributed early stoppingNEWLINE local_schedules = ["train_and_evaluate", "continuous_train_and_eval"]NEWLINE use_early_stopping = (NEWLINE schedule not in local_schedules and eval_early_stopping_steps)NEWLINE train_hooks, eval_hooks = create_hooks(NEWLINE use_tfdbg=use_tfdbg,NEWLINE use_dbgprofile=use_dbgprofile,NEWLINE dbgprofile_kwargs=dbgprofile_kwargs,NEWLINE use_validation_monitor=use_validation_monitor,NEWLINE validation_monitor_kwargs=validation_monitor_kwargs,NEWLINE use_early_stopping=use_early_stopping,NEWLINE early_stopping_kwargs=early_stopping_kwargs)NEWLINE train_hooks += t2t_model.T2TModel.get_train_hooks(model_name)NEWLINE eval_hooks += t2t_model.T2TModel.get_eval_hooks(model_name)NEWLINENEWLINE train_hooks = tf.contrib.learn.monitors.replace_monitors_with_hooks(NEWLINE train_hooks, estimator)NEWLINE eval_hooks = tf.contrib.learn.monitors.replace_monitors_with_hooks(NEWLINE eval_hooks, estimator)NEWLINENEWLINE train_spec = tf.estimator.TrainSpec(NEWLINE train_input_fn, max_steps=train_steps, hooks=train_hooks)NEWLINE eval_spec = tf.estimator.EvalSpec(NEWLINE eval_input_fn,NEWLINE steps=eval_steps,NEWLINE hooks=eval_hooks,NEWLINE start_delay_secs=0 if hparams.schedule == "evaluate" else 120,NEWLINE throttle_secs=eval_throttle_seconds)NEWLINENEWLINE if autotune:NEWLINE hooks_kwargs = {"train_monitors": train_hooks, "eval_hooks": eval_hooks}NEWLINE return tf.contrib.learn.Experiment(NEWLINE estimator=estimator,NEWLINE train_input_fn=train_input_fn,NEWLINE eval_input_fn=eval_input_fn,NEWLINE train_steps=train_steps,NEWLINE eval_steps=eval_steps,NEWLINE min_eval_frequency=min_eval_frequency,NEWLINE train_steps_per_iteration=min(min_eval_frequency, train_steps),NEWLINE eval_delay_secs=0 if schedule == "evaluate" else 120,NEWLINE **hooks_kwargs if not use_tpu else {})NEWLINE return T2TExperiment(estimator, hparams, train_spec, eval_spec,NEWLINE use_validation_monitor, decode_hparams)NEWLINENEWLINENEWLINEdef create_experiment_fn(*args, **kwargs):NEWLINE """Wrapper for canonical experiment_fn. See create_experiment."""NEWLINENEWLINE def experiment_fn(run_config, hparams):NEWLINE return create_experiment(run_config, hparams, *args, **kwargs)NEWLINENEWLINE return experiment_fnNEWLINENEWLINENEWLINEdef create_export_strategy(problem, hparams):NEWLINE return tf.contrib.learn.make_export_strategy(NEWLINE lambda: problem.serving_input_fn(hparams), as_text=True)NEWLINENEWLINENEWLINEdef add_problem_hparams(hparams, problem_name):NEWLINE """Add problem hparams for the problems."""NEWLINE problem = registry.problem(problem_name)NEWLINE p_hparams = problem.get_hparams(hparams)NEWLINENEWLINE hparams.problem = problemNEWLINE hparams.problem_hparams = p_hparamsNEWLINENEWLINENEWLINEdef set_random_seed(seed):NEWLINE tf.set_random_seed(seed)NEWLINE random.seed(seed)NEWLINE np.random.seed(seed)NEWLINENEWLINENEWLINEdef restore_checkpoint(ckpt_dir, saver, sess, must_restore=False):NEWLINE """Restore from a checkpoint."""NEWLINE ckpt = tf.train.get_checkpoint_state(ckpt_dir)NEWLINE if must_restore and not ckpt:NEWLINE raise ValueError("No checkpoint found in %s" % ckpt_dir)NEWLINE if not ckpt:NEWLINE return 0NEWLINENEWLINE path = ckpt.model_checkpoint_pathNEWLINE tf.logging.info("Restoring checkpoint %s", path)NEWLINE saver.restore(sess, path)NEWLINE step = int(path.split("-")[-1])NEWLINE return stepNEWLINE
"""NEWLINETests for navtagsNEWLINE"""NEWLINENEWLINEimport pytestNEWLINEassert pytestNEWLINENEWLINEfrom django.http import HttpRequestNEWLINENEWLINEfrom hm_web.templatetags import navtagsNEWLINENEWLINENEWLINEdef build_request(path):NEWLINE """NEWLINE Build an HttpRequest object with the given pathNEWLINE """NEWLINE request = HttpRequest()NEWLINE request.path = pathNEWLINE return requestNEWLINENEWLINENEWLINEdef test_home_active():NEWLINE assert navtags.active(build_request('/'), '/') == 'active'NEWLINE assert navtags.active(build_request('/login'), '/') == ''NEWLINENEWLINENEWLINEdef test_login_active():NEWLINE assert navtags.active(build_request('/'), '/login') == ''NEWLINE assert navtags.active(build_request('/login'), '/login') == 'active'NEWLINE
import timeNEWLINEimport typingNEWLINEimport inspectNEWLINEfrom uuid import uuid4NEWLINEfrom broccoli.injector import ASyncInjectorNEWLINEfrom broccoli.components import ReturnValueNEWLINEfrom broccoli.task import create_taskNEWLINEfrom broccoli.result import AsyncResultNEWLINEfrom broccoli.types import App, Broker, Task, Message, Arguments, Fence, TaskLoggerNEWLINEfrom broccoli.traceback import extract_log_tbNEWLINEfrom broccoli.utils import cached_propertyNEWLINEfrom broccoli.graph import GraphNEWLINEfrom broccoli.exceptions import RejectNEWLINEfrom broccoli.router import ROUTER_COMPONENTSNEWLINEfrom broccoli.broker import BROKER_COMPONENTSNEWLINEfrom broccoli.logger import LOGGER_COMPONENTSNEWLINEfrom broccoli.config import CONFIG_COMPONENTSNEWLINEfrom broccoli.arguments import ARGUMENT_COMPONENTSNEWLINENEWLINE__all__ = ('Broccoli',)NEWLINENEWLINENEWLINEclass nullfence:NEWLINENEWLINE def __enter__(self):NEWLINE passNEWLINENEWLINE def __exit__(self, *excinfo):NEWLINE passNEWLINENEWLINENEWLINEclass Broccoli(App):NEWLINE _injector: ASyncInjector = NoneNEWLINE _tasks: typing.Dict[str, Task] = NoneNEWLINE result_factory = AsyncResultNEWLINE graph_factory = GraphNEWLINENEWLINE def __init__(self, components=None, settings=None) -> None:NEWLINE if components:NEWLINE msg = 'components must be a list of instances of Component.'NEWLINE assert all([(not isinstance(component, type) and hasattr(component, 'resolve'))NEWLINE for component in components]), msgNEWLINE if settings is not None:NEWLINE msg = 'settings must be a dict.'NEWLINE assert isinstance(settings, dict), msgNEWLINENEWLINE self.settings = settingsNEWLINE self._init_injector(components or [])NEWLINE self._tasks = {}NEWLINE self._context = {}NEWLINE self._graphs = {}NEWLINENEWLINE def set_context(self, **context):NEWLINE self._context = dict(self._context, **context)NEWLINE self._graphs = {}NEWLINE self._injector.clear_cache()NEWLINENEWLINE def get_context(self):NEWLINE return self._contextNEWLINENEWLINE def set_hooks(self,NEWLINE on_request: typing.Callable = None,NEWLINE on_response: typing.Callable = None):NEWLINE if on_request:NEWLINE if inspect.iscoroutinefunction(on_request):NEWLINE msg = 'Function %r may not be async.'NEWLINE raise TypeError(msg % on_request)NEWLINE self._on_request_hook = on_requestNEWLINE elif '_on_request_hook' in self.__dict__:NEWLINE del self._on_request_hookNEWLINE if on_response:NEWLINE if inspect.iscoroutinefunction(on_response):NEWLINE msg = 'Function %r may not be async.'NEWLINE raise TypeError(msg % on_response)NEWLINE self._on_response_hook = on_responseNEWLINE elif '_on_response_hook' in self.__dict__:NEWLINE del self._on_response_hookNEWLINENEWLINE def _init_injector(self, components):NEWLINE components = components or []NEWLINE components += ROUTER_COMPONENTSNEWLINE components += LOGGER_COMPONENTSNEWLINE components += BROKER_COMPONENTSNEWLINE components += CONFIG_COMPONENTSNEWLINE components += ARGUMENT_COMPONENTSNEWLINENEWLINE initial = {NEWLINE 'app': App,NEWLINE 'message': Message,NEWLINE 'args': Arguments,NEWLINE 'task': Task,NEWLINE 'exc': Exception,NEWLINE 'fence': FenceNEWLINE }NEWLINENEWLINE self._injector = ASyncInjector(components, initial)NEWLINENEWLINE def inject(self, funcs, args=None, cache=True):NEWLINE state = {NEWLINE 'app': self,NEWLINE 'message': None,NEWLINE 'args': args,NEWLINE 'task': None,NEWLINE 'exc': None,NEWLINE 'fence': NoneNEWLINE }NEWLINE return self._injector.run(NEWLINE funcs,NEWLINE state=state,NEWLINE cache=cacheNEWLINE )NEWLINENEWLINE def get_task(self, name: str):NEWLINE try:NEWLINE return self._tasks[name]NEWLINE except KeyError:NEWLINE raise Reject('Task %s not found' % name)NEWLINENEWLINE def task(self, *args, **kwargs):NEWLINE def create_task_wrapper(func):NEWLINE if inspect.iscoroutinefunction(func):NEWLINE msg = 'Function %r may not be async.'NEWLINE raise TypeError(msg % func)NEWLINE task = create_task(self, func, **kwargs)NEWLINE if task.name in self._tasks:NEWLINE msg = 'Task with name %r is already registered.'NEWLINE raise TypeError(msg % task.name)NEWLINE self._tasks[task.name] = taskNEWLINE return taskNEWLINENEWLINE if len(args) == 1:NEWLINE if callable(args[0]):NEWLINE return create_task_wrapper(*args)NEWLINE raise TypeError("Argument 1 to @task() must be a callable")NEWLINENEWLINE if args:NEWLINE raise TypeError("@task() takes exactly 1 argument")NEWLINENEWLINE return create_task_wrapperNEWLINENEWLINE def send_message(self, message: dict):NEWLINE self._broker.send_message(message)NEWLINENEWLINE def result(self, result_key: str):NEWLINE return self.result_factory(self, result_key)NEWLINENEWLINE def serve_message(self, message: dict, fence: Fence = None):NEWLINE if 'id' not in message:NEWLINE raise Reject('no id')NEWLINENEWLINE if 'task' not in message:NEWLINE raise Reject('no task')NEWLINENEWLINE if 'reply_id' in message:NEWLINE if 'graph_id' not in message:NEWLINE raise Reject('no graph_id')NEWLINE graph_id = message['graph_id']NEWLINE if graph_id not in self._graphs:NEWLINE raise Reject('unexpected graph_id')NEWLINE graph = self._graphs[graph_id]NEWLINE if message['reply_id'] not in graph:NEWLINE raise Reject('unexpected reply id')NEWLINE graph.run_reply(message)NEWLINE return graph.get_pending_messages()NEWLINE else:NEWLINE coro = self._run_async(message, fence)NEWLINE try:NEWLINE graph = coro.send(None)NEWLINE graph.set_coroutine(coro)NEWLINE return graph.get_pending_messages()NEWLINE except StopIteration as stop:NEWLINE return [stop.value]NEWLINENEWLINE async def _run_async(self, message, fence):NEWLINE state = {NEWLINE 'app': self,NEWLINE 'message': message,NEWLINE 'fence': fence,NEWLINE 'args': None,NEWLINE 'task': None,NEWLINE 'exc': None,NEWLINE 'return_value': NoneNEWLINE }NEWLINENEWLINE try:NEWLINE __log_tb_start__ = NoneNEWLINE task = self.get_task(message['task'])NEWLINE state['task'] = taskNEWLINE funcs = (NEWLINE self._on_request,NEWLINE self._on_request_hook,NEWLINE self._build_graph,NEWLINE task.handler,NEWLINE self._on_response_hook,NEWLINE self._on_response,NEWLINE )NEWLINE return await self._injector.run_async(funcs, state=state)NEWLINE except Exception as exc:NEWLINE try:NEWLINE state['exc'] = excNEWLINE step = state.get('$step', 0)NEWLINE if 0 < step < 4:NEWLINE funcs = (self._on_response_hook, self._on_response)NEWLINE else:NEWLINE funcs = (self._on_response,)NEWLINE return self._injector.run(funcs, state=state)NEWLINE except Exception as inner_exc:NEWLINE state['exc'] = inner_excNEWLINE return self._injector.run((self._on_response,), state)NEWLINENEWLINE @staticmethodNEWLINE def _on_request(message: Message):NEWLINE expires_at = message.get('expires_at')NEWLINE if expires_at is not None and isinstance(expires_at, (int, float)):NEWLINE if expires_at < time.time():NEWLINE raise Reject('Due to expiration time.')NEWLINENEWLINE @staticmethodNEWLINE def _on_request_hook(ret: ReturnValue):NEWLINE return retNEWLINENEWLINE async def _build_graph(self, task: Task, message: Message) -> Arguments:NEWLINE args = ()NEWLINE if message.get('subtasks'):NEWLINE graph = self.graph_factory(message)NEWLINE self._graphs[graph.id] = graphNEWLINE try:NEWLINE args = await graphNEWLINE finally:NEWLINE graph.close()NEWLINE del self._graphs[graph.id]NEWLINE return task.get_arguments(NEWLINE *((message.get('args') or ()) + tuple(args)),NEWLINE **(message.get('kwargs') or {})NEWLINE )NEWLINENEWLINE @staticmethodNEWLINE def _on_response_hook(ret: ReturnValue):NEWLINE return retNEWLINENEWLINE @staticmethodNEWLINE def _on_response(message: Message,NEWLINE exc: Exception,NEWLINE logger: TaskLogger,NEWLINE return_value: ReturnValue,NEWLINE task: Task):NEWLINE reply = {'id': str(uuid4()), 'task': message['task'], 'reply_id': message['id']}NEWLINE if 'graph_id' in message:NEWLINE reply['graph_id'] = message['graph_id']NEWLINE if 'reply_to' in message:NEWLINE reply['reply_to'] = message['reply_to']NEWLINE if 'result_key' in message:NEWLINE if message.get('ignore_result', task.ignore_result):NEWLINE reply['result_key'] = NoneNEWLINE else:NEWLINE reply['result_key'] = message['result_key']NEWLINE if '_context' in message:NEWLINE reply['_context'] = message['_context']NEWLINE if exc is not None:NEWLINE reply['exc'] = excNEWLINE if isinstance(exc, task.throws) or isinstance(exc, Reject):NEWLINE logger.error("Task {'id': %r, 'task': %r} raised exception %s: %s",NEWLINE message['id'], message['task'], exc.__class__.__name__, exc)NEWLINE return replyNEWLINE else:NEWLINE traceback = extract_log_tb(exc)NEWLINE if traceback:NEWLINE reply['traceback'] = tracebackNEWLINE logger.error("Task {'id': %r, 'task': %r} raised exception %s: %s\n%s",NEWLINE message['id'], message['task'], exc.__class__.__name__, exc, traceback)NEWLINE return replyNEWLINE reply['value'] = return_valueNEWLINE return replyNEWLINENEWLINE @cached_propertyNEWLINE def _broker(self) -> Broker:NEWLINE def get(obj: Broker):NEWLINE return objNEWLINENEWLINE return self.inject([get], cache=False)NEWLINE
import osNEWLINEimport numpy as npNEWLINEimport streamlit as stNEWLINEimport pikapi.utils.loggingNEWLINENEWLINEimport pikapi.facelandmark_utils as fluNEWLINEfrom pikapi.head_gestures import YesOrNoEstimator, get_minmax_feature_from_base_dir, get_stateNEWLINENEWLINEdef detection_analysis_dashboard():NEWLINE # @st.cache(allow_output_mutation=True)NEWLINE def load_data(result_folder):NEWLINE return pikapi.utils.logging.HumanReadableLog.load_from_path(result_folder)NEWLINENEWLINE def get_from_box(box):NEWLINE return ((box[2] + box[0])/2 - 250)/50 * 0.05NEWLINENEWLINE def get_x_from_box(box):NEWLINE return ((box[3] + box[1])/2 - 425)NEWLINENEWLINE def get_positions(detection_lists):NEWLINE positions = []NEWLINE for detection_list in detection_lists:NEWLINE found = FalseNEWLINE for detection in detection_list[1]:NEWLINE if detection["label"] == "onahole":NEWLINE found = TrueNEWLINE positions.append(get_x_from_box(detection["box"]))NEWLINE breakNEWLINE NEWLINE if not found:NEWLINE if len(positions) == 0:NEWLINE positions.append(None)NEWLINE else:NEWLINE positions.append(positions[-1])NEWLINENEWLINE return positionsNEWLINENEWLINE def get_sequence_from_label(sequence, labels):NEWLINE assert(len(labels) > 0)NEWLINE previous_label = labels[0].dataNEWLINE partial_seq = []NEWLINE # st.write(labels)NEWLINE for elm, label in zip(sequence, labels):NEWLINE # st.write(label.data)NEWLINE if label.data == previous_label:NEWLINE partial_seq.append(elm)NEWLINE else:NEWLINE yield partial_seq, previous_labelNEWLINE partial_seq = []NEWLINE previous_label = label.dataNEWLINENEWLINE # Choose result dir.NEWLINE result_folders_dir = st.text_input("Location of result folders.", "output-data/")NEWLINE result_folders = sorted(list(next(os.walk(result_folders_dir))[1]), reverse=True)NEWLINE result_folder = st.selectbox("Result folder", result_folders)NEWLINENEWLINE logged_data = load_data(os.path.join("output-data", result_folder))NEWLINENEWLINE images = logged_data.get_images_with_timestamp('input_frame')NEWLINE multi_face_landmark_lists = logged_data.get_data("multi_face_landmarks")NEWLINE motion_labels = logged_data.get_data("motion_label")NEWLINENEWLINE label_to_values = {NEWLINE "Nodding": 1,NEWLINE "Shaking": -1,NEWLINE }NEWLINE label_values = [label_to_values[motion_label.data] if motion_label.data is not None else 0 for motion_label in motion_labels]NEWLINE assert(len(images) == len(multi_face_landmark_lists))NEWLINENEWLINE frame_index = st.slider("Index", 0, len(images))NEWLINENEWLINE st.image(images[frame_index].data)NEWLINE st.write(multi_face_landmark_lists[frame_index].data)NEWLINE st.write(flu.simple_face_direction(multi_face_landmark_lists[frame_index].data[0], only_direction=True))NEWLINE direction_ys = [NEWLINE flu.simple_face_direction(multi_face_landmarks.data[0], only_direction=True)[1] \NEWLINE if len(multi_face_landmarks.data) > 0 else NoneNEWLINE for multi_face_landmarks in multi_face_landmark_listsNEWLINE ]NEWLINE direction_xs = [NEWLINE flu.simple_face_direction(multi_face_landmarks.data[0], only_direction=True)[0] \NEWLINE if len(multi_face_landmarks.data) > 0 else NoneNEWLINE for multi_face_landmarks in multi_face_landmark_listsNEWLINE ]NEWLINE st.write(direction_ys)NEWLINE timestamps = [NEWLINE multi_face_landmarks.timestamp - multi_face_landmark_lists[0].timestampNEWLINE for multi_face_landmarks in multi_face_landmark_listsNEWLINE ]NEWLINE # aaa = range(0, )NEWLINE # predictions = [NEWLINE # get_state(multi_face_landmark_lists[:i])NEWLINE # for i in range(1, len(multi_face_landmark_lists))NEWLINE # ]NEWLINE estimator = YesOrNoEstimator()NEWLINE predictions = []NEWLINE for multi_face_landmark_list in multi_face_landmark_lists:NEWLINE predictions.append(estimator.get_state(multi_face_landmark_list))NEWLINENEWLINE assert len(timestamps) == len(motion_labels)NEWLINENEWLINE import plotly.graph_objects as goNEWLINE fig = go.Figure(NEWLINE data=[NEWLINE go.Scatter(x=timestamps, y=direction_ys, name="y", line = dict(width=4, dash='dot')),NEWLINE go.Scatter(x=timestamps, y=direction_xs, name="x", line = dict(width=4, dash='dot')),NEWLINE go.Scatter(x=timestamps, y=label_values, name="true", line = dict(width=2)),NEWLINE go.Scatter(x=timestamps, y=predictions, name="preds", line = dict(width=4, dash='dot')),NEWLINE ],NEWLINE )NEWLINE fig.update_layout(xaxis_title='timestamp')NEWLINE st.write(fig)NEWLINENEWLINE # for landmark_partial_seq, label in get_sequence_from_label(multi_face_landmark_lists, motion_labels):NEWLINE # if label == "Nodding" or label == "Shaking":NEWLINE # st.write(label)NEWLINE # st.write(get_minmax_feature_from_base_dir(landmark_partial_seq, None))NEWLINENEWLINENEWLINE def draw_landmark_2d_with_index(landmark, filter_ids=[]):NEWLINE import matplotlib.pyplot as pltNEWLINE fig = plt.figure()NEWLINE ax1 = fig.add_subplot(111)NEWLINENEWLINE for i, keypoint in enumerate(landmark):NEWLINE if len(filter_ids) == 0 or i in filter_ids:NEWLINE ax1.text(keypoint[0], keypoint[1], s=str(i))NEWLINENEWLINE # direction = flu.simple_face_direction(landmark)NEWLINE # direction = direction / np.linalg.norm(direction)NEWLINE # ax1.plot(direction[:,0], direction[:,1], direction[:,2])NEWLINE if len(filter_ids) == 0:NEWLINE ax1.scatter(landmark[:,0],landmark[:,1])NEWLINE else:NEWLINE ax1.scatter(landmark[filter_ids,0],landmark[filter_ids,1])NEWLINE # st.write(fig)NEWLINE plt.show()NEWLINENEWLINE st.plotly_chart(get_landmark_3d_with_index_v2(np.array(multi_face_landmark_lists[frame_index].data[0])))NEWLINENEWLINENEWLINEdef get_landmark_3d_with_index_v2(landmark):NEWLINE import plotly.graph_objects as goNEWLINE fig = go.Figure()NEWLINENEWLINE fig.add_trace(go.Scatter3d(NEWLINE x=landmark[:,0],NEWLINE y=landmark[:,1],NEWLINE z=landmark[:,2],NEWLINE mode='markers'NEWLINE ))NEWLINE NEWLINE fig.update_layout(NEWLINE scene=dict(NEWLINE aspectmode="manual",NEWLINE aspectratio=dict(NEWLINE x=1,NEWLINE y=1,NEWLINE z=1NEWLINE ),NEWLINE annotations=[NEWLINE dict(NEWLINE showarrow=False,NEWLINE xanchor="left",NEWLINE xshift=10,NEWLINE x=x,NEWLINE y=y,NEWLINE z=z,NEWLINE text=str(index)NEWLINE ) for index, (x,y,z) in enumerate(landmark)NEWLINE ]NEWLINE )NEWLINE )NEWLINE return figNEWLINENEWLINEdetection_analysis_dashboard()NEWLINE
# Copyright 2020-present, Pietro Buzzega, Matteo Boschini, Angelo Porrello, Davide Abati, Simone Calderara.NEWLINE# All rights reserved.NEWLINE# This source code is licensed under the license found in theNEWLINE# LICENSE file in the root directory of this source tree.NEWLINENEWLINEimport randomNEWLINEimport torchNEWLINEimport numpy as npNEWLINENEWLINEdef get_device() -> torch.device:NEWLINE """NEWLINE Returns the GPU device if available else CPU.NEWLINE """NEWLINE return torch.device("cuda:0" if torch.cuda.is_available() else "cpu")NEWLINENEWLINENEWLINEdef base_path() -> str:NEWLINE """NEWLINE Returns the base bath where to log accuracies and tensorboard data.NEWLINE """NEWLINE return './data/'NEWLINENEWLINENEWLINEdef set_random_seed(seed: int) -> None:NEWLINE """NEWLINE Sets the seeds at a certain value.NEWLINE :param seed: the value to be setNEWLINE """NEWLINE random.seed(seed)NEWLINE np.random.seed(seed)NEWLINE torch.manual_seed(seed)NEWLINE torch.cuda.manual_seed_all(seed)NEWLINE
#!/usr/bin/env pythonNEWLINE#NEWLINE# ontoviz documentation build configuration file, created byNEWLINE# sphinx-quickstart on Fri Jun 9 13:47:02 2017.NEWLINE#NEWLINE# This file is execfile()d with the current directory set to itsNEWLINE# containing dir.NEWLINE#NEWLINE# Note that not all possible configuration values are present in thisNEWLINE# autogenerated file.NEWLINE#NEWLINE# All configuration values have a default; values that are commented outNEWLINE# serve to show the default.NEWLINENEWLINE# If extensions (or modules to document with autodoc) are in anotherNEWLINE# directory, add these directories to sys.path here. If the directory isNEWLINE# relative to the documentation root, use os.path.abspath to make itNEWLINE# absolute, like shown here.NEWLINE#NEWLINEimport sysNEWLINEfrom pathlib import PathNEWLINENEWLINEthis_dir = Path(__file__).resolve().parentNEWLINEroot_dir = (this_dir / '..').resolve()NEWLINEsys.path.insert(0, str(root_dir))NEWLINEsys.path.insert(0, str(this_dir))NEWLINENEWLINEimport ontovizNEWLINENEWLINE# -- General configuration ---------------------------------------------NEWLINENEWLINE# If your documentation needs a minimal Sphinx version, state it here.NEWLINE#NEWLINE# needs_sphinx = '1.0'NEWLINENEWLINE# Add any Sphinx extension module names here, as strings. They can beNEWLINE# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.NEWLINEextensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode', "autoapi", "myst_nb"]NEWLINENEWLINE# Add any paths that contain templates here, relative to this directory.NEWLINEtemplates_path = ['_templates']NEWLINENEWLINE# The suffix(es) of source filenames.NEWLINE# You can specify multiple suffix as a list of string:NEWLINE#NEWLINE# source_suffix = ['.rst', '.md']NEWLINEsource_suffix = {NEWLINE '.rst': 'restructuredtext',NEWLINE '.ipynb': 'myst-nb',NEWLINE '.md': 'myst-nb',NEWLINE}NEWLINENEWLINE# The master toctree document.NEWLINEmaster_doc = 'index'NEWLINENEWLINE# General information about the project.NEWLINEproject = 'ontoviz'NEWLINEcopyright = "2021, René Fritze"NEWLINEauthor = "René Fritze"NEWLINENEWLINE# The version info for the project you're documenting, acts as replacementNEWLINE# for |version| and |release|, also used in various other places throughoutNEWLINE# the built documents.NEWLINE#NEWLINE# The short X.Y version.NEWLINEversion = ontoviz.__version__NEWLINE# The full version, including alpha/beta/rc tags.NEWLINErelease = ontoviz.__version__NEWLINENEWLINE# The language for content autogenerated by Sphinx. Refer to documentationNEWLINE# for a list of supported languages.NEWLINE#NEWLINE# This is also used if you do content translation via gettext catalogs.NEWLINE# Usually you set "language" from the command line for these cases.NEWLINElanguage = NoneNEWLINENEWLINE# List of patterns, relative to source directory, that match files andNEWLINE# directories to ignore when looking for source files.NEWLINE# This patterns also effect to html_static_path and html_extra_pathNEWLINEexclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']NEWLINENEWLINE# The name of the Pygments (syntax highlighting) style to use.NEWLINEpygments_style = 'sphinx'NEWLINENEWLINE# If true, `todo` and `todoList` produce output, else they produce nothing.NEWLINEtodo_include_todos = TrueNEWLINENEWLINENEWLINE# -- Options for HTML output -------------------------------------------NEWLINENEWLINE# The theme to use for HTML and HTML Help pages. See the documentation forNEWLINE# a list of builtin themes.NEWLINE#NEWLINEhtml_theme = 'alabaster'NEWLINENEWLINE# Theme options are theme-specific and customize the look and feel of aNEWLINE# theme further. For a list of options available for each theme, see theNEWLINE# documentation.NEWLINE#NEWLINE# html_theme_options = {}NEWLINENEWLINE# Add any paths that contain custom static files (such as style sheets) here,NEWLINE# relative to this directory. They are copied after the builtin static files,NEWLINE# so a file named "default.css" will overwrite the builtin "default.css".NEWLINEhtml_static_path = ['_static']NEWLINENEWLINENEWLINE# -- Options for HTMLHelp output ---------------------------------------NEWLINENEWLINE# Output file base name for HTML help builder.NEWLINEhtmlhelp_basename = 'ontovizdoc'NEWLINENEWLINENEWLINE# -- Options for LaTeX output ------------------------------------------NEWLINENEWLINElatex_elements = {NEWLINE # The paper size ('letterpaper' or 'a4paper').NEWLINE #NEWLINE # 'papersize': 'letterpaper',NEWLINE # The font size ('10pt', '11pt' or '12pt').NEWLINE #NEWLINE # 'pointsize': '10pt',NEWLINE # Additional stuff for the LaTeX preamble.NEWLINE #NEWLINE # 'preamble': '',NEWLINE # Latex figure (float) alignmentNEWLINE #NEWLINE # 'figure_align': 'htbp',NEWLINE}NEWLINENEWLINE# Grouping the document tree into LaTeX files. List of tuplesNEWLINE# (source start file, target name, title, author, documentclassNEWLINE# [howto, manual, or own class]).NEWLINElatex_documents = [NEWLINE (master_doc, 'ontoviz.tex', 'ontoviz Documentation', 'René Fritze', 'manual'),NEWLINE]NEWLINENEWLINENEWLINE# -- Options for manual page output ------------------------------------NEWLINENEWLINE# One entry per manual page. List of tuplesNEWLINE# (source start file, name, description, authors, manual section).NEWLINEman_pages = [(master_doc, 'ontoviz', 'ontoviz Documentation', [author], 1)]NEWLINENEWLINENEWLINE# -- Options for Texinfo output ----------------------------------------NEWLINENEWLINE# Grouping the document tree into Texinfo files. List of tuplesNEWLINE# (source start file, target name, title, author,NEWLINE# dir menu entry, description, category)NEWLINEtexinfo_documents = [NEWLINE (NEWLINE master_doc,NEWLINE 'ontoviz',NEWLINE 'ontoviz Documentation',NEWLINE author,NEWLINE 'ontoviz',NEWLINE 'One line description of project.',NEWLINE 'Miscellaneous',NEWLINE ),NEWLINE]NEWLINENEWLINEautoapi_python_use_implicit_namespaces = TrueNEWLINEautoapi_dirs = [root_dir / 'ontoviz']NEWLINEautoapi_type = 'python'NEWLINE# allows incremental buildNEWLINEautoapi_keep_files = TrueNEWLINEautoapi_template_dir = this_dir / '_templates' / 'autoapi'NEWLINENEWLINEnb_execution_mode = "cache"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
#!/usr/bin/env python3NEWLINE# -*- coding: utf-8 -*-NEWLINENEWLINE# @author Copyright (c) 2022 Damir Dzeko AnticNEWLINE# @license MIT No AttributionNEWLINE# @version 0.1.2NEWLINE# @lastUpdate 2022-02-05NEWLINENEWLINE# ChangeLog:NEWLINE# - can be tested with: python3 -m unittest tomtomLookup.pyNEWLINE# - added object destructor to close the session/socketNEWLINENEWLINENEWLINEimport sysNEWLINEtry:NEWLINE assert (sys.version_info.major == 3 and sys.version_info.minor >= 7), "Python version must be 3.7 or newer"NEWLINEexcept Exception as e:NEWLINE print (e)NEWLINE sys.exit(1)NEWLINENEWLINEimport timeNEWLINEfrom os import environNEWLINENEWLINEfrom datetime import timedeltaNEWLINENEWLINEfrom requests_cache import CachedSessionNEWLINEimport unittestNEWLINEimport jsonNEWLINENEWLINENEWLINETOMTOM_AUTH_KEY = environ.get("TOMTOM_AUTH_KEY")NEWLINENEWLINEdef tomtom_url(gps_od, gps_do):NEWLINE def prefix():NEWLINE return 'https://api.tomtom.com/routing/1/calculateRoute/'NEWLINE def suffix():NEWLINE return (f'/json?key={TOMTOM_AUTH_KEY}&routeRepresentation=summaryOnly&maxAlternatives=0' + NEWLINE '&computeTravelTimeFor=none&routeType=fastest&traffic=false&travelMode=car')NEWLINE return f'{prefix()}{",".join(gps_od)}:{",".join(gps_do)}{suffix()}'NEWLINENEWLINENEWLINEclass TomTomLookup():NEWLINENEWLINE def _make_throttle_hook(timeout=1.0):NEWLINE """Make a request hook function that adds a custom delay for non-cached requests"""NEWLINE def hook(response, *args, **kwargs):NEWLINE if not getattr(response, 'from_cache', False):NEWLINE # print('sleeping')NEWLINE time.sleep(timeout)NEWLINE return responseNEWLINE return hookNEWLINENEWLINE def __init__(self):NEWLINE session = CachedSession('./requests_cache.db', NEWLINE backend='sqlite', NEWLINE timeout=30, NEWLINE expire_after=timedelta(days=30),NEWLINE old_data_on_error=True,NEWLINE serializer='json')NEWLINE session.hooks['response'].append(TomTomLookup._make_throttle_hook(1.25))NEWLINE self.session = sessionNEWLINENEWLINE def getUrl(self, url):NEWLINE response = self.session.get(url)NEWLINE if response.status_code != 200:NEWLINE raise Exception("TomTomLookup: GET call returned invalid response")NEWLINE return response.textNEWLINENEWLINE def getDistance_from_resp(self, response_text):NEWLINE try:NEWLINE json_obj = json.loads(response_text)NEWLINE return json_obj['routes'][0]['summary']['lengthInMeters']NEWLINE except:NEWLINE raise Exception("TomTomLookup: Failed to decode REST API response")NEWLINENEWLINE def getDistance_from_url(self, url):NEWLINE response_text = self.getUrl(url)NEWLINE return self.getDistance_from_resp(response_text)NEWLINENEWLINE def __del__(self):NEWLINE self.session.close()NEWLINENEWLINEclass TestTomTomLookup(unittest.TestCase):NEWLINE def setUp(self):NEWLINE self.tomtom = TomTomLookup()NEWLINENEWLINE def test_one_url(self):NEWLINE response_text = self.tomtom.getUrl('http://httpbin.org/delay/3')NEWLINE response_obj = json.loads(response_text)NEWLINE self.assertTrue(response_obj['url'] is not None)NEWLINENEWLINENEWLINEdef main():NEWLINE print(f'{__file__} should not be run as stand-alone program')NEWLINE return 2NEWLINENEWLINEif __name__ == '__main__':NEWLINE sys.exit(main())
import unittestNEWLINENEWLINENEWLINEclass TestLocalizable(unittest.TestCase):NEWLINE def test___init__(self):NEWLINE # localizable = Localizable(project, subpath, created)NEWLINE assert False # TODO: implement your test hereNEWLINENEWLINE def test_exists(self):NEWLINE # localizable = Localizable(project, subpath, created)NEWLINE # self.assertEqual(expected, localizable.exists())NEWLINE assert False # TODO: implement your test hereNEWLINENEWLINE def test_get_path(self):NEWLINE # localizable = Localizable(project, subpath, created)NEWLINE # self.assertEqual(expected, localizable.get_path())NEWLINE assert False # TODO: implement your test hereNEWLINENEWLINE def test_is_out_of_sync(self):NEWLINE # localizable = Localizable(project, subpath, created)NEWLINE # self.assertEqual(expected, localizable.is_out_of_sync())NEWLINE assert False # TODO: implement your test hereNEWLINENEWLINE def test_is_up_to_date(self):NEWLINE # localizable = Localizable(project, subpath, created)NEWLINE # self.assertEqual(expected, localizable.is_up_to_date())NEWLINE assert False # TODO: implement your test hereNEWLINENEWLINE def test_write(self):NEWLINE # localizable = Localizable(project, subpath, created)NEWLINE # self.assertEqual(expected, localizable.write(new_content))NEWLINE assert False # TODO: implement your test hereNEWLINENEWLINEif __name__ == '__main__':NEWLINE unittest.main()NEWLINE
# Generated by Django 3.2.4 on 2021-06-18 02:41NEWLINENEWLINEfrom django.db import migrations, modelsNEWLINENEWLINENEWLINEclass Migration(migrations.Migration):NEWLINENEWLINE initial = TrueNEWLINENEWLINE dependencies = [NEWLINE ]NEWLINENEWLINE operations = [NEWLINE migrations.CreateModel(NEWLINE name='Project',NEWLINE fields=[NEWLINE ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),NEWLINE ('title', models.CharField(max_length=200)),NEWLINE ('description', models.TextField()),NEWLINE ('image', models.ImageField(upload_to='')),NEWLINE ('created', models.DateField(auto_now_add=True)),NEWLINE ('updated', models.DateTimeField(auto_now=True)),NEWLINE ],NEWLINE ),NEWLINE ]NEWLINE
import osNEWLINEimport reNEWLINEfrom collections import defaultdictNEWLINEfrom dataclasses import dataclassNEWLINEfrom typing import Dict, SetNEWLINENEWLINEimport easyargsNEWLINEfrom colorama import Fore, StyleNEWLINEfrom javalang import parse as parserNEWLINEfrom javalang.parser import JavaSyntaxErrorNEWLINEfrom javalang.tree import (NEWLINE ClassDeclaration,NEWLINE FieldDeclaration,NEWLINE FormalParameter,NEWLINE Import,NEWLINE Literal,NEWLINE MethodInvocation,NEWLINE ReferenceType,NEWLINE VariableDeclaration,NEWLINE)NEWLINEfrom tqdm import tqdmNEWLINENEWLINENEWLINE@dataclass(frozen=True)NEWLINEclass CalleeDesc:NEWLINE class_name: strNEWLINE method_name: strNEWLINENEWLINENEWLINEdef traverse(t, visitor):NEWLINE if not hasattr(t, "children"):NEWLINE returnNEWLINE for child in t.children:NEWLINE if not child:NEWLINE continueNEWLINE if isinstance(child, list):NEWLINE for item in child:NEWLINE traverse(item, visitor)NEWLINE else:NEWLINE traverse(child, visitor)NEWLINE visitor(t)NEWLINENEWLINENEWLINEdef print_file_name(filename):NEWLINE tqdm.write(Fore.RED + filename + Style.RESET_ALL)NEWLINENEWLINENEWLINEclass Scanner:NEWLINE def __init__(self, filename) -> None:NEWLINENEWLINE self.filename = filenameNEWLINE with open(filename) as fl:NEWLINE text = fl.read()NEWLINE self.AST = parser.parse(text)NEWLINE self.text_by_lines = text.split("\n")NEWLINE self.env: Dict[str, str] = {}NEWLINE self.call_nodes: Dict[CalleeDesc, Set[MethodInvocation]] = defaultdict(set)NEWLINE self.imports: Set[str] = set()NEWLINE self.wildcard_imports: Set[str] = set()NEWLINE self.extend_nodes: Dict[str, Set[ClassDeclaration]] = defaultdict(set)NEWLINE traverse(self.AST, self.visitor)NEWLINE self.inverted_import_names = {NEWLINE import_name.split(".")[-1]: import_name for import_name in self.importsNEWLINE }NEWLINENEWLINE def lookup_type(self, name):NEWLINE if name in self.env:NEWLINE return self.env[name]NEWLINE return NoneNEWLINENEWLINE @staticmethodNEWLINE def literal_arguments_only(call_node):NEWLINE for arg in call_node.arguments:NEWLINE if not isinstance(arg, Literal):NEWLINE return FalseNEWLINE return TrueNEWLINENEWLINE def push_type_resolution(self, name, assigned_type):NEWLINE self.env[name] = assigned_typeNEWLINENEWLINE def visitor(self, node):NEWLINE if isinstance(node, Import):NEWLINE if node.wildcard:NEWLINE self.wildcard_imports.add(node.path)NEWLINE else:NEWLINE self.imports.add(node.path)NEWLINENEWLINE elif isinstance(node, ClassDeclaration):NEWLINE if isinstance(node.extends, ReferenceType):NEWLINE self.push_type_resolution(node.name, node.extends.name)NEWLINE self.extend_nodes[node.extends.name].add(node)NEWLINENEWLINE elif isinstance(node, (VariableDeclaration, FieldDeclaration)):NEWLINE for declarator in node.declarators:NEWLINE self.push_type_resolution(declarator.name, node.type.name)NEWLINENEWLINE elif isinstance(node, MethodInvocation):NEWLINE relevant_type = self.lookup_type(node.qualifier)NEWLINE if relevant_type:NEWLINE self.call_nodes[CalleeDesc(relevant_type, node.member)].add(node)NEWLINENEWLINE elif isinstance(node, FormalParameter):NEWLINE self.push_type_resolution(node.name, node.type.name)NEWLINENEWLINE def class_name_matches(self, class_name, regex):NEWLINE if "." in class_name:NEWLINE return regex.match(class_name)NEWLINE if class_name in self.inverted_import_names:NEWLINE return regex.match(self.inverted_import_names[class_name])NEWLINE return any(NEWLINE regex.match(f"{wildcard_import}.{class_name}")NEWLINE for wildcard_import in self.wildcard_importsNEWLINE )NEWLINENEWLINE def find_calls(self, class_regex_compiled, method_regex_compiled):NEWLINE for callee, call_nodes in self.call_nodes.items():NEWLINE if self.class_name_matches(NEWLINE callee.class_name, class_regex_compiledNEWLINE ) and method_regex_compiled.match(callee.method_name):NEWLINENEWLINE non_constant_calls = [NEWLINE node for node in call_nodes if not self.literal_arguments_only(node)NEWLINE ]NEWLINE if non_constant_calls:NEWLINE yield non_constant_callsNEWLINENEWLINE def find_extends(self, class_compiled_regex):NEWLINE for class_name, class_nodes in self.extend_nodes.items():NEWLINE if self.class_name_matches(class_name, class_compiled_regex):NEWLINE yield class_nodesNEWLINENEWLINE def print_node_code_lines(self, nodes):NEWLINE for node in nodes:NEWLINE tqdm.write(NEWLINE Fore.GREENNEWLINE + f"{node.position.line:5d} "NEWLINE + Style.RESET_ALLNEWLINE + f"{self.text_by_lines[node.position.line - 1]}"NEWLINE )NEWLINENEWLINENEWLINEdef quick_match(filename, match_regex_compiled):NEWLINE txt = open(filename).read()NEWLINE return match_regex_compiled.search(txt)NEWLINENEWLINENEWLINEdef find_use_in_file(filename, root_folder, class_regex, method_regex):NEWLINE class_regex_compiled = re.compile(class_regex)NEWLINE method_regex_compiled = re.compile(method_regex)NEWLINE if not quick_match(filename, class_regex_compiled):NEWLINE returnNEWLINE relative_filename = os.path.relpath(filename, root_folder)NEWLINE first = TrueNEWLINE extends = FalseNEWLINE scanner = Scanner(filename)NEWLINE for nodelist in scanner.find_calls(class_regex_compiled, method_regex_compiled):NEWLINE if first:NEWLINE print_file_name(relative_filename)NEWLINE first = FalseNEWLINE scanner.print_node_code_lines(nodelist)NEWLINE for nodelist in scanner.find_extends(class_regex_compiled):NEWLINE if first:NEWLINE print_file_name(relative_filename)NEWLINE first = FalseNEWLINE extends = TrueNEWLINE scanner.print_node_code_lines(nodelist)NEWLINE if extends:NEWLINE tqdm.write(NEWLINE f"{Fore.RED}!!! Warning: vulnerable class extended !!!{Style.RESET_ALL}"NEWLINE )NEWLINENEWLINENEWLINEdef traverse_folder(root_dir):NEWLINE for directory, dirs, files in os.walk(root_dir):NEWLINE for filename in files:NEWLINE if filename.endswith(".java"):NEWLINE yield os.path.join(directory, filename)NEWLINENEWLINENEWLINE@easyargsNEWLINEdef scan(NEWLINE root_dir,NEWLINE class_regex=r"org.apache.logging.log4j.Logger",NEWLINE method_regex="(info|warn|error|log|debug|trace|fatal|catching|throwing|traceEntry|printf|logMessage)",NEWLINE):NEWLINE parsing_failed_files = []NEWLINE for filename in tqdm(list(traverse_folder(root_dir))):NEWLINE try:NEWLINE find_use_in_file(filename, root_dir, class_regex, method_regex)NEWLINE except (IOError, JavaSyntaxError):NEWLINE parsing_failed_files.append(filename)NEWLINE if parsing_failed_files:NEWLINE with open("err.log", "w") as f:NEWLINE f.write("Parsing failed:\n" + "\n".join(parsing_failed_files))NEWLINENEWLINENEWLINEif __name__ == "__main__":NEWLINE scan()NEWLINE
import torchNEWLINEimport numpy as npNEWLINENEWLINEfrom torch.nn.utils.clip_grad import clip_grad_norm_NEWLINEfrom maml.utils import accuracyNEWLINENEWLINEdef get_grad_norm(parameters, norm_type=2):NEWLINE if isinstance(parameters, torch.Tensor):NEWLINE parameters = [parameters]NEWLINE parameters = list(filter(lambda p: p.grad is not None, parameters))NEWLINE norm_type = float(norm_type)NEWLINE total_norm = 0NEWLINE for p in parameters:NEWLINE param_norm = p.grad.data.norm(norm_type)NEWLINE total_norm += param_norm.item() ** norm_typeNEWLINE total_norm = total_norm ** (1. / norm_type)NEWLINENEWLINE return total_normNEWLINENEWLINEclass MetaLearner(object):NEWLINE def __init__(self, model, embedding_model, optimizers, fast_lr, loss_func,NEWLINE first_order, num_updates, inner_loop_grad_clip,NEWLINE collect_accuracies, device, alternating=False,NEWLINE embedding_schedule=10, classifier_schedule=10,NEWLINE embedding_grad_clip=0):NEWLINE self._model = modelNEWLINE self._embedding_model = embedding_modelNEWLINE self._fast_lr = fast_lrNEWLINE self._optimizers = optimizersNEWLINE self._loss_func = loss_funcNEWLINE self._first_order = first_orderNEWLINE self._num_updates = num_updatesNEWLINE self._inner_loop_grad_clip = inner_loop_grad_clipNEWLINE self._collect_accuracies = collect_accuraciesNEWLINE self._device = deviceNEWLINE self._alternating = alternatingNEWLINE self._alternating_schedules = (classifier_schedule, embedding_schedule)NEWLINE self._alternating_count = 0NEWLINE self._alternating_index = 1NEWLINE self._embedding_grad_clip = embedding_grad_clipNEWLINE self._grads_mean = []NEWLINENEWLINE self.to(device)NEWLINENEWLINE self._reset_measurements()NEWLINENEWLINE def _reset_measurements(self):NEWLINE self._count_iters = 0.0NEWLINE self._cum_loss = 0.0NEWLINE self._cum_accuracy = 0.0NEWLINENEWLINE def _update_measurements(self, task, loss, preds):NEWLINE self._count_iters += 1.0NEWLINE self._cum_loss += loss.data.cpu().numpy()NEWLINE if self._collect_accuracies:NEWLINE self._cum_accuracy += accuracy(NEWLINE preds, task.y).data.cpu().numpy()NEWLINENEWLINE def _pop_measurements(self):NEWLINE measurements = {}NEWLINE loss = self._cum_loss / self._count_itersNEWLINE measurements['loss'] = lossNEWLINE if self._collect_accuracies:NEWLINE accuracy = self._cum_accuracy / self._count_itersNEWLINE measurements['accuracy'] = accuracyNEWLINE self._reset_measurements()NEWLINE return measurementsNEWLINENEWLINE def measure(self, tasks, train_tasks=None, adapted_params_list=None,NEWLINE embeddings_list=None):NEWLINE """Measures performance on tasks. Either train_tasks has to be a listNEWLINE of training task for computing embeddings, or adapted_params_list andNEWLINE embeddings_list have to contain adapted_params and embeddings"""NEWLINE if adapted_params_list is None:NEWLINE adapted_params_list = [None] * len(tasks)NEWLINE if embeddings_list is None:NEWLINE embeddings_list = [None] * len(tasks)NEWLINE for i in range(len(tasks)):NEWLINE params = adapted_params_list[i]NEWLINE if params is None:NEWLINE params = self._model.param_dictNEWLINE embeddings = embeddings_list[i]NEWLINE task = tasks[i]NEWLINE preds = self._model(task, params=params, embeddings=embeddings)NEWLINE loss = self._loss_func(preds, task.y)NEWLINE self._update_measurements(task, loss, preds)NEWLINENEWLINE measurements = self._pop_measurements()NEWLINE return measurementsNEWLINENEWLINE def measure_each(self, tasks, train_tasks=None, adapted_params_list=None,NEWLINE embeddings_list=None):NEWLINE """Measures performance on tasks. Either train_tasks has to be a listNEWLINE of training task for computing embeddings, or adapted_params_list andNEWLINE embeddings_list have to contain adapted_params and embeddings"""NEWLINE """Return a list of losses and accuracies"""NEWLINE if adapted_params_list is None:NEWLINE adapted_params_list = [None] * len(tasks)NEWLINE if embeddings_list is None:NEWLINE embeddings_list = [None] * len(tasks)NEWLINE accuracies = []NEWLINE for i in range(len(tasks)):NEWLINE params = adapted_params_list[i]NEWLINE if params is None:NEWLINE params = self._model.param_dictNEWLINE embeddings = embeddings_list[i]NEWLINE task = tasks[i]NEWLINE preds = self._model(task, params=params, embeddings=embeddings)NEWLINE pred_y = np.argmax(preds.data.cpu().numpy(), axis=-1)NEWLINE accuracy = np.mean(NEWLINE task.y.data.cpu().numpy() == NEWLINE np.argmax(preds.data.cpu().numpy(), axis=-1))NEWLINE accuracies.append(accuracy)NEWLINENEWLINE return accuraciesNEWLINENEWLINE def update_params(self, loss, params):NEWLINE """Apply one step of gradient descent on the loss function `loss`,NEWLINE with step-size `self._fast_lr`, and returns the updated parameters.NEWLINE """NEWLINE create_graph = not self._first_orderNEWLINE grads = torch.autograd.grad(loss, params.values(),NEWLINE create_graph=create_graph, allow_unused=True)NEWLINE for (name, param), grad in zip(params.items(), grads):NEWLINE if self._inner_loop_grad_clip > 0 and grad is not None:NEWLINE grad = grad.clamp(min=-self._inner_loop_grad_clip,NEWLINE max=self._inner_loop_grad_clip)NEWLINE if grad is not None:NEWLINE params[name] = param - self._fast_lr * gradNEWLINENEWLINE return paramsNEWLINENEWLINE def adapt(self, train_tasks):NEWLINE adapted_params = []NEWLINE embeddings_list = []NEWLINENEWLINE for task in train_tasks:NEWLINE params = self._model.param_dictNEWLINE embeddings = NoneNEWLINE if self._embedding_model:NEWLINE embeddings = self._embedding_model(task)NEWLINE for i in range(self._num_updates):NEWLINE preds = self._model(task, params=params, embeddings=embeddings)NEWLINE loss = self._loss_func(preds, task.y)NEWLINE params = self.update_params(loss, params=params)NEWLINE if i == 0:NEWLINE self._update_measurements(task, loss, preds)NEWLINE adapted_params.append(params)NEWLINE embeddings_list.append(embeddings)NEWLINENEWLINE measurements = self._pop_measurements()NEWLINE return measurements, adapted_params, embeddings_listNEWLINENEWLINE def step(self, adapted_params_list, embeddings_list, val_tasks,NEWLINE is_training):NEWLINE for optimizer in self._optimizers:NEWLINE optimizer.zero_grad()NEWLINE post_update_losses = []NEWLINENEWLINE for adapted_params, embeddings, task in zip(NEWLINE adapted_params_list, embeddings_list, val_tasks):NEWLINE preds = self._model(task, params=adapted_params,NEWLINE embeddings=embeddings)NEWLINE loss = self._loss_func(preds, task.y)NEWLINE post_update_losses.append(loss)NEWLINE self._update_measurements(task, loss, preds)NEWLINENEWLINE mean_loss = torch.mean(torch.stack(post_update_losses))NEWLINE if is_training:NEWLINE mean_loss.backward()NEWLINE if self._alternating:NEWLINE self._optimizers[self._alternating_index].step()NEWLINE self._alternating_count += 1NEWLINE if self._alternating_count % self._alternating_schedules[self._alternating_index] == 0:NEWLINE self._alternating_index = (1 - self._alternating_index)NEWLINE self._alternating_count = 0NEWLINE else:NEWLINE self._optimizers[0].step()NEWLINE if len(self._optimizers) > 1:NEWLINE if self._embedding_grad_clip > 0:NEWLINE _grad_norm = clip_grad_norm_(self._embedding_model.parameters(), self._embedding_grad_clip)NEWLINE else:NEWLINE _grad_norm = get_grad_norm(self._embedding_model.parameters())NEWLINE # grad_normNEWLINE self._grads_mean.append(_grad_norm)NEWLINE self._optimizers[1].step()NEWLINENEWLINE measurements = self._pop_measurements()NEWLINE return measurementsNEWLINENEWLINE def to(self, device, **kwargs):NEWLINE self._device = deviceNEWLINE self._model.to(device, **kwargs)NEWLINE if self._embedding_model:NEWLINE self._embedding_model.to(device, **kwargs)NEWLINENEWLINE def state_dict(self):NEWLINE state = {NEWLINE 'model_state_dict': self._model.state_dict(),NEWLINE 'optimizers': [ optimizer.state_dict() for optimizer in self._optimizers ]NEWLINE }NEWLINE if self._embedding_model:NEWLINE state.update(NEWLINE {'embedding_model_state_dict':NEWLINE self._embedding_model.state_dict()})NEWLINE return stateNEWLINE
import numpy as npNEWLINEimport itertools as itNEWLINENEWLINEfrom big_ol_pile_of_manim_imports import *NEWLINENEWLINEfrom old_projects.brachistochrone.curves import \NEWLINE Cycloid, PathSlidingScene, RANDY_SCALE_FACTOR, TryManyPathsNEWLINENEWLINENEWLINEclass Lens(Arc):NEWLINE CONFIG = {NEWLINE "radius" : 2,NEWLINE "angle" : np.pi/2,NEWLINE "color" : BLUE_B,NEWLINE }NEWLINE def __init__(self, **kwargs):NEWLINE digest_config(self, kwargs)NEWLINE Arc.__init__(self, self.angle, **kwargs)NEWLINENEWLINE def generate_points(self):NEWLINE Arc.generate_points(self)NEWLINE self.rotate(-np.pi/4)NEWLINE self.shift(-self.get_left())NEWLINE self.add_points(self.copy().rotate(np.pi).points)NEWLINENEWLINENEWLINENEWLINEclass PhotonScene(Scene):NEWLINE def wavify(self, mobject):NEWLINE result = mobject.copy()NEWLINE result.ingest_submobjects()NEWLINE tangent_vectors = result.points[1:]-result.points[:-1]NEWLINE lengths = np.apply_along_axis(NEWLINE np.linalg.norm, 1, tangent_vectorsNEWLINE )NEWLINE thick_lengths = lengths.repeat(3).reshape((len(lengths), 3))NEWLINE unit_tangent_vectors = tangent_vectors/thick_lengthsNEWLINE rot_matrix = np.transpose(rotation_matrix(np.pi/2, OUT))NEWLINE normal_vectors = np.dot(unit_tangent_vectors, rot_matrix)NEWLINE # total_length = np.sum(lengths)NEWLINE times = np.cumsum(lengths)NEWLINE nudge_sizes = 0.1*np.sin(2*np.pi*times)NEWLINE thick_nudge_sizes = nudge_sizes.repeat(3).reshape((len(nudge_sizes), 3))NEWLINE nudges = thick_nudge_sizes*normal_vectorsNEWLINE result.points[1:] += nudgesNEWLINE return resultNEWLINENEWLINENEWLINE def photon_run_along_path(self, path, color = YELLOW, **kwargs):NEWLINE if "rate_func" not in kwargs:NEWLINE kwargs["rate_func"] = NoneNEWLINE photon = self.wavify(path)NEWLINE photon.set_color(color)NEWLINE return ShowPassingFlash(photon, **kwargs)NEWLINENEWLINENEWLINEclass SimplePhoton(PhotonScene):NEWLINE def construct(self):NEWLINE text = TextMobject("Light")NEWLINE text.to_edge(UP)NEWLINE self.play(ShimmerIn(text))NEWLINE self.play(self.photon_run_along_path(NEWLINE Cycloid(), rate_func = NoneNEWLINE ))NEWLINE self.wait()NEWLINENEWLINENEWLINEclass MultipathPhotonScene(PhotonScene):NEWLINE CONFIG = {NEWLINE "num_paths" : 5NEWLINE }NEWLINE def run_along_paths(self, **kwargs):NEWLINE paths = self.get_paths()NEWLINE colors = Color(YELLOW).range_to(WHITE, len(paths))NEWLINE for path, color in zip(paths, colors):NEWLINE path.set_color(color)NEWLINE photon_runs = [NEWLINE self.photon_run_along_path(path)NEWLINE for path in pathsNEWLINE ]NEWLINE for photon_run, path in zip(photon_runs, paths):NEWLINE self.play(NEWLINE photon_run,NEWLINE ShowCreation(NEWLINE path,NEWLINE rate_func = lambda t : 0.9*smooth(t)NEWLINE ), NEWLINE **kwargsNEWLINE )NEWLINE self.wait()NEWLINENEWLINE def generate_paths(self):NEWLINE raise Exception("Not Implemented")NEWLINENEWLINENEWLINEclass PhotonThroughLens(MultipathPhotonScene):NEWLINE def construct(self):NEWLINE self.lens = Lens()NEWLINE self.add(self.lens)NEWLINE self.run_along_paths()NEWLINENEWLINENEWLINE def get_paths(self):NEWLINE interval_values = np.arange(self.num_paths).astype('float')NEWLINE interval_values /= (self.num_paths-1.)NEWLINE first_contact = [NEWLINE self.lens.point_from_proportion(0.4*v+0.55)NEWLINE for v in reversed(interval_values)NEWLINE ]NEWLINE second_contact = [NEWLINE self.lens.point_from_proportion(0.3*v + 0.1)NEWLINE for v in interval_valuesNEWLINE ]NEWLINE focal_point = 2*RIGHTNEWLINE return [NEWLINE Mobject(NEWLINE Line(FRAME_X_RADIUS*LEFT + fc[1]*UP, fc),NEWLINE Line(fc, sc),NEWLINE Line(sc, focal_point),NEWLINE Line(focal_point, 6*focal_point-5*sc)NEWLINE ).ingest_submobjects()NEWLINE for fc, sc in zip(first_contact, second_contact)NEWLINE ]NEWLINENEWLINEclass TransitionToOptics(PhotonThroughLens):NEWLINE def construct(self):NEWLINE optics = TextMobject("Optics")NEWLINE optics.to_edge(UP)NEWLINE self.add(optics)NEWLINE self.has_started = FalseNEWLINE PhotonThroughLens.construct(self)NEWLINENEWLINE def play(self, *args, **kwargs):NEWLINE if not self.has_started:NEWLINE self.has_started = TrueNEWLINE everything = Mobject(*self.mobjects)NEWLINE vect = FRAME_WIDTH*RIGHTNEWLINE everything.shift(vect)NEWLINE self.play(ApplyMethod(NEWLINE everything.shift, -vect,NEWLINE rate_func = rush_fromNEWLINE ))NEWLINE Scene.play(self, *args, **kwargs)NEWLINENEWLINENEWLINEclass PhotonOffMirror(MultipathPhotonScene):NEWLINE def construct(self):NEWLINE self.mirror = Line(*FRAME_Y_RADIUS*np.array([DOWN, UP]))NEWLINE self.mirror.set_color(GREY)NEWLINE self.add(self.mirror)NEWLINE self.run_along_paths()NEWLINENEWLINE def get_paths(self):NEWLINE interval_values = np.arange(self.num_paths).astype('float')NEWLINE interval_values /= (self.num_paths-1)NEWLINE anchor_points = [NEWLINE self.mirror.point_from_proportion(0.6*v+0.3)NEWLINE for v in interval_valuesNEWLINE ]NEWLINE start_point = 5*LEFT+3*UPNEWLINE end_points = []NEWLINE for point in anchor_points:NEWLINE vect = start_point-pointNEWLINE vect[1] *= -1NEWLINE end_points.append(point+2*vect)NEWLINE return [NEWLINE Mobject(NEWLINE Line(start_point, anchor_point), NEWLINE Line(anchor_point, end_point)NEWLINE ).ingest_submobjects()NEWLINE for anchor_point, end_point in zip(anchor_points, end_points)NEWLINE ]NEWLINENEWLINEclass PhotonsInWater(MultipathPhotonScene):NEWLINE def construct(self):NEWLINE water = Region(lambda x, y : y < 0, color = BLUE_E)NEWLINE self.add(water)NEWLINE self.run_along_paths()NEWLINENEWLINE def get_paths(self):NEWLINE x, y = -3, 3NEWLINE start_point = x*RIGHT + y*UPNEWLINE angles = np.arange(np.pi/18, np.pi/3, np.pi/18)NEWLINE midpoints = y*np.arctan(angles)NEWLINE end_points = midpoints + FRAME_Y_RADIUS*np.arctan(2*angles)NEWLINE return [NEWLINE Mobject(NEWLINE Line(start_point, [midpoint, 0, 0]),NEWLINE Line([midpoint, 0, 0], [end_point, -FRAME_Y_RADIUS, 0])NEWLINE ).ingest_submobjects()NEWLINE for midpoint, end_point in zip(midpoints, end_points)NEWLINE ]NEWLINENEWLINENEWLINEclass ShowMultiplePathsScene(PhotonScene):NEWLINE def construct(self):NEWLINE text = TextMobject("Which path minimizes travel time?")NEWLINE text.to_edge(UP)NEWLINE self.generate_start_and_end_points()NEWLINE point_a = Dot(self.start_point)NEWLINE point_b = Dot(self.end_point)NEWLINE A = TextMobject("A").next_to(point_a, UP)NEWLINE B = TextMobject("B").next_to(point_b, DOWN)NEWLINE paths = self.get_paths()NEWLINENEWLINE for point, letter in [(point_a, A), (point_b, B)]:NEWLINE self.play(NEWLINE ShowCreation(point),NEWLINE ShimmerIn(letter)NEWLINE )NEWLINE self.play(ShimmerIn(text))NEWLINE curr_path = paths[0].copy()NEWLINE curr_path_copy = curr_path.copy().ingest_submobjects()NEWLINE self.play(NEWLINE self.photon_run_along_path(curr_path),NEWLINE ShowCreation(curr_path_copy, rate_func = rush_into)NEWLINE )NEWLINE self.remove(curr_path_copy)NEWLINE for path in paths[1:] + [paths[0]]:NEWLINE self.play(Transform(curr_path, path, run_time = 4))NEWLINE self.wait()NEWLINE self.path = curr_path.ingest_submobjects()NEWLINENEWLINE def generate_start_and_end_points(self):NEWLINE raise Exception("Not Implemented")NEWLINENEWLINE def get_paths(self):NEWLINE raise Exception("Not implemented")NEWLINENEWLINENEWLINEclass ShowMultiplePathsThroughLens(ShowMultiplePathsScene):NEWLINE def construct(self):NEWLINE self.lens = Lens()NEWLINE self.add(self.lens)NEWLINE ShowMultiplePathsScene.construct(self)NEWLINENEWLINE def generate_start_and_end_points(self):NEWLINE self.start_point = 3*LEFT + UPNEWLINE self.end_point = 2*RIGHTNEWLINENEWLINE def get_paths(self):NEWLINE alphas = [0.25, 0.4, 0.58, 0.75]NEWLINE lower_right, upper_right, upper_left, lower_left = map(NEWLINE self.lens.point_from_proportion, alphasNEWLINE )NEWLINE return [NEWLINE Mobject(NEWLINE Line(self.start_point, a),NEWLINE Line(a, b),NEWLINE Line(b, self.end_point)NEWLINE ).set_color(color)NEWLINE for (a, b), color in zip(NEWLINE [NEWLINE (upper_left, upper_right),NEWLINE (upper_left, lower_right),NEWLINE (lower_left, lower_right),NEWLINE (lower_left, upper_right),NEWLINE ],NEWLINE Color(YELLOW).range_to(WHITE, 4)NEWLINE )NEWLINE ]NEWLINENEWLINENEWLINEclass ShowMultiplePathsOffMirror(ShowMultiplePathsScene):NEWLINE def construct(self):NEWLINE mirror = Line(*FRAME_Y_RADIUS*np.array([DOWN, UP]))NEWLINE mirror.set_color(GREY)NEWLINE self.add(mirror)NEWLINE ShowMultiplePathsScene.construct(self)NEWLINENEWLINE def generate_start_and_end_points(self):NEWLINE self.start_point = 4*LEFT + 2*UPNEWLINE self.end_point = 4*LEFT + 2*DOWNNEWLINENEWLINE def get_paths(self):NEWLINE return [NEWLINE Mobject(NEWLINE Line(self.start_point, midpoint),NEWLINE Line(midpoint, self.end_point)NEWLINE ).set_color(color)NEWLINE for midpoint, color in zip(NEWLINE [2*UP, 2*DOWN],NEWLINE Color(YELLOW).range_to(WHITE, 2)NEWLINE )NEWLINE ]NEWLINENEWLINENEWLINEclass ShowMultiplePathsInWater(ShowMultiplePathsScene):NEWLINE def construct(self):NEWLINE glass = Region(lambda x, y : y < 0, color = BLUE_E)NEWLINE self.generate_start_and_end_points()NEWLINE straight = Line(self.start_point, self.end_point)NEWLINE slow = TextMobject("Slow")NEWLINE slow.rotate(np.arctan(straight.get_slope()))NEWLINE slow.shift(straight.points[int(0.7*straight.get_num_points())])NEWLINE slow.shift(0.5*DOWN)NEWLINE too_long = TextMobject("Too long")NEWLINE too_long.shift(UP)NEWLINE air = TextMobject("Air").shift(2*UP)NEWLINE water = TextMobject("Water").shift(2*DOWN)NEWLINENEWLINE self.add(glass)NEWLINE self.play(GrowFromCenter(air))NEWLINE self.play(GrowFromCenter(water))NEWLINE self.wait()NEWLINE self.remove(air, water)NEWLINE ShowMultiplePathsScene.construct(self)NEWLINE self.play(NEWLINE Transform(self.path, straight)NEWLINE )NEWLINE self.wait()NEWLINE self.play(GrowFromCenter(slow))NEWLINE self.wait()NEWLINE self.remove(slow)NEWLINE self.leftmost.ingest_submobjects()NEWLINE self.play(Transform(self.path, self.leftmost, run_time = 3))NEWLINE self.wait()NEWLINE self.play(ShimmerIn(too_long))NEWLINE self.wait()NEWLINENEWLINENEWLINE def generate_start_and_end_points(self):NEWLINE self.start_point = 3*LEFT + 2*UPNEWLINE self.end_point = 3*RIGHT + 2*DOWNNEWLINENEWLINE def get_paths(self):NEWLINE self.leftmost, self.rightmost = result = [NEWLINE Mobject(NEWLINE Line(self.start_point, midpoint),NEWLINE Line(midpoint, self.end_point)NEWLINE ).set_color(color)NEWLINE for midpoint, color in zip(NEWLINE [3*LEFT, 3*RIGHT],NEWLINE Color(YELLOW).range_to(WHITE, 2)NEWLINE )NEWLINE ]NEWLINE return resultNEWLINENEWLINENEWLINEclass StraightLinesFastestInConstantMedium(PhotonScene):NEWLINE def construct(self):NEWLINE kwargs = {"size" : "\\Large"}NEWLINE left = TextMobject("Speed of light is constant", **kwargs)NEWLINE arrow = TexMobject("\\Rightarrow", **kwargs)NEWLINE right = TextMobject("Staight path is fastest", **kwargs)NEWLINE left.next_to(arrow, LEFT)NEWLINE right.next_to(arrow, RIGHT)NEWLINE squaggle, line = self.get_paths() NEWLINENEWLINE self.play(*map(ShimmerIn, [left, arrow, right]))NEWLINE self.play(ShowCreation(squaggle))NEWLINE self.play(self.photon_run_along_path(NEWLINE squaggle, run_time = 2, rate_func = NoneNEWLINE ))NEWLINE self.play(Transform(NEWLINE squaggle, line, NEWLINE path_func = path_along_arc(np.pi)NEWLINE ))NEWLINE self.play(self.photon_run_along_path(line, rate_func = None))NEWLINE self.wait()NEWLINENEWLINENEWLINE def get_paths(self):NEWLINE squaggle = ParametricFunction(NEWLINE lambda t : (0.5*t+np.cos(t))*RIGHT+np.sin(t)*UP,NEWLINE start = -np.pi,NEWLINE end = 2*np.piNEWLINE )NEWLINE squaggle.shift(2*UP)NEWLINE start, end = squaggle.points[0], squaggle.points[-1]NEWLINE line = Line(start, end)NEWLINE result = [squaggle, line]NEWLINE for mob in result:NEWLINE mob.set_color(BLUE_D)NEWLINE return resultNEWLINENEWLINEclass PhtonBendsInWater(PhotonScene, ZoomedScene):NEWLINE def construct(self):NEWLINE glass = Region(lambda x, y : y < 0, color = BLUE_E)NEWLINE kwargs = {NEWLINE "density" : self.zoom_factor*DEFAULT_POINT_DENSITY_1DNEWLINE }NEWLINE top_line = Line(FRAME_Y_RADIUS*UP+2*LEFT, ORIGIN, **kwargs)NEWLINE extension = Line(ORIGIN, FRAME_Y_RADIUS*DOWN+2*RIGHT, **kwargs)NEWLINE bottom_line = Line(ORIGIN, FRAME_Y_RADIUS*DOWN+RIGHT, **kwargs)NEWLINE path1 = Mobject(top_line, extension)NEWLINE path2 = Mobject(top_line, bottom_line)NEWLINE for mob in path1, path2:NEWLINE mob.ingest_submobjects()NEWLINE extension.set_color(RED)NEWLINE theta1 = np.arctan(bottom_line.get_slope())NEWLINE theta2 = np.arctan(extension.get_slope())NEWLINE arc = Arc(theta2-theta1, start_angle = theta1, radius = 2)NEWLINE question_mark = TextMobject("$\\theta$?")NEWLINE question_mark.shift(arc.get_center()+0.5*DOWN+0.25*RIGHT)NEWLINE wave = self.wavify(path2)NEWLINE wave.set_color(YELLOW)NEWLINE wave.scale(0.5)NEWLINENEWLINE self.add(glass)NEWLINE self.play(ShowCreation(path1))NEWLINE self.play(Transform(path1, path2))NEWLINE self.wait()NEWLINE # self.activate_zooming()NEWLINE self.wait() NEWLINE self.play(ShowPassingFlash(NEWLINE wave, run_time = 3, rate_func = NoneNEWLINE ))NEWLINE self.wait()NEWLINE self.play(ShowCreation(extension))NEWLINE self.play(NEWLINE ShowCreation(arc),NEWLINE ShimmerIn(question_mark)NEWLINE )NEWLINENEWLINEclass LightIsFasterInAirThanWater(ShowMultiplePathsInWater):NEWLINE def construct(self):NEWLINE glass = Region(lambda x, y : y < 0, color = BLUE_E)NEWLINE equation = TexMobject("v_{\\text{air}} > v_{\\text{water}}")NEWLINE equation.to_edge(UP)NEWLINE path = Line(FRAME_X_RADIUS*LEFT, FRAME_X_RADIUS*RIGHT)NEWLINE path1 = path.copy().shift(2*UP)NEWLINE path2 = path.copy().shift(2*DOWN)NEWLINENEWLINE self.add(glass)NEWLINE self.play(ShimmerIn(equation))NEWLINE self.wait()NEWLINE photon_runs = []NEWLINE photon_runs.append(self.photon_run_along_path(NEWLINE path1, rate_func = lambda t : min(1, 1.2*t)NEWLINE ))NEWLINE photon_runs.append(self.photon_run_along_path(path2))NEWLINE self.play(*photon_runs, **{"run_time" : 2})NEWLINE self.wait()NEWLINENEWLINENEWLINEclass GeometryOfGlassSituation(ShowMultiplePathsInWater):NEWLINE def construct(self):NEWLINE glass = Region(lambda x, y : y < 0, color = BLUE_E)NEWLINE self.generate_start_and_end_points()NEWLINE left = self.start_point[0]*RIGHTNEWLINE right = self.end_point[0]*RIGHTNEWLINE start_x = interpolate(left, right, 0.2)NEWLINE end_x = interpolate(left, right, 1.0)NEWLINE left_line = Line(self.start_point, left, color = RED_D)NEWLINE right_line = Line(self.end_point, right, color = RED_D)NEWLINE h_1, h_2 = map(TexMobject, ["h_1", "h_2"])NEWLINE h_1.next_to(left_line, LEFT)NEWLINE h_2.next_to(right_line, RIGHT)NEWLINE point_a = Dot(self.start_point)NEWLINE point_b = Dot(self.end_point)NEWLINE A = TextMobject("A").next_to(point_a, UP)NEWLINE B = TextMobject("B").next_to(point_b, DOWN)NEWLINENEWLINE x = start_xNEWLINE left_brace = Brace(Mobject(Point(left), Point(x)))NEWLINE right_brace = Brace(Mobject(Point(x), Point(right)), UP)NEWLINE x_mob = TexMobject("x")NEWLINE x_mob.next_to(left_brace, DOWN)NEWLINE w_minus_x = TexMobject("w-x")NEWLINE w_minus_x.next_to(right_brace, UP)NEWLINE top_line = Line(self.start_point, x)NEWLINE bottom_line = Line(x, self.end_point)NEWLINE top_dist = TexMobject("\\sqrt{h_1^2+x^2}")NEWLINE top_dist.scale(0.5)NEWLINE a = 0.3NEWLINE n = top_line.get_num_points()NEWLINE point = top_line.points[int(a*n)]NEWLINE top_dist.next_to(Point(point), RIGHT, buff = 0.3)NEWLINE bottom_dist = TexMobject("\\sqrt{h_2^2+(w-x)^2}")NEWLINE bottom_dist.scale(0.5)NEWLINE n = bottom_line.get_num_points()NEWLINE point = bottom_line.points[int((1-a)*n)]NEWLINE bottom_dist.next_to(Point(point), LEFT, buff = 1)NEWLINENEWLINE end_top_line = Line(self.start_point, end_x)NEWLINE end_bottom_line = Line(end_x, self.end_point)NEWLINE end_brace = Brace(Mobject(Point(left), Point(end_x)))NEWLINE end_x_mob = TexMobject("x").next_to(end_brace, DOWN)NEWLINENEWLINE axes = Mobject(NEWLINE NumberLine(),NEWLINE NumberLine().rotate(np.pi/2).shift(7*LEFT)NEWLINE )NEWLINE graph = FunctionGraph(NEWLINE lambda x : 0.4*(x+1)*(x-3)+4,NEWLINE x_min = -2,NEWLINE x_max = 4NEWLINE )NEWLINE graph.set_color(YELLOW)NEWLINE Mobject(axes, graph).scale(0.2).to_corner(UP+RIGHT, buff = 1)NEWLINE axes.add(TexMobject("x", size = "\\small").next_to(axes, RIGHT))NEWLINE axes.add(TextMobject("Travel time", size = "\\small").next_to(NEWLINE axes, UPNEWLINE ))NEWLINE new_graph = graph.copy()NEWLINE midpoint = new_graph.points[new_graph.get_num_points()/2]NEWLINE new_graph.filter_out(lambda p : p[0] < midpoint[0])NEWLINE new_graph.reverse_points()NEWLINE pairs_for_end_transform = [NEWLINE (mob, mob.copy())NEWLINE for mob in (top_line, bottom_line, left_brace, x_mob)NEWLINE ]NEWLINENEWLINE self.add(glass, point_a, point_b, A, B)NEWLINE line = Mobject(top_line, bottom_line).ingest_submobjects()NEWLINE self.play(ShowCreation(line))NEWLINE self.wait()NEWLINE self.play(NEWLINE GrowFromCenter(left_brace), NEWLINE GrowFromCenter(x_mob)NEWLINE )NEWLINE self.play(NEWLINE GrowFromCenter(right_brace), NEWLINE GrowFromCenter(w_minus_x)NEWLINE )NEWLINE self.play(ShowCreation(left_line), ShimmerIn(h_1))NEWLINE self.play(ShowCreation(right_line), GrowFromCenter(h_2))NEWLINE self.play(ShimmerIn(top_dist))NEWLINE self.play(GrowFromCenter(bottom_dist))NEWLINE self.wait(3)NEWLINE self.clear()NEWLINE self.add(glass, point_a, point_b, A, B, NEWLINE top_line, bottom_line, left_brace, x_mob)NEWLINE self.play(ShowCreation(axes))NEWLINE kwargs = {NEWLINE "run_time" : 4,NEWLINE }NEWLINE self.play(*[NEWLINE Transform(*pair, **kwargs)NEWLINE for pair in [NEWLINE (top_line, end_top_line),NEWLINE (bottom_line, end_bottom_line),NEWLINE (left_brace, end_brace),NEWLINE (x_mob, end_x_mob)NEWLINE ]NEWLINE ]+[ShowCreation(graph, **kwargs)])NEWLINE self.wait()NEWLINE self.show_derivatives(graph)NEWLINE line = self.show_derivatives(new_graph)NEWLINE self.add(line)NEWLINE self.play(*[NEWLINE Transform(*pair, rate_func = lambda x : 0.3*smooth(x))NEWLINE for pair in pairs_for_end_transformNEWLINE ])NEWLINE self.wait()NEWLINENEWLINE def show_derivatives(self, graph, run_time = 2):NEWLINE step = self.frame_duration/run_timeNEWLINE for a in smooth(np.arange(0, 1-step, step)):NEWLINE index = int(a*graph.get_num_points())NEWLINE p1, p2 = graph.points[index], graph.points[index+1]NEWLINE line = Line(LEFT, RIGHT)NEWLINE line.rotate(angle_of_vector(p2-p1))NEWLINE line.shift(p1)NEWLINE self.add(line)NEWLINE self.wait(self.frame_duration)NEWLINE self.remove(line)NEWLINE return lineNEWLINENEWLINENEWLINEclass Spring(Line):NEWLINE CONFIG = {NEWLINE "num_loops" : 5,NEWLINE "loop_radius" : 0.3,NEWLINE "color" : GREYNEWLINE }NEWLINENEWLINE def generate_points(self):NEWLINE ## self.start, self.endNEWLINE length = np.linalg.norm(self.end-self.start)NEWLINE angle = angle_of_vector(self.end-self.start)NEWLINE micro_radius = self.loop_radius/lengthNEWLINE m = 2*np.pi*(self.num_loops+0.5)NEWLINE def loop(t):NEWLINE return micro_radius*(NEWLINE RIGHT + np.cos(m*t)*LEFT + np.sin(m*t)*UPNEWLINE )NEWLINE new_epsilon = self.epsilon/(m*micro_radius)/lengthNEWLINENEWLINE self.add_points([NEWLINE t*RIGHT + loop(t)NEWLINE for t in np.arange(0, 1, new_epsilon)NEWLINE ])NEWLINE self.scale(length/(1+2*micro_radius))NEWLINE self.rotate(angle)NEWLINE self.shift(self.start)NEWLINENEWLINENEWLINEclass SpringSetup(ShowMultiplePathsInWater):NEWLINE def construct(self):NEWLINE self.ring_shift_val = 6*RIGHTNEWLINE self.slide_kwargs = {NEWLINE "rate_func" : there_and_back,NEWLINE "run_time" : 5NEWLINE }NEWLINENEWLINE self.setup_background()NEWLINE rod = Region(NEWLINE lambda x, y : (abs(x) < 5) & (abs(y) < 0.05),NEWLINE color = GOLD_ENEWLINE )NEWLINE ring = Arc(NEWLINE angle = 11*np.pi/6,NEWLINE start_angle = -11*np.pi/12,NEWLINE radius = 0.2,NEWLINE color = YELLOWNEWLINE )NEWLINE ring.shift(-self.ring_shift_val/2)NEWLINE self.generate_springs(ring) NEWLINENEWLINENEWLINE self.add_rod_and_ring(rod, ring)NEWLINE self.slide_ring(ring)NEWLINE self.wait()NEWLINE self.add_springs()NEWLINE self.add_force_definitions()NEWLINE self.slide_system(ring)NEWLINE self.show_horizontal_component(ring)NEWLINE self.show_angles(ring)NEWLINE self.show_equation()NEWLINENEWLINENEWLINE def setup_background(self):NEWLINE glass = Region(lambda x, y : y < 0, color = BLUE_E)NEWLINE self.generate_start_and_end_points()NEWLINE point_a = Dot(self.start_point)NEWLINE point_b = Dot(self.end_point)NEWLINE A = TextMobject("A").next_to(point_a, UP)NEWLINE B = TextMobject("B").next_to(point_b, DOWN)NEWLINE self.add(glass, point_a, point_b, A, B)NEWLINENEWLINE def generate_springs(self, ring):NEWLINE self.start_springs, self.end_springs = [NEWLINE Mobject(NEWLINE Spring(self.start_point, r.get_top()),NEWLINE Spring(self.end_point, r.get_bottom())NEWLINE )NEWLINE for r in (ring, ring.copy().shift(self.ring_shift_val))NEWLINE ]NEWLINE NEWLINE def add_rod_and_ring(self, rod, ring):NEWLINE rod_word = TextMobject("Rod")NEWLINE rod_word.next_to(Point(), UP)NEWLINE ring_word = TextMobject("Ring")NEWLINE ring_word.next_to(ring, UP)NEWLINE self.wait()NEWLINE self.add(rod)NEWLINE self.play(ShimmerIn(rod_word))NEWLINE self.wait()NEWLINE self.remove(rod_word)NEWLINE self.play(ShowCreation(ring))NEWLINE self.play(ShimmerIn(ring_word))NEWLINE self.wait()NEWLINE self.remove(ring_word)NEWLINENEWLINE def slide_ring(self, ring):NEWLINE self.play(ApplyMethod(NEWLINE ring.shift, self.ring_shift_val,NEWLINE **self.slide_kwargsNEWLINE ))NEWLINENEWLINE def add_springs(self):NEWLINE colors = iter([BLACK, BLUE_E])NEWLINE for spring in self.start_springs.split():NEWLINE circle = Circle(color = next(colors))NEWLINE circle.reverse_points()NEWLINE circle.scale(spring.loop_radius)NEWLINE circle.shift(spring.points[0])NEWLINENEWLINE self.play(Transform(circle, spring))NEWLINE self.remove(circle)NEWLINE self.add(spring)NEWLINE self.wait()NEWLINENEWLINE def add_force_definitions(self):NEWLINE top_force = TexMobject("F_1 = \\dfrac{1}{v_{\\text{air}}}")NEWLINE bottom_force = TexMobject("F_2 = \\dfrac{1}{v_{\\text{water}}}")NEWLINE top_spring, bottom_spring = self.start_springs.split()NEWLINE top_force.next_to(top_spring)NEWLINE bottom_force.next_to(bottom_spring, DOWN, buff = -0.5)NEWLINE words = TextMobject("""NEWLINE The force in a real spring is NEWLINE proportional to that spring's lengthNEWLINE """)NEWLINE words.to_corner(UP+RIGHT)NEWLINE for force in top_force, bottom_force:NEWLINE self.play(GrowFromCenter(force))NEWLINE self.wait()NEWLINE self.play(ShimmerIn(words))NEWLINE self.wait(3)NEWLINE self.remove(top_force, bottom_force, words)NEWLINENEWLINE def slide_system(self, ring):NEWLINE equilibrium_slide_kwargs = dict(self.slide_kwargs)NEWLINE def jiggle_to_equilibrium(t):NEWLINE return 0.7*(1+((1-t)**2)*(-np.cos(10*np.pi*t)))NEWLINE equilibrium_slide_kwargs = {NEWLINE "rate_func" : jiggle_to_equilibrium,NEWLINE "run_time" : 3NEWLINE }NEWLINE start = Mobject(ring, self.start_springs)NEWLINE end = Mobject(NEWLINE ring.copy().shift(self.ring_shift_val),NEWLINE self.end_springsNEWLINE )NEWLINE for kwargs in self.slide_kwargs, equilibrium_slide_kwargs:NEWLINE self.play(Transform(start, end, **kwargs))NEWLINE self.wait()NEWLINE NEWLINE def show_horizontal_component(self, ring):NEWLINE v_right = Vector(ring.get_top(), RIGHT)NEWLINE v_left = Vector(ring.get_bottom(), LEFT)NEWLINE self.play(*map(ShowCreation, [v_right, v_left]))NEWLINE self.wait()NEWLINE self.remove(v_right, v_left)NEWLINENEWLINE def show_angles(self, ring):NEWLINE ring_center = ring.get_center()NEWLINE lines, arcs, thetas = [], [], []NEWLINE counter = it.count(1)NEWLINE for point in self.start_point, self.end_point:NEWLINE line = Line(point, ring_center, color = GREY)NEWLINE angle = np.pi/2-np.abs(np.arctan(line.get_slope()))NEWLINE arc = Arc(angle, radius = 0.5).rotate(np.pi/2)NEWLINE if point is self.end_point:NEWLINE arc.rotate(np.pi)NEWLINE theta = TexMobject("\\theta_%d"%next(counter))NEWLINE theta.scale(0.5)NEWLINE theta.shift(2*arc.get_center())NEWLINE arc.shift(ring_center)NEWLINE theta.shift(ring_center)NEWLINENEWLINE lines.append(line)NEWLINE arcs.append(arc)NEWLINE thetas.append(theta)NEWLINE vert_line = Line(2*UP, 2*DOWN)NEWLINE vert_line.shift(ring_center)NEWLINE top_spring, bottom_spring = self.start_springs.split()NEWLINENEWLINE self.play(NEWLINE Transform(ring, Point(ring_center)),NEWLINE Transform(top_spring, lines[0]),NEWLINE Transform(bottom_spring, lines[1])NEWLINE )NEWLINE self.play(ShowCreation(vert_line))NEWLINE anims = []NEWLINE for arc, theta in zip(arcs, thetas):NEWLINE anims += [NEWLINE ShowCreation(arc),NEWLINE GrowFromCenter(theta)NEWLINE ]NEWLINE self.play(*anims)NEWLINE self.wait()NEWLINENEWLINE def show_equation(self):NEWLINE equation = TexMobject([NEWLINE "\\left(\\dfrac{1}{\\phantom{v_air}}\\right)",NEWLINE "\\sin(\\theta_1)", NEWLINE "=", NEWLINE "\\left(\\dfrac{1}{\\phantom{v_water}}\\right)",NEWLINE "\\sin(\\theta_2)"NEWLINE ])NEWLINE equation.to_corner(UP+RIGHT)NEWLINE frac1, sin1, equals, frac2, sin2 = equation.split()NEWLINE v_air, v_water = [NEWLINE TexMobject("v_{\\text{%s}}"%s, size = "\\Large")NEWLINE for s in ("air", "water")NEWLINE ]NEWLINE v_air.next_to(Point(frac1.get_center()), DOWN)NEWLINE v_water.next_to(Point(frac2.get_center()), DOWN)NEWLINE frac1.add(v_air)NEWLINE frac2.add(v_water)NEWLINE f1, f2 = [NEWLINE TexMobject("F_%d"%d, size = "\\Large") NEWLINE for d in (1, 2)NEWLINE ]NEWLINE f1.next_to(sin1, LEFT)NEWLINE f2.next_to(equals, RIGHT)NEWLINE sin2_start = sin2.copy().next_to(f2, RIGHT)NEWLINE bar1 = TexMobject("\\dfrac{\\qquad}{\\qquad}")NEWLINE bar2 = bar1.copy()NEWLINE bar1.next_to(sin1, DOWN)NEWLINE bar2.next_to(sin2, DOWN) NEWLINE v_air_copy = v_air.copy().next_to(bar1, DOWN)NEWLINE v_water_copy = v_water.copy().next_to(bar2, DOWN)NEWLINE bars = Mobject(bar1, bar2)NEWLINE new_eq = equals.copy().center().shift(bars.get_center())NEWLINE snells = TextMobject("Snell's Law")NEWLINE snells.set_color(YELLOW)NEWLINE snells.shift(new_eq.get_center()[0]*RIGHT)NEWLINE snells.shift(UP)NEWLINENEWLINE anims = []NEWLINE for mob in f1, sin1, equals, f2, sin2_start:NEWLINE anims.append(ShimmerIn(mob))NEWLINE self.play(*anims)NEWLINE self.wait()NEWLINE for f, frac in (f1, frac1), (f2, frac2):NEWLINE target = frac.copy().ingest_submobjects()NEWLINE also = []NEWLINE if f is f2:NEWLINE also.append(Transform(sin2_start, sin2))NEWLINE sin2 = sin2_startNEWLINE self.play(Transform(f, target), *also)NEWLINE self.remove(f)NEWLINE self.add(frac)NEWLINE self.wait()NEWLINE self.play(NEWLINE FadeOut(frac1),NEWLINE FadeOut(frac2),NEWLINE Transform(v_air, v_air_copy),NEWLINE Transform(v_water, v_water_copy),NEWLINE ShowCreation(bars),NEWLINE Transform(equals, new_eq)NEWLINE )NEWLINE self.wait()NEWLINE frac1 = Mobject(sin1, bar1, v_air)NEWLINE frac2 = Mobject(sin2, bar2, v_water)NEWLINE for frac, vect in (frac1, LEFT), (frac2, RIGHT):NEWLINE self.play(ApplyMethod(NEWLINE frac.next_to, equals, vectNEWLINE ))NEWLINE self.wait()NEWLINE self.play(ShimmerIn(snells))NEWLINE self.wait()NEWLINENEWLINEclass WhatGovernsTheSpeedOfLight(PhotonScene, PathSlidingScene):NEWLINE def construct(self):NEWLINE randy = Randolph()NEWLINE randy.scale(RANDY_SCALE_FACTOR)NEWLINE randy.shift(-randy.get_bottom())NEWLINE self.add_cycloid_end_points() NEWLINENEWLINE self.add(self.cycloid)NEWLINE self.slide(randy, self.cycloid)NEWLINE self.play(self.photon_run_along_path(self.cycloid))NEWLINENEWLINE self.wait()NEWLINENEWLINEclass WhichPathWouldLightTake(PhotonScene, TryManyPaths):NEWLINE def construct(self):NEWLINE words = TextMobject(NEWLINE ["Which path ", "would \\emph{light} take", "?"]NEWLINE )NEWLINE words.split()[1].set_color(YELLOW)NEWLINE words.to_corner(UP+RIGHT)NEWLINE self.add_cycloid_end_points()NEWLINENEWLINE anims = [NEWLINE self.photon_run_along_path(NEWLINE path, NEWLINE rate_func = smoothNEWLINE )NEWLINE for path in self.get_paths()NEWLINE ]NEWLINE self.play(anims[0], ShimmerIn(words))NEWLINE for anim in anims[1:]:NEWLINE self.play(anim)NEWLINENEWLINENEWLINENEWLINEclass StateSnellsLaw(PhotonScene):NEWLINE def construct(self):NEWLINE point_a = 3*LEFT+3*UPNEWLINE point_b = 1.5*RIGHT+3*DOWNNEWLINE midpoint = ORIGINNEWLINENEWLINE lines, arcs, thetas = [], [], []NEWLINE counter = it.count(1)NEWLINE for point in point_a, point_b:NEWLINE line = Line(point, midpoint, color = RED_D)NEWLINE angle = np.pi/2-np.abs(np.arctan(line.get_slope()))NEWLINE arc = Arc(angle, radius = 0.5).rotate(np.pi/2)NEWLINE if point is point_b:NEWLINE arc.rotate(np.pi)NEWLINE line.reverse_points()NEWLINE theta = TexMobject("\\theta_%d"%next(counter))NEWLINE theta.scale(0.5)NEWLINE theta.shift(2*arc.get_center())NEWLINE arc.shift(midpoint)NEWLINE theta.shift(midpoint)NEWLINENEWLINE lines.append(line)NEWLINE arcs.append(arc)NEWLINE thetas.append(theta)NEWLINE vert_line = Line(2*UP, 2*DOWN)NEWLINE vert_line.shift(midpoint)NEWLINE path = Mobject(*lines).ingest_submobjects()NEWLINE glass = Region(lambda x, y : y < 0, color = BLUE_E)NEWLINE self.add(glass)NEWLINE equation = TexMobject([NEWLINE "\\dfrac{\\sin(\\theta_1)}{v_{\\text{air}}}",NEWLINE "=", NEWLINE "\\dfrac{\\sin(\\theta_2)}{v_{\\text{water}}}",NEWLINE ])NEWLINE equation.to_corner(UP+RIGHT)NEWLINE exp1, equals, exp2 = equation.split()NEWLINE snells_law = TextMobject("Snell's Law:")NEWLINE snells_law.set_color(YELLOW)NEWLINE snells_law.to_edge(UP)NEWLINENEWLINE self.play(ShimmerIn(snells_law))NEWLINE self.wait()NEWLINE self.play(ShowCreation(path))NEWLINE self.play(self.photon_run_along_path(path))NEWLINE self.wait()NEWLINE self.play(ShowCreation(vert_line))NEWLINE self.play(*map(ShowCreation, arcs))NEWLINE self.play(*map(GrowFromCenter, thetas))NEWLINE self.wait()NEWLINE self.play(ShimmerIn(exp1))NEWLINE self.wait()NEWLINE self.play(*map(ShimmerIn, [equals, exp2]))NEWLINE self.wait()NEWLINE NEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE
import argparseNEWLINEimport osNEWLINEfrom math import log10NEWLINENEWLINEimport pandas as pdNEWLINEimport torch.optim as optimNEWLINEimport torch.utils.dataNEWLINEimport torchvision.utils as utilsNEWLINEfrom torch.autograd import VariableNEWLINEfrom torch.utils.data import DataLoaderNEWLINEfrom tqdm import tqdmNEWLINENEWLINEimport pytorch_ssimNEWLINEfrom data_utils import TrainDatasetFromFolder, ValDatasetFromFolder, display_transformNEWLINEfrom loss import GeneratorLossNEWLINEfrom model import GeneratorNEWLINE# from PGD import *NEWLINE# from model import DiscriminatorNEWLINEimport timeNEWLINEfrom torch.utils.tensorboard import writerNEWLINEimport torch.nn.functional as FNEWLINEimport torch.nn as nnNEWLINEfrom distillmodel import DiscriminatorNEWLINENEWLINEparser = argparse.ArgumentParser('PGDSRGAN') # progressive growing discriminator SRGANNEWLINENEWLINEparser.add_argument('--fsize', default=128, type=int)NEWLINEparser.add_argument('--crop_size', default=96, type=int, help='training images crop size')NEWLINEparser.add_argument('--upscale_factor', default=4, type=int, choices=[2, 4, 8],NEWLINE help='super resolution upscale factor')NEWLINEparser.add_argument('--num_epochs', default=80, type=int, help='train epoch number')NEWLINEparser.add_argument('--batch_size', default=32, type=int)NEWLINEparser.add_argument('--TICK', type=int, default=1000)NEWLINEparser.add_argument('--trans_tick', type=int, default=200)NEWLINEparser.add_argument('--stabile_tick', type=int, default=100)NEWLINEparser.add_argument('--is_fade', type=bool, default=False)NEWLINEparser.add_argument('--grow', type=int, default=0)NEWLINEparser.add_argument('--max_grow', type=int, default=3)NEWLINEparser.add_argument('--when_to_grow', type=int, default=256) # discriminator 증가 언제NEWLINEparser.add_argument('--version', type=int, default=0) # 1/4, 1/2, 1 -> 1, 2, 3로 주자NEWLINEparser.add_argument('--kd_range', type=int, default=5)NEWLINEparser.add_argument('--kd1', type=int, default=12)NEWLINEparser.add_argument('--kd2', type=int, default=42)NEWLINENEWLINENEWLINEdef distill_loss(y, label, score, T, alpha):NEWLINE return nn.KLDivLoss()(F.log_softmax(y / T),NEWLINE F.softmax(score / T)) * (T * T * 2.0 + alpha) + \NEWLINE F.binary_cross_entropy(y, label) * (1 - alpha)NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE opt = parser.parse_args()NEWLINENEWLINE CROP_SIZE = opt.crop_sizeNEWLINE UPSCALE_FACTOR = opt.upscale_factorNEWLINE NUM_EPOCHS = opt.num_epochsNEWLINE batch_size = opt.batch_sizeNEWLINE count_image_number = 0NEWLINE trns_tick = opt.trans_tickNEWLINE stab_tick = opt.stabile_tickNEWLINE is_fade = opt.is_fadeNEWLINE change_iter = opt.when_to_growNEWLINE version = opt.versionNEWLINE kd_range = opt.kd_rangeNEWLINE kd1 = opt.kd1NEWLINE kd2 = opt.kd2NEWLINE cur_grow = 0NEWLINENEWLINE delta = 1.0 / (2 * trns_tick + 2 * stab_tick)NEWLINE d_alpha = 1.0 * batch_size / trns_tick / opt.TICKNEWLINENEWLINE fadein = {'dis': is_fade}NEWLINENEWLINE writer = writer.SummaryWriter('runs/distill')NEWLINENEWLINE train_set = TrainDatasetFromFolder('../data/train/gt', crop_size=CROP_SIZE,NEWLINE upscale_factor=UPSCALE_FACTOR,NEWLINE batch_size=batch_size)NEWLINE val_set = ValDatasetFromFolder('../data/val/gt',NEWLINE upscale_factor=UPSCALE_FACTOR)NEWLINE train_loader = DataLoader(dataset=train_set, num_workers=4, batch_size=batch_size, shuffle=True)NEWLINE val_loader = DataLoader(dataset=val_set, num_workers=1, batch_size=1, shuffle=False)NEWLINENEWLINE netG = Generator(UPSCALE_FACTOR)NEWLINE print('# generator parameters:', sum(param.numel() for param in netG.parameters()))NEWLINE # netD = Discriminator(opt)NEWLINE netD = Discriminator(opt)NEWLINENEWLINE print('# discriminator parameters:', sum(param.numel() for param in netD.parameters()))NEWLINE generator_criterion = GeneratorLoss()NEWLINENEWLINE print(torch.cuda.is_available())NEWLINENEWLINE if torch.cuda.is_available():NEWLINE netG.cuda()NEWLINE netD.cuda()NEWLINE print(netD)NEWLINE generator_criterion.cuda()NEWLINENEWLINE optimizerG = optim.Adam(netG.parameters())NEWLINE optimizerD = optim.Adam(netD.parameters())NEWLINENEWLINE results = {'d_loss': [], 'g_loss': [], 'd_score': [], 'g_score': [], 'psnr': [], 'ssim': []}NEWLINENEWLINE start = time.time()NEWLINE cnt = 0NEWLINE ncnt = 0NEWLINE distill_batch = 0NEWLINENEWLINE for epoch in range(1, NUM_EPOCHS + 1):NEWLINE epoch_flag = 0NEWLINENEWLINE train_bar = tqdm(train_loader, leave=True)NEWLINE running_results = {'batch_sizes': 0, 'd_loss': 0, 'g_loss': 0, 'd_score': 0, 'g_score': 0, 'distill_loss': 0}NEWLINENEWLINE netG.train()NEWLINE netD.train()NEWLINENEWLINE if kd1 < epoch <= kd1 + kd_range + 1 or kd2 < epoch <= kd2 + kd_range + 1:NEWLINE writer.add_scalar("loss/KD_loss", running_results['distill_loss'] / distill_batch,NEWLINE epoch - 1)NEWLINENEWLINE i = 0NEWLINE for data, target in train_bar: # train epoch (lr, hr)NEWLINE count_image_number += batch_sizeNEWLINE i += 1NEWLINENEWLINE g_update_first = TrueNEWLINE running_results['batch_sizes'] += batch_sizeNEWLINENEWLINE if kd1 <= epoch <= (kd1 + kd_range - 1) or kd2 <= epoch <= (kd2 + kd_range - 1): # discriminator KDNEWLINE epoch_flag = 1NEWLINE distill_batch += batch_sizeNEWLINE if (epoch == kd1 and cnt == 0) or (epoch == kd2 and cnt == 0):NEWLINE print("KD Phase start!")NEWLINE cnt = cnt + 1NEWLINE ncnt = 0NEWLINE opt.version = opt.version + 1NEWLINE student = Discriminator(opt)NEWLINE optimizersD = optim.Adam(student.parameters())NEWLINE print(student)NEWLINE student.cuda()NEWLINENEWLINE netG.eval()NEWLINE netD.eval()NEWLINE student.train()NEWLINE real_img = Variable(target)NEWLINE real_img = real_img.cuda()NEWLINENEWLINE z = Variable(data)NEWLINE z = z.cuda()NEWLINENEWLINE fake_img = netG(z) # lr->hrNEWLINENEWLINE netD.zero_grad()NEWLINENEWLINE teacher_fake_out = netD(fake_img).mean().reshape(1) # 학습해야함NEWLINE student_fake_out = student(fake_img).mean().reshape(1)NEWLINENEWLINE student_real_out = student(real_img).mean().reshape(1)NEWLINE teacher_real_out = netD(real_img).mean().reshape(1)NEWLINENEWLINE one = torch.Tensor([1]).reshape(1)NEWLINE one = one.cuda()NEWLINENEWLINE zero = torch.Tensor([0]).reshape(1)NEWLINE zero = zero.cuda()NEWLINENEWLINE distill_real_loss = distill_loss(student_real_out, one, teacher_real_out, 10, 0.5)NEWLINE distill_fake_loss = distill_loss(student_fake_out, zero, teacher_fake_out, 10, 0.5)NEWLINENEWLINE total_distill_loss = 0.3*distill_real_loss + 0.7*distill_fake_lossNEWLINE optimizerD.zero_grad()NEWLINE optimizersD.zero_grad()NEWLINE # writer.add_scalar("loss/distill_loss", total_distill_loss, epoch)NEWLINENEWLINE running_results['distill_loss'] += total_distill_lossNEWLINENEWLINE total_distill_loss.backward()NEWLINE optimizerD.step()NEWLINE optimizersD.step()NEWLINENEWLINE if (epoch == kd1 + kd_range - 1 and ncnt == 0 and i == len(train_loader)) or (NEWLINE epoch == kd2 + kd_range - 1 and ncnt == 0 and i == len(train_loader)): # +1NEWLINE print('netD is dumped with Student\n')NEWLINE netD = studentNEWLINE optimizerD = optimizersDNEWLINE epoch_flag = 0NEWLINE cnt = 0NEWLINE ncnt = 1NEWLINENEWLINE ############################NEWLINE # (1) Update D network: maximize D(x)-1-D(G(z))NEWLINE ###########################NEWLINE if epoch < kd1 or (kd1 + kd_range - 1 < epoch < kd2) or epoch > kd2 + kd_range - 1:NEWLINENEWLINE real_img = Variable(target)NEWLINE if torch.cuda.is_available():NEWLINE real_img = real_img.cuda()NEWLINE z = Variable(data)NEWLINE if torch.cuda.is_available():NEWLINE z = z.cuda()NEWLINE fake_img = netG(z)NEWLINENEWLINE netD.zero_grad()NEWLINE real_out = netD(real_img).mean()NEWLINE fake_out = netD(fake_img).mean()NEWLINE d_loss = 1 - real_out + fake_outNEWLINENEWLINE d_loss.backward(retain_graph=True)NEWLINE optimizerD.step()NEWLINENEWLINE ############################NEWLINE # (2) Update G network: minimize 1-D(G(z)) + Perception Loss + Image Loss + TV LossNEWLINE ###########################NEWLINE netG.zero_grad()NEWLINE ## The two lines below are added to prevent runetime error in Google Colab ##NEWLINE fake_img = netG(z)NEWLINE fake_out = netD(fake_img).mean()NEWLINE ##NEWLINE g_loss = generator_criterion(fake_out, fake_img, real_img)NEWLINENEWLINE g_loss.backward()NEWLINENEWLINE optimizerG.step()NEWLINENEWLINE # loss for current batch before optimizationNEWLINE running_results['g_loss'] += g_loss.item() * batch_sizeNEWLINE running_results['d_loss'] += d_loss.item() * batch_sizeNEWLINE running_results['d_score'] += real_out.item() * batch_sizeNEWLINE running_results['g_score'] += fake_out.item() * batch_sizeNEWLINENEWLINE # train_bar.set_description(desc='[%d/%d] Loss_D: %.4f Loss_G: %.4f D(x): %.4f D(G(z)): %.4f' % (NEWLINE # epoch, NUM_EPOCHS, running_results['d_loss'] / running_results['batch_sizes'],NEWLINE # running_results['g_loss'] / running_results['batch_sizes'],NEWLINE # running_results['d_score'] / running_results['batch_sizes'],NEWLINE # running_results['g_score'] / running_results['batch_sizes']))NEWLINENEWLINE if epoch < kd1 or (kd1 + kd_range - 1 < epoch < kd2) or epoch > kd2 + kd_range - 1:NEWLINE print('[%d/%d] Loss_D: %.4f Loss_G: %.4f D(x): %.4f D(G(z)): %.4f' % (NEWLINE epoch, NUM_EPOCHS, running_results['d_loss'] / running_results['batch_sizes'],NEWLINE running_results['g_loss'] / running_results['batch_sizes'],NEWLINE running_results['d_score'] / running_results['batch_sizes'],NEWLINE running_results['g_score'] / running_results['batch_sizes']))NEWLINENEWLINE netG.eval()NEWLINE out_path = 'training_results/SRF_' + '/'NEWLINE if not os.path.exists(out_path):NEWLINE os.makedirs(out_path)NEWLINENEWLINE with torch.no_grad():NEWLINE val_bar = tqdm(val_loader)NEWLINE valing_results = {'mse': 0, 'ssims': 0, 'psnr': 0, 'ssim': 0, 'batch_sizes': 0}NEWLINE val_images = []NEWLINE for val_lr, val_hr_restore, val_hr in val_bar:NEWLINE batch_size = val_lr.size(0)NEWLINE valing_results['batch_sizes'] += batch_sizeNEWLINE lr = val_lrNEWLINE hr = val_hrNEWLINE if torch.cuda.is_available():NEWLINE lr = lr.cuda()NEWLINE hr = hr.cuda()NEWLINE sr = netG(lr)NEWLINENEWLINE batch_mse = ((sr - hr) ** 2).data.mean()NEWLINE valing_results['mse'] += batch_mse * batch_sizeNEWLINE batch_ssim = pytorch_ssim.ssim(sr, hr).item()NEWLINE valing_results['ssims'] += batch_ssim * batch_sizeNEWLINE valing_results['psnr'] = 10 * log10(NEWLINE (hr.max() ** 2) / (valing_results['mse'] / valing_results['batch_sizes']))NEWLINE valing_results['ssim'] = valing_results['ssims'] / valing_results['batch_sizes']NEWLINE # val_bar.set_description(NEWLINE # desc='[converting LR images to SR images] PSNR: %.4f dB SSIM: %.4f' % (NEWLINE # valing_results['psnr'], valing_results['ssim']))NEWLINENEWLINE val_images.extend(NEWLINE [display_transform()(val_hr_restore.squeeze(0)), display_transform()(hr.data.cpu().squeeze(0)),NEWLINE display_transform()(sr.data.cpu().squeeze(0))]) # bicubic, gt, srNEWLINE print('PSNR: %.4f dB SSIM: %.4f' % (valing_results['psnr'], valing_results['ssim']))NEWLINE val_images = torch.stack(val_images)NEWLINE val_images = torch.chunk(val_images, val_images.size(0) // 15)NEWLINE val_save_bar = tqdm(val_images)NEWLINE index = 1NEWLINE print('[saving training results]')NEWLINE for image in val_save_bar:NEWLINE image = utils.make_grid(image, nrow=3, padding=5)NEWLINE utils.save_image(image, out_path + 'epoch_%d_index_%d.png' % (epoch, index), padding=5)NEWLINE index += 1NEWLINENEWLINE # save model parametersNEWLINE torch.save(netG.state_dict(), 'epochs/netG_epoch_%d_%d.pth' % (UPSCALE_FACTOR, epoch))NEWLINE torch.save(netD.state_dict(), 'epochs/netD_epoch_%d_%d.pth' % (UPSCALE_FACTOR, epoch))NEWLINE # save loss\scores\psnr\ssimNEWLINE results['d_loss'].append(running_results['d_loss'] / running_results['batch_sizes'])NEWLINE results['g_loss'].append(running_results['g_loss'] / running_results['batch_sizes'])NEWLINE results['d_score'].append(running_results['d_score'] / running_results['batch_sizes'])NEWLINE results['g_score'].append(running_results['g_score'] / running_results['batch_sizes'])NEWLINE results['psnr'].append(valing_results['psnr'])NEWLINE results['ssim'].append(valing_results['ssim'])NEWLINENEWLINE writer.add_scalar('VAL/psnr', valing_results['psnr'], epoch)NEWLINE writer.add_scalar('VAL/ssim', valing_results['ssim'], epoch)NEWLINE writer.add_scalar("loss/G_loss", running_results['g_loss'] / running_results['batch_sizes'], epoch)NEWLINE writer.add_scalar("loss/D_loss", running_results['d_loss'] / running_results['batch_sizes'], epoch)NEWLINENEWLINE writer.flush()NEWLINE writer.close()NEWLINE end = time.time()NEWLINE print('time elapsed: ', end - start)NEWLINE
import osNEWLINEimport timeNEWLINEimport statNEWLINEimport jsonNEWLINEimport zlibNEWLINEimport typingNEWLINEfrom typing import List, Sequence, MutableSequence, OptionalNEWLINEfrom collections import UserDictNEWLINEfrom hashlib import sha256NEWLINEfrom operator import attrgetterNEWLINEfrom torba.client.hash import better_aes_encrypt, better_aes_decryptNEWLINENEWLINEif typing.TYPE_CHECKING:NEWLINE from torba.client import basemanager, baseaccount, baseledgerNEWLINENEWLINENEWLINEclass TimestampedPreferences(UserDict):NEWLINENEWLINE def __getitem__(self, key):NEWLINE return self.data[key]['value']NEWLINENEWLINE def __setitem__(self, key, value):NEWLINE self.data[key] = {NEWLINE 'value': value,NEWLINE 'ts': time.time()NEWLINE }NEWLINENEWLINE def __repr__(self):NEWLINE return repr(self.to_dict_without_ts())NEWLINENEWLINE def to_dict_without_ts(self):NEWLINE return {NEWLINE key: value['value'] for key, value in self.data.items()NEWLINE }NEWLINENEWLINE @propertyNEWLINE def hash(self):NEWLINE return sha256(json.dumps(self.data).encode()).digest()NEWLINENEWLINE def merge(self, other: dict):NEWLINE for key, value in other.items():NEWLINE if key in self.data and value['ts'] < self.data[key]['ts']:NEWLINE continueNEWLINE self.data[key] = valueNEWLINENEWLINENEWLINEclass Wallet:NEWLINE """ The primary role of Wallet is to encapsulate a collectionNEWLINE of accounts (seed/private keys) and the spending rules / settingsNEWLINE for the coins attached to those accounts. Wallets are representedNEWLINE by physical files on the filesystem.NEWLINE """NEWLINENEWLINE preferences: TimestampedPreferencesNEWLINENEWLINE def __init__(self, name: str = 'Wallet', accounts: MutableSequence['baseaccount.BaseAccount'] = None,NEWLINE storage: 'WalletStorage' = None, preferences: dict = None) -> None:NEWLINE self.name = nameNEWLINE self.accounts = accounts or []NEWLINE self.storage = storage or WalletStorage()NEWLINE self.preferences = TimestampedPreferences(preferences or {})NEWLINENEWLINE @propertyNEWLINE def id(self):NEWLINE if self.storage.path:NEWLINE return os.path.basename(self.storage.path)NEWLINE return self.nameNEWLINENEWLINE def add_account(self, account: 'baseaccount.BaseAccount'):NEWLINE self.accounts.append(account)NEWLINENEWLINE def generate_account(self, ledger: 'baseledger.BaseLedger') -> 'baseaccount.BaseAccount':NEWLINE return ledger.account_class.generate(ledger, self)NEWLINENEWLINE @propertyNEWLINE def default_account(self) -> Optional['baseaccount.BaseAccount']:NEWLINE for account in self.accounts:NEWLINE return accountNEWLINE return NoneNEWLINENEWLINE def get_account_or_default(self, account_id: str) -> Optional['baseaccount.BaseAccount']:NEWLINE if account_id is None:NEWLINE return self.default_accountNEWLINE return self.get_account_or_error(account_id)NEWLINENEWLINE def get_account_or_error(self, account_id: str) -> 'baseaccount.BaseAccount':NEWLINE for account in self.accounts:NEWLINE if account.id == account_id:NEWLINE return accountNEWLINE raise ValueError(f"Couldn't find account: {account_id}.")NEWLINENEWLINE def get_accounts_or_all(self, account_ids: List[str]) -> Sequence['baseaccount.BaseAccount']:NEWLINE return [NEWLINE self.get_account_or_error(account_id)NEWLINE for account_id in account_idsNEWLINE ] if account_ids else self.accountsNEWLINENEWLINE async def get_detailed_accounts(self, **kwargs):NEWLINE ledgers = {}NEWLINE for i, account in enumerate(self.accounts):NEWLINE details = await account.get_details(**kwargs)NEWLINE details['is_default'] = i == 0NEWLINE ledger_id = account.ledger.get_id()NEWLINE ledgers.setdefault(ledger_id, [])NEWLINE ledgers[ledger_id].append(details)NEWLINE return ledgersNEWLINENEWLINE @classmethodNEWLINE def from_storage(cls, storage: 'WalletStorage', manager: 'basemanager.BaseWalletManager') -> 'Wallet':NEWLINE json_dict = storage.read()NEWLINE wallet = cls(NEWLINE name=json_dict.get('name', 'Wallet'),NEWLINE preferences=json_dict.get('preferences', {}),NEWLINE storage=storageNEWLINE )NEWLINE account_dicts: Sequence[dict] = json_dict.get('accounts', [])NEWLINE for account_dict in account_dicts:NEWLINE ledger = manager.get_or_create_ledger(account_dict['ledger'])NEWLINE ledger.account_class.from_dict(ledger, wallet, account_dict)NEWLINE return walletNEWLINENEWLINE def to_dict(self):NEWLINE return {NEWLINE 'version': WalletStorage.LATEST_VERSION,NEWLINE 'name': self.name,NEWLINE 'preferences': self.preferences.data,NEWLINE 'accounts': [a.to_dict() for a in self.accounts]NEWLINE }NEWLINENEWLINE def save(self):NEWLINE self.storage.write(self.to_dict())NEWLINENEWLINE @propertyNEWLINE def hash(self) -> bytes:NEWLINE h = sha256()NEWLINE h.update(self.preferences.hash)NEWLINE for account in sorted(self.accounts, key=attrgetter('id')):NEWLINE h.update(account.hash)NEWLINE return h.digest()NEWLINENEWLINE def pack(self, password):NEWLINE new_data = json.dumps(self.to_dict())NEWLINE new_data_compressed = zlib.compress(new_data.encode())NEWLINE return better_aes_encrypt(password, new_data_compressed)NEWLINENEWLINE @classmethodNEWLINE def unpack(cls, password, encrypted):NEWLINE decrypted = better_aes_decrypt(password, encrypted)NEWLINE decompressed = zlib.decompress(decrypted)NEWLINE return json.loads(decompressed)NEWLINENEWLINE def merge(self, manager: 'basemanager.BaseWalletManager',NEWLINE password: str, data: str) -> List['baseaccount.BaseAccount']:NEWLINE added_accounts = []NEWLINE decrypted_data = self.unpack(password, data)NEWLINE self.preferences.merge(decrypted_data.get('preferences', {}))NEWLINE for account_dict in decrypted_data['accounts']:NEWLINE ledger = manager.get_or_create_ledger(account_dict['ledger'])NEWLINE _, _, pubkey = ledger.account_class.keys_from_dict(ledger, account_dict)NEWLINE account_id = pubkey.addressNEWLINE local_match = NoneNEWLINE for local_account in self.accounts:NEWLINE if account_id == local_account.id:NEWLINE local_match = local_accountNEWLINE breakNEWLINE if local_match is not None:NEWLINE local_match.merge(account_dict)NEWLINE else:NEWLINE new_account = ledger.account_class.from_dict(ledger, self, account_dict)NEWLINE added_accounts.append(new_account)NEWLINE return added_accountsNEWLINENEWLINE @propertyNEWLINE def is_locked(self) -> bool:NEWLINE for account in self.accounts:NEWLINE if account.encrypted:NEWLINE return TrueNEWLINE return FalseNEWLINENEWLINE def unlock(self, password):NEWLINE for account in self.accounts:NEWLINE if account.encrypted:NEWLINE account.decrypt(password)NEWLINE return TrueNEWLINENEWLINE def lock(self):NEWLINE for account in self.accounts:NEWLINE if not account.encrypted:NEWLINE assert account.password is not None, "account was never encrypted"NEWLINE account.encrypt(account.password)NEWLINE return TrueNEWLINENEWLINE @propertyNEWLINE def is_encrypted(self) -> bool:NEWLINE for account in self.accounts:NEWLINE if account.serialize_encrypted:NEWLINE return TrueNEWLINE return FalseNEWLINENEWLINE def decrypt(self):NEWLINE for account in self.accounts:NEWLINE account.serialize_encrypted = FalseNEWLINE self.save()NEWLINE return TrueNEWLINENEWLINE def encrypt(self, password):NEWLINE for account in self.accounts:NEWLINE if not account.encrypted:NEWLINE account.encrypt(password)NEWLINE account.serialize_encrypted = TrueNEWLINE self.save()NEWLINE self.unlock(password)NEWLINE return TrueNEWLINENEWLINENEWLINEclass WalletStorage:NEWLINENEWLINE LATEST_VERSION = 1NEWLINENEWLINE def __init__(self, path=None, default=None):NEWLINE self.path = pathNEWLINE self._default = default or {NEWLINE 'version': self.LATEST_VERSION,NEWLINE 'name': 'My Wallet',NEWLINE 'preferences': {},NEWLINE 'accounts': []NEWLINE }NEWLINENEWLINE def read(self):NEWLINE if self.path and os.path.exists(self.path):NEWLINE with open(self.path, 'r') as f:NEWLINE json_data = f.read()NEWLINE json_dict = json.loads(json_data)NEWLINE if json_dict.get('version') == self.LATEST_VERSION and \NEWLINE set(json_dict) == set(self._default):NEWLINE return json_dictNEWLINE else:NEWLINE return self.upgrade(json_dict)NEWLINE else:NEWLINE return self._default.copy()NEWLINENEWLINE def upgrade(self, json_dict):NEWLINE json_dict = json_dict.copy()NEWLINE version = json_dict.pop('version', -1)NEWLINE if version == -1:NEWLINE passNEWLINE upgraded = self._default.copy()NEWLINE upgraded.update(json_dict)NEWLINE return json_dictNEWLINENEWLINE def write(self, json_dict):NEWLINENEWLINE json_data = json.dumps(json_dict, indent=4, sort_keys=True)NEWLINE if self.path is None:NEWLINE return json_dataNEWLINENEWLINE temp_path = "%s.tmp.%s" % (self.path, os.getpid())NEWLINE with open(temp_path, "w") as f:NEWLINE f.write(json_data)NEWLINE f.flush()NEWLINE os.fsync(f.fileno())NEWLINENEWLINE if os.path.exists(self.path):NEWLINE mode = os.stat(self.path).st_modeNEWLINE else:NEWLINE mode = stat.S_IREAD | stat.S_IWRITENEWLINE try:NEWLINE os.rename(temp_path, self.path)NEWLINE except Exception: # pylint: disable=broad-exceptNEWLINE os.remove(self.path)NEWLINE os.rename(temp_path, self.path)NEWLINE os.chmod(self.path, mode)NEWLINE
"""NEWLINEThe tsnet.postprocessing.time_history module contains functionsNEWLINEto plot the time history of head and velocity at the start andNEWLINEend point of a pipeNEWLINE"""NEWLINEfrom __future__ import print_functionNEWLINEimport matplotlib.pyplot as pltNEWLINENEWLINEdef plot_head_history(pipe,H,wn,tt):NEWLINE """Plot Head history on the start and end node of a pipeNEWLINENEWLINE ParametersNEWLINE ----------NEWLINE pipe : strNEWLINE Name of the pipe where you want to report the headNEWLINE H : listNEWLINE Head resultsNEWLINE wn : wntr.network.model.WaterNetworkModelNEWLINE NetworkNEWLINE tt : listNEWLINE Simulation timestampsNEWLINE """NEWLINENEWLINE pipeid = wn.links[pipe].id-1NEWLINE plt.figure(figsize=(10,4), dpi=80, facecolor='w', edgecolor='k')NEWLINE plt.plot(tt,H[pipeid][0,:], 'b-',label='Start Node')NEWLINE plt.plot(tt,H[pipeid][-1,:], 'r-',label='End Node')NEWLINE plt.xlim([tt[0],tt[-1]])NEWLINE plt.title('Pressure Head of Pipe %s '%pipe)NEWLINE plt.xlabel("Time")NEWLINE plt.ylabel("Pressure Head (m)")NEWLINE plt.legend(loc='best')NEWLINE plt.grid(True)NEWLINE plt.show()NEWLINENEWLINEdef plot_velocity_history(pipe,V,wn,tt):NEWLINE """Plot Velocity history on the start and end node of a pipeNEWLINENEWLINE ParametersNEWLINE ----------NEWLINE pipe : strNEWLINE Name of the pipe where you want to report the headNEWLINE V : listNEWLINE velocity resultsNEWLINE wn : wntr.network.model.WaterNetworkModelNEWLINE NetworkNEWLINE tt : listNEWLINE Simulation timestampsNEWLINE """NEWLINENEWLINE pipeid = wn.links[pipe].id-1NEWLINE plt.figure(figsize=(10,4), dpi=80, facecolor='w', edgecolor='k')NEWLINE plt.plot(tt,V[pipeid][0,:], 'b-',label='Start Node')NEWLINE plt.plot(tt,V[pipeid][-1,:], 'r-',label='End Node')NEWLINE plt.xlim([tt[0],tt[-1]])NEWLINE plt.title('Velocity Head of Pipe %s ' %pipe)NEWLINE plt.xlabel("Time")NEWLINE plt.ylabel("Velocity (m/s)")NEWLINE plt.legend(loc='best')NEWLINE plt.grid(True)NEWLINE plt.show()
#!/usr/bin/env pythonNEWLINEPROGRAM_NAME = "cg-list-site-policy-csv.py"NEWLINEPROGRAM_DESCRIPTION = """NEWLINECloudGenix script to Create a CSV listing of all Sites and their associated PoliciesNEWLINE---------------------------------------NEWLINENEWLINEusage: cg-list-site-policy-csv.py [-h] [--token "MYTOKEN"]NEWLINE [--authtokenfile "MYTOKENFILE.TXT"]NEWLINE [--csvfile csvfile]NEWLINENEWLINEBy default we write to the file 'site-policy-mapping.csv' if none is specifiedNEWLINENEWLINEExample:NEWLINENEWLINEcg-list-site-policy-csv.py --csvfile site-report.csvNEWLINE Uses either the ENV variable or interactive login and prints the report to site-report.csvNEWLINENEWLINEcg-list-site-policy-csv.py --csvfile site-report.csvNEWLINE Uses either the ENV variable or interactive login and prints the report to site-report.csvNEWLINENEWLINE"""NEWLINEfrom cloudgenix import API, jdNEWLINEimport cloudgenix_idname NEWLINEimport osNEWLINEimport sysNEWLINEimport argparseNEWLINEimport csvNEWLINENEWLINECLIARGS = {}NEWLINEcgx_session = API() #Instantiate a new CG API Session for AUTHNEWLINENEWLINEdef parse_arguments():NEWLINE parser = argparse.ArgumentParser(NEWLINE prog=PROGRAM_NAME,NEWLINE formatter_class=argparse.RawDescriptionHelpFormatter,NEWLINE description=PROGRAM_DESCRIPTIONNEWLINE )NEWLINE parser.add_argument('--token', '-t', metavar='"MYTOKEN"', type=str, NEWLINE help='specify an authtoken to use for CloudGenix authentication')NEWLINE parser.add_argument('--authtokenfile', '-f', metavar='"MYTOKENFILE.TXT"', type=str, NEWLINE help='a file containing the authtoken')NEWLINE parser.add_argument('--csvfile', '-c', metavar='csvfile', type=str, NEWLINE help='the CSV Filename to write', default="site-policy-mapping.csv", required=False)NEWLINE args = parser.parse_args()NEWLINE CLIARGS.update(vars(args)) ##ASSIGN ARGUMENTS to our DICTNEWLINE print(CLIARGS)NEWLINENEWLINEdef authenticate():NEWLINE print("AUTHENTICATING...")NEWLINE user_email = NoneNEWLINE user_password = NoneNEWLINE NEWLINE ##First attempt to use an AuthTOKEN if definedNEWLINE if CLIARGS['token']: #Check if AuthToken is in the CLI ARGNEWLINE CLOUDGENIX_AUTH_TOKEN = CLIARGS['token']NEWLINE print(" ","Authenticating using Auth-Token in from CLI ARGS")NEWLINE elif CLIARGS['authtokenfile']: #Next: Check if an AuthToken file is usedNEWLINE tokenfile = open(CLIARGS['authtokenfile'])NEWLINE CLOUDGENIX_AUTH_TOKEN = tokenfile.read().strip()NEWLINE print(" ","Authenticating using Auth-token from file",CLIARGS['authtokenfile'])NEWLINE elif "X_AUTH_TOKEN" in os.environ: #Next: Check if an AuthToken is defined in the OS as X_AUTH_TOKENNEWLINE CLOUDGENIX_AUTH_TOKEN = os.environ.get('X_AUTH_TOKEN')NEWLINE print(" ","Authenticating using environment variable X_AUTH_TOKEN")NEWLINE elif "AUTH_TOKEN" in os.environ: #Next: Check if an AuthToken is defined in the OS as AUTH_TOKENNEWLINE CLOUDGENIX_AUTH_TOKEN = os.environ.get('AUTH_TOKEN')NEWLINE print(" ","Authenticating using environment variable AUTH_TOKEN")NEWLINE else: #Next: If we are not using an AUTH TOKEN, set it to NULL NEWLINE CLOUDGENIX_AUTH_TOKEN = NoneNEWLINE print(" ","Authenticating using interactive login")NEWLINE ##ATTEMPT AUTHENTICATIONNEWLINE if CLOUDGENIX_AUTH_TOKEN:NEWLINE cgx_session.interactive.use_token(CLOUDGENIX_AUTH_TOKEN)NEWLINE if cgx_session.tenant_id is None:NEWLINE print(" ","ERROR: AUTH_TOKEN login failure, please check token.")NEWLINE sys.exit()NEWLINE else:NEWLINE while cgx_session.tenant_id is None:NEWLINE cgx_session.interactive.login(user_email, user_password)NEWLINE # clear after one failed login, force relogin.NEWLINE if not cgx_session.tenant_id:NEWLINE user_email = NoneNEWLINE user_password = None NEWLINE print(" ","SUCCESS: Authentication Complete")NEWLINENEWLINEdef go():NEWLINE name_to_id = cloudgenix_idname.generate_id_name_map(cgx_session)NEWLINENEWLINE ####CODE GOES BELOW HERE#########NEWLINE resp = cgx_session.get.tenants()NEWLINE if resp.cgx_status:NEWLINE tenant_name = resp.cgx_content.get("name", None)NEWLINE print("======== TENANT NAME",tenant_name,"========")NEWLINE else:NEWLINE logout()NEWLINE print("ERROR: API Call failure when enumerating TENANT Name! Exiting!")NEWLINE print(resp.cgx_status)NEWLINE sys.exit((vars(resp)))NEWLINENEWLINE csvfilename = CLIARGS['csvfile']NEWLINE NEWLINE counter = 0NEWLINE with open(csvfilename, 'w', newline='') as csvfile:NEWLINE csvwriter = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)NEWLINE resp = cgx_session.get.sites()NEWLINE if resp.cgx_status:NEWLINE site_list = resp.cgx_content.get("items", None) #EVENT_LIST contains an list of all returned eventsNEWLINE csvwriter.writerow( [ "Site-Name", "Path-Policy", "QoS-Policy", "NAT-Policy"])NEWLINE for site in site_list: NEWLINE NEWLINENEWLINE site_name = name_to_id[site['id']]NEWLINE if (site['element_cluster_role'] == "SPOKE"): ###ONLY do this for SPOKE'sNEWLINE if (site['policy_set_id']): ###Are we using Classic Policies? If so, there is no separate "QoS" PolicyNEWLINE path_name = name_to_id[site['policy_set_id']]NEWLINE qos_name = name_to_id[site['policy_set_id']]NEWLINE nat_name = name_to_id[site['policy_set_id']]NEWLINE elif (site['network_policysetstack_id']): ### Using Stacked policy instead!NEWLINE path_name = name_to_id[site['network_policysetstack_id']]NEWLINE qos_name = name_to_id[site['priority_policysetstack_id']]NEWLINE nat_name = name_to_id[site['nat_policysetstack_id']]NEWLINE else:NEWLINE path_name = "None"NEWLINE qos_name = "None"NEWLINE nat_name = "None"NEWLINE NEWLINE counter += 1NEWLINE csvwriter.writerow( [ NEWLINE site_name, path_name, qos_name, nat_nameNEWLINE ] ) NEWLINE else:NEWLINE logout()NEWLINE print("ERROR: API Call failure when enumerating SITES in tenant! Exiting!")NEWLINE sys.exit((jd(resp)))NEWLINENEWLINE print("Wrote to CSV File:", csvfilename, " - ", counter, 'rows')NEWLINE ####CODE GOES ABOVE HERE#########NEWLINE NEWLINEdef logout():NEWLINE print("Logging out")NEWLINE cgx_session.get.logout()NEWLINENEWLINEif __name__ == "__main__":NEWLINE parse_arguments()NEWLINE authenticate()NEWLINE go()NEWLINE logout()NEWLINE
#!/usr/bin/pythonNEWLINE# -*- coding: UTF-8 -*-NEWLINEimport jsonNEWLINEimport osNEWLINEimport shutilNEWLINENEWLINEfrom django.conf import settingsNEWLINEfrom django.core.management.base import BaseCommandNEWLINEfrom django.template.loader import render_to_stringNEWLINENEWLINEimport tastypie_swaggerNEWLINENEWLINENEWLINEclass Command(BaseCommand):NEWLINE help = 'Collect swagger-ui static file and compile index.html.'NEWLINE dest_dir = getattr(settings, 'TASTYPIE_SWAGGER_DOCS_DIR')NEWLINE swagger_static_dir = os.path.join(tastypie_swagger.__path__[0], 'static')NEWLINENEWLINE def _compile_index(self):NEWLINE self.stdout.write('Compiling index.html, please wait patiently.')NEWLINE context = {NEWLINE 'index_title': getattr(settings, 'TASTYPIE_SWAGGER_INDEX_TITLE',NEWLINE 'Swagger UI'),NEWLINE 'STATIC_URL': './',NEWLINE 'json_spec': json.dumps(NEWLINE tastypie_swagger.mapping.build_openapi_spec()),NEWLINE }NEWLINE return render_to_string('tastypie_swagger/index.html', context)NEWLINENEWLINE def _copy_index(self):NEWLINE index_path = os.path.join(self.dest_dir, 'index.html')NEWLINE self.stdout.write('Copy index.html to {}.'.format(index_path))NEWLINE with open(index_path, 'w') as f:NEWLINE f.write(self._compile_index())NEWLINENEWLINE def _copy_static_file(self):NEWLINE ignore_pattern_list = getattr(settings,NEWLINE 'TASTYPIE_SWAGGER_IGNORE_PATTERN_LIST',NEWLINE None)NEWLINE if ignore_pattern_list:NEWLINE ignore_pattern = shutil.ignore_patterns(*ignore_pattern_list)NEWLINE else:NEWLINE ignore_pattern = NoneNEWLINE self.stdout.write('Copy static files to {}.'.format(self.dest_dir))NEWLINE shutil.copytree(self.swagger_static_dir, self.dest_dir,NEWLINE ignore=ignore_pattern)NEWLINENEWLINE def _remove_outdated_docs(self):NEWLINE if os.path.exists(self.dest_dir):NEWLINE self.stdout.write(NEWLINE 'Remove outdated api docs:{}.'.format(self.dest_dir))NEWLINE shutil.rmtree(self.dest_dir)NEWLINENEWLINE def handle(self, *args, **options):NEWLINE self._remove_outdated_docs()NEWLINE self._copy_static_file()NEWLINE self._copy_index()NEWLINE self.stdout.write('Done!')NEWLINE
# Copyright 2013-2018 Lawrence Livermore National Security, LLC and otherNEWLINE# Spack Project Developers. See the top-level COPYRIGHT file for details.NEWLINE#NEWLINE# SPDX-License-Identifier: (Apache-2.0 OR MIT)NEWLINENEWLINEfrom spack import *NEWLINENEWLINENEWLINEclass RPsych(RPackage):NEWLINE """A general purpose toolbox for personality, psychometric theory andNEWLINE experimental psychology. Functions are primarily for multivariateNEWLINE analysis and scale construction using factor analysis, principalNEWLINE component analysis, cluster analysis and reliability analysis, althoughNEWLINE others provide basic descriptive statistics. Item Response Theory isNEWLINE done using factor analysis of tetrachoric and polychoric correlations.NEWLINE Functions for analyzing data at multiple levels include within andNEWLINE between group statistics, including correlations and factor analysis.NEWLINE Functions for simulating and testing particular item and test structuresNEWLINE are included. Several functions serve as a useful front end forNEWLINE structural equation modeling. Graphical displays of path diagrams,NEWLINE factor analysis and structural equation models are created using basicNEWLINE graphics. Some of the functions are written to support a book onNEWLINE psychometric theory as well as publications in personality research.NEWLINE For more information, see the <http://personality-project.org/r> webNEWLINE page."""NEWLINENEWLINE homepage = "http://personality-project.org/r/psych"NEWLINE url = "https://cran.r-project.org/src/contrib/psych_1.7.8.tar.gz"NEWLINE list_url = "https://cran.r-project.org/src/contrib/Archive/psych"NEWLINENEWLINE version('1.7.8', 'db37f2f85ff5470ee40bbc0a58ebe22b')NEWLINENEWLINE depends_on('r-mnormt', type=('build', 'run'))NEWLINE depends_on('r-foreign', type=('build', 'run'))NEWLINE depends_on('r-lattice', type=('build', 'run'))NEWLINE depends_on('r-nlme', type=('build', 'run'))NEWLINE
import numpy as npNEWLINEimport torchNEWLINEimport torch.nn as nnNEWLINENEWLINEfrom mmcv.cnn import constant_init, normal_initNEWLINEfrom mmdet.models.anchor_heads.ssd_head import SSDHeadNEWLINEfrom mmdet.models.registry import HEADSNEWLINENEWLINEfrom .operations import conv_dw_headNEWLINENEWLINENEWLINE@HEADS.register_moduleNEWLINEclass SSDLightHead(SSDHead):NEWLINENEWLINE def __init__(self,NEWLINE input_size=300,NEWLINE num_classes=81,NEWLINE in_channels=(512, 1024, 512, 256, 256, 256),NEWLINE anchor_strides=(8, 16, 32, 64, 100, 300),NEWLINE basesize_ratio_range=(0.1, 0.9),NEWLINE anchor_ratios=([2], [2, 3], [2, 3], [2, 3], [2], [2]),NEWLINE target_means=(.0, .0, .0, .0),NEWLINE target_stds=(1.0, 1.0, 1.0, 1.0),NEWLINE search=False):NEWLINE super(SSDLightHead, self).__init__(input_size, num_classes, in_channels, NEWLINE anchor_strides, basesize_ratio_range, anchor_ratios,NEWLINE target_means, target_stds)NEWLINE self.search = searchNEWLINE num_anchors = [len(ratios) * 2 + 2 for ratios in anchor_ratios]NEWLINE reg_convs = []NEWLINE cls_convs = []NEWLINE for i in range(len(in_channels)):NEWLINE reg_convs.append(NEWLINE conv_dw_head(in_channels[i], num_anchors[i] * 4)NEWLINE )NEWLINE cls_convs.append(NEWLINE conv_dw_head(in_channels[i], num_anchors[i] * num_classes)NEWLINE )NEWLINE self.reg_convs = nn.ModuleList(reg_convs)NEWLINE self.cls_convs = nn.ModuleList(cls_convs)NEWLINENEWLINE def init_weights(self):NEWLINE for m in self.modules():NEWLINE if isinstance(m, nn.Conv2d):NEWLINE normal_init(m, std=0.03)NEWLINE elif isinstance(m, nn.BatchNorm2d):NEWLINE constant_init(m, 1)NEWLINENEWLINE def forward(self, feats):NEWLINE if self.search:NEWLINE feats, net_sub_obj = featsNEWLINE cls_scores = []NEWLINE bbox_preds = []NEWLINE for feat, reg_conv, cls_conv in zip(feats, self.reg_convs,NEWLINE self.cls_convs):NEWLINE cls_scores.append(cls_conv(feat))NEWLINE bbox_preds.append(reg_conv(feat))NEWLINE if self.search:NEWLINE return (cls_scores, bbox_preds), net_sub_obj NEWLINE else:NEWLINE return cls_scores, bbox_preds
from pycat.geometry.point import PointNEWLINENEWLINENEWLINEdef line_intersection(NEWLINE ax: float,NEWLINE ay: float,NEWLINE bx: float,NEWLINE by: float,NEWLINE cx: float,NEWLINE cy: float,NEWLINE dx: float,NEWLINE dy: float,NEWLINE ) -> Point:NEWLINE d = ay*cx - by*cx - ax*cy + bx*cy - ay*dx + by*dx + ax*dy - bx*dyNEWLINE if abs(d) < 0.0001:NEWLINE # parallel linesNEWLINE # still need to check special case if lines overlapNEWLINE return NoneNEWLINE t1 = (bx*cy - bx*dy - by*cx + by*dx + cx*dy - cy*dx) / dNEWLINE t2 = (ay*bx - ax*by - ay*dx + by*dx + ax*dy - bx*dy) / dNEWLINE if 0 <= t1 <= 1 and 0 <= t2 <= 1:NEWLINE # return t1 to test multiple intersectionsNEWLINE return Point(t1*ax + (1-t1)*bx, t1*ay + (1-t1)*by)NEWLINE return NoneNEWLINENEWLINE # if sprite.is_moving_through(prev_position, other_sprite):NEWLINE # sprite.get_intersecting_points(other_sprite)NEWLINE
import osNEWLINEimport numpy as npNEWLINEimport cv2NEWLINEimport torchNEWLINEimport torchvisionNEWLINEimport carlaNEWLINENEWLINEfrom PIL import Image, ImageDrawNEWLINENEWLINEfrom carla_project.src.image_model import ImageModelNEWLINEfrom carla_project.src.converter import ConverterNEWLINENEWLINEfrom team_code.base_agent import BaseAgentNEWLINEfrom team_code.pid_controller import PIDControllerNEWLINE# additionNEWLINEimport datetimeNEWLINEimport pathlibNEWLINENEWLINEDEBUG = int(os.environ.get('HAS_DISPLAY', 0))NEWLINENEWLINE# additionNEWLINEfrom carla_project.src.carla_env import draw_traffic_lights, get_nearby_lightsNEWLINEfrom carla_project.src.common import CONVERTER, COLORNEWLINEfrom srunner.scenariomanager.carla_data_provider import CarlaDataProviderNEWLINEfrom local_planner import LocalPlannerNEWLINEimport jsonNEWLINEdef get_entry_point():NEWLINE return 'ImageAgent'NEWLINENEWLINENEWLINEdef debug_display(tick_data, target_cam, out, steer, throttle, brake, desired_speed, step):NEWLINE # modificationNEWLINENEWLINE # rgb = np.hstack((tick_data['rgb_left'], tick_data['rgb'], tick_data['rgb_right']))NEWLINENEWLINENEWLINE _rgb = Image.fromarray(tick_data['rgb'])NEWLINE _draw_rgb = ImageDraw.Draw(_rgb)NEWLINE _draw_rgb.ellipse((target_cam[0]-3,target_cam[1]-3,target_cam[0]+3,target_cam[1]+3), (255, 255, 255))NEWLINENEWLINE for x, y in out:NEWLINE x = (x + 1) / 2 * 256NEWLINE y = (y + 1) / 2 * 144NEWLINENEWLINE _draw_rgb.ellipse((x-2, y-2, x+2, y+2), (0, 0, 255))NEWLINENEWLINE _combined = Image.fromarray(np.hstack([tick_data['rgb_left'], _rgb, tick_data['rgb_right']]))NEWLINENEWLINE _combined = _combined.resize((int(256 / _combined.size[1] * _combined.size[0]), 256))NEWLINE _topdown = Image.fromarray(COLOR[CONVERTER[tick_data['topdown']]])NEWLINE _topdown.thumbnail((256, 256))NEWLINE _combined = Image.fromarray(np.hstack((_combined, _topdown)))NEWLINENEWLINENEWLINE _draw = ImageDraw.Draw(_combined)NEWLINE _draw.text((5, 10), 'Steer: %.3f' % steer)NEWLINE _draw.text((5, 30), 'Throttle: %.3f' % throttle)NEWLINE _draw.text((5, 50), 'Brake: %s' % brake)NEWLINE _draw.text((5, 70), 'Speed: %.3f' % tick_data['speed'])NEWLINE _draw.text((5, 90), 'Desired: %.3f' % desired_speed)NEWLINE _draw.text((5, 110), 'Far Command: %s' % str(tick_data['far_command']))NEWLINENEWLINE cv2.imshow('map', cv2.cvtColor(np.array(_combined), cv2.COLOR_BGR2RGB))NEWLINE cv2.waitKey(1)NEWLINENEWLINENEWLINEclass ImageAgent(BaseAgent):NEWLINE def setup(self, path_to_conf_file):NEWLINE super().setup(path_to_conf_file)NEWLINENEWLINE self.converter = Converter()NEWLINE self.net = ImageModel.load_from_checkpoint(path_to_conf_file)NEWLINE self.net.cuda()NEWLINE self.net.eval()NEWLINENEWLINENEWLINENEWLINENEWLINE # addition: modified from leaderboard/team_code/auto_pilot.pyNEWLINE def save(self, steer, throttle, brake, tick_data):NEWLINE # frame = self.step // 10NEWLINE frame = self.stepNEWLINENEWLINE pos = self._get_position(tick_data)NEWLINE far_command = tick_data['far_command']NEWLINE speed = tick_data['speed']NEWLINENEWLINENEWLINENEWLINE center = os.path.join('rgb', ('%04d.png' % frame))NEWLINE left = os.path.join('rgb_left', ('%04d.png' % frame))NEWLINE right = os.path.join('rgb_right', ('%04d.png' % frame))NEWLINE topdown = os.path.join('topdown', ('%04d.png' % frame))NEWLINE rgb_with_car = os.path.join('rgb_with_car', ('%04d.png' % frame))NEWLINENEWLINE data_row = ','.join([str(i) for i in [frame, far_command, speed, steer, throttle, brake, str(center), str(left), str(right)]])NEWLINE with (self.save_path / 'measurements.csv' ).open("a") as f_out:NEWLINE f_out.write(data_row+'\n')NEWLINENEWLINENEWLINE Image.fromarray(tick_data['rgb']).save(self.save_path / center)NEWLINE Image.fromarray(tick_data['rgb_left']).save(self.save_path / left)NEWLINE Image.fromarray(tick_data['rgb_right']).save(self.save_path / right)NEWLINENEWLINE # additionNEWLINE Image.fromarray(COLOR[CONVERTER[tick_data['topdown']]]).save(self.save_path / topdown)NEWLINE Image.fromarray(tick_data['rgb_with_car']).save(self.save_path / rgb_with_car)NEWLINENEWLINENEWLINENEWLINE ########################################################################NEWLINE # log necessary info for action-basedNEWLINE if self.args.save_action_based_measurements:NEWLINE from affordances import get_driving_affordancesNEWLINENEWLINE self._pedestrian_forbidden_distance = 10.0NEWLINE self._pedestrian_max_detected_distance = 50.0NEWLINE self._vehicle_forbidden_distance = 10.0NEWLINE self._vehicle_max_detected_distance = 50.0NEWLINE self._tl_forbidden_distance = 10.0NEWLINE self._tl_max_detected_distance = 50.0NEWLINE self._speed_detected_distance = 10.0NEWLINENEWLINE self._default_target_speed = 10NEWLINE self._angle = NoneNEWLINENEWLINE current_affordances = get_driving_affordances(self, self._pedestrian_forbidden_distance, self._pedestrian_max_detected_distance, self._vehicle_forbidden_distance, self._vehicle_max_detected_distance, self._tl_forbidden_distance, self._tl_max_detected_distance, self._angle_rad, self._default_target_speed, self._target_speed, self._speed_detected_distance, angle=True)NEWLINENEWLINE is_vehicle_hazard = current_affordances['is_vehicle_hazard']NEWLINE is_red_tl_hazard = current_affordances['is_red_tl_hazard']NEWLINE is_pedestrian_hazard = current_affordances['is_pedestrian_hazard']NEWLINE forward_speed = current_affordances['forward_speed']NEWLINE relative_angle = current_affordances['relative_angle']NEWLINE target_speed = current_affordances['target_speed']NEWLINE closest_pedestrian_distance = current_affordances['closest_pedestrian_distance']NEWLINE closest_vehicle_distance = current_affordances['closest_vehicle_distance']NEWLINE closest_red_tl_distance = current_affordances['closest_red_tl_distance']NEWLINENEWLINENEWLINENEWLINE log_folder = str(self.save_path / 'affordance_measurements')NEWLINE if not os.path.exists(log_folder):NEWLINE os.mkdir(log_folder)NEWLINE log_path = os.path.join(log_folder, f'{self.step:06}.json')NEWLINENEWLINENEWLINE ego_transform = self._vehicle.get_transform()NEWLINE ego_location = ego_transform.locationNEWLINE ego_rotation = ego_transform.rotationNEWLINE ego_velocity = self._vehicle.get_velocity()NEWLINENEWLINE brake_noise = 0.0NEWLINE throttle_noise = 0.0 # 1.0 -> 0.0NEWLINE steer_noise = 0.0 # NaN -> 0.0NEWLINENEWLINE # class RoadOptionNEWLINE map_roadoption_to_action_based_roadoption = {-1:2, 1:3, 2:4, 3:5, 4:2, 5:2, 6:2}NEWLINENEWLINE # save info for action-based repNEWLINE json_log_data = {NEWLINE "brake": float(brake),NEWLINE "closest_red_tl_distance": closest_red_tl_distance,NEWLINE "throttle": throttle,NEWLINE "directions": float(map_roadoption_to_action_based_roadoption[far_command.value]),NEWLINE "brake_noise": brake_noise,NEWLINE "is_red_tl_hazard": is_red_tl_hazard,NEWLINE "opponents": {},NEWLINE "closest_pedestrian_distance": closest_pedestrian_distance,NEWLINE "is_pedestrian_hazard": is_pedestrian_hazard,NEWLINE "lane": {},NEWLINE "is_vehicle_hazard": is_vehicle_hazard,NEWLINE "throttle_noise": throttle_noise,NEWLINE "ego_actor": {NEWLINE "velocity": [NEWLINE ego_velocity.x,NEWLINE ego_velocity.y,NEWLINE ego_velocity.zNEWLINE ],NEWLINE "position": [NEWLINE ego_location.x,NEWLINE ego_location.y,NEWLINE ego_location.zNEWLINE ],NEWLINE "orientation": [NEWLINE ego_rotation.roll,NEWLINE ego_rotation.pitch,NEWLINE ego_rotation.yawNEWLINE ]NEWLINE },NEWLINE "hand_brake": False,NEWLINE "steer_noise": steer_noise,NEWLINE "reverse": False,NEWLINE "relative_angle": relative_angle,NEWLINE "closest_vehicle_distance": closest_vehicle_distance,NEWLINE "walkers": {},NEWLINE "forward_speed": forward_speed,NEWLINE "steer": steer,NEWLINE "target_speed": target_speedNEWLINE }NEWLINENEWLINE with open(log_path, 'w') as f_out:NEWLINE json.dump(json_log_data, f_out, indent=4)NEWLINENEWLINENEWLINE def _init(self):NEWLINE super()._init()NEWLINENEWLINE self._turn_controller = PIDController(K_P=1.25, K_I=0.75, K_D=0.3, n=40)NEWLINE self._speed_controller = PIDController(K_P=5.0, K_I=0.5, K_D=1.0, n=40)NEWLINENEWLINE # addition:NEWLINE self._vehicle = CarlaDataProvider.get_hero_actor()NEWLINE self._world = self._vehicle.get_world()NEWLINENEWLINENEWLINE # -------------------------------------------------------NEWLINE # add a local_planner in order to estimate relative angleNEWLINE # self.target_speed = 10NEWLINE # args_lateral_dict = {NEWLINE # 'K_P': 1,NEWLINE # 'K_D': 0.4,NEWLINE # 'K_I': 0,NEWLINE # 'dt': 1.0/10.0}NEWLINE # self._local_planner = LocalPlanner(NEWLINE # self._vehicle, opt_dict={'target_speed' : self.target_speed,NEWLINE # 'lateral_control_dict':args_lateral_dict})NEWLINE # self._hop_resolution = 2.0NEWLINE # self._path_seperation_hop = 2NEWLINE # self._path_seperation_threshold = 0.5NEWLINE # self._grp = NoneNEWLINE #NEWLINE # self._map = CarlaDataProvider.get_map()NEWLINE # route = [(self._map.get_waypoint(x[0].location), x[1]) for x in self._global_plan_world_coord]NEWLINE #NEWLINE # self._local_planner.set_global_plan(route)NEWLINENEWLINENEWLINE def tick(self, input_data):NEWLINENEWLINENEWLINENEWLINE result = super().tick(input_data)NEWLINE result['image'] = np.concatenate(tuple(result[x] for x in ['rgb', 'rgb_left', 'rgb_right']), -1)NEWLINENEWLINENEWLINE rgb_with_car = cv2.cvtColor(input_data['rgb_with_car'][1][:, :, :3], cv2.COLOR_BGR2RGB)NEWLINE result['rgb_with_car'] = rgb_with_carNEWLINENEWLINE result['radar_central'] = input_data['radar_central']NEWLINENEWLINE theta = result['compass']NEWLINE theta = 0.0 if np.isnan(theta) else thetaNEWLINE theta = theta + np.pi / 2NEWLINE R = np.array([NEWLINE [np.cos(theta), -np.sin(theta)],NEWLINE [np.sin(theta), np.cos(theta)],NEWLINE ])NEWLINENEWLINE gps = self._get_position(result)NEWLINE # modificationNEWLINE far_node, far_command = self._command_planner.run_step(gps)NEWLINE target = R.T.dot(far_node - gps)NEWLINE target *= 5.5NEWLINE target += [128, 256]NEWLINE target = np.clip(target, 0, 256)NEWLINENEWLINE result['target'] = targetNEWLINE # addition:NEWLINE self._actors = self._world.get_actors()NEWLINE self._traffic_lights = get_nearby_lights(self._vehicle, self._actors.filter('*traffic_light*'))NEWLINE result['far_command'] = far_commandNEWLINE topdown = input_data['map'][1][:, :, 2]NEWLINE topdown = draw_traffic_lights(topdown, self._vehicle, self._traffic_lights)NEWLINE result['topdown'] = topdownNEWLINENEWLINENEWLINE return resultNEWLINENEWLINE @torch.no_grad()NEWLINE def run_step_using_learned_controller(self, input_data, timestamp):NEWLINE if not self.initialized:NEWLINE self._init()NEWLINENEWLINE tick_data = self.tick(input_data)NEWLINENEWLINE img = torchvision.transforms.functional.to_tensor(tick_data['image'])NEWLINE img = img[None].cuda()NEWLINENEWLINE target = torch.from_numpy(tick_data['target'])NEWLINE target = target[None].cuda()NEWLINENEWLINE import randomNEWLINE torch.manual_seed(2)NEWLINE torch.cuda.manual_seed_all(2)NEWLINE torch.backends.cudnn.deterministic = TrueNEWLINE np.random.seed(1)NEWLINE random.seed(1)NEWLINE device = torch.device('cuda')NEWLINE torch.backends.cudnn.benchmark = FalseNEWLINENEWLINE points, (target_cam, _) = self.net.forward(img, target)NEWLINE control = self.net.controller(points).cpu().squeeze()NEWLINENEWLINE steer = control[0].item()NEWLINE desired_speed = control[1].item()NEWLINE speed = tick_data['speed']NEWLINENEWLINE brake = desired_speed < 0.4 or (speed / desired_speed) > 1.1NEWLINENEWLINE delta = np.clip(desired_speed - speed, 0.0, 0.25)NEWLINE throttle = self._speed_controller.step(delta)NEWLINE throttle = np.clip(throttle, 0.0, 0.75)NEWLINE throttle = throttle if not brake else 0.0NEWLINENEWLINE control = carla.VehicleControl()NEWLINE control.steer = steerNEWLINE control.throttle = throttleNEWLINE control.brake = float(brake)NEWLINENEWLINE if DEBUG:NEWLINE debug_display(NEWLINE tick_data, target_cam.squeeze(), points.cpu().squeeze(),NEWLINE steer, throttle, brake, desired_speed,NEWLINE self.step)NEWLINENEWLINE return controlNEWLINENEWLINE @torch.no_grad()NEWLINE def run_step(self, input_data, timestamp):NEWLINE if not self.initialized:NEWLINE self._init()NEWLINENEWLINE tick_data = self.tick(input_data)NEWLINE radar_data = tick_data['radar_central'][1]NEWLINENEWLINENEWLINENEWLINE img = torchvision.transforms.functional.to_tensor(tick_data['image'])NEWLINE img = img[None].cuda()NEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE target = torch.from_numpy(tick_data['target'])NEWLINE target = target[None].cuda()NEWLINENEWLINE points, (target_cam, _) = self.net.forward(img, target)NEWLINE points_cam = points.clone().cpu()NEWLINENEWLINE if self.step == 0:NEWLINE print('\n'*5)NEWLINE print('step :', self.step)NEWLINE # print('radar')NEWLINE # print(radar_data.shape)NEWLINE # print(radar_data)NEWLINE # print(np.max(radar_data, axis=0))NEWLINE print('image', np.sum(tick_data['image']))NEWLINE # print('img', torch.sum(img))NEWLINE # print('target', target)NEWLINE # print('points', points)NEWLINE print('\n'*5)NEWLINENEWLINE points_cam[..., 0] = (points_cam[..., 0] + 1) / 2 * img.shape[-1]NEWLINE points_cam[..., 1] = (points_cam[..., 1] + 1) / 2 * img.shape[-2]NEWLINE points_cam = points_cam.squeeze()NEWLINE points_world = self.converter.cam_to_world(points_cam).numpy()NEWLINENEWLINENEWLINE aim = (points_world[1] + points_world[0]) / 2.0NEWLINE angle = np.degrees(np.pi / 2 - np.arctan2(aim[1], aim[0]))NEWLINE self._angle_rad = np.radians(angle)NEWLINE angle = angle / 90NEWLINE steer = self._turn_controller.step(angle)NEWLINE steer = np.clip(steer, -1.0, 1.0)NEWLINENEWLINE desired_speed = np.linalg.norm(points_world[0] - points_world[1]) * 2.0NEWLINE # desired_speed *= (1 - abs(angle)) ** 2NEWLINE self._target_speed = desired_speedNEWLINE speed = tick_data['speed']NEWLINENEWLINE brake = desired_speed < 0.4 or (speed / desired_speed) > 1.1NEWLINENEWLINE delta = np.clip(desired_speed - speed, 0.0, 0.25)NEWLINE throttle = self._speed_controller.step(delta)NEWLINE throttle = np.clip(throttle, 0.0, 0.75)NEWLINE throttle = throttle if not brake else 0.0NEWLINENEWLINE control = carla.VehicleControl()NEWLINE control.steer = steerNEWLINE control.throttle = throttleNEWLINE control.brake = float(brake)NEWLINENEWLINE if DEBUG:NEWLINE debug_display(tick_data, target_cam.squeeze(), points.cpu().squeeze(), steer, throttle, brake, desired_speed, self.step)NEWLINENEWLINE # addition: from leaderboard/team_code/auto_pilot.pyNEWLINE if self.step == 0:NEWLINE title_row = ','.join(['frame_id', 'far_command', 'speed', 'steering', 'throttle', 'brake', 'center', 'left', 'right'])NEWLINE with (self.save_path / 'measurements.csv' ).open("a") as f_out:NEWLINE f_out.write(title_row+'\n')NEWLINE if self.step % 1 == 0:NEWLINE self.gather_info((steer, throttle, float(brake), speed))NEWLINENEWLINE record_every_n_steps = self.record_every_n_stepNEWLINE if self.step % record_every_n_steps == 0:NEWLINE self.save(steer, throttle, brake, tick_data)NEWLINE return controlNEWLINE
#===============================================================================NEWLINE#NEWLINE# FILE: parse_log_3.pyNEWLINE#NEWLINE# USAGE:NEWLINE#NEWLINE# DESCRIPTION:NEWLINE#NEWLINE# OPTIONS: NEWLINE# REQUIREMENTS: NEWLINE# BUGS: NEWLINE# NOTES: NEWLINE# AUTHOR: Debjit PalNEWLINE# CONTACT: debjit.pal@cornell.eduNEWLINE# ORGANIZATION: ECE, Cornell UniversityNEWLINE# VERSION: NEWLINE# CREATED: 22-11-2019NEWLINE# REVISION: NEWLINE# LMODIFIED: Fri 22 Nov 2019 11:49:26 PM ESTNEWLINE#===============================================================================NEWLINENEWLINEimport os, sysNEWLINEfrom shutil import copyfile as cpfNEWLINENEWLINEgl_dir = os.environ.get('GRAPHLEARN')NEWLINESOURCE_PATH = gl_dir + '/data_app_source_bit'NEWLINEDEST_PATH = gl_dir + '/num_source'NEWLINENEWLINE#SOURCE_PATH = 'path..../source_data/data_app_source_bit'NEWLINE#DEST_PATH = 'path..../source_data/num_source'NEWLINENEWLINEfiles = [f for f in os.listdir(SOURCE_PATH) if f.endswith('.edgelist')]NEWLINEfiles_sorted = sorted(files)NEWLINEdel filesNEWLINENEWLINEcounter = 0NEWLINENEWLINEmh = open('nfile_efile_glearn.map', 'w')NEWLINEfor file_ in files_sorted:NEWLINE name = file_[:file_.find('.')]NEWLINE cpf_name = str(counter)NEWLINE cpf(SOURCE_PATH + '/' + name + '.edgelist', DEST_PATH + '/' + cpf_name + '.edgelist')NEWLINE cpf(SOURCE_PATH + '/' + name + '.nodelist', DEST_PATH + '/' + cpf_name + '.nodelist')NEWLINE mh.write(name + '\t' + cpf_name + '\n')NEWLINE counter = counter + 1NEWLINENEWLINEmh.close()NEWLINE
# -*- coding: utf-8 -*-NEWLINENEWLINE"""NEWLINEtaiga_ncurses.ui.signalsNEWLINE~~~~~~~~~~~~~~~~~~~~~~~~NEWLINE"""NEWLINENEWLINEimport urwidNEWLINENEWLINEconnect = urwid.connect_signalNEWLINEdisconnect = urwid.disconnect_signalNEWLINENEWLINEdef emit(widget, signal):NEWLINE widget._emit(signal)NEWLINE
# -*- coding: utf-8 -*-NEWLINE"""NEWLINECreated on Thu Apr 16 10:17:24 2020NEWLINENEWLINE@author: roger.marquezNEWLINE"""NEWLINENEWLINEfrom . import datafileNEWLINEfrom . import tao5datafileNEWLINEfrom . import naldatafileNEWLINEfrom . import azuredatalaketoa5datafileNEWLINENEWLINEclass DataFileFactory:NEWLINE @staticmethodNEWLINE def GenerateDataFileByType(dfType: str, file: str, limitData30days: bool, cfg: dict) -> datafile.DataFile:NEWLINE ttype = dfType.lower()NEWLINE if ttype == 'tao5':NEWLINE return tao5datafile.TAO5DataFile(file, limitData30days, cfg)NEWLINE elif ttype == 'nal':NEWLINE return naldatafile.NALDataFile(file, limitData30days, cfg)NEWLINE elif ttype == 'caf':NEWLINE return azuredatalaketoa5datafile.AzureDataLakeTOA5DataFile(file, limitData30days, cfg)NEWLINE else:NEWLINE raise ValueError(dfType) NEWLINENEWLINENEWLINE NEWLINE
S = input()NEWLINENEWLINEwhile S != "0+0=0":NEWLINE S = S[::-1]NEWLINE a, b = S.split('=')NEWLINE b, c = b.split('+')NEWLINENEWLINE if int(a) == int(b) + int(c):NEWLINE print('True')NEWLINE else:NEWLINE print('False')NEWLINENEWLINE S = input()NEWLINENEWLINEprint('True')NEWLINE
NEWLINENEWLINENEWLINEdef custom_jwt_response_handler(token, user=None, request=None):NEWLINENEWLINE return {NEWLINE "username": user.username,NEWLINE "user_id": user.id,NEWLINE "token": tokenNEWLINE }
from django.conf import settingsNEWLINEfrom rest_framework.routers import DefaultRouter, SimpleRouterNEWLINEfrom django.urls import pathNEWLINEfrom scrape_imdb.movies.views import MovieSerializerView, scrape_moviesNEWLINENEWLINEfrom scrape_imdb.users.api.views import UserViewSetNEWLINENEWLINEif settings.DEBUG:NEWLINE router = DefaultRouter()NEWLINEelse:NEWLINE router = SimpleRouter()NEWLINENEWLINErouter.register("users", UserViewSet)NEWLINErouter.register("movies", MovieSerializerView)NEWLINENEWLINEapp_name = "api"NEWLINEurlpatterns = router.urlsNEWLINENEWLINEurlpatterns += [path("utils/scrape_movies", scrape_movies)]NEWLINE
from os import mkdirNEWLINEfrom os.path import existsNEWLINENEWLINEfrom .dist_tree import DistTreeNEWLINEfrom ...typehint import *NEWLINENEWLINENEWLINEdef main(conf: TConf):NEWLINE """ Create dist-side tree (all empty folders under `dst_root`) """NEWLINE _precheck(conf)NEWLINE NEWLINE # create main folders under dst_root.NEWLINE mkdir(conf['build']['dist_dir'])NEWLINE mkdir(conf['build']['dist_dir'] + '/' + 'build')NEWLINE mkdir(conf['build']['dist_dir'] + '/' + 'lib')NEWLINE mkdir(conf['build']['dist_dir'] + '/' + 'src')NEWLINE mkdir(conf['build']['dist_dir'] + '/' + 'src' + '/' + '.pylauncher_conf')NEWLINE NEWLINE dist_tree = DistTree()NEWLINE NEWLINE """NEWLINE Add to source dirs list:NEWLINE conf:NEWLINE build:NEWLINE + proj_dirNEWLINE + targetNEWLINE + attachmentsNEWLINENEWLINE Do not add to source dirs list:NEWLINE conf:NEWLINE build:NEWLINE - dist_dirNEWLINE - iconNEWLINE - readmeNEWLINE - module_pathsNEWLINE """NEWLINE dist_tree.add_src_dirs(NEWLINE conf['build']['proj_dir'],NEWLINE *(v['file'] for v in conf['build']['launchers'].values()),NEWLINE *(k for k, v in conf['build']['attachments'].items()NEWLINE if v['path'] == ''),NEWLINE )NEWLINE NEWLINE src_root = dist_tree.suggest_src_root()NEWLINE dst_root = conf['build']['dist_dir']NEWLINE print(f'the suggested source root directory is: {src_root}', ':v2')NEWLINE NEWLINE dist_tree.build_dst_dirs(src_root, f'{dst_root}/src')NEWLINE NEWLINE # init global path modelsNEWLINE _init_path_models(src_root, dst_root, conf)NEWLINE NEWLINE return src_root, dst_rootNEWLINENEWLINENEWLINEdef _precheck(conf: TConf):NEWLINE assert not exists(d := conf['build']['dist_dir']), (NEWLINE 'The target distribution directory ({}) already exists, please appoint 'NEWLINE 'another (non-existent) folder to distribute.'.format(d)NEWLINE )NEWLINE NEWLINE paths_not_exist = []NEWLINE for src_path in conf['build']['attachments']:NEWLINE if not exists(src_path):NEWLINE paths_not_exist.append(src_path)NEWLINE if paths_not_exist:NEWLINE print(':l', paths_not_exist)NEWLINE raise FileNotFoundError(NEWLINE 'Please make sure all required paths in `conf["build"]'NEWLINE '["attachments"]` are existed.'NEWLINE )NEWLINE NEWLINE # if conf['build']['venv']['enabled']:NEWLINE # from .embed_python import EmbedPythonManagerNEWLINE # builder = EmbedPythonManager(NEWLINE # pyversion=conf['build']['venv']['python_version']NEWLINE # )NEWLINE # # try to get a valid embed python path, if failed, this method willNEWLINE # # raise an exception to terminate process.NEWLINE # builder.get_embed_python_dir()NEWLINE #NEWLINE # mode = conf['build']['venv']['mode']NEWLINE # if mode == 'source_venv':NEWLINE # if venv_path := conf['build']['venv']['options'][mode]['path']:NEWLINE # if venv_path.startswith(src_path := conf['build']['proj_dir']):NEWLINE # lk.logt('[W2015]', f'''NEWLINE # Please do not put the Python virtual environment folderNEWLINE # in your source code folder! This will make the third-NEWLINE # party libraries to be encrypted, which usually leads toNEWLINE # unpredicatable errors.NEWLINE # You can put venv aside with the source code dir, thisNEWLINE # is the recommended parctice.NEWLINE #NEWLINE # Current venv dir: {venv_path}NEWLINE # Suggest moved to: {ospath.dirname(src_path)}/venvNEWLINE # ''')NEWLINE # if input('Continue the process? (y/n): ').lower() != 'y':NEWLINE # raise SystemExitNEWLINENEWLINENEWLINEdef _init_path_models(src_root, dst_root, conf: TConf):NEWLINE from ...path_model import dst_modelNEWLINE from ...path_model import src_modelNEWLINE from ...path_model import relpathNEWLINE NEWLINE src_model.init(NEWLINE src_root=src_root, prj_root=conf['build']['proj_dir'],NEWLINE readme=conf['build']['readme']NEWLINE )NEWLINE dst_model.init(NEWLINE dst_root=dst_root,NEWLINE prj_relroot=relpath(src_model.prj_root, src_model.src_root),NEWLINE launcher_name=conf['build']['launcher_name'],NEWLINE readme=conf['build']['readme']NEWLINE )NEWLINE
#-----------------------------------------------------------------------------NEWLINE# Copyright (c) 2005-2016, PyInstaller Development Team.NEWLINE#NEWLINE# Distributed under the terms of the GNU General Public License with exceptionNEWLINE# for distributing bootloader.NEWLINE#NEWLINE# The full license is in the file COPYING.txt, distributed with this software.NEWLINE#-----------------------------------------------------------------------------NEWLINENEWLINENEWLINE"""NEWLINEUtilities to create data structures for embedding Python modules and additionalNEWLINEfiles into the executable.NEWLINE"""NEWLINENEWLINE# While an Archive is really an abstraction for any "filesystemNEWLINE# within a file", it is tuned for use with imputil.FuncImporter.NEWLINE# This assumes it contains python code objects, indexed by theNEWLINE# the internal name (ie, no '.py').NEWLINE#NEWLINE# See pyi_carchive.py for a more general archive (contains anything)NEWLINE# that can be understood by a C program.NEWLINENEWLINEimport osNEWLINEimport sysNEWLINEimport structNEWLINEfrom types import CodeTypeNEWLINEimport marshalNEWLINEimport zlibNEWLINENEWLINEfrom PyInstaller.building.utils import get_code_object, strip_paths_in_codeNEWLINEfrom .readers import PYZ_TYPE_MODULE, PYZ_TYPE_PKG, PYZ_TYPE_DATANEWLINEfrom ..compat import BYTECODE_MAGIC, is_py2NEWLINENEWLINENEWLINEclass ArchiveWriter(object):NEWLINE """NEWLINE A base class for a repository of python code objects.NEWLINE The extract method is used by imputil.ArchiveImporterNEWLINE to get code objects by name (fully qualified name), soNEWLINE an enduser "import a.b" would becomeNEWLINE extract('a.__init__')NEWLINE extract('a.b')NEWLINE """NEWLINE MAGIC = b'PYL\0'NEWLINE HDRLEN = 12 # default is MAGIC followed by python's magic, int pos of tocNEWLINE TOCPOS = 8NEWLINENEWLINE def __init__(self, archive_path, logical_toc):NEWLINE """NEWLINE Create an archive file of name 'archive_path'.NEWLINE logical_toc is a 'logical TOC' - a list of (name, path, ...)NEWLINE where name is the internal name, eg 'a'NEWLINE and path is a file to get the object from, eg './a.pyc'.NEWLINE """NEWLINE self.start = 0NEWLINENEWLINE self._start_add_entries(archive_path)NEWLINE self._add_from_table_of_contents(logical_toc)NEWLINE self._finalize()NEWLINENEWLINE def _start_add_entries(self, archive_path):NEWLINE """NEWLINE Open an empty archive for addition of entries.NEWLINE """NEWLINE self.lib = open(archive_path, 'wb')NEWLINE # Reserve space for the header.NEWLINE if self.HDRLEN:NEWLINE self.lib.write(b'\0' * self.HDRLEN)NEWLINE # Create an empty table of contents.NEWLINE # Use a list to support reproducible buildsNEWLINE self.toc = []NEWLINENEWLINE def _add_from_table_of_contents(self, toc):NEWLINE """NEWLINE Add entries from a logical TOC (without absolute positioning info).NEWLINE An entry is an entry in a logical TOC is a tuple,NEWLINE entry[0] is name (under which it will be saved).NEWLINE entry[1] is fullpathname of the file.NEWLINE entry[2] is a flag for it's storage format (True or 1 if compressed)NEWLINE entry[3] is the entry's type code.NEWLINE """NEWLINE for toc_entry in toc:NEWLINE self.add(toc_entry) # The guts of the archive.NEWLINENEWLINE def _finalize(self):NEWLINE """NEWLINE Finalize an archive which has been opened using _start_add_entries(),NEWLINE writing any needed padding and the table of contents.NEWLINE """NEWLINE toc_pos = self.lib.tell()NEWLINE self.save_trailer(toc_pos)NEWLINE if self.HDRLEN:NEWLINE self.update_headers(toc_pos)NEWLINE self.lib.close()NEWLINENEWLINENEWLINE ####### manages keeping the internal TOC and the guts in sync #######NEWLINE def add(self, entry):NEWLINE """NEWLINE Override this to influence the mechanics of the Archive.NEWLINE Assumes entry is a seq beginning with (nm, pth, ...) whereNEWLINE nm is the key by which we'll be asked for the object.NEWLINE pth is the name of where we find the object. Overrides ofNEWLINE get_obj_from can make use of further elements in entry.NEWLINE """NEWLINE nm = entry[0]NEWLINE pth = entry[1]NEWLINE pynm, ext = os.path.splitext(os.path.basename(pth))NEWLINE ispkg = pynm == '__init__'NEWLINE assert ext in ('.pyc', '.pyo')NEWLINE self.toc.append((nm, (ispkg, self.lib.tell())))NEWLINE f = open(entry[1], 'rb')NEWLINE f.seek(8) # skip magic and timestampNEWLINE self.lib.write(f.read())NEWLINENEWLINE def save_trailer(self, tocpos):NEWLINE """NEWLINE Default - toc is a dictNEWLINE Gets marshaled to self.libNEWLINE """NEWLINE try:NEWLINE self.lib.write(marshal.dumps(self.toc))NEWLINE # If the TOC to be marshalled contains an unmarshallable object, PythonNEWLINE # raises a cryptic exception providing no details on why such object isNEWLINE # unmarshallable. Correct this by iteratively inspecting the TOC forNEWLINE # unmarshallable objects.NEWLINE except ValueError as exception:NEWLINE if str(exception) == 'unmarshallable object':NEWLINENEWLINE # List of all marshallable types.NEWLINE MARSHALLABLE_TYPES = set((NEWLINE bool, int, float, complex, str, bytes, bytearray,NEWLINE tuple, list, set, frozenset, dict, CodeType))NEWLINE if sys.version_info[0] == 2:NEWLINE MARSHALLABLE_TYPES.add(long)NEWLINENEWLINE for module_name, module_tuple in self.toc.items():NEWLINE if type(module_name) not in MARSHALLABLE_TYPES:NEWLINE print('Module name "%s" (%s) unmarshallable.' % (module_name, type(module_name)))NEWLINE if type(module_tuple) not in MARSHALLABLE_TYPES:NEWLINE print('Module "%s" tuple "%s" (%s) unmarshallable.' % (module_name, module_tuple, type(module_tuple)))NEWLINE elif type(module_tuple) == tuple:NEWLINE for i in range(len(module_tuple)):NEWLINE if type(module_tuple[i]) not in MARSHALLABLE_TYPES:NEWLINE print('Module "%s" tuple index %s item "%s" (%s) unmarshallable.' % (module_name, i, module_tuple[i], type(module_tuple[i])))NEWLINENEWLINE raiseNEWLINENEWLINE def update_headers(self, tocpos):NEWLINE """NEWLINE Default - MAGIC + Python's magic + tocposNEWLINE """NEWLINE self.lib.seek(self.start)NEWLINE self.lib.write(self.MAGIC)NEWLINE self.lib.write(BYTECODE_MAGIC)NEWLINE self.lib.write(struct.pack('!i', tocpos))NEWLINENEWLINENEWLINEclass ZlibArchiveWriter(ArchiveWriter):NEWLINE """NEWLINE ZlibArchive - an archive with compressed entries. Archive is readNEWLINE from the executable created by PyInstaller.NEWLINENEWLINE This archive is used for bundling python modules inside the executable.NEWLINENEWLINE NOTE: The whole ZlibArchive (PYZ) is compressed so it is not necessaryNEWLINE to compress single modules with zlib.NEWLINE """NEWLINE MAGIC = b'PYZ\0'NEWLINE TOCPOS = 8NEWLINE HDRLEN = ArchiveWriter.HDRLEN + 5NEWLINE COMPRESSION_LEVEL = 6 # Default level of the 'zlib' module from Python.NEWLINENEWLINE def __init__(self, archive_path, logical_toc, code_dict=None, cipher=None):NEWLINE """NEWLINE code_dict dict containing module code objects from ModuleGraph.NEWLINE """NEWLINE # Keep references to module code objects constructed by ModuleGraphNEWLINE # to avoid writting .pyc/pyo files to hdd.NEWLINE self.code_dict = code_dict or {}NEWLINE self.cipher = cipher or NoneNEWLINENEWLINE super(ZlibArchiveWriter, self).__init__(archive_path, logical_toc)NEWLINENEWLINENEWLINE def add(self, entry):NEWLINE name, path, typ = entryNEWLINE if typ == 'PYMODULE':NEWLINE typ = PYZ_TYPE_MODULENEWLINE if path in ('-', None):NEWLINE # This is a NamespacePackage, modulegraph marks themNEWLINE # by using the filename '-'. (But wants to use None,NEWLINE # so check for None, too, to be forward-compatible.)NEWLINE typ = PYZ_TYPE_PKGNEWLINE else:NEWLINE base, ext = os.path.splitext(os.path.basename(path))NEWLINE if base == '__init__':NEWLINE typ = PYZ_TYPE_PKGNEWLINE data = marshal.dumps(self.code_dict[name])NEWLINE else:NEWLINE # Any data files, that might be required by pkg_resources.NEWLINE typ = PYZ_TYPE_DATANEWLINE with open(path, 'rb') as fh:NEWLINE data = fh.read()NEWLINE # No need to use forward slash as path-separator here sinceNEWLINE # pkg_resources on Windows back slash as path-separator.NEWLINENEWLINE obj = zlib.compress(data, self.COMPRESSION_LEVEL)NEWLINENEWLINE # First compress then encrypt.NEWLINE if self.cipher:NEWLINE obj = self.cipher.encrypt(obj)NEWLINENEWLINE self.toc.append((name, (typ, self.lib.tell(), len(obj))))NEWLINE self.lib.write(obj)NEWLINENEWLINE def update_headers(self, tocpos):NEWLINE """NEWLINE add levelNEWLINE """NEWLINE ArchiveWriter.update_headers(self, tocpos)NEWLINE self.lib.write(struct.pack('!B', self.cipher is not None))NEWLINENEWLINENEWLINENEWLINEclass CTOC(object):NEWLINE """NEWLINE A class encapsulating the table of contents of a CArchive.NEWLINENEWLINE When written to disk, it is easily read from C.NEWLINE """NEWLINE ENTRYSTRUCT = '!iiiiBB' # (structlen, dpos, dlen, ulen, flag, typcd) followed by nameNEWLINE ENTRYLEN = struct.calcsize(ENTRYSTRUCT)NEWLINENEWLINE def __init__(self):NEWLINE self.data = []NEWLINENEWLINE def tobinary(self):NEWLINE """NEWLINE Return self as a binary string.NEWLINE """NEWLINE rslt = []NEWLINE for (dpos, dlen, ulen, flag, typcd, nm) in self.data:NEWLINE # Encode all names using UTF-8. This should be save asNEWLINE # standard python modules only contain ascii-charactersNEWLINE # (and standard shared libraries should have the same) andNEWLINE # thus the C-code still can handle this correctly.NEWLINE if is_py2 and isinstance(nm, str):NEWLINE nm = nm.decode(sys.getfilesystemencoding())NEWLINENEWLINE nm = nm.encode('utf-8')NEWLINE nmlen = len(nm) + 1 # add 1 for a '\0'NEWLINE # align to 16 byte boundary so xplatform C can readNEWLINE toclen = nmlen + self.ENTRYLENNEWLINE if toclen % 16 == 0:NEWLINE pad = b'\0'NEWLINE else:NEWLINE padlen = 16 - (toclen % 16)NEWLINE pad = b'\0' * padlenNEWLINE nmlen = nmlen + padlenNEWLINE rslt.append(struct.pack(self.ENTRYSTRUCT + '%is' % nmlen,NEWLINE nmlen + self.ENTRYLEN, dpos, dlen, ulen,NEWLINE flag, ord(typcd), nm + pad))NEWLINENEWLINE return b''.join(rslt)NEWLINENEWLINE def add(self, dpos, dlen, ulen, flag, typcd, nm):NEWLINE """NEWLINE Add an entry to the table of contents.NEWLINENEWLINE DPOS is data position.NEWLINE DLEN is data length.NEWLINE ULEN is the uncompressed data len.NEWLINE FLAG says if the data is compressed.NEWLINE TYPCD is the "type" of the entry (used by the C code)NEWLINE NM is the entry's name.NEWLINENEWLINE This function is used only while creating an executable.NEWLINE """NEWLINE # Ensure forward slashes in paths are on Windows converted to backNEWLINE # slashes '\\' since on Windows the bootloader works only with backNEWLINE # slashes.NEWLINE nm = os.path.normpath(nm)NEWLINE self.data.append((dpos, dlen, ulen, flag, typcd, nm))NEWLINENEWLINENEWLINEclass CArchiveWriter(ArchiveWriter):NEWLINE """NEWLINE An Archive subclass that can hold arbitrary data.NEWLINENEWLINE This class encapsulates all files that are bundled within an executable.NEWLINE It can contain ZlibArchive (Python .pyc files), dlls, Python C extensionsNEWLINE and all other data files that are bundled in --onefile mode.NEWLINENEWLINE Easily handled from C or from Python.NEWLINE """NEWLINE # MAGIC is usefull to verify that conversion of Python data typesNEWLINE # to C structure and back works properly.NEWLINE MAGIC = b'MEI\014\013\012\013\016'NEWLINE HDRLEN = 0NEWLINE LEVEL = 9NEWLINENEWLINE # Cookie - holds some information for the bootloader. C struct formatNEWLINE # definition. '!' at the beginning means network byte order.NEWLINE # C struct looks like:NEWLINE #NEWLINE # typedef struct _cookie {NEWLINE # char magic[8]; /* 'MEI\014\013\012\013\016' */NEWLINE # int len; /* len of entire package */NEWLINE # int TOC; /* pos (rel to start) of TableOfContents */NEWLINE # int TOClen; /* length of TableOfContents */NEWLINE # int pyvers; /* new in v4 */NEWLINE # char pylibname[64]; /* Filename of Python dynamic library. */NEWLINE # } COOKIE;NEWLINE #NEWLINE _cookie_format = '!8siiii64s'NEWLINE _cookie_size = struct.calcsize(_cookie_format)NEWLINENEWLINE def __init__(self, archive_path, logical_toc, pylib_name):NEWLINE """NEWLINE Constructor.NEWLINENEWLINE archive_path path name of file (create empty CArchive if path is None).NEWLINE start is the seekposition within PATH.NEWLINE len is the length of the CArchive (if 0, then read till EOF).NEWLINE pylib_name name of Python DLL which bootloader will use.NEWLINE """NEWLINE self._pylib_name = pylib_nameNEWLINENEWLINE # A CArchive created from scratch starts at 0, no leading bootloader.NEWLINE super(CArchiveWriter, self).__init__(archive_path, logical_toc)NEWLINENEWLINE def _start_add_entries(self, path):NEWLINE """NEWLINE Open an empty archive for addition of entries.NEWLINE """NEWLINE super(CArchiveWriter, self)._start_add_entries(path)NEWLINE # Override parents' toc {} with a class.NEWLINE self.toc = CTOC()NEWLINENEWLINE def add(self, entry):NEWLINE """NEWLINE Add an ENTRY to the CArchive.NEWLINENEWLINE ENTRY must have:NEWLINE entry[0] is name (under which it will be saved).NEWLINE entry[1] is fullpathname of the file.NEWLINE entry[2] is a flag for it's storage format (0==uncompressed,NEWLINE 1==compressed)NEWLINE entry[3] is the entry's type code.NEWLINE Version 5:NEWLINE If the type code is 'o':NEWLINE entry[0] is the runtime optionNEWLINE eg: v (meaning verbose imports)NEWLINE u (menaing unbuffered)NEWLINE W arg (warning option arg)NEWLINE s (meaning do site.py processing.NEWLINE """NEWLINE (nm, pathnm, flag, typcd) = entry[:4]NEWLINE # FIXME Could we make the version 5 the default one?NEWLINE # Version 5 - allow type 'o' = runtime option.NEWLINE code_data = NoneNEWLINE fh = NoneNEWLINE try:NEWLINE if typcd in ('o', 'd'):NEWLINE ulen = 0NEWLINE flag = 0NEWLINE elif typcd == 's':NEWLINE # If it's a source code file, compile it to a code object and marshallNEWLINE # the object so it can be unmarshalled by the bootloader.NEWLINENEWLINE code = get_code_object(nm, pathnm)NEWLINE code = strip_paths_in_code(code)NEWLINENEWLINE code_data = marshal.dumps(code)NEWLINE ulen = len(code_data)NEWLINE else:NEWLINE fh = open(pathnm, 'rb')NEWLINE ulen = os.fstat(fh.fileno()).st_sizeNEWLINE except IOError:NEWLINE print("Cannot find ('%s', '%s', %s, '%s')" % (nm, pathnm, flag, typcd))NEWLINE raiseNEWLINENEWLINE where = self.lib.tell()NEWLINE assert flag in range(3)NEWLINE if not fh and not code_data:NEWLINE # no need to write anythingNEWLINE passNEWLINE elif flag == 1:NEWLINE comprobj = zlib.compressobj(self.LEVEL)NEWLINE if code_data is not None:NEWLINE self.lib.write(comprobj.compress(code_data))NEWLINE else:NEWLINE assert fhNEWLINE while 1:NEWLINE buf = fh.read(16*1024)NEWLINE if not buf:NEWLINE breakNEWLINE self.lib.write(comprobj.compress(buf))NEWLINE self.lib.write(comprobj.flush())NEWLINENEWLINE else:NEWLINE if code_data is not None:NEWLINE self.lib.write(code_data)NEWLINE else:NEWLINE assert fhNEWLINE while 1:NEWLINE buf = fh.read(16*1024)NEWLINE if not buf:NEWLINE breakNEWLINE self.lib.write(buf)NEWLINENEWLINE dlen = self.lib.tell() - whereNEWLINE if typcd == 'm':NEWLINE if pathnm.find('.__init__.py') > -1:NEWLINE typcd = 'M'NEWLINENEWLINE # Record the entry in the CTOCNEWLINE self.toc.add(where, dlen, ulen, flag, typcd, nm)NEWLINENEWLINENEWLINE def save_trailer(self, tocpos):NEWLINE """NEWLINE Save the table of contents and the cookie for the bootlader toNEWLINE disk.NEWLINENEWLINE CArchives can be opened from the end - the cookie pointsNEWLINE back to the start.NEWLINE """NEWLINE tocstr = self.toc.tobinary()NEWLINE self.lib.write(tocstr)NEWLINE toclen = len(tocstr)NEWLINENEWLINE # now save teh cookieNEWLINE total_len = tocpos + toclen + self._cookie_sizeNEWLINE pyvers = sys.version_info[0] * 10 + sys.version_info[1]NEWLINE # Before saving cookie we need to convert it to correspondingNEWLINE # C representation.NEWLINE cookie = struct.pack(self._cookie_format, self.MAGIC, total_len,NEWLINE tocpos, toclen, pyvers,NEWLINE self._pylib_name.encode('ascii'))NEWLINE self.lib.write(cookie)NEWLINE
#!/Users/administrator/dev/njode/env/bin/python2.7NEWLINE#NEWLINE# The Python Imaging Library.NEWLINE# $Id$NEWLINE#NEWLINE# print image files to postscript printerNEWLINE#NEWLINE# History:NEWLINE# 0.1 1996-04-20 fl CreatedNEWLINE# 0.2 1996-10-04 fl Use draft mode when converting.NEWLINE# 0.3 2003-05-06 fl Fixed a typo or two.NEWLINE#NEWLINENEWLINEfrom __future__ import print_functionNEWLINENEWLINEVERSION = "pilprint 0.3/2003-05-05"NEWLINENEWLINEfrom PIL import ImageNEWLINEfrom PIL import PSDrawNEWLINENEWLINEletter = ( 1.0*72, 1.0*72, 7.5*72, 10.0*72 )NEWLINENEWLINEdef description(file, image):NEWLINE import osNEWLINE title = os.path.splitext(os.path.split(file)[1])[0]NEWLINE format = " (%dx%d "NEWLINE if image.format:NEWLINE format = " (" + image.format + " %dx%d "NEWLINE return title + format % image.size + image.mode + ")"NEWLINENEWLINEimport getopt, os, sysNEWLINENEWLINEif len(sys.argv) == 1:NEWLINE print("PIL Print 0.2a1/96-10-04 -- print image files")NEWLINE print("Usage: pilprint files...")NEWLINE print("Options:")NEWLINE print(" -c colour printer (default is monochrome)")NEWLINE print(" -p print via lpr (default is stdout)")NEWLINE print(" -P <printer> same as -p but use given printer")NEWLINE sys.exit(1)NEWLINENEWLINEtry:NEWLINE opt, argv = getopt.getopt(sys.argv[1:], "cdpP:")NEWLINEexcept getopt.error as v:NEWLINE print(v)NEWLINE sys.exit(1)NEWLINENEWLINEprinter = None # print to stdoutNEWLINEmonochrome = 1 # reduce file size for most common caseNEWLINENEWLINEfor o, a in opt:NEWLINE if o == "-d":NEWLINE # debug: show available driversNEWLINE Image.init()NEWLINE print(Image.ID)NEWLINE sys.exit(1)NEWLINE elif o == "-c":NEWLINE # colour printerNEWLINE monochrome = 0NEWLINE elif o == "-p":NEWLINE # default printer channelNEWLINE printer = "lpr"NEWLINE elif o == "-P":NEWLINE # printer channelNEWLINE printer = "lpr -P%s" % aNEWLINENEWLINEfor file in argv:NEWLINE try:NEWLINENEWLINE im = Image.open(file)NEWLINENEWLINE title = description(file, im)NEWLINENEWLINE if monochrome and im.mode not in ["1", "L"]:NEWLINE im.draft("L", im.size)NEWLINE im = im.convert("L")NEWLINENEWLINE if printer:NEWLINE fp = os.popen(printer, "w")NEWLINE else:NEWLINE fp = sys.stdoutNEWLINENEWLINE ps = PSDraw.PSDraw(fp)NEWLINENEWLINE ps.begin_document()NEWLINE ps.setfont("Helvetica-Narrow-Bold", 18)NEWLINE ps.text((letter[0], letter[3]+24), title)NEWLINE ps.setfont("Helvetica-Narrow-Bold", 8)NEWLINE ps.text((letter[0], letter[1]-30), VERSION)NEWLINE ps.image(letter, im)NEWLINE ps.end_document()NEWLINENEWLINE except:NEWLINE print("cannot print image", end=' ')NEWLINE print("(%s:%s)" % (sys.exc_info()[0], sys.exc_info()[1]))NEWLINE
import osNEWLINEimport win32security,win32file,win32api,ntsecuritycon,win32conNEWLINEfrom security_enums import TRUSTEE_TYPE,TRUSTEE_FORM,ACE_FLAGS,ACCESS_MODENEWLINENEWLINEfname = os.path.join(win32api.GetTempPath(), "win32security_test.txt")NEWLINEf=open(fname, "w")NEWLINEf.write("Hello from Python\n");NEWLINEf.close()NEWLINEprint "Testing on file", fnameNEWLINENEWLINEnew_privs = ((win32security.LookupPrivilegeValue('',ntsecuritycon.SE_SECURITY_NAME),win32con.SE_PRIVILEGE_ENABLED),NEWLINE (win32security.LookupPrivilegeValue('',ntsecuritycon.SE_SHUTDOWN_NAME),win32con.SE_PRIVILEGE_ENABLED),NEWLINE (win32security.LookupPrivilegeValue('',ntsecuritycon.SE_RESTORE_NAME),win32con.SE_PRIVILEGE_ENABLED),NEWLINE (win32security.LookupPrivilegeValue('',ntsecuritycon.SE_TAKE_OWNERSHIP_NAME),win32con.SE_PRIVILEGE_ENABLED),NEWLINE (win32security.LookupPrivilegeValue('',ntsecuritycon.SE_CREATE_PERMANENT_NAME),win32con.SE_PRIVILEGE_ENABLED),NEWLINE (win32security.LookupPrivilegeValue('','SeEnableDelegationPrivilege'),win32con.SE_PRIVILEGE_ENABLED) ##doesn't seem to be in ntsecuritycon.py ?NEWLINE )NEWLINENEWLINEph = win32api.GetCurrentProcess()NEWLINEth = win32security.OpenProcessToken(ph,win32security.TOKEN_ALL_ACCESS) ##win32con.TOKEN_ADJUST_PRIVILEGES)NEWLINEwin32security.AdjustTokenPrivileges(th,0,new_privs)NEWLINENEWLINEall_security_info = \NEWLINE win32security.OWNER_SECURITY_INFORMATION|win32security.GROUP_SECURITY_INFORMATION| \NEWLINE win32security.DACL_SECURITY_INFORMATION|win32security.SACL_SECURITY_INFORMATIONNEWLINENEWLINEsd=win32security.GetFileSecurity(fname,all_security_info)NEWLINENEWLINEold_sacl=sd.GetSecurityDescriptorSacl()NEWLINEif old_sacl==None:NEWLINE old_sacl=win32security.ACL()NEWLINEold_dacl=sd.GetSecurityDescriptorDacl()NEWLINEif old_dacl==None:NEWLINE old_dacl=win32security.ACL()NEWLINENEWLINEmy_sid = win32security.GetTokenInformation(th,ntsecuritycon.TokenUser)[0]NEWLINEtmp_sid = win32security.LookupAccountName('','tmp')[0]NEWLINEpwr_sid = win32security.LookupAccountName('','Power Users')[0]NEWLINENEWLINENEWLINE## MultipleTrustee,MultipleTrusteeOperation,TrusteeForm,TrusteeType,IdentifierNEWLINE## first two are ignoredNEWLINEmy_trustee = {}NEWLINEmy_trustee['MultipleTrustee']=NoneNEWLINEmy_trustee['MultipleTrusteeOperation']=0NEWLINEmy_trustee['TrusteeForm']=TRUSTEE_FORM.TRUSTEE_IS_SIDNEWLINEmy_trustee['TrusteeType']=TRUSTEE_TYPE.TRUSTEE_IS_USERNEWLINEmy_trustee['Identifier']=my_sidNEWLINENEWLINEtmp_trustee = {}NEWLINEtmp_trustee['MultipleTrustee']=NoneNEWLINEtmp_trustee['MultipleTrusteeOperation']=0NEWLINEtmp_trustee['TrusteeForm']=TRUSTEE_FORM.TRUSTEE_IS_NAMENEWLINEtmp_trustee['TrusteeType']=TRUSTEE_TYPE.TRUSTEE_IS_USERNEWLINEtmp_trustee['Identifier']='rupole\\tmp'NEWLINENEWLINEpwr_trustee = {}NEWLINEpwr_trustee['MultipleTrustee']=NoneNEWLINEpwr_trustee['MultipleTrusteeOperation']=0NEWLINEpwr_trustee['TrusteeForm']=TRUSTEE_FORM.TRUSTEE_IS_SIDNEWLINEpwr_trustee['TrusteeType']=TRUSTEE_TYPE.TRUSTEE_IS_USERNEWLINEpwr_trustee['Identifier']=pwr_sidNEWLINENEWLINEexpl_list=[]NEWLINEexpl_list.append(NEWLINE {NEWLINE 'Trustee':my_trustee,NEWLINE 'Inheritance':ACE_FLAGS.NO_INHERITANCE,NEWLINE 'AccessMode':ACCESS_MODE.SET_AUDIT_SUCCESS, ##|ACCESS_MODE.SET_AUDIT_FAILURE,NEWLINE 'AccessPermissions':win32con.GENERIC_ALLNEWLINE }NEWLINE )NEWLINENEWLINEexpl_list.append(NEWLINE {NEWLINE 'Trustee':my_trustee,NEWLINE 'Inheritance':ACE_FLAGS.NO_INHERITANCE,NEWLINE 'AccessMode':ACCESS_MODE.SET_AUDIT_FAILURE,NEWLINE 'AccessPermissions':win32con.GENERIC_ALLNEWLINE }NEWLINE )NEWLINENEWLINEexpl_list.append(NEWLINE {NEWLINE 'Trustee':tmp_trustee,NEWLINE 'Inheritance':ACE_FLAGS.NO_INHERITANCE,NEWLINE 'AccessMode':ACCESS_MODE.SET_AUDIT_SUCCESS,NEWLINE 'AccessPermissions':win32con.GENERIC_ALLNEWLINE }NEWLINE )NEWLINENEWLINEexpl_list.append(NEWLINE {NEWLINE 'Trustee':tmp_trustee,NEWLINE 'Inheritance':ACE_FLAGS.NO_INHERITANCE,NEWLINE 'AccessMode':ACCESS_MODE.SET_AUDIT_FAILURE,NEWLINE 'AccessPermissions':win32con.GENERIC_ALLNEWLINE }NEWLINE )NEWLINEold_sacl.SetEntriesInAcl(expl_list)NEWLINENEWLINEexpl_list=[]NEWLINEexpl_list.append(NEWLINE {NEWLINE 'Trustee':tmp_trustee,NEWLINE 'Inheritance':ACE_FLAGS.NO_INHERITANCE,NEWLINE 'AccessMode':ACCESS_MODE.DENY_ACCESS,NEWLINE 'AccessPermissions':win32con.DELETENEWLINE }NEWLINE )NEWLINENEWLINEexpl_list.append(NEWLINE {NEWLINE 'Trustee':tmp_trustee,NEWLINE 'Inheritance':ACE_FLAGS.NO_INHERITANCE,NEWLINE 'AccessMode':ACCESS_MODE.GRANT_ACCESS,NEWLINE 'AccessPermissions':win32con.WRITE_OWNERNEWLINE }NEWLINE )NEWLINEexpl_list.append(NEWLINE {NEWLINE 'Trustee':pwr_trustee,NEWLINE 'Inheritance':ACE_FLAGS.NO_INHERITANCE,NEWLINE 'AccessMode':ACCESS_MODE.GRANT_ACCESS,NEWLINE 'AccessPermissions':win32con.GENERIC_READNEWLINE }NEWLINE )NEWLINEexpl_list.append(NEWLINE {NEWLINE 'Trustee':my_trustee,NEWLINE 'Inheritance':ACE_FLAGS.NO_INHERITANCE,NEWLINE 'AccessMode':ACCESS_MODE.GRANT_ACCESS,NEWLINE 'AccessPermissions':win32con.GENERIC_ALLNEWLINE }NEWLINE )NEWLINENEWLINEold_dacl.SetEntriesInAcl(expl_list)NEWLINEsd.SetSecurityDescriptorSacl(1,old_sacl,1)NEWLINEsd.SetSecurityDescriptorDacl(1,old_dacl,1)NEWLINEsd.SetSecurityDescriptorOwner(pwr_sid,1)NEWLINENEWLINEwin32security.SetFileSecurity(fname,NEWLINE all_security_info,NEWLINE sd)NEWLINE
#!/usr/bin/env python3NEWLINE# ------------------------------------------------------------------------NEWLINE# Copyright (c) 2021 megvii-model. All Rights Reserved.NEWLINE# ------------------------------------------------------------------------NEWLINEfrom .database import *NEWLINEimport random, pdbNEWLINEimport numpy as npNEWLINEimport matplotlib.pyplot as pltNEWLINEclass DisplayInfo(object):NEWLINE """NEWLINE :class: bbox and image information for displayNEWLINE :ivar dtbox: the current detection resultNEWLINE :ivar tag: the tag of current detection result, e.g., "Fp", "Miss"NEWLINE :ivar imgID: the current imageIDNEWLINE :ivar pos: the rank position of current detection result NEWLINE :ivar n: the total number of all detection resultsNEWLINE :type dtbox: DetBoxNEWLINE :type tag: strNEWLINE :type imgID: strNEWLINE :type pos: intNEWLINE :type n: intNEWLINE """NEWLINE def __init__(self, imgID, tag=None, dtbox=None, pos=None, n=None):NEWLINE self.imgID = imgIDNEWLINE self.dtbox = dtboxNEWLINE self.tag = tagNEWLINE self.pos = posNEWLINE self.n = nNEWLINENEWLINE def sprint(self):NEWLINE """NEWLINE :meth: convert into stringNEWLINE """NEWLINE tagStr = "None" if self.tag is None else self.tagNEWLINE dtboxStr = "[None]" if self.dtbox is None else \NEWLINE "[{}, {}, {}, {}, {}]".format(int(self.dtbox.x), int(self.dtbox.y), \NEWLINE int(self.dtbox.w), int(self.dtbox.h), \NEWLINE self.dtbox.score)NEWLINENEWLINE if self.pos is not None and self.n is not None:NEWLINE rankStr = "{}/{}".format(self.pos, self.n)NEWLINE elif self.pos is not None:NEWLINE rankStr = "{}/None".format(self.pos)NEWLINE else:NEWLINE rankStr = "None/None"NEWLINE return tagStr + ", " + rankStr + ", " + dtboxStr + ", " + self.imgID NEWLINENEWLINENEWLINEclass Evaluator(object):NEWLINE """NEWLINE :class: evaluator for multiple algorithmsNEWLINE :ivar DBs: the detection results as well as groundtruth (stored in EvalDB) of all algorithms, using EvalDB.dbName as the keyNEWLINE :ivar splitDBs: the splitted databases for self.DBs, using EvalDB.dbName as the keyNEWLINE :ivar n: the number of EvalDBsNEWLINE :ivar colors: the colors for drawing curvesNEWLINE :ivar results: the evaluation results of all EvalDBs, using EvalDB.dbName as the keyNEWLINE :type DBs: dictNEWLINE :type splitDBs: dictNEWLINE :type n: intNEWLINE :type colors: listNEWLINE :type results: dictNEWLINE """NEWLINE def __init__(self, databases):NEWLINE self.DBs = dict()NEWLINENEWLINE if type(databases) == EvalDB:NEWLINE self.DBs[databases.dbName] = databasesNEWLINE else:NEWLINE for db in databases:NEWLINE self.DBs[db.dbName] = dbNEWLINENEWLINE self.n = len(self.DBs)NEWLINE self.colors = [(max(0.3,78*(i+1)%255/255.0), max(0.3,121*(i+1)%255/255.0),\NEWLINE max(0.3,42*(i+1)%255/255.0)) for i in range(self.n)]NEWLINE self.results = NoneNEWLINE self.splitDBs = NoneNEWLINENEWLINE def _splitClass(self):NEWLINE if self.splitDBs is None:NEWLINE self.splitDBs = dict()NEWLINE for dbName in self.DBs:NEWLINE self.splitDBs[dbName] = self.DBs[dbName].splitClass()NEWLINENEWLINE def eval_MR(self, iouThres=0.5, matching=None, ref="CALTECH_-2", splitClass=False):NEWLINE """NEWLINE :meth: match the detection results with the groundtruth by iou measure for all algorithms, and draw fppi-miss and recall-precision curves NEWLINE :param iouThres: iou threshold, default 0.5NEWLINE :param matching: match strategy, default None (Caltech matching strategy)NEWLINE :param ref: anchor points for calculating log-average miss rate, default "CALTECH_-2"NEWLINE :param splitClass: split database by class and evaluate each independently, default FalseNEWLINE :type iouThres: floatNEWLINE :type matching: str - None/"VOC"NEWLINE :type ref: str - "CALTECH_-2"/"CALTECH_-4"NEWLINE :type splitClass: boolNEWLINE """NEWLINE self.results = dict()NEWLINE NEWLINE mMRv = []NEWLINE if splitClass is False: # evaluate over allNEWLINE for dbName in self.DBs:NEWLINE self.DBs[dbName].compare(iouThres, matching)NEWLINE self.results[dbName] = self.DBs[dbName].eval_MR(ref)NEWLINENEWLINE mMRv.append(self.results[dbName][0])NEWLINENEWLINE # plot curvesNEWLINE # plt.figure("fppi-missrate result") NEWLINE # plotlines = list()NEWLINE # legends = list()NEWLINE # for i, dbName in enumerate(self.results):NEWLINE # fppi, missrate = self.results[dbName][1]NEWLINE # plotline, = plt.semilogx(fppi, missrate, color=self.colors[i])NEWLINE # plotlines.append(plotline)NEWLINE # legends.append("{} {:.3f}".format(dbName, self.results[dbName][0]))NEWLINE # plt.legend(plotlines, legends)NEWLINE # plt.xlabel("false positive per image")NEWLINE # plt.ylabel("miss rate")NEWLINE # plt.show()NEWLINE else: # evaluate over each classNEWLINE self._splitClass()NEWLINE for dbName in self.splitDBs:NEWLINE mMR = 0.0NEWLINE MRs = dict()NEWLINE nCls = 0NEWLINE for cls in self.splitDBs[dbName]:NEWLINE if cls <= 0:NEWLINE continueNEWLINE tmpDB = self.splitDBs[dbName][cls]NEWLINE tag = tmpDB.mapClass2Tag(cls)NEWLINE tmpDB.compare(iouThres, matching)NEWLINE MR, curve = tmpDB.eval_MR(ref)NEWLINE mMR += MRNEWLINE MRs[tag] = MRNEWLINE nCls += 1NEWLINE self.results[dbName] = [mMR/nCls, MRs]NEWLINE mMRv.append(self.results[dbName][0])NEWLINE # print(dbName, "mMR = {}".format(self.results[dbName][0]))NEWLINE # print(self.results[dbName][1])NEWLINE return mMRvNEWLINENEWLINE def eval_AP_detail(self, iouThres=0.5, matching=None, metric=None, splitClass=False, csvname=None):NEWLINE """NEWLINE :meth: match the detection results with the groundtruth by iou measure for all algorithms, and draw fppi-miss and recall-precision curves NEWLINE :param iouThres: iou threshold, default 0.5NEWLINE :param matching: match strategy, default None (Caltech matching strategy)NEWLINE :param metric: metric for calculating AP, default None (general AP calculation)NEWLINE :param splitClass: split database by class and evaluate each independently, default FalseNEWLINE :type iouThres: floatNEWLINE :type matching: str - None/"VOC"NEWLINE :type metric: str - None/"VOC"NEWLINE :type splitClass: boolNEWLINE """NEWLINE NEWLINE self.results = dict()NEWLINE if splitClass is False: # evaluate over allNEWLINE for dbName in self.DBs:NEWLINE self.DBs[dbName].compare(iouThres, matching)NEWLINE self.results[dbName] = self.DBs[dbName].eval_AP_detail(metric)NEWLINE print(dbName, "mAP = {}".format(self.results[dbName][0]))NEWLINENEWLINE curve = self.results[dbName][1]NEWLINE total_dets = len(self.results[dbName][1][0])NEWLINE total_gts = self.DBs[dbName].getGtNum() - self.DBs[dbName].getIgnNum() NEWLINE print("FP: {}/{}, recall: {}/{}:{}, images: {}\n".format((1-curve[1][-1])*total_dets, total_dets, \NEWLINE curve[0][-1]*total_gts, total_gts, curve[0][-1], len(self.DBs[dbName].images)))NEWLINE NEWLINE def dump_curve_csv(curve, filename=None):NEWLINE if filename == None:NEWLINE fres = open( 'res.csv', 'w')NEWLINE else:NEWLINE fres = open(filename, 'w')NEWLINE fres.write('threshold, fp, recall, fppi, recallrate, precision\n')NEWLINE for r, p, thr, fpn, recalln, fppi in zip(*curve):NEWLINE fres.write( '{},{},{},{},{},{}\n'.format(thr, fpn, recalln, fppi, r, p))NEWLINE fres.close()NEWLINE return all_mAPNEWLINENEWLINENEWLINE def eval_AP(self, iouThres=0.5, matching=None, metric=None, splitClass=False, noshow=True):NEWLINE """NEWLINE :meth: match the detection results with the groundtruth by iou measure for all algorithms, and draw fppi-miss and recall-precision curves NEWLINE :param iouThres: iou threshold, default 0.5NEWLINE :param matching: match strategy, default None (Caltech matching strategy)NEWLINE :param metric: metric for calculating AP, default None (general AP calculation)NEWLINE :param splitClass: split database by class and evaluate each independently, default FalseNEWLINE :type iouThres: floatNEWLINE :type matching: str - None/"VOC"NEWLINE :type metric: str - None/"VOC"NEWLINE :type splitClass: boolNEWLINE """NEWLINE self.results = dict()NEWLINE all_mAP = []NEWLINE if splitClass is False: # evaluate over allNEWLINE for dbName in self.DBs:NEWLINENEWLINE self.DBs[dbName].compare(iouThres, matching)NEWLINE self.results[dbName] = self.DBs[dbName].eval_AP_detail(metric)NEWLINENEWLINE all_mAP.append(self.results[dbName][0])NEWLINE curve = self.results[dbName][1]NEWLINE total_dets = len(self.results[dbName][1][0])NEWLINE total_gts = self.DBs[dbName].getGtNum() - self.DBs[dbName].getIgnNum() NEWLINENEWLINENEWLINE # if not noshow:NEWLINE # # plot curvesNEWLINE # plt.figure("recall-precision result") NEWLINE # plotlines = list()NEWLINE # legends = list()NEWLINE # for i, dbName in enumerate(self.results):NEWLINE # #recall, precision = self.results[dbName][1]NEWLINE # recall = self.results[dbName][1][0]NEWLINE # precision = self.results[dbName][1][1]NEWLINE # plotline, = plt.plot(recall, precision, color=self.colors[i])NEWLINE # plotlines.append(plotline)NEWLINE # legends.append("{} {:.3f}".format(dbName, self.results[dbName][0]))NEWLINE # plt.legend(plotlines, legends, loc="lower left")NEWLINE # plt.xlabel("recall")NEWLINE # plt.ylabel("precision")NEWLINE # #plt.show()NEWLINE # else:NEWLINE return all_mAP,(int((1-curve[1][-1])*total_dets), total_dets, \NEWLINE curve[0][-1]*total_gts, total_gts, curve[0][-1], len(self.DBs[dbName].images))NEWLINE NEWLINE else: # evaluate over each classNEWLINE self._splitClass()NEWLINE for dbName in self.splitDBs:NEWLINE mAP = 0.0NEWLINE APs = dict()NEWLINE nCls = 0NEWLINE for cls in self.splitDBs[dbName]:NEWLINE if cls <= 0:NEWLINE continueNEWLINE tmpDB = self.splitDBs[dbName][cls]NEWLINE tag = tmpDB.mapClass2Tag(cls)NEWLINE tmpDB.compare(iouThres, matching)NEWLINE AP, curve = tmpDB.eval_AP(metric)NEWLINE mAP += APNEWLINE APs[tag] = APNEWLINE nCls += 1NEWLINE self.results[dbName] = [mAP/nCls, APs]NEWLINE print(dbName, "mAP = {}".format(self.results[dbName][0]))NEWLINE print(self.results[dbName][1])NEWLINE def eval_AP_condition(self, iouThres=0.5,score_thresh=0.1, matching=None, NEWLINE metric=None, splitClass=False, noshow=True):NEWLINE """NEWLINE :meth: match the detection results with the groundtruth by iou measure for all algorithms, and draw fppi-miss and recall-precision curves NEWLINE :param iouThres: iou threshold, default 0.5NEWLINE :param matching: match strategy, default None (Caltech matching strategy)NEWLINE :param metric: metric for calculating AP, default None (general AP calculation)NEWLINE :param splitClass: split database by class and evaluate each independently, default FalseNEWLINE :type iouThres: floatNEWLINE :type matching: str - None/"VOC"NEWLINE :type metric: str - None/"VOC"NEWLINE :type splitClass: boolNEWLINE """NEWLINE self.results = dict()NEWLINE all_mAP = []NEWLINE if splitClass is False: # evaluate over allNEWLINE for dbName in self.DBs:NEWLINE self.DBs[dbName].compare(iouThres, matching)NEWLINE self.DBs[dbName].filter(score_thresh)NEWLINE self.results[dbName] = self.DBs[dbName].eval_AP_detail(metric)NEWLINE NEWLINE all_mAP.append(self.results[dbName][0])NEWLINE curve = self.results[dbName][1]NEWLINE total_dets = len(self.results[dbName][1][0])NEWLINE total_gts = self.DBs[dbName].getGtNum() - self.DBs[dbName].getIgnNum() NEWLINE # print("FP: {}/{}, recall: {}/{}:{}, images: {}\n".format((1-curve[1][-1])*total_dets, total_dets, \NEWLINE # curve[0][-1]*total_gts, total_gts, curve[0][-1], len(self.DBs[dbName].images)))NEWLINE NEWLINE # if not noshow:NEWLINE # # plot curvesNEWLINE # plt.figure("recall-precision result") NEWLINE # plotlines = list()NEWLINE # legends = list()NEWLINE # for i, dbName in enumerate(self.results):NEWLINE # #recall, precision = self.results[dbName][1]NEWLINE # recall = self.results[dbName][1][0]NEWLINE # precision = self.results[dbName][1][1]NEWLINE # plotline, = plt.plot(recall, precision, color=self.colors[i])NEWLINE # plotlines.append(plotline)NEWLINE # legends.append("{} {:.3f}".format(dbName, self.results[dbName][0]))NEWLINE # plt.legend(plotlines, legends, loc="lower left")NEWLINE # plt.xlabel("recall")NEWLINE # plt.ylabel("precision")NEWLINE # #plt.show()NEWLINE # else:NEWLINE # return all_mAP,(int((1-curve[1][-1])*total_dets), total_dets, \NEWLINE # curve[0][-1]*total_gts, total_gts, curve[0][-1], len(self.DBs[dbName].images))NEWLINE NEWLINE else: # evaluate over each classNEWLINE self._splitClass()NEWLINE for dbName in self.splitDBs:NEWLINE mAP = 0.0NEWLINE APs = dict()NEWLINE nCls = 0NEWLINE for cls in self.splitDBs[dbName]:NEWLINE if cls <= 0:NEWLINE continueNEWLINE tmpDB = self.splitDBs[dbName][cls]NEWLINE tag = tmpDB.mapClass2Tag(cls)NEWLINE tmpDB.compare(iouThres, matching)NEWLINE AP, curve = tmpDB.eval_AP(metric)NEWLINE mAP += APNEWLINE APs[tag] = APNEWLINE nCls += 1NEWLINE self.results[dbName] = [mAP/nCls, APs]NEWLINE print(dbName, "mAP = {}".format(self.results[dbName][0]))NEWLINE print(self.results[dbName][1])NEWLINE def getShowlist(self, dbName, clsID=None, option="all"):NEWLINE """NEWLINE :meth: get showlist from the evaluation resultsNEWLINE :param dbName: assigned database name NEWLINE :param option: option to select showlist from all resultsNEWLINE :type dbName: strNEWLINE :type option: str - "all"/"fp"/"miss"/"watchlist"NEWLINE """NEWLINE assert dbName in self.DBs, "{} does not exist in self.DBs".format(dbName)NEWLINE if clsID is None:NEWLINE assert self.DBs[dbName].scorelist is not NoneNEWLINE else:NEWLINE assert self.splitDBs is not None and dbName in self.splitDBsNEWLINE assert self.splitDBs[dbName][clsID].scorelist is not NoneNEWLINE NEWLINE scorelist = self.DBs[dbName].scorelist if clsID is None else \NEWLINE self.splitDBs[dbName][clsID].scorelistNEWLINE nrBox = len(scorelist)NEWLINENEWLINE showlist = list()NEWLINE if option == "miss":NEWLINE missSet = list()NEWLINE for i, (dtbox, imageID) in enumerate(scorelist):NEWLINE if imageID in missSet: NEWLINE continueNEWLINE miss_num = 0NEWLINE for gtbox in self.DBs[dbName].images[imageID].gtboxes:NEWLINE if gtbox.matched == 0 and gtbox.ign == 0:NEWLINE miss_num += 1NEWLINE breakNEWLINE if miss_num != 0:NEWLINE missSet.append(imageID)NEWLINE info = DisplayInfo(imageID, "Miss", None, i, nrBox)NEWLINE showlist.append(info)NEWLINE elif option == "fp":NEWLINE for i, (dtbox, imageID) in enumerate(scorelist):NEWLINE if dtbox.matched == 0: # false positive onlyNEWLINE info = DisplayInfo(imageID, "Fp", dtbox, i, nrBox)NEWLINE showlist.append(info)NEWLINE elif option == "all":NEWLINE for i, (dtbox, imageID) in enumerate(scorelist):NEWLINE info = DisplayInfo(imageID, "Tp" if dtbox.matched else "Fp", dtbox, i, nrBox)NEWLINE showlist.append(info)NEWLINE else:NEWLINE with open(option, "r") as f:NEWLINE watchlist = f.readlines()NEWLINE for watchterm in watchlist:NEWLINE ID, score = watchterm.strip().split()NEWLINE for i, (dtbox, imageID) in enumerate(scorelist):NEWLINE if imageID == ID and abs(dtbox.score - float(score)) < 0.1:NEWLINE info = DisplayInfo(imageID, "Tp" if dtbox.matched else "Fp", dtbox, i, nrBox)NEWLINE showlist.append(info)NEWLINE breakNEWLINE return showlistNEWLINENEWLINENEWLINEclass Displayer(object):NEWLINE """NEWLINE :class: displayer to show imagesNEWLINE :ivar DBs: the detection results as well as groundtruth (stored in DBBase/TrainDB/EvalDB) of all algorithms, using DB.dbName as the keyNEWLINE :ivar n: the number of databasesNEWLINE :type DBs: dictNEWLINE :type n: intNEWLINE """NEWLINE def __init__(self, databases):NEWLINE self.DBs = dict()NEWLINE if isinstance(databases, DBBase):NEWLINE self.DBs[databases.dbName] = databasesNEWLINE else:NEWLINE for db in databases:NEWLINE self.DBs[db.dbName] = dbNEWLINE self.n = len(self.DBs)NEWLINENEWLINE def show(self, showRef, shuffle=False, concAxis=1, maxsize=960):NEWLINE """NEWLINE :meth: show images according to the assigned sortNEWLINE :ivar showRef: the reference for showing image. It could be in 3 formats: 1) a dbName; 2) a list of DetImage.ID; and 3) a show list of DisplayInfo.NEWLINE :ivar shuffle: shuffle or not (default False)NEWLINE :ivar concAxis: concatenate axis, 1 means horizontally (default) while 0 means verticallyNEWLINE :ivar maxsize: maxsize of the show imageNEWLINE :type showRef: list or strNEWLINE :type shuffle: boolNEWLINE :type concAxis: int (0/1)NEWLINE :type maxsize: int NEWLINE """NEWLINE showlist = list()NEWLINE if type(showRef) == str: # show by dbNameNEWLINE db = self.DBs[showRef]NEWLINE for i, imageID in enumerate(db.images):NEWLINE info = DisplayInfo(imageID, None, None, i, len(db.images))NEWLINE showlist.append(info)NEWLINE elif type(showRef[0]) == str: # show by showlist in format 1NEWLINE for i, imageID in enumerate(showRef):NEWLINE info = DisplayInfo(imageID, None, None, i, len(showRef))NEWLINE showlist.append(info)NEWLINE else: # show by showlist in format 2NEWLINE assert type(showRef[0]) == DisplayInfo, "Unrecognized showRef format."NEWLINE showlist = showRefNEWLINENEWLINE if shuffle is True:NEWLINE random.shuffle(showlist)NEWLINENEWLINE i = 0NEWLINE while i < len(showlist):NEWLINE print("{}/{}: {}".format(i, len(showlist), showlist[i].sprint()))NEWLINE imgbatch = list()NEWLINE for dbName in self.DBs:NEWLINE db = self.DBs[dbName]NEWLINE imgID = showlist[i].imgIDNEWLINE boldScore = showlist[i].dtbox.score if showlist[i].dtbox is not None else NoneNEWLINE dtShowThres = db.dtShowThres if type(db) is EvalDB else NoneNEWLINE img = db.images[imgID].draw(dtShowThres, boldScore)NEWLINE assert len(img.shape) == 2 or len(img.shape) == 3, 'error image shape'NEWLINE if len(img.shape) == 3:NEWLINE h, w, d = img.shapeNEWLINE elif len(img.shape) == 2:NEWLINE h, w = img.shapeNEWLINE if max(h, w) > maxsize:NEWLINE ratio = float(maxsize)/max(h, w)NEWLINE img = cv2.resize(img, (int(w*ratio), int(h*ratio)))NEWLINE imgbatch.append(img)NEWLINE NEWLINE showimg = np.concatenate(imgbatch, axis=concAxis)NEWLINENEWLINE '''NEWLINE cv2.imwrite( "/home/yugang/res/{}.png".format(i), showimg)NEWLINE i = i + 1NEWLINE '''NEWLINE #cv2.namedWindow(imgID, 0)NEWLINE #cv2.imshow(imgID, showimg)NEWLINE cv2.namedWindow("img", 0)NEWLINE cv2.imshow("img", showimg)NEWLINE action = cv2.waitKey(0)NEWLINE cv2.destroyAllWindows()NEWLINENEWLINE if action == 65361: #left keyNEWLINE i = i - 1 if i >= 1 else 0NEWLINE elif action == 65366: #pagedownNEWLINE i = i + 20 if i < len(showlist)-21 else len(showlist)-1NEWLINE elif action == 65365: #pageupNEWLINE i = i - 20 if i >= 20 else 0NEWLINE elif action == 113: #escNEWLINE returnNEWLINE else:NEWLINE i = i + 1NEWLINENEWLINE
# Copyright 2015 The Crashpad 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.NEWLINENEWLINE{NEWLINE 'includes': [NEWLINE '../build/crashpad.gypi',NEWLINE ],NEWLINE 'targets': [NEWLINE {NEWLINE 'target_name': 'crashpad_test',NEWLINE 'type': 'static_library',NEWLINE 'dependencies': [NEWLINE '../compat/compat.gyp:crashpad_compat',NEWLINE '../third_party/gtest/gtest.gyp:gtest',NEWLINE '../third_party/mini_chromium/mini_chromium.gyp:base',NEWLINE '../util/util.gyp:crashpad_util',NEWLINE ],NEWLINE 'include_dirs': [NEWLINE '..',NEWLINE ],NEWLINE 'sources': [NEWLINE 'errors.cc',NEWLINE 'errors.h',NEWLINE 'file.cc',NEWLINE 'file.h',NEWLINE 'filesystem.cc',NEWLINE 'filesystem.h',NEWLINE 'gtest_death.h',NEWLINE 'hex_string.cc',NEWLINE 'hex_string.h',NEWLINE 'linux/fake_ptrace_connection.cc',NEWLINE 'linux/fake_ptrace_connection.h',NEWLINE 'linux/get_tls.cc',NEWLINE 'linux/get_tls.h',NEWLINE 'mac/dyld.cc',NEWLINE 'mac/dyld.h',NEWLINE 'mac/exception_swallower.cc',NEWLINE 'mac/exception_swallower.h',NEWLINE 'mac/mach_errors.cc',NEWLINE 'mac/mach_errors.h',NEWLINE 'mac/mach_multiprocess.cc',NEWLINE 'mac/mach_multiprocess.h',NEWLINE 'main_arguments.cc',NEWLINE 'main_arguments.h',NEWLINE 'multiprocess.h',NEWLINE 'multiprocess_exec.cc',NEWLINE 'multiprocess_exec.h',NEWLINE 'multiprocess_exec_posix.cc',NEWLINE 'multiprocess_exec_win.cc',NEWLINE 'multiprocess_posix.cc',NEWLINE 'process_type.cc',NEWLINE 'process_type.h',NEWLINE 'scoped_guarded_page.h',NEWLINE 'scoped_guarded_page_posix.cc',NEWLINE 'scoped_module_handle.cc',NEWLINE 'scoped_module_handle.h',NEWLINE 'scoped_temp_dir.cc',NEWLINE 'scoped_temp_dir.h',NEWLINE 'scoped_temp_dir_posix.cc',NEWLINE 'scoped_temp_dir_win.cc',NEWLINE 'test_paths.cc',NEWLINE 'test_paths.h',NEWLINE 'win/child_launcher.cc',NEWLINE 'win/child_launcher.h',NEWLINE 'win/win_child_process.cc',NEWLINE 'win/win_child_process.h',NEWLINE 'win/win_multiprocess.cc',NEWLINE 'win/win_multiprocess.h',NEWLINE 'win/win_multiprocess_with_temp_dir.cc',NEWLINE 'win/win_multiprocess_with_temp_dir.h',NEWLINE ],NEWLINE 'direct_dependent_settings': {NEWLINE 'include_dirs': [NEWLINE '..',NEWLINE ],NEWLINE },NEWLINE 'conditions': [NEWLINE ['OS=="mac"', {NEWLINE 'dependencies': [NEWLINE '../handler/handler.gyp:crashpad_handler_lib',NEWLINE '../snapshot/snapshot.gyp:crashpad_snapshot',NEWLINE ],NEWLINE 'link_settings': {NEWLINE 'libraries': [NEWLINE '$(SDKROOT)/usr/lib/libbsm.dylib',NEWLINE ],NEWLINE },NEWLINE }],NEWLINE ['OS=="win"', {NEWLINE 'link_settings': {NEWLINE 'libraries': [NEWLINE '-lshell32.lib',NEWLINE ],NEWLINE },NEWLINE }],NEWLINE ],NEWLINE 'target_conditions': [NEWLINE ['OS=="android"', {NEWLINE 'sources/': [NEWLINE ['include', '^linux/'],NEWLINE ],NEWLINE }],NEWLINE ],NEWLINE },NEWLINE {NEWLINE 'target_name': 'crashpad_gmock_main',NEWLINE 'type': 'static_library',NEWLINE 'dependencies': [NEWLINE 'crashpad_test',NEWLINE '../third_party/gtest/gmock.gyp:gmock',NEWLINE '../third_party/gtest/gtest.gyp:gtest',NEWLINE '../third_party/mini_chromium/mini_chromium.gyp:base',NEWLINE ],NEWLINE 'include_dirs': [NEWLINE '..',NEWLINE ],NEWLINE 'defines': [NEWLINE 'CRASHPAD_TEST_LAUNCHER_GMOCK=1',NEWLINE ],NEWLINE 'sources': [NEWLINE 'gtest_main.cc',NEWLINE ],NEWLINE },NEWLINE {NEWLINE 'target_name': 'crashpad_gtest_main',NEWLINE 'type': 'static_library',NEWLINE 'dependencies': [NEWLINE 'crashpad_test',NEWLINE '../third_party/gtest/gtest.gyp:gtest',NEWLINE '../third_party/mini_chromium/mini_chromium.gyp:base',NEWLINE ],NEWLINE 'include_dirs': [NEWLINE '..',NEWLINE ],NEWLINE 'defines': [NEWLINE 'CRASHPAD_TEST_LAUNCHER_GTEST=1',NEWLINE ],NEWLINE 'sources': [NEWLINE 'gtest_main.cc',NEWLINE ],NEWLINE },NEWLINE ],NEWLINE}NEWLINE
# coding: utf-8NEWLINENEWLINE# Copyright 2018 IBM 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"""NEWLINEThe IBM Watson&trade; Visual Recognition service uses deep learning algorithms to identifyNEWLINEscenes, objects, and faces in images you upload to the service. You can create and trainNEWLINEa custom classifier to identify subjects that suit your needs.NEWLINE"""NEWLINENEWLINEfrom __future__ import absolute_importNEWLINENEWLINEimport jsonNEWLINEfrom .watson_service import datetime_to_string, string_to_datetimeNEWLINEfrom os.path import basenameNEWLINEimport reNEWLINEfrom .watson_service import WatsonServiceNEWLINEfrom .utils import deprecatedNEWLINENEWLINE##############################################################################NEWLINE# ServiceNEWLINE##############################################################################NEWLINENEWLINE@deprecated("watson-developer-cloud moved to ibm-watson. To get updates, use the new package.")NEWLINEclass VisualRecognitionV3(WatsonService):NEWLINE """The Visual Recognition V3 service."""NEWLINENEWLINE default_url = 'https://gateway.watsonplatform.net/visual-recognition/api'NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE version,NEWLINE url=default_url,NEWLINE iam_apikey=None,NEWLINE iam_access_token=None,NEWLINE iam_url=None,NEWLINE ):NEWLINE """NEWLINE Construct a new client for the Visual Recognition service.NEWLINENEWLINE :param str version: The API version date to use with the service, inNEWLINE "YYYY-MM-DD" format. Whenever the API is changed in a backwardsNEWLINE incompatible way, a new minor version of the API is released.NEWLINE The service uses the API version for the date you specify, orNEWLINE the most recent version before that date. Note that you shouldNEWLINE not programmatically specify the current date at runtime, inNEWLINE case the API has been updated since your application's release.NEWLINE Instead, specify a version date that is compatible with yourNEWLINE application, and don't change it until your application isNEWLINE ready for a later version.NEWLINENEWLINE :param str url: The base url to use when contacting the service (e.g.NEWLINE "https://gateway.watsonplatform.net/visual-recognition/api").NEWLINE The base url may differ between Bluemix regions.NEWLINENEWLINE :param str iam_apikey: An API key that can be used to request IAM tokens. IfNEWLINE this API key is provided, the SDK will manage the token and handle theNEWLINE refreshing.NEWLINENEWLINE :param str iam_access_token: An IAM access token is fully managed by the application.NEWLINE Responsibility falls on the application to refresh the token, either beforeNEWLINE it expires or reactively upon receiving a 401 from the service as any requestsNEWLINE made with an expired token will fail.NEWLINENEWLINE :param str iam_url: An optional URL for the IAM service API. Defaults toNEWLINE 'https://iam.bluemix.net/identity/token'.NEWLINE """NEWLINENEWLINE WatsonService.__init__(NEWLINE self,NEWLINE vcap_services_name='watson_vision_combined',NEWLINE url=url,NEWLINE iam_apikey=iam_apikey,NEWLINE iam_access_token=iam_access_token,NEWLINE iam_url=iam_url,NEWLINE use_vcap_services=True,NEWLINE display_name='Visual Recognition')NEWLINE self.version = versionNEWLINENEWLINE #########################NEWLINE # GeneralNEWLINE #########################NEWLINENEWLINE def classify(self,NEWLINE images_file=None,NEWLINE accept_language=None,NEWLINE url=None,NEWLINE threshold=None,NEWLINE owners=None,NEWLINE classifier_ids=None,NEWLINE images_file_content_type=None,NEWLINE images_filename=None,NEWLINE **kwargs):NEWLINE """NEWLINE Classify images.NEWLINENEWLINE Classify images with built-in or custom classifiers.NEWLINENEWLINE :param file images_file: An image file (.gif, .jpg, .png, .tif) or .zip file withNEWLINE images. Maximum image size is 10 MB. Include no more than 20 images and limit theNEWLINE .zip file to 100 MB. Encode the image and .zip file names in UTF-8 if they containNEWLINE non-ASCII characters. The service assumes UTF-8 encoding if it encountersNEWLINE non-ASCII characters.NEWLINE You can also include an image with the **url** parameter.NEWLINE :param str accept_language: The desired language of parts of the response. See theNEWLINE response for details.NEWLINE :param str url: The URL of an image (.gif, .jpg, .png, .tif) to analyze. TheNEWLINE minimum recommended pixel density is 32X32 pixels, but the service tends toNEWLINE perform better with images that are at least 224 x 224 pixels. The maximum imageNEWLINE size is 10 MB.NEWLINE You can also include images with the **images_file** parameter.NEWLINE :param float threshold: The minimum score a class must have to be displayed in theNEWLINE response. Set the threshold to `0.0` to return all identified classes.NEWLINE :param list[str] owners: The categories of classifiers to apply. TheNEWLINE **classifier_ids** parameter overrides **owners**, so make sure thatNEWLINE **classifier_ids** is empty.NEWLINE - Use `IBM` to classify against the `default` general classifier. You get the sameNEWLINE result if both **classifier_ids** and **owners** parameters are empty.NEWLINE - Use `me` to classify against all your custom classifiers. However, for betterNEWLINE performance use **classifier_ids** to specify the specific custom classifiers toNEWLINE apply.NEWLINE - Use both `IBM` and `me` to analyze the image against both classifier categories.NEWLINE :param list[str] classifier_ids: Which classifiers to apply. Overrides theNEWLINE **owners** parameter. You can specify both custom and built-in classifier IDs. TheNEWLINE built-in `default` classifier is used if both **classifier_ids** and **owners**NEWLINE parameters are empty.NEWLINE The following built-in classifier IDs require no training:NEWLINE - `default`: Returns classes from thousands of general tags.NEWLINE - `food`: Enhances specificity and accuracy for images of food items.NEWLINE - `explicit`: Evaluates whether the image might be pornographic.NEWLINE :param str images_file_content_type: The content type of images_file.NEWLINE :param str images_filename: The filename for images_file.NEWLINE :param dict headers: A `dict` containing the request headersNEWLINE :return: A `DetailedResponse` containing the result, headers and HTTP status code.NEWLINE :rtype: DetailedResponseNEWLINE """NEWLINENEWLINE headers = {'Accept-Language': accept_language}NEWLINE if 'headers' in kwargs:NEWLINE headers.update(kwargs.get('headers'))NEWLINE headers[NEWLINE 'X-IBMCloud-SDK-Analytics'] = 'service_name=watson_vision_combined;service_version=V3;operation_id=classify'NEWLINENEWLINE params = {'version': self.version}NEWLINENEWLINE form_data = {}NEWLINE if images_file:NEWLINE if not images_filename and hasattr(images_file, 'name'):NEWLINE images_filename = basename(images_file.name)NEWLINE form_data['images_file'] = (images_filename, images_file,NEWLINE images_file_content_type orNEWLINE 'application/octet-stream')NEWLINE if url:NEWLINE form_data['url'] = (None, url, 'text/plain')NEWLINE if threshold:NEWLINE form_data['threshold'] = (None, threshold, 'application/json')NEWLINE if owners:NEWLINE owners = self._convert_list(owners)NEWLINE form_data['owners'] = (None, owners, 'application/json')NEWLINE if classifier_ids:NEWLINE classifier_ids = self._convert_list(classifier_ids)NEWLINE form_data['classifier_ids'] = (None, classifier_ids,NEWLINE 'application/json')NEWLINENEWLINE url = '/v3/classify'NEWLINE response = self.request(NEWLINE method='POST',NEWLINE url=url,NEWLINE headers=headers,NEWLINE params=params,NEWLINE files=form_data,NEWLINE accept_json=True)NEWLINE return responseNEWLINENEWLINE #########################NEWLINE # FaceNEWLINE #########################NEWLINENEWLINE def detect_faces(self,NEWLINE images_file=None,NEWLINE url=None,NEWLINE images_file_content_type=None,NEWLINE images_filename=None,NEWLINE accept_language=None,NEWLINE **kwargs):NEWLINE """NEWLINE Detect faces in images.NEWLINENEWLINE **Important:** On April 2, 2018, the identity information in the response to callsNEWLINE to the Face model was removed. The identity information refers to the `name` ofNEWLINE the person, `score`, and `type_hierarchy` knowledge graph. For details about theNEWLINE enhanced Face model, see the [ReleaseNEWLINE notes](https://cloud.ibm.com/docs/services/visual-recognition/release-notes.html#2april2018).NEWLINE Analyze and get data about faces in images. Responses can include estimated ageNEWLINE and gender. This feature uses a built-in model, so no training is necessary. TheNEWLINE Detect faces method does not support general biometric facial recognition.NEWLINE Supported image formats include .gif, .jpg, .png, and .tif. The maximum image sizeNEWLINE is 10 MB. The minimum recommended pixel density is 32X32 pixels, but the serviceNEWLINE tends to perform better with images that are at least 224 x 224 pixels.NEWLINENEWLINE :param file images_file: An image file (gif, .jpg, .png, .tif.) or .zip file withNEWLINE images. Limit the .zip file to 100 MB. You can include a maximum of 15 images in aNEWLINE request.NEWLINE Encode the image and .zip file names in UTF-8 if they contain non-ASCIINEWLINE characters. The service assumes UTF-8 encoding if it encounters non-ASCIINEWLINE characters.NEWLINE You can also include an image with the **url** parameter.NEWLINE :param str url: The URL of an image to analyze. Must be in .gif, .jpg, .png, orNEWLINE .tif format. The minimum recommended pixel density is 32X32 pixels, but theNEWLINE service tends to perform better with images that are at least 224 x 224 pixels.NEWLINE The maximum image size is 10 MB. Redirects are followed, so you can use aNEWLINE shortened URL.NEWLINE You can also include images with the **images_file** parameter.NEWLINE :param str images_file_content_type: The content type of images_file.NEWLINE :param str images_filename: The filename for images_file.NEWLINE :param str accept_language: The desired language of parts of the response. See theNEWLINE response for details.NEWLINE :param dict headers: A `dict` containing the request headersNEWLINE :return: A `DetailedResponse` containing the result, headers and HTTP status code.NEWLINE :rtype: DetailedResponseNEWLINE """NEWLINENEWLINE headers = {'Accept-Language': accept_language}NEWLINE if 'headers' in kwargs:NEWLINE headers.update(kwargs.get('headers'))NEWLINE headers[NEWLINE 'X-IBMCloud-SDK-Analytics'] = 'service_name=watson_vision_combined;service_version=V3;operation_id=detect_faces'NEWLINENEWLINE params = {'version': self.version}NEWLINENEWLINE form_data = {}NEWLINE if images_file:NEWLINE if not images_filename and hasattr(images_file, 'name'):NEWLINE images_filename = basename(images_file.name)NEWLINE form_data['images_file'] = (images_filename, images_file,NEWLINE images_file_content_type orNEWLINE 'application/octet-stream')NEWLINE if url:NEWLINE form_data['url'] = (None, url, 'text/plain')NEWLINENEWLINE url = '/v3/detect_faces'NEWLINE response = self.request(NEWLINE method='POST',NEWLINE url=url,NEWLINE headers=headers,NEWLINE params=params,NEWLINE files=form_data,NEWLINE accept_json=True)NEWLINE return responseNEWLINENEWLINE #########################NEWLINE # CustomNEWLINE #########################NEWLINENEWLINE def create_classifier(self,NEWLINE name,NEWLINE negative_examples=None,NEWLINE negative_examples_filename=None,NEWLINE **kwargs):NEWLINE """NEWLINE Create a classifier.NEWLINENEWLINE Train a new multi-faceted classifier on the uploaded image data. Create yourNEWLINE custom classifier with positive or negative examples. Include at least two sets ofNEWLINE examples, either two positive example files or one positive and one negative file.NEWLINE You can upload a maximum of 256 MB per call.NEWLINE Encode all names in UTF-8 if they contain non-ASCII characters (.zip and imageNEWLINE file names, and classifier and class names). The service assumes UTF-8 encoding ifNEWLINE it encounters non-ASCII characters.NEWLINENEWLINE :param str name: The name of the new classifier. Encode special characters inNEWLINE UTF-8.NEWLINE :param file negative_examples: A .zip file of images that do not depict the visualNEWLINE subject of any of the classes of the new classifier. Must contain a minimum of 10NEWLINE images.NEWLINE Encode special characters in the file name in UTF-8.NEWLINE :param str negative_examples_filename: The filename for negative_examples.NEWLINE :param file positive_examples: A .zip file of images that depict the visualNEWLINE subject of a class in the new classifier. You can include more than one positiveNEWLINE example file in a call.NEWLINE Specify the parameter name by appending `_positive_examples` to the class name.NEWLINE For example, `goldenretriever_positive_examples` creates the classNEWLINE **goldenretriever**.NEWLINE Include at least 10 images in .jpg or .png format. The minimum recommended imageNEWLINE resolution is 32X32 pixels. The maximum number of images is 10,000 images or 100NEWLINE MB per .zip file.NEWLINE Encode special characters in the file name in UTF-8.NEWLINE :param str positive_examples_filename: The filename for positive_examples.NEWLINE :param dict headers: A `dict` containing the request headersNEWLINE :return: A `DetailedResponse` containing the result, headers and HTTP status code.NEWLINE :rtype: DetailedResponseNEWLINE """NEWLINENEWLINE if name is None:NEWLINE raise ValueError('name must be provided')NEWLINE positive_examples_keys = [NEWLINE key for key in kwargs if re.match('^.+_positive_examples$', key)NEWLINE ]NEWLINE if not positive_examples_keys:NEWLINE raise ValueError(NEWLINE 'At least one <classname>_positive_examples parameter must be provided'NEWLINE )NEWLINENEWLINE headers = {}NEWLINE if 'headers' in kwargs:NEWLINE headers.update(kwargs.get('headers'))NEWLINE headers[NEWLINE 'X-IBMCloud-SDK-Analytics'] = 'service_name=watson_vision_combined;service_version=V3;operation_id=create_classifier'NEWLINENEWLINE params = {'version': self.version}NEWLINENEWLINE form_data = {}NEWLINE form_data['name'] = (None, name, 'text/plain')NEWLINE if negative_examples:NEWLINE if not negative_examples_filename and hasattr(NEWLINE negative_examples, 'name'):NEWLINE negative_examples_filename = basename(negative_examples.name)NEWLINE if not negative_examples_filename:NEWLINE raise ValueError('negative_examples_filename must be provided')NEWLINE form_data['negative_examples'] = (negative_examples_filename,NEWLINE negative_examples,NEWLINE 'application/octet-stream')NEWLINE for key in positive_examples_keys:NEWLINE value = kwargs[key]NEWLINE filename = kwargs.get(key + '_filename')NEWLINE if not filename and hasattr(value, 'name'):NEWLINE filename = basename(value.name)NEWLINE form_data[key] = (filename, value, 'application/octet-stream')NEWLINENEWLINE url = '/v3/classifiers'NEWLINE response = self.request(NEWLINE method='POST',NEWLINE url=url,NEWLINE headers=headers,NEWLINE params=params,NEWLINE files=form_data,NEWLINE accept_json=True)NEWLINE return responseNEWLINENEWLINE def delete_classifier(self, classifier_id, **kwargs):NEWLINE """NEWLINE Delete a classifier.NEWLINENEWLINE :param str classifier_id: The ID of the classifier.NEWLINE :param dict headers: A `dict` containing the request headersNEWLINE :return: A `DetailedResponse` containing the result, headers and HTTP status code.NEWLINE :rtype: DetailedResponseNEWLINE """NEWLINENEWLINE if classifier_id is None:NEWLINE raise ValueError('classifier_id must be provided')NEWLINENEWLINE headers = {}NEWLINE if 'headers' in kwargs:NEWLINE headers.update(kwargs.get('headers'))NEWLINE headers[NEWLINE 'X-IBMCloud-SDK-Analytics'] = 'service_name=watson_vision_combined;service_version=V3;operation_id=delete_classifier'NEWLINENEWLINE params = {'version': self.version}NEWLINENEWLINE url = '/v3/classifiers/{0}'.format(NEWLINE *self._encode_path_vars(classifier_id))NEWLINE response = self.request(NEWLINE method='DELETE',NEWLINE url=url,NEWLINE headers=headers,NEWLINE params=params,NEWLINE accept_json=True)NEWLINE return responseNEWLINENEWLINE def get_classifier(self, classifier_id, **kwargs):NEWLINE """NEWLINE Retrieve classifier details.NEWLINENEWLINE Retrieve information about a custom classifier.NEWLINENEWLINE :param str classifier_id: The ID of the classifier.NEWLINE :param dict headers: A `dict` containing the request headersNEWLINE :return: A `DetailedResponse` containing the result, headers and HTTP status code.NEWLINE :rtype: DetailedResponseNEWLINE """NEWLINENEWLINE if classifier_id is None:NEWLINE raise ValueError('classifier_id must be provided')NEWLINENEWLINE headers = {}NEWLINE if 'headers' in kwargs:NEWLINE headers.update(kwargs.get('headers'))NEWLINE headers[NEWLINE 'X-IBMCloud-SDK-Analytics'] = 'service_name=watson_vision_combined;service_version=V3;operation_id=get_classifier'NEWLINENEWLINE params = {'version': self.version}NEWLINENEWLINE url = '/v3/classifiers/{0}'.format(NEWLINE *self._encode_path_vars(classifier_id))NEWLINE response = self.request(NEWLINE method='GET',NEWLINE url=url,NEWLINE headers=headers,NEWLINE params=params,NEWLINE accept_json=True)NEWLINE return responseNEWLINENEWLINE def list_classifiers(self, verbose=None, **kwargs):NEWLINE """NEWLINE Retrieve a list of classifiers.NEWLINENEWLINE :param bool verbose: Specify `true` to return details about the classifiers. OmitNEWLINE this parameter to return a brief list of classifiers.NEWLINE :param dict headers: A `dict` containing the request headersNEWLINE :return: A `DetailedResponse` containing the result, headers and HTTP status code.NEWLINE :rtype: DetailedResponseNEWLINE """NEWLINENEWLINE headers = {}NEWLINE if 'headers' in kwargs:NEWLINE headers.update(kwargs.get('headers'))NEWLINE headers[NEWLINE 'X-IBMCloud-SDK-Analytics'] = 'service_name=watson_vision_combined;service_version=V3;operation_id=list_classifiers'NEWLINENEWLINE params = {'version': self.version, 'verbose': verbose}NEWLINENEWLINE url = '/v3/classifiers'NEWLINE response = self.request(NEWLINE method='GET',NEWLINE url=url,NEWLINE headers=headers,NEWLINE params=params,NEWLINE accept_json=True)NEWLINE return responseNEWLINENEWLINE def update_classifier(self,NEWLINE classifier_id,NEWLINE negative_examples=None,NEWLINE negative_examples_filename=None,NEWLINE **kwargs):NEWLINE """NEWLINE Update a classifier.NEWLINENEWLINE Update a custom classifier by adding new positive or negative classes or by addingNEWLINE new images to existing classes. You must supply at least one set of positive orNEWLINE negative examples. For details, see [Updating customNEWLINE classifiers](https://cloud.ibm.com/docs/services/visual-recognition/customizing.html#updating-custom-classifiers).NEWLINE Encode all names in UTF-8 if they contain non-ASCII characters (.zip and imageNEWLINE file names, and classifier and class names). The service assumes UTF-8 encoding ifNEWLINE it encounters non-ASCII characters.NEWLINE **Tip:** Don't make retraining calls on a classifier until the status is ready.NEWLINE When you submit retraining requests in parallel, the last request overwrites theNEWLINE previous requests. The retrained property shows the last time the classifierNEWLINE retraining finished.NEWLINENEWLINE :param str classifier_id: The ID of the classifier.NEWLINE :param file negative_examples: A .zip file of images that do not depict the visualNEWLINE subject of any of the classes of the new classifier. Must contain a minimum of 10NEWLINE images.NEWLINE Encode special characters in the file name in UTF-8.NEWLINE :param str negative_examples_filename: The filename for negative_examples.NEWLINE :param file positive_examples: A .zip file of images that depict the visualNEWLINE subject of a class in the classifier. The positive examples create or updateNEWLINE classes in the classifier. You can include more than one positive example file inNEWLINE a call.NEWLINE Specify the parameter name by appending `_positive_examples` to the class name.NEWLINE For example, `goldenretriever_positive_examples` creates the classNEWLINE `goldenretriever`.NEWLINE Include at least 10 images in .jpg or .png format. The minimum recommended imageNEWLINE resolution is 32X32 pixels. The maximum number of images is 10,000 images or 100NEWLINE MB per .zip file.NEWLINE Encode special characters in the file name in UTF-8.NEWLINE :param str positive_examples_filename: The filename for positive_examples.NEWLINE :param dict headers: A `dict` containing the request headersNEWLINE :return: A `DetailedResponse` containing the result, headers and HTTP status code.NEWLINE :rtype: DetailedResponseNEWLINE """NEWLINENEWLINE if classifier_id is None:NEWLINE raise ValueError('classifier_id must be provided')NEWLINE positive_examples_keys = [NEWLINE key for key in kwargs if re.match('^.+_positive_examples$', key)NEWLINE ]NEWLINENEWLINE headers = {}NEWLINE if 'headers' in kwargs:NEWLINE headers.update(kwargs.get('headers'))NEWLINE headers[NEWLINE 'X-IBMCloud-SDK-Analytics'] = 'service_name=watson_vision_combined;service_version=V3;operation_id=update_classifier'NEWLINENEWLINE params = {'version': self.version}NEWLINENEWLINE form_data = {}NEWLINE if negative_examples:NEWLINE if not negative_examples_filename and hasattr(NEWLINE negative_examples, 'name'):NEWLINE negative_examples_filename = basename(negative_examples.name)NEWLINE if not negative_examples_filename:NEWLINE raise ValueError('negative_examples_filename must be provided')NEWLINE form_data['negative_examples'] = (negative_examples_filename,NEWLINE negative_examples,NEWLINE 'application/octet-stream')NEWLINE for key in positive_examples_keys:NEWLINE value = kwargs[key]NEWLINE filename = kwargs.get(key + '_filename')NEWLINE if not filename and hasattr(value, 'name'):NEWLINE filename = basename(value.name)NEWLINE form_data[key] = (filename, value, 'application/octet-stream')NEWLINENEWLINE url = '/v3/classifiers/{0}'.format(NEWLINE *self._encode_path_vars(classifier_id))NEWLINE response = self.request(NEWLINE method='POST',NEWLINE url=url,NEWLINE headers=headers,NEWLINE params=params,NEWLINE files=form_data,NEWLINE accept_json=True)NEWLINE return responseNEWLINENEWLINE #########################NEWLINE # Core MLNEWLINE #########################NEWLINENEWLINE def get_core_ml_model(self, classifier_id, **kwargs):NEWLINE """NEWLINE Retrieve a Core ML model of a classifier.NEWLINENEWLINE Download a Core ML model file (.mlmodel) of a custom classifier that returnsNEWLINE <tt>\"core_ml_enabled\": true</tt> in the classifier details.NEWLINENEWLINE :param str classifier_id: The ID of the classifier.NEWLINE :param dict headers: A `dict` containing the request headersNEWLINE :return: A `DetailedResponse` containing the result, headers and HTTP status code.NEWLINE :rtype: DetailedResponseNEWLINE """NEWLINENEWLINE if classifier_id is None:NEWLINE raise ValueError('classifier_id must be provided')NEWLINENEWLINE headers = {}NEWLINE if 'headers' in kwargs:NEWLINE headers.update(kwargs.get('headers'))NEWLINE headers[NEWLINE 'X-IBMCloud-SDK-Analytics'] = 'service_name=watson_vision_combined;service_version=V3;operation_id=get_core_ml_model'NEWLINENEWLINE params = {'version': self.version}NEWLINENEWLINE url = '/v3/classifiers/{0}/core_ml_model'.format(NEWLINE *self._encode_path_vars(classifier_id))NEWLINE response = self.request(NEWLINE method='GET',NEWLINE url=url,NEWLINE headers=headers,NEWLINE params=params,NEWLINE accept_json=False)NEWLINE return responseNEWLINENEWLINE #########################NEWLINE # User dataNEWLINE #########################NEWLINENEWLINE def delete_user_data(self, customer_id, **kwargs):NEWLINE """NEWLINE Delete labeled data.NEWLINENEWLINE Deletes all data associated with a specified customer ID. The method has no effectNEWLINE if no data is associated with the customer ID.NEWLINE You associate a customer ID with data by passing the `X-Watson-Metadata` headerNEWLINE with a request that passes data. For more information about personal data andNEWLINE customer IDs, see [InformationNEWLINE security](https://cloud.ibm.com/docs/services/visual-recognition/information-security.html).NEWLINENEWLINE :param str customer_id: The customer ID for which all data is to be deleted.NEWLINE :param dict headers: A `dict` containing the request headersNEWLINE :return: A `DetailedResponse` containing the result, headers and HTTP status code.NEWLINE :rtype: DetailedResponseNEWLINE """NEWLINENEWLINE if customer_id is None:NEWLINE raise ValueError('customer_id must be provided')NEWLINENEWLINE headers = {}NEWLINE if 'headers' in kwargs:NEWLINE headers.update(kwargs.get('headers'))NEWLINE headers[NEWLINE 'X-IBMCloud-SDK-Analytics'] = 'service_name=watson_vision_combined;service_version=V3;operation_id=delete_user_data'NEWLINENEWLINE params = {'version': self.version, 'customer_id': customer_id}NEWLINENEWLINE url = '/v3/user_data'NEWLINE response = self.request(NEWLINE method='DELETE',NEWLINE url=url,NEWLINE headers=headers,NEWLINE params=params,NEWLINE accept_json=True)NEWLINE return responseNEWLINENEWLINENEWLINE##############################################################################NEWLINE# ModelsNEWLINE##############################################################################NEWLINENEWLINENEWLINEclass Class(object):NEWLINE """NEWLINE A category within a classifier.NEWLINENEWLINE :attr str class_name: The name of the class.NEWLINE """NEWLINENEWLINE def __init__(self, class_name):NEWLINE """NEWLINE Initialize a Class object.NEWLINENEWLINE :param str class_name: The name of the class.NEWLINE """NEWLINE self.class_name = class_nameNEWLINENEWLINE @classmethodNEWLINE def _from_dict(cls, _dict):NEWLINE """Initialize a Class object from a json dictionary."""NEWLINE args = {}NEWLINE if 'class' in _dict or 'class_name' in _dict:NEWLINE args['class_name'] = _dict.get('class') or _dict.get('class_name')NEWLINE else:NEWLINE raise ValueError(NEWLINE 'Required property \'class\' not present in Class JSON')NEWLINE return cls(**args)NEWLINENEWLINE def _to_dict(self):NEWLINE """Return a json dictionary representing this model."""NEWLINE _dict = {}NEWLINE if hasattr(self, 'class_name') and self.class_name is not None:NEWLINE _dict['class'] = self.class_nameNEWLINE return _dictNEWLINENEWLINE def __str__(self):NEWLINE """Return a `str` version of this Class object."""NEWLINE return json.dumps(self._to_dict(), indent=2)NEWLINENEWLINE def __eq__(self, other):NEWLINE """Return `true` when self and other are equal, false otherwise."""NEWLINE if not isinstance(other, self.__class__):NEWLINE return FalseNEWLINE return self.__dict__ == other.__dict__NEWLINENEWLINE def __ne__(self, other):NEWLINE """Return `true` when self and other are not equal, false otherwise."""NEWLINE return not self == otherNEWLINENEWLINENEWLINEclass ClassResult(object):NEWLINE """NEWLINE Result of a class within a classifier.NEWLINENEWLINE :attr str class_name: Name of the class.NEWLINE Class names are translated in the language defined by the **Accept-Language** requestNEWLINE header for the build-in classifier IDs (`default`, `food`, and `explicit`). ClassNEWLINE names of custom classifiers are not translated. The response might not be in theNEWLINE specified language when the requested language is not supported or when there is noNEWLINE translation for the class name.NEWLINE :attr float score: Confidence score for the property in the range of 0 to 1. A higherNEWLINE score indicates greater likelihood that the class is depicted in the image. TheNEWLINE default threshold for returning scores from a classifier is 0.5.NEWLINE :attr str type_hierarchy: (optional) Knowledge graph of the property. For example,NEWLINE `/fruit/pome/apple/eating apple/Granny Smith`. Included only if identified.NEWLINE """NEWLINENEWLINE def __init__(self, class_name, score, type_hierarchy=None):NEWLINE """NEWLINE Initialize a ClassResult object.NEWLINENEWLINE :param str class_name: Name of the class.NEWLINE Class names are translated in the language defined by the **Accept-Language**NEWLINE request header for the build-in classifier IDs (`default`, `food`, andNEWLINE `explicit`). Class names of custom classifiers are not translated. The responseNEWLINE might not be in the specified language when the requested language is notNEWLINE supported or when there is no translation for the class name.NEWLINE :param float score: Confidence score for the property in the range of 0 to 1. ANEWLINE higher score indicates greater likelihood that the class is depicted in the image.NEWLINE The default threshold for returning scores from a classifier is 0.5.NEWLINE :param str type_hierarchy: (optional) Knowledge graph of the property. ForNEWLINE example, `/fruit/pome/apple/eating apple/Granny Smith`. Included only ifNEWLINE identified.NEWLINE """NEWLINE self.class_name = class_nameNEWLINE self.score = scoreNEWLINE self.type_hierarchy = type_hierarchyNEWLINENEWLINE @classmethodNEWLINE def _from_dict(cls, _dict):NEWLINE """Initialize a ClassResult object from a json dictionary."""NEWLINE args = {}NEWLINE if 'class' in _dict or 'class_name' in _dict:NEWLINE args['class_name'] = _dict.get('class') or _dict.get('class_name')NEWLINE else:NEWLINE raise ValueError(NEWLINE 'Required property \'class\' not present in ClassResult JSON')NEWLINE if 'score' in _dict:NEWLINE args['score'] = _dict.get('score')NEWLINE else:NEWLINE raise ValueError(NEWLINE 'Required property \'score\' not present in ClassResult JSON')NEWLINE if 'type_hierarchy' in _dict:NEWLINE args['type_hierarchy'] = _dict.get('type_hierarchy')NEWLINE return cls(**args)NEWLINENEWLINE def _to_dict(self):NEWLINE """Return a json dictionary representing this model."""NEWLINE _dict = {}NEWLINE if hasattr(self, 'class_name') and self.class_name is not None:NEWLINE _dict['class'] = self.class_nameNEWLINE if hasattr(self, 'score') and self.score is not None:NEWLINE _dict['score'] = self.scoreNEWLINE if hasattr(self, 'type_hierarchy') and self.type_hierarchy is not None:NEWLINE _dict['type_hierarchy'] = self.type_hierarchyNEWLINE return _dictNEWLINENEWLINE def __str__(self):NEWLINE """Return a `str` version of this ClassResult object."""NEWLINE return json.dumps(self._to_dict(), indent=2)NEWLINENEWLINE def __eq__(self, other):NEWLINE """Return `true` when self and other are equal, false otherwise."""NEWLINE if not isinstance(other, self.__class__):NEWLINE return FalseNEWLINE return self.__dict__ == other.__dict__NEWLINENEWLINE def __ne__(self, other):NEWLINE """Return `true` when self and other are not equal, false otherwise."""NEWLINE return not self == otherNEWLINENEWLINENEWLINEclass ClassifiedImage(object):NEWLINE """NEWLINE Results for one image.NEWLINENEWLINE :attr str source_url: (optional) Source of the image before any redirects. NotNEWLINE returned when the image is uploaded.NEWLINE :attr str resolved_url: (optional) Fully resolved URL of the image after redirects areNEWLINE followed. Not returned when the image is uploaded.NEWLINE :attr str image: (optional) Relative path of the image file if uploaded directly. NotNEWLINE returned when the image is passed by URL.NEWLINE :attr ErrorInfo error: (optional) Information about what might have caused a failure,NEWLINE such as an image that is too large. Not returned when there is no error.NEWLINE :attr list[ClassifierResult] classifiers: The classifiers.NEWLINE """NEWLINENEWLINE def __init__(self,NEWLINE classifiers,NEWLINE source_url=None,NEWLINE resolved_url=None,NEWLINE image=None,NEWLINE error=None):NEWLINE """NEWLINE Initialize a ClassifiedImage object.NEWLINENEWLINE :param list[ClassifierResult] classifiers: The classifiers.NEWLINE :param str source_url: (optional) Source of the image before any redirects. NotNEWLINE returned when the image is uploaded.NEWLINE :param str resolved_url: (optional) Fully resolved URL of the image afterNEWLINE redirects are followed. Not returned when the image is uploaded.NEWLINE :param str image: (optional) Relative path of the image file if uploaded directly.NEWLINE Not returned when the image is passed by URL.NEWLINE :param ErrorInfo error: (optional) Information about what might have caused aNEWLINE failure, such as an image that is too large. Not returned when there is no error.NEWLINE """NEWLINE self.source_url = source_urlNEWLINE self.resolved_url = resolved_urlNEWLINE self.image = imageNEWLINE self.error = errorNEWLINE self.classifiers = classifiersNEWLINENEWLINE @classmethodNEWLINE def _from_dict(cls, _dict):NEWLINE """Initialize a ClassifiedImage object from a json dictionary."""NEWLINE args = {}NEWLINE if 'source_url' in _dict:NEWLINE args['source_url'] = _dict.get('source_url')NEWLINE if 'resolved_url' in _dict:NEWLINE args['resolved_url'] = _dict.get('resolved_url')NEWLINE if 'image' in _dict:NEWLINE args['image'] = _dict.get('image')NEWLINE if 'error' in _dict:NEWLINE args['error'] = ErrorInfo._from_dict(_dict.get('error'))NEWLINE if 'classifiers' in _dict:NEWLINE args['classifiers'] = [NEWLINE ClassifierResult._from_dict(x)NEWLINE for x in (_dict.get('classifiers'))NEWLINE ]NEWLINE else:NEWLINE raise ValueError(NEWLINE 'Required property \'classifiers\' not present in ClassifiedImage JSON'NEWLINE )NEWLINE return cls(**args)NEWLINENEWLINE def _to_dict(self):NEWLINE """Return a json dictionary representing this model."""NEWLINE _dict = {}NEWLINE if hasattr(self, 'source_url') and self.source_url is not None:NEWLINE _dict['source_url'] = self.source_urlNEWLINE if hasattr(self, 'resolved_url') and self.resolved_url is not None:NEWLINE _dict['resolved_url'] = self.resolved_urlNEWLINE if hasattr(self, 'image') and self.image is not None:NEWLINE _dict['image'] = self.imageNEWLINE if hasattr(self, 'error') and self.error is not None:NEWLINE _dict['error'] = self.error._to_dict()NEWLINE if hasattr(self, 'classifiers') and self.classifiers is not None:NEWLINE _dict['classifiers'] = [x._to_dict() for x in self.classifiers]NEWLINE return _dictNEWLINENEWLINE def __str__(self):NEWLINE """Return a `str` version of this ClassifiedImage object."""NEWLINE return json.dumps(self._to_dict(), indent=2)NEWLINENEWLINE def __eq__(self, other):NEWLINE """Return `true` when self and other are equal, false otherwise."""NEWLINE if not isinstance(other, self.__class__):NEWLINE return FalseNEWLINE return self.__dict__ == other.__dict__NEWLINENEWLINE def __ne__(self, other):NEWLINE """Return `true` when self and other are not equal, false otherwise."""NEWLINE return not self == otherNEWLINENEWLINENEWLINEclass ClassifiedImages(object):NEWLINE """NEWLINE Results for all images.NEWLINENEWLINE :attr int custom_classes: (optional) Number of custom classes identified in theNEWLINE images.NEWLINE :attr int images_processed: (optional) Number of images processed for the API call.NEWLINE :attr list[ClassifiedImage] images: Classified images.NEWLINE :attr list[WarningInfo] warnings: (optional) Information about what might cause lessNEWLINE than optimal output. For example, a request sent with a corrupt .zip file and a listNEWLINE of image URLs will still complete, but does not return the expected output. NotNEWLINE returned when there is no warning.NEWLINE """NEWLINENEWLINE def __init__(self,NEWLINE images,NEWLINE custom_classes=None,NEWLINE images_processed=None,NEWLINE warnings=None):NEWLINE """NEWLINE Initialize a ClassifiedImages object.NEWLINENEWLINE :param list[ClassifiedImage] images: Classified images.NEWLINE :param int custom_classes: (optional) Number of custom classes identified in theNEWLINE images.NEWLINE :param int images_processed: (optional) Number of images processed for the APINEWLINE call.NEWLINE :param list[WarningInfo] warnings: (optional) Information about what might causeNEWLINE less than optimal output. For example, a request sent with a corrupt .zip file andNEWLINE a list of image URLs will still complete, but does not return the expected output.NEWLINE Not returned when there is no warning.NEWLINE """NEWLINE self.custom_classes = custom_classesNEWLINE self.images_processed = images_processedNEWLINE self.images = imagesNEWLINE self.warnings = warningsNEWLINENEWLINE @classmethodNEWLINE def _from_dict(cls, _dict):NEWLINE """Initialize a ClassifiedImages object from a json dictionary."""NEWLINE args = {}NEWLINE if 'custom_classes' in _dict:NEWLINE args['custom_classes'] = _dict.get('custom_classes')NEWLINE if 'images_processed' in _dict:NEWLINE args['images_processed'] = _dict.get('images_processed')NEWLINE if 'images' in _dict:NEWLINE args['images'] = [NEWLINE ClassifiedImage._from_dict(x) for x in (_dict.get('images'))NEWLINE ]NEWLINE else:NEWLINE raise ValueError(NEWLINE 'Required property \'images\' not present in ClassifiedImages JSON'NEWLINE )NEWLINE if 'warnings' in _dict:NEWLINE args['warnings'] = [NEWLINE WarningInfo._from_dict(x) for x in (_dict.get('warnings'))NEWLINE ]NEWLINE return cls(**args)NEWLINENEWLINE def _to_dict(self):NEWLINE """Return a json dictionary representing this model."""NEWLINE _dict = {}NEWLINE if hasattr(self, 'custom_classes') and self.custom_classes is not None:NEWLINE _dict['custom_classes'] = self.custom_classesNEWLINE if hasattr(self,NEWLINE 'images_processed') and self.images_processed is not None:NEWLINE _dict['images_processed'] = self.images_processedNEWLINE if hasattr(self, 'images') and self.images is not None:NEWLINE _dict['images'] = [x._to_dict() for x in self.images]NEWLINE if hasattr(self, 'warnings') and self.warnings is not None:NEWLINE _dict['warnings'] = [x._to_dict() for x in self.warnings]NEWLINE return _dictNEWLINENEWLINE def __str__(self):NEWLINE """Return a `str` version of this ClassifiedImages object."""NEWLINE return json.dumps(self._to_dict(), indent=2)NEWLINENEWLINE def __eq__(self, other):NEWLINE """Return `true` when self and other are equal, false otherwise."""NEWLINE if not isinstance(other, self.__class__):NEWLINE return FalseNEWLINE return self.__dict__ == other.__dict__NEWLINENEWLINE def __ne__(self, other):NEWLINE """Return `true` when self and other are not equal, false otherwise."""NEWLINE return not self == otherNEWLINENEWLINENEWLINEclass Classifier(object):NEWLINE """NEWLINE Information about a classifier.NEWLINENEWLINE :attr str classifier_id: ID of a classifier identified in the image.NEWLINE :attr str name: Name of the classifier.NEWLINE :attr str owner: (optional) Unique ID of the account who owns the classifier. MightNEWLINE not be returned by some requests.NEWLINE :attr str status: (optional) Training status of classifier.NEWLINE :attr bool core_ml_enabled: (optional) Whether the classifier can be downloaded as aNEWLINE Core ML model after the training status is `ready`.NEWLINE :attr str explanation: (optional) If classifier training has failed, this field mightNEWLINE explain why.NEWLINE :attr datetime created: (optional) Date and time in Coordinated Universal Time (UTC)NEWLINE that the classifier was created.NEWLINE :attr list[Class] classes: (optional) Classes that define a classifier.NEWLINE :attr datetime retrained: (optional) Date and time in Coordinated Universal Time (UTC)NEWLINE that the classifier was updated. Might not be returned by some requests. Identical toNEWLINE `updated` and retained for backward compatibility.NEWLINE :attr datetime updated: (optional) Date and time in Coordinated Universal Time (UTC)NEWLINE that the classifier was most recently updated. The field matches either `retrained` orNEWLINE `created`. Might not be returned by some requests.NEWLINE """NEWLINENEWLINE def __init__(self,NEWLINE classifier_id,NEWLINE name,NEWLINE owner=None,NEWLINE status=None,NEWLINE core_ml_enabled=None,NEWLINE explanation=None,NEWLINE created=None,NEWLINE classes=None,NEWLINE retrained=None,NEWLINE updated=None):NEWLINE """NEWLINE Initialize a Classifier object.NEWLINENEWLINE :param str classifier_id: ID of a classifier identified in the image.NEWLINE :param str name: Name of the classifier.NEWLINE :param str owner: (optional) Unique ID of the account who owns the classifier.NEWLINE Might not be returned by some requests.NEWLINE :param str status: (optional) Training status of classifier.NEWLINE :param bool core_ml_enabled: (optional) Whether the classifier can be downloadedNEWLINE as a Core ML model after the training status is `ready`.NEWLINE :param str explanation: (optional) If classifier training has failed, this fieldNEWLINE might explain why.NEWLINE :param datetime created: (optional) Date and time in Coordinated Universal TimeNEWLINE (UTC) that the classifier was created.NEWLINE :param list[Class] classes: (optional) Classes that define a classifier.NEWLINE :param datetime retrained: (optional) Date and time in Coordinated Universal TimeNEWLINE (UTC) that the classifier was updated. Might not be returned by some requests.NEWLINE Identical to `updated` and retained for backward compatibility.NEWLINE :param datetime updated: (optional) Date and time in Coordinated Universal TimeNEWLINE (UTC) that the classifier was most recently updated. The field matches eitherNEWLINE `retrained` or `created`. Might not be returned by some requests.NEWLINE """NEWLINE self.classifier_id = classifier_idNEWLINE self.name = nameNEWLINE self.owner = ownerNEWLINE self.status = statusNEWLINE self.core_ml_enabled = core_ml_enabledNEWLINE self.explanation = explanationNEWLINE self.created = createdNEWLINE self.classes = classesNEWLINE self.retrained = retrainedNEWLINE self.updated = updatedNEWLINENEWLINE @classmethodNEWLINE def _from_dict(cls, _dict):NEWLINE """Initialize a Classifier object from a json dictionary."""NEWLINE args = {}NEWLINE if 'classifier_id' in _dict:NEWLINE args['classifier_id'] = _dict.get('classifier_id')NEWLINE else:NEWLINE raise ValueError(NEWLINE 'Required property \'classifier_id\' not present in Classifier JSON'NEWLINE )NEWLINE if 'name' in _dict:NEWLINE args['name'] = _dict.get('name')NEWLINE else:NEWLINE raise ValueError(NEWLINE 'Required property \'name\' not present in Classifier JSON')NEWLINE if 'owner' in _dict:NEWLINE args['owner'] = _dict.get('owner')NEWLINE if 'status' in _dict:NEWLINE args['status'] = _dict.get('status')NEWLINE if 'core_ml_enabled' in _dict:NEWLINE args['core_ml_enabled'] = _dict.get('core_ml_enabled')NEWLINE if 'explanation' in _dict:NEWLINE args['explanation'] = _dict.get('explanation')NEWLINE if 'created' in _dict:NEWLINE args['created'] = string_to_datetime(_dict.get('created'))NEWLINE if 'classes' in _dict:NEWLINE args['classes'] = [NEWLINE Class._from_dict(x) for x in (_dict.get('classes'))NEWLINE ]NEWLINE if 'retrained' in _dict:NEWLINE args['retrained'] = string_to_datetime(_dict.get('retrained'))NEWLINE if 'updated' in _dict:NEWLINE args['updated'] = string_to_datetime(_dict.get('updated'))NEWLINE return cls(**args)NEWLINENEWLINE def _to_dict(self):NEWLINE """Return a json dictionary representing this model."""NEWLINE _dict = {}NEWLINE if hasattr(self, 'classifier_id') and self.classifier_id is not None:NEWLINE _dict['classifier_id'] = self.classifier_idNEWLINE if hasattr(self, 'name') and self.name is not None:NEWLINE _dict['name'] = self.nameNEWLINE if hasattr(self, 'owner') and self.owner is not None:NEWLINE _dict['owner'] = self.ownerNEWLINE if hasattr(self, 'status') and self.status is not None:NEWLINE _dict['status'] = self.statusNEWLINE if hasattr(self,NEWLINE 'core_ml_enabled') and self.core_ml_enabled is not None:NEWLINE _dict['core_ml_enabled'] = self.core_ml_enabledNEWLINE if hasattr(self, 'explanation') and self.explanation is not None:NEWLINE _dict['explanation'] = self.explanationNEWLINE if hasattr(self, 'created') and self.created is not None:NEWLINE _dict['created'] = datetime_to_string(self.created)NEWLINE if hasattr(self, 'classes') and self.classes is not None:NEWLINE _dict['classes'] = [x._to_dict() for x in self.classes]NEWLINE if hasattr(self, 'retrained') and self.retrained is not None:NEWLINE _dict['retrained'] = datetime_to_string(self.retrained)NEWLINE if hasattr(self, 'updated') and self.updated is not None:NEWLINE _dict['updated'] = datetime_to_string(self.updated)NEWLINE return _dictNEWLINENEWLINE def __str__(self):NEWLINE """Return a `str` version of this Classifier object."""NEWLINE return json.dumps(self._to_dict(), indent=2)NEWLINENEWLINE def __eq__(self, other):NEWLINE """Return `true` when self and other are equal, false otherwise."""NEWLINE if not isinstance(other, self.__class__):NEWLINE return FalseNEWLINE return self.__dict__ == other.__dict__NEWLINENEWLINE def __ne__(self, other):NEWLINE """Return `true` when self and other are not equal, false otherwise."""NEWLINE return not self == otherNEWLINENEWLINENEWLINEclass ClassifierResult(object):NEWLINE """NEWLINE Classifier and score combination.NEWLINENEWLINE :attr str name: Name of the classifier.NEWLINE :attr str classifier_id: ID of a classifier identified in the image.NEWLINE :attr list[ClassResult] classes: Classes within the classifier.NEWLINE """NEWLINENEWLINE def __init__(self, name, classifier_id, classes):NEWLINE """NEWLINE Initialize a ClassifierResult object.NEWLINENEWLINE :param str name: Name of the classifier.NEWLINE :param str classifier_id: ID of a classifier identified in the image.NEWLINE :param list[ClassResult] classes: Classes within the classifier.NEWLINE """NEWLINE self.name = nameNEWLINE self.classifier_id = classifier_idNEWLINE self.classes = classesNEWLINENEWLINE @classmethodNEWLINE def _from_dict(cls, _dict):NEWLINE """Initialize a ClassifierResult object from a json dictionary."""NEWLINE args = {}NEWLINE if 'name' in _dict:NEWLINE args['name'] = _dict.get('name')NEWLINE else:NEWLINE raise ValueError(NEWLINE 'Required property \'name\' not present in ClassifierResult JSON'NEWLINE )NEWLINE if 'classifier_id' in _dict:NEWLINE args['classifier_id'] = _dict.get('classifier_id')NEWLINE else:NEWLINE raise ValueError(NEWLINE 'Required property \'classifier_id\' not present in ClassifierResult JSON'NEWLINE )NEWLINE if 'classes' in _dict:NEWLINE args['classes'] = [NEWLINE ClassResult._from_dict(x) for x in (_dict.get('classes'))NEWLINE ]NEWLINE else:NEWLINE raise ValueError(NEWLINE 'Required property \'classes\' not present in ClassifierResult JSON'NEWLINE )NEWLINE return cls(**args)NEWLINENEWLINE def _to_dict(self):NEWLINE """Return a json dictionary representing this model."""NEWLINE _dict = {}NEWLINE if hasattr(self, 'name') and self.name is not None:NEWLINE _dict['name'] = self.nameNEWLINE if hasattr(self, 'classifier_id') and self.classifier_id is not None:NEWLINE _dict['classifier_id'] = self.classifier_idNEWLINE if hasattr(self, 'classes') and self.classes is not None:NEWLINE _dict['classes'] = [x._to_dict() for x in self.classes]NEWLINE return _dictNEWLINENEWLINE def __str__(self):NEWLINE """Return a `str` version of this ClassifierResult object."""NEWLINE return json.dumps(self._to_dict(), indent=2)NEWLINENEWLINE def __eq__(self, other):NEWLINE """Return `true` when self and other are equal, false otherwise."""NEWLINE if not isinstance(other, self.__class__):NEWLINE return FalseNEWLINE return self.__dict__ == other.__dict__NEWLINENEWLINE def __ne__(self, other):NEWLINE """Return `true` when self and other are not equal, false otherwise."""NEWLINE return not self == otherNEWLINENEWLINENEWLINEclass Classifiers(object):NEWLINE """NEWLINE A container for the list of classifiers.NEWLINENEWLINE :attr list[Classifier] classifiers: List of classifiers.NEWLINE """NEWLINENEWLINE def __init__(self, classifiers):NEWLINE """NEWLINE Initialize a Classifiers object.NEWLINENEWLINE :param list[Classifier] classifiers: List of classifiers.NEWLINE """NEWLINE self.classifiers = classifiersNEWLINENEWLINE @classmethodNEWLINE def _from_dict(cls, _dict):NEWLINE """Initialize a Classifiers object from a json dictionary."""NEWLINE args = {}NEWLINE if 'classifiers' in _dict:NEWLINE args['classifiers'] = [NEWLINE Classifier._from_dict(x) for x in (_dict.get('classifiers'))NEWLINE ]NEWLINE else:NEWLINE raise ValueError(NEWLINE 'Required property \'classifiers\' not present in Classifiers JSON'NEWLINE )NEWLINE return cls(**args)NEWLINENEWLINE def _to_dict(self):NEWLINE """Return a json dictionary representing this model."""NEWLINE _dict = {}NEWLINE if hasattr(self, 'classifiers') and self.classifiers is not None:NEWLINE _dict['classifiers'] = [x._to_dict() for x in self.classifiers]NEWLINE return _dictNEWLINENEWLINE def __str__(self):NEWLINE """Return a `str` version of this Classifiers object."""NEWLINE return json.dumps(self._to_dict(), indent=2)NEWLINENEWLINE def __eq__(self, other):NEWLINE """Return `true` when self and other are equal, false otherwise."""NEWLINE if not isinstance(other, self.__class__):NEWLINE return FalseNEWLINE return self.__dict__ == other.__dict__NEWLINENEWLINE def __ne__(self, other):NEWLINE """Return `true` when self and other are not equal, false otherwise."""NEWLINE return not self == otherNEWLINENEWLINENEWLINEclass DetectedFaces(object):NEWLINE """NEWLINE Results for all faces.NEWLINENEWLINE :attr int images_processed: Number of images processed for the API call.NEWLINE :attr list[ImageWithFaces] images: The images.NEWLINE :attr list[WarningInfo] warnings: (optional) Information about what might cause lessNEWLINE than optimal output. For example, a request sent with a corrupt .zip file and a listNEWLINE of image URLs will still complete, but does not return the expected output. NotNEWLINE returned when there is no warning.NEWLINE """NEWLINENEWLINE def __init__(self, images_processed, images, warnings=None):NEWLINE """NEWLINE Initialize a DetectedFaces object.NEWLINENEWLINE :param int images_processed: Number of images processed for the API call.NEWLINE :param list[ImageWithFaces] images: The images.NEWLINE :param list[WarningInfo] warnings: (optional) Information about what might causeNEWLINE less than optimal output. For example, a request sent with a corrupt .zip file andNEWLINE a list of image URLs will still complete, but does not return the expected output.NEWLINE Not returned when there is no warning.NEWLINE """NEWLINE self.images_processed = images_processedNEWLINE self.images = imagesNEWLINE self.warnings = warningsNEWLINENEWLINE @classmethodNEWLINE def _from_dict(cls, _dict):NEWLINE """Initialize a DetectedFaces object from a json dictionary."""NEWLINE args = {}NEWLINE if 'images_processed' in _dict:NEWLINE args['images_processed'] = _dict.get('images_processed')NEWLINE else:NEWLINE raise ValueError(NEWLINE 'Required property \'images_processed\' not present in DetectedFaces JSON'NEWLINE )NEWLINE if 'images' in _dict:NEWLINE args['images'] = [NEWLINE ImageWithFaces._from_dict(x) for x in (_dict.get('images'))NEWLINE ]NEWLINE else:NEWLINE raise ValueError(NEWLINE 'Required property \'images\' not present in DetectedFaces JSON'NEWLINE )NEWLINE if 'warnings' in _dict:NEWLINE args['warnings'] = [NEWLINE WarningInfo._from_dict(x) for x in (_dict.get('warnings'))NEWLINE ]NEWLINE return cls(**args)NEWLINENEWLINE def _to_dict(self):NEWLINE """Return a json dictionary representing this model."""NEWLINE _dict = {}NEWLINE if hasattr(self,NEWLINE 'images_processed') and self.images_processed is not None:NEWLINE _dict['images_processed'] = self.images_processedNEWLINE if hasattr(self, 'images') and self.images is not None:NEWLINE _dict['images'] = [x._to_dict() for x in self.images]NEWLINE if hasattr(self, 'warnings') and self.warnings is not None:NEWLINE _dict['warnings'] = [x._to_dict() for x in self.warnings]NEWLINE return _dictNEWLINENEWLINE def __str__(self):NEWLINE """Return a `str` version of this DetectedFaces object."""NEWLINE return json.dumps(self._to_dict(), indent=2)NEWLINENEWLINE def __eq__(self, other):NEWLINE """Return `true` when self and other are equal, false otherwise."""NEWLINE if not isinstance(other, self.__class__):NEWLINE return FalseNEWLINE return self.__dict__ == other.__dict__NEWLINENEWLINE def __ne__(self, other):NEWLINE """Return `true` when self and other are not equal, false otherwise."""NEWLINE return not self == otherNEWLINENEWLINENEWLINEclass ErrorInfo(object):NEWLINE """NEWLINE Information about what might have caused a failure, such as an image that is tooNEWLINE large. Not returned when there is no error.NEWLINENEWLINE :attr int code: HTTP status code.NEWLINE :attr str description: Human-readable error description. For example, `File size limitNEWLINE exceeded`.NEWLINE :attr str error_id: Codified error string. For example, `limit_exceeded`.NEWLINE """NEWLINENEWLINE def __init__(self, code, description, error_id):NEWLINE """NEWLINE Initialize a ErrorInfo object.NEWLINENEWLINE :param int code: HTTP status code.NEWLINE :param str description: Human-readable error description. For example, `File sizeNEWLINE limit exceeded`.NEWLINE :param str error_id: Codified error string. For example, `limit_exceeded`.NEWLINE """NEWLINE self.code = codeNEWLINE self.description = descriptionNEWLINE self.error_id = error_idNEWLINENEWLINE @classmethodNEWLINE def _from_dict(cls, _dict):NEWLINE """Initialize a ErrorInfo object from a json dictionary."""NEWLINE args = {}NEWLINE if 'code' in _dict:NEWLINE args['code'] = _dict.get('code')NEWLINE else:NEWLINE raise ValueError(NEWLINE 'Required property \'code\' not present in ErrorInfo JSON')NEWLINE if 'description' in _dict:NEWLINE args['description'] = _dict.get('description')NEWLINE else:NEWLINE raise ValueError(NEWLINE 'Required property \'description\' not present in ErrorInfo JSON'NEWLINE )NEWLINE if 'error_id' in _dict:NEWLINE args['error_id'] = _dict.get('error_id')NEWLINE else:NEWLINE raise ValueError(NEWLINE 'Required property \'error_id\' not present in ErrorInfo JSON')NEWLINE return cls(**args)NEWLINENEWLINE def _to_dict(self):NEWLINE """Return a json dictionary representing this model."""NEWLINE _dict = {}NEWLINE if hasattr(self, 'code') and self.code is not None:NEWLINE _dict['code'] = self.codeNEWLINE if hasattr(self, 'description') and self.description is not None:NEWLINE _dict['description'] = self.descriptionNEWLINE if hasattr(self, 'error_id') and self.error_id is not None:NEWLINE _dict['error_id'] = self.error_idNEWLINE return _dictNEWLINENEWLINE def __str__(self):NEWLINE """Return a `str` version of this ErrorInfo object."""NEWLINE return json.dumps(self._to_dict(), indent=2)NEWLINENEWLINE def __eq__(self, other):NEWLINE """Return `true` when self and other are equal, false otherwise."""NEWLINE if not isinstance(other, self.__class__):NEWLINE return FalseNEWLINE return self.__dict__ == other.__dict__NEWLINENEWLINE def __ne__(self, other):NEWLINE """Return `true` when self and other are not equal, false otherwise."""NEWLINE return not self == otherNEWLINENEWLINENEWLINEclass Face(object):NEWLINE """NEWLINE Information about the face.NEWLINENEWLINE :attr FaceAge age: (optional) Age information about a face.NEWLINE :attr FaceGender gender: (optional) Information about the gender of the face.NEWLINE :attr FaceLocation face_location: (optional) The location of the bounding box aroundNEWLINE the face.NEWLINE """NEWLINENEWLINE def __init__(self, age=None, gender=None, face_location=None):NEWLINE """NEWLINE Initialize a Face object.NEWLINENEWLINE :param FaceAge age: (optional) Age information about a face.NEWLINE :param FaceGender gender: (optional) Information about the gender of the face.NEWLINE :param FaceLocation face_location: (optional) The location of the bounding boxNEWLINE around the face.NEWLINE """NEWLINE self.age = ageNEWLINE self.gender = genderNEWLINE self.face_location = face_locationNEWLINENEWLINE @classmethodNEWLINE def _from_dict(cls, _dict):NEWLINE """Initialize a Face object from a json dictionary."""NEWLINE args = {}NEWLINE if 'age' in _dict:NEWLINE args['age'] = FaceAge._from_dict(_dict.get('age'))NEWLINE if 'gender' in _dict:NEWLINE args['gender'] = FaceGender._from_dict(_dict.get('gender'))NEWLINE if 'face_location' in _dict:NEWLINE args['face_location'] = FaceLocation._from_dict(NEWLINE _dict.get('face_location'))NEWLINE return cls(**args)NEWLINENEWLINE def _to_dict(self):NEWLINE """Return a json dictionary representing this model."""NEWLINE _dict = {}NEWLINE if hasattr(self, 'age') and self.age is not None:NEWLINE _dict['age'] = self.age._to_dict()NEWLINE if hasattr(self, 'gender') and self.gender is not None:NEWLINE _dict['gender'] = self.gender._to_dict()NEWLINE if hasattr(self, 'face_location') and self.face_location is not None:NEWLINE _dict['face_location'] = self.face_location._to_dict()NEWLINE return _dictNEWLINENEWLINE def __str__(self):NEWLINE """Return a `str` version of this Face object."""NEWLINE return json.dumps(self._to_dict(), indent=2)NEWLINENEWLINE def __eq__(self, other):NEWLINE """Return `true` when self and other are equal, false otherwise."""NEWLINE if not isinstance(other, self.__class__):NEWLINE return FalseNEWLINE return self.__dict__ == other.__dict__NEWLINENEWLINE def __ne__(self, other):NEWLINE """Return `true` when self and other are not equal, false otherwise."""NEWLINE return not self == otherNEWLINENEWLINENEWLINEclass FaceAge(object):NEWLINE """NEWLINE Age information about a face.NEWLINENEWLINE :attr int min: (optional) Estimated minimum age.NEWLINE :attr int max: (optional) Estimated maximum age.NEWLINE :attr float score: Confidence score in the range of 0 to 1. A higher score indicatesNEWLINE greater confidence in the estimated value for the property.NEWLINE """NEWLINENEWLINE def __init__(self, score, min=None, max=None):NEWLINE """NEWLINE Initialize a FaceAge object.NEWLINENEWLINE :param float score: Confidence score in the range of 0 to 1. A higher scoreNEWLINE indicates greater confidence in the estimated value for the property.NEWLINE :param int min: (optional) Estimated minimum age.NEWLINE :param int max: (optional) Estimated maximum age.NEWLINE """NEWLINE self.min = minNEWLINE self.max = maxNEWLINE self.score = scoreNEWLINENEWLINE @classmethodNEWLINE def _from_dict(cls, _dict):NEWLINE """Initialize a FaceAge object from a json dictionary."""NEWLINE args = {}NEWLINE if 'min' in _dict:NEWLINE args['min'] = _dict.get('min')NEWLINE if 'max' in _dict:NEWLINE args['max'] = _dict.get('max')NEWLINE if 'score' in _dict:NEWLINE args['score'] = _dict.get('score')NEWLINE else:NEWLINE raise ValueError(NEWLINE 'Required property \'score\' not present in FaceAge JSON')NEWLINE return cls(**args)NEWLINENEWLINE def _to_dict(self):NEWLINE """Return a json dictionary representing this model."""NEWLINE _dict = {}NEWLINE if hasattr(self, 'min') and self.min is not None:NEWLINE _dict['min'] = self.minNEWLINE if hasattr(self, 'max') and self.max is not None:NEWLINE _dict['max'] = self.maxNEWLINE if hasattr(self, 'score') and self.score is not None:NEWLINE _dict['score'] = self.scoreNEWLINE return _dictNEWLINENEWLINE def __str__(self):NEWLINE """Return a `str` version of this FaceAge object."""NEWLINE return json.dumps(self._to_dict(), indent=2)NEWLINENEWLINE def __eq__(self, other):NEWLINE """Return `true` when self and other are equal, false otherwise."""NEWLINE if not isinstance(other, self.__class__):NEWLINE return FalseNEWLINE return self.__dict__ == other.__dict__NEWLINENEWLINE def __ne__(self, other):NEWLINE """Return `true` when self and other are not equal, false otherwise."""NEWLINE return not self == otherNEWLINENEWLINENEWLINEclass FaceGender(object):NEWLINE """NEWLINE Information about the gender of the face.NEWLINENEWLINE :attr str gender: Gender identified by the face. For example, `MALE` or `FEMALE`.NEWLINE :attr str gender_label: The word for "male" or "female" in the language defined by theNEWLINE **Accept-Language** request header.NEWLINE :attr float score: Confidence score in the range of 0 to 1. A higher score indicatesNEWLINE greater confidence in the estimated value for the property.NEWLINE """NEWLINENEWLINE def __init__(self, gender, gender_label, score):NEWLINE """NEWLINE Initialize a FaceGender object.NEWLINENEWLINE :param str gender: Gender identified by the face. For example, `MALE` or `FEMALE`.NEWLINE :param str gender_label: The word for "male" or "female" in the language definedNEWLINE by the **Accept-Language** request header.NEWLINE :param float score: Confidence score in the range of 0 to 1. A higher scoreNEWLINE indicates greater confidence in the estimated value for the property.NEWLINE """NEWLINE self.gender = genderNEWLINE self.gender_label = gender_labelNEWLINE self.score = scoreNEWLINENEWLINE @classmethodNEWLINE def _from_dict(cls, _dict):NEWLINE """Initialize a FaceGender object from a json dictionary."""NEWLINE args = {}NEWLINE if 'gender' in _dict:NEWLINE args['gender'] = _dict.get('gender')NEWLINE else:NEWLINE raise ValueError(NEWLINE 'Required property \'gender\' not present in FaceGender JSON')NEWLINE if 'gender_label' in _dict:NEWLINE args['gender_label'] = _dict.get('gender_label')NEWLINE else:NEWLINE raise ValueError(NEWLINE 'Required property \'gender_label\' not present in FaceGender JSON'NEWLINE )NEWLINE if 'score' in _dict:NEWLINE args['score'] = _dict.get('score')NEWLINE else:NEWLINE raise ValueError(NEWLINE 'Required property \'score\' not present in FaceGender JSON')NEWLINE return cls(**args)NEWLINENEWLINE def _to_dict(self):NEWLINE """Return a json dictionary representing this model."""NEWLINE _dict = {}NEWLINE if hasattr(self, 'gender') and self.gender is not None:NEWLINE _dict['gender'] = self.genderNEWLINE if hasattr(self, 'gender_label') and self.gender_label is not None:NEWLINE _dict['gender_label'] = self.gender_labelNEWLINE if hasattr(self, 'score') and self.score is not None:NEWLINE _dict['score'] = self.scoreNEWLINE return _dictNEWLINENEWLINE def __str__(self):NEWLINE """Return a `str` version of this FaceGender object."""NEWLINE return json.dumps(self._to_dict(), indent=2)NEWLINENEWLINE def __eq__(self, other):NEWLINE """Return `true` when self and other are equal, false otherwise."""NEWLINE if not isinstance(other, self.__class__):NEWLINE return FalseNEWLINE return self.__dict__ == other.__dict__NEWLINENEWLINE def __ne__(self, other):NEWLINE """Return `true` when self and other are not equal, false otherwise."""NEWLINE return not self == otherNEWLINENEWLINENEWLINEclass FaceLocation(object):NEWLINE """NEWLINE The location of the bounding box around the face.NEWLINENEWLINE :attr float width: Width in pixels of face region.NEWLINE :attr float height: Height in pixels of face region.NEWLINE :attr float left: X-position of top-left pixel of face region.NEWLINE :attr float top: Y-position of top-left pixel of face region.NEWLINE """NEWLINENEWLINE def __init__(self, width, height, left, top):NEWLINE """NEWLINE Initialize a FaceLocation object.NEWLINENEWLINE :param float width: Width in pixels of face region.NEWLINE :param float height: Height in pixels of face region.NEWLINE :param float left: X-position of top-left pixel of face region.NEWLINE :param float top: Y-position of top-left pixel of face region.NEWLINE """NEWLINE self.width = widthNEWLINE self.height = heightNEWLINE self.left = leftNEWLINE self.top = topNEWLINENEWLINE @classmethodNEWLINE def _from_dict(cls, _dict):NEWLINE """Initialize a FaceLocation object from a json dictionary."""NEWLINE args = {}NEWLINE if 'width' in _dict:NEWLINE args['width'] = _dict.get('width')NEWLINE else:NEWLINE raise ValueError(NEWLINE 'Required property \'width\' not present in FaceLocation JSON')NEWLINE if 'height' in _dict:NEWLINE args['height'] = _dict.get('height')NEWLINE else:NEWLINE raise ValueError(NEWLINE 'Required property \'height\' not present in FaceLocation JSON')NEWLINE if 'left' in _dict:NEWLINE args['left'] = _dict.get('left')NEWLINE else:NEWLINE raise ValueError(NEWLINE 'Required property \'left\' not present in FaceLocation JSON')NEWLINE if 'top' in _dict:NEWLINE args['top'] = _dict.get('top')NEWLINE else:NEWLINE raise ValueError(NEWLINE 'Required property \'top\' not present in FaceLocation JSON')NEWLINE return cls(**args)NEWLINENEWLINE def _to_dict(self):NEWLINE """Return a json dictionary representing this model."""NEWLINE _dict = {}NEWLINE if hasattr(self, 'width') and self.width is not None:NEWLINE _dict['width'] = self.widthNEWLINE if hasattr(self, 'height') and self.height is not None:NEWLINE _dict['height'] = self.heightNEWLINE if hasattr(self, 'left') and self.left is not None:NEWLINE _dict['left'] = self.leftNEWLINE if hasattr(self, 'top') and self.top is not None:NEWLINE _dict['top'] = self.topNEWLINE return _dictNEWLINENEWLINE def __str__(self):NEWLINE """Return a `str` version of this FaceLocation object."""NEWLINE return json.dumps(self._to_dict(), indent=2)NEWLINENEWLINE def __eq__(self, other):NEWLINE """Return `true` when self and other are equal, false otherwise."""NEWLINE if not isinstance(other, self.__class__):NEWLINE return FalseNEWLINE return self.__dict__ == other.__dict__NEWLINENEWLINE def __ne__(self, other):NEWLINE """Return `true` when self and other are not equal, false otherwise."""NEWLINE return not self == otherNEWLINENEWLINENEWLINEclass ImageWithFaces(object):NEWLINE """NEWLINE Information about faces in the image.NEWLINENEWLINE :attr list[Face] faces: Faces detected in the images.NEWLINE :attr str image: (optional) Relative path of the image file if uploaded directly. NotNEWLINE returned when the image is passed by URL.NEWLINE :attr str source_url: (optional) Source of the image before any redirects. NotNEWLINE returned when the image is uploaded.NEWLINE :attr str resolved_url: (optional) Fully resolved URL of the image after redirects areNEWLINE followed. Not returned when the image is uploaded.NEWLINE :attr ErrorInfo error: (optional) Information about what might have caused a failure,NEWLINE such as an image that is too large. Not returned when there is no error.NEWLINE """NEWLINENEWLINE def __init__(self,NEWLINE faces,NEWLINE image=None,NEWLINE source_url=None,NEWLINE resolved_url=None,NEWLINE error=None):NEWLINE """NEWLINE Initialize a ImageWithFaces object.NEWLINENEWLINE :param list[Face] faces: Faces detected in the images.NEWLINE :param str image: (optional) Relative path of the image file if uploaded directly.NEWLINE Not returned when the image is passed by URL.NEWLINE :param str source_url: (optional) Source of the image before any redirects. NotNEWLINE returned when the image is uploaded.NEWLINE :param str resolved_url: (optional) Fully resolved URL of the image afterNEWLINE redirects are followed. Not returned when the image is uploaded.NEWLINE :param ErrorInfo error: (optional) Information about what might have caused aNEWLINE failure, such as an image that is too large. Not returned when there is no error.NEWLINE """NEWLINE self.faces = facesNEWLINE self.image = imageNEWLINE self.source_url = source_urlNEWLINE self.resolved_url = resolved_urlNEWLINE self.error = errorNEWLINENEWLINE @classmethodNEWLINE def _from_dict(cls, _dict):NEWLINE """Initialize a ImageWithFaces object from a json dictionary."""NEWLINE args = {}NEWLINE if 'faces' in _dict:NEWLINE args['faces'] = [Face._from_dict(x) for x in (_dict.get('faces'))]NEWLINE else:NEWLINE raise ValueError(NEWLINE 'Required property \'faces\' not present in ImageWithFaces JSON'NEWLINE )NEWLINE if 'image' in _dict:NEWLINE args['image'] = _dict.get('image')NEWLINE if 'source_url' in _dict:NEWLINE args['source_url'] = _dict.get('source_url')NEWLINE if 'resolved_url' in _dict:NEWLINE args['resolved_url'] = _dict.get('resolved_url')NEWLINE if 'error' in _dict:NEWLINE args['error'] = ErrorInfo._from_dict(_dict.get('error'))NEWLINE return cls(**args)NEWLINENEWLINE def _to_dict(self):NEWLINE """Return a json dictionary representing this model."""NEWLINE _dict = {}NEWLINE if hasattr(self, 'faces') and self.faces is not None:NEWLINE _dict['faces'] = [x._to_dict() for x in self.faces]NEWLINE if hasattr(self, 'image') and self.image is not None:NEWLINE _dict['image'] = self.imageNEWLINE if hasattr(self, 'source_url') and self.source_url is not None:NEWLINE _dict['source_url'] = self.source_urlNEWLINE if hasattr(self, 'resolved_url') and self.resolved_url is not None:NEWLINE _dict['resolved_url'] = self.resolved_urlNEWLINE if hasattr(self, 'error') and self.error is not None:NEWLINE _dict['error'] = self.error._to_dict()NEWLINE return _dictNEWLINENEWLINE def __str__(self):NEWLINE """Return a `str` version of this ImageWithFaces object."""NEWLINE return json.dumps(self._to_dict(), indent=2)NEWLINENEWLINE def __eq__(self, other):NEWLINE """Return `true` when self and other are equal, false otherwise."""NEWLINE if not isinstance(other, self.__class__):NEWLINE return FalseNEWLINE return self.__dict__ == other.__dict__NEWLINENEWLINE def __ne__(self, other):NEWLINE """Return `true` when self and other are not equal, false otherwise."""NEWLINE return not self == otherNEWLINENEWLINENEWLINEclass WarningInfo(object):NEWLINE """NEWLINE Information about something that went wrong.NEWLINENEWLINE :attr str warning_id: Codified warning string, such as `limit_reached`.NEWLINE :attr str description: Information about the error.NEWLINE """NEWLINENEWLINE def __init__(self, warning_id, description):NEWLINE """NEWLINE Initialize a WarningInfo object.NEWLINENEWLINE :param str warning_id: Codified warning string, such as `limit_reached`.NEWLINE :param str description: Information about the error.NEWLINE """NEWLINE self.warning_id = warning_idNEWLINE self.description = descriptionNEWLINENEWLINE @classmethodNEWLINE def _from_dict(cls, _dict):NEWLINE """Initialize a WarningInfo object from a json dictionary."""NEWLINE args = {}NEWLINE if 'warning_id' in _dict:NEWLINE args['warning_id'] = _dict.get('warning_id')NEWLINE else:NEWLINE raise ValueError(NEWLINE 'Required property \'warning_id\' not present in WarningInfo JSON'NEWLINE )NEWLINE if 'description' in _dict:NEWLINE args['description'] = _dict.get('description')NEWLINE else:NEWLINE raise ValueError(NEWLINE 'Required property \'description\' not present in WarningInfo JSON'NEWLINE )NEWLINE return cls(**args)NEWLINENEWLINE def _to_dict(self):NEWLINE """Return a json dictionary representing this model."""NEWLINE _dict = {}NEWLINE if hasattr(self, 'warning_id') and self.warning_id is not None:NEWLINE _dict['warning_id'] = self.warning_idNEWLINE if hasattr(self, 'description') and self.description is not None:NEWLINE _dict['description'] = self.descriptionNEWLINE return _dictNEWLINENEWLINE def __str__(self):NEWLINE """Return a `str` version of this WarningInfo object."""NEWLINE return json.dumps(self._to_dict(), indent=2)NEWLINENEWLINE def __eq__(self, other):NEWLINE """Return `true` when self and other are equal, false otherwise."""NEWLINE if not isinstance(other, self.__class__):NEWLINE return FalseNEWLINE return self.__dict__ == other.__dict__NEWLINENEWLINE def __ne__(self, other):NEWLINE """Return `true` when self and other are not equal, false otherwise."""NEWLINE return not self == otherNEWLINE
import httpNEWLINEimport osNEWLINEfrom datetime import datetime, timedeltaNEWLINEfrom pathlib import PathNEWLINEfrom typing import ListNEWLINENEWLINEimport flaskNEWLINEimport sassNEWLINEimport torchNEWLINEfrom flask_sqlalchemy import SQLAlchemyNEWLINEfrom sqlalchemy import funcNEWLINENEWLINEfrom reporter.database.misc import in_jst, in_utcNEWLINEfrom reporter.database.model import GenerationResult, Headline, HumanEvaluationNEWLINEfrom reporter.database.read import (NEWLINE fetch_date_range,NEWLINE fetch_max_t_of_prev_trading_day,NEWLINE fetch_ricsNEWLINE)NEWLINEfrom reporter.predict import PredictorNEWLINEfrom reporter.util.config import ConfigNEWLINEfrom reporter.util.constant import JST, NIKKEI_DATETIME_FORMAT, UTC, CodeNEWLINEfrom reporter.webapp.chart import (NEWLINE fetch_all_closes_fast,NEWLINE fetch_all_points_fast,NEWLINE fetch_close,NEWLINE fetch_pointsNEWLINE)NEWLINEfrom reporter.webapp.human_evaluation import populate_for_human_evaluationNEWLINEfrom reporter.webapp.search import construct_constraint_queryNEWLINEfrom reporter.webapp.table import (NEWLINE Table,NEWLINE create_ric_tables,NEWLINE load_ric_to_ric_infoNEWLINE)NEWLINENEWLINEconfig = Config('config.toml')NEWLINEapp = flask.Flask(__name__)NEWLINEapp.config['TESTING'] = TrueNEWLINEapp.config['SQLALCHEMY_DATABASE_URI'] = config.db_uriNEWLINEapp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = FalseNEWLINEapp.jinja_env.add_extension('pypugjs.ext.jinja.PyPugJSExtension')NEWLINENEWLINEdir_scss = Path('reporter/webapp/static/scss').resolve()NEWLINEdir_css = Path('reporter/webapp/static/css').resolve()NEWLINEsass.compile(dirname=(str(dir_scss), str(dir_css)), output_style='expanded')NEWLINENEWLINEdb = SQLAlchemy(app)NEWLINENEWLINEric_to_ric_info = load_ric_to_ric_info()NEWLINEpopulate_for_human_evaluation(db.session, config.result)NEWLINEdemo_initial_date = config.demo_initial_dateNEWLINENEWLINEdevice = os.environ.get('DEVICE', 'cpu')NEWLINEoutput = os.environ.get('OUTPUT')NEWLINENEWLINEpredictor = Predictor(config, torch.device(device), Path(output)) \NEWLINE if output is not None and Path(output).exists() \NEWLINE else NoneNEWLINENEWLINE# TODO move to some util/misc module?NEWLINEEPOCH = datetime.fromtimestamp(0, tz=UTC)NEWLINENEWLINENEWLINEdef epoch(dt: datetime) -> float:NEWLINE return (dt - EPOCH).total_seconds()NEWLINENEWLINENEWLINEclass EvalTarget:NEWLINE def __init__(self, method_name: str, text: str, is_debug: bool):NEWLINE self.method_name = method_nameNEWLINE self.text = textNEWLINE self.is_debug = is_debugNEWLINENEWLINENEWLINEclass EvalListRow:NEWLINE def __init__(self,NEWLINE article_id: str,NEWLINE jst: str,NEWLINE phase: str,NEWLINE eval_targets: List[EvalTarget],NEWLINE fluency: str,NEWLINE informativeness: str,NEWLINE note: str,NEWLINE is_target: bool,NEWLINE is_finished: bool):NEWLINE self.article_id = article_idNEWLINE self.jst = jstNEWLINE self.phase = phaseNEWLINE self.methods = eval_targetsNEWLINE self.fluency = fluencyNEWLINE self.informativeness = informativenessNEWLINE self.note = noteNEWLINE self.is_target = is_targetNEWLINE self.is_finished = is_finishedNEWLINENEWLINENEWLINEclass DummyPagination:NEWLINE def __init__(self, has_prev: bool, has_next: bool, display_msg: str):NEWLINE self.has_prev = has_prevNEWLINE self.has_next = has_nextNEWLINE self.display_msg = display_msgNEWLINENEWLINENEWLINEdef order_method_names_for_debug(method_names: List[str]) -> List[str]:NEWLINE result = []NEWLINE if 'Gold' in method_names:NEWLINE result.append((0, 'Gold'))NEWLINENEWLINE if 'Base' in method_names:NEWLINE result.append((1, 'Base'))NEWLINENEWLINE for method_name in [m for m in method_names if m not in ['Gold', 'Base']]:NEWLINE result.append((2, method_name))NEWLINENEWLINE return [m for (_, m) in sorted(result)]NEWLINENEWLINENEWLINE@app.route('/')NEWLINEdef index() -> flask.Response:NEWLINE return flask.redirect('/debug', code=http.HTTPStatus.FOUND)NEWLINENEWLINENEWLINEdef list_targets_of_human_evaluation(is_debug: bool) -> flask.Response:NEWLINE args = flask.request.argsNEWLINE page = int(args.get('page', default=1))NEWLINE conditions = []NEWLINE for i in range(5):NEWLINE field = args.get('field' + str(i))NEWLINE relation = args.get('rel' + str(i))NEWLINE val = args.get('val' + str(i))NEWLINE if field is not None and relation is not None and val is not None:NEWLINE constraint = construct_constraint_query(field.strip(), relation.strip(), val.strip())NEWLINE conditions.append(constraint)NEWLINENEWLINE q = db \NEWLINE .session \NEWLINE .query(HumanEvaluation.article_id,NEWLINE HumanEvaluation.ordering,NEWLINE HumanEvaluation.is_target,NEWLINE (func.coalesce(HumanEvaluation.fluency, '')).label('fluency'),NEWLINE (func.coalesce(HumanEvaluation.informativeness, '')).label('informativeness'),NEWLINE (func.coalesce(HumanEvaluation.note, '')).label('note'),NEWLINE Headline.simple_headline.label('gold_result'),NEWLINE Headline.phase,NEWLINE func.to_char(in_jst(Headline.t), 'YYYY-MM-DD HH24:MI').label('jst')) \NEWLINE .outerjoin(Headline,NEWLINE HumanEvaluation.article_id == Headline.article_id) \NEWLINE .filter(Headline.is_used.is_(True), *conditions) \NEWLINE .order_by(Headline.t)NEWLINENEWLINE n_results = q.count()NEWLINE per_page = config.n_items_per_pageNEWLINE articles = []NEWLINE for h in q.limit(per_page).offset((page - 1) * per_page).all():NEWLINE method_names = ['Gold'] if h.ordering is None else h.orderingNEWLINE if is_debug:NEWLINE method_names = order_method_names_for_debug(method_names)NEWLINENEWLINE eval_targets = []NEWLINE for method_name in method_names:NEWLINE res = db \NEWLINE .session \NEWLINE .query(GenerationResult.article_id,NEWLINE GenerationResult.result,NEWLINE GenerationResult.correctness) \NEWLINE .filter(GenerationResult.article_id == h.article_id,NEWLINE GenerationResult.method_name == method_name) \NEWLINE .one_or_none()NEWLINENEWLINE if res is None:NEWLINE et = EvalTarget(method_name, h.gold_result, None) \NEWLINE if method_name == 'Gold' \NEWLINE else EvalTarget(method_name, '', None)NEWLINE else:NEWLINE text = h.gold_result \NEWLINE if method_name == 'Gold' \NEWLINE else res.resultNEWLINE et = EvalTarget(method_name, text, is_debug)NEWLINE eval_targets.append(et)NEWLINENEWLINE is_finished = \NEWLINE len(list(config.result.keys()) + ['Gold']) == \NEWLINE len(h.fluency) > 0 \NEWLINE and len(h.informativeness) > 0NEWLINENEWLINE e = EvalListRow(h.article_id,NEWLINE h.jst,NEWLINE h.phase,NEWLINE eval_targets,NEWLINE h.fluency,NEWLINE h.informativeness,NEWLINE h.note,NEWLINE h.is_target,NEWLINE is_finished)NEWLINE articles.append(e)NEWLINENEWLINE if n_results == 0:NEWLINE display_msg = 'No headline is found'NEWLINE else:NEWLINE offset = (page - 1) * per_page + 1NEWLINE end = offset + per_page - 1 if page < (n_results // per_page) else n_resultsNEWLINE display_msg = 'Displaying {:,} to {:,} of {:,}'.format(offset, end, n_results)NEWLINENEWLINE pagination = DummyPagination(has_prev=page > 1,NEWLINE has_next=page < (n_results // per_page),NEWLINE display_msg=display_msg)NEWLINENEWLINE return flask.render_template('list_human_evaluation.pug',NEWLINE title='debug' if is_debug else 'human-evaluation',NEWLINE condition=conditions,NEWLINE articles=articles,NEWLINE pagination=pagination)NEWLINENEWLINENEWLINEdef article_evaluation(article_id: str,NEWLINE method: str,NEWLINE is_debug: bool) -> flask.Response:NEWLINENEWLINE if method == 'POST':NEWLINENEWLINE h = db \NEWLINE .session \NEWLINE .query(HumanEvaluation) \NEWLINE .filter(HumanEvaluation.article_id == article_id) \NEWLINE .one()NEWLINENEWLINE form = flask.request.formNEWLINE nth = dict([(method_name, i + 1) for (i, method_name) in enumerate(h.ordering)])NEWLINENEWLINE note = form.get('note')NEWLINE h.note = None \NEWLINE if note is None or note.strip() == '' \NEWLINE else noteNEWLINENEWLINE fluency = form.get('fluency')NEWLINE h.fluency = None \NEWLINE if fluency is None or fluency.strip() == '' \NEWLINE else fluencyNEWLINENEWLINE informativeness = form.get('informativeness')NEWLINE h.informativeness = None \NEWLINE if informativeness is None or informativeness.strip() == '' \NEWLINE else informativenessNEWLINENEWLINE r = db \NEWLINE .session \NEWLINE .query(GenerationResult) \NEWLINE .filter(GenerationResult.article_id == article_id,NEWLINE GenerationResult.method_name == 'Base') \NEWLINE .one()NEWLINE r.correctness = form.get('correctness-{}'.format(nth['Base']))NEWLINENEWLINE g = db \NEWLINE .session \NEWLINE .query(GenerationResult) \NEWLINE .filter(GenerationResult.article_id == article_id,NEWLINE GenerationResult.method_name == 'Gold') \NEWLINE .one()NEWLINE g.correctness = form.get('correctness-{}'.format(nth['Gold']))NEWLINENEWLINE e = db \NEWLINE .session \NEWLINE .query(GenerationResult) \NEWLINE .filter(GenerationResult.article_id == article_id,NEWLINE GenerationResult.method_name == 'Ours') \NEWLINE .one()NEWLINE e.correctness = form.get('correctness-{}'.format(nth['Ours']))NEWLINENEWLINE db.session.commit()NEWLINENEWLINE referrer = flask.request.form.get('referrer', '/')NEWLINE return flask.redirect(referrer)NEWLINE else:NEWLINE headline = db \NEWLINE .session \NEWLINE .query(Headline.article_id,NEWLINE Headline.simple_headline.label('gold_result'),NEWLINE Headline.t,NEWLINE func.to_char(in_jst(Headline.t), 'YYYY-MM-DD HH24:MI:SS').label('s_jst')) \NEWLINE .filter(Headline.article_id == article_id) \NEWLINE .one()NEWLINENEWLINE ric_tables = create_ric_tables(db.session, config.rics, ric_to_ric_info, headline.t)NEWLINE group_size = 3NEWLINE while len(ric_tables) % 3 != 0:NEWLINE ric_tables.append(Table('', '', '', [], is_dummy=True))NEWLINE ric_table_groups = [ric_tables[i:i + group_size]NEWLINE for i in range(0, len(ric_tables), group_size)]NEWLINE # It is better to share one procedure with the search,NEWLINE # but we keep this procedure for convenienceNEWLINE target = db \NEWLINE .session \NEWLINE .query(HumanEvaluation) \NEWLINE .filter(HumanEvaluation.article_id == article_id) \NEWLINE .one_or_none()NEWLINENEWLINE targets = []NEWLINE method_names = ['Gold'] if target.ordering is None else target.orderingNEWLINE if is_debug:NEWLINE method_names = order_method_names_for_debug(method_names)NEWLINE d = dict()NEWLINE m = []NEWLINE for method_name in method_names:NEWLINE res = db \NEWLINE .session \NEWLINE .query(GenerationResult.article_id,NEWLINE GenerationResult.result,NEWLINE GenerationResult.correctness) \NEWLINE .filter(GenerationResult.article_id == article_id,NEWLINE GenerationResult.method_name == method_name) \NEWLINE .one_or_none()NEWLINENEWLINE if res is not None:NEWLINE text = headline.gold_result \NEWLINE if method_name == 'Gold' \NEWLINE else res.resultNEWLINE d[method_name] = EvalTarget(method_name, text, is_debug)NEWLINE m.append(method_name)NEWLINENEWLINE note = '' if target.note is None else target.noteNEWLINE fluency = '' if target.fluency is None else target.fluencyNEWLINE informativeness = '' if target.informativeness is None else target.informativenessNEWLINE targets = [(i + 1, d[method_name]) for (i, method_name) in enumerate(m)]NEWLINENEWLINE return flask.render_template('human_evaluation.pug',NEWLINE title='debug' if is_debug else 'human-evaluation',NEWLINE article_id=headline.article_id,NEWLINE timestamp=headline.s_jst + ' JST',NEWLINE targets=targets,NEWLINE fluency=fluency,NEWLINE informativeness=informativeness,NEWLINE note=note,NEWLINE ric_table_groups=ric_table_groups)NEWLINENEWLINENEWLINE@app.route('/data/<string:article_id>')NEWLINEdef data(article_id: str) -> flask.Response:NEWLINENEWLINE headline = db \NEWLINE .session \NEWLINE .query(Headline, in_utc(Headline.t).label('utc')) \NEWLINE .filter(Headline.article_id == article_id) \NEWLINE .one()NEWLINENEWLINE data = []NEWLINE for ric in [Code.N225.value, Code.TOPIX.value]:NEWLINENEWLINE end = headline.utc.replace(tzinfo=UTC)NEWLINE start = datetime(end.year, end.month, end.day, 0, 0, tzinfo=UTC)NEWLINE xs, ys = fetch_points(db.session, ric, start, end)NEWLINENEWLINE end_prev = datetime \NEWLINE .utcfromtimestamp(fetch_max_t_of_prev_trading_day(db.session, ric, end)) \NEWLINE .replace(tzinfo=UTC)NEWLINE start_prev = datetime(end_prev.year, end_prev.month, end_prev.day, 0, 0, tzinfo=UTC)NEWLINE xs_prev, ys_prev = fetch_points(db.session, ric, start_prev, end_prev)NEWLINENEWLINE data.append({NEWLINE 'ric': ric,NEWLINE 'chart': {NEWLINE 'xs': xs,NEWLINE 'ys': ys,NEWLINE 'title': '{} {}'.format(ric, end.strftime('%Y-%m-%d'))NEWLINE },NEWLINE 'chart-prev': {NEWLINE 'xs': xs_prev,NEWLINE 'ys': ys_prev,NEWLINE 'title': '{} {}'.format(ric, end_prev.strftime('%Y-%m-%d'))NEWLINE }NEWLINE })NEWLINENEWLINE return app.response_class(response=flask.json.dumps(data),NEWLINE status=http.HTTPStatus.OK,NEWLINE mimetype='application/json')NEWLINENEWLINENEWLINE@app.route('/human-evaluation')NEWLINEdef human_evaluation() -> flask.Response:NEWLINE return flask.redirect('/human-evaluation/list', code=http.HTTPStatus.FOUND)NEWLINENEWLINENEWLINE@app.route('/debug')NEWLINEdef debug() -> flask.Response:NEWLINE return flask.redirect('/debug/list', code=http.HTTPStatus.FOUND)NEWLINENEWLINENEWLINE@app.route('/<string:page_name>/list')NEWLINEdef list_targets(page_name: str) -> flask.Response:NEWLINE return list_targets_of_human_evaluation(is_debug=page_name == 'debug')NEWLINENEWLINENEWLINE@app.route('/<string:page_name>/article/<string:article_id>', methods=['POST', 'GET'])NEWLINEdef articles(page_name: str, article_id: str) -> flask.Response:NEWLINE return article_evaluation(article_id,NEWLINE flask.request.method,NEWLINE is_debug=page_name == 'debug')NEWLINENEWLINENEWLINE@app.route('/demo')NEWLINEdef demo() -> flask.Response:NEWLINE min_date, max_date = fetch_date_range(db.session)NEWLINE rics = fetch_rics(db.session)NEWLINE return flask.render_template('demo.pug', title='demo',NEWLINE min_date=min_date.timestamp(),NEWLINE max_date=max_date.timestamp(),NEWLINE rics=rics,NEWLINE rics_json=flask.json.dumps(rics),NEWLINE initial_date=flask.json.dumps(demo_initial_date))NEWLINENEWLINENEWLINE@app.route('/data_ts/<string:timestamp>')NEWLINEdef data_ts(timestamp: str) -> flask.Response:NEWLINE start = datetime.fromtimestamp(int(timestamp), JST)NEWLINE one_day = timedelta(days=1)NEWLINE end = start + one_day - timedelta(seconds=1)NEWLINE day_before = start - one_dayNEWLINENEWLINE rics = config.ricsNEWLINENEWLINE # PostgreSQL-specific speedup (raw query)NEWLINE if db.session.bind.dialect.name == 'postgresql':NEWLINE prices = fetch_all_points_fast(db.session, rics, start, end)NEWLINE closes = fetch_all_closes_fast(db.session, rics, day_before, start)NEWLINE else:NEWLINE prices = {}NEWLINE closes = {}NEWLINE for ric in rics:NEWLINE xs, ys = fetch_points(db.session, ric, start, end)NEWLINE prices[ric] = {NEWLINE 'xs': [epoch(x) for x in xs],NEWLINE 'ys': [float(y) if y is not None else None for y in ys],NEWLINE }NEWLINE closes[ric] = fetch_close(db.session, ric, day_before)NEWLINENEWLINE data = {NEWLINE 'start': start.timestamp(),NEWLINE 'end': end.timestamp(),NEWLINE 'prices': prices,NEWLINE 'closes': closes,NEWLINE }NEWLINE return app.response_class(response=flask.json.dumps(data),NEWLINE status=http.HTTPStatus.OK,NEWLINE mimetype='application/json')NEWLINENEWLINENEWLINE@app.route('/predict/<string:ric>/<string:timestamp>')NEWLINEdef predict(ric: str, timestamp: str) -> flask.Response:NEWLINE time = datetime.fromtimestamp(int(timestamp), JST)NEWLINE sentence = predictor.predict(time.strftime(NIKKEI_DATETIME_FORMAT), ric)NEWLINE return app.response_class(response=flask.json.dumps(sentence),NEWLINE status=http.HTTPStatus.OK,NEWLINE mimetype='application/json')NEWLINE
# -*- coding: utf-8 -*-NEWLINENEWLINEfrom __future__ import absolute_importNEWLINENEWLINEimport copyNEWLINEimport contextlibNEWLINEimport threadingNEWLINEimport uuidNEWLINENEWLINEctx = threading.local()NEWLINENEWLINENEWLINEclass TrackerBase(object):NEWLINE def __init__(self, client=None, server=None):NEWLINE self.client = clientNEWLINE self.server = serverNEWLINENEWLINE def handle(self, header):NEWLINE ctx.header = headerNEWLINE ctx.counter = 0NEWLINENEWLINE def gen_header(self, header):NEWLINE header.request_id = self.get_request_id()NEWLINENEWLINE if not hasattr(ctx, "counter"):NEWLINE ctx.counter = 0NEWLINENEWLINE ctx.counter += 1NEWLINENEWLINE if hasattr(ctx, "header"):NEWLINE header.seq = "{prev_seq}.{cur_counter}".format(NEWLINE prev_seq=ctx.header.seq, cur_counter=ctx.counter)NEWLINE header.meta = ctx.header.metaNEWLINE else:NEWLINE header.meta = {}NEWLINE header.seq = str(ctx.counter)NEWLINENEWLINE if hasattr(ctx, "meta"):NEWLINE header.meta.update(ctx.meta)NEWLINENEWLINE def record(self, header, exception):NEWLINE passNEWLINENEWLINE @classmethodNEWLINE @contextlib.contextmanagerNEWLINE def counter(cls, init=0):NEWLINE """Context for manually setting counter of seq number.NEWLINENEWLINE :init: init valueNEWLINE """NEWLINE if not hasattr(ctx, "counter"):NEWLINE ctx.counter = 0NEWLINENEWLINE old = ctx.counterNEWLINE ctx.counter = initNEWLINENEWLINE try:NEWLINE yieldNEWLINE finally:NEWLINE ctx.counter = oldNEWLINENEWLINE @classmethodNEWLINE @contextlib.contextmanagerNEWLINE def annotate(cls, **kwargs):NEWLINE ctx.annotation = kwargsNEWLINE try:NEWLINE yield ctx.annotationNEWLINE finally:NEWLINE del ctx.annotationNEWLINENEWLINE @classmethodNEWLINE @contextlib.contextmanagerNEWLINE def add_meta(cls, **kwds):NEWLINE if hasattr(ctx, 'meta'):NEWLINE old_dict = copy.copy(ctx.meta)NEWLINE ctx.meta.update(kwds)NEWLINE try:NEWLINE yield ctx.metaNEWLINE finally:NEWLINE ctx.meta = old_dictNEWLINE else:NEWLINE ctx.meta = kwdsNEWLINE try:NEWLINE yield ctx.metaNEWLINE finally:NEWLINE del ctx.metaNEWLINENEWLINE @propertyNEWLINE def meta(self):NEWLINE meta = ctx.header.meta if hasattr(ctx, "header") else {}NEWLINE if hasattr(ctx, "meta"):NEWLINE meta.update(ctx.meta)NEWLINE return metaNEWLINENEWLINE @propertyNEWLINE def annotation(self):NEWLINE return ctx.annotation if hasattr(ctx, "annotation") else {}NEWLINENEWLINE def get_request_id(self):NEWLINE if hasattr(ctx, "header"):NEWLINE return ctx.header.request_idNEWLINE return str(uuid.uuid4())NEWLINENEWLINE def init_handshake_info(self, handshake_obj):NEWLINE passNEWLINENEWLINE def handle_handshake_info(self, handshake_obj):NEWLINE passNEWLINENEWLINENEWLINEclass ConsoleTracker(TrackerBase):NEWLINE def record(self, header, exception):NEWLINE print(header)NEWLINE
#!/usr/bin/env pythonNEWLINEimport argparseNEWLINEimport networkx as nxNEWLINEimport numpy as npNEWLINEimport matplotlib as mplNEWLINEimport matplotlib.pyplot as pltNEWLINEfrom matplotlib import rcNEWLINEimport prmfNEWLINEimport prmf.plotNEWLINErc('text', usetex=True)NEWLINENEWLINEDPI = prmf.plot.DPINEWLINEEPSILON = np.finfo(np.float32).epsNEWLINENEWLINEdef project(w, G):NEWLINE inds = []NEWLINE for node in G:NEWLINE inds.append(node)NEWLINE inds = sorted(inds)NEWLINE return w[inds]NEWLINENEWLINEdef manifold_penalty(w, G):NEWLINE L = nx.laplacian_matrix(G).todense()NEWLINE w = project(w, G)NEWLINE return L.dot(w).dot(w)NEWLINENEWLINEdef ignore_penalty(w, G):NEWLINE # node identifiers are indexesNEWLINE rv = 0.0NEWLINE w = project(w, G)NEWLINE for i in range(w.shape[0]):NEWLINE rv += 1 / (w[i] + 1)NEWLINE return rvNEWLINENEWLINEif __name__ == "__main__":NEWLINE parser = argparse.ArgumentParser()NEWLINE parser.add_argument("--outfile")NEWLINE args = parser.parse_args()NEWLINENEWLINE fig = plt.figure()NEWLINE fig = plt.figure(figsize=(1000/DPI, 500/DPI), dpi=DPI)NEWLINENEWLINE gs = mpl.gridspec.GridSpec(1, 5, width_ratios=[1,5,1,1,5])NEWLINE ax1 = plt.subplot(gs[0,0])NEWLINE ax2 = plt.subplot(gs[0,1])NEWLINE #ax3 = plt.subplot(gs[0,2])NEWLINE ax4 = plt.subplot(gs[0,3])NEWLINE ax5 = plt.subplot(gs[0,4])NEWLINENEWLINE # graph defined on 2-NEWLINE order = 7NEWLINE nodelist = list(range(order))NEWLINE G = nx.path_graph(order)NEWLINE G.remove_node(0)NEWLINE G.remove_node(1)NEWLINE #G.add_edge(3,6)NEWLINENEWLINE # no penalty because smoothNEWLINE data1 = np.array([0.8, 0.9, 0.0, 0.0, 0.0, 0.0, 0.0])NEWLINE data1[data1 == 0] = EPSILONNEWLINE vmin = 0.0NEWLINE vmax = 1.0NEWLINE prmf.plot.plot_vec(data1, ax1, aspect=3, vmin=vmin, vmax=vmax)NEWLINENEWLINE man_pen = manifold_penalty(data1, G)[0,0]NEWLINE title1 = "$w^T L w = {:1.3f}$".format(man_pen)NEWLINENEWLINE # introduce penalty term for above dataNEWLINE man_pen = manifold_penalty(data1, G)[0,0]NEWLINE ign_pen = ignore_penalty(data1, G)NEWLINE title2 = r'$w^T L w + \sum_L \frac{1}{w_L + 1} = ' + '{:1.3f}'.format(man_pen + ign_pen) + r'$'NEWLINENEWLINE title = title1 + '\n' + title2NEWLINE pos = prmf.plot.plot_graph(G, ax2, title=title, title_fontsize=24, title_y=1.08)NEWLINE #prmf.plot.plot_graph(G, ax3, pos=pos, title=title)NEWLINENEWLINE # penalty because not smooth on 2-NEWLINE data2 = np.array([0.0, 0.1, 0.8, 0.9, 0.8, 0.9, 0.7])NEWLINE data2[data2 == 0] = EPSILONNEWLINE prmf.plot.plot_vec(data2, ax4, aspect=3, vmin=vmin, vmax=vmax)NEWLINENEWLINE man_pen = manifold_penalty(data2, G)[0,0]NEWLINE ign_pen = ignore_penalty(data2, G)NEWLINE title = r'$w^T L w + \sum_L \frac{1}{w_L + 1} = ' + '{:1.3f}'.format(man_pen + ign_pen) + '$'NEWLINE prmf.plot.plot_graph(G, ax5, pos=pos, title=title, title_fontsize=24, title_y=1.08)NEWLINENEWLINE plt.savefig(args.outfile, bbox_inches='tight')NEWLINE
from hs.entities.cluster_config import ClusterConfigNEWLINEimport pytestNEWLINENEWLINE@pytest.mark.xfailNEWLINEdef test_config_read_failed():NEWLINE d = {NEWLINE 'aaaaa': 'failed'NEWLINE }NEWLINE ClusterConfig.deserialize(d)NEWLINENEWLINEdef test_config_read_successful():NEWLINE d = {NEWLINE "clusters": [NEWLINE {NEWLINE "cluster": {NEWLINE "server": "http://localhost:9090"NEWLINE },NEWLINE "name": "local"NEWLINE }NEWLINE ],NEWLINE "current_cluster": "local",NEWLINE }NEWLINE res = ClusterConfig.parse_obj(d)NEWLINE print(res)NEWLINENEWLINEdef test_config_write_successful():NEWLINE d = {NEWLINE "clusters": [NEWLINE {NEWLINE "cluster": {NEWLINE "server": "http://localhost:9090"NEWLINE },NEWLINE "name": "local"NEWLINE }NEWLINE ],NEWLINE "current-cluster": "local",NEWLINE }NEWLINE res = ClusterConfig.parse_obj(d)NEWLINE dict = res.dict(by_alias=True)NEWLINE print(d, dict, sep="\n")NEWLINE assert d == dict
"""NEWLINEGiven a Singly Linked-List, implement a method to insert a node at a specific position.NEWLINEIf the given position is greater than the list size, simply insert the node at the end.NEWLINENEWLINEExample:NEWLINEGiven 1->2->3,NEWLINENEWLINEinsert_at_pos(data,position) :NEWLINEinsert_at_pos(4,2) ==> 1->4->2->3NEWLINENEWLINE*position=2 means 2nd node in the listNEWLINE"""NEWLINENEWLINENEWLINEclass SinglyLinkedList:NEWLINE # constructorNEWLINE def __init__(self):NEWLINE self.head = NoneNEWLINENEWLINE # method for setting the head of the Linked ListNEWLINE def setHead(self, head):NEWLINE self.head = headNEWLINENEWLINE # Method for inserting a new node at the start of a Linked ListNEWLINE def insert_at_pos(self, data, pos):NEWLINE new_node = Node()NEWLINE new_node.setData(data)NEWLINE if not self.head or pos == 1:NEWLINE new_node.setNext(self.head)NEWLINE self.setHead(new_node)NEWLINE returnNEWLINENEWLINE current = self.headNEWLINE i = 1NEWLINE while current.getNext() != None:NEWLINE if i == pos - 1:NEWLINE new_node.setNext(current.getNext())NEWLINE current.setNext(new_node)NEWLINE returnNEWLINE else:NEWLINE i += 1NEWLINE current = current.getNext()NEWLINE current.setNext(new_node)
#!/usr/bin/env pythonNEWLINENEWLINEfrom setuptools import setupNEWLINENEWLINENEWLINEsetup(name='txTemplate',NEWLINE version='1.0.1',NEWLINE description='Twisted Adapters for Templating Engines',NEWLINE long_description=open("README.rst", "r").read(),NEWLINE author='Mike Steder',NEWLINE author_email='steder@gmail.com',NEWLINE url='http://github.com/steder/txtemplate',NEWLINE packages=['txtemplate',NEWLINE 'txtemplate.test'],NEWLINE test_suite="txtemplate.test",NEWLINE install_requires=["genshi",NEWLINE "jinja2",NEWLINE "twisted"],NEWLINE license="MIT",NEWLINE classifiers=[NEWLINE 'Development Status :: 3 - Alpha',NEWLINE 'Intended Audience :: Developers',NEWLINE 'License :: OSI Approved :: MIT License',NEWLINE 'Programming Language :: Python',NEWLINE ]NEWLINE)NEWLINE
# -*- coding: utf-8 -*-NEWLINE# Generated by Django 1.10.5 on 2017-11-03 13:12NEWLINEfrom __future__ import unicode_literalsNEWLINENEWLINEfrom django.db import migrations, modelsNEWLINENEWLINENEWLINEclass Migration(migrations.Migration):NEWLINENEWLINE dependencies = [NEWLINE ('main', '0003_profile'),NEWLINE ]NEWLINENEWLINE operations = [NEWLINE migrations.AlterField(NEWLINE model_name='medication',NEWLINE name='img_path',NEWLINE field=models.CharField(max_length=200, null=True),NEWLINE ),NEWLINE migrations.AlterField(NEWLINE model_name='medication',NEWLINE name='title',NEWLINE field=models.CharField(max_length=200, unique=True),NEWLINE ),NEWLINE ]NEWLINE
import timeNEWLINEfrom flask import g, requestNEWLINEfrom flask.signals import got_request_exceptionNEWLINEfrom pybrake.utils import loggerNEWLINENEWLINEtry:NEWLINE from flask_login import current_userNEWLINEexcept ImportError:NEWLINE flask_login_imported = FalseNEWLINEelse:NEWLINE flask_login_imported = TrueNEWLINENEWLINEfrom .notifier import NotifierNEWLINENEWLINENEWLINEdef init_app(app):NEWLINE if "pybrake" in app.extensions:NEWLINE raise ValueError("pybrake is already injected")NEWLINE if "PYBRAKE" not in app.config:NEWLINE raise ValueError("app.config['PYBRAKE'] is not defined")NEWLINENEWLINE notifier = Notifier(**app.config["PYBRAKE"])NEWLINENEWLINE app.extensions["pybrake"] = notifierNEWLINE got_request_exception.connect(_handle_exception, sender=app)NEWLINENEWLINE app.before_request(_before_request())NEWLINE app.after_request(_after_request(notifier))NEWLINENEWLINE return appNEWLINENEWLINENEWLINEdef _before_request():NEWLINE def before_request_middleware():NEWLINE g.request_start_time = time.time()NEWLINENEWLINE return before_request_middlewareNEWLINENEWLINENEWLINEdef _after_request(notifier):NEWLINE def after_request_middleware(response):NEWLINE if not hasattr(g, "request_start_time"):NEWLINE logger.error("request_start_time is empty")NEWLINE return responseNEWLINENEWLINE notifier.routes.notify(NEWLINE method=request.method,NEWLINE route=request.url_rule.rule,NEWLINE status_code=response.status_code,NEWLINE start_time=g.request_start_time,NEWLINE end_time=time.time(),NEWLINE )NEWLINENEWLINE return responseNEWLINENEWLINE return after_request_middlewareNEWLINENEWLINENEWLINEdef _handle_exception(sender, exception, **_):NEWLINE notifier = sender.extensions["pybrake"]NEWLINENEWLINE notice = notifier.build_notice(exception)NEWLINE ctx = notice["context"]NEWLINE ctx["method"] = request.methodNEWLINE ctx["url"] = request.urlNEWLINE ctx["route"] = str(request.endpoint)NEWLINENEWLINE try:NEWLINE user_addr = request.access_route[0]NEWLINE except IndexError:NEWLINE user_addr = request.remote_addrNEWLINE if user_addr:NEWLINE ctx["userAddr"] = user_addrNEWLINENEWLINE if flask_login_imported and current_user.is_authenticated:NEWLINE user = dict(id=current_user.get_id())NEWLINE for s in ["username", "name"]:NEWLINE if hasattr(current_user, s):NEWLINE user[s] = getattr(current_user, s)NEWLINE ctx["user"] = userNEWLINENEWLINE notice["params"]["request"] = dict(NEWLINE form=request.form,NEWLINE json=request.json,NEWLINE files=request.files,NEWLINE cookies=request.cookies,NEWLINE headers=dict(request.headers),NEWLINE environ=request.environ,NEWLINE blueprint=request.blueprint,NEWLINE url_rule=request.url_rule,NEWLINE view_args=request.view_args,NEWLINE )NEWLINENEWLINE notifier.send_notice(notice)NEWLINE
# -*- coding: utf-8 -*-NEWLINENEWLINEfrom ..expr import *NEWLINENEWLINEdef_Topic(NEWLINE Title("Riemann zeta function"),NEWLINE Section("Definitions"),NEWLINE Entries(NEWLINE "e0a6a2",NEWLINE ),NEWLINE Section("Illustrations"),NEWLINE Entries(NEWLINE "3131df",NEWLINE ),NEWLINE Section("Dirichlet series"),NEWLINE Entries(NEWLINE "da2fdb", # Dirichlet seriesNEWLINE "1d46d4",NEWLINE ),NEWLINE Section("Euler product"),NEWLINE Entries(NEWLINE "8f5e66", # Euler productNEWLINE ),NEWLINE Section("Laurent series"),NEWLINE Description("Related topic:", TopicReference("Stieltjes constants")),NEWLINE Entries(NEWLINE "b1a2e1",NEWLINE ),NEWLINE Section("Special values"),NEWLINE Entries(NEWLINE "a01b6e", # zeta(2)NEWLINE "e84983", # zeta(3) irrationalNEWLINE "72ccda", # zeta(2n)NEWLINE "51fd98", # zeta(-n)NEWLINE "7cb17f", # table of zeta(2n)NEWLINE "e50a56", # table of zeta(-n)NEWLINE "e93ca8", # table of zeta(n) to 50 digitsNEWLINE ),NEWLINE Section("Analytic properties"),NEWLINE Entries(NEWLINE "8b5ddb", # holomorphic domainNEWLINE "52c4ab", # polesNEWLINE "fdb94b", # essential singularitiesNEWLINE "36a095", # branch pointsNEWLINE "9a258f", # branch cutsNEWLINE ),NEWLINE Section("Zeros"),NEWLINE SeeTopics("Zeros of the Riemann zeta function"),NEWLINE Entries(NEWLINE "669509", # RiemannZetaZeroNEWLINE "c03de4", # RiemannHypothesisNEWLINE "49704a", # RH formulaNEWLINE "2e1ff3", # real zerosNEWLINE "a78abc", # nontrivial zerosNEWLINE "692e42", # complex zerosNEWLINE "cbbf16", # 0 < re < 1NEWLINE "e6ff64", # re = 1/2NEWLINE "60c2ec", # conjugate symmetryNEWLINE "71d9d9", # table of rho_n to 50 digitsNEWLINE ),NEWLINE Section("Complex parts"),NEWLINE Entries(NEWLINE "69348a", # conjugateNEWLINE ),NEWLINE Section("Functional equation"),NEWLINE Entries(NEWLINE "9ee8bc", # functional equationNEWLINE "1a63af",NEWLINE ),NEWLINE Section("Bounds and inequalities"),NEWLINE Entries(NEWLINE "809bc0", # bound in right planeNEWLINE "3a5eb6", # bound in critical stripNEWLINE ),NEWLINE Section("Euler-Maclaurin formula"),NEWLINE Entries(NEWLINE "792f7b", # Euler-Maclaurin formulaNEWLINE ),NEWLINE Section("Approximations"),NEWLINE Entries(NEWLINE "d31b04", # Euler-Maclaurin formulaNEWLINE "e37535", # BorweinNEWLINE ),NEWLINE #Section("Related topics"),NEWLINE #SeeTopics("Gamma function", "Bernoulli number"),NEWLINE)NEWLINENEWLINEdef_Topic(NEWLINE Title("Zeros of the Riemann zeta function"),NEWLINE Entries(NEWLINE "e0a6a2",NEWLINE "669509",NEWLINE "c03de4",NEWLINE ),NEWLINE Section("Main properties"),NEWLINE Description("See also: ", TopicReference("Riemann hypothesis")),NEWLINE Entries(NEWLINE "9fa2a1", # RH formulaNEWLINE "49704a", # RHNEWLINE "2e1ff3", # real zerosNEWLINE "a78abc", # nontrivial zerosNEWLINE "692e42", # complex zerosNEWLINE "cbbf16", # 0 < re < 1NEWLINE "e6ff64", # re = 1/2NEWLINE "60c2ec", # conjugate symmetryNEWLINE ),NEWLINE Section("Numerical values"),NEWLINE Entries(NEWLINE "945fa5", # rho_1 to 50 digitsNEWLINE "c0ae99", # rho_2 to 50 digitsNEWLINE "71d9d9", # table of rho_n to 50 digitsNEWLINE "dc558b", # table of rho_n to 10 digitsNEWLINE "2e1cc7" # table of rho_10^n to 50 digitsNEWLINE ),NEWLINE Section("Related topics"),NEWLINE SeeTopics("Riemann zeta function"),NEWLINE)NEWLINENEWLINEmake_entry(ID("e0a6a2"),NEWLINE SymbolDefinition(RiemannZeta, RiemannZeta(s), "Riemann zeta function"),NEWLINE Description("The Riemann zeta function", RiemannZeta(s), "is a function of one complex variable", s,NEWLINE ". It is a meromorphic function with a pole at", Equal(s, 1), ".",NEWLINE "The following table lists all conditions such that", SourceForm(RiemannZeta(s)), "is defined in Fungrim."),NEWLINE Table(TableRelation(Tuple(P, Q), Implies(P, Q)),NEWLINE TableHeadings(Description("Domain"), Description("Codomain")),NEWLINE List(NEWLINE TableSection("Numbers"),NEWLINE Tuple(Element(s, OpenInterval(1, Infinity)), Element(RiemannZeta(s), OpenInterval(1, Infinity))),NEWLINE Tuple(Element(s, SetMinus(RR, Set(1))), Element(RiemannZeta(s), RR)),NEWLINE Tuple(Element(s, SetMinus(CC, Set(1))), Element(RiemannZeta(s), CC)),NEWLINE TableSection("Infinities"),NEWLINE Tuple(Element(s, Set(1)), Element(RiemannZeta(s), Set(UnsignedInfinity))),NEWLINE Tuple(Element(s, Set(Infinity)), Element(RiemannZeta(s), Set(1))),NEWLINE TableSection("Formal power series"),NEWLINE Tuple(And(Element(s, PowerSeries(RR, x)), NotEqual(SeriesCoefficient(s, x, 0), 1)),NEWLINE Element(RiemannZeta(s), PowerSeries(RR, x))),NEWLINE Tuple(And(Element(s, PowerSeries(CC, x)), NotEqual(SeriesCoefficient(s, x, 0), 1)),NEWLINE Element(RiemannZeta(s), PowerSeries(CC, x))),NEWLINE Tuple(And(Element(s, PowerSeries(RR, x)), NotEqual(s, 1)),NEWLINE Element(RiemannZeta(s), LaurentSeries(RR, x))),NEWLINE Tuple(And(Element(s, PowerSeries(CC, x)), NotEqual(s, 1)),NEWLINE Element(RiemannZeta(s), LaurentSeries(CC, x))),NEWLINE )),NEWLINE )NEWLINENEWLINEmake_entry(ID("669509"),NEWLINE SymbolDefinition(RiemannZetaZero, RiemannZetaZero(n), "Nontrivial zero of the Riemann zeta function"),NEWLINE Table(TableRelation(Tuple(P, Q), Implies(P, Q)),NEWLINE TableHeadings(Description("Domain"), Description("Codomain")),NEWLINE List(NEWLINE Tuple(Element(n, SetMinus(ZZ, Set(0))), Element(RiemannZetaZero(n), CC))NEWLINE )))NEWLINENEWLINEmake_entry(ID("3131df"),NEWLINE Image(Description("X-ray of", RiemannZeta(s), "on", Element(s, ClosedInterval(-22,22) + ClosedInterval(-27,27)*ConstI), "with the critical strip highlighted"),NEWLINE ImageSource("xray_zeta")),NEWLINE description_xray,NEWLINE )NEWLINENEWLINEmake_entry(ID("da2fdb"),NEWLINE Formula(Equal(RiemannZeta(s), Sum(1/k**s, For(k, 1, Infinity)))),NEWLINE Variables(s),NEWLINE Assumptions(And(Element(s, CC), Greater(Re(s), 1))))NEWLINENEWLINEmake_entry(ID("1d46d4"),NEWLINE Formula(Equal(1/RiemannZeta(s), Sum(MoebiusMu(k)/k**s, For(k, 1, Infinity)))),NEWLINE Variables(s),NEWLINE Assumptions(And(Element(s, CC), Greater(Re(s), 1))))NEWLINENEWLINEmake_entry(ID("8f5e66"),NEWLINE Formula(Equal(RiemannZeta(s), PrimeProduct(1/(1-1/p**s), For(p)))),NEWLINE Variables(s),NEWLINE Assumptions(And(Element(s, CC), Greater(Re(s), 1))))NEWLINENEWLINEmake_entry(ID("a01b6e"),NEWLINE Formula(Equal(RiemannZeta(2), Pi**2 / 6)))NEWLINENEWLINEmake_entry(ID("e84983"),NEWLINE Formula(NotElement(RiemannZeta(3), QQ)),NEWLINE References("R. Apéry (1979), Irrationalité de ζ(2) et ζ(3), Astérisque, 61: 11-13."))NEWLINENEWLINEmake_entry(ID("72ccda"),NEWLINE Formula(Equal(RiemannZeta(2*n), (-1)**(n+1) * BernoulliB(2*n) * (2*Pi)**(2*n) / (2 * Factorial(2*n)))),NEWLINE Variables(n),NEWLINE Assumptions(And(Element(n, ZZ), GreaterEqual(n, 1))))NEWLINENEWLINEmake_entry(ID("51fd98"),NEWLINE Formula(Equal(RiemannZeta(-n), (-1)**n * BernoulliB(n+1) / (n+1))),NEWLINE Variables(n),NEWLINE Assumptions(And(Element(n, ZZ), GreaterEqual(n, 0))))NEWLINENEWLINEmake_entry(ID("9ee8bc"),NEWLINE Formula(Equal(RiemannZeta(s), 2 * (2*Pi)**(s-1) * Sin(Pi*s/2) * Gamma(1-s) * RiemannZeta(1-s))),NEWLINE Variables(s),NEWLINE Assumptions(NEWLINE And(Element(s, CC), NotElement(s, ZZGreaterEqual(0))),NEWLINE And(Element(s, PowerSeries(CC, SerX)), NotElement(s, ZZGreaterEqual(0))),NEWLINE ))NEWLINENEWLINEmake_entry(ID("1a63af"),NEWLINE Formula(Equal(RiemannZeta(1-s), (2 * Cos(Div(1,2)*Pi*s)) / (2*Pi)**(s) * Gamma(s) * RiemannZeta(s))),NEWLINE Variables(s),NEWLINE Assumptions(NEWLINE And(Element(s, CC), NotElement(s, ZZLessEqual(1))),NEWLINE And(Element(s, PowerSeries(CC, SerX)), NotElement(s, ZZLessEqual(1))),NEWLINE ))NEWLINENEWLINEmake_entry(ID("7cb17f"),NEWLINE Description("Table of", RiemannZeta(2*n), "for", LessEqual(1, n, 20)),NEWLINE Table(NEWLINE Var(n),NEWLINE # todo: support writing 2n and still parse table?NEWLINE TableValueHeadings(n, RiemannZeta(n)),NEWLINE TableSplit(2),NEWLINE List(NEWLINE Tuple(2, Div(1, 6) * Pi**2),NEWLINE Tuple(4, Div(1, 90) * Pi**4),NEWLINE Tuple(6, Div(1, 945) * Pi**6),NEWLINE Tuple(8, Div(1, 9450) * Pi**8),NEWLINE Tuple(10, Div(1, 93555) * Pi**10),NEWLINE Tuple(12, Div(691, 638512875) * Pi**12),NEWLINE Tuple(14, Div(2, 18243225) * Pi**14),NEWLINE Tuple(16, Div(3617, 325641566250) * Pi**16),NEWLINE Tuple(18, Div(43867, 38979295480125) * Pi**18),NEWLINE Tuple(20, Div(174611, 1531329465290625) * Pi**20),NEWLINE Tuple(22, Div(155366, 13447856940643125) * Pi**22),NEWLINE Tuple(24, Div(236364091, 201919571963756521875) * Pi**24),NEWLINE Tuple(26, Div(1315862, 11094481976030578125) * Pi**26),NEWLINE Tuple(28, Div(6785560294, 564653660170076273671875) * Pi**28),NEWLINE Tuple(30, Div(6892673020804, 5660878804669082674070015625) * Pi**30),NEWLINE Tuple(32, Div(7709321041217, 62490220571022341207266406250) * Pi**32),NEWLINE Tuple(34, Div(151628697551, 12130454581433748587292890625) * Pi**34),NEWLINE Tuple(36, Div(26315271553053477373, 20777977561866588586487628662044921875) * Pi**36),NEWLINE Tuple(38, Div(308420411983322, 2403467618492375776343276883984375) * Pi**38),NEWLINE Tuple(40, Div(261082718496449122051, 20080431172289638826798401128390556640625) * Pi**40))))NEWLINENEWLINEmake_entry(ID("e50a56"),NEWLINE Description("Table of", RiemannZeta(-n), "for", LessEqual(0, n, 30)),NEWLINE Table(NEWLINE Var(n),NEWLINE # todo: support writing -n and still parse table?NEWLINE TableValueHeadings(n, RiemannZeta(n)),NEWLINE TableSplit(3),NEWLINE List(NEWLINE Tuple(0, -Div(1, 2)),NEWLINE Tuple(-1, -Div(1, 12)),NEWLINE Tuple(-2, 0),NEWLINE Tuple(-3, Div(1, 120)),NEWLINE Tuple(-4, 0),NEWLINE Tuple(-5, -Div(1, 252)),NEWLINE Tuple(-6, 0),NEWLINE Tuple(-7, Div(1, 240)),NEWLINE Tuple(-8, 0),NEWLINE Tuple(-9, -Div(1, 132)),NEWLINE Tuple(-10, 0),NEWLINE Tuple(-11, Div(691, 32760)),NEWLINE Tuple(-12, 0),NEWLINE Tuple(-13, -Div(1, 12)),NEWLINE Tuple(-14, 0),NEWLINE Tuple(-15, Div(3617, 8160)),NEWLINE Tuple(-16, 0),NEWLINE Tuple(-17, -Div(43867, 14364)),NEWLINE Tuple(-18, 0),NEWLINE Tuple(-19, Div(174611, 6600)),NEWLINE Tuple(-20, 0),NEWLINE Tuple(-21, -Div(77683, 276)),NEWLINE Tuple(-22, 0),NEWLINE Tuple(-23, Div(236364091, 65520)),NEWLINE Tuple(-24, 0),NEWLINE Tuple(-25, -Div(657931, 12)),NEWLINE Tuple(-26, 0),NEWLINE Tuple(-27, Div(3392780147, 3480)),NEWLINE Tuple(-28, 0),NEWLINE Tuple(-29, -Div(1723168255201, 85932)),NEWLINE Tuple(-30, 0))))NEWLINENEWLINEmake_entry(ID("e93ca8"),NEWLINE Description("Table of", RiemannZeta(n), "to 50 digits for", LessEqual(2, n, 50)),NEWLINE Table(NEWLINE Var(n),NEWLINE # todo: support writing -n and still parse table?NEWLINE TableValueHeadings(n, NearestDecimal(RiemannZeta(n), 50)),NEWLINE TableSplit(1),NEWLINE List(NEWLINE Tuple(2, Decimal("1.6449340668482264364724151666460251892189499012068")),NEWLINE Tuple(3, Decimal("1.2020569031595942853997381615114499907649862923405")),NEWLINE Tuple(4, Decimal("1.0823232337111381915160036965411679027747509519187")),NEWLINE Tuple(5, Decimal("1.0369277551433699263313654864570341680570809195019")),NEWLINE Tuple(6, Decimal("1.0173430619844491397145179297909205279018174900329")),NEWLINE Tuple(7, Decimal("1.0083492773819228268397975498497967595998635605652")),NEWLINE Tuple(8, Decimal("1.0040773561979443393786852385086524652589607906499")),NEWLINE Tuple(9, Decimal("1.0020083928260822144178527692324120604856058513949")),NEWLINE Tuple(10, Decimal("1.0009945751278180853371459589003190170060195315645")),NEWLINE Tuple(11, Decimal("1.0004941886041194645587022825264699364686064357582")),NEWLINE Tuple(12, Decimal("1.0002460865533080482986379980477396709604160884580")),NEWLINE Tuple(13, Decimal("1.0001227133475784891467518365263573957142751058955")),NEWLINE Tuple(14, Decimal("1.0000612481350587048292585451051353337474816961692")),NEWLINE Tuple(15, Decimal("1.0000305882363070204935517285106450625876279487069")),NEWLINE Tuple(16, Decimal("1.0000152822594086518717325714876367220232373889905")),NEWLINE Tuple(17, Decimal("1.0000076371976378997622736002935630292130882490903")),NEWLINE Tuple(18, Decimal("1.0000038172932649998398564616446219397304546972190")),NEWLINE Tuple(19, Decimal("1.0000019082127165539389256569577951013532585711448")),NEWLINE Tuple(20, Decimal("1.0000009539620338727961131520386834493459437941874")),NEWLINE Tuple(21, Decimal("1.0000004769329867878064631167196043730459664466948")),NEWLINE Tuple(22, Decimal("1.0000002384505027277329900036481867529949350418218")),NEWLINE Tuple(23, Decimal("1.0000001192199259653110730677887188823263872549978")),NEWLINE Tuple(24, Decimal("1.0000000596081890512594796124402079358012275039188")),NEWLINE Tuple(25, Decimal("1.0000000298035035146522801860637050693660118447309")),NEWLINE Tuple(26, Decimal("1.0000000149015548283650412346585066306986288647882")),NEWLINE Tuple(27, Decimal("1.0000000074507117898354294919810041706041194547190")),NEWLINE Tuple(28, Decimal("1.0000000037253340247884570548192040184024232328931")),NEWLINE Tuple(29, Decimal("1.0000000018626597235130490064039099454169480616653")),NEWLINE Tuple(30, Decimal("1.0000000009313274324196681828717647350212198135680")),NEWLINE Tuple(31, Decimal("1.0000000004656629065033784072989233251220071062692")),NEWLINE Tuple(32, Decimal("1.0000000002328311833676505492001455975940495024830")),NEWLINE Tuple(33, Decimal("1.0000000001164155017270051977592973835456309516522")),NEWLINE Tuple(34, Decimal("1.0000000000582077208790270088924368598910630541731")),NEWLINE Tuple(35, Decimal("1.0000000000291038504449709968692942522788404641070")),NEWLINE Tuple(36, Decimal("1.0000000000145519218910419842359296322453184209838")),NEWLINE Tuple(37, Decimal("1.0000000000072759598350574810145208690123380592649")),NEWLINE Tuple(38, Decimal("1.0000000000036379795473786511902372363558732735126")),NEWLINE Tuple(39, Decimal("1.0000000000018189896503070659475848321007300850306")),NEWLINE Tuple(40, Decimal("1.0000000000009094947840263889282533118386949087539")),NEWLINE Tuple(41, Decimal("1.0000000000004547473783042154026799112029488570339")),NEWLINE Tuple(42, Decimal("1.0000000000002273736845824652515226821577978691214")),NEWLINE Tuple(43, Decimal("1.0000000000001136868407680227849349104838025906437")),NEWLINE Tuple(44, Decimal("1.0000000000000568434198762758560927718296752406855")),NEWLINE Tuple(45, Decimal("1.0000000000000284217097688930185545507370494266207")),NEWLINE Tuple(46, Decimal("1.0000000000000142108548280316067698343071417395377")),NEWLINE Tuple(47, Decimal("1.0000000000000071054273952108527128773544799568000")),NEWLINE Tuple(48, Decimal("1.0000000000000035527136913371136732984695340593430")),NEWLINE Tuple(49, Decimal("1.0000000000000017763568435791203274733490144002796")),NEWLINE Tuple(50, Decimal("1.0000000000000008881784210930815903096091386391386")))))NEWLINENEWLINENEWLINEmake_entry(ID("809bc0"),NEWLINE Formula(LessEqual(Abs(RiemannZeta(s)), RiemannZeta(Re(s)))),NEWLINE Variables(s),NEWLINE Assumptions(And(Element(s, CC), Greater(Re(s), 1))))NEWLINENEWLINEmake_entry(ID("3a5eb6"),NEWLINE Formula(Less(Abs(RiemannZeta(s)), 3 * Abs((1+s)/(1-s)) * Abs((1+s)/(2*Pi))**((1+eta-Re(s))/2) * RiemannZeta(1+eta))),NEWLINE Variables(s, eta),NEWLINE Assumptions(NEWLINE And(Element(s, CC), Element(eta, RR), NotEqual(s, 1), Element(eta, OpenClosedInterval(0, Div(1,2))), LessEqual(-eta, Re(s), 1 + eta))),NEWLINE References("H. Rademacher, Topics in analytic number theory, Springer, 1973. Equation 43.3."))NEWLINENEWLINEmake_entry(ID("792f7b"),NEWLINE Formula(Equal(RiemannZeta(s),NEWLINE Sum(1/k**s, For(k, 1, N-1)) + N**(1-s)/(s-1) + 1/N**s * (Div(1,2) +NEWLINE Sum((BernoulliB(2*k) / Factorial(2*k)) * (RisingFactorial(s, 2*k-1) / N**(2*k-1)), For(k, 1, M))) -NEWLINE Integral((BernoulliPolynomial(2*M, t - Floor(t)) / Factorial(2 * M)) * (RisingFactorial(s, 2*M) / t**(s+2*M)), For(t, N, Infinity)))),NEWLINE Assumptions(And(Element(s, CC), NotEqual(s, 1), Element(N, ZZ), Element(M, ZZ), Greater(Re(s+2*M-1), 0), GreaterEqual(N, 1), GreaterEqual(M, 1))),NEWLINE Variables(s, N, M),NEWLINE References("""F. Johansson (2015), Rigorous high-precision computation of the Hurwitz zeta function and its derivatives, Numerical Algorithms 69:253, DOI: 10.1007/s11075-014-9893-1""",NEWLINE """F. W. J. Olver, Asymptotics and Special Functions, AK Peters, 1997. Chapter 8."""))NEWLINENEWLINEmake_entry(ID("d31b04"),NEWLINE Formula(LessEqual(Abs(RiemannZeta(s) -NEWLINE Parentheses(Sum(1/k**s, For(k, 1, N-1)) + N**(1-s)/(s-1) + 1/N**s * (Div(1,2) +NEWLINE Sum((BernoulliB(2*k) / Factorial(2*k)) * (RisingFactorial(s, 2*k-1) / N**(2*k-1)), For(k, 1, M))))),NEWLINE (4 * Abs(RisingFactorial(s, 2*M)) / (2*Pi)**(2*M)) * (N**(-Parentheses(Re(s)+2*M-1)) / (Re(s)+2*M-1)))),NEWLINE Assumptions(And(Element(s, CC), NotEqual(s, 1), Element(N, ZZ), Element(M, ZZ), Greater(Re(s+2*M-1), 0), GreaterEqual(N, 1), GreaterEqual(M, 1))),NEWLINE Variables(s, N, M),NEWLINE References("""F. Johansson (2015), Rigorous high-precision computation of the Hurwitz zeta function and its derivatives, Numerical Algorithms 69:253, DOI: 10.1007/s11075-014-9893-1""",NEWLINE """F. W. J. Olver, Asymptotics and Special Functions, AK Peters, 1997. Chapter 8."""))NEWLINENEWLINEmake_entry(ID("e37535"),NEWLINE Formula(Where(NEWLINE LessEqual(Abs((1-2**(1-s))*RiemannZeta(s) - Div(1,d(n)) * Sum(((-1)**k*(d(n)-d(k)))/(k+1)**s, For(k, 0, n-1))),NEWLINE (3*(1 + 2*Abs(Im(s)))/(3+Sqrt(8))**n) * Exp(Abs(Im(s))*Pi/2)),NEWLINE Equal(d(k), n*Sum(Factorial(n+i-1)*4**i/(Factorial(n-i)*Factorial(2*i)), For(i, 0, k))))),NEWLINE Variables(s, n),NEWLINE Assumptions(And(Element(s, CC), GreaterEqual(Re(s), Div(1,2)), NotEqual(s, 1), Element(n, ZZGreaterEqual(1)))),NEWLINE References("P. Borwein. An efficient algorithm for the Riemann zeta function. Canadian Mathematical Society Conference Proceedings, vol. 27, pp. 29-34. 2000.")NEWLINE )NEWLINENEWLINEmake_entry(ID("69348a"),NEWLINE Formula(Equal(RiemannZeta(Conjugate(s)), Conjugate(RiemannZeta(s)))),NEWLINE Variables(s),NEWLINE Assumptions(And(Element(s, CC), NotEqual(s, 1))))NEWLINENEWLINEmake_entry(ID("8b5ddb"),NEWLINE Formula(IsHolomorphic(RiemannZeta(s), ForElement(s, SetMinus(CC, Set(1))))))NEWLINENEWLINEmake_entry(ID("52c4ab"),NEWLINE Formula(Equal(Poles(RiemannZeta(s), ForElement(s, Union(CC, Set(UnsignedInfinity)))), Set(1))))NEWLINENEWLINEmake_entry(ID("fdb94b"),NEWLINE Formula(Equal(EssentialSingularities(RiemannZeta(s), s, Union(CC, Set(UnsignedInfinity))), Set(UnsignedInfinity))))NEWLINENEWLINEmake_entry(ID("36a095"),NEWLINE Formula(Equal(BranchPoints(RiemannZeta(s), s, Union(CC, Set(UnsignedInfinity))), Set())))NEWLINENEWLINEmake_entry(ID("9a258f"),NEWLINE Formula(Equal(BranchCuts(RiemannZeta(s), s, Union(CC)), Set())))NEWLINENEWLINEmake_entry(ID("2e1ff3"),NEWLINE Formula(Equal(Zeros(RiemannZeta(s), ForElement(s, RR)), Set(-(2*n), ForElement(n, ZZGreaterEqual(1))))))NEWLINENEWLINEmake_entry(ID("a78abc"),NEWLINE Formula(Equal(Zeros(RiemannZeta(s), ForElement(s, CC), LessEqual(0, Re(s), 1)), Set(RiemannZetaZero(n), For(n), And(Element(n, ZZ), NotEqual(n, 0))))))NEWLINENEWLINEmake_entry(ID("692e42"),NEWLINE Formula(Equal(Zeros(RiemannZeta(s), ForElement(s, CC)), Union(Set(-(2*n), ForElement(n, ZZGreaterEqual(1))),NEWLINE Set(RiemannZetaZero(n), For(n), And(Element(n, ZZ), NotEqual(n, 0)))))))NEWLINENEWLINEmake_entry(ID("cbbf16"),NEWLINE Formula(Less(0, Re(RiemannZetaZero(n)), 1)),NEWLINE Variables(n),NEWLINE Assumptions(And(Element(n, ZZ), NotEqual(n, 0))))NEWLINENEWLINEmake_entry(ID("60c2ec"),NEWLINE Formula(Equal(RiemannZetaZero(-n), Conjugate(RiemannZetaZero(n)))),NEWLINE Variables(n),NEWLINE Assumptions(And(Element(n, ZZ), NotEqual(n, 0))))NEWLINENEWLINEmake_entry(ID("e6ff64"),NEWLINE Formula(Equal(Re(RiemannZetaZero(n)), Div(1,2))),NEWLINE Variables(n),NEWLINE Assumptions(And(Element(n, ZZ), NotEqual(n, 0), Or(Less(Abs(n), 103800788359), RiemannHypothesis))),NEWLINE References("""D. J. Platt (2016), Isolating some non-trivial zeros of zeta, Mathematics of Computation 86(307):1, DOI: 10.1090/mcom/3198"""))NEWLINENEWLINEmake_entry(ID("945fa5"),NEWLINE Formula(Element(RiemannZetaZero(1),NEWLINE Div(1,2) + RealBall(Decimal("14.134725141734693790457251983562470270784257115699"), Decimal("2.44e-49")) * ConstI)))NEWLINENEWLINEmake_entry(ID("c0ae99"),NEWLINE Formula(Element(RiemannZetaZero(2),NEWLINE Div(1,2) + RealBall(Decimal("21.022039638771554992628479593896902777334340524903"), Decimal("2.19e-49")) * ConstI)))NEWLINENEWLINEmake_entry(ID("dc558b"),NEWLINE Description("Table of", Im(RiemannZetaZero(n)), "to 10 digits for", LessEqual(1, n, 500)),NEWLINE Table(TableRelation(Tuple(n, y), And(Equal(Re(RiemannZetaZero(n)), Div(1,2)), Equal(NearestDecimal(Im(RiemannZetaZero(n)), 10), y))),NEWLINE TableHeadings(n, Im(RiemannZetaZero(n))), TableSplit(5),NEWLINE List(*(NEWLINE Tuple(1, Decimal("14.13472514")),NEWLINE Tuple(2, Decimal("21.02203964")),NEWLINE Tuple(3, Decimal("25.01085758")),NEWLINE Tuple(4, Decimal("30.42487613")),NEWLINE Tuple(5, Decimal("32.93506159")),NEWLINE Tuple(6, Decimal("37.58617816")),NEWLINE Tuple(7, Decimal("40.91871901")),NEWLINE Tuple(8, Decimal("43.32707328")),NEWLINE Tuple(9, Decimal("48.00515088")),NEWLINE Tuple(10, Decimal("49.77383248")),NEWLINE Tuple(11, Decimal("52.97032148")),NEWLINE Tuple(12, Decimal("56.44624770")),NEWLINE Tuple(13, Decimal("59.34704400")),NEWLINE Tuple(14, Decimal("60.83177852")),NEWLINE Tuple(15, Decimal("65.11254405")),NEWLINE Tuple(16, Decimal("67.07981053")),NEWLINE Tuple(17, Decimal("69.54640171")),NEWLINE Tuple(18, Decimal("72.06715767")),NEWLINE Tuple(19, Decimal("75.70469070")),NEWLINE Tuple(20, Decimal("77.14484007")),NEWLINE Tuple(21, Decimal("79.33737502")),NEWLINE Tuple(22, Decimal("82.91038085")),NEWLINE Tuple(23, Decimal("84.73549298")),NEWLINE Tuple(24, Decimal("87.42527461")),NEWLINE Tuple(25, Decimal("88.80911121")),NEWLINE Tuple(26, Decimal("92.49189927")),NEWLINE Tuple(27, Decimal("94.65134404")),NEWLINE Tuple(28, Decimal("95.87063423")),NEWLINE Tuple(29, Decimal("98.83119422")),NEWLINE Tuple(30, Decimal("101.3178510")),NEWLINE Tuple(31, Decimal("103.7255380")),NEWLINE Tuple(32, Decimal("105.4466231")),NEWLINE Tuple(33, Decimal("107.1686112")),NEWLINE Tuple(34, Decimal("111.0295355")),NEWLINE Tuple(35, Decimal("111.8746592")),NEWLINE Tuple(36, Decimal("114.3202209")),NEWLINE Tuple(37, Decimal("116.2266803")),NEWLINE Tuple(38, Decimal("118.7907829")),NEWLINE Tuple(39, Decimal("121.3701250")),NEWLINE Tuple(40, Decimal("122.9468293")),NEWLINE Tuple(41, Decimal("124.2568186")),NEWLINE Tuple(42, Decimal("127.5166839")),NEWLINE Tuple(43, Decimal("129.5787042")),NEWLINE Tuple(44, Decimal("131.0876885")),NEWLINE Tuple(45, Decimal("133.4977372")),NEWLINE Tuple(46, Decimal("134.7565098")),NEWLINE Tuple(47, Decimal("138.1160421")),NEWLINE Tuple(48, Decimal("139.7362090")),NEWLINE Tuple(49, Decimal("141.1237074")),NEWLINE Tuple(50, Decimal("143.1118458")),NEWLINE Tuple(51, Decimal("146.0009825")),NEWLINE Tuple(52, Decimal("147.4227653")),NEWLINE Tuple(53, Decimal("150.0535204")),NEWLINE Tuple(54, Decimal("150.9252576")),NEWLINE Tuple(55, Decimal("153.0246938")),NEWLINE Tuple(56, Decimal("156.1129093")),NEWLINE Tuple(57, Decimal("157.5975918")),NEWLINE Tuple(58, Decimal("158.8499882")),NEWLINE Tuple(59, Decimal("161.1889641")),NEWLINE Tuple(60, Decimal("163.0307097")),NEWLINE Tuple(61, Decimal("165.5370692")),NEWLINE Tuple(62, Decimal("167.1844400")),NEWLINE Tuple(63, Decimal("169.0945154")),NEWLINE Tuple(64, Decimal("169.9119765")),NEWLINE Tuple(65, Decimal("173.4115365")),NEWLINE Tuple(66, Decimal("174.7541915")),NEWLINE Tuple(67, Decimal("176.4414343")),NEWLINE Tuple(68, Decimal("178.3774078")),NEWLINE Tuple(69, Decimal("179.9164840")),NEWLINE Tuple(70, Decimal("182.2070785")),NEWLINE Tuple(71, Decimal("184.8744678")),NEWLINE Tuple(72, Decimal("185.5987837")),NEWLINE Tuple(73, Decimal("187.2289226")),NEWLINE Tuple(74, Decimal("189.4161587")),NEWLINE Tuple(75, Decimal("192.0266564")),NEWLINE Tuple(76, Decimal("193.0797266")),NEWLINE Tuple(77, Decimal("195.2653967")),NEWLINE Tuple(78, Decimal("196.8764818")),NEWLINE Tuple(79, Decimal("198.0153097")),NEWLINE Tuple(80, Decimal("201.2647519")),NEWLINE Tuple(81, Decimal("202.4935945")),NEWLINE Tuple(82, Decimal("204.1896718")),NEWLINE Tuple(83, Decimal("205.3946972")),NEWLINE Tuple(84, Decimal("207.9062589")),NEWLINE Tuple(85, Decimal("209.5765097")),NEWLINE Tuple(86, Decimal("211.6908626")),NEWLINE Tuple(87, Decimal("213.3479194")),NEWLINE Tuple(88, Decimal("214.5470448")),NEWLINE Tuple(89, Decimal("216.1695385")),NEWLINE Tuple(90, Decimal("219.0675963")),NEWLINE Tuple(91, Decimal("220.7149188")),NEWLINE Tuple(92, Decimal("221.4307056")),NEWLINE Tuple(93, Decimal("224.0070003")),NEWLINE Tuple(94, Decimal("224.9833247")),NEWLINE Tuple(95, Decimal("227.4214443")),NEWLINE Tuple(96, Decimal("229.3374133")),NEWLINE Tuple(97, Decimal("231.2501887")),NEWLINE Tuple(98, Decimal("231.9872353")),NEWLINE Tuple(99, Decimal("233.6934042")),NEWLINE Tuple(100, Decimal("236.5242297")),NEWLINE Tuple(101, Decimal("237.7698205")),NEWLINE Tuple(102, Decimal("239.5554776")),NEWLINE Tuple(103, Decimal("241.0491578")),NEWLINE Tuple(104, Decimal("242.8232719")),NEWLINE Tuple(105, Decimal("244.0708985")),NEWLINE Tuple(106, Decimal("247.1369901")),NEWLINE Tuple(107, Decimal("248.1019901")),NEWLINE Tuple(108, Decimal("249.5736896")),NEWLINE Tuple(109, Decimal("251.0149478")),NEWLINE Tuple(110, Decimal("253.0699867")),NEWLINE Tuple(111, Decimal("255.3062565")),NEWLINE Tuple(112, Decimal("256.3807137")),NEWLINE Tuple(113, Decimal("258.6104395")),NEWLINE Tuple(114, Decimal("259.8744070")),NEWLINE Tuple(115, Decimal("260.8050845")),NEWLINE Tuple(116, Decimal("263.5738939")),NEWLINE Tuple(117, Decimal("265.5578518")),NEWLINE Tuple(118, Decimal("266.6149738")),NEWLINE Tuple(119, Decimal("267.9219151")),NEWLINE Tuple(120, Decimal("269.9704490")),NEWLINE Tuple(121, Decimal("271.4940556")),NEWLINE Tuple(122, Decimal("273.4596092")),NEWLINE Tuple(123, Decimal("275.5874926")),NEWLINE Tuple(124, Decimal("276.4520495")),NEWLINE Tuple(125, Decimal("278.2507435")),NEWLINE Tuple(126, Decimal("279.2292509")),NEWLINE Tuple(127, Decimal("282.4651148")),NEWLINE Tuple(128, Decimal("283.2111857")),NEWLINE Tuple(129, Decimal("284.8359640")),NEWLINE Tuple(130, Decimal("286.6674454")),NEWLINE Tuple(131, Decimal("287.9119205")),NEWLINE Tuple(132, Decimal("289.5798549")),NEWLINE Tuple(133, Decimal("291.8462913")),NEWLINE Tuple(134, Decimal("293.5584341")),NEWLINE Tuple(135, Decimal("294.9653696")),NEWLINE Tuple(136, Decimal("295.5732549")),NEWLINE Tuple(137, Decimal("297.9792771")),NEWLINE Tuple(138, Decimal("299.8403261")),NEWLINE Tuple(139, Decimal("301.6493255")),NEWLINE Tuple(140, Decimal("302.6967496")),NEWLINE Tuple(141, Decimal("304.8643713")),NEWLINE Tuple(142, Decimal("305.7289126")),NEWLINE Tuple(143, Decimal("307.2194961")),NEWLINE Tuple(144, Decimal("310.1094631")),NEWLINE Tuple(145, Decimal("311.1651415")),NEWLINE Tuple(146, Decimal("312.4278012")),NEWLINE Tuple(147, Decimal("313.9852857")),NEWLINE Tuple(148, Decimal("315.4756161")),NEWLINE Tuple(149, Decimal("317.7348059")),NEWLINE Tuple(150, Decimal("318.8531043")),NEWLINE Tuple(151, Decimal("321.1601343")),NEWLINE Tuple(152, Decimal("322.1445587")),NEWLINE Tuple(153, Decimal("323.4669696")),NEWLINE Tuple(154, Decimal("324.8628661")),NEWLINE Tuple(155, Decimal("327.4439013")),NEWLINE Tuple(156, Decimal("329.0330717")),NEWLINE Tuple(157, Decimal("329.9532397")),NEWLINE Tuple(158, Decimal("331.4744676")),NEWLINE Tuple(159, Decimal("333.6453785")),NEWLINE Tuple(160, Decimal("334.2113548")),NEWLINE Tuple(161, Decimal("336.8418504")),NEWLINE Tuple(162, Decimal("338.3399929")),NEWLINE Tuple(163, Decimal("339.8582167")),NEWLINE Tuple(164, Decimal("341.0422611")),NEWLINE Tuple(165, Decimal("342.0548775")),NEWLINE Tuple(166, Decimal("344.6617029")),NEWLINE Tuple(167, Decimal("346.3478706")),NEWLINE Tuple(168, Decimal("347.2726776")),NEWLINE Tuple(169, Decimal("349.3162609")),NEWLINE Tuple(170, Decimal("350.4084193")),NEWLINE Tuple(171, Decimal("351.8786490")),NEWLINE Tuple(172, Decimal("353.4889005")),NEWLINE Tuple(173, Decimal("356.0175750")),NEWLINE Tuple(174, Decimal("357.1513023")),NEWLINE Tuple(175, Decimal("357.9526851")),NEWLINE Tuple(176, Decimal("359.7437550")),NEWLINE Tuple(177, Decimal("361.2893617")),NEWLINE Tuple(178, Decimal("363.3313306")),NEWLINE Tuple(179, Decimal("364.7360241")),NEWLINE Tuple(180, Decimal("366.2127103")),NEWLINE Tuple(181, Decimal("367.9935755")),NEWLINE Tuple(182, Decimal("368.9684381")),NEWLINE Tuple(183, Decimal("370.0509192")),NEWLINE Tuple(184, Decimal("373.0619284")),NEWLINE Tuple(185, Decimal("373.8648739")),NEWLINE Tuple(186, Decimal("375.8259128")),NEWLINE Tuple(187, Decimal("376.3240922")),NEWLINE Tuple(188, Decimal("378.4366802")),NEWLINE Tuple(189, Decimal("379.8729753")),NEWLINE Tuple(190, Decimal("381.4844686")),NEWLINE Tuple(191, Decimal("383.4435294")),NEWLINE Tuple(192, Decimal("384.9561168")),NEWLINE Tuple(193, Decimal("385.8613008")),NEWLINE Tuple(194, Decimal("387.2228902")),NEWLINE Tuple(195, Decimal("388.8461284")),NEWLINE Tuple(196, Decimal("391.4560836")),NEWLINE Tuple(197, Decimal("392.2450833")),NEWLINE Tuple(198, Decimal("393.4277438")),NEWLINE Tuple(199, Decimal("395.5828700")),NEWLINE Tuple(200, Decimal("396.3818542")),NEWLINE Tuple(201, Decimal("397.9187362")),NEWLINE Tuple(202, Decimal("399.9851199")),NEWLINE Tuple(203, Decimal("401.8392286")),NEWLINE Tuple(204, Decimal("402.8619178")),NEWLINE Tuple(205, Decimal("404.2364418")),NEWLINE Tuple(206, Decimal("405.1343875")),NEWLINE Tuple(207, Decimal("407.5814604")),NEWLINE Tuple(208, Decimal("408.9472455")),NEWLINE Tuple(209, Decimal("410.5138692")),NEWLINE Tuple(210, Decimal("411.9722678")),NEWLINE Tuple(211, Decimal("413.2627361")),NEWLINE Tuple(212, Decimal("415.0188098")),NEWLINE Tuple(213, Decimal("415.4552150")),NEWLINE Tuple(214, Decimal("418.3877058")),NEWLINE Tuple(215, Decimal("419.8613648")),NEWLINE Tuple(216, Decimal("420.6438276")),NEWLINE Tuple(217, Decimal("422.0767101")),NEWLINE Tuple(218, Decimal("423.7165796")),NEWLINE Tuple(219, Decimal("425.0698825")),NEWLINE Tuple(220, Decimal("427.2088251")),NEWLINE Tuple(221, Decimal("428.1279141")),NEWLINE Tuple(222, Decimal("430.3287454")),NEWLINE Tuple(223, Decimal("431.3013069")),NEWLINE Tuple(224, Decimal("432.1386417")),NEWLINE Tuple(225, Decimal("433.8892185")),NEWLINE Tuple(226, Decimal("436.1610064")),NEWLINE Tuple(227, Decimal("437.5816982")),NEWLINE Tuple(228, Decimal("438.6217387")),NEWLINE Tuple(229, Decimal("439.9184422")),NEWLINE Tuple(230, Decimal("441.6831992")),NEWLINE Tuple(231, Decimal("442.9045463")),NEWLINE Tuple(232, Decimal("444.3193363")),NEWLINE Tuple(233, Decimal("446.8606227")),NEWLINE Tuple(234, Decimal("447.4417042")),NEWLINE Tuple(235, Decimal("449.1485457")),NEWLINE Tuple(236, Decimal("450.1269458")),NEWLINE Tuple(237, Decimal("451.4033084")),NEWLINE Tuple(238, Decimal("453.9867378")),NEWLINE Tuple(239, Decimal("454.9746838")),NEWLINE Tuple(240, Decimal("456.3284267")),NEWLINE Tuple(241, Decimal("457.9038931")),NEWLINE Tuple(242, Decimal("459.5134153")),NEWLINE Tuple(243, Decimal("460.0879444")),NEWLINE Tuple(244, Decimal("462.0653673")),NEWLINE Tuple(245, Decimal("464.0572869")),NEWLINE Tuple(246, Decimal("465.6715392")),NEWLINE Tuple(247, Decimal("466.5702869")),NEWLINE Tuple(248, Decimal("467.4390462")),NEWLINE Tuple(249, Decimal("469.5360046")),NEWLINE Tuple(250, Decimal("470.7736555")),NEWLINE Tuple(251, Decimal("472.7991747")),NEWLINE Tuple(252, Decimal("473.8352323")),NEWLINE Tuple(253, Decimal("475.6003394")),NEWLINE Tuple(254, Decimal("476.7690152")),NEWLINE Tuple(255, Decimal("478.0752638")),NEWLINE Tuple(256, Decimal("478.9421815")),NEWLINE Tuple(257, Decimal("481.8303394")),NEWLINE Tuple(258, Decimal("482.8347828")),NEWLINE Tuple(259, Decimal("483.8514272")),NEWLINE Tuple(260, Decimal("485.5391481")),NEWLINE Tuple(261, Decimal("486.5287183")),NEWLINE Tuple(262, Decimal("488.3805671")),NEWLINE Tuple(263, Decimal("489.6617616")),NEWLINE Tuple(264, Decimal("491.3988216")),NEWLINE Tuple(265, Decimal("493.3144416")),NEWLINE Tuple(266, Decimal("493.9579978")),NEWLINE Tuple(267, Decimal("495.3588288")),NEWLINE Tuple(268, Decimal("496.4296962")),NEWLINE Tuple(269, Decimal("498.5807824")),NEWLINE Tuple(270, Decimal("500.3090849")),NEWLINE Tuple(271, Decimal("501.6044470")),NEWLINE Tuple(272, Decimal("502.2762703")),NEWLINE Tuple(273, Decimal("504.4997733")),NEWLINE Tuple(274, Decimal("505.4152317")),NEWLINE Tuple(275, Decimal("506.4641527")),NEWLINE Tuple(276, Decimal("508.8007003")),NEWLINE Tuple(277, Decimal("510.2642279")),NEWLINE Tuple(278, Decimal("511.5622897")),NEWLINE Tuple(279, Decimal("512.6231445")),NEWLINE Tuple(280, Decimal("513.6689856")),NEWLINE Tuple(281, Decimal("515.4350572")),NEWLINE Tuple(282, Decimal("517.5896686")),NEWLINE Tuple(283, Decimal("518.2342231")),NEWLINE Tuple(284, Decimal("520.1063104")),NEWLINE Tuple(285, Decimal("521.5251934")),NEWLINE Tuple(286, Decimal("522.4566962")),NEWLINE Tuple(287, Decimal("523.9605309")),NEWLINE Tuple(288, Decimal("525.0773857")),NEWLINE Tuple(289, Decimal("527.9036416")),NEWLINE Tuple(290, Decimal("528.4062139")),NEWLINE Tuple(291, Decimal("529.8062263")),NEWLINE Tuple(292, Decimal("530.8669179")),NEWLINE Tuple(293, Decimal("532.6881830")),NEWLINE Tuple(294, Decimal("533.7796308")),NEWLINE Tuple(295, Decimal("535.6643141")),NEWLINE Tuple(296, Decimal("537.0697591")),NEWLINE Tuple(297, Decimal("538.4285262")),NEWLINE Tuple(298, Decimal("540.2131664")),NEWLINE Tuple(299, Decimal("540.6313902")),NEWLINE Tuple(300, Decimal("541.8474371")),NEWLINE Tuple(301, Decimal("544.3238901")),NEWLINE Tuple(302, Decimal("545.6368332")),NEWLINE Tuple(303, Decimal("547.0109121")),NEWLINE Tuple(304, Decimal("547.9316134")),NEWLINE Tuple(305, Decimal("549.4975676")),NEWLINE Tuple(306, Decimal("550.9700100")),NEWLINE Tuple(307, Decimal("552.0495722")),NEWLINE Tuple(308, Decimal("553.7649721")),NEWLINE Tuple(309, Decimal("555.7920206")),NEWLINE Tuple(310, Decimal("556.8994764")),NEWLINE Tuple(311, Decimal("557.5646592")),NEWLINE Tuple(312, Decimal("559.3162370")),NEWLINE Tuple(313, Decimal("560.2408075")),NEWLINE Tuple(314, Decimal("562.5592076")),NEWLINE Tuple(315, Decimal("564.1608791")),NEWLINE Tuple(316, Decimal("564.5060559")),NEWLINE Tuple(317, Decimal("566.6987877")),NEWLINE Tuple(318, Decimal("567.7317579")),NEWLINE Tuple(319, Decimal("568.9239552")),NEWLINE Tuple(320, Decimal("570.0511148")),NEWLINE Tuple(321, Decimal("572.4199841")),NEWLINE Tuple(322, Decimal("573.6146105")),NEWLINE Tuple(323, Decimal("575.0938860")),NEWLINE Tuple(324, Decimal("575.8072471")),NEWLINE Tuple(325, Decimal("577.0390035")),NEWLINE Tuple(326, Decimal("579.0988347")),NEWLINE Tuple(327, Decimal("580.1369594")),NEWLINE Tuple(328, Decimal("581.9465763")),NEWLINE Tuple(329, Decimal("583.2360882")),NEWLINE Tuple(330, Decimal("584.5617059")),NEWLINE Tuple(331, Decimal("585.9845632")),NEWLINE Tuple(332, Decimal("586.7427719")),NEWLINE Tuple(333, Decimal("588.1396633")),NEWLINE Tuple(334, Decimal("590.6603975")),NEWLINE Tuple(335, Decimal("591.7258581")),NEWLINE Tuple(336, Decimal("592.5713583")),NEWLINE Tuple(337, Decimal("593.9747147")),NEWLINE Tuple(338, Decimal("595.7281537")),NEWLINE Tuple(339, Decimal("596.3627683")),NEWLINE Tuple(340, Decimal("598.4930773")),NEWLINE Tuple(341, Decimal("599.5456404")),NEWLINE Tuple(342, Decimal("601.6021367")),NEWLINE Tuple(343, Decimal("602.5791679")),NEWLINE Tuple(344, Decimal("603.6256189")),NEWLINE Tuple(345, Decimal("604.6162185")),NEWLINE Tuple(346, Decimal("606.3834604")),NEWLINE Tuple(347, Decimal("608.4132173")),NEWLINE Tuple(348, Decimal("609.3895752")),NEWLINE Tuple(349, Decimal("610.8391629")),NEWLINE Tuple(350, Decimal("611.7742096")),NEWLINE Tuple(351, Decimal("613.5997787")),NEWLINE Tuple(352, Decimal("614.6462379")),NEWLINE Tuple(353, Decimal("615.5385634")),NEWLINE Tuple(354, Decimal("618.1128314")),NEWLINE Tuple(355, Decimal("619.1844826")),NEWLINE Tuple(356, Decimal("620.2728937")),NEWLINE Tuple(357, Decimal("621.7092945")),NEWLINE Tuple(358, Decimal("622.3750027")),NEWLINE Tuple(359, Decimal("624.2699000")),NEWLINE Tuple(360, Decimal("626.0192834")),NEWLINE Tuple(361, Decimal("627.2683969")),NEWLINE Tuple(362, Decimal("628.3258624")),NEWLINE Tuple(363, Decimal("630.4738874")),NEWLINE Tuple(364, Decimal("630.8057809")),NEWLINE Tuple(365, Decimal("632.2251412")),NEWLINE Tuple(366, Decimal("633.5468583")),NEWLINE Tuple(367, Decimal("635.5238003")),NEWLINE Tuple(368, Decimal("637.3971932")),NEWLINE Tuple(369, Decimal("637.9255140")),NEWLINE Tuple(370, Decimal("638.9279383")),NEWLINE Tuple(371, Decimal("640.6947947")),NEWLINE Tuple(372, Decimal("641.9454997")),NEWLINE Tuple(373, Decimal("643.2788838")),NEWLINE Tuple(374, Decimal("644.9905782")),NEWLINE Tuple(375, Decimal("646.3481916")),NEWLINE Tuple(376, Decimal("647.7617530")),NEWLINE Tuple(377, Decimal("648.7864009")),NEWLINE Tuple(378, Decimal("650.1975193")),NEWLINE Tuple(379, Decimal("650.6686839")),NEWLINE Tuple(380, Decimal("653.6495716")),NEWLINE Tuple(381, Decimal("654.3019206")),NEWLINE Tuple(382, Decimal("655.7094630")),NEWLINE Tuple(383, Decimal("656.9640846")),NEWLINE Tuple(384, Decimal("658.1756144")),NEWLINE Tuple(385, Decimal("659.6638460")),NEWLINE Tuple(386, Decimal("660.7167326")),NEWLINE Tuple(387, Decimal("662.2965864")),NEWLINE Tuple(388, Decimal("664.2446047")),NEWLINE Tuple(389, Decimal("665.3427631")),NEWLINE Tuple(390, Decimal("666.5151477")),NEWLINE Tuple(391, Decimal("667.1484949")),NEWLINE Tuple(392, Decimal("668.9758488")),NEWLINE Tuple(393, Decimal("670.3235852")),NEWLINE Tuple(394, Decimal("672.4581836")),NEWLINE Tuple(395, Decimal("673.0435783")),NEWLINE Tuple(396, Decimal("674.3558978")),NEWLINE Tuple(397, Decimal("676.1396744")),NEWLINE Tuple(398, Decimal("677.2301807")),NEWLINE Tuple(399, Decimal("677.8004447")),NEWLINE Tuple(400, Decimal("679.7421979")),NEWLINE Tuple(401, Decimal("681.8949915")),NEWLINE Tuple(402, Decimal("682.6027350")),NEWLINE Tuple(403, Decimal("684.0135498")),NEWLINE Tuple(404, Decimal("684.9726299")),NEWLINE Tuple(405, Decimal("686.1632236")),NEWLINE Tuple(406, Decimal("687.9615432")),NEWLINE Tuple(407, Decimal("689.3689414")),NEWLINE Tuple(408, Decimal("690.4747350")),NEWLINE Tuple(409, Decimal("692.4516844")),NEWLINE Tuple(410, Decimal("693.1769701")),NEWLINE Tuple(411, Decimal("694.5339087")),NEWLINE Tuple(412, Decimal("695.7263359")),NEWLINE Tuple(413, Decimal("696.6260699")),NEWLINE Tuple(414, Decimal("699.1320955")),NEWLINE Tuple(415, Decimal("700.2967391")),NEWLINE Tuple(416, Decimal("701.3017430")),NEWLINE Tuple(417, Decimal("702.2273431")),NEWLINE Tuple(418, Decimal("704.0338393")),NEWLINE Tuple(419, Decimal("705.1258140")),NEWLINE Tuple(420, Decimal("706.1846548")),NEWLINE Tuple(421, Decimal("708.2690709")),NEWLINE Tuple(422, Decimal("709.2295886")),NEWLINE Tuple(423, Decimal("711.1302742")),NEWLINE Tuple(424, Decimal("711.9002899")),NEWLINE Tuple(425, Decimal("712.7493835")),NEWLINE Tuple(426, Decimal("714.0827718")),NEWLINE Tuple(427, Decimal("716.1123965")),NEWLINE Tuple(428, Decimal("717.4825697")),NEWLINE Tuple(429, Decimal("718.7427865")),NEWLINE Tuple(430, Decimal("719.6971010")),NEWLINE Tuple(431, Decimal("721.3511622")),NEWLINE Tuple(432, Decimal("722.2775050")),NEWLINE Tuple(433, Decimal("723.8458210")),NEWLINE Tuple(434, Decimal("724.5626139")),NEWLINE Tuple(435, Decimal("727.0564032")),NEWLINE Tuple(436, Decimal("728.4054816")),NEWLINE Tuple(437, Decimal("728.7587498")),NEWLINE Tuple(438, Decimal("730.4164821")),NEWLINE Tuple(439, Decimal("731.4173549")),NEWLINE Tuple(440, Decimal("732.8180527")),NEWLINE Tuple(441, Decimal("734.7896433")),NEWLINE Tuple(442, Decimal("735.7654592")),NEWLINE Tuple(443, Decimal("737.0529289")),NEWLINE Tuple(444, Decimal("738.5804212")),NEWLINE Tuple(445, Decimal("739.9095237")),NEWLINE Tuple(446, Decimal("740.5738074")),NEWLINE Tuple(447, Decimal("741.7573356")),NEWLINE Tuple(448, Decimal("743.8950131")),NEWLINE Tuple(449, Decimal("745.3449896")),NEWLINE Tuple(450, Decimal("746.4993059")),NEWLINE Tuple(451, Decimal("747.6745636")),NEWLINE Tuple(452, Decimal("748.2427545")),NEWLINE Tuple(453, Decimal("750.6559504")),NEWLINE Tuple(454, Decimal("750.9663811")),NEWLINE Tuple(455, Decimal("752.8876216")),NEWLINE Tuple(456, Decimal("754.3223705")),NEWLINE Tuple(457, Decimal("755.8393090")),NEWLINE Tuple(458, Decimal("756.7682484")),NEWLINE Tuple(459, Decimal("758.1017292")),NEWLINE Tuple(460, Decimal("758.9002382")),NEWLINE Tuple(461, Decimal("760.2823670")),NEWLINE Tuple(462, Decimal("762.7000332")),NEWLINE Tuple(463, Decimal("763.5930662")),NEWLINE Tuple(464, Decimal("764.3075227")),NEWLINE Tuple(465, Decimal("766.0875401")),NEWLINE Tuple(466, Decimal("767.2184722")),NEWLINE Tuple(467, Decimal("768.2814618")),NEWLINE Tuple(468, Decimal("769.6934073")),NEWLINE Tuple(469, Decimal("771.0708393")),NEWLINE Tuple(470, Decimal("772.9616176")),NEWLINE Tuple(471, Decimal("774.1177446")),NEWLINE Tuple(472, Decimal("775.0478471")),NEWLINE Tuple(473, Decimal("775.9997120")),NEWLINE Tuple(474, Decimal("777.2997485")),NEWLINE Tuple(475, Decimal("779.1570769")),NEWLINE Tuple(476, Decimal("780.3489250")),NEWLINE Tuple(477, Decimal("782.1376644")),NEWLINE Tuple(478, Decimal("782.5979439")),NEWLINE Tuple(479, Decimal("784.2888226")),NEWLINE Tuple(480, Decimal("785.7390897")),NEWLINE Tuple(481, Decimal("786.4611475")),NEWLINE Tuple(482, Decimal("787.4684638")),NEWLINE Tuple(483, Decimal("790.0590924")),NEWLINE Tuple(484, Decimal("790.8316205")),NEWLINE Tuple(485, Decimal("792.4277076")),NEWLINE Tuple(486, Decimal("792.8886526")),NEWLINE Tuple(487, Decimal("794.4837919")),NEWLINE Tuple(488, Decimal("795.6065962")),NEWLINE Tuple(489, Decimal("797.2634700")),NEWLINE Tuple(490, Decimal("798.7075702")),NEWLINE Tuple(491, Decimal("799.6543362")),NEWLINE Tuple(492, Decimal("801.6042465")),NEWLINE Tuple(493, Decimal("802.5419849")),NEWLINE Tuple(494, Decimal("803.2430962")),NEWLINE Tuple(495, Decimal("804.7622391")),NEWLINE Tuple(496, Decimal("805.8616357")),NEWLINE Tuple(497, Decimal("808.1518149")),NEWLINE Tuple(498, Decimal("809.1977834")),NEWLINE Tuple(499, Decimal("810.0818049")),NEWLINE Tuple(500, Decimal("811.1843588"))))))NEWLINENEWLINENEWLINEmake_entry(ID("2e1cc7"),NEWLINE Description("Table of", Im(RiemannZetaZero(10**n)), "to 50 digits for", LessEqual(0, n, 16)),NEWLINE Table(NEWLINE Var(n),NEWLINE TableValueHeadings(n, NearestDecimal(Im(RiemannZetaZero(10**n)), 50)),NEWLINE TableSplit(1),NEWLINE List(NEWLINE Tuple(0, Decimal("14.134725141734693790457251983562470270784257115699")),NEWLINE Tuple(1, Decimal("49.773832477672302181916784678563724057723178299677")),NEWLINE Tuple(2, Decimal("236.52422966581620580247550795566297868952949521219")),NEWLINE Tuple(3, Decimal("1419.4224809459956864659890380799168192321006010642")),NEWLINE Tuple(4, Decimal("9877.7826540055011427740990706901235776224680517811")),NEWLINE Tuple(5, Decimal("74920.827498994186793849200946918346620223555216802")),NEWLINE Tuple(6, Decimal("600269.67701244495552123391427049074396819125790619")),NEWLINE Tuple(7, Decimal("4992381.0140031786660182508391600932712387635814368")),NEWLINE Tuple(8, Decimal("42653549.760951553903050309232819667982595130452178")),NEWLINE Tuple(9, Decimal("371870203.83702805273405479598662519100082698522485")),NEWLINE Tuple(10, Decimal("3293531632.3971367042089917031338769677069644102625")),NEWLINE Tuple(11, Decimal("29538618431.613072810689561192671546108506486777642")),NEWLINE Tuple(12, Decimal("267653395648.62594824214264940920070899588029633790")),NEWLINE Tuple(13, Decimal("2445999556030.2468813938032396773514175248139258741")),NEWLINE Tuple(14, Decimal("22514484222485.729124253904444090280880182979014905")),NEWLINE Tuple(15, Decimal("208514052006405.46942460229754774510609948399247941")),NEWLINE Tuple(16, Decimal("1941393531395154.7112809113883108073327538053720311")))))NEWLINENEWLINEmake_entry(ID("71d9d9"),NEWLINE Description("Table of", Im(RiemannZetaZero(n)), "to 50 digits for", LessEqual(1, n, 50)),NEWLINE Table(NEWLINE Var(n),NEWLINE TableValueHeadings(n, NearestDecimal(Im(RiemannZetaZero(n)), 50)),NEWLINE TableSplit(1),NEWLINE List(NEWLINE Tuple(1, Decimal("14.134725141734693790457251983562470270784257115699")),NEWLINE Tuple(2, Decimal("21.022039638771554992628479593896902777334340524903")),NEWLINE Tuple(3, Decimal("25.010857580145688763213790992562821818659549672558")),NEWLINE Tuple(4, Decimal("30.424876125859513210311897530584091320181560023715")),NEWLINE Tuple(5, Decimal("32.935061587739189690662368964074903488812715603517")),NEWLINE Tuple(6, Decimal("37.586178158825671257217763480705332821405597350831")),NEWLINE Tuple(7, Decimal("40.918719012147495187398126914633254395726165962777")),NEWLINE Tuple(8, Decimal("43.327073280914999519496122165406805782645668371837")),NEWLINE Tuple(9, Decimal("48.005150881167159727942472749427516041686844001144")),NEWLINE Tuple(10, Decimal("49.773832477672302181916784678563724057723178299677")),NEWLINE Tuple(11, Decimal("52.970321477714460644147296608880990063825017888821")),NEWLINE Tuple(12, Decimal("56.446247697063394804367759476706127552782264471717")),NEWLINE Tuple(13, Decimal("59.347044002602353079653648674992219031098772806467")),NEWLINE Tuple(14, Decimal("60.831778524609809844259901824524003802910090451219")),NEWLINE Tuple(15, Decimal("65.112544048081606660875054253183705029348149295167")),NEWLINE Tuple(16, Decimal("67.079810529494173714478828896522216770107144951746")),NEWLINE Tuple(17, Decimal("69.546401711173979252926857526554738443012474209603")),NEWLINE Tuple(18, Decimal("72.067157674481907582522107969826168390480906621457")),NEWLINE Tuple(19, Decimal("75.704690699083933168326916762030345922811903530697")),NEWLINE Tuple(20, Decimal("77.144840068874805372682664856304637015796032449234")),NEWLINE Tuple(21, Decimal("79.337375020249367922763592877116228190613246743120")),NEWLINE Tuple(22, Decimal("82.910380854086030183164837494770609497508880593782")),NEWLINE Tuple(23, Decimal("84.735492980517050105735311206827741417106627934241")),NEWLINE Tuple(24, Decimal("87.425274613125229406531667850919213252171886401269")),NEWLINE Tuple(25, Decimal("88.809111207634465423682348079509378395444893409819")),NEWLINE Tuple(26, Decimal("92.491899270558484296259725241810684878721794027731")),NEWLINE Tuple(27, Decimal("94.651344040519886966597925815208153937728027015655")),NEWLINE Tuple(28, Decimal("95.870634228245309758741029219246781695256461224988")),NEWLINE Tuple(29, Decimal("98.831194218193692233324420138622327820658039063428")),NEWLINE Tuple(30, Decimal("101.31785100573139122878544794029230890633286638430")),NEWLINE Tuple(31, Decimal("103.72553804047833941639840810869528083448117306950")),NEWLINE Tuple(32, Decimal("105.44662305232609449367083241411180899728275392854")),NEWLINE Tuple(33, Decimal("107.16861118427640751512335196308619121347670788140")),NEWLINE Tuple(34, Decimal("111.02953554316967452465645030994435041534596839007")),NEWLINE Tuple(35, Decimal("111.87465917699263708561207871677059496031174987339")),NEWLINE Tuple(36, Decimal("114.32022091545271276589093727619107980991765772383")),NEWLINE Tuple(37, Decimal("116.22668032085755438216080431206475512732985123238")),NEWLINE Tuple(38, Decimal("118.79078286597621732297913970269982434730621059281")),NEWLINE Tuple(39, Decimal("121.37012500242064591894553297049992272300131063173")),NEWLINE Tuple(40, Decimal("122.94682929355258820081746033077001649621438987386")),NEWLINE Tuple(41, Decimal("124.25681855434576718473200796612992444157353877469")),NEWLINE Tuple(42, Decimal("127.51668387959649512427932376690607626808830988155")),NEWLINE Tuple(43, Decimal("129.57870419995605098576803390617997360864095326466")),NEWLINE Tuple(44, Decimal("131.08768853093265672356637246150134905920354750298")),NEWLINE Tuple(45, Decimal("133.49773720299758645013049204264060766497417494390")),NEWLINE Tuple(46, Decimal("134.75650975337387133132606415716973617839606861365")),NEWLINE Tuple(47, Decimal("138.11604205453344320019155519028244785983527462415")),NEWLINE Tuple(48, Decimal("139.73620895212138895045004652338246084679005256538")),NEWLINE Tuple(49, Decimal("141.12370740402112376194035381847535509030066087975")),NEWLINE Tuple(50, Decimal("143.11184580762063273940512386891392996623310243035")))))NEWLINENEWLINEdef_Topic(NEWLINE Title("Riemann hypothesis"),NEWLINE Section("Definitions"),NEWLINE Entries(NEWLINE "c03de4",NEWLINE ),NEWLINE Section("Formal statement"),NEWLINE Description("Related topics:",NEWLINE TopicReference("Riemann zeta function"), ",",NEWLINE TopicReference("Zeros of the Riemann zeta function"),NEWLINE ),NEWLINE Entries(NEWLINE "9fa2a1",NEWLINE "49704a",NEWLINE ),NEWLINE Section("Statements equivalent to the Riemann hypothesis"),NEWLINE Subsection("Prime counting function"),NEWLINE Description("Related topic:",NEWLINE TopicReference("Prime numbers"),NEWLINE ),NEWLINE Entries(NEWLINE "bfaeb5",NEWLINE ),NEWLINE Subsection("Robin's criterion"),NEWLINE Entries(NEWLINE "3142ec",NEWLINE "e4287f",NEWLINE ),NEWLINE Subsection("Li's criterion"),NEWLINE Description("Related topic:", TopicReference("Keiper-Li coefficients")),NEWLINE Entries(NEWLINE "e68f82",NEWLINE "a5d65f",NEWLINE ),NEWLINE Subsection("Landau's function"),NEWLINE Description("Related topic:", TopicReference("Landau's function")),NEWLINE Entries(NEWLINE "65fa9f", # included from landau's functionNEWLINE ),NEWLINE Subsection("Definite integrals"),NEWLINE Entries(NEWLINE "7783f9",NEWLINE "cf70ce",NEWLINE ),NEWLINE Subsection("De Bruijn-Newman constant"),NEWLINE Entries(NEWLINE "22ab47",NEWLINE "a71ddd",NEWLINE ),NEWLINE Section("Formulas conditional on the Riemann hypothesis"),NEWLINE Entries(NEWLINE "e6ff64",NEWLINE "375afe",NEWLINE ),NEWLINE Section("Generalizations"),NEWLINE Description("Related topic:",NEWLINE TopicReference("Dirichlet L-functions"),NEWLINE ),NEWLINE Entries(NEWLINE "dc593e",NEWLINE "e2a734",NEWLINE ),NEWLINE)NEWLINENEWLINEmake_entry(ID("c03de4"),NEWLINE SymbolDefinition(RiemannHypothesis, RiemannHypothesis, "Riemann hypothesis"),NEWLINE Description("Represents the truth value of the Riemann hypothesis, defined in ", EntryReference("49704a"), "."),NEWLINE Description("Semantically, ", Element(RiemannHypothesis, Set(True_, False_)), "."),NEWLINE Description("This symbol can be used in an assumption to express that a formula is valid conditionally on the truth of the Riemann hypothesis."))NEWLINENEWLINEmake_entry(ID("9fa2a1"),NEWLINE Formula(Equivalent(RiemannHypothesis, All(Equal(Re(s), Div(1,2)), ForElement(s, CC), And(LessEqual(0, Re(s), 1), Equal(RiemannZeta(s), 0))))))NEWLINENEWLINEmake_entry(ID("49704a"),NEWLINE Formula(Equivalent(RiemannHypothesis, All(Equal(Re(RiemannZetaZero(n)), Div(1,2)), ForElement(n, ZZGreaterEqual(1))))))NEWLINENEWLINEmake_entry(ID("bfaeb5"),NEWLINE Formula(Equivalent(RiemannHypothesis, All(Less(Abs(PrimePi(x) - LogIntegral(x)), Sqrt(x) * Log(x)), ForElement(x, ClosedOpenInterval(2, Infinity))))),NEWLINE References("https://mathoverflow.net/q/338066"))NEWLINENEWLINEmake_entry(ID("3142ec"),NEWLINE Formula(Equivalent(RiemannHypothesis, All(Less(DivisorSigma(1,n), Exp(ConstGamma) * n*Log(Log(n))), ForElement(n, ZZGreaterEqual(5041))))))NEWLINENEWLINEmake_entry(ID("e4287f"),NEWLINE Formula(Equivalent(RiemannHypothesis, All(Less(DivisorSigma(1,n), HarmonicNumber(n) + Exp(HarmonicNumber(n)) * Log(HarmonicNumber(n))), ForElement(n, ZZGreaterEqual(2))))),NEWLINE References("https://doi.org/10.2307/2695443"))NEWLINENEWLINEmake_entry(ID("22ab47"),NEWLINE SymbolDefinition(DeBruijnNewmanLambda, DeBruijnNewmanLambda, "De Bruijn-Newman constant"))NEWLINENEWLINEmake_entry(ID("a71ddd"),NEWLINE Formula(Equivalent(RiemannHypothesis, Equal(DeBruijnNewmanLambda, 0))),NEWLINE References("https://arxiv.org/abs/1801.05914"))NEWLINENEWLINEmake_entry(ID("7783f9"),NEWLINE Formula(Equivalent(RiemannHypothesis, Equal(NEWLINE (1/Pi) * Integral(Log(Abs(RiemannZeta(Div(1,2)+ConstI*t)/RiemannZeta(Div(1,2)))) * Div(1,t**2), For(t, 0, Infinity)),NEWLINE Pi/8 + ConstGamma/4 + Log(8*Pi)/4 - 2))),NEWLINE References("https://mathoverflow.net/q/279936"))NEWLINENEWLINEmake_entry(ID("cf70ce"),NEWLINE Formula(Equivalent(RiemannHypothesis, Equal(NEWLINE Integral((1-12*t**2)/(1+4*t**2)**3 * Integral(Log(Abs(RiemannZeta(sigma + ConstI*t))), For(sigma, Div(1,2), Infinity)), For(t, 0, Infinity)),NEWLINE Pi * (3-ConstGamma) / 32))),NEWLINE References("https://doi.org/10.1007/BF01056314"))NEWLINENEWLINENEWLINEdef_Topic(NEWLINE Title("Keiper-Li coefficients"),NEWLINE Section("Definitions"),NEWLINE Entries(NEWLINE "432bee",NEWLINE ),NEWLINE Section("Representations"),NEWLINE Entries(NEWLINE "fcab61",NEWLINE "cce75b",NEWLINE ),NEWLINE Section("Specific values"),NEWLINE Entries(NEWLINE "081205",NEWLINE "d8d820",NEWLINE "faf448",NEWLINE "706f66",NEWLINE ),NEWLINE Section("Asymptotics"),NEWLINE Entries(NEWLINE "64bd32",NEWLINE ),NEWLINE Section("Riemann hypothesis (Li's criterion)"),NEWLINE EntriesNEWLINE (NEWLINE "e68f82",NEWLINE "a5d65f",NEWLINE "8f8fb7",NEWLINE ),NEWLINE)NEWLINENEWLINEmake_entry(ID("432bee"),NEWLINE SymbolDefinition(KeiperLiLambda, KeiperLiLambda(n), "Keiper-Li coefficient"),NEWLINE Description(SourceForm(KeiperLiLambda(n)), ", rendered as", KeiperLiLambda(n),NEWLINE ", denotes a power series coefficient associated with the Riemann zeta function. "),NEWLINE Description("The definition", EntryReference("fcab61"), "follows Keiper (1992). Li (1997) defines the coefficients with a different scaling factor, equivalent to", n*KeiperLiLambda(n), "in Keiper's (and Fungrim's) notation."),NEWLINE References("https://doi.org/10.2307/2153215", "https://doi.org/10.1006/jnth.1997.2137", "https://doi.org/10.7169/facm/1317045228"))NEWLINENEWLINEmake_entry(ID("fcab61"),NEWLINE Formula(Equal(KeiperLiLambda(n), (1/Factorial(n)) * ComplexDerivative(Log(2 * RiemannXi(s/(s-1))), For(s, 0, n)))),NEWLINE Variables(n),NEWLINE Assumptions(Element(n, ZZGreaterEqual(0))))NEWLINENEWLINE# todo: absolute convergence? need to encode order of summation?NEWLINEmake_entry(ID("cce75b"),NEWLINE Formula(Equal(KeiperLiLambda(n), (1/n) * Sum(Parentheses(1 - (RiemannZetaZero(k) / (RiemannZetaZero(k) - 1))**n), ForElement(k, ZZ), NotEqual(k, 0)))),NEWLINE Variables(n),NEWLINE Assumptions(Element(n, ZZGreaterEqual(1))))NEWLINENEWLINEmake_entry(ID("081205"),NEWLINE Formula(Equal(KeiperLiLambda(0), 0)))NEWLINENEWLINEmake_entry(ID("d8d820"),NEWLINE Formula(Equal(KeiperLiLambda(1), (ConstGamma/2 + 1) - Log(4*Pi)/2)))NEWLINENEWLINEmake_entry(ID("faf448"),NEWLINE Description("Table of", KeiperLiLambda(n), "to 50 digits for", LessEqual(0, n, 30)),NEWLINE Table(NEWLINE Var(n),NEWLINE TableValueHeadings(n, NearestDecimal(KeiperLiLambda(n), 50)),NEWLINE TableSplit(1),NEWLINE List(NEWLINE Tuple(0, Decimal("0")),NEWLINE Tuple(1, Decimal("0.023095708966121033814310247906495291621932127152051")),NEWLINE Tuple(2, Decimal("0.046172867614023335192864243096033943387066108314123")),NEWLINE Tuple(3, Decimal("0.069212973518108267930497348872601068994212026393200")),NEWLINE Tuple(4, Decimal("0.092197619873060409647627872409439018065541673490213")),NEWLINE Tuple(5, Decimal("0.11510854289223549048622128109857276671349132303596")),NEWLINE Tuple(6, Decimal("0.13792766871372988290416713700341666356138966078654")),NEWLINE Tuple(7, Decimal("0.16063715965299421294040287257385366292282442046163")),NEWLINE Tuple(8, Decimal("0.18321945964338257908193931774721859848998098273432")),NEWLINE Tuple(9, Decimal("0.20565733870917046170289387421343304741236553410044")),NEWLINE Tuple(10, Decimal("0.22793393631931577436930340573684453380748385942738")),NEWLINE Tuple(11, Decimal("0.25003280347456327821404973571398176484638012641151")),NEWLINE Tuple(12, Decimal("0.27193794338538498733992383249265390667786600994911")),NEWLINE Tuple(13, Decimal("0.29363385060368815285418215009889439246684857721098")),NEWLINE Tuple(14, Decimal("0.31510554847718560800576009263276843951188505373007")),NEWLINE Tuple(15, Decimal("0.33633862480178623056900742916909716316435743073656")),NEWLINE Tuple(16, Decimal("0.35731926555429953996369166686545971896237127626351")),NEWLINE Tuple(17, Decimal("0.37803428659512958242032593887899541131751543174423")),NEWLINE Tuple(18, Decimal("0.39847116323842905329183170701797400318996274958010")),NEWLINE Tuple(19, Decimal("0.41861805759536317393727500409965507879749928476235")),NEWLINE Tuple(20, Decimal("0.43846384360466075647997306767236011141956127351910")),NEWLINE Tuple(21, Decimal("0.45799812967347233249339981618322155418048244629837")),NEWLINE Tuple(22, Decimal("0.47721127886067612259488922142809435229670372335579")),NEWLINE Tuple(23, Decimal("0.49609442654413481917007764284527175942412402470703")),NEWLINE Tuple(24, Decimal("0.51463949552297154237641907033478550942000739520745")),NEWLINE Tuple(25, Decimal("0.53283920851566303199773431527093937195060386800653")),NEWLINE Tuple(26, Decimal("0.55068709802460266427322142354105110711472096137358")),NEWLINE Tuple(27, Decimal("0.56817751354772529773768642819955547787404863111699")),NEWLINE Tuple(28, Decimal("0.58530562612777004271739082427374534543603950676386")),NEWLINE Tuple(29, Decimal("0.60206743023974549532618306036749838157067445931420")),NEWLINE Tuple(30, Decimal("0.61845974302711452077115586049317787034309975741269")),NEWLINE )))NEWLINENEWLINEmake_entry(ID("706f66"),NEWLINE Description("Table of", KeiperLiLambda(10**n), "to 50 digits for", LessEqual(0, n, 5)),NEWLINE Table(NEWLINE Var(n),NEWLINE TableValueHeadings(n, NearestDecimal(KeiperLiLambda(10**n), 50)),NEWLINE TableSplit(1),NEWLINE List(NEWLINE Tuple(0, Decimal("0.023095708966121033814310247906495291621932127152051")),NEWLINE Tuple(1, Decimal("0.22793393631931577436930340573684453380748385942738")),NEWLINE Tuple(2, Decimal("1.1860377537679132992736469839793792693298702359323")),NEWLINE Tuple(3, Decimal("2.3260531616864664574065046940832238158044982041693")),NEWLINE Tuple(4, Decimal("3.4736579732241613740180609478145593215167373519711")),NEWLINE Tuple(5, Decimal("4.6258078240690223140941603808334320467617286152507")),NEWLINE )))NEWLINENEWLINEmake_entry(ID("64bd32"),NEWLINE Formula(Implies(RiemannHypothesis, AsymptoticTo(KeiperLiLambda(n), Log(n)/2 - (Log(2*Pi) + 1 - ConstGamma)/2, n, Infinity))),NEWLINE References("https://doi.org/10.7169/facm/1317045228"))NEWLINENEWLINEmake_entry(ID("e68f82"),NEWLINE Formula(Equivalent(RiemannHypothesis, All(Greater(KeiperLiLambda(n), 0), ForElement(n, ZZGreaterEqual(1))))),NEWLINE References("https://doi.org/10.1006/jnth.1997.2137"))NEWLINENEWLINEmake_entry(ID("a5d65f"),NEWLINE Formula(Equivalent(RiemannHypothesis, Where(Less(Sum(Abs(KeiperLiLambda(n) - a(n))**2, For(n, 1, Infinity)), Infinity),NEWLINE Equal(a(n), Log(n)/2 - (Log(2*Pi) + 1 - ConstGamma)/2)))),NEWLINE References("https://doi.org/10.7169/facm/1317045228"))NEWLINENEWLINEmake_entry(ID("8f8fb7"),NEWLINE Formula(Implies(NEWLINE All(Equal(Re(RiemannZetaZero(n)), Div(1,2)), ForElement(n, ZZGreaterEqual(1)), Less(Im(RiemannZetaZero(n)), T)),NEWLINE All(GreaterEqual(KeiperLiLambda(n), 0), ForElement(n, ZZGreaterEqual(0)), LessEqual(n, T**2)))),NEWLINE Variables(T),NEWLINE Assumptions(Element(T, ClosedOpenInterval(0, Infinity))),NEWLINE References("https://arxiv.org/abs/1703.02844"))NEWLINENEWLINENEWLINEdef_Topic(NEWLINE Title("Stieltjes constants"),NEWLINE Section("Definitions"),NEWLINE Entries(NEWLINE "d10029",NEWLINE ),NEWLINE Section("Generating functions"),NEWLINE Entries(NEWLINE "b1a2e1",NEWLINE "60c6da",NEWLINE ),NEWLINE Section("Limit representations"),NEWLINE Entries(NEWLINE "411f3b",NEWLINE ),NEWLINE Section("Specific values"),NEWLINE Entries(NEWLINE "51206a",NEWLINE "8ae153",NEWLINE "b6808d",NEWLINE "70a705",NEWLINE "e5bd3c",NEWLINE "569d5c",NEWLINE ),NEWLINE Section("Recurrence relations"),NEWLINE Entries(NEWLINE "687b4d",NEWLINE ),NEWLINE Section("Integral representations"),NEWLINE Entries(NEWLINE "a41c92",NEWLINE ),NEWLINE Section("Bounds and inequalities"),NEWLINE Entries(NEWLINE "1dec0d",NEWLINE )NEWLINE)NEWLINENEWLINEmake_entry(ID("d10029"),NEWLINE SymbolDefinition(StieltjesGamma, StieltjesGamma(n, a), "Stieltjes constant"),NEWLINE Description(SourceForm(StieltjesGamma(n)), ", rendered as", StieltjesGamma(n), ", represents the Stieltjes constant of index", n, "."),NEWLINE Description(SourceForm(StieltjesGamma(n, a)), ", rendered as", StieltjesGamma(n, a), ", represents the generalized Stieltjes constant of index", n, " with parameter", a, "."),NEWLINE Table(TableRelation(Tuple(P, Q), Implies(P, Q)),NEWLINE TableHeadings(Description("Domain"), Description("Codomain")),NEWLINE List(NEWLINE Tuple(Element(n, ZZGreaterEqual(0)), Element(StieltjesGamma(n), RR)),NEWLINE Tuple(And(Element(n, ZZGreaterEqual(0)), Element(a, CC), NotElement(a, ZZLessEqual(0))), Element(StieltjesGamma(n, a), CC)),NEWLINE ))NEWLINE)NEWLINENEWLINE# Generating functionsNEWLINENEWLINEmake_entry(ID("b1a2e1"),NEWLINE Formula(Equal(RiemannZeta(s), 1/(s-1) + Sum((-1)**n/Factorial(n) * StieltjesGamma(n) * (s-1)**n, For(n, 0, Infinity)))),NEWLINE Variables(s),NEWLINE Assumptions(Element(s, CC)))NEWLINENEWLINEmake_entry(ID("60c6da"),NEWLINE Formula(Equal(HurwitzZeta(s, a), 1/(s-1) + Sum((-1)**n/Factorial(n) * StieltjesGamma(n, a) * (s-1)**n, For(n, 0, Infinity)))),NEWLINE Variables(s, a),NEWLINE Assumptions(And(Element(s, CC), Element(a, CC), NotElement(a, ZZLessEqual(0)))))NEWLINENEWLINE# Limit representationsNEWLINENEWLINEmake_entry(ID("411f3b"),NEWLINE Formula(Equal(StieltjesGamma(n, a), SequenceLimit(Brackets(Parentheses(Sum(Log(k+a)**n / (k+a), For(k, 0, N))) - Log(N+a)**(n+1)/(n+1)), For(N, Infinity)))),NEWLINE Variables(n, a),NEWLINE Assumptions(And(Element(n, ZZGreaterEqual(0)), Element(a, CC), NotElement(a, ZZLessEqual(0)))))NEWLINENEWLINE# Specific valuesNEWLINENEWLINEmake_entry(ID("51206a"),NEWLINE Formula(Equal(StieltjesGamma(n, 1), StieltjesGamma(n))),NEWLINE Variables(n),NEWLINE Assumptions(Element(n, ZZGreaterEqual(0))))NEWLINENEWLINEmake_entry(ID("8ae153"),NEWLINE Formula(Equal(StieltjesGamma(0, 1), StieltjesGamma(0), ConstGamma)))NEWLINENEWLINEmake_entry(ID("b6808d"),NEWLINE Formula(Equal(StieltjesGamma(0, a), -DigammaFunction(a))),NEWLINE Variables(a),NEWLINE Assumptions(And(Element(a, CC), NotElement(a, ZZLessEqual(0)))))NEWLINENEWLINEmake_entry(ID("70a705"),NEWLINE Formula(Equal(StieltjesGamma(1, Div(1,2)), StieltjesGamma(1) - 2*ConstGamma*Log(2) - Log(2)**2)))NEWLINENEWLINEmake_entry(ID("e5bd3c"),NEWLINE Description("Table of", StieltjesGamma(n), "to 50 digits for", LessEqual(0, n, 30)),NEWLINE Table(NEWLINE Var(n),NEWLINE TableValueHeadings(n, NearestDecimal(StieltjesGamma(n), 50)),NEWLINE TableSplit(1),NEWLINE List(NEWLINE Tuple(0, Decimal("0.57721566490153286060651209008240243104215933593992")),NEWLINE Tuple(1, Decimal("-0.072815845483676724860586375874901319137736338334338")),NEWLINE Tuple(2, Decimal("-0.0096903631928723184845303860352125293590658061013407")),NEWLINE Tuple(3, Decimal("0.0020538344203033458661600465427533842857158044454106")),NEWLINE Tuple(4, Decimal("0.0023253700654673000574681701775260680009044694137849")),NEWLINE Tuple(5, Decimal("0.00079332381730106270175333487744444483073153940458489")),NEWLINE Tuple(6, Decimal("-0.00023876934543019960987242184190800427778371515635808")),NEWLINE Tuple(7, Decimal("-0.00052728956705775104607409750547885828199625347296990")),NEWLINE Tuple(8, Decimal("-0.00035212335380303950960205216500120874172918053379235")),NEWLINE Tuple(9, Decimal("-3.4394774418088048177914623798227390620789538594442e-5")),NEWLINE Tuple(10, Decimal("0.00020533281490906479468372228923706530295985377416676")),NEWLINE Tuple(11, Decimal("0.00027018443954390352667290208206795567382784205868840")),NEWLINE Tuple(12, Decimal("0.00016727291210514019335350154334118344660780663280557")),NEWLINE Tuple(13, Decimal("-2.7463806603760158860007603693355181526785337670396e-5")),NEWLINE Tuple(14, Decimal("-0.00020920926205929994583713969734458495783154421150607")),NEWLINE Tuple(15, Decimal("-0.00028346865532024144664293447499712697706870298071768")),NEWLINE Tuple(16, Decimal("-0.00019969685830896977470778456320324039191576497403406")),NEWLINE Tuple(17, Decimal("2.6277037109918336699466597630510122816078692929114e-5")),NEWLINE Tuple(18, Decimal("0.00030736840814925282659275475194862564552381129073146")),NEWLINE Tuple(19, Decimal("0.00050360545304735562905559643771716003532126980764950")),NEWLINE Tuple(20, Decimal("0.00046634356151155944940059482443355052511314347392569")),NEWLINE Tuple(21, Decimal("0.00010443776975600011581079567436772049104442825070555")),NEWLINE Tuple(22, Decimal("-0.00054159958220399770165519617317410558454386092870075")),NEWLINE Tuple(23, Decimal("-0.0012439620904082457792997415995371658091470281139646")),NEWLINE Tuple(24, Decimal("-0.0015885112789035615619061966115211158573187228221441")),NEWLINE Tuple(25, Decimal("-0.0010745919527384888247242919873531730892739793314532")),NEWLINE Tuple(26, Decimal("0.00065680351863715443150477300335621524888606506047754")),NEWLINE Tuple(27, Decimal("0.0034778369136185382090073595742588115476629156638859")),NEWLINE Tuple(28, Decimal("0.0064000685317006294581072282219458636666371981445885")),NEWLINE Tuple(29, Decimal("0.0073711517704722391344124024235594021578413274885128")),NEWLINE Tuple(30, Decimal("0.0035577288555731609479135377489084026108096506495221")),NEWLINE )))NEWLINENEWLINEmake_entry(ID("569d5c"),NEWLINE Description("Table of", StieltjesGamma(10**n), "to 50 digits for", LessEqual(0, n, 20)),NEWLINE Table(NEWLINE Var(n),NEWLINE TableValueHeadings(n, NearestDecimal(StieltjesGamma(10**n), 50)),NEWLINE TableSplit(1),NEWLINE List(NEWLINE Tuple(0, Decimal("-0.072815845483676724860586375874901319137736338334338")),NEWLINE Tuple(1, Decimal("0.00020533281490906479468372228923706530295985377416676")),NEWLINE Tuple(2, Decimal("-425340157170802696.23144385197278358247028931053473")),NEWLINE Tuple(3, Decimal("-1.5709538442047449345494023425120825242380299554570e+486")),NEWLINE Tuple(4, Decimal("-2.2104970567221060862971082857536501900234397174729e+6883")),NEWLINE Tuple(5, Decimal("1.9919273063125410956582272431568589205211659777533e+83432")),NEWLINE Tuple(6, Decimal("-4.4209504730980210273285480902514758066667150603243e+947352")),NEWLINE Tuple(7, Decimal("-2.7882974834697458134414289662704891120456603986498e+10390401")),NEWLINE Tuple(8, Decimal("2.7324629454457814909592178706122081982218137653871e+111591574")),NEWLINE Tuple(9, Decimal("2.1048416655418517821363600001419516191053973500980e+1181965380")),NEWLINE Tuple(10, Decimal("7.5883621237131051948224033799125486921750410324510e+12397849705")),NEWLINE Tuple(11, Decimal("3.4076163168007069203916546697422088077748515862016e+129115149508")),NEWLINE Tuple(12, Decimal("-1.1713923594956898094830946178584108308869819425684e+1337330792656")),NEWLINE Tuple(13, Decimal("5.1442844004429501778205029347495102582243127602569e+13792544216233")),NEWLINE Tuple(14, Decimal("-5.8565687699062182176274937548885177768345135170181e+141762672271719")),NEWLINE Tuple(15, Decimal("1.8441017255847322907032695598351364885675746553316e+1452992510427658")),NEWLINE Tuple(16, Decimal("1.0887949866822670316936532894122644696901837098117e+14857814744168222")),NEWLINE Tuple(17, Decimal("-9.0932573236841531922129808939176217547651121139948e+151633823511792145")),NEWLINE Tuple(18, Decimal("2.6314370018873515830151010192294307578971415626833e+1544943249673388947")),NEWLINE Tuple(19, Decimal("4.8807917914447513336887536981308809263719031557975e+15718277029330950920")),NEWLINE Tuple(20, Decimal("2.3945266166432844875810628102042011083015231233149e+159718433793014252763")),NEWLINE )))NEWLINENEWLINE# Recurrence relationsNEWLINENEWLINEmake_entry(ID("687b4d"),NEWLINE Formula(Equal(StieltjesGamma(n, a+1), StieltjesGamma(n, a) - Log(a)**n / a)),NEWLINE Variables(n, a),NEWLINE Assumptions(And(Element(n, ZZGreaterEqual(0)), Element(a, CC), NotElement(a, ZZLessEqual(0)))))NEWLINENEWLINE# Integral representationsNEWLINENEWLINEmake_entry(ID("a41c92"),NEWLINE Formula(Equal(StieltjesGamma(n, a), -((Pi/(2*(n+1))) * Integral((Log(a-Div(1,2)+ConstI*x)**(n+1) + Log(a-Div(1,2)-ConstI*x)**(n+1))/Cosh(Pi*x)**2, For(x, 0, Infinity))))),NEWLINE Variables(n, a),NEWLINE Assumptions(And(Element(n, ZZGreaterEqual(0)), Element(a, CC), Greater(Re(a), Div(1,2)))))NEWLINENEWLINE# Bounds and inequalitiesNEWLINENEWLINEmake_entry(ID("1dec0d"),NEWLINE Formula(Less(Abs(StieltjesGamma(n)), Pow(10,-4) * Exp(n*Log(Log(n))))),NEWLINE Variables(n),NEWLINE Assumptions(Element(n, ZZGreaterEqual(5))))NEWLINENEWLINE
#!/usr/bin/env python3NEWLINE"""NEWLINEpixivNEWLINENEWLINEUsage:NEWLINE pixiv.pyNEWLINE pixiv.py <id>...NEWLINE pixiv.py -r [-d | --date=<date>]NEWLINE pixiv.py -uNEWLINENEWLINEArguments:NEWLINE <id> user_idsNEWLINENEWLINEOptions:NEWLINE -r Download by rankingNEWLINE -d <date> --date <date> Target dateNEWLINE -u Update exist folderNEWLINE -h --help Show this screenNEWLINE -v --version Show versionNEWLINENEWLINEExamples:NEWLINE pixiv.py 7210261 1980643NEWLINE pixiv.py -r -d 2016-09-24NEWLINE"""NEWLINEimport datetimeNEWLINEimport mathNEWLINEimport osNEWLINEimport queueNEWLINEimport reNEWLINEimport sysNEWLINEimport threadingNEWLINEimport timeNEWLINEimport tracebackNEWLINENEWLINEimport requestsNEWLINEfrom docopt import docoptNEWLINEfrom tqdm import tqdmNEWLINENEWLINEfrom api import PixivApiNEWLINEfrom i18n import i18n as _NEWLINEfrom model import PixivIllustModelNEWLINENEWLINE_THREADING_NUMBER = 10NEWLINE_finished_download = 0NEWLINE_CREATE_FOLDER_LOCK = threading.Lock()NEWLINE_PROGRESS_LOCK = threading.Lock()NEWLINE_SPEED_LOCK = threading.Lock()NEWLINE_Global_Download = 0NEWLINE_error_count = {}NEWLINE_ILLUST_PER_PAGE = 30NEWLINE_MAX_ERROR_COUNT = 5NEWLINENEWLINENEWLINEdef get_default_save_path():NEWLINE current_path = os.path.dirname(os.path.abspath(sys.argv[0]))NEWLINE filepath = os.path.join(current_path, 'illustrations')NEWLINE if not os.path.exists(filepath):NEWLINE with _CREATE_FOLDER_LOCK:NEWLINE if not os.path.exists(os.path.dirname(filepath)):NEWLINE os.makedirs(os.path.dirname(filepath))NEWLINE os.makedirs(filepath)NEWLINE return filepathNEWLINENEWLINENEWLINEdef get_speed(elapsed):NEWLINE """Get current download speed"""NEWLINE with _SPEED_LOCK:NEWLINE global _Global_DownloadNEWLINE down = _Global_DownloadNEWLINE _Global_Download = 0NEWLINE speed = down / elapsedNEWLINE if speed == 0:NEWLINE return '%8.2f /s' % 0NEWLINE units = [' B', 'KB', 'MB', 'GB', 'TB', 'PB']NEWLINE unit = math.floor(math.log(speed, 1024.0))NEWLINE speed /= math.pow(1024.0, unit)NEWLINE return '%6.2f %s/s' % (speed, units[unit])NEWLINENEWLINENEWLINEdef print_progress(max_size):NEWLINE global _finished_downloadNEWLINE pbar = tqdm(total=max_size)NEWLINENEWLINE last = 0NEWLINE while _finished_download != max_size:NEWLINE pbar.update(_finished_download - last)NEWLINE last = _finished_downloadNEWLINE time.sleep(0.5)NEWLINE pbar.update(_finished_download - last)NEWLINE pbar.close()NEWLINENEWLINENEWLINEdef download_file(url, filepath):NEWLINE headers = {'Referer': 'http://www.pixiv.net/'}NEWLINE r = requests.get(url, headers=headers, stream=True, timeout=PixivApi.timeout)NEWLINE if r.status_code == requests.codes.ok:NEWLINE total_length = r.headers.get('content-length')NEWLINE if total_length:NEWLINE data = []NEWLINE for chunk in r.iter_content(1024 * 16):NEWLINE data.append(chunk)NEWLINE with _SPEED_LOCK:NEWLINE global _Global_DownloadNEWLINE _Global_Download += len(chunk)NEWLINE with open(filepath, 'wb') as f:NEWLINE list(map(f.write, data))NEWLINE else:NEWLINE raise ConnectionError('\r', _('Connection error: %s') % r.status_code)NEWLINENEWLINENEWLINEdef download_threading(download_queue):NEWLINE global _finished_downloadNEWLINE while not download_queue.empty():NEWLINE illustration = download_queue.get()NEWLINE filepath = illustration['path']NEWLINE filename = illustration['file']NEWLINE url = illustration['url']NEWLINE count = _error_count.get(url, 0)NEWLINE if count < _MAX_ERROR_COUNT:NEWLINE if not os.path.exists(filepath):NEWLINE with _CREATE_FOLDER_LOCK:NEWLINE if not os.path.exists(os.path.dirname(filepath)):NEWLINE os.makedirs(os.path.dirname(filepath))NEWLINE try:NEWLINE download_file(url, filepath)NEWLINE with _PROGRESS_LOCK:NEWLINE _finished_download += 1NEWLINE except Exception as e:NEWLINE if count < _MAX_ERROR_COUNT:NEWLINE print(_('%s => %s download error, retry') % (e, filename))NEWLINE download_queue.put(illustration)NEWLINE _error_count[url] = count + 1NEWLINE else:NEWLINE print(url, 'reach max retries, canceled')NEWLINE with _PROGRESS_LOCK:NEWLINE _finished_download += 1NEWLINE download_queue.task_done()NEWLINENEWLINENEWLINEdef start_and_wait_download_threading(download_queue, count):NEWLINE """start download threading and wait till complete"""NEWLINE progress_t = threading.Thread(target=print_progress, args=(count,))NEWLINE progress_t.daemon = TrueNEWLINE progress_t.start()NEWLINE for i in range(_THREADING_NUMBER):NEWLINE download_t = threading.Thread(target=download_threading, args=(download_queue,))NEWLINE download_t.daemon = TrueNEWLINE download_t.start()NEWLINENEWLINE progress_t.join()NEWLINE download_queue.join()NEWLINENEWLINENEWLINEdef get_filepath(url, illustration, save_path='.', add_user_folder=False, add_rank=False):NEWLINE """return (filename,filepath)"""NEWLINENEWLINE if add_user_folder:NEWLINE user_id = illustration.user_idNEWLINE user_name = illustration.user_nameNEWLINE current_path = get_default_save_path()NEWLINE cur_dirs = list(filter(os.path.isdir, [os.path.join(current_path, i) for i in os.listdir(current_path)]))NEWLINE cur_user_ids = [os.path.basename(cur_dir).split()[0] for cur_dir in cur_dirs]NEWLINE if user_id not in cur_user_ids:NEWLINE dir_name = re.sub(r'[<>:"/\\|\?\*]', ' ', user_id + ' ' + user_name)NEWLINE else:NEWLINE dir_name = list(i for i in cur_dirs if os.path.basename(i).split()[0] == user_id)[0]NEWLINE save_path = os.path.join(save_path, dir_name)NEWLINENEWLINE filename = url.split('/')[-1]NEWLINE if add_rank:NEWLINE filename = f'{illustration.rank} - {filename}'NEWLINE filepath = os.path.join(save_path, filename)NEWLINE return filename, filepathNEWLINENEWLINENEWLINEdef check_files(illustrations, save_path='.', add_user_folder=False, add_rank=False):NEWLINE download_queue = queue.Queue()NEWLINE index_list = []NEWLINE count = 0NEWLINE if illustrations:NEWLINE last_i = -1NEWLINE for index, illustration in enumerate(illustrations):NEWLINE if not illustration.image_urls:NEWLINE continueNEWLINE else:NEWLINE for url in illustration.image_urls:NEWLINE filename, filepath = get_filepath(url, illustration, save_path, add_user_folder, add_rank)NEWLINE if os.path.exists(filepath):NEWLINE continueNEWLINE else:NEWLINE if last_i != index:NEWLINE last_i = indexNEWLINE index_list.append(index)NEWLINE download_queue.put({'url': url, 'file': filename, 'path': filepath})NEWLINE count += 1NEWLINE return download_queue, count, index_listNEWLINENEWLINENEWLINEdef count_illustrations(illustrations):NEWLINE return sum(len(i.image_urls) for i in illustrations)NEWLINENEWLINENEWLINEdef is_manga(illustrate):NEWLINE return True if illustrate.is_manga or illustrate.type == 'manga' else FalseNEWLINENEWLINENEWLINEdef download_illustrations(user, data_list, save_path='.', add_user_folder=False, add_rank=False, skip_manga=False):NEWLINE """Download illustratonsNEWLINENEWLINE Args:NEWLINE user: PixivApi()NEWLINE data_list: jsonNEWLINE save_path: str, download path of the illustrationsNEWLINE add_user_folder: bool, whether put the illustration into user folderNEWLINE add_rank: bool, add illustration rank at the beginning of filenameNEWLINE """NEWLINE illustrations = PixivIllustModel.from_data(data_list)NEWLINE if skip_manga:NEWLINE manga_number = sum([is_manga(i) for i in illustrations])NEWLINE if manga_number:NEWLINE print('skip', manga_number, 'manga')NEWLINE illustrations = list(filter(lambda x: not is_manga(x), illustrations))NEWLINE download_queue, count = check_files(illustrations, save_path, add_user_folder, add_rank)[0:2]NEWLINE if count > 0:NEWLINE print(_('Start download, total illustrations '), count)NEWLINE global _finished_download, _Global_DownloadNEWLINE _finished_download = 0NEWLINE _Global_Download = 0NEWLINE start_and_wait_download_threading(download_queue, count)NEWLINE print()NEWLINE else:NEWLINE print(_('There is no new illustration need to download'))NEWLINENEWLINENEWLINEdef download_by_user_id(user, user_ids=None):NEWLINE save_path = get_default_save_path()NEWLINE if not user_ids:NEWLINE user_ids = input(_('Input the artist\'s id:(separate with space)')).strip().split(' ')NEWLINE for user_id in user_ids:NEWLINE print(_('Artists %s') % user_id)NEWLINE data_list = user.get_all_user_illustrations(user_id)NEWLINE download_illustrations(user, data_list, save_path, add_user_folder=True)NEWLINENEWLINENEWLINEdef download_by_ranking(user):NEWLINE today = str(datetime.date.today())NEWLINE save_path = os.path.join(get_default_save_path(), today + ' ranking')NEWLINE data_list = user.get_ranking_illustrations()NEWLINE download_illustrations(user, data_list, save_path, add_rank=True)NEWLINENEWLINENEWLINEdef download_by_history_ranking(user, date=''):NEWLINE if not date:NEWLINE date = input(_('Input the date:(eg:2015-07-10)'))NEWLINE if not (re.search("^\d{4}-\d{2}-\d{2}", date)):NEWLINE print(_('[invalid date format]'))NEWLINE date = str(datetime.date.today() - datetime.timedelta(days=1))NEWLINE save_path = os.path.join(get_default_save_path(), date + ' ranking')NEWLINE data_list = user.get_ranking_illustrations(date=date)NEWLINE download_illustrations(user, data_list, save_path, add_rank=True)NEWLINENEWLINENEWLINEdef artist_folder_scanner(user, user_id_list, save_path, final_list, fast):NEWLINE while not user_id_list.empty():NEWLINE user_info = user_id_list.get()NEWLINE user_id = user_info['id']NEWLINE folder = user_info['folder']NEWLINE try:NEWLINE if fast:NEWLINE data_list = []NEWLINE offset = 0NEWLINE page_result = user.get_all_user_illustrations(user_id, offset, _ILLUST_PER_PAGE)NEWLINE if len(page_result) > 0:NEWLINE data_list.extend(page_result)NEWLINE file_path = os.path.join(save_path, folder, data_list[-1]['image_urls']['large'].split('/')[-1])NEWLINE while not os.path.exists(file_path) and len(page_result) == _ILLUST_PER_PAGE:NEWLINE offset += _ILLUST_PER_PAGENEWLINE page_result = user.get_all_user_illustrations(user_id, offset, _ILLUST_PER_PAGE)NEWLINE data_list.extend(page_result)NEWLINE file_path = os.path.join(save_path, folder, data_list[-1]['image_urls']['large'].split('/')[-1])NEWLINE # prevent rate limitNEWLINE time.sleep(1)NEWLINE else:NEWLINE data_list = user.get_all_user_illustrations(user_id)NEWLINE illustrations = PixivIllustModel.from_data(data_list)NEWLINE count, checked_list = check_files(illustrations, save_path, add_user_folder=True, add_rank=False)[1:3]NEWLINE if len(sys.argv) < 2 or count:NEWLINE try:NEWLINE print(_('Artists %s [%s]') % (folder, count))NEWLINE except UnicodeError:NEWLINE print(_('Artists %s ?? [%s]') % (user_id, count))NEWLINE with _PROGRESS_LOCK:NEWLINE for index in checked_list:NEWLINE final_list.append(data_list[index])NEWLINE except Exception:NEWLINE traceback.print_exc()NEWLINE user_id_list.task_done()NEWLINENEWLINENEWLINEdef update_exist(user, fast=True):NEWLINE current_path = get_default_save_path()NEWLINE final_list = []NEWLINE user_id_list = queue.Queue()NEWLINE for folder in os.listdir(current_path):NEWLINE if os.path.isdir(os.path.join(current_path, folder)):NEWLINE user_id = re.search('^(\d+) ', folder)NEWLINE if user_id:NEWLINE user_id = user_id.group(1)NEWLINE user_id_list.put({'id': user_id, 'folder': folder})NEWLINE for i in range(1):NEWLINE # use one thread to prevent Rate Limit in new App APINEWLINE scan_t = threading.Thread(target=artist_folder_scanner,NEWLINE args=(user, user_id_list, current_path, final_list, fast,))NEWLINE scan_t.daemon = TrueNEWLINE scan_t.start()NEWLINE user_id_list.join()NEWLINE download_illustrations(user, final_list, current_path, add_user_folder=True)NEWLINENEWLINENEWLINEdef remove_repeat(_):NEWLINE """Delete xxxxx.img if xxxxx_p0.img exist"""NEWLINE choice = input(_('Dangerous Action: continue?(y/n)'))NEWLINE if choice == 'y':NEWLINE illust_path = get_default_save_path()NEWLINE for folder in os.listdir(illust_path):NEWLINE if os.path.isdir(os.path.join(illust_path, folder)):NEWLINE if re.search('^(\d+) ', folder):NEWLINE path = os.path.join(illust_path, folder)NEWLINE for file_name in os.listdir(path):NEWLINE illustration_id = re.search('^\d+\.', file_name)NEWLINE if illustration_id:NEWLINE if os.path.isfile(os.path.join(pathNEWLINE , illustration_id.string.replace('.', '_p0.'))):NEWLINE os.remove(os.path.join(path, file_name))NEWLINE print('Delete', os.path.join(path, file_name))NEWLINENEWLINENEWLINEdef main():NEWLINE user = PixivApi()NEWLINE if len(sys.argv) > 1:NEWLINE print(datetime.datetime.now().strftime('%X %x'))NEWLINE ids = arguments['<id>']NEWLINE is_rank = arguments['-r']NEWLINE date = arguments['--date']NEWLINE is_update = arguments['-u']NEWLINE if ids:NEWLINE download_by_user_id(user, ids)NEWLINE elif is_rank:NEWLINE if date:NEWLINE date = date[0]NEWLINE download_by_history_ranking(user, date)NEWLINE else:NEWLINE download_by_ranking(user)NEWLINE elif is_update:NEWLINE update_exist(user)NEWLINE print(datetime.datetime.now().strftime('%X %x'))NEWLINE else:NEWLINE print(_(' Pixiv Downloader 2.4 ').center(77, '#'))NEWLINE options = {NEWLINE '1': download_by_user_id,NEWLINE '2': download_by_ranking,NEWLINE '3': download_by_history_ranking,NEWLINE '4': update_exist,NEWLINE '5': remove_repeatNEWLINE }NEWLINE while True:NEWLINE print(_('Which do you want to:'))NEWLINE for i in sorted(options.keys()):NEWLINE print('\t %s %s' % (i, _(options[i].__name__).replace('_', ' ')))NEWLINE choose = input('\t e %s \n:' % _('exit'))NEWLINE if choose in [str(i) for i in range(1, len(options) + 1)]:NEWLINE print((' ' + _(options[choose].__name__).replace('_', ' ') + ' ').center(60, '#') + '\n')NEWLINE if choose == 4:NEWLINE options[choose](user, False)NEWLINE else:NEWLINE options[choose](user)NEWLINE print('\n' + (' ' + _(options[choose].__name__).replace('_', ' ') + _(' finished ')).center(60,NEWLINE '#') + '\n')NEWLINE elif choose == 'e':NEWLINE breakNEWLINE else:NEWLINE print(_('Wrong input!'))NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE arguments = docopt(__doc__, version='pixiv 3')NEWLINE sys.exit(main())NEWLINE
#NEWLINE# Copyright 2015 Quantopian, Inc.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.NEWLINEfrom contextlib2 import ExitStackNEWLINEfrom copy import copyNEWLINEfrom logbook import Logger, ProcessorNEWLINEfrom zipline.finance.order import ORDER_STATUSNEWLINEfrom zipline.protocol import BarDataNEWLINEfrom zipline.utils.api_support import ZiplineAPINEWLINEfrom six import viewkeysNEWLINENEWLINEfrom zipline.gens.sim_engine import (NEWLINE BAR,NEWLINE SESSION_START,NEWLINE SESSION_END,NEWLINE MINUTE_END,NEWLINE BEFORE_TRADING_START_BARNEWLINE)NEWLINENEWLINElog = Logger('Trade Simulation')NEWLINENEWLINENEWLINEclass AlgorithmSimulator(object):NEWLINENEWLINE EMISSION_TO_PERF_KEY_MAP = {NEWLINE 'minute': 'minute_perf',NEWLINE 'daily': 'daily_perf'NEWLINE }NEWLINENEWLINE def __init__(self, algo, sim_params, data_portal, clock, benchmark_source,NEWLINE restrictions, universe_func):NEWLINENEWLINE # ==============NEWLINE # SimulationNEWLINE # Param SetupNEWLINE # ==============NEWLINE self.sim_params = sim_paramsNEWLINE self.data_portal = data_portalNEWLINE self.restrictions = restrictionsNEWLINENEWLINE # ==============NEWLINE # Algo SetupNEWLINE # ==============NEWLINE self.algo = algoNEWLINENEWLINE # ==============NEWLINE # Snapshot SetupNEWLINE # ==============NEWLINENEWLINE # This object is the way that user algorithms interact with OHLCV data,NEWLINE # fetcher data, and some API methods like `data.can_trade`.NEWLINE self.current_data = self._create_bar_data(universe_func)NEWLINENEWLINE # We don't have a datetime for the current snapshot until weNEWLINE # receive a message.NEWLINE self.simulation_dt = NoneNEWLINENEWLINE self.clock = clockNEWLINENEWLINE self.benchmark_source = benchmark_sourceNEWLINENEWLINE # =============NEWLINE # Logging SetupNEWLINE # =============NEWLINENEWLINE # Processor function for injecting the algo_dt intoNEWLINE # user prints/logs.NEWLINE def inject_algo_dt(record):NEWLINE if 'algo_dt' not in record.extra:NEWLINE record.extra['algo_dt'] = self.simulation_dtNEWLINE self.processor = Processor(inject_algo_dt)NEWLINENEWLINE def get_simulation_dt(self):NEWLINE return self.simulation_dtNEWLINENEWLINE def _create_bar_data(self, universe_func):NEWLINE return BarData(NEWLINE data_portal=self.data_portal,NEWLINE simulation_dt_func=self.get_simulation_dt,NEWLINE data_frequency=self.sim_params.data_frequency,NEWLINE trading_calendar=self.algo.trading_calendar,NEWLINE restrictions=self.restrictions,NEWLINE universe_func=universe_funcNEWLINE )NEWLINENEWLINE def transform(self):NEWLINE """NEWLINE Main generator work loop.NEWLINE """NEWLINE algo = self.algoNEWLINE metrics_tracker = algo.metrics_trackerNEWLINE emission_rate = metrics_tracker.emission_rateNEWLINENEWLINE def every_bar(dt_to_use, current_data=self.current_data,NEWLINE handle_data=algo.event_manager.handle_data):NEWLINE for capital_change in calculate_minute_capital_changes(dt_to_use):NEWLINE yield capital_changeNEWLINENEWLINE self.simulation_dt = dt_to_useNEWLINE # called every tick (minute or day).NEWLINE algo.on_dt_changed(dt_to_use)NEWLINENEWLINE blotter = algo.blotterNEWLINENEWLINE # handle any transactions and commissions coming out new ordersNEWLINE # placed in the last barNEWLINE new_transactions, new_commissions, closed_orders = \NEWLINE blotter.get_transactions(current_data, dt_to_use)NEWLINENEWLINE blotter.prune_orders(closed_orders)NEWLINENEWLINE for transaction in new_transactions:NEWLINE metrics_tracker.process_transaction(transaction)NEWLINENEWLINE # since this order was modified, record itNEWLINE order = blotter.orders[transaction.order_id]NEWLINE metrics_tracker.process_order(order)NEWLINENEWLINE for commission in new_commissions:NEWLINE metrics_tracker.process_commission(commission)NEWLINENEWLINE handle_data(algo, current_data, dt_to_use)NEWLINENEWLINE # grab any new orders from the blotter, then clear the list.NEWLINE # this includes cancelled orders.NEWLINE new_orders = blotter.new_ordersNEWLINE blotter.new_orders = []NEWLINENEWLINE # if we have any new orders, record them so that we knowNEWLINE # in what perf period they were placed.NEWLINE for new_order in new_orders:NEWLINE metrics_tracker.process_order(new_order)NEWLINENEWLINE def once_a_day(midnight_dt, current_data=self.current_data,NEWLINE data_portal=self.data_portal):NEWLINE # process any capital changes that came overnightNEWLINE for capital_change in algo.calculate_capital_changes(NEWLINE midnight_dt, emission_rate=emission_rate,NEWLINE is_interday=True):NEWLINE yield capital_changeNEWLINENEWLINE # set all the timestampsNEWLINE self.simulation_dt = midnight_dtNEWLINE algo.on_dt_changed(midnight_dt)NEWLINENEWLINE metrics_tracker.handle_market_open(NEWLINE midnight_dt,NEWLINE algo.data_portal,NEWLINE )NEWLINENEWLINE # handle any splits that impact any positions or any open orders.NEWLINE assets_we_care_about = (NEWLINE viewkeys(metrics_tracker.positions) |NEWLINE viewkeys(algo.blotter.open_orders)NEWLINE )NEWLINENEWLINE if assets_we_care_about:NEWLINE splits = data_portal.get_splits(assets_we_care_about,NEWLINE midnight_dt)NEWLINE if splits:NEWLINE algo.blotter.process_splits(splits)NEWLINE metrics_tracker.handle_splits(splits)NEWLINENEWLINE def on_exit():NEWLINE # Remove references to algo, data portal, et al to break cyclesNEWLINE # and ensure deterministic cleanup of these objects when theNEWLINE # simulation finishes.NEWLINE self.algo = NoneNEWLINE self.benchmark_source = self.current_data = self.data_portal = NoneNEWLINENEWLINE with ExitStack() as stack:NEWLINE stack.callback(on_exit)NEWLINE stack.enter_context(self.processor)NEWLINE stack.enter_context(ZiplineAPI(self.algo))NEWLINENEWLINE if algo.data_frequency == 'minute':NEWLINE def execute_order_cancellation_policy():NEWLINE algo.blotter.execute_cancel_policy(SESSION_END)NEWLINENEWLINE def calculate_minute_capital_changes(dt):NEWLINE # process any capital changes that came between the lastNEWLINE # and current minutesNEWLINE return algo.calculate_capital_changes(NEWLINE dt, emission_rate=emission_rate, is_interday=False)NEWLINE else:NEWLINE def execute_order_cancellation_policy():NEWLINE passNEWLINENEWLINE def calculate_minute_capital_changes(dt):NEWLINE return []NEWLINENEWLINE for dt, action in self.clock:NEWLINE if action == BAR:NEWLINE for capital_change_packet in every_bar(dt):NEWLINE yield capital_change_packetNEWLINE elif action == SESSION_START:NEWLINE for capital_change_packet in once_a_day(dt):NEWLINE yield capital_change_packetNEWLINE elif action == SESSION_END:NEWLINE # End of the session.NEWLINE positions = metrics_tracker.positionsNEWLINE position_assets = algo.asset_finder.retrieve_all(positions)NEWLINE self._cleanup_expired_assets(dt, position_assets)NEWLINENEWLINE execute_order_cancellation_policy()NEWLINE algo.validate_account_controls()NEWLINENEWLINE yield self._get_daily_message(dt, algo, metrics_tracker)NEWLINE elif action == BEFORE_TRADING_START_BAR:NEWLINE self.simulation_dt = dtNEWLINE algo.on_dt_changed(dt)NEWLINE algo.before_trading_start(self.current_data)NEWLINE elif action == MINUTE_END:NEWLINE minute_msg = self._get_minute_message(NEWLINE dt,NEWLINE algo,NEWLINE metrics_tracker,NEWLINE )NEWLINENEWLINE yield minute_msgNEWLINENEWLINE risk_message = metrics_tracker.handle_simulation_end(NEWLINE self.data_portal,NEWLINE )NEWLINE yield risk_messageNEWLINENEWLINE def _cleanup_expired_assets(self, dt, position_assets):NEWLINE """NEWLINE Clear out any assets that have expired before starting a new sim day.NEWLINENEWLINE Performs two functions:NEWLINENEWLINE 1. Finds all assets for which we have open orders and clears anyNEWLINE orders whose assets are on or after their auto_close_date.NEWLINENEWLINE 2. Finds all assets for which we have positions and generatesNEWLINE close_position events for any assets that have reached theirNEWLINE auto_close_date.NEWLINE """NEWLINE algo = self.algoNEWLINENEWLINE def past_auto_close_date(asset):NEWLINE acd = asset.auto_close_dateNEWLINE return acd is not None and acd <= dtNEWLINENEWLINE # Remove positions in any sids that have reached their auto_close date.NEWLINE assets_to_clear = \NEWLINE [asset for asset in position_assets if past_auto_close_date(asset)]NEWLINE metrics_tracker = algo.metrics_trackerNEWLINE data_portal = self.data_portalNEWLINE for asset in assets_to_clear:NEWLINE metrics_tracker.process_close_position(asset, dt, data_portal)NEWLINENEWLINE # Remove open orders for any sids that have reached their auto closeNEWLINE # date. These orders get processed immediately because otherwise theyNEWLINE # would not be processed until the first bar of the next day.NEWLINE blotter = algo.blotterNEWLINE assets_to_cancel = [NEWLINE asset for asset in blotter.open_ordersNEWLINE if past_auto_close_date(asset)NEWLINE ]NEWLINE for asset in assets_to_cancel:NEWLINE blotter.cancel_all_orders_for_asset(asset)NEWLINENEWLINE # Make a copy here so that we are not modifying the list that is beingNEWLINE # iterated over.NEWLINE for order in copy(blotter.new_orders):NEWLINE if order.status == ORDER_STATUS.CANCELLED:NEWLINE metrics_tracker.process_order(order)NEWLINE blotter.new_orders.remove(order)NEWLINENEWLINE def _get_daily_message(self, dt, algo, metrics_tracker):NEWLINE """NEWLINE Get a perf message for the given datetime.NEWLINE """NEWLINE perf_message = metrics_tracker.handle_market_close(NEWLINE dt,NEWLINE self.data_portal,NEWLINE )NEWLINE perf_message['daily_perf']['recorded_vars'] = algo.recorded_varsNEWLINE return perf_messageNEWLINENEWLINE def _get_minute_message(self, dt, algo, metrics_tracker):NEWLINE """NEWLINE Get a perf message for the given datetime.NEWLINE """NEWLINE rvars = algo.recorded_varsNEWLINENEWLINE minute_message = metrics_tracker.handle_minute_close(NEWLINE dt,NEWLINE self.data_portal,NEWLINE )NEWLINENEWLINE minute_message['minute_perf']['recorded_vars'] = rvarsNEWLINE return minute_messageNEWLINE
# This file is part of the Indico plugins.NEWLINE# Copyright (C) 2002 - 2021 CERNNEWLINE#NEWLINE# The Indico plugins are free software; you can redistributeNEWLINE# them and/or modify them under the terms of the MIT License;NEWLINE# see the LICENSE file for more details.NEWLINENEWLINEimport reNEWLINEimport sysNEWLINEimport threadingNEWLINEfrom functools import wrapsNEWLINENEWLINEfrom flask import current_appNEWLINEfrom flask.globals import _app_ctx_stackNEWLINENEWLINENEWLINEdef parallelize(func, entries, batch_size=200):NEWLINE @wraps(func)NEWLINE def wrapper(*args, **kwargs):NEWLINE iterable_lock = threading.Lock()NEWLINE result_lock = threading.Lock()NEWLINE abort = threading.Event()NEWLINE finished = threading.Event()NEWLINE results = []NEWLINE app = current_app._get_current_object()NEWLINE main_app_context = _app_ctx_stack.topNEWLINE worker_exc_info = NoneNEWLINENEWLINE def worker(iterator):NEWLINE nonlocal worker_exc_infoNEWLINE while not abort.is_set() and not finished.is_set():NEWLINE try:NEWLINE with iterable_lock:NEWLINE with main_app_context:NEWLINE item = next(iterator)NEWLINE except StopIteration:NEWLINE finished.set()NEWLINE breakNEWLINENEWLINE with app.app_context():NEWLINE try:NEWLINE res = func(item, *args, **kwargs)NEWLINE except BaseException:NEWLINE worker_exc_info = sys.exc_info()NEWLINE finished.set()NEWLINE returnNEWLINE with result_lock:NEWLINE results.append(res)NEWLINENEWLINE it = iter(entries)NEWLINE threads = [threading.Thread(target=worker, name=f'worker/{i}', args=(it,))NEWLINE for i in enumerate(range(batch_size))]NEWLINENEWLINE for t in threads:NEWLINE t.start()NEWLINENEWLINE try:NEWLINE finished.wait()NEWLINE except KeyboardInterrupt:NEWLINE print('\nFinishing pending jobs before aborting')NEWLINE abort.set()NEWLINENEWLINE for t in threads:NEWLINE t.join()NEWLINENEWLINE if worker_exc_info:NEWLINE raise worker_exc_info[1].with_traceback(worker_exc_info[2])NEWLINENEWLINE return results, abort.is_set()NEWLINENEWLINE return wrapperNEWLINENEWLINENEWLINEdef format_query(query, placeholders):NEWLINE """Format and split the query into keywords and placeholders.NEWLINENEWLINE https://cern-search.docs.cern.ch/usage/operations/#advanced-queriesNEWLINENEWLINE :param query: search queryNEWLINE :param placeholders: placeholder whitelistNEWLINE :returns escaped queryNEWLINE """NEWLINE patt = r'(?:^|\s)({}):([^:"\s]+|"[^"]+")(?:$|\s)'.format('|'.join(map(re.escape, placeholders)))NEWLINE idx = 0NEWLINE keys = []NEWLINE for match in re.finditer(patt, query):NEWLINE placeholder = f'{placeholders[match.group(1)]}:{escape(match.group(2))}'NEWLINE if idx != match.start():NEWLINE keys.append(escape(query[idx:match.start()]))NEWLINE keys.append(placeholder)NEWLINE idx = match.end()NEWLINENEWLINE if idx != len(query):NEWLINE keys.append(escape(query[idx:len(query)]))NEWLINENEWLINE return ' '.join(keys).strip()NEWLINENEWLINENEWLINEdef format_filters(params, filters, range_filters):NEWLINE """Extract any special placeholder filter, such as ranges, from the query params.NEWLINENEWLINE https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html#_rangesNEWLINENEWLINE :param params: The filter query paramsNEWLINE :param filters: The filter whitelistNEWLINE :param range_filters: The range filter whitelistNEWLINE :returns: filters, extracted placeholdersNEWLINE """NEWLINE _filters = {}NEWLINE query = []NEWLINE for k, v in params.items():NEWLINE if k not in filters:NEWLINE continueNEWLINE if k in range_filters:NEWLINE match = re.match(r'[[{].+ TO .+[]}]', v)NEWLINE if match:NEWLINE query.append(f'+{range_filters[k]}:{v}')NEWLINE continueNEWLINE _filters[k] = vNEWLINE return _filters, ' '.join(query)NEWLINENEWLINENEWLINEdef escape(query):NEWLINE """Prepend all special ElasticSearch characters with a backslash."""NEWLINE patt = r'([+\-=><!(){}[\]\^~?:\\\/]|&&|\|\|)'NEWLINE return re.sub(patt, r'\\\1', query)NEWLINENEWLINENEWLINEdef remove_none_entries(obj):NEWLINE """Remove dict entries that are ``None``.NEWLINENEWLINE This is cascaded in case of nested dicts/collections.NEWLINE """NEWLINE if isinstance(obj, dict):NEWLINE return {k: remove_none_entries(v) for k, v in obj.items() if v is not None}NEWLINE elif isinstance(obj, (list, tuple, set)):NEWLINE return type(obj)(map(remove_none_entries, obj))NEWLINE return objNEWLINE
NEWLINENEWLINEdef add_(a,b):NEWLINE return a+bNEWLINENEWLINEdef sub_(a,b):NEWLINE return a-b
"""This is the one place the version number is stored."""NEWLINENEWLINE__version__ = '0.5.1'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 numpy as npNEWLINEimport streamlit as stNEWLINEimport pikapi.utils.loggingNEWLINENEWLINEimport pikapi.facelandmark_utils as fluNEWLINEfrom pikapi.head_gestures import YesOrNoEstimator, get_minmax_feature_from_base_dir, get_stateNEWLINENEWLINEdef detection_analysis_dashboard():NEWLINE # @st.cache(allow_output_mutation=True)NEWLINE def load_data(result_folder):NEWLINE return pikapi.utils.logging.HumanReadableLog.load_from_path(result_folder)NEWLINENEWLINE def get_from_box(box):NEWLINE return ((box[2] + box[0])/2 - 250)/50 * 0.05NEWLINENEWLINE def get_x_from_box(box):NEWLINE return ((box[3] + box[1])/2 - 425)NEWLINENEWLINE def get_positions(detection_lists):NEWLINE positions = []NEWLINE for detection_list in detection_lists:NEWLINE found = FalseNEWLINE for detection in detection_list[1]:NEWLINE if detection["label"] == "onahole":NEWLINE found = TrueNEWLINE positions.append(get_x_from_box(detection["box"]))NEWLINE breakNEWLINE NEWLINE if not found:NEWLINE if len(positions) == 0:NEWLINE positions.append(None)NEWLINE else:NEWLINE positions.append(positions[-1])NEWLINENEWLINE return positionsNEWLINENEWLINE def get_sequence_from_label(sequence, labels):NEWLINE assert(len(labels) > 0)NEWLINE previous_label = labels[0].dataNEWLINE partial_seq = []NEWLINE # st.write(labels)NEWLINE for elm, label in zip(sequence, labels):NEWLINE # st.write(label.data)NEWLINE if label.data == previous_label:NEWLINE partial_seq.append(elm)NEWLINE else:NEWLINE yield partial_seq, previous_labelNEWLINE partial_seq = []NEWLINE previous_label = label.dataNEWLINENEWLINE # Choose result dir.NEWLINE result_folders_dir = st.text_input("Location of result folders.", "output-data/")NEWLINE result_folders = sorted(list(next(os.walk(result_folders_dir))[1]), reverse=True)NEWLINE result_folder = st.selectbox("Result folder", result_folders)NEWLINENEWLINE logged_data = load_data(os.path.join("output-data", result_folder))NEWLINENEWLINE images = logged_data.get_images_with_timestamp('input_frame')NEWLINE multi_face_landmark_lists = logged_data.get_data("multi_face_landmarks")NEWLINE motion_labels = logged_data.get_data("motion_label")NEWLINENEWLINE label_to_values = {NEWLINE "Nodding": 1,NEWLINE "Shaking": -1,NEWLINE }NEWLINE label_values = [label_to_values[motion_label.data] if motion_label.data is not None else 0 for motion_label in motion_labels]NEWLINE assert(len(images) == len(multi_face_landmark_lists))NEWLINENEWLINE frame_index = st.slider("Index", 0, len(images))NEWLINENEWLINE st.image(images[frame_index].data)NEWLINE st.write(multi_face_landmark_lists[frame_index].data)NEWLINE st.write(flu.simple_face_direction(multi_face_landmark_lists[frame_index].data[0], only_direction=True))NEWLINE direction_ys = [NEWLINE flu.simple_face_direction(multi_face_landmarks.data[0], only_direction=True)[1] \NEWLINE if len(multi_face_landmarks.data) > 0 else NoneNEWLINE for multi_face_landmarks in multi_face_landmark_listsNEWLINE ]NEWLINE direction_xs = [NEWLINE flu.simple_face_direction(multi_face_landmarks.data[0], only_direction=True)[0] \NEWLINE if len(multi_face_landmarks.data) > 0 else NoneNEWLINE for multi_face_landmarks in multi_face_landmark_listsNEWLINE ]NEWLINE st.write(direction_ys)NEWLINE timestamps = [NEWLINE multi_face_landmarks.timestamp - multi_face_landmark_lists[0].timestampNEWLINE for multi_face_landmarks in multi_face_landmark_listsNEWLINE ]NEWLINE # aaa = range(0, )NEWLINE # predictions = [NEWLINE # get_state(multi_face_landmark_lists[:i])NEWLINE # for i in range(1, len(multi_face_landmark_lists))NEWLINE # ]NEWLINE estimator = YesOrNoEstimator()NEWLINE predictions = []NEWLINE for multi_face_landmark_list in multi_face_landmark_lists:NEWLINE predictions.append(estimator.get_state(multi_face_landmark_list))NEWLINENEWLINE assert len(timestamps) == len(motion_labels)NEWLINENEWLINE import plotly.graph_objects as goNEWLINE fig = go.Figure(NEWLINE data=[NEWLINE go.Scatter(x=timestamps, y=direction_ys, name="y", line = dict(width=4, dash='dot')),NEWLINE go.Scatter(x=timestamps, y=direction_xs, name="x", line = dict(width=4, dash='dot')),NEWLINE go.Scatter(x=timestamps, y=label_values, name="true", line = dict(width=2)),NEWLINE go.Scatter(x=timestamps, y=predictions, name="preds", line = dict(width=4, dash='dot')),NEWLINE ],NEWLINE )NEWLINE fig.update_layout(xaxis_title='timestamp')NEWLINE st.write(fig)NEWLINENEWLINE # for landmark_partial_seq, label in get_sequence_from_label(multi_face_landmark_lists, motion_labels):NEWLINE # if label == "Nodding" or label == "Shaking":NEWLINE # st.write(label)NEWLINE # st.write(get_minmax_feature_from_base_dir(landmark_partial_seq, None))NEWLINENEWLINENEWLINE def draw_landmark_2d_with_index(landmark, filter_ids=[]):NEWLINE import matplotlib.pyplot as pltNEWLINE fig = plt.figure()NEWLINE ax1 = fig.add_subplot(111)NEWLINENEWLINE for i, keypoint in enumerate(landmark):NEWLINE if len(filter_ids) == 0 or i in filter_ids:NEWLINE ax1.text(keypoint[0], keypoint[1], s=str(i))NEWLINENEWLINE # direction = flu.simple_face_direction(landmark)NEWLINE # direction = direction / np.linalg.norm(direction)NEWLINE # ax1.plot(direction[:,0], direction[:,1], direction[:,2])NEWLINE if len(filter_ids) == 0:NEWLINE ax1.scatter(landmark[:,0],landmark[:,1])NEWLINE else:NEWLINE ax1.scatter(landmark[filter_ids,0],landmark[filter_ids,1])NEWLINE # st.write(fig)NEWLINE plt.show()NEWLINENEWLINE st.plotly_chart(get_landmark_3d_with_index_v2(np.array(multi_face_landmark_lists[frame_index].data[0])))NEWLINENEWLINENEWLINEdef get_landmark_3d_with_index_v2(landmark):NEWLINE import plotly.graph_objects as goNEWLINE fig = go.Figure()NEWLINENEWLINE fig.add_trace(go.Scatter3d(NEWLINE x=landmark[:,0],NEWLINE y=landmark[:,1],NEWLINE z=landmark[:,2],NEWLINE mode='markers'NEWLINE ))NEWLINE NEWLINE fig.update_layout(NEWLINE scene=dict(NEWLINE aspectmode="manual",NEWLINE aspectratio=dict(NEWLINE x=1,NEWLINE y=1,NEWLINE z=1NEWLINE ),NEWLINE annotations=[NEWLINE dict(NEWLINE showarrow=False,NEWLINE xanchor="left",NEWLINE xshift=10,NEWLINE x=x,NEWLINE y=y,NEWLINE z=z,NEWLINE text=str(index)NEWLINE ) for index, (x,y,z) in enumerate(landmark)NEWLINE ]NEWLINE )NEWLINE )NEWLINE return figNEWLINENEWLINEdetection_analysis_dashboard()NEWLINE
#!/usr/bin/env python3NEWLINEimport globNEWLINEimport osNEWLINEfrom PIL import ImageNEWLINENEWLINEhdrs = []NEWLINEdata = []NEWLINEimgs = []NEWLINENEWLINEdef encode_pixels(img):NEWLINE r = ''NEWLINE img = [ (x[0] + x[1] + x[2] > 384 and '1' or '0') for x in img]NEWLINE for i in range(len(img) // 8):NEWLINE c = ''.join(img[i * 8 : i * 8 + 8])NEWLINE r += '0x%02x, ' % int(c, 2)NEWLINE return rNEWLINENEWLINEcnt = 0NEWLINEfor fn in sorted(glob.glob('*.png')):NEWLINE print('Processing:', fn)NEWLINE im = Image.open(fn)NEWLINE name = os.path.splitext(fn)[0]NEWLINE w, h = im.sizeNEWLINE if w % 8 != 0:NEWLINE raise Exception('Width must be divisable by 8! (%s is %dx%d)' % (fn, w, h))NEWLINE img = list(im.getdata())NEWLINE hdrs.append('extern const BITMAP bmp_%s;\n' % name)NEWLINE imgs.append('const BITMAP bmp_%s = {%d, %d, bmp_%s_data};\n' % (name, w, h, name))NEWLINE data.append('const uint8_t bmp_%s_data[] = { %s};\n' % (name, encode_pixels(img)))NEWLINE cnt += 1NEWLINENEWLINEwith open('../bitmaps.c', 'wt') as f:NEWLINE f.write('#include "bitmaps.h"\n\n')NEWLINE for i in range(cnt):NEWLINE f.write(data[i])NEWLINE f.write('\n')NEWLINE for i in range(cnt):NEWLINE f.write(imgs[i])NEWLINE f.close()NEWLINENEWLINEwith open('../bitmaps.h', 'wt') as f:NEWLINE f.write('''#ifndef __BITMAPS_H__NEWLINE#define __BITMAPS_H__NEWLINENEWLINE#include <stdint.h>NEWLINENEWLINEtypedef struct {NEWLINE uint8_t width, height;NEWLINE const uint8_t *data;NEWLINE} BITMAP;NEWLINENEWLINE''')NEWLINENEWLINE for i in range(cnt):NEWLINE f.write(hdrs[i])NEWLINENEWLINE f.write('\n#endif\n')NEWLINE f.close()NEWLINE
import mathNEWLINENEWLINEfrom engine.geometry import calcsNEWLINEfrom engine.geometry.obstacle.target import TargetNEWLINEfrom gui.draw import DEFAULT_DASHNEWLINEimport gui.drawNEWLINEimport numpy as npNEWLINENEWLINENEWLINEclass VertexTarget(Target):NEWLINENEWLINE def __init__(self, startPosition, velocity, normal, vertexAngle):NEWLINE Target.__init__(self, startPosition, velocity)NEWLINE self.normal = normalNEWLINE self.lowerCosLimit = math.cos(math.pi - vertexAngle / 2.0)NEWLINE self.upperCosLimit = math.cos(vertexAngle / 2.0)NEWLINE NEWLINE def testEntryVelocity(self, entryVelocity):NEWLINE """NEWLINE Is the given absolute velocity OK? Illegal velocities are ones which are headed "into" the shape and would cause an immediate collision.NEWLINE """NEWLINE relativeVelocity = calcs.unit(entryVelocity - self.velocity)NEWLINE cosEntryAngle = np.dot(relativeVelocity, self.normal)NEWLINE return cosEntryAngle <= self.upperCosLimit and cosEntryAngle >= self.lowerCosLimit NEWLINENEWLINE def draw(self, visualizer, **kwargs):NEWLINE gui.draw.drawCircle(visualizer, self.position, 4.0, dash=DEFAULT_DASH)NEWLINE
#!/usr/bin/pythonNEWLINENEWLINEimport roslibNEWLINEimport rospyNEWLINEimport numpy as npNEWLINEimport zmqNEWLINEimport mathNEWLINEfrom sensor_msgs.msg import JointStateNEWLINEglobal joint_poses, socketNEWLINENEWLINEjoint_poses = [90,90,90]NEWLINENEWLINEport = "5556"NEWLINENEWLINEcontext = zmq.Context()NEWLINEsocket = context.socket(zmq.PUB)NEWLINEsocket.bind("tcp://*:%s" % port)NEWLINENEWLINEdef callback(msg):NEWLINE global joint_poses, socketNEWLINE joint_poses[0] = math.degrees(msg.position[0])+90NEWLINE joint_poses[1] = math.degrees(-msg.position[1])+90NEWLINE joint_poses[2] = math.degrees(msg.position[2])+90NEWLINE x_arrstr = np.char.mod('%f', np.array(joint_poses))NEWLINE messagedata = ",".join(x_arrstr)NEWLINE socket.send(messagedata)NEWLINENEWLINEif __name__ == "__main__":NEWLINE rospy.init_node('JointState_Servo')NEWLINE joint_poses[0] = 90NEWLINE joint_poses[1] = 90NEWLINE joint_poses[2] = 90NEWLINE rospy.Subscriber("joint_states", JointState, callback)NEWLINE rospy.spin()NEWLINE
"""NEWLINEThis module contains the main image processing class for the currentNEWLINEsetup with the camera beneath the chess board. It uses colorsNEWLINEto distinguish among the pieces. It also has a setup mode toNEWLINEinitialize the location of the center of each square on the board.NEWLINE"""NEWLINEimport cv2NEWLINEimport numpy as npNEWLINEimport bisectNEWLINEimport mathNEWLINEimport operatorNEWLINEfrom PIL import ImageNEWLINEfrom camera.setup_board import get_square_centers_from_boardNEWLINENEWLINE# TODO: refactor to put all code and magic numbers in here, but for nowNEWLINE# just importing the other working modulesNEWLINENEWLINE# TODO put this in the classNEWLINEdef open_image(image_path):NEWLINE """Simple wrapper to load an image obj from an image file."""NEWLINE with open(image_path, 'rb') as image_file:NEWLINE image = Image.open(image_file)NEWLINE image.load()NEWLINE return imageNEWLINENEWLINEclass BoardProcessor:NEWLINE """NEWLINE You can poll the BoardProcessor at any time to get the currentNEWLINE state from the last image it successfully processed.NEWLINE """NEWLINENEWLINE def __init__(self, debug_image_mode=False):NEWLINE self._num_squares = 8 # Width of board, standard chess boardNEWLINE self._contour_len_threshold = 10 # Perimeter of shape in pixelsNEWLINE self._centers = []NEWLINE self._cur_state = [ [None for x in xrange(self._num_squares)] for x in xrange(self._num_squares) ]NEWLINE self._debug_images = debug_image_modeNEWLINE self._color_map = {'WB': (np.array([110, 50, 50]), # light blueNEWLINE np.array([130, 255, 255])),NEWLINE # Also BK with dotNEWLINE 'BB': (np.array([222, 50, 50]), # dark blueNEWLINE np.array([243, 255, 255])),NEWLINE # Also BR with dotNEWLINE 'WP': (np.array([57, 50, 50]), # greenNEWLINE np.array([96, 255, 255])),NEWLINE # also BQ with dotNEWLINE 'WR': (np.array([110, 50, 50]), # purpleNEWLINE np.array([130, 255, 255])),NEWLINE # also WK with dot - this seems to be offNEWLINE 'BP': (np.array([351, 50, 50]), # redNEWLINE np.array([360, 255, 255])),NEWLINE # also WQ with dotNEWLINE 'WP': (np.array([25, 50, 50]), # yellowNEWLINE np.array([55, 255, 255])),NEWLINE # also WK with dotNEWLINE }NEWLINENEWLINE def set_color_map(self, color_map):NEWLINE self._color_map = color_mapNEWLINENEWLINE def _cache_pil_im(self, image_path):NEWLINE self._pil_im = open_image(image_path)NEWLINENEWLINE def _open_image(self, image_path):NEWLINE self._cache_pil_im(image_path)NEWLINE return cv2.imread(image_path)NEWLINENEWLINE def _show_image(self, im_array, title='image', show_this_image=False):NEWLINE if self._debug_images or show_this_image:NEWLINE cv2.imshow(title, im_array)NEWLINE cv2.waitKey(0)NEWLINENEWLINE def update_state(self, image):NEWLINE state = self.get_board_state(image)NEWLINE if state != self._cur_state:NEWLINE self._cur_state = stateNEWLINENEWLINE def get_cur_state(self):NEWLINE return self._cur_stateNEWLINENEWLINE def setup_board(self, image_path):NEWLINE """Get the center of each square from a given board image,NEWLINE corresponding to it's i-j position in a 2d array (representingNEWLINE the board state).NEWLINE """NEWLINE self._centers = self._sort_centers(NEWLINE get_square_centers_from_board(image_path, self._num_squares))NEWLINENEWLINE def _setup_default_board(self):NEWLINE """For the case when we don't have time to put all the littleNEWLINE squares.NEWLINE NEWLINE I apologize for the formatting but I am a monster."""NEWLINE self._centers={(387, 440): (7, 6), (190, 192): (3, 3), (82, 384): (6, 1), (210, 445): (7, 3), (21, 383): (6, 0), (327, 444): (7, 5), (20, 135): (2, 0), (71, 256): (4, 1), (477, 130): (2, 7), (452, 437): (7, 7), (196, 258): (4, 3), (460, 316): (5, 7), (20, 78): (1, 0), (74, 319): (5, 1), (397, 65): (1, 6), (69, 138): (2, 1), (73, 79): (1, 1), (331, 8): (0, 5),(455, 379): (6, 7), (25, 19): (0, 0), (326, 126): (2, 5),(198, 67): (1, 3), (129, 133): (2, 2), (139, 321): (5, 2),(194, 128): (2, 3), (269, 320): (5, 4), (265, 7): (0, 4),(132, 10): (0, 2), (454, 9): (0, 7), (340, 184): (3, 5),(203, 386): (6, 3), (395, 9): (0, 6), (273, 445): (7, 4),(200, 9): (0, 3), (263, 62): (1, 4), (332, 320): (5, 5),(458, 65): (1, 7), (140, 388): (6, 2), (145, 442): (7, 2),(131, 71): (1, 2), (394, 253): (4, 6), (338, 389): (6, 5),(17, 260): (4, 0), (330, 255): (4, 5), (269, 385): (6, 4),(136, 259): (4, 2), (32, 437): (7, 0), (16, 202): (3, 0),(398, 190): (3, 6), (76, 13): (0, 1), (21, 321): (5, 0),(262, 129): (2, 4), (69, 199): (3, 1), (395, 387): (6, 6),(390, 126): (2, 6), (399, 317): (5, 6), (264, 190): (3, 4),(262, 258): (4, 4), (130, 194): (3, 2), (460, 253): (4, 7),(458, 188): (3, 7), (89, 439): (7, 1), (198, 321): (5, 3),(330, 66): (1, 5)}NEWLINENEWLINENEWLINE def _sort_centers(self, centers):NEWLINE """Sort the centers into a 2D array.NEWLINENEWLINE Take the (min, min), and then for each point get the vector from theNEWLINE min to that point. Sort the vectors by length, and multiply by theNEWLINE jacobian. Just kidding. I'm not clever.NEWLINENEWLINE If everything were not warped, we would be making a transformationNEWLINE from (i*w, j*h) = i, j -> However, things are warped. So. Nope.NEWLINENEWLINE Alright, what if we just sort by y, break it into rows of 8, thenNEWLINE sort by x, and then store point -> (i, j) pairNEWLINENEWLINE Return:NEWLINE The 2D array of the center points, in their proper i,j position.NEWLINE """NEWLINE center_dict = {}NEWLINE center_array = [] # purely for quick visualization and debuggingNEWLINE sorted_by_y = centers[:]NEWLINE sorted_by_y.sort(key=operator.itemgetter(1))NEWLINE for i in range(self._num_squares):NEWLINE row = sorted_by_y[i*self._num_squares:(i+1)*self._num_squares]NEWLINE row.sort()NEWLINE for j, point in enumerate(row):NEWLINE center_dict[point] = (i, j)NEWLINE center_array.append(row)NEWLINE if self._debug_images:NEWLINE print 'Got centers of board:'NEWLINE for row in center_array:NEWLINE print rowNEWLINE return center_dictNEWLINENEWLINE def _point_within_square(self, shape_center, half_square_threshold):NEWLINE """Get the i,j coordinate of the square center closest to this pointNEWLINE and test whether it is within the half-square threshold"""NEWLINE dists = []NEWLINE for square_center in self._centers:NEWLINE bisect.insort(dists, (np.linalg.norm(np.array(square_center) -NEWLINE np.array(shape_center)),NEWLINE square_center))NEWLINE assert len(dists) > 0, ('Got no dists from ', str(shape_center),NEWLINE str(self._centers))NEWLINE if dists[0][0] < half_square_threshold:NEWLINE if self._debug_images:NEWLINE print('dists [0] = ', dists[0], '< ', half_square_threshold)NEWLINE return self._centers[dists[0][1]]NEWLINENEWLINE def _shape_in_square(self, image):NEWLINE centers = self._get_centers(image)NEWLINE if len(centers) > 0:NEWLINE return TrueNEWLINE return FalseNEWLINENEWLINENEWLINE def get_board_state(self, image):NEWLINE """Breaks the image into an image per square, and looks at a radius around the centerNEWLINE of each square to see if it has a piece in it. NEWLINENEWLINE Returns the board stateNEWLINE """NEWLINE if not self._centers:NEWLINE self._setup_default_board()NEWLINE height, width, channels = image.shapeNEWLINE radius = height/(self._num_squares*2)NEWLINE board = [ [None for x in xrange(self._num_squares)] for x in xrange(self._num_squares)]NEWLINE for pixels, indices in self._centers.items():NEWLINE NEWLINE cropped = self._pil_im.crop((pixels[0] - radius, pixels[1] - radius, pixels[0] + radius, pixels[1] + radius))NEWLINENEWLINE im = np.array(cropped)NEWLINE NEWLINE if self._get_circle_in_square(im):NEWLINE board[indices[0]][indices[1]] = TrueNEWLINENEWLINE# for piece, color_range in self._color_map.items():NEWLINE# #filtered_square = self._get_convolved_image(im, color_range)NEWLINE# if self._debug_images:NEWLINE# self._show_image(filtered_square, 'filtered square')NEWLINE# if self._shape_in_square(filtered_square):NEWLINE# # just early out - don't check the other color options...NEWLINE# # may want to change this later...we'll see how noisy it isNEWLINE# board[indices[0]][indices[1]] = pieceNEWLINE return boardNEWLINENEWLINENEWLINE def get_board_state_retired(self, image):NEWLINE """Return the state of the board (in terms of pieces in eachNEWLINE square) from the given board image.NEWLINENEWLINE Centers are np.arrays, which have point-like behavior for subtraction.NEWLINE """NEWLINE if not self._centers:NEWLINE self._setup_default_board()NEWLINE height, width, channels = image.shapeNEWLINE half_square_threshold = height / (self._num_squares * 2)NEWLINE # Fun python fact - the code commented below makes copies of each listNEWLINE # board = [ [0]*self._num_squares ]*self._num_squaresNEWLINE board = [ [None for x in xrange(self._num_squares)]NEWLINE for x in xrange(self._num_squares)]NEWLINE # Get a convolved image for each color in our color mapNEWLINE for piece, color_range in self._color_map.items():NEWLINE filtered_image = self._get_convolved_image(image, color_range)NEWLINE if self._debug_images:NEWLINE print('Now for piece', piece, 'color range', color_range)NEWLINE self._show_image(filtered_image, 'convolved')NEWLINE # I love O(n**2). As sweet as microwaved bananas.NEWLINE for shape_center in self._get_centers(filtered_image):NEWLINE if self._debug_images:NEWLINE print('Now for shape center', shape_center)NEWLINE coords = self._point_within_square(shape_center,NEWLINE half_square_threshold)NEWLINE if self._debug_images:NEWLINE print('coordinate = ', coords)NEWLINE if coords is not None:NEWLINE board[coords[0]][coords[1]] = pieceNEWLINE return boardNEWLINENEWLINE def _get_circle_in_square(self, im):NEWLINENEWLINE imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)NEWLINE #circle = self._get_circle(imgray)NEWLINE self._show_image(imgray)NEWLINE# Night time Treshold values # TODO make this something you pass in from the command line NEWLINE ret,thresh = cv2.threshold(imgray,182,222,0)NEWLINE# Day Time Treshold values and invertNEWLINE# ret,thresh = cv2.threshold(imgray,100,160,0)NEWLINE# thresh = cv2.bitwise_not(thresh)NEWLINE # print 'thresh = ', threshNEWLINE self._show_image(thresh)NEWLINE mask = cv2.inRange(thresh, 100, 255)NEWLINE self._show_image(mask)NEWLINENEWLINE # RETR_LIST=1, CHAIN_APPROX_SIMPLE=2NEWLINE contours, heirarchy = cv2.findContours(NEWLINE mask, cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)NEWLINE #cv2.drawContours(im, contours, -1, (0,255,0), 3)NEWLINE circles = []NEWLINE for cnt in contours:NEWLINE (x,y),radius = cv2.minEnclosingCircle(cnt)NEWLINE center = (int(x),int(y))NEWLINE radius = int(radius)NEWLINE area = cv2.contourArea(cnt)NEWLINE circle_area = math.pi * radius**2NEWLINE if circle_area < 250.0 or abs(area - circle_area) > 100.0: # Arbitrary magic thresholdNEWLINE continueNEWLINE if self._debug_images:NEWLINE print("center",center)NEWLINE print("radius",radius)NEWLINE if radius < 5 or radius > 15:NEWLINE continueNEWLINE if self._debug_images:NEWLINE print 'contour area =', area, 'circle_area = ', circle_areaNEWLINE NEWLINE cv2.circle(im, center, radius, (0, 255, 0), 2)NEWLINE self._show_image(im, show_this_image=False)NEWLINE circles.append(center)NEWLINE if len(circles) == 1:NEWLINE return TrueNEWLINE elif len(circles) > 1:NEWLINE print '\033[31;1m SOMETHING WEIRD HERE...\033[0m', circlesNEWLINE else:NEWLINE return FalseNEWLINE def _get_circle(self, im):NEWLINE contours, heirarchy = cv2.findContours(NEWLINE im, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)NEWLINENEWLINE for cnt in contours:NEWLINE if cv2.isContourConvex(cnt):NEWLINE self._show_image(im)NEWLINE return TrueNEWLINE return FalseNEWLINENEWLINENEWLINENEWLINENEWLINE def _get_convolved_image(self, image, color_range):NEWLINE """Get an image mask filtered to just the locations of a certainNEWLINE color within the provided color range.NEWLINE """NEWLINE lower, upper = color_rangeNEWLINE # put into HSV color space because hue is more reliable - RGB variesNEWLINE # based on brightness - so we would have lots of possible valuesNEWLINE hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)NEWLINE self._show_image(hsv, 'HSV')NEWLINENEWLINE # Threshold the HSV image to get only colors within the rangeNEWLINE mask = cv2.inRange(hsv, lower, upper) # TODO is it actually moreNEWLINE # optimal to overwrite?NEWLINE self._show_image(mask, 'Masked by ' + str(lower) + str(upper))NEWLINENEWLINE # Blur the mask - this helps bring out more of the colored pixelsNEWLINE blurred = cv2.GaussianBlur(mask, (5, 5), 0)NEWLINE self._show_image(blurred, 'Blurred')NEWLINENEWLINE # Dilate the image to make the blue spots biggerNEWLINE # TODO: figure out which dilate configuration makes the best shapesNEWLINE kernel = cv2.getStructuringElement((cv2.MORPH_DILATE), (4, 4))NEWLINE dilated = cv2.dilate(blurred, kernel, iterations=5)NEWLINE self._show_image(dilated, 'Dilated')NEWLINENEWLINE # TODO: threshold one more timeNEWLINE thresh = 127NEWLINE im_bw = cv2.threshold(dilated, thresh, 255, cv2.THRESH_BINARY)[1]NEWLINE self._show_image(im_bw, 'Threshold')NEWLINENEWLINE return im_bwNEWLINENEWLINE def _get_centers(self, image):NEWLINE """Image needs to be a masked image, easily contourizable."""NEWLINE centers = []NEWLINE contours, heirarchy = cv2.findContours(NEWLINE image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)NEWLINENEWLINE # Filter out small contours around noiseNEWLINE cnts = [c for c in contours if len(c) > self._contour_len_threshold]NEWLINE for c in cnts:NEWLINE # compute the center of the contourNEWLINE M = cv2.moments(c)NEWLINE denom = M["m00"]NEWLINE if denom == 0:NEWLINE continueNEWLINE cX = int(M["m10"] / denom)NEWLINE cY = int(M["m01"] / denom)NEWLINENEWLINE # Insert center into our list of centersNEWLINE bisect.insort(centers, (cX, cY))NEWLINENEWLINE # draw the contour and center of the shape on the imageNEWLINE cv2.drawContours(image, [c], -1, (0, 255, 0), 2)NEWLINE cv2.circle(image, (cX, cY), 7, (255, 255, 255), -1)NEWLINE cv2.putText(image, "center", (cX - 20, cY - 20),NEWLINE cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)NEWLINENEWLINE self._show_image(image, 'Centers')NEWLINE return centersNEWLINENEWLINE
for c in range(0,51):NEWLINE if c % 2 == 0:NEWLINE print(c)NEWLINEprint('Programa Finalizado')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
'''cron function.NEWLINENEWLINEScans the user table and, for each user, invokes one lambda checker.NEWLINEIf the check generates an alert, invokes mailer lambda to notify the user.'''NEWLINEfrom sslnotifyme import (lambda_db, lambda_checker, lambda_main_wrapper, LOGGER)NEWLINENEWLINENEWLINEclass Cron(object):NEWLINE '''Cron object class.'''NEWLINENEWLINE @staticmethodNEWLINE def scan_and_notify_alerts_queue():NEWLINE '''Trigger a lambda checker for each validated user.'''NEWLINE counter = 0NEWLINE for record in lambda_db('get_validated_users').get('response'):NEWLINE lambda_checker('check_and_send_alert', record)NEWLINE counter += 1NEWLINE msg = '%d record(s) processed successfully' % counterNEWLINE LOGGER.info(msg)NEWLINE return {'response': msg}NEWLINENEWLINENEWLINE# pylint: disable=unused-argumentNEWLINEdef lambda_main(event, context):NEWLINE '''Lambda entry point.'''NEWLINE return lambda_main_wrapper(event, Cron,NEWLINE default=['scan_and_notify_alerts_queue'])NEWLINE
"""Support to select a date and/or a time."""NEWLINEimport datetimeNEWLINEimport loggingNEWLINEimport typingNEWLINENEWLINEimport voluptuous as volNEWLINENEWLINEfrom homeassistant.const import (NEWLINE ATTR_DATE,NEWLINE ATTR_EDITABLE,NEWLINE ATTR_TIME,NEWLINE CONF_ICON,NEWLINE CONF_ID,NEWLINE CONF_NAME,NEWLINE SERVICE_RELOAD,NEWLINE)NEWLINEfrom homeassistant.core import callbackNEWLINEfrom homeassistant.helpers import collectionNEWLINEimport homeassistant.helpers.config_validation as cvNEWLINEfrom homeassistant.helpers.entity_component import EntityComponentNEWLINEfrom homeassistant.helpers.restore_state import RestoreEntityNEWLINEimport homeassistant.helpers.serviceNEWLINEfrom homeassistant.helpers.storage import StoreNEWLINEfrom homeassistant.helpers.typing import ConfigType, HomeAssistantType, ServiceCallTypeNEWLINEfrom homeassistant.util import dt as dt_utilNEWLINENEWLINE_LOGGER = logging.getLogger(__name__)NEWLINENEWLINEDOMAIN = "input_datetime"NEWLINENEWLINECONF_HAS_DATE = "has_date"NEWLINECONF_HAS_TIME = "has_time"NEWLINECONF_INITIAL = "initial"NEWLINENEWLINEDEFAULT_VALUE = "1970-01-01 00:00:00"NEWLINEDEFAULT_DATE = datetime.date(1970, 1, 1)NEWLINEDEFAULT_TIME = datetime.time(0, 0, 0)NEWLINENEWLINEATTR_DATETIME = "datetime"NEWLINENEWLINESERVICE_SET_DATETIME = "set_datetime"NEWLINESTORAGE_KEY = DOMAINNEWLINESTORAGE_VERSION = 1NEWLINENEWLINECREATE_FIELDS = {NEWLINE vol.Required(CONF_NAME): vol.All(str, vol.Length(min=1)),NEWLINE vol.Optional(CONF_HAS_DATE, default=False): cv.boolean,NEWLINE vol.Optional(CONF_HAS_TIME, default=False): cv.boolean,NEWLINE vol.Optional(CONF_ICON): cv.icon,NEWLINE vol.Optional(CONF_INITIAL): cv.string,NEWLINE}NEWLINEUPDATE_FIELDS = {NEWLINE vol.Optional(CONF_NAME): cv.string,NEWLINE vol.Optional(CONF_HAS_DATE): cv.boolean,NEWLINE vol.Optional(CONF_HAS_TIME): cv.boolean,NEWLINE vol.Optional(CONF_ICON): cv.icon,NEWLINE vol.Optional(CONF_INITIAL): cv.string,NEWLINE}NEWLINENEWLINENEWLINEdef has_date_or_time(conf):NEWLINE """Check at least date or time is true."""NEWLINE if conf[CONF_HAS_DATE] or conf[CONF_HAS_TIME]:NEWLINE return confNEWLINENEWLINE raise vol.Invalid("Entity needs at least a date or a time")NEWLINENEWLINENEWLINECONFIG_SCHEMA = vol.Schema(NEWLINE {NEWLINE DOMAIN: cv.schema_with_slug_keys(NEWLINE vol.All(NEWLINE {NEWLINE vol.Optional(CONF_NAME): cv.string,NEWLINE vol.Optional(CONF_HAS_DATE, default=False): cv.boolean,NEWLINE vol.Optional(CONF_HAS_TIME, default=False): cv.boolean,NEWLINE vol.Optional(CONF_ICON): cv.icon,NEWLINE vol.Optional(CONF_INITIAL): cv.string,NEWLINE },NEWLINE has_date_or_time,NEWLINE )NEWLINE )NEWLINE },NEWLINE extra=vol.ALLOW_EXTRA,NEWLINE)NEWLINERELOAD_SERVICE_SCHEMA = vol.Schema({})NEWLINENEWLINENEWLINEasync def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool:NEWLINE """Set up an input datetime."""NEWLINE component = EntityComponent(_LOGGER, DOMAIN, hass)NEWLINE id_manager = collection.IDManager()NEWLINENEWLINE yaml_collection = collection.YamlCollection(NEWLINE logging.getLogger(f"{__name__}.yaml_collection"), id_managerNEWLINE )NEWLINE collection.attach_entity_component_collection(NEWLINE component, yaml_collection, InputDatetime.from_yamlNEWLINE )NEWLINENEWLINE storage_collection = DateTimeStorageCollection(NEWLINE Store(hass, STORAGE_VERSION, STORAGE_KEY),NEWLINE logging.getLogger(f"{__name__}.storage_collection"),NEWLINE id_manager,NEWLINE )NEWLINE collection.attach_entity_component_collection(NEWLINE component, storage_collection, InputDatetimeNEWLINE )NEWLINENEWLINE await yaml_collection.async_load(NEWLINE [{CONF_ID: id_, **cfg} for id_, cfg in config.get(DOMAIN, {}).items()]NEWLINE )NEWLINE await storage_collection.async_load()NEWLINENEWLINE collection.StorageCollectionWebsocket(NEWLINE storage_collection, DOMAIN, DOMAIN, CREATE_FIELDS, UPDATE_FIELDSNEWLINE ).async_setup(hass)NEWLINENEWLINE collection.attach_entity_registry_cleaner(hass, DOMAIN, DOMAIN, yaml_collection)NEWLINE collection.attach_entity_registry_cleaner(hass, DOMAIN, DOMAIN, storage_collection)NEWLINENEWLINE async def reload_service_handler(service_call: ServiceCallType) -> None:NEWLINE """Reload yaml entities."""NEWLINE conf = await component.async_prepare_reload(skip_reset=True)NEWLINE if conf is None:NEWLINE conf = {DOMAIN: {}}NEWLINE await yaml_collection.async_load(NEWLINE [{CONF_ID: id_, **cfg} for id_, cfg in conf.get(DOMAIN, {}).items()]NEWLINE )NEWLINENEWLINE homeassistant.helpers.service.async_register_admin_service(NEWLINE hass,NEWLINE DOMAIN,NEWLINE SERVICE_RELOAD,NEWLINE reload_service_handler,NEWLINE schema=RELOAD_SERVICE_SCHEMA,NEWLINE )NEWLINENEWLINE async def async_set_datetime_service(entity, call):NEWLINE """Handle a call to the input datetime 'set datetime' service."""NEWLINE time = call.data.get(ATTR_TIME)NEWLINE date = call.data.get(ATTR_DATE)NEWLINE dttm = call.data.get(ATTR_DATETIME)NEWLINE if (NEWLINE dttmNEWLINE and (date or time)NEWLINE or entity.has_dateNEWLINE and not (date or dttm)NEWLINE or entity.has_timeNEWLINE and not (time or dttm)NEWLINE ):NEWLINE _LOGGER.error(NEWLINE "Invalid service data for %s input_datetime.set_datetime: %s",NEWLINE entity.entity_id,NEWLINE str(call.data),NEWLINE )NEWLINE returnNEWLINENEWLINE if dttm:NEWLINE date = dttm.date()NEWLINE time = dttm.time()NEWLINE entity.async_set_datetime(date, time)NEWLINENEWLINE component.async_register_entity_service(NEWLINE SERVICE_SET_DATETIME,NEWLINE {NEWLINE vol.Optional(ATTR_DATE): cv.date,NEWLINE vol.Optional(ATTR_TIME): cv.time,NEWLINE vol.Optional(ATTR_DATETIME): cv.datetime,NEWLINE },NEWLINE async_set_datetime_service,NEWLINE )NEWLINENEWLINE return TrueNEWLINENEWLINENEWLINEclass DateTimeStorageCollection(collection.StorageCollection):NEWLINE """Input storage based collection."""NEWLINENEWLINE CREATE_SCHEMA = vol.Schema(vol.All(CREATE_FIELDS, has_date_or_time))NEWLINE UPDATE_SCHEMA = vol.Schema(UPDATE_FIELDS)NEWLINENEWLINE async def _process_create_data(self, data: typing.Dict) -> typing.Dict:NEWLINE """Validate the config is valid."""NEWLINE return self.CREATE_SCHEMA(data)NEWLINENEWLINE @callbackNEWLINE def _get_suggested_id(self, info: typing.Dict) -> str:NEWLINE """Suggest an ID based on the config."""NEWLINE return info[CONF_NAME]NEWLINENEWLINE async def _update_data(self, data: dict, update_data: typing.Dict) -> typing.Dict:NEWLINE """Return a new updated data object."""NEWLINE update_data = self.UPDATE_SCHEMA(update_data)NEWLINE return has_date_or_time({**data, **update_data})NEWLINENEWLINENEWLINEclass InputDatetime(RestoreEntity):NEWLINE """Representation of a datetime input."""NEWLINENEWLINE def __init__(self, config: typing.Dict) -> None:NEWLINE """Initialize a select input."""NEWLINE self._config = configNEWLINE self.editable = TrueNEWLINE self._current_datetime = NoneNEWLINE initial = config.get(CONF_INITIAL)NEWLINE if initial:NEWLINE if self.has_date and self.has_time:NEWLINE self._current_datetime = dt_util.parse_datetime(initial)NEWLINE elif self.has_date:NEWLINE date = dt_util.parse_date(initial)NEWLINE self._current_datetime = datetime.datetime.combine(date, DEFAULT_TIME)NEWLINE else:NEWLINE time = dt_util.parse_time(initial)NEWLINE self._current_datetime = datetime.datetime.combine(DEFAULT_DATE, time)NEWLINENEWLINE @classmethodNEWLINE def from_yaml(cls, config: typing.Dict) -> "InputDatetime":NEWLINE """Return entity instance initialized from yaml storage."""NEWLINE input_dt = cls(config)NEWLINE input_dt.entity_id = f"{DOMAIN}.{config[CONF_ID]}"NEWLINE input_dt.editable = FalseNEWLINE return input_dtNEWLINENEWLINE async def async_added_to_hass(self):NEWLINE """Run when entity about to be added."""NEWLINE await super().async_added_to_hass()NEWLINENEWLINE # Priority 1: Initial valueNEWLINE if self.state is not None:NEWLINE returnNEWLINENEWLINE # Priority 2: Old stateNEWLINE old_state = await self.async_get_last_state()NEWLINE if old_state is None:NEWLINE self._current_datetime = dt_util.parse_datetime(DEFAULT_VALUE)NEWLINE returnNEWLINENEWLINE if self.has_date and self.has_time:NEWLINE date_time = dt_util.parse_datetime(old_state.state)NEWLINE if date_time is None:NEWLINE self._current_datetime = dt_util.parse_datetime(DEFAULT_VALUE)NEWLINE returnNEWLINE self._current_datetime = date_timeNEWLINE elif self.has_date:NEWLINE date = dt_util.parse_date(old_state.state)NEWLINE if date is None:NEWLINE self._current_datetime = dt_util.parse_datetime(DEFAULT_VALUE)NEWLINE returnNEWLINE self._current_datetime = datetime.datetime.combine(date, DEFAULT_TIME)NEWLINE else:NEWLINE time = dt_util.parse_time(old_state.state)NEWLINE if time is None:NEWLINE self._current_datetime = dt_util.parse_datetime(DEFAULT_VALUE)NEWLINE returnNEWLINE self._current_datetime = datetime.datetime.combine(DEFAULT_DATE, time)NEWLINENEWLINE @propertyNEWLINE def should_poll(self):NEWLINE """If entity should be polled."""NEWLINE return FalseNEWLINENEWLINE @propertyNEWLINE def name(self):NEWLINE """Return the name of the select input."""NEWLINE return self._config.get(CONF_NAME)NEWLINENEWLINE @propertyNEWLINE def has_date(self) -> bool:NEWLINE """Return True if entity has date."""NEWLINE return self._config[CONF_HAS_DATE]NEWLINENEWLINE @propertyNEWLINE def has_time(self) -> bool:NEWLINE """Return True if entity has time."""NEWLINE return self._config[CONF_HAS_TIME]NEWLINENEWLINE @propertyNEWLINE def icon(self):NEWLINE """Return the icon to be used for this entity."""NEWLINE return self._config.get(CONF_ICON)NEWLINENEWLINE @propertyNEWLINE def state(self):NEWLINE """Return the state of the component."""NEWLINE if self._current_datetime is None:NEWLINE return NoneNEWLINENEWLINE if self.has_date and self.has_time:NEWLINE return self._current_datetimeNEWLINE if self.has_date:NEWLINE return self._current_datetime.date()NEWLINE return self._current_datetime.time()NEWLINENEWLINE @propertyNEWLINE def state_attributes(self):NEWLINE """Return the state attributes."""NEWLINE attrs = {NEWLINE ATTR_EDITABLE: self.editable,NEWLINE CONF_HAS_DATE: self.has_date,NEWLINE CONF_HAS_TIME: self.has_time,NEWLINE }NEWLINENEWLINE if self._current_datetime is None:NEWLINE return attrsNEWLINENEWLINE if self.has_date and self._current_datetime is not None:NEWLINE attrs["year"] = self._current_datetime.yearNEWLINE attrs["month"] = self._current_datetime.monthNEWLINE attrs["day"] = self._current_datetime.dayNEWLINENEWLINE if self.has_time and self._current_datetime is not None:NEWLINE attrs["hour"] = self._current_datetime.hourNEWLINE attrs["minute"] = self._current_datetime.minuteNEWLINE attrs["second"] = self._current_datetime.secondNEWLINENEWLINE if not self.has_date:NEWLINE attrs["timestamp"] = (NEWLINE self._current_datetime.hour * 3600NEWLINE + self._current_datetime.minute * 60NEWLINE + self._current_datetime.secondNEWLINE )NEWLINE elif not self.has_time:NEWLINE extended = datetime.datetime.combine(NEWLINE self._current_datetime, datetime.time(0, 0)NEWLINE )NEWLINE attrs["timestamp"] = extended.timestamp()NEWLINE else:NEWLINE attrs["timestamp"] = self._current_datetime.timestamp()NEWLINENEWLINE return attrsNEWLINENEWLINE @propertyNEWLINE def unique_id(self) -> typing.Optional[str]:NEWLINE """Return unique id of the entity."""NEWLINE return self._config[CONF_ID]NEWLINENEWLINE @callbackNEWLINE def async_set_datetime(self, date_val, time_val):NEWLINE """Set a new date / time."""NEWLINE if self.has_date and self.has_time and date_val and time_val:NEWLINE self._current_datetime = datetime.datetime.combine(date_val, time_val)NEWLINE elif self.has_date and not self.has_time and date_val:NEWLINE self._current_datetime = datetime.datetime.combine(NEWLINE date_val, self._current_datetime.time()NEWLINE )NEWLINE if self.has_time and not self.has_date and time_val:NEWLINE self._current_datetime = datetime.datetime.combine(NEWLINE self._current_datetime.date(), time_valNEWLINE )NEWLINENEWLINE self.async_write_ha_state()NEWLINENEWLINE async def async_update_config(self, config: typing.Dict) -> None:NEWLINE """Handle when the config is updated."""NEWLINE self._config = configNEWLINE self.async_write_ha_state()NEWLINE
[ ## this file was manually modified by jtNEWLINE {NEWLINE 'functor' : {NEWLINE 'arity' : '1',NEWLINE 'call_types' : [],NEWLINE 'ret_arity' : '0',NEWLINE 'rturn' : {NEWLINE 'default' : 'T',NEWLINE },NEWLINE 'simd_types' : [],NEWLINE 'special' : ['fdlibm'],NEWLINE 'type_defs' : [],NEWLINE 'types' : ['real_'],NEWLINE },NEWLINE 'info' : 'manually modified',NEWLINE 'unit' : {NEWLINE 'global_header' : {NEWLINE 'first_stamp' : 'created by jt the 03/03/2011',NEWLINE 'included' : ['#include <nt2/include/functions/atan.hpp>'],NEWLINE 'notes' : [],NEWLINE 'stamp' : 'modified by jt the 03/03/2011',NEWLINE },NEWLINE 'ranges' : {NEWLINE 'default' : [['T(-1)', 'T(1)']],NEWLINE },NEWLINE 'specific_values' : {NEWLINE },NEWLINE 'verif_test' : {NEWLINE 'property_call' : {NEWLINE 'default' : ['nt2::fdlibm::atan(a0)'],NEWLINE },NEWLINE 'property_value' : {NEWLINE 'default' : ['nt2::atan(a0)'],NEWLINE },NEWLINE 'simd' : {NEWLINE },NEWLINE 'ulp_thresh' : {NEWLINE 'default' : ['1'],NEWLINE },NEWLINE },NEWLINE },NEWLINE },NEWLINE]NEWLINE
"""NEWLINEUnit and regression test for the analyze_foldamers package.NEWLINE"""NEWLINENEWLINE# Import package, test suite, and other packages as neededNEWLINEimport analyze_foldamersNEWLINEimport pytestNEWLINEimport sysNEWLINEimport osNEWLINEimport pickleNEWLINEfrom cg_openmm.cg_model.cgmodel import CGModelNEWLINEfrom analyze_foldamers.ensembles.cluster import *NEWLINENEWLINEcurrent_path = os.path.dirname(os.path.abspath(__file__))NEWLINEdata_path = os.path.join(current_path, 'test_data')NEWLINENEWLINEdef test_clustering_kmedoids_pdb(tmpdir):NEWLINE """Test Kmeans clustering"""NEWLINE NEWLINE output_directory = tmpdir.mkdir("output")NEWLINE NEWLINE # Load in cgmodelNEWLINE cgmodel_path = os.path.join(data_path, "stored_cgmodel.pkl")NEWLINE cgmodel = pickle.load(open(cgmodel_path, "rb"))NEWLINE NEWLINE # Create list of trajectory files for clustering analysisNEWLINE number_replicas = 12NEWLINE pdb_file_list = []NEWLINE for i in range(number_replicas):NEWLINE pdb_file_list.append(f"{data_path}/replica_%s.pdb" %(i+1))NEWLINENEWLINE # Set clustering parametersNEWLINE n_clusters=2NEWLINE frame_start=10NEWLINE frame_stride=1NEWLINE frame_end=-1NEWLINENEWLINE # Run KMeans clusteringNEWLINE medoid_positions, cluster_size, cluster_rmsd, silhouette_avg, labels, original_indices = \NEWLINE get_cluster_medoid_positions_KMedoids(NEWLINE pdb_file_list,NEWLINE cgmodel,NEWLINE n_clusters=n_clusters,NEWLINE frame_start=frame_start,NEWLINE frame_stride=frame_stride,NEWLINE frame_end=-1,NEWLINE output_dir=output_directory,NEWLINE plot_silhouette=True,NEWLINE plot_rmsd_hist=True,NEWLINE filter=True,NEWLINE filter_ratio=0.20,NEWLINE )NEWLINE NEWLINE assert len(cluster_rmsd) == n_clustersNEWLINE assert len(labels) == len(original_indices)NEWLINE assert os.path.isfile(f"{output_directory}/medoid_1.pdb")NEWLINE assert os.path.isfile(f"{output_directory}/silhouette_kmedoids_ncluster_{n_clusters}.pdf") NEWLINE assert os.path.isfile(f"{output_directory}/distances_rmsd_hist.pdf")NEWLINE NEWLINENEWLINEdef test_clustering_kmedoids_pdb_no_cgmodel(tmpdir):NEWLINE """Test Kmeans clustering without a cgmodel"""NEWLINE NEWLINE output_directory = tmpdir.mkdir("output")NEWLINE NEWLINE # Create list of trajectory files for clustering analysisNEWLINE number_replicas = 12NEWLINE pdb_file_list = []NEWLINE for i in range(number_replicas):NEWLINE pdb_file_list.append(f"{data_path}/replica_%s.pdb" %(i+1))NEWLINENEWLINE # Set clustering parametersNEWLINE n_clusters=2NEWLINE frame_start=10NEWLINE frame_stride=1NEWLINE frame_end=-1NEWLINENEWLINE # Run KMeans clusteringNEWLINE medoid_positions, cluster_size, cluster_rmsd, silhouette_avg, labels, original_indices = \NEWLINE get_cluster_medoid_positions_KMedoids(NEWLINE pdb_file_list,NEWLINE cgmodel=None,NEWLINE n_clusters=n_clusters,NEWLINE frame_start=frame_start,NEWLINE frame_stride=frame_stride,NEWLINE frame_end=-1,NEWLINE output_dir=output_directory,NEWLINE plot_silhouette=True,NEWLINE plot_rmsd_hist=True,NEWLINE filter=True,NEWLINE filter_ratio=0.20,NEWLINE )NEWLINE NEWLINE assert len(cluster_rmsd) == n_clustersNEWLINE assert len(labels) == len(original_indices)NEWLINE assert os.path.isfile(f"{output_directory}/medoid_1.pdb")NEWLINE assert os.path.isfile(f"{output_directory}/silhouette_kmedoids_ncluster_{n_clusters}.pdf") NEWLINE assert os.path.isfile(f"{output_directory}/distances_rmsd_hist.pdf")NEWLINE NEWLINE NEWLINEdef test_clustering_kmedoids_dcd(tmpdir):NEWLINE """Test KMedoids clustering"""NEWLINE NEWLINE output_directory = tmpdir.mkdir("output")NEWLINE NEWLINE # Load in cgmodelNEWLINE cgmodel_path = os.path.join(data_path, "stored_cgmodel.pkl")NEWLINE cgmodel = pickle.load(open(cgmodel_path, "rb"))NEWLINE NEWLINE # Create list of trajectory files for clustering analysisNEWLINE number_replicas = 12NEWLINE dcd_file_list = []NEWLINE for i in range(number_replicas):NEWLINE dcd_file_list.append(f"{data_path}/replica_%s.dcd" %(i+1))NEWLINENEWLINE # Set clustering parametersNEWLINE n_clusters=2NEWLINE frame_start=10NEWLINE frame_stride=1NEWLINE frame_end=-1NEWLINENEWLINE # Run KMeans clusteringNEWLINE medoid_positions, cluster_size, cluster_rmsd, silhouette_avg, labels, original_indices = \NEWLINE get_cluster_medoid_positions_KMedoids(NEWLINE dcd_file_list,NEWLINE cgmodel,NEWLINE n_clusters=n_clusters,NEWLINE frame_start=frame_start,NEWLINE frame_stride=frame_stride,NEWLINE frame_end=-1,NEWLINE output_format="dcd",NEWLINE output_dir=output_directory,NEWLINE plot_silhouette=True,NEWLINE plot_rmsd_hist=True,NEWLINE filter=True,NEWLINE filter_ratio=0.20,NEWLINE )NEWLINE NEWLINE assert len(cluster_rmsd) == n_clustersNEWLINE assert len(labels) == len(original_indices)NEWLINE assert os.path.isfile(f"{output_directory}/medoid_1.dcd")NEWLINE assert os.path.isfile(f"{output_directory}/silhouette_kmedoids_ncluster_{n_clusters}.pdf")NEWLINE assert os.path.isfile(f"{output_directory}/distances_rmsd_hist.pdf") NEWLINE NEWLINE NEWLINEdef test_clustering_dbscan_pdb(tmpdir):NEWLINE """Test DBSCAN clustering"""NEWLINE NEWLINE output_directory = tmpdir.mkdir("output")NEWLINE NEWLINE # Load in cgmodelNEWLINE cgmodel_path = os.path.join(data_path, "stored_cgmodel.pkl")NEWLINE cgmodel = pickle.load(open(cgmodel_path, "rb"))NEWLINE NEWLINE # Create list of trajectory files for clustering analysisNEWLINE number_replicas = 12NEWLINE pdb_file_list = []NEWLINE for i in range(number_replicas):NEWLINE pdb_file_list.append(f"{data_path}/replica_%s.pdb" %(i+1))NEWLINENEWLINE # Set clustering parametersNEWLINE min_samples=3NEWLINE eps=0.5NEWLINE frame_start=10NEWLINE frame_stride=1NEWLINE frame_end=-1NEWLINENEWLINE # Run DBSCAN density-based clusteringNEWLINE medoid_positions, cluster_sizes, cluster_rmsd, n_noise, silhouette_avg, labels, original_indices = \NEWLINE get_cluster_medoid_positions_DBSCAN(NEWLINE pdb_file_list,NEWLINE cgmodel,NEWLINE min_samples=min_samples,NEWLINE eps=eps,NEWLINE frame_start=frame_start,NEWLINE frame_stride=frame_stride,NEWLINE frame_end=-1,NEWLINE output_dir=output_directory,NEWLINE plot_silhouette=True,NEWLINE plot_rmsd_hist=True,NEWLINE filter=True,NEWLINE filter_ratio=0.20,NEWLINE core_points_only=False,NEWLINE )NEWLINE NEWLINE assert len(labels) == len(original_indices)NEWLINE assert os.path.isfile(f"{output_directory}/medoid_0.pdb")NEWLINE assert os.path.isfile(f"{output_directory}/distances_rmsd_hist.pdf")NEWLINE NEWLINEdef test_clustering_dbscan_pdb_core_medoids(tmpdir):NEWLINE """Test DBSCAN clustering"""NEWLINE NEWLINE output_directory = tmpdir.mkdir("output")NEWLINE NEWLINE # Load in cgmodelNEWLINE cgmodel_path = os.path.join(data_path, "stored_cgmodel.pkl")NEWLINE cgmodel = pickle.load(open(cgmodel_path, "rb"))NEWLINE NEWLINE # Create list of trajectory files for clustering analysisNEWLINE number_replicas = 12NEWLINE pdb_file_list = []NEWLINE for i in range(number_replicas):NEWLINE pdb_file_list.append(f"{data_path}/replica_%s.pdb" %(i+1))NEWLINENEWLINE # Set clustering parametersNEWLINE min_samples=3NEWLINE eps=0.5NEWLINE frame_start=10NEWLINE frame_stride=1NEWLINE frame_end=-1NEWLINENEWLINE # Run DBSCAN density-based clusteringNEWLINE medoid_positions, cluster_sizes, cluster_rmsd, n_noise, silhouette_avg, labels, original_indices = \NEWLINE get_cluster_medoid_positions_DBSCAN(NEWLINE pdb_file_list,NEWLINE cgmodel,NEWLINE min_samples=min_samples,NEWLINE eps=eps,NEWLINE frame_start=frame_start,NEWLINE frame_stride=frame_stride,NEWLINE frame_end=-1,NEWLINE output_dir=output_directory,NEWLINE plot_silhouette=True,NEWLINE plot_rmsd_hist=True,NEWLINE filter=True,NEWLINE filter_ratio=0.20,NEWLINE core_points_only=True,NEWLINE )NEWLINE NEWLINE assert len(labels) == len(original_indices)NEWLINE assert os.path.isfile(f"{output_directory}/medoid_0.pdb")NEWLINE assert os.path.isfile(f"{output_directory}/distances_rmsd_hist.pdf")NEWLINE NEWLINENEWLINEdef test_clustering_dbscan_pdb_no_cgmodel(tmpdir):NEWLINE """Test DBSCAN clustering without cgmodel object"""NEWLINE NEWLINE output_directory = tmpdir.mkdir("output")NEWLINE NEWLINE # Create list of trajectory files for clustering analysisNEWLINE number_replicas = 12NEWLINE pdb_file_list = []NEWLINE for i in range(number_replicas):NEWLINE pdb_file_list.append(f"{data_path}/replica_%s.pdb" %(i+1))NEWLINENEWLINE # Set clustering parametersNEWLINE min_samples=3NEWLINE eps=0.5NEWLINE frame_start=10NEWLINE frame_stride=1NEWLINE frame_end=-1NEWLINENEWLINE # Run DBSCAN density-based clusteringNEWLINE medoid_positions, cluster_sizes, cluster_rmsd, n_noise, silhouette_avg, labels, original_indices = \NEWLINE get_cluster_medoid_positions_DBSCAN(NEWLINE pdb_file_list,NEWLINE cgmodel = None,NEWLINE min_samples=min_samples,NEWLINE eps=eps,NEWLINE frame_start=frame_start,NEWLINE frame_stride=frame_stride,NEWLINE frame_end=-1,NEWLINE output_dir=output_directory,NEWLINE plot_silhouette=True,NEWLINE plot_rmsd_hist=True,NEWLINE filter=True,NEWLINE filter_ratio=0.20,NEWLINE core_points_only=False,NEWLINE )NEWLINE assert len(labels) == len(original_indices)NEWLINE assert os.path.isfile(f"{output_directory}/medoid_0.pdb")NEWLINE assert os.path.isfile(f"{output_directory}/distances_rmsd_hist.pdf")NEWLINENEWLINE NEWLINEdef test_clustering_dbscan_dcd(tmpdir):NEWLINE """Test DBSCAN clustering"""NEWLINE NEWLINE output_directory = tmpdir.mkdir("output")NEWLINE NEWLINE # Load in cgmodelNEWLINE cgmodel_path = os.path.join(data_path, "stored_cgmodel.pkl")NEWLINE cgmodel = pickle.load(open(cgmodel_path, "rb"))NEWLINE NEWLINE # Create list of trajectory files for clustering analysisNEWLINE number_replicas = 12NEWLINE dcd_file_list = []NEWLINE for i in range(number_replicas):NEWLINE dcd_file_list.append(f"{data_path}/replica_%s.dcd" %(i+1))NEWLINENEWLINE # Set clustering parametersNEWLINE min_samples=3NEWLINE eps=0.5NEWLINE frame_start=10NEWLINE frame_stride=1NEWLINE frame_end=-1NEWLINENEWLINE # Run OPTICS density-based clusteringNEWLINE medoid_positions, cluster_sizes, cluster_rmsd, n_noise, silhouette_avg, labels, original_indices = \NEWLINE get_cluster_medoid_positions_DBSCAN(NEWLINE dcd_file_list,NEWLINE cgmodel,NEWLINE min_samples=min_samples,NEWLINE eps=eps,NEWLINE frame_start=frame_start,NEWLINE frame_stride=frame_stride,NEWLINE frame_end=-1,NEWLINE output_format="dcd",NEWLINE output_dir=output_directory,NEWLINE plot_silhouette=True,NEWLINE plot_rmsd_hist=True,NEWLINE filter=True,NEWLINE filter_ratio=0.20,NEWLINE core_points_only=False,NEWLINE )NEWLINE assert len(labels) == len(original_indices)NEWLINE assert os.path.isfile(f"{output_directory}/medoid_0.dcd") NEWLINE assert os.path.isfile(f"{output_directory}/distances_rmsd_hist.pdf") NEWLINE NEWLINE NEWLINEdef test_clustering_optics_pdb(tmpdir):NEWLINE """Test OPTICS clustering"""NEWLINE NEWLINE output_directory = tmpdir.mkdir("output")NEWLINE NEWLINE # Load in cgmodelNEWLINE cgmodel_path = os.path.join(data_path, "stored_cgmodel.pkl")NEWLINE cgmodel = pickle.load(open(cgmodel_path, "rb"))NEWLINE NEWLINE # Create list of trajectory files for clustering analysisNEWLINE number_replicas = 12NEWLINE pdb_file_list = []NEWLINE for i in range(number_replicas):NEWLINE pdb_file_list.append(f"{data_path}/replica_%s.pdb" %(i+1))NEWLINENEWLINE # Set clustering parametersNEWLINE min_samples=5NEWLINE frame_start=10NEWLINE frame_stride=1NEWLINE frame_end=-1NEWLINENEWLINE # Run OPTICS density-based clusteringNEWLINE medoid_positions, cluster_sizes, cluster_rmsd, n_noise, silhouette_avg, labels, original_indices = \NEWLINE get_cluster_medoid_positions_OPTICS(NEWLINE pdb_file_list,NEWLINE cgmodel,NEWLINE min_samples=min_samples,NEWLINE frame_start=frame_start,NEWLINE frame_stride=frame_stride,NEWLINE frame_end=-1,NEWLINE output_dir=output_directory,NEWLINE plot_silhouette=True,NEWLINE plot_rmsd_hist=True,NEWLINE filter=True,NEWLINE filter_ratio=0.20,NEWLINE )NEWLINE assert len(labels) == len(original_indices)NEWLINE assert os.path.isfile(f"{output_directory}/medoid_0.pdb")NEWLINE assert os.path.isfile(f"{output_directory}/distances_rmsd_hist.pdf") NEWLINENEWLINEdef test_clustering_optics_pdb_no_cgmodel(tmpdir):NEWLINE """Test OPTICS clustering without a cgmodel object"""NEWLINE NEWLINE output_directory = tmpdir.mkdir("output")NEWLINE NEWLINE # Create list of trajectory files for clustering analysisNEWLINE number_replicas = 12NEWLINE pdb_file_list = []NEWLINE for i in range(number_replicas):NEWLINE pdb_file_list.append(f"{data_path}/replica_%s.pdb" %(i+1))NEWLINENEWLINE # Set clustering parametersNEWLINE min_samples=5NEWLINE frame_start=10NEWLINE frame_stride=1NEWLINE frame_end=-1NEWLINENEWLINE # Run OPTICS density-based clusteringNEWLINE medoid_positions, cluster_sizes, cluster_rmsd, n_noise, silhouette_avg, labels, original_indices = \NEWLINE get_cluster_medoid_positions_OPTICS(NEWLINE pdb_file_list,NEWLINE cgmodel = None,NEWLINE min_samples=min_samples,NEWLINE frame_start=frame_start,NEWLINE frame_stride=frame_stride,NEWLINE frame_end=-1,NEWLINE output_dir=output_directory,NEWLINE plot_silhouette=True,NEWLINE plot_rmsd_hist=True,NEWLINE filter=True,NEWLINE filter_ratio=0.20,NEWLINE )NEWLINE assert len(labels) == len(original_indices)NEWLINE assert os.path.isfile(f"{output_directory}/medoid_0.pdb")NEWLINE assert os.path.isfile(f"{output_directory}/distances_rmsd_hist.pdf") NEWLINENEWLINENEWLINE NEWLINEdef test_clustering_optics_dcd(tmpdir):NEWLINE """Test OPTICS clustering"""NEWLINE NEWLINE output_directory = tmpdir.mkdir("output")NEWLINE NEWLINE # Load in cgmodelNEWLINE cgmodel_path = os.path.join(data_path, "stored_cgmodel.pkl")NEWLINE cgmodel = pickle.load(open(cgmodel_path, "rb"))NEWLINE NEWLINE # Create list of trajectory files for clustering analysisNEWLINE number_replicas = 12NEWLINE dcd_file_list = []NEWLINE for i in range(number_replicas):NEWLINE dcd_file_list.append(f"{data_path}/replica_%s.dcd" %(i+1))NEWLINENEWLINE # Set clustering parametersNEWLINE min_samples=5NEWLINE frame_start=10NEWLINE frame_stride=1NEWLINE frame_end=-1NEWLINENEWLINE # Run OPTICS density-based clusteringNEWLINE medoid_positions, cluster_sizes, cluster_rmsd, n_noise, silhouette_avg, labels, original_indices = \NEWLINE get_cluster_medoid_positions_OPTICS(NEWLINE dcd_file_list,NEWLINE cgmodel,NEWLINE min_samples=min_samples,NEWLINE frame_start=frame_start,NEWLINE frame_stride=frame_stride,NEWLINE frame_end=-1,NEWLINE output_format="dcd",NEWLINE output_dir=output_directory,NEWLINE plot_silhouette=True,NEWLINE plot_rmsd_hist=True,NEWLINE filter=True,NEWLINE filter_ratio=0.20,NEWLINE )NEWLINE assert len(labels) == len(original_indices)NEWLINE assert os.path.isfile(f"{output_directory}/medoid_0.dcd") NEWLINE assert os.path.isfile(f"{output_directory}/distances_rmsd_hist.pdf")NEWLINENEWLINEdef test_clustering_dbscan_pdb_output_clusters(tmpdir):NEWLINE """Test DBSCAN clustering"""NEWLINE NEWLINE output_directory = tmpdir.mkdir("output")NEWLINE NEWLINE # Load in cgmodelNEWLINE cgmodel_path = os.path.join(data_path, "stored_cgmodel.pkl")NEWLINE cgmodel = pickle.load(open(cgmodel_path, "rb"))NEWLINE NEWLINE # Create list of trajectory files for clustering analysisNEWLINE number_replicas = 12NEWLINE pdb_file_list = []NEWLINE for i in range(number_replicas):NEWLINE pdb_file_list.append(f"{data_path}/replica_%s.pdb" %(i+1))NEWLINENEWLINE # Set clustering parametersNEWLINE min_samples=3NEWLINE eps=0.5NEWLINE frame_start=10NEWLINE frame_stride=1NEWLINE frame_end=-1NEWLINENEWLINE # Run DBSCAN density-based clusteringNEWLINE medoid_positions, cluster_sizes, cluster_rmsd, n_noise, silhouette_avg, labels, original_indices = \NEWLINE get_cluster_medoid_positions_DBSCAN(NEWLINE pdb_file_list,NEWLINE cgmodel,NEWLINE min_samples=min_samples,NEWLINE eps=eps,NEWLINE frame_start=frame_start,NEWLINE frame_stride=frame_stride,NEWLINE frame_end=-1,NEWLINE output_dir=output_directory,NEWLINE output_cluster_traj=True,NEWLINE plot_silhouette=True,NEWLINE plot_rmsd_hist=True,NEWLINE filter=True,NEWLINE filter_ratio=0.20,NEWLINE )NEWLINE assert len(labels) == len(original_indices)NEWLINE assert os.path.isfile(f"{output_directory}/medoid_0.pdb")NEWLINE assert os.path.isfile(f"{output_directory}/cluster_0.pdb")NEWLINE
from typing import Any, Dict, Type, TypeVar, UnionNEWLINENEWLINEimport attrNEWLINENEWLINEfrom ..types import UNSET, UnsetNEWLINENEWLINET = TypeVar("T", bound="Definition")NEWLINENEWLINENEWLINE@attr.s(auto_attribs=True)NEWLINEclass Definition:NEWLINE """ """NEWLINENEWLINE definition: strNEWLINE source: Union[Unset, str] = UNSETNEWLINE lang: Union[Unset, str] = UNSETNEWLINENEWLINE def to_dict(self) -> Dict[str, Any]:NEWLINE definition = self.definitionNEWLINE source = self.sourceNEWLINE lang = self.langNEWLINENEWLINE field_dict: Dict[str, Any] = {}NEWLINE field_dict.update(NEWLINE {NEWLINE "definition": definition,NEWLINE }NEWLINE )NEWLINE if source is not UNSET:NEWLINE field_dict["source"] = sourceNEWLINE if lang is not UNSET:NEWLINE field_dict["lang"] = langNEWLINENEWLINE return field_dictNEWLINENEWLINE @classmethodNEWLINE def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:NEWLINE d = src_dict.copy()NEWLINE definition = d.pop("definition")NEWLINENEWLINE source = d.pop("source", UNSET)NEWLINENEWLINE lang = d.pop("lang", UNSET)NEWLINENEWLINE definition = cls(NEWLINE definition=definition,NEWLINE source=source,NEWLINE lang=lang,NEWLINE )NEWLINENEWLINE return definitionNEWLINE
from securitycenter import SecurityCenter5NEWLINEfrom datetime import dateNEWLINEfrom time import mktimeNEWLINEfrom pygal.style import BlueStyleNEWLINEfrom pygal import DateLineNEWLINEfrom sys import stdoutNEWLINENEWLINEusername = 'USER'NEWLINEpassword = 'PASS'NEWLINEaddress = 'HOST'NEWLINEresults = [True,True]NEWLINEstart_boundry = date(2015,1,1)NEWLINEend_boundry = date(2016,12,31)NEWLINEdata = {}NEWLINENEWLINEsc = SecurityCenter5(address)NEWLINEsc.login(username, password)NEWLINENEWLINEoffset = 0NEWLINEdone = FalseNEWLINEwhile len(results) > 0 or done:NEWLINE print '\nPulling plugins from %s to %s' % (offset, offset + 10000)NEWLINE results = sc.get('plugin', params={NEWLINE 'fields': 'pluginPubDate,modifiedTime',NEWLINE 'size': 1000,NEWLINE 'startOffset': offset,NEWLINE 'endOffset': offset + 10000,NEWLINE }).json()['response']NEWLINENEWLINE for item in results:NEWLINE stdout.write('\rProcessing Plugin %s of %s' % (results.index(item) + 1, len(results)))NEWLINE stdout.flush()NEWLINE try:NEWLINE d = date.fromtimestamp(int(item['pluginPubDate']))NEWLINE m = date.fromtimestamp(int(item['modifiedTime']))NEWLINE except:NEWLINE passNEWLINE else:NEWLINE if d > start_boundry and d < end_boundry:NEWLINE if d not in data:NEWLINE data[d] = 0NEWLINE data[d] += 1NEWLINE offset += 10000NEWLINENEWLINEchart = DateLine(NEWLINE style=BlueStyle,NEWLINE show_dots=False,NEWLINE fill=True,NEWLINE)NEWLINEchart.add('Plugins', sorted([(x, data[x]) for x in data], key=lambda tup: tup[0]))NEWLINEchart.render_in_browser()NEWLINE
# 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# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#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 __future__ import unicode_literalsNEWLINEfrom __future__ import absolute_importNEWLINEfrom setuptools import setup, find_packagesNEWLINENEWLINEfrom forgediscussion.version import __version__NEWLINENEWLINEsetup(name='ForgeDiscussion',NEWLINE version=__version__,NEWLINE description="",NEWLINE long_description="""\NEWLINE""",NEWLINE # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiersNEWLINE classifiers=[],NEWLINE keywords='',NEWLINE author='',NEWLINE author_email='',NEWLINE url='',NEWLINE license='',NEWLINE packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),NEWLINE include_package_data=True,NEWLINE zip_safe=False,NEWLINE install_requires=[NEWLINE # -*- Extra requirements: -*-NEWLINE 'Allura',NEWLINE ],NEWLINE test_suite='nose.collector',NEWLINE tests_require=['WebTest', 'BeautifulSoup'],NEWLINE entry_points="""NEWLINE # -*- Entry points: -*-NEWLINE [allura]NEWLINE Discussion=forgediscussion.forum_main:ForgeDiscussionAppNEWLINENEWLINE [allura.site_stats]NEWLINE posts_24hr=forgediscussion.site_stats:posts_24hrNEWLINE """,NEWLINE )NEWLINE
from __future__ import absolute_importNEWLINENEWLINEimport osNEWLINEimport reNEWLINENEWLINEfrom django.conf import settingsNEWLINEfrom django.template import TemplateDoesNotExistNEWLINEfrom django.template.loaders import cachedNEWLINENEWLINEfrom pypugjs.utils import processNEWLINEfrom .compiler import CompilerNEWLINENEWLINENEWLINEclass Loader(cached.Loader):NEWLINE is_usable = TrueNEWLINENEWLINE def include_pug_sources(self, contents):NEWLINE """Lets fetch top level pug includes to enable mixins"""NEWLINE match = re.search(r'^include (.*)$', contents, re.MULTILINE)NEWLINE while match:NEWLINE mixin_name = match.groups()[0]NEWLINE origin = [o for o in self.get_template_sources(mixin_name)][0]NEWLINE template = origin.loader.get_contents(origin)NEWLINE template = self.include_pug_sources(template)NEWLINE contents = re.sub(r'^include (.*)$', template, contents, flags=re.MULTILINE)NEWLINE match = re.search(r'^include (.*)$', contents, re.MULTILINE)NEWLINE return contentsNEWLINENEWLINE def get_contents(self, origin):NEWLINE contents = origin.loader.get_contents(origin)NEWLINE if os.path.splitext(origin.template_name)[1] in ('.pug', '.jade'):NEWLINE contents = self.include_pug_sources(contents)NEWLINE contents = process(NEWLINE contents, filename=origin.template_name, compiler=CompilerNEWLINE )NEWLINE return contentsNEWLINENEWLINE def get_template(self, template_name, **kwargs):NEWLINE """NEWLINE Uses cache if debug is False, otherwise re-reads from file system.NEWLINE """NEWLINE if getattr(settings, 'TEMPLATE_DEBUG', settings.DEBUG):NEWLINE try:NEWLINE return super(cached.Loader, self).get_template(template_name, **kwargs)NEWLINE # TODO: Change IOError to FileNotFoundError after future==0.17.0NEWLINE except IOError:NEWLINE raise TemplateDoesNotExist(template_name)NEWLINENEWLINE return super(Loader, self).get_template(template_name, **kwargs)NEWLINE
#!/usr/bin/python3NEWLINENEWLINE'''NEWLINEConvert Japanese datasets to Hepburn RomanizationNEWLINECopyright 2016 Xiang ZhangNEWLINENEWLINEUsage: python3 construct_hepburn.py -i [input] -o [output]NEWLINE'''NEWLINENEWLINE# Input fileNEWLINEINPUT = '../data/rakuten/sentiment/full_train.csv'NEWLINE# Output fileNEWLINEOUTPUT = '../data/rakuten/sentiment/full_train_hepburn.csv'NEWLINENEWLINEimport argparseNEWLINEimport csvNEWLINEimport MeCabNEWLINEimport romkanNEWLINEimport unidecodeNEWLINENEWLINE# Main programNEWLINEdef main():NEWLINE global INPUTNEWLINE global OUTPUTNEWLINENEWLINE parser = argparse.ArgumentParser()NEWLINE parser.add_argument('-i', '--input', help = 'Input file', default = INPUT)NEWLINE parser.add_argument(NEWLINE '-o', '--output', help = 'Output file', default = OUTPUT)NEWLINENEWLINE args = parser.parse_args()NEWLINENEWLINE INPUT = args.inputNEWLINE OUTPUT = args.outputNEWLINENEWLINE mecab = MeCab.Tagger()NEWLINENEWLINE convertRoman(mecab)NEWLINENEWLINEdef romanizeText(mecab, text):NEWLINE parsed = mecab.parse(text)NEWLINE result = list()NEWLINE for token in parsed.split('\n'):NEWLINE splitted = token.split('\t')NEWLINE if len(splitted) == 2:NEWLINE word = splitted[0]NEWLINE features = splitted[1].split(',')NEWLINE if len(features) > 7 and features[7] != '*':NEWLINE result.append(romkan.to_hepburn(features[7]))NEWLINE else:NEWLINE result.append(word)NEWLINE return resultNEWLINENEWLINE# Convert the text in Chinese to pintinNEWLINEdef convertRoman(mecab):NEWLINE # Open the filesNEWLINE ifd = open(INPUT, encoding = 'utf-8', newline = '')NEWLINE ofd = open(OUTPUT, 'w', encoding = 'utf-8', newline = '')NEWLINE reader = csv.reader(ifd, quoting = csv.QUOTE_ALL)NEWLINE writer = csv.writer(ofd, quoting = csv.QUOTE_ALL, lineterminator = '\n')NEWLINE # Loop over the csv rowsNEWLINE n = 0NEWLINE for row in reader:NEWLINE new_row = list()NEWLINE new_row.append(row[0])NEWLINE for i in range(1, len(row)):NEWLINE new_row.append(' '.join(map(NEWLINE str.strip,NEWLINE map(lambda s: s.replace('\n', '\\n'),NEWLINE map(unidecode.unidecode,NEWLINE romanizeText(mecab, row[i]))))))NEWLINE writer.writerow(new_row)NEWLINE n = n + 1NEWLINE if n % 1000 == 0:NEWLINE print('\rProcessing line: {}'.format(n), end = '')NEWLINE print('\rProcessed lines: {}'.format(n))NEWLINENEWLINEif __name__ == '__main__':NEWLINE main()NEWLINE
# exercise 1NEWLINEdef max_array(array):NEWLINE return max(array)NEWLINENEWLINE# exercise 2NEWLINEdef reverse_array(array):NEWLINE result=[]NEWLINE for i in range(len(array)-1,-1,-1):NEWLINE result.append(array[i])NEWLINE return resultNEWLINENEWLINE# exercise 3NEWLINEdef check(array,char):NEWLINE if char in array:NEWLINE return 'yes'NEWLINE else:NEWLINE return 'dont find'NEWLINENEWLINE# exercise 4NEWLINEdef phan_tu_le(array):NEWLINE result=[]NEWLINE for i in range(1,len(array),2):NEWLINE result.append(array[i])NEWLINE return resultNEWLINE# exercise 5:NEWLINEdef sum(array):NEWLINE tong=0NEWLINE for i in range(len(array)):NEWLINE tong+=array[i]NEWLINE return tongNEWLINENEWLINE#excercise 6NEWLINEdef check_symmetry(str):NEWLINE for i in range(int(len(str)/2)+1):NEWLINE if str[i]!=str[len(str)-i-1]:NEWLINE return FalseNEWLINE return TrueNEWLINENEWLINE# exercise 7NEWLINE# use for loopNEWLINEdef sum1(array):NEWLINE tong=0NEWLINE for i in range(len(array)):NEWLINE tong+=array[i]NEWLINE return tongNEWLINENEWLINE# use while loopNEWLINEdef sum2(array):NEWLINE tong=0NEWLINE i=0NEWLINE while i<len(array):NEWLINE tong+=array[i]NEWLINE i+=1NEWLINE return tongNEWLINENEWLINE# use recursionNEWLINEdef cal_sum(array):NEWLINE if len(array)==1:NEWLINE return array[0]NEWLINE else:NEWLINE return array[0]+cal_sum(array[1:])NEWLINENEWLINE# exercise 8NEWLINEimport mathNEWLINEdef square(array):NEWLINE result=[]NEWLINE for i in array:NEWLINE if pow(int(math.sqrt(i)),2)==i:NEWLINE result.append(i)NEWLINE return resultNEWLINENEWLINENEWLINE# excercise 9NEWLINEdef conCat(array1,array2):NEWLINE return array1+array2NEWLINENEWLINENEWLINENEWLINENEWLINE
S = input()NEWLINENEWLINEwhile S != "0+0=0":NEWLINE S = S[::-1]NEWLINE a, b = S.split('=')NEWLINE b, c = b.split('+')NEWLINENEWLINE if int(a) == int(b) + int(c):NEWLINE print('True')NEWLINE else:NEWLINE print('False')NEWLINENEWLINE S = input()NEWLINENEWLINEprint('True')NEWLINE
from django import formsNEWLINEfrom app.models import BrewPiDevice, OldControlConstants, NewControlConstants, SensorDevice, FermentationProfile, FermentationProfilePointNEWLINEfrom django.core import validatorsNEWLINEimport fermentrack_django.settings as settingsNEWLINEfrom django.core.exceptions import ObjectDoesNotExistNEWLINENEWLINEfrom django.forms import ModelFormNEWLINEfrom . import udev_integrationNEWLINENEWLINEimport reNEWLINEimport datetimeNEWLINEimport pytzNEWLINEimport randomNEWLINENEWLINENEWLINEclass DeviceForm(forms.Form):NEWLINE device_name = forms.CharField(max_length=48, help_text="Unique name for this device",NEWLINE widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Device Name'}))NEWLINENEWLINE temp_format = forms.ChoiceField(choices=BrewPiDevice.TEMP_FORMAT_CHOICES, initial='C', help_text="Temperature units",NEWLINE widget=forms.Select(attrs={'class': 'form-control'}))NEWLINENEWLINE data_point_log_interval = forms.ChoiceField(initial=30, choices=BrewPiDevice.DATA_POINT_TIME_CHOICES,NEWLINE help_text="Time between logged data points",NEWLINE widget=forms.Select(attrs={'class': 'form-control'}))NEWLINENEWLINE connection_type = forms.ChoiceField(initial='serial', choices=BrewPiDevice.CONNECTION_TYPE_CHOICES,NEWLINE help_text="Type of connection between the Raspberry Pi and the hardware",NEWLINE widget=forms.Select(attrs={'class': 'form-control'}))NEWLINENEWLINE useInetSocket = forms.BooleanField(required=False, initial=True,NEWLINE help_text="Whether or not to use an internet socket (rather than local)")NEWLINENEWLINE # Note - initial=random.randint(2000,3000) only assigns at Fermentrack load-time, not when the form is instantiatedNEWLINE # There is code on the forms which will effectively accomplish the same thing every time the user accesses the formNEWLINE socketPort = forms.IntegerField(initial=random.randint(2000,3000), min_value=1024, max_value=65536, required=False,NEWLINE help_text="The socket port to use, this needs to be unique per fermentrack device",NEWLINE widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Ex: 1234'}))NEWLINENEWLINE socketHost = forms.CharField(max_length=128, initial="localhost", required=False,NEWLINE help_text="The ip or a hostname on the local machine for the fermentrack controller script will bind to",NEWLINE widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Ex: localhost'}))NEWLINENEWLINE serial_port = forms.CharField(max_length=255, initial="auto", required=False,NEWLINE help_text="Serial port to which the BrewPi device is connected (Only used if " +NEWLINE "connection_type is serial)",NEWLINE widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'auto'}))NEWLINENEWLINE serial_alt_port = forms.CharField(max_length=255, initial="None", required=False,NEWLINE help_text="Alternate serial port path (Only used if connection_type is serial)",NEWLINE widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'None'}))NEWLINENEWLINE board_type = forms.ChoiceField(initial="uno", choices=BrewPiDevice.BOARD_TYPE_CHOICES,NEWLINE help_text="Board type to which BrewPi is connected",NEWLINE widget=forms.Select(attrs={'class': 'form-control'}))NEWLINENEWLINE socket_name = forms.CharField(max_length=25, initial="BEERSOCKET", required=False,NEWLINE help_text="Name of the file-based socket (Only used if useInetSocket is False)",NEWLINE widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'BEERSOCKET'}))NEWLINENEWLINE wifi_host = forms.CharField(max_length=40, initial='', required=False,NEWLINE help_text="mDNS host name or IP address for WiFi connected hardware (only used if " +NEWLINE "connection_type is wifi)",NEWLINE widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Ex: brewpi.local'}))NEWLINENEWLINE wifi_port = forms.IntegerField(initial=23, min_value=10, max_value=65536, required=False,NEWLINE help_text="The internet port to use (almost always 23)",NEWLINE widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Ex: 1222'}))NEWLINENEWLINE prefer_connecting_via_udev = forms.BooleanField(initial=True, required=False,NEWLINE help_text="Whether to autodetect the appropriate serial port " +NEWLINE "using the device's USB serial number")NEWLINENEWLINE # Check that the Start At format is valid, and if it is, replace it with a datetime delta objectNEWLINE def clean_device_name(self):NEWLINE if 'device_name' not in self.cleaned_data:NEWLINE raise forms.ValidationError("A device name must be specified")NEWLINE else:NEWLINE device_name = self.cleaned_data['device_name']NEWLINENEWLINE try:NEWLINE existing_device = BrewPiDevice.objects.get(device_name=device_name)NEWLINE raise forms.ValidationError("A device already exists with the name {}".format(device_name))NEWLINENEWLINE except ObjectDoesNotExist:NEWLINE # There was no existing device - we're good.NEWLINE return device_nameNEWLINENEWLINE def clean(self):NEWLINE cleaned_data = self.cleaned_dataNEWLINENEWLINE # Check the connection type and default parameters that don't applyNEWLINE if cleaned_data['connection_type'] == 'serial':NEWLINE cleaned_data['wifi_host'] = "NA"NEWLINE cleaned_data['wifi_port'] = 23NEWLINENEWLINE # Since we've skipped automated validation above, validate here.NEWLINE if cleaned_data['serial_port'] is None or cleaned_data['serial_alt_port'] is None:NEWLINE raise forms.ValidationError("Serial Port & Serial Alt Port are required for connection type 'serial'")NEWLINE elif len(cleaned_data['serial_port']) < 2:NEWLINE raise forms.ValidationError("Must specify a valid serial port when using connection type 'serial'")NEWLINE elif len(cleaned_data['serial_alt_port']) < 2:NEWLINE raise forms.ValidationError("Must specify a valid alt serial port (or None) when using connection " +NEWLINE "type 'serial'")NEWLINENEWLINE if 'prefer_connecting_via_udev' in cleaned_data and cleaned_data['prefer_connecting_via_udev']:NEWLINE # The user clicked "prefer_connecting_via_udev". Check if there is another device that already existsNEWLINE # with the same udev serial number, and if there is, raise an error.NEWLINE udev = udev_integration.get_serial_from_node(cleaned_data['serial_port'])NEWLINE devices_with_udev = BrewPiDevice.objects.filter(udev_serial_number=udev)NEWLINENEWLINE if len(devices_with_udev) != 0:NEWLINE raise forms.ValidationError("Prefer connecting via udev is set, but another device "NEWLINE "is set up with a similar udev serial number. To proceed, uncheck "NEWLINE "this option or remove the other device.")NEWLINE else:NEWLINE # The user didn't click "prefer_connecting_via_udev". Check two things:NEWLINE # First, check that there isn't a device that exists already with the same serial_port or serial_alt_portNEWLINENEWLINE devices_with_port = BrewPiDevice.objects.filter(serial_port=cleaned_data['serial_port'])NEWLINE devices_with_port_alt = BrewPiDevice.objects.filter(serial_alt_port=cleaned_data['serial_port'])NEWLINE devices_with_alt = BrewPiDevice.objects.filter(serial_port=cleaned_data['serial_alt_port'])NEWLINE devices_with_alt_alt = BrewPiDevice.objects.filter(serial_alt_port=cleaned_data['serial_alt_port'])NEWLINENEWLINE if len(devices_with_port) != 0 or len(devices_with_port_alt) != 0 or len(devices_with_alt) != 0 or len(devices_with_alt_alt) != 0:NEWLINE raise forms.ValidationError("A device is already set up with that serial port or alternate serial "NEWLINE "port. To proceed, change ports, or remove the other device.")NEWLINENEWLINE udev = udev_integration.get_serial_from_node(cleaned_data['serial_port'])NEWLINE devices_with_udev = BrewPiDevice.objects.filter(udev_serial_number=udev)NEWLINENEWLINE for this_device in devices_with_udev:NEWLINE if this_device.prefer_connecting_via_udev:NEWLINE raise forms.ValidationError("The device {} has a ".format(this_device) +NEWLINE "conflicting udev serial number to the one you are currently"NEWLINE "attempting to set up, and has 'prefer connecting via udev' turned"NEWLINE "on. This can cause unexpected behavior. Please disable this option"NEWLINE "on the other device (or delete it entirely) to proceed with adding"NEWLINE "this one.")NEWLINENEWLINE elif cleaned_data['connection_type'] == 'wifi':NEWLINE cleaned_data['serial_port'] = 'auto'NEWLINE cleaned_data['serial_alt_port'] = 'None'NEWLINE cleaned_data['prefer_connecting_via_udev'] = TrueNEWLINENEWLINE # Since we've skipped automated validation above, validate here.NEWLINE if cleaned_data['wifi_host'] is None or cleaned_data['wifi_port'] is None:NEWLINE raise forms.ValidationError("WiFi Host & Port are required for connection type 'WiFi'")NEWLINE elif cleaned_data['wifi_port'] < 0 or cleaned_data['wifi_port'] > 65536:NEWLINE raise forms.ValidationError("WiFi port must be between 1 and 65536 (but is generally 23)")NEWLINE elif len(cleaned_data['wifi_host']) < 5:NEWLINE raise forms.ValidationError("Must specify a valid hostname or IP address for WiFi Host")NEWLINE else:NEWLINE raise forms.ValidationError("Invalid connection type specified")NEWLINENEWLINE # Check if we are using inet sockets to connect to brewpi-script and default parameters that don't applyNEWLINE if cleaned_data['useInetSocket']:NEWLINE cleaned_data['socket_name'] = "BEERSOCKET"NEWLINE else:NEWLINE cleaned_data['socketPort'] = 2222NEWLINE cleaned_data['socketHost'] = "localhost"NEWLINENEWLINE return cleaned_dataNEWLINENEWLINENEWLINEclass OldCCModelForm(ModelForm):NEWLINE class Meta:NEWLINE model = OldControlConstantsNEWLINE fields = OldControlConstants.firmware_field_listNEWLINENEWLINE def __init__(self, *args, **kwargs):NEWLINE super(OldCCModelForm, self).__init__(*args, **kwargs)NEWLINE for this_field in self.fields:NEWLINE self.fields[this_field].widget.attrs['class'] = "form-control"NEWLINENEWLINENEWLINEclass NewCCModelForm(ModelForm):NEWLINE class Meta:NEWLINE model = NewControlConstantsNEWLINE fields = NewControlConstants.firmware_field_listNEWLINENEWLINE def __init__(self, *args, **kwargs):NEWLINE super(NewCCModelForm, self).__init__(*args, **kwargs)NEWLINE for this_field in self.fields:NEWLINE self.fields[this_field].widget.attrs['class'] = "form-control"NEWLINENEWLINENEWLINEclass SensorForm(ModelForm):NEWLINE # TODO - Delete if no longer requiredNEWLINE class Meta:NEWLINE model = SensorDeviceNEWLINE fields = ['device_function', 'invert', 'pin', 'address']NEWLINENEWLINE def __init__(self, *args, **kwargs):NEWLINE super(SensorForm, self).__init__(*args, **kwargs)NEWLINE for this_field in self.fields:NEWLINE self.fields[this_field].widget.attrs['class'] = "form-control"NEWLINENEWLINENEWLINEclass SensorFormRevised(forms.Form):NEWLINE # TODO - Overwrite the DEVICE_FUNCTION_CHOICES to match the type of device being configuredNEWLINE device_function = forms.ChoiceField(label="Device Function",NEWLINE widget=forms.Select(attrs={'class': 'form-control select select-primary',NEWLINE 'data-toggle': 'select'}),NEWLINE choices=SensorDevice.DEVICE_FUNCTION_CHOICES, required=False)NEWLINE invert = forms.ChoiceField(label="Invert Pin",NEWLINE widget=forms.Select(attrs={'class': 'form-control select select-primary', 'data-toggle': 'select'}),NEWLINE choices=SensorDevice.INVERT_CHOICES, required=False)NEWLINE # Not sure if I want to change 'invert' to be a switch or a dropdownNEWLINE # invert = forms.BooleanField(required=False, widget=forms.CheckboxInput(attrs={'data-toggle': 'switch'}))NEWLINENEWLINE calibration = forms.FloatField(label="Temp Calibration Offset", required=False, initial=0.0,NEWLINE help_text="The temperature calibration to be added to each reading (in case "NEWLINE "your temperature sensors misread temps)")NEWLINENEWLINE address = forms.CharField(widget=forms.HiddenInput, required=False)NEWLINE pin = forms.CharField(widget=forms.HiddenInput)NEWLINE installed = forms.BooleanField(widget=forms.HiddenInput, initial=False, required=False)NEWLINENEWLINE # perform_uninstall is just used so we can combine all the actions into this formNEWLINE perform_uninstall = forms.BooleanField(widget=forms.HiddenInput, initial=False, required=False)NEWLINENEWLINE def clean(self):NEWLINE cleaned_data = self.cleaned_dataNEWLINENEWLINE # TODO - Add checks for device_function/pin to make sure they're in the valid rangeNEWLINE if cleaned_data.get("perform_uninstall"):NEWLINE perform_uninstall = cleaned_data.get("perform_uninstall")NEWLINE else:NEWLINE perform_uninstall = FalseNEWLINENEWLINE if perform_uninstall:NEWLINE device_function = SensorDevice.DEVICE_FUNCTION_NONENEWLINE else:NEWLINE device_function = cleaned_data.get("device_function") # TODO - Add additional checks based on device typeNEWLINENEWLINE pin = int(cleaned_data.get("pin"))NEWLINE address = cleaned_data.get("address")NEWLINENEWLINE if cleaned_data.get("installed"):NEWLINE installed = cleaned_data.get("installed")NEWLINE else:NEWLINE installed = FalseNEWLINENEWLINE if len(address) <= 0:NEWLINE if cleaned_data.get("invert"):NEWLINE invert = cleaned_data.get("invert")NEWLINE elif perform_uninstall is True:NEWLINE # We don't care if we're uninstallingNEWLINE invert = SensorDevice.INVERT_NOT_INVERTEDNEWLINE else:NEWLINE raise forms.ValidationError("Invert must be specified for non-OneWire devices")NEWLINE else:NEWLINE invert = SensorDevice.INVERT_NOT_INVERTEDNEWLINENEWLINE # All the fields that MAY have been omitted have been set - return cleaned_dataNEWLINE cleaned_data['invert'] = invertNEWLINE cleaned_data['device_function'] = int(device_function)NEWLINE cleaned_data['installed'] = installedNEWLINE cleaned_data['pin'] = pin # To handle the int conversionNEWLINE cleaned_data['perform_uninstall'] = perform_uninstallNEWLINENEWLINE return cleaned_dataNEWLINENEWLINENEWLINEclass TempControlForm(forms.Form):NEWLINE # TODO - Add validation for temperature_setting to make sure its in range of the device (somehow)NEWLINE TEMP_CONTROL_FUNCTIONS = (NEWLINE ('off','Off'),NEWLINE ('beer_profile', 'Beer Profile'),NEWLINE ('fridge_constant', 'Fridge Constant'),NEWLINE ('beer_constant', 'Beer Constant'),NEWLINE )NEWLINENEWLINE @staticmethodNEWLINE def get_profile_choices():NEWLINE choices = []NEWLINE available_profiles = FermentationProfile.objects.filter(status=FermentationProfile.STATUS_ACTIVE)NEWLINE for this_profile in available_profiles:NEWLINE if this_profile.is_assignable():NEWLINE profile_tuple = (this_profile.id, this_profile.name)NEWLINE choices.append(profile_tuple)NEWLINE return choicesNEWLINENEWLINE # This is actually going to almost always be hidden, but I'm setting it up as a select class here just in caseNEWLINE # we ever decide to actually render this formNEWLINE temp_control = forms.ChoiceField(label="Temperature Control Function",NEWLINE widget=forms.Select(attrs={'class': 'form-control select select-primary',NEWLINE 'data-toggle': 'select'}),NEWLINE choices=TEMP_CONTROL_FUNCTIONS, required=True)NEWLINENEWLINE temperature_setting = forms.DecimalField(label="Temperature Setting", max_digits=4, decimal_places=1,NEWLINE required=False)NEWLINE profile = forms.ChoiceField(required=False) # Choices set in __init__ belowNEWLINE start_at = forms.CharField(help_text="How far into the profile you want to start (optional) " +NEWLINE "(Example: 7d 3h 15m 4s)",NEWLINE widget=forms.TextInput(attrs={'placeholder': '0h 0s'}), required=False,NEWLINE validators=[validators.RegexValidator(regex="([0-9]+[ ]*[ywdhms]{1}[ ]*)+",NEWLINE message="Invalid 'Start At' format")])NEWLINENEWLINE def __init__(self, *args, **kwargs):NEWLINE super(TempControlForm, self).__init__(*args, **kwargs)NEWLINE # for this_field in self.fields:NEWLINE # self.fields[this_field].widget.attrs['class'] = "form-control"NEWLINE self.fields['profile'] = forms.ChoiceField(required=False,NEWLINE choices=self.get_profile_choices(),NEWLINE widget=forms.Select(attrs={'class': 'form-control'}))NEWLINENEWLINE # Check that the Start At format is valid, and if it is, replace it with a datetime delta objectNEWLINE def clean_start_at(self):NEWLINE if 'start_at' in self.cleaned_data:NEWLINE ttl_text = self.cleaned_data['start_at']NEWLINE else:NEWLINE return NoneNEWLINENEWLINE if len(ttl_text) <= 1:NEWLINE return NoneNEWLINENEWLINE return FermentationProfilePoint.string_to_ttl(ttl_text)NEWLINENEWLINE def clean(self):NEWLINE cleaned_data = self.cleaned_dataNEWLINENEWLINE if 'temp_control' in cleaned_data:NEWLINE if cleaned_data['temp_control'] == 'off':NEWLINE # If temp control is off, we don't need a profile or settingNEWLINE return cleaned_dataNEWLINE elif cleaned_data['temp_control'] == 'beer_constant' or cleaned_data['temp_control'] == 'fridge_constant':NEWLINE # For constant modes, we must have a temperature settingNEWLINE if 'temperature_setting' in cleaned_data:NEWLINE if 'temperature_setting' is None:NEWLINE raise forms.ValidationError("A temperature setting must be provided for 'constant' modes")NEWLINE else:NEWLINE return cleaned_dataNEWLINE else:NEWLINE raise forms.ValidationError("A temperature setting must be provided for 'constant' modes")NEWLINE elif cleaned_data['temp_control'] == 'beer_profile':NEWLINE # and for profile modes, we must have a profileNEWLINE if 'profile' in cleaned_data:NEWLINE return cleaned_dataNEWLINE else:NEWLINE raise forms.ValidationError("A temperature profile must be provided for 'profile' modes")NEWLINE else:NEWLINE raise forms.ValidationError("Invalid temperature control mode specified!")NEWLINE else:NEWLINE raise forms.ValidationError("Temperature control mode must be specified!")NEWLINENEWLINE
#!/usr/bin/pythonNEWLINENEWLINE# Copyright (c) 2016-2020 Dell Inc. or its subsidiaries.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.NEWLINENEWLINEimport argparseNEWLINEimport jsonNEWLINEimport loggingNEWLINEimport osNEWLINEimport sysNEWLINEimport subprocessNEWLINEimport utilsNEWLINEfrom arg_helper import ArgHelperNEWLINEfrom command_helper import ExecNEWLINEfrom ironic_helper import IronicHelperNEWLINEfrom logging_helper import LoggingHelperNEWLINENEWLINElogging.basicConfig()NEWLINElogger = logging.getLogger(os.path.splitext(os.path.basename(sys.argv[0]))[0])NEWLINENEWLINEDOWNSTREAM_ATTRS = ["model", "provisioning_mac", "service_tag"]NEWLINENEWLINENEWLINEdef parse_arguments():NEWLINE parser = argparse.ArgumentParser(NEWLINE description="Loads nodes into ironic.",NEWLINE formatter_class=argparse.ArgumentDefaultsHelpFormatter)NEWLINENEWLINE ArgHelper.add_instack_arg(parser)NEWLINENEWLINE LoggingHelper.add_argument(parser)NEWLINENEWLINE return parser.parse_args()NEWLINENEWLINENEWLINEdef main():NEWLINE args = parse_arguments()NEWLINENEWLINE LoggingHelper.configure_logging(args.logging_level)NEWLINENEWLINE # Load the nodes into ironicNEWLINE import_json = os.path.expanduser('~/nodes.json')NEWLINE content = json.load(open(args.node_definition))NEWLINE for node in content['nodes']:NEWLINE for k in node.keys():NEWLINE if k in DOWNSTREAM_ATTRS:NEWLINE node.pop(k)NEWLINE with open(import_json, 'w') as out:NEWLINE json.dump(content, out)NEWLINE logger.info("Importing {} into ironic".format(args.node_definition))NEWLINE cmd = ["openstack", "overcloud", "node", "import", import_json]NEWLINE exit_code, stdin, stderr = Exec.execute_command(cmd)NEWLINE if exit_code != 0:NEWLINE logger.error("Failed to import nodes into ironic: {}, {}".format(NEWLINE stdin, stderr))NEWLINE sys.exit(1)NEWLINENEWLINE # Load the instack fileNEWLINE try:NEWLINE json_file = os.path.expanduser(args.node_definition)NEWLINE with open(json_file, 'r') as instackenv_json:NEWLINE instackenv = json.load(instackenv_json)NEWLINE except (IOError, ValueError):NEWLINE logger.exception("Failed to load node definition file {}".format(NEWLINE args.node_definition))NEWLINE sys.exit(1)NEWLINENEWLINE nodes = instackenv["nodes"]NEWLINENEWLINE # Loop thru the nodesNEWLINE for node in nodes:NEWLINE # Find the node in ironicNEWLINE ironic_client = IronicHelper.get_ironic_client()NEWLINE ironic_node = IronicHelper.get_ironic_node(ironic_client,NEWLINE node["pm_addr"])NEWLINENEWLINE # Set the model and service tag on the nodeNEWLINE logger.info("Setting model ({}), service tag ({}), and provisioning "NEWLINE "MAC ({}) on {}".format(NEWLINE node["model"] if "model" in node else "None",NEWLINE node["service_tag"],NEWLINE node["provisioning_mac"] if "provisioning_mac" inNEWLINE node else "None",NEWLINE node["pm_addr"]))NEWLINE patch = [{'op': 'add',NEWLINE 'value': node["service_tag"],NEWLINE 'path': '/properties/service_tag'}]NEWLINENEWLINE if "model" in node:NEWLINE patch.append({'op': 'add',NEWLINE 'value': node["model"],NEWLINE 'path': '/properties/model'})NEWLINENEWLINE if "provisioning_mac" in node:NEWLINE patch.append({'op': 'add',NEWLINE 'value': node["provisioning_mac"],NEWLINE 'path': '/properties/provisioning_mac'})NEWLINE if utils.Utils.is_enable_routed_networks():NEWLINE logger.info("Adding port with physical address to node: %s",NEWLINE str(ironic_node.uuid))NEWLINE kwargs = {'address': node["provisioning_mac"],NEWLINE 'physical_network': 'ctlplane',NEWLINE 'node_uuid': ironic_node.uuid}NEWLINE ironic_client.port.create(**kwargs)NEWLINENEWLINE ironic_client.node.update(ironic_node.uuid, patch)NEWLINENEWLINENEWLINEif __name__ == "__main__":NEWLINE main()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 forNEWLINE# license information.NEWLINE#NEWLINE# Code generated by Microsoft (R) AutoRest Code Generator.NEWLINE# Changes may cause incorrect behavior and will be lost if the code isNEWLINE# regenerated.NEWLINE# --------------------------------------------------------------------------NEWLINENEWLINEfrom msrest.paging import PagedNEWLINENEWLINENEWLINEclass VirtualMachinePaged(Paged):NEWLINE """NEWLINE A paging container for iterating over a list of :class:`VirtualMachine <azure.mgmt.compute.compute.v2016_03_30.models.VirtualMachine>` objectNEWLINE """NEWLINENEWLINE _attribute_map = {NEWLINE 'next_link': {'key': 'nextLink', 'type': 'str'},NEWLINE 'current_page': {'key': 'value', 'type': '[VirtualMachine]'}NEWLINE }NEWLINENEWLINE def __init__(self, *args, **kwargs):NEWLINENEWLINE super(VirtualMachinePaged, self).__init__(*args, **kwargs)NEWLINE
#NEWLINE# © Copyright 2020 Hewlett Packard Enterprise Development LPNEWLINE#NEWLINE# This file was auto-generated by the Python SDK generator; DO NOT EDIT.NEWLINE#NEWLINENEWLINEfrom ..resource import Resource, CollectionNEWLINEfrom ..exceptions import NimOSAPIOperationUnsupportedNEWLINENEWLINEclass Controller(Resource):NEWLINE """NEWLINE Controller is a redundant collection of hardware capable of running the array software.NEWLINENEWLINE Parameters:NEWLINE - id : Identifier of the controller.NEWLINE - name : Name of the controller.NEWLINE - array_name : Name of the array containing this controller.NEWLINE - array_id : Rest ID of the array containing this controller.NEWLINE - partial_response_ok : Indicate that it is ok to provide partially available response.NEWLINE - serial : Serial number for this controller.NEWLINE - hostname : Host name for the controller.NEWLINE - support_address : IP address used for support.NEWLINE - support_netmask : IP netmask used for support.NEWLINE - support_nic : Network card used for support.NEWLINE - power_status : Overall power supply status for the controller.NEWLINE - fan_status : Overall fan status for the controller.NEWLINE - temperature_status : Overall temperature status for the controller.NEWLINE - power_supplies : Status for each power supply in the controller.NEWLINE - fans : Status for each fan in the controller.NEWLINE - temperature_sensors : Status for temperature sensor in the controller.NEWLINE - partition_status : Status of the system's raid partitions.NEWLINE - ctrlr_side : Identifies which controller this is on its array.NEWLINE - state : Indicates whether this controller is active or not.NEWLINE - nvme_cards_enabled : Indicates if the NVMe accelerator card is enabled.NEWLINE - nvme_cards : List of NVMe accelerator cards.NEWLINE - asup_time : Time of the last autosupport by the controller.NEWLINE """NEWLINENEWLINE def create(self, **kwargs):NEWLINE raise NimOSAPIOperationUnsupported("create operation not supported")NEWLINENEWLINE def delete(self, **kwargs):NEWLINE raise NimOSAPIOperationUnsupported("delete operation not supported")NEWLINENEWLINE def update(self, **kwargs):NEWLINE raise NimOSAPIOperationUnsupported("update operation not supported")NEWLINENEWLINEclass ControllerList(Collection):NEWLINE resource = ControllerNEWLINE resource_type = "controllers"NEWLINENEWLINE def create(self, **kwargs):NEWLINE raise NimOSAPIOperationUnsupported("create operation not supported")NEWLINENEWLINE def delete(self, **kwargs):NEWLINE raise NimOSAPIOperationUnsupported("delete operation not supported")NEWLINENEWLINE def update(self, **kwargs):NEWLINE raise NimOSAPIOperationUnsupported("update operation not supported")NEWLINE
#!/usr/bin/env pythonNEWLINENEWLINEimport jsonNEWLINEimport clickNEWLINENEWLINENEWLINE@click.command()NEWLINE@click.option("--in-private")NEWLINEdef dump_pem_to_jwks(in_private):NEWLINE try:NEWLINE from jwcrypto.jwk import JWK, JWKSetNEWLINE except ImportError as e:NEWLINE msg = "You have to install jwcrypto to use this function"NEWLINE print(msg)NEWLINE raise ImportError(msg) from eNEWLINENEWLINE with open(in_private, "rb") as privfile:NEWLINE data = privfile.read()NEWLINENEWLINE jwk = JWK()NEWLINE jwk.import_from_pem(data)NEWLINENEWLINE jwks = JWKSet()NEWLINE jwks.add(jwk)NEWLINENEWLINE raw = jwks.export(private_keys=True)NEWLINE formatted = json.dumps(json.loads(raw), indent=2)NEWLINE with open("private.json", "w") as priv_jwks_file:NEWLINE priv_jwks_file.write(formatted)NEWLINENEWLINE raw = jwks.export(private_keys=False)NEWLINE formatted = json.dumps(json.loads(raw), indent=2)NEWLINE with open("public.json", "w") as public_jwks_file:NEWLINE public_jwks_file.write(formatted)NEWLINENEWLINENEWLINEif __name__ == "__main__":NEWLINE dump_pem_to_jwks()NEWLINE
# -*- coding: utf-8 -*-NEWLINE"""NEWLINECreated on Sat Jan 16 13:04:06 2016NEWLINENEWLINE@author: lilianNEWLINE"""NEWLINENEWLINE#from onvif import ONVIFCameraNEWLINEfrom cameraUtils import IPCameraNEWLINEimport urllibNEWLINEimport loggingNEWLINEimport timeNEWLINENEWLINEclass PTZCamera(IPCamera):NEWLINENEWLINE def __init__(self, host, port ,user, passwd):NEWLINE IPCamera.__init__(self, host, port, user, passwd)NEWLINE NEWLINE self.ptzService = self.create_ptz_service()NEWLINE self.profile = self.mediaService.GetProfiles()[0]NEWLINE NEWLINE self.initializePanTiltBoundaries()NEWLINE NEWLINE def initializePanTiltBoundaries(self):NEWLINE # Get PTZ configuration options for getting continuous move rangeNEWLINE request = self.ptzService.create_type('GetConfigurationOptions')NEWLINE request.ConfigurationToken = self.profile.PTZConfiguration._tokenNEWLINE ptz_configuration_options = self.ptzService.GetConfigurationOptions(request) NEWLINE NEWLINE self.XMAX = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[0].XRange.MaxNEWLINE self.XMIN = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[0].XRange.MinNEWLINE self.YMAX = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[0].YRange.MaxNEWLINE self.YMIN = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[0].YRange.MinNEWLINE self.ZMAX = ptz_configuration_options.Spaces.ContinuousZoomVelocitySpace[0].XRange.MaxNEWLINE self.ZMIN = ptz_configuration_options.Spaces.ContinuousZoomVelocitySpace[0].XRange.MinNEWLINE NEWLINE NEWLINE def getStreamUri(self):NEWLINE# return self.mediaService.GetStreamUri()[0]NEWLINE return 'rtsp://192.168.1.49:554/Streaming/Channels/1?transportmode=unicast&profile=Profile_1'NEWLINE NEWLINE NEWLINE def getStatus(self):NEWLINE media_profile = self.mediaService.GetProfiles()[0]NEWLINE NEWLINE request = self.ptzService.create_type('GetStatus')NEWLINE request.ProfileToken = media_profile._tokenNEWLINE NEWLINE ptzStatus = self.ptzService.GetStatus(request)NEWLINE pan = ptzStatus.Position.PanTilt._xNEWLINE tilt = ptzStatus.Position.PanTilt._yNEWLINE zoom = ptzStatus.Position.Zoom._xNEWLINENEWLINE return (pan, tilt, zoom)NEWLINE NEWLINE def continuousToRight(self):NEWLINE panVelocityFactor = self.XMAXNEWLINE tiltVelocityFactor = 0NEWLINE zoomVelocityFactor = 0NEWLINE self.continuousMove(panVelocityFactor, tiltVelocityFactor, zoomVelocityFactor)NEWLINE NEWLINE def continuousToLeft(self):NEWLINE panVelocityFactor = self.XMINNEWLINE tiltVelocityFactor = 0NEWLINE zoomVelocityFactor = 0NEWLINE self.continuousMove(panVelocityFactor, tiltVelocityFactor, zoomVelocityFactor)NEWLINE NEWLINE def continuousToUp(self):NEWLINE panVelocityFactor = 0NEWLINE tiltVelocityFactor = self.YMAXNEWLINE zoomVelocityFactor = 0NEWLINE self.continuousMove(panVelocityFactor, tiltVelocityFactor, zoomVelocityFactor)NEWLINE NEWLINE def continuousToDown(self):NEWLINE panVelocityFactor = 0NEWLINE tiltVelocityFactor = self.YMINNEWLINE zoomVelocityFactor = 0NEWLINE self.continuousMove(panVelocityFactor, tiltVelocityFactor, zoomVelocityFactor)NEWLINE NEWLINE def continuousZoomIn(self):NEWLINE panVelocityFactor = 0NEWLINE tiltVelocityFactor = 0NEWLINE zoomVelocityFactor = self.ZMAXNEWLINE self.continuousMove(panVelocityFactor, tiltVelocityFactor, zoomVelocityFactor)NEWLINE NEWLINE def continuousZoomOut(self):NEWLINE panVelocityFactor = 0NEWLINE tiltVelocityFactor = 0NEWLINE zoomVelocityFactor = self.ZMINNEWLINE self.continuousMove(panVelocityFactor, tiltVelocityFactor, zoomVelocityFactor)NEWLINE NEWLINE def continuousMove(self, panFactor, tiltFactor, zoomFactor):NEWLINE request = self.ptzService.create_type('ContinuousMove')NEWLINE request.ProfileToken = self.profile._tokenNEWLINE request.Velocity.PanTilt._x = panFactorNEWLINE request.Velocity.PanTilt._y = tiltFactorNEWLINE request.Velocity.Zoom._x = zoomFactorNEWLINE NEWLINE self.ptzService.ContinuousMove(request)NEWLINE # Wait a certain timeNEWLINE timeout = 1NEWLINE time.sleep(timeout)NEWLINE # Stop continuous moveNEWLINE self.ptzService.Stop({'ProfileToken': request.ProfileToken})NEWLINENEWLINENEWLINE def oneStepRight(self):NEWLINE status = self.getStatus()NEWLINE logging.info("Movimiento hacia derecha desde " + str(status))NEWLINE actualPan = status[0]NEWLINE actualTilt = status[1]NEWLINE NEWLINE media_profile = self.mediaService.GetProfiles()[0]NEWLINE NEWLINE request = self.ptzService.create_type('AbsoluteMove')NEWLINE request.ProfileToken = media_profile._tokenNEWLINE pan = actualPan - float(2)/360NEWLINE if pan <= -1:NEWLINE pan = 1NEWLINENEWLINE request.Position.PanTilt._x = panNEWLINE request.Position.PanTilt._y = actualTiltNEWLINE absoluteMoveResponse = self.ptzService.AbsoluteMove(request)NEWLINE NEWLINE def oneStepLeft(self):NEWLINE status = self.getStatus()NEWLINE print "Movimiento hacia izquierda desde " + str(status)NEWLINE actualPan = status[0]NEWLINE actualTilt = status[1]NEWLINE NEWLINE media_profile = self.mediaService.GetProfiles()[0]NEWLINE NEWLINE request = self.ptzService.create_type('AbsoluteMove')NEWLINE request.ProfileToken = media_profile._tokenNEWLINE pan = round(actualPan + float(2)/360 , 6)NEWLINE if pan >= 1:NEWLINE pan = -1NEWLINE print panNEWLINE request.Position.PanTilt._x = panNEWLINE request.Position.PanTilt._y = actualTiltNEWLINE absoluteMoveResponse = self.ptzService.AbsoluteMove(request)NEWLINE NEWLINE NEWLINE def oneStepUp(self):NEWLINE status = self.getStatus()NEWLINE print "Movimiento hacia arriba desde " + str(status)NEWLINE actualPan = status[0]NEWLINE actualTilt = status[1]NEWLINE NEWLINE media_profile = self.mediaService.GetProfiles()[0]NEWLINE NEWLINE request = self.ptzService.create_type('AbsoluteMove')NEWLINE request.ProfileToken = media_profile._tokenNEWLINE tilt = round(actualTilt - float(2)/90, 6)NEWLINE pan = actualPanNEWLINE if tilt <= -1:NEWLINE tilt = -1NEWLINE pan = actualPanNEWLINE elif tilt >= 1:NEWLINE tilt = 1NEWLINE pan = actualPan + 180*float(2)/360NEWLINE NEWLINE request.Position.PanTilt._x = panNEWLINE request.Position.PanTilt._y = tiltNEWLINE absoluteMoveResponse = self.ptzService.AbsoluteMove(request)NEWLINE NEWLINE NEWLINE NEWLINE def oneStepDown(self):NEWLINE status = self.getStatus()NEWLINE print "Movimiento hacia abajo desde " + str(status)NEWLINE actualPan = status[0]NEWLINE actualTilt = status[1]NEWLINE NEWLINE media_profile = self.mediaService.GetProfiles()[0]NEWLINE NEWLINE request = self.ptzService.create_type('AbsoluteMove')NEWLINE request.ProfileToken = media_profile._tokenNEWLINE tilt = round(actualTilt + float(2)/90, 6)NEWLINE pan = actualPanNEWLINE if tilt <= -1:NEWLINE tilt = -1NEWLINE pan = actualPanNEWLINE elif tilt >= 1:NEWLINE tilt = 1NEWLINE pan = actualPan + 180*float(2)/360NEWLINENEWLINE request.Position.PanTilt._x = panNEWLINE request.Position.PanTilt._y = tiltNEWLINE absoluteMoveResponse = self.ptzService.AbsoluteMove(request)NEWLINE NEWLINE NEWLINE def oneStepZoomIn(self):NEWLINE status = self.getStatus()NEWLINE print "Zoom in desde " + str(status)NEWLINE media_profile = self.mediaService.GetProfiles()[0]NEWLINE NEWLINE request = self.ptzService.create_type('AbsoluteMove')NEWLINE request.ProfileToken = media_profile._tokenNEWLINE NEWLINE if status[2] < 0.05:NEWLINE paso = 0.07NEWLINE else:NEWLINE paso = 0.035NEWLINE NEWLINE pZoom = status[2] + pasoNEWLINE if pZoom > 1:NEWLINE pZoom = 1NEWLINE NEWLINE request.Position.Zoom._x = pZoomNEWLINE absoluteMoveResponse = self.ptzService.AbsoluteMove(request)NEWLINE NEWLINE def oneStepZoomOut(self):NEWLINE status = self.getStatus()NEWLINE print "Zoom out desde " + str(status)NEWLINE media_profile = self.mediaService.GetProfiles()[0]NEWLINE NEWLINE request = self.ptzService.create_type('AbsoluteMove')NEWLINE request.ProfileToken = media_profile._tokenNEWLINE NEWLINE pZoom = status[2] - 0.01 # Con este paso anda bienNEWLINE if pZoom < 0:NEWLINE pZoom = 0NEWLINENEWLINE request.Position.Zoom._x = pZoomNEWLINE absoluteMoveResponse = self.ptzService.AbsoluteMove(request)NEWLINE NEWLINE NEWLINE def continuousRight(self):NEWLINE logging.info("Movimiento continuo hacia derecha")NEWLINENEWLINE NEWLINE media_profile = self.mediaService.GetProfiles()[0]NEWLINE NEWLINE request = self.ptzService.create_type('AbsoluteMove')NEWLINE request.ProfileToken = media_profile._tokenNEWLINE pan = actualPan - float(2)/360NEWLINE if pan <= -1:NEWLINE pan = 1NEWLINENEWLINE request.Position.PanTilt._x = panNEWLINE request.Position.PanTilt._y = actualTiltNEWLINE absoluteMoveResponse = self.ptzService.AbsoluteMove(request)NEWLINE NEWLINE NEWLINE NEWLINE def moveAbsolute(self, pan, tilt, zoom = 0):NEWLINE media_profile = self.mediaService.GetProfiles()[0]NEWLINE NEWLINE request = self.ptzService.create_type('AbsoluteMove')NEWLINE request.ProfileToken = media_profile._tokenNEWLINE NEWLINE# pPan = round(1 - float(pan)/180, 6)NEWLINE# pTilt = round(1 - float(tilt)/45, 6)NEWLINE# pZoom = round(float(zoom/100), 6)NEWLINE# NEWLINE request.Position.PanTilt._x = panNEWLINE request.Position.PanTilt._y = tiltNEWLINE request.Position.Zoom._x = zoomNEWLINE absoluteMoveResponse = self.ptzService.AbsoluteMove(request)NEWLINE NEWLINE NEWLINE def setHomePosition(self):NEWLINE media_profile = self.mediaService.GetProfiles()[0]NEWLINE NEWLINE request = self.ptzService.create_type('SetHomePosition')NEWLINE request.ProfileToken = media_profile._tokenNEWLINE self.ptzService.SetHomePosition(request)NEWLINE NEWLINE def gotoHomePosition(self):NEWLINE media_profile = self.mediaService.GetProfiles()[0]NEWLINE NEWLINE request = self.ptzService.create_type('GotoHomePosition')NEWLINE request.ProfileToken = media_profile._tokenNEWLINE self.ptzService.GotoHomePosition(request)NEWLINE NEWLINE def getSnapshotUri(self):NEWLINE media_profile = self.mediaService.GetProfiles()[0]NEWLINE NEWLINE request = self.mediaService.create_type('GetSnapshotUri')NEWLINE request.ProfileToken = media_profile._tokenNEWLINE response = self.mediaService.GetSnapshotUri(request)NEWLINE NEWLINE logging.info(response.Uri)NEWLINE# urllib.urlretrieve("http://10.2.1.49/onvif-http/snapshot", "local-filename.jpeg")NEWLINE NEWLINE ''' Metodo para probar capturas en la PTZ '''NEWLINE def testAbsolute(self, pan, tilt, zoom = 0):NEWLINE media_profile = self.mediaService.GetProfiles()[0]NEWLINE NEWLINE request = self.ptzService.create_type('AbsoluteMove')NEWLINE request.ProfileToken = media_profile._tokenNEWLINE NEWLINE NEWLINE request.Position.PanTilt._x = panNEWLINE request.Position.PanTilt._y = tiltNEWLINE request.Position.Zoom._x = zoomNEWLINE testAbsoluteResponse = self.ptzService.AbsoluteMove(request) NEWLINE
#!/usr/bin/env pythonNEWLINE# -*- coding: utf-8 -*-NEWLINE# @Time : 2018/7/31 12:28NEWLINE# @Author : Ma xiaoquanNEWLINE# @Email : xiaoquan.ma@nokia-sbell.comNEWLINE# @Site :NEWLINE# @File : pydbsync.pyNEWLINE# @desc:NEWLINENEWLINEimport MySQLdb as mdbNEWLINEimport reNEWLINEimport sysNEWLINEimport os.pathNEWLINEfrom datetime import datetimeNEWLINENEWLINEcfg = NoneNEWLINENEWLINEif os.path.isfile("pydbconfig.py"):NEWLINE import pydbconfigNEWLINE cfg = pydbconfig.cfgNEWLINE print "Loaded from python config"NEWLINEelse:NEWLINE import inspectNEWLINE import yamlNEWLINE cfg = yaml.load(open(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) + '/config.yaml', 'r'))NEWLINE print "Loaded from yaml"NEWLINENEWLINEtablecfg = cfg["tables"]NEWLINEsrcparams = cfg["parameters"]["source"]NEWLINEdstparams = cfg["parameters"]["destination"]NEWLINEbatchmax = cfg["parameters"]["batchmax"]NEWLINENEWLINENEWLINEdef countval(db, ctable, fromKey=None):NEWLINE cur = db.cursor()NEWLINE if fromKey is None:NEWLINE cur.execute("SELECT COUNT(*) FROM `" + ctable + "`")NEWLINE else:NEWLINE cur.execute("SELECT COUNT(*) FROM `" + ctable + "` WHERE `" + tablecfg[ctable]["updated-field"] + "` >= %s",NEWLINE [fromKey])NEWLINENEWLINE ret = cur.fetchone()[0]NEWLINE return retNEWLINENEWLINENEWLINEdef findAndCompareRow(row, cmpdescribe, showcreate):NEWLINE ret = FalseNEWLINE # Search "row" into row list (from DESCRIBE query)NEWLINE for i in range(len(cmpdescribe)):NEWLINE currow = cmpdescribe[i]NEWLINE # Found a column with the same name, comparing signatureNEWLINE if currow[0] == row[0]:NEWLINE ret = TrueNEWLINE if len(row) != len(currow):NEWLINE print rowNEWLINE print currowNEWLINE ret = FalseNEWLINE else:NEWLINE for j in range(len(row)):NEWLINE if j == 0:NEWLINE continueNEWLINE if row[j] != currow[j]:NEWLINE if row[j] == '' and currow[j] == 'on update CURRENT_TIMESTAMP':NEWLINE # May be a bug in SRC Host (MySQL 5.0)NEWLINE checkexpr = re.search('^\s*`'+row[0]+'`.*on update current_timestamp,?$', showcreate, re.MULTILINE|re.I)NEWLINE if checkexpr is None:NEWLINE print rowNEWLINE print currowNEWLINE ret = FalseNEWLINE else:NEWLINE print rowNEWLINE print currowNEWLINE ret = FalseNEWLINE return retNEWLINENEWLINENEWLINEdef synctable(srcdb, dstdb, table, fromkey=None):NEWLINE tabledef = []NEWLINE duplicatedef = []NEWLINE datetimeWorkaround = []NEWLINE cur = srcdb.cursor()NEWLINE cur.execute("DESCRIBE `" + table + "`")NEWLINE for i in range(cur.rowcount):NEWLINE row = cur.fetchone()NEWLINE tabledef.append("%s")NEWLINE duplicatedef.append("`" + row[0] + "`=VALUES(`" + row[0] + "`)")NEWLINE datetimeWorkaround.append(row[1])NEWLINENEWLINE # Sync allNEWLINE recordsToSync = countval(srcdb, table, fromkey)NEWLINE currentRecord = 0NEWLINE while currentRecord < recordsToSync:NEWLINE maxRecordToSync = min(recordsToSync, batchmax)NEWLINE print "Max Batch: " + str(maxRecordToSync) + " values; " + str(recordsToSync) + " in total, remaining: " \NEWLINE + str(recordsToSync - currentRecord)NEWLINE cur = srcdb.cursor()NEWLINE dstcur = dstdb.cursor()NEWLINE if fromkey is None:NEWLINE cur.execute("SELECT * FROM `" + table + "` ORDER BY `" + tablecfg[table]["updated-field"]NEWLINE + "` ASC LIMIT " + str(currentRecord) + "," + str(maxRecordToSync))NEWLINE else:NEWLINE cur.execute("SELECT * FROM `" + table + "` WHERE `" + tablecfg[table]["updated-field"] \NEWLINE + "` >= %s ORDER BY `" + tablecfg[table]["updated-field"]NEWLINE + "` ASC LIMIT " + str(currentRecord) + "," + str(maxRecordToSync), [fromkey])NEWLINENEWLINE for i in range(cur.rowcount):NEWLINE row = list(cur.fetchone())NEWLINE print iNEWLINE for j in range(0, len(row)):NEWLINE if row[j] is None and (datetimeWorkaround[j] == "datetime" or datetimeWorkaround[j] == "timestamp"):NEWLINE row[j] = "0000-00-00 00:00:00"NEWLINENEWLINE q = "INSERT INTO `" + table + "` VALUES (" + ",".join(tabledef) + ") ON DUPLICATE KEY UPDATE " \NEWLINE + ",".join(duplicatedef)NEWLINE dstcur.execute(q, row)NEWLINENEWLINE # if len(dstcur.messages) > 0:NEWLINE # print rowNEWLINE currentRecord += cur.rowcountNEWLINENEWLINENEWLINEdef main():NEWLINE currentTable = ""NEWLINE srcdb = NoneNEWLINE dstdb = NoneNEWLINE try:NEWLINE srcdb = mdb.connect(host=srcparams["host"], user=srcparams["user"], passwd=srcparams["pass"], port=srcparams["port"], db=srcparams["schema"])NEWLINE print "Connected to source host"NEWLINE dstdb = mdb.connect(host=dstparams["host"], user=dstparams["user"], passwd=dstparams["pass"], port=dstparams["port"], db=dstparams["schema"])NEWLINE print "Connected to destination host"NEWLINENEWLINE for table in tablecfg:NEWLINE currentTable = tableNEWLINE cur = dstdb.cursor()NEWLINE dstlast = NoneNEWLINE createTable = FalseNEWLINE try:NEWLINE cur.execute("SELECT MAX(`" + tablecfg[table]["updated-field"] + "`) FROM `" + table + "`")NEWLINE dstlast = cur.fetchone()NEWLINENEWLINE # Check table schemaNEWLINE dstdescribe = []NEWLINE cur = dstdb.cursor()NEWLINE cur.execute("DESCRIBE `" + table + "`")NEWLINE for i in range(cur.rowcount):NEWLINE row = cur.fetchone()NEWLINE dstdescribe.append(row)NEWLINENEWLINE cur = dstdb.cursor()NEWLINE cur.execute("SHOW CREATE TABLE " + table)NEWLINE showcreate = cur.fetchone()[1]NEWLINENEWLINE cur = srcdb.cursor()NEWLINE cur.execute("DESCRIBE `" + table + "`")NEWLINENEWLINE # if cur.rowcount != len(dstdescribe):NEWLINE # print "WARNING: structure of \"" + table + "\" table doesn't match between source and destination DB Host, dropping and recreating table"NEWLINE # ## dstdb.cursor().execute("DROP TABLE `" + table + "`")NEWLINE # # dstlast = NoneNEWLINE # # createTable = TrueNEWLINE # else:NEWLINE # for i in range(cur.rowcount):NEWLINE # row = cur.fetchone()NEWLINE # if findAndCompareRow(row, dstdescribe, showcreate) == False:NEWLINE # print "WARNING: structure of \"" + table + "\" table doesn't match between source and destination DB Host, dropping and recreating table"NEWLINE # ## dstdb.cursor().execute("DROP TABLE `" + table + "`")NEWLINE # # dstlast = NoneNEWLINE # # createTable = TrueNEWLINENEWLINE except mdb.Error, ex:NEWLINE if ex.args[0] != 1146:NEWLINE # If other error than "table doesn't exists" (eg. errno 1146)NEWLINE raise exNEWLINE else:NEWLINE print "Table " + table + " doesn't exists on destination host, creating now"NEWLINE # If table doesn't exists (eg. errno 1146)NEWLINE createTable = TrueNEWLINE passNEWLINENEWLINENEWLINE # cur = srcdb.cursor()NEWLINE # cur.execute("SHOW CREATE TABLE `" + table + "`")NEWLINE # createrow = cur.fetchone()NEWLINE # dstdb.cursor().execute(createrow[1])NEWLINENEWLINE # Sync only changedNEWLINE cur = srcdb.cursor()NEWLINE cur.execute("SELECT MAX(`" + tablecfg[table]["updated-field"] + "`) FROM `" + table + "`")NEWLINE srclast = cur.fetchone()NEWLINENEWLINE if dstlast[0] != srclast[0]:NEWLINE print table + ": sync from " + str(dstlast[0])NEWLINE synctable(srcdb, dstdb, table, dstlast[0] - 3000)NEWLINE print table + " sync ended"NEWLINE else:NEWLINE print table + " is already sync'ed"NEWLINENEWLINENEWLINE except mdb.Error, e:NEWLINE print "Error %d on table %s: %s" % (e.args[0], currentTable, e.args[1])NEWLINE sys.exit(1)NEWLINE finally:NEWLINE if srcdb is not None:NEWLINE srcdb.close()NEWLINE if dstdb is not None:NEWLINE dstdb.close()NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE t_start = datetime.now() # 起始时间NEWLINE main()NEWLINE t_end = datetime.now() # 关闭时间NEWLINE print "The script run time is:", (t_end - t_start).total_seconds() # 程序运行时间
#!/usr/bin/env pythonNEWLINENEWLINE# Import modulesNEWLINEfrom pcl_helper import *NEWLINENEWLINENEWLINE# TODO: Define functions as requiredNEWLINENEWLINE# Callback function for your Point Cloud SubscriberNEWLINEdef pcl_callback(pcl_msg):NEWLINE # TODO: Convert ROS msg to PCL dataNEWLINE cloud = ros_to_pcl(pcl_msg)NEWLINENEWLINE # TODO: Voxel Grid DownsamplingNEWLINE # Create a VoxelGrid filter object for our input point cloudNEWLINE vox = cloud.make_voxel_grid_filter()NEWLINENEWLINE # Choose a voxel (also known as leaf) sizeNEWLINE # Note: this (1) is a poor choice of leaf sizeNEWLINE # Experiment and find the appropriate size!NEWLINE LEAF_SIZE = 0.01NEWLINENEWLINE # Set the voxel (or leaf) sizeNEWLINE vox.set_leaf_size(LEAF_SIZE, LEAF_SIZE, LEAF_SIZE)NEWLINENEWLINE # Call the filter function to obtain the resultant downsampled point cloudNEWLINE cloud_filtered = vox.filter()NEWLINENEWLINE # TODO: PassThrough FilterNEWLINE # Create a PassThrough filter object.NEWLINE passthrough = cloud_filtered.make_passthrough_filter()NEWLINENEWLINE # Assign axis and range to the passthrough filter object.NEWLINE filter_axis = 'z'NEWLINE passthrough.set_filter_field_name(filter_axis)NEWLINE axis_min = 0.6NEWLINE axis_max = 1.1NEWLINE passthrough.set_filter_limits(axis_min, axis_max)NEWLINENEWLINE # Finally use the filter function to obtain the resultant point cloud.NEWLINE cloud_filtered = passthrough.filter()NEWLINENEWLINE # TODO: RANSAC Plane SegmentationNEWLINE # Create the segmentation objectNEWLINE seg = cloud_filtered.make_segmenter()NEWLINENEWLINE # Set the model you wish to fitNEWLINE seg.set_model_type(pcl.SACMODEL_PLANE)NEWLINE seg.set_method_type(pcl.SAC_RANSAC)NEWLINENEWLINE # Max distance for a point to be considered fitting the modelNEWLINE # Experiment with different values for max_distanceNEWLINE # for segmenting the tableNEWLINE max_distance = 0.01NEWLINE seg.set_distance_threshold(max_distance)NEWLINE # Call the segment function to obtain set of inlier indices and model coefficientsNEWLINE inliers, coefficients = seg.segment()NEWLINENEWLINE # TODO: Extract inliers and outliersNEWLINE extracted_inliers = cloud_filtered.extract(inliers, negative=False) # tableNEWLINE extracted_outliers = cloud_filtered.extract(inliers, negative=True) # objects on tableNEWLINENEWLINE # TODO: Euclidean ClusteringNEWLINE # Apply function to convert XYZRGB to XYZNEWLINE white_cloud = XYZRGB_to_XYZ(extracted_outliers)NEWLINE tree = white_cloud.make_kdtree()NEWLINE # Create a cluster extraction objectNEWLINE ec = white_cloud.make_EuclideanClusterExtraction()NEWLINE # Set tolerances for distance thresholdNEWLINE # as well as minimum and maximum cluster size (in points)NEWLINE # NOTE: These are poor choices of clustering parametersNEWLINE # Your task is to experiment and find values that work for segmenting objects.NEWLINE ec.set_ClusterTolerance(0.02)NEWLINE ec.set_MinClusterSize(10)NEWLINE ec.set_MaxClusterSize(10000)NEWLINE # Search the k-d tree for clustersNEWLINE ec.set_SearchMethod(tree)NEWLINE # Extract indices for each of the discovered clustersNEWLINE cluster_indices = ec.Extract()NEWLINENEWLINE # TODO: Create Cluster-Mask Point Cloud to visualize each cluster separatelyNEWLINE # Assign a color corresponding to each segmented object in sceneNEWLINE cluster_color = get_color_list(len(cluster_indices))NEWLINENEWLINE color_cluster_point_list = []NEWLINENEWLINE for j, indices in enumerate(cluster_indices):NEWLINE for i, indice in enumerate(indices):NEWLINE color_cluster_point_list.append([white_cloud[indice][0],NEWLINE white_cloud[indice][1],NEWLINE white_cloud[indice][2],NEWLINE rgb_to_float(cluster_color[j])])NEWLINENEWLINE # Create new cloud containing all clusters, each with unique colorNEWLINE cluster_cloud = pcl.PointCloud_PointXYZRGB()NEWLINE cluster_cloud.from_list(color_cluster_point_list)NEWLINENEWLINE # TODO: Convert PCL data to ROS messagesNEWLINE ros_objects_cloud = pcl_to_ros(extracted_outliers)NEWLINE ros_table_cloud = pcl_to_ros(extracted_inliers)NEWLINE ros_cluster_cloud = pcl_to_ros(cluster_cloud)NEWLINENEWLINE # TODO: Publish ROS messagesNEWLINE pcl_objects_pub.publish(ros_objects_cloud)NEWLINE pcl_table_pub.publish(ros_table_cloud)NEWLINE pcl_cluster_pub.publish(ros_cluster_cloud)NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINENEWLINE # TODO:ROS node initializationNEWLINE rospy.init_node('clustering', anonymous=True)NEWLINENEWLINE # TODO: Create SubscribersNEWLINE pcl_sub = rospy.Subscriber("/sensor_stick/point_cloud", pc2.PointCloud2, pcl_callback, queue_size=1)NEWLINENEWLINE # TODO: Create PublishersNEWLINE pcl_objects_pub = rospy.Publisher("/pcl_objects", PointCloud2, queue_size=1)NEWLINE pcl_table_pub = rospy.Publisher("/pcl_table", PointCloud2, queue_size=1)NEWLINE pcl_cluster_pub = rospy.Publisher("/pcl_cluster", PointCloud2, queue_size=1)NEWLINENEWLINE # Initialize color_listNEWLINE get_color_list.color_list = []NEWLINENEWLINE # TODO: Spin while node is not shutdownNEWLINE while not rospy.is_shutdown():NEWLINE rospy.spin()NEWLINE
# encoding: utf-8NEWLINEimport jsonNEWLINENEWLINEimport pytestNEWLINEimport requests_mockNEWLINENEWLINEimport configfetcherNEWLINEimport phabricatorNEWLINEimport wikibugsNEWLINEfrom tests.common import rootNEWLINEfrom tests.wikibugs_network.common import parse_request, conduit_connect, unexpectedNEWLINENEWLINENEWLINEclass WikibugsFixture:NEWLINE def __init__(self):NEWLINE self.events = []NEWLINE self.wikibugs = wikibugs.Wikibugs2(NEWLINE configfetcher.ConfigFetcher(str(root / "config.json.example"))NEWLINE )NEWLINE self.wikibugs.process_event = lambda event: self.events.append(event)NEWLINENEWLINE def poll(self):NEWLINE self.wikibugs.poll()NEWLINENEWLINENEWLINE@pytest.fixture()NEWLINEdef bugs():NEWLINE return WikibugsFixture()NEWLINENEWLINENEWLINEdef feed_query_initial(request, context):NEWLINE content = parse_request(request)NEWLINE assert int(content['limit']) == 1NEWLINE assert 'before' not in contentNEWLINE return json.loads(r"""{"result":{"PHID-STRY-cdxv7sji5d7wnjmiuqgv":{"class":"PhabricatorApplicationTransactionFeedStory","epoch":1577802875,"authorPHID":"PHID-USER-pzp7mdlx7otgdlggnyhh","chronologicalKey":"6776611750075855743","data":{"objectPHID":"PHID-TASK-rnay3rzefpqhoaqm3guo","transactionPHIDs":{"PHID-XACT-TASK-5esu7y3d7evlsi2":"PHID-XACT-TASK-5esu7y3d7evlsi2"}}}},"error_code":null,"error_info":null}""") # noqaNEWLINENEWLINENEWLINEdef feed_query_second(request, context):NEWLINE content = parse_request(request)NEWLINE assert content['before'] == 6776611750075855743NEWLINE assert content['view'] == 'data'NEWLINE return json.loads(r"""{"result":[],"error_code":null,"error_info":null}""")NEWLINENEWLINENEWLINEdef feed_query_third(request, context):NEWLINE content = parse_request(request)NEWLINE assert content['before'] == 6776611750075855743NEWLINE assert content['view'] == 'data'NEWLINE return json.loads(r"""{"result":{"PHID-STRY-etrbfg7qqflcsoexaxqr":{"class":"PhabricatorApplicationTransactionFeedStory","epoch":1577804347,"authorPHID":"PHID-USER-idceizaw6elwiwm5xshb","chronologicalKey":"6776618070283272953","data":{"objectPHID":"PHID-TASK-he2h6hqmwrdrav3cxqew","transactionPHIDs":{"PHID-XACT-TASK-k6asmqpfv2t37tp":"PHID-XACT-TASK-k6asmqpfv2t37tp"}}},"PHID-STRY-x6pr64eeimmcjl3jbsay":{"class":"PhabricatorApplicationTransactionFeedStory","epoch":1577804344,"authorPHID":"PHID-USER-idceizaw6elwiwm5xshb","chronologicalKey":"6776618060350723377","data":{"objectPHID":"PHID-TASK-he2h6hqmwrdrav3cxqew","transactionPHIDs":{"PHID-XACT-TASK-ix5urhvrpvn22e2":"PHID-XACT-TASK-ix5urhvrpvn22e2"}}},"PHID-STRY-cpcsc3r3444i3vaw66bo":{"class":"PhabricatorApplicationTransactionFeedStory","epoch":1577804267,"authorPHID":"PHID-USER-muirnivxp5hzppn2a3z7","chronologicalKey":"6776617727166200626","data":{"objectPHID":"PHID-TASK-dgq26etiz4wecd24gkmb","transactionPHIDs":{"PHID-XACT-TASK-zd6b2kmmj5pnfwm":"PHID-XACT-TASK-zd6b2kmmj5pnfwm"}}}},"error_code":null,"error_info":null}""") # noqaNEWLINENEWLINENEWLINEdef feed_query_error_response(request, context):NEWLINE return json.loads(r"""{"result":null,"error_code":"ERR-CONDUIT-CORE","error_info":"Cursor \"6771969043218032437\" does not identify a valid object in query \"PhabricatorFeedQuery\"."}""") # noqaNEWLINENEWLINENEWLINEdef test_polling(bugs):NEWLINE with requests_mock.mock() as m:NEWLINE m.post('/api/conduit.connect', [{'json': conduit_connect}, {'json': unexpected}])NEWLINE m.post('/api/feed.query', [{'json': feed_query_initial}, {'json': feed_query_second}, {'json': unexpected}])NEWLINE bugs.poll()NEWLINE assert bugs.events == []NEWLINENEWLINE m.post('/api/feed.query', [{'json': feed_query_third}, {'json': unexpected}])NEWLINE bugs.poll()NEWLINENEWLINE assert len(bugs.events) == 3NEWLINENEWLINE # TODO: add more extensive testsNEWLINENEWLINENEWLINEdef test_error_response(bugs):NEWLINE with requests_mock.mock() as m:NEWLINE m.post('/api/conduit.connect', [{'json': conduit_connect}, {'json': unexpected}])NEWLINE m.post('/api/feed.query', [{'json': feed_query_initial}, {'json': feed_query_second}])NEWLINE bugs.poll()NEWLINENEWLINE m.post('/api/feed.query', [{'json': feed_query_error_response}, {'json': unexpected}])NEWLINE with pytest.raises(phabricator.PhabricatorException):NEWLINE bugs.poll()NEWLINE
# Generated by Django 2.2 on 2020-02-19 18:16NEWLINENEWLINEfrom django.db import migrations, modelsNEWLINEimport django.db.models.deletionNEWLINENEWLINENEWLINEclass Migration(migrations.Migration):NEWLINENEWLINE dependencies = [NEWLINE ('home', '0108_fullwidthpage_citations'),NEWLINE ]NEWLINENEWLINE operations = [NEWLINE migrations.AlterField(NEWLINE model_name='custompage',NEWLINE name='page_ptr',NEWLINE field=models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='wagtailcore.Page'),NEWLINE ),NEWLINE migrations.AlterField(NEWLINE model_name='digestpageauthors',NEWLINE name='author',NEWLINE field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='home.Author'),NEWLINE ),NEWLINE migrations.AlterField(NEWLINE model_name='homepage',NEWLINE name='page_ptr',NEWLINE field=models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='wagtailcore.Page'),NEWLINE ),NEWLINE migrations.AlterField(NEWLINE model_name='pressreleasepageauthors',NEWLINE name='author',NEWLINE field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='home.Author'),NEWLINE ),NEWLINE migrations.AlterField(NEWLINE model_name='recordpageauthors',NEWLINE name='author',NEWLINE field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='home.Author'),NEWLINE ),NEWLINE ]NEWLINE
# Copyright 2015 The Chromium Authors. All rights reserved.NEWLINE# Use of this source code is governed by a BSD-style license that can beNEWLINE# found in the LICENSE file.NEWLINE"""NEWLINEGenerator that produces an externs file for the Closure Compiler.NEWLINENote: This is a work in progress, and generated externs may require tweaking.NEWLINENEWLINESee https://developers.google.com/closure/compiler/docs/api-tutorial3#externsNEWLINE"""NEWLINENEWLINEfrom code import CodeNEWLINEfrom js_util import JsUtilNEWLINEfrom model import *NEWLINEfrom schema_util import *NEWLINENEWLINEimport osNEWLINEimport sysNEWLINEimport reNEWLINENEWLINENOTE = """// NOTE: The format of types has changed. 'FooType' is nowNEWLINE// 'chrome.%s.FooType'.NEWLINE// Please run the closure compiler before committing changes.NEWLINE// See https://chromium.googlesource.com/chromium/src/+/master/docs/closure_compilation.mdNEWLINE"""NEWLINENEWLINEclass JsExternsGenerator(object):NEWLINE def Generate(self, namespace):NEWLINE return _Generator(namespace).Generate()NEWLINENEWLINEclass _Generator(object):NEWLINE def __init__(self, namespace):NEWLINE self._namespace = namespaceNEWLINE self._class_name = NoneNEWLINE self._js_util = JsUtil()NEWLINENEWLINE def Generate(self):NEWLINE """Generates a Code object with the schema for the entire namespace.NEWLINE """NEWLINE c = Code()NEWLINE # /abs/path/src/tools/json_schema_compiler/NEWLINE script_dir = os.path.dirname(os.path.abspath(__file__))NEWLINE # /abs/path/src/NEWLINE src_root = os.path.normpath(os.path.join(script_dir, '..', '..'))NEWLINE # tools/json_schema_compiler/NEWLINE src_to_script = os.path.relpath(script_dir, src_root)NEWLINE # tools/json_schema_compiler/compiler.pyNEWLINE compiler_path = os.path.join(src_to_script, 'compiler.py')NEWLINE (c.Append(self._GetHeader(compiler_path, self._namespace.name))NEWLINE .Append())NEWLINENEWLINE self._AppendNamespaceObject(c)NEWLINENEWLINE for js_type in self._namespace.types.values():NEWLINE self._AppendType(c, js_type)NEWLINENEWLINE for function in self._namespace.functions.values():NEWLINE self._AppendFunction(c, function)NEWLINENEWLINE for event in self._namespace.events.values():NEWLINE self._AppendEvent(c, event)NEWLINENEWLINE c.TrimTrailingNewlines()NEWLINENEWLINE return cNEWLINENEWLINE def _GetHeader(self, tool, namespace):NEWLINE """Returns the file header text.NEWLINE """NEWLINE return (self._js_util.GetLicense() + '\n' +NEWLINE self._js_util.GetInfo(tool) + (NOTE % namespace) + '\n' +NEWLINE ('/** @fileoverview Externs generated from namespace: %s */' %NEWLINE namespace))NEWLINENEWLINE def _AppendType(self, c, js_type):NEWLINE """Given a Type object, generates the Code for this type's definition.NEWLINE """NEWLINE if js_type.property_type is PropertyType.ENUM:NEWLINE self._AppendEnumJsDoc(c, js_type)NEWLINE else:NEWLINE self._AppendTypeJsDoc(c, js_type)NEWLINE c.Append()NEWLINENEWLINE def _AppendEnumJsDoc(self, c, js_type):NEWLINE """ Given an Enum Type object, generates the Code for the enum's definition.NEWLINE """NEWLINE (c.Sblock(line='/**', line_prefix=' * ')NEWLINE .Append('@enum {string}')NEWLINE .Append(self._js_util.GetSeeLink(self._namespace.name, 'type',NEWLINE js_type.simple_name))NEWLINE .Eblock(' */'))NEWLINE c.Append('%s.%s = {' % (self._GetNamespace(), js_type.name))NEWLINENEWLINE def get_property_name(e):NEWLINE # Enum properties are normified to be in ALL_CAPS_STYLE.NEWLINE # Assume enum '1ring-rulesThemAll'.NEWLINE # Transform to '1ring-rules_Them_All'.NEWLINE e = re.sub(r'([a-z])([A-Z])', r'\1_\2', e)NEWLINE # Transform to '1ring_rules_Them_All'.NEWLINE e = re.sub(r'\W', '_', e)NEWLINE # Transform to '_1ring_rules_Them_All'.NEWLINE e = re.sub(r'^(\d)', r'_\1', e)NEWLINE # Transform to '_1RING_RULES_THEM_ALL'.NEWLINE return e.upper()NEWLINENEWLINE c.Append('\n'.join(NEWLINE [" %s: '%s'," % (get_property_name(v.name), v.name)NEWLINE for v in js_type.enum_values]))NEWLINE c.Append('};')NEWLINENEWLINE def _IsTypeConstructor(self, js_type):NEWLINE """Returns true if the given type should be a @constructor. If this returnsNEWLINE false, the type is a typedef.NEWLINE """NEWLINE return any(prop.type_.property_type is PropertyType.FUNCTIONNEWLINE for prop in js_type.properties.values())NEWLINENEWLINE def _AppendTypeJsDoc(self, c, js_type, optional=False):NEWLINE """Appends the documentation for a type as a Code.NEWLINE """NEWLINE c.Sblock(line='/**', line_prefix=' * ')NEWLINENEWLINE if js_type.description:NEWLINE for line in js_type.description.splitlines():NEWLINE c.Append(line)NEWLINENEWLINE if js_type.jsexterns:NEWLINE for line in js_type.jsexterns.splitlines():NEWLINE c.Append(line)NEWLINENEWLINE is_constructor = self._IsTypeConstructor(js_type)NEWLINE if js_type.property_type is not PropertyType.OBJECT:NEWLINE self._js_util.AppendTypeJsDoc(c, self._namespace.name, js_type, optional)NEWLINE elif is_constructor:NEWLINE c.Comment('@constructor', comment_prefix = '', wrap_indent=4)NEWLINE c.Comment('@private', comment_prefix = '', wrap_indent=4)NEWLINE else:NEWLINE self._AppendTypedef(c, js_type.properties)NEWLINENEWLINE c.Append(self._js_util.GetSeeLink(self._namespace.name, 'type',NEWLINE js_type.simple_name))NEWLINE c.Eblock(' */')NEWLINENEWLINE var = '%s.%s' % (self._GetNamespace(), js_type.simple_name)NEWLINE if is_constructor: var += ' = function() {}'NEWLINE var += ';'NEWLINE c.Append(var)NEWLINENEWLINE if is_constructor:NEWLINE c.Append()NEWLINE self._class_name = js_type.nameNEWLINE for prop in js_type.properties.values():NEWLINE if prop.type_.property_type is PropertyType.FUNCTION:NEWLINE self._AppendFunction(c, prop.type_.function)NEWLINE else:NEWLINE self._AppendTypeJsDoc(c, prop.type_, prop.optional)NEWLINE c.Append()NEWLINE self._class_name = NoneNEWLINENEWLINE def _AppendTypedef(self, c, properties):NEWLINE """Given an OrderedDict of properties, Appends code containing a @typedef.NEWLINE """NEWLINE if not properties: returnNEWLINENEWLINE c.Append('@typedef {')NEWLINE self._js_util.AppendObjectDefinition(c, self._namespace.name, properties,NEWLINE new_line=False)NEWLINE c.Append('}', new_line=False)NEWLINENEWLINE def _AppendFunction(self, c, function):NEWLINE """Appends the code representing a function, including its documentation.NEWLINE For example:NEWLINENEWLINE /**NEWLINE * @param {string} title The new title.NEWLINE */NEWLINE chrome.window.setTitle = function(title) {};NEWLINE """NEWLINE self._js_util.AppendFunctionJsDoc(c, self._namespace.name, function)NEWLINE params = self._GetFunctionParams(function)NEWLINE c.Append('%s.%s = function(%s) {};' % (self._GetNamespace(),NEWLINE function.name, params))NEWLINE c.Append()NEWLINENEWLINE def _AppendEvent(self, c, event):NEWLINE """Appends the code representing an event.NEWLINE For example:NEWLINENEWLINE /** @type {!ChromeEvent} */NEWLINE chrome.bookmarks.onChildrenReordered;NEWLINE """NEWLINE c.Sblock(line='/**', line_prefix=' * ')NEWLINE if (event.description):NEWLINE c.Comment(event.description, comment_prefix='')NEWLINE c.Append('@type {!ChromeEvent}')NEWLINE c.Append(self._js_util.GetSeeLink(self._namespace.name, 'event',NEWLINE event.name))NEWLINE c.Eblock(' */')NEWLINE c.Append('%s.%s;' % (self._GetNamespace(), event.name))NEWLINE c.Append()NEWLINENEWLINE def _AppendNamespaceObject(self, c):NEWLINE """Appends the code creating namespace object.NEWLINE For example:NEWLINENEWLINE /**NEWLINE * @constNEWLINE */NEWLINE chrome.bookmarks = {};NEWLINE """NEWLINE c.Append("""/**NEWLINE * @constNEWLINE */""")NEWLINE c.Append('chrome.%s = {};' % self._namespace.name)NEWLINE c.Append()NEWLINENEWLINE def _GetFunctionParams(self, function):NEWLINE """Returns the function params string for function.NEWLINE """NEWLINE params = function.params[:]NEWLINE if function.callback:NEWLINE params.append(function.callback)NEWLINE return ', '.join(param.name for param in params)NEWLINENEWLINE def _GetNamespace(self):NEWLINE """Returns the namespace to be prepended to a top-level typedef.NEWLINENEWLINE For example, it might return "chrome.namespace".NEWLINENEWLINE Also optionally includes the class name if this is in the contextNEWLINE of outputting the members of a class.NEWLINENEWLINE For example, "chrome.namespace.ClassName.prototype"NEWLINE """NEWLINE if self._class_name:NEWLINE return 'chrome.%s.%s.prototype' % (self._namespace.name, self._class_name)NEWLINE return 'chrome.%s' % self._namespace.nameNEWLINE
"""NEWLINEPython的内置函数NEWLINE- 数学相关: abs / divmod / pow / round / min / max / sumNEWLINE- 序列相关: len / range / next / filter / map / sorted / slice / reversedNEWLINE- 类型转换: chr / ord / str / bool / int / float / complex / bin / oct / hexNEWLINE- 数据结构: dict / list / set / tupleNEWLINE- 其他函数: all / any / id / input / open / print / typeNEWLINENEWLINEVersion: 0.1NEWLINEAuthor: BDFDNEWLINEDate: 2018-03-05NEWLINE"""NEWLINENEWLINENEWLINEdef myfilter(mystr):NEWLINE return len(mystr) == 6NEWLINENEWLINENEWLINE# help()NEWLINEprint(chr(0x9a86))NEWLINEprint(hex(ord('骆')))NEWLINEprint(abs(-1.2345))NEWLINEprint(round(-1.2345))NEWLINEprint(pow(1.2345, 5))NEWLINEfruits = ['orange', 'peach', 'durian', 'watermelon']NEWLINEprint(fruits[slice(1, 3)])NEWLINEfruits2 = list(filter(myfilter, fruits))NEWLINEprint(fruits)NEWLINEprint(fruits2)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
r"""NEWLINEModule for some integrators.NEWLINENEWLINE - IRK3: Implicit third order Runge-KuttaNEWLINE - RK4: Runge-Kutta fourth orderNEWLINE - ETD: Exponential time differencing Euler methodNEWLINE - ETDRK4: Exponential time differencing Runge-Kutta fourth orderNEWLINENEWLINESee, e.g.,NEWLINEH. Montanelli and N. Bootland "Solving periodic semilinear PDEs in 1D, 2D andNEWLINE3D with exponential integrators", https://arxiv.org/pdf/1604.08900.pdfNEWLINENEWLINEIntegrators are set up to solve equations likeNEWLINENEWLINE.. math::NEWLINENEWLINE \frac{\partial u}{\partial t} = L u + N(u)NEWLINENEWLINEwhere :math:`u` is the solution, :math:`L` is a linear operator andNEWLINE:math:`N(u)` is the nonlinear part of the right hand side.NEWLINENEWLINENoteNEWLINE----NEWLINE`RK4`, `ETD` and `ETDRK4` can only be used with Fourier function spaces,NEWLINEas they assume all matrices are diagonal.NEWLINENEWLINE"""NEWLINEimport typesNEWLINEimport numpy as npNEWLINEfrom shenfun import Function, TPMatrix, TrialFunction, TestFunction,\NEWLINE inner, la, Expr, CompositeSpace, BlockMatrix, extract_bc_matrices,\NEWLINE SparseMatrix, get_simplified_tpmatrices, ScipyMatrixNEWLINENEWLINE__all__ = ('IRK3', 'BackwardEuler', 'RK4', 'ETDRK4', 'ETD')NEWLINENEWLINE#pylint: disable=unused-variableNEWLINENEWLINEclass IntegratorBase:NEWLINE """Abstract base class for integratorsNEWLINENEWLINE ParametersNEWLINE ----------NEWLINE T : TensorProductSpaceNEWLINE L : functionNEWLINE To compute linear part of right hand sideNEWLINE N : functionNEWLINE To compute nonlinear part of right hand sideNEWLINE update : functionNEWLINE To be called at the end of a timestepNEWLINE params : dictionaryNEWLINE Any relevant keyword argumentsNEWLINENEWLINE """NEWLINENEWLINE def __init__(self, T,NEWLINE L=None,NEWLINE N=None,NEWLINE update=None,NEWLINE **params):NEWLINE _p = {'dt': 0}NEWLINE _p.update(params)NEWLINE self.params = _pNEWLINE self.T = TNEWLINE if L is not None:NEWLINE self.LinearRHS = types.MethodType(L, self)NEWLINE if N is not None:NEWLINE self.NonlinearRHS = types.MethodType(N, self)NEWLINE if update is not None:NEWLINE self.update = types.MethodType(update, self)NEWLINENEWLINE def update(self, u, u_hat, t, tstep, **par):NEWLINE passNEWLINENEWLINE def LinearRHS(self, *args, **kwargs):NEWLINE return 0NEWLINENEWLINE def NonlinearRHS(self, *args, **kwargs):NEWLINE return 0NEWLINENEWLINE def setup(self, dt):NEWLINE """Set up solver"""NEWLINE passNEWLINENEWLINE def solve(self, u, u_hat, dt, trange):NEWLINE """Integrate forward in timeNEWLINENEWLINE ParametersNEWLINE ----------NEWLINE u : arrayNEWLINE The solution array in physical spaceNEWLINE u_hat : arrayNEWLINE The solution array in spectral spaceNEWLINE dt : floatNEWLINE TimestepNEWLINE trange : two-tupleNEWLINE Time and end timeNEWLINE """NEWLINE passNEWLINENEWLINENEWLINEclass IRK3(IntegratorBase):NEWLINE """Third order implicit Runge KuttaNEWLINENEWLINE ParametersNEWLINE ----------NEWLINE T : TensorProductSpaceNEWLINE L : function of TrialFunction(T)NEWLINE To compute linear part of right hand sideNEWLINE N : functionNEWLINE To compute nonlinear part of right hand sideNEWLINE update : functionNEWLINE To be called at the end of a timestepNEWLINE params : dictionaryNEWLINE Any relevant keyword argumentsNEWLINENEWLINE """NEWLINE def __init__(self, T,NEWLINE L=None,NEWLINE N=None,NEWLINE update=None,NEWLINE **params):NEWLINE IntegratorBase.__init__(self, T, L=L, N=N, update=update, **params)NEWLINE self.dU = Function(T)NEWLINE self.dU1 = Function(T)NEWLINE self.a = (8./15., 5./12., 3./4.)NEWLINE self.b = (0.0, -17./60., -5./12.)NEWLINE self.c = (0.0, 8./15., 2./3., 1)NEWLINE self.solver = NoneNEWLINE self.bm = NoneNEWLINE self.rhs_mats = NoneNEWLINE self.w0 = Function(self.T)NEWLINE self.mask = NoneNEWLINE if hasattr(T, 'get_mask_nyquist'):NEWLINE self.mask = T.get_mask_nyquist()NEWLINENEWLINE def setup(self, dt):NEWLINE if isinstance(self.T, CompositeSpace):NEWLINE assert self.T.tensor_rank > 0, 'IRK3 only works for tensors, not generic CompositeSpaces'NEWLINENEWLINE self.params['dt'] = dtNEWLINE u = TrialFunction(self.T)NEWLINE v = TestFunction(self.T)NEWLINENEWLINE # Note that we are here assembling implicit left hand side matrices,NEWLINE # as well as matrices that can be used to assemble the right hand sideNEWLINE # much faster through matrix-vector productsNEWLINENEWLINE a, b = self.a, self.bNEWLINE self.solver = []NEWLINE self.rhs_mats = []NEWLINE u0 = self.LinearRHS(u)NEWLINE for rk in range(3):NEWLINE if u0:NEWLINE mats = inner(v, u-((a[rk]+b[rk])*dt/2)*u0)NEWLINE else:NEWLINE mats = inner(v, u)NEWLINE if self.T.dimensions == 1:NEWLINE self.solver.append(la.Solver(mats))NEWLINENEWLINE elif self.T.tensor_rank == 0:NEWLINE if len(mats[0].naxes) == 1:NEWLINE self.solver.append(la.SolverGeneric1ND(mats))NEWLINE elif len(mats[0].naxes) == 2:NEWLINE self.solver.append(la.SolverGeneric2ND(mats))NEWLINE else:NEWLINE raise NotImplementedErrorNEWLINE else:NEWLINE self.solver.append(BlockMatrixSolver(mats))NEWLINENEWLINE if u0:NEWLINE rhs_mats = inner(v, u+((a[rk]+b[rk])*dt/2)*u0)NEWLINE else:NEWLINE rhs_mats = inner(v, u)NEWLINE mat = ScipyMatrix if self.T.dimensions == 1 else BlockMatrixNEWLINE self.rhs_mats.append(mat(rhs_mats))NEWLINENEWLINE def compute_rhs(self, u, u_hat, dU, dU1, rk):NEWLINE a = self.a[rk]NEWLINE b = self.b[rk]NEWLINE dt = self.params['dt']NEWLINE dU = self.NonlinearRHS(u, u_hat, dU, **self.params)NEWLINE if self.mask:NEWLINE dU.mask_nyquist(self.mask)NEWLINE w1 = dU*a*dt + dU1*b*dtNEWLINE dU1[:] = dUNEWLINE if isinstance(dU, np.ndarray):NEWLINE dU[:] = w1NEWLINE return dUNEWLINENEWLINE def solve(self, u, u_hat, dt, trange):NEWLINE if self.solver is None or abs(self.params['dt']-dt) > 1e-12:NEWLINE self.setup(dt)NEWLINE t, end_time = trangeNEWLINE tstep = self.tstep = 0NEWLINE while t < end_time-1e-8:NEWLINE self.tstep = tstepNEWLINE for rk in range(3):NEWLINE self.params['ti'] = t+self.c[rk]*dtNEWLINE dU = self.compute_rhs(u, u_hat, self.dU, self.dU1, rk)NEWLINE dU += self.rhs_mats[rk].matvec(u_hat, self.w0)NEWLINE u_hat = self.solver[rk](dU, u=u_hat)NEWLINE if self.mask:NEWLINE u_hat.mask_nyquist(self.mask)NEWLINENEWLINE t += dtNEWLINE tstep += 1NEWLINE self.update(u, u_hat, t, tstep, **self.params)NEWLINENEWLINEclass BackwardEuler(IntegratorBase):NEWLINE """First order backward EulerNEWLINENEWLINE ParametersNEWLINE ----------NEWLINE T : TensorProductSpaceNEWLINE L : function of TrialFunction(T)NEWLINE To compute linear part of right hand sideNEWLINE N : functionNEWLINE To compute nonlinear part of right hand sideNEWLINE update : functionNEWLINE To be called at the end of a timestepNEWLINE params : dictionaryNEWLINE Any relevant keyword argumentsNEWLINENEWLINE """NEWLINE def __init__(self, T,NEWLINE L=None,NEWLINE N=None,NEWLINE update=None,NEWLINE **params):NEWLINE IntegratorBase.__init__(self, T, L=L, N=N, update=update, **params)NEWLINE self.dU = Function(T)NEWLINE self.dU1 = Function(T)NEWLINE self.solver = NoneNEWLINE self.rhs_mats = NoneNEWLINE self.w0 = Function(self.T)NEWLINE self.mask = NoneNEWLINE if hasattr(T, 'get_mask_nyquist'):NEWLINE self.mask = T.get_mask_nyquist()NEWLINENEWLINE def setup(self, dt):NEWLINE if isinstance(self.T, CompositeSpace):NEWLINE assert self.T.tensor_rank > 0, 'BackwardEuler only works for tensors, not generic CompositeSpaces'NEWLINENEWLINE self.params['dt'] = dtNEWLINE u = TrialFunction(self.T)NEWLINE v = TestFunction(self.T)NEWLINE mats = inner(u-dt*self.LinearRHS(u), v)NEWLINE M = inner(u, v)NEWLINENEWLINE if self.T.dimensions == 1:NEWLINE self.solver = la.Solve(mats)NEWLINE self.rhs_mats = MNEWLINE returnNEWLINENEWLINE if self.T.tensor_rank == 0:NEWLINE if len(mats[0].naxes) == 1:NEWLINE self.solver = la.SolverGeneric1ND(mats)NEWLINE elif len(mats[0].naxes) == 2:NEWLINE self.solver = la.SolverGeneric2ND(mats)NEWLINE else:NEWLINE raise NotImplementedErrorNEWLINE else:NEWLINE self.solver = BlockMatrixSolver(mats)NEWLINE self.rhs_mats = BlockMatrix(M if isinstance(M, list) else [M])NEWLINENEWLINE def compute_rhs(self, u, u_hat, dU, dU1):NEWLINE dt = self.params['dt']NEWLINE dU = self.NonlinearRHS(u, u_hat, dU, **self.params)NEWLINE if self.mask:NEWLINE dU.mask_nyquist(self.mask)NEWLINE w1 = dU*2*dt - dU1*dtNEWLINE dU1[:] = dUNEWLINE return w1NEWLINENEWLINE def solve(self, u, u_hat, dt, trange):NEWLINE if self.solver is None or abs(self.params['dt']-dt) > 1e-12:NEWLINE self.setup(dt)NEWLINE t, end_time = trangeNEWLINE tstep = self.tstep = 0NEWLINE while t < end_time-1e-8:NEWLINE self.params['ti'] = tNEWLINE self.tstep = tstepNEWLINE dU = self.compute_rhs(u, u_hat, self.dU, self.dU1)NEWLINE dU += self.rhs_mats.matvec(u_hat, self.w0)NEWLINE u_hat = self.solver(dU, u=u_hat)NEWLINE if self.mask:NEWLINE u_hat.mask_nyquist(self.mask)NEWLINE t += dtNEWLINE tstep += 1NEWLINE self.update(u, u_hat, t, tstep, **self.params)NEWLINENEWLINENEWLINEclass ETD(IntegratorBase):NEWLINE """Exponential time differencing Euler methodNEWLINENEWLINE H. Montanelli and N. Bootland "Solving periodic semilinear PDEs in 1D, 2D andNEWLINE 3D with exponential integrators", https://arxiv.org/pdf/1604.08900.pdfNEWLINENEWLINE ParametersNEWLINE ----------NEWLINE T : TensorProductSpaceNEWLINE L : functionNEWLINE To compute linear part of right hand sideNEWLINE N : functionNEWLINE To compute nonlinear part of right hand sideNEWLINE update : functionNEWLINE To be called at the end of a timestepNEWLINE params : dictionaryNEWLINE Any relevant keyword argumentsNEWLINE """NEWLINENEWLINE def __init__(self, T,NEWLINE L=None,NEWLINE N=None,NEWLINE update=None,NEWLINE **params):NEWLINE IntegratorBase.__init__(self, T, L=L, N=N, update=update, **params)NEWLINE self.dU = Function(T)NEWLINE self.psi = NoneNEWLINE self.ehL = NoneNEWLINENEWLINE def setup(self, dt):NEWLINE """Set up ETD ODE solver"""NEWLINE self.params['dt'] = dtNEWLINE u = TrialFunction(self.T)NEWLINE v = TestFunction(self.T)NEWLINE L = self.LinearRHS(u, **self.params)NEWLINE if isinstance(L, Expr):NEWLINE L = inner(v, L)NEWLINE L = get_simplified_tpmatrices(L)[0]NEWLINE if isinstance(L, list):NEWLINE assert self.T.tensor_rank == 1NEWLINE assert L[0].isidentity()NEWLINE L = L[0].scaleNEWLINE # Use only L[0] and let numpy broadcasting take care of the restNEWLINE elif isinstance(L, TPMatrix):NEWLINE assert L.isidentity()NEWLINE L = L.scaleNEWLINE elif isinstance(L, SparseMatrix):NEWLINE L.simplify_diagonal_matrices()NEWLINE L = L.scaleNEWLINENEWLINE L = np.atleast_1d(L)NEWLINE hL = L*dtNEWLINE self.ehL = np.exp(hL)NEWLINE M = 50NEWLINE psi = self.psi = np.zeros(hL.shape, dtype=float)NEWLINE for k in range(1, M+1):NEWLINE ll = hL+np.exp(np.pi*1j*(k-0.5)/M)NEWLINE psi += ((np.exp(ll)-1.)/ll).realNEWLINE psi /= MNEWLINENEWLINE def solve(self, u, u_hat, dt, trange):NEWLINE """Integrate forward in timeNEWLINENEWLINE ParametersNEWLINE ----------NEWLINE u : arrayNEWLINE The solution array in physical spaceNEWLINE u_hat : arrayNEWLINE The solution array in spectral spaceNEWLINE dt : floatNEWLINE TimestepNEWLINE trange : two-tupleNEWLINE Time and end timeNEWLINE """NEWLINE if self.psi is None or abs(self.params['dt']-dt) > 1e-12:NEWLINE self.setup(dt)NEWLINE t, end_time = trangeNEWLINE tstep = 0NEWLINE while t < end_time-1e-8:NEWLINE t += dtNEWLINE tstep += 1NEWLINE self.dU = self.NonlinearRHS(u, u_hat, self.dU, **self.params)NEWLINE u_hat[:] = self.ehL*u_hat + dt*self.psi*self.dUNEWLINE self.update(u, u_hat, t, tstep, **self.params)NEWLINE return u_hatNEWLINENEWLINENEWLINEclass ETDRK4(IntegratorBase):NEWLINE """Exponential time differencing Runge-Kutta 4'th order methodNEWLINENEWLINE H. Montanelli and N. Bootland "Solving periodic semilinear PDEs in 1D, 2D andNEWLINE 3D with exponential integrators", https://arxiv.org/pdf/1604.08900.pdfNEWLINENEWLINE ParametersNEWLINE ----------NEWLINE T : TensorProductSpaceNEWLINE L : functionNEWLINE To compute linear part of right hand sideNEWLINE N : functionNEWLINE To compute nonlinear part of right hand sideNEWLINE update : functionNEWLINE To be called at the end of a timestepNEWLINE params : dictionaryNEWLINE Any relevant keyword argumentsNEWLINE """NEWLINE def __init__(self, T,NEWLINE L=None,NEWLINE N=None,NEWLINE update=None,NEWLINE **params):NEWLINE IntegratorBase.__init__(self, T, L=L, N=N, update=update, **params)NEWLINE self.U_hat0 = Function(T)NEWLINE self.U_hat1 = Function(T)NEWLINE self.dU = Function(T)NEWLINE self.dU0 = Function(T)NEWLINE self.V2 = Function(T)NEWLINE self.psi = np.zeros((4,)+self.U_hat0.shape, dtype=float)NEWLINE self.a = NoneNEWLINE self.b = [0.5, 0.5, 0.5]NEWLINE self.ehL = NoneNEWLINE self.ehL_h = NoneNEWLINENEWLINE def setup(self, dt):NEWLINE """Set up ETDRK4 ODE solver"""NEWLINE self.params['dt'] = dtNEWLINE u = TrialFunction(self.T)NEWLINE v = TestFunction(self.T)NEWLINE L = self.LinearRHS(u, **self.params)NEWLINE if isinstance(L, Expr):NEWLINE L = inner(v, L)NEWLINE L = get_simplified_tpmatrices(L)[0]NEWLINE if isinstance(L, list):NEWLINE assert self.T.tensor_rank == 1NEWLINE assert L[0].isidentity()NEWLINE L = L[0].scaleNEWLINE # Use only L[0] and let numpy broadcasting take care of the restNEWLINE elif isinstance(L, TPMatrix):NEWLINE assert L.isidentity()NEWLINE L = L.scaleNEWLINE elif isinstance(L, SparseMatrix):NEWLINE L.simplify_diagonal_matrices()NEWLINE L = L.scaleNEWLINENEWLINE L = np.atleast_1d(L)NEWLINE hL = L*dtNEWLINE self.ehL = np.exp(hL)NEWLINE self.ehL_h = np.exp(hL/2.)NEWLINE M = 50NEWLINE psi = self.psi = np.zeros((4,) + hL.shape, dtype=float)NEWLINE for k in range(1, M+1):NEWLINE ll = hL+np.exp(np.pi*1j*(k-0.5)/M)NEWLINE psi[0] += ((np.exp(ll)-1.)/ll).realNEWLINE psi[1] += ((np.exp(ll)-ll-1.)/ll**2).realNEWLINE psi[2] += ((np.exp(ll)-0.5*ll**2-ll-1.)/ll**3).realNEWLINE ll2 = hL/2.+np.exp(np.pi*1j*(k-0.5)/M)NEWLINE psi[3] += ((np.exp(ll2)-1.)/(ll2)).realNEWLINENEWLINE psi /= MNEWLINE a = [psi[0]-3*psi[1]+4*psi[2]]NEWLINE a.append(2*psi[1]-4*psi[2])NEWLINE a.append(2*psi[1]-4*psi[2])NEWLINE a.append(-psi[1]+4*psi[2])NEWLINE self.a = aNEWLINENEWLINE def solve(self, u, u_hat, dt, trange):NEWLINE """Integrate forward in timeNEWLINENEWLINE ParametersNEWLINE ----------NEWLINE u : arrayNEWLINE The solution array in physical spaceNEWLINE u_hat : arrayNEWLINE The solution array in spectral spaceNEWLINE dt : floatNEWLINE TimestepNEWLINE trange : two-tupleNEWLINE Time and end timeNEWLINE """NEWLINE if self.a is None or abs(self.params['dt']-dt) > 1e-12:NEWLINE self.setup(dt)NEWLINE t, end_time = trangeNEWLINE tstep = 0NEWLINE while t < end_time-1e-8:NEWLINE t += dtNEWLINE tstep += 1NEWLINENEWLINE self.U_hat0[:] = u_hat*self.ehL_hNEWLINE self.U_hat1[:] = u_hat*self.ehLNEWLINE for rk in range(4):NEWLINE self.dU = self.NonlinearRHS(u, u_hat, self.dU, **self.params)NEWLINE if rk < 2:NEWLINE u_hat[:] = self.U_hat0 + self.b[rk]*dt*self.psi[3]*self.dUNEWLINE elif rk == 2:NEWLINE u_hat[:] = self.ehL_h*self.V2 + self.b[rk]*dt*self.psi[3]*(2*self.dU-self.dU0)NEWLINENEWLINE if rk == 0:NEWLINE self.dU0[:] = self.dUNEWLINE self.V2[:] = u_hatNEWLINENEWLINE self.U_hat1 += self.a[rk]*dt*self.dUNEWLINE u_hat[:] = self.U_hat1NEWLINE self.update(u, u_hat, t, tstep, **self.params)NEWLINE return u_hatNEWLINENEWLINENEWLINEclass RK4(IntegratorBase):NEWLINE """Regular 4'th order Runge-Kutta integratorNEWLINENEWLINE ParametersNEWLINE ----------NEWLINE T : TensorProductSpaceNEWLINE L : functionNEWLINE To compute linear part of right hand sideNEWLINE N : functionNEWLINE To compute nonlinear part of right hand sideNEWLINE update : functionNEWLINE To be called at the end of a timestepNEWLINE params : dictionaryNEWLINE Any relevant keyword argumentsNEWLINE """NEWLINE def __init__(self, T,NEWLINE L=None,NEWLINE N=None,NEWLINE update=None,NEWLINE **params):NEWLINE IntegratorBase.__init__(self, T, L=L, N=N, update=update, **params)NEWLINE self.U_hat0 = Function(T)NEWLINE self.U_hat1 = Function(T)NEWLINE self.dU = Function(T)NEWLINE self.a = np.array([1./6., 1./3., 1./3., 1./6.])NEWLINE self.b = np.array([0.5, 0.5, 1.])NEWLINENEWLINE def setup(self, dt):NEWLINE """Set up RK4 ODE solver"""NEWLINE self.params['dt'] = dtNEWLINENEWLINE def solve(self, u, u_hat, dt, trange):NEWLINE """Integrate forward in end_timeNEWLINENEWLINE ParametersNEWLINE ----------NEWLINE u : arrayNEWLINE The solution array in physical spaceNEWLINE u_hat : arrayNEWLINE The solution array in spectral spaceNEWLINE dt : floatNEWLINE TimestepNEWLINE trange : two-tupleNEWLINE Time and end timeNEWLINE """NEWLINE if self.a is None or abs(self.params['dt']-dt) > 1e-12:NEWLINE self.setup(dt)NEWLINE t, end_time = trangeNEWLINE tstep = 0NEWLINE ut = TrialFunction(self.T)NEWLINE vt = TestFunction(self.T)NEWLINE L = self.LinearRHS(ut, **self.params)NEWLINE if isinstance(L, Expr):NEWLINE L = inner(vt, L)NEWLINE L = get_simplified_tpmatrices(L)[0]NEWLINE if isinstance(L, list):NEWLINE assert self.T.tensor_rank == 1NEWLINE assert L[0].isidentity()NEWLINE L = L[0].scaleNEWLINE # Use only L[0] and let numpy broadcasting take care of the restNEWLINE elif isinstance(L, TPMatrix):NEWLINE assert L.isidentity()NEWLINE L = L.scaleNEWLINE elif isinstance(L, SparseMatrix):NEWLINE L.simplify_diagonal_matrices()NEWLINE L = L.scaleNEWLINENEWLINE while t < end_time-1e-8:NEWLINE t += dtNEWLINE tstep += 1NEWLINE self.U_hat0[:] = self.U_hat1[:] = u_hatNEWLINE for rk in range(4):NEWLINE dU = self.NonlinearRHS(u, u_hat, self.dU, **self.params)NEWLINE if isinstance(L, np.ndarray):NEWLINE dU += L*u_hatNEWLINE if rk < 3:NEWLINE u_hat[:] = self.U_hat0 + self.b[rk]*dt*dUNEWLINE self.U_hat1 += self.a[rk]*dt*dUNEWLINE u_hat[:] = self. U_hat1NEWLINE self.update(u, u_hat, t, tstep, **self.params)NEWLINE return u_hatNEWLINE
# -*- coding: utf-8 -*-NEWLINENEWLINEimport osNEWLINEimport argparseNEWLINEfrom lxml import etree, htmlNEWLINEfrom lxml.html.clean import CleanerNEWLINEimport fnmatch # To match files by patternNEWLINEimport regex as re # Maybe not necessaryNEWLINEimport timeNEWLINEimport dateparserNEWLINEimport jsonNEWLINENEWLINENEWLINEdef timeit(method):NEWLINE """Time methods."""NEWLINE def timed(*args, **kw):NEWLINE ts = time.time()NEWLINE result = method(*args, **kw)NEWLINE te = time.time()NEWLINENEWLINE print('%r %2.2f sec' %NEWLINE (method.__name__, te-ts))NEWLINE return resultNEWLINENEWLINE return timedNEWLINENEWLINENEWLINEclass TransformHtmlProceedingsToXml(object):NEWLINE """Get proceedings of the European Parliament."""NEWLINENEWLINE @timeitNEWLINE def __init__(self):NEWLINE self.cli()NEWLINE self.infiles = self.get_files(self.indir, self.pattern)NEWLINE self.n_proceedings = 0NEWLINE self.ns = {'re': 'http://exslt.org/regular-expressions'}NEWLINE self.loc = self.get_localized_vars()NEWLINE self.explanations_of_vote = re.compile(r' *EXPLANATIONS? OF VOTES?')NEWLINE self.langs = [NEWLINE "BG",NEWLINE "ES",NEWLINE "CS",NEWLINE "DA",NEWLINE "DE",NEWLINE "ET",NEWLINE "EL",NEWLINE "EN",NEWLINE "FR",NEWLINE "GA",NEWLINE "HR",NEWLINE "IT",NEWLINE "LV",NEWLINE "LT",NEWLINE "HU",NEWLINE "MT",NEWLINE "NL",NEWLINE "PL",NEWLINE "PT",NEWLINE "RO",NEWLINE "SK",NEWLINE "SL",NEWLINE "FI",NEWLINE "SV",NEWLINE ]NEWLINE self.main()NEWLINENEWLINE def __str__(self):NEWLINE message = "{} EuroParl's {} proceedings transformed!".format(NEWLINE str(self.n_proceedings),NEWLINE self.language)NEWLINE return messageNEWLINENEWLINE def get_files(self, directory, fileclue):NEWLINE """Get all files in a directory matching a pattern.NEWLINENEWLINE Keyword arguments:NEWLINE directory -- a string for the input folder pathNEWLINE fileclue -- a string as glob patternNEWLINE """NEWLINE matches = []NEWLINE for root, dirnames, filenames in os.walk(directory):NEWLINE for filename in fnmatch.filter(filenames, fileclue):NEWLINE matches.append(os.path.join(root, filename))NEWLINE return matchesNEWLINENEWLINE def get_localized_vars(self):NEWLINE fname = self.language+".json"NEWLINE fpath = os.path.join('localization', fname)NEWLINE with open(fpath, mode="r", encoding="utf-8") as jfile:NEWLINE content = jfile.read()NEWLINE vars = json.loads(content)NEWLINE return varsNEWLINENEWLINE def read_html(self, infile):NEWLINE """Parse a HTML file."""NEWLINE with open(infile, encoding='utf-8', mode='r') as input:NEWLINE return html.parse(input)NEWLINENEWLINE def regextract(self, content, a_pattern, target_dic, dic_attrib):NEWLINE """Extract information with a regular expression.NEWLINENEWLINE Keyword arguments:NEWLINE a_string -- stringNEWLINE a_regex -- a stringNEWLINE target_dic -- a dictionary where the extraction has to be storedNEWLINE dic_attrib -- dictionary key where to store extractionNEWLINE """NEWLINE # match the a_regex in a_stringNEWLINE is_match = re.match(r'{}'.format(a_pattern), content)NEWLINE # if matchNEWLINE if is_match is not None:NEWLINE if dic_attrib not in target_dic.keys():NEWLINE target_dic[dic_attrib] = is_match.group(1)NEWLINE content = re.sub(r'{}'.format(a_pattern), r'', content)NEWLINE return content, target_dicNEWLINENEWLINE def get_speaker_name(self, intervention):NEWLINE speaker_name = intervention.xpath(NEWLINE './/span[@class="doc_subtitle_level1_bis"]//text()')NEWLINE speaker_name = ''.join(speaker_name)NEWLINE speaker_name = re.sub(r'\n', r'', speaker_name)NEWLINE speaker_name = re.sub(r'\&amp;', r'&', speaker_name)NEWLINE speaker_name = re.sub(r'\([\p{Lu}\&/\-–\s]+\)', r'', speaker_name)NEWLINE speaker_name = re.sub(r'\(\p{Lu}\p{Ll}+[/-]ALE\)', r'', speaker_name)NEWLINE speaker_name = re.sub(r' +', r' ', speaker_name)NEWLINE speaker_name = re.sub(r'\A[\xad\s\.—–\-−,\)]+', r'', speaker_name)NEWLINE speaker_name = re.sub(NEWLINE r'([ \.]\p{LU}\.)[\xad\s\.—–\-−,:]+\Z',NEWLINE r'\1',NEWLINE speaker_name)NEWLINE speaker_name = re.sub(NEWLINE r'(\p{L}\p{L})[\xad\s\.—–\-−,\):]+\Z',NEWLINE r'\1',NEWLINE speaker_name)NEWLINE speaker_name = re.sub(r'(\p{L}\p{L}) . —\Z', r'\1', speaker_name)NEWLINE speaker_name = re.sub(NEWLINE r'(Figel’)[\xad\s\.—–\-−,\):]+\Z',NEWLINE r'\1',NEWLINE speaker_name)NEWLINE speaker_name = re.sub(r' \.\Z', r'', speaker_name)NEWLINE speaker_name = re.sub(r'\([\p{Lu}/\xad\-–]+\Z', r'', speaker_name)NEWLINE speaker_name = re.sub(r' +\Z', r'', speaker_name)NEWLINE speaker_name = re.sub(r', +,', r',', speaker_name)NEWLINE speaker_name = re.sub(r' +, +', r',', speaker_name)NEWLINE speaker_name = re.sub(r',+', r',', speaker_name)NEWLINE speaker_name = re.sub(r' *,(\S)', r', \1', speaker_name)NEWLINE speaker_name = re.sub(r',\Z', r'', speaker_name)NEWLINE speaker_name = re.sub(r'(Bartholomeos I)\.', r'\1', speaker_name)NEWLINE speaker_name = re.sub(NEWLINE r', im Namen der Delegation der britischen Konservativen',NEWLINE r'',NEWLINE speaker_name)NEWLINE return speaker_nameNEWLINENEWLINE def get_speaker_id(self, intervention):NEWLINE speaker_id = intervention.xpath('.//img[@alt="MPphoto"]')NEWLINE speaker_id = speaker_id[0].attrib['src']NEWLINE speaker_id = os.path.split(speaker_id)[1]NEWLINE speaker_id = os.path.splitext(speaker_id)[0]NEWLINE return speaker_idNEWLINENEWLINE def get_is_mep(self, speaker_id):NEWLINE if speaker_id is not 'photo_generic':NEWLINE output = TrueNEWLINE else:NEWLINE output = FalseNEWLINE return outputNEWLINENEWLINE def get_mode(self, intervention):NEWLINE in_writing = intervention.xpath(NEWLINE './/span[@class="italic"][text()[re:test(.,"{}")]]'.format(NEWLINE self.loc['in_writing']),NEWLINE namespaces=self.ns)NEWLINE if len(in_writing) > 0:NEWLINE output = 'written'NEWLINE for writing in in_writing:NEWLINE writing.drop_tree()NEWLINE else:NEWLINE output = 'spoken'NEWLINE return outputNEWLINENEWLINE def get_role(self, intervention):NEWLINE roles = intervention.xpath('.//span[@class="italic"][text()[re:test(.,"^[\s\xad\-–−—\.]*(?:{})[\s\xad\-–−\.]*(?:\([A-Z][A-Z]\))?[\s\xad\-–−—\.]*$", "m")]]'.format('|'.join(self.loc['roles'])), namespaces=self.ns)NEWLINE if len(roles) > 0:NEWLINE output = []NEWLINE for role in roles:NEWLINE if type(role) is str:NEWLINE output.append(role)NEWLINE elif type(role) is html.HtmlElement:NEWLINE output.append(role.text)NEWLINE for role in roles:NEWLINE lang = re.match(NEWLINE r'.*({}).*'.format('|'.join(self.langs)),NEWLINE role.text)NEWLINE if lang is not None:NEWLINE i_lang = lang.group(1)NEWLINE else:NEWLINE i_lang = NoneNEWLINE role.drop_tree()NEWLINE else:NEWLINE output = NoneNEWLINE i_lang = NoneNEWLINE if output is not None:NEWLINE output = " ".join(output)NEWLINE output = re.sub(r'\n', r' ', output)NEWLINE output = re.sub(r' +', r' ', output)NEWLINE output = re.sub(r'\([\p{Lu}\&/\-–]+\)', r'', output)NEWLINE output = re.sub(r'(\p{Ll})[\s\.\xad–\-−—,\)]+\Z', r'\1', output)NEWLINE output = re.sub(r'\A[\xad\s\.—–\-−,\)\(]+', r'', output)NEWLINE output = re.sub(r'[\xad\s\.—–\-−,\)]+\Z', r'', output)NEWLINE return output, i_langNEWLINENEWLINE def get_heading(self, section):NEWLINE heading = section.xpath('.//td[@class="doc_title"]//text()')NEWLINE heading = ''.join(heading)NEWLINE heading = heading.strip()NEWLINE heading = re.sub(r'\(\n', r'(', heading)NEWLINE heading = re.sub(r'\n,', r',', heading)NEWLINE return headingNEWLINENEWLINE def get_language(self, s_intervention, p, i_lang, new_paragraphs):NEWLINE language = p.xpath('.//span[@class="italic"][text()[re:test(.,"^[\xad\s\.—–\-−,\(]*({})[\xad\s\.—–\-−,\)]*")]]'.format('|'.join(self.langs)), namespaces=self.ns)NEWLINE if len(language) > 0 and not self.explanations_of_vote.match(language[0].text):NEWLINE lang = re.match(NEWLINE r'.*({}).*'.format('|'.join(self.langs)),NEWLINE language[0].text)NEWLINE output = lang.group(1)NEWLINE for l in language:NEWLINE l.drop_tree()NEWLINE else:NEWLINE p = html.tostring(p, with_tail=True, encoding='utf-8').decode('utf-8')NEWLINE lang_in_text = re.search(NEWLINE r'\(({})\)'.format('|'.join(self.langs)),NEWLINE p)NEWLINE if lang_in_text is not None:NEWLINE output = lang_in_text.group(1)NEWLINE p = re.sub(r'\(({})\) *'.format('|'.join(self.langs)), r'', p)NEWLINE else:NEWLINE if len(new_paragraphs) == 0:NEWLINE if 'role' in s_intervention.keys():NEWLINE president_pattern = '|'.join(self.loc['president'])NEWLINE if re.match(r'{}\Z'.format(president_pattern), s_intervention['role']):NEWLINE output = 'unknown'NEWLINE else:NEWLINE if i_lang is None:NEWLINE output = self.language.upper()NEWLINE else:NEWLINE output = i_langNEWLINE else:NEWLINE if i_lang is None:NEWLINE output = self.language.upper()NEWLINE else:NEWLINE output = i_langNEWLINE else:NEWLINE output = new_paragraphs[-1]['language']NEWLINE p = html.fromstring(p)NEWLINE return output, pNEWLINENEWLINE def clean_paragraph(self, p):NEWLINE cleaner = Cleaner(remove_tags=['a'], kill_tags=['sup', 'img'])NEWLINE p = cleaner.clean_html(p)NEWLINE doc_subtitle = p.xpath('.//span[@class="doc_subtitle_level1_bis"]')NEWLINE for d in doc_subtitle:NEWLINE d.drop_tree()NEWLINE return pNEWLINENEWLINE def get_paragraphs(self, intervention, s_intervention, i_lang):NEWLINE paragraphs = intervention.xpath(NEWLINE './/p[@class="contents" or @class="doc_subtitle_level1"]')NEWLINE new_paragraphs = []NEWLINE for p in paragraphs:NEWLINE new_p = {}NEWLINE p = html.tostring(NEWLINE p,NEWLINE with_tail=True,NEWLINE encoding='utf-8').decode('utf-8')NEWLINE p = re.sub(r'\n+', r' ', p)NEWLINE p = re.sub(r'<br ?/?>', r' ', p)NEWLINE p = html.fromstring(p)NEWLINE p = self.clean_paragraph(p)NEWLINE new_p['language'], p = self.get_language(NEWLINE s_intervention,NEWLINE p,NEWLINE i_lang,NEWLINE new_paragraphs)NEWLINE content = p.text_content()NEWLINE content = content.strip()NEWLINE content = re.sub(r'\t', r' ', content)NEWLINE content = re.sub(r'\xad', r'-', content) # reviseNEWLINE content = re.sub(r'\xa0', r' ', content)NEWLINE content = re.sub(r' +', r' ', content)NEWLINE content = re.sub(r'\. \. \.', r'...', content)NEWLINE content = re.sub(r'\.{3,}', r'…', content)NEWLINE content = re.sub(r'…\.\.', r'…', content)NEWLINE content = re.sub(r'^([\s\.—–\-−,\)]+)', r'', content)NEWLINE content = re.sub(r'([^\.])(…)', r'\1 \2', content)NEWLINE content = re.sub(r'\.…', r' …', content)NEWLINE content = re.sub(r'\( ?… ?\)', r'(…)', content)NEWLINE content = re.sub(r'(…)(\.)(\w)', r'\1\2 \3', content)NEWLINE content = re.sub(r'([\w”])(…)', r'\1 \2', content)NEWLINE content = re.sub(r'(…)(\w)', r'\1 \2', content)NEWLINE content = re.sub(r'\( +\)', r'', content)NEWLINE content = re.sub(r'\( +?', r'(', content)NEWLINE content = re.sub(r' +\)', r')', content)NEWLINE content = re.sub(r'(\[lt\]|<) ?BRK ?(\[gt\]|>)?', r'', content)NEWLINE content = re.sub(r'>(.+?)=', r'"\1"', content)NEWLINE content = re.sub(r's= ', r"s' ", content)NEWLINE content = re.sub(r'<Titre>', r'Titre', content)NEWLINE content = re.sub(r'<0', r'', content)NEWLINE content = re.sub(r'>', r'', content)NEWLINE content = re.sub(r'<', r'', content)NEWLINE content = re.sub(r'^,? *Neil,? +\. +– +', r'', content)NEWLINE content = re.sub(r'^\(PPE-DE\), +\. +– +', r'', content)NEWLINE content = re.sub(r'^\(Verts/ALE\), +\. +– +', r'', content)NEWLINE content = re.sub(r'\A\([\p{Lu}\&/\-–]+\)', r'', content)NEWLINE content = re.sub(r' +', r' ', content)NEWLINE content = re.sub(r'\A([\s\.—–\-−,\)]+)', r'', content)NEWLINE content = re.sub(r'^\((Madam President)', r'\1', content)NEWLINE content = re.sub(r'^\((Mr President)', r'\1', content)NEWLINE for pattern in self.loc['more_roles']:NEWLINE content, s_intervention = self.regextract(NEWLINE content,NEWLINE pattern,NEWLINE s_intervention,NEWLINE 'role')NEWLINE content = re.sub(r'\*{3,}', r'', content)NEWLINE new_p['content'] = contentNEWLINE new_paragraphs.append(new_p)NEWLINE s_intervention['contents'] = new_paragraphsNEWLINE return s_interventionNEWLINENEWLINE def add_root_attributes(self, root, tree, infile):NEWLINE root.attrib['id'] = os.path.splitext(os.path.basename(infile))[0]NEWLINE root.attrib['lang'] = self.language.lower()NEWLINE date_string = re.match(NEWLINE r'^(.+?,? \d.+?) - (.+)$',NEWLINE tree.xpath('//td[@class="doc_title" and @align="left" and @valign="top"]')[0].text)NEWLINE date = dateparser.parse(date_string.group(1)).date()NEWLINE place = date_string.group(2)NEWLINE root.attrib['date'] = str(date)NEWLINE root.attrib['place'] = placeNEWLINE root.attrib['edition'] = tree.xpath('//td[@class="doc_title" and @align="right" and @valign="top"]')[0].textNEWLINE passNEWLINENEWLINE def intervention_to_xml(self, x_section, s_intervention):NEWLINE x_intervention = etree.SubElement(x_section, 'intervention')NEWLINE if 'id' in s_intervention.keys():NEWLINE x_intervention.attrib['id'] = s_intervention['id']NEWLINE if 'speaker_id' in s_intervention.keys():NEWLINE x_intervention.attrib['speaker_id'] = s_intervention['speaker_id']NEWLINE if 'name' in s_intervention.keys():NEWLINE x_intervention.attrib['name'] = s_intervention['name']NEWLINE if 'is_mep' in s_intervention.keys():NEWLINE x_intervention.attrib['is_mep'] = str(s_intervention['is_mep'])NEWLINE if 'mode' in s_intervention.keys():NEWLINE x_intervention.attrib['mode'] = s_intervention['mode']NEWLINE if 'role' in s_intervention.keys():NEWLINE x_intervention.attrib['role'] = s_intervention['role']NEWLINE for paragraph in s_intervention['contents']:NEWLINE if len(paragraph['content']) > 0:NEWLINE if not re.match(r'^\(.+?\)$', paragraph['content']):NEWLINE x_p = etree.SubElement(NEWLINE x_intervention,NEWLINE 'p',NEWLINE sl=paragraph['language'].lower())NEWLINE x_p.text = paragraph['content']NEWLINE else:NEWLINE etree.SubElement(NEWLINE x_intervention,NEWLINE 'a',NEWLINE text=paragraph['content'])NEWLINE passNEWLINENEWLINE def serialize(self, infile, root):NEWLINE ofile_name = os.path.splitext(os.path.basename(infile))[0]NEWLINE ofile_path = os.path.join(self.outdir, ofile_name+'.xml')NEWLINE xml = etree.tostring(NEWLINE root,NEWLINE encoding='utf-8',NEWLINE xml_declaration=True,NEWLINE pretty_print=True).decode('utf-8')NEWLINE with open(ofile_path, mode='w', encoding='utf-8') as ofile:NEWLINE ofile.write(xml)NEWLINE passNEWLINENEWLINE def get_element_id(self, element):NEWLINE output = element.getprevious().attrib['name']NEWLINE return outputNEWLINENEWLINE def main(self):NEWLINE for infile in self.infiles:NEWLINE print(infile)NEWLINE tree = self.read_html(infile)NEWLINE root = etree.Element('text')NEWLINE self.add_root_attributes(root, tree, infile)NEWLINE sections = tree.xpath(NEWLINE '//table[@class="doc_box_header" and @cellpadding="0"]')NEWLINE for section in sections:NEWLINE heading = self.get_heading(section)NEWLINE section_id = self.get_element_id(section)NEWLINE x_section = etree.SubElement(root, 'section')NEWLINE x_section.attrib['id'] = section_idNEWLINE x_section.attrib['title'] = headingNEWLINE interventions = section.xpath(NEWLINE './/table[@cellpadding="5"][.//img[@alt="MPphoto"]]')NEWLINE for idx, intervention in enumerate(interventions):NEWLINE s_intervention = {}NEWLINE intervention_id = self.get_element_id(intervention)NEWLINE s_intervention['id'] = intervention_idNEWLINE i_lang = NoneNEWLINE s_intervention['speaker_id'] = self.get_speaker_id(intervention)NEWLINE s_intervention['is_mep'] = self.get_is_mep(NEWLINE s_intervention['speaker_id'])NEWLINE s_intervention['mode'] = self.get_mode(intervention)NEWLINE speaker_name = self.get_speaker_name(intervention)NEWLINE president_pattern = '|'.join(self.loc['president'])NEWLINE if re.match(r'{}\Z'.format(president_pattern), speaker_name):NEWLINE s_intervention['role'] = speaker_nameNEWLINE else:NEWLINE s_intervention['name'] = speaker_nameNEWLINE role, i_lang = self.get_role(intervention)NEWLINE if role is not None:NEWLINE s_intervention['role'] = roleNEWLINE s_intervention = self.get_paragraphs(NEWLINE intervention,NEWLINE s_intervention,NEWLINE i_lang)NEWLINE self.intervention_to_xml(x_section, s_intervention)NEWLINE self.serialize(infile, root)NEWLINE self.n_proceedings += 1NEWLINE passNEWLINENEWLINE def cli(self):NEWLINE """CLI parses command-line arguments"""NEWLINE parser = argparse.ArgumentParser()NEWLINE parser.add_argument(NEWLINE "-i", "--input",NEWLINE required=True,NEWLINE help="path to the input directory.")NEWLINE parser.add_argument(NEWLINE "-o", "--output",NEWLINE required=True,NEWLINE help="path to the output directory.")NEWLINE parser.add_argument(NEWLINE "-l", "--language",NEWLINE required=True,NEWLINE choices=['en', 'es', 'de'],NEWLINE help="language of the version to be processed.")NEWLINE parser.add_argument(NEWLINE '-p', "--pattern",NEWLINE required=False,NEWLINE default="*.html",NEWLINE help="glob pattern to filter files.")NEWLINE args = parser.parse_args()NEWLINE self.indir = args.inputNEWLINE self.outdir = args.outputNEWLINE if not os.path.exists(self.outdir):NEWLINE os.makedirs(self.outdir)NEWLINE self.language = args.languageNEWLINE self.pattern = args.patternNEWLINE passNEWLINENEWLINENEWLINEprint(TransformHtmlProceedingsToXml())NEWLINE
# --------------------------------------------------------NEWLINE# DenseCap-TensorflowNEWLINE# Written by InnerPeaceNEWLINE# This file is adapted from Ross Girshick's workNEWLINE# --------------------------------------------------------NEWLINE# Fast R-CNNNEWLINE# Copyright (c) 2015 MicrosoftNEWLINE# Licensed under The MIT License [see LICENSE for details]NEWLINE# Written by Ross GirshickNEWLINE# --------------------------------------------------------NEWLINEfrom __future__ import absolute_importNEWLINEfrom __future__ import divisionNEWLINEfrom __future__ import print_functionNEWLINENEWLINE""" config system for DensecapNEWLINENEWLINETHis file specifies default config for Densecap. One can change the value of the file byNEWLINEwriting a config file(in yaml) and use cfg_from_file(yaml_file) to load and override theNEWLINEdefault options.NEWLINE"""NEWLINENEWLINEimport osNEWLINEimport os.path as ospNEWLINEfrom os.path import join as pjoinNEWLINEimport numpy as npNEWLINE# from distutils import spawnNEWLINE# run: pip install easydictNEWLINEfrom easydict import EasyDict as edictNEWLINENEWLINE__C = edict()NEWLINE# get config by:NEWLINE# from lib.config import cfgNEWLINEcfg = __CNEWLINENEWLINE#NEWLINE# Training optionsNEWLINE#NEWLINENEWLINE__C.TRAIN = edict()NEWLINENEWLINE# learning rate manully decayNEWLINE__C.TRAIN.LR_DIY_DECAY = TrueNEWLINENEWLINE# training optimizer: either 'adam' 'sgd_m'NEWLINE__C.TRAIN.OPTIMIZER = 'sgd_m'NEWLINENEWLINE# Initial learning rateNEWLINE__C.TRAIN.LEARNING_RATE = 0.001NEWLINENEWLINE# Weight decay, for regularizationNEWLINE__C.TRAIN.WEIGHT_DECAY = 0.NEWLINENEWLINE# clip norm for gradient clipping(tf.clip_by_norm)NEWLINE__C.TRAIN.CLIP_NORM = 40.NEWLINE# Step size for reducing the learning rate, currently only support one stepNEWLINE__C.TRAIN.STEPSIZE = [100000]NEWLINENEWLINE# Factor for reducing the learning rateNEWLINE__C.TRAIN.GAMMA = 0.5NEWLINENEWLINE# MomentumNEWLINE__C.TRAIN.MOMENTUM = 0.98NEWLINENEWLINE# Iteration intervals for showing the loss during training, on command line interfaceNEWLINE__C.TRAIN.DISPLAY = 10NEWLINENEWLINE# The number of snapshots kept, older ones are deleted to save spaceNEWLINE__C.TRAIN.SNAPSHOT_KEPT = 3NEWLINENEWLINE# Iterations between snapshotsNEWLINE__C.TRAIN.SNAPSHOT_ITERS = 5000NEWLINENEWLINE# The time interval for saving tensorflow summariesNEWLINE__C.TRAIN.SUMMARY_INTERVAL = 180NEWLINENEWLINE# Whether to double the learning rate for biasNEWLINE__C.TRAIN.DOUBLE_BIAS = FalseNEWLINENEWLINE# Whether to have weight decay on bias as wellNEWLINE__C.TRAIN.BIAS_DECAY = FalseNEWLINENEWLINE# learning rate exponentially decay rateNEWLINE__C.TRAIN.EXP_DECAY_RATE = 0.9NEWLINENEWLINE# learning rate exponentially decay step sizeNEWLINE__C.TRAIN.EXP_DECAY_STEPS = 5000NEWLINENEWLINE# Training using proposalNEWLINE__C.TRAIN.PROPOSAL_METHOD = 'gt'NEWLINENEWLINE# Use horizontally-flipped images during training?NEWLINE__C.TRAIN.USE_FLIPPED = TrueNEWLINENEWLINE# Make minibatches from images that have similar aspect ratios (i.e. bothNEWLINE# tall and thin or both short and wide) in order to avoid wasting computationNEWLINE# on zero-padding.NEWLINE__C.TRAIN.ASPECT_GROUPING = TrueNEWLINENEWLINE# images to use per minibatch, we use 1 in defaultNEWLINE__C.TRAIN.IMS_PER_BATCH = 1NEWLINENEWLINE# Scales to use during training (can list multiple scales)NEWLINE# Each scale is the pixel size of an image's shortest sideNEWLINE__C.TRAIN.SCALES = (600,)NEWLINENEWLINE# Max pixel size of the longest side of a scaled input imageNEWLINE__C.TRAIN.MAX_SIZE = 720NEWLINENEWLINE# Minibatch size (number of regions of interest [ROIs])NEWLINE__C.TRAIN.BATCH_SIZE = 256NEWLINENEWLINE# Fraction of minibatch that is labeled foreground (i.e. class > 0)NEWLINE__C.TRAIN.FG_FRACTION = 0.25NEWLINENEWLINE# Overlap threshold for a ROI to be considered foreground (if >= FG_THRESH)NEWLINE__C.TRAIN.FG_THRESH = 0.5NEWLINENEWLINE# Overlap threshold for a ROI to be considered background (class = 0 ifNEWLINE# overlap in [LO, HI))NEWLINE__C.TRAIN.BG_THRESH_HI = 0.5NEWLINE__C.TRAIN.BG_THRESH_LO = 0.1NEWLINENEWLINE# Use RPN to detect objectsNEWLINE__C.TRAIN.HAS_RPN = TrueNEWLINENEWLINE# Train bounding-box regressorsNEWLINE__C.TRAIN.BBOX_REG = TrueNEWLINENEWLINE# Normalize the targets (subtract empirical mean, divide by empirical stddev)NEWLINE__C.TRAIN.BBOX_NORMALIZE_TARGETS = TrueNEWLINENEWLINE# Normalize the targets using "precomputed" (or made up) means and stdevsNEWLINE# (BBOX_NORMALIZE_TARGETS must also be True)NEWLINE__C.TRAIN.BBOX_NORMALIZE_TARGETS_PRECOMPUTED = FalseNEWLINE__C.TRAIN.BBOX_NORMALIZE_MEANS = (0.0, 0.0, 0.0, 0.0)NEWLINE__C.TRAIN.BBOX_NORMALIZE_STDS = (0.1, 0.1, 0.2, 0.2)NEWLINENEWLINE# solver.prototxt specifies the snapshot path prefix, this adds an optionalNEWLINE# infix to yield the path: <prefix>[_<infix>]_iters_XYZ.caffemodelNEWLINE__C.TRAIN.SNAPSHOT_PREFIX = 'res50_densecap'NEWLINENEWLINE# Weight decay, for regularizationNEWLINE__C.TRAIN.WEIGHT_DECAY = 0.0001NEWLINENEWLINE# Whether to have weight decay on bias as wellNEWLINE__C.TRAIN.BIAS_DECAY = FalseNEWLINENEWLINE# Weight initializer: 'xavier', 'truncated', 'normal'NEWLINE__C.TRAIN.WEIGHT_INITIALIZER = 'xavier'NEWLINENEWLINE# RPN OPTIONS FOR TRAININGNEWLINENEWLINE# IOU >= thresh: positive exampleNEWLINE__C.TRAIN.RPN_POSITIVE_OVERLAP = 0.7NEWLINENEWLINE# IOU < thresh: negative exampleNEWLINE__C.TRAIN.RPN_NEGATIVE_OVERLAP = 0.3NEWLINENEWLINE# If an anchor statisfied by positive and negative conditions set to negativeNEWLINE__C.TRAIN.RPN_CLOBBER_POSITIVES = FalseNEWLINENEWLINE# Max number of foreground examplesNEWLINE__C.TRAIN.RPN_FG_FRACTION = 0.5NEWLINENEWLINE# Total number of examplesNEWLINE__C.TRAIN.RPN_BATCHSIZE = 256NEWLINENEWLINE# NMS threshold used on RPN proposalsNEWLINE__C.TRAIN.RPN_NMS_THRESH = 0.7NEWLINENEWLINE# Number of top scoring boxes to keep before apply NMS to RPN proposalsNEWLINE__C.TRAIN.RPN_PRE_NMS_TOP_N = 12000NEWLINENEWLINE# Number of top scoring boxes to keep after applying NMS to RPN proposalsNEWLINE__C.TRAIN.RPN_POST_NMS_TOP_N = 2000NEWLINENEWLINE# Proposal height and width both need to be greater than RPN_MIN_SIZE (at orig image scale)NEWLINE# Follow tf_faster_rcnn we do not use itNEWLINE__C.TRAIN.RPN_MIN_SIZE = 16NEWLINENEWLINE# Deprecated (outside weights)NEWLINE__C.TRAIN.RPN_BBOX_INSIDE_WEIGHTS = (1.0, 1.0, 1.0, 1.0)NEWLINENEWLINE# Give the positive RPN examples weight of p * 1 / {num positives}NEWLINE# and give negatives a weight of (1 - p)NEWLINE# Set to -1.0 to use uniform example weightingNEWLINE__C.TRAIN.RPN_POSITIVE_WEIGHT = -1.0NEWLINENEWLINE# Whether to add ground truth boxes to the pool when sampling regionsNEWLINE__C.TRAIN.USE_GT = FalseNEWLINENEWLINE# Deprecated (inside weights)NEWLINE__C.TRAIN.BBOX_INSIDE_WEIGHTS = (1.0, 1.0, 1.0, 1.0)NEWLINENEWLINE# Overlap required between a ROI and ground-truth box in order for that ROI toNEWLINE# be used as a bounding-box regression training exampleNEWLINE__C.TRAIN.BBOX_THRESH = 0.5NEWLINENEWLINENEWLINE#NEWLINE# ResNet optionsNEWLINE#NEWLINENEWLINE__C.RESNET = edict()NEWLINENEWLINE# Option to set if max-pooling is appended after crop_and_resize.NEWLINE# if true, the region will be resized to a square of 2xPOOLING_SIZE,NEWLINE# then 2x2 max-pooling is applied; otherwise the region will be directlyNEWLINE# resized to a square of POOLING_SIZENEWLINE__C.RESNET.MAX_POOL = FalseNEWLINENEWLINE# Number of fixed blocks during training, by default the first of all 4 blocks is fixedNEWLINE# Range: 0 (none) to 3 (all)NEWLINE__C.RESNET.FIXED_BLOCKS = 1NEWLINENEWLINENEWLINE#NEWLINE# Testing optionsNEWLINE#NEWLINE__C.TEST = edict()NEWLINENEWLINE# Scale to use during testing (can NOT list multiple scales)NEWLINE# The scale is the pixel size of an image's shortest sideNEWLINE__C.TEST.SCALES = (600,)NEWLINENEWLINE# Max pixel size of the longest side of a scaled input imageNEWLINE__C.TEST.MAX_SIZE = 1000NEWLINENEWLINE# Overlap threshold used for non-maximum suppression (suppress boxes withNEWLINE# IoU >= this threshold)NEWLINE__C.TEST.NMS = 0.3NEWLINENEWLINE# Experimental: treat the (K+1) units in the cls_score layer as linearNEWLINE# predictors (trained, eg, with one-vs-rest SVMs).NEWLINE__C.TEST.SVM = FalseNEWLINENEWLINE# Test using bounding-box regressorsNEWLINE__C.TEST.BBOX_REG = TrueNEWLINENEWLINE# Propose boxesNEWLINE__C.TEST.HAS_RPN = FalseNEWLINENEWLINE# Test using these proposalsNEWLINE__C.TEST.PROPOSAL_METHOD = 'gt'NEWLINENEWLINE# NMS threshold used on RPN proposalsNEWLINE__C.TEST.RPN_NMS_THRESH = 0.7NEWLINENEWLINE# Number of top scoring boxes to keep before apply NMS to RPN proposalsNEWLINE__C.TEST.RPN_PRE_NMS_TOP_N = 6000NEWLINENEWLINE# Number of top scoring boxes to keep after applying NMS to RPN proposalsNEWLINE__C.TEST.RPN_POST_NMS_TOP_N = 300NEWLINENEWLINE# Proposal height and width both need to be greater than RPN_MIN_SIZE (at orig image scale)NEWLINE__C.TEST.RPN_MIN_SIZE = 16NEWLINENEWLINE# Testing mode, default to be 'nms', 'top' is slower but betterNEWLINE# See report for detailsNEWLINE__C.TEST.MODE = 'nms'NEWLINENEWLINE# Only useful when TEST.MODE is 'top', specifies the number of top proposals to selectNEWLINE__C.TEST.RPN_TOP_N = 5000NEWLINENEWLINE# Use beam search to generate captionsNEWLINE__C.TEST.USE_BEAM_SEARCH = FalseNEWLINENEWLINE# Beam size for beam searchNEWLINE__C.TEST.BEAM_SIZE = 3NEWLINENEWLINE"""NEWLINElength_normalization_factor: If != 0, a number x such that captions areNEWLINE scored by logprob/length^x, rather than logprob. This changes theNEWLINE relative scores of captions depending on their lengths. For example, ifNEWLINE x > 0 then longer captions will be favored.NEWLINE"""NEWLINE__C.TEST.LN_FACTOR = 0.NEWLINENEWLINE#NEWLINE# MISCNEWLINE#NEWLINENEWLINE# Root directory of projectNEWLINE__C.ROOT_DIR = osp.abspath(pjoin(osp.dirname(__file__), '..'))NEWLINENEWLINE# Data directoryNEWLINE# __C.DATA_DIR = osp.abspath(pjoin(__C.ROOT_DIR, 'data'))NEWLINE# TODO: delete testing optionsNEWLINE__C.DATA_DIR = '/home/joe/git/visual_genome'NEWLINENEWLINE# Log directoryNEWLINE__C.LOG_DIR = osp.abspath(pjoin(__C.ROOT_DIR, 'logs'))NEWLINENEWLINE# Cache directoryNEWLINE__C.CACHE_DIR = __C.DATA_DIR + '/1.2'NEWLINENEWLINE# Dataset splits directoryNEWLINE__C.SPLIT_DIR = osp.abspath(pjoin(__C.ROOT_DIR, 'info'))NEWLINENEWLINE# Place outputs under an experiment directoryNEWLINE__C.EXP_DIR = 'default'NEWLINENEWLINE# Limited memory which is less than 16G and unable to read the wholeNEWLINE# region description JSON fileNEWLINE__C.LIMIT_RAM = TrueNEWLINENEWLINE# For reproducibilityNEWLINE__C.RNG_SEED = 3NEWLINENEWLINE# Pixel mean values (BGR order) as a (1, 1, 3) arrayNEWLINE# We use the same pixel mean for all networks even though it's not exactly whatNEWLINE# they were trained withNEWLINE__C.PIXEL_MEANS = np.array([[[102.9801, 115.9465, 122.7717]]])NEWLINENEWLINE# Store the meta information for continuing training.NEWLINE# __C.STORE_META_INFO = TrueNEWLINENEWLINE# Use GPU implementation of non-maximum suppressionNEWLINE__C.USE_GPU_NMS = TrueNEWLINENEWLINE# Default pooling mode, only 'crop' is availableNEWLINE__C.POOLING_MODE = 'crop'NEWLINENEWLINE# Size of the pooled region after RoI poolingNEWLINE__C.POOLING_SIZE = 7NEWLINENEWLINE# Anchor scales for RPNNEWLINE__C.ANCHOR_SCALES = [4, 8, 16, 32]NEWLINENEWLINE# Anchor ratios for RPNNEWLINE__C.ANCHOR_RATIOS = [0.5, 1, 2]NEWLINENEWLINE# Number of filters for the RPN layerNEWLINE__C.RPN_CHANNELS = 512NEWLINENEWLINE# Filter out small boxesNEWLINE__C.FILTER_SMALL_BOX = FalseNEWLINENEWLINE# Time steps for recurrent netsNEWLINE# It's related to the max_length of the sentenceNEWLINE__C.TIME_STEPS = 12NEWLINENEWLINE# For overall debugNEWLINE__C.DEBUG_ALL = TrueNEWLINENEWLINE# maximum words for training and testingNEWLINE__C.MAX_WORDS = 10NEWLINENEWLINE# index of word "<EOS>" in vocabluryNEWLINE__C.END_INDEX = 2NEWLINENEWLINE# Default GPU device idNEWLINE__C.GPU_ID = 0NEWLINENEWLINE# dimension of embeddingNEWLINE__C.EMBED_DIM = 512NEWLINENEWLINE# Size of vacabularyNEWLINE__C.VOCAB_SIZE = 10000NEWLINENEWLINE# image context mode, 'concat' or 'repeat'NEWLINE# 'concat': concat context feature at the first time step during rnn.NEWLINE# 'repeat': repeat context feature at the every time step during rnn.NEWLINE__C.CONTEXT_MODE = 'concat'NEWLINENEWLINE# follow tf_faster_rcnn, sample a fixed number of regionsNEWLINE__C.SAMPLE_NUM_FIXED_REGIONS = FalseNEWLINENEWLINE# overall test, i.e. overfit minibatchNEWLINE__C.ALL_TEST = FalseNEWLINENEWLINE# number of training examples for overall testNEWLINE__C.ALL_TEST_NUM_TRAIN = 100NEWLINENEWLINE# number of validation examles for overall testNEWLINE__C.ALL_TEST_NUM_VAL = 100NEWLINENEWLINE# number of test examples for overall testNEWLINE__C.ALL_TEST_NUM_TEST = 10NEWLINENEWLINE#NEWLINE# LOSS optionsNEWLINE#NEWLINENEWLINE__C.LOSS = edict()NEWLINENEWLINE# weight of caption lossNEWLINE__C.LOSS.CAP_W = 1.NEWLINENEWLINE# weight of final class lossNEWLINE__C.LOSS.CLS_W = 0.1NEWLINENEWLINE# weight of bbox lossNEWLINE__C.LOSS.BBOX_W = 0.01NEWLINENEWLINE# weight of rpn bbox lossNEWLINE__C.LOSS.RPN_BBOX_W = 0.05NEWLINENEWLINE# weight of rpn class lossNEWLINE__C.LOSS.RPN_CLS_W = 0.1NEWLINENEWLINE# train with context fusionNEWLINE__C.CONTEXT_FUSION = FalseNEWLINENEWLINE# mode of context fusion e.g. "sum" "concat"NEWLINE__C.CONTEXT_FUSION_MODE = "sum"NEWLINENEWLINE# Dimension of glove word vectorsNEWLINE__C.GLOVE_DIM = 300NEWLINENEWLINE# Initialize word vectors and classifier with gloveNEWLINE__C.INIT_BY_GLOVE = FalseNEWLINENEWLINE# Train the glove word vectorsNEWLINE__C.TRAIN_GLOVE = FalseNEWLINENEWLINE# Keep Glove word vectors dimensionNEWLINE__C.KEEP_AS_GLOVE_DIM = TrueNEWLINENEWLINE# Start id of vocabularyNEWLINE__C.VOCAB_START_ID = 1NEWLINENEWLINE# End id of vocabularyNEWLINE__C.VOCAB_END_ID = 2NEWLINENEWLINENEWLINE#NEWLINE# FunctionsNEWLINE#NEWLINENEWLINENEWLINEdef get_output_dir(imdb, weights_filename):NEWLINE """Return the directory where experimental artifacts are placed.NEWLINE If the directory does not exist, it is created.NEWLINENEWLINE A canonical path is built using the name from an imdb and a networkNEWLINE (if not None).NEWLINE """NEWLINE outdir = osp.abspath(osp.join(__C.ROOT_DIR, 'output', __C.EXP_DIR, imdb.name))NEWLINE if weights_filename is not None:NEWLINE outdir = osp.join(outdir, weights_filename)NEWLINE if not os.path.exists(outdir):NEWLINE os.makedirs(outdir)NEWLINE return outdirNEWLINENEWLINENEWLINEdef get_output_tb_dir(imdb, weights_filename):NEWLINE """Return the directory where tensorflow summaries are placed.NEWLINE If the directory does not exist, it is created.NEWLINENEWLINE A canonical path is built using the name from an imdb and a networkNEWLINE (if not None).NEWLINE """NEWLINE outdir = osp.abspath(osp.join(__C.ROOT_DIR, 'output', __C.EXP_DIR, 'tb', imdb.name))NEWLINE if weights_filename is None:NEWLINE weights_filename = 'default'NEWLINE outdir = osp.join(outdir, weights_filename)NEWLINE if not os.path.exists(outdir):NEWLINE os.makedirs(outdir)NEWLINE return outdirNEWLINENEWLINENEWLINEdef _merge_a_into_b(a, b):NEWLINE """Merge config dictionary a into config dictionary b, clobbering theNEWLINE options in b whenever they are also specified in a.NEWLINE """NEWLINE if type(a) is not edict:NEWLINE returnNEWLINENEWLINE for k, v in a.iteritems():NEWLINE # a must specify keys that are in bNEWLINE if not b.has_key(k):NEWLINE raise KeyError('{} is not a valid config key'.format(k))NEWLINENEWLINE # the types must match, tooNEWLINE old_type = type(b[k])NEWLINE if old_type is not type(v):NEWLINE if isinstance(b[k], np.ndarray):NEWLINE v = np.array(v, dtype=b[k].dtype)NEWLINE else:NEWLINE raise ValueError(('Type mismatch ({} vs. {}) 'NEWLINE 'for config key: {}').format(type(b[k]),NEWLINE type(v), k))NEWLINENEWLINE # recursively merge dictsNEWLINE if type(v) is edict:NEWLINE try:NEWLINE _merge_a_into_b(a[k], b[k])NEWLINE except:NEWLINE print('Error under config key: {}'.format(k))NEWLINE raiseNEWLINE else:NEWLINE b[k] = vNEWLINENEWLINENEWLINEdef cfg_from_file(filename):NEWLINE """Load a config file and merge it into the default options."""NEWLINE import yamlNEWLINE with open(filename, 'r') as f:NEWLINE yaml_cfg = edict(yaml.load(f))NEWLINENEWLINE _merge_a_into_b(yaml_cfg, __C)NEWLINENEWLINENEWLINEdef cfg_from_list(cfg_list):NEWLINE """Set config keys via list (e.g., from command line)."""NEWLINE from ast import literal_evalNEWLINE assert len(cfg_list) % 2 == 0NEWLINE for k, v in zip(cfg_list[0::2], cfg_list[1::2]):NEWLINE key_list = k.split('.')NEWLINE d = __CNEWLINE for subkey in key_list[:-1]:NEWLINE assert d.has_key(subkey)NEWLINE d = d[subkey]NEWLINE subkey = key_list[-1]NEWLINE assert d.has_key(subkey)NEWLINE try:NEWLINE value = literal_eval(v)NEWLINE except:NEWLINE # handle the case when v is a string literalNEWLINE value = vNEWLINE assert type(value) == type(d[subkey]), \NEWLINE 'type {} does not match original type {}'.format(NEWLINE type(value), type(d[subkey]))NEWLINE d[subkey] = valueNEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE print(cfg.ROOT_DIR)NEWLINE
# Generated by Django 2.2.8 on 2019-12-23 10:46NEWLINENEWLINEimport datetimeNEWLINEfrom django.db import migrations, modelsNEWLINEfrom django.utils.timezone import utcNEWLINENEWLINENEWLINEclass Migration(migrations.Migration):NEWLINENEWLINE initial = TrueNEWLINENEWLINE dependencies = [NEWLINE ]NEWLINENEWLINE operations = [NEWLINE migrations.CreateModel(NEWLINE name='BulletinUpdate',NEWLINE fields=[NEWLINE ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),NEWLINE ('time_of_quake', models.DateTimeField(default=datetime.datetime(1900, 1, 1, 0, 0, tzinfo=utc))),NEWLINE ('url', models.URLField(unique=True)),NEWLINE ('latitude', models.DecimalField(decimal_places=2, max_digits=5)),NEWLINE ('longitude', models.DecimalField(decimal_places=2, max_digits=5)),NEWLINE ('depth', models.DecimalField(decimal_places=1, max_digits=4)),NEWLINE ('magnitude', models.DecimalField(decimal_places=1, max_digits=3)),NEWLINE ('location', models.CharField(default='', max_length=2048)),NEWLINE ],NEWLINE options={NEWLINE 'ordering': ['-time_of_quake'],NEWLINE },NEWLINE ),NEWLINE migrations.AddIndex(NEWLINE model_name='bulletinupdate',NEWLINE index=models.Index(fields=['time_of_quake'], name='bulletin_bu_time_of_9e0643_idx'),NEWLINE ),NEWLINE migrations.AddIndex(NEWLINE model_name='bulletinupdate',NEWLINE index=models.Index(fields=['url'], name='bulletin_bu_url_4b9def_idx'),NEWLINE ),NEWLINE ]NEWLINE
# coding=utf-8NEWLINE# *** WARNING: this file was generated by the Pulumi SDK Generator. ***NEWLINE# *** Do not edit by hand unless you're certain you know what you are doing! ***NEWLINENEWLINEimport warningsNEWLINEimport pulumiNEWLINEimport pulumi.runtimeNEWLINEfrom typing import Any, Mapping, Optional, Sequence, Union, overloadNEWLINEfrom ... import _utilitiesNEWLINENEWLINE__all__ = ['InstanceArgs', 'Instance']NEWLINENEWLINE@pulumi.input_typeNEWLINEclass InstanceArgs:NEWLINE def __init__(__self__, *,NEWLINE config: pulumi.Input[str],NEWLINE display_name: pulumi.Input[str],NEWLINE instance_id: pulumi.Input[str],NEWLINE labels: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,NEWLINE name: Optional[pulumi.Input[str]] = None,NEWLINE node_count: Optional[pulumi.Input[int]] = None,NEWLINE processing_units: Optional[pulumi.Input[int]] = None,NEWLINE project: Optional[pulumi.Input[str]] = None):NEWLINE """NEWLINE The set of arguments for constructing a Instance resource.NEWLINE :param pulumi.Input[str] config: The name of the instance's configuration. Values are of the form `projects//instanceConfigs/`. See also InstanceConfig and ListInstanceConfigs.NEWLINE :param pulumi.Input[str] display_name: The descriptive name for this instance as it appears in UIs. Must be unique per project and between 4 and 30 characters in length.NEWLINE :param pulumi.Input[str] instance_id: The ID of the instance to create. Valid identifiers are of the form `a-z*[a-z0-9]` and must be between 2 and 64 characters in length.NEWLINE :param pulumi.Input[Mapping[str, pulumi.Input[str]]] labels: Cloud Labels are a flexible and lightweight mechanism for organizing cloud resources into groups that reflect a customer's organizational needs and deployment strategies. Cloud Labels can be used to filter collections of resources. They can be used to control how resource metrics are aggregated. And they can be used as arguments to policy management rules (e.g. route, firewall, load balancing, etc.). * Label keys must be between 1 and 63 characters long and must conform to the following regular expression: `a-z{0,62}`. * Label values must be between 0 and 63 characters long and must conform to the regular expression `[a-z0-9_-]{0,63}`. * No more than 64 labels can be associated with a given resource. See https://goo.gl/xmQnxf for more information on and examples of labels. If you plan to use labels in your own code, please note that additional characters may be allowed in the future. And so you are advised to use an internal label representation, such as JSON, which doesn't rely upon specific characters being disallowed. For example, representing labels as the string: name + "_" + value would prove problematic if we were to allow "_" in a future release.NEWLINE :param pulumi.Input[str] name: A unique identifier for the instance, which cannot be changed after the instance is created. Values are of the form `projects//instances/a-z*[a-z0-9]`. The final segment of the name must be between 2 and 64 characters in length.NEWLINE :param pulumi.Input[int] node_count: The number of nodes allocated to this instance. At most one of either node_count or processing_units should be present in the message. This may be zero in API responses for instances that are not yet in state `READY`. See [the documentation](https://cloud.google.com/spanner/docs/compute-capacity) for more information about nodes and processing units.NEWLINE :param pulumi.Input[int] processing_units: The number of processing units allocated to this instance. At most one of processing_units or node_count should be present in the message. This may be zero in API responses for instances that are not yet in state `READY`. See [the documentation](https://cloud.google.com/spanner/docs/compute-capacity) for more information about nodes and processing units.NEWLINE """NEWLINE pulumi.set(__self__, "config", config)NEWLINE pulumi.set(__self__, "display_name", display_name)NEWLINE pulumi.set(__self__, "instance_id", instance_id)NEWLINE if labels is not None:NEWLINE pulumi.set(__self__, "labels", labels)NEWLINE if name is not None:NEWLINE pulumi.set(__self__, "name", name)NEWLINE if node_count is not None:NEWLINE pulumi.set(__self__, "node_count", node_count)NEWLINE if processing_units is not None:NEWLINE pulumi.set(__self__, "processing_units", processing_units)NEWLINE if project is not None:NEWLINE pulumi.set(__self__, "project", project)NEWLINENEWLINE @propertyNEWLINE @pulumi.getterNEWLINE def config(self) -> pulumi.Input[str]:NEWLINE """NEWLINE The name of the instance's configuration. Values are of the form `projects//instanceConfigs/`. See also InstanceConfig and ListInstanceConfigs.NEWLINE """NEWLINE return pulumi.get(self, "config")NEWLINENEWLINE @config.setterNEWLINE def config(self, value: pulumi.Input[str]):NEWLINE pulumi.set(self, "config", value)NEWLINENEWLINE @propertyNEWLINE @pulumi.getter(name="displayName")NEWLINE def display_name(self) -> pulumi.Input[str]:NEWLINE """NEWLINE The descriptive name for this instance as it appears in UIs. Must be unique per project and between 4 and 30 characters in length.NEWLINE """NEWLINE return pulumi.get(self, "display_name")NEWLINENEWLINE @display_name.setterNEWLINE def display_name(self, value: pulumi.Input[str]):NEWLINE pulumi.set(self, "display_name", value)NEWLINENEWLINE @propertyNEWLINE @pulumi.getter(name="instanceId")NEWLINE def instance_id(self) -> pulumi.Input[str]:NEWLINE """NEWLINE The ID of the instance to create. Valid identifiers are of the form `a-z*[a-z0-9]` and must be between 2 and 64 characters in length.NEWLINE """NEWLINE return pulumi.get(self, "instance_id")NEWLINENEWLINE @instance_id.setterNEWLINE def instance_id(self, value: pulumi.Input[str]):NEWLINE pulumi.set(self, "instance_id", value)NEWLINENEWLINE @propertyNEWLINE @pulumi.getterNEWLINE def labels(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]:NEWLINE """NEWLINE Cloud Labels are a flexible and lightweight mechanism for organizing cloud resources into groups that reflect a customer's organizational needs and deployment strategies. Cloud Labels can be used to filter collections of resources. They can be used to control how resource metrics are aggregated. And they can be used as arguments to policy management rules (e.g. route, firewall, load balancing, etc.). * Label keys must be between 1 and 63 characters long and must conform to the following regular expression: `a-z{0,62}`. * Label values must be between 0 and 63 characters long and must conform to the regular expression `[a-z0-9_-]{0,63}`. * No more than 64 labels can be associated with a given resource. See https://goo.gl/xmQnxf for more information on and examples of labels. If you plan to use labels in your own code, please note that additional characters may be allowed in the future. And so you are advised to use an internal label representation, such as JSON, which doesn't rely upon specific characters being disallowed. For example, representing labels as the string: name + "_" + value would prove problematic if we were to allow "_" in a future release.NEWLINE """NEWLINE return pulumi.get(self, "labels")NEWLINENEWLINE @labels.setterNEWLINE def labels(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]):NEWLINE pulumi.set(self, "labels", value)NEWLINENEWLINE @propertyNEWLINE @pulumi.getterNEWLINE def name(self) -> Optional[pulumi.Input[str]]:NEWLINE """NEWLINE A unique identifier for the instance, which cannot be changed after the instance is created. Values are of the form `projects//instances/a-z*[a-z0-9]`. The final segment of the name must be between 2 and 64 characters in length.NEWLINE """NEWLINE return pulumi.get(self, "name")NEWLINENEWLINE @name.setterNEWLINE def name(self, value: Optional[pulumi.Input[str]]):NEWLINE pulumi.set(self, "name", value)NEWLINENEWLINE @propertyNEWLINE @pulumi.getter(name="nodeCount")NEWLINE def node_count(self) -> Optional[pulumi.Input[int]]:NEWLINE """NEWLINE The number of nodes allocated to this instance. At most one of either node_count or processing_units should be present in the message. This may be zero in API responses for instances that are not yet in state `READY`. See [the documentation](https://cloud.google.com/spanner/docs/compute-capacity) for more information about nodes and processing units.NEWLINE """NEWLINE return pulumi.get(self, "node_count")NEWLINENEWLINE @node_count.setterNEWLINE def node_count(self, value: Optional[pulumi.Input[int]]):NEWLINE pulumi.set(self, "node_count", value)NEWLINENEWLINE @propertyNEWLINE @pulumi.getter(name="processingUnits")NEWLINE def processing_units(self) -> Optional[pulumi.Input[int]]:NEWLINE """NEWLINE The number of processing units allocated to this instance. At most one of processing_units or node_count should be present in the message. This may be zero in API responses for instances that are not yet in state `READY`. See [the documentation](https://cloud.google.com/spanner/docs/compute-capacity) for more information about nodes and processing units.NEWLINE """NEWLINE return pulumi.get(self, "processing_units")NEWLINENEWLINE @processing_units.setterNEWLINE def processing_units(self, value: Optional[pulumi.Input[int]]):NEWLINE pulumi.set(self, "processing_units", value)NEWLINENEWLINE @propertyNEWLINE @pulumi.getterNEWLINE def project(self) -> Optional[pulumi.Input[str]]:NEWLINE return pulumi.get(self, "project")NEWLINENEWLINE @project.setterNEWLINE def project(self, value: Optional[pulumi.Input[str]]):NEWLINE pulumi.set(self, "project", value)NEWLINENEWLINENEWLINEclass Instance(pulumi.CustomResource):NEWLINE @overloadNEWLINE def __init__(__self__,NEWLINE resource_name: str,NEWLINE opts: Optional[pulumi.ResourceOptions] = None,NEWLINE config: Optional[pulumi.Input[str]] = None,NEWLINE display_name: Optional[pulumi.Input[str]] = None,NEWLINE instance_id: Optional[pulumi.Input[str]] = None,NEWLINE labels: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,NEWLINE name: Optional[pulumi.Input[str]] = None,NEWLINE node_count: Optional[pulumi.Input[int]] = None,NEWLINE processing_units: Optional[pulumi.Input[int]] = None,NEWLINE project: Optional[pulumi.Input[str]] = None,NEWLINE __props__=None):NEWLINE """NEWLINE Creates an instance and begins preparing it to begin serving. The returned long-running operation can be used to track the progress of preparing the new instance. The instance name is assigned by the caller. If the named instance already exists, `CreateInstance` returns `ALREADY_EXISTS`. Immediately upon completion of this request: * The instance is readable via the API, with all requested attributes but no allocated resources. Its state is `CREATING`. Until completion of the returned operation: * Cancelling the operation renders the instance immediately unreadable via the API. * The instance can be deleted. * All other attempts to modify the instance are rejected. Upon completion of the returned operation: * Billing for all successfully-allocated resources begins (some types may have lower than the requested levels). * Databases can be created in the instance. * The instance's allocated resource levels are readable via the API. * The instance's state becomes `READY`. The returned long-running operation will have a name of the format `/operations/` and can be used to track creation of the instance. The metadata field type is CreateInstanceMetadata. The response field type is Instance, if successful.NEWLINENEWLINE :param str resource_name: The name of the resource.NEWLINE :param pulumi.ResourceOptions opts: Options for the resource.NEWLINE :param pulumi.Input[str] config: The name of the instance's configuration. Values are of the form `projects//instanceConfigs/`. See also InstanceConfig and ListInstanceConfigs.NEWLINE :param pulumi.Input[str] display_name: The descriptive name for this instance as it appears in UIs. Must be unique per project and between 4 and 30 characters in length.NEWLINE :param pulumi.Input[str] instance_id: The ID of the instance to create. Valid identifiers are of the form `a-z*[a-z0-9]` and must be between 2 and 64 characters in length.NEWLINE :param pulumi.Input[Mapping[str, pulumi.Input[str]]] labels: Cloud Labels are a flexible and lightweight mechanism for organizing cloud resources into groups that reflect a customer's organizational needs and deployment strategies. Cloud Labels can be used to filter collections of resources. They can be used to control how resource metrics are aggregated. And they can be used as arguments to policy management rules (e.g. route, firewall, load balancing, etc.). * Label keys must be between 1 and 63 characters long and must conform to the following regular expression: `a-z{0,62}`. * Label values must be between 0 and 63 characters long and must conform to the regular expression `[a-z0-9_-]{0,63}`. * No more than 64 labels can be associated with a given resource. See https://goo.gl/xmQnxf for more information on and examples of labels. If you plan to use labels in your own code, please note that additional characters may be allowed in the future. And so you are advised to use an internal label representation, such as JSON, which doesn't rely upon specific characters being disallowed. For example, representing labels as the string: name + "_" + value would prove problematic if we were to allow "_" in a future release.NEWLINE :param pulumi.Input[str] name: A unique identifier for the instance, which cannot be changed after the instance is created. Values are of the form `projects//instances/a-z*[a-z0-9]`. The final segment of the name must be between 2 and 64 characters in length.NEWLINE :param pulumi.Input[int] node_count: The number of nodes allocated to this instance. At most one of either node_count or processing_units should be present in the message. This may be zero in API responses for instances that are not yet in state `READY`. See [the documentation](https://cloud.google.com/spanner/docs/compute-capacity) for more information about nodes and processing units.NEWLINE :param pulumi.Input[int] processing_units: The number of processing units allocated to this instance. At most one of processing_units or node_count should be present in the message. This may be zero in API responses for instances that are not yet in state `READY`. See [the documentation](https://cloud.google.com/spanner/docs/compute-capacity) for more information about nodes and processing units.NEWLINE """NEWLINE ...NEWLINE @overloadNEWLINE def __init__(__self__,NEWLINE resource_name: str,NEWLINE args: InstanceArgs,NEWLINE opts: Optional[pulumi.ResourceOptions] = None):NEWLINE """NEWLINE Creates an instance and begins preparing it to begin serving. The returned long-running operation can be used to track the progress of preparing the new instance. The instance name is assigned by the caller. If the named instance already exists, `CreateInstance` returns `ALREADY_EXISTS`. Immediately upon completion of this request: * The instance is readable via the API, with all requested attributes but no allocated resources. Its state is `CREATING`. Until completion of the returned operation: * Cancelling the operation renders the instance immediately unreadable via the API. * The instance can be deleted. * All other attempts to modify the instance are rejected. Upon completion of the returned operation: * Billing for all successfully-allocated resources begins (some types may have lower than the requested levels). * Databases can be created in the instance. * The instance's allocated resource levels are readable via the API. * The instance's state becomes `READY`. The returned long-running operation will have a name of the format `/operations/` and can be used to track creation of the instance. The metadata field type is CreateInstanceMetadata. The response field type is Instance, if successful.NEWLINENEWLINE :param str resource_name: The name of the resource.NEWLINE :param InstanceArgs args: The arguments to use to populate this resource's properties.NEWLINE :param pulumi.ResourceOptions opts: Options for the resource.NEWLINE """NEWLINE ...NEWLINE def __init__(__self__, resource_name: str, *args, **kwargs):NEWLINE resource_args, opts = _utilities.get_resource_args_opts(InstanceArgs, pulumi.ResourceOptions, *args, **kwargs)NEWLINE if resource_args is not None:NEWLINE __self__._internal_init(resource_name, opts, **resource_args.__dict__)NEWLINE else:NEWLINE __self__._internal_init(resource_name, *args, **kwargs)NEWLINENEWLINE def _internal_init(__self__,NEWLINE resource_name: str,NEWLINE opts: Optional[pulumi.ResourceOptions] = None,NEWLINE config: Optional[pulumi.Input[str]] = None,NEWLINE display_name: Optional[pulumi.Input[str]] = None,NEWLINE instance_id: Optional[pulumi.Input[str]] = None,NEWLINE labels: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,NEWLINE name: Optional[pulumi.Input[str]] = None,NEWLINE node_count: Optional[pulumi.Input[int]] = None,NEWLINE processing_units: Optional[pulumi.Input[int]] = None,NEWLINE project: Optional[pulumi.Input[str]] = None,NEWLINE __props__=None):NEWLINE if opts is None:NEWLINE opts = pulumi.ResourceOptions()NEWLINE if not isinstance(opts, pulumi.ResourceOptions):NEWLINE raise TypeError('Expected resource options to be a ResourceOptions instance')NEWLINE if opts.version is None:NEWLINE opts.version = _utilities.get_version()NEWLINE if opts.id is None:NEWLINE if __props__ is not None:NEWLINE raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')NEWLINE __props__ = InstanceArgs.__new__(InstanceArgs)NEWLINENEWLINE if config is None and not opts.urn:NEWLINE raise TypeError("Missing required property 'config'")NEWLINE __props__.__dict__["config"] = configNEWLINE if display_name is None and not opts.urn:NEWLINE raise TypeError("Missing required property 'display_name'")NEWLINE __props__.__dict__["display_name"] = display_nameNEWLINE if instance_id is None and not opts.urn:NEWLINE raise TypeError("Missing required property 'instance_id'")NEWLINE __props__.__dict__["instance_id"] = instance_idNEWLINE __props__.__dict__["labels"] = labelsNEWLINE __props__.__dict__["name"] = nameNEWLINE __props__.__dict__["node_count"] = node_countNEWLINE __props__.__dict__["processing_units"] = processing_unitsNEWLINE __props__.__dict__["project"] = projectNEWLINE __props__.__dict__["state"] = NoneNEWLINE super(Instance, __self__).__init__(NEWLINE 'google-native:spanner/v1:Instance',NEWLINE resource_name,NEWLINE __props__,NEWLINE opts)NEWLINENEWLINE @staticmethodNEWLINE def get(resource_name: str,NEWLINE id: pulumi.Input[str],NEWLINE opts: Optional[pulumi.ResourceOptions] = None) -> 'Instance':NEWLINE """NEWLINE Get an existing Instance resource's state with the given name, id, and optional extraNEWLINE properties used to qualify the lookup.NEWLINENEWLINE :param str resource_name: The unique name of the resulting resource.NEWLINE :param pulumi.Input[str] id: The unique provider ID of the resource to lookup.NEWLINE :param pulumi.ResourceOptions opts: Options for the resource.NEWLINE """NEWLINE opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))NEWLINENEWLINE __props__ = InstanceArgs.__new__(InstanceArgs)NEWLINENEWLINE __props__.__dict__["config"] = NoneNEWLINE __props__.__dict__["display_name"] = NoneNEWLINE __props__.__dict__["labels"] = NoneNEWLINE __props__.__dict__["name"] = NoneNEWLINE __props__.__dict__["node_count"] = NoneNEWLINE __props__.__dict__["processing_units"] = NoneNEWLINE __props__.__dict__["state"] = NoneNEWLINE return Instance(resource_name, opts=opts, __props__=__props__)NEWLINENEWLINE @propertyNEWLINE @pulumi.getterNEWLINE def config(self) -> pulumi.Output[str]:NEWLINE """NEWLINE The name of the instance's configuration. Values are of the form `projects//instanceConfigs/`. See also InstanceConfig and ListInstanceConfigs.NEWLINE """NEWLINE return pulumi.get(self, "config")NEWLINENEWLINE @propertyNEWLINE @pulumi.getter(name="displayName")NEWLINE def display_name(self) -> pulumi.Output[str]:NEWLINE """NEWLINE The descriptive name for this instance as it appears in UIs. Must be unique per project and between 4 and 30 characters in length.NEWLINE """NEWLINE return pulumi.get(self, "display_name")NEWLINENEWLINE @propertyNEWLINE @pulumi.getterNEWLINE def labels(self) -> pulumi.Output[Mapping[str, str]]:NEWLINE """NEWLINE Cloud Labels are a flexible and lightweight mechanism for organizing cloud resources into groups that reflect a customer's organizational needs and deployment strategies. Cloud Labels can be used to filter collections of resources. They can be used to control how resource metrics are aggregated. And they can be used as arguments to policy management rules (e.g. route, firewall, load balancing, etc.). * Label keys must be between 1 and 63 characters long and must conform to the following regular expression: `a-z{0,62}`. * Label values must be between 0 and 63 characters long and must conform to the regular expression `[a-z0-9_-]{0,63}`. * No more than 64 labels can be associated with a given resource. See https://goo.gl/xmQnxf for more information on and examples of labels. If you plan to use labels in your own code, please note that additional characters may be allowed in the future. And so you are advised to use an internal label representation, such as JSON, which doesn't rely upon specific characters being disallowed. For example, representing labels as the string: name + "_" + value would prove problematic if we were to allow "_" in a future release.NEWLINE """NEWLINE return pulumi.get(self, "labels")NEWLINENEWLINE @propertyNEWLINE @pulumi.getterNEWLINE def name(self) -> pulumi.Output[str]:NEWLINE """NEWLINE A unique identifier for the instance, which cannot be changed after the instance is created. Values are of the form `projects//instances/a-z*[a-z0-9]`. The final segment of the name must be between 2 and 64 characters in length.NEWLINE """NEWLINE return pulumi.get(self, "name")NEWLINENEWLINE @propertyNEWLINE @pulumi.getter(name="nodeCount")NEWLINE def node_count(self) -> pulumi.Output[int]:NEWLINE """NEWLINE The number of nodes allocated to this instance. At most one of either node_count or processing_units should be present in the message. This may be zero in API responses for instances that are not yet in state `READY`. See [the documentation](https://cloud.google.com/spanner/docs/compute-capacity) for more information about nodes and processing units.NEWLINE """NEWLINE return pulumi.get(self, "node_count")NEWLINENEWLINE @propertyNEWLINE @pulumi.getter(name="processingUnits")NEWLINE def processing_units(self) -> pulumi.Output[int]:NEWLINE """NEWLINE The number of processing units allocated to this instance. At most one of processing_units or node_count should be present in the message. This may be zero in API responses for instances that are not yet in state `READY`. See [the documentation](https://cloud.google.com/spanner/docs/compute-capacity) for more information about nodes and processing units.NEWLINE """NEWLINE return pulumi.get(self, "processing_units")NEWLINENEWLINE @propertyNEWLINE @pulumi.getterNEWLINE def state(self) -> pulumi.Output[str]:NEWLINE """NEWLINE The current instance state. For CreateInstance, the state must be either omitted or set to `CREATING`. For UpdateInstance, the state must be either omitted or set to `READY`.NEWLINE """NEWLINE return pulumi.get(self, "state")NEWLINENEWLINE
#!/bin/env python2.7NEWLINE# encoding: utf-8NEWLINEimport ctypesNEWLINEimport osNEWLINEimport reNEWLINEimport sysNEWLINEimport timeNEWLINENEWLINEIS_32_BITS_PYTHON = ctypes.sizeof(ctypes.c_voidp)==4NEWLINE# 4 for 32 bit or 8 for 64 bit. NEWLINENEWLINEfrom fixtures import *NEWLINENEWLINENEWLINEtry:NEWLINE FileNotFoundErrorNEWLINEexcept NameError:NEWLINE FileNotFoundError = OSErrorNEWLINENEWLINENEWLINEdef test_Version(rawfile):NEWLINE assert re.match(r"\d+\.\d+\.\d+\.\d+", rawfile.Version())NEWLINENEWLINEdef test_GetFileName(rawfile, rawfilename):NEWLINE assert rawfile.GetFileName() == os.path.abspath(rawfilename)NEWLINENEWLINEdef test_GetCreatorID(rawfile):NEWLINE assert rawfile.GetCreatorID() == 'Administrator'NEWLINENEWLINEdef test_GetVersionNumber(rawfile):NEWLINE assert rawfile.GetVersionNumber() == 50NEWLINENEWLINEdef test_GetCreationDate(rawfile):NEWLINE creation_date_iso = time.strftime('%Y-%m-%dT%H:%M:%SZ', rawfile.GetCreationDate())NEWLINE assert creation_date_iso == '1970-01-01T10:37:55Z'NEWLINENEWLINEdef test_IsError(rawfile):NEWLINE assert rawfile.IsError() == FalseNEWLINENEWLINEdef test_IsNewFile(rawfile):NEWLINE assert rawfile.IsNewFile() == FalseNEWLINENEWLINEdef test_IsThereMSData(rawfile):NEWLINE assert rawfile.IsThereMSData() == TrueNEWLINENEWLINEdef test_HasExpMethod(rawfile):NEWLINE assert rawfile.HasExpMethod() == TrueNEWLINENEWLINEdef test_InAcquisition(rawfile):NEWLINE assert rawfile.InAcquisition() == FalseNEWLINENEWLINEdef test_GetErrorCode(rawfile):NEWLINE assert rawfile.GetErrorCode() == FalseNEWLINENEWLINEdef test_GetErrorMessage(rawfile):NEWLINE assert rawfile.GetErrorMessage() == ''NEWLINENEWLINEdef test_GetWarningMessage(rawfile):NEWLINE assert rawfile.GetWarningMessage() == ''NEWLINENEWLINEdef test_RefreshViewOfFile(rawfile):NEWLINE assert rawfile.RefreshViewOfFile() == NoneNEWLINENEWLINEdef test_GetNumberOfControllers(rawfile):NEWLINE assert rawfile.GetNumberOfControllers() == 1NEWLINENEWLINEdef test_GetNumberOfControllersOfType_minus1(rawfile):NEWLINE assert rawfile.GetNumberOfControllersOfType(-1) == 0NEWLINENEWLINEdef test_GetNumberOfControllersOfType_zero(rawfile):NEWLINE assert rawfile.GetNumberOfControllersOfType(0) == 1NEWLINENEWLINEdef test_GetNumberOfControllersOfType_plus1(rawfile):NEWLINE assert rawfile.GetNumberOfControllersOfType(1) == 0NEWLINENEWLINEdef test_GetNumberOfControllersOfType_plus2(rawfile):NEWLINE assert rawfile.GetNumberOfControllersOfType(2) == 0NEWLINENEWLINEdef test_GetNumberOfControllersOfType_plus3(rawfile):NEWLINE assert rawfile.GetNumberOfControllersOfType(3) == 0NEWLINENEWLINEdef test_GetNumberOfControllersOfType_plus4(rawfile):NEWLINE assert rawfile.GetNumberOfControllersOfType(4) == 0NEWLINENEWLINEdef test_GetControllerType_zero(rawfile):NEWLINE assert rawfile.GetControllerType(0) == 'MS'NEWLINENEWLINE# def test_GetControllerType_one(rawfile):NEWLINE# assert rawfile.GetControllerType(1) == 1NEWLINENEWLINEdef test_GetCurrentController(rawfile):NEWLINE assert rawfile.GetCurrentController() == (0, 1)NEWLINENEWLINENEWLINE # print( 'GetCurrentController()', rawfile.GetCurrentController() )NEWLINE # # print( 'SetCurrentController(4,1)', rawfile.SetCurrentController(4,1) )NEWLINENEWLINE # print( 'GetCurrentController()', rawfile.GetCurrentController() )NEWLINE # # print( 'SetCurrentController(0,1)', rawfile.SetCurrentController(0,1) )NEWLINENEWLINE # print( 'GetCurrentController()', rawfile.GetCurrentController() )NEWLINENEWLINEdef test_GetExpectedRunTime(rawfile):NEWLINE assert rawfile.GetExpectedRunTime() == 100.0NEWLINENEWLINEdef test_GetMaxIntegratedIntensity(rawfile):NEWLINE assert rawfile.GetMaxIntegratedIntensity() == 1120672896.0NEWLINENEWLINEdef test_GetMaxIntensity(rawfile):NEWLINE assert rawfile.GetMaxIntensity() == 0NEWLINENEWLINEdef test_GetInletID(rawfile):NEWLINE assert rawfile.GetInletID() == 0NEWLINENEWLINEdef test_GetErrorFlag(rawfile):NEWLINE assert rawfile.GetErrorFlag() == 0NEWLINENEWLINEdef test_GetFlags(rawfile):NEWLINE assert rawfile.GetFlags() == ''NEWLINENEWLINEdef test_GetAcquisitionFileName(rawfile):NEWLINE assert rawfile.GetAcquisitionFileName() == ''NEWLINENEWLINEdef test_GetOperator(rawfile):NEWLINE assert rawfile.GetOperator() == ''NEWLINENEWLINEdef test_GetComment1(rawfile):NEWLINE assert rawfile.GetComment1() == ''NEWLINENEWLINEdef test_GetComment2(rawfile):NEWLINE assert rawfile.GetComment2() == ''NEWLINENEWLINEdef test_GetFilters(rawfile, filters_3_0, filters_3_1):NEWLINE DLL_VERSION = rawfile.VersionAsATuple()NEWLINE if DLL_VERSION.major<=3 and DLL_VERSION.minor<1:NEWLINE # GetFilters results for 3.0-NEWLINE assert rawfile.GetFilters() == filters_3_0NEWLINE assert len(rawfile.GetFilters()) == 1724NEWLINE else:NEWLINE # GetFilters results for 3.1+NEWLINE assert rawfile.GetFilters() == filters_3_1NEWLINE assert len(rawfile.GetFilters()) == 1690NEWLINENEWLINEdef test_GetMassTolerance(rawfile):NEWLINE assert rawfile.GetMassTolerance() == (False, 500.0, 0)NEWLINENEWLINEdef test_SetMassTolerance(rawfile):NEWLINE rawfile.SetMassTolerance(userDefined=True, massTolerance=555.0, units=2)NEWLINE assert rawfile.GetMassTolerance() == (True, 555.0, 2)NEWLINENEWLINEdef test_GetMassResolution(rawfile):NEWLINE assert rawfile.GetMassResolution() == 0.5NEWLINENEWLINEdef test_GetNumTrailerExtra(rawfile):NEWLINE assert rawfile.GetNumTrailerExtra() == 3316NEWLINENEWLINEdef test_GetLowMass(rawfile):NEWLINE assert rawfile.GetLowMass() == 100.0NEWLINENEWLINEdef test_GetHighMass(rawfile):NEWLINE assert rawfile.GetHighMass() == 2000.0NEWLINENEWLINEdef test_GetStartTime(rawfile):NEWLINE assert rawfile.GetStartTime() == 0.005666666666666667NEWLINENEWLINEdef test_GetEndTime(rawfile):NEWLINE assert rawfile.GetEndTime() == 99.97766666666666NEWLINENEWLINEdef test_GetNumSpectra(rawfile):NEWLINE assert rawfile.GetNumSpectra() == 3316NEWLINENEWLINEdef test_GetFirstSpectrumNumber(rawfile):NEWLINE assert rawfile.GetFirstSpectrumNumber() == 1NEWLINENEWLINEdef test_GetLastSpectrumNumber(rawfile):NEWLINE assert rawfile.GetLastSpectrumNumber() == 3316NEWLINENEWLINEdef test_GetAcquisitionDate(rawfile):NEWLINE assert rawfile.GetAcquisitionDate() == ''NEWLINENEWLINEdef test_GetUniqueCompoundNames(rawfile):NEWLINE assert rawfile.GetUniqueCompoundNames() == ('',)NEWLINENEWLINENEWLINE # print( '############################################## INSTRUMENT BEGIN')NEWLINENEWLINEdef test_GetInstrumentDescription(rawfile):NEWLINE assert rawfile.GetInstrumentDescription() == ''NEWLINENEWLINEdef test_GetInstrumentID(rawfile):NEWLINE assert rawfile.GetInstrumentID() == 0NEWLINENEWLINEdef test_GetInstSerialNumber(rawfile):NEWLINE assert rawfile.GetInstSerialNumber() == 'LC000718'NEWLINENEWLINEdef test_GetInstName(rawfile):NEWLINE assert rawfile.GetInstName() == 'LCQ'NEWLINENEWLINEdef test_GetInstModel(rawfile):NEWLINE assert rawfile.GetInstModel() == 'LCQ'NEWLINENEWLINEdef test_GetInstSoftwareVersion(rawfile):NEWLINE assert rawfile.GetInstSoftwareVersion() == '1.3'NEWLINENEWLINEdef test_GetInstHardwareVersion(rawfile):NEWLINE assert rawfile.GetInstHardwareVersion() == ''NEWLINENEWLINEdef test_GetInstFlags(rawfile):NEWLINE assert rawfile.GetInstFlags() == ''NEWLINENEWLINEdef test_GetInstNumChannelLabels(rawfile):NEWLINE assert rawfile.GetInstNumChannelLabels() == 0NEWLINENEWLINE# def test_GetInstChannelLabel(rawfile):NEWLINE# assert rawfile.GetInstChannelLabel(0) == 0NEWLINENEWLINEdef test_IsQExactive(rawfile):NEWLINE assert rawfile.IsQExactive() == FalseNEWLINENEWLINE # scanNumber = 1NEWLINE# print( '############################################## XCALIBUR INTERFACE BEGIN')NEWLINENEWLINEdef test_GetScanHeaderInfoForScanNum(rawfile):NEWLINE scanheader = rawfile.GetScanHeaderInfoForScanNum(scanNumber=1)NEWLINENEWLINE assert scanheader['numPackets'] == 0NEWLINE assert scanheader['StartTime'] == 0.005666666666666667NEWLINE assert scanheader['LowMass'] == 300.0NEWLINE assert scanheader['HighMass'] == 2000.0NEWLINE assert scanheader['TIC'] == 0.0NEWLINE assert scanheader['BasePeakMass'] == 0.0NEWLINE assert scanheader['BasePeakIntensity'] == 0.0NEWLINE assert scanheader['numChannels'] == 0NEWLINE assert scanheader['uniformTime'] == 0NEWLINE assert scanheader['Frequency'] == 0.0NEWLINENEWLINEdef test_GetTrailerExtraForScanNum(rawfile):NEWLINE scantrailer = rawfile.GetTrailerExtraForScanNum(scanNumber=1)NEWLINE assert scantrailer['Wideband Activation'] == 'Off'NEWLINE assert scantrailer['Micro Scan Count'] == 3.0NEWLINE assert scantrailer['Ion Injection Time (ms)'] == 49.98NEWLINE assert scantrailer['Scan Segment'] == 1.0NEWLINE assert scantrailer['Scan Event'] == 1.0NEWLINE assert scantrailer['Elapsed Scan Time (sec)'] == 1.38NEWLINE assert scantrailer['API Source CID Energy'] == 0.0NEWLINE assert scantrailer['Resolution'] == 'Low'NEWLINE assert scantrailer['Average Scan by Inst'] == 'No'NEWLINE assert scantrailer['BackGd Subtracted by Inst'] == 'No'NEWLINE assert scantrailer['Charge State'] == 0.0NEWLINENEWLINEdef test_GetNumTuneData(rawfile):NEWLINE assert rawfile.GetNumTuneData() == 2NEWLINENEWLINEdef test_GetTuneData(rawfile):NEWLINE assert rawfile.GetTuneData(0) == 'Capillary Temp (C):200.00\nAPCI Vaporizer Temp (C):450.00\nAGC:On\nAGC Off Ion Time (ms):5.00\nSheath Gas Flow ():0.00\nAux Gas Flow ():0.00\nSource Type:ESI\nInjection Waveforms:Off\n\nPOSITIVE POLARITY\nSource Voltage (kV):0.00\nSource Current (uA):80.00\nCapillary Voltage (V):25.00\nTube Lens Offset (V):10.00\nMultipole RF Amplifier (Vp-p):400.00\nMultipole 1 Offset (V):-7.00\nMultipole 2 Offset (V):-28.50\nInterMultipole Lens Voltage (V):-16.00\nTrap DC Offset Voltage (V):-10.00\nZoom Micro Scans:5\nZoom AGC Target:20000000.00\nZoom Max Ion Time (ms):50.00\nFull Micro Scans:3\nFull AGC Target:50000000.00\nFull Max Ion Time (ms):50.00\nSIM Micro Scans:5\nSIM AGC Target:40000000.00\nSIM Max Ion Time (ms):200.00\nMSn Micro Scans:3\nMSn AGC Target:40000000.00\nMSn Max Ion Time (ms):200.00\n\nNEGATIVE POLARITY\nSource Voltage (kV):4.00\nSource Current (uA):100.00\nCapillary Voltage (V):10.00\nTube Lens Offset (V):-50.00\nMultipole RF Amplifier (Vp-p):400.00\nMultipole 1 Offset (V):3.00\nMultipole 2 Offset (V):7.00\nInterMultipole Lens Voltage (V):16.00\nTrap DC Offset Voltage (V):10.00\nZoom Micro Scans:5\nZoom AGC Target:10000000.00\nZoom Max Ion Time (ms):50.00\nFull Micro Scans:3\nFull AGC Target:10000000.00\nFull Max Ion Time (ms):50.00\nSIM Micro Scans:5\nSIM AGC Target:20000000.00\nSIM Max Ion Time (ms):200.00\nMSn Micro Scans:3\nMSn AGC Target:20000000.00\nMSn Max Ion Time (ms):200.00\n'NEWLINENEWLINEdef test_GetNumInstMethods(rawfile):NEWLINE assert rawfile.GetNumInstMethods() == 1NEWLINENEWLINEdef test_GetInstMethodNames(rawfile):NEWLINE assert rawfile.GetInstMethodNames() == ('LCQ',)NEWLINENEWLINEdef test_GetInstMethod(rawfile, instmethod):NEWLINE assert rawfile.GetInstMethod(0) == instmethodNEWLINENEWLINEdef test_ExtractInstMethodFromRaw(rawfile):NEWLINE method_filename = rawfile.filename + '.meth'NEWLINE try:NEWLINE os.remove(method_filename)NEWLINE except FileNotFoundError:NEWLINE passNEWLINE rawfile.ExtractInstMethodFromRaw(method_filename)NEWLINE assert os.path.exists(method_filename)NEWLINENEWLINE# # # # # # # "View/Report/Sample Information" BEGINNEWLINENEWLINEdef test_GetVialNumber(rawfile):NEWLINE assert rawfile.GetVialNumber() == 0NEWLINENEWLINEdef test_GetInjectionVolume(rawfile):NEWLINE assert rawfile.GetInjectionVolume() == 0NEWLINENEWLINEdef test_GetInjectionAmountUnits(rawfile):NEWLINE assert rawfile.GetInjectionAmountUnits() == ''NEWLINENEWLINEdef test_GetSampleVolume(rawfile):NEWLINE assert rawfile.GetSampleVolume() == 0.0NEWLINENEWLINEdef test_GetSampleVolumeUnits(rawfile):NEWLINE assert rawfile.GetSampleVolumeUnits() == ''NEWLINENEWLINEdef test_GetSampleWeight(rawfile):NEWLINE assert rawfile.GetSampleWeight() == 0.0NEWLINENEWLINEdef test_GetSampleAmountUnits(rawfile):NEWLINE assert rawfile.GetSampleAmountUnits() == ''NEWLINENEWLINEdef test_GetSeqRowNumber(rawfile):NEWLINE assert rawfile.GetSeqRowNumber() == 1NEWLINENEWLINEdef test_GetSeqRowSampleType(rawfile):NEWLINE assert rawfile.GetSeqRowSampleType() == 'Unknown'NEWLINENEWLINEdef test_GetSeqRowDataPath(rawfile):NEWLINE assert rawfile.GetSeqRowDataPath() == ''NEWLINENEWLINEdef test_GetSeqRowRawFileName(rawfile):NEWLINE assert rawfile.GetSeqRowRawFileName() == 'Shew_246a_LCQa_15Oct04_Andro_0904-2_4-20.RAW'NEWLINENEWLINEdef test_GetSeqRowSampleName(rawfile):NEWLINE assert rawfile.GetSeqRowSampleName() == ''NEWLINENEWLINEdef test_GetSeqRowSampleID(rawfile):NEWLINE assert rawfile.GetSeqRowSampleID() == ''NEWLINENEWLINEdef test_GetSeqRowComment(rawfile):NEWLINE assert rawfile.GetSeqRowComment() == ''NEWLINENEWLINEdef test_GetSeqRowLevelName(rawfile):NEWLINE assert rawfile.GetSeqRowLevelName() == ''NEWLINENEWLINEdef test_GetSeqRowUserText(rawfile):NEWLINE assert rawfile.GetSeqRowUserText(index=0) == ''NEWLINENEWLINEdef test_GetSeqRowInstrumentMethod(rawfile):NEWLINE assert rawfile.GetSeqRowInstrumentMethod() == r'C:\xcalibur\methods\Std 100 min\4-20ddTop3_100min.meth'NEWLINENEWLINEdef test_GetSeqRowProcessingMethod(rawfile):NEWLINE assert rawfile.GetSeqRowProcessingMethod() == ''NEWLINENEWLINEdef test_GetSeqRowCalibrationFile(rawfile):NEWLINE assert rawfile.GetSeqRowCalibrationFile() == ''NEWLINENEWLINEdef test_GetSeqRowVial(rawfile):NEWLINE assert rawfile.GetSeqRowVial() == ''NEWLINENEWLINEdef test_GetSeqRowInjectionVolume(rawfile):NEWLINE assert rawfile.GetSeqRowInjectionVolume() == 0.0NEWLINENEWLINEdef test_GetSeqRowSampleWeight(rawfile):NEWLINE assert rawfile.GetSeqRowSampleWeight() == 0.0NEWLINENEWLINEdef test_GetSeqRowSampleVolume(rawfile):NEWLINE assert rawfile.GetSeqRowSampleVolume() == 0.0NEWLINENEWLINEdef test_GetSeqRowISTDAmount(rawfile):NEWLINE assert rawfile.GetSeqRowISTDAmount() == 0.0NEWLINENEWLINEdef test_GetSeqRowDilutionFactor(rawfile):NEWLINE assert rawfile.GetSeqRowDilutionFactor() == 1.0NEWLINENEWLINEdef test_GetSeqRowUserLabel0(rawfile):NEWLINE assert rawfile.GetSeqRowUserLabel(index=0) == 'Study'NEWLINENEWLINEdef test_GetSeqRowUserLabel1(rawfile):NEWLINE assert rawfile.GetSeqRowUserLabel(index=1) == 'Client'NEWLINENEWLINEdef test_GetSeqRowUserLabel2(rawfile):NEWLINE assert rawfile.GetSeqRowUserLabel(index=2) == 'Laboratory'NEWLINENEWLINEdef test_GetSeqRowUserLabel3(rawfile):NEWLINE assert rawfile.GetSeqRowUserLabel(index=3) == 'Company'NEWLINENEWLINEdef test_GetSeqRowUserLabel4(rawfile):NEWLINE assert rawfile.GetSeqRowUserLabel(index=4) == 'Phone'NEWLINENEWLINEdef test_GetSeqRowUserTextEx0(rawfile):NEWLINE assert rawfile.GetSeqRowUserTextEx(index=0) == ''NEWLINENEWLINEdef test_GetSeqRowUserTextEx1(rawfile):NEWLINE assert rawfile.GetSeqRowUserTextEx(index=1) == ''NEWLINENEWLINEdef test_GetSeqRowUserTextEx2(rawfile):NEWLINE assert rawfile.GetSeqRowUserTextEx(index=2) == ''NEWLINENEWLINEdef test_GetSeqRowUserTextEx3(rawfile):NEWLINE assert rawfile.GetSeqRowUserTextEx(index=3) == ''NEWLINENEWLINEdef test_GetSeqRowUserTextEx4(rawfile):NEWLINE assert rawfile.GetSeqRowUserTextEx(index=4) == ''NEWLINENEWLINEdef test_GetSeqRowBarcode(rawfile):NEWLINE assert rawfile.GetSeqRowBarcode() == ''NEWLINENEWLINEdef test_GetSeqRowBarcodeStatus(rawfile):NEWLINE assert rawfile.GetSeqRowBarcodeStatus() == 0NEWLINENEWLINENEWLINEdef test_GetNumStatusLog(rawfile):NEWLINE assert rawfile.GetNumStatusLog() == 2767NEWLINENEWLINEdef test_GetStatusLogForScanNum(rawfile):NEWLINE assert rawfile.GetStatusLogForScanNum(scanNumber=1) == (0.052666667848825455, [('API SOURCE', ''), ('Source Voltage (kV)', '0.03'), ('Source Current (uA)', '0.10'), ('Vaporizer Thermocouple OK', 'No'), ('Vaporizer Temp (C)', '-0.00'), ('Sheath Gas Flow Rate ()', '-0.20'), ('Aux Gas Flow Rate()', '-0.27'), ('Capillary RTD OK', 'Yes'), ('Capillary Voltage (V)', '25.39'), ('Capillary Temp (C)', '199.50'), ('Tube Lens Voltage (V, set point)', '10.00'), ('8 kV supply at limit', 'No'), ('', ''), ('VACUUM', ''), ('Vacuum OK', 'Yes'), ('Ion Gauge Pressure OK', 'Yes'), ('Ion Gauge Status', 'On'), ('Ion Gauge (x10e-5 Torr)', '1.64'), ('Convectron Pressure OK', 'Yes'), ('Convectron Gauge (Torr)', '0.94'), ('', ''), ('TURBO PUMP', ''), ('Status', 'Running'), ('Life (hours)', '54878'), ('Speed (rpm)', '60000'), ('Power (Watts)', '73'), ('Temperature (C)', '40.00'), ('', ''), ('ION OPTICS', ''), ('Multipole Frequency On', 'Yes'), ('Multipole 1 Offset (V)', '-6.74'), ('Lens Voltage (V)', '-15.15'), ('Multipole 2 Offset (V)', '-28.11'), ('Multipole RF Amplitude (Vp-p, set point)', '400.00'), ('Coarse Trap DC Offset (V)', '-9.88'), ('', ''), ('MAIN RF', ''), ('Reference Sine Wave OK', 'Yes'), ('Standing Wave Ratio OK', 'Yes'), ('Main RF DAC (steps)', '-33.00'), ('Main RF Detected (V)', '-0.00'), ('RF Detector Temp (C)', '37.45'), ('Main RF Modulation (V)', '0.04'), ('Main RF Amplifier (Vp-p)', '8.74'), ('RF Generator Temp (C)', '27.73'), ('', ''), ('ION DETECTION SYSTEM', ''), ('Multiplier Actual (V)', '-1182.88'), ('', ''), ('POWER SUPPLIES', ''), ('+5V Supply Voltage (V)', '5.14'), ('-15V Supply Voltage (V)', '-14.97'), ('+15V Supply Voltage (V)', '14.94'), ('+24V Supply Voltage (V)', '24.13'), ('-28V Supply Voltage (V)', '-28.09'), ('+28V Supply Voltage (V)', '28.29'), ('+28V Supply Current (Amps)', '0.80'), ('+35V Supply Voltage (V)', '35.55'), ('+36V Supply Voltage (V)', '36.22'), ('-150V Supply Voltage (V)', '-148.98'), ('+150V Supply Voltage (V)', '150.86'), ('-205V Supply Voltage (V)', '-203.87'), ('+205V Supply Voltage (V)', '205.34'), ('Ambient Temp (C)', '27.68'), ('', ''), ('INSTRUMENT STATUS', ''), ('Instrument', 'On'), ('Analysis', 'Acquiring'), ('', ''), ('SYRINGE PUMP', ''), ('Status', 'Ready'), ('Flow Rate (uL/min)', '3.00'), ('Infused Volume (uL)', '0.00'), ('Syringe Diameter (mm)', '2.30'), ('', ''), ('DIGITAL INPUTS', ''), ('READY IN is active', 'No'), ('START IN is active', 'No'), ('Divert/Inject valve', 'Load')])NEWLINENEWLINEdef test_GetStatusLogForPos(rawfile, statuslogforpos0):NEWLINE assert rawfile.GetStatusLogForPos(position=0) == statuslogforpos0NEWLINENEWLINEdef test_GetStatusLogPlottableIndex(rawfile):NEWLINE assert rawfile.GetStatusLogPlottableIndex() == (('Source Voltage (kV):', 'Source Current (uA):', 'Vaporizer Temp (C):', 'Sheath Gas Flow Rate ():', 'Aux Gas Flow Rate():', 'Capillary Voltage (V):', 'Capillary Temp (C):', 'Tube Lens Voltage (V, set point):', 'Ion Gauge (x10e-5 Torr):', 'Convectron Gauge (Torr):', 'Life (hours):', 'Speed (rpm):', 'Power (Watts):', 'Temperature (C):', 'Multipole 1 Offset (V):', 'Lens Voltage (V):', 'Multipole 2 Offset (V):', 'Multipole RF Amplitude (Vp-p, set point):', 'Coarse Trap DC Offset (V):', 'Main RF DAC (steps):', 'Main RF Detected (V):', 'RF Detector Temp (C):', 'Main RF Modulation (V):', 'Main RF Amplifier (Vp-p):', 'RF Generator Temp (C):', 'Multiplier Actual (V):', '+5V Supply Voltage (V):', '-15V Supply Voltage (V):', '+15V Supply Voltage (V):', '+24V Supply Voltage (V):', '-28V Supply Voltage (V):', '+28V Supply Voltage (V):', '+28V Supply Current (Amps):', '+35V Supply Voltage (V):', '+36V Supply Voltage (V):', '-150V Supply Voltage (V):', '+150V Supply Voltage (V):', '-205V Supply Voltage (V):', '+205V Supply Voltage (V):', 'Ambient Temp (C):', 'Flow Rate (uL/min):', 'Infused Volume (uL):', 'Syringe Diameter (mm):'), (1, 2, 4, 5, 6, 8, 9, 10, 17, 19, 23, 24, 25, 26, 30, 31, 32, 33, 34, 39, 40, 41, 42, 43, 44, 47, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 71, 72, 73))NEWLINENEWLINEdef test_GetNumErrorLog(rawfile):NEWLINE assert rawfile.GetNumErrorLog() == 1289NEWLINENEWLINEdef test_GetErrorLogItem(rawfile):NEWLINE assert rawfile.GetErrorLogItem(0) == ('Dynamic exclusion list is full. Mass 1026.89 has been dropped.', 15.657333374023438)NEWLINENEWLINEdef test_GetMassListFromScanNum(rawfile):NEWLINE assert rawfile.GetMassListFromScanNum(scanNumber=1) == (((), ()), None)NEWLINENEWLINEdef test_GetMassListRangeFromScanNum(rawfile):NEWLINE assert rawfile.GetMassListRangeFromScanNum(scanNumber=1) == (((), ()), None)NEWLINENEWLINEdef test_GetSegmentedMassListFromScanNum(rawfile):NEWLINE assert rawfile.GetSegmentedMassListFromScanNum(scanNumber=1) == (((), ()), None, (0,), 1)NEWLINENEWLINEdef test_GetAverageMassList(rawfile):NEWLINE assert rawfile.GetAverageMassList(firstAvgScanNumber=1, lastAvgScanNumber=11) == (((), ()), None)NEWLINENEWLINEdef test_GetAveragedMassSpectrum(rawfile):NEWLINE assert rawfile.GetAveragedMassSpectrum(listOfScanNumbers=[1,2,3]) == (((), ()), None)NEWLINENEWLINEdef test_GetSummedMassSpectrum(rawfile):NEWLINE assert rawfile.GetSummedMassSpectrum(listOfScanNumbers=[1,2,3]) == (((), ()), None)NEWLINENEWLINEdef test_GetLabelData(rawfile):NEWLINE labels, flags = rawfile.GetLabelData(scanNumber=1)NEWLINE assert labels.mass == ()NEWLINE assert labels.intensity == ()NEWLINE assert labels.resolution == ()NEWLINE assert labels.baseline == ()NEWLINE assert labels.noise == ()NEWLINE assert labels.charge == ()NEWLINE assert flags.saturated == ()NEWLINE assert flags.fragmented == ()NEWLINE assert flags.merged == ()NEWLINE assert flags.exception == ()NEWLINE assert flags.reference == ()NEWLINE assert flags.modified == ()NEWLINENEWLINEdef test_GetAveragedLabelData(rawfile):NEWLINE values, flags = rawfile.GetAveragedLabelData(listOfScanNumbers=[1,2,3])NEWLINE assert values == (((), (), (), (), (), ()))NEWLINE assert flags.saturated == ()NEWLINE assert flags.fragmented == ()NEWLINE assert flags.merged == ()NEWLINE assert flags.exception == ()NEWLINE assert flags.reference == ()NEWLINE assert flags.modified == ()NEWLINENEWLINENEWLINEdef test_GetAllMSOrderData(rawfile):NEWLINE labels, flags, numberOfMSOrders = rawfile.GetAllMSOrderData(scanNumber=1)NEWLINE assert labels.mass == ()NEWLINE assert labels.intensity == ()NEWLINE assert labels.resolution == ()NEWLINE assert labels.baseline == ()NEWLINE assert labels.noise == ()NEWLINE assert labels.charge == ()NEWLINE assert flags.activation_type == ()NEWLINE assert flags.is_precursor_range_valid == ()NEWLINE assert numberOfMSOrders == 0NEWLINENEWLINEdef test_GetChroData(rawfile, chrodata):NEWLINE chroData, peakFlags = rawfile.GetChroData(startTime=rawfile.StartTime,NEWLINE endTime=rawfile.EndTime,NEWLINE massRange1="{}-{}".format(rawfile.LowMass, rawfile.HighMass),NEWLINE scanFilter="Full ms ")NEWLINE assert chroData == chrodataNEWLINE assert peakFlags == NoneNEWLINENEWLINE# def test_GetChroByCompoundName(rawfile):NEWLINE# assert rawfile.GetChroByCompoundName(["methyltestosterone"]) == ''NEWLINENEWLINE# def test_GetMassPrecisionEstimate(rawfile):NEWLINE# assert rawfile.GetMassPrecisionEstimate(scanNumber=1) == ''NEWLINENEWLINEdef test_GetFullMSOrderPrecursorDataFromScanNum(rawfile):NEWLINE precursorData = rawfile.GetFullMSOrderPrecursorDataFromScanNum(scanNumber=1, MSOrder=0)NEWLINE assert precursorData.precursorMass == 50.0NEWLINE assert precursorData.isolationWidth == 1.0NEWLINE assert precursorData.collisionEnergy == 25.0NEWLINENEWLINE if (sys.version_info.major, sys.version_info.minor) == (2, 7) and IS_32_BITS_PYTHON:NEWLINE assert precursorData.collisionEnergyValid >= 1e+100NEWLINE else:NEWLINE assert precursorData.collisionEnergyValid <= 1e-200NEWLINENEWLINE assert precursorData.rangeIsValid == 0.0NEWLINE assert precursorData.firstPrecursorMass == 0.0NEWLINE assert precursorData.lastPrecursorMass == 0.0NEWLINENEWLINEdef test_GetPrecursorInfoFromScanNum(rawfile):NEWLINE assert rawfile.GetPrecursorInfoFromScanNum(scanNumber=1) == NoneNEWLINE
import connexionNEWLINEfrom swagger_server.models.add_index_response import AddIndexResponseNEWLINEfrom swagger_server.models.index import IndexNEWLINEfrom datetime import date, datetimeNEWLINEfrom typing import List, DictNEWLINEfrom six import iteritemsNEWLINEfrom ..util import deserialize_date, deserialize_datetimeNEWLINENEWLINEfrom orm.indexes import IndexesNEWLINENEWLINENEWLINEdef add_index(body):NEWLINE """NEWLINE Added a new IndexNEWLINE NEWLINE :param body: Object that needs to be added to the db.NEWLINE :type body: dict | bytesNEWLINENEWLINE :rtype: AddIndexResponseNEWLINE """NEWLINE return Indexes.add_index(connexion)NEWLINENEWLINEdef get_index_by_index_id(indexId):NEWLINE """NEWLINE Get IndexNEWLINE Returns a single IndexNEWLINE :param indexId: ID of Index to returnNEWLINE :type indexId: strNEWLINENEWLINE :rtype: GetIndexResponseNEWLINE """NEWLINE return Indexes.get_index_by_index_id(indexId)NEWLINENEWLINEdef get_index_by_object_id(objectId):NEWLINE """NEWLINE Get Index by objectIdNEWLINE Returns a single IndexNEWLINE :param objectId: ID of Object to returnNEWLINE :type objectId: strNEWLINENEWLINE :rtype: GetIndexResponseNEWLINE """NEWLINE return Indexes.get_index_by_object_id(objectId)NEWLINE