text
stringlengths
3
1.05M
# terrascript/provider/time.py # Automatically generated by tools/makecode.py (24-Sep-2021 15:28:43 UTC) # # For imports without namespace, e.g. # # >>> import terrascript.provider.time # # instead of # # >>> import terrascript.provider.hashicorp.time # # This is only available for 'official' and 'partner' providers. from terrascript.provider.hashicorp.time import *
import React from 'react'; import { Formik } from 'formik'; import schema from './login-form.schema'; import Form from './Form'; const initialValues = { email: '', password: '' }; export default ({ handleSubmit }) => { return ( <Formik initialValues={initialValues} onSubmit={handleSubmit} validationSchema={schema} render={Form} /> ); };
import chalk from 'chalk'; import { GeneralError, APIError } from '../errors/runtime'; import { RUNTIME_ERRORS } from '../errors/types'; import CliArgumentParser from './argument-parser'; import TerminationHandler from './termination-handler'; import log from './log'; import remotesWizard from './remotes-wizard'; import correctBrowsersAndSources from './correct-browsers-and-sources'; import createTestCafe from '../'; import debug from 'debug'; import logEntry from '../utils/log-entry'; const LOGGER = debug('testcafe:cli'); // NOTE: Load the provider pool lazily to reduce startup time const lazyRequire = require('import-lazy')(require); const browserProviderPool = lazyRequire('../browser/provider/pool'); let showMessageOnExit = true; let exitMessageShown = false; let exiting = false; function exitHandler (terminationLevel) { if (showMessageOnExit && !exitMessageShown) { exitMessageShown = true; log.write('Stopping TestCafe...'); process.on('exit', () => log.hideSpinner(true)); } if (exiting || terminationLevel < 2) return; exiting = true; exit(0); } function exit (code) { log.hideSpinner(true); // NOTE: give a process time to flush the output. // It's necessary in some environments. setTimeout(() => process.exit(code), 0); } function error (err) { log.hideSpinner(); let message = null; if (err instanceof GeneralError) message = err.message; else if (err instanceof APIError) message = err.coloredStack; else message = err.stack; log.write(chalk.red('ERROR ') + message + '\n'); log.write(chalk.gray('Type "testcafe -h" for help.')); exit(1); } async function runTests (argParser) { const opts = argParser.opts; const port1 = opts.ports && opts.ports[0]; const port2 = opts.ports && opts.ports[1]; const proxy = opts.proxy; const proxyBypass = opts.proxyBypass; const configFile = opts.configFile; log.showSpinner(); const { hostname, ssl, dev, experimentalDebug, retryTestPages, cache, disableHttp2, v8Flags } = opts; const testCafe = await createTestCafe({ developmentMode: dev, hostname, port1, port2, ssl, experimentalDebug, retryTestPages, cache, configFile, disableHttp2, v8Flags, }); const correctedBrowsersAndSources = await correctBrowsersAndSources(argParser, testCafe.configuration); const automatedBrowsers = correctedBrowsersAndSources.browsers; const remoteBrowsers = await remotesWizard(testCafe, argParser.remoteCount, opts.qrCode); const browsers = automatedBrowsers.concat(remoteBrowsers); const sources = correctedBrowsersAndSources.sources; const runner = opts.live ? testCafe.createLiveModeRunner() : testCafe.createRunner(); let failed = 0; runner.isCli = true; runner .useProxy(proxy, proxyBypass) .src(sources) .tsConfigPath(argParser.opts.tsConfigPath) .browsers(browsers) .reporter(argParser.opts.reporter) .concurrency(argParser.opts.concurrency) .filter(argParser.opts.filter) .video(opts.video, opts.videoOptions, opts.videoEncodingOptions) .screenshots(opts.screenshots) .startApp(opts.app, opts.appInitDelay) .clientScripts(argParser.opts.clientScripts) .compilerOptions(argParser.opts.compilerOptions); runner.once('done-bootstrapping', () => log.hideSpinner()); try { const runOpts = argParser.getRunOptions(); failed = await runner.run(runOpts); } finally { showMessageOnExit = false; await testCafe.close(); } exit(failed); } async function listBrowsers (providerName) { const provider = await browserProviderPool.getProvider(providerName); if (!provider) throw new GeneralError(RUNTIME_ERRORS.browserProviderNotFound, providerName); if (provider.isMultiBrowser) { const browserNames = await provider.getBrowserList(); await browserProviderPool.dispose(); if (providerName === 'locally-installed') console.log(browserNames.join('\n')); else console.log(browserNames.map(browserName => `"${providerName}:${browserName}"`).join('\n')); } else console.log(`"${providerName}"`); exit(0); } (async function cli () { const terminationHandler = new TerminationHandler(); terminationHandler.on(TerminationHandler.TERMINATION_LEVEL_INCREASED_EVENT, exitHandler); try { const argParser = new CliArgumentParser(); logEntry(LOGGER, process.argv); await argParser.parse(process.argv); logEntry(LOGGER, argParser.opts); if (argParser.opts.listBrowsers) await listBrowsers(argParser.opts.providerName); else await runTests(argParser); } catch (err) { showMessageOnExit = false; error(err); } })();
import * as wasm from "wasm-bellman-ford"; var data = JSON.stringify( { "graph": [ [1.00, 2.00, 4.00], [0.50, 1.00, 2.00], [0.25, 0.50, 1.00] ] }) var bool_response = wasm.bellman_ford_neg_cycle(data); console.log(bool_response)
from .actions import ActionProcessor from .log import LogProcessor
const { cat, rm, cp, exec, mkdir } = require("shelljs") const replace = require('replace-in-file'); const ora = require('ora'); const { readFile, writeFile } = require('jsonfile') const os = require("os"); const typingSource = "build/output/node/js/**/*.d.ts"; const typingFile = "typings/ExchangeWebService.d.ts"; const typePrefixFile = "scripts/config/tsd.start"; const typeSuffixFile = "scripts/config/tsd.end"; const outputDir = "build/output/node"; const spinner = ora({ spinner: "arc", color: "yellow" }); (async () => { try { spinner.start("Cleaning up from previous session"); preClean(); spinner.succeed(); spinner.start("Compiling TypeScript"); await compile(); spinner.succeed(); spinner.start("Combining TypeScript definitions") mergeDef(); cleanDef(); fixDef(); cleanupDef(); spinner.succeed(); spinner.start("Copying npm files") copyFiles(); copyPackageJson(); spinner.succeed(); } catch (error) { console.error(error); spinner.fail(); } finally { spinner.stop(); spinner.clear(); } })(); function preClean() { rm('-rf', outputDir); try { mkdir("-p", outputDir); } catch (error) { } } function compile() { return new Promise(resolve => { exec("tsc -p tsconfig.build.json", { shell: true, stdio: 'inherit' }, resolve); }) } function mergeDef() { cat(typingSource).to(typingFile); } function cleanDef() { const options = { files: typingFile, from: [ /\r?\n?^.*import.*\{.*\}.*from.*\;/gm, /\r?\nimport \* as moment from 'moment-timezone';/g, /^.*export.*\{.*\}.*from.*\;/gm, /^.*export.*\{.*\};$/gm, /^.*\/\/\/\s*\<reference.*\>/gm, /(\r?\n\s*\/\*\*\s*\r?\n([^\*]|(\*(?!\/)))*\*\/)?\r?\n\s*private\s.*;/gm, // replace line with private and also preceding lines with jsdoc comments // /^\s*private\s.*;/gm, // original replacing private did not replace p /\r\n\r\n/g, /\n\n/g, /export declare/g, ], to: '', }; replace.sync(options); } function fixDef() { cat(typePrefixFile, typingFile, typeSuffixFile).to(typingFile) } function cleanupDef() { rm(typingSource); } function copyFiles() { cp([ "./README.md", "./LICENSE", "./COPYRIGHT", ], outputDir); mkdir("build/output/node/typings"); cp("./typings/ExchangeWebService.d.ts", "build/output/node/typings/ExchangeWebService.d.ts"); } function copyPackageJson() { return new Promise(async resolve => { const file = 'package.json' const obj = await readFile(file).catch(error => console.error(error)); delete obj.devDependencies; await writeFile(`${outputDir}/package.json`, obj, { spaces: 4, EOL: os.EOL }).catch(error => console.error(error)); resolve(); }); }
var gulp = require('gulp'); var del = require('del'); var gulpsync = require('gulp-sync')(gulp); var uglify = require('gulp-uglify'); var rename = require('gulp-rename'); var gzip = require('gulp-gzip'); var replace = require('gulp-string-replace'); gulp.task('default', gulpsync.sync([ 'version.update', 'clean', 'uglify', 'zip', 'copy.to.docs', ])); var version = '"1.2.3"'; var pattern = /(\"|\')(\d+\.\d+\.\d+)(\"|\')/; gulp.task('version.update', function() { return gulp.src(["./pakka.js", "./bower.json", "./package.json"]) .pipe(replace(pattern, version)) .pipe(gulp.dest('./')); }); gulp.task('clean', function() { return del.sync(['pakka.min.js', 'pakka.min.js.gz']); }); gulp.task('uglify', function() { return gulp.src('./pakka.js') .pipe(uglify()) .pipe(rename({ suffix: '.min' })) .pipe(gulp.dest('./')); }); gulp.task('zip', function() { return gulp.src('./pakka.min.js') .pipe(gzip()) .pipe(gulp.dest('./')); }); gulp.task('copy.to.docs', function() { return gulp.src([ './pakka.js', './node_modules/lodash/lodash.js' ]) .pipe(gulp.dest('./docs/')); });
export const cibMozilla = ["32 32","<path d='M0 32v-32h32v32zM21.855 9.016l-0.308 0.036-0.292 0.052-0.281 0.084-0.265 0.093-0.271 0.093-0.249 0.12-0.24 0.131-0.229 0.145-0.224 0.161-0.213 0.172-0.203 0.188-0.183 0.203-0.177 0.213-0.172 0.224-0.145 0.229-0.147 0.251-0.135 0.255-0.12 0.281-0.104-0.297-0.136-0.276-0.135-0.271-0.156-0.249-0.177-0.229-0.188-0.213-0.197-0.199-0.199-0.187-0.229-0.172-0.224-0.147-0.255-0.145-0.24-0.125-0.265-0.104-0.265-0.093-0.271-0.079-0.276-0.068-0.297-0.052-0.292-0.025-0.291-0.032h-0.573l-0.281 0.032-0.265 0.025-0.271 0.037-0.251 0.067-0.24 0.068-0.239 0.079-0.245 0.093-0.208 0.109-0.229 0.104-0.197 0.136-0.204 0.129-0.187 0.152-0.183 0.156-0.177 0.177-0.156 0.172-0.161 0.187-0.147 0.199-0.135 0.213-0.12 0.213v-2.068h-5.803v2.964h1.829v7.812h-1.829v3.011h8.443v-3.011h-2.64v-5.083l0.016-0.276 0.036-0.271 0.041-0.251 0.052-0.24 0.068-0.239 0.079-0.213 0.093-0.215 0.109-0.187 0.12-0.188 0.145-0.161 0.147-0.145 0.161-0.136 0.187-0.12 0.199-0.104 0.197-0.077 0.229-0.068 0.256-0.052 0.249-0.032 0.281-0.011h0.229l0.208 0.027 0.213 0.041 0.188 0.052 0.188 0.068 0.171 0.079 0.163 0.093 0.145 0.12 0.135 0.135 0.131 0.147 0.109 0.161 0.104 0.183 0.084 0.213 0.077 0.213 0.068 0.255 0.052 0.256 0.041 0.276 0.043 0.307 0.011 0.333v8.12h5.733v-3.011h-1.828v-4.801l0.016-0.281 0.011-0.276 0.025-0.271 0.057-0.251 0.052-0.24 0.068-0.239 0.079-0.213 0.093-0.215 0.104-0.187 0.125-0.188 0.131-0.161 0.161-0.145 0.161-0.136 0.181-0.12 0.188-0.104 0.213-0.077 0.229-0.068 0.251-0.052 0.255-0.032 0.281-0.011h0.224l0.213 0.027 0.213 0.041 0.188 0.052 0.187 0.068 0.172 0.079 0.161 0.093 0.147 0.12 0.135 0.135 0.12 0.147 0.12 0.161 0.104 0.183 0.084 0.213 0.077 0.213 0.068 0.255 0.052 0.256 0.041 0.276 0.037 0.307 0.015 0.333v8.12h5.735v-3.011h-1.828v-6.296l-0.016-0.48-0.052-0.437-0.077-0.427-0.109-0.401-0.131-0.375-0.161-0.344-0.188-0.323-0.213-0.308-0.239-0.265-0.24-0.249-0.281-0.215-0.276-0.203-0.308-0.172-0.323-0.161-0.333-0.12-0.333-0.104-0.359-0.083-0.344-0.052-0.375-0.043h-0.693z'/>"]
import React, { Component } from 'react'; import Iframe from 'react-iframe'; import './Contact.css'; class Contact extends Component { render () { // <div className="map-canvas" id="map-canvas-contact" data-lat="19.433555" data-lng="-99.172938" data-string="<div className='map-content'> // <p><i><img src='images/icon/location-ic.png' alt='Dirección' /></i>Gutemberg 47-A, Verónic Anzúres, 11300. CDMX, México</p> // <p><i><img src='images/icon/phone-ic.png' alt='Teléfono' /></i><a href='tel:+525563930808'>+52 (55) 6393 0808</a></p> // </div>" data-zoom="18"></div> return ( <main className="site-main page-spacing"> <div className="page-banner contact-banner container-fluid no-padding"> <div className="page-banner-content"> <div className="container"> <h3>Contáctanos</h3> <p>¿Dudas? ¡Ponte en contacto con nuestros expertos!</p> </div> </div> <div className="banner-content container-fluid no-padding"> <div className="container"> <h4 className="pull-left">Dirección</h4> </div> </div> </div> <div className="contact-us container-fluid no-padding"> <div className="map container-fluid no-padding"> <div className="map-canvas" id="map-canvas-contact"> <Iframe url="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3762.510099940134!2d-99.17513368564478!3d19.43356198688378!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x85d1f8b49ca7f27d%3A0xb0654b427fbc58b9!2sMipecera!5e0!3m2!1ses-419!2smx!4v1540507548259" width="100%" height="100%" frameborder="0" style="border:0" allowfullscreen /> </div> </div> <div className="section-padding"></div> <div className="container"> <div className="section-header"> <h3>Mándanos un mensaje</h3> <p>Nuestros expertos se pondrán en contacto contigo a la brevedad</p> </div> <form className="contact-form"> <div className="row"> <div className="form-group col-md-6"> <input type="text" name="contact-name" className="form-control" id="input_name" placeholder="Nombre completo *" required/> </div> <div className="form-group col-md-6"> <input type="email" name="contact-email" className="form-control" id="input_email" placeholder="Correo Electrónico *" required/> </div> <div className="form-group col-md-6"> <input type="text" name="contact-phone" className="form-control" id="input_phone" placeholder="Telefono *" required /> </div> <div className="form-group col-md-6"> <input type="text" name="contact-subject" className="form-control" id="input_subject" placeholder="Asunto *" required /> </div> <div className="form-group col-md-12"> <textarea className="form-control" rows="5" name="contact-message" id="textarea_message" placeholder="Mensaje *"></textarea> </div> <div className="form-group"> <input type="submit" title="Enviar Mensaje" value="Enviar Mensaje" id="btn_submit" name="post" /> </div> <div id="alert-msg" className="alert-msg"></div> </div> </form> </div> <div className="section-padding"></div> </div> </main> ); } } export { Contact };
#!/usr/bin/env python # -*- coding:utf-8 -*- import hashlib import re import urllib2 from django.views.decorators.csrf import csrf_exempt import pymongo from PenBlog.config.server import * from PenBlog.func import * __author__ = 'quanix' def show_homepage(request, page): """ 博客首页 """ db = connect_mongodb_database(request) info = db.infos.find_one() page = int(page) per_page = info.get('ArticlesPerPage') or 10 count = db.articles.find({'IsPublic': True}).count() #对文章数据进行分页 articles = list( db.articles.find({'IsPublic': True}, sort=[('PostOn', -1)], skip=(page-1)*per_page, limit=per_page, )) info = db.infos.find_one() for a in articles: calculate_local_timeinfo(info, a) categories = list(db.categories.find()) links = list(db.links.find(sort=[('Order', pymongo.ASCENDING)])) return render_and_back(request, 'index.html', { 'page': u'首页', 'articles': articles, 'links': links, 'categories': categories, 'paginator': { 'Current': page, 'Total': count / per_page + (1 if count % per_page else 0), 'PerPage': per_page, }, }) @csrf_exempt def install(request): """ 安装页面 """ blog = get_current_blog(request) if blog is None: return HttpResponse('安装前请配置server.py!') name = blog[STR_NAME] if not re.match(r'^\w+$', name): return HttpResponse( '博客名称"%s"不合法。规范的名称仅限字母、数字和下划线' % name ) admin = blog[STR_ADMINS] if isinstance(admin, list): admin = admin[0] if not re.match(r'^\w+$', admin): return HttpResponse( '管理员名称"%s"不合法。规范的名称仅限字母、数字和下划线' % admin ) # 检查博客是否已存在 db = connect_mongodb_database(request) info = db.infos.find_one() if info is not None: return HttpResponse('博客已存在') # 检查第一个admin账户是否存在 db = connect_mongodb_account_database(request) user = db.users.find_one({'Username': admin}) if user is None: return redirect(request, '需要创建管理员账户', 'register/?redirect=install') if request.method == 'GET': admins = blog[STR_ADMINS] if isinstance(admin, list): admins = ', '.join(admins) set_template_dir('admin') return render_to_response('install.html', { 'host': request.get_host(), 'name': blog[STR_NAME], 'admins': admins, }) elif request.method == 'POST': d = request.POST if d.get('is-blog-info-checked') is None: return redirect(request, '未勾选确认按钮', 'install/') db = connect_mongodb_database(request) db.categories.insert({ 'Title': '默认分类', 'Description': '', 'Order': 0 }) db.infos.insert({ 'TopId': 0, 'Title': 'PenBlog', 'Subtitle': 'A blog based of Django and MongoDB', 'Description': 'No description', 'Theme': 'default', 'DefaultTimezone': 'Asia/Guangzhou', 'DefaultTimezoneOffset': '+8', 'ArticlesPerPage': 10, 'CustomRss': '', 'WeiboCode': '', 'CommentCode': '', 'LatestCommentsCode': '', 'StatisticsCode': '', 'StatisticsCodeInHead': False, }) ensure_index_of_blog(db) db.connection.disconnect() return redirect(request, '安装完成', '') def get_file(request, ext): """ 获取静态文件 """ path = request.path abspath = os.path.abspath('.') + '/' + 'PenBlog' + path if os.sep != '/': abspath = abspath.replace('/', '\\') stream = open(abspath, 'rb').read() mine = query_mine_type(ext) return HttpResponse(stream, mimetype=mine) @csrf_exempt def login(request): # 普通访问 if request.method == 'GET': return render_admin_and_back(request, 'login.html', { 'page': u'登录' }) # 处理提交的表单 elif request.method == 'POST': d = request.POST username = d['username'] password = d['passwordHash'] date = d['date'] db = connect_mongodb_account_database(request) user = db.users.find_one({'Username': username}) if user is None: return redirect(request, '用户名/密码错误', 'login/') hash = hashlib.sha1() hash.update(user['Password']) hash.update(date) if password != hash.hexdigest(): return redirect(request, '用户名/密码错误', 'login/') request.session['user'] = user url = '' if 'redirect' in request.GET: url = urllib2.unquote(request.GET['redirect']) return redirect(request, '登陆成功', url or 'admin/', 0) def logout(request): """ 登出 """ if 'user' in request.session: del request.session['user'] return redirect(request, '已退出', 'admin/', 0) @csrf_exempt def register(request): """ 注册功能 """ if request.method == 'GET': set_template_dir('admin') d={} #是否注册第一位管理员 if request.GET.get('redirect') == 'install': # 取出第一位管理员 blog = get_current_blog(request) admin = blog[STR_ADMINS] if isinstance(admin, list): admin = admin[0] d['admin'] = admin d['is_to_install'] = True # 标记注册后转到安装界面 return render_to_response('register.html', d) elif request.method == 'POST': d = request.POST password = d['password'] password_repeat = d['password-repeat'] # 验证两次密码输入是否正确 if password == password_repeat: db = connect_mongodb_account_database(request) # 检查用户是否已存在 username = d['username'] if db.users.find_one({'Username':username}): return redirect(request, '用户已存在', 'register/') # 检查Email是否已存在 email = d['email'] if db.users.find_one({'Email':email}): return redirect(request, 'Email已存在', 'register/') nickname = d['nickname'] # 对密码进行哈希 hash = hashlib.sha1() hash.update((username+password).encode('utf8')) passwordHash = hash.hexdigest() # 插入用户信息 db.users.insert({ 'Username': username, 'Password':passwordHash, 'Nickname':nickname, 'Email':email, }) db.connection.disconnect() # 是否转到安装界面 is_to_install = d['is-to-install'] == 'True' return redirect(request, '新建用户成功', 'install/' if is_to_install else '') else: return redirect(request, '密码重复') def show_article(request, id): """ 展示文章 """ db = connect_mongodb_database(request) article = db.articles.find_one({ 'Id':int(id), 'IsPublic': True }) if article is None: return HttpResponse('404') info = db.infos.find_one() calculate_local_timeinfo(info, article) categories = list(db.categories.find()) links = list(db.links.find(sort=[('Order', pymongo.ASCENDING)])) return render_and_back(request, 'detail.html', { 'page': u'文章 - ' + article['Title'], 'article': article, 'links': links, 'categories':categories, }) def show_category(request,category): """ 展示分类下的文章 """ db = connect_mongodb_database(request) category = urllib2.unquote(category) categoryObject = db.categories.find_one({'Title': category}) if categoryObject is None: return HttpResponse('404') links = db.links.find(sort=[('Order', pymongo.ASCENDING)]) articles = db.articles.find( {'Categories': category, 'IsPublic': True}, sort=[('PostOn', pymongo.DESCENDING)] ) categories = db.categories.find() return render_and_back(request, 'index.html', { 'page': u'分类 - ' + category, 'links': links, 'articles': articles, 'categories': categories, }) def show_tag(request,tag): """ 展示标签 """ db = connect_mongodb_database(request) tag = urllib2.unquote(tag) links = db.links.find(sort=[('Order', pymongo.ASCENDING)]) articles = db.articles.find( {'Tags': tag,'IsPublic': True}, sort=[('PostOn', pymongo.DESCENDING)] ) categories = db.categories.find() return render_and_back(request, 'index.html', { 'page': u'标签 - ' + tag, 'links': links, 'articles': articles, 'categories': categories, })
from abc import ABCMeta, abstractmethod import numpy as np from scipy.linalg import hankel from scipy.sparse import lil_matrix from scipy.sparse import csr_matrix as spmatrix class StructureMeta: __metaclass__ = ABCMeta @abstractmethod def struct_from_vec(self, x): # reads an input vector # returns a structured matrix pass @abstractmethod def vec_from_struct(self, X): # reads a structured matrix # returns the underlying data vector pass @abstractmethod def orth_proj(self, X): # reads an unstructured matrix # returns its orthogonal projection on the space of structured matrices pass @abstractmethod def vec_via_orth_proj(self, X): # reads an unstructured matrix # returns the underlying data vector of its orthogonal projection on the space of structured matrices pass class Hankel(StructureMeta): def __init__(self, m, n): self.m = m self.n = n N = m + n - 1 self.N = N self.S = np.zeros((m*n, N)) for i in xrange(m): self.S[:,i] = hankel(np.vstack((np.zeros((i, 1)), 1, np.zeros((m - i - 1, 1)))), np.zeros((1, n))).reshape((m*n,), order='F') for i in xrange(m, N): self.S[:, i] = hankel(np.zeros((m, 1)), np.hstack((np.zeros((1, i+1 - m)), np.ones((1,1)), np.zeros((1, N - i - 1))))).reshape((m*n,), order='F') self.S = spmatrix(self.S) self.ST = self.S.T STSinvdiag = 1.0 / (self.ST.dot(self.S)).diagonal() STSinv = lil_matrix((N, N)) STSinv.setdiag(STSinvdiag) self.S_pinv = STSinv.dot(self.ST) self.Pi_S = self.S.dot(self.S_pinv) def struct_from_vec(self, x): X_vec = self.S.dot(x) X = np.reshape(X_vec, (self.m, self.n), order='F') return X def vec_from_struct(self, X): return np.concatenate((X[0, :], X[1:, -1])) def orth_proj(self, X): X_H = np.reshape(self.Pi_S.dot(X.flatten(1)), (self.m, self.n), order='F') return X_H def vec_via_orth_proj(self, X): x_h = self.S_pinv.dot(X.flatten(1)) return x_h
/* * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The OpenAirInterface Software Alliance licenses this file to You under * the terms found in the LICENSE file in the root of this source tree. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *------------------------------------------------------------------------------- * For more information about the OpenAirInterface (OAI) Software Alliance: * contact@openairinterface.org */ /*! \file mme_app_itti_messaging.h \brief \author Sebastien ROUX, Lionel Gauthier \company Eurecom \email: lionel.gauthier@eurecom.fr */ #ifndef FILE_MME_APP_ITTI_MESSAGING_SEEN #define FILE_MME_APP_ITTI_MESSAGING_SEEN #include <inttypes.h> #include <string.h> #include "lte/gateway/c/core/oai/common/log.h" #include "lte/gateway/c/core/oai/include/mme_config.h" #include "lte/gateway/c/core/oai/lib/3gpp/3gpp_36.401.h" #include "lte/gateway/c/core/oai/common/common_types.h" #include "lte/gateway/c/core/oai/lib/itti/intertask_interface.h" #include "lte/gateway/c/core/oai/lib/itti/intertask_interface_types.h" #include "lte/gateway/c/core/oai/lib/itti/itti_types.h" #include "lte/gateway/c/core/oai/include/mme_app_desc.h" #include "lte/gateway/c/core/oai/include/mme_app_ue_context.h" #include "lte/gateway/c/core/oai/tasks/mme_app/mme_app_procedures.h" #include "lte/gateway/c/core/oai/include/s1ap_messages_types.h" #include "lte/gateway/c/core/oai/tasks/mme_app/mme_app_defs.h" #include "lte/gateway/c/core/oai/tasks/mme_app/mme_app_timer.h" void mme_app_itti_ue_context_release( struct ue_mm_context_s* ue_context_p, enum s1cause cause); int mme_app_notify_s1ap_ue_context_released(const mme_ue_s1ap_id_t ue_idP); status_code_e mme_app_send_s11_release_access_bearers_req( struct ue_mm_context_s* const ue_mm_context, const pdn_cid_t pdn_index); status_code_e mme_app_send_s11_create_session_req( mme_app_desc_t* mme_app_desc_p, struct ue_mm_context_s* const ue_mm_context, const pdn_cid_t pdn_cid); static inline void mme_app_itti_ue_context_mod_for_csfb( struct ue_mm_context_s* ue_context_p) { MessageDef* message_p; message_p = itti_alloc_new_message( TASK_MME_APP, S1AP_UE_CONTEXT_MODIFICATION_REQUEST); memset( (void*) &message_p->ittiMsg.s1ap_ue_context_mod_request, 0, sizeof(itti_s1ap_ue_context_mod_req_t)); S1AP_UE_CONTEXT_MODIFICATION_REQUEST(message_p).mme_ue_s1ap_id = ue_context_p->mme_ue_s1ap_id; S1AP_UE_CONTEXT_MODIFICATION_REQUEST(message_p).enb_ue_s1ap_id = ue_context_p->enb_ue_s1ap_id; if ((ue_context_p->sgs_context != NULL) && ((ue_context_p->sgs_context->csfb_service_type == CSFB_SERVICE_MO_CALL) || (ue_context_p->sgs_context->csfb_service_type == CSFB_SERVICE_MT_CALL))) { S1AP_UE_CONTEXT_MODIFICATION_REQUEST(message_p).presencemask = S1AP_UE_CONTEXT_MOD_LAI_PRESENT; mme_config_read_lock(&mme_config); S1AP_UE_CONTEXT_MODIFICATION_REQUEST(message_p).lai = mme_config.lai; mme_config_unlock(&mme_config); S1AP_UE_CONTEXT_MODIFICATION_REQUEST(message_p).presencemask |= S1AP_UE_CONTEXT_MOD_CSFB_INDICATOR_PRESENT; if (ue_context_p->sgs_context->is_emergency_call == true) { S1AP_UE_CONTEXT_MODIFICATION_REQUEST(message_p).cs_fallback_indicator = CSFB_HIGH_PRIORITY; ue_context_p->sgs_context->is_emergency_call = false; } else { S1AP_UE_CONTEXT_MODIFICATION_REQUEST(message_p).cs_fallback_indicator = CSFB_REQUIRED; } } OAILOG_INFO( LOG_MME_APP, "Sent S1AP_UE_CONTEXT_MODIFICATION_REQUEST " "mme_ue_s1ap_id " MME_UE_S1AP_ID_FMT "\n", S1AP_UE_CONTEXT_MODIFICATION_REQUEST(message_p).mme_ue_s1ap_id); send_msg_to_task(&mme_app_task_zmq_ctx, TASK_S1AP, message_p); /* Start timer to wait for UE Context Modification from eNB * If timer expires treat this as failure of ongoing procedure * and abort corresponding NAS procedure * such as SERVICE REQUEST and Send Service Reject to eNB */ if ((ue_context_p->ue_context_modification_timer.id = mme_app_start_timer( ue_context_p->ue_context_modification_timer.msec, TIMER_REPEAT_ONCE, mme_app_handle_ue_context_modification_timer_expiry, ue_context_p->mme_ue_s1ap_id)) == -1) { OAILOG_ERROR( LOG_MME_APP, "Failed to start UE context modification timer for UE id %d \n", ue_context_p->mme_ue_s1ap_id); ue_context_p->ue_context_modification_timer.id = MME_APP_TIMER_INACTIVE_ID; } else { OAILOG_DEBUG( LOG_MME_APP, "MME APP :Sent UE context modification request and Started guard timer " "for UE id " MME_UE_S1AP_ID_FMT, ue_context_p->mme_ue_s1ap_id); } OAILOG_FUNC_OUT(LOG_MME_APP); } void mme_app_send_s1ap_e_rab_modification_confirm( const mme_ue_s1ap_id_t mme_ue_s1ap_id, const enb_ue_s1ap_id_t enb_ue_s1ap_id, const mme_app_s1ap_proc_modify_bearer_ind_t* const proc); void nas_itti_sgsap_uplink_unitdata( const char* const imsi, uint8_t imsi_len, bstring nas_msg, imeisv_t* imeisv, MobileStationClassmark2* mobilestationclassmark2, tai_t* tai, ecgi_t* ecgi, bool sms_orc8r_enabled); void mme_app_itti_sgsap_tmsi_reallocation_comp( const char* imsi, const unsigned int imsi_len); void mme_app_itti_sgsap_ue_activity_ind( const char* imsi, const unsigned int imsi_len); #endif /* FILE_MME_APP_ITTI_MESSAGING_SEEN */
from collections import OrderedDict import torch from torch import nn from torch.nn import functional as F class _SimpleSegmentationModel(nn.Module): __constants__ = ['aux_classifier'] def __init__(self, backbone, classifier, aux_classifier=None): super(_SimpleSegmentationModel, self).__init__() self.backbone = backbone self.classifier = classifier self.aux_classifier = aux_classifier def forward(self, x): input_shape = x.shape[-2:] # contract: features is a dict of tensors features = self.backbone(x) result = OrderedDict() x = features["out"] x = self.classifier(x) x = F.interpolate(x, size=input_shape, mode='bilinear', align_corners=False) result["out"] = x if self.aux_classifier is not None: x = features["aux"] x = self.aux_classifier(x) x = F.interpolate(x, size=input_shape, mode='bilinear', align_corners=False) result["aux"] = x return result
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # @auther:FelixFu # @Date: 2021.10.1 # @github:https://github.com/felixfu520 import math from functools import partial from core.modules.register import Registers @Registers.schedulers.register class yolox_warm_cos: def __init__(self, lr, iters_per_epoch, total_epochs, **kwargs): """ Args: lr (float): learning rate. iters_per_peoch (int): number of iterations in one epoch. total_epochs (int): number of epochs in training. kwargs (dict): - warmup_epochs - warmup_lr_start (default 1e-6) """ self.lr = lr self.iters_per_epoch = iters_per_epoch self.total_epochs = total_epochs self.total_iters = iters_per_epoch * total_epochs self.__dict__.update(kwargs) # update self.attr, if not add self.lr_func = self._get_lr_func() def update_lr(self, iters): return self.lr_func(iters) def _get_lr_func(self): warmup_total_iters = self.iters_per_epoch * self.warmup_epochs no_aug_iters = self.iters_per_epoch * self.no_aug_epochs warmup_lr_start = getattr(self, "warmup_lr_start", 0) min_lr_ratio = getattr(self, "min_lr_ratio", 0.2) lr_func = partial( fun_lr, self.lr, min_lr_ratio, self.total_iters, warmup_total_iters, warmup_lr_start, no_aug_iters, ) return lr_func def fun_lr( lr, min_lr_ratio, total_iters, warmup_total_iters, warmup_lr_start, no_aug_iter, iters, ): """Cosine learning rate with warm up.""" min_lr = lr * min_lr_ratio if iters <= warmup_total_iters: # lr = (lr - warmup_lr_start) * iters / float(warmup_total_iters) + warmup_lr_start lr = (lr - warmup_lr_start) * pow( iters / float(warmup_total_iters), 2 ) + warmup_lr_start elif iters >= total_iters - no_aug_iter: lr = min_lr else: lr = min_lr + 0.5 * (lr - min_lr) * ( 1.0 + math.cos( math.pi * (iters - warmup_total_iters) / (total_iters - warmup_total_iters - no_aug_iter) ) ) return lr
require('../../modules/es6.object.statics-accept-primitives'); module.exports = require('../../modules/$.core').Object.isSealed;
import Vue from "vue" import Element from "element-ui" import locale from "element-ui/lib/locale/lang/en" Vue.use(Element, { locale })
import VJOTGFilter from '../prototype.js'; /** * @customelement vj-otg-mirror * @description Custom element for mirroring the current corrdinate. * @property mode {number} value from 0-3 describing how the mirror is done * - 0, No mirror * - 1, Left to Right * - 2, Top to Bottom * - 3, Left to Right and Top to Bottom * @example * <vj-otg-mirror mode="1"></vj-otg-mirror> */ class VJOTGMirror extends VJOTGFilter { constructor() { super(); } static get types() { return { mode: 'i' }; } allAttributesChangedCallback(glAttributes) { if (glAttributes.mode.uniform) { glAttributes.mode.uniform.value = glAttributes.mode.value; } this.shaderChunks.main = ` int sym = ${ glAttributes.mode.isSnippet ? glAttributes.mode.glslSnippet : glAttributes.mode.uniformName }; if (sym == 1 || sym == 3) { if (newUV.x > 0.5) { newUV.x = 0.5 - (newUV.x - 0.5); } } if (sym == 2 || sym == 3) { if (newUV.y > 0.5) { newUV.y = 0.5 - (newUV.y - 0.5); } }` } } customElements.define('vj-otg-mirror', VJOTGMirror);
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); (() => { llm.initializeTabs(document.querySelector("#tabs--reports")); })();
# -*- coding: utf-8 -*- """ pwdcheck.helpers ~~~~~~~~~~~~~~~~ """ class Dotdict(dict): """dot.notation access to dict attributes.""" __getattr__ = dict.__getitem__ __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ class cached_property(object): """Decorator that converts a method with a single self argument into a property cached on the instance. """ def __init__(self, fn): self.__fn = fn def __get__(self, instance, type=None): if instance is None: return self res = instance.__dict__[self.__fn.__name__] = self.__fn(instance) return res
''' Module: libs.sdk Description: This is the library sub-component of Genie for `genie.sdk`. ''' # metadata __version__ = '19.10' __author__ = 'Cisco Systems Inc.' __contact__ = ['pyats-support@cisco.com', 'pyats-support-ext@cisco.com'] __copyright__ = 'Copyright (c) 2018, Cisco Systems Inc.' from genie import abstract abstract.declare_package(__name__) # try to record usage statistics # - only internal cisco users will have stats.CesMonitor module # - below code does nothing for DevNet users - we DO NOT track usage stats # for PyPI/public/customer users try: # new internal cisco-only pkg since devnet release from ats.cisco.stats import CesMonitor except Exception: try: # legacy pyats version, stats was inside utils module from ats.utils.stats import CesMonitor except Exception: CesMonitor = None finally: if CesMonitor is not None: # CesMonitor exists -> this is an internal cisco user CesMonitor(action = __name__, application='Genie').post() CesMonitor(action = __name__, application='pyATS Packages').post()
/** * @license * Copyright (c) 2014 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt * Code distributed by Google as part of the polymer project is also * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ // @version 0.7.22 "undefined"==typeof WeakMap&&!function(){var e=Object.defineProperty,t=Date.now()%1e9,n=function(){this.name="__st"+(1e9*Math.random()>>>0)+(t++ +"__")};n.prototype={set:function(t,n){var r=t[this.name];return r&&r[0]===t?r[1]=n:e(t,this.name,{value:[t,n],writable:!0}),this},get:function(e){var t;return(t=e[this.name])&&t[0]===e?t[1]:void 0},"delete":function(e){var t=e[this.name];return t&&t[0]===e?(t[0]=t[1]=void 0,!0):!1},has:function(e){var t=e[this.name];return t?t[0]===e:!1}},window.WeakMap=n}(),function(e){function t(e){E.push(e),g||(g=!0,f(r))}function n(e){return window.ShadowDOMPolyfill&&window.ShadowDOMPolyfill.wrapIfNeeded(e)||e}function r(){g=!1;var e=E;E=[],e.sort(function(e,t){return e.uid_-t.uid_});var t=!1;e.forEach(function(e){var n=e.takeRecords();o(e),n.length&&(e.callback_(n,e),t=!0)}),t&&r()}function o(e){e.nodes_.forEach(function(t){var n=v.get(t);n&&n.forEach(function(t){t.observer===e&&t.removeTransientObservers()})})}function i(e,t){for(var n=e;n;n=n.parentNode){var r=v.get(n);if(r)for(var o=0;o<r.length;o++){var i=r[o],a=i.options;if(n===e||a.subtree){var s=t(a);s&&i.enqueue(s)}}}}function a(e){this.callback_=e,this.nodes_=[],this.records_=[],this.uid_=++_}function s(e,t){this.type=e,this.target=t,this.addedNodes=[],this.removedNodes=[],this.previousSibling=null,this.nextSibling=null,this.attributeName=null,this.attributeNamespace=null,this.oldValue=null}function d(e){var t=new s(e.type,e.target);return t.addedNodes=e.addedNodes.slice(),t.removedNodes=e.removedNodes.slice(),t.previousSibling=e.previousSibling,t.nextSibling=e.nextSibling,t.attributeName=e.attributeName,t.attributeNamespace=e.attributeNamespace,t.oldValue=e.oldValue,t}function c(e,t){return y=new s(e,t)}function u(e){return L?L:(L=d(y),L.oldValue=e,L)}function l(){y=L=void 0}function h(e){return e===L||e===y}function m(e,t){return e===t?e:L&&h(e)?L:null}function p(e,t,n){this.observer=e,this.target=t,this.options=n,this.transientObservedNodes=[]}if(!e.JsMutationObserver){var f,v=new WeakMap;if(/Trident|Edge/.test(navigator.userAgent))f=setTimeout;else if(window.setImmediate)f=window.setImmediate;else{var w=[],b=String(Math.random());window.addEventListener("message",function(e){if(e.data===b){var t=w;w=[],t.forEach(function(e){e()})}}),f=function(e){w.push(e),window.postMessage(b,"*")}}var g=!1,E=[],_=0;a.prototype={observe:function(e,t){if(e=n(e),!t.childList&&!t.attributes&&!t.characterData||t.attributeOldValue&&!t.attributes||t.attributeFilter&&t.attributeFilter.length&&!t.attributes||t.characterDataOldValue&&!t.characterData)throw new SyntaxError;var r=v.get(e);r||v.set(e,r=[]);for(var o,i=0;i<r.length;i++)if(r[i].observer===this){o=r[i],o.removeListeners(),o.options=t;break}o||(o=new p(this,e,t),r.push(o),this.nodes_.push(e)),o.addListeners()},disconnect:function(){this.nodes_.forEach(function(e){for(var t=v.get(e),n=0;n<t.length;n++){var r=t[n];if(r.observer===this){r.removeListeners(),t.splice(n,1);break}}},this),this.records_=[]},takeRecords:function(){var e=this.records_;return this.records_=[],e}};var y,L;p.prototype={enqueue:function(e){var n=this.observer.records_,r=n.length;if(n.length>0){var o=n[r-1],i=m(o,e);if(i)return void(n[r-1]=i)}else t(this.observer);n[r]=e},addListeners:function(){this.addListeners_(this.target)},addListeners_:function(e){var t=this.options;t.attributes&&e.addEventListener("DOMAttrModified",this,!0),t.characterData&&e.addEventListener("DOMCharacterDataModified",this,!0),t.childList&&e.addEventListener("DOMNodeInserted",this,!0),(t.childList||t.subtree)&&e.addEventListener("DOMNodeRemoved",this,!0)},removeListeners:function(){this.removeListeners_(this.target)},removeListeners_:function(e){var t=this.options;t.attributes&&e.removeEventListener("DOMAttrModified",this,!0),t.characterData&&e.removeEventListener("DOMCharacterDataModified",this,!0),t.childList&&e.removeEventListener("DOMNodeInserted",this,!0),(t.childList||t.subtree)&&e.removeEventListener("DOMNodeRemoved",this,!0)},addTransientObserver:function(e){if(e!==this.target){this.addListeners_(e),this.transientObservedNodes.push(e);var t=v.get(e);t||v.set(e,t=[]),t.push(this)}},removeTransientObservers:function(){var e=this.transientObservedNodes;this.transientObservedNodes=[],e.forEach(function(e){this.removeListeners_(e);for(var t=v.get(e),n=0;n<t.length;n++)if(t[n]===this){t.splice(n,1);break}},this)},handleEvent:function(e){switch(e.stopImmediatePropagation(),e.type){case"DOMAttrModified":var t=e.attrName,n=e.relatedNode.namespaceURI,r=e.target,o=new c("attributes",r);o.attributeName=t,o.attributeNamespace=n;var a=e.attrChange===MutationEvent.ADDITION?null:e.prevValue;i(r,function(e){return!e.attributes||e.attributeFilter&&e.attributeFilter.length&&-1===e.attributeFilter.indexOf(t)&&-1===e.attributeFilter.indexOf(n)?void 0:e.attributeOldValue?u(a):o});break;case"DOMCharacterDataModified":var r=e.target,o=c("characterData",r),a=e.prevValue;i(r,function(e){return e.characterData?e.characterDataOldValue?u(a):o:void 0});break;case"DOMNodeRemoved":this.addTransientObserver(e.target);case"DOMNodeInserted":var s,d,h=e.target;"DOMNodeInserted"===e.type?(s=[h],d=[]):(s=[],d=[h]);var m=h.previousSibling,p=h.nextSibling,o=c("childList",e.target.parentNode);o.addedNodes=s,o.removedNodes=d,o.previousSibling=m,o.nextSibling=p,i(e.relatedNode,function(e){return e.childList?o:void 0})}l()}},e.JsMutationObserver=a,e.MutationObserver||(e.MutationObserver=a,a._isPolyfilled=!0)}}(self),function(e){"use strict";if(!window.performance){var t=Date.now();window.performance={now:function(){return Date.now()-t}}}window.requestAnimationFrame||(window.requestAnimationFrame=function(){var e=window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame;return e?function(t){return e(function(){t(performance.now())})}:function(e){return window.setTimeout(e,1e3/60)}}()),window.cancelAnimationFrame||(window.cancelAnimationFrame=function(){return window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame||function(e){clearTimeout(e)}}());var n=function(){var e=document.createEvent("Event");return e.initEvent("foo",!0,!0),e.preventDefault(),e.defaultPrevented}();if(!n){var r=Event.prototype.preventDefault;Event.prototype.preventDefault=function(){this.cancelable&&(r.call(this),Object.defineProperty(this,"defaultPrevented",{get:function(){return!0},configurable:!0}))}}var o=/Trident/.test(navigator.userAgent);if((!window.CustomEvent||o&&"function"!=typeof window.CustomEvent)&&(window.CustomEvent=function(e,t){t=t||{};var n=document.createEvent("CustomEvent");return n.initCustomEvent(e,Boolean(t.bubbles),Boolean(t.cancelable),t.detail),n},window.CustomEvent.prototype=window.Event.prototype),!window.Event||o&&"function"!=typeof window.Event){var i=window.Event;window.Event=function(e,t){t=t||{};var n=document.createEvent("Event");return n.initEvent(e,Boolean(t.bubbles),Boolean(t.cancelable)),n},window.Event.prototype=i.prototype}}(window.WebComponents),window.HTMLImports=window.HTMLImports||{flags:{}},function(e){function t(e,t){t=t||p,r(function(){i(e,t)},t)}function n(e){return"complete"===e.readyState||e.readyState===w}function r(e,t){if(n(t))e&&e();else{var o=function(){"complete"!==t.readyState&&t.readyState!==w||(t.removeEventListener(b,o),r(e,t))};t.addEventListener(b,o)}}function o(e){e.target.__loaded=!0}function i(e,t){function n(){d==c&&e&&e({allImports:s,loadedImports:u,errorImports:l})}function r(e){o(e),u.push(this),d++,n()}function i(e){l.push(this),d++,n()}var s=t.querySelectorAll("link[rel=import]"),d=0,c=s.length,u=[],l=[];if(c)for(var h,m=0;c>m&&(h=s[m]);m++)a(h)?(u.push(this),d++,n()):(h.addEventListener("load",r),h.addEventListener("error",i));else n()}function a(e){return l?e.__loaded||e["import"]&&"loading"!==e["import"].readyState:e.__importParsed}function s(e){for(var t,n=0,r=e.length;r>n&&(t=e[n]);n++)d(t)&&c(t)}function d(e){return"link"===e.localName&&"import"===e.rel}function c(e){var t=e["import"];t?o({target:e}):(e.addEventListener("load",o),e.addEventListener("error",o))}var u="import",l=Boolean(u in document.createElement("link")),h=Boolean(window.ShadowDOMPolyfill),m=function(e){return h?window.ShadowDOMPolyfill.wrapIfNeeded(e):e},p=m(document),f={get:function(){var e=window.HTMLImports.currentScript||document.currentScript||("complete"!==document.readyState?document.scripts[document.scripts.length-1]:null);return m(e)},configurable:!0};Object.defineProperty(document,"_currentScript",f),Object.defineProperty(p,"_currentScript",f);var v=/Trident/.test(navigator.userAgent),w=v?"complete":"interactive",b="readystatechange";l&&(new MutationObserver(function(e){for(var t,n=0,r=e.length;r>n&&(t=e[n]);n++)t.addedNodes&&s(t.addedNodes)}).observe(document.head,{childList:!0}),function(){if("loading"===document.readyState)for(var e,t=document.querySelectorAll("link[rel=import]"),n=0,r=t.length;r>n&&(e=t[n]);n++)c(e)}()),t(function(e){window.HTMLImports.ready=!0,window.HTMLImports.readyTime=(new Date).getTime();var t=p.createEvent("CustomEvent");t.initCustomEvent("HTMLImportsLoaded",!0,!0,e),p.dispatchEvent(t)}),e.IMPORT_LINK_TYPE=u,e.useNative=l,e.rootDocument=p,e.whenReady=t,e.isIE=v}(window.HTMLImports),function(e){var t=[],n=function(e){t.push(e)},r=function(){t.forEach(function(t){t(e)})};e.addModule=n,e.initializeModules=r}(window.HTMLImports),window.HTMLImports.addModule(function(e){var t=/(url\()([^)]*)(\))/g,n=/(@import[\s]+(?!url\())([^;]*)(;)/g,r={resolveUrlsInStyle:function(e,t){var n=e.ownerDocument,r=n.createElement("a");return e.textContent=this.resolveUrlsInCssText(e.textContent,t,r),e},resolveUrlsInCssText:function(e,r,o){var i=this.replaceUrls(e,o,r,t);return i=this.replaceUrls(i,o,r,n)},replaceUrls:function(e,t,n,r){return e.replace(r,function(e,r,o,i){var a=o.replace(/["']/g,"");return n&&(a=new URL(a,n).href),t.href=a,a=t.href,r+"'"+a+"'"+i})}};e.path=r}),window.HTMLImports.addModule(function(e){var t={async:!0,ok:function(e){return e.status>=200&&e.status<300||304===e.status||0===e.status},load:function(n,r,o){var i=new XMLHttpRequest;return(e.flags.debug||e.flags.bust)&&(n+="?"+Math.random()),i.open("GET",n,t.async),i.addEventListener("readystatechange",function(e){if(4===i.readyState){var n=null;try{var a=i.getResponseHeader("Location");a&&(n="/"===a.substr(0,1)?location.origin+a:a)}catch(e){console.error(e.message)}r.call(o,!t.ok(i)&&i,i.response||i.responseText,n)}}),i.send(),i},loadDocument:function(e,t,n){this.load(e,t,n).responseType="document"}};e.xhr=t}),window.HTMLImports.addModule(function(e){var t=e.xhr,n=e.flags,r=function(e,t){this.cache={},this.onload=e,this.oncomplete=t,this.inflight=0,this.pending={}};r.prototype={addNodes:function(e){this.inflight+=e.length;for(var t,n=0,r=e.length;r>n&&(t=e[n]);n++)this.require(t);this.checkDone()},addNode:function(e){this.inflight++,this.require(e),this.checkDone()},require:function(e){var t=e.src||e.href;e.__nodeUrl=t,this.dedupe(t,e)||this.fetch(t,e)},dedupe:function(e,t){if(this.pending[e])return this.pending[e].push(t),!0;return this.cache[e]?(this.onload(e,t,this.cache[e]),this.tail(),!0):(this.pending[e]=[t],!1)},fetch:function(e,r){if(n.load&&console.log("fetch",e,r),e)if(e.match(/^data:/)){var o=e.split(","),i=o[0],a=o[1];a=i.indexOf(";base64")>-1?atob(a):decodeURIComponent(a),setTimeout(function(){this.receive(e,r,null,a)}.bind(this),0)}else{var s=function(t,n,o){this.receive(e,r,t,n,o)}.bind(this);t.load(e,s)}else setTimeout(function(){this.receive(e,r,{error:"href must be specified"},null)}.bind(this),0)},receive:function(e,t,n,r,o){this.cache[e]=r;for(var i,a=this.pending[e],s=0,d=a.length;d>s&&(i=a[s]);s++)this.onload(e,i,r,n,o),this.tail();this.pending[e]=null},tail:function(){--this.inflight,this.checkDone()},checkDone:function(){this.inflight||this.oncomplete()}},e.Loader=r}),window.HTMLImports.addModule(function(e){var t=function(e){this.addCallback=e,this.mo=new MutationObserver(this.handler.bind(this))};t.prototype={handler:function(e){for(var t,n=0,r=e.length;r>n&&(t=e[n]);n++)"childList"===t.type&&t.addedNodes.length&&this.addedNodes(t.addedNodes)},addedNodes:function(e){this.addCallback&&this.addCallback(e);for(var t,n=0,r=e.length;r>n&&(t=e[n]);n++)t.children&&t.children.length&&this.addedNodes(t.children)},observe:function(e){this.mo.observe(e,{childList:!0,subtree:!0})}},e.Observer=t}),window.HTMLImports.addModule(function(e){function t(e){return"link"===e.localName&&e.rel===u}function n(e){var t=r(e);return"data:text/javascript;charset=utf-8,"+encodeURIComponent(t)}function r(e){return e.textContent+o(e)}function o(e){var t=e.ownerDocument;t.__importedScripts=t.__importedScripts||0;var n=e.ownerDocument.baseURI,r=t.__importedScripts?"-"+t.__importedScripts:"";return t.__importedScripts++,"\n//# sourceURL="+n+r+".js\n"}function i(e){var t=e.ownerDocument.createElement("style");return t.textContent=e.textContent,a.resolveUrlsInStyle(t),t}var a=e.path,s=e.rootDocument,d=e.flags,c=e.isIE,u=e.IMPORT_LINK_TYPE,l="link[rel="+u+"]",h={documentSelectors:l,importsSelectors:[l,"link[rel=stylesheet]:not([type])","style:not([type])","script:not([type])",'script[type="application/javascript"]','script[type="text/javascript"]'].join(","),map:{link:"parseLink",script:"parseScript",style:"parseStyle"},dynamicElements:[],parseNext:function(){var e=this.nextToParse();e&&this.parse(e)},parse:function(e){if(this.isParsed(e))return void(d.parse&&console.log("[%s] is already parsed",e.localName));var t=this[this.map[e.localName]];t&&(this.markParsing(e),t.call(this,e))},parseDynamic:function(e,t){this.dynamicElements.push(e),t||this.parseNext()},markParsing:function(e){d.parse&&console.log("parsing",e),this.parsingElement=e},markParsingComplete:function(e){e.__importParsed=!0,this.markDynamicParsingComplete(e),e.__importElement&&(e.__importElement.__importParsed=!0,this.markDynamicParsingComplete(e.__importElement)),this.parsingElement=null,d.parse&&console.log("completed",e)},markDynamicParsingComplete:function(e){var t=this.dynamicElements.indexOf(e);t>=0&&this.dynamicElements.splice(t,1)},parseImport:function(e){if(e["import"]=e.__doc,window.HTMLImports.__importsParsingHook&&window.HTMLImports.__importsParsingHook(e),e["import"]&&(e["import"].__importParsed=!0),this.markParsingComplete(e),e.__resource&&!e.__error?e.dispatchEvent(new CustomEvent("load",{bubbles:!1})):e.dispatchEvent(new CustomEvent("error",{bubbles:!1})),e.__pending)for(var t;e.__pending.length;)t=e.__pending.shift(),t&&t({target:e});this.parseNext()},parseLink:function(e){t(e)?this.parseImport(e):(e.href=e.href,this.parseGeneric(e))},parseStyle:function(e){var t=e;e=i(e),t.__appliedElement=e,e.__importElement=t,this.parseGeneric(e)},parseGeneric:function(e){this.trackElement(e),this.addElementToDocument(e)},rootImportForElement:function(e){for(var t=e;t.ownerDocument.__importLink;)t=t.ownerDocument.__importLink;return t},addElementToDocument:function(e){var t=this.rootImportForElement(e.__importElement||e);t.parentNode.insertBefore(e,t)},trackElement:function(e,t){var n=this,r=function(o){e.removeEventListener("load",r),e.removeEventListener("error",r),t&&t(o),n.markParsingComplete(e),n.parseNext()};if(e.addEventListener("load",r),e.addEventListener("error",r),c&&"style"===e.localName){var o=!1;if(-1==e.textContent.indexOf("@import"))o=!0;else if(e.sheet){o=!0;for(var i,a=e.sheet.cssRules,s=a?a.length:0,d=0;s>d&&(i=a[d]);d++)i.type===CSSRule.IMPORT_RULE&&(o=o&&Boolean(i.styleSheet))}o&&setTimeout(function(){e.dispatchEvent(new CustomEvent("load",{bubbles:!1}))})}},parseScript:function(t){var r=document.createElement("script");r.__importElement=t,r.src=t.src?t.src:n(t),e.currentScript=t,this.trackElement(r,function(t){r.parentNode&&r.parentNode.removeChild(r),e.currentScript=null}),this.addElementToDocument(r)},nextToParse:function(){return this._mayParse=[],!this.parsingElement&&(this.nextToParseInDoc(s)||this.nextToParseDynamic())},nextToParseInDoc:function(e,n){if(e&&this._mayParse.indexOf(e)<0){this._mayParse.push(e);for(var r,o=e.querySelectorAll(this.parseSelectorsForNode(e)),i=0,a=o.length;a>i&&(r=o[i]);i++)if(!this.isParsed(r))return this.hasResource(r)?t(r)?this.nextToParseInDoc(r.__doc,r):r:void 0}return n},nextToParseDynamic:function(){return this.dynamicElements[0]},parseSelectorsForNode:function(e){var t=e.ownerDocument||e;return t===s?this.documentSelectors:this.importsSelectors},isParsed:function(e){return e.__importParsed},needsDynamicParsing:function(e){return this.dynamicElements.indexOf(e)>=0},hasResource:function(e){return!t(e)||void 0!==e.__doc}};e.parser=h,e.IMPORT_SELECTOR=l}),window.HTMLImports.addModule(function(e){function t(e){return n(e,a)}function n(e,t){return"link"===e.localName&&e.getAttribute("rel")===t}function r(e){return!!Object.getOwnPropertyDescriptor(e,"baseURI")}function o(e,t){var n=document.implementation.createHTMLDocument(a);n._URL=t;var o=n.createElement("base");o.setAttribute("href",t),n.baseURI||r(n)||Object.defineProperty(n,"baseURI",{value:t});var i=n.createElement("meta");return i.setAttribute("charset","utf-8"),n.head.appendChild(i),n.head.appendChild(o),n.body.innerHTML=e,window.HTMLTemplateElement&&HTMLTemplateElement.bootstrap&&HTMLTemplateElement.bootstrap(n),n}var i=e.flags,a=e.IMPORT_LINK_TYPE,s=e.IMPORT_SELECTOR,d=e.rootDocument,c=e.Loader,u=e.Observer,l=e.parser,h={documents:{},documentPreloadSelectors:s,importsPreloadSelectors:[s].join(","),loadNode:function(e){m.addNode(e)},loadSubtree:function(e){var t=this.marshalNodes(e);m.addNodes(t)},marshalNodes:function(e){return e.querySelectorAll(this.loadSelectorsForNode(e))},loadSelectorsForNode:function(e){var t=e.ownerDocument||e;return t===d?this.documentPreloadSelectors:this.importsPreloadSelectors},loaded:function(e,n,r,a,s){if(i.load&&console.log("loaded",e,n),n.__resource=r,n.__error=a,t(n)){var d=this.documents[e];void 0===d&&(d=a?null:o(r,s||e),d&&(d.__importLink=n,this.bootDocument(d)),this.documents[e]=d),n.__doc=d}l.parseNext()},bootDocument:function(e){this.loadSubtree(e),this.observer.observe(e),l.parseNext()},loadedAll:function(){l.parseNext()}},m=new c(h.loaded.bind(h),h.loadedAll.bind(h));if(h.observer=new u,!document.baseURI){var p={get:function(){var e=document.querySelector("base");return e?e.href:window.location.href},configurable:!0};Object.defineProperty(document,"baseURI",p),Object.defineProperty(d,"baseURI",p)}e.importer=h,e.importLoader=m}),window.HTMLImports.addModule(function(e){var t=e.parser,n=e.importer,r={added:function(e){for(var r,o,i,a,s=0,d=e.length;d>s&&(a=e[s]);s++)r||(r=a.ownerDocument,o=t.isParsed(r)),i=this.shouldLoadNode(a),i&&n.loadNode(a),this.shouldParseNode(a)&&o&&t.parseDynamic(a,i)},shouldLoadNode:function(e){return 1===e.nodeType&&o.call(e,n.loadSelectorsForNode(e))},shouldParseNode:function(e){return 1===e.nodeType&&o.call(e,t.parseSelectorsForNode(e))}};n.observer.addCallback=r.added.bind(r);var o=HTMLElement.prototype.matches||HTMLElement.prototype.matchesSelector||HTMLElement.prototype.webkitMatchesSelector||HTMLElement.prototype.mozMatchesSelector||HTMLElement.prototype.msMatchesSelector}),function(e){function t(){window.HTMLImports.importer.bootDocument(r)}var n=e.initializeModules;e.isIE;if(!e.useNative){n();var r=e.rootDocument;"complete"===document.readyState||"interactive"===document.readyState&&!window.attachEvent?t():document.addEventListener("DOMContentLoaded",t)}}(window.HTMLImports);
function init(asyncId, type, triggerAsyncId) { const parentContext = executionContextMap.get(triggerAsyncId); if (!parentContext) return; let traceArray; if (parentContext.traceArray) { traceArray = parentContext.traceArray.concat( `asyncId ${asyncId}: ${type}, eAID: ${asyncHooks.executionAsyncId()}, tAID: ${triggerAsyncId}` ); } const newContext = { context: parentContext.context }; // direct use instaed of deconstruct for performance if (traceArray) newContext.traceArray = traceArray; executionContextMap.set(asyncId, newContext); } function destroy(asyncId) { executionContextMap.delete(asyncId); } module.exports = { init, destroy };
var lcn = require("../../../../../source/lcn.js"); var rs = lcn.rolesystem; module.exports = function (game, message, params) { var actions = game.actions; var config = game.config; // Run checks, etc if (params[0] === undefined) { message.channel.send(":x: Wrong syntax! Please use `" + config["command-prefix"] + "choose <alphabet/username/nobody>` instead!"); return null; }; var to = game.getPlayerMatch(params[0]); var from = game.getPlayerById(message.author.id); if (from.misc.oracle_last_target) { var target = game.getPlayerByIdentifier(from.misc.oracle_last_target); message.channel.send(":x: Your current target is **" + target.getDisplayName() + "**. You may not change this unless your target is dead!"); return null; }; actions.delete(x => x.from === from.identifier && x.identifier === "sentinel_oracle/choose"); if (to.score < 0.7 || params[0].toLowerCase() === "nobody") { message.channel.send(":eye_in_speech_bubble: You have decided not to choose anyone tonight."); return null; }; to = to.player; if (!to.isAlive()) { message.channel.send(":x: You cannot choose a dead player!" + rs.misc.sarcasm(true)); return null; }; if (to.id === message.author.id) { message.channel.send(":x: You cannot choose yourself!" + rs.misc.sarcasm(true)); return null; } else { game.addAction("sentinel_oracle/choose", ["cycle"], { name: "Oracle-choose", expiry: 1, from: message.author.id, to: to.id }); var mention = to.getDisplayName(); }; message.channel.send(":eye_in_speech_bubble: You have decided to choose **" + mention + "** tonight."); }; module.exports.ALLOW_NONSPECIFIC = false; module.exports.PRIVATE_ONLY = true; module.exports.DEAD_CANNOT_USE = true; module.exports.ALIVE_CANNOT_USE = false; module.exports.DISALLOW_DAY = true; module.exports.DISALLOW_NIGHT = false;
import React from 'react' import { StyleSheet } from 'react-native'; const Style = StyleSheet.create({ Header : { backgroundColor: "#009AED", height: 120, alignItems: 'center', justifyContent: 'center', flexDirection: 'row', borderBottomLeftRadius: 15, borderBottomRightRadius: 15, }, Background: { marginTop: 45, height: 350, resizeMode: 'stretch', justifyContent: 'center' }, VersionSoft: { color: '#fff', fontSize: 30, marginRight: 8, marginTop: 35 }, Dados: { justifyContent: 'center', alignSelf: 'center', }, Botao: { backgroundColor: "#00abff", width: 160, height: 50, justifyContent: 'center', borderColor: '#fff', borderWidth: 3, borderRadius: 4, textAlign: 'center', borderBottomRightRadius: 15, }, TextDev: { fontWeight: 300, color: "#000", marginLeft: 4, fontSize: 18, }, BotaoTxt: { color: '#fff', fontWeight: 400, fontSize: 25, }, LinkedinLogo: { flexDirection: 'row' }, Linkedin: { width: 30, height: 30, }, GitHubLogo: { flexDirection: 'row', }, }) export default Style
import React from "react"; import { connect } from "react-redux"; import { clearItemFromCart, addItem, removeItem } from "../../redux/cart/cart.action"; import { CheckoutItemContainer, ImageContainer, TextContainer, QuantityContainer, RemoveButtonContainer } from "./checkout-item-styles"; const CheckoutItem = ({ cartItem, clearItem, addItem, removeItem }) => { const { imageUrl, name, quantity, price } = cartItem; return ( <CheckoutItemContainer> <ImageContainer> <img src={imageUrl} alt="item" /> </ImageContainer> <TextContainer>{name}</TextContainer> <QuantityContainer className="quantity"> <div onClick={() => removeItem(cartItem)}>&#10094;</div> <span>{quantity}</span> <div onClick={() => addItem(cartItem)}>&#10095;</div> </QuantityContainer> <TextContainer>{price}</TextContainer> <RemoveButtonContainer onClick={() => clearItem(cartItem)}> &#10005; </RemoveButtonContainer> </CheckoutItemContainer> ); }; const mapDispatchToProps = dispatch => ({ clearItem: item => dispatch(clearItemFromCart(item)), addItem: item => dispatch(addItem(item)), removeItem: item => dispatch(removeItem(item)) }); export default connect(null, mapDispatchToProps)(CheckoutItem);
import{createVNode as _createVNode,openBlock as _openBlock,createBlock as _createBlock}from"/modules/vue.js";export default function render(e,o){return _openBlock(),_createBlock("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor","aria-hidden":"true"},[_createVNode("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})])}
#!/usr/bin/env python # -*- coding: utf-8 -*- # Note: To use the 'upload' functionality of this file, you must: # $ pip install twine import io import os import sys from shutil import rmtree from setuptools import find_packages, setup, Command # Package meta-data. NAME = 'funannotate' DESCRIPTION = 'funannotate: eukaryotic genome annotation pipeline' URL = 'https://github.com/nextgenusfs/funannotate' EMAIL = 'nextgenusfs@gmail.com' AUTHOR = 'Jon Palmer' REQUIRES_PYTHON = '>=3.6.0, <3.9' VERSION = None # What packages are required for this module to be executed? REQUIRED = [ 'biopython', 'goatools', 'seaborn','psutil', 'pandas','matplotlib', 'natsort', 'numpy', 'requests', 'scikit-learn', 'scipy', 'distro' ] # What packages are optional? EXTRAS = { # 'fancy feature': ['django'], } # The rest you shouldn't have to touch too much :) # ------------------------------------------------ # Except, perhaps the License and Trove Classifiers! # If you do change the License, remember to change the Trove Classifier for that! here = os.path.abspath(os.path.dirname(__file__)) # Import the README and use it as the long-description. # Note: this will only work if 'README.md' is present in your MANIFEST.in file! try: with io.open(os.path.join(here, 'README.md'), encoding='utf-8') as f: long_description = '\n' + f.read() except FileNotFoundError: long_description = DESCRIPTION # Load the package's __version__.py module as a dictionary. about = {} if not VERSION: with open(os.path.join(here, NAME, '__version__.py')) as f: exec(f.read(), about) else: about['__version__'] = VERSION class UploadCommand(Command): """Support setup.py upload.""" description = 'Build and publish the package.' user_options = [] @staticmethod def status(s): """Prints things in bold.""" print(('\033[1m{0}\033[0m'.format(s))) def initialize_options(self): pass def finalize_options(self): pass def run(self): try: self.status('Removing previous builds…') rmtree(os.path.join(here, 'dist')) except OSError: pass self.status('Building Source and Wheel (universal) distribution…') os.system('{0} setup.py sdist bdist_wheel --universal'.format(sys.executable)) self.status('Uploading the package to PyPI via Twine…') os.system('twine upload dist/*') self.status('Pushing git tags…') os.system('git tag v{0}'.format(about['__version__'])) os.system('git push --tags') sys.exit() # Where the magic happens: setup( name=NAME, version=about['__version__'], description=DESCRIPTION, long_description=long_description, long_description_content_type='text/markdown', author=AUTHOR, author_email=EMAIL, python_requires=REQUIRES_PYTHON, url=URL, packages=find_packages(exclude=('tests',)), entry_points={ 'console_scripts': ['funannotate=funannotate.funannotate:main'], }, install_requires=REQUIRED, extras_require=EXTRAS, include_package_data=True, license='BSD-2', #scripts=['scripts/funannotate'], classifiers=[ # Trove classifiers # Full list: https://pypi.python.org/pypi?%3Aaction=list_classifiers 'Development Status :: 4 - Beta', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', 'Operating System :: Unix', 'Intended Audience :: Science/Research', 'Topic :: Scientific/Engineering :: Bio-Informatics' ], cmdclass={ 'upload': UploadCommand, }, )
import pkg_resources from functools import partial from lektor.pluginsystem import Plugin from lektor.context import get_ctx from lektor.assets import get_asset import os.path from pybtex.database.input import bibtex as pybibtex import pybtex.style.names.plain as myplain plain = myplain.NameStyle().format def generic_filter(x, key, searchterm): try: if x[1].fields[key].lower().find(searchterm) >= 0: return True else: return False except: return False def filterbibtex(bib, name=None, year=None, tag=None, labels=None, fname=None): if not fname: fname = bib.keys() if not labels: labels = [] # gather all labels for f in fname: allrefs = set(label[0] for label in bib[f].entries.items()) if name: myfilter = partial(generic_filter, key='author', searchterm=name) bib1 = set(label[0] for label in filter(myfilter, bib[f].entries.items())) allrefs = allrefs.intersection(bib1) if tag: myfilter = partial(generic_filter, key='tags', searchterm=tag) bib2 = set(label[0] for label in filter(myfilter, bib[f].entries.items())) allrefs = allrefs.intersection(bib2) if year: myfilter = partial(generic_filter, key='year', searchterm=year) bib3 = set(label[0] for label in filter(myfilter, bib[f].entries.items())) allrefs = allrefs.intersection(bib3) labels += list(allrefs) if type(labels) == str: labels = [labels] bibout = [] for label in labels: found = False for f in bib.keys(): entry = bib[f].entries.get(label) if entry: bibout.append([label, entry]) found = True if not found: print("bibtex warning: can't use entry", label) return bibout def parse_bibtex(bib, template, env): # change datastructure to list and add bibkey as a normal field newlist = [] for b in bib: key, value = b X = value.fields X['bibkey'] = key # what type of publication X['type'] = value.type # pretty print the names and also keep a bibtexcopy for bibtex output for k, v in value.persons.items(): X[k] = ' and '.join(plain(item).format().render_as('html') for item in v) tmp = X.get('author', '') # we want the author list formated nicely and not all the bibtex 'and's in there X['newauthor'] = ', '.join(x.strip() for x in tmp.split(' and', tmp.count('and')-1)) tmp = X.get('editor', '') X['neweditor'] = ', '.join(x.strip() for x in tmp.split(' and', tmp.count('and')-1)) # also remove all {} from the output and replace umlaute and other special characters myreplace = {'{': '', '}': '', '\\&': '&', '\\"a': '&auml;', '\\"A': '&Auml;', '\\"u': '&uuml;', '\\"U': '&Uuml;', '\\"o': '&ouml;', '\\"O': '&Ouml;'} for a, b in X.items(): if isinstance(b, str) or isinstance(b, unicode): for i, j in myreplace.items(): X[a] = X[a].replace(i, j) # save entry newlist.append(X) parsed = env.render_template(template, this=newlist) return parsed class BibtexSupportPlugin(Plugin): name = 'Bibtex-support' description = """Bibtex file support to include publication list. Multiple bibtex files and filtering by name, year, tag, and label are supported.""" def __init__(self, env, id): super().__init__(env, id) config = self.get_config() self.bibfiles = config.get('Bibtex.files', []).strip().split() self.template = config.get('Bibtex.template', 'lektor_bibtex_support_default_template.html') pkg_dir = pkg_resources.resource_filename('lektor_bibtex_support', 'templates') r = self.env.jinja_env.loader.searchpath.append(pkg_dir) self.bib_data = {} for f in self.bibfiles: # need separate parsers for each file, otherwise they get added together parser = pybibtex.Parser() self.bib_data[f] = parser.parse_file(os.path.join(env.root_path, 'assets',f)) def list_publications(self, name=None, tag=None, year=None, labels=None, fname=None): bib = filterbibtex(self.bib_data, name=name, tag=tag, year=year, labels=labels, fname=fname) return parse_bibtex(bib, self.template, self.env) def on_setup_env(self, **extra): self.env.jinja_env.globals.update( list_publications=self.list_publications )
from ajenti.api import * from ajenti.plugins import * info = PluginInfo( title='Ajenti Configurator', description='Configuration section for setting up Ajenti itself', icon='wrench', dependencies=[ PluginDependency('main') ], ) def init(): import api import configurator
/** * MIT License * * Copyright (c) 2016 InSoft Engineering / github.com/insoftpub * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import { statusCodes } from '../../constants'; import { headers } from '../config'; function allowMethods(req, res, next) { if (req.method === 'OPTIONS') { res.set('Access-Control-Allow-Methods', headers.accessControl.ALLOW_METHODS); res.sendStatus(statusCodes.OK); } else { next(); } }; export default allowMethods;
define(function(require) { var formatUtil = require('./format'); var nubmerUtil = require('./number'); var Model = require('../model/Model'); var zrUtil = require('zrender/core/util'); var each = zrUtil.each; var isObject = zrUtil.isObject; var modelUtil = {}; /** * If value is not array, then translate it to array. * @param {*} value * @return {Array} [value] or value */ modelUtil.normalizeToArray = function (value) { return value instanceof Array ? value : value == null ? [] : [value]; }; /** * Sync default option between normal and emphasis like `position` and `show` * In case some one will write code like * label: { * normal: { * show: false, * position: 'outside', * textStyle: { * fontSize: 18 * } * }, * emphasis: { * show: true * } * } * @param {Object} opt * @param {Array.<string>} subOpts */ modelUtil.defaultEmphasis = function (opt, subOpts) { if (opt) { var emphasisOpt = opt.emphasis = opt.emphasis || {}; var normalOpt = opt.normal = opt.normal || {}; // Default emphasis option from normal each(subOpts, function (subOptName) { var val = zrUtil.retrieve(emphasisOpt[subOptName], normalOpt[subOptName]); if (val != null) { emphasisOpt[subOptName] = val; } }); } }; modelUtil.LABEL_OPTIONS = ['position', 'offset', 'show', 'textStyle', 'distance', 'formatter']; /** * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}] * This helper method retieves value from data. * @param {string|number|Date|Array|Object} dataItem * @return {number|string|Date|Array.<number|string|Date>} */ modelUtil.getDataItemValue = function (dataItem) { // Performance sensitive. return dataItem && (dataItem.value == null ? dataItem : dataItem.value); }; /** * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}] * This helper method determine if dataItem has extra option besides value * @param {string|number|Date|Array|Object} dataItem */ modelUtil.isDataItemOption = function (dataItem) { return isObject(dataItem) && !(dataItem instanceof Array); // // markLine data can be array // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array)); }; /** * This helper method convert value in data. * @param {string|number|Date} value * @param {Object|string} [dimInfo] If string (like 'x'), dimType defaults 'number'. */ modelUtil.converDataValue = function (value, dimInfo) { // Performance sensitive. var dimType = dimInfo && dimInfo.type; if (dimType === 'ordinal') { return value; } if (dimType === 'time' // spead up when using timestamp && typeof value !== 'number' && value != null && value !== '-' ) { value = +nubmerUtil.parseDate(value); } // dimType defaults 'number'. // If dimType is not ordinal and value is null or undefined or NaN or '-', // parse to NaN. return (value == null || value === '') ? NaN : +value; // If string (like '-'), using '+' parse to NaN }; /** * Create a model proxy to be used in tooltip for edge data, markLine data, markPoint data. * @param {module:echarts/data/List} data * @param {Object} opt * @param {string} [opt.seriesIndex] * @param {Object} [opt.name] * @param {Object} [opt.mainType] * @param {Object} [opt.subType] */ modelUtil.createDataFormatModel = function (data, opt) { var model = new Model(); zrUtil.mixin(model, modelUtil.dataFormatMixin); model.seriesIndex = opt.seriesIndex; model.name = opt.name || ''; model.mainType = opt.mainType; model.subType = opt.subType; model.getData = function () { return data; }; return model; }; // PENDING A little ugly modelUtil.dataFormatMixin = { /** * Get params for formatter * @param {number} dataIndex * @param {string} [dataType] * @return {Object} */ getDataParams: function (dataIndex, dataType) { var data = this.getData(dataType); var rawValue = this.getRawValue(dataIndex, dataType); var rawDataIndex = data.getRawIndex(dataIndex); var name = data.getName(dataIndex, true); var itemOpt = data.getRawDataItem(dataIndex); return { componentType: this.mainType, componentSubType: this.subType, seriesType: this.mainType === 'series' ? this.subType : null, seriesIndex: this.seriesIndex, seriesId: this.id, seriesName: this.name, name: name, dataIndex: rawDataIndex, data: itemOpt, dataType: dataType, value: rawValue, color: data.getItemVisual(dataIndex, 'color'), // Param name list for mapping `a`, `b`, `c`, `d`, `e` $vars: ['seriesName', 'name', 'value'] }; }, /** * Format label * @param {number} dataIndex * @param {string} [status='normal'] 'normal' or 'emphasis' * @param {string} [dataType] * @param {number} [dimIndex] * @return {string} */ getFormattedLabel: function (dataIndex, status, dataType, dimIndex) { status = status || 'normal'; var data = this.getData(dataType); var itemModel = data.getItemModel(dataIndex); var params = this.getDataParams(dataIndex, dataType); if (dimIndex != null && (params.value instanceof Array)) { params.value = params.value[dimIndex]; } var formatter = itemModel.get(['label', status, 'formatter']); if (typeof formatter === 'function') { params.status = status; return formatter(params); } else if (typeof formatter === 'string') { return formatUtil.formatTpl(formatter, params); } }, /** * Get raw value in option * @param {number} idx * @param {string} [dataType] * @return {Object} */ getRawValue: function (idx, dataType) { var data = this.getData(dataType); var dataItem = data.getRawDataItem(idx); if (dataItem != null) { return (isObject(dataItem) && !(dataItem instanceof Array)) ? dataItem.value : dataItem; } }, /** * Should be implemented. * @param {number} dataIndex * @param {boolean} [multipleSeries=false] * @param {number} [dataType] * @return {string} tooltip string */ formatTooltip: zrUtil.noop }; /** * Mapping to exists for merge. * * @public * @param {Array.<Object>|Array.<module:echarts/model/Component>} exists * @param {Object|Array.<Object>} newCptOptions * @return {Array.<Object>} Result, like [{exist: ..., option: ...}, {}], * index of which is the same as exists. */ modelUtil.mappingToExists = function (exists, newCptOptions) { // Mapping by the order by original option (but not order of // new option) in merge mode. Because we should ensure // some specified index (like xAxisIndex) is consistent with // original option, which is easy to understand, espatially in // media query. And in most case, merge option is used to // update partial option but not be expected to change order. newCptOptions = (newCptOptions || []).slice(); var result = zrUtil.map(exists || [], function (obj, index) { return {exist: obj}; }); // Mapping by id or name if specified. each(newCptOptions, function (cptOption, index) { if (!isObject(cptOption)) { return; } // id has highest priority. for (var i = 0; i < result.length; i++) { if (!result[i].option // Consider name: two map to one. && cptOption.id != null && result[i].exist.id === cptOption.id + '' ) { result[i].option = cptOption; newCptOptions[index] = null; return; } } for (var i = 0; i < result.length; i++) { var exist = result[i].exist; if (!result[i].option // Consider name: two map to one. // Can not match when both ids exist but different. && (exist.id == null || cptOption.id == null) && cptOption.name != null && !modelUtil.isIdInner(cptOption) && !modelUtil.isIdInner(exist) && exist.name === cptOption.name + '' ) { result[i].option = cptOption; newCptOptions[index] = null; return; } } }); // Otherwise mapping by index. each(newCptOptions, function (cptOption, index) { if (!isObject(cptOption)) { return; } var i = 0; for (; i < result.length; i++) { var exist = result[i].exist; if (!result[i].option // Existing model that already has id should be able to // mapped to (because after mapping performed model may // be assigned with a id, whish should not affect next // mapping), except those has inner id. && !modelUtil.isIdInner(exist) // Caution: // Do not overwrite id. But name can be overwritten, // because axis use name as 'show label text'. // 'exist' always has id and name and we dont // need to check it. && cptOption.id == null ) { result[i].option = cptOption; break; } } if (i >= result.length) { result.push({option: cptOption}); } }); return result; }; /** * Make id and name for mapping result (result of mappingToExists) * into `keyInfo` field. * * @public * @param {Array.<Object>} Result, like [{exist: ..., option: ...}, {}], * which order is the same as exists. * @return {Array.<Object>} The input. */ modelUtil.makeIdAndName = function (mapResult) { // We use this id to hash component models and view instances // in echarts. id can be specified by user, or auto generated. // The id generation rule ensures new view instance are able // to mapped to old instance when setOption are called in // no-merge mode. So we generate model id by name and plus // type in view id. // name can be duplicated among components, which is convenient // to specify multi components (like series) by one name. // Ensure that each id is distinct. var idMap = {}; each(mapResult, function (item, index) { var existCpt = item.exist; existCpt && (idMap[existCpt.id] = item); }); each(mapResult, function (item, index) { var opt = item.option; zrUtil.assert( !opt || opt.id == null || !idMap[opt.id] || idMap[opt.id] === item, 'id duplicates: ' + (opt && opt.id) ); opt && opt.id != null && (idMap[opt.id] = item); !item.keyInfo && (item.keyInfo = {}); }); // Make name and id. each(mapResult, function (item, index) { var existCpt = item.exist; var opt = item.option; var keyInfo = item.keyInfo; if (!isObject(opt)) { return; } // name can be overwitten. Consider case: axis.name = '20km'. // But id generated by name will not be changed, which affect // only in that case: setOption with 'not merge mode' and view // instance will be recreated, which can be accepted. keyInfo.name = opt.name != null ? opt.name + '' : existCpt ? existCpt.name : '\0-'; // name may be displayed on screen, so use '-'. if (existCpt) { keyInfo.id = existCpt.id; } else if (opt.id != null) { keyInfo.id = opt.id + ''; } else { // Consider this situatoin: // optionA: [{name: 'a'}, {name: 'a'}, {..}] // optionB [{..}, {name: 'a'}, {name: 'a'}] // Series with the same name between optionA and optionB // should be mapped. var idNum = 0; do { keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++; } while (idMap[keyInfo.id]); } idMap[keyInfo.id] = item; }); }; /** * @public * @param {Object} cptOption * @return {boolean} */ modelUtil.isIdInner = function (cptOption) { return isObject(cptOption) && cptOption.id && (cptOption.id + '').indexOf('\0_ec_\0') === 0; }; /** * A helper for removing duplicate items between batchA and batchB, * and in themselves, and categorize by series. * * @param {Array.<Object>} batchA Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...] * @param {Array.<Object>} batchB Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...] * @return {Array.<Array.<Object>, Array.<Object>>} result: [resultBatchA, resultBatchB] */ modelUtil.compressBatches = function (batchA, batchB) { var mapA = {}; var mapB = {}; makeMap(batchA || [], mapA); makeMap(batchB || [], mapB, mapA); return [mapToArray(mapA), mapToArray(mapB)]; function makeMap(sourceBatch, map, otherMap) { for (var i = 0, len = sourceBatch.length; i < len; i++) { var seriesId = sourceBatch[i].seriesId; var dataIndices = modelUtil.normalizeToArray(sourceBatch[i].dataIndex); var otherDataIndices = otherMap && otherMap[seriesId]; for (var j = 0, lenj = dataIndices.length; j < lenj; j++) { var dataIndex = dataIndices[j]; if (otherDataIndices && otherDataIndices[dataIndex]) { otherDataIndices[dataIndex] = null; } else { (map[seriesId] || (map[seriesId] = {}))[dataIndex] = 1; } } } } function mapToArray(map, isData) { var result = []; for (var i in map) { if (map.hasOwnProperty(i) && map[i] != null) { if (isData) { result.push(+i); } else { var dataIndices = mapToArray(map[i], true); dataIndices.length && result.push({seriesId: i, dataIndex: dataIndices}); } } } return result; } }; /** * @param {module:echarts/data/List} data * @param {Object} payload Contains dataIndex (means rawIndex) / dataIndexInside / name * each of which can be Array or primary type. * @return {number|Array.<number>} dataIndex If not found, return undefined/null. */ modelUtil.queryDataIndex = function (data, payload) { if (payload.dataIndexInside != null) { return payload.dataIndexInside; } else if (payload.dataIndex != null) { return zrUtil.isArray(payload.dataIndex) ? zrUtil.map(payload.dataIndex, function (value) { return data.indexOfRawIndex(value); }) : data.indexOfRawIndex(payload.dataIndex); } else if (payload.name != null) { return zrUtil.isArray(payload.name) ? zrUtil.map(payload.name, function (value) { return data.indexOfName(value); }) : data.indexOfName(payload.name); } }; /** * Enable property storage to any host object. * Notice: Serialization is not supported. * * For example: * var get = modelUitl.makeGetter(); * * function some(hostObj) { * get(hostObj)._someProperty = 1212; * ... * } * * @return {Function} */ modelUtil.makeGetter = (function () { var index = 0; return function () { var key = '\0__ec_prop_getter_' + index++; return function (hostObj) { return hostObj[key] || (hostObj[key] = {}); }; }; })(); /** * @param {module:echarts/model/Global} ecModel * @param {string|Object} finder * If string, e.g., 'geo', means {geoIndex: 0}. * If Object, could contain some of these properties below: * { * seriesIndex, seriesId, seriesName, * geoIndex, geoId, geoName, * bmapIndex, bmapId, bmapName, * xAxisIndex, xAxisId, xAxisName, * yAxisIndex, yAxisId, yAxisName, * gridIndex, gridId, gridName, * ... (can be extended) * } * Each properties can be number|string|Array.<number>|Array.<string> * For example, a finder could be * { * seriesIndex: 3, * geoId: ['aa', 'cc'], * gridName: ['xx', 'rr'] * } * xxxIndex can be set as 'all' (means all xxx) or 'none' (means not specify) * If nothing or null/undefined specified, return nothing. * @param {Object} [opt] * @param {string} [opt.defaultMainType] * @param {Array.<string>} [opt.includeMainTypes] * @return {Object} result like: * { * seriesModels: [seriesModel1, seriesModel2], * seriesModel: seriesModel1, // The first model * geoModels: [geoModel1, geoModel2], * geoModel: geoModel1, // The first model * ... * } */ modelUtil.parseFinder = function (ecModel, finder, opt) { if (zrUtil.isString(finder)) { var obj = {}; obj[finder + 'Index'] = 0; finder = obj; } var defaultMainType = opt && opt.defaultMainType; if (defaultMainType && !has(finder, defaultMainType + 'Index') && !has(finder, defaultMainType + 'Id') && !has(finder, defaultMainType + 'Name') ) { finder[defaultMainType + 'Index'] = 0; } var result = {}; each(finder, function (value, key) { var value = finder[key]; // Exclude 'dataIndex' and other illgal keys. if (key === 'dataIndex' || key === 'dataIndexInside') { result[key] = value; return; } var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || []; var mainType = parsedKey[1]; var queryType = (parsedKey[2] || '').toLowerCase(); if (!mainType || !queryType || value == null || (queryType === 'index' && value === 'none') || (opt && opt.includeMainTypes && zrUtil.indexOf(opt.includeMainTypes, mainType) < 0) ) { return; } var queryParam = {mainType: mainType}; if (queryType !== 'index' || value !== 'all') { queryParam[queryType] = value; } var models = ecModel.queryComponents(queryParam); result[mainType + 'Models'] = models; result[mainType + 'Model'] = models[0]; }); return result; }; function has(obj, prop) { return obj && obj.hasOwnProperty(prop); } return modelUtil; });
""" The filehelp-system allows for defining help files outside of the game. These will be treated as non-command help entries and displayed in the same way as help entries created using the `sethelp` default command. After changing an entry on-disk you need to reload the server to have the change show in-game. An filehelp file is a regular python module with dicts representing each help entry. If a list `HELP_ENTRY_DICTS` is found in the module, this should be a list of dicts. Otherwise *all* top-level dicts in the module will be assumed to be a help-entry dict. Each help-entry dict is on the form :: {'key': <str>, 'text': <str>, 'category': <str>, # optional, otherwise settings.DEFAULT_HELP_CATEGORY 'aliases': <list>, # optional 'locks': <str>} # optional, use access-type 'view'. Default is view:all() The `text`` should be formatted on the same form as other help entry-texts and can contain ``# subtopics`` as normal. New help-entry modules are added to the system by providing the python-path to the module to `settings.FILE_HELP_ENTRY_MODULES`. Note that if same-key entries are added, entries in latter modules will override that of earlier ones. Use `settings.DEFAULT_HELP_CATEGORY`` to customize what category is used if not set explicitly. An example of the contents of a module: :: help_entry1 = { "key": "The Gods", # case-insensitive, also partial-matching ('gods') works "aliases": ['pantheon', 'religion'], "category": "Lore", "locks": "view:all()", # this is optional unless restricting access "text": ''' The gods formed the world ... # Subtopics ## Pantheon ... ### God of love ... ### God of war ... ''' } HELP_ENTRY_DICTS = [ help_entry1, ... ] ---- """ from dataclasses import dataclass from django.conf import settings from django.urls import reverse from django.utils.text import slugify from evennia.utils.utils import ( variable_from_module, make_iter, all_from_module) from evennia.utils import logger from evennia.utils.utils import lazy_property from evennia.locks.lockhandler import LockHandler _DEFAULT_HELP_CATEGORY = settings.DEFAULT_HELP_CATEGORY @dataclass class FileHelpEntry: """ Represents a help entry read from file. This mimics the api of the database-bound HelpEntry so that they can be used interchangeably in the help command. """ key: str aliases: list help_category: str entrytext: str lock_storage: str @property def search_index_entry(self): """ Property for easily retaining a search index entry for this object. """ return { "key": self.key, "aliases": " ".join(self.aliases), "category": self.help_category, "no_prefix": "", "tags": "", "locks": "", "text": self.entrytext, } def __str__(self): return self.key def __repr__(self): return f"<FileHelpEntry {self.key}>" @lazy_property def locks(self): return LockHandler(self) def web_get_detail_url(self): """ Returns the URI path for a View that allows users to view details for this object. ex. Oscar (Character) = '/characters/oscar/1/' For this to work, the developer must have defined a named view somewhere in urls.py that follows the format 'modelname-action', so in this case a named view of 'character-detail' would be referenced by this method. ex. :: url(r'characters/(?P<slug>[\w\d\-]+)/(?P<pk>[0-9]+)/$', CharDetailView.as_view(), name='character-detail') If no View has been created and defined in urls.py, returns an HTML anchor. This method is naive and simply returns a path. Securing access to the actual view and limiting who can view this object is the developer's responsibility. Returns: path (str): URI path to object detail page, if defined. """ try: return reverse( 'help-entry-detail', kwargs={"category": slugify(self.help_category), "topic": slugify(self.key)}, ) except Exception: return "#" def web_get_admin_url(self): """ Returns the URI path for the Django Admin page for this object. ex. Account#1 = '/admin/accounts/accountdb/1/change/' Returns: path (str): URI path to Django Admin page for object. """ return False def access(self, accessing_obj, access_type="view", default=True): """ Determines if another object has permission to access this help entry. Args: accessing_obj (Object or Account): Entity trying to access this one. access_type (str): type of access sought. default (bool): What to return if no lock of `access_type` was found. """ return self.locks.check(accessing_obj, access_type=access_type, default=default) class FileHelpStorageHandler: """ This reads and stores help entries for quick access. By default it reads modules from `settings.FILE_HELP_ENTRY_MODULES`. Note that this is not meant to any searching/lookup - that is all handled by the help command. """ def __init__(self, help_file_modules=settings.FILE_HELP_ENTRY_MODULES): """ Initialize the storage. """ self.help_file_modules = [str(part).strip() for part in make_iter(help_file_modules)] self.help_entries = [] self.help_entries_dict = {} self.load() def load(self): """ Load/reload file-based help-entries from file. """ loaded_help_dicts = [] for module_or_path in self.help_file_modules: help_dict_list = variable_from_module( module_or_path, variable="HELP_ENTRY_DICTS" ) if not help_dict_list: help_dict_list = [ dct for dct in all_from_module(module_or_path).values() if isinstance(dct, dict)] if help_dict_list: loaded_help_dicts.extend(help_dict_list) else: logger.log_err(f"Could not find file-help module {module_or_path} (skipping).") # validate and parse dicts into FileEntryHelp objects and make sure they are unique-by-key # by letting latter added ones override earlier ones. unique_help_entries = {} for dct in loaded_help_dicts: key = dct.get('key').lower().strip() category = dct.get('category', _DEFAULT_HELP_CATEGORY).strip() aliases = list(dct.get('aliases', [])) entrytext = dct.get('text', '') locks = dct.get('locks', '') if not key and entrytext: logger.error(f"Cannot load file-help-entry (missing key or text): {dct}") continue unique_help_entries[key] = FileHelpEntry( key=key, help_category=category, aliases=aliases, lock_storage=locks, entrytext=entrytext) self.help_entries_dict = unique_help_entries self.help_entries = list(unique_help_entries.values()) def all(self, return_dict=False): """ Get all help entries. Args: return_dict (bool): Return a dict ``{key: FileHelpEntry,...}``. Otherwise, return a list of ``FileHelpEntry`. Returns: dict or list: Depending on the setting of ``return_dict``. """ return self.help_entries_dict if return_dict else self.help_entries # singleton to hold the loaded help entries FILE_HELP_ENTRIES = FileHelpStorageHandler()
import factory from factory.django import DjangoModelFactory from factory import fuzzy from accounts.factories import UserFactory from .models import Activity class ActivityFactory(DjangoModelFactory): class Meta: model = Activity actor = factory.SubFactory(UserFactory) verb = fuzzy.FuzzyChoice(Activity.VERB_CHOICES)
'use strict'; var conf = require('./gulp.conf'); var _ = require('lodash'); module.exports = function () { return _.defaultsDeep(conf.defaults.browserSync, { server: { baseDir: [conf.paths.dist] }, open: false, reloadOnRestart: true, notify: false, port: 3000, ui: { port: 3001 } }); };
/* * File : dfs_romfs.c * This file is part of Device File System in RT-Thread RTOS * COPYRIGHT (C) 2004-2011, RT-Thread Development Team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Change Logs: * Date Author Notes */ #include <rtthread.h> #include <dfs.h> #include <dfs_fs.h> #include "dfs_romfs.h" int dfs_romfs_mount(struct dfs_filesystem *fs, unsigned long rwflag, const void *data) { struct romfs_dirent *root_dirent; if (data == RT_NULL) return -DFS_STATUS_EIO; root_dirent = (struct romfs_dirent *)data; fs->data = root_dirent; return DFS_STATUS_OK; } int dfs_romfs_unmount(struct dfs_filesystem *fs) { return DFS_STATUS_OK; } int dfs_romfs_ioctl(struct dfs_fd *file, int cmd, void *args) { return -DFS_STATUS_EIO; } rt_inline int check_dirent(struct romfs_dirent *dirent) { if ((dirent->type != ROMFS_DIRENT_FILE && dirent->type != ROMFS_DIRENT_DIR) || dirent->size == ~0) return -1; return 0; } struct romfs_dirent *dfs_romfs_lookup(struct romfs_dirent *root_dirent, const char *path, rt_size_t *size) { rt_size_t index, found; const char *subpath, *subpath_end; struct romfs_dirent *dirent; rt_size_t dirent_size; /* Check the root_dirent. */ if (check_dirent(root_dirent) != 0) return RT_NULL; if (path[0] == '/' && path[1] == '\0') { *size = root_dirent->size; return root_dirent; } /* goto root directy entries */ dirent = (struct romfs_dirent *)root_dirent->data; dirent_size = root_dirent->size; /* get the end position of this subpath */ subpath_end = path; /* skip /// */ while (*subpath_end && *subpath_end == '/') subpath_end ++; subpath = subpath_end; while ((*subpath_end != '/') && *subpath_end) subpath_end ++; while (dirent != RT_NULL) { found = 0; /* search in folder */ for (index = 0; index < dirent_size; index ++) { if (check_dirent(&dirent[index]) != 0) return RT_NULL; if (rt_strncmp(dirent[index].name, subpath, (subpath_end - subpath)) == 0) { dirent_size = dirent[index].size; /* skip /// */ while (*subpath_end && *subpath_end == '/') subpath_end ++; subpath = subpath_end; while ((*subpath_end != '/') && *subpath_end) subpath_end ++; if (!(*subpath)) { *size = dirent_size; return &dirent[index]; } if (dirent[index].type == ROMFS_DIRENT_DIR) { /* enter directory */ dirent = (struct romfs_dirent*)dirent[index].data; found = 1; break; } else { /* return file dirent */ if (subpath != RT_NULL) break; /* not the end of path */ return &dirent[index]; } } } if (!found) break; /* not found */ } /* not found */ return RT_NULL; } int dfs_romfs_read(struct dfs_fd *file, void *buf, rt_size_t count) { rt_size_t length; struct romfs_dirent *dirent; dirent = (struct romfs_dirent *)file->data; RT_ASSERT(dirent != RT_NULL); if (check_dirent(dirent) != 0) { return -DFS_STATUS_EIO; } if (count < file->size - file->pos) length = count; else length = file->size - file->pos; if (length > 0) memcpy(buf, &(dirent->data[file->pos]), length); /* update file current position */ file->pos += length; return length; } int dfs_romfs_lseek(struct dfs_fd *file, rt_off_t offset) { if (offset <= file->size) { file->pos = offset; return file->pos; } return -DFS_STATUS_EIO; } int dfs_romfs_close(struct dfs_fd *file) { file->data = RT_NULL; return DFS_STATUS_OK; } int dfs_romfs_open(struct dfs_fd *file) { rt_size_t size; struct romfs_dirent *dirent; struct romfs_dirent *root_dirent; root_dirent = (struct romfs_dirent *)file->fs->data; if (check_dirent(root_dirent) != 0) return -DFS_STATUS_EIO; if (file->flags & (DFS_O_CREAT | DFS_O_WRONLY | DFS_O_APPEND | DFS_O_TRUNC | DFS_O_RDWR)) return -DFS_STATUS_EINVAL; dirent = dfs_romfs_lookup(root_dirent, file->path, &size); if (dirent == RT_NULL) return -DFS_STATUS_ENOENT; /* entry is a directory file type */ if (dirent->type == ROMFS_DIRENT_DIR) { if (!(file->flags & DFS_O_DIRECTORY)) return -DFS_STATUS_ENOENT; } else { /* entry is a file, but open it as a directory */ if (file->flags & DFS_O_DIRECTORY) return -DFS_STATUS_ENOENT; } file->data = dirent; file->size = size; file->pos = 0; return DFS_STATUS_OK; } int dfs_romfs_stat(struct dfs_filesystem *fs, const char *path, struct stat *st) { rt_size_t size; struct romfs_dirent *dirent; struct romfs_dirent *root_dirent; root_dirent = (struct romfs_dirent *)fs->data; dirent = dfs_romfs_lookup(root_dirent, path, &size); if (dirent == RT_NULL) return -DFS_STATUS_ENOENT; st->st_dev = 0; st->st_mode = DFS_S_IFREG | DFS_S_IRUSR | DFS_S_IRGRP | DFS_S_IROTH | DFS_S_IWUSR | DFS_S_IWGRP | DFS_S_IWOTH; if (dirent->type == ROMFS_DIRENT_DIR) { st->st_mode &= ~DFS_S_IFREG; st->st_mode |= DFS_S_IFDIR | DFS_S_IXUSR | DFS_S_IXGRP | DFS_S_IXOTH; } st->st_size = dirent->size; st->st_mtime = 0; st->st_blksize = 512; return DFS_STATUS_OK; } int dfs_romfs_getdents(struct dfs_fd *file, struct dirent *dirp, rt_uint32_t count) { rt_size_t index; const char *name; struct dirent *d; struct romfs_dirent *dirent, *sub_dirent; dirent = (struct romfs_dirent *)file->data; if (check_dirent(dirent) != 0) return -DFS_STATUS_EIO; RT_ASSERT(dirent->type == ROMFS_DIRENT_DIR); /* enter directory */ dirent = (struct romfs_dirent *)dirent->data; /* make integer count */ count = (count / sizeof(struct dirent)); if (count == 0) return -DFS_STATUS_EINVAL; index = 0; for (index = 0; index < count && file->pos < file->size; index ++) { d = dirp + index; sub_dirent = &dirent[file->pos]; name = sub_dirent->name; /* fill dirent */ if (sub_dirent->type == ROMFS_DIRENT_DIR) d->d_type = DFS_DT_DIR; else d->d_type = DFS_DT_REG; d->d_namlen = rt_strlen(name); d->d_reclen = (rt_uint16_t)sizeof(struct dirent); rt_strncpy(d->d_name, name, rt_strlen(name) + 1); /* move to next position */ ++ file->pos; } return index * sizeof(struct dirent); } static const struct dfs_filesystem_operation _romfs = { "rom", DFS_FS_FLAG_DEFAULT, dfs_romfs_mount, dfs_romfs_unmount, RT_NULL, RT_NULL, dfs_romfs_open, dfs_romfs_close, dfs_romfs_ioctl, dfs_romfs_read, RT_NULL, RT_NULL, dfs_romfs_lseek, dfs_romfs_getdents, RT_NULL, dfs_romfs_stat, RT_NULL, }; int dfs_romfs_init(void) { /* register rom file system */ dfs_register(&_romfs); return 0; } INIT_FS_EXPORT(dfs_romfs_init);
// Phantombuster configuration { "phantombuster command: nodejs" "phantombuster package: 5" "phantombuster dependencies: lib-StoreUtilities.js, lib-WebSearch.js" const { URL } = require("url") const Buster = require("phantombuster") const buster = new Buster() const WebSearch = require("./lib-WebSearch") const userAgent = WebSearch.getRandomUa() const Nick = require("nickjs") const nick = new Nick({ loadImages: true, userAgent, printPageErrors: false, printResourceErrors: false, printNavigation: false, printAborts: false, debug: false, timeout: 30000, // randomize viewport width: (1180 + Math.round(Math.random() * 200)), // 1180 <=> 1380 height: (700 + Math.round(Math.random() * 200)), // 700 <=> 900 }) const StoreUtilities = require("./lib-StoreUtilities") const utils = new StoreUtilities(nick, buster) const DEFAULT_DB_NAME = "result" let db // } /** * @description Function used to remove all GET params and subdomains in a LinkedIn URL * @param {String} url - URL to normalize * @return {String} Normalized URL, if an error occured, returns the original URL */ const normalizeLinkedInURL = url => { try { let parsedUrl = new URL(url) parsedUrl.searchParams.forEach((value, name) => parsedUrl.searchParams.delete(name)) if (parsedUrl.hostname !== "www.linkedin.com") { parsedUrl.hostname = "www.linkedin.com" } return parsedUrl.toString() } catch (err) { return url } } ;(async () => { const tab = await nick.newTab() const webSearch = new WebSearch(tab, buster, null, null, utils) let {spreadsheetUrl, queries, columnName, csvName, numberOfLinesToProcess} = utils.validateArguments() const toReturn = [] let i = 1 if (!csvName) { csvName = DEFAULT_DB_NAME } if (spreadsheetUrl) { if (utils.isUrl(spreadsheetUrl)) { queries = await utils.getDataFromCsv2(spreadsheetUrl, columnName) } else { queries = [ spreadsheetUrl ] } } else if (typeof(queries) === "string") { queries = [queries] } db = await utils.getDb(`${csvName}.csv`) queries = queries.filter(el => db.findIndex(line => line.query === el) < 0) queries = queries.filter(str => str) // removing empty lines queries = Array.from(new Set(queries)) if (numberOfLinesToProcess) { queries = queries.slice(0, numberOfLinesToProcess) } if (queries.length < 1) { utils.log("Input is empty OR all queries are already scraped", "warning") nick.exit(0) } console.log(`Lines to process: ${JSON.stringify(queries.slice(0, 500), null, 4)}`) for (const one of queries) { buster.progressHint(i / queries.length, `${one} (${i} / ${queries.length})`) const timeLeft = await utils.checkTimeLeft() if (!timeLeft.timeLeft) { utils.log(timeLeft.message, "warning") break } utils.log(`Searching for ${one} ...`, "loading") let search = await webSearch.search("linkedin.com " + one) if (search.error === "No more search engines available") { utils.log("No more search engines available, please retry later.", "warning") break } let link = null let description let title for (const res of search.results) { if (res.link.indexOf("linkedin.com/in/") > 0) { link = normalizeLinkedInURL(res.link) break } } const foundData = { query: one, timestamp: (new Date()).toISOString() } if (link) { foundData.linkedinUrl = link if (description) { foundData.description = description } if (title) { foundData.title = title } utils.log(`Got ${link} for ${one} (${search.codename})`, "done") } else { foundData.error = "No result found" utils.log(`No result for ${one} (${search.codename})`, "done") } toReturn.push(foundData) i++ } db.push(...toReturn) await tab.close() await utils.saveResults(toReturn, db, csvName, null, false) nick.exit() })() .catch(err => { utils.log(err, "error") nick.exit(1) })
// license:BSD-3-Clause // copyright-holders:Sergey Svishchev /********************************************************************** Poisk-1 HDC device (model B942) **********************************************************************/ #ifndef MAME_BUS_ISA_P1_HDC_H #define MAME_BUS_ISA_P1_HDC_H #pragma once #include "isa.h" #include "imagedev/harddriv.h" #include "machine/wd2010.h" //************************************************************************** // TYPE DEFINITIONS //************************************************************************** class p1_hdc_device : public device_t, public device_isa8_card_interface { public: // construction/destruction p1_hdc_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock); protected: // device-level overrides virtual void device_start() override; virtual void device_reset() override; // optional information overrides virtual void device_add_mconfig(machine_config &config) override; virtual const tiny_rom_entry *device_rom_region() const override; private: required_device<wd2010_device> m_hdc; // uint8_t m_ram[0x800]; public: DECLARE_READ8_MEMBER(p1_HDC_r); DECLARE_WRITE8_MEMBER(p1_HDC_w); }; // device type definition DECLARE_DEVICE_TYPE(P1_HDC, p1_hdc_device) #endif // MAME_BUS_ISA_P1_HDC_H
import _extends from 'babel-runtime/helpers/extends'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'mini-store'; import TableRow from './TableRow'; import { remove } from './utils'; var ExpandableTable = function (_React$Component) { _inherits(ExpandableTable, _React$Component); function ExpandableTable(props) { _classCallCheck(this, ExpandableTable); var _this = _possibleConstructorReturn(this, _React$Component.call(this, props)); _initialiseProps.call(_this); var data = props.data, childrenColumnName = props.childrenColumnName, defaultExpandAllRows = props.defaultExpandAllRows, expandedRowKeys = props.expandedRowKeys, defaultExpandedRowKeys = props.defaultExpandedRowKeys, getRowKey = props.getRowKey; var finnalExpandedRowKeys = []; var rows = [].concat(data); if (defaultExpandAllRows) { for (var i = 0; i < rows.length; i++) { var row = rows[i]; finnalExpandedRowKeys.push(getRowKey(row, i)); rows = rows.concat(row[childrenColumnName] || []); } } else { finnalExpandedRowKeys = expandedRowKeys || defaultExpandedRowKeys; } _this.columnManager = props.columnManager; _this.store = props.store; _this.store.setState({ expandedRowsHeight: {}, expandedRowKeys: finnalExpandedRowKeys }); return _this; } ExpandableTable.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { if ('expandedRowKeys' in nextProps) { this.store.setState({ expandedRowKeys: nextProps.expandedRowKeys }); } }; ExpandableTable.prototype.renderExpandedRow = function renderExpandedRow(record, index, _render, className, ancestorKeys, indent, fixed) { var _props = this.props, prefixCls = _props.prefixCls, expandIconAsCell = _props.expandIconAsCell, indentSize = _props.indentSize; var colCount = void 0; if (fixed === 'left') { colCount = this.columnManager.leftLeafColumns().length; } else if (fixed === 'right') { colCount = this.columnManager.rightLeafColumns().length; } else { colCount = this.columnManager.leafColumns().length; } var columns = [{ key: 'extra-row', render: function render() { return { props: { colSpan: colCount }, children: fixed !== 'right' ? _render(record, index, indent) : '&nbsp;' }; } }]; if (expandIconAsCell && fixed !== 'right') { columns.unshift({ key: 'expand-icon-placeholder', render: function render() { return null; } }); } var parentKey = ancestorKeys[ancestorKeys.length - 1]; var rowKey = parentKey + '-extra-row'; var components = { body: { row: 'tr', cell: 'td' } }; return React.createElement(TableRow, { key: rowKey, columns: columns, className: className, rowKey: rowKey, ancestorKeys: ancestorKeys, prefixCls: prefixCls + '-expanded-row', indentSize: indentSize, indent: indent, fixed: fixed, components: components, expandedRow: true }); }; ExpandableTable.prototype.render = function render() { var _props2 = this.props, data = _props2.data, childrenColumnName = _props2.childrenColumnName, children = _props2.children; var needIndentSpaced = data.some(function (record) { return record[childrenColumnName]; }); return children({ props: this.props, needIndentSpaced: needIndentSpaced, renderRows: this.renderRows, handleExpandChange: this.handleExpandChange, renderExpandIndentCell: this.renderExpandIndentCell }); }; return ExpandableTable; }(React.Component); ExpandableTable.propTypes = { expandIconAsCell: PropTypes.bool, expandedRowKeys: PropTypes.array, expandedRowClassName: PropTypes.func, defaultExpandAllRows: PropTypes.bool, defaultExpandedRowKeys: PropTypes.array, expandIconColumnIndex: PropTypes.number, expandedRowRender: PropTypes.func, childrenColumnName: PropTypes.string, indentSize: PropTypes.number, onExpand: PropTypes.func, onExpandedRowsChange: PropTypes.func, columnManager: PropTypes.object.isRequired, store: PropTypes.object.isRequired, prefixCls: PropTypes.string.isRequired, data: PropTypes.array, children: PropTypes.func.isRequired }; ExpandableTable.defaultProps = { expandIconAsCell: false, expandedRowClassName: function expandedRowClassName() { return ''; }, expandIconColumnIndex: 0, defaultExpandAllRows: false, defaultExpandedRowKeys: [], childrenColumnName: 'children', indentSize: 15, onExpand: function onExpand() {}, onExpandedRowsChange: function onExpandedRowsChange() {} }; var _initialiseProps = function _initialiseProps() { var _this2 = this; this.handleExpandChange = function (expanded, record, event, rowKey) { if (event) { event.preventDefault(); event.stopPropagation(); } var _props3 = _this2.props, onExpandedRowsChange = _props3.onExpandedRowsChange, onExpand = _props3.onExpand; var _store$getState = _this2.store.getState(), expandedRowKeys = _store$getState.expandedRowKeys; if (expanded) { // row was expaned expandedRowKeys = [].concat(expandedRowKeys, [rowKey]); } else { // row was collapse var expandedRowIndex = expandedRowKeys.indexOf(rowKey); if (expandedRowIndex !== -1) { expandedRowKeys = remove(expandedRowKeys, rowKey); } } if (!_this2.props.expandedRowKeys) { _this2.store.setState({ expandedRowKeys: expandedRowKeys }); } onExpandedRowsChange(expandedRowKeys); onExpand(expanded, record); }; this.renderExpandIndentCell = function (rows, fixed) { var _props4 = _this2.props, prefixCls = _props4.prefixCls, expandIconAsCell = _props4.expandIconAsCell; if (!expandIconAsCell || fixed === 'right') { return; } var iconColumn = { key: 'rc-table-expand-icon-cell', className: prefixCls + '-expand-icon-th', title: '', rowSpan: rows.length }; rows[0].unshift(_extends({}, iconColumn, { column: iconColumn })); }; this.renderRows = function (renderRows, rows, record, index, indent, fixed, parentKey, ancestorKeys) { var _props5 = _this2.props, expandedRowClassName = _props5.expandedRowClassName, expandedRowRender = _props5.expandedRowRender, childrenColumnName = _props5.childrenColumnName; var childrenData = record[childrenColumnName]; var nextAncestorKeys = [].concat(ancestorKeys, [parentKey]); var nextIndent = indent + 1; if (expandedRowRender) { rows.push(_this2.renderExpandedRow(record, index, expandedRowRender, expandedRowClassName(record, index, indent), nextAncestorKeys, nextIndent, fixed)); } if (childrenData) { rows.push.apply(rows, renderRows(childrenData, nextIndent, nextAncestorKeys)); } }; }; export default connect()(ExpandableTable);
# def f(x): # return 2*x**2 - 5*x + 3 # Function from the given equation f = lambda x: 2*x**2 - 5*x + 3 x1, x2 = map(float, input("Enter the initial interval (x1 x2): ").split()) # x1 = 0, 2 # The initial guesses # x2 = 1.3 y1 = f(x1) y2 = f(x2) if y1*y2 > 0: # Signs of y-values are not opposite print("No roots exist within the given interval") raise SystemExit if y1*y2 == 0: # One or both initial guess is the root if y1 == 0: print('The root: %0.5f' % x1) if y2 == 0: print('The root: %0.5f' % x2) raise SystemExit # Signs of y-values are opposite xh = x1 while abs(x1-x2) >= 1.0E-6: # or abs(f(xh)) >= 1e-6: xh = (x1 + x2) / 2 # Bisection equation yh = f(xh) if y1 * yh < 0: # The root is in the 1st half x2 = xh # x1 and y1 remains same elif y1 * yh > 0: # The root is in the 2nd half x1 = xh # x2 remains same y1 = f(x1) # y1 changes as x1 does else: break # The root equals to xh print('The Root: %0.5f' % xh)
#include <vector> #include "XPathNamespace.h" using namespace std; //basic element of a sequence is one of these values enum XPathItemType { not_an_item, atomic, node }; //each non atomic item is of a node type enum XPathNodeType { not_a_node, document, element, attribute, text, xml_namespace, processing_instruction, comment }; class CXPathTerm { public: CXPathTerm(); CXPathTerm(int documentOrder, CText xmlBase, XPathItemType itemType, XPathNodeType nodeType, CText typeMatches, CText qName, CText stringValue, CXPathTerm* parent); virtual ~CXPathTerm(); // generates a CXPathTerm object graph based on the // CXMLNode object graph...to be done by Kimmie. //void GenerateTree(CXMLNode *pXML); private: int m_DocumentOrder; CText m_XMLBase; XPathItemType m_ItemType; XPathNodeType m_NodeType; CText m_TypeMatches; CText m_QName; CXPathTerm *m_Parent; CXPathNamespace *m_Namespace; vector<CXPathTerm*> m_Attributes; vector<CXPathTerm*> m_Children; CText m_StringValue; CXPathTerm *m_TypedValue; public: //accessor bool IsSequence() const; bool IsAtomic() const; bool IsNode() const; XPathItemType GetItemType() const; XPathNodeType GetNodeType() const; int GetDocumentOrder() const; CText GetQName(); // returns Qname CText GetLocalName(); // returns Local Name CText GetExpandedQName(); // returns Expanded-QName (ns URI:LocalName) CText GetStringValue(); CXPathTerm* GetChildAt(int i); // return child CXPathTerm instance at index, i CXPathTerm* GetAttributeAt(int i); // return attribute (CXPathTerm instance) at index, i CXPathTerm* GetParent(); void AppendChild(CXPathTerm*); void AppendAttribute(CXPathTerm*); //Mutators void SetChildAt(int i, CXPathTerm *x); // set child CXPathTerm instance at index, i void SetAttributeAt(int i, CXPathTerm *x); // set attribute (CXPathTerm instance) at i void setNSNode(); void setStringValue(CText v); void setTypedValue(CXPathTerm* typedValueSequence); void ResetChildren(); void ResetAttributes(); };
# Copyright 2017 Mycroft AI Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import imp import sys import time from os import listdir from os.path import abspath, dirname, basename, isdir, join from threading import Lock from mycroft.configuration import Configuration from mycroft.messagebus.message import Message from mycroft.util.log import LOG from .services import RemoteAudioBackend try: import pulsectl except ImportError: pulsectl = None MAINMODULE = '__init__' sys.path.append(abspath(dirname(__file__))) def create_service_descriptor(service_folder): """Prepares a descriptor that can be used together with imp. Args: service_folder: folder that shall be imported. Returns: Dict with import information """ info = imp.find_module(MAINMODULE, [service_folder]) return {"name": basename(service_folder), "info": info} def get_services(services_folder): """ Load and initialize services from all subfolders. Args: services_folder: base folder to look for services in. Returns: Sorted list of audio services. """ LOG.info("Loading services from " + services_folder) services = [] possible_services = listdir(services_folder) for i in possible_services: location = join(services_folder, i) if (isdir(location) and not MAINMODULE + ".py" in listdir(location)): for j in listdir(location): name = join(location, j) if (not isdir(name) or not MAINMODULE + ".py" in listdir(name)): continue try: services.append(create_service_descriptor(name)) except Exception: LOG.error('Failed to create service from ' + name, exc_info=True) if (not isdir(location) or not MAINMODULE + ".py" in listdir(location)): continue try: services.append(create_service_descriptor(location)) except Exception: LOG.error('Failed to create service from ' + location, exc_info=True) return sorted(services, key=lambda p: p.get('name')) def load_services(config, bus, path=None): """ Search though the service directory and load any services. Args: config: configuration dict for the audio backends. bus: Mycroft messagebus Returns: List of started services. """ if path is None: path = dirname(abspath(__file__)) + '/services/' service_directories = get_services(path) service = [] for descriptor in service_directories: LOG.info('Loading ' + descriptor['name']) try: service_module = imp.load_module(descriptor["name"] + MAINMODULE, *descriptor["info"]) except Exception as e: LOG.error('Failed to import module ' + descriptor['name'] + '\n' + repr(e)) continue if (hasattr(service_module, 'autodetect') and callable(service_module.autodetect)): try: s = service_module.autodetect(config, bus) service += s except Exception as e: LOG.error('Failed to autodetect. ' + repr(e)) if hasattr(service_module, 'load_service'): try: s = service_module.load_service(config, bus) service += s except Exception as e: LOG.error('Failed to load service. ' + repr(e)) return service class AudioService: """ Audio Service class. Handles playback of audio and selecting proper backend for the uri to be played. """ def __init__(self, bus): """ Args: bus: Mycroft messagebus """ self.bus = bus self.config = Configuration.get().get("Audio") self.service_lock = Lock() self.default = None self.service = [] self.current = None self.play_start_time = 0 self.volume_is_low = False self.pulse = None self.pulse_quiet = None self.pulse_restore = None self.muted_sinks = [] # Setup control of pulse audio self.setup_pulseaudio_handlers(self.config.get('pulseaudio')) bus.once('open', self.load_services_callback) def load_services_callback(self): """ Main callback function for loading services. Sets up the globals service and default and registers the event handlers for the subsystem. """ services = load_services(self.config, self.bus) # Sort services so local services are checked first local = [s for s in services if not isinstance(s, RemoteAudioBackend)] remote = [s for s in services if isinstance(s, RemoteAudioBackend)] self.service = local + remote # Register end of track callback for s in self.service: s.set_track_start_callback(self.track_start) # Find default backend default_name = self.config.get('default-backend', '') LOG.info('Finding default backend...') for s in self.service: if s.name == default_name: self.default = s LOG.info('Found ' + self.default.name) break else: self.default = None LOG.info('no default found') # Setup event handlers self.bus.on('mycroft.audio.service.play', self._play) self.bus.on('mycroft.audio.service.queue', self._queue) self.bus.on('mycroft.audio.service.pause', self._pause) self.bus.on('mycroft.audio.service.resume', self._resume) self.bus.on('mycroft.audio.service.stop', self._stop) self.bus.on('mycroft.audio.service.next', self._next) self.bus.on('mycroft.audio.service.prev', self._prev) self.bus.on('mycroft.audio.service.track_info', self._track_info) self.bus.on('mycroft.audio.service.list_backends', self._list_backends) self.bus.on('mycroft.audio.service.seek_forward', self._seek_forward) self.bus.on('mycroft.audio.service.seek_backward', self._seek_backward) self.bus.on('recognizer_loop:audio_output_start', self._lower_volume) self.bus.on('recognizer_loop:record_begin', self._lower_volume) self.bus.on('recognizer_loop:audio_output_end', self._restore_volume) self.bus.on('recognizer_loop:record_end', self._restore_volume) def track_start(self, track): """ Callback method called from the services to indicate start of playback of a track. """ self.bus.emit(Message('mycroft.audio.playing_track', data={'track': track})) def _pause(self, message=None): """ Handler for mycroft.audio.service.pause. Pauses the current audio service. Args: message: message bus message, not used but required """ if self.current: self.current.pause() def _resume(self, message=None): """ Handler for mycroft.audio.service.resume. Args: message: message bus message, not used but required """ if self.current: self.current.resume() def _next(self, message=None): """ Handler for mycroft.audio.service.next. Skips current track and starts playing the next. Args: message: message bus message, not used but required """ if self.current: self.current.next() def _prev(self, message=None): """ Handler for mycroft.audio.service.prev. Starts playing the previous track. Args: message: message bus message, not used but required """ if self.current: self.current.previous() def _stop(self, message=None): """ Handler for mycroft.stop. Stops any playing service. Args: message: message bus message, not used but required """ if time.monotonic() - self.play_start_time > 1: LOG.debug('stopping all playing services') with self.service_lock: if self.current: name = self.current.name if self.current.stop(): self.bus.emit(Message("mycroft.stop.handled", {"by": "audio:" + name})) self.current = None def _lower_volume(self, message=None): """ Is triggered when mycroft starts to speak and reduces the volume. Args: message: message bus message, not used but required """ if self.current: LOG.debug('lowering volume') self.current.lower_volume() self.volume_is_low = True try: if self.pulse_quiet: self.pulse_quiet() except Exception as exc: LOG.error(exc) def pulse_mute(self): """ Mute all pulse audio input sinks except for the one named 'mycroft-voice'. """ for sink in self.pulse.sink_input_list(): if sink.name != 'mycroft-voice': self.pulse.sink_input_mute(sink.index, 1) self.muted_sinks.append(sink.index) def pulse_unmute(self): """ Unmute all pulse audio input sinks. """ for sink in self.pulse.sink_input_list(): if sink.index in self.muted_sinks: self.pulse.sink_input_mute(sink.index, 0) self.muted_sinks = [] def pulse_lower_volume(self): """ Lower volume of all pulse audio input sinks except the one named 'mycroft-voice'. """ for sink in self.pulse.sink_input_list(): if sink.name != 'mycroft-voice': volume = sink.volume volume.value_flat *= 0.3 self.pulse.volume_set(sink, volume) def pulse_restore_volume(self): """ Restore volume of all pulse audio input sinks except the one named 'mycroft-voice'. """ for sink in self.pulse.sink_input_list(): if sink.name != 'mycroft-voice': volume = sink.volume volume.value_flat /= 0.3 self.pulse.volume_set(sink, volume) def _restore_volume(self, message): """ Is triggered when mycroft is done speaking and restores the volume Args: message: message bus message, not used but required """ if self.current: LOG.debug('restoring volume') self.volume_is_low = False time.sleep(2) if not self.volume_is_low: self.current.restore_volume() if self.pulse_restore: self.pulse_restore() def play(self, tracks, prefered_service, repeat=False): """ play starts playing the audio on the prefered service if it supports the uri. If not the next best backend is found. Args: tracks: list of tracks to play. repeat: should the playlist repeat prefered_service: indecates the service the user prefer to play the tracks. """ self._stop() if isinstance(tracks[0], str): uri_type = tracks[0].split(':')[0] else: uri_type = tracks[0][0].split(':')[0] # check if user requested a particular service if prefered_service and uri_type in prefered_service.supported_uris(): selected_service = prefered_service # check if default supports the uri elif self.default and uri_type in self.default.supported_uris(): LOG.debug("Using default backend ({})".format(self.default.name)) selected_service = self.default else: # Check if any other service can play the media LOG.debug("Searching the services") for s in self.service: if uri_type in s.supported_uris(): LOG.debug("Service {} supports URI {}".format(s, uri_type)) selected_service = s break else: LOG.info('No service found for uri_type: ' + uri_type) return if not selected_service.supports_mime_hints: tracks = [t[0] if isinstance(t, list) else t for t in tracks] selected_service.clear_list() selected_service.add_list(tracks) selected_service.play(repeat) self.current = selected_service self.play_start_time = time.monotonic() def _queue(self, message): if self.current: tracks = message.data['tracks'] self.current.add_list(tracks) else: self._play(message) def _play(self, message): """ Handler for mycroft.audio.service.play. Starts playback of a tracklist. Also determines if the user requested a special service. Args: message: message bus message, not used but required """ tracks = message.data['tracks'] repeat = message.data.get('repeat', False) # Find if the user wants to use a specific backend for s in self.service: if ('utterance' in message.data and s.name in message.data['utterance']): prefered_service = s LOG.debug(s.name + ' would be prefered') break else: prefered_service = None self.play(tracks, prefered_service, repeat) def _track_info(self, message): """ Returns track info on the message bus. Args: message: message bus message, not used but required """ if self.current: track_info = self.current.track_info() else: track_info = {} self.bus.emit(Message('mycroft.audio.service.track_info_reply', data=track_info)) def _list_backends(self, message): """ Return a dict of available backends. """ data = {} for s in self.service: info = { 'supported_uris': s.supported_uris(), 'default': s == self.default, 'remote': isinstance(s, RemoteAudioBackend) } data[s.name] = info self.bus.emit(message.response(data)) def _seek_forward(self, message): """ Handle message bus command to skip X seconds Args: message: message bus message """ seconds = message.data.get("seconds", 1) if self.current: self.current.seek_forward(seconds) def _seek_backward(self, message): """ Handle message bus command to rewind X seconds Args: message: message bus message """ seconds = message.data.get("seconds", 1) if self.current: self.current.seek_backward(seconds) def setup_pulseaudio_handlers(self, pulse_choice=None): """ Select functions for handling lower volume/restore of pulse audio input sinks. Args: pulse_choice: method selection, can be eithe 'mute' or 'lower' """ if pulsectl and pulse_choice: self.pulse = pulsectl.Pulse('Mycroft-audio-service') if pulse_choice == 'mute': self.pulse_quiet = self.pulse_mute self.pulse_restore = self.pulse_unmute elif pulse_choice == 'lower': self.pulse_quiet = self.pulse_lower_volume self.pulse_restore = self.pulse_restore_volume def shutdown(self): for s in self.service: try: LOG.info('shutting down ' + s.name) s.shutdown() except Exception as e: LOG.error('shutdown of ' + s.name + ' failed: ' + repr(e)) # remove listeners self.bus.remove('mycroft.audio.service.play', self._play) self.bus.remove('mycroft.audio.service.queue', self._queue) self.bus.remove('mycroft.audio.service.pause', self._pause) self.bus.remove('mycroft.audio.service.resume', self._resume) self.bus.remove('mycroft.audio.service.stop', self._stop) self.bus.remove('mycroft.audio.service.next', self._next) self.bus.remove('mycroft.audio.service.prev', self._prev) self.bus.remove('mycroft.audio.service.track_info', self._track_info) self.bus.remove('mycroft.audio.service.seek_forward', self._seek_forward) self.bus.remove('mycroft.audio.service.seek_backward', self._seek_backward) self.bus.remove('recognizer_loop:audio_output_start', self._lower_volume) self.bus.remove('recognizer_loop:record_begin', self._lower_volume) self.bus.remove('recognizer_loop:audio_output_end', self._restore_volume) self.bus.remove('recognizer_loop:record_end', self._restore_volume)
/** * Copyright IBM Corp. 2019, 2020 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. * * Code generated by @carbon/icon-build-helpers. DO NOT EDIT. */ import { _ as _objectWithoutProperties, I as Icon, a as _extends } from '../Icon-7c760541.js'; import React from 'react'; import '@carbon/icon-helpers'; import 'prop-types'; var _path, _path2; var Rss24 = /*#__PURE__*/React.forwardRef(function Rss24(_ref, ref) { var children = _ref.children, rest = _objectWithoutProperties(_ref, ["children"]); return /*#__PURE__*/React.createElement(Icon, _extends({ width: 24, height: 24, viewBox: "0 0 32 32", xmlns: "http://www.w3.org/2000/svg", fill: "currentColor", ref: ref }, rest), _path || (_path = /*#__PURE__*/React.createElement("path", { d: "M8 18c-3.3 0-6 2.7-6 6s2.7 6 6 6 6-2.7 6-6C14 20.7 11.3 18 8 18zM8 28c-2.2 0-4-1.8-4-4s1.8-4 4-4 4 1.8 4 4C12 26.2 10.2 28 8 28zM30 24h-2C28 13 19 4 8 4V2C20.1 2 30 11.9 30 24z" })), _path2 || (_path2 = /*#__PURE__*/React.createElement("path", { d: "M22,24h-2c0-6.6-5.4-12-12-12v-2C15.7,10,22,16.3,22,24z" })), children); }); export default Rss24;
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard. // #import "NSObject.h" @class NSCache; @interface TVNPRoutingTintedImageCache : NSObject { NSCache *_imageCache; // 8 = 0x8 } + (id)sharedInstance; // IMP=0x000000010001e0e0 @property(readonly, nonatomic) NSCache *imageCache; // @synthesize imageCache=_imageCache; - (void).cxx_destruct; // IMP=0x000000010001e474 - (id)tintedImageWithName:(id)arg1 tintColor:(id)arg2; // IMP=0x000000010001e21c - (id)init; // IMP=0x000000010001e19c @end
from typing import Dict import requests from bs4 import BeautifulSoup from deutschland.config import Config, module_config class Registrations: def __init__(self, config: Config = None): if config is None: self._config = module_config else: self._config = config REQUEST_HEADERS = { "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9", "Cache-Control": "max-age=0", "Connection": "keep-alive", "Content-Type": "application/x-www-form-urlencoded", "DNT": "1", "Host": "www.handelsregister.de", "Origin": "https://www.handelsregister.de", "Referer": "https://www.handelsregister.de/rp_web/mask.do?Typ=e", "sec-ch-ua-mobile": "?0", "sec-ch-ua": '"Chromium";v="92", " Not A;Brand";v="99", "Google Chrome";v="92"', "Sec-Fetch-Dest": "document", "Sec-Fetch-Mode": "navigate", "Sec-Fetch-Site": "same-origin", "Sec-Fetch-User": "?1", "sec-gpc": "1", "Upgrade-Insecure-Requests": "1", "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36", } SEARCH_URL = "https://www.handelsregister.de/rp_web/mask.do?Typ=e" DEFAULT_FORM_DATA = { "schlagwoerter": None, "schlagwortOptionen": 2, "suchOptionenAehnlich": False, "niederlassung": None, "suchOptionenGeloescht": False, "suchOptionenNurZNneuenRechts": False, "suchTyp": "e", "registerArt": None, "registerNummer": None, "registergericht": None, "rechtsform": None, "postleitzahl": None, "ort": None, "strasse": None, "ergebnisseProSeite": "100", "btnSuche": "Suchen", } def search_with_raw_params( self, params: Dict[str, str] = {}, proxies: Dict[str, str] = None ): """ Searches the Handelsregister with a given dict of parameters. Parameters ---------- params : dict The parameters for the search. Detailed description below. Search Parameters ----------------- schlagwoerter : string One or space-separated Keywords like e.g. the company name. schlagwortOptionen : int Options for the 'schlagwoerter' parameter. 1 : Match must contain all keywords. 2 : Match must contain at least one keyword. 3 : Match's company name must equal the keyword(s). suchOptionenAehnlich : bool Match can contain similar keywords as specified in 'schlagwoerter'. bundeslandXX : string Search only in specified counties (bundeslaender). If no county is specified, all counties are searched. Each county must be specified individually in the following format: {"bundeslandXX": "on"}, where 'XX' is of the following codes: BW, BY, BE, BR, HB, HH, HE, MV, NI, NW, RP, SL, SN, ST, SH, TH niederlassung : string Location of the company. suchOptionenGeloescht : bool Search also for deleted companies. suchOptionenNurZNneuenRechts : bool Include only 'Zweigniederlassungen' registered after the 01.01.2007. More info here: https://www.handelsregister.de/rp_web/help.do?Thema=zweigniederlassungen registerArt : string Type of company registration. Possible values: HRA, HRB, GnR, PR, VR registerNummer : string The registration number of the company. registergericht : string The district court where the company is registered. rechtsform : int The legal form of the company. Possible values can be found in 'params.md'. postleitzahl : string The postal code of the company. ort : string The city of the company address. strasse : string The street of the company address. ergebnisseProSeite : int How many matches to return. Defaults to 100. """ # parameter has higher priority than member if proxies is None: if self._config is not None and self._config.proxy_config is not None: proxies = self._config.proxy_config search_params = {**self.DEFAULT_FORM_DATA, **params} response = requests.post( self.SEARCH_URL, data=search_params, headers=self.REQUEST_HEADERS, proxies=proxies, ) if response.status_code != 200: return None soup = BeautifulSoup(response.text, "html.parser") return self.__find_entries(soup) def __find_entries(self, soup): table = soup.find("table", class_="RegPortErg") if table is None: return [] trs = table.find_all("tr") results = [] next_entry = {} # Skip the first row, which is the header row for tr in trs[1:]: if tr.find("td", class_="RegPortErg_AZ"): data = self.__extract_county_court_and_registration(tr) # Save the current entry since we reached the next entry # demarcated by the .RegPortErg_AZ table cell. if next_entry: results.append(next_entry.copy()) next_entry = data elif tr.find("td", class_="RegPortErg_FirmaKopf"): data = self.__extract_name_location_and_state(tr) next_entry.update(data) elif tr.find("td", class_="RegPortErg_HistorieZn"): data = self.__extract_history(tr) next_entry.setdefault("history", []).append(data) if next_entry: results.append(next_entry) return results def __extract_county_court_and_registration(self, row): td = row.find("td", class_="RegPortErg_AZ") county = td.contents[2].strip() court_and_registration = ( td.contents[3].text.strip().replace("\n", " ").replace("\t", "").split() ) court = " ".join(court_and_registration[:-2]) [reg_type, reg_num] = court_and_registration[-2:] return { "county": county, "court": court, "registration_type": reg_type, "registration_number": reg_num, } def __extract_name_location_and_state(self, row): tds = row.find_all("td") name = tds[1].text.strip() location = tds[2].text.strip() state = tds[3].text.strip() return {"company_name": name, "location": location, "state": state} def __extract_history(self, row): tds = row.find_all("td") [position, historical_name] = tds[1].text.strip().split(".) ", 1) historical_location = tds[2].text.strip().split(".) ", 1)[1] return { "position": position, "historical_name": historical_name, "historical_location": historical_location, }
''' Created on 16 Dec 2019 @author: gualtiero ''' import pytest import os import secretwallet.utils.cryptutils as cu from secretwallet.main.configuration import set_configuration, get_configuration from secretwallet.utils.cryptutils import encrypt_key from secretwallet.constants import parameters @pytest.fixture def set_up(): path = os.path.dirname(__file__) conf_file = os.path.join(path,'data','.secretwallet','test.json') yield conf_file if os.path.exists(conf_file): os.remove(conf_file) os.rmdir(os.path.dirname(conf_file)) parameters.clear() def test_get_encrypted_key(): passwd = u"passwd" ekey = cu.encrypt_key(passwd) assert ekey is not None assert isinstance(ekey, str) ekey2 = cu.encrypt_key(passwd) assert ekey2 == ekey def test_configure_save_key(set_up): conf_file = set_up passwd = u"passwd" set_configuration(encrypt_key(passwd), None, None, None, conf_file) data = get_configuration(conf_file) key = data['key'].encode('latin1') assert key is not None assert isinstance(key, bytes) def test_configure_save_many(set_up): conf_file = set_up passwd = u"passwd" profile = 'my profile' salt = 'my salt' table = 'my table' set_configuration(encrypt_key(passwd), profile, table, salt, conf_file) data = get_configuration(conf_file) key = data['key'].encode('latin1') assert key is not None assert isinstance(key, bytes) assert profile == data['profile'] assert salt == data['salt'] assert table == data['table_name'] def test_encrypt_decrypt_secret(set_up): conf_file = set_up c_pwd = u"passwd" m_pwd = u"memorabile" secret = u"mamma" set_configuration(encrypt_key(c_pwd), None, None, None, conf_file) parameters.set_data(get_configuration(conf_file)) esecret = cu.encrypt(secret, m_pwd, parameters.get_salt_key()) v1 = cu.decrypt(esecret, m_pwd, parameters.get_salt_key()) esecret2 = cu.encrypt(secret, m_pwd, parameters.get_salt_key()) v2 = cu.decrypt(esecret2, m_pwd, parameters.get_salt_key()) assert v1 == v2 assert v1 == secret def test_encrypt_decrypt_no_config(): c_pwd = u"passwd" m_pwd = u"memorabile" secret = u"mamma" key = cu.encrypt_key(c_pwd) esecret = cu.encrypt(secret, m_pwd, key) v1 = cu.decrypt(esecret, m_pwd, key) esecret2 = cu.encrypt(secret, m_pwd, key) v2 = cu.decrypt(esecret2, m_pwd, key) assert v1 == v2 assert v1 == secret
module.exports = () => ({ plugins: { 'postcss-import': {}, 'precss': {}, 'autoprefixer': { browsers: ['last 2 versions', 'IE > 8'] }, 'lost': {}, 'postcss-reporter': { clearMessages: true } } })
# avax-python : Python tools for the exploration of the Avalanche AVAX network. # # Find tutorials and use cases at https://crypto.bi """ Copyright (C) 2021 - crypto.bi Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --- Help support this Open Source project! Donations address: X-avax1qr6yzjykcjmeflztsgv6y88dl0xnlel3chs3r4 Thank you! """ # --#--#-- class Message: def __init__(self, messageType=None, validatorID=None, requestID=None, containerID=None, container: bytes=None, containers=[], containerIDs=[], notification=None, received=None, deadline=None): self.messageType=messageType self.validatorID=validatorID self.requestID=requestID self.containerID=containerID self.container=container self.containers=containers self.containerIDs=containerIDs self.notification=notification self.received=received self.deadline=deadline def __repr__(self): c_count = 0 if self.containers: try: c_count = len(self.containers) except Exception as _: c_count = 0 _d = { "messageType": self.messageType, "validatorID": self.validatorID, "requestID": self.requestID, "containerID": self.containerID, "container": f"[BINARY] {len(self.container)} Bytes", "containers": f"[BINARY] {c_count} Containers", "containerIDs": self.containerIDs, "notification": self.notification, "received": self.received, "deadline": self.deadline } return str(_d)
from datetime import datetime, timedelta, timezone as datetime_timezone import pytz from django.conf import settings from django.db.models import ( DateField, DateTimeField, F, IntegerField, Max, OuterRef, Subquery, TimeField, ) from django.db.models.functions import ( Extract, ExtractDay, ExtractHour, ExtractIsoWeekDay, ExtractIsoYear, ExtractMinute, ExtractMonth, ExtractQuarter, ExtractSecond, ExtractWeek, ExtractWeekDay, ExtractYear, Trunc, TruncDate, TruncDay, TruncHour, TruncMinute, TruncMonth, TruncQuarter, TruncSecond, TruncTime, TruncWeek, TruncYear, ) from django.test import ( TestCase, override_settings, skipIfDBFeature, skipUnlessDBFeature, ) from django.utils import timezone from ..models import Author, DTModel, Fan def truncate_to(value, kind, tzinfo=None): # Convert to target timezone before truncation if tzinfo is not None: value = value.astimezone(tzinfo) def truncate(value, kind): if kind == 'second': return value.replace(microsecond=0) if kind == 'minute': return value.replace(second=0, microsecond=0) if kind == 'hour': return value.replace(minute=0, second=0, microsecond=0) if kind == 'day': if isinstance(value, datetime): return value.replace(hour=0, minute=0, second=0, microsecond=0) return value if kind == 'week': if isinstance(value, datetime): return (value - timedelta(days=value.weekday())).replace(hour=0, minute=0, second=0, microsecond=0) return value - timedelta(days=value.weekday()) if kind == 'month': if isinstance(value, datetime): return value.replace(day=1, hour=0, minute=0, second=0, microsecond=0) return value.replace(day=1) if kind == 'quarter': month_in_quarter = value.month - (value.month - 1) % 3 if isinstance(value, datetime): return value.replace(month=month_in_quarter, day=1, hour=0, minute=0, second=0, microsecond=0) return value.replace(month=month_in_quarter, day=1) # otherwise, truncate to year if isinstance(value, datetime): return value.replace(month=1, day=1, hour=0, minute=0, second=0, microsecond=0) return value.replace(month=1, day=1) value = truncate(value, kind) if tzinfo is not None: # If there was a daylight saving transition, then reset the timezone. value = timezone.make_aware(value.replace(tzinfo=None), tzinfo) return value @override_settings(USE_TZ=False) class DateFunctionTests(TestCase): def create_model(self, start_datetime, end_datetime): return DTModel.objects.create( name=start_datetime.isoformat() if start_datetime else 'None', start_datetime=start_datetime, end_datetime=end_datetime, start_date=start_datetime.date() if start_datetime else None, end_date=end_datetime.date() if end_datetime else None, start_time=start_datetime.time() if start_datetime else None, end_time=end_datetime.time() if end_datetime else None, duration=(end_datetime - start_datetime) if start_datetime and end_datetime else None, ) def test_extract_year_exact_lookup(self): """ Extract year uses a BETWEEN filter to compare the year to allow indexes to be used. """ start_datetime = datetime(2015, 6, 15, 14, 10) end_datetime = datetime(2016, 6, 15, 14, 10) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) for lookup in ('year', 'iso_year'): with self.subTest(lookup): qs = DTModel.objects.filter(**{'start_datetime__%s__exact' % lookup: 2015}) self.assertEqual(qs.count(), 1) query_string = str(qs.query).lower() self.assertEqual(query_string.count(' between '), 1) self.assertEqual(query_string.count('extract'), 0) # exact is implied and should be the same qs = DTModel.objects.filter(**{'start_datetime__%s' % lookup: 2015}) self.assertEqual(qs.count(), 1) query_string = str(qs.query).lower() self.assertEqual(query_string.count(' between '), 1) self.assertEqual(query_string.count('extract'), 0) # date and datetime fields should behave the same qs = DTModel.objects.filter(**{'start_date__%s' % lookup: 2015}) self.assertEqual(qs.count(), 1) query_string = str(qs.query).lower() self.assertEqual(query_string.count(' between '), 1) self.assertEqual(query_string.count('extract'), 0) # an expression rhs cannot use the between optimization. qs = DTModel.objects.annotate( start_year=ExtractYear('start_datetime'), ).filter(end_datetime__year=F('start_year') + 1) self.assertEqual(qs.count(), 1) query_string = str(qs.query).lower() self.assertEqual(query_string.count(' between '), 0) self.assertEqual(query_string.count('extract'), 3) def test_extract_year_greaterthan_lookup(self): start_datetime = datetime(2015, 6, 15, 14, 10) end_datetime = datetime(2016, 6, 15, 14, 10) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) for lookup in ('year', 'iso_year'): with self.subTest(lookup): qs = DTModel.objects.filter(**{'start_datetime__%s__gt' % lookup: 2015}) self.assertEqual(qs.count(), 1) self.assertEqual(str(qs.query).lower().count('extract'), 0) qs = DTModel.objects.filter(**{'start_datetime__%s__gte' % lookup: 2015}) self.assertEqual(qs.count(), 2) self.assertEqual(str(qs.query).lower().count('extract'), 0) qs = DTModel.objects.annotate( start_year=ExtractYear('start_datetime'), ).filter(**{'end_datetime__%s__gte' % lookup: F('start_year')}) self.assertEqual(qs.count(), 1) self.assertGreaterEqual(str(qs.query).lower().count('extract'), 2) def test_extract_year_lessthan_lookup(self): start_datetime = datetime(2015, 6, 15, 14, 10) end_datetime = datetime(2016, 6, 15, 14, 10) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) for lookup in ('year', 'iso_year'): with self.subTest(lookup): qs = DTModel.objects.filter(**{'start_datetime__%s__lt' % lookup: 2016}) self.assertEqual(qs.count(), 1) self.assertEqual(str(qs.query).count('extract'), 0) qs = DTModel.objects.filter(**{'start_datetime__%s__lte' % lookup: 2016}) self.assertEqual(qs.count(), 2) self.assertEqual(str(qs.query).count('extract'), 0) qs = DTModel.objects.annotate( end_year=ExtractYear('end_datetime'), ).filter(**{'start_datetime__%s__lte' % lookup: F('end_year')}) self.assertEqual(qs.count(), 1) self.assertGreaterEqual(str(qs.query).lower().count('extract'), 2) def test_extract_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) with self.assertRaisesMessage(ValueError, 'lookup_name must be provided'): Extract('start_datetime') msg = 'Extract input expression must be DateField, DateTimeField, TimeField, or DurationField.' with self.assertRaisesMessage(ValueError, msg): list(DTModel.objects.annotate(extracted=Extract('name', 'hour'))) with self.assertRaisesMessage( ValueError, "Cannot extract time component 'second' from DateField 'start_date'."): list(DTModel.objects.annotate(extracted=Extract('start_date', 'second'))) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=Extract('start_datetime', 'year')).order_by('start_datetime'), [(start_datetime, start_datetime.year), (end_datetime, end_datetime.year)], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=Extract('start_datetime', 'quarter')).order_by('start_datetime'), [(start_datetime, 2), (end_datetime, 2)], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=Extract('start_datetime', 'month')).order_by('start_datetime'), [(start_datetime, start_datetime.month), (end_datetime, end_datetime.month)], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=Extract('start_datetime', 'day')).order_by('start_datetime'), [(start_datetime, start_datetime.day), (end_datetime, end_datetime.day)], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=Extract('start_datetime', 'week')).order_by('start_datetime'), [(start_datetime, 25), (end_datetime, 24)], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=Extract('start_datetime', 'week_day')).order_by('start_datetime'), [ (start_datetime, (start_datetime.isoweekday() % 7) + 1), (end_datetime, (end_datetime.isoweekday() % 7) + 1) ], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate( extracted=Extract('start_datetime', 'iso_week_day'), ).order_by('start_datetime'), [ (start_datetime, start_datetime.isoweekday()), (end_datetime, end_datetime.isoweekday()), ], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=Extract('start_datetime', 'hour')).order_by('start_datetime'), [(start_datetime, start_datetime.hour), (end_datetime, end_datetime.hour)], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=Extract('start_datetime', 'minute')).order_by('start_datetime'), [(start_datetime, start_datetime.minute), (end_datetime, end_datetime.minute)], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=Extract('start_datetime', 'second')).order_by('start_datetime'), [(start_datetime, start_datetime.second), (end_datetime, end_datetime.second)], lambda m: (m.start_datetime, m.extracted) ) self.assertEqual(DTModel.objects.filter(start_datetime__year=Extract('start_datetime', 'year')).count(), 2) self.assertEqual(DTModel.objects.filter(start_datetime__hour=Extract('start_datetime', 'hour')).count(), 2) self.assertEqual(DTModel.objects.filter(start_date__month=Extract('start_date', 'month')).count(), 2) self.assertEqual(DTModel.objects.filter(start_time__hour=Extract('start_time', 'hour')).count(), 2) def test_extract_none(self): self.create_model(None, None) for t in (Extract('start_datetime', 'year'), Extract('start_date', 'year'), Extract('start_time', 'hour')): with self.subTest(t): self.assertIsNone(DTModel.objects.annotate(extracted=t).first().extracted) @skipUnlessDBFeature('has_native_duration_field') def test_extract_duration(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=Extract('duration', 'second')).order_by('start_datetime'), [ (start_datetime, (end_datetime - start_datetime).seconds % 60), (end_datetime, (start_datetime - end_datetime).seconds % 60) ], lambda m: (m.start_datetime, m.extracted) ) self.assertEqual( DTModel.objects.annotate( duration_days=Extract('duration', 'day'), ).filter(duration_days__gt=200).count(), 1 ) @skipIfDBFeature('has_native_duration_field') def test_extract_duration_without_native_duration_field(self): msg = 'Extract requires native DurationField database support.' with self.assertRaisesMessage(ValueError, msg): list(DTModel.objects.annotate(extracted=Extract('duration', 'second'))) def test_extract_duration_unsupported_lookups(self): msg = "Cannot extract component '%s' from DurationField 'duration'." for lookup in ( 'year', 'iso_year', 'month', 'week', 'week_day', 'iso_week_day', 'quarter', ): with self.subTest(lookup): with self.assertRaisesMessage(ValueError, msg % lookup): DTModel.objects.annotate(extracted=Extract('duration', lookup)) def test_extract_year_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractYear('start_datetime')).order_by('start_datetime'), [(start_datetime, start_datetime.year), (end_datetime, end_datetime.year)], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractYear('start_date')).order_by('start_datetime'), [(start_datetime, start_datetime.year), (end_datetime, end_datetime.year)], lambda m: (m.start_datetime, m.extracted) ) self.assertEqual(DTModel.objects.filter(start_datetime__year=ExtractYear('start_datetime')).count(), 2) def test_extract_iso_year_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractIsoYear('start_datetime')).order_by('start_datetime'), [(start_datetime, start_datetime.year), (end_datetime, end_datetime.year)], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractIsoYear('start_date')).order_by('start_datetime'), [(start_datetime, start_datetime.year), (end_datetime, end_datetime.year)], lambda m: (m.start_datetime, m.extracted) ) # Both dates are from the same week year. self.assertEqual(DTModel.objects.filter(start_datetime__iso_year=ExtractIsoYear('start_datetime')).count(), 2) def test_extract_iso_year_func_boundaries(self): end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: end_datetime = timezone.make_aware(end_datetime, is_dst=False) week_52_day_2014 = datetime(2014, 12, 27, 13, 0) # Sunday week_1_day_2014_2015 = datetime(2014, 12, 31, 13, 0) # Wednesday week_53_day_2015 = datetime(2015, 12, 31, 13, 0) # Thursday if settings.USE_TZ: week_1_day_2014_2015 = timezone.make_aware(week_1_day_2014_2015, is_dst=False) week_52_day_2014 = timezone.make_aware(week_52_day_2014, is_dst=False) week_53_day_2015 = timezone.make_aware(week_53_day_2015, is_dst=False) days = [week_52_day_2014, week_1_day_2014_2015, week_53_day_2015] self.create_model(week_53_day_2015, end_datetime) self.create_model(week_52_day_2014, end_datetime) self.create_model(week_1_day_2014_2015, end_datetime) qs = DTModel.objects.filter(start_datetime__in=days).annotate( extracted=ExtractIsoYear('start_datetime'), ).order_by('start_datetime') self.assertQuerysetEqual(qs, [ (week_52_day_2014, 2014), (week_1_day_2014_2015, 2015), (week_53_day_2015, 2015), ], lambda m: (m.start_datetime, m.extracted)) def test_extract_month_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractMonth('start_datetime')).order_by('start_datetime'), [(start_datetime, start_datetime.month), (end_datetime, end_datetime.month)], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractMonth('start_date')).order_by('start_datetime'), [(start_datetime, start_datetime.month), (end_datetime, end_datetime.month)], lambda m: (m.start_datetime, m.extracted) ) self.assertEqual(DTModel.objects.filter(start_datetime__month=ExtractMonth('start_datetime')).count(), 2) def test_extract_day_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractDay('start_datetime')).order_by('start_datetime'), [(start_datetime, start_datetime.day), (end_datetime, end_datetime.day)], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractDay('start_date')).order_by('start_datetime'), [(start_datetime, start_datetime.day), (end_datetime, end_datetime.day)], lambda m: (m.start_datetime, m.extracted) ) self.assertEqual(DTModel.objects.filter(start_datetime__day=ExtractDay('start_datetime')).count(), 2) def test_extract_week_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractWeek('start_datetime')).order_by('start_datetime'), [(start_datetime, 25), (end_datetime, 24)], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractWeek('start_date')).order_by('start_datetime'), [(start_datetime, 25), (end_datetime, 24)], lambda m: (m.start_datetime, m.extracted) ) # both dates are from the same week. self.assertEqual(DTModel.objects.filter(start_datetime__week=ExtractWeek('start_datetime')).count(), 2) def test_extract_quarter_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 8, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractQuarter('start_datetime')).order_by('start_datetime'), [(start_datetime, 2), (end_datetime, 3)], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractQuarter('start_date')).order_by('start_datetime'), [(start_datetime, 2), (end_datetime, 3)], lambda m: (m.start_datetime, m.extracted) ) self.assertEqual(DTModel.objects.filter(start_datetime__quarter=ExtractQuarter('start_datetime')).count(), 2) def test_extract_quarter_func_boundaries(self): end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: end_datetime = timezone.make_aware(end_datetime, is_dst=False) last_quarter_2014 = datetime(2014, 12, 31, 13, 0) first_quarter_2015 = datetime(2015, 1, 1, 13, 0) if settings.USE_TZ: last_quarter_2014 = timezone.make_aware(last_quarter_2014, is_dst=False) first_quarter_2015 = timezone.make_aware(first_quarter_2015, is_dst=False) dates = [last_quarter_2014, first_quarter_2015] self.create_model(last_quarter_2014, end_datetime) self.create_model(first_quarter_2015, end_datetime) qs = DTModel.objects.filter(start_datetime__in=dates).annotate( extracted=ExtractQuarter('start_datetime'), ).order_by('start_datetime') self.assertQuerysetEqual(qs, [ (last_quarter_2014, 4), (first_quarter_2015, 1), ], lambda m: (m.start_datetime, m.extracted)) def test_extract_week_func_boundaries(self): end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: end_datetime = timezone.make_aware(end_datetime, is_dst=False) week_52_day_2014 = datetime(2014, 12, 27, 13, 0) # Sunday week_1_day_2014_2015 = datetime(2014, 12, 31, 13, 0) # Wednesday week_53_day_2015 = datetime(2015, 12, 31, 13, 0) # Thursday if settings.USE_TZ: week_1_day_2014_2015 = timezone.make_aware(week_1_day_2014_2015, is_dst=False) week_52_day_2014 = timezone.make_aware(week_52_day_2014, is_dst=False) week_53_day_2015 = timezone.make_aware(week_53_day_2015, is_dst=False) days = [week_52_day_2014, week_1_day_2014_2015, week_53_day_2015] self.create_model(week_53_day_2015, end_datetime) self.create_model(week_52_day_2014, end_datetime) self.create_model(week_1_day_2014_2015, end_datetime) qs = DTModel.objects.filter(start_datetime__in=days).annotate( extracted=ExtractWeek('start_datetime'), ).order_by('start_datetime') self.assertQuerysetEqual(qs, [ (week_52_day_2014, 52), (week_1_day_2014_2015, 1), (week_53_day_2015, 53), ], lambda m: (m.start_datetime, m.extracted)) def test_extract_weekday_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractWeekDay('start_datetime')).order_by('start_datetime'), [ (start_datetime, (start_datetime.isoweekday() % 7) + 1), (end_datetime, (end_datetime.isoweekday() % 7) + 1), ], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractWeekDay('start_date')).order_by('start_datetime'), [ (start_datetime, (start_datetime.isoweekday() % 7) + 1), (end_datetime, (end_datetime.isoweekday() % 7) + 1), ], lambda m: (m.start_datetime, m.extracted) ) self.assertEqual(DTModel.objects.filter(start_datetime__week_day=ExtractWeekDay('start_datetime')).count(), 2) def test_extract_iso_weekday_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate( extracted=ExtractIsoWeekDay('start_datetime'), ).order_by('start_datetime'), [ (start_datetime, start_datetime.isoweekday()), (end_datetime, end_datetime.isoweekday()), ], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate( extracted=ExtractIsoWeekDay('start_date'), ).order_by('start_datetime'), [ (start_datetime, start_datetime.isoweekday()), (end_datetime, end_datetime.isoweekday()), ], lambda m: (m.start_datetime, m.extracted) ) self.assertEqual( DTModel.objects.filter( start_datetime__week_day=ExtractWeekDay('start_datetime'), ).count(), 2, ) def test_extract_hour_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractHour('start_datetime')).order_by('start_datetime'), [(start_datetime, start_datetime.hour), (end_datetime, end_datetime.hour)], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractHour('start_time')).order_by('start_datetime'), [(start_datetime, start_datetime.hour), (end_datetime, end_datetime.hour)], lambda m: (m.start_datetime, m.extracted) ) self.assertEqual(DTModel.objects.filter(start_datetime__hour=ExtractHour('start_datetime')).count(), 2) def test_extract_minute_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractMinute('start_datetime')).order_by('start_datetime'), [(start_datetime, start_datetime.minute), (end_datetime, end_datetime.minute)], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractMinute('start_time')).order_by('start_datetime'), [(start_datetime, start_datetime.minute), (end_datetime, end_datetime.minute)], lambda m: (m.start_datetime, m.extracted) ) self.assertEqual(DTModel.objects.filter(start_datetime__minute=ExtractMinute('start_datetime')).count(), 2) def test_extract_second_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractSecond('start_datetime')).order_by('start_datetime'), [(start_datetime, start_datetime.second), (end_datetime, end_datetime.second)], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=ExtractSecond('start_time')).order_by('start_datetime'), [(start_datetime, start_datetime.second), (end_datetime, end_datetime.second)], lambda m: (m.start_datetime, m.extracted) ) self.assertEqual(DTModel.objects.filter(start_datetime__second=ExtractSecond('start_datetime')).count(), 2) def test_trunc_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) msg = 'output_field must be either DateField, TimeField, or DateTimeField' with self.assertRaisesMessage(ValueError, msg): list(DTModel.objects.annotate(truncated=Trunc('start_datetime', 'year', output_field=IntegerField()))) with self.assertRaisesMessage(AssertionError, "'name' isn't a DateField, TimeField, or DateTimeField."): list(DTModel.objects.annotate(truncated=Trunc('name', 'year', output_field=DateTimeField()))) with self.assertRaisesMessage(ValueError, "Cannot truncate DateField 'start_date' to DateTimeField"): list(DTModel.objects.annotate(truncated=Trunc('start_date', 'second'))) with self.assertRaisesMessage(ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"): list(DTModel.objects.annotate(truncated=Trunc('start_time', 'month'))) with self.assertRaisesMessage(ValueError, "Cannot truncate DateField 'start_date' to DateTimeField"): list(DTModel.objects.annotate(truncated=Trunc('start_date', 'month', output_field=DateTimeField()))) with self.assertRaisesMessage(ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"): list(DTModel.objects.annotate(truncated=Trunc('start_time', 'second', output_field=DateTimeField()))) def test_datetime_kind(kind): self.assertQuerysetEqual( DTModel.objects.annotate( truncated=Trunc('start_datetime', kind, output_field=DateTimeField()) ).order_by('start_datetime'), [ (start_datetime, truncate_to(start_datetime, kind)), (end_datetime, truncate_to(end_datetime, kind)) ], lambda m: (m.start_datetime, m.truncated) ) def test_date_kind(kind): self.assertQuerysetEqual( DTModel.objects.annotate( truncated=Trunc('start_date', kind, output_field=DateField()) ).order_by('start_datetime'), [ (start_datetime, truncate_to(start_datetime.date(), kind)), (end_datetime, truncate_to(end_datetime.date(), kind)) ], lambda m: (m.start_datetime, m.truncated) ) def test_time_kind(kind): self.assertQuerysetEqual( DTModel.objects.annotate( truncated=Trunc('start_time', kind, output_field=TimeField()) ).order_by('start_datetime'), [ (start_datetime, truncate_to(start_datetime.time(), kind)), (end_datetime, truncate_to(end_datetime.time(), kind)) ], lambda m: (m.start_datetime, m.truncated) ) test_date_kind('year') test_date_kind('quarter') test_date_kind('month') test_date_kind('week') test_date_kind('day') test_time_kind('hour') test_time_kind('minute') test_time_kind('second') test_datetime_kind('year') test_datetime_kind('quarter') test_datetime_kind('month') test_datetime_kind('week') test_datetime_kind('day') test_datetime_kind('hour') test_datetime_kind('minute') test_datetime_kind('second') qs = DTModel.objects.filter(start_datetime__date=Trunc('start_datetime', 'day', output_field=DateField())) self.assertEqual(qs.count(), 2) def test_trunc_none(self): self.create_model(None, None) for t in (Trunc('start_datetime', 'year'), Trunc('start_date', 'year'), Trunc('start_time', 'hour')): with self.subTest(t): self.assertIsNone(DTModel.objects.annotate(truncated=t).first().truncated) def test_trunc_year_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = truncate_to(datetime(2016, 6, 15, 14, 10, 50, 123), 'year') if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncYear('start_datetime')).order_by('start_datetime'), [ (start_datetime, truncate_to(start_datetime, 'year')), (end_datetime, truncate_to(end_datetime, 'year')), ], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncYear('start_date')).order_by('start_datetime'), [ (start_datetime, truncate_to(start_datetime.date(), 'year')), (end_datetime, truncate_to(end_datetime.date(), 'year')), ], lambda m: (m.start_datetime, m.extracted) ) self.assertEqual(DTModel.objects.filter(start_datetime=TruncYear('start_datetime')).count(), 1) with self.assertRaisesMessage(ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"): list(DTModel.objects.annotate(truncated=TruncYear('start_time'))) with self.assertRaisesMessage(ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"): list(DTModel.objects.annotate(truncated=TruncYear('start_time', output_field=TimeField()))) def test_trunc_quarter_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = truncate_to(datetime(2016, 10, 15, 14, 10, 50, 123), 'quarter') last_quarter_2015 = truncate_to(datetime(2015, 12, 31, 14, 10, 50, 123), 'quarter') first_quarter_2016 = truncate_to(datetime(2016, 1, 1, 14, 10, 50, 123), 'quarter') if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) last_quarter_2015 = timezone.make_aware(last_quarter_2015, is_dst=False) first_quarter_2016 = timezone.make_aware(first_quarter_2016, is_dst=False) self.create_model(start_datetime=start_datetime, end_datetime=end_datetime) self.create_model(start_datetime=end_datetime, end_datetime=start_datetime) self.create_model(start_datetime=last_quarter_2015, end_datetime=end_datetime) self.create_model(start_datetime=first_quarter_2016, end_datetime=end_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncQuarter('start_date')).order_by('start_datetime'), [ (start_datetime, truncate_to(start_datetime.date(), 'quarter')), (last_quarter_2015, truncate_to(last_quarter_2015.date(), 'quarter')), (first_quarter_2016, truncate_to(first_quarter_2016.date(), 'quarter')), (end_datetime, truncate_to(end_datetime.date(), 'quarter')), ], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncQuarter('start_datetime')).order_by('start_datetime'), [ (start_datetime, truncate_to(start_datetime, 'quarter')), (last_quarter_2015, truncate_to(last_quarter_2015, 'quarter')), (first_quarter_2016, truncate_to(first_quarter_2016, 'quarter')), (end_datetime, truncate_to(end_datetime, 'quarter')), ], lambda m: (m.start_datetime, m.extracted) ) with self.assertRaisesMessage(ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"): list(DTModel.objects.annotate(truncated=TruncQuarter('start_time'))) with self.assertRaisesMessage(ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"): list(DTModel.objects.annotate(truncated=TruncQuarter('start_time', output_field=TimeField()))) def test_trunc_month_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = truncate_to(datetime(2016, 6, 15, 14, 10, 50, 123), 'month') if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncMonth('start_datetime')).order_by('start_datetime'), [ (start_datetime, truncate_to(start_datetime, 'month')), (end_datetime, truncate_to(end_datetime, 'month')), ], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncMonth('start_date')).order_by('start_datetime'), [ (start_datetime, truncate_to(start_datetime.date(), 'month')), (end_datetime, truncate_to(end_datetime.date(), 'month')), ], lambda m: (m.start_datetime, m.extracted) ) self.assertEqual(DTModel.objects.filter(start_datetime=TruncMonth('start_datetime')).count(), 1) with self.assertRaisesMessage(ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"): list(DTModel.objects.annotate(truncated=TruncMonth('start_time'))) with self.assertRaisesMessage(ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"): list(DTModel.objects.annotate(truncated=TruncMonth('start_time', output_field=TimeField()))) def test_trunc_week_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = truncate_to(datetime(2016, 6, 15, 14, 10, 50, 123), 'week') if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncWeek('start_datetime')).order_by('start_datetime'), [ (start_datetime, truncate_to(start_datetime, 'week')), (end_datetime, truncate_to(end_datetime, 'week')), ], lambda m: (m.start_datetime, m.extracted) ) self.assertEqual(DTModel.objects.filter(start_datetime=TruncWeek('start_datetime')).count(), 1) with self.assertRaisesMessage(ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"): list(DTModel.objects.annotate(truncated=TruncWeek('start_time'))) with self.assertRaisesMessage(ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"): list(DTModel.objects.annotate(truncated=TruncWeek('start_time', output_field=TimeField()))) def test_trunc_date_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncDate('start_datetime')).order_by('start_datetime'), [ (start_datetime, start_datetime.date()), (end_datetime, end_datetime.date()), ], lambda m: (m.start_datetime, m.extracted) ) self.assertEqual(DTModel.objects.filter(start_datetime__date=TruncDate('start_datetime')).count(), 2) with self.assertRaisesMessage(ValueError, "Cannot truncate TimeField 'start_time' to DateField"): list(DTModel.objects.annotate(truncated=TruncDate('start_time'))) with self.assertRaisesMessage(ValueError, "Cannot truncate TimeField 'start_time' to DateField"): list(DTModel.objects.annotate(truncated=TruncDate('start_time', output_field=TimeField()))) def test_trunc_date_none(self): self.create_model(None, None) self.assertIsNone(DTModel.objects.annotate(truncated=TruncDate('start_datetime')).first().truncated) def test_trunc_time_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncTime('start_datetime')).order_by('start_datetime'), [ (start_datetime, start_datetime.time()), (end_datetime, end_datetime.time()), ], lambda m: (m.start_datetime, m.extracted) ) self.assertEqual(DTModel.objects.filter(start_datetime__time=TruncTime('start_datetime')).count(), 2) with self.assertRaisesMessage(ValueError, "Cannot truncate DateField 'start_date' to TimeField"): list(DTModel.objects.annotate(truncated=TruncTime('start_date'))) with self.assertRaisesMessage(ValueError, "Cannot truncate DateField 'start_date' to TimeField"): list(DTModel.objects.annotate(truncated=TruncTime('start_date', output_field=DateField()))) def test_trunc_time_none(self): self.create_model(None, None) self.assertIsNone(DTModel.objects.annotate(truncated=TruncTime('start_datetime')).first().truncated) def test_trunc_day_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = truncate_to(datetime(2016, 6, 15, 14, 10, 50, 123), 'day') if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncDay('start_datetime')).order_by('start_datetime'), [ (start_datetime, truncate_to(start_datetime, 'day')), (end_datetime, truncate_to(end_datetime, 'day')), ], lambda m: (m.start_datetime, m.extracted) ) self.assertEqual(DTModel.objects.filter(start_datetime=TruncDay('start_datetime')).count(), 1) with self.assertRaisesMessage(ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"): list(DTModel.objects.annotate(truncated=TruncDay('start_time'))) with self.assertRaisesMessage(ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"): list(DTModel.objects.annotate(truncated=TruncDay('start_time', output_field=TimeField()))) def test_trunc_hour_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = truncate_to(datetime(2016, 6, 15, 14, 10, 50, 123), 'hour') if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncHour('start_datetime')).order_by('start_datetime'), [ (start_datetime, truncate_to(start_datetime, 'hour')), (end_datetime, truncate_to(end_datetime, 'hour')), ], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncHour('start_time')).order_by('start_datetime'), [ (start_datetime, truncate_to(start_datetime.time(), 'hour')), (end_datetime, truncate_to(end_datetime.time(), 'hour')), ], lambda m: (m.start_datetime, m.extracted) ) self.assertEqual(DTModel.objects.filter(start_datetime=TruncHour('start_datetime')).count(), 1) with self.assertRaisesMessage(ValueError, "Cannot truncate DateField 'start_date' to DateTimeField"): list(DTModel.objects.annotate(truncated=TruncHour('start_date'))) with self.assertRaisesMessage(ValueError, "Cannot truncate DateField 'start_date' to DateTimeField"): list(DTModel.objects.annotate(truncated=TruncHour('start_date', output_field=DateField()))) def test_trunc_minute_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = truncate_to(datetime(2016, 6, 15, 14, 10, 50, 123), 'minute') if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncMinute('start_datetime')).order_by('start_datetime'), [ (start_datetime, truncate_to(start_datetime, 'minute')), (end_datetime, truncate_to(end_datetime, 'minute')), ], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncMinute('start_time')).order_by('start_datetime'), [ (start_datetime, truncate_to(start_datetime.time(), 'minute')), (end_datetime, truncate_to(end_datetime.time(), 'minute')), ], lambda m: (m.start_datetime, m.extracted) ) self.assertEqual(DTModel.objects.filter(start_datetime=TruncMinute('start_datetime')).count(), 1) with self.assertRaisesMessage(ValueError, "Cannot truncate DateField 'start_date' to DateTimeField"): list(DTModel.objects.annotate(truncated=TruncMinute('start_date'))) with self.assertRaisesMessage(ValueError, "Cannot truncate DateField 'start_date' to DateTimeField"): list(DTModel.objects.annotate(truncated=TruncMinute('start_date', output_field=DateField()))) def test_trunc_second_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = truncate_to(datetime(2016, 6, 15, 14, 10, 50, 123), 'second') if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncSecond('start_datetime')).order_by('start_datetime'), [ (start_datetime, truncate_to(start_datetime, 'second')), (end_datetime, truncate_to(end_datetime, 'second')) ], lambda m: (m.start_datetime, m.extracted) ) self.assertQuerysetEqual( DTModel.objects.annotate(extracted=TruncSecond('start_time')).order_by('start_datetime'), [ (start_datetime, truncate_to(start_datetime.time(), 'second')), (end_datetime, truncate_to(end_datetime.time(), 'second')) ], lambda m: (m.start_datetime, m.extracted) ) self.assertEqual(DTModel.objects.filter(start_datetime=TruncSecond('start_datetime')).count(), 1) with self.assertRaisesMessage(ValueError, "Cannot truncate DateField 'start_date' to DateTimeField"): list(DTModel.objects.annotate(truncated=TruncSecond('start_date'))) with self.assertRaisesMessage(ValueError, "Cannot truncate DateField 'start_date' to DateTimeField"): list(DTModel.objects.annotate(truncated=TruncSecond('start_date', output_field=DateField()))) def test_trunc_subquery_with_parameters(self): author_1 = Author.objects.create(name='J. R. R. Tolkien') author_2 = Author.objects.create(name='G. R. R. Martin') fan_since_1 = datetime(2016, 2, 3, 15, 0, 0) fan_since_2 = datetime(2015, 2, 3, 15, 0, 0) fan_since_3 = datetime(2017, 2, 3, 15, 0, 0) if settings.USE_TZ: fan_since_1 = timezone.make_aware(fan_since_1, is_dst=False) fan_since_2 = timezone.make_aware(fan_since_2, is_dst=False) fan_since_3 = timezone.make_aware(fan_since_3, is_dst=False) Fan.objects.create(author=author_1, name='Tom', fan_since=fan_since_1) Fan.objects.create(author=author_1, name='Emma', fan_since=fan_since_2) Fan.objects.create(author=author_2, name='Isabella', fan_since=fan_since_3) inner = Fan.objects.filter( author=OuterRef('pk'), name__in=('Emma', 'Isabella', 'Tom') ).values('author').annotate(newest_fan=Max('fan_since')).values('newest_fan') outer = Author.objects.annotate( newest_fan_year=TruncYear(Subquery(inner, output_field=DateTimeField())) ) tz = pytz.UTC if settings.USE_TZ else None self.assertSequenceEqual( outer.order_by('name').values('name', 'newest_fan_year'), [ {'name': 'G. R. R. Martin', 'newest_fan_year': datetime(2017, 1, 1, 0, 0, tzinfo=tz)}, {'name': 'J. R. R. Tolkien', 'newest_fan_year': datetime(2016, 1, 1, 0, 0, tzinfo=tz)}, ] ) @override_settings(USE_TZ=True, TIME_ZONE='UTC') class DateFunctionWithTimeZoneTests(DateFunctionTests): def test_extract_func_with_timezone(self): start_datetime = datetime(2015, 6, 15, 23, 30, 1, 321) end_datetime = datetime(2015, 6, 16, 13, 11, 27, 123) start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) melb = pytz.timezone('Australia/Melbourne') delta_tzinfo_pos = datetime_timezone(timedelta(hours=5)) delta_tzinfo_neg = datetime_timezone(timedelta(hours=-5, minutes=17)) qs = DTModel.objects.annotate( day=Extract('start_datetime', 'day'), day_melb=Extract('start_datetime', 'day', tzinfo=melb), week=Extract('start_datetime', 'week', tzinfo=melb), isoyear=ExtractIsoYear('start_datetime', tzinfo=melb), weekday=ExtractWeekDay('start_datetime'), weekday_melb=ExtractWeekDay('start_datetime', tzinfo=melb), isoweekday=ExtractIsoWeekDay('start_datetime'), isoweekday_melb=ExtractIsoWeekDay('start_datetime', tzinfo=melb), quarter=ExtractQuarter('start_datetime', tzinfo=melb), hour=ExtractHour('start_datetime'), hour_melb=ExtractHour('start_datetime', tzinfo=melb), hour_with_delta_pos=ExtractHour('start_datetime', tzinfo=delta_tzinfo_pos), hour_with_delta_neg=ExtractHour('start_datetime', tzinfo=delta_tzinfo_neg), minute_with_delta_neg=ExtractMinute('start_datetime', tzinfo=delta_tzinfo_neg), ).order_by('start_datetime') utc_model = qs.get() self.assertEqual(utc_model.day, 15) self.assertEqual(utc_model.day_melb, 16) self.assertEqual(utc_model.week, 25) self.assertEqual(utc_model.isoyear, 2015) self.assertEqual(utc_model.weekday, 2) self.assertEqual(utc_model.weekday_melb, 3) self.assertEqual(utc_model.isoweekday, 1) self.assertEqual(utc_model.isoweekday_melb, 2) self.assertEqual(utc_model.quarter, 2) self.assertEqual(utc_model.hour, 23) self.assertEqual(utc_model.hour_melb, 9) self.assertEqual(utc_model.hour_with_delta_pos, 4) self.assertEqual(utc_model.hour_with_delta_neg, 18) self.assertEqual(utc_model.minute_with_delta_neg, 47) with timezone.override(melb): melb_model = qs.get() self.assertEqual(melb_model.day, 16) self.assertEqual(melb_model.day_melb, 16) self.assertEqual(melb_model.week, 25) self.assertEqual(melb_model.isoyear, 2015) self.assertEqual(melb_model.weekday, 3) self.assertEqual(melb_model.isoweekday, 2) self.assertEqual(melb_model.quarter, 2) self.assertEqual(melb_model.weekday_melb, 3) self.assertEqual(melb_model.isoweekday_melb, 2) self.assertEqual(melb_model.hour, 9) self.assertEqual(melb_model.hour_melb, 9) def test_extract_func_explicit_timezone_priority(self): start_datetime = datetime(2015, 6, 15, 23, 30, 1, 321) end_datetime = datetime(2015, 6, 16, 13, 11, 27, 123) start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) melb = pytz.timezone('Australia/Melbourne') with timezone.override(melb): model = DTModel.objects.annotate( day_melb=Extract('start_datetime', 'day'), day_utc=Extract('start_datetime', 'day', tzinfo=timezone.utc), ).order_by('start_datetime').get() self.assertEqual(model.day_melb, 16) self.assertEqual(model.day_utc, 15) def test_trunc_timezone_applied_before_truncation(self): start_datetime = datetime(2016, 1, 1, 1, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) melb = pytz.timezone('Australia/Melbourne') pacific = pytz.timezone('US/Pacific') model = DTModel.objects.annotate( melb_year=TruncYear('start_datetime', tzinfo=melb), pacific_year=TruncYear('start_datetime', tzinfo=pacific), ).order_by('start_datetime').get() self.assertEqual(model.start_datetime, start_datetime) self.assertEqual(model.melb_year, truncate_to(start_datetime, 'year', melb)) self.assertEqual(model.pacific_year, truncate_to(start_datetime, 'year', pacific)) self.assertEqual(model.start_datetime.year, 2016) self.assertEqual(model.melb_year.year, 2016) self.assertEqual(model.pacific_year.year, 2015) def test_trunc_ambiguous_and_invalid_times(self): sao = pytz.timezone('America/Sao_Paulo') utc = pytz.timezone('UTC') start_datetime = utc.localize(datetime(2016, 10, 16, 13)) end_datetime = utc.localize(datetime(2016, 2, 21, 1)) self.create_model(start_datetime, end_datetime) with timezone.override(sao): with self.assertRaisesMessage(pytz.NonExistentTimeError, '2016-10-16 00:00:00'): model = DTModel.objects.annotate(truncated_start=TruncDay('start_datetime')).get() with self.assertRaisesMessage(pytz.AmbiguousTimeError, '2016-02-20 23:00:00'): model = DTModel.objects.annotate(truncated_end=TruncHour('end_datetime')).get() model = DTModel.objects.annotate( truncated_start=TruncDay('start_datetime', is_dst=False), truncated_end=TruncHour('end_datetime', is_dst=False), ).get() self.assertEqual(model.truncated_start.dst(), timedelta(0)) self.assertEqual(model.truncated_end.dst(), timedelta(0)) model = DTModel.objects.annotate( truncated_start=TruncDay('start_datetime', is_dst=True), truncated_end=TruncHour('end_datetime', is_dst=True), ).get() self.assertEqual(model.truncated_start.dst(), timedelta(0, 3600)) self.assertEqual(model.truncated_end.dst(), timedelta(0, 3600)) def test_trunc_func_with_timezone(self): """ If the truncated datetime transitions to a different offset (daylight saving) then the returned value will have that new timezone/offset. """ start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) melb = pytz.timezone('Australia/Melbourne') def test_datetime_kind(kind): self.assertQuerysetEqual( DTModel.objects.annotate( truncated=Trunc('start_datetime', kind, output_field=DateTimeField(), tzinfo=melb) ).order_by('start_datetime'), [ (start_datetime, truncate_to(start_datetime.astimezone(melb), kind, melb)), (end_datetime, truncate_to(end_datetime.astimezone(melb), kind, melb)) ], lambda m: (m.start_datetime, m.truncated) ) def test_date_kind(kind): self.assertQuerysetEqual( DTModel.objects.annotate( truncated=Trunc('start_date', kind, output_field=DateField(), tzinfo=melb) ).order_by('start_datetime'), [ (start_datetime, truncate_to(start_datetime.date(), kind)), (end_datetime, truncate_to(end_datetime.date(), kind)) ], lambda m: (m.start_datetime, m.truncated) ) def test_time_kind(kind): self.assertQuerysetEqual( DTModel.objects.annotate( truncated=Trunc('start_time', kind, output_field=TimeField(), tzinfo=melb) ).order_by('start_datetime'), [ (start_datetime, truncate_to(start_datetime.time(), kind)), (end_datetime, truncate_to(end_datetime.time(), kind)) ], lambda m: (m.start_datetime, m.truncated) ) test_date_kind('year') test_date_kind('quarter') test_date_kind('month') test_date_kind('week') test_date_kind('day') test_time_kind('hour') test_time_kind('minute') test_time_kind('second') test_datetime_kind('year') test_datetime_kind('quarter') test_datetime_kind('month') test_datetime_kind('week') test_datetime_kind('day') test_datetime_kind('hour') test_datetime_kind('minute') test_datetime_kind('second') qs = DTModel.objects.filter(start_datetime__date=Trunc('start_datetime', 'day', output_field=DateField())) self.assertEqual(qs.count(), 2)
/****************************************************************************** * * This file is provided under a dual BSD/GPLv2 license. When using or * redistributing this file, you may do so under either license. * * GPL LICENSE SUMMARY * * Copyright(c) 2014 Intel Corporation. All rights reserved. * Copyright(c) 2014 - 2015 Intel Mobile Communications GmbH * Copyright(c) 2016 - 2017 Intel Deutschland GmbH * Copyright (C) 2018 Intel Corporation * * This program is free software; you can redistribute it and/or modify * it under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * The full GNU General Public License is included in this distribution * in the file called COPYING. * * Contact Information: * Intel Linux Wireless <linuxwifi@intel.com> * Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497 * * BSD LICENSE * * Copyright(c) 2014 Intel Corporation. All rights reserved. * Copyright(c) 2014 - 2015 Intel Mobile Communications GmbH * Copyright(c) 2016 - 2017 Intel Deutschland GmbH * Copyright (C) 2018 Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ #ifndef __fw_error_dump_h__ #define __fw_error_dump_h__ #include <linux/types.h> #define IWL_FW_ERROR_DUMP_BARKER 0x14789632 /** * enum iwl_fw_error_dump_type - types of data in the dump file * @IWL_FW_ERROR_DUMP_CSR: Control Status Registers - from offset 0 * @IWL_FW_ERROR_DUMP_RXF: * @IWL_FW_ERROR_DUMP_TXCMD: last TX command data, structured as * &struct iwl_fw_error_dump_txcmd packets * @IWL_FW_ERROR_DUMP_DEV_FW_INFO: struct %iwl_fw_error_dump_info * info on the device / firmware. * @IWL_FW_ERROR_DUMP_FW_MONITOR: firmware monitor * @IWL_FW_ERROR_DUMP_PRPH: range of periphery registers - there can be several * sections like this in a single file. * @IWL_FW_ERROR_DUMP_FH_REGS: range of FH registers * @IWL_FW_ERROR_DUMP_MEM: chunk of memory * @IWL_FW_ERROR_DUMP_ERROR_INFO: description of what triggered this dump. * Structured as &struct iwl_fw_error_dump_trigger_desc. * @IWL_FW_ERROR_DUMP_RB: the content of an RB structured as * &struct iwl_fw_error_dump_rb * @IWL_FW_ERROR_PAGING: UMAC's image memory segments which were * paged to the DRAM. * @IWL_FW_ERROR_DUMP_RADIO_REG: Dump the radio registers. * @IWL_FW_ERROR_DUMP_EXTERNAL: used only by external code utilities, and * for that reason is not in use in any other place in the Linux Wi-Fi * stack. * @IWL_FW_ERROR_DUMP_MEM_CFG: the addresses and sizes of fifos in the smem, * which we get from the fw after ALIVE. The content is structured as * &struct iwl_fw_error_dump_smem_cfg. */ enum iwl_fw_error_dump_type { /* 0 is deprecated */ IWL_FW_ERROR_DUMP_CSR = 1, IWL_FW_ERROR_DUMP_RXF = 2, IWL_FW_ERROR_DUMP_TXCMD = 3, IWL_FW_ERROR_DUMP_DEV_FW_INFO = 4, IWL_FW_ERROR_DUMP_FW_MONITOR = 5, IWL_FW_ERROR_DUMP_PRPH = 6, IWL_FW_ERROR_DUMP_TXF = 7, IWL_FW_ERROR_DUMP_FH_REGS = 8, IWL_FW_ERROR_DUMP_MEM = 9, IWL_FW_ERROR_DUMP_ERROR_INFO = 10, IWL_FW_ERROR_DUMP_RB = 11, IWL_FW_ERROR_DUMP_PAGING = 12, IWL_FW_ERROR_DUMP_RADIO_REG = 13, IWL_FW_ERROR_DUMP_INTERNAL_TXF = 14, IWL_FW_ERROR_DUMP_EXTERNAL = 15, /* Do not move */ IWL_FW_ERROR_DUMP_MEM_CFG = 16, IWL_FW_ERROR_DUMP_D3_DEBUG_DATA = 17, IWL_FW_ERROR_DUMP_MAX, }; /** * struct iwl_fw_error_dump_data - data for one type * @type: &enum iwl_fw_error_dump_type * @len: the length starting from %data * @data: the data itself */ struct iwl_fw_error_dump_data { __le32 type; __le32 len; __u8 data[]; } __packed; /** * struct iwl_fw_error_dump_file - the layout of the header of the file * @barker: must be %IWL_FW_ERROR_DUMP_BARKER * @file_len: the length of all the file starting from %barker * @data: array of &struct iwl_fw_error_dump_data */ struct iwl_fw_error_dump_file { __le32 barker; __le32 file_len; u8 data[0]; } __packed; /** * struct iwl_fw_error_dump_txcmd - TX command data * @cmdlen: original length of command * @caplen: captured length of command (may be less) * @data: captured command data, @caplen bytes */ struct iwl_fw_error_dump_txcmd { __le32 cmdlen; __le32 caplen; u8 data[]; } __packed; /** * struct iwl_fw_error_dump_fifo - RX/TX FIFO data * @fifo_num: number of FIFO (starting from 0) * @available_bytes: num of bytes available in FIFO (may be less than FIFO size) * @wr_ptr: position of write pointer * @rd_ptr: position of read pointer * @fence_ptr: position of fence pointer * @fence_mode: the current mode of the fence (before locking) - * 0=follow RD pointer ; 1 = freeze * @data: all of the FIFO's data */ struct iwl_fw_error_dump_fifo { __le32 fifo_num; __le32 available_bytes; __le32 wr_ptr; __le32 rd_ptr; __le32 fence_ptr; __le32 fence_mode; u8 data[]; } __packed; enum iwl_fw_error_dump_family { IWL_FW_ERROR_DUMP_FAMILY_7 = 7, IWL_FW_ERROR_DUMP_FAMILY_8 = 8, }; /** * struct iwl_fw_error_dump_info - info on the device / firmware * @device_family: the family of the device (7 / 8) * @hw_step: the step of the device * @fw_human_readable: human readable FW version * @dev_human_readable: name of the device * @bus_human_readable: name of the bus used * @rt_status: the error_id/rt_status that that triggered the latest dump * if the dump collection was not initiated by an assert, the value is 0 */ struct iwl_fw_error_dump_info { __le32 device_family; __le32 hw_step; u8 fw_human_readable[FW_VER_HUMAN_READABLE_SZ]; u8 dev_human_readable[64]; u8 bus_human_readable[8]; __le32 rt_status; } __packed; /** * struct iwl_fw_error_dump_fw_mon - FW monitor data * @fw_mon_wr_ptr: the position of the write pointer in the cyclic buffer * @fw_mon_base_ptr: base pointer of the data * @fw_mon_cycle_cnt: number of wraparounds * @reserved: for future use * @data: captured data */ struct iwl_fw_error_dump_fw_mon { __le32 fw_mon_wr_ptr; __le32 fw_mon_base_ptr; __le32 fw_mon_cycle_cnt; __le32 reserved[3]; u8 data[]; } __packed; #define MAX_NUM_LMAC 2 #define TX_FIFO_INTERNAL_MAX_NUM 6 #define TX_FIFO_MAX_NUM 15 /** * struct iwl_fw_error_dump_smem_cfg - Dump SMEM configuration * This must follow &struct iwl_fwrt_shared_mem_cfg. * @num_lmacs: number of lmacs * @num_txfifo_entries: number of tx fifos * @lmac: sizes of lmacs txfifos and rxfifo1 * @rxfifo2_size: size of rxfifo2 * @internal_txfifo_addr: address of internal tx fifo * @internal_txfifo_size: size of internal tx fifo */ struct iwl_fw_error_dump_smem_cfg { __le32 num_lmacs; __le32 num_txfifo_entries; struct { __le32 txfifo_size[TX_FIFO_MAX_NUM]; __le32 rxfifo1_size; } lmac[MAX_NUM_LMAC]; __le32 rxfifo2_size; __le32 internal_txfifo_addr; __le32 internal_txfifo_size[TX_FIFO_INTERNAL_MAX_NUM]; } __packed; /** * struct iwl_fw_error_dump_prph - periphery registers data * @prph_start: address of the first register in this chunk * @data: the content of the registers */ struct iwl_fw_error_dump_prph { __le32 prph_start; __le32 data[]; }; enum iwl_fw_error_dump_mem_type { IWL_FW_ERROR_DUMP_MEM_SRAM, IWL_FW_ERROR_DUMP_MEM_SMEM, IWL_FW_ERROR_DUMP_MEM_NAMED_MEM = 10, }; /** * struct iwl_fw_error_dump_mem - chunk of memory * @type: &enum iwl_fw_error_dump_mem_type * @offset: the offset from which the memory was read * @data: the content of the memory */ struct iwl_fw_error_dump_mem { __le32 type; __le32 offset; u8 data[]; }; /** * struct iwl_fw_error_dump_named_mem - chunk of memory * @type: &enum iwl_fw_error_dump_mem_type * @offset: the offset from which the memory was read * @name_len: name length * @name: file name * @data: the content of the memory */ struct iwl_fw_error_dump_named_mem { __le32 type; __le32 offset; u8 name_len; u8 name[32]; u8 data[]; }; /** * struct iwl_fw_error_dump_rb - content of an Receive Buffer * @index: the index of the Receive Buffer in the Rx queue * @rxq: the RB's Rx queue * @reserved: * @data: the content of the Receive Buffer */ struct iwl_fw_error_dump_rb { __le32 index; __le32 rxq; __le32 reserved; u8 data[]; }; /** * struct iwl_fw_error_dump_paging - content of the UMAC's image page * block on DRAM * @index: the index of the page block * @reserved: * @data: the content of the page block */ struct iwl_fw_error_dump_paging { __le32 index; __le32 reserved; u8 data[]; }; /** * iwl_fw_error_next_data - advance fw error dump data pointer * @data: previous data block * Returns: next data block */ static inline struct iwl_fw_error_dump_data * iwl_fw_error_next_data(struct iwl_fw_error_dump_data *data) { return (void *)(data->data + le32_to_cpu(data->len)); } /** * enum iwl_fw_dbg_trigger - triggers available * * @FW_DBG_TRIGGER_USER: trigger log collection by user * This should not be defined as a trigger to the driver, but a value the * driver should set to indicate that the trigger was initiated by the * user. * @FW_DBG_TRIGGER_FW_ASSERT: trigger log collection when the firmware asserts * @FW_DBG_TRIGGER_MISSED_BEACONS: trigger log collection when beacons are * missed. * @FW_DBG_TRIGGER_CHANNEL_SWITCH: trigger log collection upon channel switch. * @FW_DBG_TRIGGER_FW_NOTIF: trigger log collection when the firmware sends a * command response or a notification. * @FW_DBG_TRIGGER_MLME: trigger log collection upon MLME event. * @FW_DBG_TRIGGER_STATS: trigger log collection upon statistics threshold. * @FW_DBG_TRIGGER_RSSI: trigger log collection when the rssi of the beacon * goes below a threshold. * @FW_DBG_TRIGGER_TXQ_TIMERS: configures the timers for the Tx queue hang * detection. * @FW_DBG_TRIGGER_TIME_EVENT: trigger log collection upon time events related * events. * @FW_DBG_TRIGGER_BA: trigger log collection upon BlockAck related events. * @FW_DBG_TX_LATENCY: trigger log collection when the tx latency goes above a * threshold. * @FW_DBG_TDLS: trigger log collection upon TDLS related events. * @FW_DBG_TRIGGER_TX_STATUS: trigger log collection upon tx status when * the firmware sends a tx reply. * @FW_DBG_TRIGGER_NO_ALIVE: trigger log collection if alive flow fails */ enum iwl_fw_dbg_trigger { FW_DBG_TRIGGER_INVALID = 0, FW_DBG_TRIGGER_USER, FW_DBG_TRIGGER_FW_ASSERT, FW_DBG_TRIGGER_MISSED_BEACONS, FW_DBG_TRIGGER_CHANNEL_SWITCH, FW_DBG_TRIGGER_FW_NOTIF, FW_DBG_TRIGGER_MLME, FW_DBG_TRIGGER_STATS, FW_DBG_TRIGGER_RSSI, FW_DBG_TRIGGER_TXQ_TIMERS, FW_DBG_TRIGGER_TIME_EVENT, FW_DBG_TRIGGER_BA, FW_DBG_TRIGGER_TX_LATENCY, FW_DBG_TRIGGER_TDLS, FW_DBG_TRIGGER_TX_STATUS, FW_DBG_TRIGGER_NO_ALIVE, /* must be last */ FW_DBG_TRIGGER_MAX, }; /** * struct iwl_fw_error_dump_trigger_desc - describes the trigger condition * @type: &enum iwl_fw_dbg_trigger * @data: raw data about what happened */ struct iwl_fw_error_dump_trigger_desc { __le32 type; u8 data[]; }; #endif /* __fw_error_dump_h__ */
# Generated by Django 3.2.8 on 2021-10-11 12:32 import datetime from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Paciente', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nome', models.CharField(max_length=100)), ('RG', models.CharField(max_length=14)), ('CPF', models.CharField(max_length=14)), ('DataCadastro', models.DateTimeField(blank=True, default=datetime.datetime.now)), ('DataNascimento', models.DateTimeField(blank=True)), ], ), ]
module.exports={A:{A:{"1":"B A","2":"K C G E WB"},B:{"1":"D u Y I M H"},C:{"2":"UB z F J K C G E B A D u Y I M H N O P Q R S SB RB","66":"T U V W X w Z","129":"0 1 2 3 5 6 7 a b c d e f L h i j k l m n o p q r s t y v g"},D:{"1":"0 1 2 3 5 6 7 N O P Q R S T U V W X w Z a b c d e f L h i j k l m n o p q r s t y v g GB BB DB VB EB","2":"F J K C G E B A D u Y I M H"},E:{"1":"K C G E B A IB JB KB LB MB","2":"F J FB AB HB"},F:{"1":"I M H N O P Q R S T U V W X w Z a b c d e f L h i j k l m n o p q r s t","2":"8 9 E A D NB OB PB QB TB x"},G:{"1":"G A ZB aB bB cB dB eB","2":"4 AB CB XB YB"},H:{"2":"fB"},I:{"1":"v kB lB","2":"4 z F gB hB iB jB"},J:{"1":"B","2":"C"},K:{"1":"L","2":"8 9 B A D x"},L:{"1":"BB"},M:{"1":"g"},N:{"1":"A","2":"B"},O:{"2":"mB"},P:{"1":"F J"},Q:{"1":"nB"},R:{"1":"oB"}},B:5,C:"WebVTT - Web Video Text Tracks"};
function enter(pi) { pi.warp(925040000,0); //backstreet }
/*! For license information please see 262bf9f6bb83288aa934600be7ca63bba17eff5d-22c69fbf2a4dddf2c2ae.js.LICENSE.txt */ (self.webpackChunkgatsby_starter_ghost=self.webpackChunkgatsby_starter_ghost||[]).push([[552],{4936:function(t){"use strict";t.exports=JSON.parse('{"layout":"constrained","placeholder":{"fallback":"data:image/webp;base64,UklGRhoCAABXRUJQVlA4WAoAAAAQAAAAEwAADwAAQUxQSDsBAAABkHTbtqnHok9s27Zt27Zt23bLtm3btlWu6ge90m28JCIUtm2DjBnewAXAhXd1Cb9E4AOScn2os0JiQEeEgdFSbxv4THUugDJizN9gAxyAt0xAtj6xIkha/rdnLyXGgHzhJVu2pwTJSP1de2bDXoKvNVRI73pTCWlpIenzm3eVzFW1gWC+GtoR5DBn4LeojilrK1dTRwt7CxtXW3NHKxtlIMADRQ1NeV01ZTVJaV0lFQNVQcyxYSXwASlF9rJAMBEDK07RJm/YK3dAsktFKeUvcW0b8Nv7a9HP8KjlkqOiIwW+oMc69U/2p9Yo6tO43Ne58JtdntfY4zac+7VKBWRlKAffd0jREDx3jv2AbmQBu6sHlvjmeiAhQ6NpRe7AK6NJzigapk+gGBtfmpSZmJaQHROXmZCfGh+b7AMAVlA4ILgAAAAwBQCdASoUABAAPtFUo0uoJKMhsAgBABoJbAB34HjP9APf/u1UgshN3Su15/waHf3EAAD+9OAFTZBT4vog/gTbnA/WHMYiL8ckN1Noje+p8q4lJnkIP2DPE8GAeaiCQWVdxURH7M7rvydxr34AwiHBfVg4FMAUqqiS9I373bbTFnbFfzf+jZ7X8TGoxM0XjD/i5QzKdWdM5CcFx+v9JQR2DS+Ds2tBzAwjBz3Mr9Zpwpza83mtoQAA"},"images":{"fallback":{"src":"/static/354cde8a94f8433635f05141d0c13a13/923ce/verticalondark.webp","srcSet":"/static/354cde8a94f8433635f05141d0c13a13/b90ba/verticalondark.webp 50w,\\n/static/354cde8a94f8433635f05141d0c13a13/d67c1/verticalondark.webp 100w,\\n/static/354cde8a94f8433635f05141d0c13a13/923ce/verticalondark.webp 200w","sizes":"(min-width: 200px) 200px, 100vw"},"sources":[]},"width":200,"height":160}')},4644:function(t){"use strict";t.exports=JSON.parse('{"layout":"constrained","placeholder":{"fallback":"data:image/webp;base64,UklGRvABAABXRUJQVlA4WAoAAAAQAAAAEwAADwAAQUxQSDsBAAABkHTbtqnHok9s27Zt27Zt23bLtm3btlWu6ge90m28JCIUtm2DjBnewAXAhXd1Cb9E4AOScn2os0JiQEeEgdFSbxv4THUugDJizN9gAxyAt0xAtj6xIkha/rdnLyXGgHzhJVu2pwTJSP1de2bDXoKvNVRI73pTCWlpIenzm3eVzFW1gWC+GtoR5DBn4LeojilrK1dTRwt7CxtXW3NHKxtlIMADRQ1NeV01ZTVJaV0lFQNVQcyxYSXwASlF9rJAMBEDK07RJm/YK3dAsktFKeUvcW0b8Nv7a9HP8KjlkqOiIwW+oMc69U/2p9Yo6tO43Ne58JtdntfY4zac+7VKBWRlKAffd0jREDx3jv2AbmQBu6sHlvjmeiAhQ6NpRe7AK6NJzigapk+gGBtfmpSZmJaQHROXmZCfGh+b7AMAVlA4II4AAABwBACdASoUABAAPtFUo0uoJKMhsAgBABoJagAxQD9APf/FrNt8sUL2mfot0AD+9CAj+e4SJKfdQAoRjMGdY+2X6ql2AIl2Mj8kLVkAUmG47hD2thazXLt7mn86NyZ9zxkfmLMeKnSvxAEQBfa5DeTc/6Q+ACOY08g07meJlFXdAYjV9mMSo5m8zugAAAAA"},"images":{"fallback":{"src":"/static/c04a985d22ece0df22764575d418cb6c/98dcb/stackedonwhitebg.webp","srcSet":"/static/c04a985d22ece0df22764575d418cb6c/470f0/stackedonwhitebg.webp 60w,\\n/static/c04a985d22ece0df22764575d418cb6c/83587/stackedonwhitebg.webp 120w,\\n/static/c04a985d22ece0df22764575d418cb6c/98dcb/stackedonwhitebg.webp 240w","sizes":"(min-width: 240px) 240px, 100vw"},"sources":[]},"width":400,"height":320}')},9169:function(t){"use strict";t.exports=JSON.parse('{"layout":"constrained","placeholder":{"fallback":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAALCAYAAAB/Ca1DAAAACXBIWXMAAAsTAAALEwEAmpwYAAADY0lEQVQozy3S/0/UdRwH8BcRLhdqfCkPPhJTb2KcSw497j7HfYX73Pf7cMcdHhzciceRub6QE3QiUSaluZirH7Jv+0xo68tGa+MXa2yttbm1VWs1rcSZXz/wQeXufUInytGztfk3PB7U0fATDRhBEdOFSMSe/igksKmAO/2dJ5Abc4hXhqziua3WJIhvv0jbj6JA2zNbuD3xQ4G6b5bUBxZoa+obUg0phbzVSo+P5oh27Zws6+Jvf9tpeoCoHQgLQIsX8IqAs3UF9rZ7eXP7nUlj9HdH3SBI2zNL2o6vqXoUtPY0CnT+Q6QamiFn7eqiNW9niHbrbk11G4AuMxC1r6BVyEP05OEV83C2Ak1RwNwJ8In70HWnz9XvuZzQtk9UPn0SVPouyK63ruIOXoqVHpu/WT58sYW6dNOhhOEeOkzZ8yHb9HNBx7xG9GQ1Lu9fMSF464y9bZGZYyvgdwO6FFC3dxmaF3KZLa8s/rbpwPwv3JHc1SffeIA17wDFJ+/OU1IPivLnHSJ/qrjNOkdBIUuiJ0du3w1ytYKsvon15l03XuXjC9d1yWXU7QNqXwbU/UD1IFDxGlD+JrDuxH2sG5k5TnH9zCMx/hq5dT4KW/9eJTZfKvS7rhS6vH8UCcHFIpv3K7LElsnkPFzcEL/co03d+V7z4tLclv3/LG0cWFzhhpbSquH0j6rBP0OPfgyikGGcXHw/+Ro/IK9lnNy2MRKaxqjZMUZ25ziZ3e+TaUclNfpPU0PnBarbm6cdkU8fezZxVv1MakpT0ztZUn5smSoO/kpad5QoaJDKRF6q8jdKnMcicW6rxAlNEtfskDi7U+IsHokzeyXOGDizQR/6vFoX/rKqPvKJSht+r7QuPFpS2/nhU+rUF1Wbez+r3tgrVVJCd/VswpDNx0yZdJuNsVYHYwE3Y14/Y84gY/YIY5Z2xoxdjDV0M6ZNsey2fZlsTV9mYVN/ZmHD4czd9cOZbMlINrv2+O152rMz83NSD8RNQIcNiAhA0AP4RMD1sI2lEzB2P1T+H6UPUA8A1UeAiteBsreA4lFg9al/QXHd9ETcMMfaTcr1iE2RQ82KHHApssenyEKLItvDimyOKrIxpsgNCUWuTyrytucVueYlRd68X5GrDimyakiRy47OzTwxcvPaf4tIrpJITE+4AAAAAElFTkSuQmCC"},"images":{"fallback":{"src":"/static/7e21e0b0c9963a5eaadf44a8064b076e/4f6e6/symbol.svg","srcSet":"/static/7e21e0b0c9963a5eaadf44a8064b076e/ef180/symbol.svg 13w,\\n/static/7e21e0b0c9963a5eaadf44a8064b076e/caf6c/symbol.svg 26w,\\n/static/7e21e0b0c9963a5eaadf44a8064b076e/4f6e6/symbol.svg 52w","sizes":"(min-width: 52px) 52px, 100vw"},"sources":[{"srcSet":"/static/7e21e0b0c9963a5eaadf44a8064b076e/363ee/symbol.webp 13w,\\n/static/7e21e0b0c9963a5eaadf44a8064b076e/9e40c/symbol.webp 26w,\\n/static/7e21e0b0c9963a5eaadf44a8064b076e/8fac9/symbol.webp 52w","type":"image/webp","sizes":"(min-width: 52px) 52px, 100vw"}]},"width":200,"height":107.6923076923077}')},7966:function(t){"use strict";t.exports=JSON.parse('{"layout":"constrained","placeholder":{"fallback":"data:image/webp;base64,UklGRvIAAABXRUJQVlA4WAoAAAAQAAAAEwAABAAAQUxQSGUAAAAAAAgABgAYrAsDAAAAAg0AAAAACQB4iEhdkzyZY3JcdmVXjXtiT32egLpZr3m9Za++M7auw22wo4a0o7OJWnA2dXxbeXlic1N2QIZVRYgOiUA+U0NMTU5NTkEtUk1OUU9RT0tWSgBWUDggZgAAADAEAJ0BKhQABQA+0VikTCglI6IwCAEAGglsAJ0yga/+A35e/8BTaDLnlAD+9P3ScjjZhP2F3nN3tJc/Gb2akbbQeyIjb+8rboYBv6/Owzc0p6cvmZJcAhEhtZxDT6bvINDTNkgAAA=="},"images":{"fallback":{"src":"/static/f3da8d6541b836d3d1178d98b540a4cf/0fef8/darkbgwhitelogo.webp","srcSet":"/static/f3da8d6541b836d3d1178d98b540a4cf/7e1ee/darkbgwhitelogo.webp 50w,\\n/static/f3da8d6541b836d3d1178d98b540a4cf/6f2cf/darkbgwhitelogo.webp 100w,\\n/static/f3da8d6541b836d3d1178d98b540a4cf/0fef8/darkbgwhitelogo.webp 200w","sizes":"(min-width: 200px) 200px, 100vw"},"sources":[]},"width":200,"height":50}')},7460:function(t){"use strict";t.exports=JSON.parse('{"layout":"constrained","placeholder":{"fallback":"data:image/webp;base64,UklGRuYAAABXRUJQVlA4WAoAAAAQAAAAEwAABAAAQUxQSGUAAAAAAAgABgAYrAsDAAAAAg0AAAAACQB4iEhdkzyZY3JcdmVXjXtiT32egLpZr3m9Za++M7auw22wo4a0o7OJWnA2dXxbeXlic1N2QIZVRYgOiUA+U0NMTU5NTkEtUk1OUU9RT0tWSgBWUDggWgAAAHAEAJ0BKhQABQA+0VSjS6gkoyGwCAEAGglsAJ0ygoAFv/gQF6H4Do0fyi6AAP70P+JRJF+P91xUcHBWyo/t326GAb+vx1mC/Eu+GBBzcIfHCYrJl02KDfMAAA=="},"images":{"fallback":{"src":"/static/091d2bdfb5066c799b52b99c36442d13/0fef8/lightbglogo.webp","srcSet":"/static/091d2bdfb5066c799b52b99c36442d13/7e1ee/lightbglogo.webp 50w,\\n/static/091d2bdfb5066c799b52b99c36442d13/6f2cf/lightbglogo.webp 100w,\\n/static/091d2bdfb5066c799b52b99c36442d13/0fef8/lightbglogo.webp 200w","sizes":"(min-width: 200px) 200px, 100vw"},"sources":[]},"width":200,"height":50}')},9439:function(t){"use strict";t.exports=JSON.parse('{"layout":"constrained","placeholder":{"fallback":"data:image/webp;base64,UklGRowBAABXRUJQVlA4WAoAAAAQAAAAEwAACwAAQUxQSO0AAAABkHPb1rHXsk9s27ZtO5VtO3m/lLZt27btVGbl5Nr26W5EJLAlLKxmi4CKFQ/Q6pkyA7OePs8B1uZ/f640gGmggxgMDnhZjF0AiTjuj10Q+e9bD5Aw9RqLKSEcX9jjMcfo/tYbmja0+I7lAFH4zv4IZd+1VKLR0TeRV1hKBhH4VboeXTA5EJO/LTEOYhVANJ5DBLZ9dtR4M4VZoPXtk5fVFbqBxR98KUl7h+gKYLzz8HDiSg5CW7hOBiP/ThThfyyi7AC0ovwAldU1FeU1NVVcJkutTnY9c7FW0kAQBIlEEASrjFvcyFS0U+OWHQAAVlA4IHgAAABQBACdASoUAAwAPtFWpEwoJKOiMAgBABoJbAAxQAVx432v9r8bvvCBmq2AAP72AXFZjNbXDwgY1qZQ0JELOeOg+/ja2fLNLwQk3D//efeRQ34z7yKC/705PA0UD9Vw9S7IR38t50VdXxVvulDZUmKj9b9W22gAAAA="},"images":{"fallback":{"src":"/static/0d74d0ec34f2e08fa6d73b9d3796a721/df6d5/abbreviation.webp","srcSet":"/static/0d74d0ec34f2e08fa6d73b9d3796a721/72517/abbreviation.webp 25w,\\n/static/0d74d0ec34f2e08fa6d73b9d3796a721/a7d58/abbreviation.webp 50w,\\n/static/0d74d0ec34f2e08fa6d73b9d3796a721/df6d5/abbreviation.webp 100w","sizes":"(min-width: 100px) 100px, 100vw"},"sources":[]},"width":100,"height":61}')},7673:function(t){"use strict";t.exports=JSON.parse('{"layout":"constrained","placeholder":{"fallback":"data:image/webp;base64,UklGRvABAABXRUJQVlA4WAoAAAAQAAAAEwAADwAAQUxQSDsBAAABkHTbtqnHok9s27Zt27Zt23bLtm3btlWu6ge90m28JCIUtm2DjBnewAXAhXd1Cb9E4AOScn2os0JiQEeEgdFSbxv4THUugDJizN9gAxyAt0xAtj6xIkha/rdnLyXGgHzhJVu2pwTJSP1de2bDXoKvNVRI73pTCWlpIenzm3eVzFW1gWC+GtoR5DBn4LeojilrK1dTRwt7CxtXW3NHKxtlIMADRQ1NeV01ZTVJaV0lFQNVQcyxYSXwASlF9rJAMBEDK07RJm/YK3dAsktFKeUvcW0b8Nv7a9HP8KjlkqOiIwW+oMc69U/2p9Yo6tO43Ne58JtdntfY4zac+7VKBWRlKAffd0jREDx3jv2AbmQBu6sHlvjmeiAhQ6NpRe7AK6NJzigapk+gGBtfmpSZmJaQHROXmZCfGh+b7AMAVlA4II4AAABwBACdASoUABAAPtFUo0uoJKMhsAgBABoJagAxQD9APf/FrNt8sUL2mfot0AD+9CAj+e4SJKfdQAoRjMGdY+2X6ql2AIl2Mj8kLVkAUmG47hD2thazXLt7mn86NyZ9zxkfmLMeKnSvxAEQBfa5DeTc/6Q+ACOY08g07meJlFXdAYjV9mMSo5m8zugAAAAA"},"images":{"fallback":{"src":"/static/c04a985d22ece0df22764575d418cb6c/d67c1/stackedonwhitebg.webp","srcSet":"/static/c04a985d22ece0df22764575d418cb6c/55a61/stackedonwhitebg.webp 25w,\\n/static/c04a985d22ece0df22764575d418cb6c/b90ba/stackedonwhitebg.webp 50w,\\n/static/c04a985d22ece0df22764575d418cb6c/d67c1/stackedonwhitebg.webp 100w,\\n/static/c04a985d22ece0df22764575d418cb6c/923ce/stackedonwhitebg.webp 200w","sizes":"(min-width: 100px) 100px, 100vw"},"sources":[]},"width":100,"height":80}')},1530:function(t,e,n){"use strict";var r=n(8710).charAt;t.exports=function(t,e,n){return e+(n?r(t,e).length:1)}},1194:function(t,e,n){var r=n(7293),a=n(5112),o=n(7392),i=a("species");t.exports=function(t){return o>=51||!r((function(){var e=[];return(e.constructor={})[i]=function(){return{foo:1}},1!==e[t](Boolean).foo}))}},6135:function(t,e,n){"use strict";var r=n(7593),a=n(3070),o=n(9114);t.exports=function(t,e,n){var i=r(e);i in t?a.f(t,i,o(0,n)):t[i]=n}},7007:function(t,e,n){"use strict";n(4916);var r=n(1320),a=n(2261),o=n(7293),i=n(5112),c=n(8880),s=i("species"),l=RegExp.prototype;t.exports=function(t,e,n,u){var f=i(t),p=!o((function(){var e={};return e[f]=function(){return 7},7!=""[t](e)})),d=p&&!o((function(){var e=!1,n=/a/;return"split"===t&&((n={}).constructor={},n.constructor[s]=function(){return n},n.flags="",n[f]=/./[f]),n.exec=function(){return e=!0,null},n[f](""),!e}));if(!p||!d||n){var h=/./[f],m=e(f,""[t],(function(t,e,n,r,o){var i=e.exec;return i===a||i===l.exec?p&&!o?{done:!0,value:h.call(e,n,r)}:{done:!0,value:t.call(n,e,r)}:{done:!1}}));r(String.prototype,t,m[0]),r(l,f,m[1])}u&&c(l[f],"sham",!0)}},647:function(t,e,n){var r=n(7908),a=Math.floor,o="".replace,i=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,c=/\$([$&'`]|\d{1,2})/g;t.exports=function(t,e,n,s,l,u){var f=n+t.length,p=s.length,d=c;return void 0!==l&&(l=r(l),d=i),o.call(u,d,(function(r,o){var i;switch(o.charAt(0)){case"$":return"$";case"&":return t;case"`":return e.slice(0,n);case"'":return e.slice(f);case"<":i=l[o.slice(1,-1)];break;default:var c=+o;if(0===c)return r;if(c>p){var u=a(c/10);return 0===u?r:u<=p?void 0===s[u-1]?o.charAt(1):s[u-1]+o.charAt(1):r}i=s[c-1]}return void 0===i?"":i}))}},490:function(t,e,n){var r=n(5005);t.exports=r("document","documentElement")},3157:function(t,e,n){var r=n(4326);t.exports=Array.isArray||function(t){return"Array"==r(t)}},7850:function(t,e,n){var r=n(111),a=n(4326),o=n(5112)("match");t.exports=function(t){var e;return r(t)&&(void 0!==(e=t[o])?!!e:"RegExp"==a(t))}},30:function(t,e,n){var r,a=n(9670),o=n(6048),i=n(748),c=n(3501),s=n(490),l=n(317),u=n(6200),f=u("IE_PROTO"),p=function(){},d=function(t){return"<script>"+t+"</"+"script>"},h=function(){try{r=document.domain&&new ActiveXObject("htmlfile")}catch(a){}var t,e;h=r?function(t){t.write(d("")),t.close();var e=t.parentWindow.Object;return t=null,e}(r):((e=l("iframe")).style.display="none",s.appendChild(e),e.src=String("javascript:"),(t=e.contentWindow.document).open(),t.write(d("document.F=Object")),t.close(),t.F);for(var n=i.length;n--;)delete h.prototype[i[n]];return h()};c[f]=!0,t.exports=Object.create||function(t,e){var n;return null!==t?(p.prototype=a(t),n=new p,p.prototype=null,n[f]=t):n=h(),void 0===e?n:o(n,e)}},6048:function(t,e,n){var r=n(9781),a=n(3070),o=n(9670),i=n(1956);t.exports=r?Object.defineProperties:function(t,e){o(t);for(var n,r=i(e),c=r.length,s=0;c>s;)a.f(t,n=r[s++],e[n]);return t}},1956:function(t,e,n){var r=n(6324),a=n(748);t.exports=Object.keys||function(t){return r(t,a)}},7651:function(t,e,n){var r=n(4326),a=n(2261);t.exports=function(t,e){var n=t.exec;if("function"==typeof n){var o=n.call(t,e);if("object"!=typeof o)throw TypeError("RegExp exec method returned something other than an Object or null");return o}if("RegExp"!==r(t))throw TypeError("RegExp#exec called on incompatible receiver");return a.call(t,e)}},2261:function(t,e,n){"use strict";var r,a,o=n(7066),i=n(2999),c=n(2309),s=n(30),l=n(9909).get,u=n(9441),f=n(8173),p=RegExp.prototype.exec,d=c("native-string-replace",String.prototype.replace),h=p,m=(r=/a/,a=/b*/g,p.call(r,"a"),p.call(a,"a"),0!==r.lastIndex||0!==a.lastIndex),v=i.UNSUPPORTED_Y||i.BROKEN_CARET,g=void 0!==/()??/.exec("")[1];(m||g||v||u||f)&&(h=function(t){var e,n,r,a,i,c,u,f=this,b=l(f),y=b.raw;if(y)return y.lastIndex=f.lastIndex,e=h.call(y,t),f.lastIndex=y.lastIndex,e;var w=b.groups,A=v&&f.sticky,x=o.call(f),E=f.source,O=0,j=t;if(A&&(-1===(x=x.replace("y","")).indexOf("g")&&(x+="g"),j=String(t).slice(f.lastIndex),f.lastIndex>0&&(!f.multiline||f.multiline&&"\n"!==t[f.lastIndex-1])&&(E="(?: "+E+")",j=" "+j,O++),n=new RegExp("^(?:"+E+")",x)),g&&(n=new RegExp("^"+E+"$(?!\\s)",x)),m&&(r=f.lastIndex),a=p.call(A?n:f,j),A?a?(a.input=a.input.slice(O),a[0]=a[0].slice(O),a.index=f.lastIndex,f.lastIndex+=a[0].length):f.lastIndex=0:m&&a&&(f.lastIndex=f.global?a.index+a[0].length:r),g&&a&&a.length>1&&d.call(a[0],n,(function(){for(i=1;i<arguments.length-2;i++)void 0===arguments[i]&&(a[i]=void 0)})),a&&w)for(a.groups=c=s(null),i=0;i<w.length;i++)c[(u=w[i])[0]]=a[u[1]];return a}),t.exports=h},7066:function(t,e,n){"use strict";var r=n(9670);t.exports=function(){var t=r(this),e="";return t.global&&(e+="g"),t.ignoreCase&&(e+="i"),t.multiline&&(e+="m"),t.dotAll&&(e+="s"),t.unicode&&(e+="u"),t.sticky&&(e+="y"),e}},2999:function(t,e,n){var r=n(7293),a=function(t,e){return RegExp(t,e)};e.UNSUPPORTED_Y=r((function(){var t=a("a","y");return t.lastIndex=2,null!=t.exec("abcd")})),e.BROKEN_CARET=r((function(){var t=a("^r","gy");return t.lastIndex=2,null!=t.exec("str")}))},9441:function(t,e,n){var r=n(7293);t.exports=r((function(){var t=RegExp(".","string".charAt(0));return!(t.dotAll&&t.exec("\n")&&"s"===t.flags)}))},8173:function(t,e,n){var r=n(7293);t.exports=r((function(){var t=RegExp("(?<a>b)","string".charAt(5));return"b"!==t.exec("b").groups.a||"bc"!=="b".replace(t,"$<a>c")}))},8710:function(t,e,n){var r=n(9958),a=n(4488),o=function(t){return function(e,n){var o,i,c=String(a(e)),s=r(n),l=c.length;return s<0||s>=l?t?"":void 0:(o=c.charCodeAt(s))<55296||o>56319||s+1===l||(i=c.charCodeAt(s+1))<56320||i>57343?t?c.charAt(s):o:t?c.slice(s,s+2):i-56320+(o-55296<<10)+65536}};t.exports={codeAt:o(!1),charAt:o(!0)}},7042:function(t,e,n){"use strict";var r=n(2109),a=n(111),o=n(3157),i=n(1400),c=n(7466),s=n(5656),l=n(6135),u=n(5112),f=n(1194)("slice"),p=u("species"),d=[].slice,h=Math.max;r({target:"Array",proto:!0,forced:!f},{slice:function(t,e){var n,r,u,f=s(this),m=c(f.length),v=i(t,m),g=i(void 0===e?m:e,m);if(o(f)&&("function"!=typeof(n=f.constructor)||n!==Array&&!o(n.prototype)?a(n)&&null===(n=n[p])&&(n=void 0):n=void 0,n===Array||void 0===n))return d.call(f,v,g);for(r=new(void 0===n?Array:n)(h(g-v,0)),u=0;v<g;v++,u++)v in f&&l(r,u,f[v]);return r.length=u,r}})},8309:function(t,e,n){var r=n(9781),a=n(3070).f,o=Function.prototype,i=o.toString,c=/^\s*function ([^ (]*)/,s="name";r&&!(s in o)&&a(o,s,{configurable:!0,get:function(){try{return i.call(this).match(c)[1]}catch(t){return""}}})},4916:function(t,e,n){"use strict";var r=n(2109),a=n(2261);r({target:"RegExp",proto:!0,forced:/./.exec!==a},{exec:a})},4723:function(t,e,n){"use strict";var r=n(7007),a=n(9670),o=n(7466),i=n(4488),c=n(1530),s=n(7651);r("match",(function(t,e,n){return[function(e){var n=i(this),r=null==e?void 0:e[t];return void 0!==r?r.call(e,n):new RegExp(e)[t](String(n))},function(t){var r=n(e,this,t);if(r.done)return r.value;var i=a(this),l=String(t);if(!i.global)return s(i,l);var u=i.unicode;i.lastIndex=0;for(var f,p=[],d=0;null!==(f=s(i,l));){var h=String(f[0]);p[d]=h,""===h&&(i.lastIndex=c(l,o(i.lastIndex),u)),d++}return 0===d?null:p}]}))},5306:function(t,e,n){"use strict";var r=n(7007),a=n(7293),o=n(9670),i=n(7466),c=n(9958),s=n(4488),l=n(1530),u=n(647),f=n(7651),p=n(5112)("replace"),d=Math.max,h=Math.min,m="$0"==="a".replace(/./,"$0"),v=!!/./[p]&&""===/./[p]("a","$0");r("replace",(function(t,e,n){var r=v?"$":"$0";return[function(t,n){var r=s(this),a=null==t?void 0:t[p];return void 0!==a?a.call(t,r,n):e.call(String(r),t,n)},function(t,a){if("string"==typeof a&&-1===a.indexOf(r)&&-1===a.indexOf("$<")){var s=n(e,this,t,a);if(s.done)return s.value}var p=o(this),m=String(t),v="function"==typeof a;v||(a=String(a));var g=p.global;if(g){var b=p.unicode;p.lastIndex=0}for(var y=[];;){var w=f(p,m);if(null===w)break;if(y.push(w),!g)break;""===String(w[0])&&(p.lastIndex=l(m,i(p.lastIndex),b))}for(var A,x="",E=0,O=0;O<y.length;O++){w=y[O];for(var j=String(w[0]),_=d(h(c(w.index),m.length),0),k=[],S=1;S<w.length;S++)k.push(void 0===(A=w[S])?A:String(A));var T=w.groups;if(v){var C=[j].concat(k,_,m);void 0!==T&&C.push(T);var I=String(a.apply(void 0,C))}else I=u(j,m,_,k,T,a);_>=E&&(x+=m.slice(E,_)+I,E=_+j.length)}return x+m.slice(E)}]}),!!a((function(){var t=/./;return t.exec=function(){var t=[];return t.groups={a:"7"},t},"7"!=="".replace(t,"$<a>")}))||!m||v)},3123:function(t,e,n){"use strict";var r=n(7007),a=n(7850),o=n(9670),i=n(4488),c=n(6707),s=n(1530),l=n(7466),u=n(7651),f=n(2261),p=n(2999),d=n(7293),h=p.UNSUPPORTED_Y,m=[].push,v=Math.min,g=4294967295;r("split",(function(t,e,n){var r;return r="c"=="abbc".split(/(b)*/)[1]||4!="test".split(/(?:)/,-1).length||2!="ab".split(/(?:ab)*/).length||4!=".".split(/(.?)(.?)/).length||".".split(/()()/).length>1||"".split(/.?/).length?function(t,n){var r=String(i(this)),o=void 0===n?g:n>>>0;if(0===o)return[];if(void 0===t)return[r];if(!a(t))return e.call(r,t,o);for(var c,s,l,u=[],p=(t.ignoreCase?"i":"")+(t.multiline?"m":"")+(t.unicode?"u":"")+(t.sticky?"y":""),d=0,h=new RegExp(t.source,p+"g");(c=f.call(h,r))&&!((s=h.lastIndex)>d&&(u.push(r.slice(d,c.index)),c.length>1&&c.index<r.length&&m.apply(u,c.slice(1)),l=c[0].length,d=s,u.length>=o));)h.lastIndex===c.index&&h.lastIndex++;return d===r.length?!l&&h.test("")||u.push(""):u.push(r.slice(d)),u.length>o?u.slice(0,o):u}:"0".split(void 0,0).length?function(t,n){return void 0===t&&0===n?[]:e.call(this,t,n)}:e,[function(e,n){var a=i(this),o=null==e?void 0:e[t];return void 0!==o?o.call(e,a,n):r.call(String(a),e,n)},function(t,a){var i=n(r,this,t,a,r!==e);if(i.done)return i.value;var f=o(this),p=String(t),d=c(f,RegExp),m=f.unicode,b=(f.ignoreCase?"i":"")+(f.multiline?"m":"")+(f.unicode?"u":"")+(h?"g":"y"),y=new d(h?"^(?:"+f.source+")":f,b),w=void 0===a?g:a>>>0;if(0===w)return[];if(0===p.length)return null===u(y,p)?[p]:[];for(var A=0,x=0,E=[];x<p.length;){y.lastIndex=h?0:x;var O,j=u(y,h?p.slice(x):p);if(null===j||(O=v(l(y.lastIndex+(h?x:0)),p.length))===A)x=s(p,x,m);else{if(E.push(p.slice(A,x)),E.length===w)return E;for(var _=1;_<=j.length-1;_++)if(E.push(j[_]),E.length===w)return E;x=A=O}}return E.push(p.slice(A)),E}]}),!!d((function(){var t=/(?:)/,e=t.exec;t.exec=function(){return e.apply(this,arguments)};var n="ab".split(t);return 2!==n.length||"a"!==n[0]||"b"!==n[1]})),h)},3954:function(t,e,n){"use strict";var r=n(7294);e.Z=function(t){var e=t.btnlink,n=t.btntext;return r.createElement("div",{className:"button-group"},r.createElement("a",{className:"rn-button wow fadeInLeft","data-wow-delay":"100ms","data-wow-duration":"1000ms",href:e},r.createElement("span",null,n)))}},6547:function(t,e,n){"use strict";n(7294),n.p},1431:function(t,e,n){"use strict";n.d(e,{U:function(){return I}});var r=n(7490),a=n(7294),o=n(5444),i=n(4755),c=n(6895),s=n.n(c),l=n(7361),u=n.n(l),f=n(5161),p=n.n(f),d=n(1232),h=n(8611),m=n.n(h),v=n(9693),g=n.n(v),b=n(5697),y=n.n(b),w=function(t){var e=[];return e.push(t.website?t.website:null,t.twitter?"https://twitter.com/"+t.twitter.replace(/^@/,"")+"/":null,t.facebook?"https://www.facebook.com/"+t.facebook.replace(/^\//,"")+"/":null),e=g()(e),{name:t.name||null,sameAsArray:e.length?'["'+m()(e,'", "')+'"]':null,image:t.profile_image||null,facebookUrl:t.facebook?"https://www.facebook.com/"+t.facebook.replace(/^\//,"")+"/":null}};w.defaultProps={fetchAuthorData:!1},w.PropTypes={primaryAuthor:y().shape({name:y().string.isRequired,profile_image:y().string,website:y().string,twitter:y().string,facebook:y().string}).isRequired};var A=w,x=function(t){var e=t.image;return e?a.createElement(d.q,null,a.createElement("meta",{name:"twitter:card",content:"summary_large_image"}),a.createElement("meta",{name:"twitter:image",content:e}),a.createElement("meta",{property:"og:image",content:e}),a.createElement("meta",{property:"og:image:width",content:s().shareImageWidth}),a.createElement("meta",{property:"og:image:height",content:s().shareImageHeight})):null},E=n(8733),O=function(t){var e=t.data,n=t.settings,r=t.canonical,o=e;n=n.allGhostSettings.edges[0].node;var c=A(o.primary_author),l=p()((0,E.tags)(o,{visibility:"public",fn:function(t){return t}}),"name"),f=l[0]||"",h=o.feature_image?o.feature_image:u()(n,"cover_image",null),m=n.logo||s().siteIcon?i.resolve(s().siteUrl,n.logo||s().siteIcon):null,v={"@context":"https://schema.org/","@type":"Article",author:{"@type":"Person",name:c.name,image:c.image?c.image:void 0,sameAs:c.sameAsArray?c.sameAsArray:void 0},keywords:l.length?l.join(", "):void 0,headline:o.meta_title||o.title,url:r,datePublished:o.published_at,dateModified:o.updated_at,image:h?{"@type":"ImageObject",url:h,width:s().shareImageWidth,height:s().shareImageHeight}:void 0,publisher:{"@type":"Organization",name:n.title,logo:{"@type":"ImageObject",url:m,width:60,height:60}},description:o.meta_description||o.excerpt,mainEntityOfPage:{"@type":"WebPage","@id":s().siteUrl}};return a.createElement(a.Fragment,null,a.createElement(d.q,null,a.createElement("title",null,o.meta_title||o.title),a.createElement("meta",{name:"description",content:o.meta_description||o.excerpt}),a.createElement("link",{rel:"canonical",href:r}),a.createElement("meta",{property:"og:site_name",content:n.title}),a.createElement("meta",{property:"og:type",content:"article"}),a.createElement("meta",{property:"og:title",content:o.og_title||o.meta_title||o.title}),a.createElement("meta",{property:"og:description",content:o.og_description||o.excerpt||o.meta_description}),a.createElement("meta",{property:"og:url",content:r}),a.createElement("meta",{property:"article:published_time",content:o.published_at}),a.createElement("meta",{property:"article:modified_time",content:o.updated_at}),l.map((function(t,e){return a.createElement("meta",{property:"article:tag",content:t,key:e})})),c.facebookUrl&&a.createElement("meta",{property:"article:author",content:c.facebookUrl}),a.createElement("meta",{name:"twitter:title",content:o.twitter_title||o.meta_title||o.title}),a.createElement("meta",{name:"twitter:description",content:o.twitter_description||o.excerpt||o.meta_description}),a.createElement("meta",{name:"twitter:url",content:r}),a.createElement("meta",{name:"twitter:label1",content:"Written by"}),a.createElement("meta",{name:"twitter:data1",content:c.name}),f&&a.createElement("meta",{name:"twitter:label2",content:"Filed under"}),f&&a.createElement("meta",{name:"twitter:data2",content:f}),n.twitter&&a.createElement("meta",{name:"twitter:site",content:"https://twitter.com/"+n.twitter.replace(/^@/,"")+"/"}),n.twitter&&a.createElement("meta",{name:"twitter:creator",content:n.twitter}),a.createElement("script",{type:"application/ld+json"},JSON.stringify(v,void 0,4))),a.createElement(x,{image:h}))},j=function(t){return a.createElement(o.StaticQuery,{query:"2731221146",render:function(e){return a.createElement(O,(0,r.Z)({settings:e},t))}})},_=function(t){var e=t.data,n=t.settings,r=t.canonical,o=t.title,c=t.description,l=t.image,f=t.type;n=n.allGhostSettings.edges[0].node;var p=i.resolve(s().siteUrl,n.logo||s().siteIcon),h=l||e.feature_image||u()(n,"cover_image",null);h=h?i.resolve(s().siteUrl,h):null,c=c||e.meta_description||e.description||s().siteDescriptionMeta||n.description,o=(o||e.meta_title||e.name||e.title)+" - "+n.title;var m={"@context":"https://schema.org/","@type":f,url:r,image:h?{"@type":"ImageObject",url:h,width:s().shareImageWidth,height:s().shareImageHeight}:void 0,publisher:{"@type":"Organization",name:n.title,logo:{"@type":"ImageObject",url:p,width:60,height:60}},mainEntityOfPage:{"@type":"WebPage","@id":s().siteUrl},description:c};return a.createElement(a.Fragment,null,a.createElement(d.q,null,a.createElement("title",null,o),a.createElement("meta",{name:"description",content:c}),a.createElement("link",{rel:"canonical",href:r}),a.createElement("meta",{property:"og:site_name",content:n.title}),a.createElement("meta",{property:"og:type",content:"website"}),a.createElement("meta",{property:"og:title",content:o}),a.createElement("meta",{property:"og:description",content:c}),a.createElement("meta",{property:"og:url",content:r}),a.createElement("meta",{name:"twitter:title",content:o}),a.createElement("meta",{name:"twitter:description",content:c}),a.createElement("meta",{name:"twitter:url",content:r}),n.twitter&&a.createElement("meta",{name:"twitter:site",content:"https://twitter.com/"+n.twitter.replace(/^@/,"")+"/"}),n.twitter&&a.createElement("meta",{name:"twitter:creator",content:n.twitter}),a.createElement("script",{type:"application/ld+json"},JSON.stringify(m,void 0,4))),a.createElement(x,{image:h}))},k=function(t){return a.createElement(o.StaticQuery,{query:"2561578252",render:function(e){return a.createElement(_,(0,r.Z)({settings:e},t))}})},S=function(t){var e=t.data,n=t.settings,r=t.canonical;n=n.allGhostSettings.edges[0].node;var o=A(e),i=o.image||u()(n,"cover_image",null),c=e.name+" - "+n.title,l=e.bio||s().siteDescriptionMeta||n.description,f={"@context":"https://schema.org/","@type":"Person",name:e.name,sameAs:o.sameAsArray?o.sameAsArray:void 0,url:r,image:i?{"@type":"ImageObject",url:i,width:s().shareImageWidth,height:s().shareImageHeight}:void 0,mainEntityOfPage:{"@type":"WebPage","@id":s().siteUrl},description:l};return a.createElement(a.Fragment,null,a.createElement(d.q,null,a.createElement("title",null,c),a.createElement("meta",{name:"description",content:l}),a.createElement("link",{rel:"canonical",href:r}),a.createElement("meta",{property:"og:site_name",content:n.title}),a.createElement("meta",{property:"og:type",content:"profile"}),a.createElement("meta",{property:"og:title",content:c}),a.createElement("meta",{property:"og:description",content:l}),a.createElement("meta",{property:"og:url",content:r}),a.createElement("meta",{name:"twitter:title",content:c}),a.createElement("meta",{name:"twitter:description",content:l}),a.createElement("meta",{name:"twitter:url",content:r}),n.twitter&&a.createElement("meta",{name:"twitter:site",content:"https://twitter.com/"+n.twitter.replace(/^@/,"")+"/"}),n.twitter&&a.createElement("meta",{name:"twitter:creator",content:n.twitter}),a.createElement("script",{type:"application/ld+json"},JSON.stringify(f,void 0,4))),a.createElement(x,{image:i}))},T=function(t){return a.createElement(o.StaticQuery,{query:"4145280475",render:function(e){return a.createElement(S,(0,r.Z)({settings:e},t))}})},C=function(t){var e=t.data,n=t.settings,r=t.title,o=t.description,c=t.image,l=t.location,u=i.resolve(s().siteUrl,l.pathname),f=e.ghostPost,p=e.ghostTag,d=e.ghostAuthor,h=e.ghostPage;return n=n.allGhostSettings.edges[0].node,f?a.createElement(j,{data:f,canonical:u}):p?a.createElement(k,{data:p,canonical:u,type:"Series"}):d?a.createElement(T,{data:d,canonical:u}):h?a.createElement(k,{data:h,canonical:u,type:"WebSite"}):(r=r||s().siteTitleMeta||n.title,o=o||s().siteDescriptionMeta||n.description,c=(c=c||n.cover_image||null)?i.resolve(s().siteUrl,c):null,a.createElement(k,{data:{},canonical:u,title:r,description:o,image:c,type:"WebSite"}))};C.defaultProps={data:{}};var I=function(t){return a.createElement(o.StaticQuery,{query:"2358152166",render:function(e){return a.createElement(C,(0,r.Z)({settings:e},t))}})}},3904:function(t,e,n){"use strict";n.d(e,{Z:function(){return nt}});var r=n(7294),a=r.lazy((function(){return n.e(959).then(n.bind(n,2959))})),o=function(){var t="undefined"==typeof window;return r.createElement(r.Fragment,null,!t&&r.createElement(r.Suspense,{fallback:r.createElement("div",null)},r.createElement(a,null)))},i=n(3954),c=n(2407);function s(t){var e=t.type,a=t.classes;switch(e){case"standard":return r.createElement(r.Fragment,null,r.createElement(c.S,{src:"../../images/logo/darkbgwhitelogo.webp",alt:"White Logo",placeholder:"blurred",layout:"constrained",width:200,className:a,__imageData:n(7966)}));case"darkversion":return r.createElement(r.Fragment,null,r.createElement(c.S,{src:"../../images/logo/lightbglogo.webp",alt:"Black Logo",placeholder:"blurred",layout:"constrained",width:200,className:a,__imageData:n(7460)}));case"stackedwhite":return r.createElement(r.Fragment,null,r.createElement(c.S,{src:"../../images/logo/stackedonwhitebg.webp",alt:"White Logo",placeholder:"blurred",layout:"constrained",width:100,className:a,__imageData:n(7673)}));case"stackeddark":return r.createElement(r.Fragment,null,r.createElement(c.S,{src:"../../images/logo/verticalondark.webp",alt:"BlackLogo",placeholder:"blurred",layout:"constrained",width:200,className:a,__imageData:n(4936)}));case"symbol":return r.createElement(r.Fragment,null,r.createElement(c.S,{src:"../../images/logo/symbol.svg",alt:"Symbol",placeholder:"blurred",layout:"constrained",width:200,className:a,__imageData:n(9169)}));case"abbreviation":return r.createElement(r.Fragment,null,r.createElement(c.S,{src:"../../images/logo/abbreviation.webp",alt:"Abbreviation",placeholder:"blurred",layout:"constrained",width:100,className:a,__imageData:n(9439)}));default:return r.createElement(r.Fragment,null,r.createElement(c.S,{src:"../../images/logo/stackedonwhitebg.webp",alt:"Placeholder",placeholder:"blurred",layout:"constrained",width:400,className:a,__imageData:n(4644)}))}}s.defaultProps={type:"standard",classes:""};var l,u,f,p=s,d=n(1943),h=function(t){function e(){return t.apply(this,arguments)||this}return(0,d.Z)(e,t),e.prototype.render=function(){var t=this.props.text,e=this.props.link;return r.createElement("a",{className:"linky","data-text":t,href:e},t)},e}(r.Component),m=n(5444);function v(){return(v=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t}).apply(this,arguments)}function g(t,e){if(null==t)return{};var n,r,a={},o=Object.keys(t);for(r=0;r<o.length;r++)n=o[r],e.indexOf(n)>=0||(a[n]=t[n]);return a}function b(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}function y(t,e){var n;if("undefined"==typeof Symbol||null==t[Symbol.iterator]){if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return b(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?b(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}return(n=t[Symbol.iterator]()).next.bind(n)}function w(t,e){if(t in e){for(var n=e[t],r=arguments.length,a=new Array(r>2?r-2:0),o=2;o<r;o++)a[o-2]=arguments[o];return"function"==typeof n?n.apply(void 0,a):n}var i=new Error('Tried to handle "'+t+'" but there is no handler defined. Only defined handlers are: '+Object.keys(e).map((function(t){return'"'+t+'"'})).join(", ")+".");throw Error.captureStackTrace&&Error.captureStackTrace(i,w),i}function A(t){var e=t.props,n=t.slot,r=t.defaultTag,a=t.features,o=t.visible,i=void 0===o||o,c=t.name;if(i)return x(e,n,r,c);var s=null!=a?a:l.None;if(s&l.Static){var f=e.static,p=void 0!==f&&f,d=g(e,["static"]);if(p)return x(d,n,r,c)}if(s&l.RenderStrategy){var h,m=e.unmount,b=void 0===m||m,y=g(e,["unmount"]);return w(b?u.Unmount:u.Hidden,((h={})[u.Unmount]=function(){return null},h[u.Hidden]=function(){return x(v({},y,{hidden:!0,style:{display:"none"}}),n,r,c)},h))}return x(e,n,r,c)}function x(t,e,n,a){var o;void 0===e&&(e={});var i=O(t,["unmount","static"]),c=i.as,s=void 0===c?n:c,l=i.children,u=i.refName,f=void 0===u?"ref":u,p=g(i,["as","children","refName"]),d=void 0!==t.ref?((o={})[f]=t.ref,o):{},h="function"==typeof l?l(e):l;if(p.className&&"function"==typeof p.className&&(p.className=p.className(e)),s===r.Fragment&&Object.keys(p).length>0){if(!(0,r.isValidElement)(h)||Array.isArray(h)&&h.length>1)throw new Error(['Passing props on "Fragment"!',"","The current component <"+a+' /> is rendering a "Fragment".',"However we need to passthrough the following props:",Object.keys(p).map((function(t){return" - "+t})).join("\n"),"","You can apply a few solutions:",['Add an `as="..."` prop, to ensure that we render an actual element instead of a "Fragment".',"Render a single element as the child so that we can forward the props onto that element."].map((function(t){return" - "+t})).join("\n")].join("\n"));return(0,r.cloneElement)(h,Object.assign({},function(t,e,n){for(var r,a=Object.assign({},t),o=function(){var n,o=r.value;void 0!==t[o]&&void 0!==e[o]&&Object.assign(a,((n={})[o]=function(n){n.defaultPrevented||t[o](n),n.defaultPrevented||e[o](n)},n))},i=y(n);!(r=i()).done;)o();return a}(function(t){var e=Object.assign({},t);for(var n in e)void 0===e[n]&&delete e[n];return e}(O(p,["ref"])),h.props,["onClick"]),d))}return(0,r.createElement)(s,Object.assign({},O(p,["ref"]),s!==r.Fragment&&d),h)}function E(t){var e;return Object.assign((0,r.forwardRef)(t),{displayName:null!=(e=t.displayName)?e:t.name})}function O(t,e){void 0===e&&(e=[]);for(var n,r=Object.assign({},t),a=y(e);!(n=a()).done;){var o=n.value;o in r&&delete r[o]}return r}function j(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];var a=(0,r.useRef)(e);return(0,r.useEffect)((function(){a.current=e}),[e]),(0,r.useCallback)((function(t){for(var e,n=y(a.current);!(e=n()).done;){var r=e.value;null!=r&&("function"==typeof r?r(t):r.current=t)}}),[a])}function _(t){for(var e,n,r=t.parentElement,a=null;r&&!(r instanceof HTMLFieldSetElement);)r instanceof HTMLLegendElement&&(a=r),r=r.parentElement;var o=null!=(e=""===(null==(n=r)?void 0:n.getAttribute("disabled")))&&e;return(!o||!function(t){if(!t)return!1;var e=t.previousElementSibling;for(;null!==e;){if(e instanceof HTMLLegendElement)return!1;e=e.previousElementSibling}return!0}(a))&&o}!function(t){t[t.None=0]="None",t[t.RenderStrategy=1]="RenderStrategy",t[t.Static=2]="Static"}(l||(l={})),function(t){t[t.Unmount=0]="Unmount",t[t.Hidden=1]="Hidden"}(u||(u={})),function(t){t.Space=" ",t.Enter="Enter",t.Escape="Escape",t.Backspace="Backspace",t.ArrowLeft="ArrowLeft",t.ArrowUp="ArrowUp",t.ArrowRight="ArrowRight",t.ArrowDown="ArrowDown",t.Home="Home",t.End="End",t.PageUp="PageUp",t.PageDown="PageDown",t.Tab="Tab"}(f||(f={}));var k="undefined"!=typeof window?r.useLayoutEffect:r.useEffect,S={serverHandoffComplete:!1};var T=0;function C(){return++T}function I(){var t=function(){var t=(0,r.useState)(S.serverHandoffComplete),e=t[0],n=t[1];return(0,r.useEffect)((function(){!0!==e&&n(!0)}),[e]),(0,r.useEffect)((function(){!1===S.serverHandoffComplete&&(S.serverHandoffComplete=!0)}),[]),e}(),e=(0,r.useState)(t?C:null),n=e[0],a=e[1];return k((function(){null===n&&a(C())}),[n]),null!=n?""+n:void 0}var N,P,z,M,U=(0,r.createContext)(null);function R(t){var e=t.value,n=t.children;return r.createElement(U.Provider,{value:e},n)}U.displayName="OpenClosedContext",function(t){t[t.Open=0]="Open",t[t.Closed=1]="Closed"}(N||(N={})),function(t){t[t.Open=0]="Open",t[t.Closed=1]="Closed"}(z||(z={})),function(t){t[t.ToggleDisclosure=0]="ToggleDisclosure",t[t.SetButtonId=1]="SetButtonId",t[t.SetPanelId=2]="SetPanelId",t[t.LinkPanel=3]="LinkPanel",t[t.UnlinkPanel=4]="UnlinkPanel"}(M||(M={}));var L=((P={})[M.ToggleDisclosure]=function(t){var e;return v({},t,{disclosureState:w(t.disclosureState,(e={},e[z.Open]=z.Closed,e[z.Closed]=z.Open,e))})},P[M.LinkPanel]=function(t){return!0===t.linkedPanel?t:v({},t,{linkedPanel:!0})},P[M.UnlinkPanel]=function(t){return!1===t.linkedPanel?t:v({},t,{linkedPanel:!1})},P[M.SetButtonId]=function(t,e){return t.buttonId===e.buttonId?t:v({},t,{buttonId:e.buttonId})},P[M.SetPanelId]=function(t,e){return t.panelId===e.panelId?t:v({},t,{panelId:e.panelId})},P),D=(0,r.createContext)(null);function B(t){var e=(0,r.useContext)(D);if(null===e){var n=new Error("<"+t+" /> is missing a parent <"+W.name+" /> component.");throw Error.captureStackTrace&&Error.captureStackTrace(n,B),n}return e}function F(t,e){return w(e.type,L,t,e)}D.displayName="DisclosureContext";var H=r.Fragment;function W(t){var e,n=t.defaultOpen,a=void 0!==n&&n,o=g(t,["defaultOpen"]),i="headlessui-disclosure-button-"+I(),c="headlessui-disclosure-panel-"+I(),s=(0,r.useReducer)(F,{disclosureState:a?z.Open:z.Closed,linkedPanel:!1,buttonId:i,panelId:c}),l=s[0].disclosureState,u=s[1];(0,r.useEffect)((function(){return u({type:M.SetButtonId,buttonId:i})}),[i,u]),(0,r.useEffect)((function(){return u({type:M.SetPanelId,panelId:c})}),[c,u]);var f=(0,r.useMemo)((function(){return{open:l===z.Open}}),[l]);return r.createElement(D.Provider,{value:s},r.createElement(R,{value:w(l,(e={},e[z.Open]=N.Open,e[z.Closed]=N.Closed,e))},A({props:o,slot:f,defaultTag:H,name:"Disclosure"})))}var Q=E((function t(e,n){var a=B([W.name,t.name].join(".")),o=a[0],i=a[1],c=j(n),s=(0,r.useCallback)((function(t){switch(t.key){case f.Space:case f.Enter:t.preventDefault(),t.stopPropagation(),i({type:M.ToggleDisclosure})}}),[i]),l=(0,r.useCallback)((function(t){switch(t.key){case f.Space:t.preventDefault()}}),[]),u=(0,r.useCallback)((function(t){_(t.currentTarget)||e.disabled||i({type:M.ToggleDisclosure})}),[i,e.disabled]),p=(0,r.useMemo)((function(){return{open:o.disclosureState===z.Open}}),[o]);return A({props:v({},e,{ref:c,id:o.buttonId,type:"button","aria-expanded":e.disabled?void 0:o.disclosureState===z.Open,"aria-controls":o.linkedPanel?o.panelId:void 0,onKeyDown:s,onKeyUp:l,onClick:u}),slot:p,defaultTag:"button",name:"Disclosure.Button"})})),J=l.RenderStrategy|l.Static,V=E((function t(e,n){var a=B([W.name,t.name].join(".")),o=a[0],i=a[1],c=j(n,(function(){o.linkedPanel||i({type:M.LinkPanel})})),s=(0,r.useContext)(U),l=null!==s?s===N.Open:o.disclosureState===z.Open;(0,r.useEffect)((function(){return function(){return i({type:M.UnlinkPanel})}}),[i]),(0,r.useEffect)((function(){var t;o.disclosureState!==z.Closed||null!=(t=e.unmount)&&!t||i({type:M.UnlinkPanel})}),[o.disclosureState,e.unmount,i]);var u=(0,r.useMemo)((function(){return{open:o.disclosureState===z.Open}}),[o]),f={ref:c,id:o.panelId};return A({props:v({},e,f),slot:u,defaultTag:"div",features:J,visible:l,name:"Disclosure.Panel"})}));W.Button=Q,W.Panel=V;var K=function(t){return r.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor"},t),r.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 6h16M4 12h16M4 18h16"}))};var X=function(t){return r.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor"},t),r.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"}))};var Y=n(4815),q=n(6987);n(6895);function Z(){return r.createElement(W,{as:"nav",className:"bg-transparent"},(function(t){var e=t.open;return r.createElement(r.Fragment,null,r.createElement("div",{className:"h-40 max-w-full px-16 mx-auto sm:px-10 lg:px-10 sm:py-10 lg:py-8"},r.createElement("div",{className:"flex justify-between h-40 px-16"},r.createElement("div",{className:"flex h402"},r.createElement("div",{className:"flex items-center h-40 mr-2 -ml-2 md:hidden"},r.createElement(W.Button,{className:"inline-flex items-center justify-center p-2 text-white rounded-md hover:text-white hover:bg-gray-100 focus:outline-none "},r.createElement("span",{className:"sr-only"},"Open main menu"),e?r.createElement(X,{className:"block w-10 h-10","aria-hidden":"true"}):r.createElement(K,{className:"block w-10 h-10","aria-hidden":"true"}))),r.createElement("div",{className:"flex items-center flex-shrink-0"},r.createElement(m.Link,{href:"/"}," ",r.createElement(p,{type:"abbreviation",classes:"inline-block lg:hidden xl:hidden md:hidden h-auto w-auto"}))," ",r.createElement(m.Link,{href:"/"}," ",r.createElement(p,{type:"standard",classes:"hidden lg:inline-block xl:inline-block md:inline-block h-auto w-auto"}))," "),r.createElement("div",{className:"hidden ml-10 md:ml-6 md:flex md:items-center md:space-x-4"},r.createElement(m.Link,{href:"/",className:"text-base font-medium"}," ",r.createElement("span",null,r.createElement(h,{text:"Home"}))),r.createElement(m.Link,{href:"/about",className:"text-base font-medium"}," ",r.createElement("span",null,r.createElement(h,{text:"About Us"}))),r.createElement(m.Link,{href:"/#services",className:"text-base font-medium"}," ",r.createElement("span",null,r.createElement(h,{text:"Services"}))),r.createElement(m.Link,{href:"/contact",className:"text-base font-medium"}," ",r.createElement("span",null,r.createElement(h,{text:"Contact"}))))),r.createElement("div",{className:"flex items-center"},r.createElement("div",{className:"flex-shrink-0"},r.createElement(i.Z,{btntext:"Schedule a Call",className:"wow fadeInLeft","data-wow-delay":"100ms","data-wow-duration":"1000ms",btnlink:"schedule"}))))),r.createElement(W.Panel,{className:" md:hidden"},r.createElement("div",{className:"h-full px-2 pt-2 pb-3 ml-10 space-y-1 rounded-4xl sm:px-3 bg-black-gradient"},r.createElement("ul",null,r.createElement("li",null," ",r.createElement(m.Link,{href:"/",className:"text-base font-heaviest"}," ",r.createElement("span",null,r.createElement(h,{text:"Home"})))),r.createElement("li",null," ",r.createElement(m.Link,{href:"/about",className:"text-base font-heaviest"}," ",r.createElement("span",null,r.createElement(h,{text:"About Us"})))),r.createElement("li",null," ",r.createElement(m.Link,{href:"/#services",className:"text-base font-heaviest"}," ",r.createElement("span",null,r.createElement(h,{text:"Services"})))),r.createElement("li",null," ",r.createElement(m.Link,{href:"/contact",className:"text-base font-heaviest"}," ",r.createElement("span",null,r.createElement(h,{text:"Contact"})))),r.createElement("li",null," ",r.createElement(m.Link,{href:"/schedule",className:"text-base font-heaviest3r11"}," ",r.createElement("span",null,r.createElement(h,{text:"Schedule"}))))))))}))}var G=n(1066),$=n.n(G),tt=(n(6547),n(4297));var et=function(t){var e=t.showBelow,n=(0,r.useState)(!e),a=n[0],o=n[1],i=function(){window.pageYOffset>e?a||o(!0):a&&o(!1)};return(0,r.useEffect)((function(){if(e)return window.addEventListener("scroll",i),function(){return window.removeEventListener("scroll",i)}})),r.createElement(r.Fragment,null,r.createElement("footer",null,r.createElement("div",null,r.createElement("div",{className:" bg-black-gradient lg:px-0"},r.createElement("div",{className:"container justify-between w-full mx-auto lg:flex"},r.createElement("div",{className:"justify-between lg:w-1/2 lg:flex"},r.createElement("div",{className:"flex flex-col mt-4 lg:mt-0 "},r.createElement("div",{className:"mt-20"}," ",r.createElement(p,{type:"abbreviation",className:""}))),r.createElement("div",{className:"flex flex-col mt-4 lg:mt-0"}),r.createElement("div",{className:"flex flex-col mt-4 lg:mt-0 lg:items-center"},r.createElement("dl",{className:"inline-block mt-8 text-xl text-gray-50 montserrat"},r.createElement("div",null,r.createElement("dt",{className:"sr-only"},"Postal address"),r.createElement("dd",{className:"flex text-sm"},r.createElement(Y.G,{className:"flex-shrink-0 inline-block w-5 h-5 text-gray-50",icon:q.faHome}),r.createElement("span",{className:"pl-10"},"Raleigh, NC"))),r.createElement("div",{className:"mt-6"},r.createElement("dt",{className:"sr-only"},"Phone number"),r.createElement("dd",{className:"flex text-sm"},r.createElement(Y.G,{className:"flex-shrink-0 inline-block w-5 h-5 text-gray-50",icon:q.faPhone}),r.createElement("span",{className:"pl-10"},r.createElement("a",{href:"tel:9198234333"},r.createElement("span",{className:"text-white hover:text-white"},"+1 (919) 823-4333"))))),r.createElement("div",{className:"mt-3"},r.createElement("dt",{className:"sr-only"},"Email"),r.createElement("dd",{className:"flex"},r.createElement(Y.G,{className:"flex-shrink-0 inline-block w-5 h-5 text-gray-50",icon:q.faEnvelope}),r.createElement("span",{className:"ml-3 text-sm "},"hello@oakwave.com"))),r.createElement("div",{className:""},r.createElement("dt",{className:"sr-only"},"Social"),r.createElement("div",{className:"social-share","data-wow-delay":"200ms","data-wow-duration":"1000ms"},r.createElement("a",{href:"https://www.facebook.com/oakwave"},r.createElement(Y.G,{className:"inline-block w-5 h-5 mx-10 text-gray-50 ",icon:tt.AYu})),r.createElement("a",{href:"https://linkedin.com/company/oakwave"},r.createElement(Y.G,{className:"inline-block w-5 h-5 mx-10 text-gray-50",icon:tt.hwn})),r.createElement("a",{href:"#link"},r.createElement(Y.G,{className:"inline-block w-10 h-5 mx-5 text-gray-50",icon:tt.lLR})),r.createElement("a",{href:"https://www.twitter.com/oakwave"},r.createElement(Y.G,{className:"inline-block w-5 h-5 mx-10 text-gray-50",icon:tt.mdU}))))))),r.createElement("div",{className:"flex w-full pb-4 justify-top lg:w-1/2 lg:mt-0 lg:justify-end lg:pb-0"},r.createElement("div",{className:"w-10/12 lg:w-1/2"},r.createElement("h5",{className:"text-white"},"Subscribe to our Newsletter"),r.createElement($(),{portalId:"8988772",formId:"9ad7037d-3e57-4d91-8874-fd9af54dbc27",onSubmit:function(){return console.log("Submit!")},onReady:function(t){return console.log("Form ready!")},loading:r.createElement("div",null,"Loading...")}))))),r.createElement("div",{className:"py-5 "},r.createElement("span",{className:"text-white"}," © 2021 OAKwave, LLC. All Rights Reserved."))),r.createElement("div",{className:"back-to-top"},r.createElement("div",{className:"backtop",onClick:function(){window.scrollTo({top:0,behavior:"smooth"})}},r.createElement("span",{className:"top"})))))},nt=function(t){var e=t.children;return r.createElement(r.Fragment,null,r.createElement("div",{className:"relative z-0 main-wrapper active-dark bg-black-gradient"},r.createElement(Z,null),r.createElement(o,null),r.createElement("main",null,e),r.createElement(et,null)))}},6895:function(t){t.exports={siteUrl:"https://www.oakwave.com",postsPerPage:12,siteTitleMeta:"OAKwave Creative, Branding, and Digital",siteDescriptionMeta:"A scrappy creative, brand, and digital marketing, advertising, and consulting firm out of Raleigh, North Carolina",shareImageWidth:1e3,shareImageHeight:523,shortTitle:"OAKwave",siteIcon:"favicon.png",backgroundColor:"#121212",themeColor:"#ffffff"}},4815:function(t,e,n){"use strict";function r(t){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function a(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}function o(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function i(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter((function(t){return Object.getOwnPropertyDescriptor(n,t).enumerable})))),r.forEach((function(e){o(t,e,n[e])}))}return t}function c(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var n=[],r=!0,a=!1,o=void 0;try{for(var i,c=t[Symbol.iterator]();!(r=(i=c.next()).done)&&(n.push(i.value),!e||n.length!==e);r=!0);}catch(s){a=!0,o=s}finally{try{r||null==c.return||c.return()}finally{if(a)throw o}}return n}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}n.d(e,{G:function(){return Qt}});var s=function(){},l={},u={},f={mark:s,measure:s};try{"undefined"!=typeof window&&(l=window),"undefined"!=typeof document&&(u=document),"undefined"!=typeof MutationObserver&&MutationObserver,"undefined"!=typeof performance&&(f=performance)}catch(Vt){}var p=(l.navigator||{}).userAgent,d=void 0===p?"":p,h=l,m=u,v=f,g=(h.document,!!m.documentElement&&!!m.head&&"function"==typeof m.addEventListener&&"function"==typeof m.createElement),b=(~d.indexOf("MSIE")||d.indexOf("Trident/"),"svg-inline--fa"),y="data-fa-i2svg",w=(function(){try{}catch(Vt){return!1}}(),[1,2,3,4,5,6,7,8,9,10]),A=w.concat([11,12,13,14,15,16,17,18,19,20]),x={GROUP:"group",SWAP_OPACITY:"swap-opacity",PRIMARY:"primary",SECONDARY:"secondary"},E=(["xs","sm","lg","fw","ul","li","border","pull-left","pull-right","spin","pulse","rotate-90","rotate-180","rotate-270","flip-horizontal","flip-vertical","flip-both","stack","stack-1x","stack-2x","inverse","layers","layers-text","layers-counter",x.GROUP,x.SWAP_OPACITY,x.PRIMARY,x.SECONDARY].concat(w.map((function(t){return"".concat(t,"x")}))).concat(A.map((function(t){return"w-".concat(t)}))),h.FontAwesomeConfig||{});if(m&&"function"==typeof m.querySelector){[["data-family-prefix","familyPrefix"],["data-replacement-class","replacementClass"],["data-auto-replace-svg","autoReplaceSvg"],["data-auto-add-css","autoAddCss"],["data-auto-a11y","autoA11y"],["data-search-pseudo-elements","searchPseudoElements"],["data-observe-mutations","observeMutations"],["data-mutate-approach","mutateApproach"],["data-keep-original-source","keepOriginalSource"],["data-measure-performance","measurePerformance"],["data-show-missing-icons","showMissingIcons"]].forEach((function(t){var e=c(t,2),n=e[0],r=e[1],a=function(t){return""===t||"false"!==t&&("true"===t||t)}(function(t){var e=m.querySelector("script["+t+"]");if(e)return e.getAttribute(t)}(n));null!=a&&(E[r]=a)}))}var O=i({},{familyPrefix:"fa",replacementClass:b,autoReplaceSvg:!0,autoAddCss:!0,autoA11y:!0,searchPseudoElements:!1,observeMutations:!0,mutateApproach:"async",keepOriginalSource:!0,measurePerformance:!1,showMissingIcons:!0},E);O.autoReplaceSvg||(O.observeMutations=!1);var j=i({},O);h.FontAwesomeConfig=j;var _=h||{};_.___FONT_AWESOME___||(_.___FONT_AWESOME___={}),_.___FONT_AWESOME___.styles||(_.___FONT_AWESOME___.styles={}),_.___FONT_AWESOME___.hooks||(_.___FONT_AWESOME___.hooks={}),_.___FONT_AWESOME___.shims||(_.___FONT_AWESOME___.shims=[]);var k=_.___FONT_AWESOME___,S=[];g&&((m.documentElement.doScroll?/^loaded|^c/:/^loaded|^i|^c/).test(m.readyState)||m.addEventListener("DOMContentLoaded",(function t(){m.removeEventListener("DOMContentLoaded",t),1,S.map((function(t){return t()}))})));var T,C="pending",I="settled",N="fulfilled",P="rejected",z=function(){},M=void 0!==n.g&&void 0!==n.g.process&&"function"==typeof n.g.process.emit,U="undefined"==typeof setImmediate?setTimeout:setImmediate,R=[];function L(){for(var t=0;t<R.length;t++)R[t][0](R[t][1]);R=[],T=!1}function D(t,e){R.push([t,e]),T||(T=!0,U(L,0))}function B(t){var e=t.owner,n=e._state,r=e._data,a=t[n],o=t.then;if("function"==typeof a){n=N;try{r=a(r)}catch(Vt){Q(o,Vt)}}F(o,r)||(n===N&&H(o,r),n===P&&Q(o,r))}function F(t,e){var n;try{if(t===e)throw new TypeError("A promises callback cannot return that same promise.");if(e&&("function"==typeof e||"object"===r(e))){var a=e.then;if("function"==typeof a)return a.call(e,(function(r){n||(n=!0,e===r?W(t,r):H(t,r))}),(function(e){n||(n=!0,Q(t,e))})),!0}}catch(Vt){return n||Q(t,Vt),!0}return!1}function H(t,e){t!==e&&F(t,e)||W(t,e)}function W(t,e){t._state===C&&(t._state=I,t._data=e,D(V,t))}function Q(t,e){t._state===C&&(t._state=I,t._data=e,D(K,t))}function J(t){t._then=t._then.forEach(B)}function V(t){t._state=N,J(t)}function K(t){t._state=P,J(t),!t._handled&&M&&n.g.process.emit("unhandledRejection",t._data,t)}function X(t){n.g.process.emit("rejectionHandled",t)}function Y(t){if("function"!=typeof t)throw new TypeError("Promise resolver "+t+" is not a function");if(this instanceof Y==!1)throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");this._then=[],function(t,e){function n(t){Q(e,t)}try{t((function(t){H(e,t)}),n)}catch(Vt){n(Vt)}}(t,this)}Y.prototype={constructor:Y,_state:C,_then:null,_data:void 0,_handled:!1,then:function(t,e){var n={owner:this,then:new this.constructor(z),fulfilled:t,rejected:e};return!e&&!t||this._handled||(this._handled=!0,this._state===P&&M&&D(X,this)),this._state===N||this._state===P?D(B,n):this._then.push(n),n.then},catch:function(t){return this.then(null,t)}},Y.all=function(t){if(!Array.isArray(t))throw new TypeError("You must pass an array to Promise.all().");return new Y((function(e,n){var r=[],a=0;function o(t){return a++,function(n){r[t]=n,--a||e(r)}}for(var i,c=0;c<t.length;c++)(i=t[c])&&"function"==typeof i.then?i.then(o(c),n):r[c]=i;a||e(r)}))},Y.race=function(t){if(!Array.isArray(t))throw new TypeError("You must pass an array to Promise.race().");return new Y((function(e,n){for(var r,a=0;a<t.length;a++)(r=t[a])&&"function"==typeof r.then?r.then(e,n):e(r)}))},Y.resolve=function(t){return t&&"object"===r(t)&&t.constructor===Y?t:new Y((function(e){e(t)}))},Y.reject=function(t){return new Y((function(e,n){n(t)}))};var q={size:16,x:0,y:0,rotate:0,flipX:!1,flipY:!1};function Z(t){if(t&&g){var e=m.createElement("style");e.setAttribute("type","text/css"),e.innerHTML=t;for(var n=m.head.childNodes,r=null,a=n.length-1;a>-1;a--){var o=n[a],i=(o.tagName||"").toUpperCase();["STYLE","LINK"].indexOf(i)>-1&&(r=o)}return m.head.insertBefore(e,r),t}}function G(){for(var t=12,e="";t-- >0;)e+="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"[62*Math.random()|0];return e}function $(t){return"".concat(t).replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function tt(t){return Object.keys(t||{}).reduce((function(e,n){return e+"".concat(n,": ").concat(t[n],";")}),"")}function et(t){return t.size!==q.size||t.x!==q.x||t.y!==q.y||t.rotate!==q.rotate||t.flipX||t.flipY}function nt(t){var e=t.transform,n=t.containerWidth,r=t.iconWidth,a={transform:"translate(".concat(n/2," 256)")},o="translate(".concat(32*e.x,", ").concat(32*e.y,") "),i="scale(".concat(e.size/16*(e.flipX?-1:1),", ").concat(e.size/16*(e.flipY?-1:1),") "),c="rotate(".concat(e.rotate," 0 0)");return{outer:a,inner:{transform:"".concat(o," ").concat(i," ").concat(c)},path:{transform:"translate(".concat(r/2*-1," -256)")}}}var rt={x:0,y:0,width:"100%",height:"100%"};function at(t){var e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return t.attributes&&(t.attributes.fill||e)&&(t.attributes.fill="black"),t}function ot(t){var e=t.icons,n=e.main,r=e.mask,a=t.prefix,o=t.iconName,c=t.transform,s=t.symbol,l=t.title,u=t.maskId,f=t.titleId,p=t.extra,d=t.watchable,h=void 0!==d&&d,m=r.found?r:n,v=m.width,g=m.height,b="fak"===a,w=b?"":"fa-w-".concat(Math.ceil(v/g*16)),A=[j.replacementClass,o?"".concat(j.familyPrefix,"-").concat(o):"",w].filter((function(t){return-1===p.classes.indexOf(t)})).filter((function(t){return""!==t||!!t})).concat(p.classes).join(" "),x={children:[],attributes:i({},p.attributes,{"data-prefix":a,"data-icon":o,class:A,role:p.attributes.role||"img",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 ".concat(v," ").concat(g)})},E=b&&!~p.classes.indexOf("fa-fw")?{width:"".concat(v/g*16*.0625,"em")}:{};h&&(x.attributes[y]=""),l&&x.children.push({tag:"title",attributes:{id:x.attributes["aria-labelledby"]||"title-".concat(f||G())},children:[l]});var O=i({},x,{prefix:a,iconName:o,main:n,mask:r,maskId:u,transform:c,symbol:s,styles:i({},E,p.styles)}),_=r.found&&n.found?function(t){var e,n=t.children,r=t.attributes,a=t.main,o=t.mask,c=t.maskId,s=t.transform,l=a.width,u=a.icon,f=o.width,p=o.icon,d=nt({transform:s,containerWidth:f,iconWidth:l}),h={tag:"rect",attributes:i({},rt,{fill:"white"})},m=u.children?{children:u.children.map(at)}:{},v={tag:"g",attributes:i({},d.inner),children:[at(i({tag:u.tag,attributes:i({},u.attributes,d.path)},m))]},g={tag:"g",attributes:i({},d.outer),children:[v]},b="mask-".concat(c||G()),y="clip-".concat(c||G()),w={tag:"mask",attributes:i({},rt,{id:b,maskUnits:"userSpaceOnUse",maskContentUnits:"userSpaceOnUse"}),children:[h,g]},A={tag:"defs",children:[{tag:"clipPath",attributes:{id:y},children:(e=p,"g"===e.tag?e.children:[e])},w]};return n.push(A,{tag:"rect",attributes:i({fill:"currentColor","clip-path":"url(#".concat(y,")"),mask:"url(#".concat(b,")")},rt)}),{children:n,attributes:r}}(O):function(t){var e=t.children,n=t.attributes,r=t.main,a=t.transform,o=tt(t.styles);if(o.length>0&&(n.style=o),et(a)){var c=nt({transform:a,containerWidth:r.width,iconWidth:r.width});e.push({tag:"g",attributes:i({},c.outer),children:[{tag:"g",attributes:i({},c.inner),children:[{tag:r.icon.tag,children:r.icon.children,attributes:i({},r.icon.attributes,c.path)}]}]})}else e.push(r.icon);return{children:e,attributes:n}}(O),k=_.children,S=_.attributes;return O.children=k,O.attributes=S,s?function(t){var e=t.prefix,n=t.iconName,r=t.children,a=t.attributes,o=t.symbol;return[{tag:"svg",attributes:{style:"display: none;"},children:[{tag:"symbol",attributes:i({},a,{id:!0===o?"".concat(e,"-").concat(j.familyPrefix,"-").concat(n):o}),children:r}]}]}(O):function(t){var e=t.children,n=t.main,r=t.mask,a=t.attributes,o=t.styles,c=t.transform;if(et(c)&&n.found&&!r.found){var s={x:n.width/n.height/2,y:.5};a.style=tt(i({},o,{"transform-origin":"".concat(s.x+c.x/16,"em ").concat(s.y+c.y/16,"em")}))}return[{tag:"svg",attributes:a,children:e}]}(O)}var it=function(){},ct=(j.measurePerformance&&v&&v.mark&&v.measure,function(t,e,n,r){var a,o,i,c=Object.keys(t),s=c.length,l=void 0!==r?function(t,e){return function(n,r,a,o){return t.call(e,n,r,a,o)}}(e,r):e;for(void 0===n?(a=1,i=t[c[0]]):(a=0,i=n);a<s;a++)i=l(i,t[o=c[a]],o,t);return i});function st(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=n.skipHooks,a=void 0!==r&&r,o=Object.keys(e).reduce((function(t,n){var r=e[n];return!!r.icon?t[r.iconName]=r.icon:t[n]=r,t}),{});"function"!=typeof k.hooks.addPack||a?k.styles[t]=i({},k.styles[t]||{},o):k.hooks.addPack(t,o),"fas"===t&&st("fa",e)}var lt=k.styles,ut=k.shims,ft=function(){var t=function(t){return ct(lt,(function(e,n,r){return e[r]=ct(n,t,{}),e}),{})};t((function(t,e,n){return e[3]&&(t[e[3]]=n),t})),t((function(t,e,n){var r=e[2];return t[n]=n,r.forEach((function(e){t[e]=n})),t}));var e="far"in lt;ct(ut,(function(t,n){var r=n[0],a=n[1],o=n[2];return"far"!==a||e||(a="fas"),t[r]={prefix:a,iconName:o},t}),{})};ft();k.styles;function pt(t,e,n){if(t&&t[e]&&t[e][n])return{prefix:e,iconName:n,icon:t[e][n]}}function dt(t){var e=t.tag,n=t.attributes,r=void 0===n?{}:n,a=t.children,o=void 0===a?[]:a;return"string"==typeof t?$(t):"<".concat(e," ").concat(function(t){return Object.keys(t||{}).reduce((function(e,n){return e+"".concat(n,'="').concat($(t[n]),'" ')}),"").trim()}(r),">").concat(o.map(dt).join(""),"</").concat(e,">")}var ht=function(t){var e={size:16,x:0,y:0,flipX:!1,flipY:!1,rotate:0};return t?t.toLowerCase().split(" ").reduce((function(t,e){var n=e.toLowerCase().split("-"),r=n[0],a=n.slice(1).join("-");if(r&&"h"===a)return t.flipX=!0,t;if(r&&"v"===a)return t.flipY=!0,t;if(a=parseFloat(a),isNaN(a))return t;switch(r){case"grow":t.size=t.size+a;break;case"shrink":t.size=t.size-a;break;case"left":t.x=t.x-a;break;case"right":t.x=t.x+a;break;case"up":t.y=t.y-a;break;case"down":t.y=t.y+a;break;case"rotate":t.rotate=t.rotate+a}return t}),e):e};function mt(t){this.name="MissingIcon",this.message=t||"Icon unavailable",this.stack=(new Error).stack}mt.prototype=Object.create(Error.prototype),mt.prototype.constructor=mt;var vt={fill:"currentColor"},gt={attributeType:"XML",repeatCount:"indefinite",dur:"2s"},bt={tag:"path",attributes:i({},vt,{d:"M156.5,447.7l-12.6,29.5c-18.7-9.5-35.9-21.2-51.5-34.9l22.7-22.7C127.6,430.5,141.5,440,156.5,447.7z M40.6,272H8.5 c1.4,21.2,5.4,41.7,11.7,61.1L50,321.2C45.1,305.5,41.8,289,40.6,272z M40.6,240c1.4-18.8,5.2-37,11.1-54.1l-29.5-12.6 C14.7,194.3,10,216.7,8.5,240H40.6z M64.3,156.5c7.8-14.9,17.2-28.8,28.1-41.5L69.7,92.3c-13.7,15.6-25.5,32.8-34.9,51.5 L64.3,156.5z M397,419.6c-13.9,12-29.4,22.3-46.1,30.4l11.9,29.8c20.7-9.9,39.8-22.6,56.9-37.6L397,419.6z M115,92.4 c13.9-12,29.4-22.3,46.1-30.4l-11.9-29.8c-20.7,9.9-39.8,22.6-56.8,37.6L115,92.4z M447.7,355.5c-7.8,14.9-17.2,28.8-28.1,41.5 l22.7,22.7c13.7-15.6,25.5-32.9,34.9-51.5L447.7,355.5z M471.4,272c-1.4,18.8-5.2,37-11.1,54.1l29.5,12.6 c7.5-21.1,12.2-43.5,13.6-66.8H471.4z M321.2,462c-15.7,5-32.2,8.2-49.2,9.4v32.1c21.2-1.4,41.7-5.4,61.1-11.7L321.2,462z M240,471.4c-18.8-1.4-37-5.2-54.1-11.1l-12.6,29.5c21.1,7.5,43.5,12.2,66.8,13.6V471.4z M462,190.8c5,15.7,8.2,32.2,9.4,49.2h32.1 c-1.4-21.2-5.4-41.7-11.7-61.1L462,190.8z M92.4,397c-12-13.9-22.3-29.4-30.4-46.1l-29.8,11.9c9.9,20.7,22.6,39.8,37.6,56.9 L92.4,397z M272,40.6c18.8,1.4,36.9,5.2,54.1,11.1l12.6-29.5C317.7,14.7,295.3,10,272,8.5V40.6z M190.8,50 c15.7-5,32.2-8.2,49.2-9.4V8.5c-21.2,1.4-41.7,5.4-61.1,11.7L190.8,50z M442.3,92.3L419.6,115c12,13.9,22.3,29.4,30.5,46.1 l29.8-11.9C470,128.5,457.3,109.4,442.3,92.3z M397,92.4l22.7-22.7c-15.6-13.7-32.8-25.5-51.5-34.9l-12.6,29.5 C370.4,72.1,384.4,81.5,397,92.4z"})},yt=i({},gt,{attributeName:"opacity"});i({},vt,{cx:"256",cy:"364",r:"28"}),i({},gt,{attributeName:"r",values:"28;14;28;28;14;28;"}),i({},yt,{values:"1;0;1;1;0;1;"}),i({},vt,{opacity:"1",d:"M263.7,312h-16c-6.6,0-12-5.4-12-12c0-71,77.4-63.9,77.4-107.8c0-20-17.8-40.2-57.4-40.2c-29.1,0-44.3,9.6-59.2,28.7 c-3.9,5-11.1,6-16.2,2.4l-13.1-9.2c-5.6-3.9-6.9-11.8-2.6-17.2c21.2-27.2,46.4-44.7,91.2-44.7c52.3,0,97.4,29.8,97.4,80.2 c0,67.6-77.4,63.5-77.4,107.8C275.7,306.6,270.3,312,263.7,312z"}),i({},yt,{values:"1;0;0;0;0;1;"}),i({},vt,{opacity:"0",d:"M232.5,134.5l7,168c0.3,6.4,5.6,11.5,12,11.5h9c6.4,0,11.7-5.1,12-11.5l7-168c0.3-6.8-5.2-12.5-12-12.5h-23 C237.7,122,232.2,127.7,232.5,134.5z"}),i({},yt,{values:"0;0;1;1;0;0;"}),k.styles;function wt(t){var e=t[0],n=t[1],r=c(t.slice(4),1)[0];return{found:!0,width:e,height:n,icon:Array.isArray(r)?{tag:"g",attributes:{class:"".concat(j.familyPrefix,"-").concat(x.GROUP)},children:[{tag:"path",attributes:{class:"".concat(j.familyPrefix,"-").concat(x.SECONDARY),fill:"currentColor",d:r[0]}},{tag:"path",attributes:{class:"".concat(j.familyPrefix,"-").concat(x.PRIMARY),fill:"currentColor",d:r[1]}}]}:{tag:"path",attributes:{fill:"currentColor",d:r}}}}k.styles;function At(){var t="fa",e=b,n=j.familyPrefix,r=j.replacementClass,a='svg:not(:root).svg-inline--fa {\n overflow: visible;\n}\n\n.svg-inline--fa {\n display: inline-block;\n font-size: inherit;\n height: 1em;\n overflow: visible;\n vertical-align: -0.125em;\n}\n.svg-inline--fa.fa-lg {\n vertical-align: -0.225em;\n}\n.svg-inline--fa.fa-w-1 {\n width: 0.0625em;\n}\n.svg-inline--fa.fa-w-2 {\n width: 0.125em;\n}\n.svg-inline--fa.fa-w-3 {\n width: 0.1875em;\n}\n.svg-inline--fa.fa-w-4 {\n width: 0.25em;\n}\n.svg-inline--fa.fa-w-5 {\n width: 0.3125em;\n}\n.svg-inline--fa.fa-w-6 {\n width: 0.375em;\n}\n.svg-inline--fa.fa-w-7 {\n width: 0.4375em;\n}\n.svg-inline--fa.fa-w-8 {\n width: 0.5em;\n}\n.svg-inline--fa.fa-w-9 {\n width: 0.5625em;\n}\n.svg-inline--fa.fa-w-10 {\n width: 0.625em;\n}\n.svg-inline--fa.fa-w-11 {\n width: 0.6875em;\n}\n.svg-inline--fa.fa-w-12 {\n width: 0.75em;\n}\n.svg-inline--fa.fa-w-13 {\n width: 0.8125em;\n}\n.svg-inline--fa.fa-w-14 {\n width: 0.875em;\n}\n.svg-inline--fa.fa-w-15 {\n width: 0.9375em;\n}\n.svg-inline--fa.fa-w-16 {\n width: 1em;\n}\n.svg-inline--fa.fa-w-17 {\n width: 1.0625em;\n}\n.svg-inline--fa.fa-w-18 {\n width: 1.125em;\n}\n.svg-inline--fa.fa-w-19 {\n width: 1.1875em;\n}\n.svg-inline--fa.fa-w-20 {\n width: 1.25em;\n}\n.svg-inline--fa.fa-pull-left {\n margin-right: 0.3em;\n width: auto;\n}\n.svg-inline--fa.fa-pull-right {\n margin-left: 0.3em;\n width: auto;\n}\n.svg-inline--fa.fa-border {\n height: 1.5em;\n}\n.svg-inline--fa.fa-li {\n width: 2em;\n}\n.svg-inline--fa.fa-fw {\n width: 1.25em;\n}\n\n.fa-layers svg.svg-inline--fa {\n bottom: 0;\n left: 0;\n margin: auto;\n position: absolute;\n right: 0;\n top: 0;\n}\n\n.fa-layers {\n display: inline-block;\n height: 1em;\n position: relative;\n text-align: center;\n vertical-align: -0.125em;\n width: 1em;\n}\n.fa-layers svg.svg-inline--fa {\n -webkit-transform-origin: center center;\n transform-origin: center center;\n}\n\n.fa-layers-counter, .fa-layers-text {\n display: inline-block;\n position: absolute;\n text-align: center;\n}\n\n.fa-layers-text {\n left: 50%;\n top: 50%;\n -webkit-transform: translate(-50%, -50%);\n transform: translate(-50%, -50%);\n -webkit-transform-origin: center center;\n transform-origin: center center;\n}\n\n.fa-layers-counter {\n background-color: #ff253a;\n border-radius: 1em;\n -webkit-box-sizing: border-box;\n box-sizing: border-box;\n color: #fff;\n height: 1.5em;\n line-height: 1;\n max-width: 5em;\n min-width: 1.5em;\n overflow: hidden;\n padding: 0.25em;\n right: 0;\n text-overflow: ellipsis;\n top: 0;\n -webkit-transform: scale(0.25);\n transform: scale(0.25);\n -webkit-transform-origin: top right;\n transform-origin: top right;\n}\n\n.fa-layers-bottom-right {\n bottom: 0;\n right: 0;\n top: auto;\n -webkit-transform: scale(0.25);\n transform: scale(0.25);\n -webkit-transform-origin: bottom right;\n transform-origin: bottom right;\n}\n\n.fa-layers-bottom-left {\n bottom: 0;\n left: 0;\n right: auto;\n top: auto;\n -webkit-transform: scale(0.25);\n transform: scale(0.25);\n -webkit-transform-origin: bottom left;\n transform-origin: bottom left;\n}\n\n.fa-layers-top-right {\n right: 0;\n top: 0;\n -webkit-transform: scale(0.25);\n transform: scale(0.25);\n -webkit-transform-origin: top right;\n transform-origin: top right;\n}\n\n.fa-layers-top-left {\n left: 0;\n right: auto;\n top: 0;\n -webkit-transform: scale(0.25);\n transform: scale(0.25);\n -webkit-transform-origin: top left;\n transform-origin: top left;\n}\n\n.fa-lg {\n font-size: 1.3333333333em;\n line-height: 0.75em;\n vertical-align: -0.0667em;\n}\n\n.fa-xs {\n font-size: 0.75em;\n}\n\n.fa-sm {\n font-size: 0.875em;\n}\n\n.fa-1x {\n font-size: 1em;\n}\n\n.fa-2x {\n font-size: 2em;\n}\n\n.fa-3x {\n font-size: 3em;\n}\n\n.fa-4x {\n font-size: 4em;\n}\n\n.fa-5x {\n font-size: 5em;\n}\n\n.fa-6x {\n font-size: 6em;\n}\n\n.fa-7x {\n font-size: 7em;\n}\n\n.fa-8x {\n font-size: 8em;\n}\n\n.fa-9x {\n font-size: 9em;\n}\n\n.fa-10x {\n font-size: 10em;\n}\n\n.fa-fw {\n text-align: center;\n width: 1.25em;\n}\n\n.fa-ul {\n list-style-type: none;\n margin-left: 2.5em;\n padding-left: 0;\n}\n.fa-ul > li {\n position: relative;\n}\n\n.fa-li {\n left: -2em;\n position: absolute;\n text-align: center;\n width: 2em;\n line-height: inherit;\n}\n\n.fa-border {\n border: solid 0.08em #eee;\n border-radius: 0.1em;\n padding: 0.2em 0.25em 0.15em;\n}\n\n.fa-pull-left {\n float: left;\n}\n\n.fa-pull-right {\n float: right;\n}\n\n.fa.fa-pull-left,\n.fas.fa-pull-left,\n.far.fa-pull-left,\n.fal.fa-pull-left,\n.fab.fa-pull-left {\n margin-right: 0.3em;\n}\n.fa.fa-pull-right,\n.fas.fa-pull-right,\n.far.fa-pull-right,\n.fal.fa-pull-right,\n.fab.fa-pull-right {\n margin-left: 0.3em;\n}\n\n.fa-spin {\n -webkit-animation: fa-spin 2s infinite linear;\n animation: fa-spin 2s infinite linear;\n}\n\n.fa-pulse {\n -webkit-animation: fa-spin 1s infinite steps(8);\n animation: fa-spin 1s infinite steps(8);\n}\n\n@-webkit-keyframes fa-spin {\n 0% {\n -webkit-transform: rotate(0deg);\n transform: rotate(0deg);\n }\n 100% {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n}\n\n@keyframes fa-spin {\n 0% {\n -webkit-transform: rotate(0deg);\n transform: rotate(0deg);\n }\n 100% {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n}\n.fa-rotate-90 {\n -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=1)";\n -webkit-transform: rotate(90deg);\n transform: rotate(90deg);\n}\n\n.fa-rotate-180 {\n -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=2)";\n -webkit-transform: rotate(180deg);\n transform: rotate(180deg);\n}\n\n.fa-rotate-270 {\n -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=3)";\n -webkit-transform: rotate(270deg);\n transform: rotate(270deg);\n}\n\n.fa-flip-horizontal {\n -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=0, mirror=1)";\n -webkit-transform: scale(-1, 1);\n transform: scale(-1, 1);\n}\n\n.fa-flip-vertical {\n -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1)";\n -webkit-transform: scale(1, -1);\n transform: scale(1, -1);\n}\n\n.fa-flip-both, .fa-flip-horizontal.fa-flip-vertical {\n -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1)";\n -webkit-transform: scale(-1, -1);\n transform: scale(-1, -1);\n}\n\n:root .fa-rotate-90,\n:root .fa-rotate-180,\n:root .fa-rotate-270,\n:root .fa-flip-horizontal,\n:root .fa-flip-vertical,\n:root .fa-flip-both {\n -webkit-filter: none;\n filter: none;\n}\n\n.fa-stack {\n display: inline-block;\n height: 2em;\n position: relative;\n width: 2.5em;\n}\n\n.fa-stack-1x,\n.fa-stack-2x {\n bottom: 0;\n left: 0;\n margin: auto;\n position: absolute;\n right: 0;\n top: 0;\n}\n\n.svg-inline--fa.fa-stack-1x {\n height: 1em;\n width: 1.25em;\n}\n.svg-inline--fa.fa-stack-2x {\n height: 2em;\n width: 2.5em;\n}\n\n.fa-inverse {\n color: #fff;\n}\n\n.sr-only {\n border: 0;\n clip: rect(0, 0, 0, 0);\n height: 1px;\n margin: -1px;\n overflow: hidden;\n padding: 0;\n position: absolute;\n width: 1px;\n}\n\n.sr-only-focusable:active, .sr-only-focusable:focus {\n clip: auto;\n height: auto;\n margin: 0;\n overflow: visible;\n position: static;\n width: auto;\n}\n\n.svg-inline--fa .fa-primary {\n fill: var(--fa-primary-color, currentColor);\n opacity: 1;\n opacity: var(--fa-primary-opacity, 1);\n}\n\n.svg-inline--fa .fa-secondary {\n fill: var(--fa-secondary-color, currentColor);\n opacity: 0.4;\n opacity: var(--fa-secondary-opacity, 0.4);\n}\n\n.svg-inline--fa.fa-swap-opacity .fa-primary {\n opacity: 0.4;\n opacity: var(--fa-secondary-opacity, 0.4);\n}\n\n.svg-inline--fa.fa-swap-opacity .fa-secondary {\n opacity: 1;\n opacity: var(--fa-primary-opacity, 1);\n}\n\n.svg-inline--fa mask .fa-primary,\n.svg-inline--fa mask .fa-secondary {\n fill: black;\n}\n\n.fad.fa-inverse {\n color: #fff;\n}';if(n!==t||r!==e){var o=new RegExp("\\.".concat(t,"\\-"),"g"),i=new RegExp("\\--".concat(t,"\\-"),"g"),c=new RegExp("\\.".concat(e),"g");a=a.replace(o,".".concat(n,"-")).replace(i,"--".concat(n,"-")).replace(c,".".concat(r))}return a}function xt(){j.autoAddCss&&!kt&&(Z(At()),kt=!0)}function Et(t,e){return Object.defineProperty(t,"abstract",{get:e}),Object.defineProperty(t,"html",{get:function(){return t.abstract.map((function(t){return dt(t)}))}}),Object.defineProperty(t,"node",{get:function(){if(g){var e=m.createElement("div");return e.innerHTML=t.html,e.children}}}),t}function Ot(t){var e=t.prefix,n=void 0===e?"fa":e,r=t.iconName;if(r)return pt(_t.definitions,n,r)||pt(k.styles,n,r)}var jt,_t=new(function(){function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.definitions={}}var e,n,r;return e=t,(n=[{key:"add",value:function(){for(var t=this,e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];var a=n.reduce(this._pullDefinitions,{});Object.keys(a).forEach((function(e){t.definitions[e]=i({},t.definitions[e]||{},a[e]),st(e,a[e]),ft()}))}},{key:"reset",value:function(){this.definitions={}}},{key:"_pullDefinitions",value:function(t,e){var n=e.prefix&&e.iconName&&e.icon?{0:e}:e;return Object.keys(n).map((function(e){var r=n[e],a=r.prefix,o=r.iconName,i=r.icon;t[a]||(t[a]={}),t[a][o]=i})),t}}])&&a(e.prototype,n),r&&a(e,r),t}()),kt=!1,St={transform:function(t){return ht(t)}},Tt=(jt=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=e.transform,r=void 0===n?q:n,a=e.symbol,o=void 0!==a&&a,c=e.mask,s=void 0===c?null:c,l=e.maskId,u=void 0===l?null:l,f=e.title,p=void 0===f?null:f,d=e.titleId,h=void 0===d?null:d,m=e.classes,v=void 0===m?[]:m,g=e.attributes,b=void 0===g?{}:g,y=e.styles,w=void 0===y?{}:y;if(t){var A=t.prefix,x=t.iconName,E=t.icon;return Et(i({type:"icon"},t),(function(){return xt(),j.autoA11y&&(p?b["aria-labelledby"]="".concat(j.replacementClass,"-title-").concat(h||G()):(b["aria-hidden"]="true",b.focusable="false")),ot({icons:{main:wt(E),mask:s?wt(s.icon):{found:!1,width:null,height:null,icon:{}}},prefix:A,iconName:x,transform:i({},q,r),symbol:o,title:p,maskId:u,titleId:h,extra:{attributes:b,styles:w,classes:v}})}))}},function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=(t||{}).icon?t:Ot(t||{}),r=e.mask;return r&&(r=(r||{}).icon?r:Ot(r||{})),jt(n,i({},e,{mask:r}))}),Ct=n(5697),It=n.n(Ct),Nt=n(7294);function Pt(t){return(Pt="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function zt(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function Mt(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function Ut(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{};e%2?Mt(Object(n),!0).forEach((function(e){zt(t,e,n[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Mt(Object(n)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(n,e))}))}return t}function Rt(t,e){if(null==t)return{};var n,r,a=function(t,e){if(null==t)return{};var n,r,a={},o=Object.keys(t);for(r=0;r<o.length;r++)n=o[r],e.indexOf(n)>=0||(a[n]=t[n]);return a}(t,e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);for(r=0;r<o.length;r++)n=o[r],e.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(t,n)&&(a[n]=t[n])}return a}function Lt(t){return function(t){if(Array.isArray(t)){for(var e=0,n=new Array(t.length);e<t.length;e++)n[e]=t[e];return n}}(t)||function(t){if(Symbol.iterator in Object(t)||"[object Arguments]"===Object.prototype.toString.call(t))return Array.from(t)}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance")}()}function Dt(t){return e=t,(e-=0)==e?t:(t=t.replace(/[\-_\s]+(.)?/g,(function(t,e){return e?e.toUpperCase():""}))).substr(0,1).toLowerCase()+t.substr(1);var e}function Bt(t){return t.split(";").map((function(t){return t.trim()})).filter((function(t){return t})).reduce((function(t,e){var n,r=e.indexOf(":"),a=Dt(e.slice(0,r)),o=e.slice(r+1).trim();return a.startsWith("webkit")?t[(n=a,n.charAt(0).toUpperCase()+n.slice(1))]=o:t[a]=o,t}),{})}var Ft=!1;try{Ft=!0}catch(Vt){}function Ht(t){return St.icon?St.icon(t):null===t?null:"object"===Pt(t)&&t.prefix&&t.iconName?t:Array.isArray(t)&&2===t.length?{prefix:t[0],iconName:t[1]}:"string"==typeof t?{prefix:"fas",iconName:t}:void 0}function Wt(t,e){return Array.isArray(e)&&e.length>0||!Array.isArray(e)&&e?zt({},t,e):{}}function Qt(t){var e=t.forwardedRef,n=Rt(t,["forwardedRef"]),r=n.icon,a=n.mask,o=n.symbol,i=n.className,c=n.title,s=n.titleId,l=Ht(r),u=Wt("classes",[].concat(Lt(function(t){var e,n=t.spin,r=t.pulse,a=t.fixedWidth,o=t.inverse,i=t.border,c=t.listItem,s=t.flip,l=t.size,u=t.rotation,f=t.pull,p=(zt(e={"fa-spin":n,"fa-pulse":r,"fa-fw":a,"fa-inverse":o,"fa-border":i,"fa-li":c,"fa-flip-horizontal":"horizontal"===s||"both"===s,"fa-flip-vertical":"vertical"===s||"both"===s},"fa-".concat(l),null!=l),zt(e,"fa-rotate-".concat(u),null!=u&&0!==u),zt(e,"fa-pull-".concat(f),null!=f),zt(e,"fa-swap-opacity",t.swapOpacity),e);return Object.keys(p).map((function(t){return p[t]?t:null})).filter((function(t){return t}))}(n)),Lt(i.split(" ")))),f=Wt("transform","string"==typeof n.transform?St.transform(n.transform):n.transform),p=Wt("mask",Ht(a)),d=Tt(l,Ut({},u,{},f,{},p,{symbol:o,title:c,titleId:s}));if(!d)return function(){var t;!Ft&&console&&"function"==typeof console.error&&(t=console).error.apply(t,arguments)}("Could not find icon",l),null;var h=d.abstract,m={ref:e};return Object.keys(n).forEach((function(t){Qt.defaultProps.hasOwnProperty(t)||(m[t]=n[t])})),Jt(h[0],m)}Qt.displayName="FontAwesomeIcon",Qt.propTypes={border:It().bool,className:It().string,mask:It().oneOfType([It().object,It().array,It().string]),fixedWidth:It().bool,inverse:It().bool,flip:It().oneOf(["horizontal","vertical","both"]),icon:It().oneOfType([It().object,It().array,It().string]),listItem:It().bool,pull:It().oneOf(["right","left"]),pulse:It().bool,rotation:It().oneOf([0,90,180,270]),size:It().oneOf(["lg","xs","sm","1x","2x","3x","4x","5x","6x","7x","8x","9x","10x"]),spin:It().bool,symbol:It().oneOfType([It().bool,It().string]),title:It().string,transform:It().oneOfType([It().string,It().object]),swapOpacity:It().bool},Qt.defaultProps={border:!1,className:"",mask:null,fixedWidth:!1,inverse:!1,flip:null,icon:null,listItem:!1,pull:null,pulse:!1,rotation:null,size:null,spin:!1,symbol:!1,title:"",transform:null,swapOpacity:!1};var Jt=function t(e,n){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if("string"==typeof n)return n;var a=(n.children||[]).map((function(n){return t(e,n)})),o=Object.keys(n.attributes||{}).reduce((function(t,e){var r=n.attributes[e];switch(e){case"class":t.attrs.className=r,delete n.attributes.class;break;case"style":t.attrs.style=Bt(r);break;default:0===e.indexOf("aria-")||0===e.indexOf("data-")?t.attrs[e.toLowerCase()]=r:t.attrs[Dt(e)]=r}return t}),{attrs:{}}),i=r.style,c=void 0===i?{}:i,s=Rt(r,["style"]);return o.attrs.style=Ut({},o.attrs.style,{},c),e.apply(void 0,[n.tag,Ut({},o.attrs,{},s)].concat(Lt(a)))}.bind(null,Nt.createElement)},8733:function(t,e,n){"use strict";n.r(e),n.d(e,{readingTime:function(){return gn},tags:function(){return Yn},utils:function(){return qn}});n(3123),n(5306),n(4723),n(8309),n(7042);function r(t){return t!=t}function a(t,e,n){return e==e?function(t,e,n){for(var r=n-1,a=t.length;++r<a;)if(t[r]===e)return r;return-1}(t,e,n):function(t,e,n,r){for(var a=t.length,o=n+(r?1:-1);r?o--:++o<a;)if(e(t[o],o,t))return o;return-1}(t,r,n)}t=n.hmd(t);var o="object"==typeof n.g&&n.g&&n.g.Object===Object&&n.g,i="object"==typeof self&&self&&self.Object===Object&&self,c=o||i||Function("return this")(),s=c.Symbol,l=Object.prototype,u=l.hasOwnProperty,f=l.toString,p=s?s.toStringTag:void 0;var d=Object.prototype.toString;var h=s?s.toStringTag:void 0;function m(t){return null==t?void 0===t?"[object Undefined]":"[object Null]":h&&h in Object(t)?function(t){var e=u.call(t,p),n=t[p];try{t[p]=void 0;var r=!0}catch(o){}var a=f.call(t);return r&&(e?t[p]=n:delete t[p]),a}(t):function(t){return d.call(t)}(t)}function v(t){var e=typeof t;return null!=t&&("object"==e||"function"==e)}function g(t){if(!v(t))return!1;var e=m(t);return"[object Function]"==e||"[object GeneratorFunction]"==e||"[object AsyncFunction]"==e||"[object Proxy]"==e}function b(t){return"number"==typeof t&&t>-1&&t%1==0&&t<=9007199254740991}function y(t){return null!=t&&b(t.length)&&!g(t)}var w=Array.isArray;function A(t){return null!=t&&"object"==typeof t}function x(t){return"string"==typeof t||!w(t)&&A(t)&&"[object String]"==m(t)}var E=/\s/;var O=/^\s+/;function j(t){return t?t.slice(0,function(t){for(var e=t.length;e--&&E.test(t.charAt(e)););return e}(t)+1).replace(O,""):t}function _(t){return"symbol"==typeof t||A(t)&&"[object Symbol]"==m(t)}var k=/^[-+]0x[0-9a-f]+$/i,S=/^0b[01]+$/i,T=/^0o[0-7]+$/i,C=parseInt;var I=1/0;function N(t){return t?(t=function(t){if("number"==typeof t)return t;if(_(t))return NaN;if(v(t)){var e="function"==typeof t.valueOf?t.valueOf():t;t=v(e)?e+"":e}if("string"!=typeof t)return 0===t?t:+t;t=j(t);var n=S.test(t);return n||T.test(t)?C(t.slice(2),n?2:8):k.test(t)?NaN:+t}(t))===I||t===-1/0?17976931348623157e292*(t<0?-1:1):t==t?t:0:0===t?t:0}function P(t){var e=N(t),n=e%1;return e==e?n?e-n:e:0}function z(t,e){for(var n=-1,r=null==t?0:t.length,a=Array(r);++n<r;)a[n]=e(t[n],n,t);return a}function M(t,e){for(var n=-1,r=Array(t);++n<t;)r[n]=e(n);return r}function U(t){return A(t)&&"[object Arguments]"==m(t)}var R=Object.prototype,L=R.hasOwnProperty,D=R.propertyIsEnumerable,B=U(function(){return arguments}())?U:function(t){return A(t)&&L.call(t,"callee")&&!D.call(t,"callee")};var F="object"==typeof exports&&exports&&!exports.nodeType&&exports,H=F&&t&&!t.nodeType&&t,W=H&&H.exports===F?c.Buffer:void 0,Q=(W?W.isBuffer:void 0)||function(){return!1},J=/^(?:0|[1-9]\d*)$/;function V(t,e){var n=typeof t;return!!(e=null==e?9007199254740991:e)&&("number"==n||"symbol"!=n&&J.test(t))&&t>-1&&t%1==0&&t<e}var K={};K["[object Float32Array]"]=K["[object Float64Array]"]=K["[object Int8Array]"]=K["[object Int16Array]"]=K["[object Int32Array]"]=K["[object Uint8Array]"]=K["[object Uint8ClampedArray]"]=K["[object Uint16Array]"]=K["[object Uint32Array]"]=!0,K["[object Arguments]"]=K["[object Array]"]=K["[object ArrayBuffer]"]=K["[object Boolean]"]=K["[object DataView]"]=K["[object Date]"]=K["[object Error]"]=K["[object Function]"]=K["[object Map]"]=K["[object Number]"]=K["[object Object]"]=K["[object RegExp]"]=K["[object Set]"]=K["[object String]"]=K["[object WeakMap]"]=!1;var X,Y="object"==typeof exports&&exports&&!exports.nodeType&&exports,q=Y&&t&&!t.nodeType&&t,Z=q&&q.exports===Y&&o.process,G=function(){try{var t=q&&q.require&&q.require("util").types;return t||Z&&Z.binding&&Z.binding("util")}catch(e){}}(),$=G&&G.isTypedArray,tt=$?(X=$,function(t){return X(t)}):function(t){return A(t)&&b(t.length)&&!!K[m(t)]},et=Object.prototype.hasOwnProperty;var nt=Object.prototype;var rt=function(t,e){return function(n){return t(e(n))}}(Object.keys,Object),at=Object.prototype.hasOwnProperty;function ot(t){if(n=(e=t)&&e.constructor,e!==("function"==typeof n&&n.prototype||nt))return rt(t);var e,n,r=[];for(var a in Object(t))at.call(t,a)&&"constructor"!=a&&r.push(a);return r}function it(t){return y(t)?function(t,e){var n=w(t),r=!n&&B(t),a=!n&&!r&&Q(t),o=!n&&!r&&!a&&tt(t),i=n||r||a||o,c=i?M(t.length,String):[],s=c.length;for(var l in t)!e&&!et.call(t,l)||i&&("length"==l||a&&("offset"==l||"parent"==l)||o&&("buffer"==l||"byteLength"==l||"byteOffset"==l)||V(l,s))||c.push(l);return c}(t):ot(t)}function ct(t){return null==t?[]:function(t,e){return z(e,(function(e){return t[e]}))}(t,it(t))}var st=Math.max;function lt(t,e,n,r){t=y(t)?t:ct(t),n=n&&!r?P(n):0;var o=t.length;return n<0&&(n=st(o+n,0)),x(t)?n<=o&&t.indexOf(e,n)>-1:!!o&&a(t,e,n)>-1}function ut(t,e){return t===e||t!=t&&e!=e}function ft(t,e){for(var n=t.length;n--;)if(ut(t[n][0],e))return n;return-1}var pt=Array.prototype.splice;function dt(t){var e=-1,n=null==t?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}dt.prototype.clear=function(){this.__data__=[],this.size=0},dt.prototype.delete=function(t){var e=this.__data__,n=ft(e,t);return!(n<0)&&(n==e.length-1?e.pop():pt.call(e,n,1),--this.size,!0)},dt.prototype.get=function(t){var e=this.__data__,n=ft(e,t);return n<0?void 0:e[n][1]},dt.prototype.has=function(t){return ft(this.__data__,t)>-1},dt.prototype.set=function(t,e){var n=this.__data__,r=ft(n,t);return r<0?(++this.size,n.push([t,e])):n[r][1]=e,this};var ht,mt=c["__core-js_shared__"],vt=(ht=/[^.]+$/.exec(mt&&mt.keys&&mt.keys.IE_PROTO||""))?"Symbol(src)_1."+ht:"";var gt=Function.prototype.toString;function bt(t){if(null!=t){try{return gt.call(t)}catch(e){}try{return t+""}catch(e){}}return""}var yt=/^\[object .+?Constructor\]$/,wt=Function.prototype,At=Object.prototype,xt=wt.toString,Et=At.hasOwnProperty,Ot=RegExp("^"+xt.call(Et).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function jt(t){return!(!v(t)||function(t){return!!vt&&vt in t}(t))&&(g(t)?Ot:yt).test(bt(t))}function _t(t,e){var n=function(t,e){return null==t?void 0:t[e]}(t,e);return jt(n)?n:void 0}var kt=_t(c,"Map"),St=_t(Object,"create");var Tt=Object.prototype.hasOwnProperty;var Ct=Object.prototype.hasOwnProperty;function It(t){var e=-1,n=null==t?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}function Nt(t,e){var n,r,a=t.__data__;return("string"==(r=typeof(n=e))||"number"==r||"symbol"==r||"boolean"==r?"__proto__"!==n:null===n)?a["string"==typeof e?"string":"hash"]:a.map}function Pt(t){var e=-1,n=null==t?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}It.prototype.clear=function(){this.__data__=St?St(null):{},this.size=0},It.prototype.delete=function(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e},It.prototype.get=function(t){var e=this.__data__;if(St){var n=e[t];return"__lodash_hash_undefined__"===n?void 0:n}return Tt.call(e,t)?e[t]:void 0},It.prototype.has=function(t){var e=this.__data__;return St?void 0!==e[t]:Ct.call(e,t)},It.prototype.set=function(t,e){var n=this.__data__;return this.size+=this.has(t)?0:1,n[t]=St&&void 0===e?"__lodash_hash_undefined__":e,this},Pt.prototype.clear=function(){this.size=0,this.__data__={hash:new It,map:new(kt||dt),string:new It}},Pt.prototype.delete=function(t){var e=Nt(this,t).delete(t);return this.size-=e?1:0,e},Pt.prototype.get=function(t){return Nt(this,t).get(t)},Pt.prototype.has=function(t){return Nt(this,t).has(t)},Pt.prototype.set=function(t,e){var n=Nt(this,t),r=n.size;return n.set(t,e),this.size+=n.size==r?0:1,this};function zt(t){var e=this.__data__=new dt(t);this.size=e.size}zt.prototype.clear=function(){this.__data__=new dt,this.size=0},zt.prototype.delete=function(t){var e=this.__data__,n=e.delete(t);return this.size=e.size,n},zt.prototype.get=function(t){return this.__data__.get(t)},zt.prototype.has=function(t){return this.__data__.has(t)},zt.prototype.set=function(t,e){var n=this.__data__;if(n instanceof dt){var r=n.__data__;if(!kt||r.length<199)return r.push([t,e]),this.size=++n.size,this;n=this.__data__=new Pt(r)}return n.set(t,e),this.size=n.size,this};function Mt(t){var e=-1,n=null==t?0:t.length;for(this.__data__=new Pt;++e<n;)this.add(t[e])}function Ut(t,e){for(var n=-1,r=null==t?0:t.length;++n<r;)if(e(t[n],n,t))return!0;return!1}Mt.prototype.add=Mt.prototype.push=function(t){return this.__data__.set(t,"__lodash_hash_undefined__"),this},Mt.prototype.has=function(t){return this.__data__.has(t)};function Rt(t,e,n,r,a,o){var i=1&n,c=t.length,s=e.length;if(c!=s&&!(i&&s>c))return!1;var l=o.get(t),u=o.get(e);if(l&&u)return l==e&&u==t;var f=-1,p=!0,d=2&n?new Mt:void 0;for(o.set(t,e),o.set(e,t);++f<c;){var h=t[f],m=e[f];if(r)var v=i?r(m,h,f,e,t,o):r(h,m,f,t,e,o);if(void 0!==v){if(v)continue;p=!1;break}if(d){if(!Ut(e,(function(t,e){if(i=e,!d.has(i)&&(h===t||a(h,t,n,r,o)))return d.push(e);var i}))){p=!1;break}}else if(h!==m&&!a(h,m,n,r,o)){p=!1;break}}return o.delete(t),o.delete(e),p}var Lt=c.Uint8Array;function Dt(t){var e=-1,n=Array(t.size);return t.forEach((function(t,r){n[++e]=[r,t]})),n}function Bt(t){var e=-1,n=Array(t.size);return t.forEach((function(t){n[++e]=t})),n}var Ft=s?s.prototype:void 0,Ht=Ft?Ft.valueOf:void 0;function Wt(t,e){for(var n=-1,r=e.length,a=t.length;++n<r;)t[a+n]=e[n];return t}function Qt(t,e){for(var n=-1,r=null==t?0:t.length,a=0,o=[];++n<r;){var i=t[n];e(i,n,t)&&(o[a++]=i)}return o}var Jt=Object.prototype.propertyIsEnumerable,Vt=Object.getOwnPropertySymbols,Kt=Vt?function(t){return null==t?[]:(t=Object(t),Qt(Vt(t),(function(e){return Jt.call(t,e)})))}:function(){return[]};function Xt(t){return function(t,e,n){var r=e(t);return w(t)?r:Wt(r,n(t))}(t,it,Kt)}var Yt=Object.prototype.hasOwnProperty;var qt=_t(c,"DataView"),Zt=_t(c,"Promise"),Gt=_t(c,"Set"),$t=_t(c,"WeakMap"),te="[object Map]",ee="[object Promise]",ne="[object Set]",re="[object WeakMap]",ae="[object DataView]",oe=bt(qt),ie=bt(kt),ce=bt(Zt),se=bt(Gt),le=bt($t),ue=m;(qt&&ue(new qt(new ArrayBuffer(1)))!=ae||kt&&ue(new kt)!=te||Zt&&ue(Zt.resolve())!=ee||Gt&&ue(new Gt)!=ne||$t&&ue(new $t)!=re)&&(ue=function(t){var e=m(t),n="[object Object]"==e?t.constructor:void 0,r=n?bt(n):"";if(r)switch(r){case oe:return ae;case ie:return te;case ce:return ee;case se:return ne;case le:return re}return e});var fe=ue,pe="[object Arguments]",de="[object Array]",he="[object Object]",me=Object.prototype.hasOwnProperty;function ve(t,e,n,r,a,o){var i=w(t),c=w(e),s=i?de:fe(t),l=c?de:fe(e),u=(s=s==pe?he:s)==he,f=(l=l==pe?he:l)==he,p=s==l;if(p&&Q(t)){if(!Q(e))return!1;i=!0,u=!1}if(p&&!u)return o||(o=new zt),i||tt(t)?Rt(t,e,n,r,a,o):function(t,e,n,r,a,o,i){switch(n){case"[object DataView]":if(t.byteLength!=e.byteLength||t.byteOffset!=e.byteOffset)return!1;t=t.buffer,e=e.buffer;case"[object ArrayBuffer]":return!(t.byteLength!=e.byteLength||!o(new Lt(t),new Lt(e)));case"[object Boolean]":case"[object Date]":case"[object Number]":return ut(+t,+e);case"[object Error]":return t.name==e.name&&t.message==e.message;case"[object RegExp]":case"[object String]":return t==e+"";case"[object Map]":var c=Dt;case"[object Set]":var s=1&r;if(c||(c=Bt),t.size!=e.size&&!s)return!1;var l=i.get(t);if(l)return l==e;r|=2,i.set(t,e);var u=Rt(c(t),c(e),r,a,o,i);return i.delete(t),u;case"[object Symbol]":if(Ht)return Ht.call(t)==Ht.call(e)}return!1}(t,e,s,n,r,a,o);if(!(1&n)){var d=u&&me.call(t,"__wrapped__"),h=f&&me.call(e,"__wrapped__");if(d||h){var m=d?t.value():t,v=h?e.value():e;return o||(o=new zt),a(m,v,n,r,o)}}return!!p&&(o||(o=new zt),function(t,e,n,r,a,o){var i=1&n,c=Xt(t),s=c.length;if(s!=Xt(e).length&&!i)return!1;for(var l=s;l--;){var u=c[l];if(!(i?u in e:Yt.call(e,u)))return!1}var f=o.get(t),p=o.get(e);if(f&&p)return f==e&&p==t;var d=!0;o.set(t,e),o.set(e,t);for(var h=i;++l<s;){var m=t[u=c[l]],v=e[u];if(r)var g=i?r(v,m,u,e,t,o):r(m,v,u,t,e,o);if(!(void 0===g?m===v||a(m,v,n,r,o):g)){d=!1;break}h||(h="constructor"==u)}if(d&&!h){var b=t.constructor,y=e.constructor;b==y||!("constructor"in t)||!("constructor"in e)||"function"==typeof b&&b instanceof b&&"function"==typeof y&&y instanceof y||(d=!1)}return o.delete(t),o.delete(e),d}(t,e,n,r,a,o))}function ge(t,e,n,r,a){return t===e||(null==t||null==e||!A(t)&&!A(e)?t!=t&&e!=e:ve(t,e,n,r,ge,a))}function be(t){return t==t&&!v(t)}function ye(t,e){return function(n){return null!=n&&(n[t]===e&&(void 0!==e||t in Object(n)))}}function we(t){var e=function(t){for(var e=it(t),n=e.length;n--;){var r=e[n],a=t[r];e[n]=[r,a,be(a)]}return e}(t);return 1==e.length&&e[0][2]?ye(e[0][0],e[0][1]):function(n){return n===t||function(t,e,n,r){var a=n.length,o=a,i=!r;if(null==t)return!o;for(t=Object(t);a--;){var c=n[a];if(i&&c[2]?c[1]!==t[c[0]]:!(c[0]in t))return!1}for(;++a<o;){var s=(c=n[a])[0],l=t[s],u=c[1];if(i&&c[2]){if(void 0===l&&!(s in t))return!1}else{var f=new zt;if(r)var p=r(l,u,s,t,e,f);if(!(void 0===p?ge(u,l,3,r,f):p))return!1}}return!0}(n,t,e)}}var Ae=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,xe=/^\w*$/;function Ee(t,e){if(w(t))return!1;var n=typeof t;return!("number"!=n&&"symbol"!=n&&"boolean"!=n&&null!=t&&!_(t))||(xe.test(t)||!Ae.test(t)||null!=e&&t in Object(e))}function Oe(t,e){if("function"!=typeof t||null!=e&&"function"!=typeof e)throw new TypeError("Expected a function");var n=function n(){var r=arguments,a=e?e.apply(this,r):r[0],o=n.cache;if(o.has(a))return o.get(a);var i=t.apply(this,r);return n.cache=o.set(a,i)||o,i};return n.cache=new(Oe.Cache||Pt),n}Oe.Cache=Pt;var je=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,_e=/\\(\\)?/g,ke=function(t){var e=Oe(t,(function(t){return 500===n.size&&n.clear(),t})),n=e.cache;return e}((function(t){var e=[];return 46===t.charCodeAt(0)&&e.push(""),t.replace(je,(function(t,n,r,a){e.push(r?a.replace(_e,"$1"):n||t)})),e})),Se=s?s.prototype:void 0,Te=Se?Se.toString:void 0;function Ce(t){if("string"==typeof t)return t;if(w(t))return z(t,Ce)+"";if(_(t))return Te?Te.call(t):"";var e=t+"";return"0"==e&&1/t==-Infinity?"-0":e}function Ie(t){return null==t?"":Ce(t)}function Ne(t,e){return w(t)?t:Ee(t,e)?[t]:ke(Ie(t))}function Pe(t){if("string"==typeof t||_(t))return t;var e=t+"";return"0"==e&&1/t==-Infinity?"-0":e}function ze(t,e){for(var n=0,r=(e=Ne(e,t)).length;null!=t&&n<r;)t=t[Pe(e[n++])];return n&&n==r?t:void 0}function Me(t,e){return null!=t&&e in Object(t)}function Ue(t,e){return null!=t&&function(t,e,n){for(var r=-1,a=(e=Ne(e,t)).length,o=!1;++r<a;){var i=Pe(e[r]);if(!(o=null!=t&&n(t,i)))break;t=t[i]}return o||++r!=a?o:!!(a=null==t?0:t.length)&&b(a)&&V(i,a)&&(w(t)||B(t))}(t,e,Me)}function Re(t,e){return Ee(t)&&be(e)?ye(Pe(t),e):function(n){var r=function(t,e,n){var r=null==t?void 0:ze(t,e);return void 0===r?n:r}(n,t);return void 0===r&&r===e?Ue(n,t):ge(e,r,3)}}function Le(t){return t}function De(t){return function(e){return null==e?void 0:e[t]}}function Be(t){return Ee(t)?De(Pe(t)):function(t){return function(e){return ze(e,t)}}(t)}function Fe(t){return"function"==typeof t?t:null==t?Le:"object"==typeof t?w(t)?Re(t[0],t[1]):we(t):Be(t)}var He,We=function(t,e,n){for(var r=-1,a=Object(t),o=n(t),i=o.length;i--;){var c=o[He?i:++r];if(!1===e(a[c],c,a))break}return t};var Qe=function(t,e){return function(n,r){if(null==n)return n;if(!y(n))return t(n,r);for(var a=n.length,o=e?a:-1,i=Object(n);(e?o--:++o<a)&&!1!==r(i[o],o,i););return n}}((function(t,e){return t&&We(t,e,it)}));function Je(t,e){var n=-1,r=y(t)?Array(t.length):[];return Qe(t,(function(t,a,o){r[++n]=e(t,a,o)})),r}function Ve(t,e,n,r){var a=-1,o=null==t?0:t.length;for(r&&o&&(n=t[++a]);++a<o;)n=e(n,t[a],a,t);return n}function Ke(t,e,n,r,a){return a(t,(function(t,a,o){n=r?(r=!1,t):e(n,t,a,o)})),n}function Xe(t,e,n){var r=t.length;return n=void 0===n?r:n,!e&&n>=r?t:function(t,e,n){var r=-1,a=t.length;e<0&&(e=-e>a?0:a+e),(n=n>a?a:n)<0&&(n+=a),a=e>n?0:n-e>>>0,e>>>=0;for(var o=Array(a);++r<a;)o[r]=t[r+e];return o}(t,e,n)}var Ye=RegExp("[\\u200d\\ud800-\\udfff\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff\\ufe0e\\ufe0f]");function qe(t){return Ye.test(t)}var Ze="[\\ud800-\\udfff]",Ge="[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]",$e="\\ud83c[\\udffb-\\udfff]",tn="[^\\ud800-\\udfff]",en="(?:\\ud83c[\\udde6-\\uddff]){2}",nn="[\\ud800-\\udbff][\\udc00-\\udfff]",rn="(?:"+Ge+"|"+$e+")"+"?",an="[\\ufe0e\\ufe0f]?",on=an+rn+("(?:\\u200d(?:"+[tn,en,nn].join("|")+")"+an+rn+")*"),cn="(?:"+[tn+Ge+"?",Ge,en,nn,Ze].join("|")+")",sn=RegExp($e+"(?="+$e+")|"+cn+on,"g");function ln(t){return qe(t)?function(t){return t.match(sn)||[]}(t):function(t){return t.split("")}(t)}function un(t,e,n){if((t=Ie(t))&&(n||void 0===e))return j(t);if(!t||!(e=Ce(e)))return t;var r=ln(t),o=ln(e);return Xe(r,function(t,e){for(var n=-1,r=t.length;++n<r&&a(e,t[n],0)>-1;);return n}(r,o),function(t,e){for(var n=t.length;n--&&a(e,t[n],0)>-1;);return n}(r,o)+1).join("")}var fn=function(t){return t?(e=t.split(","),n=un,(w(e)?z:Je)(e,Fe(n))):["public"];var e,n},pn=function(t,e,n){g(e)&&(n=e,e=null);var r=w(t)?[]:{},a=w(e)?e:fn(e),o=lt(a,"public");return function(t,e,n){var r=w(t)?Ve:Ke,a=arguments.length<3;return r(t,Fe(e),n,a,Qe)}(t,(function(t,e,i){if(lt(a,"all")||e.visibility&&lt(a,e.visibility)||!e.visibility&&o){var c=n?n(e):e;w(t)?r.push(c):r[i]=c}return r}),r)},dn=Object.freeze({__proto__:null,parse:fn,filter:pn});function hn(t){if(!t)return 0;Object.prototype.hasOwnProperty.call(t,"string")&&(t=t.string);var e=(t=t.replace(/<(.|\n)*?>/g," ")).match(/[a-zA-ZÀ-ÿ0-9_\u0392-\u03c9\u0410-\u04F9]+|[\u4E00-\u9FFF\u3400-\u4dbf\uf900-\ufaff\u3040-\u309f\uac00-\ud7af]+/g),n=0;if(null===e)return n;for(var r=0;r<e.length;r+=1)e[r].charCodeAt(0)>=19968?n+=e[r].length:n+=1;return n}function mn(t){return t?(Object.prototype.hasOwnProperty.call(t,"string")&&(t=t.string),(t.match(/<img(.|\n)*?>/g)||[]).length):0}function vn(t,e){if(!t)return"";var n=mn(t);return e&&(n+=e),function(t){for(var e=t.wordCount,n=t.imageCount,r=e/4.583333333333333,a=12;a>12-n;a-=1)r+=Math.max(a,3);return Math.round(r/60)}({wordCount:hn(t),imageCount:n})}function gn(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n="string"==typeof e.minute?e.minute:"1 min read",r="string"==typeof e.minutes?e.minutes:"% min read";if(!t.html&&!t.reading_time)return"";var a=0;t.feature_image&&(a+=1);var o=t.reading_time||vn(t.html,a);return o<=1?n:r.replace("%",o)}function bn(t){for(var e=-1,n=null==t?0:t.length,r=0,a=[];++e<n;){var o=t[e];o&&(a[r++]=o)}return a}var yn=s?s.isConcatSpreadable:void 0;function wn(t){return w(t)||B(t)||!!(yn&&t&&t[yn])}function An(t,e,n,r,a){var o=-1,i=t.length;for(n||(n=wn),a||(a=[]);++o<i;){var c=t[o];e>0&&n(c)?e>1?An(c,e-1,n,r,a):Wt(a,c):r||(a[a.length]=c)}return a}function xn(t,e){var n=-1,r=t.length;for(e||(e=Array(r));++n<r;)e[n]=t[n];return e}function En(){var t=arguments.length;if(!t)return[];for(var e=Array(t-1),n=arguments[0],r=t;r--;)e[r-1]=arguments[r];return Wt(w(n)?xn(n):[n],An(e,1))}function On(t,e,n,r){var a=t.length;for((n=P(n))<0&&(n=-n>a?0:a+n),(r=void 0===r||r>a?a:P(r))<0&&(r+=a),r=n>r?0:function(t){return t?(e=P(t),n=0,r=4294967295,e==e&&(void 0!==r&&(e=e<=r?e:r),void 0!==n&&(e=e>=n?e:n)),e):0;var e,n,r}(r);n<r;)t[n++]=e;return t}function jn(t,e,n,r){var a=null==t?0:t.length;return a?(n&&"number"!=typeof n&&function(t,e,n){if(!v(n))return!1;var r=typeof e;return!!("number"==r?y(n)&&V(e,n.length):"string"==r&&e in n)&&ut(n[e],t)}(t,e,n)&&(n=0,r=a),On(t,e,n,r)):[]}function _n(t){return(null==t?0:t.length)?An(t,1):[]}var kn=De("length"),Sn="[\\ud800-\\udfff]",Tn="[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]",Cn="\\ud83c[\\udffb-\\udfff]",In="[^\\ud800-\\udfff]",Nn="(?:\\ud83c[\\udde6-\\uddff]){2}",Pn="[\\ud800-\\udbff][\\udc00-\\udfff]",zn="(?:"+Tn+"|"+Cn+")"+"?",Mn="[\\ufe0e\\ufe0f]?",Un=Mn+zn+("(?:\\u200d(?:"+[In,Nn,Pn].join("|")+")"+Mn+zn+")*"),Rn="(?:"+[In+Tn+"?",Tn,Nn,Pn,Sn].join("|")+")",Ln=RegExp(Cn+"(?="+Cn+")|"+Rn+Un,"g");function Dn(t){return qe(t)?function(t){for(var e=Ln.lastIndex=0;Ln.test(t);)++e;return e}(t):kn(t)}function Bn(t){if(null==t)return 0;if(y(t))return x(t)?Dn(t):t.length;var e=fe(t);return"[object Map]"==e||"[object Set]"==e?t.size:ot(t).length}function Fn(t,e,n){switch(n.length){case 0:return t.call(e);case 1:return t.call(e,n[0]);case 2:return t.call(e,n[0],n[1]);case 3:return t.call(e,n[0],n[1],n[2])}return t.apply(e,n)}var Hn=Math.max;var Wn=function(){try{var t=_t(Object,"defineProperty");return t({},"",{}),t}catch(e){}}(),Qn=Wn?function(t,e){return Wn(t,"toString",{configurable:!0,enumerable:!1,value:(n=e,function(){return n}),writable:!0});var n}:Le,Jn=Date.now;var Vn=function(t){var e=0,n=0;return function(){var r=Jn(),a=16-(r-n);if(n=r,a>0){if(++e>=800)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(Qn);var Kn=Math.max;var Xn=function(t,e){return Vn(function(t,e,n){return e=Hn(void 0===e?t.length-1:e,0),function(){for(var r=arguments,a=-1,o=Hn(r.length-e,0),i=Array(o);++a<o;)i[a]=r[e+a];a=-1;for(var c=Array(e+1);++a<e;)c[a]=r[a];return c[e]=n(i),Fn(t,this,c)}}(t,e,Le),t+"")}((function(t){if(!t||!t.length)return[];var e=0;return t=Qt(t,(function(t){if(A(n=t)&&y(n))return e=Kn(t.length,e),!0;var n})),M(e,(function(e){return z(t,De(e))}))}));function Yn(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n="",r=e.separator?e.separator:"",a=e.prefix?e.prefix:"",o=e.suffix?e.suffix:"",i=e.limit?parseInt(e.limit,10):void 0,c=e.from?parseInt(e.from,10):1,s=e.to?parseInt(e.to,10):void 0,l=fn(e.visibility),u=e.fallback?w(e.fallback)?e.fallback:[e.fallback]:void 0,f=e.fn?e.fn:function(t){return t.name};return t.tags&&t.tags.length&&(0===Bn(n=pn(t.tags,l,f))&&u&&(n=pn(u,l,f)),c-=1,s=s||i+c||n.length,n=n.slice(c,s)),Bn(n)>0&&(x(n[0])?(r=r||", ",n=a+n.join(r)+o):(r&&(n=_n(n=Xn(n,jn(Array(n.length),r))).slice(0,-1)),n=bn(n=En(a,n,o)))),n}var qn={countImages:mn,countWords:hn,visibility:dn,readingMinutes:vn}},1275:function(t){var e="undefined"!=typeof Element,n="function"==typeof Map,r="function"==typeof Set,a="function"==typeof ArrayBuffer&&!!ArrayBuffer.isView;function o(t,i){if(t===i)return!0;if(t&&i&&"object"==typeof t&&"object"==typeof i){if(t.constructor!==i.constructor)return!1;var c,s,l,u;if(Array.isArray(t)){if((c=t.length)!=i.length)return!1;for(s=c;0!=s--;)if(!o(t[s],i[s]))return!1;return!0}if(n&&t instanceof Map&&i instanceof Map){if(t.size!==i.size)return!1;for(u=t.entries();!(s=u.next()).done;)if(!i.has(s.value[0]))return!1;for(u=t.entries();!(s=u.next()).done;)if(!o(s.value[1],i.get(s.value[0])))return!1;return!0}if(r&&t instanceof Set&&i instanceof Set){if(t.size!==i.size)return!1;for(u=t.entries();!(s=u.next()).done;)if(!i.has(s.value[0]))return!1;return!0}if(a&&ArrayBuffer.isView(t)&&ArrayBuffer.isView(i)){if((c=t.length)!=i.length)return!1;for(s=c;0!=s--;)if(t[s]!==i[s])return!1;return!0}if(t.constructor===RegExp)return t.source===i.source&&t.flags===i.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===i.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===i.toString();if((c=(l=Object.keys(t)).length)!==Object.keys(i).length)return!1;for(s=c;0!=s--;)if(!Object.prototype.hasOwnProperty.call(i,l[s]))return!1;if(e&&t instanceof Element)return!1;for(s=c;0!=s--;)if(("_owner"!==l[s]&&"__v"!==l[s]&&"__o"!==l[s]||!t.$$typeof)&&!o(t[l[s]],i[l[s]]))return!1;return!0}return t!=t&&i!=i}t.exports=function(t,e){try{return o(t,e)}catch(n){if((n.message||"").match(/stack|recursion/i))return console.warn("react-fast-compare cannot handle circular refs"),!1;throw n}}},1232:function(t,e,n){"use strict";n.d(e,{q:function(){return mt}});var r,a,o,i,c=n(5697),s=n.n(c),l=n(8412),u=n.n(l),f=n(1275),p=n.n(f),d=n(7294),h=n(1209),m=n.n(h),v="bodyAttributes",g="htmlAttributes",b="titleAttributes",y={BASE:"base",BODY:"body",HEAD:"head",HTML:"html",LINK:"link",META:"meta",NOSCRIPT:"noscript",SCRIPT:"script",STYLE:"style",TITLE:"title"},w=(Object.keys(y).map((function(t){return y[t]})),"charset"),A="cssText",x="href",E="http-equiv",O="innerHTML",j="itemprop",_="name",k="property",S="rel",T="src",C="target",I={accesskey:"accessKey",charset:"charSet",class:"className",contenteditable:"contentEditable",contextmenu:"contextMenu","http-equiv":"httpEquiv",itemprop:"itemProp",tabindex:"tabIndex"},N="defaultTitle",P="defer",z="encodeSpecialCharacters",M="onChangeClientState",U="titleTemplate",R=Object.keys(I).reduce((function(t,e){return t[I[e]]=e,t}),{}),L=[y.NOSCRIPT,y.SCRIPT,y.STYLE],D="data-react-helmet",B="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},F=function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")},H=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),W=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},Q=function(t,e){var n={};for(var r in t)e.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(t,r)&&(n[r]=t[r]);return n},J=function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e},V=function(t){var e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return!1===e?String(t):String(t).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;")},K=function(t){var e=G(t,y.TITLE),n=G(t,U);if(n&&e)return n.replace(/%s/g,(function(){return Array.isArray(e)?e.join(""):e}));var r=G(t,N);return e||r||void 0},X=function(t){return G(t,M)||function(){}},Y=function(t,e){return e.filter((function(e){return void 0!==e[t]})).map((function(e){return e[t]})).reduce((function(t,e){return W({},t,e)}),{})},q=function(t,e){return e.filter((function(t){return void 0!==t[y.BASE]})).map((function(t){return t[y.BASE]})).reverse().reduce((function(e,n){if(!e.length)for(var r=Object.keys(n),a=0;a<r.length;a++){var o=r[a].toLowerCase();if(-1!==t.indexOf(o)&&n[o])return e.concat(n)}return e}),[])},Z=function(t,e,n){var r={};return n.filter((function(e){return!!Array.isArray(e[t])||(void 0!==e[t]&&rt("Helmet: "+t+' should be of type "Array". Instead found type "'+B(e[t])+'"'),!1)})).map((function(e){return e[t]})).reverse().reduce((function(t,n){var a={};n.filter((function(t){for(var n=void 0,o=Object.keys(t),i=0;i<o.length;i++){var c=o[i],s=c.toLowerCase();-1===e.indexOf(s)||n===S&&"canonical"===t[n].toLowerCase()||s===S&&"stylesheet"===t[s].toLowerCase()||(n=s),-1===e.indexOf(c)||c!==O&&c!==A&&c!==j||(n=c)}if(!n||!t[n])return!1;var l=t[n].toLowerCase();return r[n]||(r[n]={}),a[n]||(a[n]={}),!r[n][l]&&(a[n][l]=!0,!0)})).reverse().forEach((function(e){return t.push(e)}));for(var o=Object.keys(a),i=0;i<o.length;i++){var c=o[i],s=m()({},r[c],a[c]);r[c]=s}return t}),[]).reverse()},G=function(t,e){for(var n=t.length-1;n>=0;n--){var r=t[n];if(r.hasOwnProperty(e))return r[e]}return null},$=(r=Date.now(),function(t){var e=Date.now();e-r>16?(r=e,t(e)):setTimeout((function(){$(t)}),0)}),tt=function(t){return clearTimeout(t)},et="undefined"!=typeof window?window.requestAnimationFrame&&window.requestAnimationFrame.bind(window)||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||$:n.g.requestAnimationFrame||$,nt="undefined"!=typeof window?window.cancelAnimationFrame||window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame||tt:n.g.cancelAnimationFrame||tt,rt=function(t){return console&&"function"==typeof console.warn&&console.warn(t)},at=null,ot=function(t,e){var n=t.baseTag,r=t.bodyAttributes,a=t.htmlAttributes,o=t.linkTags,i=t.metaTags,c=t.noscriptTags,s=t.onChangeClientState,l=t.scriptTags,u=t.styleTags,f=t.title,p=t.titleAttributes;st(y.BODY,r),st(y.HTML,a),ct(f,p);var d={baseTag:lt(y.BASE,n),linkTags:lt(y.LINK,o),metaTags:lt(y.META,i),noscriptTags:lt(y.NOSCRIPT,c),scriptTags:lt(y.SCRIPT,l),styleTags:lt(y.STYLE,u)},h={},m={};Object.keys(d).forEach((function(t){var e=d[t],n=e.newTags,r=e.oldTags;n.length&&(h[t]=n),r.length&&(m[t]=d[t].oldTags)})),e&&e(),s(t,h,m)},it=function(t){return Array.isArray(t)?t.join(""):t},ct=function(t,e){void 0!==t&&document.title!==t&&(document.title=it(t)),st(y.TITLE,e)},st=function(t,e){var n=document.getElementsByTagName(t)[0];if(n){for(var r=n.getAttribute(D),a=r?r.split(","):[],o=[].concat(a),i=Object.keys(e),c=0;c<i.length;c++){var s=i[c],l=e[s]||"";n.getAttribute(s)!==l&&n.setAttribute(s,l),-1===a.indexOf(s)&&a.push(s);var u=o.indexOf(s);-1!==u&&o.splice(u,1)}for(var f=o.length-1;f>=0;f--)n.removeAttribute(o[f]);a.length===o.length?n.removeAttribute(D):n.getAttribute(D)!==i.join(",")&&n.setAttribute(D,i.join(","))}},lt=function(t,e){var n=document.head||document.querySelector(y.HEAD),r=n.querySelectorAll(t+"["+"data-react-helmet]"),a=Array.prototype.slice.call(r),o=[],i=void 0;return e&&e.length&&e.forEach((function(e){var n=document.createElement(t);for(var r in e)if(e.hasOwnProperty(r))if(r===O)n.innerHTML=e.innerHTML;else if(r===A)n.styleSheet?n.styleSheet.cssText=e.cssText:n.appendChild(document.createTextNode(e.cssText));else{var c=void 0===e[r]?"":e[r];n.setAttribute(r,c)}n.setAttribute(D,"true"),a.some((function(t,e){return i=e,n.isEqualNode(t)}))?a.splice(i,1):o.push(n)})),a.forEach((function(t){return t.parentNode.removeChild(t)})),o.forEach((function(t){return n.appendChild(t)})),{oldTags:a,newTags:o}},ut=function(t){return Object.keys(t).reduce((function(e,n){var r=void 0!==t[n]?n+'="'+t[n]+'"':""+n;return e?e+" "+r:r}),"")},ft=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return Object.keys(t).reduce((function(e,n){return e[I[n]||n]=t[n],e}),e)},pt=function(t,e,n){switch(t){case y.TITLE:return{toComponent:function(){return t=e.title,n=e.titleAttributes,(r={key:t})[D]=!0,a=ft(n,r),[d.createElement(y.TITLE,a,t)];var t,n,r,a},toString:function(){return function(t,e,n,r){var a=ut(n),o=it(e);return a?"<"+t+' data-react-helmet="true" '+a+">"+V(o,r)+"</"+t+">":"<"+t+' data-react-helmet="true">'+V(o,r)+"</"+t+">"}(t,e.title,e.titleAttributes,n)}};case v:case g:return{toComponent:function(){return ft(e)},toString:function(){return ut(e)}};default:return{toComponent:function(){return function(t,e){return e.map((function(e,n){var r,a=((r={key:n})[D]=!0,r);return Object.keys(e).forEach((function(t){var n=I[t]||t;if(n===O||n===A){var r=e.innerHTML||e.cssText;a.dangerouslySetInnerHTML={__html:r}}else a[n]=e[t]})),d.createElement(t,a)}))}(t,e)},toString:function(){return function(t,e,n){return e.reduce((function(e,r){var a=Object.keys(r).filter((function(t){return!(t===O||t===A)})).reduce((function(t,e){var a=void 0===r[e]?e:e+'="'+V(r[e],n)+'"';return t?t+" "+a:a}),""),o=r.innerHTML||r.cssText||"",i=-1===L.indexOf(t);return e+"<"+t+' data-react-helmet="true" '+a+(i?"/>":">"+o+"</"+t+">")}),"")}(t,e,n)}}}},dt=function(t){var e=t.baseTag,n=t.bodyAttributes,r=t.encode,a=t.htmlAttributes,o=t.linkTags,i=t.metaTags,c=t.noscriptTags,s=t.scriptTags,l=t.styleTags,u=t.title,f=void 0===u?"":u,p=t.titleAttributes;return{base:pt(y.BASE,e,r),bodyAttributes:pt(v,n,r),htmlAttributes:pt(g,a,r),link:pt(y.LINK,o,r),meta:pt(y.META,i,r),noscript:pt(y.NOSCRIPT,c,r),script:pt(y.SCRIPT,s,r),style:pt(y.STYLE,l,r),title:pt(y.TITLE,{title:f,titleAttributes:p},r)}},ht=u()((function(t){return{baseTag:q([x,C],t),bodyAttributes:Y(v,t),defer:G(t,P),encode:G(t,z),htmlAttributes:Y(g,t),linkTags:Z(y.LINK,[S,x],t),metaTags:Z(y.META,[_,w,E,k,j],t),noscriptTags:Z(y.NOSCRIPT,[O],t),onChangeClientState:X(t),scriptTags:Z(y.SCRIPT,[T,O],t),styleTags:Z(y.STYLE,[A],t),title:K(t),titleAttributes:Y(b,t)}}),(function(t){at&&nt(at),t.defer?at=et((function(){ot(t,(function(){at=null}))})):(ot(t),at=null)}),dt)((function(){return null})),mt=(a=ht,i=o=function(t){function e(){return F(this,e),J(this,t.apply(this,arguments))}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,t),e.prototype.shouldComponentUpdate=function(t){return!p()(this.props,t)},e.prototype.mapNestedChildrenToProps=function(t,e){if(!e)return null;switch(t.type){case y.SCRIPT:case y.NOSCRIPT:return{innerHTML:e};case y.STYLE:return{cssText:e}}throw new Error("<"+t.type+" /> elements are self-closing and can not contain children. Refer to our API for more information.")},e.prototype.flattenArrayTypeChildren=function(t){var e,n=t.child,r=t.arrayTypeChildren,a=t.newChildProps,o=t.nestedChildren;return W({},r,((e={})[n.type]=[].concat(r[n.type]||[],[W({},a,this.mapNestedChildrenToProps(n,o))]),e))},e.prototype.mapObjectTypeChildren=function(t){var e,n,r=t.child,a=t.newProps,o=t.newChildProps,i=t.nestedChildren;switch(r.type){case y.TITLE:return W({},a,((e={})[r.type]=i,e.titleAttributes=W({},o),e));case y.BODY:return W({},a,{bodyAttributes:W({},o)});case y.HTML:return W({},a,{htmlAttributes:W({},o)})}return W({},a,((n={})[r.type]=W({},o),n))},e.prototype.mapArrayTypeChildrenToProps=function(t,e){var n=W({},e);return Object.keys(t).forEach((function(e){var r;n=W({},n,((r={})[e]=t[e],r))})),n},e.prototype.warnOnInvalidChildren=function(t,e){return!0},e.prototype.mapChildrenToProps=function(t,e){var n=this,r={};return d.Children.forEach(t,(function(t){if(t&&t.props){var a=t.props,o=a.children,i=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return Object.keys(t).reduce((function(e,n){return e[R[n]||n]=t[n],e}),e)}(Q(a,["children"]));switch(n.warnOnInvalidChildren(t,o),t.type){case y.LINK:case y.META:case y.NOSCRIPT:case y.SCRIPT:case y.STYLE:r=n.flattenArrayTypeChildren({child:t,arrayTypeChildren:r,newChildProps:i,nestedChildren:o});break;default:e=n.mapObjectTypeChildren({child:t,newProps:e,newChildProps:i,nestedChildren:o})}}})),e=this.mapArrayTypeChildrenToProps(r,e)},e.prototype.render=function(){var t=this.props,e=t.children,n=Q(t,["children"]),r=W({},n);return e&&(r=this.mapChildrenToProps(e,r)),d.createElement(a,r)},H(e,null,[{key:"canUseDOM",set:function(t){a.canUseDOM=t}}]),e}(d.Component),o.propTypes={base:s().object,bodyAttributes:s().object,children:s().oneOfType([s().arrayOf(s().node),s().node]),defaultTitle:s().string,defer:s().bool,encodeSpecialCharacters:s().bool,htmlAttributes:s().object,link:s().arrayOf(s().object),meta:s().arrayOf(s().object),noscript:s().arrayOf(s().object),onChangeClientState:s().func,script:s().arrayOf(s().object),style:s().arrayOf(s().object),title:s().string,titleAttributes:s().object,titleTemplate:s().string},o.defaultProps={defer:!0,encodeSpecialCharacters:!0},o.peek=a.peek,o.rewind=function(){var t=a.rewind();return t||(t=dt({baseTag:[],bodyAttributes:{},encodeSpecialCharacters:!0,htmlAttributes:{},linkTags:[],metaTags:[],noscriptTags:[],scriptTags:[],styleTags:[],title:"",titleAttributes:{}})),t},i);mt.renderStatic=mt.rewind},1066:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},a=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),o=i(n(7294));i(n(3935));function i(t){return t&&t.__esModule?t:{default:t}}var c=0,s=function(t){function e(t){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e);var n=function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t));return n.state={loaded:!1},n.id=c++,n.createForm=n.createForm.bind(n),n.findFormElement=n.findFormElement.bind(n),n}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,t),a(e,[{key:"createForm",value:function(){var t=this;if(window.hbspt){if(null===this.el)return;var e=r({},this.props);delete e.loading,delete e.onSubmit,delete e.onReady;var n=r({},e,{target:"#"+this.el.getAttribute("id"),onFormSubmit:function(e){var n=e.serializeArray();t.props.onSubmit(n)}});return window.hbspt.forms.create(n),!0}setTimeout(this.createForm,1)}},{key:"loadScript",value:function(){var t=this,e=document.createElement("script");e.defer=!0,e.onload=function(){t.createForm(),t.findFormElement()},e.src="//js.hsforms.net/forms/v2.js",document.head.appendChild(e)}},{key:"findFormElement",value:function(){if(null!==this.el){var t=this.el.querySelector("iframe");t?(this.setState({loaded:!0}),this.props.onReady&&this.props.onReady(t)):setTimeout(this.findFormElement,1)}}},{key:"componentDidMount",value:function(){window.hbspt||this.props.noScript?(this.createForm(),this.findFormElement()):this.loadScript()}},{key:"componentWillUnmount",value:function(){}},{key:"render",value:function(){var t=this;return o.default.createElement("div",null,o.default.createElement("div",{ref:function(e){return t.el=e},id:"reactHubspotForm"+this.id,style:{display:this.state.loaded?"block":"none"}}),!this.state.loaded&&this.props.loading)}}]),e}(o.default.Component);e.default=s,t.exports=e.default},8412:function(t,e,n){"use strict";var r,a=n(7294),o=(r=a)&&"object"==typeof r&&"default"in r?r.default:r;function i(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}var c=!("undefined"==typeof window||!window.document||!window.document.createElement);t.exports=function(t,e,n){if("function"!=typeof t)throw new Error("Expected reducePropsToState to be a function.");if("function"!=typeof e)throw new Error("Expected handleStateChangeOnClient to be a function.");if(void 0!==n&&"function"!=typeof n)throw new Error("Expected mapStateOnServer to either be undefined or a function.");return function(r){if("function"!=typeof r)throw new Error("Expected WrappedComponent to be a React component.");var s,l=[];function u(){s=t(l.map((function(t){return t.props}))),f.canUseDOM?e(s):n&&(s=n(s))}var f=function(t){var e,n;function a(){return t.apply(this,arguments)||this}n=t,(e=a).prototype=Object.create(n.prototype),e.prototype.constructor=e,e.__proto__=n,a.peek=function(){return s},a.rewind=function(){if(a.canUseDOM)throw new Error("You may only call rewind() on the server. Call peek() to read the current state.");var t=s;return s=void 0,l=[],t};var i=a.prototype;return i.UNSAFE_componentWillMount=function(){l.push(this),u()},i.componentDidUpdate=function(){u()},i.componentWillUnmount=function(){var t=l.indexOf(this);l.splice(t,1),u()},i.render=function(){return o.createElement(r,this.props)},a}(a.PureComponent);return i(f,"displayName","SideEffect("+function(t){return t.displayName||t.name||"Component"}(r)+")"),i(f,"canUseDOM",c),f}}},9914:function(t,e,n){var r;t=n.nmd(t),function(a){e&&e.nodeType,t&&t.nodeType;var o="object"==typeof n.g&&n.g;o.global!==o&&o.window!==o&&o.self;var i,c=2147483647,s=36,l=/^xn--/,u=/[^\x20-\x7E]/,f=/[\x2E\u3002\uFF0E\uFF61]/g,p={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},d=Math.floor,h=String.fromCharCode;function m(t){throw RangeError(p[t])}function v(t,e){for(var n=t.length,r=[];n--;)r[n]=e(t[n]);return r}function g(t,e){var n=t.split("@"),r="";return n.length>1&&(r=n[0]+"@",t=n[1]),r+v((t=t.replace(f,".")).split("."),e).join(".")}function b(t){for(var e,n,r=[],a=0,o=t.length;a<o;)(e=t.charCodeAt(a++))>=55296&&e<=56319&&a<o?56320==(64512&(n=t.charCodeAt(a++)))?r.push(((1023&e)<<10)+(1023&n)+65536):(r.push(e),a--):r.push(e);return r}function y(t){return v(t,(function(t){var e="";return t>65535&&(e+=h((t-=65536)>>>10&1023|55296),t=56320|1023&t),e+=h(t)})).join("")}function w(t,e){return t+22+75*(t<26)-((0!=e)<<5)}function A(t,e,n){var r=0;for(t=n?d(t/700):t>>1,t+=d(t/e);t>455;r+=s)t=d(t/35);return d(r+36*t/(t+38))}function x(t){var e,n,r,a,o,i,l,u,f,p,h,v=[],g=t.length,b=0,w=128,x=72;for((n=t.lastIndexOf("-"))<0&&(n=0),r=0;r<n;++r)t.charCodeAt(r)>=128&&m("not-basic"),v.push(t.charCodeAt(r));for(a=n>0?n+1:0;a<g;){for(o=b,i=1,l=s;a>=g&&m("invalid-input"),((u=(h=t.charCodeAt(a++))-48<10?h-22:h-65<26?h-65:h-97<26?h-97:s)>=s||u>d((c-b)/i))&&m("overflow"),b+=u*i,!(u<(f=l<=x?1:l>=x+26?26:l-x));l+=s)i>d(c/(p=s-f))&&m("overflow"),i*=p;x=A(b-o,e=v.length+1,0==o),d(b/e)>c-w&&m("overflow"),w+=d(b/e),b%=e,v.splice(b++,0,w)}return y(v)}function E(t){var e,n,r,a,o,i,l,u,f,p,v,g,y,x,E,O=[];for(g=(t=b(t)).length,e=128,n=0,o=72,i=0;i<g;++i)(v=t[i])<128&&O.push(h(v));for(r=a=O.length,a&&O.push("-");r<g;){for(l=c,i=0;i<g;++i)(v=t[i])>=e&&v<l&&(l=v);for(l-e>d((c-n)/(y=r+1))&&m("overflow"),n+=(l-e)*y,e=l,i=0;i<g;++i)if((v=t[i])<e&&++n>c&&m("overflow"),v==e){for(u=n,f=s;!(u<(p=f<=o?1:f>=o+26?26:f-o));f+=s)E=u-p,x=s-p,O.push(h(w(p+E%x,0))),u=d(E/x);O.push(h(w(u,0))),o=A(n,y,r==a),n=0,++r}++n,++e}return O.join("")}i={version:"1.3.2",ucs2:{decode:b,encode:y},decode:x,encode:E,toASCII:function(t){return g(t,(function(t){return u.test(t)?"xn--"+E(t):t}))},toUnicode:function(t){return g(t,(function(t){return l.test(t)?x(t.slice(4).toLowerCase()):t}))}},void 0===(r=function(){return i}.call(e,n,e,t))||(t.exports=r)}()},4525:function(t){"use strict";function e(t,e){return Object.prototype.hasOwnProperty.call(t,e)}t.exports=function(t,n,r,a){n=n||"&",r=r||"=";var o={};if("string"!=typeof t||0===t.length)return o;var i=/\+/g;t=t.split(n);var c=1e3;a&&"number"==typeof a.maxKeys&&(c=a.maxKeys);var s=t.length;c>0&&s>c&&(s=c);for(var l=0;l<s;++l){var u,f,p,d,h=t[l].replace(i,"%20"),m=h.indexOf(r);m>=0?(u=h.substr(0,m),f=h.substr(m+1)):(u=h,f=""),p=decodeURIComponent(u),d=decodeURIComponent(f),e(o,p)?Array.isArray(o[p])?o[p].push(d):o[p]=[o[p],d]:o[p]=d}return o}},1690:function(t){"use strict";var e=function(t){switch(typeof t){case"string":return t;case"boolean":return t?"true":"false";case"number":return isFinite(t)?t:"";default:return""}};t.exports=function(t,n,r,a){return n=n||"&",r=r||"=",null===t&&(t=void 0),"object"==typeof t?Object.keys(t).map((function(a){var o=encodeURIComponent(e(a))+r;return Array.isArray(t[a])?t[a].map((function(t){return o+encodeURIComponent(e(t))})).join(n):o+encodeURIComponent(e(t[a]))})).join(n):a?encodeURIComponent(e(a))+r+encodeURIComponent(e(t)):""}},7844:function(t,e,n){"use strict";e.decode=e.parse=n(4525),e.encode=e.stringify=n(1690)},4755:function(t,e,n){"use strict";var r=n(9914),a=n(2438);function o(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}e.parse=y,e.resolve=function(t,e){return y(t,!1,!0).resolve(e)},e.resolveObject=function(t,e){return t?y(t,!1,!0).resolveObject(e):e},e.format=function(t){a.isString(t)&&(t=y(t));return t instanceof o?t.format():o.prototype.format.call(t)},e.Url=o;var i=/^([a-z0-9.+-]+:)/i,c=/:[0-9]*$/,s=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,l=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),u=["'"].concat(l),f=["%","/","?",";","#"].concat(u),p=["/","?","#"],d=/^[+a-z0-9A-Z_-]{0,63}$/,h=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,m={javascript:!0,"javascript:":!0},v={javascript:!0,"javascript:":!0},g={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},b=n(7844);function y(t,e,n){if(t&&a.isObject(t)&&t instanceof o)return t;var r=new o;return r.parse(t,e,n),r}o.prototype.parse=function(t,e,n){if(!a.isString(t))throw new TypeError("Parameter 'url' must be a string, not "+typeof t);var o=t.indexOf("?"),c=-1!==o&&o<t.indexOf("#")?"?":"#",l=t.split(c);l[0]=l[0].replace(/\\/g,"/");var y=t=l.join(c);if(y=y.trim(),!n&&1===t.split("#").length){var w=s.exec(y);if(w)return this.path=y,this.href=y,this.pathname=w[1],w[2]?(this.search=w[2],this.query=e?b.parse(this.search.substr(1)):this.search.substr(1)):e&&(this.search="",this.query={}),this}var A=i.exec(y);if(A){var x=(A=A[0]).toLowerCase();this.protocol=x,y=y.substr(A.length)}if(n||A||y.match(/^\/\/[^@\/]+@[^@\/]+/)){var E="//"===y.substr(0,2);!E||A&&v[A]||(y=y.substr(2),this.slashes=!0)}if(!v[A]&&(E||A&&!g[A])){for(var O,j,_=-1,k=0;k<p.length;k++){-1!==(S=y.indexOf(p[k]))&&(-1===_||S<_)&&(_=S)}-1!==(j=-1===_?y.lastIndexOf("@"):y.lastIndexOf("@",_))&&(O=y.slice(0,j),y=y.slice(j+1),this.auth=decodeURIComponent(O)),_=-1;for(k=0;k<f.length;k++){var S;-1!==(S=y.indexOf(f[k]))&&(-1===_||S<_)&&(_=S)}-1===_&&(_=y.length),this.host=y.slice(0,_),y=y.slice(_),this.parseHost(),this.hostname=this.hostname||"";var T="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!T)for(var C=this.hostname.split(/\./),I=(k=0,C.length);k<I;k++){var N=C[k];if(N&&!N.match(d)){for(var P="",z=0,M=N.length;z<M;z++)N.charCodeAt(z)>127?P+="x":P+=N[z];if(!P.match(d)){var U=C.slice(0,k),R=C.slice(k+1),L=N.match(h);L&&(U.push(L[1]),R.unshift(L[2])),R.length&&(y="/"+R.join(".")+y),this.hostname=U.join(".");break}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),T||(this.hostname=r.toASCII(this.hostname));var D=this.port?":"+this.port:"",B=this.hostname||"";this.host=B+D,this.href+=this.host,T&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==y[0]&&(y="/"+y))}if(!m[x])for(k=0,I=u.length;k<I;k++){var F=u[k];if(-1!==y.indexOf(F)){var H=encodeURIComponent(F);H===F&&(H=escape(F)),y=y.split(F).join(H)}}var W=y.indexOf("#");-1!==W&&(this.hash=y.substr(W),y=y.slice(0,W));var Q=y.indexOf("?");if(-1!==Q?(this.search=y.substr(Q),this.query=y.substr(Q+1),e&&(this.query=b.parse(this.query)),y=y.slice(0,Q)):e&&(this.search="",this.query={}),y&&(this.pathname=y),g[x]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){D=this.pathname||"";var J=this.search||"";this.path=D+J}return this.href=this.format(),this},o.prototype.format=function(){var t=this.auth||"";t&&(t=(t=encodeURIComponent(t)).replace(/%3A/i,":"),t+="@");var e=this.protocol||"",n=this.pathname||"",r=this.hash||"",o=!1,i="";this.host?o=t+this.host:this.hostname&&(o=t+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(o+=":"+this.port)),this.query&&a.isObject(this.query)&&Object.keys(this.query).length&&(i=b.stringify(this.query));var c=this.search||i&&"?"+i||"";return e&&":"!==e.substr(-1)&&(e+=":"),this.slashes||(!e||g[e])&&!1!==o?(o="//"+(o||""),n&&"/"!==n.charAt(0)&&(n="/"+n)):o||(o=""),r&&"#"!==r.charAt(0)&&(r="#"+r),c&&"?"!==c.charAt(0)&&(c="?"+c),e+o+(n=n.replace(/[?#]/g,(function(t){return encodeURIComponent(t)})))+(c=c.replace("#","%23"))+r},o.prototype.resolve=function(t){return this.resolveObject(y(t,!1,!0)).format()},o.prototype.resolveObject=function(t){if(a.isString(t)){var e=new o;e.parse(t,!1,!0),t=e}for(var n=new o,r=Object.keys(this),i=0;i<r.length;i++){var c=r[i];n[c]=this[c]}if(n.hash=t.hash,""===t.href)return n.href=n.format(),n;if(t.slashes&&!t.protocol){for(var s=Object.keys(t),l=0;l<s.length;l++){var u=s[l];"protocol"!==u&&(n[u]=t[u])}return g[n.protocol]&&n.hostname&&!n.pathname&&(n.path=n.pathname="/"),n.href=n.format(),n}if(t.protocol&&t.protocol!==n.protocol){if(!g[t.protocol]){for(var f=Object.keys(t),p=0;p<f.length;p++){var d=f[p];n[d]=t[d]}return n.href=n.format(),n}if(n.protocol=t.protocol,t.host||v[t.protocol])n.pathname=t.pathname;else{for(var h=(t.pathname||"").split("/");h.length&&!(t.host=h.shift()););t.host||(t.host=""),t.hostname||(t.hostname=""),""!==h[0]&&h.unshift(""),h.length<2&&h.unshift(""),n.pathname=h.join("/")}if(n.search=t.search,n.query=t.query,n.host=t.host||"",n.auth=t.auth,n.hostname=t.hostname||t.host,n.port=t.port,n.pathname||n.search){var m=n.pathname||"",b=n.search||"";n.path=m+b}return n.slashes=n.slashes||t.slashes,n.href=n.format(),n}var y=n.pathname&&"/"===n.pathname.charAt(0),w=t.host||t.pathname&&"/"===t.pathname.charAt(0),A=w||y||n.host&&t.pathname,x=A,E=n.pathname&&n.pathname.split("/")||[],O=(h=t.pathname&&t.pathname.split("/")||[],n.protocol&&!g[n.protocol]);if(O&&(n.hostname="",n.port=null,n.host&&(""===E[0]?E[0]=n.host:E.unshift(n.host)),n.host="",t.protocol&&(t.hostname=null,t.port=null,t.host&&(""===h[0]?h[0]=t.host:h.unshift(t.host)),t.host=null),A=A&&(""===h[0]||""===E[0])),w)n.host=t.host||""===t.host?t.host:n.host,n.hostname=t.hostname||""===t.hostname?t.hostname:n.hostname,n.search=t.search,n.query=t.query,E=h;else if(h.length)E||(E=[]),E.pop(),E=E.concat(h),n.search=t.search,n.query=t.query;else if(!a.isNullOrUndefined(t.search)){if(O)n.hostname=n.host=E.shift(),(T=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=T.shift(),n.host=n.hostname=T.shift());return n.search=t.search,n.query=t.query,a.isNull(n.pathname)&&a.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.href=n.format(),n}if(!E.length)return n.pathname=null,n.search?n.path="/"+n.search:n.path=null,n.href=n.format(),n;for(var j=E.slice(-1)[0],_=(n.host||t.host||E.length>1)&&("."===j||".."===j)||""===j,k=0,S=E.length;S>=0;S--)"."===(j=E[S])?E.splice(S,1):".."===j?(E.splice(S,1),k++):k&&(E.splice(S,1),k--);if(!A&&!x)for(;k--;k)E.unshift("..");!A||""===E[0]||E[0]&&"/"===E[0].charAt(0)||E.unshift(""),_&&"/"!==E.join("/").substr(-1)&&E.push("");var T,C=""===E[0]||E[0]&&"/"===E[0].charAt(0);O&&(n.hostname=n.host=C?"":E.length?E.shift():"",(T=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=T.shift(),n.host=n.hostname=T.shift()));return(A=A||n.host&&E.length)&&!C&&E.unshift(""),E.length?n.pathname=E.join("/"):(n.pathname=null,n.path=null),a.isNull(n.pathname)&&a.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.auth=t.auth||n.auth,n.slashes=n.slashes||t.slashes,n.href=n.format(),n},o.prototype.parseHost=function(){var t=this.host,e=c.exec(t);e&&(":"!==(e=e[0])&&(this.port=e.substr(1)),t=t.substr(0,t.length-e.length)),t&&(this.hostname=t)}},2438:function(t){"use strict";t.exports={isString:function(t){return"string"==typeof t},isObject:function(t){return"object"==typeof t&&null!==t},isNull:function(t){return null===t},isNullOrUndefined:function(t){return null==t}}},8552:function(t,e,n){var r=n(852)(n(5639),"DataView");t.exports=r},1989:function(t,e,n){var r=n(1789),a=n(401),o=n(7667),i=n(1327),c=n(1866);function s(t){var e=-1,n=null==t?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}s.prototype.clear=r,s.prototype.delete=a,s.prototype.get=o,s.prototype.has=i,s.prototype.set=c,t.exports=s},8407:function(t,e,n){var r=n(7040),a=n(4125),o=n(2117),i=n(7518),c=n(3399);function s(t){var e=-1,n=null==t?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}s.prototype.clear=r,s.prototype.delete=a,s.prototype.get=o,s.prototype.has=i,s.prototype.set=c,t.exports=s},7071:function(t,e,n){var r=n(852)(n(5639),"Map");t.exports=r},3369:function(t,e,n){var r=n(4785),a=n(1285),o=n(6e3),i=n(9916),c=n(5265);function s(t){var e=-1,n=null==t?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}s.prototype.clear=r,s.prototype.delete=a,s.prototype.get=o,s.prototype.has=i,s.prototype.set=c,t.exports=s},3818:function(t,e,n){var r=n(852)(n(5639),"Promise");t.exports=r},8525:function(t,e,n){var r=n(852)(n(5639),"Set");t.exports=r},8668:function(t,e,n){var r=n(3369),a=n(619),o=n(2385);function i(t){var e=-1,n=null==t?0:t.length;for(this.__data__=new r;++e<n;)this.add(t[e])}i.prototype.add=i.prototype.push=a,i.prototype.has=o,t.exports=i},6384:function(t,e,n){var r=n(8407),a=n(7465),o=n(3779),i=n(7599),c=n(4758),s=n(4309);function l(t){var e=this.__data__=new r(t);this.size=e.size}l.prototype.clear=a,l.prototype.delete=o,l.prototype.get=i,l.prototype.has=c,l.prototype.set=s,t.exports=l},2705:function(t,e,n){var r=n(5639).Symbol;t.exports=r},1149:function(t,e,n){var r=n(5639).Uint8Array;t.exports=r},577:function(t,e,n){var r=n(852)(n(5639),"WeakMap");t.exports=r},4963:function(t){t.exports=function(t,e){for(var n=-1,r=null==t?0:t.length,a=0,o=[];++n<r;){var i=t[n];e(i,n,t)&&(o[a++]=i)}return o}},4636:function(t,e,n){var r=n(2545),a=n(5694),o=n(1469),i=n(4144),c=n(5776),s=n(6719),l=Object.prototype.hasOwnProperty;t.exports=function(t,e){var n=o(t),u=!n&&a(t),f=!n&&!u&&i(t),p=!n&&!u&&!f&&s(t),d=n||u||f||p,h=d?r(t.length,String):[],m=h.length;for(var v in t)!e&&!l.call(t,v)||d&&("length"==v||f&&("offset"==v||"parent"==v)||p&&("buffer"==v||"byteLength"==v||"byteOffset"==v)||c(v,m))||h.push(v);return h}},9932:function(t){t.exports=function(t,e){for(var n=-1,r=null==t?0:t.length,a=Array(r);++n<r;)a[n]=e(t[n],n,t);return a}},2488:function(t){t.exports=function(t,e){for(var n=-1,r=e.length,a=t.length;++n<r;)t[a+n]=e[n];return t}},2908:function(t){t.exports=function(t,e){for(var n=-1,r=null==t?0:t.length;++n<r;)if(e(t[n],n,t))return!0;return!1}},8470:function(t,e,n){var r=n(7813);t.exports=function(t,e){for(var n=t.length;n--;)if(r(t[n][0],e))return n;return-1}},9881:function(t,e,n){var r=n(7816),a=n(9291)(r);t.exports=a},8483:function(t,e,n){var r=n(5063)();t.exports=r},7816:function(t,e,n){var r=n(8483),a=n(3674);t.exports=function(t,e){return t&&r(t,e,a)}},7786:function(t,e,n){var r=n(1811),a=n(327);t.exports=function(t,e){for(var n=0,o=(e=r(e,t)).length;null!=t&&n<o;)t=t[a(e[n++])];return n&&n==o?t:void 0}},8866:function(t,e,n){var r=n(2488),a=n(1469);t.exports=function(t,e,n){var o=e(t);return a(t)?o:r(o,n(t))}},4239:function(t,e,n){var r=n(2705),a=n(9607),o=n(2333),i=r?r.toStringTag:void 0;t.exports=function(t){return null==t?void 0===t?"[object Undefined]":"[object Null]":i&&i in Object(t)?a(t):o(t)}},13:function(t){t.exports=function(t,e){return null!=t&&e in Object(t)}},9454:function(t,e,n){var r=n(4239),a=n(7005);t.exports=function(t){return a(t)&&"[object Arguments]"==r(t)}},939:function(t,e,n){var r=n(2492),a=n(7005);t.exports=function t(e,n,o,i,c){return e===n||(null==e||null==n||!a(e)&&!a(n)?e!=e&&n!=n:r(e,n,o,i,t,c))}},2492:function(t,e,n){var r=n(6384),a=n(7114),o=n(8351),i=n(6096),c=n(4160),s=n(1469),l=n(4144),u=n(6719),f="[object Arguments]",p="[object Array]",d="[object Object]",h=Object.prototype.hasOwnProperty;t.exports=function(t,e,n,m,v,g){var b=s(t),y=s(e),w=b?p:c(t),A=y?p:c(e),x=(w=w==f?d:w)==d,E=(A=A==f?d:A)==d,O=w==A;if(O&&l(t)){if(!l(e))return!1;b=!0,x=!1}if(O&&!x)return g||(g=new r),b||u(t)?a(t,e,n,m,v,g):o(t,e,w,n,m,v,g);if(!(1&n)){var j=x&&h.call(t,"__wrapped__"),_=E&&h.call(e,"__wrapped__");if(j||_){var k=j?t.value():t,S=_?e.value():e;return g||(g=new r),v(k,S,n,m,g)}}return!!O&&(g||(g=new r),i(t,e,n,m,v,g))}},2958:function(t,e,n){var r=n(6384),a=n(939);t.exports=function(t,e,n,o){var i=n.length,c=i,s=!o;if(null==t)return!c;for(t=Object(t);i--;){var l=n[i];if(s&&l[2]?l[1]!==t[l[0]]:!(l[0]in t))return!1}for(;++i<c;){var u=(l=n[i])[0],f=t[u],p=l[1];if(s&&l[2]){if(void 0===f&&!(u in t))return!1}else{var d=new r;if(o)var h=o(f,p,u,t,e,d);if(!(void 0===h?a(p,f,3,o,d):h))return!1}}return!0}},8458:function(t,e,n){var r=n(3560),a=n(5346),o=n(3218),i=n(346),c=/^\[object .+?Constructor\]$/,s=Function.prototype,l=Object.prototype,u=s.toString,f=l.hasOwnProperty,p=RegExp("^"+u.call(f).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");t.exports=function(t){return!(!o(t)||a(t))&&(r(t)?p:c).test(i(t))}},8749:function(t,e,n){var r=n(4239),a=n(1780),o=n(7005),i={};i["[object Float32Array]"]=i["[object Float64Array]"]=i["[object Int8Array]"]=i["[object Int16Array]"]=i["[object Int32Array]"]=i["[object Uint8Array]"]=i["[object Uint8ClampedArray]"]=i["[object Uint16Array]"]=i["[object Uint32Array]"]=!0,i["[object Arguments]"]=i["[object Array]"]=i["[object ArrayBuffer]"]=i["[object Boolean]"]=i["[object DataView]"]=i["[object Date]"]=i["[object Error]"]=i["[object Function]"]=i["[object Map]"]=i["[object Number]"]=i["[object Object]"]=i["[object RegExp]"]=i["[object Set]"]=i["[object String]"]=i["[object WeakMap]"]=!1,t.exports=function(t){return o(t)&&a(t.length)&&!!i[r(t)]}},7206:function(t,e,n){var r=n(1573),a=n(6432),o=n(6557),i=n(1469),c=n(9601);t.exports=function(t){return"function"==typeof t?t:null==t?o:"object"==typeof t?i(t)?a(t[0],t[1]):r(t):c(t)}},280:function(t,e,n){var r=n(5726),a=n(6916),o=Object.prototype.hasOwnProperty;t.exports=function(t){if(!r(t))return a(t);var e=[];for(var n in Object(t))o.call(t,n)&&"constructor"!=n&&e.push(n);return e}},9199:function(t,e,n){var r=n(9881),a=n(8612);t.exports=function(t,e){var n=-1,o=a(t)?Array(t.length):[];return r(t,(function(t,r,a){o[++n]=e(t,r,a)})),o}},1573:function(t,e,n){var r=n(2958),a=n(1499),o=n(2634);t.exports=function(t){var e=a(t);return 1==e.length&&e[0][2]?o(e[0][0],e[0][1]):function(n){return n===t||r(n,t,e)}}},6432:function(t,e,n){var r=n(939),a=n(7361),o=n(9095),i=n(5403),c=n(9162),s=n(2634),l=n(327);t.exports=function(t,e){return i(t)&&c(e)?s(l(t),e):function(n){var i=a(n,t);return void 0===i&&i===e?o(n,t):r(e,i,3)}}},371:function(t){t.exports=function(t){return function(e){return null==e?void 0:e[t]}}},9152:function(t,e,n){var r=n(7786);t.exports=function(t){return function(e){return r(e,t)}}},2545:function(t){t.exports=function(t,e){for(var n=-1,r=Array(t);++n<t;)r[n]=e(n);return r}},531:function(t,e,n){var r=n(2705),a=n(9932),o=n(1469),i=n(3448),c=r?r.prototype:void 0,s=c?c.toString:void 0;t.exports=function t(e){if("string"==typeof e)return e;if(o(e))return a(e,t)+"";if(i(e))return s?s.call(e):"";var n=e+"";return"0"==n&&1/e==-Infinity?"-0":n}},1717:function(t){t.exports=function(t){return function(e){return t(e)}}},4757:function(t){t.exports=function(t,e){return t.has(e)}},1811:function(t,e,n){var r=n(1469),a=n(5403),o=n(5514),i=n(9833);t.exports=function(t,e){return r(t)?t:a(t,e)?[t]:o(i(t))}},4429:function(t,e,n){var r=n(5639)["__core-js_shared__"];t.exports=r},9291:function(t,e,n){var r=n(8612);t.exports=function(t,e){return function(n,a){if(null==n)return n;if(!r(n))return t(n,a);for(var o=n.length,i=e?o:-1,c=Object(n);(e?i--:++i<o)&&!1!==a(c[i],i,c););return n}}},5063:function(t){t.exports=function(t){return function(e,n,r){for(var a=-1,o=Object(e),i=r(e),c=i.length;c--;){var s=i[t?c:++a];if(!1===n(o[s],s,o))break}return e}}},7114:function(t,e,n){var r=n(8668),a=n(2908),o=n(4757);t.exports=function(t,e,n,i,c,s){var l=1&n,u=t.length,f=e.length;if(u!=f&&!(l&&f>u))return!1;var p=s.get(t),d=s.get(e);if(p&&d)return p==e&&d==t;var h=-1,m=!0,v=2&n?new r:void 0;for(s.set(t,e),s.set(e,t);++h<u;){var g=t[h],b=e[h];if(i)var y=l?i(b,g,h,e,t,s):i(g,b,h,t,e,s);if(void 0!==y){if(y)continue;m=!1;break}if(v){if(!a(e,(function(t,e){if(!o(v,e)&&(g===t||c(g,t,n,i,s)))return v.push(e)}))){m=!1;break}}else if(g!==b&&!c(g,b,n,i,s)){m=!1;break}}return s.delete(t),s.delete(e),m}},8351:function(t,e,n){var r=n(2705),a=n(1149),o=n(7813),i=n(7114),c=n(8776),s=n(1814),l=r?r.prototype:void 0,u=l?l.valueOf:void 0;t.exports=function(t,e,n,r,l,f,p){switch(n){case"[object DataView]":if(t.byteLength!=e.byteLength||t.byteOffset!=e.byteOffset)return!1;t=t.buffer,e=e.buffer;case"[object ArrayBuffer]":return!(t.byteLength!=e.byteLength||!f(new a(t),new a(e)));case"[object Boolean]":case"[object Date]":case"[object Number]":return o(+t,+e);case"[object Error]":return t.name==e.name&&t.message==e.message;case"[object RegExp]":case"[object String]":return t==e+"";case"[object Map]":var d=c;case"[object Set]":var h=1&r;if(d||(d=s),t.size!=e.size&&!h)return!1;var m=p.get(t);if(m)return m==e;r|=2,p.set(t,e);var v=i(d(t),d(e),r,l,f,p);return p.delete(t),v;case"[object Symbol]":if(u)return u.call(t)==u.call(e)}return!1}},6096:function(t,e,n){var r=n(8234),a=Object.prototype.hasOwnProperty;t.exports=function(t,e,n,o,i,c){var s=1&n,l=r(t),u=l.length;if(u!=r(e).length&&!s)return!1;for(var f=u;f--;){var p=l[f];if(!(s?p in e:a.call(e,p)))return!1}var d=c.get(t),h=c.get(e);if(d&&h)return d==e&&h==t;var m=!0;c.set(t,e),c.set(e,t);for(var v=s;++f<u;){var g=t[p=l[f]],b=e[p];if(o)var y=s?o(b,g,p,e,t,c):o(g,b,p,t,e,c);if(!(void 0===y?g===b||i(g,b,n,o,c):y)){m=!1;break}v||(v="constructor"==p)}if(m&&!v){var w=t.constructor,A=e.constructor;w==A||!("constructor"in t)||!("constructor"in e)||"function"==typeof w&&w instanceof w&&"function"==typeof A&&A instanceof A||(m=!1)}return c.delete(t),c.delete(e),m}},1957:function(t,e,n){var r="object"==typeof n.g&&n.g&&n.g.Object===Object&&n.g;t.exports=r},8234:function(t,e,n){var r=n(8866),a=n(9551),o=n(3674);t.exports=function(t){return r(t,o,a)}},5050:function(t,e,n){var r=n(7019);t.exports=function(t,e){var n=t.__data__;return r(e)?n["string"==typeof e?"string":"hash"]:n.map}},1499:function(t,e,n){var r=n(9162),a=n(3674);t.exports=function(t){for(var e=a(t),n=e.length;n--;){var o=e[n],i=t[o];e[n]=[o,i,r(i)]}return e}},852:function(t,e,n){var r=n(8458),a=n(7801);t.exports=function(t,e){var n=a(t,e);return r(n)?n:void 0}},9607:function(t,e,n){var r=n(2705),a=Object.prototype,o=a.hasOwnProperty,i=a.toString,c=r?r.toStringTag:void 0;t.exports=function(t){var e=o.call(t,c),n=t[c];try{t[c]=void 0;var r=!0}catch(s){}var a=i.call(t);return r&&(e?t[c]=n:delete t[c]),a}},9551:function(t,e,n){var r=n(4963),a=n(479),o=Object.prototype.propertyIsEnumerable,i=Object.getOwnPropertySymbols,c=i?function(t){return null==t?[]:(t=Object(t),r(i(t),(function(e){return o.call(t,e)})))}:a;t.exports=c},4160:function(t,e,n){var r=n(8552),a=n(7071),o=n(3818),i=n(8525),c=n(577),s=n(4239),l=n(346),u="[object Map]",f="[object Promise]",p="[object Set]",d="[object WeakMap]",h="[object DataView]",m=l(r),v=l(a),g=l(o),b=l(i),y=l(c),w=s;(r&&w(new r(new ArrayBuffer(1)))!=h||a&&w(new a)!=u||o&&w(o.resolve())!=f||i&&w(new i)!=p||c&&w(new c)!=d)&&(w=function(t){var e=s(t),n="[object Object]"==e?t.constructor:void 0,r=n?l(n):"";if(r)switch(r){case m:return h;case v:return u;case g:return f;case b:return p;case y:return d}return e}),t.exports=w},7801:function(t){t.exports=function(t,e){return null==t?void 0:t[e]}},222:function(t,e,n){var r=n(1811),a=n(5694),o=n(1469),i=n(5776),c=n(1780),s=n(327);t.exports=function(t,e,n){for(var l=-1,u=(e=r(e,t)).length,f=!1;++l<u;){var p=s(e[l]);if(!(f=null!=t&&n(t,p)))break;t=t[p]}return f||++l!=u?f:!!(u=null==t?0:t.length)&&c(u)&&i(p,u)&&(o(t)||a(t))}},1789:function(t,e,n){var r=n(4536);t.exports=function(){this.__data__=r?r(null):{},this.size=0}},401:function(t){t.exports=function(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}},7667:function(t,e,n){var r=n(4536),a=Object.prototype.hasOwnProperty;t.exports=function(t){var e=this.__data__;if(r){var n=e[t];return"__lodash_hash_undefined__"===n?void 0:n}return a.call(e,t)?e[t]:void 0}},1327:function(t,e,n){var r=n(4536),a=Object.prototype.hasOwnProperty;t.exports=function(t){var e=this.__data__;return r?void 0!==e[t]:a.call(e,t)}},1866:function(t,e,n){var r=n(4536);t.exports=function(t,e){var n=this.__data__;return this.size+=this.has(t)?0:1,n[t]=r&&void 0===e?"__lodash_hash_undefined__":e,this}},5776:function(t){var e=/^(?:0|[1-9]\d*)$/;t.exports=function(t,n){var r=typeof t;return!!(n=null==n?9007199254740991:n)&&("number"==r||"symbol"!=r&&e.test(t))&&t>-1&&t%1==0&&t<n}},5403:function(t,e,n){var r=n(1469),a=n(3448),o=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,i=/^\w*$/;t.exports=function(t,e){if(r(t))return!1;var n=typeof t;return!("number"!=n&&"symbol"!=n&&"boolean"!=n&&null!=t&&!a(t))||(i.test(t)||!o.test(t)||null!=e&&t in Object(e))}},7019:function(t){t.exports=function(t){var e=typeof t;return"string"==e||"number"==e||"symbol"==e||"boolean"==e?"__proto__"!==t:null===t}},5346:function(t,e,n){var r,a=n(4429),o=(r=/[^.]+$/.exec(a&&a.keys&&a.keys.IE_PROTO||""))?"Symbol(src)_1."+r:"";t.exports=function(t){return!!o&&o in t}},5726:function(t){var e=Object.prototype;t.exports=function(t){var n=t&&t.constructor;return t===("function"==typeof n&&n.prototype||e)}},9162:function(t,e,n){var r=n(3218);t.exports=function(t){return t==t&&!r(t)}},7040:function(t){t.exports=function(){this.__data__=[],this.size=0}},4125:function(t,e,n){var r=n(8470),a=Array.prototype.splice;t.exports=function(t){var e=this.__data__,n=r(e,t);return!(n<0)&&(n==e.length-1?e.pop():a.call(e,n,1),--this.size,!0)}},2117:function(t,e,n){var r=n(8470);t.exports=function(t){var e=this.__data__,n=r(e,t);return n<0?void 0:e[n][1]}},7518:function(t,e,n){var r=n(8470);t.exports=function(t){return r(this.__data__,t)>-1}},3399:function(t,e,n){var r=n(8470);t.exports=function(t,e){var n=this.__data__,a=r(n,t);return a<0?(++this.size,n.push([t,e])):n[a][1]=e,this}},4785:function(t,e,n){var r=n(1989),a=n(8407),o=n(7071);t.exports=function(){this.size=0,this.__data__={hash:new r,map:new(o||a),string:new r}}},1285:function(t,e,n){var r=n(5050);t.exports=function(t){var e=r(this,t).delete(t);return this.size-=e?1:0,e}},6e3:function(t,e,n){var r=n(5050);t.exports=function(t){return r(this,t).get(t)}},9916:function(t,e,n){var r=n(5050);t.exports=function(t){return r(this,t).has(t)}},5265:function(t,e,n){var r=n(5050);t.exports=function(t,e){var n=r(this,t),a=n.size;return n.set(t,e),this.size+=n.size==a?0:1,this}},8776:function(t){t.exports=function(t){var e=-1,n=Array(t.size);return t.forEach((function(t,r){n[++e]=[r,t]})),n}},2634:function(t){t.exports=function(t,e){return function(n){return null!=n&&(n[t]===e&&(void 0!==e||t in Object(n)))}}},4523:function(t,e,n){var r=n(8306);t.exports=function(t){var e=r(t,(function(t){return 500===n.size&&n.clear(),t})),n=e.cache;return e}},4536:function(t,e,n){var r=n(852)(Object,"create");t.exports=r},6916:function(t,e,n){var r=n(5569)(Object.keys,Object);t.exports=r},1167:function(t,e,n){t=n.nmd(t);var r=n(1957),a=e&&!e.nodeType&&e,o=a&&t&&!t.nodeType&&t,i=o&&o.exports===a&&r.process,c=function(){try{var t=o&&o.require&&o.require("util").types;return t||i&&i.binding&&i.binding("util")}catch(e){}}();t.exports=c},2333:function(t){var e=Object.prototype.toString;t.exports=function(t){return e.call(t)}},5569:function(t){t.exports=function(t,e){return function(n){return t(e(n))}}},5639:function(t,e,n){var r=n(1957),a="object"==typeof self&&self&&self.Object===Object&&self,o=r||a||Function("return this")();t.exports=o},619:function(t){t.exports=function(t){return this.__data__.set(t,"__lodash_hash_undefined__"),this}},2385:function(t){t.exports=function(t){return this.__data__.has(t)}},1814:function(t){t.exports=function(t){var e=-1,n=Array(t.size);return t.forEach((function(t){n[++e]=t})),n}},7465:function(t,e,n){var r=n(8407);t.exports=function(){this.__data__=new r,this.size=0}},3779:function(t){t.exports=function(t){var e=this.__data__,n=e.delete(t);return this.size=e.size,n}},7599:function(t){t.exports=function(t){return this.__data__.get(t)}},4758:function(t){t.exports=function(t){return this.__data__.has(t)}},4309:function(t,e,n){var r=n(8407),a=n(7071),o=n(3369);t.exports=function(t,e){var n=this.__data__;if(n instanceof r){var i=n.__data__;if(!a||i.length<199)return i.push([t,e]),this.size=++n.size,this;n=this.__data__=new o(i)}return n.set(t,e),this.size=n.size,this}},5514:function(t,e,n){var r=n(4523),a=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,o=/\\(\\)?/g,i=r((function(t){var e=[];return 46===t.charCodeAt(0)&&e.push(""),t.replace(a,(function(t,n,r,a){e.push(r?a.replace(o,"$1"):n||t)})),e}));t.exports=i},327:function(t,e,n){var r=n(3448);t.exports=function(t){if("string"==typeof t||r(t))return t;var e=t+"";return"0"==e&&1/t==-Infinity?"-0":e}},346:function(t){var e=Function.prototype.toString;t.exports=function(t){if(null!=t){try{return e.call(t)}catch(n){}try{return t+""}catch(n){}}return""}},9693:function(t){t.exports=function(t){for(var e=-1,n=null==t?0:t.length,r=0,a=[];++e<n;){var o=t[e];o&&(a[r++]=o)}return a}},7813:function(t){t.exports=function(t,e){return t===e||t!=t&&e!=e}},7361:function(t,e,n){var r=n(7786);t.exports=function(t,e,n){var a=null==t?void 0:r(t,e);return void 0===a?n:a}},9095:function(t,e,n){var r=n(13),a=n(222);t.exports=function(t,e){return null!=t&&a(t,e,r)}},6557:function(t){t.exports=function(t){return t}},5694:function(t,e,n){var r=n(9454),a=n(7005),o=Object.prototype,i=o.hasOwnProperty,c=o.propertyIsEnumerable,s=r(function(){return arguments}())?r:function(t){return a(t)&&i.call(t,"callee")&&!c.call(t,"callee")};t.exports=s},1469:function(t){var e=Array.isArray;t.exports=e},8612:function(t,e,n){var r=n(3560),a=n(1780);t.exports=function(t){return null!=t&&a(t.length)&&!r(t)}},4144:function(t,e,n){t=n.nmd(t);var r=n(5639),a=n(5062),o=e&&!e.nodeType&&e,i=o&&t&&!t.nodeType&&t,c=i&&i.exports===o?r.Buffer:void 0,s=(c?c.isBuffer:void 0)||a;t.exports=s},3560:function(t,e,n){var r=n(4239),a=n(3218);t.exports=function(t){if(!a(t))return!1;var e=r(t);return"[object Function]"==e||"[object GeneratorFunction]"==e||"[object AsyncFunction]"==e||"[object Proxy]"==e}},1780:function(t){t.exports=function(t){return"number"==typeof t&&t>-1&&t%1==0&&t<=9007199254740991}},3218:function(t){t.exports=function(t){var e=typeof t;return null!=t&&("object"==e||"function"==e)}},7005:function(t){t.exports=function(t){return null!=t&&"object"==typeof t}},3448:function(t,e,n){var r=n(4239),a=n(7005);t.exports=function(t){return"symbol"==typeof t||a(t)&&"[object Symbol]"==r(t)}},6719:function(t,e,n){var r=n(8749),a=n(1717),o=n(1167),i=o&&o.isTypedArray,c=i?a(i):r;t.exports=c},8611:function(t){var e=Array.prototype.join;t.exports=function(t,n){return null==t?"":e.call(t,n)}},3674:function(t,e,n){var r=n(4636),a=n(280),o=n(8612);t.exports=function(t){return o(t)?r(t):a(t)}},5161:function(t,e,n){var r=n(9932),a=n(7206),o=n(9199),i=n(1469);t.exports=function(t,e){return(i(t)?r:o)(t,a(e,3))}},8306:function(t,e,n){var r=n(3369);function a(t,e){if("function"!=typeof t||null!=e&&"function"!=typeof e)throw new TypeError("Expected a function");var n=function(){var r=arguments,a=e?e.apply(this,r):r[0],o=n.cache;if(o.has(a))return o.get(a);var i=t.apply(this,r);return n.cache=o.set(a,i)||o,i};return n.cache=new(a.Cache||r),n}a.Cache=r,t.exports=a},9601:function(t,e,n){var r=n(371),a=n(9152),o=n(5403),i=n(327);t.exports=function(t){return o(t)?r(i(t)):a(t)}},479:function(t){t.exports=function(){return[]}},5062:function(t){t.exports=function(){return!1}},9833:function(t,e,n){var r=n(531);t.exports=function(t){return null==t?"":r(t)}}}]); //# sourceMappingURL=262bf9f6bb83288aa934600be7ca63bba17eff5d-22c69fbf2a4dddf2c2ae.js.map
// Copyright (C) 2020, Aktiv-Soft JSC. All rights reserved. // This file is part of rtuart project licensed under the terms of the 2-clause // BSD license. See the LICENSE file found in the top-level directory of this // distribution. #include <rtuartscreader/iso7816_3/apdu_t0.h> #include <rtuartscreader/iso7816_3/detail/error.h> #include <rtuartscreader/log/log.h> #include <rtuartscreader/transport/sendrecv.h> #include <rtuartscreader/transport/transport_t.h> #include <rtuartscreader/utils/buffer_view.h> #define APDU_HEADER_SIZE 5 #define APDU_INS_OFFSET 1 #define APDU_P3_OFFSET 4 #define APDU_MAX_NE_VALUE 0x100 #define PROCEDURE_BYTE_NULL 0x60 static inline uint16_t le_to_ne(uint8_t le) { if (le == 0x00) return APDU_MAX_NE_VALUE; return le; } static transport_status_t send_apdu_header(const transport_t* transport, const uint8_t* tx_buf, uint8_t p3) { transport_status_t r; r = transport_send_bytes(transport, tx_buf, APDU_HEADER_SIZE - 1); POPULATE_ERROR(r, transport_status_ok, r); return transport_send_byte(transport, p3); } static iso7816_3_status_t t0_transceive_data(const transport_t* transport, const uint8_t ack, pop_front_buffer_view* send_data, push_back_buffer_view* recv_data) { const uint8_t inv_ack = ~ack; while (1) { uint8_t proc_byte; transport_status_t r = transport_recv_byte(transport, &proc_byte); RETURN_ON_TRANSPORT_ERROR(r); // NULL byte if (proc_byte == PROCEDURE_BYTE_NULL) continue; // SW1 byte, recieve SW2 and quit if ((proc_byte & 0xf0) == 0x60 || (proc_byte & 0xf0) == 0x90) { if (push_back_buffer_view_full(recv_data)) { LOG_RETURN_ISO7816_3_ERROR_MSG(iso7816_3_status_unexpected_card_response, "The card sent more data than expected"); } push_back_buffer_view_push(recv_data, proc_byte); if (push_back_buffer_view_full(recv_data)) { LOG_RETURN_ISO7816_3_ERROR_MSG(iso7816_3_status_unexpected_card_response, "The card sent more data than expected"); } r = transport_recv_byte(transport, push_back_buffer_view_reserve_n(recv_data, 1)); RETURN_ON_TRANSPORT_ERROR(r); break; } if (proc_byte == ack) { if (!pop_front_buffer_view_empty(send_data)) { size_t data_size = pop_front_buffer_view_size(send_data); const uint8_t* data = pop_front_buffer_view_pop_n(send_data, data_size); r = transport_send_bytes(transport, data, data_size); RETURN_ON_TRANSPORT_ERROR(r); } else { size_t free_space = push_back_buffer_view_free_space(recv_data); if (free_space <= 2) { LOG_RETURN_ISO7816_3_ERROR_MSG(iso7816_3_status_unexpected_card_response, "The card sent more data than expected"); } uint8_t* data = push_back_buffer_view_reserve_n(recv_data, free_space - 2); r = transport_recv_bytes(transport, data, free_space - 2); RETURN_ON_TRANSPORT_ERROR(r); } continue; } if (proc_byte == inv_ack) { if (!pop_front_buffer_view_empty(send_data)) { r = transport_send_byte(transport, pop_front_buffer_view_pop(send_data)); RETURN_ON_TRANSPORT_ERROR(r); } else { size_t free_space = push_back_buffer_view_free_space(recv_data); if (free_space <= 2) { LOG_RETURN_ISO7816_3_ERROR_MSG(iso7816_3_status_unexpected_card_response, "The card sent more data than expected"); } r = transport_recv_byte(transport, push_back_buffer_view_reserve_n(recv_data, 1)); RETURN_ON_TRANSPORT_ERROR(r); } } } return iso7816_3_status_ok; } // TODO: add logging for transport IO functions iso7816_3_status_t t0_transmit_apdu(const transport_t* transport, const uint8_t* tx_buf, uint16_t tx_len, uint8_t* rx_buf, uint16_t* rx_len) { transport_status_t r; uint16_t ne = 0; // expected data size to receive uint8_t nc = 0; // expected data size to send uint8_t p3; if (tx_len < APDU_HEADER_SIZE - 1) { LOG_RETURN_ISO7816_3_ERROR_MSG(iso7816_3_status_invalid_params, "APDU buffer too short"); } else if (tx_len == APDU_HEADER_SIZE - 1) { p3 = 0; } else if (tx_len == APDU_HEADER_SIZE) { p3 = tx_buf[APDU_P3_OFFSET]; ne = le_to_ne(p3); } else if (tx_len > APDU_HEADER_SIZE) { p3 = tx_buf[APDU_P3_OFFSET]; nc = p3; if (tx_len < APDU_HEADER_SIZE + nc) { LOG_RETURN_ISO7816_3_ERROR_MSG(iso7816_3_status_invalid_params, "APDU is not complete"); } else if (tx_len == nc + APDU_HEADER_SIZE) { ne = 0; } else if (tx_len == nc + APDU_HEADER_SIZE + 1) { ne = le_to_ne(tx_buf[tx_len - 1]); } else { LOG_RETURN_ISO7816_3_ERROR_MSG(iso7816_3_status_invalid_params, "APDU buffer has excess data"); } } if (*rx_len < ne + 2) { LOG_RETURN_ISO7816_3_ERROR_MSG(iso7816_3_status_insufficient_buffer, "Response buffer too short"); } r = send_apdu_header(transport, tx_buf, p3); RETURN_ON_TRANSPORT_ERROR(r); pop_front_buffer_view send_data; pop_front_buffer_view_init(&send_data, tx_buf + APDU_HEADER_SIZE, nc); push_back_buffer_view recv_data; push_back_buffer_view_init(&recv_data, rx_buf, ne + 2); const uint8_t ack = tx_buf[APDU_INS_OFFSET]; iso7816_3_status_t transceive_data_result = t0_transceive_data(transport, ack, &send_data, &recv_data); POPULATE_ERROR(transceive_data_result, iso7816_3_status_ok, transceive_data_result); *rx_len = push_back_buffer_view_size(&recv_data); return iso7816_3_status_ok; }
from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activation import data_prep from nn import * from keras.layers import Conv1D, Conv2D, Dense, MaxPooling1D, Flatten, Embedding, Reshape, MaxPool2D, LSTM # from keras import backend as K # from rnn import w_categorical_crossentropy, loss_class_accuracy # from functools import partial, update_wrapper class CNNLSTM: def __init__(self, input_shape, output_dim): self.input_shape = input_shape self.output_dim = output_dim self.model = self.__prepare_model() def __prepare_model(self): print('Build model...') # w_array = np.ones((3, 3)) # penalty = 1.2 # w_array[2, 1] = penalty # w_array[1, 2] = penalty # custom_loss = partial(w_categorical_crossentropy, weights=w_array) # custom_loss.__name__ = 'w_categorical_crossentropy' # convolutional layer self.nb_filter = 50 # 50 output channels self.kernel_size_x = self.input_shape[0]//10 # 50 -> 5 self.kernel_size_y = self.input_shape[1] # 48 model = Sequential() model.add(Conv2D(self.nb_filter, (self.kernel_size_x, self.kernel_size_y), input_shape=self.input_shape, activation='relu')) # model.add(MaxPool2D(pool_size=(2, 2))) by imposing kernel_size_y to #features model.add(Dropout(0.2)) model.add(Reshape(target_shape=(50-self.kernel_size_x+1, self.nb_filter))) model.add(LSTM(64, return_sequences=False)) model.add(Dense(128, activation='relu')) model.add(Dense(self.output_dim, activation='softmax')) print('Compile model...') model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return model def get_model(self): return self.model def main(): timestep = 50 n_cross_validation = 3 data = data_prep.get_test_data(timestep, predict_step=5, filename="upbit_l2_orderbook_ADA") # for convolutional layer consider sample as a 2d gray picture # x.shape[1] time step(input_length) # x.shape[2] features(input_dim) # data.x.shape <- (n_training_samples, timestep, 1, n_features) data.x = data.x.reshape(data.x.shape[0], data.x.shape[1], data.x.shape[2], 1).astype('float32') nn = NeuralNetwork(CNNLSTM(input_shape = data.x.shape[1:], output_dim= data.y.shape[1]), class_weight= {0:1., 1:1., 2:1.}) # num of output dim print("TRAIN") nn.train(data) print("TEST") nn.test(data) print("TRAIN WITH CROSS-VALIDATION") # nn.run_with_cross_validation(data, n_cross_validation) if __name__ == '__main__': main()
/** * Copyright IBM Corp. 2019, 2020 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. * * Code generated by @carbon/icon-build-helpers. DO NOT EDIT. */ import { _ as _objectWithoutProperties, I as Icon, a as _extends } from '../Icon-63ed8f4f.js'; import '@carbon/icon-helpers'; import 'prop-types'; import React from 'react'; var _ref2 = /*#__PURE__*/ /*#__PURE__*/ React.createElement("path", { d: "M16,7h0a7.66,7.66,0,0,1,1.51.15,8,8,0,0,1,6.35,6.34l.26,1.35,1.35.24a5.5,5.5,0,0,1-1,10.92H7.5a5.5,5.5,0,0,1-1-10.92l1.34-.24.26-1.35A8,8,0,0,1,16,7m0-2a10,10,0,0,0-9.83,8.12A7.5,7.5,0,0,0,7.49,28h17a7.5,7.5,0,0,0,1.32-14.88,10,10,0,0,0-7.94-7.94A10.27,10.27,0,0,0,16,5Z" }); var Cloud20 = /*#__PURE__*/React.forwardRef(function Cloud20(_ref, ref) { var children = _ref.children, rest = _objectWithoutProperties(_ref, ["children"]); return /*#__PURE__*/React.createElement(Icon, _extends({ width: 20, height: 20, viewBox: "0 0 32 32", xmlns: "http://www.w3.org/2000/svg", fill: "currentColor", ref: ref }, rest), _ref2, children); }); export default Cloud20;
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. cr.exportPath('options'); /** * @typedef {{actionLinkText: (string|undefined), * accountInfo: (string|undefined), * childUser: (boolean|undefined), * hasError: (boolean|undefined), * hasUnrecoverableError: (boolean|undefined), * managed: (boolean|undefined), * setupCompleted: (boolean|undefined), * setupInProgress: (boolean|undefined), * signedIn: (boolean|undefined), * signinAllowed: (boolean|undefined), * signoutAllowed: (boolean|undefined), * statusAction: (string|undefined), * statusText: (string|undefined), * supervisedUser: (boolean|undefined), * syncSystemEnabled: (boolean|undefined)}} * @see chrome/browser/ui/webui/options/browser_options_handler.cc */ options.SyncStatus; /** * @typedef {{id: string, name: string}} */ options.ExtensionData; /** * @typedef {{name: string, * filePath: string, * isCurrentProfile: boolean, * isSupervised: boolean, * isChild: boolean, * iconUrl: string}} * @see chrome/browser/ui/webui/options/browser_options_handler.cc */ options.Profile; /** * Device policy SystemTimezoneAutomaticDetection values. * @enum {number} * @const */ options.AutomaticTimezoneDetectionType = { USERS_DECIDE: 0, DISABLED: 1, IP_ONLY: 2, SEND_WIFI_ACCESS_POINTS: 3, }; cr.define('options', function() { var OptionsPage = options.OptionsPage; var Page = cr.ui.pageManager.Page; var PageManager = cr.ui.pageManager.PageManager; var ArrayDataModel = cr.ui.ArrayDataModel; var RepeatingButton = cr.ui.RepeatingButton; var HotwordSearchSettingIndicator = options.HotwordSearchSettingIndicator; var NetworkPredictionOptions = { ALWAYS: 0, WIFI_ONLY: 1, NEVER: 2, DEFAULT: 1 }; /** * Encapsulated handling of browser options page. * @constructor * @extends {cr.ui.pageManager.Page} */ function BrowserOptions() { Page.call(this, 'settings', loadTimeData.getString('settingsTitle'), 'settings'); } cr.addSingletonGetter(BrowserOptions); /** * @param {HTMLElement} section The section to show or hide. * @return {boolean} Whether the section should be shown. * @private */ BrowserOptions.shouldShowSection_ = function(section) { // If the section is hidden or hiding, it should be shown. return section.style.height == '' || section.style.height == '0px'; }; BrowserOptions.prototype = { __proto__: Page.prototype, /** * Keeps track of whether the user is signed in or not. * @private {boolean} */ signedIn_: false, /** * Indicates whether signing out is allowed or whether a complete profile * wipe is required to remove the current enterprise account. * @private {boolean} */ signoutAllowed_: true, /** * Keeps track of whether |onShowHomeButtonChanged_| has been called. See * |onShowHomeButtonChanged_|. * @private {boolean} */ onShowHomeButtonChangedCalled_: false, /** * Track if page initialization is complete. All C++ UI handlers have the * chance to manipulate page content within their InitializePage methods. * This flag is set to true after all initializers have been called. * @private {boolean} */ initializationComplete_: false, /** * Current status of "Resolve Timezone by Geolocation" checkbox. * @private {boolean} */ resolveTimezoneByGeolocation_: false, /** * True if system timezone is managed by policy. * @private {boolean} */ systemTimezoneIsManaged_: false, /** * True if system timezone detection is managed by policy. * @private {boolean} */ systemTimezoneAutomaticDetectionIsManaged_: false, /** * This is the value of SystemTimezoneAutomaticDetection policy. * @private {number} */ systemTimezoneAutomaticDetectionValue_: 0, /** * Cached bluetooth adapter state. * @private {?chrome.bluetooth.AdapterState} */ bluetoothAdapterState_: null, /** @override */ initializePage: function() { Page.prototype.initializePage.call(this); var self = this; if (window.top != window) { // The options page is not in its own window. document.body.classList.add('uber-frame'); PageManager.horizontalOffset = 155; } // Ensure that navigation events are unblocked on uber page. A reload of // the settings page while an overlay is open would otherwise leave uber // page in a blocked state, where tab switching is not possible. uber.invokeMethodOnParent('stopInterceptingEvents'); window.addEventListener('message', this.handleWindowMessage_.bind(this)); if (loadTimeData.getBoolean('allowAdvancedSettings')) { $('advanced-settings-expander').onclick = function(e) { var showAdvanced = BrowserOptions.shouldShowSection_($('advanced-settings')); if (showAdvanced) { chrome.send('coreOptionsUserMetricsAction', ['Options_ShowAdvancedSettings']); } self.toggleSectionWithAnimation_( $('advanced-settings'), $('advanced-settings-container')); // If the click was triggered using the keyboard and it showed the // section (rather than hiding it), focus the first element in the // container. if (e.detail == 0 && showAdvanced) { var focusElement = $('advanced-settings-container').querySelector( 'button, input, list, select, a[href]'); if (focusElement) focusElement.focus(); } }; } else { $('advanced-settings-footer').hidden = true; $('advanced-settings').hidden = true; } $('advanced-settings').addEventListener('webkitTransitionEnd', this.updateAdvancedSettingsExpander_.bind(this)); if (loadTimeData.getBoolean('showAbout')) { $('about-button').hidden = false; $('about-button').addEventListener('click', function() { PageManager.showPageByName('help'); chrome.send('coreOptionsUserMetricsAction', ['Options_About']); }); } if (cr.isChromeOS) { UIAccountTweaks.applyGuestSessionVisibility(document); UIAccountTweaks.applyPublicSessionVisibility(document); if (loadTimeData.getBoolean('secondaryUser')) $('secondary-user-banner').hidden = false; } // Sync (Sign in) section. this.updateSyncState_(/** @type {options.SyncStatus} */( loadTimeData.getValue('syncData'))); if (!$('sync-overview').hidden) { chrome.send('metricsHandler:recordAction', ['Signin_Impression_FromSettings']); } $('start-stop-sync').onclick = function(event) { if (self.signedIn_) { if (self.signoutAllowed_) SyncSetupOverlay.showStopSyncingUI(); else chrome.send('showDisconnectManagedProfileDialog'); } else if (cr.isChromeOS) { SyncSetupOverlay.showSetupUI(); } else { SyncSetupOverlay.startSignIn(false /* creatingSupervisedUser */); } }; $('customize-sync').onclick = function(event) { SyncSetupOverlay.showSetupUI(); }; // Internet connection section (ChromeOS only). if (cr.isChromeOS) { options.network.NetworkList.decorate($('network-list')); // Show that the network settings are shared if this is a secondary user // in a multi-profile session. if (loadTimeData.getBoolean('secondaryUser')) { var networkIndicator = document.querySelector( '#network-section-header > .controlled-setting-indicator'); networkIndicator.setAttribute('controlled-by', 'shared'); networkIndicator.location = cr.ui.ArrowLocation.TOP_START; } } // On Startup section. Preferences.getInstance().addEventListener('session.restore_on_startup', this.onRestoreOnStartupChanged_.bind(this)); Preferences.getInstance().addEventListener( 'session.startup_urls', function(event) { $('startup-set-pages').disabled = event.value.disabled; }); $('startup-set-pages').onclick = function() { PageManager.showPageByName('startup'); }; // Appearance section. Preferences.getInstance().addEventListener('browser.show_home_button', this.onShowHomeButtonChanged_.bind(this)); Preferences.getInstance().addEventListener('homepage', this.onHomePageChanged_.bind(this)); Preferences.getInstance().addEventListener('homepage_is_newtabpage', this.onHomePageIsNtpChanged_.bind(this)); $('change-home-page').onclick = function(event) { PageManager.showPageByName('homePageOverlay'); chrome.send('coreOptionsUserMetricsAction', ['Options_Homepage_ShowSettings']); }; HotwordSearchSettingIndicator.decorate( $('hotword-search-setting-indicator')); HotwordSearchSettingIndicator.decorate( $('hotword-no-dsp-search-setting-indicator')); var hotwordIndicator = $('hotword-always-on-search-setting-indicator'); HotwordSearchSettingIndicator.decorate(hotwordIndicator); hotwordIndicator.disabledOnErrorSection = $('hotword-always-on-search-checkbox'); chrome.send('requestHotwordAvailable'); chrome.send('requestGoogleNowAvailable'); if ($('set-wallpaper')) { $('set-wallpaper').onclick = function(event) { chrome.send('openWallpaperManager'); chrome.send('coreOptionsUserMetricsAction', ['Options_OpenWallpaperManager']); }; } // Control the hotword-always-on pref with the Hotword Audio // Verification app. $('hotword-always-on-search-checkbox').customChangeHandler = function(event) { if (!$('hotword-always-on-search-checkbox').checked) return false; $('hotword-always-on-search-checkbox').checked = false; chrome.send('launchHotwordAudioVerificationApp', [false]); return true; }; // Open the Hotword Audio Verification app to retrain a voice model. $('hotword-retrain-link').onclick = function(event) { chrome.send('launchHotwordAudioVerificationApp', [true]); }; Preferences.getInstance().addEventListener( 'hotword.always_on_search_enabled', this.onHotwordAlwaysOnChanged_.bind(this)); $('themes-gallery').onclick = function(event) { window.open(loadTimeData.getString('themesGalleryURL')); chrome.send('coreOptionsUserMetricsAction', ['Options_ThemesGallery']); }; $('themes-reset').onclick = function(event) { chrome.send('themesReset'); }; if (loadTimeData.getBoolean('profileIsSupervised')) { if ($('themes-native-button')) { $('themes-native-button').disabled = true; $('themes-native-button').hidden = true; } // Supervised users have just one default theme, even on Linux. So use // the same button for Linux as for the other platforms. $('themes-reset').textContent = loadTimeData.getString('themesReset'); } // Device section (ChromeOS only). if (cr.isChromeOS) { if (loadTimeData.getBoolean('showStylusSettings')) { $('stylus-settings-link').onclick = function(event) { PageManager.showPageByName('stylus-overlay'); }; $('stylus-row').hidden = false; } if (loadTimeData.getBoolean('showPowerStatus')) { $('power-settings-link').onclick = function(evt) { PageManager.showPageByName('power-overlay'); chrome.send('coreOptionsUserMetricsAction', ['Options_ShowPowerSettings']); }; $('power-row').hidden = false; } $('keyboard-settings-button').onclick = function(evt) { PageManager.showPageByName('keyboard-overlay'); chrome.send('coreOptionsUserMetricsAction', ['Options_ShowKeyboardSettings']); }; $('pointer-settings-button').onclick = function(evt) { PageManager.showPageByName('pointer-overlay'); chrome.send('coreOptionsUserMetricsAction', ['Options_ShowTouchpadSettings']); }; $('storage-manager-button').onclick = function(evt) { PageManager.showPageByName('storage'); chrome.send('coreOptionsUserMetricsAction', ['Options_ShowStorageManager']); }; } // Search section. $('manage-default-search-engines').onclick = function(event) { PageManager.showPageByName('searchEngines'); chrome.send('coreOptionsUserMetricsAction', ['Options_ManageSearchEngines']); }; $('default-search-engine').addEventListener('change', this.setDefaultSearchEngine_); // Users section. if (loadTimeData.valueExists('profilesInfo')) { $('profiles-section').hidden = false; this.maybeShowUserSection_(); var profilesList = $('profiles-list'); options.browser_options.ProfileList.decorate(profilesList); profilesList.autoExpands = true; // The profiles info data in |loadTimeData| might be stale. this.setProfilesInfo_(/** @type {!Array<!options.Profile>} */( loadTimeData.getValue('profilesInfo'))); chrome.send('requestProfilesInfo'); profilesList.addEventListener('change', this.setProfileViewButtonsStatus_); $('profiles-create').onclick = function(event) { chrome.send('metricsHandler:recordAction', ['Options_ShowCreateProfileDlg']); ManageProfileOverlay.showCreateDialog(); }; $('profiles-manage').onclick = function(event) { chrome.send('metricsHandler:recordAction', ['Options_ShowEditProfileDlg']); ManageProfileOverlay.showManageDialog(); }; $('profiles-delete').onclick = function(event) { var selectedProfile = self.getSelectedProfileItem_(); if (selectedProfile) { chrome.send('metricsHandler:recordAction', ['Options_ShowDeleteProfileDlg']); ManageProfileOverlay.showDeleteDialog(selectedProfile); } }; if (loadTimeData.getBoolean('profileIsSupervised')) { $('profiles-create').disabled = true; } if (!loadTimeData.getBoolean('allowProfileDeletion')) { $('profiles-delete').disabled = true; $('profiles-list').canDeleteItems = false; } } if (cr.isChromeOS) { // Username (canonical email) of the currently logged in user or // |kGuestUser| if a guest session is active. this.username_ = loadTimeData.getString('username'); this.updateAccountPicture_(); $('account-picture').onclick = this.showImagerPickerOverlay_; $('change-picture-caption').onclick = this.showImagerPickerOverlay_; $('manage-accounts-button').onclick = function(event) { PageManager.showPageByName('accounts'); chrome.send('coreOptionsUserMetricsAction', ['Options_ManageAccounts']); }; if (loadTimeData.getBoolean('showQuickUnlockSettings')) { $('manage-screenlock').onclick = function(event) { PageManager.showPageByName('quickUnlockConfigureOverlay'); settings.recordLockScreenProgress( LockScreenProgress.START_SCREEN_LOCK); }; $('manage-screenlock').hidden = false; } } else { $('import-data').onclick = function(event) { ImportDataOverlay.show(); chrome.send('coreOptionsUserMetricsAction', ['Import_ShowDlg']); }; if ($('themes-native-button')) { $('themes-native-button').onclick = function(event) { chrome.send('themesSetNative'); }; } } // Date and time section (CrOS only). if (cr.isChromeOS) { if ($('set-time-button')) $('set-time-button').onclick = this.handleSetTime_.bind(this); // Timezone if (loadTimeData.getBoolean('enableTimeZoneTrackingOption')) { $('resolve-timezone-by-geolocation-selection').hidden = false; this.resolveTimezoneByGeolocation_ = loadTimeData.getBoolean( 'resolveTimezoneByGeolocationInitialValue'); this.updateTimezoneSectionState_(); Preferences.getInstance().addEventListener( 'settings.resolve_timezone_by_geolocation', this.onResolveTimezoneByGeolocationChanged_.bind(this)); } } // Default browser section. if (!cr.isChromeOS) { if (!loadTimeData.getBoolean('showSetDefault')) { $('set-default-browser-section').hidden = true; } $('set-as-default-browser').onclick = function(event) { chrome.send('becomeDefaultBrowser'); }; } // Privacy section. $('privacyContentSettingsButton').onclick = function(event) { PageManager.showPageByName('content'); OptionsPage.showTab($('cookies-nav-tab')); chrome.send('coreOptionsUserMetricsAction', ['Options_ContentSettings']); }; $('privacyClearDataButton').onclick = function(event) { PageManager.showPageByName('clearBrowserData'); chrome.send('coreOptionsUserMetricsAction', ['Options_ClearData']); }; if ($('metrics-reporting-enabled')) { $('metrics-reporting-enabled').checked = loadTimeData.getBoolean('metricsReportingEnabledAtStart'); // A browser restart is never needed to toggle metrics reporting, // and is only needed to toggle crash reporting when using Breakpad. // Crashpad, used on Mac, does not require a browser restart. var togglingMetricsRequiresRestart = !cr.isMac && !cr.isChromeOS; $('metrics-reporting-enabled').onclick = function(event) { chrome.send('metricsReportingCheckboxChanged', [Boolean(event.currentTarget.checked)]); if (cr.isChromeOS) { // 'metricsReportingEnabled' element is only present on Chrome // branded builds, and the 'metricsReportingCheckboxAction' message // is only handled on ChromeOS. chrome.send('metricsReportingCheckboxAction', [String(event.currentTarget.checked)]); } if (togglingMetricsRequiresRestart) { $('metrics-reporting-reset-restart').hidden = loadTimeData.getBoolean('metricsReportingEnabledAtStart') == $('metrics-reporting-enabled').checked; } }; // Initialize restart button if needed. if (togglingMetricsRequiresRestart) { // The localized string has the | symbol on each side of the text that // needs to be made into a button to restart Chrome. We parse the text // and build the button from that. var restartTextFragments = loadTimeData.getString('metricsReportingResetRestart').split('|'); // Assume structure is something like "starting text |link text| // ending text" where both starting text and ending text may or may // not be present, but the split should always be in three pieces. var restartElements = $('metrics-reporting-reset-restart').querySelectorAll('*'); for (var i = 0; i < restartTextFragments.length; i++) { restartElements[i].textContent = restartTextFragments[i]; } restartElements[1].onclick = function(event) { chrome.send('restartBrowser'); }; } } $('networkPredictionOptions').onchange = function(event) { var value = (event.target.checked ? NetworkPredictionOptions.WIFI_ONLY : NetworkPredictionOptions.NEVER); var metric = event.target.metric; Preferences.setIntegerPref( 'net.network_prediction_options', value, true, metric); }; if (loadTimeData.valueExists('showWakeOnWifi') && loadTimeData.getBoolean('showWakeOnWifi')) { $('wake-on-wifi').hidden = false; } // Bluetooth (CrOS only). if (cr.isChromeOS) { // Request the intial bluetooth adapter state. var adapterStateChanged = this.onBluetoothAdapterStateChanged_.bind(this); chrome.bluetooth.getAdapterState(adapterStateChanged); // Set up observers. chrome.bluetooth.onAdapterStateChanged.addListener(adapterStateChanged); var deviceAddedOrChanged = this.onBluetoothDeviceAddedOrChanged_.bind(this); chrome.bluetooth.onDeviceAdded.addListener(deviceAddedOrChanged); chrome.bluetooth.onDeviceChanged.addListener(deviceAddedOrChanged); chrome.bluetooth.onDeviceRemoved.addListener( this.onBluetoothDeviceRemoved_.bind(this)); chrome.bluetoothPrivate.onPairing.addListener( this.onBluetoothPrivatePairing_.bind(this)); // Initialize UI. options.system.bluetooth.BluetoothDeviceList.decorate( $('bluetooth-paired-devices-list')); $('bluetooth-add-device').onclick = this.handleAddBluetoothDevice_.bind(this); $('enable-bluetooth').onchange = function(event) { var state = $('enable-bluetooth').checked; chrome.bluetoothPrivate.setAdapterState({powered: state}, function() { if (chrome.runtime.lastError) { console.error('Error enabling bluetooth:', chrome.runtime.lastError.message); } }); }; $('bluetooth-reconnect-device').onclick = function(event) { chrome.send('coreOptionsUserMetricsAction', ['Options_BluetoothConnectPairedDevice']); var device = $('bluetooth-paired-devices-list').selectedItem; BluetoothPairing.connect(device); }; $('bluetooth-paired-devices-list').addEventListener('change', function() { var item = $('bluetooth-paired-devices-list').selectedItem; var disabled = !item || item.connected || !item.connectable; $('bluetooth-reconnect-device').disabled = disabled; }); } // Passwords and Forms section. $('autofill-settings').onclick = function(event) { PageManager.showPageByName('autofill'); chrome.send('coreOptionsUserMetricsAction', ['Options_ShowAutofillSettings']); }; $('manage-passwords').onclick = function(event) { PageManager.showPageByName('passwords'); OptionsPage.showTab($('passwords-nav-tab')); chrome.send('coreOptionsUserMetricsAction', ['Options_ShowPasswordManager']); }; if (cr.isChromeOS && UIAccountTweaks.loggedInAsGuest()) { // Disable and turn off Autofill in guest mode. var autofillEnabled = $('autofill-enabled'); autofillEnabled.disabled = true; autofillEnabled.checked = false; cr.dispatchSimpleEvent(autofillEnabled, 'change'); $('autofill-settings').disabled = true; // Disable and turn off Password Manager in guest mode. var passwordManagerEnabled = $('password-manager-enabled'); passwordManagerEnabled.disabled = true; passwordManagerEnabled.checked = false; cr.dispatchSimpleEvent(passwordManagerEnabled, 'change'); $('manage-passwords').disabled = true; } if (cr.isMac) { $('mac-passwords-warning').hidden = !loadTimeData.getBoolean('multiple_profiles'); } // Network section. if (!cr.isChromeOS) { $('proxiesConfigureButton').onclick = function(event) { chrome.send('showNetworkProxySettings'); }; } // Easy Unlock section. if (loadTimeData.getBoolean('easyUnlockAllowed')) { $('easy-unlock-section').hidden = false; $('easy-unlock-setup-button').onclick = function(event) { chrome.send('launchEasyUnlockSetup'); }; $('easy-unlock-turn-off-button').onclick = function(event) { PageManager.showPageByName('easyUnlockTurnOffOverlay'); }; } $('easy-unlock-enable-proximity-detection').hidden = !loadTimeData.getBoolean('easyUnlockProximityDetectionAllowed'); // Web Content section. $('fontSettingsCustomizeFontsButton').onclick = function(event) { PageManager.showPageByName('fonts'); chrome.send('coreOptionsUserMetricsAction', ['Options_ShowFontSettings']); }; $('defaultFontSize').onchange = function(event) { var value = event.target.options[event.target.selectedIndex].value; Preferences.setIntegerPref( 'webkit.webprefs.default_fixed_font_size', value - OptionsPage.SIZE_DIFFERENCE_FIXED_STANDARD, true); chrome.send('defaultFontSizeAction', [String(value)]); }; $('defaultZoomFactor').onchange = function(event) { chrome.send('defaultZoomFactorAction', [String(event.target.options[event.target.selectedIndex].value)]); }; $('safeBrowsingExtendedReportingCheckbox').onchange = function(event) { chrome.send('safeBrowsingExtendedReportingAction', [event.target.checked]); }; // Languages section. var showLanguageOptions = function(event) { PageManager.showPageByName('languages'); chrome.send('coreOptionsUserMetricsAction', ['Options_LanuageAndSpellCheckSettings']); }; $('language-button').onclick = showLanguageOptions; $('manage-languages').onclick = showLanguageOptions; // Downloads section. Preferences.getInstance().addEventListener('download.default_directory', this.onDefaultDownloadDirectoryChanged_.bind(this)); $('downloadLocationChangeButton').onclick = function(event) { chrome.send('selectDownloadLocation'); }; if (cr.isChromeOS) { $('disable-drive-row').hidden = UIAccountTweaks.loggedInAsSupervisedUser(); } $('autoOpenFileTypesResetToDefault').onclick = function(event) { chrome.send('autoOpenFileTypesAction'); }; // HTTPS/SSL section. if (cr.isWindows || cr.isMac) { $('certificatesManageButton').onclick = function(event) { chrome.send('showManageSSLCertificates'); }; } else { $('certificatesManageButton').onclick = function(event) { PageManager.showPageByName('certificates'); chrome.send('coreOptionsUserMetricsAction', ['Options_ManageSSLCertificates']); }; } // CUPS Print section (CrOS only). if (cr.isChromeOS) { if (loadTimeData.getBoolean('cupsPrintEnabled')) { $('cups-printers-section').hidden = false; $('cupsPrintersManageButton').onclick = function() { chrome.send('showCupsPrintDevicesPage'); }; } } if (loadTimeData.getBoolean('cloudPrintShowMDnsOptions')) { $('cloudprint-options-mdns').hidden = false; $('cloudPrintDevicesPageButton').onclick = function() { chrome.send('showCloudPrintDevicesPage'); }; } // Accessibility section (CrOS only). if (cr.isChromeOS) { var updateAccessibilitySettingsSection = function() { $('accessibility-settings').hidden = !($('accessibility-spoken-feedback-check').checked); }; Preferences.getInstance().addEventListener( 'settings.accessibility', updateAccessibilitySettingsSection); $('accessibility-learn-more').onclick = function(unused_event) { chrome.send('coreOptionsUserMetricsAction', ['Options_AccessibilityLearnMore']); }; $('accessibility-settings-button').onclick = function(unused_event) { window.open(loadTimeData.getString('accessibilitySettingsURL')); }; $('talkback-settings-button').onclick = function(unused_event) { chrome.send('showAccessibilityTalkBackSettings'); }; $('accessibility-spoken-feedback-check').onchange = updateAccessibilitySettingsSection; updateAccessibilitySettingsSection(); var updateScreenMagnifierCenterFocus = function() { $('accessibility-screen-magnifier-center-focus-check').disabled = !$('accessibility-screen-magnifier-check').checked; }; Preferences.getInstance().addEventListener( $('accessibility-screen-magnifier-check').getAttribute('pref'), updateScreenMagnifierCenterFocus); var updateDelayDropdown = function() { $('accessibility-autoclick-dropdown').disabled = !$('accessibility-autoclick-check').checked; }; Preferences.getInstance().addEventListener( $('accessibility-autoclick-check').getAttribute('pref'), updateDelayDropdown); $('experimental-accessibility-features').hidden = !loadTimeData.getBoolean('enableExperimentalAccessibilityFeatures'); } // Display management section (CrOS only). if (cr.isChromeOS) { $('display-options').onclick = function(event) { PageManager.showPageByName('display'); chrome.send('coreOptionsUserMetricsAction', ['Options_Display']); }; } // Factory reset section (CrOS only). if (cr.isChromeOS) { $('factory-reset-restart').onclick = function(event) { PageManager.showPageByName('factoryResetData'); chrome.send('onPowerwashDialogShow'); }; } // System section. if (!cr.isChromeOS) { var updateGpuRestartButton = function() { $('gpu-mode-reset-restart').hidden = loadTimeData.getBoolean('gpuEnabledAtStart') == $('gpu-mode-checkbox').checked; }; Preferences.getInstance().addEventListener( $('gpu-mode-checkbox').getAttribute('pref'), updateGpuRestartButton); $('gpu-mode-reset-restart-button').onclick = function(event) { chrome.send('restartBrowser'); }; updateGpuRestartButton(); } // Reset profile settings section. $('reset-profile-settings').onclick = function(event) { // We use the hash to indicate the source of the reset request. The hash // is removed by the reset profile settings overlay once it has been // consumed. PageManager.showPageByName('resetProfileSettings', true, {hash: '#userclick'}); }; // Extension controlled UI. this.addExtensionControlledBox_('search-section-content', 'search-engine-controlled', true); this.addExtensionControlledBox_('extension-controlled-container', 'homepage-controlled', true); this.addExtensionControlledBox_('startup-section-content', 'startpage-controlled', false); this.addExtensionControlledBox_('newtab-section-content', 'newtab-controlled', false); this.addExtensionControlledBox_('proxy-section-content', 'proxy-controlled', true); document.body.addEventListener('click', function(e) { var target = assertInstanceof(e.target, Node); var button = findAncestor(target, function(el) { return el.tagName == 'BUTTON' && el.dataset.extensionId !== undefined && el.dataset.extensionId.length; }); if (button) chrome.send('disableExtension', [button.dataset.extensionId]); }); // Setup ARC section. if (cr.isChromeOS) { $('android-apps-settings-label').innerHTML = loadTimeData.getString('androidAppsSettingsLabel'); Preferences.getInstance().addEventListener('arc.enabled', function(e) { // Only change settings visibility on committed settings changes. if (e.value.uncommitted) return; var isArcEnabled = !e.value.value; var androidAppSettings = $('android-apps-settings'); if (androidAppSettings != null) androidAppSettings.hidden = isArcEnabled; var talkbackSettingsButton = $('talkback-settings-button'); if (talkbackSettingsButton != null) talkbackSettingsButton.hidden = isArcEnabled; }); $('android-apps-settings-link').addEventListener('click', function(e) { // MouseEvent.detail indicates the current click count (or tap // count, in the case of touch events) in the 'click' event. var activatedFromKeyboard = e.detail == 0; chrome.send('showAndroidAppsSettings', [activatedFromKeyboard]); }); } }, /** @override */ didShowPage: function() { $('search-field').focus(); }, /** * Called after all C++ UI handlers have called InitializePage to notify * that initialization is complete. * @private */ notifyInitializationComplete_: function() { this.initializationComplete_ = true; cr.dispatchSimpleEvent(document, 'initializationComplete'); }, /** * Event listener for the 'session.restore_on_startup' pref. * @param {Event} event The preference change event. * @private */ onRestoreOnStartupChanged_: function(event) { /** @const */ var showHomePageValue = 0; if (event.value.value == showHomePageValue) { // If the user previously selected "Show the homepage", the // preference will already be migrated to "Open a specific page". So // the only way to reach this code is if the 'restore on startup' // preference is managed. assert(event.value.controlledBy); // Select "open the following pages" and lock down the list of URLs // to reflect the intention of the policy. $('startup-show-pages').checked = true; StartupOverlay.getInstance().setControlsDisabled(true); } else { // Re-enable the controls in the startup overlay if necessary. StartupOverlay.getInstance().updateControlStates(); } }, /** * Handler for messages sent from the main uber page. * @param {Event} e The 'message' event from the uber page. * @private */ handleWindowMessage_: function(e) { if ((/** @type {{method: string}} */(e.data)).method == 'frameSelected') $('search-field').focus(); }, /** * Animatedly changes height |from| a px number |to| a px number. * @param {HTMLElement} section The section to animate. * @param {HTMLElement} container The container of |section|. * @param {boolean} showing Whether to go from 0 -> container height or * container height -> 0. * @private */ animatedSectionHeightChange_: function(section, container, showing) { // If the section is already animating, dispatch a synthetic transition // end event as the upcoming code will cancel the current one. if (section.classList.contains('sliding')) cr.dispatchSimpleEvent(section, 'webkitTransitionEnd'); this.addTransitionEndListener_(section); section.hidden = false; section.style.height = (showing ? 0 : container.offsetHeight) + 'px'; section.classList.add('sliding'); // Force a style recalc before starting the animation. /** @suppress {suspiciousCode} */ section.offsetHeight; section.style.height = (showing ? container.offsetHeight : 0) + 'px'; }, /** * Shows the given section. * @param {HTMLElement} section The section to be shown. * @param {HTMLElement} container The container for the section. Must be * inside of |section|. * @param {boolean} animate Indicate if the expansion should be animated. * @private */ showSection_: function(section, container, animate) { if (section == $('advanced-settings') && !loadTimeData.getBoolean('allowAdvancedSettings')) { return; } // Delay starting the transition if animating so that hidden change will // be processed. if (animate) { this.animatedSectionHeightChange_(section, container, true); } else { section.hidden = false; section.style.height = 'auto'; } }, /** * Shows the given section, with animation. * @param {HTMLElement} section The section to be shown. * @param {HTMLElement} container The container for the section. Must be * inside of |section|. * @private */ showSectionWithAnimation_: function(section, container) { this.showSection_(section, container, /* animate */ true); }, /** * Hides the given |section| with animation. * @param {HTMLElement} section The section to be hidden. * @param {HTMLElement} container The container for the section. Must be * inside of |section|. * @private */ hideSectionWithAnimation_: function(section, container) { this.animatedSectionHeightChange_(section, container, false); }, /** * Toggles the visibility of |section| in an animated way. * @param {HTMLElement} section The section to be toggled. * @param {HTMLElement} container The container for the section. Must be * inside of |section|. * @private */ toggleSectionWithAnimation_: function(section, container) { if (BrowserOptions.shouldShowSection_(section)) this.showSectionWithAnimation_(section, container); else this.hideSectionWithAnimation_(section, container); }, /** * Scrolls the settings page to make the section visible auto-expanding * advanced settings if required. The transition is not animated. This * method is used to ensure that a section associated with an overlay * is visible when the overlay is closed. * @param {!Element} section The section to make visible. * @private */ scrollToSection_: function(section) { var advancedSettings = $('advanced-settings'); var container = $('advanced-settings-container'); var expander = $('advanced-settings-expander'); if (!expander.hidden && advancedSettings.hidden && section.parentNode == container) { this.showSection_($('advanced-settings'), $('advanced-settings-container'), /* animate */ false); this.updateAdvancedSettingsExpander_(); } if (!this.initializationComplete_) { var self = this; var callback = function() { document.removeEventListener('initializationComplete', callback); self.scrollToSection_(section); }; document.addEventListener('initializationComplete', callback); return; } var pageContainer = $('page-container'); // pageContainer.offsetTop is relative to the screen. var pageTop = pageContainer.offsetTop; var sectionBottom = section.offsetTop + section.offsetHeight; // section.offsetTop is relative to the 'page-container'. var sectionTop = section.offsetTop; if (pageTop + sectionBottom > document.body.scrollHeight || pageTop + sectionTop < 0) { // Currently not all layout updates are guaranteed to precede the // initializationComplete event (for example 'set-as-default-browser' // button) leaving some uncertainty in the optimal scroll position. // The section is placed approximately in the middle of the screen. var top = Math.min(0, document.body.scrollHeight / 2 - sectionBottom); pageContainer.style.top = top + 'px'; pageContainer.oldScrollTop = -top; } }, /** * Adds a |webkitTransitionEnd| listener to the given section so that * it can be animated. The listener will only be added to a given section * once, so this can be called as multiple times. * @param {HTMLElement} section The section to be animated. * @private */ addTransitionEndListener_: function(section) { if (section.hasTransitionEndListener_) return; section.addEventListener('webkitTransitionEnd', this.onTransitionEnd_.bind(this)); section.hasTransitionEndListener_ = true; }, /** * Called after an animation transition has ended. * @param {Event} event The webkitTransitionEnd event. NOTE: May be * synthetic. * @private */ onTransitionEnd_: function(event) { if (event.propertyName && event.propertyName != 'height') { // If not a synthetic event or a real transition we care about, bail. return; } var section = event.target; section.classList.remove('sliding'); if (!event.propertyName) { // Only real transitions past this point. return; } if (section.style.height == '0px') { // Hide the content so it can't get tab focus. section.hidden = true; section.style.height = ''; } else { // Set the section height to 'auto' to allow for size changes // (due to font change or dynamic content). section.style.height = 'auto'; } }, /** @private */ updateAdvancedSettingsExpander_: function() { var expander = $('advanced-settings-expander'); if (BrowserOptions.shouldShowSection_($('advanced-settings'))) expander.textContent = loadTimeData.getString('showAdvancedSettings'); else expander.textContent = loadTimeData.getString('hideAdvancedSettings'); }, /** * Updates the sync section with the given state. * @param {options.SyncStatus} syncData A bunch of data records that * describe the status of the sync system. * @private */ updateSyncState_: function(syncData) { if (!syncData.signinAllowed && (!syncData.supervisedUser || !cr.isChromeOS)) { $('sync-section').hidden = true; this.maybeShowUserSection_(); return; } $('sync-section').hidden = false; this.maybeShowUserSection_(); if (cr.isChromeOS && syncData.supervisedUser && !syncData.childUser) { var subSection = $('sync-section').firstChild; while (subSection) { if (subSection.nodeType == Node.ELEMENT_NODE) subSection.hidden = true; subSection = subSection.nextSibling; } $('account-picture-wrapper').hidden = false; $('sync-general').hidden = false; $('sync-status').hidden = true; return; } // If the user gets signed out while the advanced sync settings dialog is // visible, say, due to a dashboard clear, close the dialog. // However, if the user gets signed out as a result of abandoning first // time sync setup, do not call closeOverlay as it will redirect the // browser to the main settings page and override any in-progress // user-initiated navigation. See crbug.com/278030. // Note: SyncSetupOverlay.closeOverlay is a no-op if the overlay is // already hidden. if (this.signedIn_ && !syncData.signedIn && !syncData.setupInProgress) SyncSetupOverlay.closeOverlay(); this.signedIn_ = !!syncData.signedIn; // Display the "advanced settings" button if we're signed in and sync is // not managed/disabled. If the user is signed in, but sync is disabled, // this button is used to re-enable sync. var customizeSyncButton = $('customize-sync'); customizeSyncButton.hidden = !this.signedIn_ || syncData.managed || !syncData.syncSystemEnabled; // Only modify the customize button's text if the new text is different. // Otherwise, it can affect search-highlighting in the settings page. // See http://crbug.com/268265. var customizeSyncButtonNewText = syncData.setupCompleted ? loadTimeData.getString('customizeSync') : loadTimeData.getString('syncButtonTextStart'); if (customizeSyncButton.textContent != customizeSyncButtonNewText) customizeSyncButton.textContent = customizeSyncButtonNewText; // Disable the "sign in" button if we're currently signing in, or if we're // already signed in and signout is not allowed. var signInButton = $('start-stop-sync'); signInButton.disabled = syncData.setupInProgress; this.signoutAllowed_ = !!syncData.signoutAllowed; if (!syncData.signoutAllowed) $('start-stop-sync-indicator').setAttribute('controlled-by', 'policy'); else $('start-stop-sync-indicator').removeAttribute('controlled-by'); // Hide the "sign in" button on Chrome OS, and show it on desktop Chrome // (except for supervised users, which can't change their signed-in // status). signInButton.hidden = cr.isChromeOS || syncData.supervisedUser; signInButton.textContent = this.signedIn_ ? loadTimeData.getString('syncButtonTextStop') : syncData.setupInProgress ? loadTimeData.getString('syncButtonTextInProgress') : loadTimeData.getString('syncButtonTextSignIn'); $('start-stop-sync-indicator').hidden = signInButton.hidden; $('account-info').textContent = syncData.accountInfo; $('account-info').hidden = !this.signedIn_; // TODO(estade): can this just be textContent? $('sync-status-text').innerHTML = syncData.statusText; var statusSet = syncData.statusText.length != 0; $('sync-overview').hidden = statusSet || (cr.isChromeOS && UIAccountTweaks.loggedInAsPublicAccount()); $('sync-status').hidden = !statusSet; $('sync-action-link').textContent = syncData.actionLinkText; // Don't show the action link if it is empty or undefined. $('sync-action-link').hidden = syncData.actionLinkText.length == 0; $('sync-action-link').disabled = syncData.managed || !syncData.syncSystemEnabled; $('sync-action-link').onclick = function(event) { switch (syncData.statusAction) { case 'reauthenticate': SyncSetupOverlay.startSignIn(false /* creatingSupervisedUser */); break; case 'signOutAndSignIn': // <if expr="chromeos"> // On Chrome OS, sign out the user and sign in again to get fresh // credentials on auth errors. SyncSetupOverlay.doSignOutOnAuthError(); // </if> // <if expr="not chromeos"> if (syncData.signoutAllowed) { // Silently sign the user out without deleting their profile and // prompt them to sign back in. chrome.send('SyncSetupStopSyncing', [false /* deleteProfile */]); SyncSetupOverlay.startSignIn(false /* creatingSupervisedUser */); } else { chrome.send('showDisconnectManagedProfileDialog'); } // </if> break; case 'upgradeClient': PageManager.showPageByName('help'); break; default: SyncSetupOverlay.showSetupUI(); } }; if (syncData.hasError) $('sync-status').classList.add('sync-error'); else $('sync-status').classList.remove('sync-error'); // Disable the "customize / set up sync" button if sync has an // unrecoverable error. Also disable the button if sync has not been set // up and the user is being presented with a link to re-auth. // See crbug.com/289791. customizeSyncButton.disabled = syncData.hasUnrecoverableError || (!syncData.setupCompleted && !$('sync-action-link').hidden); }, /** * Update the UI depending on whether Easy Unlock is enabled for the current * profile. * @param {boolean} isEnabled True if the feature is enabled for the current * profile. */ updateEasyUnlock_: function(isEnabled) { $('easy-unlock-disabled').hidden = isEnabled; $('easy-unlock-enabled').hidden = !isEnabled; if (!isEnabled && EasyUnlockTurnOffOverlay.getInstance().visible) { EasyUnlockTurnOffOverlay.dismiss(); } }, /** * Update the UI depending on whether the current profile manages any * supervised users. * @param {boolean} show True if the current profile manages any supervised * users. */ updateManagesSupervisedUsers_: function(show) { $('profiles-supervised-dashboard-tip').hidden = !show; this.maybeShowUserSection_(); }, /** * Get the start/stop sync button DOM element. Used for testing. * @return {Element} The start/stop sync button. * @private */ getStartStopSyncButton_: function() { return $('start-stop-sync'); }, /** * Event listener for the 'show home button' preference. Shows/hides the * UI for changing the home page with animation, unless this is the first * time this function is called, in which case there is no animation. * @param {Event} event The preference change event. */ onShowHomeButtonChanged_: function(event) { var section = $('change-home-page-section'); if (this.onShowHomeButtonChangedCalled_) { var container = $('change-home-page-section-container'); if (event.value.value) this.showSectionWithAnimation_(section, container); else this.hideSectionWithAnimation_(section, container); } else { section.hidden = !event.value.value; this.onShowHomeButtonChangedCalled_ = true; } }, /** * Activates the Hotword section from the System settings page. * @param {string} sectionId The id of the section to display. * @param {string} indicatorId The id of the indicator to display. * @param {string=} opt_error The error message to display. * @private */ showHotwordCheckboxAndIndicator_: function(sectionId, indicatorId, opt_error) { $(sectionId).hidden = false; $(indicatorId).setError(opt_error); if (opt_error) $(indicatorId).updateBasedOnError(); }, /** * Activates the Hotword section from the System settings page. * @param {string=} opt_error The error message to display. * @private */ showHotwordSection_: function(opt_error) { this.showHotwordCheckboxAndIndicator_( 'hotword-search', 'hotword-search-setting-indicator', opt_error); }, /** * Activates the Always-On Hotword sections from the * System settings page. * @param {string=} opt_error The error message to display. * @private */ showHotwordAlwaysOnSection_: function(opt_error) { this.showHotwordCheckboxAndIndicator_( 'hotword-always-on-search', 'hotword-always-on-search-setting-indicator', opt_error); }, /** * Activates the Hotword section on devices with no DSP * from the System settings page. * @param {string=} opt_error The error message to display. * @private */ showHotwordNoDspSection_: function(opt_error) { this.showHotwordCheckboxAndIndicator_( 'hotword-no-dsp-search', 'hotword-no-dsp-search-setting-indicator', opt_error); }, /** * Controls the visibility of all the hotword sections. * @param {boolean} visible Whether to show hotword sections. * @private */ setAllHotwordSectionsVisible_: function(visible) { $('hotword-search').hidden = !visible; $('hotword-always-on-search').hidden = !visible; $('hotword-no-dsp-search').hidden = !visible; $('audio-history').hidden = !visible; }, /** * Shows or hides the hotword retrain link * @param {boolean} visible Whether to show the link. * @private */ setHotwordRetrainLinkVisible_: function(visible) { $('hotword-retrain-link').hidden = !visible; }, /** * Event listener for the 'hotword always on search enabled' preference. * Updates the visibility of the 'retrain' link. * @param {Event} event The preference change event. * @private */ onHotwordAlwaysOnChanged_: function(event) { this.setHotwordRetrainLinkVisible_(event.value.value); }, /** * Controls the visibility of the Now settings. * @param {boolean} visible Whether to show Now settings. * @private */ setNowSectionVisible_: function(visible) { $('google-now-launcher').hidden = !visible; }, /** * Activates the Audio History section of the Settings page. * @param {boolean} visible Whether the audio history section is visible. * @param {string} labelText Text describing current audio history state. * @private */ setAudioHistorySectionVisible_: function(visible, labelText) { $('audio-history').hidden = !visible; $('audio-history-label').textContent = labelText; }, /** * Event listener for the 'homepage is NTP' preference. Updates the label * next to the 'Change' button. * @param {Event} event The preference change event. */ onHomePageIsNtpChanged_: function(event) { if (!event.value.uncommitted) { $('home-page-url').hidden = event.value.value; $('home-page-ntp').hidden = !event.value.value; } }, /** * Event listener for changes to the homepage preference. Updates the label * next to the 'Change' button. * @param {Event} event The preference change event. */ onHomePageChanged_: function(event) { if (!event.value.uncommitted) $('home-page-url').textContent = this.stripHttp_(event.value.value); }, /** * Removes the 'http://' from a URL, like the omnibox does. If the string * doesn't start with 'http://' it is returned unchanged. * @param {string} url The url to be processed * @return {string} The url with the 'http://' removed. */ stripHttp_: function(url) { return url.replace(/^http:\/\//, ''); }, /** * Called when the value of the download.default_directory preference * changes. * @param {Event} event Change event. * @private */ onDefaultDownloadDirectoryChanged_: function(event) { $('downloadLocationPath').value = event.value.value; if (cr.isChromeOS) { // On ChromeOS, replace /special/drive-<hash>/root with "Google Drive" // for remote files, /home/chronos/user/Downloads or // /home/chronos/u-<hash>/Downloads with "Downloads" for local paths, // and '/' with ' \u203a ' (angled quote sign) everywhere. The modified // path is used only for display purpose. var path = $('downloadLocationPath').value; path = path.replace(/^\/special\/drive[^\/]*\/root/, 'Google Drive'); path = path.replace(/^\/home\/chronos\/(user|u-[^\/]*)\//, ''); path = path.replace(/\//g, ' \u203a '); $('downloadLocationPath').value = path; } $('download-location-label').classList.toggle('disabled', event.value.disabled); $('downloadLocationChangeButton').disabled = event.value.disabled; }, /** * Update the Default Browsers section based on the current state. * @param {string} statusString Description of the current default state. * @param {boolean} isDefault Whether or not the browser is currently * default. * @param {boolean} canBeDefault Whether or not the browser can be default. * @private */ updateDefaultBrowserState_: function(statusString, isDefault, canBeDefault) { if (!cr.isChromeOS) { var label = $('default-browser-state'); label.textContent = statusString; $('set-as-default-browser').hidden = !canBeDefault || isDefault; } }, /** * Clears the search engine popup. * @private */ clearSearchEngines_: function() { $('default-search-engine').textContent = ''; }, /** * Updates the search engine popup with the given entries. * @param {Array} engines List of available search engines. * @param {number} defaultValue The value of the current default engine. * @param {boolean} defaultManaged Whether the default search provider is * managed. If true, the default search provider can't be changed. * @private */ updateSearchEngines_: function(engines, defaultValue, defaultManaged) { this.clearSearchEngines_(); var engineSelect = $('default-search-engine'); engineSelect.disabled = defaultManaged; if (defaultManaged && defaultValue == -1) return; var engineCount = engines.length; var defaultIndex = -1; for (var i = 0; i < engineCount; i++) { var engine = engines[i]; var option = new Option(engine.name, engine.index); if (defaultValue == option.value) defaultIndex = i; engineSelect.appendChild(option); } if (defaultIndex >= 0) engineSelect.selectedIndex = defaultIndex; }, /** * Set the default search engine based on the popup selection. * @private */ setDefaultSearchEngine_: function() { var engineSelect = $('default-search-engine'); var selectedIndex = engineSelect.selectedIndex; if (selectedIndex >= 0) { var selection = engineSelect.options[selectedIndex]; chrome.send('setDefaultSearchEngine', [String(selection.value)]); } }, /** * Get the selected profile item from the profile list. This also works * correctly if the list is not displayed. * @return {?Object} The profile item object, or null if nothing is * selected. * @private */ getSelectedProfileItem_: function() { var profilesList = $('profiles-list'); if (profilesList.hidden) { if (profilesList.dataModel.length > 0) return profilesList.dataModel.item(0); } else { return profilesList.selectedItem; } return null; }, /** * Helper function to set the status of profile view buttons to disabled or * enabled, depending on the number of profiles and selection status of the * profiles list. * @private */ setProfileViewButtonsStatus_: function() { var profilesList = $('profiles-list'); var selectedProfile = profilesList.selectedItem; var hasSelection = selectedProfile != null; var hasSingleProfile = profilesList.dataModel.length == 1; $('profiles-manage').disabled = !hasSelection || !selectedProfile.isCurrentProfile; if (hasSelection && !selectedProfile.isCurrentProfile) $('profiles-manage').title = loadTimeData.getString('currentUserOnly'); else $('profiles-manage').title = ''; $('profiles-delete').disabled = !profilesList.canDeleteItems || !hasSelection; var importData = $('import-data'); if (importData) { importData.disabled = $('import-data').disabled = hasSelection && !selectedProfile.isCurrentProfile; } }, /** * Display the correct dialog layout, depending on how many profiles are * available. * @param {number} numProfiles The number of profiles to display. * @private */ setProfileViewSingle_: function(numProfiles) { // Always show the profiles list when using the new Profiles UI. var usingNewProfilesUI = loadTimeData.getBoolean('usingNewProfilesUI'); var showSingleProfileView = !usingNewProfilesUI && numProfiles == 1; $('profiles-list').hidden = showSingleProfileView; $('profiles-single-message').hidden = !showSingleProfileView; $('profiles-manage').hidden = showSingleProfileView; $('profiles-delete').textContent = showSingleProfileView ? loadTimeData.getString('profilesDeleteSingle') : loadTimeData.getString('profilesDelete'); }, /** * Adds all |profiles| to the list. * @param {!Array<!options.Profile>} profiles An array of profile info * objects. * @private */ setProfilesInfo_: function(profiles) { this.setProfileViewSingle_(profiles.length); // add it to the list, even if the list is hidden so we can access it // later. $('profiles-list').dataModel = new ArrayDataModel(profiles); // Received new data. If showing the "manage" overlay, keep it up to // date. If showing the "delete" overlay, close it. if (ManageProfileOverlay.getInstance().visible && !$('manage-profile-overlay-manage').hidden) { ManageProfileOverlay.showManageDialog(false); } else { ManageProfileOverlay.getInstance().visible = false; } this.setProfileViewButtonsStatus_(); }, /** * Reports supervised user import errors to the SupervisedUserImportOverlay. * @param {string} error The error message to display. * @private */ showSupervisedUserImportError_: function(error) { SupervisedUserImportOverlay.onError(error); }, /** * Reports successful importing of a supervised user to * the SupervisedUserImportOverlay. * @private */ showSupervisedUserImportSuccess_: function() { SupervisedUserImportOverlay.onSuccess(); }, /** * Reports an error to the "create" overlay during profile creation. * @param {string} error The error message to display. * @private */ showCreateProfileError_: function(error) { CreateProfileOverlay.onError(error); }, /** * Sends a warning message to the "create" overlay during profile creation. * @param {string} warning The warning message to display. * @private */ showCreateProfileWarning_: function(warning) { CreateProfileOverlay.onWarning(warning); }, /** * Reports successful profile creation to the "create" overlay. * @param {options.Profile} profileInfo An object of the form: * profileInfo = { * name: "Profile Name", * filePath: "/path/to/profile/data/on/disk" * isSupervised: (true|false), * }; * @private */ showCreateProfileSuccess_: function(profileInfo) { CreateProfileOverlay.onSuccess(profileInfo); }, /** * Returns the currently active profile for this browser window. * @return {options.Profile} A profile info object. * @private */ getCurrentProfile_: function() { for (var i = 0; i < $('profiles-list').dataModel.length; i++) { var profile = $('profiles-list').dataModel.item(i); if (profile.isCurrentProfile) return profile; } assertNotReached('There should always be a current profile.'); }, /** * Propmpts user to confirm deletion of the profile for this browser * window. * @private */ deleteCurrentProfile_: function() { ManageProfileOverlay.showDeleteDialog(this.getCurrentProfile_()); }, /** * @param {boolean} enabled */ setNativeThemeButtonEnabled_: function(enabled) { var button = $('themes-native-button'); if (button) button.disabled = !enabled; }, /** * @param {boolean} enabled */ setThemesResetButtonEnabled_: function(enabled) { $('themes-reset').disabled = !enabled; }, /** * @param {boolean} managed */ setAccountPictureManaged_: function(managed) { var picture = $('account-picture'); if (managed || UIAccountTweaks.loggedInAsGuest()) { picture.disabled = true; ChangePictureOptions.closeOverlay(); } else { picture.disabled = false; } // Create a synthetic pref change event decorated as // CoreOptionsHandler::CreateValueForPref() does. var event = new Event('account-picture'); if (managed) event.value = { controlledBy: 'policy' }; else event.value = {}; $('account-picture-indicator').handlePrefChange(event); }, /** * (Re)loads IMG element with current user account picture. * @private */ updateAccountPicture_: function() { var picture = $('account-picture'); if (picture) { picture.src = 'chrome://userimage/' + this.username_ + '?id=' + Date.now(); } }, /** * @param {boolean} managed */ setWallpaperManaged_: function(managed) { if (managed) $('set-wallpaper').disabled = true; else this.enableElementIfPossible_(getRequiredElement('set-wallpaper')); // Create a synthetic pref change event decorated as // CoreOptionsHandler::CreateValueForPref() does. var event = new Event('wallpaper'); event.value = managed ? { controlledBy: 'policy' } : {}; $('wallpaper-indicator').handlePrefChange(event); }, /** * This enables or disables dependent settings in timezone section. * @private */ updateTimezoneSectionState_: function() { var self = this; $('resolve-timezone-by-geolocation') .onclick = function(event) { self.resolveTimezoneByGeolocation_ = event.currentTarget.checked; }; if (this.systemTimezoneIsManaged_) { $('resolve-timezone-by-geolocation').disabled = true; $('resolve-timezone-by-geolocation').checked = false; } else if (this.systemTimezoneAutomaticDetectionIsManaged_) { if (this.systemTimezoneAutomaticDetectionValue_ == options.AutomaticTimezoneDetectionType.USERS_DECIDE) { $('resolve-timezone-by-geolocation').disabled = false; $('resolve-timezone-by-geolocation') .checked = this.resolveTimezoneByGeolocation_; $('timezone-value-select') .disabled = this.resolveTimezoneByGeolocation_; } else { $('resolve-timezone-by-geolocation').disabled = true; $('resolve-timezone-by-geolocation') .checked = (this.systemTimezoneAutomaticDetectionValue_ != options.AutomaticTimezoneDetectionType.DISABLED); $('timezone-value-select').disabled = true; } } else { this.enableElementIfPossible_( getRequiredElement('resolve-timezone-by-geolocation')); $('timezone-value-select').disabled = this.resolveTimezoneByGeolocation_; $('resolve-timezone-by-geolocation') .checked = this.resolveTimezoneByGeolocation_; } }, /** * This is called from chromium code when system timezone "managed" state * is changed. Enables or disables dependent settings. * @param {boolean} managed Is true when system Timezone is managed by * enterprise policy. False otherwize. */ setSystemTimezoneManaged_: function(managed) { this.systemTimezoneIsManaged_ = managed; this.updateTimezoneSectionState_(); }, /** * This is called from chromium code when system timezone detection * "managed" state is changed. Enables or disables dependent settings. * @param {boolean} managed Is true when system timezone autodetection is * managed by enterprise policy. False otherwize. * @param {options.AutomaticTimezoneDetectionType} value Current value of * SystemTimezoneAutomaticDetection device policy. */ setSystemTimezoneAutomaticDetectionManaged_: function(managed, value) { this.systemTimezoneAutomaticDetectionIsManaged_ = managed; this.systemTimezoneAutomaticDetectionValue_ = value; this.updateTimezoneSectionState_(); }, /** * This is Preferences event listener, which is called when * kResolveTimezoneByGeolocation preference is changed. * Enables or disables dependent settings. * @param {Event} value New preference state. */ onResolveTimezoneByGeolocationChanged_: function(value) { this.resolveTimezoneByGeolocation_ = value.value.value; this.updateTimezoneSectionState_(); }, /** * Handle the 'add device' button click. * @private */ handleAddBluetoothDevice_: function() { chrome.send('coreOptionsUserMetricsAction', ['Options_BluetoothShowAddDevice']); PageManager.showPageByName('bluetooth', false); }, /** * Enables or disables the Manage SSL Certificates button. * @private */ enableCertificateButton_: function(enabled) { $('certificatesManageButton').disabled = !enabled; }, /** * Enables or disables the Chrome OS display settings button and overlay. * @param {boolean} uiEnabled * @param {boolean} unifiedEnabled * @param {boolean} mirroredEnabled * @private */ enableDisplaySettings_: function( uiEnabled, unifiedEnabled, mirroredEnabled) { if (cr.isChromeOS) { $('display-options').disabled = !uiEnabled; DisplayOptions.getInstance().setEnabled( uiEnabled, unifiedEnabled, mirroredEnabled); } }, /** * Enables factory reset section. * @private */ enableFactoryResetSection_: function() { $('factory-reset-section').hidden = false; }, /** * Set the checked state of the metrics reporting checkbox. * @private */ setMetricsReportingCheckboxState_: function(checked, policyManaged, ownerManaged) { $('metrics-reporting-enabled').checked = checked; $('metrics-reporting-enabled').disabled = policyManaged || ownerManaged; // If checkbox gets disabled then add an attribute for displaying the // special icon. Otherwise remove the indicator attribute. if (policyManaged) { $('metrics-reporting-disabled-icon').setAttribute('controlled-by', 'policy'); } else if (ownerManaged) { $('metrics-reporting-disabled-icon').setAttribute('controlled-by', 'owner'); } else { $('metrics-reporting-disabled-icon').removeAttribute('controlled-by'); } }, /** * @private */ setMetricsReportingSettingVisibility_: function(visible) { if (visible) $('metrics-reporting-setting').style.display = 'block'; else $('metrics-reporting-setting').style.display = 'none'; }, /** * Set the checked state of the Safe Browsing Extended Reporting Enabled * checkbox. * @private */ setExtendedReportingEnabledCheckboxState_: function(checked) { $('safeBrowsingExtendedReportingCheckbox').checked = checked; }, /** * Set network prediction checkbox value. * * @param {{value: number, disabled: boolean}} pref Information about * network prediction options. |pref.value| is the value of network * prediction options. |pref.disabled| shows if the pref is not user * modifiable. * @private */ setNetworkPredictionValue_: function(pref) { var checkbox = $('networkPredictionOptions'); checkbox.disabled = pref.disabled || loadTimeData.getBoolean('profileIsGuest'); checkbox.checked = (pref.value != NetworkPredictionOptions.NEVER); }, /** * Set the font size selected item. This item actually reflects two * preferences: the default font size and the default fixed font size. * * @param {{value: number, disabled: boolean, controlledBy: string}} pref * Information about the font size preferences. |pref.value| is the * value of the default font size pref. |pref.disabled| is true if * either pref not user modifiable. |pref.controlledBy| is the source of * the pref value(s) if either pref is currently not controlled by the * user. * @private */ setFontSize_: function(pref) { var selectCtl = /** @type {HTMLSelectElement} */($('defaultFontSize')); selectCtl.disabled = pref.disabled; // Create a synthetic pref change event decorated as // CoreOptionsHandler::CreateValueForPref() does. var event = new Event('synthetic-font-size'); event.value = { value: pref.value, controlledBy: pref.controlledBy, disabled: pref.disabled }; $('font-size-indicator').handlePrefChange(event); for (var i = 0; i < selectCtl.options.length; i++) { if (selectCtl.options[i].value == pref.value) { selectCtl.selectedIndex = i; if ($('Custom')) selectCtl.remove($('Custom').index); return; } } // Add/Select Custom Option in the font size label list. if (!$('Custom')) { var option = new Option(loadTimeData.getString('fontSizeLabelCustom'), -1, false, true); option.setAttribute('id', 'Custom'); selectCtl.add(option); } $('Custom').selected = true; }, /** * Populate the page zoom selector with values received from the caller. * @param {Array} items An array of items to populate the selector. * each object is an array with three elements as follows: * 0: The title of the item (string). * 1: The value of the item (number). * 2: Whether the item should be selected (boolean). * @private */ setupPageZoomSelector_: function(items) { var element = $('defaultZoomFactor'); // Remove any existing content. element.textContent = ''; // Insert new child nodes into select element. var value, title, selected; for (var i = 0; i < items.length; i++) { title = items[i][0]; value = items[i][1]; selected = items[i][2]; element.appendChild(new Option(title, value, false, selected)); } }, /** * Shows/hides the autoOpenFileTypesResetToDefault button and label, with * animation. * @param {boolean} display Whether to show the button and label or not. * @private */ setAutoOpenFileTypesDisplayed_: function(display) { if ($('advanced-settings').hidden) { // If the Advanced section is hidden, don't animate the transition. $('auto-open-file-types-section').hidden = !display; } else { if (display) { this.showSectionWithAnimation_( $('auto-open-file-types-section'), $('auto-open-file-types-container')); } else { this.hideSectionWithAnimation_( $('auto-open-file-types-section'), $('auto-open-file-types-container')); } } }, /** * Set the enabled state for the proxy settings button and its associated * message when extension controlled. * @param {boolean} disabled Whether the button should be disabled. * @param {boolean} extensionControlled Whether the proxy is extension * controlled. * @private */ setupProxySettingsButton_: function(disabled, extensionControlled) { if (!cr.isChromeOS) { $('proxiesConfigureButton').disabled = disabled; $('proxiesLabel').textContent = loadTimeData.getString(extensionControlled ? 'proxiesLabelExtension' : 'proxiesLabelSystem'); } }, /** * Set the initial state of the spoken feedback checkbox. * @private */ setSpokenFeedbackCheckboxState_: function(checked) { $('accessibility-spoken-feedback-check').checked = checked; }, /** * Set the initial state of the high contrast checkbox. * @private */ setHighContrastCheckboxState_: function(checked) { $('accessibility-high-contrast-check').checked = checked; }, /** * Set the initial state of the virtual keyboard checkbox. * @private */ setVirtualKeyboardCheckboxState_: function(checked) { // TODO(zork): Update UI }, /** * Show/hide mouse settings slider. * @private */ showMouseControls_: function(show) { $('mouse-settings').hidden = !show; }, /** * Adds hidden warning boxes for settings potentially controlled by * extensions. * @param {string} parentDiv The div name to append the bubble to. * @param {string} bubbleId The ID to use for the bubble. * @param {boolean} first Add as first node if true, otherwise last. * @private */ addExtensionControlledBox_: function(parentDiv, bubbleId, first) { var bubble = $('extension-controlled-warning-template').cloneNode(true); bubble.id = bubbleId; var parent = $(parentDiv); if (first) parent.insertBefore(bubble, parent.firstChild); else parent.appendChild(bubble); }, /** * Adds a bubble showing that an extension is controlling a particular * setting. * @param {string} parentDiv The div name to append the bubble to. * @param {string} bubbleId The ID to use for the bubble. * @param {string} extensionId The ID of the controlling extension. * @param {string} extensionName The name of the controlling extension. * @private */ toggleExtensionControlledBox_: function( parentDiv, bubbleId, extensionId, extensionName) { var bubble = $(bubbleId); assert(bubble); bubble.hidden = extensionId.length == 0; if (bubble.hidden) return; // Set the extension image. var div = bubble.firstElementChild; div.style.backgroundImage = 'url(chrome://extension-icon/' + extensionId + '/24/1)'; // Set the bubble label. var label = loadTimeData.getStringF('extensionControlled', extensionName); var docFrag = parseHtmlSubset('<div>' + label + '</div>', ['B', 'DIV']); div.innerHTML = docFrag.firstChild.innerHTML; // Wire up the button to disable the right extension. var button = div.nextElementSibling; button.dataset.extensionId = extensionId; }, /** * Toggles the warning boxes that show which extension is controlling * various settings of Chrome. * @param {{searchEngine: options.ExtensionData, * homePage: options.ExtensionData, * startUpPage: options.ExtensionData, * newTabPage: options.ExtensionData, * proxy: options.ExtensionData}} details A dictionary of ID+name * pairs for each of the settings controlled by an extension. * @private */ toggleExtensionIndicators_: function(details) { this.toggleExtensionControlledBox_('search-section-content', 'search-engine-controlled', details.searchEngine.id, details.searchEngine.name); this.toggleExtensionControlledBox_('extension-controlled-container', 'homepage-controlled', details.homePage.id, details.homePage.name); this.toggleExtensionControlledBox_('startup-section-content', 'startpage-controlled', details.startUpPage.id, details.startUpPage.name); this.toggleExtensionControlledBox_('newtab-section-content', 'newtab-controlled', details.newTabPage.id, details.newTabPage.name); this.toggleExtensionControlledBox_('proxy-section-content', 'proxy-controlled', details.proxy.id, details.proxy.name); // The proxy section contains just the warning box and nothing else, so // if we're hiding the proxy warning box, we should also hide its header // section. $('proxy-section').hidden = details.proxy.id.length == 0; }, /** * Show/hide touchpad-related settings. * @private */ showTouchpadControls_: function(show) { $('touchpad-settings').hidden = !show; $('accessibility-tap-dragging').hidden = !show; }, /** * Sets the state of the checkbox indicating if Bluetooth is turned on. The * state of the "Find devices" button and the list of discovered devices may * also be affected by a change to the state. * @param {boolean} checked Flag Indicating if Bluetooth is turned on. * @private */ setBluetoothState_: function(checked) { $('enable-bluetooth').checked = checked; $('bluetooth-paired-devices-list').parentNode.hidden = !checked; $('bluetooth-add-device').hidden = !checked; $('bluetooth-reconnect-device').hidden = !checked; }, /** * Process a bluetooth.onAdapterStateChanged event. * @param {!chrome.bluetooth.AdapterState} state * @private */ onBluetoothAdapterStateChanged_: function(state) { var disallowBluetooth = !loadTimeData.getBoolean('allowBluetooth'); // If allowBluetooth is false, state.available will always be false, so // assume Bluetooth is available but disabled by policy. if (!state || (!state.available && !disallowBluetooth)) { this.bluetoothAdapterState_ = null; $('bluetooth-devices').hidden = true; return; } $('bluetooth-devices').hidden = false; this.bluetoothAdapterState_ = state; this.setBluetoothState_(state.powered); var enableBluetoothEl = $('enable-bluetooth'); if (disallowBluetooth) { enableBluetoothEl.setAttribute('pref', 'cros.device.allow_bluetooth'); enableBluetoothEl.setAttribute('controlled-by', 'policy'); enableBluetoothEl.disabled = true; $('bluetooth-controlled-setting-indicator').hidden = false; return; } enableBluetoothEl.removeAttribute('pref'); enableBluetoothEl.removeAttribute('controlled-by'); enableBluetoothEl.disabled = false; $('bluetooth-controlled-setting-indicator').hidden = true; // Flush the device lists. $('bluetooth-paired-devices-list').clear(); $('bluetooth-unpaired-devices-list').clear(); if (state.powered) { options.BluetoothOptions.updateDiscoveryState(state.discovering); // Update the device lists. chrome.bluetooth.getDevices(function(devices) { for (var device of devices) this.updateBluetoothDevicesList_(device); }.bind(this)); } else { options.BluetoothOptions.dismissOverlay(); } }, /** * Process a bluetooth.onDeviceAdded or onDeviceChanged event and update the * device list. * @param {!chrome.bluetooth.Device} device * @private */ onBluetoothDeviceAddedOrChanged_: function(device) { this.updateBluetoothDevicesList_(device); }, /** * Process a bluetooth.onDeviceRemoved event and update the device list. * @param {!chrome.bluetooth.Device} device * @private */ onBluetoothDeviceRemoved_: function(device) { this.removeBluetoothDevice_(device.address); }, /** * Process a bluetoothPrivate onPairing event and update the device list. * @param {!chrome.bluetoothPrivate.PairingEvent} pairing_event * @private */ onBluetoothPrivatePairing_: function(pairing_event) { this.updateBluetoothDevicesList_(pairing_event.device); BluetoothPairing.onBluetoothPairingEvent(pairing_event); }, /** * Add |device| to the appropriate list of Bluetooth devices. * @param {!chrome.bluetooth.Device} device * @private */ addBluetoothDeviceToList_: function(device) { // Display the "connecting" (already paired or not yet paired) and the // paired devices in the same list. if (device.paired || device.connecting) $('bluetooth-paired-devices-list').appendDevice(device); else $('bluetooth-unpaired-devices-list').appendDevice(device); }, /** * Add |device| to the appropriate list of Bluetooth devices or update the * entry if a device with a matching |address| property exists. * @param {!chrome.bluetooth.Device} device * @private */ updateBluetoothDevicesList_: function(device) { // Display the "connecting" (already paired or not yet paired) and the // paired devices in the same list. if (device.paired || device.connecting) { // Test to see if the device is currently in the unpaired list, in which // case it should be removed from that list. var index = $('bluetooth-unpaired-devices-list').find(device.address); if (index != undefined) $('bluetooth-unpaired-devices-list').deleteItemAtIndex(index); } else { // Test to see if the device is currently in the paired list, in which // case it should be removed from that list. var index = $('bluetooth-paired-devices-list').find(device.address); if (index != undefined) $('bluetooth-paired-devices-list').deleteItemAtIndex(index); } this.addBluetoothDeviceToList_(device); }, /** * Removes an element from the list of available devices. * @param {string} address Unique address of the device. * @private */ removeBluetoothDevice_: function(address) { var index = $('bluetooth-unpaired-devices-list').find(address); if (index != undefined) { $('bluetooth-unpaired-devices-list').deleteItemAtIndex(index); } else { index = $('bluetooth-paired-devices-list').find(address); if (index != undefined) $('bluetooth-paired-devices-list').deleteItemAtIndex(index); } }, /** * Shows the overlay dialog for changing the user avatar image. * @private */ showImagerPickerOverlay_: function() { PageManager.showPageByName('changePicture'); }, /** * Shows (or not) the "User" section of the settings page based on whether * any of the sub-sections are present (or not). * @private */ maybeShowUserSection_: function() { $('sync-users-section').hidden = $('profiles-section').hidden && $('sync-section').hidden && $('profiles-supervised-dashboard-tip').hidden; }, /** * Updates the date and time section with time sync information. * @param {boolean} canSetTime Whether the system time can be set. * @private */ setCanSetTime_: function(canSetTime) { // If the time has been network-synced, it cannot be set manually. $('set-time').hidden = !canSetTime; }, /** * Handle the 'set date and time' button click. * @private */ handleSetTime_: function() { chrome.send('showSetTime'); }, /** * Enables the given element if possible; on Chrome OS, it won't enable * an element that must stay disabled for the session type. * @param {!Element} element Element to enable. */ enableElementIfPossible_: function(element) { if (cr.isChromeOS) UIAccountTweaks.enableElementIfPossible(element); else element.disabled = false; }, }; // Forward public APIs to private implementations. cr.makePublic(BrowserOptions, [ 'deleteCurrentProfile', 'enableCertificateButton', 'enableDisplaySettings', 'enableFactoryResetSection', 'getCurrentProfile', 'getStartStopSyncButton', 'notifyInitializationComplete', 'removeBluetoothDevice', 'scrollToSection', 'setAccountPictureManaged', 'setAllHotwordSectionsVisible', 'setAudioHistorySectionVisible', 'setAutoOpenFileTypesDisplayed', 'setCanSetTime', 'setExtendedReportingEnabledCheckboxState', 'setFontSize', 'setHighContrastCheckboxState', 'setHotwordRetrainLinkVisible', 'setMetricsReportingCheckboxState', 'setMetricsReportingSettingVisibility', 'setNativeThemeButtonEnabled', 'setNetworkPredictionValue', 'setNowSectionVisible', 'setProfilesInfo', 'setSpokenFeedbackCheckboxState', 'setSystemTimezoneAutomaticDetectionManaged', 'setSystemTimezoneManaged', 'setThemesResetButtonEnabled', 'setVirtualKeyboardCheckboxState', 'setWallpaperManaged', 'setupPageZoomSelector', 'setupProxySettingsButton', 'showCreateProfileError', 'showCreateProfileSuccess', 'showCreateProfileWarning', 'showHotwordAlwaysOnSection', 'showHotwordNoDspSection', 'showHotwordSection', 'showMouseControls', 'showSupervisedUserImportError', 'showSupervisedUserImportSuccess', 'showTouchpadControls', 'toggleExtensionIndicators', 'updateAccountPicture', 'updateDefaultBrowserState', 'updateEasyUnlock', 'updateManagesSupervisedUsers', 'updateSearchEngines', 'updateSyncState', ]); if (cr.isChromeOS) { /** * Returns username (canonical email) of the user logged in (ChromeOS only). * @return {string} user email. */ // TODO(jhawkins): Investigate the use case for this method. BrowserOptions.getLoggedInUsername = function() { return BrowserOptions.getInstance().username_; }; /** * Shows Android Apps settings when they are available. * (Chrome OS only). */ BrowserOptions.showAndroidAppsSection = function(isArcEnabled) { var section = $('android-apps-section'); if (!section) return; section.hidden = false; }; /** * Shows/hides Android Settings app section. * (Chrome OS only). */ BrowserOptions.setAndroidAppsSettingsVisibility = function(isVisible) { var settings = $('android-apps-settings'); if (!settings) return; settings.hidden = !isVisible; }; } // Export return { BrowserOptions: BrowserOptions }; });
#!/usr/bin/env python3 # IBM_PROLOG_BEGIN_TAG # OpenPOWER Automated Test Project # # Contributors Listed Below - COPYRIGHT 2022 # [+] International Business Machines Corp. # # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. See the License for the specific language governing # permissions and limitations under the License. # # IBM_PROLOG_END_TAG # import os import re import time import common from common.Exceptions import CommandFailed import OpTestLogger log = OpTestLogger.optest_logger_glob.get_logger(__name__) class OpTestVIOS(): def __init__(self, vios_name, vios_ip, vios_username, vios_password, conf=None): self.name = vios_name self.host = vios_ip self.user = vios_username self.passwd = vios_password self.ssh = common.OpTestSSH.OpTestSSH(vios_ip, vios_username, vios_password) self.conf = conf def set_system(self, system): self.ssh.set_system(system) def gather_logs(self, list_of_commands=[], output_dir=None): if not output_dir: output_dir = "Vios_Logs_%s" % (time.asctime(time.localtime())).replace(" ", "_") output_dir = os.path.join(self.conf.host().results_dir, output_dir, self.name) if not os.path.exists(output_dir): os.makedirs(output_dir) default_commands = ['cat /proc/version', 'ioslevel', 'errlog', 'snap'] list_of_commands.extend(default_commands) try: for cmd in set(list_of_commands): output = "\n".join(self.run_command(r"%s" % cmd, timeout=600)) filename = "%s.log" % '-'.join((re.sub(r'[^a-zA-Z0-9]', ' ', cmd)).split()) filepath = os.path.join(output_dir, filename) with open(filepath, 'w') as f: f.write(output) snap_backup_filename = time.strftime("%d_%m_%Y_%H_%M_%S") + "_snap.pax.Z" self.run_command("mv snap.pax.Z %s" % snap_backup_filename) log.info("snap.pax.Z renamed to %s" % snap_backup_filename) return True except CommandFailed as cmd_failed: raise cmd_failed def run_command(self, cmd, timeout=60): return self.ssh.run_command(cmd, timeout)
'use strict'; var randtoken = require('rand-token'), nodemailer = require('nodemailer'); module.exports = function(mongoose) { var isPositiveInteger = function(x) { return ((parseInt(x, 10) === x) && (x >= 0)); }; var createOptionError = function(optionName, optionValue, expectedType) { return new TypeError('Expected ' + optionName + ' to be a ' + expectedType + ', got ' + typeof optionValue); }; /** * Retrieve a nested value of an object given a string, using dot notation. * * @func getNestedValue * @param {object} obj - object to retrieve the value from * @param {string} path - path to value * @param {string} def - default value to return if not found */ var getNestedValue = function(obj, path, def) { path = path.split('.'); for (let i = 0, len = path.length; i < len; i++) { if (!obj || typeof obj !== 'object') { return def; } obj = obj[path[i]]; } if (obj === undefined) { return def; } return obj; }; // default options var options = { verificationURL: 'http://example.com/email-verification/${URL}', URLLength: 48, // mongo-stuff persistentUserModel: null, tempUserModel: null, tempUserCollection: 'temporary_users', emailFieldName: 'email', passwordFieldName: 'password', URLFieldName: 'GENERATED_VERIFYING_URL', expirationTime: 86400, // emailing options transportOptions: { service: 'Gmail', auth: { user: 'user@gmail.com', pass: 'password' } }, verifyMailOptions: { from: 'Do Not Reply <user@gmail.com>', subject: 'Confirm your account', html: '<p>Please verify your account by clicking <a href="${URL}">this link</a>. If you are unable to do so, copy and ' + 'paste the following link into your browser:</p><p>${URL}</p>', text: 'Please verify your account by clicking the following link, or by copying and pasting it into your browser: ${URL}' }, verifySendMailCallback: function(err, info) { if (err) { throw err; } else { console.log(info.response); } }, shouldSendConfirmation: true, confirmMailOptions: { from: 'Do Not Reply <user@gmail.com>', subject: 'Successfully verified!', html: '<p>Your account has been successfully verified.</p>', text: 'Your account has been successfully verified.' }, confirmSendMailCallback: function(err, info) { if (err) { throw err; } else { console.log(info.response); } }, hashingFunction: null, }; var transporter; /** * Modify the default configuration. * * @func configure * @param {object} o - options to be changed */ var configure = function(optionsToConfigure, callback) { for (let key in optionsToConfigure) { if (optionsToConfigure.hasOwnProperty(key)) { options[key] = optionsToConfigure[key]; } } transporter = nodemailer.createTransport(options.transportOptions); var err; if (typeof options.verificationURL !== 'string') { err = err || createOptionError('verificationURL', options.verificationURL, 'string'); } else if (options.verificationURL.indexOf('${URL}') === -1) { err = err || new Error('Verification URL does not contain ${URL}'); } if (typeof options.URLLength !== 'number') { err = err || createOptionError('URLLength', options.URLLength, 'number'); } else if (!isPositiveInteger(options.URLLength)) { err = err || new Error('URLLength must be a positive integer'); } if (typeof options.tempUserCollection !== 'string') { err = err || createOptionError('tempUserCollection', options.tempUserCollection, 'string'); } if (typeof options.emailFieldName !== 'string') { err = err || createOptionError('emailFieldName', options.emailFieldName, 'string'); } if (typeof options.passwordFieldName !== 'string') { err = err || createOptionError('passwordFieldName', options.passwordFieldName, 'string'); } if (typeof options.URLFieldName !== 'string') { err = err || createOptionError('URLFieldName', options.URLFieldName, 'string'); } if (typeof options.expirationTime !== 'number') { err = err || createOptionError('expirationTime', options.expirationTime, 'number'); } else if (!isPositiveInteger(options.expirationTime)) { err = err || new Error('expirationTime must be a positive integer'); } if (err) { return callback(err, null); } return callback(null, options); }; /** * Create a Mongoose Model for the temporary user, based off of the persistent * User model, i.e. the temporary user inherits the persistent user. An * additional field for the URL is created, as well as a TTL. * * @func generateTempUserModel * @param {object} User - the persistent User model. * @return {object} the temporary user model */ var generateTempUserModel = function(User, callback) { if (!User) { return callback(new TypeError('Persistent user model undefined.'), null); } var tempUserSchemaObject = {}, // a copy of the schema tempUserSchema; // copy over the attributes of the schema Object.keys(User.schema.paths).forEach(function(field) { tempUserSchemaObject[field] = User.schema.paths[field].options; }); tempUserSchemaObject[options.URLFieldName] = String; // create a TTL tempUserSchemaObject.createdAt = { type: Date, expires: options.expirationTime.toString() + 's', default: Date.now }; tempUserSchema = mongoose.Schema(tempUserSchemaObject); // copy over the methods of the schema Object.keys(User.schema.methods).forEach(function(meth) { // tread lightly tempUserSchema.methods[meth] = User.schema.methods[meth]; }); options.tempUserModel = mongoose.model(options.tempUserCollection, tempUserSchema); return callback(null, mongoose.model(options.tempUserCollection)); }; /** * Helper function for actually inserting the temporary user into the database. * * @func insertTempUser * @param {string} password - the user's password, possibly hashed * @param {object} tempUserData - the temporary user's data * @param {function} callback - a callback function, which takes an error and the * temporary user object as params * @return {function} returns the callback function */ var insertTempUser = function(password, tempUserData, callback) { // password may or may not be hashed tempUserData[options.passwordFieldName] = password; var newTempUser = new options.tempUserModel(tempUserData); newTempUser.save(function(err, tempUser) { if (err) { return callback(err, null, null); } return callback(null, null, tempUser); }); }; /** * Attempt to create an instance of a temporary user based off of an instance of a * persistent user. If user already exists in the temporary collection, passes null * to the callback function; otherwise, passes the instance to the callback, with a * randomly generated URL associated to it. * * @func createTempUser * @param {object} user - an instance of the persistent User model * @param {function} callback - a callback function that takes an error (if one exists), * a persistent user (if it exists) and the new temporary user as arguments; if the * temporary user already exists, then null is returned in its place * @return {function} returns the callback function */ var createTempUser = function(user, callback) { if (!options.tempUserModel) { return callback(new TypeError('Temporary user model not defined. Either you forgot' + 'to generate one or you did not predefine one.'), null); } // create our mongoose query var query = {}; if(options.emailFieldName.split('.').length > 1){ var levels = options.emailFieldName.split('.'); query[levels[0]] = {}; var queryObj = query[levels[0]]; var userObj = user[levels[0]]; for(var i=0; i<levels.length; i++){ queryObj[levels[i+1]] = {}; queryObj = queryObj[levels[i+1]]; userObj = userObj[levels[i+1]]; } queryObj = userObj; }else { query[options.emailFieldName] = user[options.emailFieldName]; } options.persistentUserModel.findOne(query, function(err, existingPersistentUser) { if (err) { return callback(err, null, null); } // user has already signed up and confirmed their account if (existingPersistentUser) { return callback(null, existingPersistentUser, null); } options.tempUserModel.findOne(query, function(err, existingTempUser) { if (err) { return callback(err, null, null); } // user has already signed up but not yet confirmed their account if (existingTempUser) { return callback(null, null, null); } else { var tempUserData = {}; // copy the credentials for the user Object.keys(user._doc).forEach(function(field) { tempUserData[field] = user[field]; }); tempUserData[options.URLFieldName] = randtoken.generate(options.URLLength); if (options.hashingFunction) { return options.hashingFunction(tempUserData[options.passwordFieldName], tempUserData, insertTempUser, callback); } else { return insertTempUser(tempUserData[options.passwordFieldName], tempUserData, callback); } } }); }); }; /** * Send an email to the user requesting confirmation. * * @func sendVerificationEmail * @param {string} email - the user's email address. * @param {string} url - the unique url generated for the user. * @param {function} callback - the callback to pass to Nodemailer's transporter */ var sendVerificationEmail = function(email, url, callback) { var r = /\$\{URL\}/g; // inject newly-created URL into the email's body and FIRE // stringify --> parse is used to deep copy var URL = options.verificationURL.replace(r, url), mailOptions = JSON.parse(JSON.stringify(options.verifyMailOptions)); mailOptions.to = email; mailOptions.html = mailOptions.html.replace(r, URL); mailOptions.text = mailOptions.text.replace(r, URL); if (!callback) { callback = options.verifySendMailCallback; } transporter.sendMail(mailOptions, callback); }; /** * Send an email to the user requesting confirmation. * * @func sendConfirmationEmail * @param {string} email - the user's email address. * @param {function} callback - the callback to pass to Nodemailer's transporter */ var sendConfirmationEmail = function(email, callback) { var mailOptions = JSON.parse(JSON.stringify(options.confirmMailOptions)); mailOptions.to = email; if (options.shouldSendConfirmation) { if (!callback) { callback = options.confirmSendMailCallback; } transporter.sendMail(mailOptions, callback); } }; /** * Transfer a temporary user from the temporary collection to the persistent * user collection, removing the URL assigned to it. * * @func confirmTempUser * @param {string} url - the randomly generated URL assigned to a unique email */ var confirmTempUser = function(url, callback) { var TempUser = options.tempUserModel, query = {}; query[options.URLFieldName] = url; TempUser.findOne(query, function(err, tempUserData) { if (err) { return callback(err, null); } // temp user is found (i.e. user accessed URL before their data expired) if (tempUserData) { var userData = JSON.parse(JSON.stringify(tempUserData)), // copy data User = options.persistentUserModel, user; delete userData[options.URLFieldName]; user = new User(userData); // save the temporary user to the persistent user collection user.save(function(err, savedUser) { if (err) { return callback(err, null); } TempUser.remove(query, function(err) { if (err) { return callback(err, null); } if (options.shouldSendConfirmation) { sendConfirmationEmail(savedUser.email, null); } return callback(null, user); }); }); // temp user is not found (i.e. user accessed URL after data expired, or something else...) } else { return callback(null, null); } }); }; /** * Resend the verification email to the user given only their email. * * @func resendVerificationEmail * @param {object} email - the user's email address */ var resendVerificationEmail = function(email, callback) { var query = {}; query[options.emailFieldName] = email; options.tempUserModel.findOne(query, function(err, tempUser) { if (err) { return callback(err, null); } // user found (i.e. user re-requested verification email before expiration) if (tempUser) { // generate new user token tempUser[options.URLFieldName] = randtoken.generate(options.URLLength); tempUser.save(function(err) { if (err) { return callback(err, null); } sendVerificationEmail(getNestedValue(tempUser, options.emailFieldName), tempUser[options.URLFieldName], function(err) { if (err) { return callback(err, null); } return callback(null, true); }); }); } else { return callback(null, false); } }); }; return { options: options, configure: configure, generateTempUserModel: generateTempUserModel, createTempUser: createTempUser, confirmTempUser: confirmTempUser, resendVerificationEmail: resendVerificationEmail, sendConfirmationEmail: sendConfirmationEmail, sendVerificationEmail: sendVerificationEmail, }; };
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables from . import outputs from ._inputs import * __all__ = ['LocalNetworkGateway'] class LocalNetworkGateway(pulumi.CustomResource): def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, bgp_settings: Optional[pulumi.Input[pulumi.InputType['BgpSettingsArgs']]] = None, etag: Optional[pulumi.Input[str]] = None, gateway_ip_address: Optional[pulumi.Input[str]] = None, id: Optional[pulumi.Input[str]] = None, local_network_address_space: Optional[pulumi.Input[pulumi.InputType['AddressSpaceArgs']]] = None, local_network_gateway_name: Optional[pulumi.Input[str]] = None, location: Optional[pulumi.Input[str]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, resource_guid: Optional[pulumi.Input[str]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, __props__=None, __name__=None, __opts__=None): """ A common class for general resource information :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[pulumi.InputType['BgpSettingsArgs']] bgp_settings: Local network gateway's BGP speaker settings. :param pulumi.Input[str] etag: A unique read-only string that changes whenever the resource is updated. :param pulumi.Input[str] gateway_ip_address: IP address of local network gateway. :param pulumi.Input[str] id: Resource ID. :param pulumi.Input[pulumi.InputType['AddressSpaceArgs']] local_network_address_space: Local network site address space. :param pulumi.Input[str] local_network_gateway_name: The name of the local network gateway. :param pulumi.Input[str] location: Resource location. :param pulumi.Input[str] resource_group_name: The name of the resource group. :param pulumi.Input[str] resource_guid: The resource GUID property of the LocalNetworkGateway resource. :param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: Resource tags. """ if __name__ is not None: warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning) resource_name = __name__ if __opts__ is not None: warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning) opts = __opts__ if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = dict() __props__['bgp_settings'] = bgp_settings __props__['etag'] = etag __props__['gateway_ip_address'] = gateway_ip_address __props__['id'] = id __props__['local_network_address_space'] = local_network_address_space __props__['local_network_gateway_name'] = local_network_gateway_name __props__['location'] = location if resource_group_name is None and not opts.urn: raise TypeError("Missing required property 'resource_group_name'") __props__['resource_group_name'] = resource_group_name __props__['resource_guid'] = resource_guid __props__['tags'] = tags __props__['name'] = None __props__['provisioning_state'] = None __props__['type'] = None alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-nextgen:network:LocalNetworkGateway"), pulumi.Alias(type_="azure-nextgen:network/latest:LocalNetworkGateway"), pulumi.Alias(type_="azure-nextgen:network/v20150615:LocalNetworkGateway"), pulumi.Alias(type_="azure-nextgen:network/v20160330:LocalNetworkGateway"), pulumi.Alias(type_="azure-nextgen:network/v20160601:LocalNetworkGateway"), pulumi.Alias(type_="azure-nextgen:network/v20160901:LocalNetworkGateway"), pulumi.Alias(type_="azure-nextgen:network/v20161201:LocalNetworkGateway"), pulumi.Alias(type_="azure-nextgen:network/v20170301:LocalNetworkGateway"), pulumi.Alias(type_="azure-nextgen:network/v20170801:LocalNetworkGateway"), pulumi.Alias(type_="azure-nextgen:network/v20170901:LocalNetworkGateway"), pulumi.Alias(type_="azure-nextgen:network/v20171001:LocalNetworkGateway"), pulumi.Alias(type_="azure-nextgen:network/v20171101:LocalNetworkGateway"), pulumi.Alias(type_="azure-nextgen:network/v20180101:LocalNetworkGateway"), pulumi.Alias(type_="azure-nextgen:network/v20180201:LocalNetworkGateway"), pulumi.Alias(type_="azure-nextgen:network/v20180401:LocalNetworkGateway"), pulumi.Alias(type_="azure-nextgen:network/v20180601:LocalNetworkGateway"), pulumi.Alias(type_="azure-nextgen:network/v20180701:LocalNetworkGateway"), pulumi.Alias(type_="azure-nextgen:network/v20180801:LocalNetworkGateway"), pulumi.Alias(type_="azure-nextgen:network/v20181001:LocalNetworkGateway"), pulumi.Alias(type_="azure-nextgen:network/v20181101:LocalNetworkGateway"), pulumi.Alias(type_="azure-nextgen:network/v20181201:LocalNetworkGateway"), pulumi.Alias(type_="azure-nextgen:network/v20190201:LocalNetworkGateway"), pulumi.Alias(type_="azure-nextgen:network/v20190401:LocalNetworkGateway"), pulumi.Alias(type_="azure-nextgen:network/v20190601:LocalNetworkGateway"), pulumi.Alias(type_="azure-nextgen:network/v20190701:LocalNetworkGateway"), pulumi.Alias(type_="azure-nextgen:network/v20190801:LocalNetworkGateway"), pulumi.Alias(type_="azure-nextgen:network/v20190901:LocalNetworkGateway"), pulumi.Alias(type_="azure-nextgen:network/v20191101:LocalNetworkGateway"), pulumi.Alias(type_="azure-nextgen:network/v20191201:LocalNetworkGateway"), pulumi.Alias(type_="azure-nextgen:network/v20200301:LocalNetworkGateway"), pulumi.Alias(type_="azure-nextgen:network/v20200401:LocalNetworkGateway"), pulumi.Alias(type_="azure-nextgen:network/v20200501:LocalNetworkGateway"), pulumi.Alias(type_="azure-nextgen:network/v20200601:LocalNetworkGateway"), pulumi.Alias(type_="azure-nextgen:network/v20200701:LocalNetworkGateway"), pulumi.Alias(type_="azure-nextgen:network/v20200801:LocalNetworkGateway")]) opts = pulumi.ResourceOptions.merge(opts, alias_opts) super(LocalNetworkGateway, __self__).__init__( 'azure-nextgen:network/v20170601:LocalNetworkGateway', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None) -> 'LocalNetworkGateway': """ Get an existing LocalNetworkGateway resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource. """ opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = dict() return LocalNetworkGateway(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name="bgpSettings") def bgp_settings(self) -> pulumi.Output[Optional['outputs.BgpSettingsResponse']]: """ Local network gateway's BGP speaker settings. """ return pulumi.get(self, "bgp_settings") @property @pulumi.getter def etag(self) -> pulumi.Output[Optional[str]]: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter(name="gatewayIpAddress") def gateway_ip_address(self) -> pulumi.Output[Optional[str]]: """ IP address of local network gateway. """ return pulumi.get(self, "gateway_ip_address") @property @pulumi.getter(name="localNetworkAddressSpace") def local_network_address_space(self) -> pulumi.Output[Optional['outputs.AddressSpaceResponse']]: """ Local network site address space. """ return pulumi.get(self, "local_network_address_space") @property @pulumi.getter def location(self) -> pulumi.Output[Optional[str]]: """ Resource location. """ return pulumi.get(self, "location") @property @pulumi.getter def name(self) -> pulumi.Output[str]: """ Resource name. """ return pulumi.get(self, "name") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> pulumi.Output[str]: """ The provisioning state of the LocalNetworkGateway resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter(name="resourceGuid") def resource_guid(self) -> pulumi.Output[Optional[str]]: """ The resource GUID property of the LocalNetworkGateway resource. """ return pulumi.get(self, "resource_guid") @property @pulumi.getter def tags(self) -> pulumi.Output[Optional[Mapping[str, str]]]: """ Resource tags. """ return pulumi.get(self, "tags") @property @pulumi.getter def type(self) -> pulumi.Output[str]: """ Resource type. """ return pulumi.get(self, "type") def translate_output_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop def translate_input_property(self, prop): return _tables.SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or prop
#!/usr/bin/env python3 """ kiwi_manage.py Script to control donkey car with GPS navigation along with IMU-based heading and ultrasonic-based object detection. Waypoints are set with GPS coordinates in degrees. Call: gps_manage.py -drive """ # import GPS Planner and other DK parts import donkeycar as dk from wp_parts.personFinder import PersonFinder from donkeycar.vehicle import Vehicle from donkeycar.parts.actuator import PCA9685, PWMSteering, PWMThrottle from donkeycar.parts.controller import LocalWebController # other important modules import time import threading #for geting the GPS coordinates import json def drive(): # initialize vehicle V = Vehicle() ctr = LocalWebController() # Planner is a DK part that calculates control signals to actuators based on current location # from GPS planner = PersonFinder(steer_gain=0.5, distance_calibration=466) # Actuators: steering and throttle steering_controller = PCA9685(1, 0x40, busnum=1) steering = PWMSteering(controller=steering_controller, left_pulse=300, right_pulse=475) throttle_controller = PCA9685(2, 0x40, busnum=1) throttle = PWMThrottle(controller=throttle_controller, max_pulse=460, zero_pulse=370, min_pulse=330) from donkeycar.parts.camera import Webcam cam = Webcam(image_w=400, image_h=300, image_d=3) V.add(cam, inputs=[], outputs=['cam/img'], threaded=True) # add planner, actuator parts # Previous location is no longer needed # Instead, use actual bearing from DMP # It also takes in stop_cmd, a boolean indicating whether to stop # in which case it reverts to "STOPPED_PWM" V.add(planner, inputs=["cam/img"], outputs=["steer_cmd", "throttle_cmd", "proc/img"], threaded=True) #steer_cmd is a pwm value V.add(steering, inputs=['steer_cmd']) # throttle takes in a throttle_cmd pwm value, V.add(throttle, inputs=['throttle_cmd']) V.add(ctr, inputs=['proc/img'], outputs=['user/angle', 'user/throttle', 'user/mode', 'recording'], threaded=True) print("You can now go to <your pis hostname.local>:8887 to view your car's camera.") V.start() if __name__ == '__main__': drive()
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import numpy as np import math import warp as wp from warp.tests.test_base import * wp.init() @wp.kernel def test_operators_scalar_float(): a = 1.0 b = 2.0 c = a*b d = a+b e = a/b f = a-b g = b**8.0 h = 10.0//3.0 expect_eq(c, 2.0) expect_eq(d, 3.0) expect_eq(e, 0.5) expect_eq(f, -1.0) expect_eq(g, 256.0) expect_eq(h, 3.0) @wp.kernel def test_operators_scalar_int(): a = 1 b = 2 c = a*b d = a+b e = a/b f = a-b # g = b**8 # integer pow not implemented h = 10//3 expect_eq(c, 2) expect_eq(d, 3) expect_eq(e, 0) expect_eq(f, -1) # expect_eq(g, 256) expect_eq(h, 3) @wp.kernel def test_operators_vector_index(): v = wp.vec4(1.0, 2.0, 3.0, 4.0) expect_eq(v[0], 1.0) expect_eq(v[1], 2.0) expect_eq(v[2], 3.0) expect_eq(v[3], 4.0) @wp.kernel def test_operators_matrix_index(): m22 = wp.mat22(1.0, 2.0, 3.0, 4.0) expect_eq(m22[0,0], 1.0) expect_eq(m22[0,1], 2.0) expect_eq(m22[1,0], 3.0) expect_eq(m22[1,1], 4.0) @wp.kernel def test_operators_vec3(): v = vec3(1.0, 2.0, 3.0) r0 = v*3.0 r1 = 3.0*v expect_eq(r0, vec3(3.0, 6.0, 9.0)) expect_eq(r1, vec3(3.0, 6.0, 9.0)) col0 = vec3(1.0, 0.0, 0.0) col1 = vec3(0.0, 2.0, 0.0) col2 = vec3(0.0, 0.0, 3.0) m = mat33(col0, col1, col2) expect_eq(m*vec3(1.0, 0.0, 0.0), col0) expect_eq(m*vec3(0.0, 1.0, 0.0), col1) expect_eq(m*vec3(0.0, 0.0, 1.0), col2) two = vec3(1.0)*2.0 expect_eq(two, vec3(2.0, 2.0, 2.0)) @wp.kernel def test_operators_vec4(): v = vec4(1.0, 2.0, 3.0, 4.0) r0 = v*3.0 r1 = 3.0*v expect_eq(r0, vec4(3.0, 6.0, 9.0, 12.0)) expect_eq(r1, vec4(3.0, 6.0, 9.0, 12.0)) col0 = vec4(1.0, 0.0, 0.0, 0.0) col1 = vec4(0.0, 2.0, 0.0, 0.0) col2 = vec4(0.0, 0.0, 3.0, 0.0) col3 = vec4(0.0, 0.0, 0.0, 4.0) m = mat44(col0, col1, col2, col3) expect_eq(m*vec4(1.0, 0.0, 0.0, 0.0), col0) expect_eq(m*vec4(0.0, 1.0, 0.0, 0.0), col1) expect_eq(m*vec4(0.0, 0.0, 1.0, 0.0), col2) expect_eq(m*vec4(0.0, 0.0, 0.0, 1.0), col3) two = vec4(1.0)*2.0 expect_eq(two, vec4(2.0, 2.0, 2.0, 2.0)) def register(parent): devices = wp.get_devices() class TestOperators(parent): pass add_kernel_test(TestOperators, test_operators_scalar_float, dim=1, devices=devices) add_kernel_test(TestOperators, test_operators_scalar_int, dim=1, devices=devices) add_kernel_test(TestOperators, test_operators_matrix_index, dim=1, devices=devices) add_kernel_test(TestOperators, test_operators_vector_index, dim=1, devices=devices) add_kernel_test(TestOperators, test_operators_vec3, dim=1, devices=devices) add_kernel_test(TestOperators, test_operators_vec4, dim=1, devices=devices) return TestOperators if __name__ == '__main__': c = register(unittest.TestCase) unittest.main(verbosity=2)
# DO NOT EDIT THIS FILE. This file will be overwritten when re-running go-raml. from flask import Blueprint import handlers getuserinvoices_api = Blueprint('getuserinvoices_api', __name__) @getuserinvoices_api.route('/getuserinvoices', methods=['GET']) def getuserinvoices_get(): """ Get a list of Lightning invoices along with their payment status details for the authenticated user's custody account. It is handler for GET /getuserinvoices """ return handlers.getuserinvoices_getHandler()
default_app_config = "parsifal.apps.authentication.apps.AuthenticationConfig"
/* * Copyright (c) 2015 Appirio, Inc. All rights reserved. * @author Igor Androsov * @version 1.0 */ /** * This file provides an interface needed to manage account data from database. */ "use strict"; /** * Import required modules, and functions */ var pg = require('pg'); var config = require('config'); var logger = require('../common/logger'); var errors = require('../common/errors'); require("../common/function-utils"); /** * Get All Accounts */ var getAllAccountData = function (cb) { pg.connect(config.DATABASE_URL, cb.wrap(function (client, done) { client.query( config.SQL.GET_ACCOUNTS, function (err, result) { done(); if (err) { cb(err); } else { cb(null, result.rows); } } ); })); }; /** * Get All Accounts */ var searchAccountData = function (search, cb) { var search_parm = '%'+search+'%'; pg.connect(config.DATABASE_URL, cb.wrap(function (client, done) { client.query( config.SQL.GET_ACCOUNTS_SEARCH, [search_parm], function (err, result) { done(); if (err) { cb(err); } else { cb(null, result.rows); } } ); })); }; module.exports = { getAllAccountData: logger.wrapFunction(getAllAccountData), searchAccountData: logger.wrapFunction(searchAccountData) };
import template from "./navigate-to-modules.pug" import stylesheet from "./navigate-to-modules.styl" import BaseScreenshot from "components/base-screenshot" export default class Screenshot extends BaseScreenshot { static template = template; static stylesheet = stylesheet; }
import codecs import os from setuptools import find_packages from setuptools import setup HERE = os.path.abspath(os.path.dirname(__file__)) def read(*parts): """Return the contents of the read file. - Build an absolute path from *parts* - Return the contents of the resulting file. - Assume UTF-8 encoding. Proudly copy-pasted from Hynek's attrs project (minus the typo). """ with codecs.open(os.path.join(HERE, *parts), "rb", "utf-8") as f: return f.read() LONG = read("README.rst") + "\n\n" + read("CHANGES.rst") setup( name="Flask-Reuploaded", version="0.5.1.dev", url="https://github.com/jugmac00/flask-reuploaded", project_urls={ "Source": "https://github.com/jugmac00/flask-reuploaded", "Issue Tracker": "https://github.com/jugmac00/flask-reuploaded/issues", "Documentation": "https://flask-reuploaded.readthedocs.io/en/latest/", }, license="MIT", author='Matthew "LeafStorm" Frazier', author_email="leafstormrush@gmail.com", maintainer="Jürgen Gmach", maintainer_email="juergen.gmach@googlemail.com", description="Flexible and efficient upload handling for Flask", long_description=LONG, packages=find_packages(where="src"), package_dir={"": "src"}, zip_safe=False, platforms="any", install_requires=["Flask>=1.0.4"], extras_require={ "test": [ "pytest", "pytest-cov", ], }, python_requires=">= 3.6", classifiers=[ "Development Status :: 4 - Beta", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Topic :: Internet :: WWW/HTTP :: Dynamic Content", "Topic :: Software Development :: Libraries :: Python Modules", "Framework :: Flask", ], )
// Copyright (c) Microsoft Corporation // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and // to permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING // BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // module dependencies const createError = require('@pai/utils/error'); const storageModel = require('@pai/models/v2/storage'); const {isArray, isEmpty} = require('lodash'); const getStorageServer = async (req, res, next) => { try { const name = req.params.name; const storageServerInfo = await storageModel.getStorageServer(name); return res.status(200).json(storageServerInfo); } catch (error) { return next(createError.unknown(error)); } }; const getStorageServers = async (req, res, next) => { try { const names = isEmpty(req.query.names) ? [] : isArray(req.query.names) ? req.query.names : [req.query.names]; const storageServerList = await storageModel.getStorageServers(names); return res.status(200).json(storageServerList); } catch (error) { return next(createError.unknown(error)); } }; const getStorageConfig = async (req, res, next) => { try { const name = req.params.name; const storageConfigInfo = await storageModel.getStorageConfig(name); return res.status(200).json(storageConfigInfo); } catch (error) { return next(createError.unknown(error)); } }; const getStorageConfigs = async (req, res, next) => { try { const names = isEmpty(req.query.names) ? [] : isArray(req.query.names) ? req.query.names : [req.query.names]; const storageConfigList = await storageModel.getStorageConfigs(names); return res.status(200).json(storageConfigList); } catch (error) { return next(createError.unknown(error)); } }; const createStorageServer = async (req, res, next) => { try { if (!req.user.admin) { next( createError( 'Forbidden', 'ForbiddenUserError', `Non-admin is not allow to do this operation.` ) ); } const name = req.body.spn; const value = { spn: req.body.spn, type: req.body.type, data: req.body.data, }; await storageModel.createStorageServer(name, value); return res.status(201).json({ message: 'Storage Server is created successfully', }); } catch (error) { return next(createError.unknown(error)); } }; const updateStorageServer = async (req, res, next) => { try { if (!req.user.admin) { next( createError( 'Forbidden', 'ForbiddenUserError', `Non-admin is not allow to do this operation.` ) ); } const name = req.body.spn; const value = { spn: req.body.spn, type: req.body.type, data: req.body.data, }; await storageModel.updateStorageServer(name, value); return res.status(201).json({ message: 'Storage Server is updated successfully', }); } catch (error) { return next(createError.unknown(error)); } }; const deleteStorageServer = async (req, res, next) => { try { if (!req.user.admin) { next( createError( 'Forbidden', 'ForbiddenUserError', `Non-admin is not allow to do this operation.` ) ); } const name = req.params.name; await storageModel.deleteStorageServer(name); return res.status(201).json({ message: 'Storage Server is deleted successfully', }); } catch (error) { return next(createError.unknown(error)); } }; const createStorageConfig = async (req, res, next) => { try { if (!req.user.admin) { next( createError( 'Forbidden', 'ForbiddenUserError', `Non-admin is not allow to do this operation.` ) ); } const name = req.body.name; const value = req.body; await storageModel.createStorageConfig(name, value); return res.status(201).json({ message: 'Storage Config is created successfully', }); } catch (error) { return next(createError.unknown(error)); } }; const updateStorageConfig = async (req, res, next) => { try { if (!req.user.admin) { next( createError( 'Forbidden', 'ForbiddenUserError', `Non-admin is not allow to do this operation.` ) ); } const name = req.body.name; const value = req.body; await storageModel.updateStorageConfig(name, value); return res.status(201).json({ message: 'Storage Config is updated successfully', }); } catch (error) { return next(createError.unknown(error)); } }; const deleteStorageConfig = async (req, res, next) => { try { if (!req.user.admin) { next( createError( 'Forbidden', 'ForbiddenUserError', `Non-admin is not allow to do this operation.` ) ); } const name = req.params.name; await storageModel.deleteStorageConfig(name); return res.status(201).json({ message: 'Storage Config is deleted successfully', }); } catch (error) { return next(createError.unknown(error)); } }; // module exports module.exports = { getStorageServer, getStorageServers, getStorageConfig, getStorageConfigs, createStorageServer, updateStorageServer, deleteStorageServer, createStorageConfig, updateStorageConfig, deleteStorageConfig, };
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests and benchmarks for the ResNet50 model, executed eagerly.""" import time import tensorflow as tf def device_and_data_format(): if tf.config.list_physical_devices('GPU'): return ('/gpu:0', 'channels_first') return ('/cpu:0', 'channels_last') def random_batch(batch_size, data_format, seed=None): """Create synthetic resnet50 images and labels for testing.""" if seed: tf.random.set_seed(seed) shape = (3, 224, 224) if data_format == 'channels_first' else (224, 224, 3) shape = (batch_size,) + shape num_classes = 1000 images = tf.random.uniform(shape) labels = tf.random.uniform([batch_size], minval=0, maxval=num_classes, dtype=tf.int32) one_hot = tf.one_hot(labels, num_classes) return images, one_hot def report(benchmark, label, start, num_iters, device, batch_size, data_format, num_replicas=1): avg_time = (time.time() - start) / num_iters dev = tf.DeviceSpec.from_string(device).device_type.lower() replica_str = '' if num_replicas == 1 else 'replicas_%d_' % num_replicas name = '%s_%s_batch_%d_%s%s' % (label, dev, batch_size, replica_str, data_format) extras = {'examples_per_sec': (num_replicas * batch_size) / avg_time} benchmark.report_benchmark( iters=num_iters, wall_time=avg_time, name=name, extras=extras)
// @flow import * as React from 'react' import Headroom from '@integreat-app/react-sticky-headroom' import styled, { type StyledComponent } from 'styled-components' import withPlatform from '../../platform/hocs/withPlatform' import Platform from '../../platform/Platform' import type { ThemeType } from 'build-configs/ThemeType' import HeaderTitle, { HEADER_TITLE_HEIGHT } from './HeaderTitle' import HeaderLogo from './HeaderLogo' import dimensions from '../../theme/constants/dimensions' type PropsType = {| navigationItems: Array<React.Node>, actionItems: Array<React.Node>, logoHref: string, viewportSmall: boolean, cityName?: string, onStickyTopChanged: number => void, platform: Platform |} const HeaderContainer: StyledComponent<{||}, ThemeType, *> = styled.header` display: flex; width: 100%; box-sizing: border-box; box-shadow: 0 2px 5px -3px rgba(0, 0, 0, 0.2); background-color: ${props => props.theme.colors.backgroundAccentColor}; user-select: none; flex-direction: column; overflow: visible; @media ${dimensions.minMaxWidth} { padding-right: calc((200% - 100vw - ${dimensions.maxWidth}px) / 2); padding-left: calc((100vw - ${dimensions.maxWidth}px) / 2); } ` const Row: StyledComponent<{| hasTitle?: boolean |}, ThemeType, *> = styled.div` display: flex; flex: 1; max-width: 100%; align-items: stretch; min-height: ${dimensions.headerHeightLarge}px; flex-direction: row; :first-child { z-index: 1; /* Necessary to make the LanguageFlyout cover the NavigationItems as they have opacity set */ } @media ${dimensions.smallViewport} { justify-content: space-between; flex-wrap: wrap; min-height: ${dimensions.headerHeightSmall}px; :first-child { /* this is only necessary for IE11 */ min-height: ${props => dimensions.headerHeightSmall + (props.hasTitle ? HEADER_TITLE_HEIGHT : 0)}px; } } ` const HeaderSeparator: StyledComponent<{||}, ThemeType, *> = styled.div` align-self: center; height: ${dimensions.headerHeightLarge / 2}px; width: 2px; margin: 0 5px; background-color: ${props => props.theme.colors.textDecorationColor}; order: 2; @media ${dimensions.smallViewport} { display: none; } ` const ActionBar: StyledComponent<{||}, ThemeType, *> = styled.div` order: 3; display: flex; align-items: center; justify-content: flex-end; @media ${dimensions.smallViewport} { order: 2; flex: 1 1 0%; /* The % unit is necessary for IE11 */ } ` const NavigationBar: StyledComponent<{||}, ThemeType, *> = styled.div` display: flex; padding: 0 10px; flex: 1 1 0%; /* The % unit is necessary for IE11 */ align-items: stretch; justify-content: center; ` /** * The standard header which can supplied to a Layout. Displays a logo left, a HeaderMenuBar in the middle and a * HeaderActionBar at the right (RTL: vice versa). On small viewports the HeaderMenuBar is shown underneath the rest * of the Header. * Uses Headroom to save space when scrolling. */ export const Header = ({ viewportSmall, onStickyTopChanged, actionItems = [], logoHref, navigationItems = [], platform, cityName }: PropsType) => { const { headerHeightSmall, headerHeightLarge } = dimensions const hasNavigationBar = navigationItems.length > 0 const height = viewportSmall ? (1 + (hasNavigationBar ? 1 : 0)) * headerHeightSmall + (cityName ? HEADER_TITLE_HEIGHT : 0) : (1 + (hasNavigationBar ? 1 : 0)) * headerHeightLarge const scrollHeight = viewportSmall ? headerHeightSmall + (cityName ? HEADER_TITLE_HEIGHT : 0) : headerHeightLarge return ( <Headroom onStickyTopChanged={onStickyTopChanged} scrollHeight={scrollHeight} height={height} positionStickyDisabled={platform.positionStickyDisabled}> <HeaderContainer> <Row hasTitle={!!cityName}> <HeaderLogo link={logoHref} /> {!viewportSmall && cityName && <HeaderSeparator />} {(!viewportSmall || cityName) && <HeaderTitle>{cityName}</HeaderTitle>} <ActionBar>{actionItems}</ActionBar> </Row> {hasNavigationBar && ( <Row> <NavigationBar>{navigationItems}</NavigationBar> </Row> )} </HeaderContainer> </Headroom> ) } export default withPlatform(Header)
# This file is part of Propagator, a KDE Sysadmin Project # # Copyright (C) 2015-2016 Boudhayan Gupta <bgupta@kde.org> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. Neither the name of KDE e.V. (or its successor approved by the # membership of KDE e.V.) nor the names of its contributors may be used # to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT # NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from propagator.remotes.remotebase import RemoteBase class Remote(RemoteBase): def __init__(self, opslog): self.logger = opslog self.plugin_init() @property def plugin_name(self): return "dummy" def plugin_init(self, *args, **kwargs): self.logger.info("loaded dummy plugin") print("loaded dummy plugin") def can_handle_repo(self, name): return True def create(self, name, desc): print("create repo - {}, {}".format(name, desc)) def rename(self, name, dest): print("rename repo - {}, {}".format(name, dest)) def update(self, repo, name): print("update repo - {}".format(name)) def delete(self, name): print("delete repo - {}".format(name)) def setdesc(self, name, desc): print("set repo desc: {}, {}".format(name, desc))
""" Autopsy Forensic Browser Copyright 2016-2021 Basis Technology Corp. Contact: carrier <at> sleuthkit <dot> org Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from java.io import File from java.lang import Class from java.lang import ClassNotFoundException from java.lang import Long from java.lang import String from java.sql import Connection from java.sql import DriverManager from java.sql import ResultSet from java.sql import SQLException from java.sql import Statement from java.util.logging import Level from java.util import ArrayList from org.apache.commons.codec.binary import Base64 from org.sleuthkit.autopsy.casemodule import Case from org.sleuthkit.autopsy.casemodule import NoCurrentCaseException from org.sleuthkit.autopsy.casemodule.services import FileManager from org.sleuthkit.autopsy.coreutils import Logger from org.sleuthkit.autopsy.coreutils import MessageNotifyUtil from org.sleuthkit.autopsy.datamodel import ContentUtils from org.sleuthkit.autopsy.ingest import IngestJobContext from org.sleuthkit.datamodel import AbstractFile from org.sleuthkit.datamodel import Blackboard from org.sleuthkit.datamodel import BlackboardArtifact from org.sleuthkit.datamodel import BlackboardAttribute from org.sleuthkit.datamodel import Content from org.sleuthkit.datamodel import TskCoreException from org.sleuthkit.datamodel import Account from org.sleuthkit.datamodel.Blackboard import BlackboardException from org.sleuthkit.autopsy.coreutils import AppSQLiteDB from org.sleuthkit.datamodel.blackboardutils import CommunicationArtifactsHelper from org.sleuthkit.datamodel.blackboardutils.CommunicationArtifactsHelper import MessageReadStatus from org.sleuthkit.datamodel.blackboardutils.CommunicationArtifactsHelper import CommunicationDirection import traceback import general """ Locates database for the Tango app and adds info to blackboard. """ class TangoMessageAnalyzer(general.AndroidComponentAnalyzer): def __init__(self): self._logger = Logger.getLogger(self.__class__.__name__) self._PACKAGE_NAME = "com.sgiggle.production" self._PARSER_NAME = "Tango Parser" self._MESSAGE_TYPE = "Tango Message" self._VERSION = "7" # DB_VERSION in 'profiles' table def analyze(self, dataSource, fileManager, context): try: tangoDbFiles = AppSQLiteDB.findAppDatabases(dataSource, "tc.db", True, self._PACKAGE_NAME) for tangoDbFile in tangoDbFiles: try: self.__findTangoMessagesInDB(tangoDbFile, dataSource, context) except Exception as ex: self._logger.log(Level.SEVERE, "Error parsing Tango messages", ex) self._logger.log(Level.SEVERE, traceback.format_exc()) except TskCoreException as ex: # Error finding Tango messages. pass def __findTangoMessagesInDB(self, tangoDb, dataSource, context): if not tangoDb: return try: current_case = Case.getCurrentCaseThrows() # Create a helper to parse the DB tangoDbHelper = CommunicationArtifactsHelper(current_case.getSleuthkitCase(), self._PARSER_NAME, tangoDb.getDBFile(), Account.Type.TANGO, context.getJobId()) resultSet = tangoDb.runQuery( "SELECT conv_id, create_time, direction, payload FROM messages ORDER BY create_time DESC;") while resultSet.next(): fromId = None toId = None conv_id = resultSet.getString("conv_id") # seems to wrap around the message found in payload after decoding from base-64 create_time = Long.valueOf(resultSet.getString("create_time")) / 1000 if resultSet.getString("direction") == "1": # 1 incoming, 2 outgoing direction = CommunicationDirection.INCOMING else: direction = CommunicationDirection.OUTGOING payload = resultSet.getString("payload") msgBody = TangoMessageAnalyzer.decodeMessage(conv_id, payload) messageArtifact = tangoDbHelper.addMessage( self._MESSAGE_TYPE, direction, fromId, toId, create_time, MessageReadStatus.UNKNOWN, "", # subject msgBody, "") except SQLException as ex: self._logger.log(Level.WARNING, "Error processing query result for Tango messages", ex) self._logger.log(Level.WARNING, traceback.format_exc()) except TskCoreException as ex: self._logger.log(Level.SEVERE, "Failed to add Tango message artifacts.", ex) self._logger.log(Level.SEVERE, traceback.format_exc()) except BlackboardException as ex: self._logger.log(Level.WARNING, "Failed to post artifacts.", ex) self._logger.log(Level.WARNING, traceback.format_exc()) except NoCurrentCaseException as ex: self._logger.log(Level.WARNING, "No case currently open.", ex) self._logger.log(Level.WARNING, traceback.format_exc()) finally: tangoDb.close() # take the message string which is wrapped by a certain string, and return the text enclosed. @staticmethod def decodeMessage(wrapper, message): result = "" decoded = Base64.decodeBase64(message) try: Z = String(decoded, "UTF-8") result = Z.split(wrapper)[1] except Exception as ex: # Error decoding a Tango message. pass return result
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the LICENSE * file in the root directory of this source tree. */ #pragma once /** timeval inline functions */ #include <stdint.h> #include <sys/time.h> #include <sys/types.h> typedef struct timeval timeval_t; static inline void timeval_add(timeval_t* a, const timeval_t* b) { a->tv_sec += b->tv_sec; a->tv_usec += b->tv_usec; if (a->tv_usec > 1000000) { a->tv_sec += 1; a->tv_usec -= 1000000; } } static inline void timeval_sub(timeval_t* a, const timeval_t* b) { if (b->tv_usec > a->tv_usec) { a->tv_sec--; a->tv_usec += 1000000; } a->tv_sec -= b->tv_sec; a->tv_usec -= b->tv_usec; } static inline int timeval_cmp(const timeval_t* a, const timeval_t* b) { return a->tv_sec > b->tv_sec ? 1 : a->tv_sec < b->tv_sec ? -1 : a->tv_usec - b->tv_usec; } static inline int timeval_lt(const timeval_t* a, const timeval_t* b) { return timeval_cmp(a, b) < 0; } static inline int timeval_le(const timeval_t* a, const timeval_t* b) { return timeval_cmp(a, b) <= 0; } static inline int timeval_eq(const timeval_t* a, const timeval_t* b) { return timeval_cmp(a, b) == 0; } static inline int timeval_gt(const timeval_t* a, const timeval_t* b) { return timeval_cmp(a, b) > 0; } static inline int timeval_ge(const timeval_t* a, const timeval_t* b) { return timeval_cmp(a, b) >= 0; } static inline const timeval_t* timeval_min( const timeval_t* a, const timeval_t* b) { return timeval_cmp(a, b) <= 0 ? a : b; } static inline uint32_t timeval_ms(const timeval_t* t) { return (t->tv_sec * 1000) + (t->tv_usec + 500) / 1000; } static inline uint64_t timeval_us(const timeval_t* t) { return (t->tv_sec * 1000000) + t->tv_usec; } static inline timeval_t ms_to_timeval(const uint32_t ms) { timeval_t t; t.tv_sec = ms / 1000; t.tv_usec = (ms % 1000) * 1000; return t; }
/* * TechSmith Screen Codec 2 (aka Dora) decoder * Copyright (c) 2012 Konstantin Shishkov * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * TechSmith Screen Codec 2 decoder */ #include <inttypes.h> #define BITSTREAM_READER_LE #include "avcodec.h" #include "bytestream.h" #include "get_bits.h" #include "internal.h" #include "mathops.h" #include "tscc2data.h" typedef struct TSCC2Context { AVCodecContext *avctx; AVFrame *pic; int mb_width, mb_height; uint8_t *slice_quants; int quant[2]; int q[2][3]; GetBitContext gb; VLC dc_vlc, nc_vlc[NUM_VLC_SETS], ac_vlc[NUM_VLC_SETS]; int block[16]; } TSCC2Context; static av_cold void free_vlcs(TSCC2Context *c) { int i; ff_free_vlc(&c->dc_vlc); for (i = 0; i < NUM_VLC_SETS; i++) { ff_free_vlc(c->nc_vlc + i); ff_free_vlc(c->ac_vlc + i); } } static av_cold int init_vlcs(TSCC2Context *c) { int i, ret; ret = ff_init_vlc_sparse(&c->dc_vlc, 9, DC_VLC_COUNT, tscc2_dc_vlc_bits, 1, 1, tscc2_dc_vlc_codes, 2, 2, tscc2_dc_vlc_syms, 2, 2, INIT_VLC_LE); if (ret) return ret; for (i = 0; i < NUM_VLC_SETS; i++) { ret = ff_init_vlc_sparse(c->nc_vlc + i, 9, 16, tscc2_nc_vlc_bits[i], 1, 1, tscc2_nc_vlc_codes[i], 2, 2, tscc2_nc_vlc_syms, 1, 1, INIT_VLC_LE); if (ret) { free_vlcs(c); return ret; } ret = ff_init_vlc_sparse(c->ac_vlc + i, 9, tscc2_ac_vlc_sizes[i], tscc2_ac_vlc_bits[i], 1, 1, tscc2_ac_vlc_codes[i], 2, 2, tscc2_ac_vlc_syms[i], 2, 2, INIT_VLC_LE); if (ret) { free_vlcs(c); return ret; } } return 0; } #define DEQUANT(val, q) (((q) * (val) + 0x80) >> 8) #define DCT1D(d0, d1, d2, d3, s0, s1, s2, s3, OP) \ OP(d0, 5 * ((s0) + (s1) + (s2)) + 2 * (s3)); \ OP(d1, 5 * ((s0) - (s2) - (s3)) + 2 * (s1)); \ OP(d2, 5 * ((s0) - (s2) + (s3)) - 2 * (s1)); \ OP(d3, 5 * ((s0) - (s1) + (s2)) - 2 * (s3)); \ #define COL_OP(a, b) a = (b) #define ROW_OP(a, b) a = ((b) + 0x20) >> 6 static void tscc2_idct4_put(int *in, int q[3], uint8_t *dst, int stride) { int i; int tblk[4 * 4]; int t0, t1, t2, t3; for (i = 0; i < 4; i++) { t0 = DEQUANT(q[0 + (i & 1)], in[0 * 4 + i]); t1 = DEQUANT(q[1 + (i & 1)], in[1 * 4 + i]); t2 = DEQUANT(q[0 + (i & 1)], in[2 * 4 + i]); t3 = DEQUANT(q[1 + (i & 1)], in[3 * 4 + i]); DCT1D(tblk[0 * 4 + i], tblk[1 * 4 + i], tblk[2 * 4 + i], tblk[3 * 4 + i], t0, t1, t2, t3, COL_OP); } for (i = 0; i < 4; i++) { DCT1D(dst[0], dst[1], dst[2], dst[3], tblk[i * 4 + 0], tblk[i * 4 + 1], tblk[i * 4 + 2], tblk[i * 4 + 3], ROW_OP); dst += stride; } } static int tscc2_decode_mb(TSCC2Context *c, int *q, int vlc_set, uint8_t *dst, int stride, int plane) { GetBitContext *gb = &c->gb; int prev_dc, dc, nc, ac, bpos, val; int i, j, k, l; if (get_bits1(gb)) { if (get_bits1(gb)) { val = get_bits(gb, 8); for (i = 0; i < 8; i++, dst += stride) memset(dst, val, 16); } else { if (get_bits_left(gb) < 16 * 8 * 8) return AVERROR_INVALIDDATA; for (i = 0; i < 8; i++) { for (j = 0; j < 16; j++) dst[j] = get_bits(gb, 8); dst += stride; } } return 0; } prev_dc = 0; for (j = 0; j < 2; j++) { for (k = 0; k < 4; k++) { if (!(j | k)) { dc = get_bits(gb, 8); } else { dc = get_vlc2(gb, c->dc_vlc.table, 9, 2); if (dc == -1) return AVERROR_INVALIDDATA; if (dc == 0x100) dc = get_bits(gb, 8); } dc = (dc + prev_dc) & 0xFF; prev_dc = dc; c->block[0] = dc; nc = get_vlc2(gb, c->nc_vlc[vlc_set].table, 9, 1); if (nc == -1) return AVERROR_INVALIDDATA; bpos = 1; memset(c->block + 1, 0, 15 * sizeof(*c->block)); for (l = 0; l < nc; l++) { ac = get_vlc2(gb, c->ac_vlc[vlc_set].table, 9, 2); if (ac == -1) return AVERROR_INVALIDDATA; if (ac == 0x1000) ac = get_bits(gb, 12); bpos += ac & 0xF; if (bpos >= 16) return AVERROR_INVALIDDATA; val = sign_extend(ac >> 4, 8); c->block[ff_zigzag_scan[bpos++]] = val; } tscc2_idct4_put(c->block, q, dst + k * 4, stride); } dst += 4 * stride; } return 0; } static int tscc2_decode_slice(TSCC2Context *c, int mb_y, const uint8_t *buf, int buf_size) { int i, mb_x, q, ret; int off; if ((ret = init_get_bits8(&c->gb, buf, buf_size)) < 0) return ret; for (mb_x = 0; mb_x < c->mb_width; mb_x++) { q = c->slice_quants[mb_x + c->mb_width * mb_y]; if (q == 0 || q == 3) // skip block continue; for (i = 0; i < 3; i++) { off = mb_x * 16 + mb_y * 8 * c->pic->linesize[i]; ret = tscc2_decode_mb(c, c->q[q - 1], c->quant[q - 1] - 2, c->pic->data[i] + off, c->pic->linesize[i], i); if (ret) return ret; } } return 0; } static int tscc2_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { const uint8_t *buf = avpkt->data; int buf_size = avpkt->size; TSCC2Context *c = avctx->priv_data; GetByteContext gb; uint32_t frame_type, size; int i, val, len, pos = 0; int num_mb = c->mb_width * c->mb_height; int ret; bytestream2_init(&gb, buf, buf_size); frame_type = bytestream2_get_byte(&gb); if (frame_type > 1) { av_log(avctx, AV_LOG_ERROR, "Incorrect frame type %"PRIu32"\n", frame_type); return AVERROR_INVALIDDATA; } if (frame_type == 0) { // Skip duplicate frames return buf_size; } if ((ret = ff_reget_buffer(avctx, c->pic, 0)) < 0) { return ret; } if (bytestream2_get_bytes_left(&gb) < 4) { av_log(avctx, AV_LOG_ERROR, "Frame is too short\n"); return AVERROR_INVALIDDATA; } c->quant[0] = bytestream2_get_byte(&gb); c->quant[1] = bytestream2_get_byte(&gb); if (c->quant[0] < 2 || c->quant[0] > NUM_VLC_SETS + 1 || c->quant[1] < 2 || c->quant[1] > NUM_VLC_SETS + 1) { av_log(avctx, AV_LOG_ERROR, "Invalid quantisers %d / %d\n", c->quant[0], c->quant[1]); return AVERROR_INVALIDDATA; } for (i = 0; i < 3; i++) { c->q[0][i] = tscc2_quants[c->quant[0] - 2][i]; c->q[1][i] = tscc2_quants[c->quant[1] - 2][i]; } bytestream2_skip(&gb, 1); size = bytestream2_get_le32(&gb); if (size > bytestream2_get_bytes_left(&gb)) { av_log(avctx, AV_LOG_ERROR, "Slice properties chunk is too large\n"); return AVERROR_INVALIDDATA; } for (i = 0; i < size; i++) { val = bytestream2_get_byte(&gb); len = val & 0x3F; val >>= 6; if (pos + len > num_mb) { av_log(avctx, AV_LOG_ERROR, "Too many slice properties\n"); return AVERROR_INVALIDDATA; } memset(c->slice_quants + pos, val, len); pos += len; } if (pos < num_mb) { av_log(avctx, AV_LOG_ERROR, "Too few slice properties (%d / %d)\n", pos, num_mb); return AVERROR_INVALIDDATA; } for (i = 0; i < c->mb_height; i++) { size = bytestream2_peek_byte(&gb); if (size & 1) { size = bytestream2_get_byte(&gb) - 1; } else { size = bytestream2_get_le32(&gb) >> 1; } if (!size) { int skip_row = 1, j, off = i * c->mb_width; for (j = 0; j < c->mb_width; j++) { if (c->slice_quants[off + j] == 1 || c->slice_quants[off + j] == 2) { skip_row = 0; break; } } if (!skip_row) { av_log(avctx, AV_LOG_ERROR, "Non-skip row with zero size\n"); return AVERROR_INVALIDDATA; } } if (bytestream2_get_bytes_left(&gb) < size) { av_log(avctx, AV_LOG_ERROR, "Invalid slice size (%"PRIu32"/%u)\n", size, bytestream2_get_bytes_left(&gb)); return AVERROR_INVALIDDATA; } ret = tscc2_decode_slice(c, i, buf + bytestream2_tell(&gb), size); if (ret) { av_log(avctx, AV_LOG_ERROR, "Error decoding slice %d\n", i); return ret; } bytestream2_skip(&gb, size); } *got_frame = 1; if ((ret = av_frame_ref(data, c->pic)) < 0) return ret; /* always report that the buffer was completely consumed */ return buf_size; } static av_cold int tscc2_decode_end(AVCodecContext *avctx) { TSCC2Context * const c = avctx->priv_data; av_frame_free(&c->pic); av_freep(&c->slice_quants); free_vlcs(c); return 0; } static av_cold int tscc2_decode_init(AVCodecContext *avctx) { TSCC2Context * const c = avctx->priv_data; int ret; c->avctx = avctx; avctx->pix_fmt = AV_PIX_FMT_YUV444P; if ((ret = init_vlcs(c)) < 0) { av_log(avctx, AV_LOG_ERROR, "Cannot initialise VLCs\n"); return ret; } c->mb_width = FFALIGN(avctx->width, 16) >> 4; c->mb_height = FFALIGN(avctx->height, 8) >> 3; c->slice_quants = av_malloc(c->mb_width * c->mb_height); if (!c->slice_quants) { av_log(avctx, AV_LOG_ERROR, "Cannot allocate slice information\n"); free_vlcs(c); return AVERROR(ENOMEM); } c->pic = av_frame_alloc(); if (!c->pic) { tscc2_decode_end(avctx); return AVERROR(ENOMEM); } return 0; } AVCodec ff_tscc2_decoder = { .name = "tscc2", .long_name = NULL_IF_CONFIG_SMALL("TechSmith Screen Codec 2"), .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_TSCC2, .priv_data_size = sizeof(TSCC2Context), .init = tscc2_decode_init, .close = tscc2_decode_end, .decode = tscc2_decode_frame, .capabilities = AV_CODEC_CAP_DR1, };
# ========================================================================== # # Copyright NumFOCUS # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0.txt # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # ==========================================================================*/ # also test the import callback feature import itk import sys import os def custom_callback(name, progress): if progress == 0: print(f"Loading {name}...", file=sys.stderr) if progress == 1: print("done", file=sys.stderr) import itkConfig itkConfig.ImportCallback = custom_callback # test setting the number of threads itk.set_nthreads(4) assert itk.get_nthreads() == 4 # test the force load function itk.force_load() filename = sys.argv[1] mesh_filename = sys.argv[2] PixelType = itk.UC dim = 2 ImageType = itk.Image[PixelType, dim] ReaderType = itk.ImageFileReader[ImageType] reader = ReaderType.New(FileName=filename) # test snake_case keyword arguments reader = ReaderType.New(file_name=filename) # test echo itk.echo(reader) itk.echo(reader, sys.stdout) # test class_ assert itk.class_(reader) == ReaderType assert itk.class_("dummy") == str # test template assert itk.template(ReaderType) == (itk.ImageFileReader, (ImageType,)) assert itk.template(reader) == (itk.ImageFileReader, (ImageType,)) try: itk.template(str) raise Exception("unknown class should send an exception") except KeyError: pass # test ctype assert itk.ctype("unsigned short") == itk.US assert itk.ctype(" unsigned \n short \t ") == itk.US assert itk.ctype("signed short") == itk.SS assert itk.ctype("short") == itk.SS try: itk.ctype("dummy") raise Exception("unknown C type should send an exception") except KeyError: pass # test output assert itk.output(reader) == reader.GetOutput() assert itk.output(1) == 1 # test the deprecated image assert itk.image(reader) == reader.GetOutput() assert itk.image(1) == 1 # test size s = itk.size(reader) assert s[0] == s[1] == 256 s = itk.size(reader.GetOutput()) assert s[0] == s[1] == 256 # test physical size s = itk.physical_size(reader) assert s[0] == s[1] == 256.0 s = itk.physical_size(reader.GetOutput()) assert s[0] == s[1] == 256.0 # test spacing s = itk.spacing(reader) assert s[0] == s[1] == 1.0 s = itk.spacing(reader.GetOutput()) assert s[0] == s[1] == 1.0 # test origin s = itk.origin(reader) assert s[0] == s[1] == 0.0 s = itk.origin(reader.GetOutput()) assert s[0] == s[1] == 0.0 # test index s = itk.index(reader) assert s[0] == s[1] == 0 s = itk.index(reader.GetOutput()) assert s[0] == s[1] == 0 # test region s = itk.region(reader) assert s.GetIndex()[0] == s.GetIndex()[1] == 0 assert s.GetSize()[0] == s.GetSize()[1] == 256 s = itk.region(reader.GetOutput()) assert s.GetIndex()[0] == s.GetIndex()[1] == 0 assert s.GetSize()[0] == s.GetSize()[1] == 256 # test range assert itk.range(reader) == (0, 255) assert itk.range(reader.GetOutput()) == (0, 255) # test write itk.imwrite(reader, sys.argv[3]) itk.imwrite(reader, sys.argv[3], True) # test read image = itk.imread(filename) assert type(image) == itk.Image[itk.RGBPixel[itk.UC], 2] image = itk.imread(filename, itk.F) assert type(image) == itk.Image[itk.F, 2] image = itk.imread(filename, itk.F, fallback_only=True) assert type(image) == itk.Image[itk.RGBPixel[itk.UC], 2] try: image = itk.imread(filename, fallback_only=True) # Should never reach this point if test passes since an exception # is expected. raise Exception("`itk.imread()` fallback_only should have failed") except Exception as e: if str(e) == "pixel_type must be set when using the fallback_only option": pass else: raise e # test mesh read / write mesh = itk.meshread(mesh_filename) assert type(mesh) == itk.Mesh[itk.F, 3] mesh = itk.meshread(mesh_filename, itk.UC) assert type(mesh) == itk.Mesh[itk.UC, 3] mesh = itk.meshread(mesh_filename, itk.UC, fallback_only=True) assert type(mesh) == itk.Mesh[itk.F, 3] itk.meshwrite(mesh, sys.argv[4]) itk.meshwrite(mesh, sys.argv[4], compression=True) # test search res = itk.search("Index") assert res[0] == "Index" assert res[1] == "index" assert "ContinuousIndex" in res res = itk.search("index", True) assert "Index" not in res # test down_cast obj = itk.Object.cast(reader) # be sure that the reader is casted to itk::Object assert obj.__class__ == itk.Object down_casted = itk.down_cast(obj) assert down_casted == reader assert down_casted.__class__ == ReaderType # test setting the IO manually png_io = itk.PNGImageIO.New() assert png_io.GetFileName() == "" reader = itk.ImageFileReader.New(FileName=filename, ImageIO=png_io) reader.Update() assert png_io.GetFileName() == filename # test reading image series series_reader = itk.ImageSeriesReader.New(FileNames=[filename, filename]) series_reader.Update() assert series_reader.GetOutput().GetImageDimension() == 3 assert series_reader.GetOutput().GetLargestPossibleRegion().GetSize()[2] == 2 # test reading image series and check that dimension is not increased if # last dimension is 1. image_series = itk.Image[itk.UC, 3].New() image_series.SetRegions([10, 7, 1]) image_series.Allocate() image_series.FillBuffer(0) image_series3d_filename = os.path.join(sys.argv[5], "image_series_extras_py.mha") itk.imwrite(image_series, image_series3d_filename) series_reader = itk.ImageSeriesReader.New( FileNames=[image_series3d_filename, image_series3d_filename] ) series_reader.Update() assert series_reader.GetOutput().GetImageDimension() == 3 # test reading image series with itk.imread() image_series = itk.imread([filename, filename]) assert image_series.GetImageDimension() == 3 # Numeric series filename generation without any integer index. It is # only to produce an ITK object that users could set as an input to # `itk.ImageSeriesReader.New()` or `itk.imread()` and test that it works. numeric_series_filename = itk.NumericSeriesFileNames.New() numeric_series_filename.SetStartIndex(0) numeric_series_filename.SetEndIndex(3) numeric_series_filename.SetIncrementIndex(1) numeric_series_filename.SetSeriesFormat(filename) image_series = itk.imread(numeric_series_filename.GetFileNames()) number_of_files = len(numeric_series_filename.GetFileNames()) assert image_series.GetImageDimension() == 3 assert image_series.GetLargestPossibleRegion().GetSize()[2] == number_of_files # test reading image series with `itk.imread()` and check that dimension is # not increased if last dimension is 1. image_series = itk.imread([image_series3d_filename, image_series3d_filename]) assert image_series.GetImageDimension() == 3 # pipeline, auto_pipeline and templated class are tested in other files # BridgeNumPy # Images import numpy as np image = itk.imread(filename) arr = itk.array_from_image(image) arr.fill(1) assert np.any(arr != itk.array_from_image(image)) arr = itk.array_from_image(image) arr.fill(1) assert np.any(arr != itk.array_from_image(image)) view = itk.GetArrayViewFromImage(image) view.fill(1) assert np.all(view == itk.array_from_image(image)) image = itk.image_from_array(arr) image.FillBuffer(2) assert np.any(arr != itk.array_from_image(image)) image = itk.GetImageViewFromArray(arr) image.FillBuffer(2) assert np.all(arr == itk.array_from_image(image)) image = itk.image_from_array(arr, is_vector=True) assert image.GetImageDimension() == 2 image = itk.GetImageViewFromArray(arr, is_vector=True) assert image.GetImageDimension() == 2 arr = np.array([[1, 2, 3], [4, 5, 6]]).astype(np.uint8) assert arr.shape[0] == 2 assert arr.shape[1] == 3 assert arr[1, 1] == 5 image = itk.image_from_array(arr) arrKeepAxes = itk.array_from_image(image, keep_axes=True) assert arrKeepAxes.shape[0] == 3 assert arrKeepAxes.shape[1] == 2 assert arrKeepAxes[1, 1] == 4 arr = itk.array_from_image(image, keep_axes=False) assert arr.shape[0] == 2 assert arr.shape[1] == 3 assert arr[1, 1] == 5 arrKeepAxes = itk.GetArrayViewFromImage(image, keep_axes=True) assert arrKeepAxes.shape[0] == 3 assert arrKeepAxes.shape[1] == 2 assert arrKeepAxes[1, 1] == 4 arr = itk.GetArrayViewFromImage(image, keep_axes=False) assert arr.shape[0] == 2 assert arr.shape[1] == 3 assert arr[1, 1] == 5 arr = arr.copy() image = itk.image_from_array(arr) image2 = type(image).New() image2.Graft(image) del image # Delete image but pixel data should be kept in img2 image = itk.image_from_array(arr + 1) # Fill former memory if wrongly released assert np.array_equal(arr, itk.GetArrayViewFromImage(image2)) image2.SetPixel( [0] * image2.GetImageDimension(), 3 ) # For mem check in dynamic analysis # VNL Vectors v1 = itk.vnl_vector.D(2) v1.fill(1) v_np = itk.GetArrayFromVnlVector(v1) assert v1.get(0) == v_np[0] v_np[0] = 0 assert v1.get(0) != v_np[0] view = itk.GetArrayViewFromVnlVector(v1) assert v1.get(0) == view[0] view[0] = 0 assert v1.get(0) == view[0] # VNL Matrices m1 = itk.vnl_matrix.D(2, 2) m1.fill(1) m_np = itk.GetArrayFromVnlMatrix(m1) assert m1.get(0, 0) == m_np[0, 0] m_np[0, 0] = 0 assert m1.get(0, 0) != m_np[0, 0] view = itk.GetArrayViewFromVnlMatrix(m1) assert m1.get(0, 0) == view[0, 0] view[0, 0] = 0 assert m1.get(0, 0) == view[0, 0] arr = np.zeros([3, 3]) m_vnl = itk.GetVnlMatrixFromArray(arr) assert m_vnl(0, 0) == 0 m_vnl.put(0, 0, 3) assert m_vnl(0, 0) == 3 assert arr[0, 0] == 0 # ITK Matrix arr = np.zeros([3, 3], float) m_itk = itk.GetMatrixFromArray(arr) # Test snake case function m_itk = itk.matrix_from_array(arr) m_itk.SetIdentity() # Test that the numpy array has not changed,... assert arr[0, 0] == 0 # but that the ITK matrix has the correct value. assert m_itk(0, 0) == 1 arr2 = itk.GetArrayFromMatrix(m_itk) # Check that snake case function also works arr2 = itk.array_from_matrix(m_itk) # Check that the new array has the new value. assert arr2[0, 0] == 1 arr2[0, 0] = 2 # Change the array value,... assert arr2[0, 0] == 2 # and make sure that the matrix hasn't changed. assert m_itk(0, 0) == 1 # test .astype for itk.Image numpyImage = np.random.randint(0, 256, (8, 12, 5)).astype(np.uint8) image = itk.image_from_array(numpyImage, is_vector=False) cast = image.astype(np.uint8) assert cast == image (input_image_template, (input_pixel_type, input_image_dimension)) = itk.template(image) assert hasattr(itk.CastImageFilter, "IUC3IF3") for t in [ [itk.F, np.float32, "IUC3IF3"], [itk.SS, np.int16, "IUC3ISS3"], [itk.UI, np.uint32, "IUC3IUI3"], [np.float32, np.float32, "IUC3IF3"], ]: if hasattr(itk.CastImageFilter, t[2]): cast = image.astype(t[0]) (cast_image_template, (cast_pixel_type, cast_image_dimension)) = itk.template( cast ) assert ( cast_image_template == input_image_template and cast_image_dimension == input_image_dimension and cast.dtype == t[1] ) # test .astype for itk.VectorImage numpyImage = np.random.randint(0, 256, (8, 5, 3)).astype(np.float32) image = itk.image_from_array(numpyImage, is_vector=True) vectorimage = itk.cast_image_filter( Input=image, ttype=(type(image), itk.VectorImage[itk.F, 2]) ) cast = vectorimage.astype(np.float32) assert cast == vectorimage (vector_image_template, (vector_pixel_type, vector_image_dimension)) = itk.template( vectorimage ) for t in [ [itk.D, np.float64, "VIF2VID2"], [itk.SS, np.int16, "VIF2VISS2"], [itk.UI, np.uint32, "VIF2VIUI2"], [np.float64, np.float64, "VIF2VID2"], ]: if hasattr(itk.CastImageFilter, t[2]): cast = vectorimage.astype(t[0]) (cast_image_template, (cast_pixel_type, cast_image_dimension)) = itk.template( cast ) assert ( cast_image_template == vector_image_template and cast_image_dimension == vector_image_dimension and cast.dtype == t[1] ) # Test .astype for conversion between vector-like pixel types. components = 3 numpyImage = np.random.randint(0, 256, (12, 8, components)).astype(np.uint8) input_image = itk.image_from_array(numpyImage, is_vector=True) if type(input_image) == itk.Image[itk.RGBPixel[itk.UC], 2] and hasattr( itk.CastImageFilter, "IRGBUC2IVF32" ): output_pixel_type = itk.Vector[itk.F, components] output_image = input_image.astype(output_pixel_type) assert type(output_image) == itk.Image[output_pixel_type, 2] # xarray conversion try: import xarray as xr print("Testing xarray conversion") image = itk.imread(filename) image.SetSpacing((0.1, 0.2)) image.SetOrigin((30.0, 44.0)) theta = np.radians(30) cosine = np.cos(theta) sine = np.sin(theta) rotation = np.array(((cosine, -sine), (sine, cosine))) image.SetDirection(rotation) data_array = itk.xarray_from_image(image) assert data_array.dims[0] == "y" assert data_array.dims[1] == "x" assert data_array.dims[2] == "c" assert np.array_equal(data_array.values, itk.array_from_image(image)) assert len(data_array.coords["x"]) == 256 assert len(data_array.coords["y"]) == 256 assert len(data_array.coords["c"]) == 3 assert data_array.coords["x"][0] == 30.0 assert data_array.coords["x"][1] == 30.1 assert data_array.coords["y"][0] == 44.0 assert data_array.coords["y"][1] == 44.2 assert data_array.coords["c"][0] == 0 assert data_array.coords["c"][1] == 1 assert data_array.attrs["direction"][0, 0] == cosine assert data_array.attrs["direction"][0, 1] == sine assert data_array.attrs["direction"][1, 0] == -sine assert data_array.attrs["direction"][1, 1] == cosine round_trip = itk.image_from_xarray(data_array) assert np.array_equal(itk.array_from_image(round_trip), itk.array_from_image(image)) spacing = round_trip.GetSpacing() assert np.isclose(spacing[0], 0.1) assert np.isclose(spacing[1], 0.2) origin = round_trip.GetOrigin() assert np.isclose(origin[0], 30.0) assert np.isclose(origin[1], 44.0) direction = round_trip.GetDirection() assert np.isclose(direction(0, 0), cosine) assert np.isclose(direction(0, 1), -sine) assert np.isclose(direction(1, 0), sine) assert np.isclose(direction(1, 1), cosine) wrong_order = data_array.swap_dims({"y": "z"}) try: round_trip = itk.image_from_xarray(wrong_order) assert False except ValueError: pass empty_array = np.array([], dtype=np.uint8) empty_array.shape = (0, 0, 0) empty_image = itk.image_from_array(empty_array) empty_da = itk.xarray_from_image(empty_image) empty_image_round = itk.image_from_xarray(empty_da) except ImportError: print("xarray not imported. Skipping xarray conversion tests") pass # vtk conversion try: import vtk print("Testing vtk conversion") print("Testing vtk conversion") image = itk.image_from_array(np.random.rand(2, 3, 4)) vtk_image = itk.vtk_image_from_image(image) image_round = itk.image_from_vtk_image(vtk_image) assert np.array_equal(itk.origin(image), itk.origin(image_round)) assert np.array_equal(itk.spacing(image), itk.spacing(image_round)) assert np.array_equal(itk.size(image), itk.size(image_round)) assert np.array_equal( itk.array_view_from_image(image), itk.array_view_from_image(image_round) ) image = itk.image_from_array( np.random.rand(5, 4, 2).astype(np.float32), is_vector=True ) vtk_image = itk.vtk_image_from_image(image) image_round = itk.image_from_vtk_image(vtk_image) assert np.array_equal(itk.origin(image), itk.origin(image_round)) assert np.array_equal(itk.spacing(image), itk.spacing(image_round)) assert np.array_equal(itk.size(image), itk.size(image_round)) assert np.array_equal( itk.array_view_from_image(image), itk.array_view_from_image(image_round) ) except ImportError: print("vtk not imported. Skipping vtk conversion tests") pass
# XXX for development purposes only # # anneal Phe113 from 3k0n into partial omit map - if the protocol is working # properly, the sidechain should usually pop into the secondary conformation. from __future__ import division from mmtbx.building import disorder from mmtbx import building import libtbx.load_env import os def exercise(): import mmtbx.utils from iotbx.file_reader import any_file pdb_file = libtbx.env.find_in_repositories( relative_path="phenix_regression/pdb/CypA_refine_3.pdb", test=os.path.isfile) mtz_file = libtbx.env.find_in_repositories( relative_path="phenix_regression/reflection_files/3k0n.mtz", test=os.path.isfile) pdb_in = any_file(pdb_file) hierarchy = pdb_in.file_object.construct_hierarchy() xrs = pdb_in.file_object.xray_structure_simple() mtz_in = any_file(mtz_file) f_obs = mtz_in.file_server.miller_arrays[0].f_sq_as_f() flags = mtz_in.file_server.miller_arrays[-1] flags = flags.customized_copy(data=(flags.data()==0)) assert ((flags.data().count(True) / len(flags.data())) <= 0.1) f_obs, flags = f_obs.common_sets(other=flags) fmodel = mmtbx.utils.fmodel_simple( f_obs=f_obs, r_free_flags=flags, scattering_table="n_gaussian", xray_structures=[xrs]) fmodel.info().show_targets() selection = hierarchy.atom_selection_cache().selection( "chain A and resseq 111:115") two_fofc_map, fofc_map, = disorder.get_partial_omit_map( fmodel=fmodel, selection=selection, map_file_name="omit.mtz", partial_occupancy=0.7) xrs.shake_sites_in_place(0.1, selection=selection) sites_new = building.run_real_space_annealing( xray_structure=xrs, pdb_hierarchy=hierarchy, selection=selection, target_map=fofc_map, d_min=f_obs.d_min(), target_map_rsr=two_fofc_map, debug=True) hierarchy.atoms().set_xyz(sites_new) hierarchy.write_pdb_file("anneal.pdb", crystal_symmetry=xrs) print "wrote anneal.pdb and omit.mtz" if (__name__ == "__main__"): exercise()
/*Debemos lograr tomar Los numeros por ID , transformarlos a enteros (parseInt),realizar la operación correcta y mostrar el resto entre el dividendo y el divisor. ej.: "El resto es 0 ."*/ function SacarResto() { var dividendo; var divisor; var resultado; dividendo = document.getElementById("numeroDividendo").value; divisor = document.getElementById("numeroDivisor").value; dividendo = parseInt(dividendo); divisor = parseInt(divisor); resultado = dividendo % divisor; alert ("el resto es: " + resultado); }
const router = require("express").Router(); const { Client } = require("podcast-api"); require('dotenv').config({ path: './.env' }); const client = Client({ apiKey: process.env.API_KEY }); router.get("/popularPodcasts", async (req, res) => { try { client .fetchBestPodcasts({ region: "us", sort: "listen_score", safe_mode: 0, }) .then((response) => { // Get response json data here res.json(response.data.podcasts); }) .catch((error) => { console.log(error); }); } catch (err) { console.error(err); } }); router.get("/business", async (req, res) => { try { client .fetchBestPodcasts({ genre_id: 93, region: "us", sort: "listen_score", safe_mode: 0, }) .then((response) => { // Get response json data here res.json(response.data.podcasts); }) .catch((error) => { console.log(error); }); } catch (err) { console.error(err); } }); router.get("/comedy", async (req, res) => { try { client .fetchBestPodcasts({ genre_id: 133, region: "us", sort: "listen_score", safe_mode: 0, }) .then((response) => { // Get response json data here res.json(response.data.podcasts); }) .catch((error) => { console.log(error); }); } catch (err) { console.error(err); } }); router.get("/health", async (req, res) => { try { client .fetchBestPodcasts({ genre_id: 88, region: "us", sort: "listen_score", safe_mode: 0, }) .then((response) => { // Get response json data here res.json(response.data.podcasts); }) .catch((error) => { console.log(error); }); } catch (err) { console.error(err); } }); router.get("/news", (req, res) => { try { client .fetchBestPodcasts({ genre_id: 99, region: "us", sort: "listen_score", safe_mode: 0, }) .then((response) => { // Get response json data here res.json(response.data.podcasts); }) .catch((error) => { console.log(error); }); } catch (err) { console.error(err); } }); router.get("/popCulture", async (req, res) => { try { client .fetchBestPodcasts({ genre_id: 244, region: "us", sort: "listen_score", safe_mode: 0, }) .then((response) => { // Get response json data here res.json(response.data.podcasts); }) .catch((error) => { console.log(error); }); } catch (err) { console.error(err); } }); router.get("/trueCrime", async (req, res) => { try { client .fetchBestPodcasts({ genre_id: 135, region: "us", sort: "listen_score", safe_mode: 0, }) .then((response) => { // Get response json data here res.json(response.data.podcasts); }) .catch((error) => { console.log(error); }); } catch (err) { console.error(err); } }); // module.exports = router;
import _plotly_utils.basevalidators class CategoryarraysrcValidator(_plotly_utils.basevalidators.SrcValidator): def __init__( self, plotly_name='categoryarraysrc', parent_name='layout.polar.radialaxis', **kwargs ): super(CategoryarraysrcValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type='none', role='info', **kwargs )
# Copyright 2017 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ------------------------------------------------------------------------------ from __future__ import print_function import subprocess from setuptools import setup, find_packages conf_dir = "/etc/sawtooth" data_files = [ (conf_dir, ['cli.toml.example']) ] setup( name='sawtooth-cli', version=subprocess.check_output( ['../bin/get_version']).decode('utf-8').strip(), description='Sawtooth CLI', author='Hyperledger Sawtooth', url='https://github.com/hyperledger/sawtooth-core', packages=find_packages(), install_requires=[ 'colorlog', 'protobuf', 'sawtooth-sdk', 'toml', 'PyYAML', 'requests' ], data_files=data_files, entry_points={ 'console_scripts': [ 'sawadm = sawtooth_cli.sawadm:main_wrapper', 'sawnet = sawtooth_cli.sawnet:main_wrapper', 'sawset = sawtooth_cli.sawset:main_wrapper', 'sawtooth = sawtooth_cli.main:main_wrapper' ] })
from .StructBlockWithStyle import StructBlockWithStyle class JobsWholeBlock(StructBlockWithStyle): class Meta: template = 'common/blocks/jobs_whole_block.html' icon = 'fa-suitcase' label = 'Jobs Block'
import math import random import turtle import time window_length = 600 window_height = 600 turtles = 8 window = turtle.Screen() turtle.screensize(window_length, window_height) turtle.bgcolor("#bf15a9") turtle.penup() turtle.setpos(-100, 50) turtle.write("TURTLE RACE", font=("Arial",35,"bold")) turtle.penup() class racer(object): def __init__(self, color, pos): self.pos = pos self.color = color self.turt = turtle.Turtle() self.turt.shape('turtle') self.turt.color(color) self.turt.penup() self.turt.setpos(pos) self.turt.setheading(90) def move(self): r = random.randrange(1, 20) self.pos = (self.pos[0], self.pos[1] + r) self.turt.pendown() self.turt.forward(r) def reset(self): self.turt.penup() self.turt.setpos(self.pos) def setupFile(name, colors): file = open(name, 'w') for color in colors: file.write(color + ' 0 \n') file.close() def startGame(): tList = [] turtle.clearscreen() turtle.hideturtle() colors = ["red", "green", "blue", 'yellow', 'pink', 'orange', 'purple', 'black', 'grey'] start = -(window_length/2) + 20 for t in range(turtles): newPosX = start + t*(window_length)//turtles tList.append(racer(colors[t],(newPosX, -230))) tList[t].turt.showturtle() run = True while run: for t in tList: t.move() maxColor = [] maxDis = 0 for t in tList: if t.pos[1] > 230 and t.pos[1] > maxDis: maxDis = t.pos[1] maxColor = [] maxColor.append(t.color) elif t.pos[1] > 230 and t.pos[1] == maxDis: maxDis = t.pos[1] maxColor.append(t.color) if len(maxColor) > 0: run = False print('The winner is: ') for win in maxColor: print(win) oldScore = [] file = open('scores.txt', 'r') for line in file: l = line.split() color = l[0] score = l[1] oldScore.append([color, score]) file.close() file = open('scores.txt', 'w') for entry in oldScore: for winner in maxColor: if entry[0] == winner: entry[1] = int(entry[1]) + 1 file.write(str(entry[0]) + ' ' + str(entry[1]) + '\n') file.close() start = input('Would you like to play') startGame() while True: print('-----------------------------------') start = input('Would you like to play again') startGame() if __name__== "__main__": main()
from typing import Any, Dict, Type, Union, Optional from urllib.parse import quote import orjson from pydantic import Field, BaseModel from starlette.requests import Request from starlette.responses import JSONResponse from starlette.datastructures import URL class ORJSONResponse(JSONResponse): media_type = "application/json" def render(self, content: Any) -> bytes: return orjson.dumps(content) class HTTPException(Exception): def __init__( self, status_code: int, title: str, description: str, detail: Any = None, headers: Optional[Dict[str, Any]] = None, ) -> None: self.status_code = status_code self.detail = detail self.headers = headers or {} self.title = title self.description = description class HTTPRedirect(HTTPException): def __init__( self, url: Union[str, URL], status_code: int = 307, headers: dict = None, ) -> None: super().__init__( status_code=status_code, headers=headers, title="", description="" ) self.headers["location"] = quote(str(url), safe=":/%#?=@[]!$&'()*+,;") def response(model: Type = None, description: str = None) -> Dict[str, Any]: d: Dict[str, Any] = {} if model is not None: d["model"] = model if description: d["description"] = description return d class ErrorDetail(BaseModel): title: str description: str detail: Any = Field(..., description="can be anything") async def not_found_exception(request: Request): return HTTPException( status_code=404, title="Not Found", description=NotFoundDescription, detail={ "path": dict(request.path_params), "query": dict(request.query_params), }, ) NotFoundDescription = ( "resource you resource can't be found in the database or has been removed" )
import logging from pyvisdk.exceptions import InvalidArgumentError # This module is NOT auto-generated # Inspired by decompiled Java classes from vCenter's internalvim25stubs.jar # Unless states otherside, the methods and attributes were not used by esxcli, # and thus not tested log = logging.getLogger(__name__) def VimEsxCLIiscsiadapterparamgetiScsiParm(vim, *args, **kwargs): obj = vim.client.factory.create('{urn:vim25}VimEsxCLIiscsiadapterparamgetiScsiParm') # do some validation checking... if (len(args) + len(kwargs)) < 0: raise IndexError('Expected at least 1 arguments got: %d' % len(args)) required = [ ] optional = [ 'Current', 'Default', 'ID', 'Inherit', 'Max', 'Min', 'Name', 'Settable' ] for name, arg in zip(required + optional, args): setattr(obj, name, arg) for name, value in kwargs.items(): if name in required + optional: setattr(obj, name, value) else: raise InvalidArgumentError("Invalid argument: %s. Expected one of %s" % (name, ", ".join(required + optional))) return obj
import * as swcHelpers from "@swc/helpers"; var i, a, C = function() { "use strict"; swcHelpers.classCallCheck(this, C); }; (void 0)["a b"], C["c d"], i["a b"], a["a b"], ({ "a b": 1 })["a b"];
define({ "_widgetLabel": "Nacrtaj", "selectDrawMode": "Izaberi režim crtanja", "clear": "Izbriši", "point": "Tačka", "line": "Linija", "polyline": "Polilinija", "freehandPolyline": "Polilinija slobodnom rukom", "triangle": "Trougao", "extent": "Pravougaonik", "circle": "Krug", "ellipse": "Elipsa", "polygon": "Poligon", "freehandPolygon": "Poligon crtan slobodnom rukom", "text": "Tekst", "style": "Stil", "alpha": "Prozirnost", "width": "Širina", "size": "Veličina", "color": "Boja", "markerColor": "Boja označivača", "outlineColor": "Boja kontura", "lineColor": "Boja linije", "fillColor": "Boja ispune", "showMeasurements": "Prikaži mere", "showLocationMeasurement": "Prikaži merenje lokacije", "showAreaMeasurement": "Prikaži merenje površine", "showDistanceMeasurement": "Prikaži merenje rastojanja", "areaUnits": "Jedinice površine", "distanceUnits": "Jedinice rastojanja", "kilometers": "Kilometri", "miles": "Milje", "meters": "Metri", "feet": "Stope", "yards": "Jardi", "nauticalmiles": "Nautičke milje", "squareKilometers": "Kvadratni kilometri", "squareMiles": "Kvadratne milje", "acres": "Ari", "hectares": "Hektari", "squareMeters": "Kvadratni metri", "squareFeet": "Kvadratne stope", "squareYards": "Kvadratne jarde", "undo": "Opozovi radnju", "redo": "Ponovi radnju", "results": "Rezultati", "points": "Tačke", "lines": "Linije", "areas": "Površine", "locationLabel": "Lokacija: ${value}", "areaLabel": "Površina: ${value} ${unit}", "distanceLabel": "Rastojanje: ${value} ${unit}" });
from dynamikontrol import Module from flask import Flask, request, render_template module = Module() app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/change', methods=['POST']) def change(): is_locked = request.form['is_locked'] if is_locked == 'true': module.motor.angle(85) module.led.off(color='r') module.led.on(color='g') else: module.motor.angle(-45) module.led.off(color='g') module.led.on(color='r') return {'result': True} if __name__ == '__main__': app.run() module.disconnect()
import React from 'react'; import Dropdown from './Dropdown'; import Select from 'react-select'; import WebFont from 'webfontloader'; const gradients = [ {value: 'blue', label: 'Blue'}, {value: 'seafoam', label: 'Seafoam'}, {value: 'purple', label: 'Purple'}, {value: 'orange', label: 'Orange'}, {value: 'magenta', label: 'Magenta'}, {value: 'bubblegum', label: 'Bubblegum'}, {value:'sherbet', label: 'Sherbet'}, {value: 'violet', label: 'Violet'}, {value: 'forest', label: 'Forest'}, {value: 'dreamy', label: 'Dreamy'}, {value: 'wine', label: 'Wine'}, {value: 'fire', label: 'Fire'} ] class Header extends React.Component { constructor(props){ super(props); this.state = { fonts: [], categories: [], sansSerif: [], serif: [], handwriting: [], display: [], monospace: [], limit: 100 } } //Fetches Google Fonts by popularity and sets fonts state to array of all google font family names - limited to 100 by default componentDidMount(){ fetch('https://www.googleapis.com/webfonts/v1/webfonts?sort=popularity&key=AIzaSyDSHr-iLuL_U335Y437hDvqNFSuv1jAkSI') .then(res => { return res.json(); }).then((JSON) => { this.setState({ fonts: JSON.items.map(item => item.family), categories: JSON.items.map(item => item.category) }); const sansSerifFonts = []; const serifFonts = []; const handwritingFonts = []; const displayFonts = []; const monospaceFonts = []; //iterate through fonts array and categorize fonts by type (limited to 100 by default) for(var i=0; i < this.state.limit; i++){ if(this.state.categories[i] === "sans-serif"){ sansSerifFonts.push(this.state.fonts[i]); } else if(this.state.categories[i] === "serif"){ serifFonts.push(this.state.fonts[i]); } else if(this.state.categories[i] === "handwriting"){ handwritingFonts.push(this.state.fonts[i]); } else if(this.state.categories[i] === "display"){ displayFonts.push(this.state.fonts[i]); } else if(this.state.categories[i] === "monospace"){ monospaceFonts.push(this.state.fonts[i]); } } for(let i=0; i < this.state.limit; i++){ WebFont.load({ //loads webfont from Google google: { families: [this.state.fonts[i]] } }); } this.setState({ sansSerif: sansSerifFonts, serif: serifFonts, handwriting: handwritingFonts, display: displayFonts, monospace: monospaceFonts }) }) console.log(this.state.fonts); } render(){ const customStyles = { option: (styles, { data }) => { return { ...styles, fontFamily: data.fontname, outline: 'none' }; } } const sansSerifFonts = this.state.sansSerif.map(family => ({value: family, label: family, fontname: family})); const serifFonts = this.state.serif.map(family => ({value: family, label: family, fontname: family})); const displayFonts = this.state.display.map(family => ({value: family, label: family, fontname: family})); const handwritingFonts = this.state.handwriting.map(family => ({value: family, label: family, fontname: family})); const monospaceFonts = this.state.monospace.map(family => ({value: family, label: family, fontname: family})); const groupedOptions = [ { label: 'Sans-Serif', options: sansSerifFonts }, { label: 'Serif', options: serifFonts }, { label: 'Display', options: displayFonts }, { label: 'Handwriting', options: handwritingFonts }, { label: 'Monospace', options: monospaceFonts } ]; return( <header> <div className="form-container"> <Dropdown textType="Header" onChange={this.props.onHeaderChange} value={this.props.headerLabel} options={groupedOptions} styles={customStyles}/> <Dropdown textType="Body" onChange={this.props.onBodyChange} value={this.props.bodyLabel} options={groupedOptions} styles={customStyles} open={true}/> </div> <form className="form-container"> <div> <label>Choose a Background Gradient:</label> <Select value={this.props.value} onChange={this.props.onGradientChange} options={gradients} /> </div> </form> </header> ); } } export default Header;
from django.contrib.auth import get_user_model from django.test import TestCase from django_dynamic_fixture import get from readthedocs.builds.constants import EXTERNAL from readthedocs.builds.models import Build, Version from readthedocs.projects.constants import PRIVATE, PUBLIC from readthedocs.projects.models import HTMLFile, Project User = get_user_model() class TestBuildManagerBase(TestCase): def setUp(self): self.user = get(User) self.another_user = get(User) self.project = get( Project, privacy_level=PUBLIC, users=[self.user], main_language_project=None, versions=[], ) self.version_public = get( Version, privacy_level=PUBLIC, project=self.project, active=True, slug='version_public' ) self.build_public = get( Build, version=self.version_public, project=self.project, ) self.version_public_external = get( Version, privacy_level=PUBLIC, project=self.project, active=True, type=EXTERNAL, slug='version_public_external' ) self.build_public_external = get( Build, version=self.version_public_external, project=self.project, ) self.version_private = get( Version, privacy_level=PRIVATE, project=self.project, active=True, slug='version_private' ) self.build_private = get( Build, version=self.version_private, project=self.project, ) self.version_private_external = get( Version, privacy_level=PRIVATE, project=self.project, active=True, type=EXTERNAL, slug='version_private_external' ) self.build_private_external = get( Build, version=self.version_private_external, project=self.project, ) self.another_project = get( Project, privacy_level=PUBLIC, users=[self.another_user], main_language_project=None, versions=[], ) self.another_version_public = get( Version, privacy_level=PUBLIC, project=self.another_project, active=True, slug='another_version_public' ) self.another_build_public = get( Build, version=self.another_version_public, project=self.another_project, ) self.another_version_public_external = get( Version, privacy_level=PUBLIC, project=self.another_project, active=True, type=EXTERNAL, slug='another_version_public_external' ) self.another_build_public_external = get( Build, version=self.another_version_public_external, project=self.another_project, ) self.another_version_private = get( Version, privacy_level=PRIVATE, project=self.another_project, active=True, slug='another_version_private' ) self.another_build_private = get( Build, version=self.another_version_private, project=self.another_project, ) self.another_version_private_external = get( Version, privacy_level=PRIVATE, project=self.another_project, active=True, type=EXTERNAL, slug='another_version_private_external' ) self.another_build_private_external = get( Build, version=self.another_version_private_external, project=self.another_project, ) self.shared_project = get( Project, privacy_level=PUBLIC, users=[self.user, self.another_user], main_language_project=None, versions=[], ) self.shared_version_public = get( Version, privacy_level=PUBLIC, project=self.shared_project, active=True, slug='shared_version_public' ) self.shared_build_public = get( Build, version=self.shared_version_public, project=self.shared_project, ) self.shared_version_public_external = get( Version, privacy_level=PUBLIC, project=self.shared_project, active=True, type=EXTERNAL, slug='shared_version_public_external' ) self.shared_build_public_external = get( Build, version=self.shared_version_public_external, project=self.shared_project, ) self.shared_version_private = get( Version, privacy_level=PRIVATE, project=self.shared_project, active=True, slug='shared_version_private' ) self.shared_build_private = get( Build, version=self.shared_version_private, project=self.shared_project, ) self.shared_version_private_external = get( Version, privacy_level=PRIVATE, project=self.shared_project, active=True, type=EXTERNAL, slug='shared_version_private_external' ) self.shared_build_private_external = get( Build, version=self.shared_version_private_external, project=self.shared_project, ) class TestInternalBuildManager(TestBuildManagerBase): """ Queries using Internal Manager should only include Internal Version builds. It will exclude pull/merge request Version builds from the queries and only include BRANCH, TAG, UNKNOWN type Versions. """ def test_all(self): query = Build.internal.all() internal_builds = { self.build_private, self.another_build_private, self.shared_build_private, self.build_public, self.another_build_public, self.shared_build_public, } self.assertEqual(query.count(), len(internal_builds)) self.assertEqual(set(query), internal_builds) def test_public(self): query = Build.internal.public() public_internal_builds = { self.build_public, self.another_build_public, self.shared_build_public, } self.assertEqual(query.count(), len(public_internal_builds)) self.assertEqual(set(query), public_internal_builds) def test_public_user(self): query = Build.internal.public(user=self.user) builds = { self.build_private, self.shared_build_private, self.build_public, self.shared_build_public, self.another_build_public, } self.assertEqual(query.count(), len(builds)) self.assertEqual(set(query), builds) def test_public_project(self): query = Build.internal.public(user=self.user, project=self.project) builds = { self.build_private, self.build_public, } self.assertEqual(query.count(), len(builds)) self.assertEqual(set(query), builds) def test_api(self): query = Build.internal.api(user=self.user) builds = { self.build_private, self.shared_build_private, self.build_public, self.shared_build_public, self.another_build_public, } self.assertEqual(query.count(), len(builds)) self.assertEqual(set(query), builds) def test_api_user(self): query = Build.internal.api(user=self.user, detail=False) builds = { self.build_private, self.shared_build_private, self.build_public, self.shared_build_public, } self.assertEqual(query.count(), len(builds)) self.assertEqual(set(query), builds) class TestExternalBuildManager(TestBuildManagerBase): """ Queries using External Manager should only include External Version builds. It will only include pull/merge request Version builds in the queries. """ def test_all(self): query = Build.external.all() external_builds = { self.build_private_external, self.another_build_private_external, self.shared_build_private_external, self.build_public_external, self.another_build_public_external, self.shared_build_public_external, } self.assertEqual(query.count(), len(external_builds)) self.assertEqual(set(query), external_builds) def test_public(self): query = Build.external.public() public_external_builds = { self.build_public_external, self.another_build_public_external, self.shared_build_public_external, } self.assertEqual(query.count(), len(public_external_builds)) self.assertEqual(set(query), public_external_builds) def test_public_user(self): query = Build.external.public(user=self.user) builds = { self.build_private_external, self.shared_build_private_external, self.build_public_external, self.another_build_public_external, self.shared_build_public_external, } self.assertEqual(query.count(), len(builds)) self.assertEqual(set(query), builds) def test_public_project(self): query = Build.external.public(user=self.user, project=self.project) builds = { self.build_private_external, self.build_public_external, } self.assertEqual(query.count(), len(builds)) self.assertEqual(set(query), builds) def test_api(self): query = Build.external.api(user=self.user) builds = { self.build_private_external, self.shared_build_private_external, self.build_public_external, self.another_build_public_external, self.shared_build_public_external, } self.assertEqual(query.count(), len(builds)) self.assertEqual(set(query), builds) def test_api_user(self): query = Build.external.api(user=self.user, detail=False) builds = { self.build_private_external, self.shared_build_private_external, self.build_public_external, self.shared_build_public_external, } self.assertEqual(query.count(), len(builds)) self.assertEqual(set(query), builds) class TestHTMLFileManager(TestCase): fixtures = ['test_data', 'eric'] def setUp(self): self.user = User.objects.create(username='test_user', password='test') self.client.login(username='test_user', password='test') self.pip = Project.objects.get(slug='pip') # Create a External Version. ie: pull/merge request Version. self.external_version = get( Version, project=self.pip, active=True, type=EXTERNAL, privacy_level=PUBLIC ) self.internal_version = get( Version, project=self.pip, active=True, privacy_level=PUBLIC ) self.external_html_file = HTMLFile.objects.create( project=self.pip, version=self.external_version, name='file.html', path='file.html', commit='1234567890abcdef', ) self.internal_html_file = HTMLFile.objects.create( project=self.pip, version=self.internal_version, name='file.html', path='file.html', commit='1234567890abcdef', ) def test_internal_html_file_queryset(self): """ It will exclude pull/merge request Version html files from the queries and only include BRANCH, TAG, UNKNOWN type Version files. """ self.assertNotIn(self.external_html_file, HTMLFile.objects.internal()) self.assertIn(self.internal_html_file, HTMLFile.objects.internal()) def test_external_html_file_queryset(self): """ It will only include pull/merge request Version html files in the queries. """ self.assertNotIn(self.internal_html_file, HTMLFile.objects.external()) self.assertIn(self.external_html_file, HTMLFile.objects.external())
#ifndef SHARED_POINCARE_HELPERS_H #define SHARED_POINCARE_HELPERS_H #include <apps/global_preferences.h> #include <poincare/preferences.h> #include <poincare/print_float.h> #include <poincare/expression.h> namespace Shared { namespace PoincareHelpers { inline Poincare::Layout CreateLayout(const Poincare::Expression e) { Poincare::Preferences * preferences = Poincare::Preferences::sharedPreferences(); return e.createLayout(preferences->displayMode(), preferences->numberOfSignificantDigits()); } template <class T> inline int ConvertFloatToText(T d, char * buffer, int bufferSize, int numberOfSignificantDigits) { return Poincare::PrintFloat::ConvertFloatToText(d, buffer, bufferSize, Poincare::PrintFloat::glyphLengthForFloatWithPrecision(numberOfSignificantDigits), numberOfSignificantDigits, Poincare::Preferences::sharedPreferences()->displayMode()).CharLength; } template <class T> inline int ConvertFloatToTextWithDisplayMode(T d, char * buffer, int bufferSize, int numberOfSignificantDigits, Poincare::Preferences::PrintFloatMode displayMode) { return Poincare::PrintFloat::ConvertFloatToText(d, buffer, bufferSize, Poincare::PrintFloat::glyphLengthForFloatWithPrecision(numberOfSignificantDigits), numberOfSignificantDigits, displayMode).CharLength; } template <class T> // Return the nearest number from t's representation with given precision. T ValueOfFloatAsDisplayed(T t, int precision, Poincare::Context * context); inline int Serialize(const Poincare::Expression e, char * buffer, int bufferSize, int numberOfSignificantDigits = Poincare::PrintFloat::k_numberOfStoredSignificantDigits) { return e.serialize(buffer, bufferSize, Poincare::Preferences::sharedPreferences()->displayMode(), numberOfSignificantDigits); } template <class T> inline Poincare::Expression Approximate(const Poincare::Expression e, Poincare::Context * context) { Poincare::Preferences * preferences = Poincare::Preferences::sharedPreferences(); Poincare::Preferences::ComplexFormat complexFormat = Poincare::Expression::UpdatedComplexFormatWithExpressionInput(preferences->complexFormat(), e, context); return e.approximate<T>(context, complexFormat, preferences->angleUnit()); } template <class T> inline T ApproximateToScalar(const Poincare::Expression e, Poincare::Context * context) { Poincare::Preferences * preferences = Poincare::Preferences::sharedPreferences(); Poincare::Preferences::ComplexFormat complexFormat = Poincare::Expression::UpdatedComplexFormatWithExpressionInput(preferences->complexFormat(), e, context); return e.approximateToScalar<T>(context, complexFormat, preferences->angleUnit()); } template <class T> inline T ApproximateWithValueForSymbol(const Poincare::Expression e, const char * symbol, T x, Poincare::Context * context) { Poincare::Preferences * preferences = Poincare::Preferences::sharedPreferences(); Poincare::Preferences::ComplexFormat complexFormat = Poincare::Expression::UpdatedComplexFormatWithExpressionInput(preferences->complexFormat(), e, context); return e.approximateWithValueForSymbol<T>(symbol, x, context, complexFormat, preferences->angleUnit()); } template <class T> inline T ApproximateToScalar(const char * text, Poincare::Context * context, Poincare::ExpressionNode::SymbolicComputation symbolicComputation = Poincare::ExpressionNode::SymbolicComputation::ReplaceAllSymbolsWithDefinitionsOrUndefined) { Poincare::Preferences * preferences = Poincare::Preferences::sharedPreferences(); Poincare::Preferences::ComplexFormat complexFormat = Poincare::Expression::UpdatedComplexFormatWithTextInput(preferences->complexFormat(), text); return Poincare::Expression::ApproximateToScalar<T>(text, context, complexFormat, preferences->angleUnit(), GlobalPreferences::sharedGlobalPreferences()->unitFormat(), symbolicComputation); } inline Poincare::Expression ParseAndSimplify(const char * text, Poincare::Context * context, Poincare::ExpressionNode::SymbolicComputation symbolicComputation = Poincare::ExpressionNode::SymbolicComputation::ReplaceAllDefinedSymbolsWithDefinition) { Poincare::Preferences * preferences = Poincare::Preferences::sharedPreferences(); Poincare::Preferences::ComplexFormat complexFormat = Poincare::Expression::UpdatedComplexFormatWithTextInput(preferences->complexFormat(), text); return Poincare::Expression::ParseAndSimplify(text, context, complexFormat, preferences->angleUnit(), GlobalPreferences::sharedGlobalPreferences()->unitFormat(), symbolicComputation); } inline void Simplify(Poincare::Expression * e, Poincare::Context * context, Poincare::ExpressionNode::ReductionTarget target, Poincare::ExpressionNode::SymbolicComputation symbolicComputation = Poincare::ExpressionNode::SymbolicComputation::ReplaceAllDefinedSymbolsWithDefinition, Poincare::ExpressionNode::UnitConversion unitConversion = Poincare::ExpressionNode::UnitConversion::Default) { Poincare::Preferences * preferences = Poincare::Preferences::sharedPreferences(); Poincare::Preferences::ComplexFormat complexFormat = Poincare::Expression::UpdatedComplexFormatWithExpressionInput(preferences->complexFormat(), *e, context); *e = e->simplify(Poincare::ExpressionNode::ReductionContext(context, complexFormat, preferences->angleUnit(), GlobalPreferences::sharedGlobalPreferences()->unitFormat(), target, symbolicComputation, unitConversion)); } inline void Reduce(Poincare::Expression * e, Poincare::Context * context, Poincare::ExpressionNode::ReductionTarget target, Poincare::ExpressionNode::SymbolicComputation symbolicComputation = Poincare::ExpressionNode::SymbolicComputation::ReplaceAllDefinedSymbolsWithDefinition, Poincare::ExpressionNode::UnitConversion unitConversion = Poincare::ExpressionNode::UnitConversion::Default) { Poincare::Preferences * preferences = Poincare::Preferences::sharedPreferences(); Poincare::Preferences::ComplexFormat complexFormat = Poincare::Expression::UpdatedComplexFormatWithExpressionInput(preferences->complexFormat(), *e, context); *e = e->reduce(Poincare::ExpressionNode::ReductionContext(context, complexFormat, preferences->angleUnit(), GlobalPreferences::sharedGlobalPreferences()->unitFormat(), target, symbolicComputation, unitConversion)); } inline void ReduceAndRemoveUnit(Poincare::Expression * e, Poincare::Context * context, Poincare::ExpressionNode::ReductionTarget target, Poincare::Expression * unit, Poincare::ExpressionNode::SymbolicComputation symbolicComputation = Poincare::ExpressionNode::SymbolicComputation::ReplaceAllDefinedSymbolsWithDefinition, Poincare::ExpressionNode::UnitConversion unitConversion = Poincare::ExpressionNode::UnitConversion::Default) { PoincareHelpers::Reduce(e, context, target, symbolicComputation, unitConversion); *e = e->removeUnit(unit); } inline void ParseAndSimplifyAndApproximate(const char * text, Poincare::Expression * simplifiedExpression, Poincare::Expression * approximateExpression, Poincare::Context * context, Poincare::ExpressionNode::SymbolicComputation symbolicComputation = Poincare::ExpressionNode::SymbolicComputation::ReplaceAllDefinedSymbolsWithDefinition) { Poincare::Preferences * preferences = Poincare::Preferences::sharedPreferences(); Poincare::Preferences::ComplexFormat complexFormat = Poincare::Expression::UpdatedComplexFormatWithTextInput(preferences->complexFormat(), text); Poincare::Expression::ParseAndSimplifyAndApproximate(text, simplifiedExpression, approximateExpression, context, complexFormat, preferences->angleUnit(), GlobalPreferences::sharedGlobalPreferences()->unitFormat(), symbolicComputation); } inline typename Poincare::Coordinate2D<double> NextMinimum(const Poincare::Expression e, const char * symbol, double start, double max, Poincare::Context * context, double relativePrecision, double minimalStep, double maximalStep) { Poincare::Preferences * preferences = Poincare::Preferences::sharedPreferences(); Poincare::Preferences::ComplexFormat complexFormat = Poincare::Expression::UpdatedComplexFormatWithExpressionInput(preferences->complexFormat(), e, context); return e.nextMinimum(symbol, start, max, context, complexFormat, preferences->angleUnit(), relativePrecision, minimalStep, maximalStep); } inline typename Poincare::Coordinate2D<double> NextMaximum(const Poincare::Expression e, const char * symbol, double start, double max, Poincare::Context * context, double relativePrecision, double minimalStep, double maximalStep) { Poincare::Preferences * preferences = Poincare::Preferences::sharedPreferences(); Poincare::Preferences::ComplexFormat complexFormat = Poincare::Expression::UpdatedComplexFormatWithExpressionInput(preferences->complexFormat(), e, context); return e.nextMaximum(symbol, start, max, context, complexFormat, preferences->angleUnit(), relativePrecision, minimalStep, maximalStep); } inline double NextRoot(const Poincare::Expression e, const char * symbol, double start, double max, Poincare::Context * context, double relativePrecision, double minimalStep, double maximalStep) { Poincare::Preferences * preferences = Poincare::Preferences::sharedPreferences(); Poincare::Preferences::ComplexFormat complexFormat = Poincare::Expression::UpdatedComplexFormatWithExpressionInput(preferences->complexFormat(), e, context); return e.nextRoot(symbol, start, max, context, complexFormat, preferences->angleUnit(), relativePrecision, minimalStep, maximalStep); } inline typename Poincare::Coordinate2D<double> NextIntersection(const Poincare::Expression e, const char * symbol, double start, double max, Poincare::Context * context, const Poincare::Expression expression, double relativePrecision, double minimalStep, double maximalStep) { Poincare::Preferences * preferences = Poincare::Preferences::sharedPreferences(); Poincare::Preferences::ComplexFormat complexFormat = Poincare::Expression::UpdatedComplexFormatWithExpressionInput(preferences->complexFormat(), e, context); complexFormat = Poincare::Expression::UpdatedComplexFormatWithExpressionInput(complexFormat, expression, context); return e.nextIntersection(symbol, start, max, context, complexFormat, preferences->angleUnit(), expression, relativePrecision, minimalStep, maximalStep); } inline bool equalOrBothNan(double a, double b) { return a == b || (std::isnan(a) && std::isnan(b)); } } } #endif
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format */ import React from 'react'; import clsx from 'clsx'; import Layout from '@theme/Layout'; import Link from '@docusaurus/Link'; import useDocusaurusContext from '@docusaurus/useDocusaurusContext'; import useBaseUrl from '@docusaurus/useBaseUrl'; import styles from './styles.module.css'; const features = [ { title: <>Reduces human bias</>, imageUrl: 'img/take_control.svg', description: ( <> <ul> <li>Automated hyperparameter optimization with evolutionary algorithms from Facebook's AI library <a href="https://facebookresearch.github.io/nevergrad">Nevergrad</a></li> <li>Ridge regression with cross-validation to regularize multi-collinearity and prevent overfitting</li> <li>Facebook's <a href="https://facebook.github.io/prophet/">Prophet</a> library to automatically decompose the trend, seasonality and holidays patterns</li> </ul> </> ), }, { title: <>Aligns with the ground-truth</>, imageUrl: 'img/calibrate.svg', description: ( <> <ul> <li> It calibrates models based on ground-truth methodologies (Geo-based, Facebook lift, MTA, etc.) </li> <li> Facebook <a href="https://facebookresearch.github.io/nevergrad">Nevergrad</a>'s multi-objective optimization minimizing the error between MMM prediction and ground-truth </li> </ul> </> ), }, { title: <>Enables actionable decision making</>, imageUrl: 'img/focus_on_what_matters.svg', description: ( <> <ul> <li> Budget allocator using a gradient-based constrained non-linear solver to maximize the outcome by reallocating budgets </li> <li> Enables frequent modeling outcomes due to stronger automation </li> <li> Allows intuitive model comparisons via automatically generated model one-pagers </li> </ul> </> ), }, { title: <>Private by Design</>, imageUrl: 'img/security.svg', description: ( <> <ul> <li> Privacy friendly, with no requirement for PII or Individual log level data </li> <li>Not dependent on Cookies or Pixel data</li> </ul> </> ), }, ]; function Feature({ imageUrl, title, description }) { const imgUrl = useBaseUrl(imageUrl); return ( <div className={clsx('col col--6', styles.feature)}> {imgUrl && ( <div className="text--center"> <img className={styles.featureImage} src={imgUrl} alt={title} /> </div> )} <h3>{title}</h3> <p className={styles.descriptionSectionText}>{description}</p> </div> ); } function Home() { const context = useDocusaurusContext(); const { siteConfig = {} } = context; return ( <Layout description={siteConfig.tagline} > <header className={clsx('hero hero--primary', styles.heroBanner)}> <div className="container"> <h1 className={clsx('hero__title', styles.heroTitle)}>{siteConfig.title}</h1> <p className={clsx('hero__subtitle', styles.heroSubtitle)}>Robyn is an automated Marketing Mix Modeling (MMM) open source code.</p> <div className={styles.buttons}> <Link className={clsx( 'button button--secondary button--lg' )} to={useBaseUrl('docs/quick-start/')} > Install Robyn </Link> <Link className={clsx( 'button button--outline button--secondary button--lg' )} to={useBaseUrl('docs/demo-R-script/')} > Get Started </Link> </div> </div> </header> <main> <div className="padding-vert--xl"> <div className="container"> <div className="row"> <div className={clsx('col col--6', styles.descriptionSection)}> <h2>Open Source and Automated Marketing Mix Modeling</h2> <p className={styles.descriptionSectionText}>{siteConfig.tagline}</p> </div> <div className="col col--6"> <iframe width="100%" height="400" src="https://www.youtube.com/embed/8SyKRpsXn44" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen /> </div> </div> </div> </div> {features && features.length > 0 && ( <section className={clsx('padding-vert--xl', styles.features)}> <div className="container"> <div className="row"> {features.map(({ title, imageUrl, description }) => ( <Feature key={title} title={title} imageUrl={imageUrl} description={description} /> ))} </div> </div> </section> )} <div className="container padding-vert--xl"> <div className="row"> <div className="col col--6 col--offset-3 text--center"> <h2>Robyn Code Walkthrough Video</h2> <p className={styles.descriptionSectionText}>Please watch this walkthrough video to understand better how the code works</p> <iframe title="Robyn walkthrough video" width="560" height="315" src="https://www.youtube.com/embed/aIiadcfL4uw" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen /> </div> </div> </div> </main> </Layout> ); } export default Home;
import React, { Component } from 'react' import Kitten from '../components/Kitten' import { connect } from 'react-redux' import { fetchKittens } from '../actions/kittens' import KittenForm from './KittenForm' class Kittens extends Component { componentDidMount(){ console.log("componentDidMount") this.props.fetchKittens() } handleLoading = () => { if (this.props.loading) { return ( <div> <div className="kittens"> <div className="home-text"> <h2>Give a Kitten a Forever Home</h2> <h1>Knittin' Kitten Foster</h1> <p><a href="https://orphankittenclub.org/donate/">Donate</a></p> </div> </div> <div><h2>Herding the kittens... one moment please!</h2></div> </div> ) } else { return ( <> <div className="kittens"> <div className="home-text"> <h2>Give a Kitten a Forever Home</h2> <h1>Knittin' Kitten Foster</h1> <p><a href="https://orphankittenclub.org/donate/">Donate</a></p> </div> </div> <h2>Our Current Kittens</h2> <div className="wrapper"> {/* Filter/Search Component */} {this.props.kittens.map((kitten => { return ( <Kitten key={kitten.id} kitten={kitten} /> )} ))} </div> <KittenForm/> </> ) } } render() { return ( <div> {this.handleLoading()} </div> ) } } const mapStateToProps = state => { return { kittens: state.kittenReducer.kittens, loading: state.kittenReducer.loading } } export default connect(mapStateToProps, { fetchKittens })(Kittens)
""" Django settings for TukaTuka project. Generated by 'django-admin startproject' using Django 2.0.3. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'iat12)gi3&ag8uilpcjsml5^8igdwvq$9)wde8lkn%l322x=-w' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app', 'phonenumber_field', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'TukaTuka.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'TukaTuka.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'TukaTuka', 'USER': 'rustam', 'PASSWORD': 'EluTingol', 'HOST': '', 'PORT': '3306', } } # AUTH_USER_MODEL = 'app.Company' # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = False # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/' if DEBUG: INTERNAL_IPS = ('127.0.0.1',) MIDDLEWARE += ( 'debug_toolbar.middleware.DebugToolbarMiddleware', ) INSTALLED_APPS += ( 'debug_toolbar', ) DEBUG_TOOLBAR_PANELS = [ 'debug_toolbar.panels.versions.VersionsPanel', 'debug_toolbar.panels.timer.TimerPanel', 'debug_toolbar.panels.settings.SettingsPanel', 'debug_toolbar.panels.headers.HeadersPanel', 'debug_toolbar.panels.request.RequestPanel', 'debug_toolbar.panels.sql.SQLPanel', 'debug_toolbar.panels.staticfiles.StaticFilesPanel', 'debug_toolbar.panels.templates.TemplatesPanel', 'debug_toolbar.panels.cache.CachePanel', 'debug_toolbar.panels.signals.SignalsPanel', 'debug_toolbar.panels.logging.LoggingPanel', 'debug_toolbar.panels.redirects.RedirectsPanel', ] DEBUG_TOOLBAR_CONFIG = { 'INTERCEPT_REDIRECTS': False, }
import React from 'react' const Header = ({setSearchValue})=>{ return( <div className='header-container'> <div className='header-inner'> <h1>The Hacker News</h1> <input className='header-search' placeholder='Search...' onChange={(e)=>setSearchValue(e.target.value)}/> </div> </div> ) } export default Header;
"""Test PyPlumIO base frame.""" from typing import Tuple from unittest.mock import patch import pytest from pyplumio.constants import BROADCAST_ADDRESS, ECONET_ADDRESS from pyplumio.frames import ( ECONET_TYPE, ECONET_VERSION, HEADER_SIZE, Request, Response, requests, responses, ) @pytest.fixture(name="request_") def fixture_request_() -> Request: """Return program version request.""" return Request(frame_type=requests.ProgramVersion.frame_type) @pytest.fixture(name="response") def fixture_response() -> Response: """Return program version response.""" return Response(frame_type=responses.ProgramVersion.frame_type) @pytest.fixture(name="frames") def fixture_frames(request_: Request, response: Response) -> Tuple[Request, Response]: """Return request and response frames as a tuple.""" return (request_, response) @pytest.fixture(name="types") def fixture_types() -> Tuple[int, int]: """Return request and response types as a tuple.""" return (requests.ProgramVersion.frame_type, responses.ProgramVersion.frame_type) def test_passing_frame_type( frames: Tuple[Request, Response], types: Tuple[int, int] ) -> None: """Test getting frame type.""" for index, frame in enumerate(frames): assert frame.frame_type == types[index] def test_default_params(frames: Tuple[Request, Response]) -> None: """Test frame attributes.""" for frame in frames: assert frame.recipient == BROADCAST_ADDRESS assert frame.message == b"" assert frame.sender == ECONET_ADDRESS assert frame.sender_type == ECONET_TYPE assert frame.econet_version == ECONET_VERSION def test_frame_length_without_data(frames: Tuple[Request, Response]) -> None: """Test frame length without any data.""" for frame in frames: assert frame.length == HEADER_SIZE + 3 assert len(frame) == HEADER_SIZE + 3 def test_frame_get_data_without_data(frames: Tuple[Request, Response]) -> None: """Test that parse_message called when frame data is not set.""" for frame in frames: with patch( "pyplumio.frames." + frame.__class__.__name__ + ".parse_message" ) as mock_parse_message: assert frame.data is None mock_parse_message.assert_called_once() def test_get_header(frames: Tuple[Request, Response]) -> None: """Test getting frame header as bytes.""" for frame in frames: assert frame.header == b"\x68\x0a\x00\x00\x56\x30\x05" def test_base_class_with_message() -> None: """Test base request class with message.""" frame = Request( frame_type=requests.ProgramVersion.frame_type, message=bytearray(b"\xB0\x0B") ) assert frame.message == b"\xB0\x0B" def test_to_bytes() -> None: """Test conversion to bytes.""" frame = Request( frame_type=requests.ProgramVersion.frame_type, message=bytearray(b"\xB0\x0B") ) assert frame.bytes == b"\x68\x0C\x00\x00\x56\x30\x05\x40\xB0\x0B\xFC\x16" def test_to_hex() -> None: """Test conversion to hex.""" frame = Request( frame_type=requests.ProgramVersion.frame_type, message=bytearray(b"\xB0\x0B") ) hex = ["68", "0C", "00", "00", "56", "30", "05", "40", "B0", "0B", "FC", "16"] assert frame.hex == hex def test_equality() -> None: """Test equality check.""" assert responses.ProgramVersion() == responses.ProgramVersion() def test_request_repr(request_: Request) -> None: """Test serialiazible request representation.""" repr_ = """Request( type = 64, recipient = 0, message = bytearray(b''), sender = 86, sender_type = 48, econet_version = 5, data = None ) """.strip() assert repr(request_) == repr_ def test_response_repr(response: Response) -> None: """Test serialiazible response representation.""" repr_ = """Response( type = 192, recipient = 0, message = bytearray(b''), sender = 86, sender_type = 48, econet_version = 5, data = None ) """.strip() assert repr(response) == repr_
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import numpy as np from op_test import OpTest import paddle import paddle.fluid.core as core from paddle.static import program_guard, Program from paddle.fluid.framework import _test_eager_guard import os def check_randperm_out(n, data_np): assert isinstance(data_np, np.ndarray), \ "The input data_np should be np.ndarray." gt_sorted = np.arange(n) out_sorted = np.sort(data_np) return list(gt_sorted == out_sorted) def error_msg(data_np): return "The sorted ground truth and sorted out should " + \ "be equal, out = " + str(data_np) def convert_dtype(dtype_str): dtype_str_list = ["int32", "int64", "float32", "float64"] dtype_num_list = [ core.VarDesc.VarType.INT32, core.VarDesc.VarType.INT64, core.VarDesc.VarType.FP32, core.VarDesc.VarType.FP64 ] assert dtype_str in dtype_str_list, dtype_str + \ " should in " + str(dtype_str_list) return dtype_num_list[dtype_str_list.index(dtype_str)] class TestRandpermOp(OpTest): """ Test randperm op.""" def setUp(self): self.op_type = "randperm" self.python_api = paddle.randperm self.n = 200 self.dtype = "int64" self.inputs = {} self.outputs = {"Out": np.zeros((self.n)).astype(self.dtype)} self.init_attrs() self.attrs = { "n": self.n, "dtype": convert_dtype(self.dtype), } def init_attrs(self): pass def test_check_output(self): self.check_output_customized(self.verify_output) def verify_output(self, outs): out_np = np.array(outs[0]) self.assertTrue( check_randperm_out(self.n, out_np), msg=error_msg(out_np)) def test_eager(self): with _test_eager_guard(): self.test_check_output() class TestRandpermOpN(TestRandpermOp): def init_attrs(self): self.n = 10000 class TestRandpermOpInt32(TestRandpermOp): def init_attrs(self): self.dtype = "int32" class TestRandpermOpFloat32(TestRandpermOp): def init_attrs(self): self.dtype = "float32" class TestRandpermOpFloat64(TestRandpermOp): def init_attrs(self): self.dtype = "float64" class TestRandpermOpError(unittest.TestCase): def test_errors(self): with program_guard(Program(), Program()): self.assertRaises(ValueError, paddle.randperm, -3) self.assertRaises(TypeError, paddle.randperm, 10, 'int8') class TestRandpermAPI(unittest.TestCase): def test_out(self): n = 10 place = paddle.CUDAPlace(0) if core.is_compiled_with_cuda( ) else paddle.CPUPlace() with program_guard(Program(), Program()): x1 = paddle.randperm(n) x2 = paddle.randperm(n, 'float32') exe = paddle.static.Executor(place) res = exe.run(fetch_list=[x1, x2]) self.assertEqual(res[0].dtype, np.int64) self.assertEqual(res[1].dtype, np.float32) self.assertTrue(check_randperm_out(n, res[0])) self.assertTrue(check_randperm_out(n, res[1])) class TestRandpermImperative(unittest.TestCase): def test_out(self): paddle.disable_static() n = 10 for dtype in ['int32', np.int64, 'float32', 'float64']: data_p = paddle.randperm(n, dtype) data_np = data_p.numpy() self.assertTrue( check_randperm_out(n, data_np), msg=error_msg(data_np)) paddle.enable_static() class TestRandpermEager(unittest.TestCase): def test_out(self): paddle.disable_static() n = 10 with _test_eager_guard(): for dtype in ['int32', np.int64, 'float32', 'float64']: data_p = paddle.randperm(n, dtype) data_np = data_p.numpy() self.assertTrue( check_randperm_out(n, data_np), msg=error_msg(data_np)) paddle.enable_static() class TestRandomValue(unittest.TestCase): def test_fixed_random_number(self): # Test GPU Fixed random number, which is generated by 'curandStatePhilox4_32_10_t' if not paddle.is_compiled_with_cuda(): return print("Test Fixed Random number on GPU------>") paddle.disable_static() paddle.set_device('gpu') paddle.seed(2021) x = paddle.randperm(30000, dtype='int32').numpy() expect = [ 24562, 8409, 9379, 10328, 20503, 18059, 9681, 21883, 11783, 27413 ] self.assertTrue(np.array_equal(x[0:10], expect)) expect = [ 29477, 27100, 9643, 16637, 8605, 16892, 27767, 2724, 1612, 13096 ] self.assertTrue(np.array_equal(x[10000:10010], expect)) expect = [ 298, 4104, 16479, 22714, 28684, 7510, 14667, 9950, 15940, 28343 ] self.assertTrue(np.array_equal(x[20000:20010], expect)) x = paddle.randperm(30000, dtype='int64').numpy() expect = [ 6587, 1909, 5525, 23001, 6488, 14981, 14355, 3083, 29561, 8171 ] self.assertTrue(np.array_equal(x[0:10], expect)) expect = [ 23460, 12394, 22501, 5427, 20185, 9100, 5127, 1651, 25806, 4818 ] self.assertTrue(np.array_equal(x[10000:10010], expect)) expect = [5829, 4508, 16193, 24836, 8526, 242, 9984, 9243, 1977, 11839] self.assertTrue(np.array_equal(x[20000:20010], expect)) x = paddle.randperm(30000, dtype='float32').numpy() expect = [ 5154., 10537., 14362., 29843., 27185., 28399., 27561., 4144., 22906., 10705. ] self.assertTrue(np.array_equal(x[0:10], expect)) expect = [ 1958., 18414., 20090., 21910., 22746., 27346., 22347., 3002., 4564., 26991. ] self.assertTrue(np.array_equal(x[10000:10010], expect)) expect = [ 25580., 12606., 553., 16387., 29536., 4241., 20946., 16899., 16339., 4662. ] self.assertTrue(np.array_equal(x[20000:20010], expect)) x = paddle.randperm(30000, dtype='float64').numpy() expect = [ 19051., 2449., 21940., 11121., 282., 7330., 13747., 24321., 21147., 9163. ] self.assertTrue(np.array_equal(x[0:10], expect)) expect = [ 15483., 1315., 5723., 20954., 13251., 25539., 5074., 1823., 14945., 17624. ] self.assertTrue(np.array_equal(x[10000:10010], expect)) expect = [ 10516., 2552., 29970., 5941., 986., 8007., 24805., 26753., 12202., 21404. ] self.assertTrue(np.array_equal(x[20000:20010], expect)) paddle.enable_static() if __name__ == "__main__": unittest.main()
from typing import Optional, Union import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from matplotlib.axes import Axes from matplotlib.colors import Colormap from milkviz.utils import doc from milkviz.utils import get_cmap_colors, set_category_legend, set_spines def fold_add(arr): new_arr = np.zeros(arr.size) new_arr[0] = arr[0] for i in range(arr.size - 1): new_arr[i + 1] = arr[:i + 2].sum() return new_arr.astype(arr.dtype) # preserve the data type @doc def stacked_bar(data: Optional[pd.DataFrame] = None, x: Union[str, np.ndarray, None] = None, y: Union[str, np.ndarray, None] = None, stacked: Union[str, np.ndarray, None] = None, orient: str = "v", percentage: bool = False, cmap: Union[str, Colormap] = "tab20", show_values: bool = False, ax: Optional[mpl.axes.Axes] = None, **kwargs, ) -> Axes: """Stacked bar plot Args: data: [data] x: [x] y: [y] stacked: Which columns to plot as stacked type orient: "v" or "h" percentage: Normalize value to 1 cmap: [cmap] show_values: Whether to display values of each block ax: [ax] **kwargs: Pass to `seaborn.barplot <https://seaborn.pydata.org/generated/seaborn.barplot.html#seaborn.barplot>`_ Returns: [return_obj] """ if ax is None: ax = plt.gca() if data is None: data = pd.DataFrame({"x": x, "y": y, "stacked": stacked}) x = "x" y = "y" stacked = "stacked" value_key, label_key = (y, x) if orient == "v" else (x, y) stacked_order = data[stacked].unique() label_order = data[label_key].unique() all_g = [] for label in label_order: g = data[data[label_key] == label].set_index(stacked) s_order = [] for i in stacked_order: if i in g.index: s_order.append(i) g = g.loc[s_order, :] v = g[value_key].to_numpy() if percentage: v = v / v.sum() g[value_key] = fold_add(v) all_g.append(g) # This reverse step is to make the label column in the right order data_g = pd.concat(all_g[::-1]).reset_index() colors = get_cmap_colors(cmap) # This reverse step is to make the stacked column in the right order legends_cmapper = {} for (n, g), c in zip(data_g.iloc[::-1, :].groupby(stacked, sort=False), colors): bar = sns.barplot(x=x, y=y, data=g, ax=ax, color=c, orient=orient, ci=None, **kwargs) if show_values: for i in range(len(g)): text = g.iloc[i, :][value_key] if orient == "v": bar.text(i, text, text, ha="center", va="center", bbox=dict(fc="white", alpha=0.7)) else: bar.text(text, i, text, ha="center", va="center", rotation=-90, bbox=dict(fc="white", alpha=0.7)) legends_cmapper[n] = c set_category_legend(ax, legends_cmapper, (1.05, 0, 1, 1), title=stacked, marker="s") set_spines(ax, (1, 0, 1, 0)) return ax
/** * Lock action */ export const name = 'lock' export const alias = 'l' /** * Locks the layer if the condition is true or unlocks it otherwise. * * @param {Boolean} condition * @param {MSLayer} layer * @param {Array} params */ export function perform (condition, layer, params) { layer.setIsLocked(condition) }
# Copyright 2016 The Bazel Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Data structures of toolchain configs.""" import os class ContainerConfigs(object): """Group of configs that are generated using the same container. Attributes: distro: string, base distro of container used to generate configs. version: string, version of the configs. image: string, the container registry entry of the image used to generated the configs, e.g. gcr.io/cloud-marketplace/google/clang-ubuntu. package: string, the Bazel package in which we will generate the target to build configs. platform_target: string, the platform target name of the corresponding RBE container these configs will be used together with, e.g. rbe_ubuntu1604. This is required to set value for flags: --extra_execution_platforms, --host_platform and --platforms. (Platform: https://docs.bazel.build/versions/master/platforms.html) constraints: string, additional toolchain constraints needed for the cpp toolchain definition. These must be valid targets in this repo or @bazel_tools. (Toolchain: https://docs.bazel.build/versions/master/toolchains.html) configs: list of Config object, a list of configs for each supported types generated using the container specified in the current ContainerConfig. """ # Currently supported distros. _SUPPORTED_DISTROS = ["debian8", "ubuntu16_04"] # Map from the container distro to additional pre-defined cpp toolchain # definition constraints. _DISTRO_CONSTRAINTS_MAP = { "debian8": ["//constraints:jessie"], "ubuntu16_04": ["//constraints:xenial"] } def __init__(self, distro, version, image, package, config_types, platform_target, git_root, bazel_version): """Inits ContainerConfigs. Args: distro: string, base distro of container used to generate configs. version: string, version of the configs. image: string, the container registry entry of the image used to generated the configs, e.g. gcr.io/cloud-marketplace/google/clang-ubuntu. package: string, the Bazel package in which we will generate the target to build configs. config_types: types of config to generated with this container, e.g. default, msan. platform_target: string, the platform target name of the corresponding RBE container these configs will be used together with e.g. rbe_ubuntu1604. This is required to set value for flags: --extra_execution_platforms, --host_platform and --platforms. (Platform: https://docs.bazel.build/versions/master/platforms.html) git_root: the absolute path of the root directory of the current repository. bazel_version: the version of Bazel used to generated the configs. Returns: A ContainerConfigs object. Raises: ValueError: An error occurred when input distro is not supported. """ # Validate distro is supported. if distro not in ContainerConfigs._SUPPORTED_DISTROS: raise ValueError( "Input distro: %s is not supported. Supported distros are %s" % (distro, " ".join(ContainerConfigs._SUPPORTED_DISTROS))) self._git_root = git_root self._bazel_version = bazel_version self.distro = distro self.version = version self.image = image self.package = package self.platform_target = platform_target self.constraints = ContainerConfigs._DISTRO_CONSTRAINTS_MAP[distro] self.config_types = config_types self.configs = [ Config(root=self._get_config_base_dir(), config_type=config_type) for config_type in config_types ] def get_target_build_path(self): """Returns the absolute path of the target BUILD file.""" return os.path.join(self._git_root, self.package, "BUILD") def get_latest_aliases_build_path(self): """Returns the absolute path of BUILD file with latest target aliases.""" return os.path.join(self._git_root, self.package, "latest", "BUILD") def get_toolchain_bazelrc_path(self): """Returns the absolute path of the toolchain.bazelrc file.""" return os.path.join(self._git_root, self.package, self.version, "toolchain.bazelrc") def get_platform_build_path(self): """Returns the absolute path of BUILD file with platform definition.""" return os.path.join(self._git_root, self.package, self.version, "BUILD") def get_java_runtime_build_path(self): """Returns the absolute path of BUILD file with java runtime.""" return self.get_platform_build_path() def get_cpp_build_path(self): """Returns the absolute path of BUILD file with cpp toolchain definition.""" return os.path.join(self._get_config_base_dir(), "cpp", "BUILD") def _get_config_base_dir(self): """Returns the absolute path of bazel_{version} directory. This returns the absolute path of bazel_{version} directory where configs are stored in the bazel-toolchains repo. For example: /.../configs/ubuntu16_04_clang/1.0/bazel_0.15.0/ """ return os.path.join(self._git_root, self.package, self.version, "bazel_%s" % self._bazel_version) class Config(object): """Configs of a single type that are generated using a container. Attributes: config_type: string, type of the configs, e.g. default, msan. constraints: string, additional toolchain constraints needed for the cpp toolchain definition. These must be valid targets in this repo or @bazel_tools. (Toolchain: https://docs.bazel.build/versions/master/toolchains.html) """ # Currently supported config types. _SUPPORTED_CONFIG_TYPES = ["default", "msan"] # Map from the config type to additional pre-defined cpp toolchain # definition constraints. _TYPE_CONSTRAINTS_MAP = { "default": [], "msan": ["//constraints/sanitizers:support_msan"] } def __init__(self, root, config_type): """Inits Config. Args: root: string, absolute path to the bazel_{version} directory, e.g. /.../configs/ubuntu16_04_clang/1.0/bazel_0.15.0/. config_type: string, type of the configs. Returns: A Config object. Raises: ValueError: An error occurred when input config type is not supported. """ # Validate config_type is supported. if config_type not in Config._SUPPORTED_CONFIG_TYPES: raise ValueError( "Input config type: %s is not supported. Supported types are %s" % (config_type, " ".join(Config._SUPPORTED_CONFIG_TYPES))) self._root = root self.config_type = config_type self.constraints = Config._TYPE_CONSTRAINTS_MAP[config_type] def get_config_dir(self): """Returns the absolute path of the cc toolchain configs directory.""" return os.path.join(self._root, self.config_type) def get_metadata_path(self): """Returns the absolute path of the METADATA file.""" return os.path.join(self.get_config_dir(), "METADATA")
/*! * angular-datatables - v0.5.6 * https://github.com/l-lin/angular-datatables * License: MIT */ "undefined"!=typeof module&&"undefined"!=typeof exports&&module.exports===exports&&(module.exports="datatables.colreorder"),function(a,b,c,d){"use strict";function e(a){function b(a){function b(a,b){function e(){var a="R";return i.dom=i.dom?i.dom:c.fn.dataTable.defaults.sDom,-1===i.dom.indexOf(a)&&(i.dom=a+i.dom),i.hasColReorder=!0,i}function f(a,b){return d.isString(a)&&(i.oColReorder=i.oColReorder&&null!==i.oColReorder?i.oColReorder:{},i.oColReorder[a]=b),i}function g(a){return d.isArray(a)&&i.withColReorderOption("aiOrder",a),i}function h(a){if(!d.isFunction(a))throw new Error("The reorder callback must be a function");return i.withColReorderOption("fnReorderCallback",a),i}var i=a(b);return i.withColReorder=e,i.withColReorderOption=f,i.withColReorderOrder=g,i.withColReorderCallback=h,i}var e=a.newOptions,f=a.fromSource,g=a.fromFnPromise;return a.newOptions=function(){return b(e)},a.fromSource=function(a){return b(f,a)},a.fromFnPromise=function(a){return b(g,a)},a}a.decorator("DTOptionsBuilder",b),b.$inject=["$delegate"]}d.module("datatables.colreorder",["datatables"]).config(e),e.$inject=["$provide"]}(window,document,jQuery,angular);