text
stringlengths 3
1.05M
|
---|
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云(BlueKing) available.
Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://opensource.org/licenses/MIT
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.
Django settings for app-framework project.
Generated by 'django-admin startproject' using Django 1.8.3.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
import os
import sys
# Import global settings to make it easier to extend settings.
from django.conf.global_settings import * # noqa
# ==============================================================================
# 应用基本信息配置 (请按照说明修改)
# ==============================================================================
# 在蓝鲸智云开发者中心 -> 点击应用ID -> 基本信息 中获取 APP_ID 和 APP_TOKEN 的值
APP_ID = 'framework-qxy'
APP_TOKEN = '7da0d4fd-07d8-47ce-8127-be95f085d033'
# 蓝鲸智云开发者中心的域名,形如:http://paas.bking.com
BK_PAAS_HOST = 'http://paas.bking.com'
# 是否启用celery任务
IS_USE_CELERY = True
# 本地开发的 celery 的消息队列(RabbitMQ)信息
BROKER_URL_DEV = 'amqp://guest:[email protected]:5672/'
# TOCHANGE 调用celery任务的文件路径, List of modules to import when celery starts.
CELERY_IMPORTS = (
'home_application.celery_tasks',
)
# ==============================================================================
# 应用运行环境配置信息
# ==============================================================================
ENVIRONMENT = os.environ.get('BK_ENV', 'development')
# 应用基本信息从环境变量中获取,未设置环境变量(如:本地开发)时,则用用户在文件开头的填写的值
APP_ID = os.environ.get('APP_ID', APP_ID)
APP_TOKEN = os.environ.get('APP_TOKEN', APP_TOKEN)
BK_PAAS_HOST = os.environ.get('BK_PAAS_HOST', BK_PAAS_HOST)
# 应用访问路径
SITE_URL = '/'
# 运行模式, DEVELOP(开发模式), TEST(测试模式), PRODUCT(正式模式)
RUN_MODE = 'DEVELOP'
if ENVIRONMENT.endswith('production'):
RUN_MODE = 'PRODUCT'
DEBUG = False
SITE_URL = '/o/%s/' % APP_ID
elif ENVIRONMENT.endswith('testing'):
RUN_MODE = 'TEST'
DEBUG = False
SITE_URL = '/t/%s/' % APP_ID
else:
RUN_MODE = 'DEVELOP'
DEBUG = True
try:
import pymysql
pymysql.install_as_MySQLdb()
except:
pass
# ===============================================================================
# 应用基本信息
# ===============================================================================
# 应用密钥
SECRET_KEY = 'MQtd_0cw&AiY5jT&&#w7%9sCK=HW$O_e%ch4xDd*AaP(xU0s3X'
# CSRF的COOKIE域,默认使用当前域
# CSRF_COOKIE_DOMAIN =''
CSRF_COOKIE_PATH = SITE_URL
ALLOWED_HOSTS = ['*']
# ==============================================================================
# Middleware and apps
# ==============================================================================
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
'account.middlewares.LoginMiddleware', # 登录鉴权中间件
'common.middlewares.CheckXssMiddleware', # Xss攻击处理中间件
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
# OTHER 3rd Party App
'app_control',
'account',
'home_application',
)
# ==============================================================================
# Django 项目配置
# ==============================================================================
TIME_ZONE = 'Asia/Shanghai'
LANGUAGE_CODE = 'zh-CN'
SITE_ID = 1
USE_I18N = True
USE_L10N = True
# 项目路径
PROJECT_PATH = os.path.dirname(os.path.abspath(__file__))
PROJECT_ROOT, PROJECT_MODULE_NAME = os.path.split(PROJECT_PATH)
BASE_DIR = os.path.dirname(os.path.dirname(PROJECT_PATH))
PYTHON_BIN = os.path.dirname(sys.executable)
# ===============================================================================
# 静态资源设置
# ===============================================================================
# 静态资源文件(js,css等)在应用上线更新后, 由于浏览器有缓存, 可能会造成没更新的情况.
# 所以在引用静态资源的地方,都需要加上这个版本号,如:<script src="/a.js?v=${STATIC_VERSION}"></script>;
# 如果静态资源修改了以后,上线前修改这个版本号即可
STATICFILES_DIRS = (
os.path.join(PROJECT_ROOT, 'static'),
)
STATIC_VERSION = 0.1
# 应用本地静态资源目录
STATIC_URL = '%sstatic/' % SITE_URL
ROOT_URLCONF = 'urls'
# ==============================================================================
# Templates
# ==============================================================================
# mako template dir
MAKO_TEMPLATE_DIR = os.path.join(PROJECT_ROOT, 'templates')
MAKO_TEMPLATE_MODULE_DIR = os.path.join(BASE_DIR, 'templates_module', APP_ID)
if RUN_MODE not in ['DEVELOP']:
MAKO_TEMPLATE_MODULE_DIR = os.path.join(PROJECT_ROOT, 'templates_module', APP_ID)
# Django TEMPLATES配置
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(PROJECT_ROOT, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
# the context to the templates
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.request',
'django.template.context_processors.csrf',
'common.context_processors.mysetting', # 自定义模版context,可在页面中使用STATIC_URL等变量
'django.template.context_processors.i18n',
],
'debug': DEBUG
},
},
]
# ==============================================================================
# session and cache
# ==============================================================================
SESSION_EXPIRE_AT_BROWSER_CLOSE = True # 默认为false,为true时SESSION_COOKIE_AGE无效
SESSION_COOKIE_PATH = SITE_URL # NOTE 不要改动,否则,可能会改成和其他app的一样,这样会影响登录
# ===============================================================================
# Authentication
# ===============================================================================
AUTH_USER_MODEL = 'account.BkUser'
AUTHENTICATION_BACKENDS = ('account.backends.BkBackend', 'django.contrib.auth.backends.ModelBackend')
LOGIN_URL = "%s/login/?app_id=%s" % (BK_PAAS_HOST, APP_ID)
LOGOUT_URL = '%saccount/logout/' % SITE_URL
LOGIN_REDIRECT_URL = SITE_URL
REDIRECT_FIELD_NAME = "c_url"
# 验证登录的cookie名
BK_COOKIE_NAME = 'bk_token'
# 数据库初始化 管理员列表
ADMIN_USERNAME_LIST = ['admin']
# ===============================================================================
# CELERY 配置
# ===============================================================================
if IS_USE_CELERY:
try:
import djcelery
INSTALLED_APPS += (
'djcelery', # djcelery
)
djcelery.setup_loader()
CELERY_ENABLE_UTC = False
CELERYBEAT_SCHEDULER = "djcelery.schedulers.DatabaseScheduler"
if "celery" in sys.argv:
DEBUG = False
# celery 的消息队列(RabbitMQ)信息
BROKER_URL = os.environ.get('BK_BROKER_URL', BROKER_URL_DEV)
if RUN_MODE == 'DEVELOP':
from celery.signals import worker_process_init
@worker_process_init.connect
def configure_workers(*args, **kwargs):
import django
django.setup()
except:
pass
# ==============================================================================
# logging
# ==============================================================================
# 应用日志配置
BK_LOG_DIR = os.environ.get('BK_LOG_DIR', '/data/paas/apps/logs/')
LOGGING_DIR = os.path.join(BASE_DIR, 'logs', APP_ID)
LOG_CLASS = 'logging.handlers.RotatingFileHandler'
if RUN_MODE == 'DEVELOP':
LOG_LEVEL = 'DEBUG'
elif RUN_MODE == 'TEST':
LOGGING_DIR = os.path.join(BK_LOG_DIR, APP_ID)
LOG_LEVEL = 'INFO'
elif RUN_MODE == 'PRODUCT':
LOGGING_DIR = os.path.join(BK_LOG_DIR, APP_ID)
LOG_LEVEL = 'ERROR'
# 自动建立日志目录
if not os.path.exists(LOGGING_DIR):
try:
os.makedirs(LOGGING_DIR)
except:
pass
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '%(levelname)s [%(asctime)s] %(pathname)s %(lineno)d %(funcName)s %(process)d %(thread)d \n \t %(message)s \n', # noqa
'datefmt': '%Y-%m-%d %H:%M:%S'
},
'simple': {
'format': '%(levelname)s %(message)s \n'
},
},
'handlers': {
'null': {
'level': 'DEBUG',
'class': 'django.utils.log.NullHandler',
},
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler'
},
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'simple'
},
'root': {
'class': LOG_CLASS,
'formatter': 'verbose',
'filename': os.path.join(LOGGING_DIR, '%s.log' % APP_ID),
'maxBytes': 1024 * 1024 * 10,
'backupCount': 5
},
'component': {
'class': LOG_CLASS,
'formatter': 'verbose',
'filename': os.path.join(LOGGING_DIR, 'component.log'),
'maxBytes': 1024 * 1024 * 10,
'backupCount': 5
},
'wb_mysql': {
'class': LOG_CLASS,
'formatter': 'verbose',
'filename': os.path.join(LOGGING_DIR, 'wb_mysql.log'),
'maxBytes': 1024 * 1024 * 4,
'backupCount': 5
},
},
'loggers': {
'django': {
'handlers': ['null'],
'level': 'INFO',
'propagate': True,
},
'django.request': {
'handlers': ['console'],
'level': 'ERROR',
'propagate': True,
},
# the root logger ,用于整个project的logger
'root': {
'handlers': ['root'],
'level': LOG_LEVEL,
'propagate': True,
},
# 组件调用日志
'component': {
'handlers': ['component'],
'level': 'WARN',
'propagate': True,
},
# other loggers...
'django.db.backends': {
'handlers': ['wb_mysql'],
'level': 'DEBUG',
'propagate': True,
},
}
}
|
import matplotlib.pyplot as plt
import numpy as np
def plot_results_specific(targets_pd, rnn_outputs, time_axis, comment, closed_loop_enabled, close_loop_idx):
if time_axis == []:
time_axis = np.arange(0, targets_pd.shape[0])
time_axis_string = 'Sample number'
else:
time_axis = time_axis[1:]
time_axis = time_axis-min(time_axis) # Start at 0, comment out if you want to relate to a true experiment
time_axis_string = 'Time [s]'
if ('angle' in targets_pd) and ('angle' in rnn_outputs) and ('position' in targets_pd) and (
'position' in rnn_outputs):
angle_target = np.rad2deg(targets_pd['angle'].to_numpy())
position_target = targets_pd['position'].to_numpy()
angle_output = np.rad2deg(rnn_outputs['angle'].to_numpy())
position_output = rnn_outputs['position'].to_numpy()
# Create a figure instance
fig, axs = plt.subplots(2, 1, figsize=(18, 10), sharex=True)
plt.subplots_adjust(hspace=0.4)
start_idx = 0
axs[0].set_title(comment, fontsize=20)
axs[0].set_ylabel("Position (m)", fontsize=18)
axs[0].plot(time_axis, position_target, 'k:', markersize=12, label='Ground Truth')
axs[0].plot(time_axis, position_output, 'b', markersize=12, label='Predicted position')
axs[0].plot(time_axis[start_idx], position_target[start_idx], 'g.', markersize=16, label='Start')
axs[0].plot(time_axis[start_idx], position_output[start_idx], 'g.', markersize=16)
axs[0].plot(time_axis[-1], position_target[-1], 'r.', markersize=16, label='End')
axs[0].plot(time_axis[-1], position_output[-1], 'r.', markersize=16)
if closed_loop_enabled:
axs[0].plot(time_axis[close_loop_idx], position_target[close_loop_idx], '.', color='darkorange', markersize=16, label='connect output->input')
axs[0].plot(time_axis[close_loop_idx], position_output[close_loop_idx], '.', color='darkorange', markersize=16)
axs[0].legend()
axs[1].set_ylabel("Angle (deg)", fontsize=18)
axs[1].plot(time_axis, angle_target, 'k:', markersize=12, label='Ground Truth')
axs[1].plot(time_axis, angle_output, 'b', markersize=12,
label='Predicted angle')
axs[1].plot(time_axis[start_idx], angle_target[start_idx], 'g.', markersize=16,
label='Start')
axs[1].plot(time_axis[start_idx], angle_output[start_idx], 'g.', markersize=16)
axs[1].plot(time_axis[-1], angle_target[-1], 'r.', markersize=16, label='End')
axs[1].plot(time_axis[-1], angle_output[-1], 'r.', markersize=16)
if closed_loop_enabled:
axs[1].plot(time_axis[close_loop_idx], angle_target[close_loop_idx], '.',
color='darkorange', markersize=16, label='connect output->input')
axs[1].plot(time_axis[close_loop_idx], angle_output[close_loop_idx], '.',
color='darkorange', markersize=16)
axs[1].tick_params(axis='both', which='major', labelsize=16)
axs[1].set_xlabel(time_axis_string, fontsize=18)
axs[1].legend()
if 'Q' in targets_pd:
motor_power_target = targets_pd['Q'].to_numpy()
motor_power_output = targets_pd['Q'].to_numpy()
# Create a figure instance
fig, axs = plt.subplots(1, 1, figsize=(18, 10))
plt.subplots_adjust(hspace=0.4)
start_idx = 0
axs.set_title(comment, fontsize=20)
axs.set_ylabel("Motor power (-)", fontsize=18)
axs.plot(time_axis, motor_power_target, 'k:', markersize=12, label='Ground Truth')
axs.plot(time_axis, motor_power_output, 'b', markersize=12, label='Predicted position')
axs.plot(time_axis[start_idx], motor_power_target[start_idx], 'g.', markersize=16, label='Start')
axs.plot(time_axis[start_idx], motor_power_output[start_idx], 'g.', markersize=16)
axs.plot(time_axis[-1], motor_power_target[-1], 'r.', markersize=16, label='End')
axs.plot(time_axis[-1], motor_power_output[-1], 'r.', markersize=16)
axs.legend()
return fig, axs |
# Copyright 2015 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.
"""
GN-related configuration functions, e.g., to produce a Config object from a GN
args.gn file).
"""
import ast
import os.path
import re
from .config import Config
def BuildDirectoryForConfig(config, src_root):
"""
Returns the build directory for the given configuration.
"""
subdir = ""
if config.target_os == Config.OS_ANDROID:
subdir += "android_"
if config.target_cpu != Config.ARCH_ARM:
subdir += config.target_cpu + "_"
elif config.target_os == Config.OS_FNL:
subdir += "fnl_"
elif config.target_os == Config.OS_IOS:
subdir += "ios_"
if config.is_simulator:
subdir += "sim_"
if config.is_official_build:
subdir += "Official"
elif config.is_debug:
subdir += "Debug"
else:
subdir += "Release"
if config.sanitizer == Config.SANITIZER_ASAN:
subdir += "_asan"
if not(config.is_debug) and config.dcheck_always_on:
subdir += "_dcheck"
return os.path.join(src_root, "out", subdir)
def GNArgsForConfig(config):
"""
Return the arguments for gn for the given configuration. This function returns
a dictionary with boolean values as boolean.
"""
gn_args = {}
gn_args["is_debug"] = bool(config.is_debug)
gn_args["is_official_build"] = bool(config.is_official_build)
gn_args["is_asan"] = config.sanitizer == Config.SANITIZER_ASAN
if config.is_clang is not None:
gn_args["is_clang"] = bool(config.is_clang)
else:
gn_args["is_clang"] = config.target_os not in (Config.OS_ANDROID,
Config.OS_FNL,
Config.OS_WINDOWS)
if config.values.get("use_goma"):
gn_args["use_goma"] = True
gn_args["goma_dir"] = config.values["goma_dir"]
else:
gn_args["use_goma"] = False
gn_args["dcheck_always_on"] = config.dcheck_always_on
if config.target_os == Config.OS_ANDROID:
gn_args["target_os"] = "android"
elif config.target_os == Config.OS_FNL:
gn_args["target_os"] = "fnl"
gn_args["use_ozone"] = True
gn_args["target_sysroot"] = config.values.get("target_sysroot", "")
gn_args["toolchain_prefix"] = config.values.get("toolchain_prefix", "")
elif config.target_os == Config.OS_IOS:
gn_args["target_os"] = "ios"
gn_args["ios_deployment_target"] = "7.0"
gn_args["clang_use_chrome_plugins"] = False
gn_args["use_ios_simulator"] = config.is_simulator
elif config.target_os == Config.OS_LINUX:
pass
gn_args["target_cpu"] = config.target_cpu
if "use_nacl" in config.values:
gn_args["mojo_use_nacl"] = config.values.get("use_nacl", False)
if "mojo_use_go" in config.values:
gn_args["mojo_use_go"] = config.values.get("mojo_use_go", False)
if gn_args["mojo_use_go"]:
gn_args["go_build_tool"] = config.values.get("go_build_tool")
extra_args = config.values.get("gn_args")
if extra_args:
for arg in extra_args.split():
(name, val) = arg.split('=')
gn_args[name] = val
return gn_args
def CommandLineForGNArgs(gn_args):
"""
Returns the list of gn arguments to use with the gn command line.
"""
def _ToCommandLine(key, value):
if type(value) is bool:
return "%s=%s" % (key, "true" if value else "false")
return "%s=\"%s\"" % (key, value)
return [_ToCommandLine(x, y) for x, y in gn_args.iteritems()]
def ConfigForGNArgs(args):
"""
Return the Config object for the given gn arguments. This function takes a
dictionary with boolean values as boolean.
"""
config_args = {}
config_args["is_debug"] = args.get("is_debug", True)
config_args["is_official_build"] = args.get("is_official_build", False)
config_args["sanitizer"] = (
Config.SANITIZER_ASAN if args.get("is_asan") else None)
config_args["is_clang"] = args.get("is_clang", False)
config_args["use_goma"] = args.get("use_goma", False)
if config_args["use_goma"]:
config_args["goma_dir"] = args.get("goma_dir")
config_args["use_nacl"] = args.get("mojo_use_nacl", False)
config_args["mojo_use_go"] = args.get("mojo_use_go", False)
if config_args["mojo_use_go"]:
config_args["go_build_tool"] = args.get("go_build_tool")
config_args["target_os"] = args.get("target_os")
config_args["target_cpu"] = args.get("target_cpu")
config_args["dcheck_always_on"] = args.get("dcheck_always_on")
config_args["is_simulator"] = args.get("use_ios_simulator", False)
if "target_sysroot" in args:
config_args["target_sysroot"] = args.get("target_sysroot")
if "toolchain_prefix" in args:
config_args["toolchain_prefix"] = args.get("toolchain_prefix")
return Config(**config_args)
def ParseGNConfig(build_dir):
"""
Parse the gn config file present in |build_dir|. This function returns a
dictionary with boolean values as boolean.
"""
TRANSLATIONS = {
"true": "True",
"false": "False",
}
gn_file = os.path.join(build_dir, "args.gn")
values = {}
with open(gn_file, "r") as f:
for line in f.readlines():
line = re.sub("\s*#.*", "", line)
result = re.match("^\s*(\w+)\s*=\s*(.*)\s*$", line)
if result:
key = result.group(1)
value = result.group(2)
values[key] = ast.literal_eval(TRANSLATIONS.get(value, value))
return values
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.PouchDB = void 0;
exports.addPouchPlugin = addPouchPlugin;
exports.isInstanceOf = isInstanceOf;
exports.isLevelDown = isLevelDown;
exports.pouchReplicationFunction = pouchReplicationFunction;
var _pouchdbCore = _interopRequireDefault(require("pouchdb-core"));
var _pouchdbFind = _interopRequireDefault(require("pouchdb-find"));
var _rxError = require("../../rx-error");
var _customEventsPlugin = require("./custom-events-plugin");
/**
* this handles the pouchdb-instance
* to easy add modules and manipulate things
* Adapters can be found here:
* @link https://github.com/pouchdb/pouchdb/tree/master/packages/node_modules
*/
// pouchdb-find
/*
// comment in to debug
const pouchdbDebug = require('pouchdb-debug');
PouchDB.plugin(pouchdbDebug);
PouchDB.debug.enable('*');
*/
// TODO we can delete most of these functions in the file because it was migrated to rx-storage-pouchdb
addPouchPlugin(_pouchdbFind["default"]);
(0, _customEventsPlugin.addCustomEventsPluginToPouch)();
/**
* check if the given module is a leveldown-adapter
* throws if not
*/
function isLevelDown(adapter) {
if (!adapter || typeof adapter.super_ !== 'function') {
throw (0, _rxError.newRxError)('UT4', {
adapter: adapter
});
}
}
/**
* get the correct function-name for pouchdb-replication
*/
function pouchReplicationFunction(pouch, _ref) {
var _ref$pull = _ref.pull,
pull = _ref$pull === void 0 ? true : _ref$pull,
_ref$push = _ref.push,
push = _ref$push === void 0 ? true : _ref$push;
if (pull && push) return pouch.sync.bind(pouch);
if (!pull && push) return pouch.replicate.to.bind(pouch);
if (pull && !push) return pouch.replicate.from.bind(pouch);
if (!pull && !push) {
throw (0, _rxError.newRxError)('UT3', {
pull: pull,
push: push
});
}
}
function isInstanceOf(obj) {
return obj instanceof _pouchdbCore["default"];
}
/**
* Add a pouchdb plugin to the pouchdb library.
*/
function addPouchPlugin(plugin) {
if (plugin.rxdb) {
throw (0, _rxError.newRxTypeError)('PL2', {
plugin: plugin
});
}
/**
* Pouchdb has confusing typings and modules.
* So we monkeypatch the plugin to use the default property
* when it was imported or packaged this way.
*/
if (typeof plugin === 'object' && plugin["default"]) {
plugin = plugin["default"];
}
_pouchdbCore["default"].plugin(plugin);
}
var PouchDB = _pouchdbCore["default"];
exports.PouchDB = PouchDB;
//# sourceMappingURL=pouch-db.js.map |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import tempfile
import os
import copy
import shutil
from corral import run, db
import sh
import numpy as np
from ..models import Pawprint
from .. import bin
PAWPRINTS_DEFAULT_PARAMS = {
"dtype": {
"names": [
'ra_h', 'ra_m', 'ra_s', 'dec_d', 'dec_m', 'dec_s',
'x', 'y', 'mag', 'mag_err',
'chip_nro', 'stel_cls', 'elip', 'pos_ang',
],
"formats": [
int, int, float, int, int, float,
float, float, float, float,
int, int, float, float,
]
}
}
class MeasurePawprint(run.Step):
model = Pawprint
conditions = [model.status == "raw"]
procno = 3
production_procno = 30
groups = ["measurement"]
@classmethod
def class_setup(cls):
def chunk_it(seq, num):
avg = len(seq) / float(num)
out = []
last = 0.0
while last < len(seq):
out.append(seq[int(last):int(last + avg)])
last += avg
return sorted(out, reverse=True)
with db.session_scope() as session:
all_ids = tuple(
r[0] for r in
session.query(cls.model.id).filter(*cls.conditions))
db.engine.dispose()
cls.chunks = chunk_it(all_ids, cls.get_procno())
def generate(self):
if not self.chunks:
return ()
ids = self.chunks[self.current_proc]
if not ids:
return ()
query = self.session.query(self.model).filter(self.model.id.in_(ids))
return query
def setup(self):
self.work_path = tempfile.mkdtemp("_measure_pawprint")
self.asc_path = os.path.join(self.work_path, "catalogue.asc")
if os.path.isfile(self.asc_path):
raise IOError("Duplicated {}".format(self.asc_path))
self.fitsio_cat_list = sh.Command(bin.get("fitsio_cat_list"))
os.chdir(self.work_path)
def teardown(self, *args, **kwargs):
if os.path.isdir(self.work_path):
shutil.rmtree(self.work_path)
def ra_to_degree(self, arr):
return 15 * (
arr['ra_h'] +
arr['ra_m'] / 60.0 +
arr['ra_s'] / 3600.0)
def dec_to_degree(self, arr):
return np.sign(arr['dec_d']) * (
np.abs(arr['dec_d']) +
arr['dec_m'] / 60.0 +
arr['dec_s'] / 3600.0)
def to_array(self, path):
filename = os.path.basename(path)
tmp_file_path = os.path.join(self.work_path, filename)
os.symlink(path, tmp_file_path)
self.fitsio_cat_list(tmp_file_path)
odata = np.genfromtxt(self.asc_path, **PAWPRINTS_DEFAULT_PARAMS)
ra_deg = self.ra_to_degree(odata)
dec_deg = self.dec_to_degree(odata)
conf = copy.deepcopy(PAWPRINTS_DEFAULT_PARAMS)
conf["dtype"]["names"].insert(0, "dec_deg")
conf["dtype"]["names"].insert(0, "ra_deg")
conf["dtype"]["formats"].insert(0, float)
conf["dtype"]["formats"].insert(0, float)
data = np.empty(len(odata), **conf)
for name in data.dtype.names:
if name == "ra_deg":
data[name] = ra_deg
elif name == "dec_deg":
data[name] = dec_deg
else:
data[name] = odata[name]
return data
def process(self, pwp):
path = pwp.file_path()
pwp.data = self.to_array(path)
pwp.data_size = len(pwp.data)
pwp.data_readed = 0
pwp.status = "measured"
|
#!/bin/python3
import unittest
import os
import sys
from touch import touch
from parameterized import parameterized_class
sys.path.insert(0, os.path.join("..", ".."))
import lexicons_builder.wordnet_explorer.explorer as exp
sys.path.insert(0, os.path.join("..", "..", "lexicons_builder", "graphs"))
from graphs import Graph
@parameterized_class(
("lang", "depth", "word"),
[
("fra", 2, "test"),
("eng", 1, "test"),
],
)
class TestExplorer(unittest.TestCase):
wrong_langs = ("frgg", "enrr", "depp", "nlhh", "itff")
word_test_fr = "chaussette"
word_test_en = "make"
out_file = "_test"
out_file_xlsx = "_test.xlsx"
@classmethod
def setUpClass(cls):
cls.g = exp.explore_wordnet(cls.word, cls.lang, cls.depth)
def setUp(self):
touch(self.out_file)
touch(self.out_file_xlsx)
def tearDown(self):
os.remove(self.out_file)
os.remove(self.out_file_xlsx)
def test_to_list(self):
for i in range(0, 1):
g = exp.explore_wordnet(self.word_test_en, "eng", i)
self.assertEqual(len(g.to_list()), len(set(g.to_list())))
self.assertEqual(g.to_list(), sorted(g.to_list()))
if i:
self.assertTrue(len(g.to_list()) > 2)
def test_return_graph(self):
self.assertIsInstance(exp.explore_wordnet(self.word_test_fr, "fra", 1), Graph)
self.assertIsInstance(exp.explore_wordnet(self.word_test_fr, "fra", 0), Graph)
# TESTS ADDED FROM GRAPHS
def test_to_text_file(self):
self.g.to_text_file(self.out_file)
with open(self.out_file) as f:
words = sorted([line.strip() for line in f if line.strip()])
self.assertEqual(words, self.g.to_list())
def test_add_several_root_words(self):
self.g.add_root_word("root_word_string_1")
self.g.add_root_word("root_word_string_2")
self.g.add_root_word("root_word_string_3")
self.g.to_text_file(self.out_file)
with open(self.out_file) as f:
words = sorted(set([line.strip() for line in f if line.strip()]))
self.assertEqual(words, self.g.to_list())
@unittest.skip("skipping because the xlsx should be tested in integration")
def test_to_xlsx(self):
self.g.to_xlsx_file(self.out_file_xlsx)
class TestWOLF(unittest.TestCase):
words = ("chien",) # "livre", "rire")
path_2_wolf = "/home/k/models/wolf-1.0b4.xml" # change here if needed
fake_word = "adsfadsfasdfdsf"
def test_explore(self):
for word in self.words:
g = exp.explore_wolf(word, self.path_2_wolf, 2)
self.assertEqual(len(g.to_list()), len(set(g.to_list())))
self.assertEqual(g.to_list(), sorted(g.to_list()))
def test_return_graph(self):
for word in self.words:
self.assertIsInstance(exp.explore_wolf(word, self.path_2_wolf, 1), Graph)
self.assertIsInstance(exp.explore_wolf(word, self.path_2_wolf, 0), Graph)
def test_wrong_path(self):
self.assertRaises(
FileNotFoundError, exp.explore_wolf, self.words[0], "/wrong/path/2/wolf", 42
)
def test_fake_word(self):
self.assertTrue(
exp.explore_wolf(self.fake_word, self.path_2_wolf, 42).is_empty()
)
unittest.main()
|
n = int(input('Um valor inteiro:'))
a = n-1
s = n+1
print('Analisando o valor de {}, o seu antecessor é {} e o seu sucessor é {}'.format(n, a, s))
|
if __name__ == '__main__':
N = int(input())
arr = []
for _ in range(N):
cmd = input().split()
fn = cmd[0]
args = cmd[1:]
if fn != "print":
fn += "("+",".join(args)+")"
eval("arr."+fn)
else:
print(arr)
|
let nowDate = new Date();
console.log(nowDate);
let newYears = "";
// check for next new year
switch ( nowDate.getFullYear() ) {
case 2021:
newYears = '2022-01-01';
break;
case 2022:
newYears = '2023-01-01';
break;
case 2023:
newYears = '2024-01-01';
break;
case 2024:
newYears = '2025-01-01';
break;
default:
console.log('Not Supported!');
}
// set new Year
let y = new Date(newYears);
// get with DOM
let days = document.getElementById("days");
let hours = document.getElementById("hours");
let minutes = document.getElementById("minutes");
let seconds = document.getElementById("seconds");
// run
setInterval( () => {
let n = new Date();
let totalSecs = (y - n) / 1000;
let logicSeconds = Math.floor(totalSecs % 60);
let logicMinutes = Math.floor(totalSecs / 60) % 60;
let logicHours = Math.floor(totalSecs / 3600) % 24;
let logicDays = Math.floor(totalSecs / 3600 / 24);
days.innerHTML = logicDays;
hours.innerHTML = logicHours;
minutes.innerHTML = logicMinutes;
seconds.innerHTML = logicSeconds;
}, 1000); |
import React from 'react'
export const renderHelmetTags = (tags) => {
return tags.map(({ id, type, attributes, value }) => {
attributes.key = id;
return React.createElement(type, attributes, value);
});
} |
$(document).ready(function() {
oTable = $('#cambios').DataTable({
responsive: true,
columnDefs: [
{ orderable: false, targets: -1 }
],
"language": {
"info": "Mostrando _START_ a _END_ de _TOTAL_ cambios filtrados",
"paginate": {
"first": "Primera",
"last": "Ultima",
"next": "Siguiente",
"previous": "Anterior"
},
"lengthMenu": "Mostrar _MENU_ cambios",
"search": "Buscar:",
"infoFiltered": "(de un total de _MAX_ cambios)",
}
});
});
|
from flask_migrate import Migrate
from flask_restful import Api
from flask_session import Session
from App.apis import Hellos
from App.models import db
def init_ext(app):
# migrate
migrate = Migrate()
migrate.init_app(app=app, db=db)
#session
app.config['SECRET_KEY']='100'
app.config['SESSION_TYPE']='redis'
Session(app=app)
# 数据模型的初始化
db.init_app(app=app)
api = Api()
#第一个参数是我们要操作的类
#为什么为把Hello1写在了api中呢?因为增删该查都是在api中执行的
api.add_resource(Hellos, '/hellos/')
api.init_app(app=app) |
Expand Alphabets
Expand Alphabets: Given a string S with alphabets and their count, repeat the alphabets based on their count and print the value as the output.
Input Format:
The first line contains S.
Output Format:
The first line contains the alphabets repeated based on their count.
Boundary Condition:
1 <= Length of S <= 100
Example Input/Output 1:
Input:
a2c5z4
Output:
aaccccczzzz
s=input().strip()
a=[];b=[]
o=''
for i in s:
if i.isdigit():
o+=i
else:
a.append(i)
if o!='':
b.append(o)
o=''
b.append(o)
for i in range(len(a)):
print(a[i]*int(b[i]),end='')
|
import React from "react";
import Svg, { Defs, LinearGradient, Stop, Path } from "react-native-svg";
const SvgEql = props => (
<Svg width={40} height={40} viewBox="0 0 500 500" {...props}>
<Defs>
<LinearGradient id="eql_svg__a" x1="0%" y1="0%" x2="100%" y2="0%">
<Stop offset="0%" stopColor="#c9a35e" />
<Stop offset="100%" stopColor="#d9be8e" />
</LinearGradient>
</Defs>
<Path
d="M477.043 219.205L378.575 48.677a44.579 44.579 0 00-38.607-22.292H143.041a44.589 44.589 0 00-38.608 22.292L5.971 219.205a44.607 44.607 0 000 44.588l98.462 170.543a44.59 44.59 0 0038.608 22.293h196.926a44.577 44.577 0 0038.607-22.293l98.469-170.543a44.612 44.612 0 000-44.588z"
fill="url(#eql_svg__a)"
data-original="#000000"
transform="matrix(0 -1 1 0 0 483.014)"
/>
<Path
fill="#FFF"
d="M176.297 279.18a4.092 4.092 0 01-3.674 2.31H127.82a4.048 4.048 0 01-3.465-2.002 4.07 4.07 0 01-.11-4.092l81.444-146.806c1.463-2.629 5.665-2.629 7.128 0l63.492 114.158a4.356 4.356 0 01-.11 4.092 3.806 3.806 0 01-3.465 1.991h-18.568a4.191 4.191 0 01-3.564-2.09l-41.25-75.02-46.156 85.305h17.622c1.364 0 2.728.726 3.465 1.881a4.158 4.158 0 01.209 3.993l-8.184 16.258zm183.414-3.784a3.85 3.85 0 01-.11 4.092 3.806 3.806 0 01-3.454 1.991H233.904a4.092 4.092 0 01-4.092-4.092V261.14c0-2.31 1.881-4.092 4.092-4.092h86.988l-46.068-85.008-8.712 17.413c-1.463 2.728-5.973 2.728-7.337 0l-8.184-16.258a4.477 4.477 0 010-3.674l20.35-40.81a4.29 4.29 0 013.564-2.211c1.364 0 2.937.737 3.674 2.09l81.532 146.806zm-52.987 16.258l20.24 36.729a4.07 4.07 0 010 4.092 3.806 3.806 0 01-3.454 1.991H160.457a4.191 4.191 0 01-3.575-2.09 4.07 4.07 0 01.11-4.103l32.626-52.987 32.527-56.98c.737-1.353 2.2-2.2 3.674-2.09a3.85 3.85 0 013.575 2.2l8.184 16.269a3.938 3.938 0 01-.11 3.883l-41.338 71.346h91.707l-8.503-14.168a3.85 3.85 0 01-.11-4.092 4.191 4.191 0 013.575-2.09h20.35c1.474 0 2.838.836 3.575 2.09z"
/>
</Svg>
);
export default SvgEql;
|
# -*- coding: utf-8 -*-
import handlers
from django.conf.urls import patterns, url
from anaf.core.api.auth import auth_engine
from anaf.core.api.doc import documentation_view
from anaf.core.api.resource import CsrfExemptResource
ad = {'authentication': auth_engine}
# admin resources
groupResource = CsrfExemptResource(handler=handlers.GroupHandler, **ad)
userResource = CsrfExemptResource(handler=handlers.UserHandler, **ad)
moduleResource = CsrfExemptResource(handler=handlers.ModuleHandler, **ad)
perspectiveResource = CsrfExemptResource(
handler=handlers.PerspectiveHandler, **ad)
# folderResource = CsrfExemptResource(handler = handlers.PageFolderHandler, **ad)
# pageResource = CsrfExemptResource(handler = handlers.PageHandler, **ad)
urlpatterns = patterns('',
# Resources
url(r'^doc$', documentation_view, kwargs={ 'module': handlers}, name="api_admin_doc"),
url(r'^groups$', groupResource, name="api_admin_groups"),
url(r'^group/(?P<accessentity_ptr>\d+)', groupResource, name="api_admin_groups"),
url(r'^users$', userResource, name="api_admin_users"),
url(r'^user/(?P<accessentity_ptr>\d+)', userResource, name="api_admin_users"),
url(r'^modules$', moduleResource, name="api_admin_modules"),
url(r'^module/(?P<object_ptr>\d+)', moduleResource, name="api_admin_modules"),
url(r'^perspectives$', perspectiveResource, name="api_admin_perspectives"),
url(r'^perspective/(?P<object_ptr>\d+)', perspectiveResource, name="api_admin_perspectives"),
# url(r'^folders$', folderResource, name="api_admin_folders"),
# url(r'^folder/(?P<object_ptr>\d+)', folderResource, name="api_admin_folders"),
# url(r'^pages$', pageResource, name="api_admin_pages"),
# url(r'^page/(?P<object_ptr>\d+)', pageResource, name="api_admin_pages"),
)
|
# -*- coding: utf-8 -*-
# Copyright 1999-2020 Alibaba Group Holding Ltd.
#
# 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 functools
import logging
import random
import time
import uuid
from urllib.parse import urlparse
from ...session import new_session
from ..utils import wait_services_ready
from .config import NamespaceConfig, RoleConfig, RoleBindingConfig, ServiceConfig, \
MarsSchedulersConfig, MarsWorkersConfig, MarsWebsConfig
try:
from kubernetes.client.rest import ApiException as K8SApiException
except ImportError: # pragma: no cover
K8SApiException = None
logger = logging.getLogger(__name__)
class KubernetesClusterClient:
def __init__(self, cluster):
self._cluster = cluster
self._endpoint = None
self._session = None
@property
def endpoint(self):
return self._endpoint
@property
def namespace(self):
return self._cluster.namespace
@property
def session(self):
return self._session
def start(self):
self._endpoint = self._cluster.start()
self._session = new_session(self._endpoint).as_default()
def stop(self, wait=False, timeout=0):
self._cluster.stop(wait=wait, timeout=timeout)
def rescale_workers(self, new_scale, min_workers=None, wait=True, timeout=None):
self._session._sess.rescale_workers(
new_scale, min_workers=min_workers, wait=wait, timeout=timeout)
class KubernetesCluster:
_scheduler_config_cls = MarsSchedulersConfig
_worker_config_cls = MarsWorkersConfig
_web_config_cls = MarsWebsConfig
_default_service_port = 7103
def __init__(self, kube_api_client=None, image=None, namespace=None,
scheduler_num=1, scheduler_cpu=None, scheduler_mem=None,
scheduler_mem_limit_ratio=None,
worker_num=1, worker_cpu=None, worker_mem=None,
worker_spill_paths=None, worker_cache_mem=None, min_worker_num=None,
worker_min_cache_mem=None, worker_mem_limit_ratio=None,
web_num=1, web_cpu=None, web_mem=None, web_mem_limit_ratio=None,
service_type=None, timeout=None, **kwargs):
from kubernetes import client as kube_client
self._api_client = kube_api_client
self._core_api = kube_client.CoreV1Api(kube_api_client)
self._rbac_api = kube_client.RbacAuthorizationV1Api(kube_api_client)
self._namespace = namespace
self._image = image
self._timeout = timeout
self._service_type = service_type or 'NodePort'
self._extra_volumes = kwargs.pop('extra_volumes', ())
self._pre_stop_command = kwargs.pop('pre_stop_command', None)
self._log_when_fail = kwargs.pop('log_when_fail', False)
extra_modules = kwargs.pop('extra_modules', None) or []
extra_modules = extra_modules.split(',') if isinstance(extra_modules, str) \
else extra_modules
extra_envs = kwargs.pop('extra_env', None) or dict()
extra_labels = kwargs.pop('extra_labels', None) or dict()
service_port = kwargs.pop('service_port', None) or self._default_service_port
def _override_modules(updates):
modules = set(extra_modules)
updates = updates.split(',') if isinstance(updates, str) \
else updates
modules.update(updates)
return sorted(modules)
def _override_dict(d, updates):
updates = updates or dict()
ret = d.copy()
ret.update(updates)
return ret
_override_envs = functools.partial(_override_dict, extra_envs)
_override_labels = functools.partial(_override_dict, extra_labels)
self._scheduler_num = scheduler_num
self._scheduler_cpu = scheduler_cpu
self._scheduler_mem = scheduler_mem
self._scheduler_mem_limit_ratio = scheduler_mem_limit_ratio
self._scheduler_extra_modules = _override_modules(kwargs.pop('scheduler_extra_modules', []))
self._scheduler_extra_env = _override_envs(kwargs.pop('scheduler_extra_env', None))
self._scheduler_extra_labels = _override_labels(kwargs.pop('scheduler_extra_labels', None))
self._scheduler_service_port = kwargs.pop('scheduler_service_port', None) or service_port
self._worker_num = worker_num
self._worker_cpu = worker_cpu
self._worker_mem = worker_mem
self._worker_mem_limit_ratio = worker_mem_limit_ratio
self._worker_spill_paths = worker_spill_paths
self._worker_cache_mem = worker_cache_mem
self._worker_min_cache_men = worker_min_cache_mem
self._min_worker_num = min_worker_num
self._worker_extra_modules = _override_modules(kwargs.pop('worker_extra_modules', []))
self._worker_extra_env = _override_envs(kwargs.pop('worker_extra_env', None))
self._worker_extra_labels = _override_labels(kwargs.pop('worker_extra_labels', None))
self._worker_service_port = kwargs.pop('worker_service_port', None) or service_port
self._web_num = web_num
self._web_cpu = web_cpu
self._web_mem = web_mem
self._web_mem_limit_ratio = web_mem_limit_ratio
self._web_extra_modules = _override_modules(kwargs.pop('web_extra_modules', []))
self._web_extra_env = _override_envs(kwargs.pop('web_extra_env', None))
self._web_extra_labels = _override_labels(kwargs.pop('web_extra_labels', None))
self._web_service_port = kwargs.pop('web_service_port', None) or service_port
@property
def namespace(self):
return self._namespace
def _get_free_namespace(self):
while True:
namespace = 'mars-ns-' + str(uuid.uuid4().hex)
try:
self._core_api.read_namespace(namespace)
except K8SApiException as ex:
if ex.status != 404: # pragma: no cover
raise
return namespace
def _create_kube_service(self):
if self._service_type != 'NodePort': # pragma: no cover
raise NotImplementedError(f'Service type {self._service_type} not supported')
service_config = ServiceConfig(
'marsservice', service_type='NodePort', port=self._web_service_port,
selector={'mars/service-type': MarsWebsConfig.rc_name},
)
self._core_api.create_namespaced_service(self._namespace, service_config.build())
time.sleep(1)
svc_data = self._core_api.read_namespaced_service('marsservice', self._namespace).to_dict()
port = svc_data['spec']['ports'][0]['node_port']
web_pods = self._core_api.list_namespaced_pod(
self._namespace, label_selector='mars/service-type=' + MarsWebsConfig.rc_name).to_dict()
host_ip = random.choice(web_pods['items'])['status']['host_ip']
# docker desktop use a VM to hold docker processes, hence
# we need to use API address instead
desktop_nodes = self._core_api.list_node(field_selector='metadata.name=docker-desktop').to_dict()
if desktop_nodes['items']: # pragma: no cover
addresses = set(
addr_info['address']
for addr_info in desktop_nodes['items'][0].get('status', {}).get('addresses', ())
)
if host_ip in addresses:
host_ip = urlparse(self._core_api.api_client.configuration.host).netloc.split(':', 1)[0]
return f'http://{host_ip}:{port}'
def _get_ready_pod_count(self, label_selector):
query = self._core_api.list_namespaced_pod(
namespace=self._namespace, label_selector=label_selector).to_dict()
cnt = 0
for el in query['items']:
if el['status']['phase'] in ('Error', 'Failed'):
logger.warning('Error in starting pod, message: %s', el['status']['message'])
continue
if 'status' not in el or 'conditions' not in el['status']:
cnt += 1
elif any(cond['type'] == 'Ready' and cond['status'] == 'True'
for cond in el['status'].get('conditions') or ()):
cnt += 1
return cnt
def _create_namespace(self):
if self._namespace is None:
namespace = self._namespace = self._get_free_namespace()
else:
namespace = self._namespace
self._core_api.create_namespace(NamespaceConfig(namespace).build())
def _create_roles_and_bindings(self):
# create role and binding
role_config = RoleConfig('mars-pod-operator', self._namespace, api_groups='',
resources='pods,replicationcontrollers/scale',
verbs='get,watch,list,patch')
self._rbac_api.create_namespaced_role(self._namespace, role_config.build())
role_binding_config = RoleBindingConfig(
'mars-pod-operator-binding', self._namespace, 'mars-pod-operator', 'default')
self._rbac_api.create_namespaced_role_binding(self._namespace, role_binding_config.build())
def _create_schedulers(self):
schedulers_config = self._scheduler_config_cls(
self._scheduler_num, image=self._image, cpu=self._scheduler_cpu,
memory=self._scheduler_mem, memory_limit_ratio=self._scheduler_mem_limit_ratio,
modules=self._scheduler_extra_modules, volumes=self._extra_volumes,
service_port=self._scheduler_service_port,
pre_stop_command=self._pre_stop_command,
)
schedulers_config.add_simple_envs(self._scheduler_extra_env)
schedulers_config.add_labels(self._scheduler_extra_labels)
self._core_api.create_namespaced_replication_controller(
self._namespace, schedulers_config.build())
def _create_workers(self):
workers_config = self._worker_config_cls(
self._worker_num, image=self._image, cpu=self._worker_cpu,
memory=self._worker_mem, memory_limit_ratio=self._worker_mem_limit_ratio,
spill_volumes=self._worker_spill_paths,
modules=self._worker_extra_modules, volumes=self._extra_volumes,
worker_cache_mem=self._worker_cache_mem,
min_cache_mem=self._worker_min_cache_men,
service_port=self._worker_service_port,
pre_stop_command=self._pre_stop_command,
)
workers_config.add_simple_envs(self._worker_extra_env)
workers_config.add_labels(self._worker_extra_labels)
self._core_api.create_namespaced_replication_controller(
self._namespace, workers_config.build())
def _create_webs(self):
webs_config = self._web_config_cls(
self._web_num, image=self._image, cpu=self._web_cpu, memory=self._web_mem,
memory_limit_ratio=self._web_mem_limit_ratio, modules=self._web_extra_modules,
volumes=self._extra_volumes, service_port=self._web_service_port,
pre_stop_command=self._pre_stop_command,
)
webs_config.add_simple_envs(self._web_extra_env)
webs_config.add_labels(self._web_extra_labels)
self._core_api.create_namespaced_replication_controller(
self._namespace, webs_config.build())
def _create_services(self):
self._create_schedulers()
self._create_workers()
self._create_webs()
def _wait_services_ready(self):
min_worker_num = int(self._min_worker_num or self._worker_num)
limits = [self._scheduler_num, min_worker_num, self._web_num]
selectors = [
'mars/service-type=' + MarsSchedulersConfig.rc_name,
'mars/service-type=' + MarsWorkersConfig.rc_name,
'mars/service-type=' + MarsWebsConfig.rc_name,
]
logger.debug('Start waiting pods to be ready')
wait_services_ready(selectors, limits,
lambda sel: self._get_ready_pod_count(sel),
timeout=self._timeout)
logger.info('All service pods ready.')
def _load_cluster_logs(self):
log_dict = dict()
pod_items = self._core_api.list_namespaced_pod(self._namespace).to_dict()
for item in pod_items['items']:
log_dict[item['metadata']['name']] = self._core_api.read_namespaced_pod_log(
name=item['metadata']['name'], namespace=self._namespace)
return log_dict
def start(self):
try:
self._create_namespace()
self._create_roles_and_bindings()
self._create_services()
self._wait_services_ready()
return self._create_kube_service()
except: # noqa: E722
if self._log_when_fail: # pargma: no cover
logger.error('Error when creating cluster')
for name, log in self._load_cluster_logs().items():
logger.error('Error logs for %s:\n%s', name, log)
self.stop()
raise
def stop(self, wait=False, timeout=0):
from kubernetes.client import CoreV1Api
api = CoreV1Api(self._api_client)
api.delete_namespace(self._namespace)
if wait:
start_time = time.time()
while True:
try:
api.read_namespace(self._namespace)
except K8SApiException as ex:
if ex.status != 404: # pragma: no cover
raise
break
else:
time.sleep(1)
if timeout and time.time() - start_time > timeout: # pragma: no cover
raise TimeoutError
def new_cluster(kube_api_client=None, image=None, scheduler_num=1, scheduler_cpu=None,
scheduler_mem=None, worker_num=1, worker_cpu=None, worker_mem=None,
worker_spill_paths=None, worker_cache_mem=None, min_worker_num=None,
web_num=1, web_cpu=None, web_mem=None, service_type=None,
timeout=None, **kwargs):
"""
:param kube_api_client: Kubernetes API client, can be created with ``new_client_from_config``
:param image: Docker image to use, ``marsproject/mars:<mars version>`` by default
:param scheduler_num: Number of schedulers in the cluster, 1 by default
:param scheduler_cpu: Number of CPUs for every scheduler
:param scheduler_mem: Memory size for every scheduler
:param worker_num: Number of workers in the cluster, 1 by default
:param worker_cpu: Number of CPUs for every worker
:param worker_mem: Memory size for every worker
:param worker_spill_paths: Spill paths for worker pods on hosts
:param worker_cache_mem: Size or ratio of cache memory for every worker
:param min_worker_num: Minimal ready workers
:param web_num: Number of web services in the cluster, 1 by default
:param web_cpu: Number of CPUs for every web service
:param web_mem: Memory size for every web service
:param service_type: Type of Kubernetes Service, currently only ``NodePort`` supported
:param timeout: Timeout when creating clusters
"""
cluster_cls = kwargs.pop('cluster_cls', KubernetesCluster)
cluster = cluster_cls(
kube_api_client, image=image, scheduler_num=scheduler_num, scheduler_cpu=scheduler_cpu,
scheduler_mem=scheduler_mem, worker_num=worker_num, worker_cpu=worker_cpu,
worker_mem=worker_mem, worker_spill_paths=worker_spill_paths, worker_cache_mem=worker_cache_mem,
min_worker_num=min_worker_num, web_num=web_num, web_cpu=web_cpu, web_mem=web_mem,
service_type=service_type, timeout=timeout, **kwargs)
client = KubernetesClusterClient(cluster)
client.start()
return client
|
module.exports = {
MODE: 'production',
PORT: process.env.PORT || 3000,
// PORT: process.env.PORT,
DATA_DIR: process.env.DATA_DIR,
STATIC_DIR: process.env.STATIC_DIR,
};
|
var spa = require('./spa');
module.exports = {
url: spa.url,
elements: {
view: {
selector: '#signin-view'
},
emailInput: {
selector: 'input[name=email]',
},
passwordInput: {
selector: 'input[name=password]'
},
submitButton: {
selector: 'button[type=submit]'
},
},
commands: [{
signin: function () {
this.api.adminUI
.waitForElementVisible('@signinView');
this
.setValue('@emailInput', '[email protected]')
.setValue('@passwordInput', 'test')
.click('@submitButton');
return this;
},
}],
}
|
'use strict';
var obsidian = require('obsidian');
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
const VIEW_TYPE_TODO = 'online.larslockefeer.obsidian-plugin-todo';
var TodoItemStatus;
(function (TodoItemStatus) {
TodoItemStatus[TodoItemStatus["Todo"] = 0] = "Todo";
TodoItemStatus[TodoItemStatus["Done"] = 1] = "Done";
})(TodoItemStatus || (TodoItemStatus = {}));
// eslint-disable-next-line @typescript-eslint/no-namespace
(function (TodoItemStatus) {
function toggleStatus(status) {
switch (status) {
case TodoItemStatus.Todo:
return TodoItemStatus.Done;
case TodoItemStatus.Done:
return TodoItemStatus.Todo;
}
}
TodoItemStatus.toggleStatus = toggleStatus;
})(TodoItemStatus || (TodoItemStatus = {}));
class TodoItem {
constructor(status, description, isSomedayMaybeNote, sourceFilePath, startIndex, length, actionDate) {
this.status = status;
this.description = description;
this.actionDate = actionDate;
this.isSomedayMaybeNote = isSomedayMaybeNote;
this.sourceFilePath = sourceFilePath;
this.startIndex = startIndex;
this.length = length;
}
}
var Icon;
(function (Icon) {
Icon[Icon["Inbox"] = 0] = "Inbox";
Icon[Icon["Reveal"] = 1] = "Reveal";
Icon[Icon["Scheduled"] = 2] = "Scheduled";
Icon[Icon["Someday"] = 3] = "Someday";
Icon[Icon["Today"] = 4] = "Today";
})(Icon || (Icon = {}));
const RenderIcon = (icon, title = '', description = '') => {
const svg = svgForIcon(icon)(title, description);
return parser.parseFromString(svg, 'text/xml').documentElement;
};
const parser = new DOMParser();
const svgForIcon = (icon) => {
switch (icon) {
case Icon.Inbox:
return inboxIcon;
case Icon.Reveal:
return revealIcon;
case Icon.Scheduled:
return scheduledIcon;
case Icon.Someday:
return somedayIcon;
case Icon.Today:
return todayIcon;
}
};
const inboxIcon = (title, description) => `
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24" aria-label="${title + description}">
<title>${title}</title>
<description>${description}</description>
<path d="M0 0h24v24H0V0z" fill="none"/>
<path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5v-3h3.56c.69 1.19 1.97 2 3.45 2s2.75-.81 3.45-2H19v3zm0-5h-4.99c0 1.1-.9 2-2 2s-2-.9-2-2H5V5h14v9z"/>
</svg>
`;
const revealIcon = (title, description) => `
<svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" height="24" viewBox="0 0 24 24" width="24" role="img" aria-label="${title + description}">
<title>${title}</title>
<description>${description}</description>
<rect fill="none" height="24" width="24"/><path d="M9,5v2h6.59L4,18.59L5.41,20L17,8.41V15h2V5H9z"/>
</svg>
`;
const scheduledIcon = (title, description) => `
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24" aria-label="${title + description}">
<title>${title}</title>
<description>${description}</description>
<path d="M0 0h24v24H0V0z" fill="none"/>
<path d="M20 3h-1V1h-2v2H7V1H5v2H4c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 18H4V10h16v11zm0-13H4V5h16v3z"/>
</svg>
`;
const somedayIcon = (title, description) => `
<svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" height="24" viewBox="0 0 24 24" width="24" aria-label="${title + description}">
<title>${title}</title>
<description>${description}</description>
<g><rect fill="none" height="24" width="24"/></g>
<g><g><path d="M20,2H4C3,2,2,2.9,2,4v3.01C2,7.73,2.43,8.35,3,8.7V20c0,1.1,1.1,2,2,2h14c0.9,0,2-0.9,2-2V8.7c0.57-0.35,1-0.97,1-1.69V4 C22,2.9,21,2,20,2z M19,20H5V9h14V20z M20,7H4V4h16V7z"/><rect height="2" width="6" x="9" y="12"/></g></g>
</svg>
`;
const todayIcon = (title, description) => `
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24" aria-label="${title + description}">
<title>${title}</title>
<description>${description}</description>
<path d="M0 0h24v24H0V0z" fill="none"/>
<path d="M22 9.24l-7.19-.62L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21 12 17.27 18.18 21l-1.63-7.03L22 9.24zM12 15.4l-3.76 2.27 1-4.28-3.32-2.88 4.38-.38L12 6.1l1.71 4.04 4.38.38-3.32 2.88 1 4.28L12 15.4z"/>
</svg>
`;
var TodoItemViewPane;
(function (TodoItemViewPane) {
TodoItemViewPane[TodoItemViewPane["Today"] = 0] = "Today";
TodoItemViewPane[TodoItemViewPane["Scheduled"] = 1] = "Scheduled";
TodoItemViewPane[TodoItemViewPane["Inbox"] = 2] = "Inbox";
TodoItemViewPane[TodoItemViewPane["Someday"] = 3] = "Someday";
})(TodoItemViewPane || (TodoItemViewPane = {}));
class TodoItemView extends obsidian.ItemView {
constructor(leaf, props) {
super(leaf);
this.props = props;
this.state = {
activePane: TodoItemViewPane.Today,
};
}
getViewType() {
return VIEW_TYPE_TODO;
}
getDisplayText() {
return 'Todo';
}
getIcon() {
return 'checkmark';
}
onClose() {
return Promise.resolve();
}
setProps(setter) {
this.props = setter(this.props);
this.render();
}
setViewState(newState) {
this.state = newState;
this.render();
}
render() {
const container = this.containerEl.children[1];
container.empty();
container.createDiv('todo-item-view-container', (el) => {
el.createDiv('todo-item-view-toolbar', (el) => {
this.renderToolBar(el);
});
el.createDiv('todo-item-view-items', (el) => {
this.renderItems(el);
});
});
}
renderToolBar(container) {
const activeClass = (pane) => {
return pane === this.state.activePane ? ' active' : '';
};
const setActivePane = (pane) => {
const newState = Object.assign(Object.assign({}, this.state), { activePane: pane });
this.setViewState(newState);
};
container.createDiv(`todo-item-view-toolbar-item${activeClass(TodoItemViewPane.Today)}`, (el) => {
el.appendChild(RenderIcon(Icon.Today, 'Today'));
el.onClickEvent(() => setActivePane(TodoItemViewPane.Today));
});
container.createDiv(`todo-item-view-toolbar-item${activeClass(TodoItemViewPane.Scheduled)}`, (el) => {
el.appendChild(RenderIcon(Icon.Scheduled, 'Scheduled'));
el.onClickEvent(() => setActivePane(TodoItemViewPane.Scheduled));
});
container.createDiv(`todo-item-view-toolbar-item${activeClass(TodoItemViewPane.Inbox)}`, (el) => {
el.appendChild(RenderIcon(Icon.Inbox, 'Inbox'));
el.onClickEvent(() => setActivePane(TodoItemViewPane.Inbox));
});
container.createDiv(`todo-item-view-toolbar-item${activeClass(TodoItemViewPane.Someday)}`, (el) => {
el.appendChild(RenderIcon(Icon.Someday, 'Someday / Maybe'));
el.onClickEvent(() => setActivePane(TodoItemViewPane.Someday));
});
}
renderItems(container) {
this.props.todos
.filter(this.filterForState, this)
.sort(this.sortByActionDate)
.forEach((todo) => {
container.createDiv('todo-item-view-item', (el) => {
el.createDiv('todo-item-view-item-checkbox', (el) => {
el.createEl('input', { type: 'checkbox' }, (el) => {
el.checked = todo.status === TodoItemStatus.Done;
el.onClickEvent(() => {
this.toggleTodo(todo);
});
});
});
el.createDiv('todo-item-view-item-description', (el) => {
obsidian.MarkdownRenderer.renderMarkdown(todo.description, el, todo.sourceFilePath, this);
});
el.createDiv('todo-item-view-item-link', (el) => {
el.appendChild(RenderIcon(Icon.Reveal, 'Open file'));
el.onClickEvent(() => {
this.openFile(todo);
});
});
});
});
}
filterForState(value, _index, _array) {
const isToday = (date) => {
const today = new Date();
return (date.getDate() == today.getDate() &&
date.getMonth() == today.getMonth() &&
date.getFullYear() == today.getFullYear());
};
const isBeforeToday = (date) => {
const today = new Date();
return date < today;
};
const isTodayNote = value.actionDate && (isToday(value.actionDate) || isBeforeToday(value.actionDate));
const isScheduledNote = !value.isSomedayMaybeNote && value.actionDate && !isTodayNote;
switch (this.state.activePane) {
case TodoItemViewPane.Inbox:
return !value.isSomedayMaybeNote && !isTodayNote && !isScheduledNote;
case TodoItemViewPane.Scheduled:
return isScheduledNote;
case TodoItemViewPane.Someday:
return value.isSomedayMaybeNote;
case TodoItemViewPane.Today:
return isTodayNote;
}
}
sortByActionDate(a, b) {
if (!a.actionDate && !b.actionDate) {
if (a.isSomedayMaybeNote && !b.isSomedayMaybeNote) {
return -1;
}
if (!a.isSomedayMaybeNote && b.isSomedayMaybeNote) {
return 1;
}
return 0;
}
return a.actionDate < b.actionDate ? -1 : a.actionDate > b.actionDate ? 1 : 0;
}
toggleTodo(todo) {
this.props.toggleTodo(todo, TodoItemStatus.toggleStatus(todo.status));
}
openFile(todo) {
this.props.openFile(todo.sourceFilePath);
}
}
class TodoParser {
parseTasks(filePath, fileContents) {
return __awaiter(this, void 0, void 0, function* () {
const pattern = /(-|\*) \[(\s|x)?\]\s(.*)/g;
return [...fileContents.matchAll(pattern)].map((task) => this.parseTask(filePath, task));
});
}
parseTask(filePath, entry) {
var _a, _b;
const todoItemOffset = 2; // Strip off `-|* `
const status = entry[2] === 'x' ? TodoItemStatus.Done : TodoItemStatus.Todo;
const description = entry[3];
const datePattern = /#(\d{4}-\d{2}-\d{2})/g;
const somedayPattern = /#(someday)/g;
const dateMatches = description.match(datePattern);
const actionDate = dateMatches != null ? new Date((_a = dateMatches[0]) === null || _a === void 0 ? void 0 : _a.substring(1)) : undefined;
return new TodoItem(status, description, description.match(somedayPattern) != null, filePath, ((_b = entry.index) !== null && _b !== void 0 ? _b : 0) + todoItemOffset, entry[0].length - todoItemOffset, actionDate);
}
}
class TodoIndex {
constructor(vault, listener) {
this.vault = vault;
this.todos = new Map();
this.listeners = [listener];
}
initialize() {
return __awaiter(this, void 0, void 0, function* () {
// TODO: persist index & last sync timestamp; only parse files that changed since then.
const todoMap = new Map();
let numberOfTodos = 0;
const timeStart = new Date().getTime();
const markdownFiles = this.vault.getMarkdownFiles();
for (const file of markdownFiles) {
const todos = yield this.parseTodosInFile(file);
numberOfTodos += todos.length;
if (todos.length > 0) {
todoMap.set(file.path, todos);
}
}
const totalTimeMs = new Date().getTime() - timeStart;
console.log(`[obsidian-plugin-todo] Parsed ${numberOfTodos} TODOs from ${markdownFiles.length} markdown files in (${totalTimeMs / 1000.0}s)`);
this.todos = todoMap;
this.registerEventHandlers();
this.invokeListeners();
});
}
setStatus(todo, newStatus) {
const file = this.vault.getAbstractFileByPath(todo.sourceFilePath);
const fileContents = this.vault.read(file);
fileContents.then((c) => {
const newTodo = `[${newStatus === TodoItemStatus.Done ? 'x' : ' '}] ${todo.description}`;
const newContents = c.substring(0, todo.startIndex) + newTodo + c.substring(todo.startIndex + todo.length);
this.vault.modify(file, newContents);
});
}
indexAbstractFile(file) {
if (!(file instanceof obsidian.TFile)) {
return;
}
this.indexFile(file);
}
indexFile(file) {
this.parseTodosInFile(file).then((todos) => {
this.todos.set(file.path, todos);
this.invokeListeners();
});
}
clearIndex(path, silent = false) {
this.todos.delete(path);
if (!silent) {
this.invokeListeners();
}
}
parseTodosInFile(file) {
return __awaiter(this, void 0, void 0, function* () {
// TODO: Does it make sense to index completed TODOs at all?
const todoParser = new TodoParser();
const fileContents = yield this.vault.cachedRead(file);
return todoParser
.parseTasks(file.path, fileContents)
.then((todos) => todos.filter((todo) => todo.status === TodoItemStatus.Todo));
});
}
registerEventHandlers() {
this.vault.on('create', (file) => {
this.indexAbstractFile(file);
});
this.vault.on('modify', (file) => {
this.indexAbstractFile(file);
});
this.vault.on('delete', (file) => {
this.clearIndex(file.path);
});
// We could simply change the references to the old path, but parsing again does the trick as well
this.vault.on('rename', (file, oldPath) => {
this.clearIndex(oldPath);
this.indexAbstractFile(file);
});
}
invokeListeners() {
const todos = [].concat(...Array.from(this.todos.values()));
this.listeners.forEach((listener) => listener(todos));
}
}
class TodoPlugin extends obsidian.Plugin {
constructor(app, manifest) {
super(app, manifest);
this.todoIndex = new TodoIndex(this.app.vault, this.tick.bind(this));
}
onload() {
return __awaiter(this, void 0, void 0, function* () {
this.registerView(VIEW_TYPE_TODO, (leaf) => {
const todos = [];
const props = {
todos: todos,
openFile: (filePath) => {
const file = this.app.vault.getAbstractFileByPath(filePath);
this.app.workspace.splitActiveLeaf().openFile(file);
},
toggleTodo: (todo, newStatus) => {
this.todoIndex.setStatus(todo, newStatus);
},
};
this.view = new TodoItemView(leaf, props);
return this.view;
});
if (this.app.workspace.layoutReady) {
this.initLeaf();
yield this.prepareIndex();
}
else {
this.registerEvent(this.app.workspace.on('layout-ready', this.initLeaf.bind(this)));
this.registerEvent(this.app.workspace.on('layout-ready', () => __awaiter(this, void 0, void 0, function* () { return yield this.prepareIndex(); })));
}
});
}
onunload() {
this.app.workspace.getLeavesOfType(VIEW_TYPE_TODO).forEach((leaf) => leaf.detach());
}
initLeaf() {
if (this.app.workspace.getLeavesOfType(VIEW_TYPE_TODO).length) {
return;
}
this.app.workspace.getRightLeaf(false).setViewState({
type: VIEW_TYPE_TODO,
});
}
prepareIndex() {
return __awaiter(this, void 0, void 0, function* () {
yield this.todoIndex.initialize();
});
}
tick(todos) {
this.view.setProps((currentProps) => {
return Object.assign(Object.assign({}, currentProps), { todos: todos });
});
}
}
module.exports = TodoPlugin;
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibWFpbi5qcyIsInNvdXJjZXMiOlsibm9kZV9tb2R1bGVzL3RzbGliL3RzbGliLmVzNi5qcyIsImNvbnN0YW50cy50cyIsIm1vZGVsL1RvZG9JdGVtLnRzIiwidWkvaWNvbnMudHMiLCJ1aS9Ub2RvSXRlbVZpZXcudHMiLCJtb2RlbC9Ub2RvUGFyc2VyLnRzIiwibW9kZWwvVG9kb0luZGV4LnRzIiwibWFpbi50cyJdLCJzb3VyY2VzQ29udGVudCI6WyIvKiEgKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqK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ztcclxuICAgICAgICAgICAgICAgIGNhc2UgNDogXy5sYWJlbCsrOyByZXR1cm4geyB2YWx1ZTogb3BbMV0sIGRvbmU6IGZhbHNlIH07XHJcbiAgICAgICAgICAgICAgICBjYXNlIDU6IF8ubGFiZWwrKzsgeSA9IG9wWzFdOyBvcCA9IFswXTsgY29udGludWU7XHJcbiAgICAgICAgICAgICAgICBjYXNlIDc6IG9wID0gXy5vcHMucG9wKCk7IF8udHJ5cy5wb3AoKTsgY29udGludWU7XHJcbiAgICAgICAgICAgICAgICBkZWZhdWx0OlxyXG4gICAgICAgICAgICAgICAgICAgIGlmICghKHQgPSBfLnRyeXMsIHQgPSB0Lmxlbmd0aCA+IDAgJiYgdFt0Lmxlbmd0aCAtIDFdKSAmJiAob3BbMF0gPT09IDYgfHwgb3BbMF0gPT09IDIpKSB7IF8gPSAwOyBjb250aW51ZTsgfVxyXG4gICAgICAgICAgICAgICAgICAgIGlmIChvcFswXSA9PT0gMyAmJiAoIXQgfHwgKG9wWzFdID4gdFswXSAmJiBvcFsxXSA8IHRbM10pKSkgeyBfLmxhYmVsID0gb3BbMV07IGJyZWFrOyB9XHJcbiAgICAgICAgICAgICAgICAgICAgaWYgKG9wWzBdID09PSA2ICYmIF8ubGFiZWwgPCB0WzFdKSB7IF8ubGFiZWwgPSB0WzFdOyB0ID0gb3A7IGJyZWFrOyB9XHJcbiAgICAgICAgICAgICAgICAgICAgaWYgKHQgJiYgXy5sYWJlbCA8IHRbMl0pIHsgXy5sYWJlbCA9IHRbMl07IF8ub3BzLnB1c2gob3ApOyBicmVhazsgfVxyXG4gICAgICAgICAgICAgICAgICAgIGlmICh0WzJdKSBfLm9wcy5wb3AoKTtcclxuICAgICAgICAgICAgICAgICAgICBfLnRyeXMucG9wKCk7IGNvbnRpbnVlO1xyXG4gICAgICAgICAgICB9XHJcbiAgICAgICAgICAgIG9wID0gYm9keS5jYWxsKHRoaXNBcmcsIF8pO1xyXG4gICAgICAgIH0gY2F0Y2ggKGUpIH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UFDLE1BQU0sRUFBRSxDQUFDLENBQUM7S0FDckY7SUFFRCxRQUFRO1FBQ04sSUFBSSxJQUFJLENBQUMsR0FBRyxDQUFDLFNBQVMsQ0FBQyxlQUFlLENBQUMsY0FBYyxDQUFDLENBQUMsTUFBTSxFQUFFO1lBQzdELE9BQU87U0FDUjtRQUNELElBQUksQ0FBQyxHQUFHLENBQUMsU0FBUyxDQUFDLFlBQVksQ0FBQyxLQUFLLENBQUMsQ0FBQyxZQUFZLENBQUM7WUFDbEQsSUFBSSxFQUFFLGNBQWM7U0FDckIsQ0FBQyxDQUFDO0tBQ0o7SUFFSyxZQUFZOztZQUNoQixNQUFNLElBQUksQ0FBQyxTQUFTLENBQUMsVUFBVSxFQUFFLENBQUM7U0FDbkM7S0FBQTtJQUVELElBQUksQ0FBQyxLQUFpQjtRQUNwQixJQUFJLENBQUMsSUFBSSxDQUFDLFFBQVEsQ0FBQyxDQUFDLFlBQStCO1lBQ2pELHVDQUNLLFlBQVksS0FDZixLQUFLLEVBQUUsS0FBSyxJQUNaO1NBQ0gsQ0FBQyxDQUFDO0tBQ0o7Ozs7OyJ9
|
/*
* Copyright (c) 2010 WiYun Inc.
* Author: luma([email protected])
*
* For all entities this program is free software; you can redistribute
* it and/or modify it under the terms of the 'WiEngine' license with
* the additional provision that 'WiEngine' must be credited in a manner
* that can be be observed by end users, for example, in the credits or during
* start up. (please find WiEngine logo in sdk's logo folder)
*
* 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.
*/
#ifndef __wyPrimitives_h__
#define __wyPrimitives_h__
#include "wyTypes.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* 画点
*
* @param x 点的x位置
* @param y 点的y位置
*/
WIENGINE_API void wyDrawPoint(float x, float y);
/**
* 画点,可以画多个点,报存在p指针中,length是p浮点的长度
*
* @param p 点坐标
* @param length p的长度, 是点数乘以2,注意不是点数
*/
WIENGINE_API void wyDrawPoints(float* p, size_t length);
/**
* 画线
*
* @param x1 起始点x位置
* @param y1 起始点y位置
* @param x2 结束点x位置
* @param y2 结束点y位置
*/
WIENGINE_API void wyDrawLine(float x1, float y1, float x2, float y2);
/**
* 画一条路径
*
* @param points 路径上的点,偶数位置是x坐标,奇数位置是y坐标
* @param length points长度,是点数乘以2,注意不是点数
*/
WIENGINE_API void wyDrawPath(float* points, size_t length);
/**
* 画一条虚线路径
*
* @param points 路径上的点,偶数位置是x坐标,奇数位置是y坐标
* @param length points长度,是点数乘以2,注意不是点数
* @param dashLength 虚线间隔
*/
WIENGINE_API void wyDrawDashPath(float* points, size_t length, float dashLength);
/**
* 画虚线
*
* @param x1 起始点x位置
* @param y1 起始点y位置
* @param x2 结束点x位置
* @param y2 结束点y位置
* @param dashLength 虚线间隔
*/
WIENGINE_API void wyDrawDashLine(float x1, float y1, float x2, float y2, float dashLength);
/**
* 画多边形
*
* @param p 多边形的端点
* @param length \c p中浮点数个数
* @param close 是否闭合多边形
*/
WIENGINE_API void wyDrawPoly(float* p, size_t length, bool close);
/**
* 画矩形
*
* @param p 矩形顶点, 必须包含8个元素以表示4个顶点坐标
*/
WIENGINE_API void wyDrawRect(float* p);
/**
* \if English
* Draw a rect
*
* @param r \link wyRect wyRect\endlink
* \else
* 画矩形
*
* @param r \link wyRect wyRect\endlink
* \endif
*/
WIENGINE_API void wyDrawRect2(wyRect& r);
/**
* 画圆形,这里画的是一个近似圆型
*
* @param centerX 圆心x位置
* @param centerY 圆心y位置
* @param r 半径
* @param radiusLineAngle 半径线与x轴成的角度,正值表示逆时针,负值表示顺时针
* @param segments 圆周分段数,分段越多越近似圆形
* @param drawLineToCenter 是否绘制半径线
*/
WIENGINE_API void wyDrawCircle(float centerX, float centerY, float r, float radiusLineAngle, int segments, bool drawLineToCenter);
/**
* \if English
* Draw a circle with a fill color
*
* @param centerX center x position of circle
* @param centerY center y position of circle
* @param r radius
* @param segments segments of circle, the more it is, the more smoother circle is
* @param color fill color
* \else
* 画圆形,这里画的是一个近似圆型
*
* @param centerX 圆心x位置
* @param centerY 圆心y位置
* @param r 半径
* @param segments 圆周分段数,分段越多越近似圆形
* @param color 填充色
* \endif
*/
WIENGINE_API void wyDrawSolidCircle(float centerX, float centerY, float r, int segments, wyColor4B color);
/**
* 画贝塞尔曲线
*
* @param c \link wyBezierConfig wyBezierConfig\endlink
* @param segments 分段数,分段数越多,曲线越平滑
*/
WIENGINE_API void wyDrawBezier(wyBezierConfig& c, int segments);
/**
* 画拉格朗日曲线
*
* @param c \link wyLagrangeConfig wyLagrangeConfig\endlink
* @param segments 线段数,越多画的越精细,当然速度也越慢
*/
WIENGINE_API void wyDrawLagrange(wyLagrangeConfig& c, int segments);
/**
* 内旋轮线
*
* @param c \link wyHypotrochoidConfig wyHypotrochoidConfig\endlink
* @param segments 分段数,分段数越多,曲线越平滑
*/
WIENGINE_API void wyDrawHypotrochoid(wyHypotrochoidConfig& c, int segments);
/**
* 画贴图
*
* @param texture
* @param texW 贴图的有效宽度
* @param texH 贴图的有效高度
* @param x 贴图绘制目标区域的x坐标
* @param y 贴图绘制目标区域的y坐标
* @param w 贴图绘制目标区域的宽度
* @param h 贴图绘制目标区域的高度
* @param flipX 标识是否以Y轴为转动轴翻转图片
* @param flipY 标识是否以X轴为转动轴翻转图片
*/
WIENGINE_API void wyDrawTexture(int texture, float texW, float texH, float x, float y, float w, float h, bool flipX, bool flipY);
/**
* 画贴图
*
* @param texture
* @param texRect 使用的贴图区域,x,y为左下点
* @param texW 贴图的有效宽度
* @param texH 贴图的有效高度
* @param x 贴图绘制目标区域的x坐标
* @param y 贴图绘制目标区域的y坐标
* @param w 贴图绘制目标区域的宽度
* @param h 贴图绘制目标区域的高度
* @param flipX 标识是否以Y轴为转动轴翻转图片
* @param flipY 标识是否以X轴为转动轴翻转图片
*/
WIENGINE_API void wyDrawTexture2(int texture, wyRect texRect, float texW, float texH, float x, float y, float w, float h, bool flipX, bool flipY);
/**
* 画填充多边形, 顶点采用逆时针或顺时针
*
* @param p 矩形顶点
* @param length 长度
* @param color 填充颜色
*/
WIENGINE_API void wyDrawSolidPoly(float* p, size_t length, wyColor4B color);
/**
* 画填充矩形, 顶点采用逆时针或顺时针
*
* @param p 矩形顶点
* @param color 填充颜色
*/
WIENGINE_API void wyDrawSolidRect(float* p, wyColor4B color);
#ifdef __cplusplus
}
#endif
#endif // __wyPrimitives_h__
|
Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:57:54) [MSC v.1924 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> nome = 'Gianne'
>>> idade = 25
>>> peso = 58
>>> print('nome,idade, peso')
nome,idade, peso
>>> print(nome, idade, peso)
Gianne 25 58
>>> |
import { saveAs } from "file-saver";
import { Document, ImageRun, Packer, Paragraph, TextRun } from "docx";
export const generateDoc=(testQuestions, fileName)=>{
const docSections=[];
testQuestions.forEach((q,qi)=>{
const child=[];
child.push(new Paragraph({
children: [new TextRun({text:`Question ${qi+1}:`, bold:true})],
}))
q.images.forEach((image,i)=>{
// let imgWidth = 0;
// let imgHeight = 0;
const img = new Image();
img.src = image;
// img.onload = function() {
// imgWidth = img.naturalWidth;
// imgHeight = img.naturalHeight;
// }
child.push(new Paragraph(q.text[i]));
child.push(
new Paragraph({
children: [
new ImageRun({
data: q.images[i],
transformation: {
width:img.naturalWidth,
height: img.naturalHeight
}
})
]
})
)
})
docSections.push({children:child})
})
const doc = new Document({
sections: docSections
});
Packer.toBlob(doc).then(blob => {
saveAs(blob, `${fileName}.docx`);
});
} |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jsonp = require('jsonp');
var _jsonp2 = _interopRequireDefault(_jsonp);
var _objectToGetParams = require('./utils/objectToGetParams');
var _objectToGetParams2 = _interopRequireDefault(_objectToGetParams);
var _shareCountFactory = require('./utils/shareCountFactory');
var _shareCountFactory2 = _interopRequireDefault(_shareCountFactory);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function getLinkedinShareCount(shareUrl, callback) {
var url = 'https://www.linkedin.com/countserv/count/share';
return (0, _jsonp2.default)(url + (0, _objectToGetParams2.default)({
url: shareUrl,
format: 'jsonp'
}), function (err, data) {
callback(data ? data.count : undefined);
});
}
exports.default = (0, _shareCountFactory2.default)(getLinkedinShareCount); |
import math
import warnings
import cupy as np
try:
import PIL
PIL_rotate_kwargs_supported = {
# [moviepy rotate argument name,
# PIL.rotate argument supported,
# minimum PIL version required]
"fillcolor": ["bg_color", False, (5, 2, 0)],
"center": ["center", False, (4, 0, 0)],
"translate": ["translate", False, (4, 0, 0)],
}
if hasattr(PIL, "__version__"):
# check support for PIL.rotate arguments
PIL__version_info__ = tuple(int(n) for n in PIL.__version__ if n.isdigit())
for PIL_rotate_kw_name, support_data in PIL_rotate_kwargs_supported.items():
if PIL__version_info__ >= support_data[2]:
PIL_rotate_kwargs_supported[PIL_rotate_kw_name][1] = True
Image = PIL.Image
except ImportError: # pragma: no cover
Image = None
def rotate(
clip,
angle,
unit="deg",
resample="bicubic",
expand=True,
center=None,
translate=None,
bg_color=None,
):
"""
Rotates the specified clip by ``angle`` degrees (or radians) anticlockwise
If the angle is not a multiple of 90 (degrees) or ``center``, ``translate``,
and ``bg_color`` are not ``None``, the package ``pillow`` must be installed,
and there will be black borders. You can make them transparent with:
>>> new_clip = clip.add_mask().rotate(72)
Parameters
----------
clip : VideoClip
A video clip.
angle : float
Either a value or a function angle(t) representing the angle of rotation.
unit : str, optional
Unit of parameter `angle` (either "deg" for degrees or "rad" for radians).
resample : str, optional
An optional resampling filter. One of "nearest", "bilinear", or "bicubic".
expand : bool, optional
If true, expands the output image to make it large enough to hold the
entire rotated image. If false or omitted, make the output image the same
size as the input image.
translate : tuple, optional
An optional post-rotate translation (a 2-tuple).
center : tuple, optional
Optional center of rotation (a 2-tuple). Origin is the upper left corner.
bg_color : tuple, optional
An optional color for area outside the rotated image. Only has effect if
``expand`` is true.
"""
if Image:
try:
resample = {
"bilinear": Image.BILINEAR,
"nearest": Image.NEAREST,
"bicubic": Image.BICUBIC,
}[resample]
except KeyError:
raise ValueError(
"'resample' argument must be either 'bilinear', 'nearest' or 'bicubic'"
)
if hasattr(angle, "__call__"):
get_angle = angle
else:
get_angle = lambda t: angle
def filter(get_frame, t):
angle = get_angle(t)
im = get_frame(t)
if unit == "rad":
angle = math.degrees(angle)
angle %= 360
if not center and not translate and not bg_color:
if (angle == 0) and expand:
return im
if (angle == 90) and expand:
transpose = [1, 0] if len(im.shape) == 2 else [1, 0, 2]
return np.transpose(im, axes=transpose)[::-1]
elif (angle == 270) and expand:
transpose = [1, 0] if len(im.shape) == 2 else [1, 0, 2]
return np.transpose(im, axes=transpose)[:, ::-1]
elif (angle == 180) and expand:
return im[::-1, ::-1]
if not Image:
raise ValueError(
'Without "Pillow" installed, only angles that are a multiple of 90'
" without centering, translation and background color transformations"
' are supported, please install "Pillow" with `pip install pillow`'
)
# build PIL.rotate kwargs
kwargs, _locals = ({}, locals())
for PIL_rotate_kw_name, (
kw_name,
supported,
min_version,
) in PIL_rotate_kwargs_supported.items():
# get the value passed to rotate FX from `locals()` dictionary
kw_value = _locals[kw_name]
if supported: # if argument supported by PIL version
kwargs[PIL_rotate_kw_name] = kw_value
else:
if kw_value is not None: # if not default value
warnings.warn(
f"rotate '{kw_name}' argument is not supported"
" by your Pillow version and is being ignored. Minimum"
" Pillow version required:"
f" v{'.'.join(str(n) for n in min_version)}",
UserWarning,
)
# PIL expects uint8 type data. However a mask image has values in the
# range [0, 1] and is of float type. To handle this we scale it up by
# a factor 'a' for use with PIL and then back again by 'a' afterwards.
if im.dtype == "float64":
# this is a mask image
a = 255.0
else:
a = 1
# call PIL.rotate
return (
np.array(
Image.fromarray(np.array(a * im).astype(np.uint8)).rotate(
angle, expand=expand, resample=resample, **kwargs
)
)
/ a
)
return clip.transform(filter, apply_to=["mask"])
|
deepmacDetailCallback("0050c2bfc000/36",[{"a":"140 58th street Brooklyn NY US 11220","o":"Altronix Corporation","d":"2010-01-31","t":"add","s":"ieee","c":"US"}]);
|
# -*- coding: utf-8 -*-
import datetime
from collections import OrderedDict
from gluon import current, A, DIV, IS_EMPTY_OR, IS_IN_SET, IS_NOT_EMPTY, SPAN, TAG, URL
from gluon.storage import Storage
from s3 import FS, IS_ONE_OF
from s3dal import original_tablename
# =============================================================================
# UI options per organisation
#
UI_DEFAULTS = {"case_bamf_first": False,
"case_document_templates": False,
"case_header_protection_themes": False,
"case_hide_default_org": False,
"case_use_action_tab": False,
"case_use_address": True,
"case_use_arrival_date": True,
"case_use_education": False,
"case_use_flags": True,
"case_use_notes": True,
"case_use_occupation": True,
"case_use_residence_status": True,
"case_use_service_contacts": True,
"case_lodging": "site", # "site"|"text"|None
"case_lodging_dates": True,
"activity_closure": True,
"activity_comments": True,
"activity_use_sector": True,
"activity_need_details": True,
"activity_follow_up": True,
"appointments_staff_link": False,
"appointments_use_organizer": False,
"response_planning": True,
"response_themes_sectors": False,
"response_themes_needs": False,
}
UI_OPTIONS = {"LEA": {"case_bamf_first": True,
"case_document_templates": True,
"case_header_protection_themes": True,
"case_hide_default_org": True,
"case_use_action_tab": True,
"case_use_address": False,
"case_use_arrival_date": False,
"case_use_education": True,
"case_use_flags": False,
"case_use_notes": False,
"case_use_occupation": False,
"case_use_residence_status": False,
"case_use_service_contacts": False,
"case_lodging": "text",
"case_lodging_dates": False,
"activity_closure": False,
"activity_comments": False,
"activity_use_sector": False,
"activity_need_details": False,
"activity_follow_up": False,
"appointments_staff_link": True,
"appointments_use_organizer": True,
"response_planning": False,
"response_themes_sectors": True,
"response_themes_needs": True,
},
}
UI_TYPES = {"LEA Ellwangen": "LEA",
}
def get_ui_options():
""" Get the UI options for the current user's root organisation """
ui_options = dict(UI_DEFAULTS)
ui_type = UI_TYPES.get(current.auth.root_org_name())
if ui_type:
ui_options.update(UI_OPTIONS[ui_type])
return ui_options
def get_ui_option(key):
""" Getter for UI options, for lazy deployment settings """
def getter(default=None):
return get_ui_options().get(key, default)
return getter
# =============================================================================
def config(settings):
"""
DRKCM Template: Case Management, German Red Cross
"""
T = current.T
settings.base.system_name = "RefuScope"
settings.base.system_name_short = "RefuScope"
# PrePopulate data
settings.base.prepopulate += ("DRKCM",)
settings.base.prepopulate_demo += ("DRKCM/Demo",)
# Theme (folder to use for views/layout.html)
settings.base.theme = "DRK"
# Authentication settings
# Should users be allowed to register themselves?
settings.security.self_registration = False
# Do new users need to verify their email address?
#settings.auth.registration_requires_verification = True
# Do new users need to be approved by an administrator prior to being able to login?
#settings.auth.registration_requires_approval = True
# Request Organisation during user registration
settings.auth.registration_requests_organisation = True
# Suppress popup-link for creating organisations during user registration
settings.auth.registration_organisation_link_create = False
settings.auth.registration_link_user_to = {"staff": T("Staff"),
#"volunteer": T("Volunteer"),
}
# Don't show alternatives, just default
settings.auth.registration_link_user_to_default = ["staff"]
# Assign all new users the STAFF role for their default realm
settings.auth.registration_roles = {None: ("STAFF",)}
# Disable password-retrieval feature
settings.auth.password_retrieval = False
# Approval emails get sent to all admins
settings.mail.approver = "ADMIN"
# Restrict the Location Selector to just certain countries
# NB This can also be over-ridden for specific contexts later
# e.g. Activities filtered to those of parent Project
settings.gis.countries = ("DE",)
gis_levels = ("L1", "L2", "L3")
# Uncomment to display the Map Legend as a floating DIV
settings.gis.legend = "float"
# Uncomment to Disable the Postcode selector in the LocationSelector
#settings.gis.postcode_selector = False # @ToDo: Vary by country (include in the gis_config!)
# Uncomment to show the Print control:
# http://eden.sahanafoundation.org/wiki/UserGuidelines/Admin/MapPrinting
#settings.gis.print_button = True
# Settings suitable for Housing Units
# - move into customise fn if also supporting other polygons
settings.gis.precision = 5
settings.gis.simplify_tolerance = 0
settings.gis.bbox_min_size = 0.001
#settings.gis.bbox_offset = 0.007
# L10n settings
# Languages used in the deployment (used for Language Toolbar & GIS Locations)
# http://www.loc.gov/standards/iso639-2/php/code_list.php
settings.L10n.languages = OrderedDict([
("de", "German"),
("en", "English"),
])
# Default language for Language Toolbar (& GIS Locations in future)
settings.L10n.default_language = "de"
# Uncomment to Hide the language toolbar
#settings.L10n.display_toolbar = False
# Default timezone for users
#settings.L10n.utc_offset = "+0100"
# Number formats (defaults to ISO 31-0)
# Decimal separator for numbers (defaults to ,)
settings.L10n.decimal_separator = "."
# Thousands separator for numbers (defaults to space)
settings.L10n.thousands_separator = ","
# Uncomment this to Translate Layer Names
#settings.L10n.translate_gis_layer = True
# Uncomment this to Translate Location Names
#settings.L10n.translate_gis_location = True
# Uncomment this to Translate Organisation Names/Acronyms
#settings.L10n.translate_org_organisation = True
# Finance settings
settings.fin.currencies = {
"EUR" : "Euros",
# "GBP" : "Great British Pounds",
# "USD" : "United States Dollars",
}
settings.fin.currency_default = "EUR"
# Do not require international phone number format
settings.msg.require_international_phone_numbers = False
# Security Policy
# http://eden.sahanafoundation.org/wiki/S3AAA#System-widePolicy
# 1: Simple (default): Global as Reader, Authenticated as Editor
# 2: Editor role required for Update/Delete, unless record owned by session
# 3: Apply Controller ACLs
# 4: Apply both Controller & Function ACLs
# 5: Apply Controller, Function & Table ACLs
# 6: Apply Controller, Function, Table ACLs and Entity Realm
# 7: Apply Controller, Function, Table ACLs and Entity Realm + Hierarchy
# 8: Apply Controller, Function, Table ACLs, Entity Realm + Hierarchy and Delegations
#
settings.security.policy = 7 # Hierarchical Realms
# Version details on About-page require login
settings.security.version_info_requires_login = True
# -------------------------------------------------------------------------
# General UI settings
#
settings.ui.calendar_clear_icon = True
# -------------------------------------------------------------------------
# Document settings
#
settings.doc.mailmerge_fields = {"ID": "pe_label",
"Vorname": "first_name",
"Name": "last_name",
"Geburtsdatum": "date_of_birth",
"Land": "pr_person_details.nationality",
"Registrierungsdatum": "dvr_case.date",
}
# -------------------------------------------------------------------------
# Realm Rules
#
def drk_realm_entity(table, row):
"""
Assign a Realm Entity to records
"""
db = current.db
s3db = current.s3db
tablename = original_tablename(table)
realm_entity = 0
if tablename == "pr_person":
# Client records are owned by the organisation
# the case is assigned to
ctable = s3db.dvr_case
query = (ctable.person_id == row.id) & \
(ctable.deleted == False)
case = db(query).select(ctable.organisation_id,
limitby = (0, 1),
).first()
if case and case.organisation_id:
realm_entity = s3db.pr_get_pe_id("org_organisation",
case.organisation_id,
)
elif tablename in ("dvr_case_activity",
"dvr_case_details",
"dvr_case_flag_case",
"dvr_case_language",
"dvr_note",
"dvr_residence_status",
"pr_group_membership",
"pr_person_details",
"pr_person_tag",
):
# Inherit from person via person_id
table = s3db.table(tablename)
ptable = s3db.pr_person
query = (table._id == row.id) & \
(ptable.id == table.person_id)
person = db(query).select(ptable.realm_entity,
limitby = (0, 1),
).first()
if person:
realm_entity = person.realm_entity
elif tablename in ("pr_address",
"pr_contact",
"pr_contact_emergency",
"pr_image",
):
# Inherit from person via PE
table = s3db.table(tablename)
ptable = s3db.pr_person
query = (table._id == row.id) & \
(ptable.pe_id == table.pe_id)
person = db(query).select(ptable.realm_entity,
limitby = (0, 1),
).first()
if person:
realm_entity = person.realm_entity
elif tablename in ("dvr_case_activity_need",
"dvr_case_activity_update",
"dvr_response_action",
):
# Inherit from case activity
table = s3db.table(tablename)
atable = s3db.dvr_case_activity
query = (table._id == row.id) & \
(atable.id == table.case_activity_id)
activity = db(query).select(atable.realm_entity,
limitby = (0, 1),
).first()
if activity:
realm_entity = activity.realm_entity
elif tablename == "pr_group":
# No realm-entity for case groups
table = s3db.pr_group
query = table._id == row.id
group = db(query).select(table.group_type,
limitby = (0, 1),
).first()
if group and group.group_type == 7:
realm_entity = None
elif tablename == "project_task":
# Inherit the realm entity from the assignee
assignee_pe_id = row.pe_id
instance_type = s3db.pr_instance_type(assignee_pe_id)
if instance_type:
table = s3db.table(instance_type)
query = table.pe_id == assignee_pe_id
assignee = db(query).select(table.realm_entity,
limitby = (0, 1),
).first()
if assignee and assignee.realm_entity:
realm_entity = assignee.realm_entity
# If there is no assignee, or the assignee has no
# realm entity, fall back to the user organisation
if realm_entity == 0:
auth = current.auth
user_org_id = auth.user.organisation_id if auth.user else None
if user_org_id:
realm_entity = s3db.pr_get_pe_id("org_organisation",
user_org_id,
)
return realm_entity
settings.auth.realm_entity = drk_realm_entity
# -------------------------------------------------------------------------
# CMS Module Settings
#
settings.cms.hide_index = True
# -------------------------------------------------------------------------
# Human Resource Module Settings
#
settings.hrm.teams_orgs = True
settings.hrm.staff_departments = False
settings.hrm.use_id = False
settings.hrm.use_address = True
settings.hrm.use_description = False
settings.hrm.use_trainings = False
settings.hrm.use_certificates = False
settings.hrm.use_credentials = False
settings.hrm.use_awards = False
settings.hrm.use_skills = False
settings.hrm.staff_experience = False
settings.hrm.vol_experience = False
# -------------------------------------------------------------------------
# Organisations Module Settings
#
settings.org.sector = True
# But hide it from the rheader
settings.org.sector_rheader = False
settings.org.branches = True
settings.org.offices_tab = False
settings.org.country = False
# -------------------------------------------------------------------------
# Persons Module Settings
#
settings.pr.hide_third_gender = False
settings.pr.separate_name_fields = 2
settings.pr.name_format= "%(last_name)s, %(first_name)s"
settings.pr.contacts_tabs = {"all": "Contact Info"}
# -------------------------------------------------------------------------
# DVR Module Settings and Customizations
#
# Enable features to manage case flags
settings.dvr.case_flags = True
# Allow cases to belong to multiple case groups ("households")
#settings.dvr.multiple_case_groups = True
# Enable household size in cases, "auto" for automatic counting
settings.dvr.household_size = "auto"
# Group/Case activities per sector
settings.dvr.activity_sectors = True
# Case activities use status field
settings.dvr.case_activity_use_status = True
# Case activities cover multiple needs
settings.dvr.case_activity_needs_multiple = True
# Case activities use follow-up fields
settings.dvr.case_activity_follow_up = get_ui_option("activity_follow_up")
# Beneficiary documents-tab includes case activity attachments
settings.dvr.case_include_activity_docs = True
# Manage individual response actions in case activities
settings.dvr.manage_response_actions = True
# Planning response actions, or just documenting them?
settings.dvr.response_planning = get_ui_option("response_planning")
# Use response themes
settings.dvr.response_themes = True
# Response themes are org-specific
settings.dvr.response_themes_org_specific = True
# Do not use response types
settings.dvr.response_types = False
# Response types hierarchical
settings.dvr.response_types_hierarchical = True
# Response themes organized by sectors
settings.dvr.response_themes_sectors = get_ui_option("response_themes_sectors")
# Response themes linked to needs
settings.dvr.response_themes_needs = get_ui_option("response_themes_needs")
# Expose flags to mark appointment types as mandatory
settings.dvr.mandatory_appointments = False
# Appointments with personal presence update last_seen_on
settings.dvr.appointments_update_last_seen_on = False
# Automatically update the case status when appointments are completed
settings.dvr.appointments_update_case_status = True
# Automatically close appointments when registering certain case events
settings.dvr.case_events_close_appointments = True
# Allowance payments update last_seen_on
#settings.dvr.payments_update_last_seen_on = True
# Configure a regular expression pattern for ID Codes (QR Codes)
#settings.dvr.id_code_pattern = "(?P<label>[^,]*),(?P<family>[^,]*),(?P<last_name>[^,]*),(?P<first_name>[^,]*),(?P<date_of_birth>[^,]*),.*"
# Issue a "not checked-in" warning in case event registration
#settings.dvr.event_registration_checkin_warning = True
# -------------------------------------------------------------------------
def customise_doc_document_resource(r, tablename):
if r.controller == "dvr" or r.function == "organisation":
s3db = current.s3db
table = s3db.doc_document
# Hide URL field
field = table.url
field.readable = field.writable = False
# Custom label for date-field
field = table.date
field.label = T("Uploaded on")
field.default = r.utcnow.date()
field.writable = False
# Custom label for name-field
field = table.name
field.label = T("Title")
# List fields
list_fields = ["name",
"file",
"date",
"comments",
]
s3db.configure("doc_document",
list_fields = list_fields,
)
settings.customise_doc_document_resource = customise_doc_document_resource
# -------------------------------------------------------------------------
def customise_doc_document_controller(**attr):
s3db = current.s3db
s3 = current.response.s3
current.deployment_settings.ui.export_formats = None
if current.request.controller == "dvr":
# Use custom rheader for case perspective
attr["rheader"] = drk_dvr_rheader
# Set contacts-method to retain the tab
s3db.set_method("pr", "person",
method = "contacts",
action = s3db.pr_Contacts,
)
# Custom prep
standard_prep = s3.prep
def custom_prep(r):
# Call standard prep
if callable(standard_prep):
result = standard_prep(r)
else:
result = True
if r.controller == "dvr" and r.interactive:
table = r.table
field = table.doc_id
field.represent = s3db.dvr_DocEntityRepresent(show_link=True)
return result
s3.prep = custom_prep
return attr
settings.customise_doc_document_controller = customise_doc_document_controller
# -------------------------------------------------------------------------
def customise_dvr_home():
""" Do not redirect to person-controller """
return {"module_name": T("Case Consulting"),
}
settings.customise_dvr_home = customise_dvr_home
# -------------------------------------------------------------------------
def pr_address_onaccept(form):
"""
Custom onaccept to set the person's Location to the Private Address
- unless their case is associated with a Site
"""
try:
record_id = form.vars.id
except AttributeError:
# Nothing we can do
return
db = current.db
s3db = current.s3db
atable = db.pr_address
row = db(atable.id == record_id).select(atable.location_id,
atable.pe_id,
limitby=(0, 1),
).first()
try:
location_id = row.location_id
except AttributeError:
# Nothing we can do
return
pe_id = row.pe_id
ctable = s3db.dvr_case
ptable = s3db.pr_person
query = (ptable.pe_id == pe_id) & \
(ptable.id == ctable.person_id)
case = db(query).select(ctable.site_id,
limitby=(0, 1),
).first()
if case and not case.site_id:
db(ptable.pe_id == pe_id).update(location_id = location_id,
# Indirect update by system rule,
# do not change modified_* fields:
modified_on = ptable.modified_on,
modified_by = ptable.modified_by,
)
# -------------------------------------------------------------------------
def customise_pr_address_resource(r, tablename):
# Custom onaccept to set the Person's Location to this address
# - unless their case is associated with a Site
current.s3db.add_custom_callback("pr_address",
"onaccept",
pr_address_onaccept,
)
settings.customise_pr_address_resource = customise_pr_address_resource
# -------------------------------------------------------------------------
def customise_pr_contact_resource(r, tablename):
table = current.s3db.pr_contact
#field = table.contact_description
#field.readable = field.writable = False
field = table.value
field.label = T("Number or Address")
field = table.contact_method
all_opts = current.msg.CONTACT_OPTS
subset = ("SMS",
"EMAIL",
"HOME_PHONE",
"WORK_PHONE",
"FACEBOOK",
"TWITTER",
"SKYPE",
"WHATSAPP",
"OTHER",
)
contact_methods = [(k, all_opts[k]) for k in subset if k in all_opts]
field.requires = IS_IN_SET(contact_methods, zero=None)
field.default = "SMS"
settings.customise_pr_contact_resource = customise_pr_contact_resource
# -------------------------------------------------------------------------
def customise_pr_person_resource(r, tablename):
s3db = current.s3db
auth = current.auth
has_permission = auth.s3_has_permission
# Users who can not register new residents also have
# only limited write-access to basic details of residents
if r.controller == "dvr" and not has_permission("create", "pr_person"):
# Can not write any fields in main person record
# (fields in components may still be writable, though)
ptable = s3db.pr_person
for field in ptable:
field.writable = False
# Can not add or edit contact data in person form
s3db.configure("pr_contact", insertable=False)
# Can not update shelter registration from person form
# - check-in/check-out may still be permitted, however
# - STAFF can update housing unit
is_staff = auth.s3_has_role("STAFF")
rtable = s3db.cr_shelter_registration
for field in rtable:
if field.name != "shelter_unit_id" or not is_staff:
field.writable = False
if r.controller == "dvr" and \
r.name == "person" and not r.component:
# Configure anonymize-method
# TODO make standard via setting
from s3 import S3Anonymize
s3db.set_method("pr", "person",
method = "anonymize",
action = S3Anonymize,
)
# Configure anonymize-rules
s3db.configure("pr_person",
anonymize = drk_person_anonymize(),
)
if current.auth.s3_has_role("CASE_MANAGEMENT"):
# Allow use of Document Templates
s3db.set_method("pr", "person",
method = "templates",
action = s3db.pr_Templates(),
)
s3db.set_method("pr", "person",
method = "template",
action = s3db.pr_Template(),
)
# Configure components to inherit realm_entity
# from the person record
s3db.configure("pr_person",
realm_components = ("case_activity",
"case_details",
"dvr_flag",
"case_language",
"case_note",
"residence_status",
"address",
"contact",
"contact_emergency",
"group_membership",
"image",
"person_details",
"person_tag",
),
)
s3db.add_custom_callback("dvr_case", "onaccept", dvr_case_onaccept)
settings.customise_pr_person_resource = customise_pr_person_resource
# -------------------------------------------------------------------------
def configure_person_tags():
"""
Configure filtered pr_person_tag components for
registration numbers:
- BAMF Registration Number (tag=BAMF)
"""
current.s3db.add_components("pr_person",
pr_person_tag = ({"name": "bamf",
"joinby": "person_id",
"filterby": {
"tag": "BAMF",
},
"multiple": False,
},
)
)
# -------------------------------------------------------------------------
def case_default_org():
"""
Determine the default organisation for new cases
"""
auth = current.auth
realms = auth.permission.permitted_realms("dvr_case", "create")
default_org = None
if realms is None:
# User can create cases for any org
orgs = []
multiple_orgs = True
else:
otable = current.s3db.org_organisation
query = (otable.pe_id.belongs(realms)) & \
(otable.deleted == False)
rows = current.db(query).select(otable.id)
orgs = [row.id for row in rows]
multiple_orgs = len(rows) > 1
if multiple_orgs:
# User can create cases for multiple orgs
user_org = auth.user.organisation_id if auth.user else None
if user_org and user_org in orgs:
default_org = user_org
elif orgs:
# User can create cases for exactly one org
default_org = orgs[0]
return default_org, multiple_orgs
# -------------------------------------------------------------------------
def customise_pr_person_controller(**attr):
s3 = current.response.s3
auth = current.auth
s3db = current.s3db
ui_options = get_ui_options()
settings.base.bigtable = True
# Custom prep
standard_prep = s3.prep
def custom_prep(r):
# Call standard prep
if callable(standard_prep):
result = standard_prep(r)
else:
result = True
crud_strings = s3.crud_strings["pr_person"]
archived = r.get_vars.get("archived")
if archived in ("1", "true", "yes"):
crud_strings["title_list"] = T("Invalid Cases")
if r.controller == "dvr":
resource = r.resource
configure = resource.configure
# Set contacts-method for tab
s3db.set_method("pr", "person",
method = "contacts",
action = s3db.pr_Contacts,
)
# Autocomplete search-method
search_fields = ("first_name", "last_name")
s3db.set_method("pr", "person",
method = "search_ac",
action = s3db.pr_PersonSearchAutocomplete(search_fields),
)
table = r.table
ctable = s3db.dvr_case
# Case-sites must be shelters
field = ctable.site_id
field.label = T("Shelter")
field.represent = s3db.org_SiteRepresent(show_type=False)
requires = field.requires
if isinstance(requires, IS_EMPTY_OR):
requires = requires.other
if hasattr(requires, "instance_types"):
requires.instance_types = ("cr_shelter",)
if not r.component:
# Can the user see cases from more than one org?
realms = auth.permission.permitted_realms("dvr_case", "read")
if realms is None or len(realms) > 1:
multiple_orgs = True
else:
multiple_orgs = False
configure_person_tags()
# Alternatives: site_id or simple text field
lodging_opt = ui_options.get("case_lodging")
if lodging_opt == "site":
lodging = "dvr_case.site_id"
elif lodging_opt == "text":
lodging = "case_details.lodging"
else:
lodging = None
if r.method == "report":
# Custom Report Options
facts = ((T("Number of Clients"), "count(id)"),
(T("Number of Actions"), "count(case_activity.response_action.id)"),
)
axes = ("gender",
"person_details.nationality",
"person_details.marital_status",
"dvr_case.status_id",
"dvr_case.site_id",
"residence_status.status_type_id",
"residence_status.permit_type_id",
)
report_options = {
"rows": axes,
"cols": axes,
"fact": facts,
"defaults": {"rows": axes[0],
"cols": axes[1],
"fact": facts[0],
"totals": True,
},
}
configure(report_options = report_options)
crud_strings["title_report"] = T("Case Statistic")
if r.interactive and r.method != "import":
from s3 import S3SQLCustomForm, \
S3SQLInlineComponent, \
S3SQLInlineLink, \
S3SQLVerticalSubFormLayout, \
S3TextFilter, \
S3DateFilter, \
S3OptionsFilter, \
s3_get_filter_opts, \
IS_PERSON_GENDER
# Default organisation
ctable = s3db.dvr_case
field = ctable.organisation_id
default_org, selectable = case_default_org()
if default_org:
if ui_options.get("case_hide_default_org"):
field.writable = selectable
field.readable = selectable or multiple_orgs
field.default = default_org
# Organisation is required
requires = field.requires
if isinstance(requires, IS_EMPTY_OR):
field.requires = requires.other
# Expose human_resource_id
field = ctable.human_resource_id
field.comment = None
human_resource_id = auth.s3_logged_in_human_resource()
if human_resource_id:
field.default = human_resource_id
field.readable = field.writable = True
field.widget = None
# Optional: Case Flags
if ui_options.get("case_use_flags"):
case_flags = S3SQLInlineLink("case_flag",
label = T("Flags"),
field = "flag_id",
help_field = "comments",
cols = 4,
)
else:
case_flags = None
# Make marital status mandatory, remove "other"
dtable = s3db.pr_person_details
field = dtable.marital_status
options = dict(s3db.pr_marital_status_opts)
del options[9] # Remove "other"
field.requires = IS_IN_SET(options, zero=None)
# Make gender mandatory, remove "unknown"
field = table.gender
field.default = None
options = dict(s3db.pr_gender_opts)
del options[1] # Remove "unknown"
field.requires = IS_PERSON_GENDER(options, sort = True)
# No comment for pe_label
field = table.pe_label
field.comment = None
# Last name is required
field = table.last_name
field.requires = IS_NOT_EMPTY()
# Alternatives: BAMF first or last
bamf = S3SQLInlineComponent(
"bamf",
fields = [("", "value")],
filterby = {"field": "tag",
"options": "BAMF",
},
label = T("BAMF Reference Number"),
multiple = False,
name = "bamf",
)
if ui_options.get("case_bamf_first"):
bamf_first = bamf
bamf_last = None
else:
bamf_first = None
bamf_last = bamf
# Optional: site dates
if ui_options.get("case_lodging_dates"):
on_site_from = (T("Moving-in Date"),
"case_details.on_site_from",
)
on_site_until = (T("Moving-out Date"),
"case_details.on_site_until",
)
else:
on_site_from = None
on_site_until = None
# Optional: Address
if ui_options.get("case_use_address"):
address = S3SQLInlineComponent(
"address",
label = T("Current Address"),
fields = [("", "location_id")],
filterby = {"field": "type",
"options": "1",
},
link = False,
multiple = False,
)
else:
address = None
# Optional: Date of Entry
if ui_options.get("case_use_arrival_date"):
arrival_date = (T("Date of Entry"),
"case_details.arrival_date",
)
else:
arrival_date = None
# Optional: Residence Status
if ui_options.get("case_use_residence_status"):
# Remove Add-links
rtable = s3db.dvr_residence_status
field = rtable.status_type_id
field.comment = None
field = rtable.permit_type_id
field.comment = None
residence_status = S3SQLInlineComponent(
"residence_status",
fields = ["status_type_id",
"permit_type_id",
#"reference",
#"valid_from",
"valid_until",
"comments",
],
label = T("Residence Status"),
multiple = False,
layout = S3SQLVerticalSubFormLayout,
)
else:
residence_status = None
# Optional: Occupation/Educational Background
if ui_options.get("case_use_occupation"):
occupation = "person_details.occupation"
else:
occupation = None
if ui_options.get("case_use_education"):
education = "person_details.education"
else:
education = None
# Custom CRUD form
crud_form = S3SQLCustomForm(
# Case Details ----------------------------
"dvr_case.date",
"dvr_case.organisation_id",
"dvr_case.human_resource_id",
(T("Case Status"), "dvr_case.status_id"),
case_flags,
# Person Details --------------------------
(T("ID"), "pe_label"),
bamf_first,
"last_name",
"first_name",
"person_details.nationality",
"date_of_birth",
"gender",
"person_details.marital_status",
# Process Data ----------------------------
lodging,
on_site_from,
on_site_until,
address,
bamf_last,
arrival_date,
residence_status,
# Other Details ---------------------------
S3SQLInlineComponent(
"contact",
fields = [("", "value")],
filterby = {"field": "contact_method",
"options": "SMS",
},
label = T("Mobile Phone"),
multiple = False,
name = "phone",
),
education,
occupation,
"person_details.literacy",
S3SQLInlineComponent(
"case_language",
fields = ["language",
"quality",
"comments",
],
label = T("Language / Communication Mode"),
),
"dvr_case.comments",
# Archived-flag ---------------------------
(T("Invalid"), "dvr_case.archived"),
)
# Custom filter widgets
# Extract case status options from original filter widget
status_opts = None
filter_widgets = resource.get_config("filter_widgets")
for fw in filter_widgets:
if fw.field == "dvr_case.status_id":
status_opts = fw.opts.get("options")
break
if status_opts is None:
# Fallback
status_opts = s3db.dvr_case_status_filter_opts
filter_widgets = [
S3TextFilter(["pe_label",
"first_name",
"middle_name",
"last_name",
"dvr_case.comments",
],
label = T("Search"),
comment = T("You can search by name, ID or comments"),
),
S3DateFilter("date_of_birth",
hidden = True,
),
S3OptionsFilter("dvr_case.status_id",
cols = 3,
#default = None,
#label = T("Case Status"),
options = status_opts,
sort = False,
hidden = True,
),
S3OptionsFilter("person_details.nationality",
hidden = True,
),
S3DateFilter("dvr_case.date",
hidden = True,
),
S3TextFilter(["bamf.value"],
label = T("BAMF Ref.No."),
hidden = True,
),
S3TextFilter(["pe_label"],
label = T("IDs"),
match_any = True,
hidden = True,
comment = T("Search for multiple IDs (separated by blanks)"),
),
]
# Ref.No.-filter if using service contacts
if ui_options.get("case_use_service_contacts"):
filter_widgets.append(S3TextFilter(
["service_contact.reference"],
label = T("Ref.No."),
hidden = True,
comment = T("Search by service contact reference number"),
))
# Flag-filter if using case flags
if case_flags:
filter_widgets.insert(2, S3OptionsFilter(
"case_flag_case.flag_id",
label = T("Flags"),
options = s3_get_filter_opts("dvr_case_flag",
translate = True,
),
cols = 3,
hidden = True,
))
# Org-filter if user can see cases from multiple orgs/branches
if multiple_orgs:
filter_widgets.insert(1,
S3OptionsFilter("dvr_case.organisation_id"),
)
configure(crud_form = crud_form,
filter_widgets = filter_widgets,
)
# Custom list fields (must be outside of r.interactive)
list_fields = [(T("ID"), "pe_label"),
"last_name",
"first_name",
"date_of_birth",
"gender",
"person_details.nationality",
"dvr_case.date",
"dvr_case.status_id",
lodging,
]
if multiple_orgs:
list_fields.insert(-1, "dvr_case.organisation_id")
configure(list_fields = list_fields)
elif r.component_name == "case_appointment":
if ui_options.get("appointments_use_organizer") and \
r.interactive and r.method is None and not r.component_id:
r.method = "organize"
elif r.controller == "default":
# Personal Profile
if r.component_name == "group_membership":
# Team memberships are read-only
r.component.configure(insertable = False,
editable = False,
deletable = False,
)
elif r.component_name == "human_resource":
# Staff/Volunteer records are read-only
r.component.configure(insertable = False,
editable = False,
deletable = False,
)
return result
s3.prep = custom_prep
standard_postp = s3.postp
def custom_postp(r, output):
# Call standard postp
if callable(standard_postp):
output = standard_postp(r, output)
if r.controller == "dvr" and \
not r.component and r.record and \
r.method in (None, "update", "read") and \
isinstance(output, dict):
# Custom CRUD buttons
if "buttons" not in output:
buttons = output["buttons"] = {}
else:
buttons = output["buttons"]
# Anonymize-button
from s3 import S3AnonymizeWidget
anonymize = S3AnonymizeWidget.widget(r,
_class="action-btn anonymize-btn")
# Doc-From-Template-button
if ui_options.get("case_document_templates") and \
auth.s3_has_role("CASE_MANAGEMENT"):
doc_from_template = A(T("Document from Template"),
_class = "action-btn s3_modal",
_title = T("Generate Document from Template"),
_href = URL(args=[r.id, "templates"]),
)
else:
doc_from_template = ""
# Render in place of the delete-button
buttons["delete_btn"] = TAG[""](doc_from_template,
anonymize,
)
return output
s3.postp = custom_postp
# Custom rheader tabs
if current.request.controller == "dvr":
attr = dict(attr)
attr["rheader"] = drk_dvr_rheader
return attr
settings.customise_pr_person_controller = customise_pr_person_controller
# -------------------------------------------------------------------------
def customise_pr_group_controller(**attr):
s3db = current.s3db
s3 = current.response.s3
# Custom prep
standard_prep = s3.prep
def custom_prep(r):
# Call standard prep
if callable(standard_prep):
result = standard_prep(r)
else:
result = True
if r.controller in ("hrm", "vol"):
if not r.component:
# No inline-adding new organisations
ottable = s3db.org_organisation_team
field = ottable.organisation_id
field.comment = None
# Organisation is required
from s3 import S3SQLCustomForm, \
S3SQLInlineComponent
crud_form = S3SQLCustomForm(
"name",
"description",
S3SQLInlineComponent("organisation_team",
label = T("Organization"),
fields = ["organisation_id"],
multiple = False,
required = True,
),
"comments",
)
r.resource.configure(crud_form = crud_form)
elif r.component_name == "group_membership":
from s3 import S3PersonAutocompleteWidget
# Make sure only HRs can be added to teams
mtable = s3db.pr_group_membership
field = mtable.person_id
field.widget = S3PersonAutocompleteWidget(
#controller="hrm",
ajax_filter="human_resource.id__ne=None",
)
return result
s3.prep = custom_prep
return attr
settings.customise_pr_group_controller = customise_pr_group_controller
# -------------------------------------------------------------------------
def customise_pr_group_membership_controller(**attr):
s3db = current.s3db
s3 = current.response.s3
# Custom prep
standard_prep = s3.prep
def custom_prep(r):
# Call standard prep
if callable(standard_prep):
result = standard_prep(r)
else:
result = True
ROLE = T("Role")
resource = r.resource
if r.controller == "dvr":
# Set contacts-method to retain the tab
s3db.set_method("pr", "person",
method = "contacts",
action = s3db.pr_Contacts,
)
if r.interactive:
table = resource.table
from s3 import S3AddPersonWidget
s3db.pr_person.pe_label.label = T("ID")
field = table.person_id
field.represent = s3db.pr_PersonRepresent(show_link=True)
field.widget = S3AddPersonWidget(controller = "dvr",
pe_label = True,
)
field = table.role_id
field.readable = field.writable = True
field.label = ROLE
field.comment = None
field.requires = IS_EMPTY_OR(
IS_ONE_OF(current.db, "pr_group_member_role.id",
field.represent,
filterby = "group_type",
filter_opts = (7,),
))
field = table.group_head
field.label = T("Head of Family")
# Custom CRUD strings for this perspective
s3.crud_strings["pr_group_membership"] = Storage(
label_create = T("Add Family Member"),
title_display = T("Family Member Details"),
title_list = T("Family Members"),
title_update = T("Edit Family Member"),
label_list_button = T("List Family Members"),
label_delete_button = T("Remove Family Member"),
msg_record_created = T("Family Member added"),
msg_record_modified = T("Family Member updated"),
msg_record_deleted = T("Family Member removed"),
msg_list_empty = T("No Family Members currently registered")
)
list_fields = [(T("ID"), "person_id$pe_label"),
"person_id",
"person_id$date_of_birth",
"person_id$gender",
"group_head",
(ROLE, "role_id"),
(T("Case Status"), "person_id$dvr_case.status_id"),
]
# Retain group_id in list_fields if added in standard prep
lfields = resource.get_config("list_fields")
if "group_id" in lfields:
list_fields.insert(0, "group_id")
resource.configure(filter_widgets = None,
list_fields = list_fields,
)
return result
s3.prep = custom_prep
attr["rheader"] = drk_dvr_rheader
return attr
settings.customise_pr_group_membership_controller = customise_pr_group_membership_controller
# -------------------------------------------------------------------------
def dvr_case_onaccept(form):
"""
Additional custom-onaccept for dvr_case to:
* Force-update the realm entity of the person record:
- the organisation managing the case is the realm-owner,
but the person record is written first, so we need to
update it after writing the case
- the case can be transferred to another organisation/branch,
and then the person record needs to be transferred to that
same realm as well
* Update the Population of all Shelters
* Update the Location of the person record:
- if the Case is linked to a Site then use that for the Location of
the Person
- otherwise use the Private Address
"""
try:
form_vars = form.vars
except AttributeError:
return
record_id = form_vars.id
if not record_id:
# Nothing we can do
return
db = current.db
s3db = current.s3db
# Update the Population of all Shelters
cr_shelter_population()
# Get the Person ID & Site ID for this case
person_id = form_vars.person_id
if not person_id or "site_id" not in form_vars:
# Reload the record
table = s3db.dvr_case
query = (table.id == record_id)
row = db(query).select(table.person_id,
table.site_id,
limitby = (0, 1),
).first()
if row:
person_id = row.person_id
site_id = row.site_id
else:
site_id = form_vars.site_id
if person_id:
set_realm_entity = current.auth.set_realm_entity
# Configure components to inherit realm_entity
# from the person record
s3db.configure("pr_person",
realm_components = ("case_activity",
"case_details",
"dvr_flag",
"case_language",
"case_note",
"residence_status",
"address",
"contact",
"contact_emergency",
"group_membership",
"image",
"person_details",
"person_tag",
),
)
# Force-update the realm entity for the person
set_realm_entity("pr_person", person_id, force_update=True)
# Configure components to inherit realm entity
# from the case activity record
s3db.configure("dvr_case_activity",
realm_components = ("case_activity_need",
"case_activity_update",
"response_action",
),
)
# Force-update the realm entity for all case activities
# linked to the person_id
atable = s3db.dvr_case_activity
query = (atable.person_id == person_id)
set_realm_entity(atable, query, force_update=True)
# Update the person's location_id
ptable = s3db.pr_person
location_id = None
if site_id:
# Use the Shelter's Address
stable = s3db.org_site
site = db(stable.site_id == site_id).select(stable.location_id,
limitby = (0, 1),
).first()
if site:
location_id = site.location_id
else:
# Use the Private Address (no need to filter by address type as only
# 'Current Address' is exposed)
# NB If this is a New/Modified Address then this won't be caught here
# - we use pr_address_onaccept to catch those
atable = s3db.pr_address
query = (ptable.id == person_id) & \
(ptable.pe_id == atable.pe_id) & \
(atable.deleted == False)
address = db(query).select(atable.location_id,
limitby = (0, 1),
).first()
if address:
location_id = address.location_id
db(ptable.id == person_id).update(location_id = location_id,
# Indirect update by system rule,
# do not change modified_* fields:
modified_on = ptable.modified_on,
modified_by = ptable.modified_by,
)
# -------------------------------------------------------------------------
def customise_dvr_case_resource(r, tablename):
s3db = current.s3db
ctable = s3db.dvr_case
get_vars = r.get_vars
if r.function == "group_membership" and "viewing" in get_vars:
# New cases created on family tab inherit organisation_id
# and human_resource_id from master case:
viewing = r.get_vars.get("viewing")
if viewing and viewing[:10] == "pr_person.":
try:
vid = int(viewing[10:])
except ValueError:
pass
else:
ctable = s3db.dvr_case
query = (ctable.person_id == vid) & \
(ctable.archived == False) & \
(ctable.deleted == False)
case = current.db(query).select(ctable.organisation_id,
ctable.human_resource_id,
limitby = (0, 1),
).first()
if case:
ctable.organisation_id.default = case.organisation_id
ctable.human_resource_id.default = case.human_resource_id
# Custom onaccept to update realm-entity of the
# beneficiary and case activities of this case
# (incl. their respective realm components)
s3db.add_custom_callback("dvr_case", "onaccept", dvr_case_onaccept)
# Update the realm-entity when the case gets updated
# (because the assigned organisation/branch can change)
s3db.configure("dvr_case", update_realm = True)
settings.customise_dvr_case_resource = customise_dvr_case_resource
# -------------------------------------------------------------------------
def customise_dvr_note_resource(r, tablename):
auth = current.auth
if not auth.s3_has_role("ADMIN"):
# Restrict access by note type
GENERAL = "General"
MEDICAL = "Medical"
SECURITY = "Security"
permitted_note_types = [GENERAL]
user = auth.user
if user:
# Roles permitted to access "Security" type notes
SECURITY_ROLES = ("ADMIN_HEAD",
"SECURITY_HEAD",
"POLICE",
"MEDICAL",
)
# Roles permitted to access "Health" type notes
MEDICAL_ROLES = ("ADMIN_HEAD",
"MEDICAL",
)
# Get role IDs
db = current.db
s3db = current.s3db
gtable = s3db.auth_group
roles = db(gtable.deleted != True).select(gtable.uuid,
gtable.id,
).as_dict(key = "uuid")
realms = user.realms
security_roles = (roles[uuid]["id"]
for uuid in SECURITY_ROLES if uuid in roles)
if any(role in realms for role in security_roles):
permitted_note_types.append(SECURITY)
medical_roles = (roles[uuid]["id"]
for uuid in MEDICAL_ROLES if uuid in roles)
if any(role in realms for role in medical_roles):
permitted_note_types.append(MEDICAL)
# Filter notes to permitted note types
query = FS("note_type_id$name").belongs(permitted_note_types)
if r.tablename == "dvr_note":
r.resource.add_filter(query)
else:
r.resource.add_component_filter("case_note", query)
# Filter note type selector to permitted note types
ttable = s3db.dvr_note_type
query = ttable.name.belongs(permitted_note_types)
rows = db(query).select(ttable.id)
note_type_ids = [row.id for row in rows]
table = s3db.dvr_note
field = table.note_type_id
field.label = T("Category")
if len(note_type_ids) == 1:
field.default = note_type_ids[0]
field.writable = False
field.requires = IS_ONE_OF(db(query), "dvr_note_type.id",
field.represent,
)
settings.customise_dvr_note_resource = customise_dvr_note_resource
# -------------------------------------------------------------------------
def customise_dvr_case_activity_resource(r, tablename):
auth = current.auth
s3db = current.s3db
table = s3db.dvr_case_activity
if r.method == "count_due_followups":
# Just counting due followups => skip customisation
return
human_resource_id = auth.s3_logged_in_human_resource()
ui_options = get_ui_options()
# Optional: closure details
if ui_options.get("activity_closure"):
# Activities can be closed
status_id = "status_id"
end_date = "end_date"
outcome = "outcome"
else:
# Activities are never closed
status_id = None
table.start_date.label = T("Date")
end_date = None
outcome = None
if r.method == "report":
# Custom Report Options
facts = ((T("Number of Activities"), "count(id)"),
(T("Number of Clients"), "count(person_id)"),
)
axes = ["person_id$gender",
"person_id$person_details.nationality",
"person_id$person_details.marital_status",
"priority",
"sector_id",
(T("Theme"), "response_action.response_theme_ids"),
]
if status_id == "status_id":
axes.insert(3, status_id)
report_options = {
"rows": axes,
"cols": axes,
"fact": facts,
"defaults": {"rows": "sector_id",
"cols": "person_id$person_details.nationality",
"fact": "count(id)",
"totals": True,
},
}
s3db.configure("dvr_case_activity",
report_options = report_options,
)
crud_strings = current.response.s3.crud_strings["dvr_case_activity"]
crud_strings["title_report"] = T("Activity Statistic")
if r.interactive or r.representation == "aadata":
from s3 import S3SQLCustomForm, \
S3SQLInlineComponent
# Represent person_id as link
field = table.person_id
#fmt = "%(pe_label)s %(last_name)s, %(first_name)s"
field.represent = s3db.pr_PersonRepresent(#fields = ("pe_label",
# "last_name",
# "first_name",
# ),
#labels = fmt,
show_link = True,
)
# If looking at a particular case, get the person_id
if r.tablename == "pr_person":
person_id = r.record.id if r.record else None
elif r.tablename == "dvr_case_activity":
person_id = r.record.person_id if r.record else None
else:
person_id = None
db = current.db
# Get the root org of the case
if person_id:
ctable = s3db.dvr_case
otable = s3db.org_organisation
left = otable.on(otable.id == ctable.organisation_id)
query = (ctable.person_id == person_id) & \
(ctable.archived == False) & \
(ctable.deleted == False)
row = db(query).select(otable.root_organisation,
left = left,
limitby = (0, 1),
orderby = ~ctable.modified_on,
).first()
case_root_org = row.root_organisation if row else None
else:
case_root_org = None
# Configure sector_id
field = table.sector_id
field.comment = None
if ui_options.get("activity_use_sector"):
# Get the root org for sector selection
if case_root_org:
sector_root_org = case_root_org
else:
sector_root_org = auth.root_org()
if sector_root_org:
# Limit the sector selection
ltable = s3db.org_sector_organisation
query = (ltable.organisation_id == sector_root_org) & \
(ltable.deleted == False)
rows = db(query).select(ltable.sector_id)
sector_ids = set(row.sector_id for row in rows)
# Default sector
if len(sector_ids) == 1:
default_sector_id = rows.first().sector_id
else:
default_sector_id = None
# Include the sector_id of the current record (if any)
record = None
component = r.component
if not component:
if r.tablename == "dvr_case_activity":
record = r.record
elif component.tablename == "dvr_case_activity" and r.component_id:
query = table.id == r.component_id
record = db(query).select(table.sector_id,
limitby = (0, 1),
).first()
if record and record.sector_id:
sector_ids.add(record.sector_id)
# Set selectable sectors
subset = db(s3db.org_sector.id.belongs(sector_ids))
field.requires = IS_EMPTY_OR(IS_ONE_OF(subset, "org_sector.id",
field.represent,
))
# Default selection?
if len(sector_ids) == 1 and default_sector_id:
# Single option => set as default and hide selector
field.default = default_sector_id
field.readable = field.writable = False
else:
field.readable = field.writable = False
# Show subject field
field = table.subject
field.readable = field.writable = True
field.requires = IS_NOT_EMPTY()
# Show need details
field = table.need_details
field.readable = field.writable = ui_options.get("activity_need_details")
# Customise Priority
field = table.priority
priority_opts = [(0, T("Emergency")),
(1, T("High")),
(2, T("Normal")),
(3, T("Low")),
]
field.readable = field.writable = True
field.label = T("Priority")
field.default = 2
field.requires = IS_IN_SET(priority_opts, sort=False, zero=None)
field.represent = PriorityRepresent(priority_opts,
{0: "red",
1: "blue",
2: "lightblue",
3: "grey",
}).represent
# Show human_resource_id
field = table.human_resource_id
field.readable = field.writable = True
field.label = T("Consultant in charge")
field.default = human_resource_id
field.widget = None
field.comment = None
# Show end_date field (read-only)
if end_date is not None:
field = table.end_date
field.label = T("Completed on")
field.readable = True
# Show comments
field = table.comments
field.readable = field.writable = ui_options.get("activity_comments")
# Inline-responses
rtable = s3db.dvr_response_action
field = rtable.human_resource_id
#field.label = T("Assigned to")
field.default = human_resource_id
field.widget = field.comment = None
if settings.get_dvr_response_themes_needs():
response_theme_selector_include_need()
if settings.get_dvr_response_planning():
response_action_fields = ["response_theme_ids",
"date_due",
"comments",
"human_resource_id",
"status_id",
"date",
"hours",
]
else:
response_action_fields = ["response_theme_ids",
"comments",
"human_resource_id",
(T("Date"), "date"),
"hours",
]
# Filter themes-options to themes of the case root org
if case_root_org and r.tablename == "pr_person" and r.record:
requires = rtable.response_theme_ids.requires
if isinstance(requires, IS_EMPTY_OR):
requires = requires.other
if hasattr(requires, "set_filter"):
requires.set_filter(filterby = "organisation_id",
filter_opts = (case_root_org,),
)
# Inline-updates
utable = current.s3db.dvr_case_activity_update
field = utable.human_resource_id
field.default = human_resource_id
field.widget = field.comment = None
# Custom CRUD form
from s3 import S3SQLVerticalSubFormLayout
crud_form = S3SQLCustomForm(
"person_id",
"sector_id",
"subject",
(T("Initial Situation Details"), ("need_details")),
"start_date",
"priority",
"human_resource_id",
S3SQLInlineComponent("response_action",
label = T("Actions"),
fields = response_action_fields,
layout = S3SQLVerticalSubFormLayout,
explicit_add = T("Add Action"),
),
"followup",
"followup_date",
S3SQLInlineComponent("case_activity_update",
label = T("Progress"),
fields = [
"date",
(T("Occasion"), "update_type_id"),
"human_resource_id",
"comments",
],
layout = S3SQLVerticalSubFormLayout,
explicit_add = T("Add Entry"),
),
status_id,
end_date,
outcome,
S3SQLInlineComponent(
"document",
name = "file",
label = T("Attachments"),
fields = ["file", "comments"],
filterby = {"field": "file",
"options": "",
"invert": True,
},
),
"comments",
)
s3db.configure("dvr_case_activity",
crud_form = crud_form,
#filter_widgets = filter_widgets,
orderby = "dvr_case_activity.priority",
)
# Custom list fields for case activity component tab
if r.tablename != "dvr_case_activity":
list_fields = ["priority",
#"sector_id",
"subject",
#"followup",
#"followup_date",
"start_date",
"human_resource_id",
status_id,
]
if table.sector_id.readable:
list_fields.insert(1, "sector_id")
# Custom list fields
s3db.configure("dvr_case_activity",
list_fields = list_fields,
)
# Configure components to inherit realm entity
# from the case activity record
s3db.configure("dvr_case_activity",
realm_components = ("case_activity_need",
"case_activity_update",
"response_action",
),
)
settings.customise_dvr_case_activity_resource = customise_dvr_case_activity_resource
# -------------------------------------------------------------------------
def customise_dvr_case_activity_controller(**attr):
auth = current.auth
s3db = current.s3db
s3 = current.response.s3
settings.base.bigtable = True
# Custom prep
standard_prep = s3.prep
def custom_prep(r):
# Call standard prep
if callable(standard_prep):
result = standard_prep(r)
else:
result = True
resource = r.resource
# Configure person tags
configure_person_tags()
# Get UI options
ui_options = get_ui_options()
# Adapt list title when filtering for priority 0 (Emergency)
if r.get_vars.get("~.priority") == "0":
emergencies = True
s3.crud_strings["dvr_case_activity"]["title_list"] = T("Emergencies")
else:
emergencies = False
# Filter to active cases
if not r.record:
query = (FS("person_id$dvr_case.archived") == False) | \
(FS("person_id$dvr_case.archived") == None)
resource.add_filter(query)
if not r.component and not r.record:
from s3 import S3TextFilter, \
S3OptionsFilter
db = current.db
# Sector filter options
# (field options are configured in customise_*_resource)
sector_id = resource.table.sector_id
sector_options = {k:v for k, v in sector_id.requires.options() if k}
# Status filter options + defaults, status list field
if ui_options.get("activity_closure"):
stable = s3db.dvr_case_activity_status
query = (stable.deleted == False)
rows = db(query).select(stable.id,
stable.name,
stable.is_closed,
cache = s3db.cache,
orderby = stable.workflow_position,
)
status_filter_options = OrderedDict((row.id, T(row.name))
for row in rows)
status_filter_defaults = [row.id for row in rows
if not row.is_closed]
status_filter = S3OptionsFilter("status_id",
options = status_filter_options,
cols = 3,
default = status_filter_defaults,
sort = False,
)
status_id = "status_id"
else:
status_filter = None
status_id = None
# Filter widgets
filter_widgets = [
S3TextFilter(["person_id$pe_label",
"person_id$first_name",
"person_id$last_name",
"need_details",
],
label = T("Search"),
),
S3OptionsFilter("person_id$person_details.nationality",
label = T("Client Nationality"),
hidden = True,
),
]
if sector_id.readable:
filter_widgets.insert(1, S3OptionsFilter(
"sector_id",
hidden = True,
options = sector_options,
))
if status_filter:
filter_widgets.insert(1, status_filter)
# Priority filter (unless pre-filtered to emergencies anyway)
if not emergencies:
field = resource.table.priority
priority_opts = OrderedDict(field.requires.options())
priority_filter = S3OptionsFilter("priority",
options = priority_opts,
cols = 4,
sort = False,
)
filter_widgets.insert(2, priority_filter)
# Can the user see cases from more than one org?
realms = auth.permission.permitted_realms("dvr_case", "read")
if realms is None:
multiple_orgs = True
elif len(realms) > 1:
otable = s3db.org_organisation
query = (otable.pe_id.belongs(realms)) & \
(otable.deleted == False)
rows = db(query).select(otable.id)
multiple_orgs = len(rows) > 1
else:
multiple_orgs = False
if multiple_orgs:
# Add org-filter widget
filter_widgets.insert(1,
S3OptionsFilter("person_id$dvr_case.organisation_id"),
)
# Custom list fields
list_fields = ["priority",
(T("ID"), "person_id$pe_label"),
(T("Case"), "person_id"),
#"sector_id",
"subject",
"start_date",
#"followup",
#"followup_date",
status_id,
]
if sector_id.readable:
list_fields.insert(3, "sector_id")
# Person responsible filter and list_field
if not r.get_vars.get("mine"):
filter_widgets.insert(2, S3OptionsFilter("human_resource_id"))
list_fields.insert(5, "human_resource_id")
# Reconfigure table
resource.configure(filter_widgets = filter_widgets,
list_fields = list_fields,
)
return result
s3.prep = custom_prep
return attr
settings.customise_dvr_case_activity_controller = customise_dvr_case_activity_controller
# -------------------------------------------------------------------------
def customise_dvr_case_appointment_resource(r, tablename):
s3db = current.s3db
# Organizer popups
if r.tablename == "pr_person":
title = "type_id"
description = ["status",
"comments",
]
elif r.tablename == "dvr_case_appointment":
title = "person_id"
description = [(T("ID"), "person_id$pe_label"),
"type_id",
"status",
"comments",
]
else:
title = description = None
table = s3db.dvr_case_appointment
field = table.status
# Using only a subset of the standard status opts
appointment_status_opts = {#1: T("Planning"),
2: T("Planned"),
#3: T("In Progress"),
4: T("Completed##appointment"),
5: T("Missed"),
6: T("Cancelled"),
#7: T("Not Required"),
}
field.default = 2
field.requires = IS_IN_SET(appointment_status_opts,
zero = None,
)
ui_options = get_ui_options()
if ui_options.get("appointments_staff_link"):
# Enable staff link and default to logged-in user
field = table.human_resource_id
field.readable = field.writable = True
field.default = current.auth.s3_logged_in_human_resource()
field.widget = None
# Also show staff link in organizer popup
if description:
description.insert(-1, "human_resource_id")
# Configure Organizer
if title:
s3db.configure("dvr_case_appointment",
organize = {"start": "date",
"title": title,
"description": description,
},
)
settings.customise_dvr_case_appointment_resource = customise_dvr_case_appointment_resource
# -------------------------------------------------------------------------
def customise_dvr_case_appointment_controller(**attr):
s3 = current.response.s3
s3db = current.s3db
# Custom prep
standard_prep = s3.prep
def custom_prep(r):
# Call standard prep
if callable(standard_prep):
result = standard_prep(r)
else:
result = True
resource = r.resource
# Filter to active cases
if not r.record:
query = (FS("person_id$dvr_case.archived") == False) | \
(FS("person_id$dvr_case.archived") == None)
resource.add_filter(query)
if not r.component:
configure_person_tags()
if r.interactive and not r.id:
# Custom filter widgets
from s3 import S3TextFilter, S3OptionsFilter, S3DateFilter, s3_get_filter_opts
filter_widgets = [
S3TextFilter(["person_id$pe_label",
"person_id$first_name",
"person_id$last_name",
],
label = T("Search"),
),
S3OptionsFilter("type_id",
options = s3_get_filter_opts("dvr_case_appointment_type",
translate = True,
),
cols = 3,
),
S3OptionsFilter("status",
options = s3db.dvr_appointment_status_opts,
default = 2,
),
S3DateFilter("date",
),
S3OptionsFilter("person_id$dvr_case.status_id$is_closed",
cols = 2,
default = False,
#hidden = True,
label = T("Case Closed"),
options = {True: T("Yes"),
False: T("No"),
},
),
S3TextFilter(["person_id$pe_label"],
label = T("IDs"),
match_any = True,
hidden = True,
comment = T("Search for multiple IDs (separated by blanks)"),
),
]
resource.configure(filter_widgets = filter_widgets)
# Default filter today's and tomorrow's appointments
from s3 import s3_set_default_filter
now = r.utcnow
today = now.replace(hour=0, minute=0, second=0, microsecond=0)
tomorrow = today + datetime.timedelta(days=1)
s3_set_default_filter("~.date",
{"ge": today, "le": tomorrow},
tablename = "dvr_case_appointment",
)
# Field Visibility
table = resource.table
field = table.case_id
field.readable = field.writable = False
# Custom list fields
list_fields = [(T("ID"), "person_id$pe_label"),
"person_id$first_name",
"person_id$last_name",
"type_id",
"date",
"status",
"comments",
]
if r.representation == "xls":
# Include Person UUID
list_fields.append(("UUID", "person_id$uuid"))
resource.configure(list_fields = list_fields,
insertable = False,
deletable = False,
update_next = r.url(method=""),
)
return result
s3.prep = custom_prep
return attr
settings.customise_dvr_case_appointment_controller = customise_dvr_case_appointment_controller
# -------------------------------------------------------------------------
def customise_dvr_case_flag_resource(r, tablename):
table = current.s3db.dvr_case_flag
# Hide unwanted fields
unused = ("advise_at_check_in",
"advise_at_check_out",
"advise_at_id_check",
"instructions",
"deny_check_in",
"deny_check_out",
"allowance_suspended",
"is_not_transferable",
"is_external",
)
for fieldname in unused:
field = table[fieldname]
field.readable = field.writable = False
settings.customise_dvr_case_flag_resource = customise_dvr_case_flag_resource
# -------------------------------------------------------------------------
def customise_dvr_need_resource(r, tablename):
table = current.s3db.dvr_need
# Expose organisation_id (only relevant for ADMINs)
field = table.organisation_id
field.readable = field.writable = True
# Expose protection flag
field = table.protection
field.readable = field.writable = True
settings.customise_dvr_need_resource = customise_dvr_need_resource
# -------------------------------------------------------------------------
def response_theme_selector_include_need():
"""
Include the need in the themes-selector
- helps to find themes using the selector search field
"""
s3db = current.s3db
table = s3db.dvr_response_action
field = table.response_theme_ids
represent = s3db.dvr_ResponseThemeRepresent(multiple = True,
translate = True,
show_need = True,
)
root_org = current.auth.root_org()
if root_org:
filterby = "organisation_id",
filter_opts = (root_org,)
else:
filterby = filter_opts = None
field.requires = IS_ONE_OF(current.db, "dvr_response_theme.id",
represent,
filterby = filterby,
filter_opts = filter_opts,
multiple = True,
)
# -------------------------------------------------------------------------
def customise_dvr_response_action_resource(r, tablename):
db = current.db
s3db = current.s3db
table = s3db.dvr_response_action
# Can the user see cases from more than one org?
realms = current.auth.permission.permitted_realms("dvr_case", "read")
if realms is None or len(realms) > 1:
multiple_orgs = True
else:
multiple_orgs = False
org_context = "case_activity_id$person_id$dvr_case.organisation_id"
is_report = r.method == "report"
if is_report:
# Sector Axis
if settings.get_dvr_response_themes_sectors():
sector = "dvr_response_action_theme.theme_id$sector_id"
default_cols = None
else:
sector = "case_activity_id$sector_id"
default_cols = sector
# Needs Axis
if settings.get_dvr_response_themes_needs():
need = "dvr_response_action_theme.theme_id$need_id"
else:
need = None
# Custom Report Options
facts = ((T("Number of Actions"), "count(id)"),
(T("Number of Clients"), "count(case_activity_id$person_id)"),
(T("Hours (Total)"), "sum(hours)"),
(T("Hours (Average)"), "avg(hours)"),
)
axes = ("case_activity_id$person_id$gender",
"case_activity_id$person_id$person_details.nationality",
"case_activity_id$person_id$person_details.marital_status",
(T("Theme"), "response_theme_ids"),
sector,
need,
"human_resource_id",
)
if multiple_orgs:
# Add case organisation as report axis
axes = axes + (org_context,)
report_options = {
"rows": axes,
"cols": axes,
"fact": facts,
"defaults": {"rows": "response_theme_ids",
"cols": default_cols,
"fact": "count(id)",
"totals": True,
},
"precision": {"hours": 2, # higher precision is impractical
},
}
s3db.configure("dvr_response_action",
report_options = report_options,
)
crud_strings = current.response.s3.crud_strings["dvr_response_action"]
crud_strings["title_report"] = T("Action Statistic")
if r.interactive or r.representation in ("aadata", "xls", "pdf"):
# Use drop-down for human_resource_id
field = table.human_resource_id
field.widget = None
field.default = current.auth.s3_logged_in_human_resource()
list_fields = ["case_activity_id",
"response_theme_ids",
"comments",
"human_resource_id",
"date",
"hours",
]
# Response planning?
response_planning = settings.get_dvr_response_planning()
if response_planning:
list_fields.insert(-3, "date_due")
list_fields.append("status_id")
# Include need in themes selector if using needs
if settings.get_dvr_response_themes_needs():
response_theme_selector_include_need()
get_vars = r.get_vars
if r.tablename == "dvr_response_action" and "viewing" in get_vars:
# Represent case_activity_id by its subject when viewing
# from case perspective
try:
vtablename, record_id = get_vars["viewing"].split(".")
except ValueError:
vtablename, record_id = None, None
if vtablename == "pr_person":
show_link = True
linkto = URL(c="dvr", f="person",
args = [record_id, "case_activity", "[id]"],
)
else:
show_link = False,
linkto = None
from s3 import S3Represent
field = table.case_activity_id
field.label = T("Subject")
field.represent = S3Represent(lookup = "dvr_case_activity",
fields = ["subject"],
show_link = show_link,
linkto = linkto,
)
s3db.configure("dvr_response_action",
list_fields = list_fields,
filter_widgets = None,
orderby = "dvr_response_action.date desc",
create_next = r.url(id="", method=""),
update_next = r.url(id="", method=""),
)
else:
# Custom format for case activity representation
field = table.case_activity_id
#fmt = "%(pe_label)s %(last_name)s, %(first_name)s"
fmt = "%(last_name)s, %(first_name)s"
field.represent = s3db.dvr_CaseActivityRepresent(fmt = fmt,
show_link = True,
)
# Custom Filter Options
from s3 import S3AgeFilter, \
S3DateFilter, \
S3OptionsFilter, \
S3TextFilter, \
s3_get_filter_opts
if response_planning:
status_filter = S3OptionsFilter("status_id",
options = lambda: \
s3_get_filter_opts("dvr_response_status"),
cols = 3,
translate = True,
)
due_filter = S3DateFilter("date_due", hidden=is_report)
else:
status_filter = due_filter = None
filter_widgets = [S3TextFilter(
["case_activity_id$person_id$pe_label",
"case_activity_id$person_id$first_name",
"case_activity_id$person_id$middle_name",
"case_activity_id$person_id$last_name",
"comments",
],
label = T("Search"),
),
status_filter,
S3DateFilter("date", hidden=not is_report),
due_filter,
S3OptionsFilter(
"response_theme_ids",
hidden = True,
options = lambda: \
s3_get_filter_opts("dvr_response_theme",
org_filter = True,
),
),
S3OptionsFilter("case_activity_id$person_id$person_details.nationality",
label = T("Client Nationality"),
hidden = True,
),
S3AgeFilter("case_activity_id$person_id$date_of_birth",
label = T("Client Age"),
hidden = True,
)
#S3DateFilter("case_activity_id$person_id$date_of_birth",
# label = T("Client Date of Birth"),
# hidden = True,
# ),
]
if r.interactive and multiple_orgs:
# Add case organisation filter
if realms:
# Provide the realms as filter options
otable = s3db.org_organisation
orgs = db(otable.pe_id.belongs(realms)).select(otable.id)
org_filter_opts = s3db.org_organisation_represent.bulk(
[org.id for org in orgs],
show_link = False,
)
org_filter_opts.pop(None, None)
else:
# Look up from records
org_filter_opts = None
filter_widgets.insert(1,
S3OptionsFilter(org_context,
options = org_filter_opts,
),
)
s3db.configure("dvr_response_action",
filter_widgets = filter_widgets,
)
if r.tablename == "dvr_response_action":
list_fields.insert(0, (T("ID"), "case_activity_id$person_id$pe_label"))
s3db.configure("dvr_response_action",
list_fields = list_fields,
)
# TODO Complete this (perspective? status?)
s3db.configure("dvr_response_action",
organize = {"title": "case_activity_id$person_id",
"description": ["response_theme_ids",
"comments",
"human_resource_id",
],
},
)
settings.customise_dvr_response_action_resource = customise_dvr_response_action_resource
# -------------------------------------------------------------------------
def customise_dvr_response_action_controller(**attr):
s3db = current.s3db
if "viewing" in current.request.get_vars:
# Set contacts-method to retain the tab
s3db.set_method("pr", "person",
method = "contacts",
action = s3db.pr_Contacts,
)
else:
settings.base.bigtable = True
# Custom rheader tabs
if current.request.controller == "dvr":
attr = dict(attr)
attr["rheader"] = drk_dvr_rheader
return attr
settings.customise_dvr_response_action_controller = customise_dvr_response_action_controller
# -------------------------------------------------------------------------
def customise_dvr_response_theme_resource(r, tablename):
is_admin = current.auth.s3_has_role("ADMIN")
if r.tablename == "org_organisation" and r.id:
s3db = current.s3db
ttable = s3db.dvr_response_theme
if is_admin or settings.get_dvr_response_themes_sectors():
# Limit sector selection to the sectors of the organisation
stable = s3db.org_sector
ltable = s3db.org_sector_organisation
dbset = current.db((ltable.sector_id == stable.id) & \
(ltable.organisation_id == r.id) & \
(ltable.deleted == False))
field = ttable.sector_id
field.comment = None
field.readable = field.writable = True
field.requires = IS_EMPTY_OR(IS_ONE_OF(dbset, "org_sector.id",
field.represent,
))
if is_admin or settings.get_dvr_response_themes_needs():
# Limit needs selection to the needs of the organisation
ntable = s3db.dvr_need
dbset = current.db(ntable.organisation_id == r.id)
field = ttable.need_id
field.comment = None
field.readable = field.writable = True
field.requires = IS_EMPTY_OR(IS_ONE_OF(dbset, "dvr_need.id",
field.represent,
))
# Custom CRUD Strings
current.response.s3.crud_strings["dvr_response_theme"] = Storage(
label_create = T("Create Counseling Theme"),
title_display = T("Counseling Theme Details"),
title_list = T("Counseling Themes"),
title_update = T("Edit Counseling Theme"),
label_list_button = T("List Counseling Themes"),
label_delete_button = T("Delete Counseling Theme"),
msg_record_created = T("Counseling Theme created"),
msg_record_modified = T("Counseling Theme updated"),
msg_record_deleted = T("Counseling Theme deleted"),
msg_list_empty = T("No Counseling Themes currently defined"),
)
settings.customise_dvr_response_theme_resource = customise_dvr_response_theme_resource
# -------------------------------------------------------------------------
def customise_dvr_service_contact_resource(r, tablename):
s3db = current.s3db
table = s3db.dvr_service_contact
field = table.type_id
field.label = T("Type")
field = table.organisation_id
field.readable = field.writable = False
field = table.organisation
field.readable = field.writable = True
settings.customise_dvr_service_contact_resource = customise_dvr_service_contact_resource
# -------------------------------------------------------------------------
# Shelter Registry Settings
#
settings.cr.people_registration = False
# -------------------------------------------------------------------------
def cr_shelter_onaccept(form):
"""
Custom onaccept for shelters:
* Update the Location for all linked Cases
(in case the Address has been updated)
"""
db = current.db
s3db = current.s3db
try:
record_id = form.vars.id
except AttributeError:
return
if not record_id:
# Nothing we can do
return
# Reload the record (need site_id which is never in form.vars)
table = s3db.cr_shelter
shelter = db(table.id == record_id).select(table.location_id,
table.site_id,
limitby = (0, 1),
).first()
# If shelter were None here, then this shouldn't have been called
# in the first place => let it raise AttributeError
location_id = shelter.location_id
site_id = shelter.site_id
ctable = s3db.dvr_case
cases = db(ctable.site_id == site_id).select(ctable.person_id)
if cases:
person_ids = set(case.person_id for case in cases)
ptable = s3db.pr_person
db(ptable.id.belongs(person_ids)).update(
location_id = location_id,
# Indirect update by system rule,
# do not change modified_* fields:
modified_on = ptable.modified_on,
modified_by = ptable.modified_by,
)
# -------------------------------------------------------------------------
def cr_shelter_population():
"""
Update the Population of all Shelters
* called onaccept from dvr_case
"""
db = current.db
s3db = current.s3db
# Get the number of open cases per site_id
ctable = s3db.dvr_case
dtable = s3db.dvr_case_details
stable = s3db.dvr_case_status
join = stable.on(stable.id == ctable.status_id)
left = dtable.on((dtable.person_id == ctable.person_id) & \
((dtable.case_id == None) |
(dtable.case_id == ctable.id)) & \
(dtable.deleted == False))
today = current.request.utcnow.date()
query = (ctable.site_id != None) & \
(ctable.deleted == False) & \
(stable.is_closed == False) & \
((dtable.on_site_from == None) | (dtable.on_site_from <= today)) & \
((dtable.on_site_until == None) | (dtable.on_site_until >= today))
site_id = ctable.site_id
count = ctable.id.count()
rows = db(query).select(site_id,
count,
groupby = site_id,
join = join,
left = left,
)
# Update shelter population count
stable = s3db.cr_shelter
for row in rows:
db(stable.site_id == row[site_id]).update(
population = row[count],
# Indirect update by system rule,
# do not change modified_* fields:
modified_on = stable.modified_on,
modified_by = stable.modified_by,
)
# -------------------------------------------------------------------------
def customise_cr_shelter_resource(r, tablename):
auth = current.auth
s3db = current.s3db
s3 = current.response.s3
# Disable name-validation of cr_shelter_type
import_prep = s3.import_prep
def custom_import_prep(data):
# Call standard import_prep
if import_prep:
from gluon.tools import callback
callback(import_prep, data, tablename="cr_shelter")
# Disable uniqueness validation for shelter type names,
# otherwise imports will fail before reaching de-duplicate
ttable = s3db.cr_shelter_type
field = ttable.name
field.requires = IS_NOT_EMPTY()
# Reset to standard (no need to repeat it)
s3.import_prep = import_prep
s3.import_prep = custom_import_prep
from s3 import S3LocationSelector, \
S3SQLCustomForm
# Field configurations
table = s3db.cr_shelter
field = table.organisation_id
user_org = auth.user.organisation_id if auth.user else None
if user_org:
field.default = user_org
field = table.shelter_type_id
field.comment = None
# Hide L2 Government District
field = table.location_id
field.widget = S3LocationSelector(levels = gis_levels,
show_address = True,
)
# Custom form
crud_form = S3SQLCustomForm("name",
"organisation_id",
"shelter_type_id",
"location_id",
"phone",
"status",
"comments",
)
# Custom list fields
list_fields = [(T("Name"), "name"),
(T("Type"), "shelter_type_id"),
"organisation_id",
(T("Number of Cases"), "population"),
"status",
]
# Which levels of Hierarchy are we using?
#levels = current.gis.get_relevant_hierarchy_levels()
lfields = ["location_id$%s" % level for level in gis_levels]
list_fields[-1:-1] = lfields
s3db.configure("cr_shelter",
crud_form = crud_form,
list_fields = list_fields,
)
# Add custom onaccept
s3db.add_custom_callback(tablename,
"onaccept",
cr_shelter_onaccept,
)
settings.customise_cr_shelter_resource = customise_cr_shelter_resource
# -------------------------------------------------------------------------
def customise_cr_shelter_controller(**attr):
s3 = current.response.s3
# Custom prep
standard_prep = s3.prep
def custom_prep(r):
# Call standard prep
if callable(standard_prep):
result = standard_prep(r)
else:
result = True
if r.interactive:
resource = r.resource
# Customise filter widgets
filter_widgets = resource.get_config("filter_widgets")
if filter_widgets:
from s3 import S3TextFilter
custom_filters = []
for fw in filter_widgets:
if fw.field == "capacity_day":
continue
elif fw.field == "location_id":
fw.opts["levels"] = gis_levels
if not isinstance(fw, S3TextFilter) and \
fw.field != "shelter_type_id":
fw.opts["hidden"] = True
custom_filters.append(fw)
resource.configure(filter_widgets = custom_filters)
return result
s3.prep = custom_prep
# Custom rheader
attr = dict(attr)
attr["rheader"] = drk_cr_rheader
return attr
settings.customise_cr_shelter_controller = customise_cr_shelter_controller
# -------------------------------------------------------------------------
def customise_org_organisation_controller(**attr):
s3 = current.response.s3
# Custom prep
standard_prep = s3.prep
def custom_prep(r):
# Call standard prep
if callable(standard_prep):
result = standard_prep(r)
else:
result = True
# Disable creation of new root orgs unless user is ORG_GROUP_ADMIN
if r.method != "hierarchy" and \
(r.representation != "popup" or not r.get_vars.get("hierarchy")):
auth = current.auth
sysroles = sysroles = auth.get_system_roles()
insertable = auth.s3_has_roles((sysroles.ADMIN,
sysroles.ORG_GROUP_ADMIN,
))
r.resource.configure(insertable = insertable)
if r.component_name == "document":
s3.crud_strings["doc_document"].label_create = T("Add Document Template")
# Done in customise_doc_document_resource
#f = current.s3db.doc_document.url
#f.readable = f.writable = False
current.s3db.doc_document.is_template.default = True
r.resource.add_component_filter("document", FS("is_template") == True)
return result
s3.prep = custom_prep
attr = dict(attr)
attr["rheader"] = drk_org_rheader
return attr
settings.customise_org_organisation_controller = customise_org_organisation_controller
# -------------------------------------------------------------------------
def org_site_check(site_id):
""" Custom tasks for scheduled site checks """
# Tasks which are not site-specific
if site_id == "all":
# Update all shelter populations
# NB will be db.committed by org_site_check in models/tasks.py
current.log.info("Updating all shelter populations")
cr_shelter_population()
settings.org.site_check = org_site_check
# -------------------------------------------------------------------------
def customise_org_facility_resource(r, tablename):
s3db = current.s3db
# Hide "code" field (not needed)
table = s3db.org_facility
field = table.code
field.readable = field.writable = False
# Location selector just needs country + address
from s3 import S3LocationSelector
field = table.location_id
field.widget = S3LocationSelector(levels = ["L0"],
show_address=True,
show_map = False,
)
field = table.obsolete
field.label = T("Inactive")
field.represent = lambda opt: T("Inactive") if opt else current.messages["NONE"]
# Custom list fields
list_fields = ["name",
"site_facility_type.facility_type_id",
"organisation_id",
"location_id",
"contact",
"phone1",
"phone2",
"email",
#"website",
"obsolete",
"comments",
]
# Custom filter widgets
from s3 import S3TextFilter, S3OptionsFilter, s3_get_filter_opts
filter_widgets = [S3TextFilter(["name",
"organisation_id$name",
"organisation_id$acronym",
"comments",
],
label = T("Search"),
),
S3OptionsFilter("site_facility_type.facility_type_id",
options = s3_get_filter_opts("org_facility_type",
translate = True,
),
),
S3OptionsFilter("organisation_id",
),
S3OptionsFilter("obsolete",
options = {False: T("No"),
True: T("Yes"),
},
default = [False],
cols = 2,
)
]
s3db.configure("org_facility",
#deletable = False,
filter_widgets = filter_widgets,
list_fields = list_fields,
)
settings.customise_org_facility_resource = customise_org_facility_resource
# -------------------------------------------------------------------------
def customise_org_facility_controller(**attr):
# Allow selection of all countries
current.deployment_settings.gis.countries = []
# Custom rheader+tabs
if current.request.controller == "org":
attr = dict(attr)
attr["rheader"] = drk_org_rheader
return attr
settings.customise_org_facility_controller = customise_org_facility_controller
# -------------------------------------------------------------------------
def customise_org_sector_resource(r, tablename):
table = current.s3db.org_sector
field = table.location_id
field.readable = field.writable = False
settings.customise_org_sector_resource = customise_org_sector_resource
# -------------------------------------------------------------------------
# Project Module Settings
#
settings.project.mode_task = True
settings.project.projects = False
settings.project.sectors = False
# NB should not add or remove options, but just comment/uncomment
settings.project.task_status_opts = {#1: T("Draft"),
2: T("New"),
3: T("Assigned"),
#4: T("Feedback"),
#5: T("Blocked"),
6: T("On Hold"),
7: T("Canceled"),
#8: T("Duplicate"),
#9: T("Ready"),
#10: T("Verified"),
#11: T("Reopened"),
12: T("Completed"),
}
settings.project.task_time = False
settings.project.my_tasks_include_team_tasks = True
# -------------------------------------------------------------------------
#def customise_project_home():
# """ Always go to task list """
#
# from s3 import s3_redirect_default
# s3_redirect_default(URL(f="task"))
#
#settings.customise_project_home = customise_project_home
# -------------------------------------------------------------------------
def customise_project_task_resource(r, tablename):
"""
Restrict list of assignees to just Staff/Volunteers
"""
db = current.db
s3db = current.s3db
# Configure custom form for tasks
from s3 import S3SQLCustomForm
crud_form = S3SQLCustomForm("name",
"status",
"priority",
"description",
#"source",
"pe_id",
"date_due",
)
s3db.configure("project_task",
crud_form = crud_form,
update_realm = True,
)
accessible_query = current.auth.s3_accessible_query
# Filter assignees to human resources
htable = s3db.hrm_human_resource
ptable = s3db.pr_person
query = accessible_query("read", htable) & \
(htable.person_id == ptable.id)
rows = db(query).select(ptable.pe_id)
pe_ids = set(row.pe_id for row in rows)
# ...and teams
gtable = s3db.pr_group
query = accessible_query("read", gtable) & \
(gtable.group_type == 3)
rows = db(query).select(gtable.pe_id)
pe_ids |= set(row.pe_id for row in rows)
s3db.project_task.pe_id.requires = IS_EMPTY_OR(
IS_ONE_OF(db, "pr_pentity.pe_id",
s3db.pr_PersonEntityRepresent(show_label = False,
show_type = True,
),
sort = True,
filterby = "pe_id",
filter_opts = pe_ids,
))
settings.customise_project_task_resource = customise_project_task_resource
# -------------------------------------------------------------------------
# Comment/uncomment modules here to disable/enable them
# Modules menu is defined in modules/eden/menu.py
settings.modules = OrderedDict([
# Core modules which shouldn't be disabled
("default", Storage(
name_nice = T("Home"),
restricted = False, # Use ACLs to control access to this module
access = None, # All Users (inc Anonymous) can see this module in the default menu & access the controller
module_type = None # This item is not shown in the menu
)),
("admin", Storage(
name_nice = T("Administration"),
#description = "Site Administration",
restricted = True,
access = "|1|", # Only Administrators can see this module in the default menu & access the controller
module_type = None # This item is handled separately for the menu
)),
("appadmin", Storage(
name_nice = T("Administration"),
#description = "Site Administration",
restricted = True,
module_type = None # No Menu
)),
("errors", Storage(
name_nice = T("Ticket Viewer"),
#description = "Needed for Breadcrumbs",
restricted = False,
module_type = None # No Menu
)),
#("sync", Storage(
# name_nice = T("Synchronization"),
# #description = "Synchronization",
# restricted = True,
# access = "|1|", # Only Administrators can see this module in the default menu & access the controller
# module_type = None # This item is handled separately for the menu
#)),
#("tour", Storage(
# name_nice = T("Guided Tour Functionality"),
# module_type = None,
#)),
#("translate", Storage(
# name_nice = T("Translation Functionality"),
# #description = "Selective translation of strings based on module.",
# module_type = None,
#)),
("gis", Storage(
name_nice = T("Map"),
#description = "Situation Awareness & Geospatial Analysis",
restricted = True,
module_type = 6, # 6th item in the menu
)),
("pr", Storage(
name_nice = T("Person Registry"),
#description = "Central point to record details on People",
restricted = True,
access = "|1|", # Only Administrators can see this module in the default menu (access to controller is possible to all still)
module_type = 10
)),
("org", Storage(
name_nice = T("Organizations"),
#description = 'Lists "who is doing what & where". Allows relief agencies to coordinate their activities',
restricted = True,
module_type = 1
)),
("hrm", Storage(
name_nice = T("Staff"),
#description = "Human Resources Management",
restricted = True,
module_type = 2,
)),
("vol", Storage(
name_nice = T("Volunteers"),
#description = "Human Resources Management",
restricted = True,
module_type = 2,
)),
("cms", Storage(
name_nice = T("Content Management"),
#description = "Content Management System",
restricted = True,
module_type = 10,
)),
("doc", Storage(
name_nice = T("Documents"),
#description = "A library of digital resources, such as photos, documents and reports",
restricted = True,
module_type = 10,
)),
("msg", Storage(
name_nice = T("Messaging"),
#description = "Sends & Receives Alerts via Email & SMS",
restricted = True,
# The user-visible functionality of this module isn't normally required. Rather it's main purpose is to be accessed from other modules.
module_type = None,
)),
#("supply", Storage(
# name_nice = T("Supply Chain Management"),
# #description = "Used within Inventory Management, Request Management and Asset Management",
# restricted = True,
# module_type = None, # Not displayed
#)),
#("inv", Storage(
# name_nice = T("Warehouses"),
# #description = "Receiving and Sending Items",
# restricted = True,
# module_type = 4
#)),
#("asset", Storage(
# name_nice = T("Assets"),
# #description = "Recording and Assigning Assets",
# restricted = True,
# module_type = 5,
#)),
# Vehicle depends on Assets
#("vehicle", Storage(
# name_nice = T("Vehicles"),
# #description = "Manage Vehicles",
# restricted = True,
# module_type = 10,
#)),
#("req", Storage(
# name_nice = T("Requests"),
# #description = "Manage requests for supplies, assets, staff or other resources. Matches against Inventories where supplies are requested.",
# restricted = True,
# module_type = 10,
#)),
("project", Storage(
name_nice = T("Projects"),
#description = "Tracking of Projects, Activities and Tasks",
restricted = True,
module_type = 2
)),
("cr", Storage(
name_nice = T("Shelters"),
#description = "Tracks the location, capacity and breakdown of victims in Shelters",
restricted = True,
module_type = 10
)),
#("hms", Storage(
# name_nice = T("Hospitals"),
# #description = "Helps to monitor status of hospitals",
# restricted = True,
# module_type = 10
#)),
("dvr", Storage(
name_nice = T("Case Management"),
#description = "Allow affected individuals & households to register to receive compensation and distributions",
restricted = True,
module_type = 10,
)),
#("event", Storage(
# name_nice = T("Events"),
# #description = "Activate Events (e.g. from Scenario templates) for allocation of appropriate Resources (Human, Assets & Facilities).",
# restricted = True,
# module_type = 10,
#)),
#("security", Storage(
# name_nice = T("Security"),
# restricted = True,
# module_type = 10,
#)),
#("transport", Storage(
# name_nice = T("Transport"),
# restricted = True,
# module_type = 10,
#)),
("stats", Storage(
name_nice = T("Statistics"),
#description = "Manages statistics",
restricted = True,
module_type = None,
)),
])
# =============================================================================
def drk_cr_rheader(r, tabs=None):
""" CR custom resource headers """
if r.representation != "html":
# Resource headers only used in interactive views
return None
from s3 import s3_rheader_resource, S3ResourceHeader
tablename, record = s3_rheader_resource(r)
if tablename != r.tablename:
resource = current.s3db.resource(tablename, id=record.id)
else:
resource = r.resource
rheader = None
rheader_fields = []
if record:
T = current.T
if tablename == "cr_shelter":
if not tabs:
tabs = [(T("Basic Details"), None),
]
rheader_fields = [["name",
],
["organisation_id",
],
["location_id",
],
]
rheader = S3ResourceHeader(rheader_fields, tabs)(r,
table=resource.table,
record=record,
)
return rheader
# =============================================================================
def get_protection_themes(person):
"""
Get response themes of a case that are linked to protection needs
@param person: the beneficiary record (pr_person Row)
@returns: list-representation of response themes
"""
db = current.db
s3db = current.s3db
# Get all theme_ids that are linked to protection needs
ntable = s3db.dvr_need
ttable = s3db.dvr_response_theme
query = (ntable.protection == True) & \
(ntable.id == ttable.need_id) & \
(ttable.deleted == False)
themes = db(query).select(ttable.id,
cache = s3db.cache,
)
theme_ids = set(theme.id for theme in themes)
# Find out which of these themes are linked to the person
atable = s3db.dvr_case_activity
rtable = s3db.dvr_response_action
ltable = s3db.dvr_response_action_theme
query = (ltable.theme_id.belongs(theme_ids)) & \
(ltable.action_id == rtable.id) & \
(ltable.deleted == False) & \
(rtable.case_activity_id == atable.id) & \
(rtable.deleted == False) & \
(atable.person_id == person.id) & \
(atable.deleted == False)
rows = db(query).select(ltable.theme_id,
groupby = ltable.theme_id,
)
theme_list = [row.theme_id for row in rows]
# Return presented as list
represent = rtable.response_theme_ids.represent
return represent(theme_list)
# =============================================================================
def drk_dvr_rheader(r, tabs=None):
""" DVR custom resource headers """
if r.representation != "html":
# Resource headers only used in interactive views
return None
from s3 import s3_rheader_resource, \
S3ResourceHeader, \
s3_fullname
tablename, record = s3_rheader_resource(r)
if tablename != r.tablename:
resource = current.s3db.resource(tablename, id=record.id)
else:
resource = r.resource
rheader = None
rheader_fields = []
if record:
T = current.T
record_id = record.id
if tablename == "pr_person":
# "Case Archived" hint
hint = lambda record: SPAN(T("Invalid Case"),
_class="invalid-case",
)
if current.request.controller == "security":
# No rheader except archived-hint
case = resource.select(["dvr_case.archived"], as_rows=True)
if case and case[0]["dvr_case.archived"]:
rheader_fields = [[(None, hint)]]
tabs = None
else:
return None
else:
ui_opts = get_ui_options()
ui_opts_get = ui_opts.get
if not tabs:
tabs = [(T("Basic Details"), None),
(T("Contact Info"), "contacts"),
(T("Family Members"), "group_membership/"),
(T("Activities"), "case_activity"),
(T("Appointments"), "case_appointment"),
#(T("Service Contacts"), "service_contact"),
(T("Photos"), "image"),
(T("Documents"), "document/"),
#(T("Notes"), "case_note"),
]
if ui_opts_get("case_use_action_tab"):
tabs.insert(4, (T("Actions"), "response_action/"))
if ui_opts_get("case_use_service_contacts"):
tabs.insert(5, (T("Service Contacts"), "service_contact"))
if ui_opts_get("case_use_notes"):
tabs.append((T("Notes"), "case_note"))
lodging_opt = ui_opts_get("case_lodging")
if lodging_opt == "site":
lodging_sel = "dvr_case.site_id"
lodging_col = "dvr_case.site_id"
elif lodging_opt == "text":
lodging_sel = "case_details.lodging"
lodging_col = "dvr_case_details.lodging"
else:
lodging_sel = None
lodging_col = None
if ui_opts_get("case_use_flags"):
flags_sel = "dvr_case_flag_case.flag_id"
else:
flags_sel = None
case = resource.select(["first_name",
"last_name",
"dvr_case.status_id",
"dvr_case.archived",
"dvr_case.household_size",
"dvr_case.organisation_id",
lodging_sel,
flags_sel,
],
represent = True,
raw_data = True,
).rows
if case:
# Extract case data
case = case[0]
name = s3_fullname
case_status = lambda row: case["dvr_case.status_id"]
archived = case["_row"]["dvr_case.archived"]
household_size = lambda row: case["dvr_case.household_size"]
organisation = lambda row: case["dvr_case.organisation_id"]
if lodging_col:
lodging = (T("Lodging"), lambda row: case[lodging_col])
else:
lodging = None
if flags_sel:
flags = lambda row: case["dvr_case_flag_case.flag_id"]
else:
flags = None
else:
# Target record exists, but doesn't match filters
return None
rheader_fields = [[(T("ID"), "pe_label"),
(T("Case Status"), case_status),
(T("Organisation"), organisation),
],
[(T("Name"), name),
(T("Size of Family"), household_size),
lodging,
],
["date_of_birth",
],
]
if flags_sel:
rheader_fields.append([(T("Flags"), flags, 5)])
if ui_opts_get("case_header_protection_themes"):
rheader_fields.append([(T("Protection Need"),
get_protection_themes,
5,
)])
if archived:
rheader_fields.insert(0, [(None, hint)])
# Generate rheader XML
rheader = S3ResourceHeader(rheader_fields, tabs)(
r,
table = resource.table,
record = record,
)
# Add profile picture
from s3 import s3_avatar_represent
rheader.insert(0, A(s3_avatar_represent(record_id,
"pr_person",
_class = "rheader-avatar",
),
_href=URL(f = "person",
args = [record_id, "image"],
vars = r.get_vars,
),
)
)
return rheader
elif tablename == "dvr_case":
if not tabs:
tabs = [(T("Basic Details"), None),
(T("Activities"), "case_activity"),
]
rheader_fields = [["reference"],
["status_id"],
]
rheader = S3ResourceHeader(rheader_fields, tabs)(r,
table=resource.table,
record=record,
)
return rheader
# =============================================================================
def drk_org_rheader(r, tabs=None):
""" ORG custom resource headers """
if r.representation != "html":
# Resource headers only used in interactive views
return None
from s3 import s3_rheader_resource, s3_rheader_tabs, S3ResourceHeader
s3db = current.s3db
tablename, record = s3_rheader_resource(r)
if tablename != r.tablename:
resource = s3db.resource(tablename, id=record.id)
else:
resource = r.resource
rheader = None
rheader_fields = []
if record:
T = current.T
record_id = record.id
ui_options = get_ui_options()
is_admin = current.auth.s3_has_role("ADMIN")
if tablename == "org_organisation":
table = resource.table
if record.root_organisation == record_id:
branch = False
else:
branch = True
# Custom tabs
tabs = [(T("Basic Details"), None),
(T("Branches"), "branch"),
(T("Facilities"), "facility"),
(T("Staff & Volunteers"), "human_resource"),
#(T("Projects"), "project"),
(T("Counseling Themes"), "response_theme"),
]
if is_admin or ui_options.get("response_themes_needs"):
# Ability to manage org-specific need types
# as they are used in themes:
tabs.append((T("Need Types"), "need"))
if not branch and \
(is_admin or \
ui_options.get("case_document_templates") and \
current.auth.s3_has_role("ORG_ADMIN")):
tabs.append((T("Document Templates"), "document"))
rheader_tabs = s3_rheader_tabs(r, tabs)
# Custom header
from gluon import TABLE, TR, TH, TD
rheader = DIV()
# Name
record_data = TABLE(TR(TH("%s: " % table.name.label),
record.name,
),
)
# Parent Organisation
if branch:
btable = s3db.org_organisation_branch
query = (btable.branch_id == record_id) & \
(btable.organisation_id == table.id)
row = current.db(query).select(table.id,
table.name,
limitby = (0, 1),
).first()
if row:
record_data.append(TR(TH("%s: " % T("Branch of")),
A(row.name, _href=URL(args=[row.id, "read"])),
))
# Website as link
if record.website:
record_data.append(TR(TH("%s: " % table.website.label),
A(record.website, _href=record.website)))
logo = s3db.org_organisation_logo(record)
if logo:
rheader.append(TABLE(TR(TD(logo),
TD(record_data),
)))
else:
rheader.append(record_data)
rheader.append(rheader_tabs)
return rheader
elif tablename == "org_facility":
if not tabs:
tabs = [(T("Basic Details"), None),
]
rheader_fields = [["name", "email"],
["organisation_id", "phone1"],
["location_id", "phone2"],
]
rheader = S3ResourceHeader(rheader_fields, tabs)(r,
table=resource.table,
record=record,
)
return rheader
# =============================================================================
def drk_anonymous_address(record_id, field, value):
"""
Helper to anonymize a pr_address location; removes street and
postcode details, but retains Lx ancestry for statistics
@param record_id: the pr_address record ID
@param field: the location_id Field
@param value: the location_id
@return: the location_id
"""
s3db = current.s3db
db = current.db
# Get the location
if value:
ltable = s3db.gis_location
row = db(ltable.id == value).select(ltable.id,
ltable.level,
limitby = (0, 1),
).first()
if not row.level:
# Specific location => remove address details
data = {"addr_street": None,
"addr_postcode": None,
"gis_feature_type": 0,
"lat": None,
"lon": None,
"wkt": None,
}
# Doesn't work - PyDAL doesn't detect the None value:
#if "the_geom" in ltable.fields:
# data["the_geom"] = None
row.update_record(**data)
if "the_geom" in ltable.fields:
db.executesql("UPDATE gis_location SET the_geom=NULL WHERE id=%s" % row.id)
return value
# -----------------------------------------------------------------------------
def drk_obscure_dob(record_id, field, value):
"""
Helper to obscure a date of birth; maps to the first day of
the quarter, thus retaining the approximate age for statistics
@param record_id: the pr_address record ID
@param field: the location_id Field
@param value: the location_id
@return: the new date
"""
if value:
month = int((value.month - 1) / 3) * 3 + 1
value = value.replace(month=month, day=1)
return value
# -----------------------------------------------------------------------------
def drk_person_anonymize():
""" Rules to anonymize a case file """
ANONYMOUS = "-"
# Helper to produce an anonymous ID (pe_label)
anonymous_id = lambda record_id, f, v: "NN%06d" % long(record_id)
# General rule for attachments
documents = ("doc_document", {"key": "doc_id",
"match": "doc_id",
"fields": {"name": ("set", ANONYMOUS),
"file": "remove",
"comments": "remove",
},
"delete": True,
})
# Cascade rule for case activities
activity_details = [("dvr_response_action", {"key": "case_activity_id",
"match": "id",
"fields": {"comments": "remove",
},
}),
("dvr_case_activity_need", {"key": "case_activity_id",
"match": "id",
"fields": {"comments": "remove",
},
}),
("dvr_case_activity_update", {"key": "case_activity_id",
"match": "id",
"fields": {"comments": ("set", ANONYMOUS),
},
}),
]
rules = [# Remove identity of beneficiary
{"name": "default",
"title": "Names, IDs, Reference Numbers, Contact Information, Addresses",
"fields": {"first_name": ("set", ANONYMOUS),
"last_name": ("set", ANONYMOUS),
"pe_label": anonymous_id,
"date_of_birth": drk_obscure_dob,
"comments": "remove",
},
"cascade": [("dvr_case", {"key": "person_id",
"match": "id",
"fields": {"comments": "remove",
},
}),
("dvr_case_details", {"key": "person_id",
"match": "id",
"fields": {"lodging": "remove",
},
}),
("pr_contact", {"key": "pe_id",
"match": "pe_id",
"fields": {"contact_description": "remove",
"value": ("set", ""),
"comments": "remove",
},
"delete": True,
}),
("pr_contact_emergency", {"key": "pe_id",
"match": "pe_id",
"fields": {"name": ("set", ANONYMOUS),
"relationship": "remove",
"phone": "remove",
"comments": "remove",
},
"delete": True,
}),
("pr_address", {"key": "pe_id",
"match": "pe_id",
"fields": {"location_id": drk_anonymous_address,
"comments": "remove",
},
}),
("pr_person_details", {"key": "person_id",
"match": "id",
"fields": {"education": "remove",
"occupation": "remove",
},
}),
("pr_person_tag", {"key": "person_id",
"match": "id",
"fields": {"value": ("set", ANONYMOUS),
},
"delete": True,
}),
("dvr_residence_status", {"key": "person_id",
"match": "id",
"fields": {"reference": ("set", ANONYMOUS),
"comments": "remove",
},
}),
("dvr_service_contact", {"key": "person_id",
"match": "id",
"fields": {"reference": "remove",
"contact": "remove",
"phone": "remove",
"email": "remove",
"comments": "remove",
},
}),
],
},
# Remove activity details, appointments and notes
{"name": "activities",
"title": "Activity Details, Appointments, Notes",
"cascade": [("dvr_case_activity", {"key": "person_id",
"match": "id",
"fields": {"subject": ("set", ANONYMOUS),
"need_details": "remove",
"outcome": "remove",
"comments": "remove",
},
"cascade": activity_details,
}),
("dvr_case_appointment", {"key": "person_id",
"match": "id",
"fields": {"comments": "remove",
},
}),
("dvr_case_language", {"key": "person_id",
"match": "id",
"fields": {"comments": "remove",
},
}),
("dvr_note", {"key": "person_id",
"match": "id",
"fields": {"note": "remove",
},
"delete": True,
}),
],
},
# Remove photos and attachments
{"name": "documents",
"title": "Photos and Documents",
"cascade": [("dvr_case", {"key": "person_id",
"match": "id",
"cascade": [documents,
],
}),
("dvr_case_activity", {"key": "person_id",
"match": "id",
"cascade": [documents,
],
}),
("pr_image", {"key": "pe_id",
"match": "pe_id",
"fields": {"image": "remove",
"url": "remove",
"description": "remove",
},
"delete": True,
}),
],
},
# TODO family membership
]
return rules
# =============================================================================
class PriorityRepresent(object):
"""
Color-coded representation of priorities
@todo: generalize/move to s3utils?
"""
def __init__(self, options, classes=None):
"""
Constructor
@param options: the options (as dict or anything that can be
converted into a dict)
@param classes: a dict mapping keys to CSS class suffixes
"""
self.options = dict(options)
self.classes = classes
def represent(self, value, row=None):
"""
Representation function
@param value: the value to represent
"""
css_class = base_class = "prio"
classes = self.classes
if classes:
suffix = classes.get(value)
if suffix:
css_class = "%s %s-%s" % (css_class, base_class, suffix)
label = self.options.get(value)
return DIV(label, _class=css_class)
# END =========================================================================
|
import sys
import os
cwd = os.getcwd()
package_path = os.path.abspath(cwd.split('phenotypy')[0])
print(f'[__init__]Append "{package_path}" to system.path')
sys.path.insert(0, package_path) |
const myStorage = window.localStorage;
|
from typing import Any, Tuple, Dict
import os, copy, os.path as osp
from colorama import Fore
from time import time
from tqdm import tqdm
import torch
import torch.nn.functional as F
import torch.optim.lr_scheduler as lr_scheduler
from torch import Tensor, nn, optim
from torch.nn.modules.loss import _Loss
from torch.utils.data import DataLoader
from .loss import KDLoss
from distiller.print_utils import print_msg, print_time, desc
folder_save = osp.realpath(osp.join(__file__, '..', '..', 'weights'))
if not osp.isdir(folder_save): os.makedirs(folder_save)
print('Model will save in ', Fore.MAGENTA, folder_save)
batch_num:int = 0
def reset_batch_num(): global batch_num; batch_num = 0
def train(loaders:Dict[str, DataLoader], dataset_sizes:Dict[str, int], device:torch.device,
teacher:nn.Module, best_acc:float,
criterion:_Loss, optimizer:optim.Optimizer, scheduler,
epochs:int, ckpt:int=20
) -> Tuple[nn.Module, float]:
global batch_num
best_teacher = copy.deepcopy(teacher)
since = time()
for epoch in range(1, epochs+1):
for phase in ('train', 'val'):
if phase == 'train':
teacher.train()
print(Fore.RED); print('Epoch : {:>2d}/{:<2d}'.format(
epoch, epochs), Fore.RESET, ' {:>48}'.format('='*46))
else:
teacher.eval()
running_loss = 0.0
running_corrects = 0.0
for datas, targets in tqdm(loaders[phase], ncols=64, colour='green',
desc='{:6}'.format(phase).capitalize()):
if phase == 'train': batch_num += 1
datas, targets = datas.to(device), targets.to(device)
optimizer.zero_grad()
with torch.set_grad_enabled(phase == 'train'):
outp = teacher(datas)
_, pred = torch.max(outp, 1)
loss = criterion(outp, targets)
if phase == 'train':
loss.backward()
optimizer.step()
running_loss += loss.item()*datas.size(0)
running_corrects += torch.sum(pred == targets.data)
#save checkpoint
if not batch_num % ckpt:
path_save = osp.join(folder_save, '{}_{}.pth'.format(
teacher.__class__.__name__, batch_num))
torch.save(teacher.state_dict(), path_save)
epoch_loss = running_loss / dataset_sizes[phase]
epoch_acc = running_corrects.double() / dataset_sizes[phase]
if phase == 'train':
scheduler.step(100. * epoch_acc) #acc
print('{} - loss = {:.6f}, accuracy = {:.3f}'.format(
'{:5}'.format(phase).capitalize(), epoch_loss, 100*epoch_acc))
if phase == 'val':
time_elapsed = time() - since
print('Time: {}m {:.3f}s'.format(
time_elapsed // 60, time_elapsed % 60))
if phase == 'val' and epoch_acc > best_acc:
best_acc = epoch_acc
best_teacher = copy.deepcopy(teacher)
path_save = osp.join(folder_save, '{}_best.pth'.format(
teacher.__class__.__name__))
torch.save(teacher.state_dict(), path_save)
return best_teacher, best_acc
def train_kd_4(loaders:Dict[str, DataLoader], dataset_sizes:Dict[str, int], device:torch.device,
teacher:nn.Module, student:nn.Module, best_acc:float,
criterion:KDLoss, optimizer:optim.Optimizer, scheduler:Any,
epochs:int, ckpt:int ) -> Tuple[nn.Module, float]:
global batch_num
model_name = student.__class__.__name__
student.to(device)
best_student = copy.deepcopy(student)
since = time()
for epoch in range(1, epochs + 1):
for phase in ('train', 'val'):
if phase == 'train':
student.train()
print(Fore.RED); print('Epoch : {:>2d}/{:<2d}'.format(
epoch, epochs), Fore.RESET, ' {:>48}'.format('='*46))
else:
student.eval()
running_loss = 0.0
running_corrects = 0.0
with tqdm(loaders[phase], ncols=128, colour='YELLOW',
desc=desc(epoch, epochs, phase, 0.0, best_acc)) as stream:
for idx, (datas, targets, soft_label) in enumerate(loaders[phase], start=1):
if phase == 'train': batch_num += 1
datas= datas.to(device)
targets = targets.to(device)
# if is_aug: soft_label = teacher(datas)
soft_label = soft_label.to(device)
optimizer.zero_grad()
with torch.set_grad_enabled(phase == 'train'):
outp_S = student(datas) # forward
_, pred = torch.max(outp_S, 1)
loss = criterion(outp_S, targets, soft_label)
if phase == 'train':
loss.backward()
optimizer.step()
#save checkpoint
if not batch_num % ckpt:
path_save = osp.join(folder_save, '{}_{}.pth'.format(model_name, batch_num))
torch.save(student.state_dict(), path_save)
running_loss += loss.item()*datas.size(0)
running_corrects += torch.sum(pred == targets.data)
# num_iter_data = idx*loaders[phase].batch_size
num_iter_data = idx*datas.size(0)
stream.set_description(
desc(epoch, epochs, phase,
loss=running_loss/num_iter_data,
acc= running_corrects / num_iter_data))
stream.update()
epoch_loss = running_loss / dataset_sizes[phase]
epoch_acc = running_corrects.double() / dataset_sizes[phase]
stream.set_description(
desc(epoch, epochs, phase, epoch_loss, epoch_acc))
print('{} - loss = {:.6f}, accuracy = {:.3f}'.format(
'{:5}'.format(phase).capitalize(), epoch_loss, 100*epoch_acc))
if phase == 'train':
scheduler.step(100. * epoch_acc) #acc
else:# phase == 'val'
time_elapsed = time() - since
print('Time: {}m {:.3f}s'.format(
time_elapsed // 60, time_elapsed % 60))
if phase == 'val' and epoch_acc > best_acc:
best_acc = epoch_acc
best_student = copy.deepcopy(student)
path_save = osp.join(folder_save, '{}_best.pth'.format(model_name))
torch.save(student.state_dict(), path_save)
return best_student, best_acc
def train_kd(loaders:Dict[str, DataLoader], dataset_sizes:Dict[str, int], device:torch.device,
teacher:nn.Module, student:nn.Module, best_acc:float,
criterion:KDLoss, optimizer:optim.Optimizer, scheduler:Any,
epochs:int, ckpt:int ) -> Tuple[nn.Module, float]:
global batch_num
model_name = student.__class__.__name__
student.to(device)
teacher.to(device).eval()
best_student = copy.deepcopy(student)
since = time()
for epoch in range(1, epochs + 1):
for phase in ('train', 'val'):
if phase == 'train':
student.train()
print(Fore.RED); print('Epoch : {:>2d}/{:<2d}'.format(
epoch, epochs), Fore.RESET, ' {:>48}'.format('='*46))
else:
student.eval()
running_loss = 0.0
running_corrects = 0.0
with tqdm(loaders[phase], ncols=128, colour='YELLOW',
desc=desc(epoch, epochs, phase, 0.0, best_acc)) as stream:
for idx, (datas, targets) in enumerate(loaders[phase], start=1):
if phase == 'train': batch_num += 1
datas= datas.to(device)
targets = targets.to(device)
with torch.no_grad():
outp_T = teacher(datas).detach()
optimizer.zero_grad()
with torch.set_grad_enabled(phase == 'train'):
outp_S = student(datas) # forward
_, pred = torch.max(outp_S, 1)
loss = criterion(outp_S, targets, outp_T)
if phase == 'train':
loss.backward()
optimizer.step()
#save checkpoint
if not batch_num % ckpt:
path_save = osp.join(folder_save, '{}_{}.pth'.format(model_name, batch_num))
torch.save(student.state_dict(), path_save)
running_loss += loss.item()*datas.size(0)
running_corrects += torch.sum(pred == targets.data)
# num_iter_data = idx*loaders[phase].batch_size
num_iter_data = idx*datas.size(0)
stream.set_description(
desc(epoch, epochs, phase,
loss=running_loss/num_iter_data,
acc= running_corrects / num_iter_data))
stream.update()
epoch_loss = running_loss / dataset_sizes[phase]
epoch_acc = running_corrects.double() / dataset_sizes[phase]
stream.set_description(
desc(epoch, epochs, phase, epoch_loss, epoch_acc))
print('{} - loss = {:.6f}, accuracy = {:.3f}'.format(
'{:5}'.format(phase).capitalize(), epoch_loss, 100*epoch_acc))
if phase == 'train':
scheduler.step(100. * epoch_acc) #acc
else:# phase == 'val'
time_elapsed = time() - since
print('Time: {}m {:.3f}s'.format(
time_elapsed // 60, time_elapsed % 60))
if phase == 'val' and epoch_acc > best_acc:
best_acc = epoch_acc
best_student = copy.deepcopy(student)
path_save = osp.join(folder_save, '{}_best.pth'.format(model_name))
torch.save(student.state_dict(), path_save)
return best_student, best_acc
class _Distiller(object):
def __init__(self, teacher:Any, student:nn.Module, criterion:_Loss) -> None:
# super().__init__()
self.teacher = teacher
self.student = student
self.criterion = criterion # KDLoss(T=6, alpha=0.1, reduction='batchmean')
@staticmethod
def distillation_loss(preds:Tensor, labels:Tensor, teacher_preds:Tensor, T, alpha:float) -> Tensor:
return T * T * alpha * F.kl_div(F.log_softmax(preds / T, dim=1),
F.softmax(teacher_preds / T, dim=1),
reduction='batchmean') + (1. - alpha) * F.cross_entropy(preds, labels)
def training_student(self, device:torch.device,
loaders:Dict[str, DataLoader], dataset_sizes:Dict[str, int],
epochs_warmup:int, epochs:int, model_name:str, ckpt:int,
) -> nn.Module:
assert len(loaders) >= 2 and len(dataset_sizes) >= 2, 'please check loaders'
reset_batch_num()
#TODO write desc of input and output
#TODO https://tinyurl.com/8wnknv9p
# all param unless classify layer must freeze at the first train
# for param in teacher.parameters():
# param.requires_grad = False
self.student.to(device)
optimizer = optim.Adam(list(self.student.children())[-1].parameters(), lr=0.001,
betas=(0.9, 0.999), eps=1e-08, weight_decay=1e-5)
scheduler = lr_scheduler.ReduceLROnPlateau(optimizer, mode='max', factor=0.2,
patience=3, verbose=True)
best_acc = 0.0
since = time()
#NOTE train only classify/fullyconnected/head layers
self.student, best_acc = train_kd(loaders, dataset_sizes, device,
self.student, best_acc,
self.criterion, optimizer, scheduler,
epochs_warmup, model_name, ckpt)
print(end='\n')
print_time('FREEZE TRAINING TIME', time() - since)
print_msg("Unfreeze all layers", model_name)
# unfrezz all layer
for param in self.student.parameters():
param.requires_grad = True
optimizer = optim.Adam(self.student.parameters(), lr=0.0001,
betas=(0.9, 0.999), eps=1e-08, weight_decay=0)
scheduler = lr_scheduler.ReduceLROnPlateau(optimizer, factor=0.2,
patience=2, verbose=True)
#NOTE train all layers of model
self.student, best_acc = train_kd(loaders, dataset_sizes, device,
self.student, best_acc,
self.criterion, optimizer, scheduler,
epochs, model_name, ckpt)
last_student = osp.join(folder_save, '{}_last.pth'.format(model_name))
torch.save(self.student.state_dict(), last_student)
time_elapsed = time() - since
print('ALL NET TRAINING TIME {} m {:.3f}s'.format(
time_elapsed//60, time_elapsed % 60))
return self.student
class Distiller(object):
r"""
# create teacher, resnet34
teacher = resnet34(pretrained=True, progress=True)
teacher.fc = nn.Linear(in_features=teacher.fc.in_features,
out_features=num_classes, bias=True)
teacher.load_state_dict(torch.load('path/to/teacher.pth'))
# create student, resnet18
student = resnet18(pretrained=True, progress=True)
student.fc = nn.Linear(in_features=teacher.fc.in_features,
out_features=num_classes, bias=True)
student.load_state_dict(torch.load('path/to/student.pth'))
# create loss function
kd_loss = KDLoss(T=6., alpha=0.1,reduction='batchmean')
distiller = Distiller(
device = torch.device('cuda:0' if torch.cuda.is_available()else 'cpu'),
teacher= teacher, teacher_name= 'resnet34',
student= student, student_name= 'resnet18',
loaders= dict_of_3_dataloaders,
dataset_sizes= dict_of_3_dataset_size,
S_criterion=kd_loss,
T_criterion=nn.CrossEntropyLoss(),
)
# train_teacher
distiller.training_teacher(0, 10, 20)
# train_student
distiller.training_student(20, 30, 20)
"""
def __init__(self, device:torch.device,
teacher:nn.Module, teacher_name:str,
student:nn.Module, student_name:str,
loaders:Dict[str, DataLoader], dataset_sizes:Dict[str, int],
S_criterion:KDLoss, T_criterion:_Loss=nn.CrossEntropyLoss()) -> None:
self.teacher = teacher.to(device)
self.teacher.__class__.__name__ = teacher_name
self.student = student.to(device)
self.student.__class__.__name__ = student_name
self.device = device
assert len(loaders) >= 2; self.loaders = loaders
assert len(dataset_sizes) >=2; self.dataset_sizes = dataset_sizes
self.S_criterion = S_criterion.to(device)
self.T_criterion = T_criterion.to(device)
print(Fore.RED)
print('Device name {}'.format(torch.cuda.get_device_name(0)), Fore.RESET)
def training_teacher(self, epochs_freeze:int, epochs_unfreeze:int, ckpt:int):
optimizer = optim.Adam(list(self.teacher.children())[-1].parameters(), lr=0.001,
betas=(0.9, 0.999), eps=1e-08, weight_decay=1e-5)
scheduler = lr_scheduler.ReduceLROnPlateau(optimizer, mode='max', factor=0.2,
patience=3, verbose=True)
since = time()
best_acc = 0.0
reset_batch_num()
self.teacher, best_acc = train(self.loaders, self.dataset_sizes, self.device,
self.teacher, best_acc,
self.T_criterion, optimizer, scheduler,
epochs_freeze, ckpt)
time_elapsed = time() - since
print('CLASSIFIER TRAINING TIME {} : {:.3f}'.format(
time_elapsed//60, time_elapsed % 60))
print_msg("Unfreeze all layers", self.teacher.__class__.__name__)
# unfrezz all layer
for param in self.teacher.parameters():
param.requires_grad = True
optimizer = optim.Adam(self.teacher.parameters(), lr=0.0001,
betas=(0.9, 0.999), eps=1e-08, weight_decay=0)
scheduler = lr_scheduler.ReduceLROnPlateau(optimizer, factor=0.2,
patience=2, verbose=True)
self.teacher, best_acc = train(self.loaders, self.dataset_sizes,
self.teacher, best_acc,
self.T_criterion, optimizer, scheduler,
epochs_unfreeze, ckpt)
last_teacher = osp.join(folder_save, '{}_last.pth'.format(
self.teacher.__class__.__name__))
torch.save(self.teacher.state_dict(), last_teacher)
time_elapsed = time() - since
print('TEACHER TRAINING TIME {} m {:.3f}s'.format(
time_elapsed//60, time_elapsed % 60))
def training_student(self, epochs_freeze:int, epochs_unfreeze:int, ckpt:int):
optimizer = optim.Adam(list(self.student.children())[-1].parameters(), lr=0.001,
betas=(0.9, 0.999), eps=1e-08, weight_decay=1e-5)
scheduler = lr_scheduler.ReduceLROnPlateau(optimizer, mode='max', factor=0.2,
patience=3, verbose=True)
best_acc = 0.0
model_name = self.student.__class__.__name__
reset_batch_num()
since = time()
#NOTE train only classify/fullyconnected/head layers
self.student, best_acc = train_kd(self.loaders, self.dataset_sizes, self.device,
self.teacher, self.student, best_acc,
self.S_criterion, optimizer, scheduler,
epochs_freeze, ckpt)
print(end='\n')
print_time('FREEZE TRAINING TIME', time() - since)
print_msg("Unfreeze all layers", model_name)
# unfrezz all layer
for param in self.student.parameters():
param.requires_grad = True
optimizer = optim.Adam(self.student.parameters(), lr=0.0001,
betas=(0.9, 0.999), eps=1e-08, weight_decay=0)
scheduler = lr_scheduler.ReduceLROnPlateau(optimizer, factor=0.2,
patience=2, verbose=True)
#NOTE train all layers of model
self.student, best_acc = train_kd(self.loaders, self.dataset_sizes, self.device,
self.teacher, self.student, best_acc,
self.S_criterion, optimizer, scheduler,
epochs_unfreeze, ckpt)
last_student = osp.join(folder_save, '{}_last.pth'.format(model_name))
torch.save(self.student.state_dict(), last_student)
time_elapsed = time() - since
print('STUDENT TRAINING TIME {} m {:.3f}s'.format(
time_elapsed//60, time_elapsed % 60))
|
import Vue from 'vue'
import Hammer from 'hammerjs'
const Zoomable = {
name: 'Zoomable',
props: {
width: {
type: Number,
required: true
},
height: {
type: Number,
required: true
},
maxScale: {
type: Number,
default: 2
},
lockX: null,
lockY: null
},
data () {
return {
scaleX_: 1,
scaleY_: 1,
offsetX_: 0,
offsetY_: 0,
lastDelta: {
scale: 1,
offsetX: 0,
offsetY: 0
}
}
},
computed: {
scaleX: {
get () {
return this.$options.synced ? this.$options.synced.scaleX_ : this.scaleX_
},
set (value) {
if (this.lockX != null) return
value = clamp(value, 1, this.maxScale)
if (this.$options.synced) this.$options.synced.scaleX_ = value
else this.scaleX_ = value
}
},
scaleY: {
get () {
return this.$options.synced ? this.$options.synced.scaleY_ : this.scaleY_
},
set (value) {
if (this.lockY != null) return
value = clamp(value, 1, this.maxScale)
if (this.$options.synced) this.$options.synced.scaleY_ = value
else this.scaleY_ = value
}
},
offsetX: {
get () {
return this.$options.synced ? this.$options.synced.offsetX_ : this.offsetX_
},
set (value) {
if (this.lockX != null) return
value = clamp(value, this.minOffsetX, 0)
if (this.$options.synced) this.$options.synced.offsetX_ = value
else this.offsetX_ = value
}
},
offsetY: {
get () {
return this.$options.synced ? this.$options.synced.offsetY_ : this.offsetY_
},
set (value) {
if (this.lockY != null) return
value = clamp(value, this.minOffsetY, 0)
if (this.$options.synced) this.$options.synced.offsetY_ = value
else this.offsetY_ = value
}
},
viewBox () {
return [
-this.offsetX / this.scaleX,
-this.offsetY / this.scaleY,
this.width / this.scaleX,
this.height / this.scaleY
].join(' ')
},
minOffsetX () {
return -this.width * (this.scaleX - 1)
},
minOffsetY () {
return -this.height * (this.scaleY - 1)
}
},
methods: {
handlePan (e) {
const deltaX = e.deltaX - this.lastDelta.offsetX
const deltaY = e.deltaY - this.lastDelta.offsetY
this.offsetX = this.offsetX + deltaX
this.offsetY = this.offsetY + deltaY
this.lastDelta.offsetX = e.deltaX
this.lastDelta.offsetY = e.deltaY
},
handlePinch (e) {
const deltaS = e.scale / this.lastDelta.scale
const {x: thisX, y: thisY} = this.$el.getBoundingClientRect()
const centerX = e.center.x - thisX
const centerY = e.center.y - thisY
const relativeCenterX = (centerX - this.offsetX) / this.scaleX
const relativeCenterY = (centerY - this.offsetY) / this.scaleY
this.scaleX = this.scaleX * deltaS
this.scaleY = this.scaleY * deltaS
this.offsetX = centerX - relativeCenterX * this.scaleX
this.offsetY = centerY - relativeCenterY * this.scaleY
this.lastDelta.scale = e.scale
}
},
mounted () {
this.$el.addEventListener('touchmove',
e => e.preventDefault(), {passive: false})
const manager = new Hammer.Manager(this.$el, {
recognizers: [
[Hammer.Pinch, {enable: true}],
[Hammer.Pan, {enable: true}]
]
})
manager.on('pinch', this.handlePinch)
manager.on('pan', this.handlePan)
manager.on('pinchend', () => {
this.lastDelta.scale = 1
})
manager.on('panend', () => {
this.lastDelta.offsetX = 0
this.lastDelta.offsetY = 0
})
},
render (h) {
return h('svg', {
class: 'vg-zoomable',
attrs: {
width: this.width,
height: this.height,
viewBox: this.viewBox,
preserveAspectRatio: 'none'
}
}, [
h('rect', {
attrs: {
width: this.width,
height: this.height,
fill: 'none'
},
style: {'pointer-events': 'all'}
}),
this.$slots.default
])
}
}
export default Zoomable
export function getSyncedZoomable () {
const synced = Vue.observable({
scaleX_: 1,
scaleY_: 1,
offsetX_: 0,
offsetY_: 0
})
return Object.assign({synced}, Zoomable)
}
function clamp (value, min, max) {
return Math.min(Math.max(value, min), max)
}
|
import numpy as np
from owcsimpy.geoobjects.models.simpleofficeenv_py import SimpleOfficeEnv_py as SimpleOfficeEnv
class TypicalSimpleOfficeEnv_py(SimpleOfficeEnv):
""" A typical realization of a simple office.
The chair and the table are located in the corner of the room.
Parameters
----------
roomDim: list
The dimensions of the room in [Length,Width,Height].
humanLoc
The human's location.
humanDirection
The humand's direction.
chairLoc
The chair's location. Note that the location of the table is
defined relative to the chair's location.
chairDirection
The chair's direction.
mode: {'tx','rx'}
Describe whether transmitting (tx) or receiving (rx)
activity: {'calling','reading','usbdongle'}
'calling' denotes the LED or the PD is near the right ear.
Meanwhile, 'reading' denotes the device is in front of the
human's chest. 'usbdongle' denotes the use of LiFi usb dongles
attached to a laptop on a desk.
position: {'standing','sitting'}
The human's positions.
furnitureConfig: {'cornerXFacingWall','cornerXNotFacingWall','cornerYFacingWall','cornerYNotFacingWall'}
The direction of the chair and the table.
Attributes
----------
See
:class:`~owcsimpy.geoobjects.model.simpleofficeenv_py.SimpleOfficeEnv_py`
"""
def __init__(self,
roomDim,
humanLoc=None,humanDirection=0,
mode='rx',
activity='calling',
position='standing',
furnitureConfig='cornerXFacingWall'
):
chairLoc,chairDirection = None,0
if position.lower()=='standing':
if furnitureConfig == 'cornerXFacingWall':
chairLoc=[0.6,1.45]
chairDirection=np.deg2rad(270)
elif furnitureConfig == 'cornerXNotFacingWall':
chairLoc=[0.6,0]
chairDirection=np.deg2rad(90)
elif furnitureConfig == 'cornerYFacingWall':
chairLoc=[1.45,0.6]
chairDirection=np.deg2rad(180)
elif furnitureConfig == 'cornerYNotFacingWall':
chairLoc=[0,0.6]
chairDirection=np.deg2rad(0)
elif position.lower()=='sitting':
# When sitting, the configuration of human will be overridden
if furnitureConfig == 'cornerXFacingWall':
humanLoc=[0.6,1.45+0.075]
humanDirection=np.deg2rad(270)
elif furnitureConfig == 'cornerXNotFacingWall':
humanLoc=[0.6,0+0.075]
humanDirection=np.deg2rad(90)
elif furnitureConfig == 'cornerYFacingWall':
humanLoc=[1.45+0.075,0.6]
humanDirection=np.deg2rad(180)
elif furnitureConfig == 'cornerYNotFacingWall':
humanLoc=[0+0.075,0.6]
humanDirection=np.deg2rad(0)
super().__init__(
roomDim=roomDim,
humanLoc=humanLoc,humanDirection=humanDirection,
chairLoc=chairLoc,chairDirection=chairDirection,
mode=mode,
activity=activity,
position=position
)
|
import DocumentTitle from 'react-document-title';
import Html from './html.react';
import Promise from 'bluebird';
import React from 'react';
import Router from 'react-router';
import config from './config';
import initialState from './initialstate';
import routes from '../client/routes';
import {state} from '../client/state';
export default function render(req, res, locale) {
const url = req.originalUrl;
return loadData(url, locale)
.then((appState) => renderPage(res, appState, url));
}
function loadData(url, locale) {
// TODO: Preload and merge user specific state.
const appState = initialState;
return new Promise((resolve, reject) => {
resolve(appState);
});
}
// TODO: Refactor.
function renderPage(res, appState, url) {
return new Promise((resolve, reject) => {
const router = Router.create({
routes,
location: url,
onError: reject,
onAbort: (abortReason) => {
// Some requireAuth higher order component requested redirect.
if (abortReason.constructor.name === 'Redirect') {
const {to, params, query} = abortReason;
const path = router.makePath(to, params, query);
res.redirect(path);
resolve();
return;
}
reject(abortReason);
}
});
router.run((Handler, routerState) => {
state.load(appState);
const html = getPageHtml(Handler, appState);
const notFound = routerState.routes.some(route => route.name === 'not-found');
const status = notFound ? 404 : 200;
res.status(status).send(html);
resolve();
});
});
}
function getPageHtml(Handler, appState) {
const appHtml = `<div id="app">${React.renderToString(<Handler />)}</div>`;
const appScriptSrc = config.isProduction
? '/build/app.js?v=' + config.version
: '//localhost:8888/build/app.js';
let scriptHtml = `
<script>
(function() {
window._appState = ${JSON.stringify(appState)};
var app = document.createElement('script'); app.type = 'text/javascript'; app.async = true;
var src = '${appScriptSrc}';
// IE<11 and Safari need Intl polyfill.
if (!window.Intl) src = src.replace('.js', 'intl.js');
app.src = src;
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(app, s);
})();
</script>`;
if (config.isProduction && config.googleAnalyticsId !== 'UA-XXXXXXX-X')
scriptHtml += `
<script>
(function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
e=o.createElement(i);r=o.getElementsByTagName(i)[0];
e.src='//www.google-analytics.com/analytics.js';
r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
ga('create','${config.googleAnalyticsId}');ga('send','pageview');
</script>`;
const title = DocumentTitle.rewind();
return '<!DOCTYPE html>' + React.renderToStaticMarkup(
<Html
bodyHtml={appHtml + scriptHtml}
isProduction={config.isProduction}
title={title}
version={config.version}
/>
);
}
|
module.exports = {
pages: {
index: {
entry:'src/main.js',
title: 'Home Brocker'
}
},
devServer: {
port: 8081
}
} |
from typing import Type
import pandas as pd
from .exceptions import BadConfigError, ColumnValidationError
from .field_checkers import (
BaseFieldChecker, MatchRegexFieldChecker, TitleCaseFieldChecker, UniqueFieldChecker, NoNAFieldChecker, OptionsFieldChecker,
IntegerFieldChecker, FloatFieldChecker, RangeFieldChecker
)
checker_dict = {
'unique': UniqueFieldChecker,
'no_na': NoNAFieldChecker,
'options': OptionsFieldChecker,
'integer': IntegerFieldChecker,
'float': FloatFieldChecker,
'range': RangeFieldChecker,
'title_case': TitleCaseFieldChecker,
'match_regex': MatchRegexFieldChecker
}
class ColumnSchema(object):
"""Describes a column and validates it
Attributes:
failed_check (str):
available if valid() is False, name of the attribute
that this column failed
sr (pd.Series):
available if valid() is False, the offending values
as a series
"""
_desc: str or None
_name: str
_checkers: dict[str, Type[BaseFieldChecker]]
failed_check: str
sr: pd.Series
def __init__(self, name: str, description: str or None = None, **kwargs) -> None:
"""Creates a new instance of FieldSchema
Args:
name (str):
name of this column
description (str):
description of this column
unique (bool):
whether this column can only contain unique values
no_na (bool):
whether this column can only contain non-NA values
options (list of str):
if given then this column can only contain values
within this list
integer (bool):
whether this column can only contain integer values
float (bool):
whether this column can only contain float (and
integer) values
range (list of 2 numbers):
ensure values in this column must be numeric and
must be between the 2 specified values
Returns:
no value
"""
self._name = name
self._desc = None if description is None else description.strip()
self._checkers = dict()
for k, v in kwargs.items():
if k not in checker_dict:
raise BadConfigError([], 'unknown option %s' % k)
try:
if v == True:
self._checkers[k] = checker_dict[k]()
elif type(v) is list:
self._checkers[k] = checker_dict[k](*v)
elif type(v) is str:
self._checkers[k] = checker_dict[k](v)
else:
raise BadConfigError([k], 'invalid option')
except BadConfigError as e:
raise BadConfigError([k]+e.path, e.msg)
def validate(self, sr: pd.Series) -> None:
"""Checks whether this column's values are all valid
Args:
sr (pd.Series):
the series to check
Raises:
FieldValidationError: column is not valid
Returns:
no value
"""
for name, checker in self._checkers.items():
res = checker.check(sr)
if res is not None:
raise ColumnValidationError(self._name, name, res)
return True
def to_markdown(self) -> str:
"""Render this field schema as markdown."""
return "\n".join(filter(None, [
"- **%s**:" % self._name,
None if self._desc is None else " - Description: %s\n" % self._desc,
None if len(self._checkers) == 0 else "\n".join(
[" - Attributes:"]+[
" "+checker.to_markdown().replace("\n", "\n ")
for checker in self._checkers.values()
]+[""]
)
]))
|
//
// ViewAdapterTypeCell5.h
// DWBaseAdapter
//
// Created by 丁巍 on 2019/3/28.
// Copyright © 2019 丁巍. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "DWBaseCellProtocol.h"
NS_ASSUME_NONNULL_BEGIN
@interface ViewAdapterTypeCell5 : UITableViewCell<DWBaseCellProtocol>
@end
NS_ASSUME_NONNULL_END
|
/**
\page subp_signals Signals
\section sec_sigintro Signals
Entities can output different types of signals. To guarante real-time
perforamces, signals are implemented using C++ and mecanism which have a low
time foot-print. All signals are templated by a Time tick type parameter (which
is used in the caching of signals) - usually \c int. Signals are also templated
after the type of data they accept or provide. For example: (example) For a more
detailed programmer-oriented description of signals, please see \ref signals
*/
|
// THIS FILE IS AUTO GENERATED
import { GenIcon } from '../lib';
export function SiMicrostrategy (props) {
return GenIcon({"tag":"svg","attr":{"role":"img","viewBox":"0 0 24 24"},"child":[{"tag":"title","attr":{},"child":[]},{"tag":"path","attr":{"d":"M9.103 2.596h5.811v18.808h-5.81zm-9.072 0h5.81v18.808H.032zm18.127 0v18.806h5.811V8.339z"}}]})(props);
};
|
import sys, re, glob, cctk, argparse, copy
import numpy as np
import pandas as pd
import multiprocessing as mp
from multiprocessing import freeze_support
from tabulate import tabulate
from tqdm import tqdm
# usage: python parse_conformations.py -c eneryg_cutoff prefix_of_new_files path/to/output/*.out
def read(file):
if re.match("slurm", file):
return
try:
output_file = cctk.GaussianFile.read_file(file)
if isinstance(output_file, list):
if len(output_file) > 0:
output_file = output_file[-1]
else:
return
return output_file
except Exception as e:
print(f"Error reading {file}\n{e}")
return
def main():
e = cctk.ConformationalEnsemble()
parser = argparse.ArgumentParser(prog="parse_conformations.py")
parser.add_argument("--cutoff", "-c", type=float, default=15)
parser.add_argument("--rmsd_cutoff", "-C", type=float, default=0.5)
parser.add_argument("prefix", type=str)
parser.add_argument("files", nargs='+')
args = vars(parser.parse_args(sys.argv[1:]))
print("\n\033[3mreading files:\033[0m")
pool = mp.Pool(processes=16)
for output_file in tqdm(pool.imap(read, args['files']), total=len(args['files'])):
molecule = output_file.get_molecule()
# there has got to be a better way to do this
e.add_molecule(*list(output_file.ensemble.items())[-1])
e[molecule, "iters"] = len(output_file.ensemble)
e[molecule, "success"] = output_file.successful_terminations
e[molecule, "imaginary"] = output_file.imaginaries()
if len(e) == 0:
print("no jobs to analyze!")
exit()
print(f"{len(e)} files read.")
e, rmsds = e.eliminate_redundant(RMSD_cutoff=args['rmsd_cutoff'], return_RMSD=True)
print(f"{len(e)} distinct conformations identified (RMSD cutoff of {args['rmsd_cutoff']:.2f}).")
print("\n\033[3manalysis:\033[0m")
property_names = ["filename", "new_filename", "rmsd", "iters", "energy", "success", "imaginary"]
values = e[:, property_names]
if not isinstance(values[0], list):
values = [values]
df = pd.DataFrame(values, columns=property_names).fillna(0)
df["rmsd"] = rmsds
df["new_filename"] = [f"{args['prefix']}_c{i:03}.gjf" for i in range(len(df))]
df["rel_energy"] = (df.energy - df.energy.min()) * 627.509469
df.sort_values("rel_energy", inplace=True)
normal_col_names = copy.deepcopy(df.columns)
df.columns = [f"\033[1m{c}\033[0m" for c in df.columns]
print(tabulate(df, headers="keys", tablefmt="presto", floatfmt=".5f"))
df.columns = normal_col_names
template_file = read(args['files'][0])
print("\n\033[3moutput:\033[0m")
for m, n, e in zip(e.molecule_list(), df["new_filename"], df["rel_energy"]):
if e <= args["cutoff"]:
template_file.write_file(n, molecule=m)
print(f"Wrote {n}")
else:
print(f"Skipping {n} and all subsequent rows: relative energy of {e:.2f} exceeds cutoff of {args['cutoff']:.2f}")
break
if __name__ == '__main__':
freeze_support()
main()
|
# from django import forms
|
import torch.utils.checkpoint as cp
from mmcv.cnn import ConvModule
from mmcv.runner import BaseModule
from .se_layer import SELayer
class InvertedResidual(BaseModule):
"""Inverted Residual Block.
Args:
in_channels (int): The input channels of this Module.
out_channels (int): The output channels of this Module.
mid_channels (int): The input channels of the depthwise convolution.
kernel_size (int): The kernal size of the depthwise convolution.
Default: 3.
stride (int): The stride of the depthwise convolution. Default: 1.
se_cfg (dict): Config dict for se layer. Defaul: None, which means no
se layer.
with_expand_conv (bool): Use expand conv or not. If set False,
mid_channels must be the same with in_channels.
Default: True.
conv_cfg (dict): Config dict for convolution layer. Default: None,
which means using conv2d.
norm_cfg (dict): Config dict for normalization layer.
Default: dict(type='BN').
act_cfg (dict): Config dict for activation layer.
Default: dict(type='ReLU').
with_cp (bool): Use checkpoint or not. Using checkpoint will save some
memory while slowing down the training speed. Default: False.
init_cfg (dict or list[dict], optional): Initialization config dict.
Default: None
Returns:
Tensor: The output tensor.
"""
def __init__(self,
in_channels,
out_channels,
mid_channels,
kernel_size=3,
stride=1,
se_cfg=None,
with_expand_conv=True,
conv_cfg=None,
norm_cfg=dict(type='BN'),
act_cfg=dict(type='ReLU'),
with_cp=False,
init_cfg=None):
super(InvertedResidual, self).__init__(init_cfg)
self.with_res_shortcut = (stride == 1 and in_channels == out_channels)
assert stride in [1, 2], f'stride must in [1, 2]. ' \
f'But received {stride}.'
self.with_cp = with_cp
self.with_se = se_cfg is not None
self.with_expand_conv = with_expand_conv
if self.with_se:
assert isinstance(se_cfg, dict)
if not self.with_expand_conv:
assert mid_channels == in_channels
if self.with_expand_conv:
self.expand_conv = ConvModule(
in_channels=in_channels,
out_channels=mid_channels,
kernel_size=1,
stride=1,
padding=0,
conv_cfg=conv_cfg,
norm_cfg=norm_cfg,
act_cfg=act_cfg)
self.depthwise_conv = ConvModule(
in_channels=mid_channels,
out_channels=mid_channels,
kernel_size=kernel_size,
stride=stride,
padding=kernel_size // 2,
groups=mid_channels,
conv_cfg=conv_cfg,
norm_cfg=norm_cfg,
act_cfg=act_cfg)
if self.with_se:
self.se = SELayer(**se_cfg)
self.linear_conv = ConvModule(
in_channels=mid_channels,
out_channels=out_channels,
kernel_size=1,
stride=1,
padding=0,
conv_cfg=conv_cfg,
norm_cfg=norm_cfg,
act_cfg=None)
def forward(self, x):
def _inner_forward(x):
out = x
if self.with_expand_conv:
out = self.expand_conv(out)
out = self.depthwise_conv(out)
if self.with_se:
out = self.se(out)
out = self.linear_conv(out)
if self.with_res_shortcut:
return x + out
else:
return out
if self.with_cp and x.requires_grad:
out = cp.checkpoint(_inner_forward, x)
else:
out = _inner_forward(x)
return out
|
###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2020, John McNamara, [email protected]
#
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename('chart_bar10.xlsx')
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({'type': 'bar', 'subtype': 'percent_stacked'})
chart.axis_ids = [40274560, 40295040]
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
]
worksheet.write_column('A1', data[0])
worksheet.write_column('B1', data[1])
worksheet.write_column('C1', data[2])
chart.add_series({'values': '=Sheet1!$A$1:$A$5'})
chart.add_series({'values': '=Sheet1!$B$1:$B$5'})
chart.add_series({'values': '=Sheet1!$C$1:$C$5'})
worksheet.insert_chart('E9', chart)
workbook.close()
self.assertExcelEqual()
|
(function(GoNorth) {
"use strict";
(function(Aika) {
(function(Shared) {
/// Width for nodes which have finish nodes as outports
Shared.finishNodeOutportNodeWidth = 250;
/// Minimum Height for nodes which have finish nodes as outports
Shared.finishNodeOutportNodeMinHeight = 150;
/// Count of outports after which the node begins to grow
var finishNodeOutportGrowStartCount = 3;
/// Amount of pixel by which a node grows for each outports bigger than the grow start count
var finishNodeOutportGrowHeight = 30;
/**
* Loads the detail view data
*
* @param {object} chapterNode Chapter Node to fill
* @param {string} detailViewId Id of the detail view
* @returns {jQuery.Deferred} Deferred for the loading process
*/
function loadDetailViewData(chapterNode, detailViewId) {
var def = new jQuery.Deferred();
// Load finish nodes
chapterNode.showLoading();
chapterNode.hideError();
jQuery.ajax({
url: "/api/AikaApi/GetChapterDetail?id=" + detailViewId,
type: "GET"
}).done(function(data) {
chapterNode.hideLoading();
Shared.addFinishNodesAsOutports(chapterNode, data.finish);
def.resolve(data);
}).fail(function(xhr) {
chapterNode.hideLoading();
chapterNode.showError();
def.reject();
});
return def.promise();
}
/**
* Adds a finish nodes as outports for a node
* @param {object} node Target node to which the outports should be added
* @param {object[]} finishNodes Finish Nodes
*/
Shared.addFinishNodesAsOutports = function(node, finishNodes)
{
if(!finishNodes)
{
finishNodes = [];
}
var links = {};
var allLinks = node.model.graph.getLinks();
for(var curLink = 0; curLink < allLinks.length; ++curLink)
{
var link = allLinks[curLink];
if(link.get("source") && link.get("source").id == node.model.id)
{
links[link.get("source").port] = link;
}
}
var outPorts = [];
var portColors = {};
for(var curFinish = 0; curFinish < finishNodes.length; ++curFinish)
{
var portName = "finish" + finishNodes[curFinish].id;
outPorts.push(portName);
portColors[portName] = finishNodes[curFinish].color;
var colorStyle = "fill: " + finishNodes[curFinish].color;
node.model.attr(".outPorts>.port" + curFinish + " circle", { "title": finishNodes[curFinish].name, "style": colorStyle });
node.model.attr(".outPorts>.port" + curFinish + " .port-label", { "title": finishNodes[curFinish].name, "class": "gn-aikaChapterFinishPort", "style": colorStyle, "dx": 13 });
if(links[portName])
{
links[portName].attr(".connection", { style: "stroke: " + finishNodes[curFinish].color });
links[portName].attr(".marker-target", { style: colorStyle });
delete links[portName];
}
}
node.model.set("outPorts", outPorts);
var targetHeight = Shared.finishNodeOutportNodeMinHeight;
if(outPorts.length > finishNodeOutportGrowStartCount)
{
targetHeight = Shared.finishNodeOutportNodeMinHeight + (outPorts.length - finishNodeOutportGrowStartCount) * finishNodeOutportGrowHeight;
}
node.model.set("size", { width: Shared.finishNodeOutportNodeWidth, height: targetHeight });
jQuery(".gn-aikaChapterFinishPort").each(function() {
jQuery(this).find("tspan").text(jQuery(this).attr("title"));
});
// Remove deleted port links
for(var curPort in links)
{
node.model.graph.removeCells([ links[curPort] ]);
}
// Handel add of new links
node.model.graph.on('add', function(cell) {
if(!cell.isLink() || !cell.get("source"))
{
return;
}
var source = cell.get("source");
if(source.id != node.model.id)
{
return;
}
if(portColors[source.port])
{
cell.attr(".connection", { style: "stroke: " + portColors[source.port] });
cell.attr(".marker-target", { style: "fill: " + portColors[source.port] });
}
});
}
/**
* Initializes the detail view connection
*
* @param {object} chapterNode Chapter Node to fill
* @param {string} detailViewId Id of the detail view
* @returns {jQuery.Deferred} Deferred for the loading process
*/
Shared.initDetailView = function (chapterNode, detailViewId) {
if(chapterNode.$box.find(".gn-aikaChapterDetailButton").length > 0)
{
return;
}
chapterNode.$box.append("<button class='gn-aikaChapterDetailButton'>" + Aika.Localization.Chapter.OpenDetailView + "</button>");
chapterNode.$box.find(".gn-aikaChapterDetailButton").click(function() {
var detailWindow = window.open("/Aika/Detail#id=" + detailViewId);
detailWindow.refreshChapterNode = function() {
loadDetailViewData(chapterNode, detailViewId);
};
});
return loadDetailViewData(chapterNode, detailViewId);
};
/**
* Checks if a chapter or chapter detail node can be deleted
*
* @param {string} detailNodeId Detail Node id
* @returns {jQuery.Deferred} Deferred for the validation process
*/
Shared.validateChapterDetailDelete = function(detailNodeId) {
if(!detailNodeId)
{
return null;
}
var def = new jQuery.Deferred();
jQuery.ajax({
url: "/api/AikaApi/ValidateChapterDetailDelete?id=" + detailNodeId,
type: "GET"
}).done(function(data) {
if(data.canBeDeleted)
{
def.resolve();
}
else
{
def.reject(data.errorMessage);
}
}).fail(function(xhr) {
def.reject("");
});
return def.promise();
};
}(Aika.Shared = Aika.Shared || {}));
}(GoNorth.Aika = GoNorth.Aika || {}));
}(window.GoNorth = window.GoNorth || {})); |
"""
Code source: https://github.com/pytorch/vision
"""
from __future__ import absolute_import
from __future__ import division
__all__ = [
'squeezenet1_0',
'squeezenet1_1',
'squeezenet1_0_fc512'
]
import torch
import torch.nn as nn
from torch.utils import model_zoo
import torch.utils.model_zoo as model_zoo
model_urls = {
'squeezenet1_0': 'https://download.pytorch.org/models/squeezenet1_0-a815701f.pth',
'squeezenet1_1': 'https://download.pytorch.org/models/squeezenet1_1-f364aa15.pth',
}
class Fire(nn.Module):
def __init__(self, inplanes, squeeze_planes,
expand1x1_planes, expand3x3_planes):
super(Fire, self).__init__()
self.inplanes = inplanes
self.squeeze = nn.Conv2d(inplanes, squeeze_planes, kernel_size=1)
self.squeeze_activation = nn.ReLU(inplace=True)
self.expand1x1 = nn.Conv2d(squeeze_planes, expand1x1_planes,
kernel_size=1)
self.expand1x1_activation = nn.ReLU(inplace=True)
self.expand3x3 = nn.Conv2d(squeeze_planes, expand3x3_planes,
kernel_size=3, padding=1)
self.expand3x3_activation = nn.ReLU(inplace=True)
def forward(self, x):
x = self.squeeze_activation(self.squeeze(x))
return torch.cat([
self.expand1x1_activation(self.expand1x1(x)),
self.expand3x3_activation(self.expand3x3(x))
], 1)
class SqueezeNet(nn.Module):
"""SqueezeNet.
Reference:
Iandola et al. SqueezeNet: AlexNet-level accuracy with 50x fewer parameters
and< 0.5 MB model size. arXiv:1602.07360.
Public keys:
- ``squeezenet1_0``: SqueezeNet (version=1.0).
- ``squeezenet1_1``: SqueezeNet (version=1.1).
- ``squeezenet1_0_fc512``: SqueezeNet (version=1.0) + FC.
"""
def __init__(self, num_classes, loss, version=1.0, fc_dims=None, dropout_p=None, **kwargs):
super(SqueezeNet, self).__init__()
self.loss = loss
self.feature_dim = 512
if version not in [1.0, 1.1]:
raise ValueError('Unsupported SqueezeNet version {version}:'
'1.0 or 1.1 expected'.format(version=version))
if version == 1.0:
self.features = nn.Sequential(
nn.Conv2d(3, 96, kernel_size=7, stride=2),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True),
Fire(96, 16, 64, 64),
Fire(128, 16, 64, 64),
Fire(128, 32, 128, 128),
nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True),
Fire(256, 32, 128, 128),
Fire(256, 48, 192, 192),
Fire(384, 48, 192, 192),
Fire(384, 64, 256, 256),
nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True),
Fire(512, 64, 256, 256),
)
else:
self.features = nn.Sequential(
nn.Conv2d(3, 64, kernel_size=3, stride=2),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True),
Fire(64, 16, 64, 64),
Fire(128, 16, 64, 64),
nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True),
Fire(128, 32, 128, 128),
Fire(256, 32, 128, 128),
nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True),
Fire(256, 48, 192, 192),
Fire(384, 48, 192, 192),
Fire(384, 64, 256, 256),
Fire(512, 64, 256, 256),
)
self.global_avgpool = nn.AdaptiveAvgPool2d(1)
self.fc = self._construct_fc_layer(fc_dims, 512, dropout_p)
self.classifier = nn.Linear(self.feature_dim, num_classes)
self._init_params()
def _construct_fc_layer(self, fc_dims, input_dim, dropout_p=None):
"""Constructs fully connected layer
Args:
fc_dims (list or tuple): dimensions of fc layers, if None, no fc layers are constructed
input_dim (int): input dimension
dropout_p (float): dropout probability, if None, dropout is unused
"""
if fc_dims is None:
self.feature_dim = input_dim
return None
assert isinstance(fc_dims, (list, tuple)), 'fc_dims must be either list or tuple, but got {}'.format(type(fc_dims))
layers = []
for dim in fc_dims:
layers.append(nn.Linear(input_dim, dim))
layers.append(nn.BatchNorm1d(dim))
layers.append(nn.ReLU(inplace=True))
if dropout_p is not None:
layers.append(nn.Dropout(p=dropout_p))
input_dim = dim
self.feature_dim = fc_dims[-1]
return nn.Sequential(*layers)
def _init_params(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
if m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.BatchNorm1d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.Linear):
nn.init.normal_(m.weight, 0, 0.01)
if m.bias is not None:
nn.init.constant_(m.bias, 0)
def forward(self, x):
f = self.features(x)
v = self.global_avgpool(f)
v = v.view(v.size(0), -1)
if self.fc is not None:
v = self.fc(v)
if not self.training:
return v
y = self.classifier(v)
if self.loss == 'softmax':
return y
elif self.loss == 'triplet':
return y, v
else:
raise KeyError('Unsupported loss: {}'.format(self.loss))
def init_pretrained_weights(model, model_url):
"""Initializes model with pretrained weights.
Layers that don't match with pretrained layers in name or size are kept unchanged.
"""
pretrain_dict = model_zoo.load_url(model_url, map_location=None)
model_dict = model.state_dict()
pretrain_dict = {k: v for k, v in pretrain_dict.items() if k in model_dict and model_dict[k].size() == v.size()}
model_dict.update(pretrain_dict)
model.load_state_dict(model_dict)
def squeezenet1_0(num_classes, loss='softmax', pretrained=True, **kwargs):
model = SqueezeNet(
num_classes,
loss,
version=1.0,
fc_dims=None,
dropout_p=None,
**kwargs
)
if pretrained:
init_pretrained_weights(model, model_urls['squeezenet1_0'])
return model
def squeezenet1_0_fc512(num_classes, loss='softmax', pretrained=True, **kwargs):
model = SqueezeNet(
num_classes,
loss,
version=1.0,
fc_dims=[512],
dropout_p=None,
**kwargs
)
if pretrained:
init_pretrained_weights(model, model_urls['squeezenet1_0'])
return model
def squeezenet1_1(num_classes, loss='softmax', pretrained=True, **kwargs):
model = SqueezeNet(
num_classes,
loss,
version=1.1,
fc_dims=None,
dropout_p=None,
**kwargs
)
if pretrained:
init_pretrained_weights(model, model_urls['squeezenet1_1'])
return model |
webpackJsonp([99],{
/***/ 1795:
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AddonModAssignIndexPageModule", function() { return AddonModAssignIndexPageModule; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_ionic_angular__ = __webpack_require__(4);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__ngx_translate_core__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__directives_directives_module__ = __webpack_require__(14);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__components_components_module__ = __webpack_require__(925);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__index__ = __webpack_require__(1916);
// (C) Copyright 2015 Martin Dougiamas
//
// 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.
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var AddonModAssignIndexPageModule = /** @class */ (function () {
function AddonModAssignIndexPageModule() {
}
AddonModAssignIndexPageModule = __decorate([
Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["I" /* NgModule */])({
declarations: [
__WEBPACK_IMPORTED_MODULE_5__index__["a" /* AddonModAssignIndexPage */],
],
imports: [
__WEBPACK_IMPORTED_MODULE_3__directives_directives_module__["a" /* CoreDirectivesModule */],
__WEBPACK_IMPORTED_MODULE_4__components_components_module__["a" /* AddonModAssignComponentsModule */],
__WEBPACK_IMPORTED_MODULE_1_ionic_angular__["l" /* IonicPageModule */].forChild(__WEBPACK_IMPORTED_MODULE_5__index__["a" /* AddonModAssignIndexPage */]),
__WEBPACK_IMPORTED_MODULE_2__ngx_translate_core__["b" /* TranslateModule */].forChild()
],
})
], AddonModAssignIndexPageModule);
return AddonModAssignIndexPageModule;
}());
//# sourceMappingURL=index.module.js.map
/***/ }),
/***/ 1916:
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return AddonModAssignIndexPage; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_ionic_angular__ = __webpack_require__(4);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__components_index_index__ = __webpack_require__(394);
// (C) Copyright 2015 Martin Dougiamas
//
// 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.
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
/**
* Page that displays an assign.
*/
var AddonModAssignIndexPage = /** @class */ (function () {
function AddonModAssignIndexPage(navParams) {
this.module = navParams.get('module') || {};
this.courseId = navParams.get('courseId');
this.title = this.module.name;
}
/**
* Update some data based on the assign instance.
*
* @param {any} assign Assign instance.
*/
AddonModAssignIndexPage.prototype.updateData = function (assign) {
this.title = assign.name || this.title;
};
__decorate([
Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["_9" /* ViewChild */])(__WEBPACK_IMPORTED_MODULE_2__components_index_index__["a" /* AddonModAssignIndexComponent */]),
__metadata("design:type", __WEBPACK_IMPORTED_MODULE_2__components_index_index__["a" /* AddonModAssignIndexComponent */])
], AddonModAssignIndexPage.prototype, "assignComponent", void 0);
AddonModAssignIndexPage = __decorate([
Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["m" /* Component */])({
selector: 'page-addon-mod-assign-index',template:/*ion-inline-start:"D:\xampp\htdocs\mobile\new\defence_works\src\addon\mod\assign\pages\index\index.html"*/'<ion-header>\n\n <ion-navbar core-back-button>\n\n <ion-title><core-format-text [text]="title"></core-format-text></ion-title>\n\n\n\n <ion-buttons end>\n\n <!-- The buttons defined by the component will be added in here. -->\n\n </ion-buttons>\n\n </ion-navbar>\n\n</ion-header>\n\n<ion-content>\n\n <ion-refresher [enabled]="assignComponent.loaded" (ionRefresh)="assignComponent.doRefresh($event)">\n\n <ion-refresher-content pullingText="{{ \'core.pulltorefresh\' | translate }}"></ion-refresher-content>\n\n </ion-refresher>\n\n\n\n <addon-mod-assign-index [module]="module" [courseId]="courseId" (dataRetrieved)="updateData($event)"></addon-mod-assign-index>\n\n</ion-content>\n\n'/*ion-inline-end:"D:\xampp\htdocs\mobile\new\defence_works\src\addon\mod\assign\pages\index\index.html"*/,
}),
__metadata("design:paramtypes", [__WEBPACK_IMPORTED_MODULE_1_ionic_angular__["s" /* NavParams */]])
], AddonModAssignIndexPage);
return AddonModAssignIndexPage;
}());
//# sourceMappingURL=index.js.map
/***/ })
});
//# sourceMappingURL=99.js.map |
'use strict';
var proxyquire = require('proxyquire').noPreserveCache();
var retailersCtrlStub = {
index: 'retailersCtrl.index',
show: 'retailersCtrl.show',
create: 'retailersCtrl.create',
update: 'retailersCtrl.update',
destroy: 'retailersCtrl.destroy'
};
var routerStub = {
get: sinon.spy(),
put: sinon.spy(),
patch: sinon.spy(),
post: sinon.spy(),
delete: sinon.spy()
};
// require the index with our stubbed out modules
var retailersIndex = proxyquire('./index.js', {
'express': {
Router: function() {
return routerStub;
}
},
'./retailers.controller': retailersCtrlStub
});
describe('Retailers API Router:', function() {
it('should return an express router instance', function() {
retailersIndex.should.equal(routerStub);
});
describe('GET /api/retailerss', function() {
it('should route to retailers.controller.index', function() {
routerStub.get
.withArgs('/', 'retailersCtrl.index')
.should.have.been.calledOnce;
});
});
describe('GET /api/retailerss/:id', function() {
it('should route to retailers.controller.show', function() {
routerStub.get
.withArgs('/:id', 'retailersCtrl.show')
.should.have.been.calledOnce;
});
});
describe('POST /api/retailerss', function() {
it('should route to retailers.controller.create', function() {
routerStub.post
.withArgs('/', 'retailersCtrl.create')
.should.have.been.calledOnce;
});
});
describe('PUT /api/retailerss/:id', function() {
it('should route to retailers.controller.update', function() {
routerStub.put
.withArgs('/:id', 'retailersCtrl.update')
.should.have.been.calledOnce;
});
});
describe('PATCH /api/retailerss/:id', function() {
it('should route to retailers.controller.update', function() {
routerStub.patch
.withArgs('/:id', 'retailersCtrl.update')
.should.have.been.calledOnce;
});
});
describe('DELETE /api/retailerss/:id', function() {
it('should route to retailers.controller.destroy', function() {
routerStub.delete
.withArgs('/:id', 'retailersCtrl.destroy')
.should.have.been.calledOnce;
});
});
});
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import math
DESTRUIDO = 'Destruido'
ATIVO = 'Ativo'
GRAVIDADE = 10 # m/s^2
class Ator:
"""
Classe que representa um ator. Ele representa um ponto cartesiano na tela.
"""
_caracter_ativo = 'A'
_caracter_destruido = ' '
def __init__(self, x=0, y=0):
"""
Método de inicialização da classe. Deve inicializar os parâmetros x, y, caracter e status
:param x: Posição horizontal inicial do ator
:param y: Posição vertical inicial do ator
"""
self.y = y
self.x = x
self.status = ATIVO
def caracter(self):
return self._caracter_ativo if self.status == ATIVO else self._caracter_destruido
def calcular_posicao(self, tempo):
"""
Método que calcula a posição do ator em determinado tempo.
Deve-se imaginar que o tempo começa em 0 e avança de 0,01 segundos
:param tempo: o tempo do jogo
:return: posição x, y do ator
"""
return self.x, self.y
def colidir(self, outro_ator, intervalo=1):
"""
Método que executa lógica de colisão entre dois atores.
Só deve haver colisão se os dois atores tiverem seus status ativos.
Para colisão, é considerado um quadrado, com lado igual ao parâmetro intervalo, em volta do ponto onde se
encontra o ator. Se os atores estiverem dentro desse mesmo quadrado, seus status devem ser alterados para
destruido, seus caracteres para destruido também.
:param outro_ator: Ator a ser considerado na colisão
:param intervalo: Intervalo a ser considerado
:return:
"""
if self.status == ATIVO and outro_ator.status == ATIVO:
delta_x = abs(self.x - outro_ator.x)
delta_y = abs(self.y - outro_ator.y)
if delta_x <= intervalo and delta_y <= intervalo:
self.status = outro_ator.status = DESTRUIDO
class Obstaculo(Ator):
_caracter_ativo = 'O'
class Porco(Ator):
_caracter_ativo = '@'
_caracter_destruido = '+'
class DuploLancamentoExcecao(Exception):
pass
class Passaro(Ator):
velocidade_escalar = 10
def __init__(self, x=0, y=0):
"""
Método de inicialização de pássaro.
Deve chamar a inicialização de ator. Além disso, deve armazenar a posição inicial e incializar o tempo de
lançamento e angulo de lançamento
:param x:
:param y:
"""
super().__init__(x, y)
self._x_inicial = x
self._y_inicial = y
self._tempo_de_lancamento = None
self._angulo_de_lancamento = None # radianos
def foi_lancado(self):
"""
Método que retorna verdaeira se o pássaro já foi lançado e falso caso contrário
:return: booleano
"""
return not self._tempo_de_lancamento is None
def colidir_com_chao(self):
"""
Método que executa lógica de colisão com o chão. Toda vez que y for menor ou igual a 0,
o status dos Passaro deve ser alterado para destruido, bem como o seu caracter
"""
if self.y <= 0:
self.status = DESTRUIDO
def _calcular_posicao_horizontal(self, delta_t):
x_atual = self._x_inicial
x_atual += self.velocidade_escalar * delta_t * math.cos(self._angulo_de_lancamento)
self.x = x_atual
def _calcular_posicao_vertical(self, delta_t):
y_atual = self._y_inicial
y_atual += self.velocidade_escalar * delta_t * math.sin(self._angulo_de_lancamento)
y_atual -= (GRAVIDADE * delta_t**2) / 2
self.y = y_atual
def calcular_posicao(self, tempo):
"""
Método que cálcula a posição do passaro de acordo com o tempo.
Antes do lançamento o pássaro deve retornar o valor de sua posição inicial
Depois do lançamento o pássaro deve calcular de acordo com sua posição inicial, velocidade escalar,
ângulo de lancamento, gravidade (constante GRAVIDADE) e o tempo do jogo.
Após a colisão, ou seja, ter seus status destruido, o pássaro deve apenas retornar a última posição calculada.
:param tempo: tempo de jogo a ser calculada a posição
:return: posição x, y
"""
if self.foi_lancado() and self.status == ATIVO:
delta_t = tempo - self._tempo_de_lancamento
self._calcular_posicao_vertical(delta_t)
self._calcular_posicao_horizontal(delta_t)
return super(Passaro, self).calcular_posicao(tempo)
def lancar(self, angulo, tempo_de_lancamento):
"""
Lógica que lança o pássaro. Deve armazenar o ângulo e o tempo de lançamento para posteriores cálculo.
O ângulo é passado em graus e deve ser transformado em radianos
:param angulo:
:param tempo_de_lancamento:
:return:
"""
angulo_em_radianos = math.radians(angulo)
self._tempo_de_lancamento = tempo_de_lancamento
self._angulo_de_lancamento = angulo_em_radianos
class PassaroAmarelo(Passaro):
_caracter_ativo = 'A'
_caracter_destruido = 'a'
velocidade_escalar = 30
class PassaroVermelho(Passaro):
_caracter_ativo = 'V'
_caracter_destruido = 'v'
velocidade_escalar = 20
|
// @flow
/*
* Generates the following:
* - data/array_types.js, which consists of:
* - StructArrayLayout_* subclasses, one for each underlying memory layout we need
* - Named exports mapping each conceptual array type (e.g., CircleLayoutArray) to its corresponding StructArrayLayout class
* - Particular, named StructArray subclasses, when fancy struct accessors are needed (e.g. CollisionBoxArray)
*/
'use strict'; // eslint-disable-line strict
const fs = require('fs');
const ejs = require('ejs');
const util = require('../src/util/util');
const {createLayout, viewTypes} = require('../src/util/struct_array');
import type {ViewType, StructArrayLayout} from '../src/util/struct_array';
const structArrayLayoutJs = ejs.compile(fs.readFileSync('src/util/struct_array_layout.js.ejs', 'utf8'), {strict: true});
const structArrayJs = ejs.compile(fs.readFileSync('src/util/struct_array.js.ejs', 'utf8'), {strict: true});
const typeAbbreviations = {
'Int8': 'b',
'Uint8': 'ub',
'Int16': 'i',
'Uint16': 'ui',
'Int32': 'l',
'Uint32': 'ul',
'Float32': 'f'
};
const arraysWithStructAccessors = [];
const arrayTypeEntries = new Set();
const layoutCache = {};
function normalizeMembers(members, usedTypes) {
return members.map((member) => {
if (usedTypes && !usedTypes.has(member.type)) {
usedTypes.add(member.type);
}
return util.extend(member, {
size: sizeOf(member.type),
view: member.type.toLowerCase()
});
});
}
// - If necessary, write the StructArrayLayout_* class for the given layout
// - If `includeStructAccessors`, write the fancy subclass
// - Add an entry for `name` in the array type registry
function createStructArrayType(name: string, layout: StructArrayLayout, includeStructAccessors: boolean = false) {
const hasAnchorPoint = layout.members.some(m => m.name === 'anchorPointX');
// create the underlying StructArrayLayout class exists
const layoutClass = createStructArrayLayoutType(layout);
const arrayClass = `${camelize(name)}Array`;
if (includeStructAccessors) {
const usedTypes = new Set(['Uint8']);
const members = normalizeMembers(layout.members, usedTypes);
arraysWithStructAccessors.push({
arrayClass,
members,
size: layout.size,
usedTypes,
hasAnchorPoint,
layoutClass,
includeStructAccessors
});
} else {
arrayTypeEntries.add(`${layoutClass} as ${arrayClass}`);
}
}
function createStructArrayLayoutType({members, size, alignment}) {
const usedTypes = new Set(['Uint8']);
members = normalizeMembers(members, usedTypes);
// combine consecutive 'members' with same underlying type, summing their
// component counts
if (!alignment || alignment === 1) members = members.reduce((memo, member) => {
if (memo.length > 0 && memo[memo.length - 1].type === member.type) {
const last = memo[memo.length - 1];
return memo.slice(0, -1).concat(util.extend({}, last, {
components: last.components + member.components,
}));
}
return memo.concat(member);
}, []);
const key = `${members.map(m => `${m.components}${typeAbbreviations[m.type]}`).join('')}${size}`;
const className = `StructArrayLayout${key}`;
// Layout alignment to 4 bytes boundaries can be an issue on some set of graphics cards. Particularly AMD.
if (size % 4 !== 0) { console.warn(`Warning: The layout ${className} is not aligned to 4-bytes boundaries.`); }
if (!layoutCache[key]) {
layoutCache[key] = {
className,
members,
size,
usedTypes
};
}
return className;
}
function sizeOf(type: ViewType): number {
return viewTypes[type].BYTES_PER_ELEMENT;
}
function camelize (str) {
return str.replace(/(?:^|[-_])(.)/g, (_, x) => {
return /^[0-9]$/.test(x) ? _ : x.toUpperCase();
});
}
global.camelize = camelize;
const posAttributes = require('../src/data/pos_attributes').default;
const rasterBoundsAttributes = require('../src/data/raster_bounds_attributes').default;
createStructArrayType('pos', posAttributes);
createStructArrayType('raster_bounds', rasterBoundsAttributes);
const circleAttributes = require('../src/data/bucket/circle_attributes').default;
const fillAttributes = require('../src/data/bucket/fill_attributes').default;
const lineAttributes = require('../src/data/bucket/line_attributes').default;
const lineAttributesExt = require('../src/data/bucket/line_attributes_ext').default;
const patternAttributes = require('../src/data/bucket/pattern_attributes').default;
const skyboxAttributes = require('../src/render/skybox_attributes').default;
const {fillExtrusionAttributes, centroidAttributes} = require('../src/data/bucket/fill_extrusion_attributes');
// layout vertex arrays
const layoutAttributes = {
circle: circleAttributes,
fill: fillAttributes,
'fill-extrusion': fillExtrusionAttributes,
heatmap: circleAttributes,
line: lineAttributes,
lineExt: lineAttributesExt,
pattern: patternAttributes
};
for (const name in layoutAttributes) {
createStructArrayType(`${name.replace(/-/g, '_')}_layout`, layoutAttributes[name]);
}
// symbol layer specific arrays
const {
symbolLayoutAttributes,
dynamicLayoutAttributes,
placementOpacityAttributes,
collisionBox,
collisionBoxLayout,
collisionCircleLayout,
collisionVertexAttributes,
collisionVertexAttributesExt,
quadTriangle,
placement,
symbolInstance,
glyphOffset,
lineVertex
} = require('../src/data/bucket/symbol_attributes');
createStructArrayType(`symbol_layout`, symbolLayoutAttributes);
createStructArrayType(`symbol_dynamic_layout`, dynamicLayoutAttributes);
createStructArrayType(`symbol_opacity`, placementOpacityAttributes);
createStructArrayType('collision_box', collisionBox, true);
createStructArrayType(`collision_box_layout`, collisionBoxLayout);
createStructArrayType(`collision_circle_layout`, collisionCircleLayout);
createStructArrayType(`collision_vertex`, collisionVertexAttributes);
createStructArrayType(`collision_vertex_ext`, collisionVertexAttributesExt);
createStructArrayType(`quad_triangle`, quadTriangle);
createStructArrayType('placed_symbol', placement, true);
createStructArrayType('symbol_instance', symbolInstance, true);
createStructArrayType('glyph_offset', glyphOffset, true);
createStructArrayType('symbol_line_vertex', lineVertex, true);
// feature index array
createStructArrayType('feature_index', createLayout([
// the index of the feature in the original vectortile
{ type: 'Uint32', name: 'featureIndex' },
// the source layer the feature appears in
{ type: 'Uint16', name: 'sourceLayerIndex' },
// the bucket the feature appears in
{ type: 'Uint16', name: 'bucketIndex' }
]), true);
// triangle index array
createStructArrayType('triangle_index', createLayout([
{ type: 'Uint16', name: 'vertices', components: 3 }
]));
// line index array
createStructArrayType('line_index', createLayout([
{ type: 'Uint16', name: 'vertices', components: 2 }
]));
// line strip index array
createStructArrayType('line_strip_index', createLayout([
{ type: 'Uint16', name: 'vertices', components: 1 }
]));
// skybox vertex array
createStructArrayType(`skybox_vertex`, skyboxAttributes);
// paint vertex arrays
// used by SourceBinder for float properties
createStructArrayLayoutType(createLayout([{
name: 'dummy name (unused for StructArrayLayout)',
type: 'Float32',
components: 1
}], 4));
// used by SourceBinder for color properties and CompositeBinder for float properties
createStructArrayLayoutType(createLayout([{
name: 'dummy name (unused for StructArrayLayout)',
type: 'Float32',
components: 2
}], 4));
// used by CompositeBinder for color properties
createStructArrayLayoutType(createLayout([{
name: 'dummy name (unused for StructArrayLayout)',
type: 'Float32',
components: 4
}], 4));
// Fill extrusion specific array
createStructArrayType(`fill_extrusion_centroid`, centroidAttributes);
const layouts = Object.keys(layoutCache).map(k => layoutCache[k]);
fs.writeFileSync('src/data/array_types.js',
`// This file is generated. Edit build/generate-struct-arrays.js, then run \`yarn run codegen\`.
// @flow
import assert from 'assert';
import {Struct, StructArray} from '../util/struct_array';
import {register} from '../util/web_worker_transfer';
import Point from '@mapbox/point-geometry';
${layouts.map(structArrayLayoutJs).join('\n')}
${arraysWithStructAccessors.map(structArrayJs).join('\n')}
export {
${layouts.map(layout => layout.className).join(',\n ')},
${[...arrayTypeEntries].join(',\n ')}
};
`);
|
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TerminalWindow = void 0;
const os_1 = __importDefault(require("os"));
const command_1 = require("./command");
const child_process = __importStar(require("child_process"));
class TerminalWindow {
constructor(app = "Terminal") {
this.app = app;
this.tabs = [];
}
addTab(cmd, cwd = undefined, title = undefined) {
this.tabs.push({
cmd: cmd,
cwd: cwd,
title: title,
});
return this;
}
// open the terminal window
open() {
const osType = os_1.default.type();
if (osType === "Darwin") {
// MacOS
let first = true;
// only open the first tab in new window
for (const tab of this.tabs) {
const r = child_process.spawnSync("osascript", [
"-e", `tell application "${this.app}" to activate`,
"-e", `tell application "System Events" to tell process "${this.app}" to keystroke "${first ? "n" : "t"}" using {command down}`,
"-e", `tell application "${this.app}" to do script "${tab.cmd.toEscapedString()}" in selected tab of the front window`,
]);
if (r.error) {
throw r.error;
}
if (r.status !== 0) {
throw new Error(r.stderr.toString());
}
first = false;
}
}
else if (osType === "Linux") {
// Linux // TODO currently only support ubuntu
let first = true;
const gnomeCmd = new command_1.Command("gnome-terminal");
for (const tab of this.tabs) {
if (first) {
gnomeCmd.append("--window");
first = false;
}
else {
gnomeCmd.append("--tab");
}
if (tab.title) {
gnomeCmd.append(`--title="${tab.title}"`);
}
if (tab.cwd) {
gnomeCmd.append(`--working-directory="${tab.cwd}"`);
}
gnomeCmd.append(`--command="${tab.cmd.toString()}"`);
}
child_process.spawnSync(gnomeCmd.command, gnomeCmd.args);
}
else {
console.error(`Cannot open terminal in system: ${osType}`);
}
}
}
exports.TerminalWindow = TerminalWindow;
//# sourceMappingURL=terminal.js.map |
const assert = require('assert');
const isFacebookProfileUrl = require('../index').isFacebookProfileUrl;
describe('isFacebookProfileUrl', function () {
it('Should return true if facebook profile url includes https', function () {
assert.strictEqual(isFacebookProfileUrl('https://www.facebook.com/johnsmith'), true);
});
it("Should return true if facebook profile url doesn't include https or http", function () {
assert.strictEqual(isFacebookProfileUrl('www.facebook.com/johnsmith'), true);
});
it('Should return true if facebook profile url includes http', function () {
assert.strictEqual(isFacebookProfileUrl('http://www.facebook.com/johnsmith'), true);
});
it("Should return true if facebook profile url doesn't include www", function () {
assert.strictEqual(isFacebookProfileUrl('http://facebook.com/johnsmith'), true);
});
it("Should return true if facebook profile url doesn't include https, http, www", function () {
assert.strictEqual(isFacebookProfileUrl('facebook.com/johnsmith'), true);
});
it("Should return true if facebook profile url doesn't include slash at the end", function () {
assert.strictEqual(isFacebookProfileUrl('https://www.facebook.com/johnsmith'), true);
});
it("Should return true if facebook profile url includes slash at the end", function () {
assert.strictEqual(isFacebookProfileUrl('https://www.facebook.com/johnsmith/'), true);
});
it('Should return true if facebook profile includes period', function () {
assert.strictEqual(isFacebookProfileUrl('https://www.facebook.com/john.smith'), true);
});
it('Should return true if facebook profile includes numbers', function () {
assert.strictEqual(isFacebookProfileUrl('https://www.facebook.com/johnsmith0123456789'), true);
});
it("Should return false if facebook profile url doesn't include facebook.com", function () {
assert.strictEqual(isFacebookProfileUrl('https://www.google.com/johnsmith'), false);
});
it("Should return false if facebook profile name's length < 5", function () {
assert.strictEqual(isFacebookProfileUrl('https://www.facebook.com/john'), false);
});
it('Should return false if facebook profile includes spaces', function () {
assert.strictEqual(isFacebookProfileUrl('https://www.facebook.com/john smith'), false);
});
it('Should return false if facebook profile includes special characters except period', function () {
assert.strictEqual(isFacebookProfileUrl('https://www.facebook.com/johnsmith!@#$%^&&*()_+'), false);
});
});
|
from __future__ import annotations
from dataclasses import dataclass
import typing as T
import builtins as py
import operator as op
import collections
import functools
from functools import partial
_NoneType = type(None)
class PyTreeTypeRegistry:
def __init__(self):
self.registrations_ = {}
@dataclass
class Registration:
# The following values are populated for custom types.
# The Python type object, used to identify the type.
type: T.Any # pybind11::object type;
# A function with signature: object -> (iterable, aux_data)
to_iterable: T.Callable = None # pybind11::function to_iterable;
# A function with signature: (aux_data, iterable) -> object
from_iterable: T.Callable = None # pybind11::function from_iterable;
def __eq__(self, other: PyTreeTypeRegistry.Registration):
if self.type != other.type:
return False
return True
@classmethod
def singleton(cls) -> PyTreeTypeRegistry:
try:
return cls.inst
except AttributeError:
cls.inst = cls()
return cls.inst
@classmethod
def register(cls, type: T.Type, to_iterable: T.Callable, from_iterable: T.Callable):
self = cls.singleton()
if type in self.registrations_:
raise ValueError("Duplicate custom PyTreeDef type registration for %s." % repr(type))
registration = cls.Registration(type, to_iterable, from_iterable)
self.registrations_[type] = registration
@classmethod
def lookup(cls, type: T.Type) -> PyTreeTypeRegistry.Registration:
self = cls.singleton()
return self.registrations_.get(type)
class PyTreeDef:
def __init__(self, nodes = None):
self.traversal_ = nodes if nodes is not None else []
@classmethod
def flatten_into(cls, handle, leaves: T.List[T.Any], nodes: T.List[T.Any], leaf_predicate: T.Callable, start_num_nodes: py.int, start_num_leaves: py.int):
objtype = type(handle)
node_data = None
node_arity = -1
num_nodes, num_leaves = start_num_nodes + 1, start_num_leaves + 1
if handle is None:
num_leaves -= 1
elif objtype in [py.int, py.float, py.bool] \
or (leaf_predicate and leaf_predicate(handle)):
objtype = None
leaves.append(handle)
else:
reg = PyTreeTypeRegistry.lookup(objtype)
if reg is not None or is_namedtuple(handle, objtype):
blades, node_data = reg.to_iterable(handle) if reg else (handle, "namedtuple")
node_arity = 0
for x in blades:
node_arity += 1
num_nodes, num_leaves = cls.flatten_into(x, leaves, nodes, leaf_predicate, num_nodes, num_leaves)
num_leaves -= 1
else:
objtype = None
leaves.append(handle)
node = (node_arity, num_leaves - start_num_leaves, num_nodes - start_num_nodes, objtype, node_data)
nodes.append(node)
return num_nodes, num_leaves
def unflatten(self, leaves: T.Iterable):
leaves: T.List = list(leaves)
leaf_count = 0
for (node_arity, num_leaves, num_nodes, objtype, node_data) in self.traversal_:
if node_arity == -1:
if objtype is _NoneType:
leaves.insert(leaf_count, None)
leaf_count += 1
leaf_count += num_leaves
else:
span = leaves[leaf_count - node_arity:leaf_count]
reg = PyTreeTypeRegistry.lookup(objtype)
if reg is not None:
o = reg.from_iterable(node_data, span)
else:
o = objtype(*span)
del leaves[leaf_count - node_arity:leaf_count]
leaf_count -= node_arity
leaves.insert(leaf_count, o)
leaf_count += 1
return leaves[-1]
def compose(self, inner: PyTreeDef) -> PyTreeDef:
"""Composes two PyTreeDefs, replacing the leaves of this tree with copies of `inner`."""
out_nodes = []
for node in self.traversal_:
(node_arity, num_leaves, num_nodes, objtype, node_data) = node
if node_arity == -1 and objtype is not _NoneType:
out_nodes.extend(inner.traversal_)
else:
out_nodes.append(node)
_, root_num_leaves, root_num_nodes, _, _ = self.traversal_[-1]
_, inner_root_num_leaves, inner_root_num_nodes, _, _ = inner.traversal_[-1]
node_arity, num_leaves, num_nodes, objtype, node_data = out_nodes.pop()
num_nodes = (root_num_nodes - root_num_leaves) + (inner_root_num_nodes * root_num_leaves)
num_leaves *= inner_root_num_leaves
node = (node_arity, num_leaves, num_nodes, objtype, node_data)
out_nodes.append(node)
return PyTreeDef(py.tuple(out_nodes))
def walk(self, f_node: T.Optional[T.Callable], f_leaf: T.Optional[T.Callable], leaves: T.Iterable):
"""Maps a function over a PyTree structure, applying f_leaf to each leaf, and
f_node to each container node.
TODO(phawkins): use flattening everywhere instead and delete this method."""
agenda = []
it = iter(leaves)
for node in self.traversal_:
(node_arity, num_leaves, num_nodes, objtype, node_data) = node
if node_arity == -1 and objtype is not _NoneType:
ok, leaf = next_value(it)
if not ok:
raise ValueError("Too few leaves for PyTreeDef")
agenda.append(f_leaf(leaf) if f_leaf is not None else leaf)
else:
assert len(agenda) >= node_arity, "Too few elements for custom type."
tuple = []
if node_arity > 0:
tuple = agenda[-node_arity:]
del agenda[-node_arity:]
tuple = py.tuple(tuple)
agenda.append(f_node(tuple) if f_node is not None else tuple)
ok, _ = next_value(it)
if ok:
raise ValueError("Too many leaves for PyTreeDef")
assert len(agenda) == 1, "PyTreeDef traversal did not yield a singleton."
return agenda[-1]
def _from_iterable_tree_helper(self, tree: T.Any, it: T.Iterator):
"""Recursive helper used to implement from_iterable_tree()"""
ok, node = next_value(it)
if not ok:
raise ValueError("Tree structures did not match.")
(node_arity, num_leaves, num_nodes, objtype, node_data) = node
if node_arity == -1:
if objtype is _NoneType:
return None
return tree
iterable: T.Iterable = tree
ys = py.list(iterable)
if len(ys) != node_arity:
raise ValueError("Arity mismatch between trees")
for j in range(node_arity - 1, -1, -1):
ys[j] = self._from_iterable_tree_helper(ys[j], it)
reg = PyTreeTypeRegistry.lookup(objtype)
if reg is not None:
o = reg.from_iterable(node_data, ys)
else:
o = objtype(*ys)
return o
def from_iterable_tree(self, tree: T.Iterable):
"""Given a tree of iterables with the same node/leaf structure as this PyTree,
build the corresponding PyTree.
TODO(phawkins): use flattening everywhere instead and delete this method."""
it = iter(self.traversal_[::-1])
out = self._from_iterable_tree_helper(tree, it)
ok, _ = next_value(it)
if ok:
raise ValueError("Tree structures did not match.")
return out
def flatten_up_to(self, xs: T.Any):
"""Flattens a Pytree up to this PyTreeDef. 'self' must be a tree prefix of
the tree-structure of 'xs'.
For example, if we flatten a value [(1, (2, 3)), {"foo": 4}] with a treedef
[(*, *), *], the result is the list of leaves [1, (2, 3), {"foo": 4}]."""
leaves = py.list(range(self.num_leaves))
agenda = [xs]
leaf = self.num_leaves - 1
for (node_arity, num_leaves, num_nodes, objtype, node_data) in self.traversal_[::-1]:
object = agenda.pop()
if objtype is _NoneType:
pass
elif node_arity == -1:
assert leaf >= 0, "Leaf count mismatch"
leaves[leaf] = object
leaf -= 1
elif objtype is py.tuple:
if not isinstance(object, py.tuple):
raise ValueError("Expected tuple, got %s." % py.repr(object))
tuple: T.Tuple = object
if len(tuple) != node_arity:
raise ValueError("Tuple arity mismatch: %d != %d; tuple: %s." % (
len(tuple), node_arity, py.repr(object)
))
agenda.extend(tuple)
elif objtype is py.list:
if not isinstance(object, py.list):
raise ValueError("Expected list, got %s." % py.repr(object))
list: T.List = object
if len(list) != node_arity:
raise ValueError("List arity mismatch: %d != %d; list: %s." % (
len(list), node_arity, py.repr(object)
))
agenda.extend(list)
elif objtype is py.dict:
if not isinstance(object, py.dict):
raise ValueError("Expected dict, got %s." % py.repr(object))
dict: T.Dict = object
keys = py.list(dict.keys())
if keys != node_data:
raise ValueError("Dict key mismatch; expected keys: %s; dict: %s." % (
py.repr(node_data), py.repr(object)
))
agenda.extend(dict.values())
elif node_data == "namedtuple" and issubclass(objtype, py.tuple):
if not isinstance(object, py.tuple) or not hasattr(object, "_fields"):
raise ValueError("Expected named tuple, got %s." % py.repr(object))
tuple: T.NamedTuple = object
if len(tuple) != node_arity:
raise ValueError("Named tuple arity mismatch: %d != %d; tuple: %s." % (
len(tuple), node_arity, py.repr(object)
))
if py.type(tuple) != objtype:
raise ValueError("Named tuple type mismatch: expected type: %s, tuple: %s." % (
py.repr(objtype), py.repr(object)
))
agenda.extend(tuple)
else:
reg = PyTreeTypeRegistry.lookup(objtype)
if reg is None:
raise ValueError("Custom node type mismatch: expected type: %s, value: %s." % (
py.repr(objtype), py.repr(object)
))
out: T.Tuple = reg.to_iterable(object)
if len(out) != 2:
raise RuntimeError("PyTree custom to_iterable function should return a pair")
if node_data != out[1]:
raise ValueError("Mismatch custom node data: %s != %s; value: %s." % (
py.repr(node_data), py.repr(out[1]), py.repr(object)
))
arity = len(out[0])
if arity != node_arity:
raise ValueError("Custom type arity mismatch: %d != %d; value: %s." % (
arity, node_arity, py.repr(object)
))
agenda.extend(out[0])
if len(agenda) <= 0:
break
if leaf != -1:
raise ValueError("Tree structures did not match: %s vs %s" % (
py.repr(xs), py.str(self)
))
return leaves
def children(self) -> T.List[PyTreeDef]:
children = []
pos = len(self.traversal_) - 1
if pos >= 0:
(root_arity, *root) = self.traversal_[-1]
for i in range(root_arity - 1, -1, -1):
(node_arity, num_leaves, num_nodes, objtype, node_data) = self.traversal_[pos - 1]
assert pos >= num_nodes, "children() walked off start of array"
child = PyTreeDef(py.tuple(self.traversal_[pos - num_nodes:pos]))
children.append(child)
pos -= num_nodes
assert pos == 0, "pos != 0 at end of PyTreeDef::Children"
return children[::-1]
@staticmethod
def tuple(defs: T.List[PyTreeDef]) -> PyTreeDef:
"""Makes a Tuple PyTreeDef out of a vector of PyTreeDefs."""
defs = py.list(defs)
nodes = []
node_arity, num_leaves, num_nodes, objtype, node_data = len(defs), 0, 0, py.tuple, None
for td in defs:
nodes.extend(td.traversal_)
num_leaves += td.num_leaves
num_nodes += td.num_nodes
node = (node_arity, num_leaves, num_nodes, objtype, node_data)
nodes.append(node)
return PyTreeDef(py.tuple(nodes))
@classmethod
def flatten(cls, tree: T.Any, is_leaf: T.Optional[T.Callable[[T.Any], py.bool]] = None) -> (T.Iterable, PyTreeDef):
"""Flattens a Pytree into a list of leaves and a PyTreeDef.
Returns references to the flattened objects, which might be temporary
objects in the case of custom pytype handlers."""
leaves = []
nodes = []
cls.flatten_into(tree, leaves, nodes, is_leaf, 0, 0)
return leaves, cls(py.tuple(nodes))
@staticmethod
def is_leaf(handle: T.Any) -> py.bool:
objtype = type(handle)
reg = PyTreeTypeRegistry.lookup(objtype)
if reg is not None or is_namedtuple(handle, objtype) or objtype is _NoneType:
return False
return True
@classmethod
def all_leaves(cls, iterable: T.Iterable) -> py.bool:
"Tests whether the given list is a flat list of leaves."
for handle in iterable:
if not cls.is_leaf(handle):
return False
return True
def __str__(self):
agenda = []
for (node_arity, num_leaves, num_nodes, objtype, node_data) in self.traversal_:
assert len(agenda) >= max(node_arity, 0), "Too few elements for container."
representation = []
if node_arity < 0 and objtype is not _NoneType:
agenda.append("*")
continue
elif node_arity < 0 and objtype is _NoneType:
representation.append("None")
else:
children = '' if node_arity <= 0 else str_join(agenda[-node_arity:], ", ")
if objtype is py.tuple:
# Tuples with only one element must have a trailing comma.
if node_arity == 1:
children += ","
representation.append(str_cat("(", children, ")"))
elif objtype is py.list:
representation.append(str_cat("[", children, "]"))
elif objtype is py.dict:
separator = "{"
keys = node_data
values = agenda[-node_arity:]
for key, value in safe_zip(keys, values):
representation.append('%s%s: %s' % (separator, repr(key), value))
separator = ", "
representation.append('}')
else:
kind = str(objtype)
if node_data == "namedtuple" and issubclass(objtype, tuple):
node_data, kind = kind, node_data
data = '[%s]' % str(node_data)
representation.append('CustomNode(%s%s, [%s])' % (kind, data, children))
if node_arity > 0:
del agenda[-node_arity:]
agenda.append(''.join(representation))
return str_cat("PyTreeDef(", agenda, ")")
def __repr__(self) -> py.str:
return str(self)
def __eq__(self, other: PyTreeDef):
if not isinstance(other, PyTreeDef):
return False
if len(self.traversal_) != len(other.traversal_):
return False
for a, b in zip(self.traversal_, other.traversal_):
(a_node_arity, a_num_leaves, a_num_nodes, a_objtype, a_node_data) = a
(b_node_arity, b_num_leaves, b_num_nodes, b_objtype, b_node_data) = b
if a_objtype != b_objtype or a_node_arity != b_node_arity:
return False
if (a_node_data is None) != (b_node_data is None):
return False
if a_node_data is not None and a_node_data != b_node_data:
return False
# We don't need to test equality of num_leaves and num_nodes since they
# are derivable from the other node data.
return True
def __hash__(self):
return py.hash(((node_arity, objtype) for (node_arity, num_leaves, num_nodes, objtype, node_data) in self.traversal_))
@property
def num_leaves(self) -> py.int:
if len(self.traversal_) <= 0:
return 0
(node_arity, num_leaves, num_nodes, objtype, node_data) = self.traversal_[-1]
return num_leaves
@property
def num_nodes(self) -> py.int:
return len(self.traversal_)
_module = type(collections)
pytree = _module("pytree")
pytree.flatten = PyTreeDef.flatten
pytree.tuple = PyTreeDef.tuple
pytree.all_leaves = PyTreeDef.all_leaves
pytree.register_node = PyTreeTypeRegistry.register
def tree_flatten(tree: T.Any, is_leaf: T.Optional[T.Callable[[T.Any], py.bool]] = None) -> (T.Iterable, PyTreeDef):
"""Flattens a pytree.
Args:
tree: a pytree to flatten.
is_leaf: an optionally specified function that will be called at each
flattening step. It should return a boolean, which indicates whether
the flattening should traverse the current object, or if it should be
stopped immediately, with the whole subtree being treated as a leaf.
Returns:
A pair where the first element is a list of leaf values and the second
element is a treedef representing the structure of the flattened tree.
"""
return pytree.flatten(tree, is_leaf)
def tree_unflatten(treedef: PyTreeDef, leaves: T.Iterable):
"""Reconstructs a pytree from the treedef and the leaves.
The inverse of `tree_flatten`.
Args:
treedef: the treedef to reconstruct
leaves: the list of leaves to use for reconstruction. The list must
match the leaves of the treedef.
Returns:
The reconstructed pytree, containing the `leaves` placed in the
structure described by `treedef`.
"""
return treedef.unflatten(leaves)
def tree_leaves(tree) -> T.List:
"""Gets the leaves of a pytree."""
return pytree.flatten(tree)[0]
def tree_structure(tree) -> PyTreeDef:
"""Gets the treedef for a pytree."""
return pytree.flatten(tree)[1]
def treedef_tuple(treedefs: T.Iterable[PyTreeDef]) -> PyTreeDef:
"""Makes a tuple treedef from a list of child treedefs."""
return pytree.tuple(list(treedefs))
def treedef_children(treedef: PyTreeDef) -> T.List[PyTreeDef]:
return treedef.children()
def treedef_is_leaf(treedef: PyTreeDef) -> py.bool:
return treedef.num_nodes == 1
def all_leaves(iterable: T.Iterable) -> py.bool:
"""Tests whether all elements in the given iterable are all leaves.
>>> tree = {"a": [1, 2, 3]}
>>> assert all_leaves(jax.tree_leaves(tree))
>>> assert not all_leaves([tree])
This function is useful in advanced cases, for example if a library allows
arbitrary map operations on a flat list of leaves it may want to check if
the result is still a flat list of leaves.
Args:
iterable: Iterable of leaves.
Returns:
A boolean indicating if all elements in the input are leaves.
"""
return pytree.all_leaves(iterable)
def register_pytree_node(nodetype: T.Type, flatten_func: T.Callable, unflatten_func: T.Callable):
"""Extends the set of types that are considered internal nodes in pytrees.
See `example usage <https://jax.readthedocs.io/en/latest/notebooks/JAX_pytrees.html#Pytrees-are-extensible>`_.
Args:
nodetype: a Python type to treat as an internal pytree node.
flatten_func: a function to be used during flattening, taking a value
of type `nodetype` and returning a pair, with (1) an iterable for
the children to be flattened recursively, and (2) some auxiliary data
to be stored in the treedef and to be passed to the `unflatten_func`.
unflatten_func: a function taking two arguments: the auxiliary data that
was returned by `flatten_func` and stored in the treedef, and the
unflattened children. The function should return an instance of
`nodetype`.
"""
pytree.register_node(nodetype, flatten_func, unflatten_func)
def register_pytree_node_class(cls: T.Type):
"""Extends the set of types that are considered internal nodes in pytrees.
This function is a thin wrapper around ``register_pytree_node``, and provides
a class-oriented interface:
@register_pytree_node_class
class Special:
def __init__(self, x, y):
self.x = x
self.y = y
def tree_flatten(self):
return ((self.x, self.y), None)
@classmethod
def tree_unflatten(cls, aux_data, children):
return cls(*children)
"""
register_pytree_node(cls, op.methodcaller('tree_flatten'), cls.tree_unflatten)
return cls
def tree_map(f: T.Callable[..., T.Any], tree: T.Any, *rest: T.Any,
is_leaf: T.Optional[T.Callable[[T.Any], py.bool]] = None) -> T.Any:
"""Maps a multi-input function over pytree args to produce a new pytree.
Args:
f: function that takes ``1 + len(rest)`` arguments, to be applied at the
corresponding leaves of the pytrees.
tree: a pytree to be mapped over, with each leaf providing the first
positional argument to ``f``.
*rest: a tuple of pytrees, each of which has the same structure as tree or
or has tree as a prefix.
is_leaf: an optionally specified function that will be called at each
flattening step. It should return a boolean, which indicates whether
the flattening should traverse the current object, or if it should be
stopped immediately, with the whole subtree being treated as a leaf.
Returns:
A new pytree with the same structure as ``tree`` but with the value at each
leaf given by ``f(x, *xs)`` where ``x`` is the value at the corresponding
leaf in ``tree`` and ``xs`` is the tuple of values at corresponding nodes in
``rest``.
"""
leaves, treedef = tree_flatten(tree, is_leaf)
all_leaves = [leaves] + [treedef.flatten_up_to(r) for r in rest]
return treedef.unflatten(f(*xs) for xs in zip(*all_leaves))
tree_multimap = tree_map
# TODO(mattjj,phawkins): consider removing this function
def _process_pytree(process_node: T.Callable, tree: T.Any):
leaves, treedef = pytree.flatten(tree)
return treedef.walk(process_node, None, leaves), treedef
def build_tree(treedef: PyTreeDef, xs: T.Any):
return treedef.from_iterable_tree(xs)
def tree_transpose(outer_treedef: PyTreeDef, inner_treedef: PyTreeDef, pytree_to_transpose: T.Any):
flat, treedef = tree_flatten(pytree_to_transpose)
inner_size = inner_treedef.num_leaves
outer_size = outer_treedef.num_leaves
if treedef.num_leaves != (inner_size * outer_size):
expected_treedef = outer_treedef.compose(inner_treedef)
raise TypeError(f"Mismatch\n{treedef}\n != \n{expected_treedef}")
flat = iter(flat)
lol = [[next(flat) for _ in range(inner_size)] for __ in range(outer_size)]
transposed_lol = zip(*lol)
subtrees = map(partial(tree_unflatten, outer_treedef), transposed_lol)
return tree_unflatten(inner_treedef, subtrees)
no_initializer = py.object()
U = T.TypeVar("U")
@T.overload
def tree_reduce(function: T.Callable[[U, T.Any], U],
tree: T.Any) -> U:
...
@T.overload
def tree_reduce(function: T.Callable[[U, T.Any], U],
tree: T.Any,
initializer: U) -> U:
...
def tree_reduce(function: T.Callable[[U, T.Any], U],
tree: T.Any,
initializer: T.Any = no_initializer) -> U:
if initializer is no_initializer:
return functools.reduce(function, tree_leaves(tree))
else:
return functools.reduce(function, tree_leaves(tree), initializer)
def tree_all(tree):
return all(tree_leaves(tree))
def is_namedtuple(obj, objtype):
return hasattr(obj, '_fields') and isinstance(obj, tuple)
# objtype.__bases__ and objtype.__bases__[0] is tuple
def next_value(it):
try:
return True, next(it)
except StopIteration:
return False, None
def str_join(xs: T.Iterable, sep=', '):
return sep.join([str(x) for x in xs])
def str_cat(*xs: T.Optional[T.Iterable, py.str], sep=', ') -> py.str:
r = []
for x in xs:
if isinstance(x, str):
r.append(x)
else:
r.append(str_join(x, sep=sep))
return ''.join(r)
def safe_zip(*args):
n = len(args[0])
for arg in args[1:]:
assert len(arg) == n, 'length mismatch: {}'.format(list(map(len, args)))
return list(zip(*args))
register_pytree_node(
list,
lambda x: (x, None),
lambda _, values: values)
register_pytree_node(
tuple,
lambda x: (x, tuple),
lambda _, values: tuple(values))
register_pytree_node(
dict,
lambda x: (list(x.values()), list(x.keys())),
lambda keys, values: dict(safe_zip(keys, values)))
register_pytree_node(
collections.OrderedDict,
lambda x: (list(x.values()), list(x.keys())),
lambda keys, values: collections.OrderedDict(safe_zip(keys, values)))
register_pytree_node(
collections.defaultdict,
lambda x: (tuple(x.values()), (x.default_factory, tuple(x.keys()))),
lambda s, values: collections.defaultdict(s[0], safe_zip(s[1], values)))
class Partial(functools.partial):
"""A version of functools.partial that works in pytrees.
Use it for partial function evaluation in a way that is compatible with JAX's
transformations, e.g., ``Partial(func, *args, **kwargs)``.
(You need to explicitly opt-in to this behavior because we didn't want to give
functools.partial different semantics than normal function closures.)
"""
register_pytree_node(
Partial,
lambda partial_: ((partial_.args, partial_.keywords), partial_.func),
lambda func, xs: Partial(func, *xs[0], **xs[1]),
)
|
//Format date into the pinnacle format
function getMonthFromString(mon) {
return new Date(Date.parse(mon + " 1, 2012")).getMonth() + 1
}
function formatDate(dateString) {
if (dateString.includes('-')) {
var splitDate = dateString.split('-');
} else if (dateString.includes('.')) {
var splitDate = dateString.split('.');
} else if (dateString.includes('/')) {
var splitDate = dateString.split('/');
}
//Seperate out month and year
var month = splitDate[1];
var year = splitDate[2];
if(year.length==2){
year = '19'+year;
}
//Convert text month to int
var regExp = /[a-zA-Z]/g;
if (regExp.test(month)) {
month = getMonthFromString(month)
}
month = month - 1 //Javascript months are 0-11
var fomattedDate = new Date()
fomattedDate.setFullYear(year)
fomattedDate.setMonth(month)
fomattedDate.setDate(splitDate[0])
return fomattedDate.toLocaleDateString(
'en-gb', {
year: 'numeric',
month: 'short',
day: 'numeric'
}
).replace(/ /g, '-').replace("Sept", "Sep")
}
//Sort list of patients alphabetically
function sortAlphabetical(objArray) {
function compare(a, b) {
if (a.Name.toLowerCase() < b.Name.toLowerCase()) {
return -1;
}
if (a.Name.toLowerCase() > b.Name.toLowerCase()) {
return 1;
}
return 0;
}
objArray.sort(compare);
return objArray;
}
//Identify the column names
function identifyCSVKeys(CSVArray) {
var keys = Object.keys(CSVArray[0]);
var nhsno_key, dob_key, name_key,address_key;
keys.forEach(function (key) {
lkey = key.toLowerCase();
if (lkey.includes('nhs')) {
nhsno_key = key;
}
if (lkey.includes('address')) {
if(lkey.includes('organisation')){}else
if(lkey.includes('organization')){}else
if(lkey.includes('practice')){}else
if(lkey.includes('pcn')){}else{
address_key = key;
}
}
if (lkey.includes('dob')) {
dob_key = key;
} else if (lkey.includes('birth')) {
dob_key = key;
}
if (lkey.includes('name')) {
//do not include if the column name has a "name" that is referencing something other than patient
if(lkey.includes('organisation')){}else
if(lkey.includes('organization')){}else
if(lkey.includes('practice')){}else
if(lkey.includes('first')){}else
if(lkey.includes('sur')){}else
if(lkey.includes('pcn')){}else{
name_key = key;
}
}
});
return {
dob: dob_key,
name: name_key,
nhsno: nhsno_key,
address: address_key
};
}
|
import React from 'react'
import { useStaticQuery, graphql } from 'gatsby'
import Img from 'gatsby-image'
import siteConfig from '../../../data/site-config'
const Image = () => {
const data = useStaticQuery(graphql`
query {
images: allFile {
edges {
node {
relativePath
name
childImageSharp {
fluid(maxWidth: 300, maxHeight: 300) {
...GatsbyImageSharpFluid
}
}
}
}
}
}
`)
// Loop through all files to find file that matches with image path
const image = data.images.edges.find((n) => {
return n.node.relativePath.includes(siteConfig.profileImageName)
})
if (!image) {
return null
}
return <Img className='img-profile p-i-test' fluid={image.node.childImageSharp.fluid} />
}
export default Image
|
from sqlalchemy.orm import joinedload
from clld.interfaces import IParameter, IValue, IIndex
from clld.db.meta import DBSession
from clld.db.models.common import ValueSet
from clld.web.adapters.base import Index
from clld.web.adapters.geojson import GeoJsonParameter
from clld.web.maps import SelectedLanguagesMap
class GeoJsonFeature(GeoJsonParameter):
def feature_iterator(self, ctx, req):
return DBSession.query(ValueSet).filter(ValueSet.parameter_pk == ctx.pk)\
.options(joinedload(ValueSet.language))
def feature_properties(self, ctx, req, valueset):
return {}
class MapView(Index):
extension = str('map.html')
mimetype = str('text/vnd.clld.map+html')
send_mimetype = str('text/html')
template = 'language/map_html.mako'
def template_context(self, ctx, req):
languages = list(v.valueset.language for v in ctx.get_query(limit=8000))
return {
'map': SelectedLanguagesMap(ctx, req, languages),
'languages': languages}
def includeme(config):
config.register_adapter(GeoJsonFeature, IParameter)
config.register_adapter(MapView, IValue, IIndex)
|
/*
* Copyright (C) 2005 - 2013 MaNGOS <http://www.getmangos.com/>
*
* Copyright (C) 2008 - 2013 Trinity <http://www.trinitycore.org/>
*
* Copyright (C) 2010 - 2013 ArkCORE <http://www.arkania.net/>
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/// \addtogroup Trinityd
/// @{
/// \file
#ifndef __WORLDRUNNABLE_H
#define __WORLDRUNNABLE_H
/// Heartbeat thread for the World
class WorldRunnable: public ACE_Based::Runnable
{
public:
void run ();
};
#endif
/// @}
|
import loading from './loading.js';
import erro from './error.js';
import permalinkProducts from './produto-pagina.js';
export function initProdutos() {
async function fetchProdutos(url) {
try {
loading(true);
const produtosResponse = await fetch(url);
if (!produtosResponse.ok) throw new Error(produtosResponse.statusText);
const produtos = await produtosResponse.json();
getProdutos(produtos);
} catch (err) {
erro(err);
} finally {
loading(false);
}
}
function getProdutos(produtos) {
const produtosGrid = document.querySelector('[data-produtos]');
if (produtosGrid) {
produtosGrid.classList.add('get-in'); // animação
produtos.forEach((produto) => {
produtosGrid.innerHTML += `
<div class="produto" data-produto-id="${produto.id}">
<img src="${produto.fotos[0].src}" alt="${produto.fotos[0].titulo}" class="produto-img">
<div class="info-produto">
<span class="preco-produto">R$ ${produto.preco}</span>
<h2 class="nome-produto">${produto.nome}</h2>
</div>
</div>
`;
});
const produtosDiv = document.querySelectorAll('.produto');
if (produtosDiv) {
produtosDiv.forEach((produto) => {
produto.addEventListener('click', (e) => permalinkProducts(e, produtos));
});
}
}
}
return fetchProdutos('https://ranekapi.origamid.dev/json/api/produto');
}
|
module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "/dist/";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 89);
/******/ })
/************************************************************************/
/******/ ({
/***/ 0:
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return normalizeComponent; });
/* globals __VUE_SSR_CONTEXT__ */
// IMPORTANT: Do NOT use ES2015 features in this file (except for modules).
// This module is a runtime utility for cleaner component module output and will
// be included in the final webpack user bundle.
function normalizeComponent (
scriptExports,
render,
staticRenderFns,
functionalTemplate,
injectStyles,
scopeId,
moduleIdentifier, /* server only */
shadowMode /* vue-cli only */
) {
// Vue.extend constructor export interop
var options = typeof scriptExports === 'function'
? scriptExports.options
: scriptExports
// render functions
if (render) {
options.render = render
options.staticRenderFns = staticRenderFns
options._compiled = true
}
// functional template
if (functionalTemplate) {
options.functional = true
}
// scopedId
if (scopeId) {
options._scopeId = 'data-v-' + scopeId
}
var hook
if (moduleIdentifier) { // server build
hook = function (context) {
// 2.3 injection
context =
context || // cached call
(this.$vnode && this.$vnode.ssrContext) || // stateful
(this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext) // functional
// 2.2 with runInNewContext: true
if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') {
context = __VUE_SSR_CONTEXT__
}
// inject component styles
if (injectStyles) {
injectStyles.call(this, context)
}
// register component module identifier for async chunk inferrence
if (context && context._registeredComponents) {
context._registeredComponents.add(moduleIdentifier)
}
}
// used by ssr in case component is cached and beforeCreate
// never gets called
options._ssrRegister = hook
} else if (injectStyles) {
hook = shadowMode
? function () { injectStyles.call(this, this.$root.$options.shadowRoot) }
: injectStyles
}
if (hook) {
if (options.functional) {
// for template-only hot-reload because in that case the render fn doesn't
// go through the normalizer
options._injectStyles = hook
// register for functioal component in vue file
var originalRender = options.render
options.render = function renderWithStyleInjection (h, context) {
hook.call(context)
return originalRender(h, context)
}
} else {
// inject component registration as beforeCreate hook
var existing = options.beforeCreate
options.beforeCreate = existing
? [].concat(existing, hook)
: [hook]
}
}
return {
exports: scriptExports,
options: options
}
}
/***/ }),
/***/ 4:
/***/ (function(module, exports) {
module.exports = require("element-ui/lib/mixins/emitter");
/***/ }),
/***/ 89:
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
// CONCATENATED MODULE: ./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/vue-loader/lib??vue-loader-options!./packages/radio/src/radio.vue?vue&type=template&id=69cd6268&
var render = function() {
var _vm = this
var _h = _vm.$createElement
var _c = _vm._self._c || _h
return _c(
"label",
{
staticClass: "el-radio",
class: [
_vm.border && _vm.radioSize ? "el-radio--" + _vm.radioSize : "",
{ "is-disabled": _vm.isDisabled },
{ "is-focus": _vm.focus },
{ "is-bordered": _vm.border },
{ "is-checked": _vm.model === _vm.label }
],
attrs: {
role: "radio",
"aria-checked": _vm.model === _vm.label,
"aria-disabled": _vm.isDisabled,
tabindex: _vm.tabIndex
},
on: {
keydown: function($event) {
if (
!("button" in $event) &&
_vm._k($event.keyCode, "space", 32, $event.key, [" ", "Spacebar"])
) {
return null
}
$event.stopPropagation()
$event.preventDefault()
_vm.model = _vm.isDisabled ? _vm.model : _vm.label
}
}
},
[
_c(
"span",
{
staticClass: "el-radio__input",
class: {
"is-disabled": _vm.isDisabled,
"is-checked": _vm.model === _vm.label
}
},
[
_c("span", { staticClass: "el-radio__inner" }),
_c("input", {
directives: [
{
name: "model",
rawName: "v-model",
value: _vm.model,
expression: "model"
}
],
ref: "radio",
staticClass: "el-radio__original",
attrs: {
type: "radio",
"aria-hidden": "true",
name: _vm.name,
disabled: _vm.isDisabled,
tabindex: "-1"
},
domProps: {
value: _vm.label,
checked: _vm._q(_vm.model, _vm.label)
},
on: {
focus: function($event) {
_vm.focus = true
},
blur: function($event) {
_vm.focus = false
},
change: [
function($event) {
_vm.model = _vm.label
},
_vm.handleChange
]
}
})
]
),
_c(
"span",
{
staticClass: "el-radio__label",
on: {
keydown: function($event) {
$event.stopPropagation()
}
}
},
[
_vm._t("default"),
!_vm.$slots.default ? [_vm._v(_vm._s(_vm.label))] : _vm._e()
],
2
)
]
)
}
var staticRenderFns = []
render._withStripped = true
// CONCATENATED MODULE: ./packages/radio/src/radio.vue?vue&type=template&id=69cd6268&
// EXTERNAL MODULE: external "element-ui/lib/mixins/emitter"
var emitter_ = __webpack_require__(4);
var emitter_default = /*#__PURE__*/__webpack_require__.n(emitter_);
// CONCATENATED MODULE: ./node_modules/babel-loader/lib!./node_modules/vue-loader/lib??vue-loader-options!./packages/radio/src/radio.vue?vue&type=script&lang=js&
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
/* harmony default export */ var radiovue_type_script_lang_js_ = ({
name: 'ElRadio',
mixins: [emitter_default.a],
inject: {
elForm: {
default: ''
},
elFormItem: {
default: ''
}
},
componentName: 'ElRadio',
props: {
value: {},
label: {},
disabled: Boolean,
name: String,
border: Boolean,
size: String
},
data: function data() {
return {
focus: false
};
},
computed: {
isGroup: function isGroup() {
var parent = this.$parent;
while (parent) {
if (parent.$options.componentName !== 'ElRadioGroup') {
parent = parent.$parent;
} else {
this._radioGroup = parent;
return true;
}
}
return false;
},
model: {
get: function get() {
return this.isGroup ? this._radioGroup.value : this.value;
},
set: function set(val) {
if (this.isGroup) {
this.dispatch('ElRadioGroup', 'input', [val]);
} else {
this.$emit('input', val);
}
this.$refs.radio && (this.$refs.radio.checked = this.model === this.label);
}
},
_elFormItemSize: function _elFormItemSize() {
return (this.elFormItem || {}).elFormItemSize;
},
radioSize: function radioSize() {
var temRadioSize = this.size || this._elFormItemSize || (this.$ELEMENT || {}).size;
return this.isGroup ? this._radioGroup.radioGroupSize || temRadioSize : temRadioSize;
},
isDisabled: function isDisabled() {
return this.isGroup ? this._radioGroup.disabled || this.disabled || (this.elForm || {}).disabled : this.disabled || (this.elForm || {}).disabled;
},
tabIndex: function tabIndex() {
return this.isDisabled || this.isGroup && this.model !== this.label ? -1 : 0;
}
},
methods: {
handleChange: function handleChange() {
var _this = this;
this.$nextTick(function () {
_this.$emit('change', _this.model);
_this.isGroup && _this.dispatch('ElRadioGroup', 'handleChange', _this.model);
});
}
}
});
// CONCATENATED MODULE: ./packages/radio/src/radio.vue?vue&type=script&lang=js&
/* harmony default export */ var src_radiovue_type_script_lang_js_ = (radiovue_type_script_lang_js_);
// EXTERNAL MODULE: ./node_modules/vue-loader/lib/runtime/componentNormalizer.js
var componentNormalizer = __webpack_require__(0);
// CONCATENATED MODULE: ./packages/radio/src/radio.vue
/* normalize component */
var component = Object(componentNormalizer["a" /* default */])(
src_radiovue_type_script_lang_js_,
render,
staticRenderFns,
false,
null,
null,
null
)
/* hot reload */
if (false) { var api; }
component.options.__file = "packages/radio/src/radio.vue"
/* harmony default export */ var src_radio = (component.exports);
// CONCATENATED MODULE: ./packages/radio/index.js
/* istanbul ignore next */
src_radio.install = function (Vue) {
Vue.component(src_radio.name, src_radio);
};
/* harmony default export */ var packages_radio = __webpack_exports__["default"] = (src_radio);
/***/ })
/******/ }); |
(function() {
angular.module("Sunburst", [])
.directive("sunburst", sunburst)
.directive("onReadFile", onReadFile)
.controller("MainCtrl", MainCtrl);
// controller function MainCtrl
function MainCtrl($http) {
var ctrl = this;
init();
// function init
function init() {
// initialize controller variables
ctrl.examples = [
"data_android_os_conversion",
"data_netflix_churn",
"data_page_clicks"
];
ctrl.exampleSelected = ctrl.examples[0];
ctrl.getData = getData;
ctrl.selectExample = selectExample;
// initialize controller functions
ctrl.selectExample(ctrl.exampleSelected);
}
// function getData
function getData($fileContent) {
ctrl.data = $fileContent;
}
// function selectExample
function selectExample(item) {
var file = item + ".csv";
$http.get(file).success(function(data) {
ctrl.data = data;
});
}
}
// directive function sunburst
function sunburst() {
return {
restrict: "E",
scope: {
data: "=",
},
link: sunburstDraw
};
}
// directive function onReadFile
function onReadFile($parse) {
return {
restrict: "A",
scope: false,
link: function(scope, element, attrs) {
var fn = $parse(attrs.onReadFile);
element.on("change", function(onChangeEvent) {
var reader = new FileReader();
reader.onload = function(onLoadEvent) {
scope.$apply(function() {
fn(scope, {
$fileContent: onLoadEvent.target.result
});
});
};
reader.readAsText((onChangeEvent.srcElement || onChangeEvent.target).files[0]);
});
}
};
}
})(); |
import json
def lambda_handler(event, context):
return {
"statusCode": 200,
"body": {"message": str(event).upper()},
}
|
const $e0_attrs$ = ["myRef"];
// ...
ContentQueryComponent.ɵcmp = $r3$.ɵɵdefineComponent({
// ...
contentQueries: function ContentQueryComponent_ContentQueries(rf, ctx, dirIndex) {
if (rf & 1) {
$r3$.ɵɵcontentQuery(dirIndex, $e0_attrs$, __QueryFlags.emitDistinctChangesOnly__);
$r3$.ɵɵcontentQuery(dirIndex, $e0_attrs$, __QueryFlags.none__);
}
if (rf & 2) {
let $tmp$;
$r3$.ɵɵqueryRefresh($tmp$ = $r3$.ɵɵloadQuery()) && (ctx.myRefs = $tmp$);
$r3$.ɵɵqueryRefresh($tmp$ = $r3$.ɵɵloadQuery()) && (ctx.oldMyRefs = $tmp$);
}
},
// ...
viewQuery: function ContentQueryComponent_Query(rf, ctx) {
if (rf & 1) {
$r3$.ɵɵviewQuery(SomeDirective, __QueryFlags.emitDistinctChangesOnly__|__QueryFlags.descendants__);
$r3$.ɵɵviewQuery(SomeDirective, __QueryFlags.descendants__);
}
if (rf & 2) {
let $tmp$;
$r3$.ɵɵqueryRefresh($tmp$ = $r3$.ɵɵloadQuery()) && (ctx.someDirs = $tmp$);
$r3$.ɵɵqueryRefresh($tmp$ = $r3$.ɵɵloadQuery()) && (ctx.oldSomeDirs = $tmp$);
}
},
//...
});
|
price=input('enter a dollar amount')
tax=input('enter tax amount as a percent')
if tax.isdecimal():
res=float(price)+(float(tax)*float(price)/100)
else:
res=float(price)+(float(tax.rstrip('%'))*float(price)/100)
print('Total is $%.2f' % res)
|
import re
import setuptools
with open("pystarlark/__init__.py", "r", encoding="utf8") as f:
version = re.search(r'__version__ = "(.*?)"', f.read()).group(1)
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="pystarlark",
version=version,
author="Kevin Chung",
author_email="[email protected]",
description="Python bindings for Starlark in Go",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/ColdHeat/pystarlark",
packages=setuptools.find_packages(),
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
python_requires=">=3.6",
# I'm not sure what this value is supposed to be
build_golang={"root": "github.com/ColdHeat/pystarlark"},
ext_modules=[setuptools.Extension("pystarlark/starlark", ["starlark.go"])],
setup_requires=["setuptools-golang==2.3.0", "cffi==1.14.3"],
install_requires=["cffi==1.14.3"],
)
|
from __future__ import absolute_import, division, print_function
import six
from collections import defaultdict
from datetime import datetime, timedelta
from django.db.models import Q
from django.utils import timezone
from six.moves import reduce
from sentry.constants import STATUS_CHOICES
from sentry.models import EventUser, Release, User
from sentry.search.base import ANY, EMPTY
from sentry.utils.auth import find_users
class InvalidQuery(Exception):
pass
def parse_release(project, value):
# TODO(dcramer): add environment support
if value == 'latest':
value = Release.objects.extra(select={
'sort': 'COALESCE(date_released, date_added)',
}).order_by('-sort').values_list('version', flat=True).first()
if value is None:
return EMPTY
return value
def get_user_tag(project, key, value):
# TODO(dcramer): do something with case of multiple matches
try:
lookup = EventUser.attr_from_keyword(key)
euser = EventUser.objects.filter(
project=project,
**{lookup: value}
)[0]
except (KeyError, IndexError):
return '{}:{}'.format(key, value)
return euser.tag_value
def parse_datetime_range(value):
try:
flag, count, interval = value[0], int(value[1:-1]), value[-1]
except (ValueError, TypeError):
raise InvalidQuery('{} is not a valid datetime query'.format(value))
if flag not in ('+', '-'):
raise InvalidQuery('{} is not a valid datetime query'.format(value))
if interval == 'h':
delta = timedelta(hours=count)
elif interval == 'w':
delta = timedelta(days=count * 7)
elif interval == 'd':
delta = timedelta(days=count)
elif interval == 'm':
delta = timedelta(minutes=count)
else:
raise InvalidQuery('{} is not a valid datetime query'.format(value))
if flag == '-':
return (timezone.now() - delta, None)
else:
return (None, timezone.now() - delta)
def parse_datetime_comparison(value):
# TODO(dcramer): currently inclusitivity is not controllable by the query
# as from date is always inclusive, and to date is always exclusive
if value[:2] in ('>=', '=>'):
return (parse_datetime_value(value[2:])[0], None)
if value[:2] in ('<=', '=<'):
return (None, parse_datetime_value(value[2:])[0])
if value[:1] in ('>'):
return (parse_datetime_value(value[1:])[0], None)
if value[:1] in ('<'):
return (None, parse_datetime_value(value[1:])[0])
if value[0] == '=':
return parse_datetime_value(value[1:])
raise InvalidQuery('{} is not a valid datetime query'.format(value))
def parse_datetime_value(value):
try:
return _parse_datetime_value(value)
except ValueError:
raise InvalidQuery('{} is not a valid datetime query'.format(value))
def _parse_datetime_value(value):
# timezones are not supported and are assumed UTC
if value[-1] == 'Z':
value = value[:-1]
value_len = len(value)
if value_len in (8, 10):
value = datetime.strptime(value, '%Y-%m-%d').replace(
tzinfo=timezone.utc,
)
return [value, value + timedelta(days=1)]
elif value[4] == '-':
try:
value = datetime.strptime(value, '%Y-%m-%dT%H:%M:%S').replace(
tzinfo=timezone.utc,
)
except ValueError:
value = datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%f').replace(
tzinfo=timezone.utc,
)
else:
value = datetime.utcfromtimestamp(float(value)).replace(
tzinfo=timezone.utc,
)
return [value - timedelta(minutes=5), value + timedelta(minutes=6)]
def parse_datetime_expression(value):
# result must be (from inclusive, to exclusive)
if value.startswith(('-', '+')):
return parse_datetime_range(value)
if value.startswith(('>', '<', '=', '<=', '>=')):
return parse_datetime_comparison(value)
return parse_datetime_value(value)
def get_date_params(value, from_field, to_field):
date_from, date_to = parse_datetime_expression(value)
result = {}
if date_from:
result.update({
from_field: date_from,
'{}_inclusive'.format(from_field): True,
})
if date_to:
result.update({
to_field: date_to,
'{}_inclusive'.format(to_field): False,
})
return result
def tokenize_query(query):
"""
Tokenizes a standard Sentry search query.
>>> query = 'is:resolved foo bar tag:value'
>>> tokenize_query(query)
{
'is': ['resolved'],
'query': ['foo', 'bar'],
'tag': ['value'],
}
"""
results = defaultdict(list)
tokens = query.split(' ')
tokens_iter = iter(tokens)
for token in tokens_iter:
# ignore empty tokens
if not token:
continue
if ':' not in token:
results['query'].append(token)
continue
key, value = token.split(':', 1)
if not value:
results['query'].append(token)
continue
if value[0] == '"':
nvalue = value
while not nvalue.endswith('"'):
try:
nvalue = six.next(tokens_iter)
except StopIteration:
break
value = '%s %s' % (value, nvalue)
if value.endswith('"'):
value = value[1:-1]
else:
value = value[1:]
results[key].append(value)
return dict(results)
def parse_query(project, query, user):
# TODO(dcramer): handle query being wrapped in quotes
tokens = tokenize_query(query)
results = {'tags': {}, 'query': []}
for key, token_list in six.iteritems(tokens):
for value in token_list:
if key == 'query':
results['query'].append(value)
elif key == 'is':
if value == 'unassigned':
results['unassigned'] = True
elif value == 'assigned':
results['unassigned'] = False
else:
try:
results['status'] = STATUS_CHOICES[value]
except KeyError:
pass
elif key == 'assigned':
if value == 'me':
results['assigned_to'] = user
else:
try:
results['assigned_to'] = find_users(value)[0]
except IndexError:
# XXX(dcramer): hacky way to avoid showing any results when
# an invalid user is entered
results['assigned_to'] = User(id=0)
elif key == 'bookmarks':
if value == 'me':
results['bookmarked_by'] = user
else:
try:
results['bookmarked_by'] = find_users(value)[0]
except IndexError:
# XXX(dcramer): hacky way to avoid showing any results when
# an invalid user is entered
results['bookmarked_by'] = User(id=0)
elif key == 'first-release':
results['first_release'] = parse_release(project, value)
elif key == 'release':
results['tags']['sentry:release'] = parse_release(project, value)
elif key == 'user':
if ':' in value:
comp, value = value.split(':', 1)
else:
comp = 'id'
results['tags']['sentry:user'] = get_user_tag(
project, comp, value)
elif key == 'has':
if value == 'user':
value = 'sentry:user'
elif value == 'release':
value = 'sentry:release'
results['tags'][value] = ANY
elif key == 'age':
results.update(get_date_params(value, 'age_from', 'age_to'))
elif key.startswith('user.'):
results['tags']['sentry:user'] = get_user_tag(
project, key.split('.', 1)[1], value)
elif key == 'event.timestamp':
results.update(get_date_params(value, 'date_from', 'date_to'))
else:
results['tags'][key] = value
results['query'] = ' '.join(results['query'])
return results
def in_iexact(column, values):
from operator import or_
query = '{}__iexact'.format(column)
return reduce(or_, [Q(**{query: v}) for v in values])
|
import os.path
import setuptools
root = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(root, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setuptools.setup(
name='rc4',
version='3.7.2',
url='https://github.com/pydump/rc4',
license='MIT',
author='mohanson',
author_email='[email protected]',
description='RC4 algorithm by pure Python',
long_description=long_description,
long_description_content_type='text/markdown',
py_modules=['rc4']
)
|
import queryString from 'query-string';
import { dateRanges, defaultFilters } from './constants';
export const filterCenters = (centers = [], filters = defaultFilters) => {
const {
minAgeLimit = [],
feeType = [],
vaccine = [],
date = '',
onlyAvailable = false
} = filters;
const filteredCenters = centers
.filter((c) => (feeType.length > 0 ? feeType.includes(c.fee_type) : true))
.map((c) => {
const filteredSessions = (c.sessions || []).filter(
(s) =>
(date ? s.date === date : true) &&
(minAgeLimit.length > 0
? minAgeLimit.includes(s.min_age_limit)
: true) &&
(vaccine.length > 0 ? vaccine.includes(s.vaccine) : true) &&
(onlyAvailable ? s.available_capacity > 0 : true)
);
return { ...c, sessions: filteredSessions };
})
.filter((c) => c.sessions && c.sessions.length > 0);
return filteredCenters;
};
export const getParamsFromSearch = (search = '') => {
const { state, district, dateRange, minAgeLimit, feeType, vaccine, date } =
queryString.parse(search, {
arrayFormat: 'bracket-separator',
parseBooleans: true,
parseNumbers: true
});
const searchCriteria = {
state: state || '',
district: district || [],
dateRange: dateRange || dateRanges[0].value
};
const filter = {
minAgeLimit: minAgeLimit || defaultFilters.minAgeLimit,
feeType: feeType || defaultFilters.feeType,
date: date || defaultFilters.date,
vaccine: vaccine || defaultFilters.vaccine
};
return { searchCriteria, filter };
};
export const setUrlParams = (searchCriteria, filters, push, pathname) => {
const paramString = queryString.stringify(
{ ...searchCriteria, ...filters },
{
arrayFormat: 'bracket-separator',
skipEmptyString: true,
skipNull: true
}
);
push(`${pathname}?${paramString}`);
};
|
const projectList = [
{
name: 'React',
imageSrc: 'https://camo.githubusercontent.com/22045498095171997ccf6a9554672519b9f67898/68747470733a2f2f63646e2e776f726c64766563746f726c6f676f2e636f6d2f6c6f676f732f72656163742e737667',
projectLink: 'https://github.com/facebook/react/contribute',
description: 'A declarative, efficient, and flexible JavaScript library for building user interfaces.',
tags: ['JavaScript', 'UI', 'Web App'],
}, {
name: 'React Native',
imageSrc: 'https://camo.githubusercontent.com/22045498095171997ccf6a9554672519b9f67898/68747470733a2f2f63646e2e776f726c64766563746f726c6f676f2e636f6d2f6c6f676f732f72656163742e737667',
projectLink: 'https://github.com/facebook/react-native/contribute',
description: 'A framework for building native apps with React.',
tags: ['JavaScript', 'React', 'React Native', 'Mobile App'],
}, {
name: 'Darktable',
imageSrc: 'https://raw.githubusercontent.com/darktable-org/darktable/master/data/pixmaps/idbutton.png',
projectLink: 'https://github.com/darktable-org/darktable',
description: 'Open source photography workflow application and raw developer.',
tags: ['C', 'Lua', 'OpenCL', 'Photography'],
}, {
name: 'Exercism',
imageSrc: 'https://avatars2.githubusercontent.com/u/5624255?v=3&s=100',
projectLink: 'https://github.com/exercism/exercism/contribute',
description: 'Quickly ramp up in new programming languages!',
tags: ['Ruby', 'Exercises', 'CLI', 'Web App'],
}, {
name: 'Gauge',
imageSrc: 'https://avatars3.githubusercontent.com/u/7044589?s=400&u=8d2ce328da30e81978c303fdb31a2a7a1f0328e3&v=4',
projectLink: 'https://github.com/getgauge/gauge/contribute',
description: 'A free and open source test automation framework',
tags: ['Golang', 'Automation', 'command line', 'testing']
}, {
name: 'Habitat',
imageSrc: 'https://avatars1.githubusercontent.com/u/18171698?v=3&s=100',
projectLink: 'https://github.com/habitat-sh/habitat/contribute',
description: 'Modern applications with built-in automation.',
tags: ['Docs', 'Front-End', 'Rust', 'MultiOS'],
}, {
name: 'Scikit-learn',
imageSrc: 'https://avatars0.githubusercontent.com/u/365630?v=3&s=100',
projectLink: 'https://github.com/scikit-learn/scikit-learn/contribute',
description: 'Machine learning in Python!',
tags: ['Python', 'Machine Learning', 'Math'],
}, {
name: 'AVA',
imageSrc: 'https://avatars0.githubusercontent.com/u/8527916?v=3&s=100',
projectLink: 'https://github.com/avajs/ava/contribute',
description: 'The Futuristic JavaScript test runner!',
tags: ['JavaScript', 'Tests', 'Docs', 'Babel'],
}, {
name: 'Numpy',
imageSrc:
'https://camo.githubusercontent.com/b310fd3c9c5f7da5de0911b77d201408b76b8a58/68747470733a2f2f696d616765732e706c6f742e6c792f706c6f746c792d646f63756d656e746174696f6e2f7468756d626e61696c2f6e756d70792d6c6f676f2e6a7067',
projectLink:
'https://github.com/numpy/numpy/contribute',
description: 'Scientific computing with Python!',
tags: ['Python', 'Math', 'Module', 'Docs'],
}, {
name: 'Elasticsearch',
imageSrc: 'https://avatars2.githubusercontent.com/u/6764390?v=3&s=100',
projectLink: 'https://github.com/elastic/elasticsearch/contribute',
description: 'Open Source, Distributed, RESTful Search Engine.',
tags: ['REST', 'Docs', 'Java', 'Lucene'],
}, {
name: 'Homebrew',
imageSrc: 'https://avatars2.githubusercontent.com/u/1503512?v=3&s=100',
projectLink: 'https://github.com/Homebrew/brew/contribute',
description: 'The missing package manager for macOS.',
tags: ['MacOS', 'Ruby', 'C++'],
}, {
name: 'Rust',
imageSrc: 'https://avatars1.githubusercontent.com/u/5430905?v=3&s=100',
projectLink: 'https://github.com/rust-lang/rust/contribute',
description: 'A safe, concurrent, practical language!',
tags: ['Rust', 'Compiler', 'Mentored', 'Parser'],
}, {
name: 'Vuejs',
imageSrc: 'https://avatars1.githubusercontent.com/u/6128107?v=3&s=100',
projectLink: 'https://github.com/vuejs/vue/contribute',
description: 'A progressive, incrementally-adoptable JavaScript framework for building UI on the web.',
tags: ['JavaScript', 'UI', 'Front-End'],
}, {
name: 'Suave',
imageSrc: 'https://avatars2.githubusercontent.com/u/5822862?v=3&s=100',
projectLink: 'https://github.com/SuaveIO/suave/contribute',
description: 'Simple web development F# library to manipulate route flow and task composition.',
tags: ['F#', 'WebDev', 'Library'],
}, {
name: 'OpenRA',
imageSrc: 'https://avatars3.githubusercontent.com/u/409046?v=3&s=100',
projectLink: 'https://github.com/OpenRA/OpenRA/contribute',
description: 'Open Source real-time strategy game engine for early Westwood games.',
tags: ['AI', 'C#', 'SDL', 'OpenGL'],
}, {
name: 'PowerShell',
imageSrc: 'https://avatars0.githubusercontent.com/u/11524380?v=3&s=100',
projectLink: 'https://github.com/powershell/powershell/contribute',
description: 'PowerShell for every system.',
tags: ['Shell', 'Linux', 'MacOS', 'Windows', '*BSD'],
}, {
name: 'Coala',
imageSrc: 'https://avatars2.githubusercontent.com/u/10620750?v=3&s=100',
projectLink: 'https://coala.io/newcomer',
description: 'Unified command-line interface for linting and fixing all your code.',
tags: ['UX', 'Linter', 'Python'],
}, {
name: 'Moment',
imageSrc: 'https://avatars2.githubusercontent.com/u/4129662?v=3&s=100',
projectLink: 'https://github.com/moment/moment/contribute',
description: 'Parse, validate, manipulate, and display dates in JavaScript.',
tags: ['JavaScript', 'Front-End', 'Meta'],
}, {
name: 'Leiningen',
imageSrc:
'https://camo.githubusercontent.com/0f302c808c8457f6460913e33aed3478124612c2/687474703a2f2f6c65696e696e67656e2e6f72672f696d672f6c65696e696e67656e2e6a7067',
projectLink:
'https://github.com/technomancy/leiningen/contribute',
description: 'Automate Clojure projects without setting your hair on fire.',
tags: ['Clojure', 'Automation'],
}, {
name: 'Brackets',
imageSrc: 'https://github.com/adobe/brackets/raw/gh-pages/images/brackets_128.png?raw=true',
projectLink: 'https://github.com/adobe/brackets/contribute',
description: 'An open source code editor for the web, written in JavaScript, HTML and CSS.',
tags: ['Editor', 'Windows', 'Linux', 'MacOS'],
}, {
name: 'Webpack',
imageSrc: 'https://avatars3.githubusercontent.com/u/2105791?v=3&s=100',
projectLink: 'https://github.com/webpack/webpack/contribute',
description: 'A bundler for JavaScript and friends. Packs many modules into a few bundled assets.',
tags: ['Bundler', 'JavaScript', 'Compiler', 'Loader'],
}, {
name: 'Babel',
imageSrc: 'https://avatars2.githubusercontent.com/u/9637642?v=3&s=100',
projectLink: 'https://github.com/babel/babel/contribute',
description: 'Babel is a compiler for writing next generation JavaScript.',
tags: ['es2015', 'JavaScript', 'Compiler'],
}, {
name: 'Pouchdb',
imageSrc: 'https://avatars3.githubusercontent.com/u/3406112?v=3&s=100',
projectLink: 'https://github.com/pouchdb/pouchdb/contribute',
description: 'A pocket-sized database.',
tags: ['JavaScript', 'Node.js', 'CouchDB'],
}, {
name: 'Neovim',
imageSrc: 'https://avatars0.githubusercontent.com/u/6471485?v=3&s=100',
projectLink: 'https://github.com/neovim/neovim/contribute',
description: 'Vim-fork focused on extensibility and usability.',
tags: ['Editor', 'API', 'Cross-Platform', 'Vim'],
}, {
name: 'Hoodie',
imageSrc: 'https://hoodiehq.github.io/hoodie-css/src/content_img/animals/low-profile-dog-1.png',
projectLink: 'https://github.com/hoodiehq/hoodie/contribute',
description: 'The Offline First JavaScript Backend.',
tags: ['JavaScript', 'Node.js', 'Web development', 'User-Friendly'],
}, {
name: 'freeCodeCamp',
imageSrc: 'https://avatars0.githubusercontent.com/u/9892522?v=3&s=100',
projectLink: 'https://github.com/freeCodeCamp/freeCodeCamp/contribute',
description: 'Open Source codebase and curriculum.',
tags: ['Learn', 'Education', 'Non-Profit', 'Certification'],
}, {
name: 'Node.js',
imageSrc: 'https://avatars1.githubusercontent.com/u/9950313?v=3&s=100',
projectLink: 'https://github.com/nodejs/node/contribute',
description: 'Node.js JavaScript runtime.',
tags: ['JavaScript', 'HTML', 'CSS'],
}, {
name: 'Semantic-UI-React',
imageSrc: 'https://avatars1.githubusercontent.com/u/5796209?s=200&v=4',
projectLink: 'https://github.com/Semantic-Org/Semantic-UI-React/contribute',
description: 'The official Semantic-UI-React integration.',
tags: ['React', 'Library', 'Component', 'Front-End'],
}, {
name: 'Contribute to Open Source',
imageSrc: 'https://image.ibb.co/fUM5oG/profile_first_pr.png',
projectLink: 'https://github.com/danthareja/contribute-to-open-source/contribute',
description: 'Learn GitHub\'s pull request process by contributing code in a fun simulation project.',
tags: ['GitHub', 'Tutorial'],
}, {
name: 'Mail For Good',
imageSrc: 'https://avatars0.githubusercontent.com/u/9892522?v=3&s=100',
projectLink: 'https://github.com/freeCodeCamp/mail-for-good/contribute',
description: 'An open source email campaign management tool.',
tags: ['Nodejs', 'JavaScript', 'Email-Campaigns'],
},
{
name: 'Visual Studio Code',
imageSrc: 'https://camo.githubusercontent.com/a7f6e01cc208b478047eade76755f46cf1098c05/68747470733a2f2f75706c6f61642e77696b696d656469612e6f72672f77696b6970656469612f636f6d6d6f6e732f322f32642f56697375616c5f53747564696f5f436f64655f312e31385f69636f6e2e737667',
projectLink: 'https://github.com/Microsoft/vscode/contribute',
description: 'VS Code is a new type of tool that combines the simplicity of a code editor with what developers need for their core edit-build-debug cycle.',
tags: ['TypeScript', 'Text-Editor', 'Electron'],
},
{
name: 'Scrapy',
imageSrc: 'https://blog-media.scrapinghub.com/production/wp-content/uploads/2016/10/06054611/Scrapy-300x300.png',
projectLink: 'https://github.com/scrapy/scrapy/contribute',
description: 'Scrapy is a fast high-level web crawling and web scraping framework, used to crawl websites and extract structured data from their pages. ',
tags: ['Python', 'Module', 'Data-Mining', 'Automated-Testing'],
},
{
name: 'Angular',
imageSrc: 'https://avatars0.githubusercontent.com/u/139426?s=200&v=4',
projectLink: 'https://github.com/angular/angular/contribute',
description: 'Angular is a development platform for building mobile and desktop Web Applications using TypeScript or JavaScript and other languages.',
tags: ['Angular', 'TypeScript', 'JavaScript'],
},
{
name: 'React Styleguidist',
imageSrc: 'https://d3vv6lp55qjaqc.cloudfront.net/items/061f0A2n1B0H3p0T1p1f/react-styleguidist-logo.png',
projectLink: 'https://github.com/styleguidist/react-styleguidist/contribute',
description: 'React Styleguidist is a component development environment with hot reloaded dev server and a living style guide that you can share with your team. It lists component propTypes and shows live, editable usage examples based on Markdown files.',
tags: ['JavaScript', 'UI'],
},
{
name: 'Flutter',
imageSrc: 'https://raw.githubusercontent.com/flutter/website/master/src/_assets/image/flutter-lockup.png',
projectLink: 'https://github.com/flutter/flutter/contribute',
description: 'Flutter makes it easy and fast to build beautiful apps for mobile and beyond.',
tags: ['Dart','Android','iOS','UI','Cross-platform'],
},
{
name: 'Python Koans',
imageSrc: 'https://s3.amazonaws.com/media-p.slid.es/thumbnails/akoebbe/b35d77/python-koans.jpg',
projectLink: 'https://github.com/gregmalcolm/python_koans/contribute',
description: 'Python Koans is a port of Edgecase\'s "Ruby Koans".',
tags: ['Python', 'Exercises', 'CLI', 'Web App'],
},
{
name: 'Scala Exercises',
imageSrc: 'https://avatars1.githubusercontent.com/u/17570897?s=200&v=4',
projectLink: 'https://github.com/scala-exercises/scala-exercises/contribute',
description: 'Scala Exercises is an Open Source project for learning different technologies based in the Scala Programming Language.',
tags: ['Scala', 'Exercises', 'Functional Programming'],
},
{
name: 'CodeWorkout',
imageSrc: 'https://i.imgur.com/ZsSiCqi.png',
projectLink: 'https://github.com/web-cat/code-workout/contribute',
description: 'CodeWorkout is an online system for people learning a programming language for the first time. It is a free, open-source solution for practicing small programming problems. Students may practice coding exercises on a variety of programming concepts within the convenience of a web browser!',
tags: ['Java', 'Ruby', 'Python', 'Exercises'],
},
{
name: 'TEAMMATES',
imageSrc: 'https://www.google-melange.com/archive/gsoc/2015/orgs/teammates/logo-200.png',
projectLink: 'https://github.com/TEAMMATES/teammates/contribute',
description: 'An online feedback management system for students and teachers',
tags: ['Java', 'Javascript', 'HTML', 'Web App'],
},
{
name: 'electron',
imageSrc: 'https://avatars3.githubusercontent.com/u/13409222?s=200&v=4',
projectLink: 'https://github.com/electron/electron/contribute',
description: 'Build cross platform desktop apps with JavaScript, HTML, and CSS!',
tags: ['JavaScript', 'Electron', 'Css', 'Html', 'Chrome', 'Nodejs', 'V8']
},
{
name: 'Oppia',
imageSrc: 'https://www.oppia.org/build/assets/images/logo/288x128_logo_mint.42f8d38467fe745205b3374b33668068.png',
projectLink: 'https://github.com/oppia/oppia/contribute',
description: 'Tool for collaboratively building interactive lessons.',
tags: ['Python', 'Javascript', 'Css', 'Html', 'Shell'],
},
{
name: 'Public Lab',
imageSrc: 'https://publiclab.org/system/images/photos/000/023/444/large/Screenshot_20180204-101546_2.png',
projectLink: 'https://publiclab.github.io/community-toolbox/#r=all',
description: 'PublicLab.org - a collaborative knowledge-exchange platform in Rails; we welcome first-time contributors! 🎈',
tags: ['Ruby on Rails', 'Ruby', 'JavaScript', 'Non-Profit', 'Web App', 'First-Timers', 'Environment', 'Science'],
},
{
name: 'MissionControl',
imageSrc: 'https://i.imgur.com/nSRLFas.gif',
projectLink: 'https://github.com/DAVFoundation/missioncontrol/contribute',
description: 'Controls and orchestrates missions between autonomous vehicles and DAV users.',
tags: ['Javascript', 'Docker', 'Thrift', 'Good First Issue']
},
{
name: 'DuckDuckGo',
imageSrc: 'https://avatars3.githubusercontent.com/u/342708?s=200&v=4',
projectLink: 'https://github.com/duckduckgo/duckduckgo-privacy-extension/contribute',
description: 'The search engine that doesn\'t track you!',
tags: ['Javascript', 'Perl', 'Python', 'Privacy']
},
{
name: 'Kinto',
imageSrc: 'https://avatars2.githubusercontent.com/u/13413813?s=200&v=4',
projectLink: 'https://github.com/Kinto/kinto/contribute',
description: 'A generic JSON document store with sharing and synchronisation capabilities.',
tags: ['Python', 'API', 'HTTP', 'Web', 'Decentralisation'],
},
{
name: 'atom',
imageSrc: 'https://upload.wikimedia.org/wikipedia/commons/e/e2/Atom_1.0_icon.png',
projectLink: 'https://github.com/atom/atom/contribute',
description: 'A customizable text editor built on electron.',
tags: ['Atom', 'Editor', 'Javascript', 'Electron', 'Windows', 'Linux', 'Macos']
},
{
name: 'OpenGenus',
imageSrc: 'https://raw.githubusercontent.com/notnerb/FamilySite/master/logo.png',
projectLink: 'https://github.com/OpenGenus/Join_OpenGenus/contribute',
description: 'A positive open-source community working to bring essential programming knowledge offline.',
tags: ['C++', 'Python', 'Java', 'Good First Issue']
},
{
name: 'css-protips',
imageSrc: 'https://camo.githubusercontent.com/9b290de6835cf807aaa81bb6a7cfdf3835636f8c/68747470733a2f2f7261776769742e636f6d2f416c6c5468696e6773536d697474792f6373732d70726f746970732f6d61737465722f6d656469612f6c6f676f2e737667',
projectLink: 'https://github.com/AllThingsSmitty/css-protips/contribute',
description: 'Simple but useful tips to improve your CSS skills.',
tags: ['CSS', 'tips', 'guide', 'simple', 'useful']
},
{
name: 'Systers',
imageSrc: 'https://avatars3.githubusercontent.com/u/6520415?s=200&v=4',
projectLink: 'https://github.com/systers',
description: 'Helping women find their potential in code.',
tags: ['Python', 'Java', 'Swift', 'Javascript', 'HTML'],
},
{
name: 'Centos',
imageSrc: 'https://avatars2.githubusercontent.com/u/79192?s=200&v=4',
projectLink: 'https://github.com/CentOS',
description: 'A community-driven free software effort focused on delivering a robust open source ecosystem.',
tags: ['Shell', 'Python', 'HTML', 'Ruby', 'Puppet'],
},
{
name: 'NPM',
imageSrc: 'https://avatars0.githubusercontent.com/u/6078720?s=200&v=4',
projectLink: 'https://github.com/npm',
description: 'Npm is the package manager for JavaScript and the world’s largest software registry. Discover packages of reusable code — and assemble them in powerful new ways.',
tags: ['Javascript', 'Shell', 'CSS', 'HTML', 'Rust'],
},
{
name: 'openEBS',
imageSrc: 'https://avatars1.githubusercontent.com/u/20769039?s=200&v=4',
projectLink: 'https://github.com/openebs/',
description: 'OpenEBS is an open source storage platform that provides persistent and containerized block storage for DevOps and container environments.',
tags: ['Containers', 'DevOps', 'Go'],
},
{
name: 'Kubernetes',
imageSrc: 'https://raw.githubusercontent.com/kubernetes/kubernetes/master/logo/logo.png',
projectLink: 'https://github.com/kubernetes',
description: 'Production-Grade Container Scheduling and Management',
tags: ['Go', 'Container', 'Orchestration'],
},
{
name: 'styled-system',
imageSrc: 'https://camo.githubusercontent.com/8b3dc6438530a7240e952b187e40bd8380090f64/68747470733a2f2f7374796c65642d73797374656d2e636f6d2f6c6f676f2e737667',
projectLink: 'https://github.com/styled-system/styled-system/contribute',
description: 'Style props for rapid UI development',
tags: ['ui', 'css-in-js', 'design-systems', 'style-props', 'theming'],
},
{
name: 'Movie-Stream',
imageSrc: 'https://image.ibb.co/faTroc/movie_stream.png',
projectLink: 'https://github.com/hrishi7/streamIt/contribute',
description: 'Provides Online free movie streaming service with adfree. flexible for mobile also',
tags: ['Web development', 'HTML', 'Javascript', 'API', 'CSS', 'Bootstrap']
},
{
name: 'ethereum',
imageSrc: 'https://avatars1.githubusercontent.com/u/6250754?s=200&v=4',
projectLink: 'https://github.com/ethereum/',
description: 'Ethereum is a decentralized platform that runs smart contracts applications.',
tags: ['Go', 'C++', 'Solidity', 'Python', 'Shell', 'Java'
]
},
{
name: 'Rust Lang Nursery',
imageSrc: 'https://avatars2.githubusercontent.com/u/14631425?s=200&v=4',
projectLink: 'https://github.com/rust-lang-nursery/rust-clippy/contribute',
description: 'A collection of lints to catch common mistakes and improve your Rust code.',
tags: ['Rust', 'Compiler', 'Parser', 'Mentors'
]
},
{
name: 'probot',
imageSrc: 'https://avatars2.githubusercontent.com/u/26350515?s=400&v=4',
projectLink: 'https://github.com/probot/probot/contribute',
description: 'Probot is a framework for building Github Apps in Node.js.',
tags: ['Node.js', 'Github', 'Javascript']
},
{
name: 'Open Data Kit',
imageSrc: 'https://opendatakit.org/assets/images/logo.png',
projectLink: 'https://github.com/opendatakit',
description: 'Free and open-source set of tools for collecting data in challenging environments.',
tags: ['Open Source', 'Software', 'JAVA', 'Android']
},
{
name: 'Sugar Labs',
imageSrc: 'https://avatars3.githubusercontent.com/u/3996398?s=280&v=4',
projectLink: 'https://github.com/sugarlabs',
description: 'Learning Software for children.',
tags: ['Ubuntu', 'Rasberry Pi', 'Debian', 'Fedora']
},
{
name: 'Jupyter Hub',
imageSrc: 'https://avatars2.githubusercontent.com/u/17927519?s=400&v=4',
projectLink: 'https://github.com/jupyterhub/jupyterhub/contribute',
description: 'A multi-user Hub, spawns, manages, and proxies multiple instances of the single-user Jupyter notebook server.',
tags: ['Proxy Server', 'Python', 'REST API']
},
{
name: 'Allenai',
imageSrc: 'https://news.cs.washington.edu/wp-content/uploads/2015/10/AI2-logo-300x300.png',
projectLink: 'https://github.com/allenai/allennlp/contribute',
description: 'conducts high-impact research and engineering to tackle key problems in artificial intelligence.',
tags: ['Artificial Intelligence', 'Python', 'NLP']
},
{
name: 'Qute Browser',
imageSrc: 'https://avatars1.githubusercontent.com/u/21955151?s=200&v=4',
projectLink: 'https://github.com/qutebrowser/qutebrowser/contribute',
description: 'A keyboard-driven, vim-like browser based on PyQt5',
tags: ['Python', 'Qt', 'pyqt5', 'Vim', 'Browser', 'qtWebEngine', 'web']
},
{
name: 'Ghost',
imageSrc: 'https://avatars1.githubusercontent.com/u/2178663?s=200&v=4',
projectLink: 'https://github.com/TryGhost/Ghost/contribute',
description: 'Just a blogging platform',
tags: ['nodejs', 'javascript', 'ember', 'cms', 'blogging']
},
{
name: 'Hyper',
imageSrc: 'https://raw.githubusercontent.com/vercel/hyper/canary/app/static/icon.png',
projectLink: 'https://github.com/zeit/hyper/contribute',
description: 'A terminal built on web technologies',
tags: ['html', 'javascript', 'css', 'react', 'terminal']
},
{
name: 'Kap',
imageSrc: 'https://avatars3.githubusercontent.com/u/16321113?s=200&v=4',
projectLink: 'https://github.com/wulkano/kap/contribute',
description: 'An open-source screen recorder built with web technology',
tags: ['electron', 'javascript', 'mac', 'oss', 'screencast']
},
{
name: 'Ember.js',
imageSrc: 'https://avatars0.githubusercontent.com/u/1253363?s=200&v=4',
projectLink: 'https://github.com/emberjs/ember.js/contribute',
description: 'A JavaScript framework for creating ambitious web applications',
tags: ['ember', 'javascript', 'javascript-framework']
},
{
name: 'Opensourcedesign',
imageSrc: 'https://avatars3.githubusercontent.com/u/4183553?s=200&v=4',
projectLink: 'https://github.com/opensourcedesign/opensourcedesign.github.io/contribute',
description: 'Source code of the website opensourcedesign.net',
tags: ['design', 'opensourcedesign', 'open-source', 'open-source-design']
},
{
name: 'ifme',
imageSrc: 'https://raw.githubusercontent.com/ifmeorg/ifme/master/public/logo_512.png',
projectLink: 'https://github.com/ifmeorg/ifme/contribute',
description: 'A community for mental health experiences',
tags: ['ruby-on-rails', 'javascript', 'react']
},
{
name: 'Rebus',
imageSrc: 'https://raw.githubusercontent.com/ollelauribostrom/rebus/master/logo.png',
projectLink: 'https://github.com/ollelauribostrom/rebus/contribute',
description: 'Helping new developers take their first steps as open source contributors by developing a simple rebus game together',
tags: ['javascript', 'html', 'css', 'tutorial']
},
{
name: 'PRoot',
imageSrc: 'https://avatars2.githubusercontent.com/u/12125707',
projectLink: 'https://github.com/proot-me/PRoot/contribute',
description: 'chroot, mount --bind, and binfmt_misc without privilege/setup for Linux ',
tags: ['chroot-environment', 'userland-exec', 'rootfs', 'chroot', 'c']
},
{
name: 'Techqueria.org',
imageSrc: 'https://avatars1.githubusercontent.com/u/17460806?s=200&v=4',
projectLink: 'https://github.com/techqueria',
description: 'We\'re a community of Latinx professionals in the tech industry.',
tags: ['latinx', 'latinx in tech', 'hugo', 'netlify', 'jamstack']
},
{
name: 'Nextcloud',
imageSrc: 'https://avatars0.githubusercontent.com/u/19211038?s=200&v=4',
projectLink: 'https://github.com/nextcloud/server/contribute',
description: 'Open source collaboration platform for files, calendar, contacts, chat & calls, mail and more.',
tags: ['javascript', 'php', 'html', 'css', 'android', 'c++', 'qt', 'design', 'ios', 'vuejs', 'web']
},
{
name: 'Open Source Diversity',
imageSrc: 'https://avatars1.githubusercontent.com/u/31018274?s=200&v=4',
projectLink: 'https://github.com/opensourcediversity/opensourcediversity.org/contribute',
description: 'For more diversity & inclusion in free & open source software communities 😊',
tags: ['javascript', 'html', 'css', 'diversity', 'inclusion', '🎉', 'web', 'community']
},
{
name: 'Bitcoin',
imageSrc: 'https://img.rawpixel.com/s3fs-private/rawpixel_images/website_content/v211-mint-aum-currency-13.jpg?auto=format&bg=F4F4F3&con=3&cs=srgb&dpr=1&fm=jpg&ixlib=php-1.1.0&mark=rawpixel-watermark.png&markalpha=90&markpad=13&markscale=10&markx=25&q=75&usm=15&vib=3&w=1000&s=435abda621bceebc1362c7e657e06c79',
projectLink: 'https://github.com/bitcoin/bitcoin/contribute',
description: 'Bitcoin is an experimental digital currency that enables instant payments to anyone, anywhere in the world.',
tags: ['C++', 'Python', 'Cryptocurrency', 'Blockchain', 'Peer-to-peer']
},
{
name: 'Tensorflow',
imageSrc: 'https://camo.githubusercontent.com/0905c7d634421f8aa4ab3ddf19a582572df568e1/68747470733a2f2f7777772e74656e736f72666c6f772e6f72672f696d616765732f74665f6c6f676f5f736f6369616c2e706e67',
projectLink: 'https://github.com/tensorflow/tensorflow/contribute',
description: 'A Machine Learning library in Python for implementing Machine Learning and Deep Learning models',
tags: ['python', 'c++', 'machine learning', 'math', 'deep learning', 'neural network']
},
{
name: 'Next',
imageSrc: 'https://cloud.githubusercontent.com/assets/13041/19686250/971bf7f8-9ac0-11e6-975c-188defd82df1.png',
projectLink: 'https://github.com/zeit/next.js/contribute',
description: 'Next.js is a framework that most notably allows you to write server-rendered React apps easily',
tags: ['JavaScript', 'server-rendering', 'node', 'nextjs', 'react']
},
{
name: 'Roc Toolkit',
imageSrc: 'https://roc-streaming.org/icon.png',
projectLink: 'https://github.com/roc-streaming/roc-toolkit/labels/help%20wanted',
description: 'A toolkit for real-time audio streaming over the network',
tags: ['C++', 'Audio', 'Streaming', 'Networking', 'Cross-Platform', 'Linux', 'MacOS', 'Windows']
},
{
name: 'Conda',
imageSrc: 'https://conda.io/en/latest/_images/conda_logo.svg',
projectLink: 'https://github.com/conda',
description: 'Conda is an open source package management system and environment management system that runs on Windows, macOS and Linux. Conda quickly installs, runs and updates packages and their dependencies. Conda easily creates, saves, loads and switches between environments on your local computer. It was created for Python programs, but it can package and distribute software for any language.',
tags: ['ML', 'Python', 'Builds', 'Package Manager']
},
{
name: 'Light Table',
imageSrc: 'http://lighttable.com/images/logo.png',
projectLink: 'https://github.com/LightTable',
description: 'Light Table is a next generation code editor that connects you to your creation with instant feedback. Light Table is very customizable and can display anything a Chromium browser can.',
tags: ['clojurescript', 'ide', 'editor', 'clojure', 'lighttable', 'clojure-development']
},
{
name: 'Dragula',
imageSrc: 'https://bevacqua.github.io/dragula/resources/icon.svg',
projectLink: 'https://github.com/bevacqua/dragula',
description: 'Dragula provides the easiest possible API to make drag and drop a breeze in your applications.',
tags: ['Javascript', 'front-end', 'drag-and-drop', 'vanilla', 'drag-drop', 'dragging', 'component']
},
{
name: 'Moby',
imageSrc: 'https://github.com/moby/moby/raw/master/docs/static_files/moby-project-logo.png',
projectLink: 'https://github.com/moby/moby',
description: 'The Moby project is a collaborative project for the container ecosystem to assemble container-based systems',
tags: ['docker', 'containers', 'go']
},
{
name: 'ScyllaDb',
imageSrc: 'https://avatars1.githubusercontent.com/u/14364730?s=200&v=4',
projectLink: 'https://github.com/scylladb/scylla',
description: 'NoSQL data store using the seastar framework, compatible with Apache Cassandra',
tags: ['nosql', 'cpp', 'cassandra']
},
{
name: 'OSRM (Open Source Routing Machine)',
imageSrc: 'https://avatars2.githubusercontent.com/u/8207060?s=200&v=4',
projectLink: 'https://github.com/Project-OSRM/osrm-backend',
description: 'High performance routing engine written in C++14 designed to run on OpenStreetMap data',
tags: ['osrm', 'routing-engine', 'cpp', 'openstreetmap']
},
{
name: 'Laravel',
imageSrc: 'https://avatars3.githubusercontent.com/u/958072?s=200&v=4',
projectLink: 'https://github.com/laravel/laravel',
description: 'A PHP Framework for Web Artisans',
tags: ['PHP', 'web development']
},
{
name: 'Django',
imageSrc: 'https://avatars3.githubusercontent.com/u/27804?s=200&v=4',
projectLink: 'https://github.com/django/django',
description: 'A high-level Python Web framework that encourages rapid development and clean, pragmatic design',
tags: ['python', 'web development']
},
{
name: 'Plotly',
imageSrc: 'https://avatars3.githubusercontent.com/u/5997976?s=200&v=4',
projectLink: 'https://github.com/plotly',
description: 'A high-level Python declarative charting library',
tags: ['python', 'javascript', 'graph', 'graph-based', 'graph visualization']
},
{
name: 'NetworkX',
imageSrc: 'https://avatars3.githubusercontent.com/u/388785?s=200&v=4',
projectLink: 'https://github.com/networkx/networkx/contribute',
description: 'Python library for studying graphs and networks',
tags: ['Python', 'graph', 'graph algorithms', 'complex networks']
},
{
name: 'Igraph',
imageSrc: 'https://avatars3.githubusercontent.com/u/3735184?s=200&v=4',
projectLink: 'https://github.com/igraph/igraph/contribute',
description: 'Python Library for creating and manipulating graphs',
tags: ['Python', 'graph', 'graph algorithms', 'complex networks']
},
{
name: 'D3',
imageSrc: 'https://avatars1.githubusercontent.com/u/1562726?s=200&v=4',
projectLink: 'https://github.com/d3/d3/contribute',
description: 'JavaScript library for visualizing data using web standards',
tags: ['Javascript', 'graph', 'graph-based', 'graph visualization', 'data visualization', 'dynamic plots']
},
{
name: 'FontAwesome',
imageSrc: 'https://avatars1.githubusercontent.com/u/1505683?s=200&v=4',
projectLink: 'https://github.com/FortAwesome/Font-Awesome/contribute',
description: 'The iconic SVG, font, and CSS toolkit',
tags: ['SVG', 'CSS', 'font']
},
{
name: 'TallyCTF',
imageSrc: 'https://raw.githubusercontent.com/CyberNinjas/TallyCTF/master/modules/core/client/img/brand/Tallylogo_1.png',
projectLink: 'https://github.com/CyberNinjas/TallyCTF/contribute',
description: 'Capture-The-Flag Scoreboard & CTF Event Running Software',
tags: ['ctf', 'ctf-scoreboard', 'ctf-platform', 'JavaScript']
},
{
name: 'Airform',
imageSrc: 'https://avatars1.githubusercontent.com/u/24883621',
projectLink: 'https://github.com/airform/airform/contribute',
description: 'Functional HTML forms for Front-End Developers.',
tags: ['airform', 'serverless', 'sendmail', 'mailer', 'html-forms', 'forms', 'smtp', 'sendgrid', 'mailchimp', 'mailgun'],
},
{
name: 'Milligram',
imageSrc: 'https://avatars0.githubusercontent.com/u/16243913',
projectLink: 'https://github.com/milligram/milligram/contribute',
description: 'A minimalist CSS framework.',
tags: ['milligram', 'css', 'html', 'framework', 'css-framework', 'design', 'minimalist', 'flexbox', 'amp'],
},
{
name: 'Gatsby',
imageSrc: 'https://raw.githubusercontent.com/gatsbyjs/gatsby/master/www/static/Gatsby-Monogram.svg',
projectLink: 'https://github.com/gatsbyjs/gatsby/contribute',
description: 'A free and open source framework based on React that helps developers build blazing fast websites and apps.',
tags: ['React', 'Javascript', 'HTML', 'CSS', 'GraphQL', 'Web Development', 'Markdown'],
},
{
name: 'ClickHouse',
imageSrc: 'https://raw.githubusercontent.com/ClickHouse/ClickHouse/master/website/images/logo.png',
projectLink: 'https://github.com/ClickHouse/ClickHouse/contribute',
description: 'Column-oriented database management system that allows generating analytical data reports in real time.',
tags: ['C++', 'C++20', 'cpp', 'Linux', 'DBMS', 'OLAP', 'Analytics', 'SQL', 'Big Data', 'Distributed Database', 'MPP'],
},
{
name: 'Game of Life',
imageSrc: 'https://raw.githubusercontent.com/TroyTae/game-of-life/master/.github/images/favicon.gif',
projectLink: 'https://github.com/TroyTae/game-of-life/contribute',
description: 'Conway\'s game of life web version!',
tags: ['Javascript', 'Typescript', 'Good First Issue'],
},
{
name: 'Mattermost',
imageSrc: 'https://raw.githubusercontent.com/mattermost/mattermost-handbook/3b54c2cd1f823d1ea012ce45d1baa61fb4fbedbc/.gitbook/assets/branding/logo-downloads/mattermost-logo-vertical-blue.png',
projectLink: 'https://github.com/mattermost/mattermost-server/contribute',
description: 'Open source Slack-alternative for DevOps teams',
tags: ['Go', 'Javascript', 'React', 'React Native'],
},
{
name: 'Markdown Dungeon',
imageSrc: 'https://avatars3.githubusercontent.com/u/67384272?v=4',
projectLink: 'https://github.com/MakeContributions/markdown-dungeon#contribution-guidelines',
description: 'This is an example that how to use Markdown creating a dungeon.',
tags: ['Markdown', 'React', 'Gatsby', 'Good First Issue', 'Beginner'],
},
{
name: 'Ansible',
imageSrc: 'https://avatars1.githubusercontent.com/u/1507452?s=200&v=4',
projectLink: 'https://docs.ansible.com/ansible/latest/community/index.html',
description: 'Ansible is a radically simple IT automation platform that makes your applications and systems easier to deploy.',
tags: ['Python', 'Automated-Testingg', 'Beginner'],
},
{
name: 'start-here-guidelines',
imageSrc: 'https://avatars2.githubusercontent.com/u/35373879?s=200&v=4',
projectLink: 'https://github.com/zero-to-mastery/start-here-guidelines#a-guide-to-get-started',
description: 'Lets Git started in the world of opensource, starting in the Zero To Mastery opensource playground. Especially designed for education and practical experience purposes.',
tags: ['Markdown', 'Beginner'],
},
{
name: 'CSS-Art',
imageSrc: 'https://avatars2.githubusercontent.com/u/35373879?s=200&v=4',
projectLink: 'https://github.com/zero-to-mastery/CSS-Art#instructions',
description: 'General Edition - A CSS art challenge, for all skill levels.',
tags: ['CSS', 'HTML', 'Javascript', 'Beginner'],
},
{
name: 'Chat-e2ee',
imageSrc: 'https://repository-images.githubusercontent.com/271544524/44353a80-d451-11ea-815c-594e4a0c5fb8',
projectLink: 'https://github.com/muke1908/chat-e2ee/labels/good%20first%20issue',
description: 'Chat app in end-to-end enctypted environment without registration',
tags: ['React', 'Chat', 'Javascript', 'Beginner', 'NodeJS'],
}
];
export default projectList;
|
"""Unit tests for the skew symmetric matrices."""
import random
import geomstats.backend as gs
from geomstats.geometry.skew_symmetric_matrices import SkewSymmetricMatrices
from tests.conftest import Parametrizer
from tests.data_generation import _MatrixLieAlgebraTestData
from tests.geometry_test_cases import MatrixLieAlgebraTestCase
class TestSkewSymmetricMatrices(MatrixLieAlgebraTestCase, metaclass=Parametrizer):
space = algebra = SkewSymmetricMatrices
class SkewSymmetricMatricesTestData(_MatrixLieAlgebraTestData):
n_list = random.sample(range(2, 5), 2)
space_args_list = [(n,) for n in n_list]
shape_list = [(n, n) for n in n_list]
n_points_list = random.sample(range(2, 5), 2)
n_vecs_list = random.sample(range(2, 5), 2)
def belongs_test_data(self):
smoke_data = [
dict(n=2, mat=[[0.0, -1.0], [1.0, 0.0]], expected=True),
dict(n=3, mat=[[0.0, -1.0], [1.0, 0.0]], expected=False),
]
return self.generate_tests(smoke_data)
def baker_campbell_hausdorff_test_data(self):
n_list = range(3, 10)
smoke_data = []
for n in n_list:
space = SkewSymmetricMatrices(n)
fb = space.basis[0]
sb = space.basis[1]
fb_sb_bracket = space.bracket(fb, sb)
expected1 = fb + sb
expected2 = expected1 + 0.5 * fb_sb_bracket
expected3 = (
expected2
+ 1.0 / 12.0 * space.bracket(fb, fb_sb_bracket)
- 1.0 / 12.0 * space.bracket(sb, fb_sb_bracket)
)
expected4 = expected3 - 1.0 / 24.0 * space.bracket(
sb, space.bracket(fb, fb_sb_bracket)
)
expected = [expected1, expected2, expected3, expected4]
for order in range(1, 5):
smoke_data.append(
dict(
n=n,
matrix_a=fb,
matrix_b=sb,
order=order,
expected=expected[order - 1],
)
)
return self.generate_tests(smoke_data)
def basis_representation_then_matrix_representation_test_data(self):
return self._basis_representation_then_matrix_representation_test_data(
SkewSymmetricMatrices, self.space_args_list, self.n_points_list
)
def matrix_representation_then_basis_representation_test_data(self):
return self._matrix_representation_then_basis_representation_test_data(
SkewSymmetricMatrices, self.space_args_list, self.n_points_list
)
def basis_belongs_test_data(self):
return self._basis_belongs_test_data(self.space_args_list)
def basis_cardinality_test_data(self):
return self._basis_cardinality_test_data(self.space_args_list)
def random_point_belongs_test_data(self):
smoke_space_args_list = [(2,), (3,)]
smoke_n_points_list = [1, 2]
return self._random_point_belongs_test_data(
smoke_space_args_list,
smoke_n_points_list,
self.space_args_list,
self.n_points_list,
)
def projection_belongs_test_data(self):
return self._projection_belongs_test_data(
self.space_args_list, self.shape_list, self.n_points_list
)
def to_tangent_is_tangent_test_data(self):
return self._to_tangent_is_tangent_test_data(
SkewSymmetricMatrices,
self.space_args_list,
self.shape_list,
self.n_vecs_list,
)
def random_tangent_vec_is_tangent_test_data(self):
return self._random_tangent_vec_is_tangent_test_data(
SkewSymmetricMatrices, self.space_args_list, self.n_vecs_list
)
def to_tangent_is_projection_test_data(self):
return self._to_tangent_is_projection_test_data(
SkewSymmetricMatrices,
self.space_args_list,
self.shape_list,
self.n_vecs_list,
)
def random_point_is_tangent_test_data(self):
return self._random_point_is_tangent_test_data(
self.space_args_list, self.n_points_list
)
testing_data = SkewSymmetricMatricesTestData()
def test_belongs(self, n, mat, expected):
skew = self.space(n)
self.assertAllClose(skew.belongs(gs.array(mat)), gs.array(expected))
def test_baker_campbell_hausdorff(self, n, matrix_a, matrix_b, order, expected):
skew = SkewSymmetricMatrices(n)
result = skew.baker_campbell_hausdorff(
gs.array(matrix_a), gs.array(matrix_b), order=order
)
self.assertAllClose(result, gs.array(expected))
|
/*******************************************************************************
*
* (C) COPYRIGHT AUTHORS, 2015 - 2018
*
* TITLE: EXCEPTH.H
*
* VERSION: 1.52
*
* DATE: 08 Jan 2018
*
* Common header file for the exception handling routines.
*
* THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
* ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED
* TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
* PARTICULAR PURPOSE.
*
*******************************************************************************/
#pragma once
INT exceptFilter(
_In_ UINT ExceptionCode,
_In_ EXCEPTION_POINTERS *ExceptionPointers);
|
#!/usr/bin/env python3
import pycrfsuite
import sys
# Inherit crfsuite.Trainer to implement message() function, which receives
# progress messages from a training process.
class Trainer(pycrfsuite.Trainer):
def message(self, s):
# Simply output the progress messages to STDOUT.
sys.stdout.write(s)
def instances(fi):
xseq = []
yseq = []
for line in fi:
line = line.strip('\n')
if not line:
# An empty line means the end of a sentence.
# Return accumulated sequences, and reinitialize.
yield xseq, yseq
xseq = []
yseq = []
continue
# Split the line with TAB characters.
fields = line.split('\t')
# Append the item features to the item sequence.
# fields are: 0=sid, 1=form, 2=span_start, 3=span_end, 4=tag, 5...N = features
item = fields[5:]
xseq.append(item)
# Append the label to the label sequence.
yseq.append(fields[4])
if __name__ == '__main__':
# Create a Trainer object.
trainer = Trainer()
# Read training instances from STDIN, and append them to the trainer.
for xseq, yseq in instances(sys.stdin):
trainer.append(xseq, yseq, 0)
# Use L2-regularized SGD and 1st-order dyad features.
trainer.select('l2sgd', 'crf1d')
# This demonstrates how to list parameters and obtain their values.
for name in trainer.params():
print (name, trainer.get(name), trainer.help(name))
# Set the coefficient for L2 regularization to 0.1
trainer.set('feature.minfreq', 1)
trainer.set('c2', 0.1)
# Start training; the training process will invoke trainer.message()
# to report the progress.
trainer.train(sys.argv[1], -1)
|
#include <conf.h>
#include <news.h>
#include <flags.h>
#include <security.h>
#include <daemons.h>
#include <objects.h>
#include <ansi.h>
#include <pwgen.h>
nosave private int __CrackCount;
nosave private string __Name;
nosave private object __Player;
nosave private string subname, xyz, __ob_name;
nosave private int flag = 0;
nosave private int __LoginTimeBuffer;
void create()
{
seteuid(UID_ROOT);
__Name = "";
__CrackCount = 0;
__Player = 0;
}
protected void logon()
{
int Z, ttl;
if (time() < __LoginTimeBuffer) {
message("logon", "Please wait one second, login time buffer in effect.", TO);
internal_remove();
return;
}
__LoginTimeBuffer = time() + 1;
if (catch(__Player = new(OB_USER))) {
if (catch(__Player = new("/adm/failsafe/user_failsafe"))) {
message("logon", "Someone appears to be messing with the user object.\n"
"Please try again in a few minutes.\n", this_object());
internal_remove();
return;
}
}
if (!((int)BANISH_D->block_access(query_ip_number()))) {
message("logon", read_file("/news/_ip_banished"), this_object());
internal_remove();
return;
}
message("logon", read_file(WELCOME), this_object());
message("logon", "\n", this_object());
if ("/adm/daemon/shutdown_d.c"->shuttingDown()) {
ttl = "/adm/daemon/shutdown_d.c"->query_time_left();
if(ttl > 0)
message("logon", "\n<<< The MUD will be rebooting. Reboot in "+ttl/60+" minute(s)! >>>\n", this_object());
else {
message("logon", "\n<<< The MUD will reboot in under a minute! >>>\n", this_object());
message("logon", "\n<<< Please consider waiting for a minute for the game to boot properly!!! >>>\n", this_object());
}
}
call_out("idle", LOGON_TIMEOUT);
call_out("internal_remove", LOGON_TIMEOUT * 10);
message("logon", " Host: shadowgate.org\n Ports: 8080, 8443 (SSL)\n", this_object());
message("logon", " E-mail: [email protected]\n", this_object());
message("logon", " This game is for adults (18+)", this_object());
message("logon", "\n",this_object());
message("logon", "\nWhat name do you choose? ", this_object());
input_to("get_name");
}
protected void get_name(string str) {
if (!str || str == "") {
message("logon", "\nInvalid entry. Please try again.\n", this_object());
internal_remove();
return;
}
__Name = lower_case(str);
if ("/adm/obj/master.c"->is_locked()) {
message("logon", read_file(LOCKED_NEWS), this_object());
if (locked_access())
message("logon", "\n >>> Access allowed <<<\n", this_object());
else {
message("logon", "\n >>> Access denied <<<\n", this_object());
internal_remove();
return;
}
}
if (!user_exists(__Name)) {
if (file_exists("/adm/save/users/arrest/"+__Name+".o")) {
message("logon",read_file("/news/_arrested"),this_object());
internal_remove();
}
if (file_size("/realms/" + __Name) == -2) {
message("logon",read_file("/news/_lost_wiz"),this_object());
internal_remove();
}
if (!((int)BANISH_D->valid_name(__Name))) {
message("logon", sprintf("\n%s is not a valid name choice for %s.\n",
capitalize(__Name), mud_name()), this_object());
message("logon", sprintf("Names must be alphabetic characters no "
"longer than %d letters,\nand no less than %d letters.\n",
MAX_USER_NAME_LENGTH, MIN_USER_NAME_LENGTH), this_object());
message("logon", "\nPlease enter another name: ", this_object());
input_to("get_name");
return;
}
if (!((int)BANISH_D->allow_logon(__Name, query_ip_number()))) {
message("logon",read_file("/news/_register"), this_object());
internal_remove();
return;
}
if (!MULTI_D->is_allowed(__Name)) {
log_file("adm/linked_denial",sprintf("%s at %s from %s\n",__Name,ctime(time()),query_ip_number()));
message("logon", read_file("/news/_link"), this_object());
internal_remove();
}
if (find_player(__Name) && interactive(find_player(__Name))) {
message("logon", sprintf("That character is already being created. Please try again later."), this_object());
internal_remove();
}
message("logon", read_file("/news/newname"), this_object());
message("logon", sprintf("Do you really wish %s to be your name? (y/n) ",
capitalize(__Name)), this_object());
input_to("new_user");
return;
}
if (!((int)BANISH_D->allow_logon(__Name, query_ip_number()))) {
message("logon", read_file("/news/register"), this_object());
internal_remove();
return;
}
if (!MULTI_D->is_allowed(__Name)) {
log_file("adm/linked_denial",sprintf("%s at %s from %s\n",__Name,ctime(time()),query_ip_number()));
message("logon", read_file("/news/_link"), this_object());
internal_remove();
}
message("logon", "Password: ", this_object());
input_to("get_password", I_NOECHO | I_NOESC);
}
void get_password(string str) {
if (!str || str == "")
{
message("logon", "\nYou must enter a password. Try again later.\n",
this_object());
internal_remove();
return;
}
if (!check_password(str))
{
message("logon", "\nInvalid password.\n", this_object());
log_file("player/bad_password",sprintf("%s at %s from %s\n",__Name,ctime(time()),query_ip_number()), 1);
if (++__CrackCount > MAX_PASSWORD_TRIES) {
message("logon", "No more attempts allowed.\n", this_object());
internal_remove();
return;
}
destruct(__Player);
__Player = new(OB_USER);
str = 0;
message("logon", "Password: ", this_object());
input_to("get_password", I_NOECHO | I_NOESC);
return;
}
str = 0;
master()->load_player_from_file(__Name, __Player);
seteuid(UID_LOG);
log_file("player/logon", sprintf("%s from %s at %s\n",__Name,query_ip_number(),ctime(time())), 1);
seteuid(getuid());
if (!is_copy()) exec_user();
}
protected int locked_access() {
int i;
string fore, aft;
if (sscanf(__Name, "%s@%s", fore, aft) == 2)
if ((int)BANISH_D->is_guest(fore))
return 1;
if ((int)BANISH_D->is_guest(__Name)) return 1;
i = sizeof(LOCKED_ACCESS_ALLOWED);
while (i--) if (member_group(__Name, LOCKED_ACCESS_ALLOWED[i])) return 1;
return 0;
}
protected int check_password(string str)
{
string pass;
master()->load_player_from_file(__Name, __Player);
if ((pass = (string)__Player->query_password()) != crypt(str, pass)) {
return 0;
}
if ((__Player->query_password())[0..2] != "$6$") {
message("logon", "\n\n Your password is too old, upgrade it as soon as you can.\n\n", this_object());
}
return valid_site(query_ip_number());
__Player->remove();
}
protected int valid_site(string ip) {
string a, b;
string *miens;
int i;
if (!(i = sizeof(miens = (string *)__Player->query_valid_sites()))) return 1;
while (i--) {
if (ip == miens[i]) return 1;
if (sscanf(miens[i], "%s.*s", a) && sscanf(ip, a+"%s", b)) return 1;
}
return 0;
}
protected int is_copy() {
object ob;
if (!(ob = find_player(__Name))) return 0;
if (interactive(ob)) {
message("logon", "\nThere currently exists an interactive copy of you.\n",
this_object());
message("logon", "Do you wish to take over this interactive copy? (y/n) ",
this_object());
input_to("disconnect_copy", I_NORMAL, ob);
return 1;
}
seteuid(UID_LOG);
log_file("player/enter", sprintf("%s (exec): %s\n", __Name, ctime(time())));
seteuid(getuid());
if (exec(ob, this_object())) ob->restart_heart();
else message("logon", "Problem reconnecting.\n", this_object());
internal_remove();
return 1;
}
protected void disconnect_copy(string str, object ob) {
object tmp;
if (str == "") {
is_copy();
return;
}
if ((str = lower_case(str)) == "" || str[0] != 'y') {
message("logon", "\nThen please try again later!\n", this_object());
internal_remove();
return;
}
message("info", "Another person is connecting with your name and password. If this is "+
"not you, please notify a member of LAW immediately and change your password with the "+
"passwd command!", ob);
if(ob->query_property("inactive")) ob->remove_property("inactive");
tmp = new(OB_USER);
exec(tmp, ob);
exec(ob, this_object());
destruct(tmp);
message("logon", "\nAllowing relog.\n", ob);
internal_remove();
}
protected void exec_user()
{
__Player->set_name(__Name);
if (!exec(__Player, this_object())) {
message("logon", "\Problem connecting.\n", this_object());
internal_remove();
return;
}
__Player->setup();
if (member_array("neck", __Player->query_limbs()) == -1) {
__Player->add_limb("neck", "neck", __Player->query_max_hp(), 0, 0);
}
destruct(this_object());
}
protected void new_user(string str) {
if ((str = lower_case(str)) == "" || str[0] != 'y') {
message("logon", "\nOk, then enter the name you really want: ", this_object());
input_to("get_name");
return;
}
message("logon", "Please choose a password of at least 6 characters: ", this_object());
input_to("choose_password", I_NOECHO | I_NOESC);
}
protected void choose_password(string str) {
if (strlen(str) < 6) {
message("logon", "\nYour password must be at least 6 characters long.\n",
this_object());
message("logon", "Please choose another password: ", this_object());
input_to("choose_password", I_NOECHO | I_NOESC);
}
message("logon", "\nPlease confirm your password choice: ", this_object());
input_to("confirm_password", I_NOECHO | I_NOESC, str);
}
protected void confirm_password(string str2, string str1)
{
string salt;
salt = PWGEN->random_salt(43);
if (str1 == str2) {
__Player->set_password(str2 = crypt(str2, "$6$"+salt));
message("logon",
"
Ccolor adds much to your enjoyment of playing. The following is a
color test. If you see color, then you support it. If you see garbage,
then you do NOT support it. If you don't see color and you don't see
garbage, then allowing color would still probably be a wise decision.
"
, this_object());
message("logon","Color test: "+HIM+"A"+HIG+"N"+HIC+"S"+HIR+"I"+BLU+
" test"+NOR+"\n\n", this_object());
message("logon","That should have read 'ANSI test' in multiple colors.\n"+
"Do you support colors? [y/n]: ", this_object());
input_to("ansi_test");
} else {
message("logon", "\nPassword entries do not match. Choose a password: ",
this_object());
input_to("choose_password", I_NOECHO | I_NOESC);
return;
}
}
protected void ansi_test(string str) {
str=capitalize(str);
if (str != "Y" && str != "N") {
message("logon", "\nPlease enter Y for yes, or N for no.\n",
this_object());
message("logon", "Do you support ANSI? [y/n]: ", this_object());
input_to("ansi_test");
return;
}
if (str == "Y") {
message("logon", "\nANSI supported turned on. Use 'set term default' to turn it off later in the game.\n",this_object());
__Player->setenv("TERM","ansi");
__Player->reset_terminal();
}
if (str =="N") {
message("logon", "\nANSI supported turned off. Use <set term "+
"ansi> to turn it on later in the game.\n",this_object());
__Player->setenv("TERM","default");
__Player->reset_terminal();
}
__Player->set_gender("other");
__Player->set_rname("Unknown");
__Player->set_email(" ");
seteuid(UID_LOG);
log_file("player/enter", sprintf("%s (new player): %s\n", __Name, ctime(time())));
log_file("player/new_players",sprintf("%s(%s) <%s> at %s from %s\n",__Name, str, __Player->query_email(),ctime(time()),query_ip_number()));
seteuid(getuid());
exec_user();
return;
}
protected void idle()
{
if (interactive(TO)) {
message("logon", "\nLogin timed out.\n", this_object());
}
internal_remove();
}
protected void receive_message(string cl, string msg)
{
mapping TermInfo;
if (cl != "logon") {
return;
}
if (!stringp(msg)) {
return;
}
TermInfo = USER_D->myTerm(TO, 1);
msg = terminal_colour(msg, TermInfo, 140, 0);
receive(msg);
}
protected void internal_remove()
{
if (__Player) {
destruct(__Player);
}
destruct(this_object());
}
void remove()
{
if (geteuid(previous_object()) != UID_ROOT) {
return;
}
internal_remove();
}
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
sys.path.append('../../../')
from rusentrel.rusentrel_ds.mi.lstm import run_testing_mi_rnn
from rusentrel.rusentrel_ds_cv.common import CV_COUNT, \
ds_cv_common_callback_modification_func, \
CV_DS_NAME_PREFIX
if __name__ == "__main__":
run_testing_mi_rnn(
cv_count=CV_COUNT,
name_prefix=CV_DS_NAME_PREFIX,
common_callback_func=ds_cv_common_callback_modification_func) |
import contractsApi from '@/api/contracts.api';
import catalog from '@/store/modules/base/catalog.store';
import Vue from "vue";
const contractsCatalog = catalog(contractsApi, 'contracts');
const state = {
suppliers : [],
administrativeUnits : []
};
const getters = {
};
const actions = {
/**
* Retrieves suppliers from DB to make them available at selection
*/
getSuppliers({commit}){
contractsApi.retrieveSuppliers({},
(result)=>{
commit('SET_SUPPLIERS', result.data.data.docs);
})
},
/**
* Retrieves suppliers from DB to make them available at selection
*/
getAdministrativeUnits({commit}){
contractsApi.retrieveAdministrativeUnits({},
(result)=>{
commit('SET_ADMINISTRATIVE_UNITS', result.data.data.docs);
})
}
};
const mutations = {
SET_SUPPLIERS(state, suppliers){
state.suppliers = suppliers;
},
SET_ADMINISTRATIVE_UNITS(state, administrativeUnits){
state.administrativeUnits = administrativeUnits;
}
};
export default {
namespaced: true,
state: {
...contractsCatalog.state,
...state
},
getters: {
...contractsCatalog.getters,
...getters
},
actions: {
...contractsCatalog.actions,
...actions
},
mutations: {
...contractsCatalog.mutations,
...mutations
}
}; |
import logging
logger = logging.getLogger(__name__)
class OVOException(Exception):
"""Generic error class, catch-all for most client issues.
"""
def __init__(self, msg, code=None, error_response={}):
self.code = code or 0
self.error_response = error_response
super(OVOException, self).__init__(msg)
class OVOTimeoutException(OVOException):
"""Raised when login fails."""
pass
class OVOBadRequest(OVOException):
"""Raised when login fails."""
pass
class InvalidPhoneNumberException(OVOException):
"""Raised when login fails."""
pass |
var annotated =
[
[ "SmartOptions", "classSmartOptions.html", "classSmartOptions" ]
]; |
// Define our eval outside of the scope of any other reference defined in this
// file to avoid adding those references to the evaluation scope.
function __eval(__source, __global, __load) {
try {
eval('(function() { var __moduleName = "' + (__load.name || '').replace('"', '\"') + '"; ' + __source + ' \n }).call(__global);');
}
catch(e) {
if (e.name == 'SyntaxError' || e.name == 'TypeError')
e.message = 'Evaluating ' + (__load.name || load.address) + '\n\t' + e.message;
throw e;
}
}
})(typeof window != 'undefined' ? window : (typeof WorkerGlobalScope != 'undefined' ?
self : global));
|
Package.describe({
summary: "Login service for Twitter accounts",
version: "1.1.12"
});
Package.onUse(function(api) {
api.use('underscore', ['server']);
api.use('accounts-base', ['client', 'server']);
// Export Accounts (etc) to packages using this one.
api.imply('accounts-base', ['client', 'server']);
api.use('accounts-oauth', ['client', 'server']);
api.use('twitter', ['client', 'server']);
api.use('http', ['client', 'server']);
api.addFiles('twitter_login_button.css', 'client');
api.addFiles("twitter.js");
});
|
require("core-js/modules/es7.string.pad-start");
|
#!/usr/bin/python
"""
Rescale baseline density files, Nring(u), into n(x) = n(u=d/lambda) / lambda^2,
which is approx. const. with frequency (and x = u / nu).
"""
import numpy as np
import pylab as P
import scipy.integrate
import scipy.interpolate
import os, sys
def process_baseline_file(fname):
"""
Process one of Prina's SKA n(u) files and output n(d), which can then be
converted into a freq.-dep. n(u).
"""
# Extract info. about baseline file
fname_end = fname.split("/")[-1]
tmp = fname_end.split("_")
freq = float(tmp[1]) / 1e6 # Freq., MHz
dec = float(tmp[2][3:]) # Declination, degrees
ts = float(tmp[3].split("sec")[0]) # Single baseline integ. time, in sec
if len(tmp) == 6:
du = float(tmp[5][2:-4]) # u bin width, ~1/sqrt(fov)
else:
du = float(tmp[4][2:-4]) # u bin width, ~1/sqrt(fov)
# Output information about this datafile
print "-"*50
print "Filename:", fname
print "-"*50
print "Ndish: ", Ndish
print "Freq.: ", freq, "MHz"
print "Dec.: ", dec, "deg"
print "t_s: ", ts, "sec"
print "du: ", du
print "-"*50
# Load datafile and convert to density (don't need bin centres; just use edges)
u, Nring = np.genfromtxt(fname).T
n = Nring / (2.*np.pi * u * du) / (24.*3600. / ts) # Eq. 18 of Mario's notes
print "\n\n\n"
print "u", u[:10]
print "n", n[:10]
print "N", Nring[:10]
print "\n\n\n"
# Remove leading zeros (or other special values), if any, to ensure
# interpolation has a sharp cut at u_min
minidx = None; jj = -1
while minidx is None:
jj += 1
if (n[jj] != 0.) and (not np.isnan(n[jj])) and (not np.isinf(n[jj])):
minidx = jj
print minidx
u = u[minidx:]
n = n[minidx:]
print "\n\n\n"
print "u", u[:10]
print "n", n[:10]
print "N", Nring[:10]
print "\n\n\n"
# Integrate n(u) to find normalisation (should be N_dish^2)
norm = scipy.integrate.simps(2.*np.pi*n*u, u)
print "Renormalising n(u) by factor of", 0.5 * Ndish * (Ndish - 1) / norm
n *= 0.5 * Ndish * (Ndish - 1) / norm
# Convert to freq.-independent expression, n(x) = n(u) * nu^2,
# where nu is in MHz.
n_x = n * freq**2.
x = u / freq
return x, n_x
infile1 = "array_config/SKAMREF2_minu/SKAMREF2_1.01e9_dec90_60sec.MS_bin34.3950_du7.75667.txt"
infile2 = "array_config/SKAMREF2_du/SKAMREF2_1.01e9_dec90_60sec.MS_du7.75667.txt"
infile3 = "array_config/SKAMREF2COMP_minu/SKAMREF2COMP_1.01e9_dec90_60sec.MS_bin60.0230_du7.75667.txt"
infile4 = "array_config/SKAMREF2COMP_du/SKAMREF2COMP_1.01e9_dec90_60sec.MS_du7.75667.txt"
dat1 = np.genfromtxt(infile1).T
dat2 = np.genfromtxt(infile2).T
dat3 = np.genfromtxt(infile3).T
dat4 = np.genfromtxt(infile4).T
"""
print "***** minu:", dat1[0,:6]
print " ", dat1[1,:6]
print "***** du__:", dat2[0,:6]
print " ", dat2[1,:6]
print "***** minu:", dat3[0,6:12]
print " ", dat3[1,6:12]
print "***** du__:", dat4[0,6:12]
print " ", dat4[1,6:12]
"""
# Process input file
Ndish = 254
x1, n_x1 = process_baseline_file(infile1)
x2, n_x2 = process_baseline_file(infile2)
x3, n_x3 = process_baseline_file(infile3)
x4, n_x4 = process_baseline_file(infile4)
# Interpolate n(u)
interp1 = scipy.interpolate.interp1d( x1, n_x1, kind='linear',
bounds_error=False, fill_value=0. )
interp2 = scipy.interpolate.interp1d( x2, n_x2, kind='linear',
bounds_error=False, fill_value=0. )
interp3 = scipy.interpolate.interp1d( x3, n_x3, kind='linear',
bounds_error=False, fill_value=0. )
interp4 = scipy.interpolate.interp1d( x4, n_x4, kind='linear',
bounds_error=False, fill_value=0. )
P.subplot(211)
ii = 30
P.plot(dat1[0][:ii], dat1[1][:ii], marker='.', label="SKAMREF2_minu")
P.plot(dat2[0][:ii], dat2[1][:ii], marker='.', label="SKAMREF2_du")
P.plot(dat3[0][:ii], dat3[1][:ii], marker='.', label="SKAMREF2COMP_minu")
P.plot(dat4[0][:ii], dat4[1][:ii], marker='.', label="SKAMREF2COMP_du", color='y')
#for i in range(ii): P.axvline(dat1[0][i], color='b', alpha=0.4)
#for i in range(ii): P.axvline(dat2[0][i], color='g', alpha=0.4)
#for i in range(ii): P.axvline(dat3[0][i], color='r', alpha=0.4)
#for i in range(ii): P.axvline(dat4[0][i], color='y', alpha=0.4)
P.xlabel(r"$u$", fontsize=20)
P.ylabel(r"$N_\mathrm{ring}$", fontsize=20)
#P.xscale('log')
#P.yscale('log')
P.legend(loc='upper right')
P.subplot(212)
P.plot(x1[:ii], n_x1[:ii], 'b.')
P.plot(x2[:ii], n_x2[:ii], 'g.')
P.plot(x3[:ii], n_x3[:ii], 'r.')
P.plot(x4[:ii], n_x4[:ii], 'y.')
xx = np.linspace(0., x4[ii], 1000)
P.plot(xx, interp1(xx), 'b-', alpha=0.5)
P.plot(xx, interp2(xx), 'g-', alpha=0.5)
P.plot(xx, interp3(xx), 'r-', alpha=0.5)
P.plot(xx, interp4(xx), 'y-', alpha=0.5)
P.xlabel(r"$x = u / \nu$", fontsize=20)
P.ylabel(r"$n^\prime(x) = n(u) \nu^2$", fontsize=20)
P.ylim((-1., 1.9e4))
#P.xscale('log')
#P.yscale('log')
P.show()
# Output to disk
#np.savetxt(outfile, np.column_stack((x, n_x)))
#print "Done."
|
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import Vuex from 'vuex'
import './assets/style/reset.css'
import Vant from 'vant';
import 'vant/lib/index.css';
createApp(App).use(store).use(router).use(Vuex).use(Vant).mount('#app') |
import axios from 'axios';
import router from '../src/router';
import Vue from 'vue';
export function request(config) {
const instance = axios.create({
baseURL: 'http://localhost:3000',
timeout: 5000
})
//请求(成功、失败)拦截
instance.interceptors.request.use(config => {
//vuex的方式
// console.log(" store jwt: " + store.getters.currentUser.usertoken)
// if (store.getters.currentUser.usertoken) {
// // config.headers['X-Token'] = getToken()
// // 因为是jwt方式鉴权 所以在header头中改为如下写法
// // config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
// }
// 本地存储方式取出
let token = localStorage.getItem('currentUser_token')
if (token) {
config.headers.Authorization = 'Bearer ' + token; //将token设置成请求头
// config.headers['X-Token'] = getToken()
// 因为是jwt方式鉴权 所以在header头中改为如下写法
// config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
}
return config;
}, err => {
})
// 响应(成功、失败)拦截
instance.interceptors.response.use(res => {
if (res.data.message == '登陆过期,请重新登陆') {
localStorage.removeItem('admin_id');
localStorage.removeItem('admin_name');
localStorage.removeItem('gender');
localStorage.removeItem('phone');
localStorage.removeItem('currentUser_token');
Vue.prototype.$message.error(res.data.message);
router.push('/');
}
return res.data;
}, err => {
console.log(err);
})
return instance(config);
}
|
import React from "react";
import IndividualDisease from "./IndividualDisease";
export default function YellowLCV() {
const post = {
heading: "Bacterial Spot of Tomato",
subheading1: "What is bacterial spot?",
content1:
" Bacterial spot can affect all above ground parts of a tomato plant , including the leaves, stems, and fruit. Bacterial spot appears on leaves as small (less than ⅛ inch), sometimes water-soaked (i.e., wet-looking) circular areas. Spots may initially be yellow-green, but darken to brownish-red as they age. When the disease is severe, extensive leaf yellowing and leaf loss can also occur. On green fruit, spots are typically small, raised and blister-like, and may have a yellowish halo. As fruit mature, the spots enlarge (reaching a maximum size of ¼ inch) and turn brown, scabby and rough. Mature spots may be raised, or sunken with raised edges. Bacterial spot symptoms can be easily confused with symptoms of another tomato disease called bacterial speck. For more information on this disease, see University of Wisconsin Garden Facts XHT1250.",
subheading2: "What does bacterial spot look like?",
content2:
"Bacterial spot can affect all above ground parts of a tomato plant, including the leaves, stems, and fruit. Bacterial spot appears on leaves as small (less than ⅛ inch), sometimes water-soaked (i.e., wet-looking) circular areas. Spots may initially be yellow-green, but darken to brownish-red as they age. When the disease is severe, extensive leaf yellowing and leaf loss can also occur. On green fruit, spots are typically small, raised and blister-like, and may have a yellowish halo. As fruit mature, the spots enlarge (reaching a maximum size of ¼ inch) and turn brown, scabby and rough. Mature spots may be raised, or sunken with raised edges. Bacterial spot symptoms can be easily confused with symptoms of another tomato disease called bacterial speck. For more information on this disease, see University of Wisconsin Garden Facts XHT1250.",
subheading3: "What does bacterial spot look like?",
content3:
"Bacterial spot can affect all above ground parts of a tomato plant, including the leaves, stems, and fruit. Bacterial spot appears on leaves as small (less than ⅛ inch), sometimes water-soaked (i.e., wet-looking) circular areas. Spots may initially be yellow-green, but darken to brownish-red as they age. When the disease is severe, extensive leaf yellowing and leaf loss can also occur. On green fruit, spots are typically small, raised and blister-like, and may have a yellowish halo. As fruit mature, the spots enlarge (reaching a maximum size of ¼ inch) and turn brown, scabby and rough. Mature spots may be raised, or sunken with raised edges. Bacterial spot symptoms can be easily confused with symptoms of another tomato disease called bacterial speck. For more information on this disease, see University of Wisconsin Garden Facts XHT1250.",
subheading4: "How do I save plants with bacterial spot?",
content4:
"A plant with bacterial spot cannot be cured. Remove symptomatic plants from the field or greenhouse to prevent the spread of bacteria to healthy plants. Burn, bury or hot compost the affected plants and DO NOT eat symptomatic fruit. Although bacterial spot pathogens are not human pathogens, the fruit blemishes that they cause can provide entry points for human pathogens that could cause illness.",
subheading5: "How can I prevent bacterial spot in the future?",
content5:
"Plant pathogen-free seed or transplants to prevent the introduction of bacterial spot pathogens on contaminated seed or seedlings. If a clean seed source is not available or you suspect that your seed is contaminated, soak seeds in water at 122°F for 25 min. to kill the pathogens. To keep leaves dry and to prevent the spread of the pathogens, avoid overhead watering (e.g., with a wand or sprinkler) of established plants and instead use a drip-tape or soaker-hose. Also to prevent spread, DO NOT handle plants when they are wet (e.g., from dew) and routinely sterilize tools with either 10% bleach solution or (better) 70% alcohol (e.g., rubbing alcohol). Where bacterial spot has been a recurring problem, consider using preventative applications of copper-based products registered for use on tomato, especially during warm, wet periods. Keep in mind however, that if used excessively or for prolonged periods, copper may no longer control the disease. Be sure to read and follow all label instructions of the product that you select to ensure that you use it in the safest and most effective manner possible. Burn, bury or hot compost tomato debris at the end of the season. Wait at least one year before planting tomatoes in a given location again, and remove and burn, bury or hot compost any volunteer tomatoes that come up in your garden.",
};
return <IndividualDisease post={post} />;
}
|
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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 io
import os
import setuptools # type: ignore
version = '0.1.0'
package_root = os.path.abspath(os.path.dirname(__file__))
readme_filename = os.path.join(package_root, 'README.rst')
with io.open(readme_filename, encoding='utf-8') as readme_file:
readme = readme_file.read()
setuptools.setup(
name='google-cloud-eventarc',
version=version,
long_description=readme,
packages=setuptools.PEP420PackageFinder.find(),
namespace_packages=('google', 'google.cloud'),
platforms='Posix; MacOS X; Windows',
include_package_data=True,
install_requires=(
'google-api-core[grpc] >= 1.27.0, < 3.0.0dev',
'libcst >= 0.2.5',
'proto-plus >= 1.15.0',
'packaging >= 14.3', ),
python_requires='>=3.6',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Topic :: Internet',
'Topic :: Software Development :: Libraries :: Python Modules',
],
zip_safe=False,
)
|
#!/usr/bin/env python
import pytest
"""
Test 2057. Smallest Index With Equal Value
"""
@pytest.fixture(scope="session")
def init_variables_2057():
from src.leetcode_2057_smallest_index_with_equal_value import Solution
solution = Solution()
def _init_variables_2057():
return solution
yield _init_variables_2057
class TestClass2057:
def test_solution_0(self, init_variables_2057):
assert init_variables_2057().smallestEqual([0, 1, 2]) == 0
def test_solution_1(self, init_variables_2057):
assert init_variables_2057().smallestEqual([4, 3, 2, 1]) == 2
def test_solution_2(self, init_variables_2057):
assert init_variables_2057().smallestEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) == -1
def test_solution_3(self, init_variables_2057):
assert init_variables_2057().smallestEqual([2, 1, 3, 5, 2]) == 1
|
"use strict";var precacheConfig=[["/index.html","d0ea3cc9a351bd3aad234c08566a06b8"],["/static/css/main.52a67cdc.css","a5d9093208b763aa7a54d92cc43422a2"],["/static/js/main.00d04584.js","dda5ac7d6c4909c038efb42104691e63"]],cacheName="sw-precache-v3-sw-precache-webpack-plugin-"+(self.registration?self.registration.scope:""),ignoreUrlParametersMatching=[/^utm_/],addDirectoryIndex=function(e,t){var n=new URL(e);return"/"===n.pathname.slice(-1)&&(n.pathname+=t),n.toString()},cleanResponse=function(t){return t.redirected?("body"in t?Promise.resolve(t.body):t.blob()).then(function(e){return new Response(e,{headers:t.headers,status:t.status,statusText:t.statusText})}):Promise.resolve(t)},createCacheKey=function(e,t,n,r){var a=new URL(e);return r&&a.pathname.match(r)||(a.search+=(a.search?"&":"")+encodeURIComponent(t)+"="+encodeURIComponent(n)),a.toString()},isPathWhitelisted=function(e,t){if(0===e.length)return!0;var n=new URL(t).pathname;return e.some(function(e){return n.match(e)})},stripIgnoredUrlParameters=function(e,n){var t=new URL(e);return t.hash="",t.search=t.search.slice(1).split("&").map(function(e){return e.split("=")}).filter(function(t){return n.every(function(e){return!e.test(t[0])})}).map(function(e){return e.join("=")}).join("&"),t.toString()},hashParamName="_sw-precache",urlsToCacheKeys=new Map(precacheConfig.map(function(e){var t=e[0],n=e[1],r=new URL(t,self.location),a=createCacheKey(r,hashParamName,n,/\.\w{8}\./);return[r.toString(),a]}));function setOfCachedUrls(e){return e.keys().then(function(e){return e.map(function(e){return e.url})}).then(function(e){return new Set(e)})}self.addEventListener("install",function(e){e.waitUntil(caches.open(cacheName).then(function(r){return setOfCachedUrls(r).then(function(n){return Promise.all(Array.from(urlsToCacheKeys.values()).map(function(t){if(!n.has(t)){var e=new Request(t,{credentials:"same-origin"});return fetch(e).then(function(e){if(!e.ok)throw new Error("Request for "+t+" returned a response with status "+e.status);return cleanResponse(e).then(function(e){return r.put(t,e)})})}}))})}).then(function(){return self.skipWaiting()}))}),self.addEventListener("activate",function(e){var n=new Set(urlsToCacheKeys.values());e.waitUntil(caches.open(cacheName).then(function(t){return t.keys().then(function(e){return Promise.all(e.map(function(e){if(!n.has(e.url))return t.delete(e)}))})}).then(function(){return self.clients.claim()}))}),self.addEventListener("fetch",function(t){if("GET"===t.request.method){var e,n=stripIgnoredUrlParameters(t.request.url,ignoreUrlParametersMatching),r="index.html";(e=urlsToCacheKeys.has(n))||(n=addDirectoryIndex(n,r),e=urlsToCacheKeys.has(n));var a="/index.html";!e&&"navigate"===t.request.mode&&isPathWhitelisted(["^(?!\\/__).*"],t.request.url)&&(n=new URL(a,self.location).toString(),e=urlsToCacheKeys.has(n)),e&&t.respondWith(caches.open(cacheName).then(function(e){return e.match(urlsToCacheKeys.get(n)).then(function(e){if(e)return e;throw Error("The cached response that was expected is missing.")})}).catch(function(e){return console.warn('Couldn\'t serve response for "%s" from cache: %O',t.request.url,e),fetch(t.request)}))}}); |
# 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.
"""Formatters."""
import logging
from pythonjsonlogger import jsonlogger
DEFAULT_FORMAT = (
"%(asctime)s [%(process)d] %(color)s%(levelname)-8.8s "
"%(name)s: %(message)s%(color_stop)s"
)
DEFAULT_EXTRAS_FORMAT = (
"%(asctime)s [%(process)d] %(color)s%(levelname)-8.8s "
"%(name)s%(extras)s: %(message)s%(color_stop)s"
)
class ColorFormatter(logging.Formatter):
"""Colorizes log output."""
# TODO(jd) Allow configuration
LEVEL_COLORS = {
logging.DEBUG: "\033[00;32m", # GREEN
logging.INFO: "\033[00;36m", # CYAN
logging.WARN: "\033[01;33m", # BOLD YELLOW
logging.ERROR: "\033[01;31m", # BOLD RED
logging.CRITICAL: "\033[01;31m", # BOLD RED
}
COLOR_STOP = "\033[0m"
def add_color(self, record):
"""Add color to a record."""
if getattr(record, "_stream_is_a_tty", False):
record.color = self.LEVEL_COLORS[record.levelno]
record.color_stop = self.COLOR_STOP
else:
record.color = ""
record.color_stop = ""
def remove_color(self, record):
"""Remove color from a record."""
del record.color
del record.color_stop
def format(self, record):
"""Format a record."""
self.add_color(record)
s = super(ColorFormatter, self).format(record)
self.remove_color(record)
return s
class ExtrasFormatter(logging.Formatter):
"""Formats extra keywords into %(extras)s placeholder.
Any keywords passed to a logging call will be formatted into a
"extras" string and included in a logging message.
Example:
logger.info('my message', extra='keyword')
will cause an "extras" string of:
[extra: keyword]
to be inserted into the format in place of %(extras)s.
The optional `keywords` argument must be passed into the init
function to enable this functionality. Without it normal daiquiri
formatting will be applied. Any keywords included in the
`keywords` parameter will not be included in the "extras" string.
Special keywords:
keywords
A set of strings containing keywords to filter out of the
"extras" string.
extras_template
A format string to use instead of '[{0}: {1}]'
extras_separator
What string to "join" multiple "extras" with.
extras_prefix and extras_suffix
Strings which will be prepended and appended to the "extras"
string respectively. These will only be prepended if the
"extras" string is not empty.
"""
def __init__(
self,
keywords=None,
extras_template="[{0}: {1}]",
extras_separator=" ",
extras_prefix=" ",
extras_suffix="",
*args,
**kwargs
):
self.keywords = set() if keywords is None else keywords
self.extras_template = extras_template
self.extras_separator = extras_separator
self.extras_prefix = extras_prefix
self.extras_suffix = extras_suffix
super(ExtrasFormatter, self).__init__(*args, **kwargs)
def add_extras(self, record):
if not hasattr(record, "_daiquiri_extra_keys"):
record.extras = ""
return
extras = self.extras_separator.join(
self.extras_template.format(k, getattr(record, k))
for k in record._daiquiri_extra_keys
if k != "_daiquiri_extra_keys" and k not in self.keywords
)
if extras != "":
extras = self.extras_prefix + extras + self.extras_suffix
record.extras = extras
def remove_extras(self, record):
del record.extras
def format(self, record):
self.add_extras(record)
s = super(ExtrasFormatter, self).format(record)
self.remove_extras(record)
return s
class ColorExtrasFormatter(ColorFormatter, ExtrasFormatter):
"""Combines functionality of ColorFormatter and ExtrasFormatter."""
def format(self, record):
self.add_color(record)
s = ExtrasFormatter.format(self, record)
self.remove_color(record)
return s
class DatadogFormatter(jsonlogger.JsonFormatter):
def __init__(self):
super(DatadogFormatter, self).__init__(timestamp=True)
def add_fields(self, log_record, record, message_dict):
super(DatadogFormatter, self).add_fields(log_record, record, message_dict)
log_record["status"] = record.levelname.lower()
log_record["logger"] = {
"name": record.name,
}
if record.exc_info:
log_record["error"] = {
"kind": record.exc_info[0].__name__,
"stack": message_dict.get("stack_info"),
"message": message_dict.get("exc_info"),
}
log_record.pop("exc_info", None)
log_record.pop("stack_info", None)
TEXT_FORMATTER = ColorExtrasFormatter(fmt=DEFAULT_EXTRAS_FORMAT)
JSON_FORMATTER = jsonlogger.JsonFormatter()
DATADOG_FORMATTER = DatadogFormatter()
|
import React from "react";
import { Store } from "react-chrome-redux";
import { render } from "react-dom";
import { Provider } from "react-redux";
import { ThemeProvider } from "styled-components";
import App from "./components/App/App";
import { theme } from "./theme";
import { BrowserRouter } from "react-router-dom";
const store = new Store({
portName: "HLS_DOWNLOADER" // communication port name
});
// The store implements the same interface as Redux's store
// so you can use tools like `react-redux` no problem!
render(
<Provider store={store}>
<ThemeProvider theme={theme}>
<BrowserRouter>
<App />
</BrowserRouter>
</ThemeProvider>
</Provider>,
document.getElementById("root")
);
|
// Variety.js v3.4.1
(function() {
var _info = {},
_list = [];
function toPID(name) {
if (!!_info[name]) {
return name;
}
for (var pid in _info) {
if (!_info[pid].alias) {
continue;
}
for (var type in _info[pid].alias) {
if (_info[pid].alias[type] === name) {
return pid;
}
}
}
return "";
}
var variety = (pzpr.variety = pzpr.genre = function(pid) {
return _info[toPID(pid)] || { valid: false };
});
variety.extend = function(obj) {
for (var n in obj) {
this[n] = obj[n];
}
};
variety.extend({
info: _info,
toPID: toPID,
exists: function(name) {
return variety(name).valid;
},
each: function(func) {
for (var pid in _info) {
func(pid);
}
},
getList: function() {
return _list.slice();
}
});
delete variety.extend;
(function(Genre, obj) {
for (var pzprid in obj) {
_info[pzprid] = new Genre(pzprid, obj[pzprid]);
try {
Object.freeze(_info[pzprid]);
Object.freeze(_info[pzprid].exists);
Object.freeze(_info[pzprid].alias);
} catch (e) {}
}
})(
// eslint-disable-next-line no-unexpected-multiline
function Genre(pzprid, datalist) {
this.valid = true;
this.pid = pzprid; /* パズルID */
this.script = !!datalist[4]
? datalist[4]
: pzprid; /* スクリプトファイル(クラス) */
this.ja = datalist[2]; /* 日本語パズル名 */
this.en = datalist[3]; /* 英語パズル名 */
this.exists = {
pzprapp: !!datalist[0],
kanpen: !!datalist[1],
pencilbox: !!datalist[1]
};
this.exists.pencilbox =
this.exists.pencilbox &&
pzprid !== "nanro" &&
pzprid !== "ayeheya" &&
pzprid !== "kurochute";
/* pzprurl : ぱずぷれID(URL出力用) */
/* kanpen : カンペンID */
/* kanpen2 : カンペンID(入力のみ) */
this.alias = !!datalist[5] ? datalist[5] : {};
this.urlid = this.alias.pzprurl || pzprid;
this.kanpenid = !!datalist[1] ? this.alias.kanpen || pzprid : "";
_list.push(pzprid);
},
{
aho: [0, 0, "アホになり切れ", "Aho-ni-Narikire", "shikaku"],
amibo: [0, 0, "あみぼー", "Amibo", "amibo"],
angleloop: [0, 0, "鋭直鈍ループ", "Angle Loop", "kouchoku"],
aqre: [0, 0, "Aqre", "Aqre", "aqre"],
aquarium: [0, 0, "アクアプレース", "Aquarium", "aquarium"],
araf: [0, 0, "相ダ部屋", "Araf", "araf"],
armyants: [0, 0, "ぐんたいあり", "Army Ants", "kaero"],
arukone: [0, 0, "アルコネ", "Arukone", "numlin"],
ayeheya: [0, 1, "∀人∃HEYA", "ekawayeh", "heyawake"],
balance: [0, 0, "Balance Loop", "Balance Loop"],
cave: [
1,
0,
"バッグ",
"Cave",
"kurodoko",
{ alias: "bag", alias2: "corral", alias3: "correl" }
],
barns: [1, 0, "バーンズ", "Barns"],
bdblock: [1, 0, "ボーダーブロック", "Border Block"],
bonsan: [1, 0, "ぼんさん", "Bonsan", "bonsan"],
bosanowa: [1, 0, "ボサノワ", "Bosanowa", "", { alias: "bossanova" }],
box: [0, 0, "ボックス", "Box"],
skyscrapers: [
0,
0,
"ビルディングパズル",
"Skyscrapers",
"",
{ alias: "building", alias2: "skyscraper" }
],
castle: [0, 0, "Castle Wall", "Castle Wall"],
cbblock: [0, 0, "コンビブロック", "Combi Block"],
chocona: [0, 0, "チョコナ", "Chocona", "shimaguni"],
cojun: [0, 0, "コージュン", "Cojun", "ripple"],
compass: [0, 0, "Compass", "Compass", "compass"],
country: [1, 0, "カントリーロード", "Country Road"],
creek: [1, 0, "クリーク", "Creek"],
curvedata: [0, 0, "カーブデータ", "Curve Data"],
"curvedata-aux": [0, 0, "図形の編集", "Edit shape"],
dbchoco: [0, 0, "ダブルチョコ", "Double Choco", "cbblock"],
detour: [0, 0, "Detour", "Detour", "country"],
doppelblock: [0, 0, "Doppelblock", "Doppelblock", "doppelblock"],
dosufuwa: [0, 0, "ドッスンフワリ", "Dosun-Fuwari"],
doubleback: [0, 0, "Double Back", "Double Back", "country"],
easyasabc: [0, 0, "ABCプレース", "Easy as ABC"],
factors: [0, 0, "因子の部屋", "Rooms of Factors"],
fillmat: [1, 0, "フィルマット", "Fillmat", "fillmat"],
fillomino: [
0,
1,
"フィルオミノ",
"Fillomino",
"",
{ kanpen2: "fillomino01" }
],
firefly: [1, 0, "ホタルビーム", "Hotaru Beam"],
fivecells: [0, 0, "ファイブセルズ", "FiveCells", "nawabari"],
fourcells: [0, 0, "フォーセルズ", "FourCells", "nawabari"],
geradeweg: [0, 0, "グラーデヴェグ", "Geradeweg"],
goishi: [0, 1, "碁石ひろい", "Goishi"],
gokigen: [1, 0, "ごきげんななめ", "Slant", "gokigen"],
haisu: [0, 0, "Haisu", "Haisu"],
hakoiri: [1, 0, "はこいり○△□", "Hakoiri-masashi"],
hanare: [0, 0, "はなれ組", "Hanare-gumi", "hanare"],
hashikake: [
0,
1,
"橋をかけろ",
"Hashiwokakero",
"",
{ pzprurl: "hashi", kanpen: "hashi", alias: "bridges" }
],
hebi: [1, 0, "へびいちご", "Hebi-Ichigo", "", { old: "snakes" }],
herugolf: [0, 0, "ヘルゴルフ", "Herugolf"],
heteromino: [0, 0, "ヘテロミノ", "Heteromino", "nawabari"],
heyabon: [1, 0, "へやぼん", "Heya-Bon", "bonsan"],
heyawake: [
0,
1,
"へやわけ",
"Heyawake",
"heyawake",
{ alias: "heyawacky" }
],
hitori: [0, 1, "ひとりにしてくれ", "Hitori"],
icebarn: [1, 0, "アイスバーン", "Icebarn", "icebarn"],
icelom: [0, 0, "アイスローム", "Icelom", "icebarn"],
icelom2: [0, 0, "アイスローム2", "Icelom 2", "icebarn"],
ichimaga: [0, 0, "イチマガ", "Ichimaga", "ichimaga"],
ichimagam: [0, 0, "磁石イチマガ", "Magnetic Ichimaga", "ichimaga"],
ichimagax: [
0,
0,
"一回曲がって交差もするの",
"Crossing Ichimaga",
"ichimaga"
],
interbd: [0, 0, "International Borders", "International Borders"],
juosan: [0, 0, "縦横さん", "Juosan"],
kaero: [1, 0, "お家に帰ろう", "Return Home"],
kakuro: [0, 1, "カックロ", "Kakuro"],
kakuru: [0, 0, "カックル", "Kakuru"],
kazunori: [0, 0, "かずのりのへや", "Kazunori Room"],
kinkonkan: [1, 0, "キンコンカン", "Kin-Kon-Kan"],
kouchoku: [0, 0, "交差は直角に限る", "Kouchoku"],
kramma: [0, 0, "快刀乱麻", "KaitoRamma", "kramma"],
kramman: [0, 0, "新・快刀乱麻", "New KaitoRamma", "kramma"],
kropki: [0, 0, "Kropki", "Kropki", "minarism"],
kurochute: [0, 1, "クロシュート", "Kurochute"],
kurodoko: [0, 1, "黒どこ(黒マスはどこだ)", "Kurodoko"],
kurotto: [0, 0, "クロット", "Kurotto"],
kusabi: [0, 0, "クサビリンク", "Kusabi"],
lightup: [
0,
1,
"美術館",
"Akari",
"",
{ pzprurl: "akari", kanpen: "bijutsukan" }
],
lits: [1, 1, "LITS", "LITS", "lits"],
lookair: [0, 0, "るっくえあ", "Look-Air"],
loopsp: [1, 0, "環状線スペシャル", "Loop Special", "pipelink"],
loute: [0, 0, "エルート", "L-route"],
makaro: [0, 0, "マカロ", "Makaro"],
mashu: [0, 1, "ましゅ", "Masyu", "", { kanpen: "masyu", alias: "pearl" }],
maxi: [0, 0, "Maxi Loop", "Maxi Loop", "country"],
meander: [0, 0, "にょろにょろナンバー", "Meandering Numbers", "ripple"],
mejilink: [0, 0, "メジリンク", "Mejilink"],
minarism: [1, 0, "マイナリズム", "Minarism"],
mines: [0, 0, "マインスイーパ", "Minesweeper", "kurotto"],
midloop: [0, 0, "ミッドループ", "Mid-loop"],
mochikoro: [1, 0, "モチコロ", "Mochikoro", "nurikabe"],
mochinyoro: [1, 0, "モチにょろ", "Mochinyoro", "nurikabe"],
moonsun: [0, 0, "月か太陽", "Moon or Sun", "country"],
nagare: [0, 0, "流れるループ", "Nagareru-Loop"],
nagenawa: [0, 0, "なげなわ", "Nagenawa", "nagenawa"],
nanro: [0, 1, "ナンロー", "Nanro"],
nawabari: [1, 0, "なわばり", "Territory", "nawabari"],
nikoji: [0, 0, "NIKOJI", "NIKOJI", "cbblock"],
nondango: [0, 0, "ノンダンゴ", "Nondango"],
nonogram: [0, 0, "ののぐらむ", "Nonogram"],
norinori: [0, 1, "のりのり", "Norinori", "lits"],
numlin: [
0,
1,
"ナンバーリンク",
"Numberlink",
"",
{ kanpen: "numberlink" }
],
nuribou: [1, 0, "ぬりぼう", "Nuribou", "nurikabe"],
nurikabe: [0, 1, "ぬりかべ", "Nurikabe", "nurikabe"],
nurimaze: [0, 0, "ぬりめいず", "Nuri-Maze", "nurimaze"],
nurimisaki: [0, 0, "ぬりみさき", "Nurimisaki", "kurodoko"],
onsen: [0, 0, "温泉めぐり", "Onsen-meguri", "country"],
paintarea: [1, 0, "ペイントエリア", "Paintarea"],
pencils: [0, 0, "ペンシルズ", "Pencils"],
pipelink: [1, 0, "パイプリンク", "Pipelink", "pipelink"],
pipelinkr: [
1,
0,
"帰ってきたパイプリンク",
"Pipelink Returns",
"pipelink"
],
putteria: [0, 0, "プッテリア", "Putteria", "hanare"],
rectslider: [0, 0, "四角スライダー", "Rectangle-Slider", "bonsan"],
reflect: [1, 0, "リフレクトリンク", "Reflect Link"],
renban: [0, 0, "連番窓口", "Renban-Madoguchi"],
ringring: [0, 0, "リングリング", "Ring-ring", "nagenawa"],
ripple: [
0,
1,
"波及効果",
"Ripple Effect",
"ripple",
{ kanpen: "hakyukoka" }
],
roma: [0, 0, "ろーま", "Roma", "", { alias: "rome" }],
sashigane: [0, 0, "さしがね", "Sashigane", "loute"],
satogaeri: [
0,
1,
"さとがえり",
"Satogaeri",
"bonsan",
{ alias: "sato", kanpen: "satogaeri" }
],
scrin: [0, 0, "スクリン", "Scrin"],
shakashaka: [0, 1, "シャカシャカ", "Shakashaka"],
shikaku: [0, 1, "四角に切れ", "Shikaku", "shikaku"],
shimaguni: [1, 0, "島国", "Islands", "shimaguni"],
shugaku: [1, 0, "修学旅行の夜", "School Trip"],
shwolf: [0, 0, "ヤギとオオカミ", "Goats and Wolves", "kramma"],
simpleloop: [0, 0, "Simple Loop", "Simple Loop", "country"],
slalom: [1, 1, "スラローム", "Slalom", "", { alias: "suraromu" }],
slither: [
0,
1,
"スリザーリンク",
"Slitherlink",
"",
{ kanpen: "slitherlink" }
],
snake: [0, 0, "Snake", "Snake"],
starbattle: [0, 0, "スターバトル", "Star Battle"],
stostone: [0, 0, "ストストーン", "Stostone", "shimaguni"],
sudoku: [0, 1, "数独", "Sudoku"],
sukoro: [1, 0, "数コロ", "Sukoro", "sukoro"],
sukororoom: [0, 0, "数コロ部屋", "Sukoro-room", "sukoro"],
symmarea: [0, 0, "シンメトリーエリア", "Symmetry Area", "fillomino"],
tapa: [0, 0, "Tapa", "Tapa"],
tapaloop: [0, 0, "Tapa-Like Loop", "Tapa-Like Loop"],
tasquare: [0, 0, "たすくえあ", "Tasquare"],
tatamibari: [1, 0, "タタミバリ", "Tatamibari"],
tateyoko: [1, 0, "タテボーヨコボー", "Tatebo-Yokobo"],
tawa: [0, 0, "たわむれんが", "Tawamurenga"],
tentaisho: [0, 0, "天体ショー", "Tentaisho"],
tents: [0, 0, "Tents", "Tents", "tents"],
tilepaint: [1, 0, "タイルペイント", "Tilepaint"],
toichika: [0, 0, "遠い誓い", "Toichika"],
toichika2: [0, 0, "遠い誓い2", "Toichika 2", "toichika"],
triplace: [0, 0, "トリプレイス", "Tri-place"],
usotatami: [0, 0, "ウソタタミ", "Uso-tatami", "fillmat"],
usoone: [0, 0, "ウソワン", "Uso-one"],
view: [1, 0, "ヴィウ", "View", "sukoro"],
wagiri: [0, 0, "ごきげんななめ・輪切", "Wagiri", "gokigen"],
walllogic: [0, 0, "ウォールロジック", "Wall Logic"],
wblink: [0, 0, "シロクロリンク", "Shirokuro-link"],
yajikazu: [1, 0, "やじさんかずさん", "Yajisan-Kazusan"],
yajilin: [
0,
1,
"ヤジリン",
"Yajilin",
"",
{ pzprurl: "yajilin", kanpen: "yajilin", alias: "yajirin" }
],
"yajilin-regions": [
0,
0,
"ヘヤジリン",
"Regional Yajilin",
"yajilin",
{ alias: "yajirin-regions" }
],
yajitatami: [0, 0, "ヤジタタミ", "Yajitatami"],
yinyang: [0, 0, "しろまるくろまる", "Yin-Yang"],
yosenabe: [0, 0, "よせなべ", "Yosenabe"]
}
);
})();
|
const parseFont = require("./parseFont");
test("parseFont - ascii", async () => {
expect(await parseFont("fixtures/ascii.fnt")).toMatchInlineSnapshot(`
"module.exports = {
\\"pages\\": [typeof require(\\"./test.png\\") === \\"object\\" && require(\\"./test.png\\") != null && require(\\"./test.png\\").__esModule && {}.hasOwnProperty.call(require(\\"./test.png\\"), \\"default\\") ? require(\\"./test.png\\").default : require(\\"./test.png\\")],
\\"chars\\": [{
\\"id\\": 32,
\\"x\\": 132,
\\"y\\": 44,
\\"width\\": 0,
\\"height\\": 0,
\\"xoffset\\": 0,
\\"yoffset\\": 46,
\\"xadvance\\": 14,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 33,
\\"x\\": 238,
\\"y\\": 334,
\\"width\\": 18,
\\"height\\": 40,
\\"xoffset\\": 3,
\\"yoffset\\": 10,
\\"xadvance\\": 14,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 34,
\\"x\\": 84,
\\"y\\": 362,
\\"width\\": 20,
\\"height\\": 18,
\\"xoffset\\": 7,
\\"yoffset\\": 8,
\\"xadvance\\": 18,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 35,
\\"x\\": 84,
\\"y\\": 318,
\\"width\\": 32,
\\"height\\": 42,
\\"xoffset\\": 3,
\\"yoffset\\": 8,
\\"xadvance\\": 28,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 36,
\\"x\\": 2,
\\"y\\": 270,
\\"width\\": 32,
\\"height\\": 48,
\\"xoffset\\": 3,
\\"yoffset\\": 6,
\\"xadvance\\": 28,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 37,
\\"x\\": 248,
\\"y\\": 2,
\\"width\\": 42,
\\"height\\": 42,
\\"xoffset\\": 5,
\\"yoffset\\": 9,
\\"xadvance\\": 45,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 38,
\\"x\\": 84,
\\"y\\": 142,
\\"width\\": 34,
\\"height\\": 42,
\\"xoffset\\": 4,
\\"yoffset\\": 8,
\\"xadvance\\": 34,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 39,
\\"x\\": 146,
\\"y\\": 362,
\\"width\\": 12,
\\"height\\": 18,
\\"xoffset\\": 7,
\\"yoffset\\": 8,
\\"xadvance\\": 10,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 40,
\\"x\\": 178,
\\"y\\": 282,
\\"width\\": 22,
\\"height\\": 52,
\\"xoffset\\": 5,
\\"yoffset\\": 8,
\\"xadvance\\": 17,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 41,
\\"x\\": 178,
\\"y\\": 228,
\\"width\\": 22,
\\"height\\": 52,
\\"xoffset\\": -2,
\\"yoffset\\": 8,
\\"xadvance\\": 17,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 42,
\\"x\\": 120,
\\"y\\": 356,
\\"width\\": 22,
\\"height\\": 20,
\\"xoffset\\": 6,
\\"yoffset\\": 8,
\\"xadvance\\": 20,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 43,
\\"x\\": 238,
\\"y\\": 228,
\\"width\\": 28,
\\"height\\": 28,
\\"xoffset\\": 5,
\\"yoffset\\": 16,
\\"xadvance\\": 30,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 44,
\\"x\\": 106,
\\"y\\": 362,
\\"width\\": 12,
\\"height\\": 18,
\\"xoffset\\": 2,
\\"yoffset\\": 39,
\\"xadvance\\": 14,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 45,
\\"x\\": 110,
\\"y\\": 44,
\\"width\\": 20,
\\"height\\": 10,
\\"xoffset\\": 3,
\\"yoffset\\": 29,
\\"xadvance\\": 17,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 46,
\\"x\\": 92,
\\"y\\": 44,
\\"width\\": 12,
\\"height\\": 10,
\\"xoffset\\": 3,
\\"yoffset\\": 40,
\\"xadvance\\": 14,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 47,
\\"x\\": 178,
\\"y\\": 184,
\\"width\\": 28,
\\"height\\": 42,
\\"xoffset\\": -2,
\\"yoffset\\": 8,
\\"xadvance\\": 14,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 48,
\\"x\\": 344,
\\"y\\": 98,
\\"width\\": 30,
\\"height\\": 42,
\\"xoffset\\": 4,
\\"yoffset\\": 8,
\\"xadvance\\": 28,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 49,
\\"x\\": 354,
\\"y\\": 56,
\\"width\\": 22,
\\"height\\": 40,
\\"xoffset\\": 8,
\\"yoffset\\": 10,
\\"xadvance\\": 28,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 50,
\\"x\\": 178,
\\"y\\": 142,
\\"width\\": 30,
\\"height\\": 40,
\\"xoffset\\": 3,
\\"yoffset\\": 10,
\\"xadvance\\": 28,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 51,
\\"x\\": 312,
\\"y\\": 98,
\\"width\\": 30,
\\"height\\": 42,
\\"xoffset\\": 3,
\\"yoffset\\": 8,
\\"xadvance\\": 28,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 52,
\\"x\\": 146,
\\"y\\": 320,
\\"width\\": 30,
\\"height\\": 40,
\\"xoffset\\": 3,
\\"yoffset\\": 10,
\\"xadvance\\": 28,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 53,
\\"x\\": 146,
\\"y\\": 278,
\\"width\\": 30,
\\"height\\": 40,
\\"xoffset\\": 4,
\\"yoffset\\": 10,
\\"xadvance\\": 28,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 54,
\\"x\\": 280,
\\"y\\": 98,
\\"width\\": 30,
\\"height\\": 42,
\\"xoffset\\": 5,
\\"yoffset\\": 8,
\\"xadvance\\": 28,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 55,
\\"x\\": 210,
\\"y\\": 142,
\\"width\\": 28,
\\"height\\": 40,
\\"xoffset\\": 7,
\\"yoffset\\": 10,
\\"xadvance\\": 28,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 56,
\\"x\\": 248,
\\"y\\": 98,
\\"width\\": 30,
\\"height\\": 42,
\\"xoffset\\": 4,
\\"yoffset\\": 8,
\\"xadvance\\": 28,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 57,
\\"x\\": 216,
\\"y\\": 98,
\\"width\\": 30,
\\"height\\": 42,
\\"xoffset\\": 4,
\\"yoffset\\": 8,
\\"xadvance\\": 28,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 58,
\\"x\\": 298,
\\"y\\": 258,
\\"width\\": 16,
\\"height\\": 30,
\\"xoffset\\": 3,
\\"yoffset\\": 20,
\\"xadvance\\": 14,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 59,
\\"x\\": 264,
\\"y\\": 342,
\\"width\\": 16,
\\"height\\": 38,
\\"xoffset\\": 2,
\\"yoffset\\": 19,
\\"xadvance\\": 14,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 60,
\\"x\\": 208,
\\"y\\": 326,
\\"width\\": 28,
\\"height\\": 30,
\\"xoffset\\": 5,
\\"yoffset\\": 14,
\\"xadvance\\": 30,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 61,
\\"x\\": 208,
\\"y\\": 358,
\\"width\\": 28,
\\"height\\": 20,
\\"xoffset\\": 5,
\\"yoffset\\": 19,
\\"xadvance\\": 30,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 62,
\\"x\\": 208,
\\"y\\": 294,
\\"width\\": 28,
\\"height\\": 30,
\\"xoffset\\": 5,
\\"yoffset\\": 14,
\\"xadvance\\": 30,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 63,
\\"x\\": 178,
\\"y\\": 336,
\\"width\\": 26,
\\"height\\": 42,
\\"xoffset\\": 7,
\\"yoffset\\": 8,
\\"xadvance\\": 28,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 64,
\\"x\\": 2,
\\"y\\": 2,
\\"width\\": 52,
\\"height\\": 52,
\\"xoffset\\": 3,
\\"yoffset\\": 8,
\\"xadvance\\": 51,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 65,
\\"x\\": 160,
\\"y\\": 56,
\\"width\\": 36,
\\"height\\": 40,
\\"xoffset\\": -1,
\\"yoffset\\": 10,
\\"xadvance\\": 34,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 66,
\\"x\\": 122,
\\"y\\": 56,
\\"width\\": 36,
\\"height\\": 40,
\\"xoffset\\": 3,
\\"yoffset\\": 10,
\\"xadvance\\": 34,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 67,
\\"x\\": 44,
\\"y\\": 226,
\\"width\\": 36,
\\"height\\": 42,
\\"xoffset\\": 5,
\\"yoffset\\": 8,
\\"xadvance\\": 37,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 68,
\\"x\\": 44,
\\"y\\": 140,
\\"width\\": 38,
\\"height\\": 40,
\\"xoffset\\": 3,
\\"yoffset\\": 10,
\\"xadvance\\": 37,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 69,
\\"x\\": 44,
\\"y\\": 98,
\\"width\\": 38,
\\"height\\": 40,
\\"xoffset\\": 3,
\\"yoffset\\": 10,
\\"xadvance\\": 34,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 70,
\\"x\\": 84,
\\"y\\": 56,
\\"width\\": 36,
\\"height\\": 40,
\\"xoffset\\": 3,
\\"yoffset\\": 10,
\\"xadvance\\": 31,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 71,
\\"x\\": 2,
\\"y\\": 226,
\\"width\\": 38,
\\"height\\": 42,
\\"xoffset\\": 5,
\\"yoffset\\": 8,
\\"xadvance\\": 39,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 72,
\\"x\\": 2,
\\"y\\": 140,
\\"width\\": 40,
\\"height\\": 40,
\\"xoffset\\": 3,
\\"yoffset\\": 10,
\\"xadvance\\": 37,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 73,
\\"x\\": 238,
\\"y\\": 292,
\\"width\\": 18,
\\"height\\": 40,
\\"xoffset\\": 3,
\\"yoffset\\": 10,
\\"xadvance\\": 14,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 74,
\\"x\\": 184,
\\"y\\": 98,
\\"width\\": 30,
\\"height\\": 42,
\\"xoffset\\": 2,
\\"yoffset\\": 8,
\\"xadvance\\": 25,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 75,
\\"x\\": 2,
\\"y\\": 98,
\\"width\\": 40,
\\"height\\": 40,
\\"xoffset\\": 3,
\\"yoffset\\": 10,
\\"xadvance\\": 34,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 76,
\\"x\\": 146,
\\"y\\": 236,
\\"width\\": 30,
\\"height\\": 40,
\\"xoffset\\": 3,
\\"yoffset\\": 10,
\\"xadvance\\": 28,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 77,
\\"x\\": 200,
\\"y\\": 2,
\\"width\\": 46,
\\"height\\": 40,
\\"xoffset\\": 3,
\\"yoffset\\": 10,
\\"xadvance\\": 42,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 78,
\\"x\\": 2,
\\"y\\": 56,
\\"width\\": 40,
\\"height\\": 40,
\\"xoffset\\": 3,
\\"yoffset\\": 10,
\\"xadvance\\": 37,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 79,
\\"x\\": 292,
\\"y\\": 2,
\\"width\\": 40,
\\"height\\": 42,
\\"xoffset\\": 5,
\\"yoffset\\": 8,
\\"xadvance\\": 39,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 80,
\\"x\\": 44,
\\"y\\": 56,
\\"width\\": 38,
\\"height\\": 40,
\\"xoffset\\": 3,
\\"yoffset\\": 10,
\\"xadvance\\": 34,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 81,
\\"x\\": 158,
\\"y\\": 2,
\\"width\\": 40,
\\"height\\": 46,
\\"xoffset\\": 5,
\\"yoffset\\": 8,
\\"xadvance\\": 39,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 82,
\\"x\\": 334,
\\"y\\": 2,
\\"width\\": 40,
\\"height\\": 40,
\\"xoffset\\": 3,
\\"yoffset\\": 10,
\\"xadvance\\": 37,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 83,
\\"x\\": 44,
\\"y\\": 182,
\\"width\\": 36,
\\"height\\": 42,
\\"xoffset\\": 4,
\\"yoffset\\": 8,
\\"xadvance\\": 34,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 84,
\\"x\\": 244,
\\"y\\": 56,
\\"width\\": 34,
\\"height\\": 40,
\\"xoffset\\": 7,
\\"yoffset\\": 10,
\\"xadvance\\": 31,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 85,
\\"x\\": 2,
\\"y\\": 182,
\\"width\\": 38,
\\"height\\": 42,
\\"xoffset\\": 5,
\\"yoffset\\": 8,
\\"xadvance\\": 37,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 86,
\\"x\\": 44,
\\"y\\": 312,
\\"width\\": 36,
\\"height\\": 40,
\\"xoffset\\": 7,
\\"yoffset\\": 10,
\\"xadvance\\": 34,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 87,
\\"x\\": 56,
\\"y\\": 2,
\\"width\\": 52,
\\"height\\": 40,
\\"xoffset\\": 7,
\\"yoffset\\": 10,
\\"xadvance\\": 48,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 88,
\\"x\\": 110,
\\"y\\": 2,
\\"width\\": 46,
\\"height\\": 40,
\\"xoffset\\": -1,
\\"yoffset\\": 10,
\\"xadvance\\": 34,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 89,
\\"x\\": 2,
\\"y\\": 320,
\\"width\\": 38,
\\"height\\": 40,
\\"xoffset\\": 6,
\\"yoffset\\": 10,
\\"xadvance\\": 34,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 90,
\\"x\\": 44,
\\"y\\": 270,
\\"width\\": 36,
\\"height\\": 40,
\\"xoffset\\": 2,
\\"yoffset\\": 10,
\\"xadvance\\": 31,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 91,
\\"x\\": 146,
\\"y\\": 184,
\\"width\\": 24,
\\"height\\": 50,
\\"xoffset\\": 1,
\\"yoffset\\": 9,
\\"xadvance\\": 14,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 92,
\\"x\\": 282,
\\"y\\": 258,
\\"width\\": 14,
\\"height\\": 42,
\\"xoffset\\": 5,
\\"yoffset\\": 8,
\\"xadvance\\": 14,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 93,
\\"x\\": 120,
\\"y\\": 304,
\\"width\\": 24,
\\"height\\": 50,
\\"xoffset\\": -2,
\\"yoffset\\": 9,
\\"xadvance\\": 14,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 94,
\\"x\\": 44,
\\"y\\": 354,
\\"width\\": 26,
\\"height\\": 24,
\\"xoffset\\": 4,
\\"yoffset\\": 9,
\\"xadvance\\": 24,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 95,
\\"x\\": 56,
\\"y\\": 44,
\\"width\\": 34,
\\"height\\": 8,
\\"xoffset\\": -3,
\\"yoffset\\": 51,
\\"xadvance\\": 28,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 96,
\\"x\\": 160,
\\"y\\": 362,
\\"width\\": 14,
\\"height\\": 12,
\\"xoffset\\": 8,
\\"yoffset\\": 8,
\\"xadvance\\": 17,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 97,
\\"x\\": 234,
\\"y\\": 184,
\\"width\\": 30,
\\"height\\": 32,
\\"xoffset\\": 3,
\\"yoffset\\": 18,
\\"xadvance\\": 28,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 98,
\\"x\\": 152,
\\"y\\": 98,
\\"width\\": 30,
\\"height\\": 42,
\\"xoffset\\": 2,
\\"yoffset\\": 8,
\\"xadvance\\": 28,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 99,
\\"x\\": 208,
\\"y\\": 228,
\\"width\\": 28,
\\"height\\": 32,
\\"xoffset\\": 3,
\\"yoffset\\": 18,
\\"xadvance\\": 25,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 100,
\\"x\\": 84,
\\"y\\": 274,
\\"width\\": 32,
\\"height\\": 42,
\\"xoffset\\": 3,
\\"yoffset\\": 8,
\\"xadvance\\": 28,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 101,
\\"x\\": 328,
\\"y\\": 184,
\\"width\\": 28,
\\"height\\": 32,
\\"xoffset\\": 3,
\\"yoffset\\": 18,
\\"xadvance\\": 28,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 102,
\\"x\\": 208,
\\"y\\": 184,
\\"width\\": 24,
\\"height\\": 42,
\\"xoffset\\": 3,
\\"yoffset\\": 8,
\\"xadvance\\": 14,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 103,
\\"x\\": 84,
\\"y\\": 230,
\\"width\\": 32,
\\"height\\": 42,
\\"xoffset\\": 2,
\\"yoffset\\": 18,
\\"xadvance\\": 28,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 104,
\\"x\\": 146,
\\"y\\": 142,
\\"width\\": 30,
\\"height\\": 40,
\\"xoffset\\": 2,
\\"yoffset\\": 10,
\\"xadvance\\": 28,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 105,
\\"x\\": 264,
\\"y\\": 300,
\\"width\\": 16,
\\"height\\": 40,
\\"xoffset\\": 2,
\\"yoffset\\": 10,
\\"xadvance\\": 12,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 106,
\\"x\\": 120,
\\"y\\": 250,
\\"width\\": 24,
\\"height\\": 52,
\\"xoffset\\": -6,
\\"yoffset\\": 8,
\\"xadvance\\": 12,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 107,
\\"x\\": 322,
\\"y\\": 56,
\\"width\\": 30,
\\"height\\": 40,
\\"xoffset\\": 2,
\\"yoffset\\": 10,
\\"xadvance\\": 25,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 108,
\\"x\\": 264,
\\"y\\": 258,
\\"width\\": 16,
\\"height\\": 40,
\\"xoffset\\": 2,
\\"yoffset\\": 10,
\\"xadvance\\": 12,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 109,
\\"x\\": 198,
\\"y\\": 56,
\\"width\\": 44,
\\"height\\": 32,
\\"xoffset\\": 2,
\\"yoffset\\": 18,
\\"xadvance\\": 42,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 110,
\\"x\\": 338,
\\"y\\": 142,
\\"width\\": 30,
\\"height\\": 32,
\\"xoffset\\": 2,
\\"yoffset\\": 18,
\\"xadvance\\": 28,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 111,
\\"x\\": 306,
\\"y\\": 142,
\\"width\\": 30,
\\"height\\": 32,
\\"xoffset\\": 3,
\\"yoffset\\": 18,
\\"xadvance\\": 28,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 112,
\\"x\\": 84,
\\"y\\": 186,
\\"width\\": 32,
\\"height\\": 42,
\\"xoffset\\": 0,
\\"yoffset\\": 17,
\\"xadvance\\": 28,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 113,
\\"x\\": 120,
\\"y\\": 98,
\\"width\\": 30,
\\"height\\": 42,
\\"xoffset\\": 3,
\\"yoffset\\": 17,
\\"xadvance\\": 28,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 114,
\\"x\\": 238,
\\"y\\": 258,
\\"width\\": 24,
\\"height\\": 32,
\\"xoffset\\": 2,
\\"yoffset\\": 18,
\\"xadvance\\": 17,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 115,
\\"x\\": 298,
\\"y\\": 184,
\\"width\\": 28,
\\"height\\": 32,
\\"xoffset\\": 2,
\\"yoffset\\": 18,
\\"xadvance\\": 25,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 116,
\\"x\\": 358,
\\"y\\": 184,
\\"width\\": 18,
\\"height\\": 40,
\\"xoffset\\": 3,
\\"yoffset\\": 10,
\\"xadvance\\": 14,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 117,
\\"x\\": 274,
\\"y\\": 142,
\\"width\\": 30,
\\"height\\": 32,
\\"xoffset\\": 4,
\\"yoffset\\": 18,
\\"xadvance\\": 28,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 118,
\\"x\\": 208,
\\"y\\": 262,
\\"width\\": 28,
\\"height\\": 30,
\\"xoffset\\": 4,
\\"yoffset\\": 20,
\\"xadvance\\": 25,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 119,
\\"x\\": 280,
\\"y\\": 56,
\\"width\\": 40,
\\"height\\": 30,
\\"xoffset\\": 4,
\\"yoffset\\": 20,
\\"xadvance\\": 37,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 120,
\\"x\\": 240,
\\"y\\": 142,
\\"width\\": 32,
\\"height\\": 30,
\\"xoffset\\": 0,
\\"yoffset\\": 20,
\\"xadvance\\": 25,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 121,
\\"x\\": 84,
\\"y\\": 98,
\\"width\\": 34,
\\"height\\": 42,
\\"xoffset\\": 0,
\\"yoffset\\": 18,
\\"xadvance\\": 25,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 122,
\\"x\\": 266,
\\"y\\": 184,
\\"width\\": 30,
\\"height\\": 30,
\\"xoffset\\": 1,
\\"yoffset\\": 20,
\\"xadvance\\": 25,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 123,
\\"x\\": 120,
\\"y\\": 196,
\\"width\\": 24,
\\"height\\": 52,
\\"xoffset\\": 3,
\\"yoffset\\": 8,
\\"xadvance\\": 17,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 124,
\\"x\\": 282,
\\"y\\": 302,
\\"width\\": 8,
\\"height\\": 52,
\\"xoffset\\": 5,
\\"yoffset\\": 8,
\\"xadvance\\": 13,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 125,
\\"x\\": 120,
\\"y\\": 142,
\\"width\\": 24,
\\"height\\": 52,
\\"xoffset\\": -4,
\\"yoffset\\": 8,
\\"xadvance\\": 17,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 126,
\\"x\\": 2,
\\"y\\": 362,
\\"width\\": 30,
\\"height\\": 14,
\\"xoffset\\": 5,
\\"yoffset\\": 22,
\\"xadvance\\": 30,
\\"page\\": 0,
\\"chnl\\": 0
}],
\\"kernings\\": [{
\\"first\\": 86,
\\"second\\": 117,
\\"amount\\": -1
}, {
\\"first\\": 84,
\\"second\\": 97,
\\"amount\\": -5
}, {
\\"first\\": 84,
\\"second\\": 99,
\\"amount\\": -5
}, {
\\"first\\": 87,
\\"second\\": 65,
\\"amount\\": -1
}, {
\\"first\\": 80,
\\"second\\": 65,
\\"amount\\": -3
}, {
\\"first\\": 86,
\\"second\\": 101,
\\"amount\\": -2
}, {
\\"first\\": 89,
\\"second\\": 111,
\\"amount\\": -4
}, {
\\"first\\": 87,
\\"second\\": 44,
\\"amount\\": -2
}, {
\\"first\\": 84,
\\"second\\": 111,
\\"amount\\": -5
}, {
\\"first\\": 89,
\\"second\\": 112,
\\"amount\\": -3
}, {
\\"first\\": 84,
\\"second\\": 65,
\\"amount\\": -3
}, {
\\"first\\": 80,
\\"second\\": 44,
\\"amount\\": -6
}, {
\\"first\\": 87,
\\"second\\": 46,
\\"amount\\": -2
}, {
\\"first\\": 89,
\\"second\\": 113,
\\"amount\\": -4
}, {
\\"first\\": 76,
\\"second\\": 84,
\\"amount\\": -3
}, {
\\"first\\": 80,
\\"second\\": 46,
\\"amount\\": -6
}, {
\\"first\\": 76,
\\"second\\": 121,
\\"amount\\": -1
}, {
\\"first\\": 76,
\\"second\\": 86,
\\"amount\\": -3
}, {
\\"first\\": 84,
\\"second\\": 114,
\\"amount\\": -1
}, {
\\"first\\": 76,
\\"second\\": 87,
\\"amount\\": -3
}, {
\\"first\\": 84,
\\"second\\": 58,
\\"amount\\": -5
}, {
\\"first\\": 84,
\\"second\\": 44,
\\"amount\\": -5
}, {
\\"first\\": 84,
\\"second\\": 115,
\\"amount\\": -5
}, {
\\"first\\": 76,
\\"second\\": 89,
\\"amount\\": -3
}, {
\\"first\\": 84,
\\"second\\": 46,
\\"amount\\": -5
}, {
\\"first\\": 89,
\\"second\\": 117,
\\"amount\\": -2
}, {
\\"first\\": 89,
\\"second\\": 97,
\\"amount\\": -3
}, {
\\"first\\": 119,
\\"second\\": 44,
\\"amount\\": -2
}, {
\\"first\\": 84,
\\"second\\": 117,
\\"amount\\": -1
}, {
\\"first\\": 89,
\\"second\\": 118,
\\"amount\\": -2
}, {
\\"first\\": 114,
\\"second\\": 44,
\\"amount\\": -2
}, {
\\"first\\": 89,
\\"second\\": 101,
\\"amount\\": -4
}, {
\\"first\\": 49,
\\"second\\": 49,
\\"amount\\": -3
}, {
\\"first\\": 86,
\\"second\\": 121,
\\"amount\\": -1
}, {
\\"first\\": 119,
\\"second\\": 46,
\\"amount\\": -2
}, {
\\"first\\": 84,
\\"second\\": 119,
\\"amount\\": -2
}, {
\\"first\\": 84,
\\"second\\": 101,
\\"amount\\": -5
}, {
\\"first\\": 114,
\\"second\\": 46,
\\"amount\\": -2
}, {
\\"first\\": 86,
\\"second\\": 97,
\\"amount\\": -3
}, {
\\"first\\": 89,
\\"second\\": 65,
\\"amount\\": -3
}, {
\\"first\\": 89,
\\"second\\": 105,
\\"amount\\": -1
}, {
\\"first\\": 118,
\\"second\\": 44,
\\"amount\\": -3
}, {
\\"first\\": 65,
\\"second\\": 84,
\\"amount\\": -3
}, {
\\"first\\": 84,
\\"second\\": 105,
\\"amount\\": -1
}, {
\\"first\\": 65,
\\"second\\": 86,
\\"amount\\": -3
}, {
\\"first\\": 65,
\\"second\\": 87,
\\"amount\\": -1
}, {
\\"first\\": 118,
\\"second\\": 46,
\\"amount\\": -3
}, {
\\"first\\": 65,
\\"second\\": 89,
\\"amount\\": -3
}, {
\\"first\\": 70,
\\"second\\": 65,
\\"amount\\": -2
}, {
\\"first\\": 89,
\\"second\\": 58,
\\"amount\\": -2
}, {
\\"first\\": 89,
\\"second\\": 44,
\\"amount\\": -6
}, {
\\"first\\": 86,
\\"second\\": 65,
\\"amount\\": -3
}, {
\\"first\\": 86,
\\"second\\": 111,
\\"amount\\": -2
}, {
\\"first\\": 89,
\\"second\\": 46,
\\"amount\\": -6
}, {
\\"first\\": 121,
\\"second\\": 44,
\\"amount\\": -3
}, {
\\"first\\": 87,
\\"second\\": 97,
\\"amount\\": -1
}, {
\\"first\\": 70,
\\"second\\": 44,
\\"amount\\": -5
}, {
\\"first\\": 84,
\\"second\\": 121,
\\"amount\\": -2
}, {
\\"first\\": 86,
\\"second\\": 114,
\\"amount\\": -1
}, {
\\"first\\": 86,
\\"second\\": 58,
\\"amount\\": -1
}, {
\\"first\\": 86,
\\"second\\": 44,
\\"amount\\": -4
}, {
\\"first\\": 70,
\\"second\\": 46,
\\"amount\\": -5
}, {
\\"first\\": 121,
\\"second\\": 46,
\\"amount\\": -3
}, {
\\"first\\": 86,
\\"second\\": 46,
\\"amount\\": -4
}],
\\"info\\": {
\\"face\\": \\"Arial\\",
\\"size\\": 50,
\\"bold\\": 0,
\\"italic\\": 0,
\\"charset\\": \\"\\",
\\"unicode\\": 0,
\\"stretchH\\": 100,
\\"smooth\\": 1,
\\"aa\\": 1,
\\"padding\\": [0, 0, 0, 0],
\\"spacing\\": [0, 0]
},
\\"common\\": {
\\"lineHeight\\": 58,
\\"base\\": 49,
\\"scaleW\\": 384,
\\"scaleH\\": 384,
\\"pages\\": 1,
\\"packed\\": 0
}
};"
`);
});
test("parseFont - binary", async () => {
expect(await parseFont("fixtures/binary.fnt")).toMatchInlineSnapshot(`
"module.exports = {
\\"kernings\\": [{
\\"first\\": 32,
\\"second\\": 65,
\\"amount\\": -2
}, {
\\"first\\": 32,
\\"second\\": 84,
\\"amount\\": -1
}, {
\\"first\\": 32,
\\"second\\": 89,
\\"amount\\": -1
}, {
\\"first\\": 121,
\\"second\\": 46,
\\"amount\\": -2
}, {
\\"first\\": 121,
\\"second\\": 44,
\\"amount\\": -2
}, {
\\"first\\": 119,
\\"second\\": 46,
\\"amount\\": -2
}, {
\\"first\\": 119,
\\"second\\": 44,
\\"amount\\": -2
}, {
\\"first\\": 118,
\\"second\\": 46,
\\"amount\\": -2
}, {
\\"first\\": 118,
\\"second\\": 44,
\\"amount\\": -2
}, {
\\"first\\": 114,
\\"second\\": 46,
\\"amount\\": -2
}, {
\\"first\\": 49,
\\"second\\": 49,
\\"amount\\": -2
}, {
\\"first\\": 65,
\\"second\\": 32,
\\"amount\\": -2
}, {
\\"first\\": 65,
\\"second\\": 84,
\\"amount\\": -2
}, {
\\"first\\": 65,
\\"second\\": 86,
\\"amount\\": -2
}, {
\\"first\\": 65,
\\"second\\": 87,
\\"amount\\": -1
}, {
\\"first\\": 65,
\\"second\\": 89,
\\"amount\\": -2
}, {
\\"first\\": 65,
\\"second\\": 118,
\\"amount\\": -1
}, {
\\"first\\": 65,
\\"second\\": 119,
\\"amount\\": -1
}, {
\\"first\\": 65,
\\"second\\": 121,
\\"amount\\": -1
}, {
\\"first\\": 114,
\\"second\\": 44,
\\"amount\\": -2
}, {
\\"first\\": 70,
\\"second\\": 44,
\\"amount\\": -3
}, {
\\"first\\": 70,
\\"second\\": 46,
\\"amount\\": -3
}, {
\\"first\\": 70,
\\"second\\": 65,
\\"amount\\": -2
}, {
\\"first\\": 76,
\\"second\\": 32,
\\"amount\\": -1
}, {
\\"first\\": 76,
\\"second\\": 84,
\\"amount\\": -2
}, {
\\"first\\": 76,
\\"second\\": 86,
\\"amount\\": -2
}, {
\\"first\\": 76,
\\"second\\": 87,
\\"amount\\": -2
}, {
\\"first\\": 76,
\\"second\\": 89,
\\"amount\\": -2
}, {
\\"first\\": 76,
\\"second\\": 121,
\\"amount\\": -1
}, {
\\"first\\": 102,
\\"second\\": 102,
\\"amount\\": -1
}, {
\\"first\\": 80,
\\"second\\": 32,
\\"amount\\": -1
}, {
\\"first\\": 80,
\\"second\\": 44,
\\"amount\\": -4
}, {
\\"first\\": 80,
\\"second\\": 46,
\\"amount\\": -4
}, {
\\"first\\": 80,
\\"second\\": 65,
\\"amount\\": -2
}, {
\\"first\\": 82,
\\"second\\": 84,
\\"amount\\": -1
}, {
\\"first\\": 82,
\\"second\\": 86,
\\"amount\\": -1
}, {
\\"first\\": 82,
\\"second\\": 87,
\\"amount\\": -1
}, {
\\"first\\": 82,
\\"second\\": 89,
\\"amount\\": -1
}, {
\\"first\\": 84,
\\"second\\": 32,
\\"amount\\": -1
}, {
\\"first\\": 84,
\\"second\\": 44,
\\"amount\\": -3
}, {
\\"first\\": 84,
\\"second\\": 45,
\\"amount\\": -2
}, {
\\"first\\": 84,
\\"second\\": 46,
\\"amount\\": -3
}, {
\\"first\\": 84,
\\"second\\": 58,
\\"amount\\": -3
}, {
\\"first\\": 89,
\\"second\\": 118,
\\"amount\\": -2
}, {
\\"first\\": 84,
\\"second\\": 65,
\\"amount\\": -2
}, {
\\"first\\": 84,
\\"second\\": 79,
\\"amount\\": -1
}, {
\\"first\\": 84,
\\"second\\": 97,
\\"amount\\": -3
}, {
\\"first\\": 84,
\\"second\\": 99,
\\"amount\\": -3
}, {
\\"first\\": 84,
\\"second\\": 101,
\\"amount\\": -3
}, {
\\"first\\": 84,
\\"second\\": 105,
\\"amount\\": -1
}, {
\\"first\\": 84,
\\"second\\": 111,
\\"amount\\": -3
}, {
\\"first\\": 84,
\\"second\\": 114,
\\"amount\\": -1
}, {
\\"first\\": 84,
\\"second\\": 115,
\\"amount\\": -3
}, {
\\"first\\": 84,
\\"second\\": 117,
\\"amount\\": -1
}, {
\\"first\\": 84,
\\"second\\": 119,
\\"amount\\": -2
}, {
\\"first\\": 84,
\\"second\\": 121,
\\"amount\\": -2
}, {
\\"first\\": 86,
\\"second\\": 44,
\\"amount\\": -3
}, {
\\"first\\": 86,
\\"second\\": 45,
\\"amount\\": -2
}, {
\\"first\\": 86,
\\"second\\": 46,
\\"amount\\": -3
}, {
\\"first\\": 86,
\\"second\\": 58,
\\"amount\\": -1
}, {
\\"first\\": 89,
\\"second\\": 117,
\\"amount\\": -2
}, {
\\"first\\": 86,
\\"second\\": 65,
\\"amount\\": -2
}, {
\\"first\\": 86,
\\"second\\": 97,
\\"amount\\": -2
}, {
\\"first\\": 86,
\\"second\\": 101,
\\"amount\\": -2
}, {
\\"first\\": 86,
\\"second\\": 105,
\\"amount\\": -1
}, {
\\"first\\": 86,
\\"second\\": 111,
\\"amount\\": -2
}, {
\\"first\\": 86,
\\"second\\": 114,
\\"amount\\": -1
}, {
\\"first\\": 86,
\\"second\\": 117,
\\"amount\\": -1
}, {
\\"first\\": 86,
\\"second\\": 121,
\\"amount\\": -1
}, {
\\"first\\": 87,
\\"second\\": 44,
\\"amount\\": -2
}, {
\\"first\\": 87,
\\"second\\": 45,
\\"amount\\": -1
}, {
\\"first\\": 87,
\\"second\\": 46,
\\"amount\\": -2
}, {
\\"first\\": 87,
\\"second\\": 58,
\\"amount\\": -1
}, {
\\"first\\": 89,
\\"second\\": 113,
\\"amount\\": -3
}, {
\\"first\\": 87,
\\"second\\": 65,
\\"amount\\": -1
}, {
\\"first\\": 87,
\\"second\\": 97,
\\"amount\\": -1
}, {
\\"first\\": 87,
\\"second\\": 101,
\\"amount\\": -1
}, {
\\"first\\": 89,
\\"second\\": 112,
\\"amount\\": -2
}, {
\\"first\\": 87,
\\"second\\": 111,
\\"amount\\": -1
}, {
\\"first\\": 87,
\\"second\\": 114,
\\"amount\\": -1
}, {
\\"first\\": 87,
\\"second\\": 117,
\\"amount\\": -1
}, {
\\"first\\": 89,
\\"second\\": 111,
\\"amount\\": -3
}, {
\\"first\\": 89,
\\"second\\": 32,
\\"amount\\": -1
}, {
\\"first\\": 89,
\\"second\\": 44,
\\"amount\\": -4
}, {
\\"first\\": 89,
\\"second\\": 45,
\\"amount\\": -3
}, {
\\"first\\": 89,
\\"second\\": 46,
\\"amount\\": -4
}, {
\\"first\\": 89,
\\"second\\": 58,
\\"amount\\": -2
}, {
\\"first\\": 89,
\\"second\\": 105,
\\"amount\\": -1
}, {
\\"first\\": 89,
\\"second\\": 65,
\\"amount\\": -2
}, {
\\"first\\": 89,
\\"second\\": 97,
\\"amount\\": -2
}, {
\\"first\\": 89,
\\"second\\": 101,
\\"amount\\": -3
}],
\\"chars\\": [{
\\"id\\": 32,
\\"x\\": 155,
\\"y\\": 75,
\\"width\\": 3,
\\"height\\": 1,
\\"xoffset\\": -1,
\\"yoffset\\": 31,
\\"xadvance\\": 8,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 33,
\\"x\\": 250,
\\"y\\": 116,
\\"width\\": 4,
\\"height\\": 20,
\\"xoffset\\": 2,
\\"yoffset\\": 6,
\\"xadvance\\": 8,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 34,
\\"x\\": 113,
\\"y\\": 219,
\\"width\\": 10,
\\"height\\": 7,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 10,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 35,
\\"x\\": 120,
\\"y\\": 120,
\\"width\\": 16,
\\"height\\": 20,
\\"xoffset\\": -1,
\\"yoffset\\": 6,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 36,
\\"x\\": 124,
\\"y\\": 53,
\\"width\\": 15,
\\"height\\": 23,
\\"xoffset\\": 0,
\\"yoffset\\": 5,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 37,
\\"x\\": 75,
\\"y\\": 79,
\\"width\\": 22,
\\"height\\": 20,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 24,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 38,
\\"x\\": 186,
\\"y\\": 96,
\\"width\\": 17,
\\"height\\": 20,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 18,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 39,
\\"x\\": 134,
\\"y\\": 219,
\\"width\\": 5,
\\"height\\": 7,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 5,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 40,
\\"x\\": 220,
\\"y\\": 27,
\\"width\\": 8,
\\"height\\": 25,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 9,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 41,
\\"x\\": 229,
\\"y\\": 27,
\\"width\\": 8,
\\"height\\": 25,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 9,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 42,
\\"x\\": 101,
\\"y\\": 219,
\\"width\\": 11,
\\"height\\": 8,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 11,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 43,
\\"x\\": 192,
\\"y\\": 196,
\\"width\\": 14,
\\"height\\": 12,
\\"xoffset\\": 1,
\\"yoffset\\": 10,
\\"xadvance\\": 16,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 44,
\\"x\\": 148,
\\"y\\": 215,
\\"width\\": 4,
\\"height\\": 6,
\\"xoffset\\": 2,
\\"yoffset\\": 24,
\\"xadvance\\": 8,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 45,
\\"x\\": 230,
\\"y\\": 209,
\\"width\\": 9,
\\"height\\": 2,
\\"xoffset\\": 0,
\\"yoffset\\": 18,
\\"xadvance\\": 9,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 46,
\\"x\\": 148,
\\"y\\": 222,
\\"width\\": 4,
\\"height\\": 2,
\\"xoffset\\": 2,
\\"yoffset\\": 24,
\\"xadvance\\": 8,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 47,
\\"x\\": 199,
\\"y\\": 159,
\\"width\\": 10,
\\"height\\": 20,
\\"xoffset\\": -1,
\\"yoffset\\": 6,
\\"xadvance\\": 8,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 48,
\\"x\\": 0,
\\"y\\": 164,
\\"width\\": 14,
\\"height\\": 20,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 49,
\\"x\\": 220,
\\"y\\": 159,
\\"width\\": 9,
\\"height\\": 20,
\\"xoffset\\": 2,
\\"yoffset\\": 6,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 50,
\\"x\\": 185,
\\"y\\": 138,
\\"width\\": 14,
\\"height\\": 20,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 51,
\\"x\\": 60,
\\"y\\": 164,
\\"width\\": 13,
\\"height\\": 20,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 52,
\\"x\\": 155,
\\"y\\": 140,
\\"width\\": 14,
\\"height\\": 20,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 53,
\\"x\\": 74,
\\"y\\": 163,
\\"width\\": 13,
\\"height\\": 20,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 54,
\\"x\\": 140,
\\"y\\": 141,
\\"width\\": 14,
\\"height\\": 20,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 55,
\\"x\\": 172,
\\"y\\": 159,
\\"width\\": 13,
\\"height\\": 20,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 56,
\\"x\\": 154,
\\"y\\": 119,
\\"width\\": 15,
\\"height\\": 20,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 57,
\\"x\\": 240,
\\"y\\": 95,
\\"width\\": 15,
\\"height\\": 20,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 58,
\\"x\\": 142,
\\"y\\": 201,
\\"width\\": 4,
\\"height\\": 15,
\\"xoffset\\": 2,
\\"yoffset\\": 11,
\\"xadvance\\": 8,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 59,
\\"x\\": 67,
\\"y\\": 185,
\\"width\\": 4,
\\"height\\": 19,
\\"xoffset\\": 2,
\\"yoffset\\": 11,
\\"xadvance\\": 8,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 60,
\\"x\\": 177,
\\"y\\": 196,
\\"width\\": 14,
\\"height\\": 13,
\\"xoffset\\": 1,
\\"yoffset\\": 10,
\\"xadvance\\": 16,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 61,
\\"x\\": 71,
\\"y\\": 221,
\\"width\\": 14,
\\"height\\": 8,
\\"xoffset\\": 1,
\\"yoffset\\": 12,
\\"xadvance\\": 16,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 62,
\\"x\\": 162,
\\"y\\": 199,
\\"width\\": 14,
\\"height\\": 13,
\\"xoffset\\": 1,
\\"yoffset\\": 10,
\\"xadvance\\": 16,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 63,
\\"x\\": 88,
\\"y\\": 163,
\\"width\\": 13,
\\"height\\": 20,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 64,
\\"x\\": 0,
\\"y\\": 0,
\\"width\\": 26,
\\"height\\": 26,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 27,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 65,
\\"x\\": 231,
\\"y\\": 74,
\\"width\\": 19,
\\"height\\": 20,
\\"xoffset\\": -1,
\\"yoffset\\": 6,
\\"xadvance\\": 18,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 66,
\\"x\\": 137,
\\"y\\": 120,
\\"width\\": 16,
\\"height\\": 20,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 18,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 67,
\\"x\\": 39,
\\"y\\": 100,
\\"width\\": 18,
\\"height\\": 20,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 20,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 68,
\\"x\\": 168,
\\"y\\": 96,
\\"width\\": 17,
\\"height\\": 20,
\\"xoffset\\": 2,
\\"yoffset\\": 6,
\\"xadvance\\": 20,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 69,
\\"x\\": 69,
\\"y\\": 121,
\\"width\\": 16,
\\"height\\": 20,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 18,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 70,
\\"x\\": 170,
\\"y\\": 117,
\\"width\\": 15,
\\"height\\": 20,
\\"xoffset\\": 2,
\\"yoffset\\": 6,
\\"xadvance\\": 17,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 71,
\\"x\\": 0,
\\"y\\": 101,
\\"width\\": 19,
\\"height\\": 20,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 21,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 72,
\\"x\\": 132,
\\"y\\": 99,
\\"width\\": 17,
\\"height\\": 20,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 19,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 73,
\\"x\\": 7,
\\"y\\": 185,
\\"width\\": 4,
\\"height\\": 20,
\\"xoffset\\": 2,
\\"yoffset\\": 6,
\\"xadvance\\": 8,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 74,
\\"x\\": 186,
\\"y\\": 159,
\\"width\\": 12,
\\"height\\": 20,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 13,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 75,
\\"x\\": 20,
\\"y\\": 101,
\\"width\\": 18,
\\"height\\": 20,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 18,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 76,
\\"x\\": 170,
\\"y\\": 138,
\\"width\\": 14,
\\"height\\": 20,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 77,
\\"x\\": 167,
\\"y\\": 75,
\\"width\\": 21,
\\"height\\": 20,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 23,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 78,
\\"x\\": 96,
\\"y\\": 100,
\\"width\\": 17,
\\"height\\": 20,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 19,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 79,
\\"x\\": 210,
\\"y\\": 75,
\\"width\\": 20,
\\"height\\": 20,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 21,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 80,
\\"x\\": 52,
\\"y\\": 121,
\\"width\\": 16,
\\"height\\": 20,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 17,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 81,
\\"x\\": 155,
\\"y\\": 53,
\\"width\\": 21,
\\"height\\": 21,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 21,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 82,
\\"x\\": 77,
\\"y\\": 100,
\\"width\\": 18,
\\"height\\": 20,
\\"xoffset\\": 2,
\\"yoffset\\": 6,
\\"xadvance\\": 20,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 83,
\\"x\\": 35,
\\"y\\": 122,
\\"width\\": 16,
\\"height\\": 20,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 18,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 84,
\\"x\\": 18,
\\"y\\": 122,
\\"width\\": 16,
\\"height\\": 20,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 16,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 85,
\\"x\\": 222,
\\"y\\": 96,
\\"width\\": 17,
\\"height\\": 20,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 19,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 86,
\\"x\\": 150,
\\"y\\": 98,
\\"width\\": 17,
\\"height\\": 20,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 17,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 87,
\\"x\\": 227,
\\"y\\": 53,
\\"width\\": 28,
\\"height\\": 20,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 28,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 88,
\\"x\\": 0,
\\"y\\": 122,
\\"width\\": 17,
\\"height\\": 20,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 17,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 89,
\\"x\\": 58,
\\"y\\": 100,
\\"width\\": 18,
\\"height\\": 20,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 18,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 90,
\\"x\\": 114,
\\"y\\": 99,
\\"width\\": 17,
\\"height\\": 20,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 17,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 91,
\\"x\\": 0,
\\"y\\": 54,
\\"width\\": 7,
\\"height\\": 25,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 8,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 92,
\\"x\\": 210,
\\"y\\": 159,
\\"width\\": 9,
\\"height\\": 20,
\\"xoffset\\": -1,
\\"yoffset\\": 6,
\\"xadvance\\": 8,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 93,
\\"x\\": 246,
\\"y\\": 27,
\\"width\\": 7,
\\"height\\": 25,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 8,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 94,
\\"x\\": 16,
\\"y\\": 222,
\\"width\\": 12,
\\"height\\": 10,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 12,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 95,
\\"x\\": 202,
\\"y\\": 209,
\\"width\\": 17,
\\"height\\": 2,
\\"xoffset\\": -1,
\\"yoffset\\": 29,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 96,
\\"x\\": 170,
\\"y\\": 213,
\\"width\\": 6,
\\"height\\": 4,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 9,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 97,
\\"x\\": 241,
\\"y\\": 180,
\\"width\\": 14,
\\"height\\": 15,
\\"xoffset\\": 0,
\\"yoffset\\": 11,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 98,
\\"x\\": 215,
\\"y\\": 138,
\\"width\\": 14,
\\"height\\": 20,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 99,
\\"x\\": 91,
\\"y\\": 203,
\\"width\\": 13,
\\"height\\": 15,
\\"xoffset\\": 0,
\\"yoffset\\": 11,
\\"xadvance\\": 14,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 100,
\\"x\\": 15,
\\"y\\": 164,
\\"width\\": 14,
\\"height\\": 20,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 101,
\\"x\\": 16,
\\"y\\": 206,
\\"width\\": 15,
\\"height\\": 15,
\\"xoffset\\": 0,
\\"yoffset\\": 11,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 102,
\\"x\\": 245,
\\"y\\": 138,
\\"width\\": 10,
\\"height\\": 20,
\\"xoffset\\": -1,
\\"yoffset\\": 6,
\\"xadvance\\": 7,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 103,
\\"x\\": 30,
\\"y\\": 164,
\\"width\\": 14,
\\"height\\": 20,
\\"xoffset\\": 0,
\\"yoffset\\": 11,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 104,
\\"x\\": 144,
\\"y\\": 162,
\\"width\\": 13,
\\"height\\": 20,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 105,
\\"x\\": 17,
\\"y\\": 185,
\\"width\\": 4,
\\"height\\": 20,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 6,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 106,
\\"x\\": 238,
\\"y\\": 27,
\\"width\\": 7,
\\"height\\": 25,
\\"xoffset\\": -2,
\\"yoffset\\": 6,
\\"xadvance\\": 6,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 107,
\\"x\\": 158,
\\"y\\": 161,
\\"width\\": 13,
\\"height\\": 20,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 14,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 108,
\\"x\\": 12,
\\"y\\": 185,
\\"width\\": 4,
\\"height\\": 20,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 6,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 109,
\\"x\\": 199,
\\"y\\": 180,
\\"width\\": 20,
\\"height\\": 15,
\\"xoffset\\": 1,
\\"yoffset\\": 11,
\\"xadvance\\": 22,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 110,
\\"x\\": 77,
\\"y\\": 204,
\\"width\\": 13,
\\"height\\": 15,
\\"xoffset\\": 1,
\\"yoffset\\": 11,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 111,
\\"x\\": 0,
\\"y\\": 206,
\\"width\\": 15,
\\"height\\": 15,
\\"xoffset\\": 0,
\\"yoffset\\": 11,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 112,
\\"x\\": 80,
\\"y\\": 142,
\\"width\\": 14,
\\"height\\": 20,
\\"xoffset\\": 1,
\\"yoffset\\": 11,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 113,
\\"x\\": 95,
\\"y\\": 142,
\\"width\\": 14,
\\"height\\": 20,
\\"xoffset\\": 0,
\\"yoffset\\": 11,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 114,
\\"x\\": 132,
\\"y\\": 203,
\\"width\\": 9,
\\"height\\": 15,
\\"xoffset\\": 1,
\\"yoffset\\": 11,
\\"xadvance\\": 9,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 115,
\\"x\\": 48,
\\"y\\": 205,
\\"width\\": 14,
\\"height\\": 15,
\\"xoffset\\": 0,
\\"yoffset\\": 11,
\\"xadvance\\": 14,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 116,
\\"x\\": 239,
\\"y\\": 159,
\\"width\\": 8,
\\"height\\": 20,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 8,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 117,
\\"x\\": 105,
\\"y\\": 203,
\\"width\\": 13,
\\"height\\": 15,
\\"xoffset\\": 1,
\\"yoffset\\": 11,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 118,
\\"x\\": 32,
\\"y\\": 205,
\\"width\\": 15,
\\"height\\": 15,
\\"xoffset\\": -1,
\\"yoffset\\": 11,
\\"xadvance\\": 13,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 119,
\\"x\\": 220,
\\"y\\": 180,
\\"width\\": 20,
\\"height\\": 15,
\\"xoffset\\": -1,
\\"yoffset\\": 11,
\\"xadvance\\": 19,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 120,
\\"x\\": 119,
\\"y\\": 203,
\\"width\\": 12,
\\"height\\": 15,
\\"xoffset\\": 0,
\\"yoffset\\": 11,
\\"xadvance\\": 12,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 121,
\\"x\\": 230,
\\"y\\": 138,
\\"width\\": 14,
\\"height\\": 20,
\\"xoffset\\": 0,
\\"yoffset\\": 11,
\\"xadvance\\": 14,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 122,
\\"x\\": 63,
\\"y\\": 205,
\\"width\\": 13,
\\"height\\": 15,
\\"xoffset\\": 0,
\\"yoffset\\": 11,
\\"xadvance\\": 13,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 123,
\\"x\\": 200,
\\"y\\": 27,
\\"width\\": 9,
\\"height\\": 25,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 9,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 124,
\\"x\\": 13,
\\"y\\": 54,
\\"width\\": 4,
\\"height\\": 25,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 6,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 125,
\\"x\\": 210,
\\"y\\": 27,
\\"width\\": 9,
\\"height\\": 25,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 9,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 126,
\\"x\\": 153,
\\"y\\": 215,
\\"width\\": 16,
\\"height\\": 4,
\\"xoffset\\": 0,
\\"yoffset\\": 14,
\\"xadvance\\": 16,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 160,
\\"x\\": 159,
\\"y\\": 75,
\\"width\\": 3,
\\"height\\": 1,
\\"xoffset\\": -1,
\\"yoffset\\": 31,
\\"xadvance\\": 8,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 161,
\\"x\\": 251,
\\"y\\": 74,
\\"width\\": 4,
\\"height\\": 20,
\\"xoffset\\": 2,
\\"yoffset\\": 11,
\\"xadvance\\": 8,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 162,
\\"x\\": 186,
\\"y\\": 27,
\\"width\\": 13,
\\"height\\": 25,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 163,
\\"x\\": 218,
\\"y\\": 117,
\\"width\\": 15,
\\"height\\": 20,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 164,
\\"x\\": 147,
\\"y\\": 201,
\\"width\\": 14,
\\"height\\": 13,
\\"xoffset\\": 0,
\\"yoffset\\": 10,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 165,
\\"x\\": 86,
\\"y\\": 121,
\\"width\\": 16,
\\"height\\": 20,
\\"xoffset\\": -1,
\\"yoffset\\": 6,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 166,
\\"x\\": 8,
\\"y\\": 54,
\\"width\\": 4,
\\"height\\": 25,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 6,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 167,
\\"x\\": 156,
\\"y\\": 27,
\\"width\\": 14,
\\"height\\": 25,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 168,
\\"x\\": 240,
\\"y\\": 208,
\\"width\\": 9,
\\"height\\": 2,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 9,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 169,
\\"x\\": 121,
\\"y\\": 78,
\\"width\\": 22,
\\"height\\": 20,
\\"xoffset\\": -1,
\\"yoffset\\": 6,
\\"xadvance\\": 20,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 170,
\\"x\\": 40,
\\"y\\": 221,
\\"width\\": 10,
\\"height\\": 10,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 10,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 171,
\\"x\\": 221,
\\"y\\": 196,
\\"width\\": 13,
\\"height\\": 12,
\\"xoffset\\": 1,
\\"yoffset\\": 13,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 172,
\\"x\\": 86,
\\"y\\": 220,
\\"width\\": 14,
\\"height\\": 8,
\\"xoffset\\": 1,
\\"yoffset\\": 12,
\\"xadvance\\": 16,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 173,
\\"x\\": 220,
\\"y\\": 209,
\\"width\\": 9,
\\"height\\": 2,
\\"xoffset\\": 0,
\\"yoffset\\": 18,
\\"xadvance\\": 9,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 174,
\\"x\\": 98,
\\"y\\": 78,
\\"width\\": 22,
\\"height\\": 20,
\\"xoffset\\": -1,
\\"yoffset\\": 6,
\\"xadvance\\": 20,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 175,
\\"x\\": 184,
\\"y\\": 210,
\\"width\\": 17,
\\"height\\": 2,
\\"xoffset\\": -1,
\\"yoffset\\": 3,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 176,
\\"x\\": 124,
\\"y\\": 219,
\\"width\\": 9,
\\"height\\": 7,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 11,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 177,
\\"x\\": 158,
\\"y\\": 182,
\\"width\\": 15,
\\"height\\": 16,
\\"xoffset\\": 0,
\\"yoffset\\": 10,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 178,
\\"x\\": 61,
\\"y\\": 221,
\\"width\\": 9,
\\"height\\": 10,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 9,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 179,
\\"x\\": 51,
\\"y\\": 221,
\\"width\\": 9,
\\"height\\": 10,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 9,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 180,
\\"x\\": 177,
\\"y\\": 210,
\\"width\\": 6,
\\"height\\": 4,
\\"xoffset\\": 2,
\\"yoffset\\": 6,
\\"xadvance\\": 9,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 181,
\\"x\\": 110,
\\"y\\": 142,
\\"width\\": 14,
\\"height\\": 20,
\\"xoffset\\": 1,
\\"yoffset\\": 11,
\\"xadvance\\": 16,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 182,
\\"x\\": 105,
\\"y\\": 27,
\\"width\\": 17,
\\"height\\": 25,
\\"xoffset\\": -1,
\\"yoffset\\": 6,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 183,
\\"x\\": 250,
\\"y\\": 207,
\\"width\\": 5,
\\"height\\": 2,
\\"xoffset\\": 2,
\\"yoffset\\": 16,
\\"xadvance\\": 9,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 184,
\\"x\\": 140,
\\"y\\": 219,
\\"width\\": 7,
\\"height\\": 6,
\\"xoffset\\": 1,
\\"yoffset\\": 26,
\\"xadvance\\": 9,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 185,
\\"x\\": 249,
\\"y\\": 196,
\\"width\\": 6,
\\"height\\": 10,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 9,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 186,
\\"x\\": 29,
\\"y\\": 222,
\\"width\\": 10,
\\"height\\": 10,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 10,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 187,
\\"x\\": 207,
\\"y\\": 196,
\\"width\\": 13,
\\"height\\": 12,
\\"xoffset\\": 1,
\\"yoffset\\": 13,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 188,
\\"x\\": 144,
\\"y\\": 77,
\\"width\\": 22,
\\"height\\": 20,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 23,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 189,
\\"x\\": 52,
\\"y\\": 79,
\\"width\\": 22,
\\"height\\": 20,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 23,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 190,
\\"x\\": 28,
\\"y\\": 79,
\\"width\\": 23,
\\"height\\": 20,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 23,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 191,
\\"x\\": 202,
\\"y\\": 117,
\\"width\\": 15,
\\"height\\": 20,
\\"xoffset\\": 1,
\\"yoffset\\": 11,
\\"xadvance\\": 17,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 192,
\\"x\\": 130,
\\"y\\": 0,
\\"width\\": 19,
\\"height\\": 26,
\\"xoffset\\": -1,
\\"yoffset\\": 0,
\\"xadvance\\": 18,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 193,
\\"x\\": 110,
\\"y\\": 0,
\\"width\\": 19,
\\"height\\": 26,
\\"xoffset\\": -1,
\\"yoffset\\": 0,
\\"xadvance\\": 18,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 194,
\\"x\\": 90,
\\"y\\": 0,
\\"width\\": 19,
\\"height\\": 26,
\\"xoffset\\": -1,
\\"yoffset\\": 0,
\\"xadvance\\": 18,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 195,
\\"x\\": 85,
\\"y\\": 27,
\\"width\\": 19,
\\"height\\": 25,
\\"xoffset\\": -1,
\\"yoffset\\": 1,
\\"xadvance\\": 18,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 196,
\\"x\\": 59,
\\"y\\": 54,
\\"width\\": 19,
\\"height\\": 24,
\\"xoffset\\": -1,
\\"yoffset\\": 2,
\\"xadvance\\": 18,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 197,
\\"x\\": 39,
\\"y\\": 54,
\\"width\\": 19,
\\"height\\": 24,
\\"xoffset\\": -1,
\\"yoffset\\": 2,
\\"xadvance\\": 18,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 198,
\\"x\\": 0,
\\"y\\": 80,
\\"width\\": 27,
\\"height\\": 20,
\\"xoffset\\": -1,
\\"yoffset\\": 6,
\\"xadvance\\": 27,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 199,
\\"x\\": 150,
\\"y\\": 0,
\\"width\\": 18,
\\"height\\": 26,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 20,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 200,
\\"x\\": 17,
\\"y\\": 27,
\\"width\\": 16,
\\"height\\": 26,
\\"xoffset\\": 1,
\\"yoffset\\": 0,
\\"xadvance\\": 18,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 201,
\\"x\\": 34,
\\"y\\": 27,
\\"width\\": 16,
\\"height\\": 26,
\\"xoffset\\": 1,
\\"yoffset\\": 0,
\\"xadvance\\": 18,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 202,
\\"x\\": 0,
\\"y\\": 27,
\\"width\\": 16,
\\"height\\": 26,
\\"xoffset\\": 1,
\\"yoffset\\": 0,
\\"xadvance\\": 18,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 203,
\\"x\\": 97,
\\"y\\": 53,
\\"width\\": 16,
\\"height\\": 24,
\\"xoffset\\": 1,
\\"yoffset\\": 2,
\\"xadvance\\": 18,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 204,
\\"x\\": 58,
\\"y\\": 27,
\\"width\\": 5,
\\"height\\": 26,
\\"xoffset\\": 1,
\\"yoffset\\": 0,
\\"xadvance\\": 8,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 205,
\\"x\\": 51,
\\"y\\": 27,
\\"width\\": 6,
\\"height\\": 26,
\\"xoffset\\": 2,
\\"yoffset\\": 0,
\\"xadvance\\": 8,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 206,
\\"x\\": 242,
\\"y\\": 0,
\\"width\\": 10,
\\"height\\": 26,
\\"xoffset\\": -1,
\\"yoffset\\": 0,
\\"xadvance\\": 8,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 207,
\\"x\\": 114,
\\"y\\": 53,
\\"width\\": 9,
\\"height\\": 24,
\\"xoffset\\": -1,
\\"yoffset\\": 2,
\\"xadvance\\": 8,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 208,
\\"x\\": 189,
\\"y\\": 75,
\\"width\\": 20,
\\"height\\": 20,
\\"xoffset\\": -1,
\\"yoffset\\": 6,
\\"xadvance\\": 20,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 209,
\\"x\\": 123,
\\"y\\": 27,
\\"width\\": 17,
\\"height\\": 25,
\\"xoffset\\": 1,
\\"yoffset\\": 1,
\\"xadvance\\": 19,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 210,
\\"x\\": 69,
\\"y\\": 0,
\\"width\\": 20,
\\"height\\": 26,
\\"xoffset\\": 1,
\\"yoffset\\": 0,
\\"xadvance\\": 21,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 211,
\\"x\\": 48,
\\"y\\": 0,
\\"width\\": 20,
\\"height\\": 26,
\\"xoffset\\": 1,
\\"yoffset\\": 0,
\\"xadvance\\": 21,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 212,
\\"x\\": 27,
\\"y\\": 0,
\\"width\\": 20,
\\"height\\": 26,
\\"xoffset\\": 1,
\\"yoffset\\": 0,
\\"xadvance\\": 21,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 213,
\\"x\\": 64,
\\"y\\": 27,
\\"width\\": 20,
\\"height\\": 25,
\\"xoffset\\": 1,
\\"yoffset\\": 1,
\\"xadvance\\": 21,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 214,
\\"x\\": 18,
\\"y\\": 54,
\\"width\\": 20,
\\"height\\": 24,
\\"xoffset\\": 1,
\\"yoffset\\": 2,
\\"xadvance\\": 21,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 215,
\\"x\\": 235,
\\"y\\": 196,
\\"width\\": 13,
\\"height\\": 11,
\\"xoffset\\": 1,
\\"yoffset\\": 11,
\\"xadvance\\": 16,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 216,
\\"x\\": 177,
\\"y\\": 53,
\\"width\\": 20,
\\"height\\": 21,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 21,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 217,
\\"x\\": 224,
\\"y\\": 0,
\\"width\\": 17,
\\"height\\": 26,
\\"xoffset\\": 1,
\\"yoffset\\": 0,
\\"xadvance\\": 19,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 218,
\\"x\\": 206,
\\"y\\": 0,
\\"width\\": 17,
\\"height\\": 26,
\\"xoffset\\": 1,
\\"yoffset\\": 0,
\\"xadvance\\": 19,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 219,
\\"x\\": 188,
\\"y\\": 0,
\\"width\\": 17,
\\"height\\": 26,
\\"xoffset\\": 1,
\\"yoffset\\": 0,
\\"xadvance\\": 19,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 220,
\\"x\\": 79,
\\"y\\": 53,
\\"width\\": 17,
\\"height\\": 24,
\\"xoffset\\": 1,
\\"yoffset\\": 2,
\\"xadvance\\": 19,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 221,
\\"x\\": 169,
\\"y\\": 0,
\\"width\\": 18,
\\"height\\": 26,
\\"xoffset\\": 0,
\\"yoffset\\": 0,
\\"xadvance\\": 18,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 222,
\\"x\\": 204,
\\"y\\": 96,
\\"width\\": 17,
\\"height\\": 20,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 18,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 223,
\\"x\\": 103,
\\"y\\": 121,
\\"width\\": 16,
\\"height\\": 20,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 17,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 224,
\\"x\\": 45,
\\"y\\": 164,
\\"width\\": 14,
\\"height\\": 20,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 225,
\\"x\\": 200,
\\"y\\": 138,
\\"width\\": 14,
\\"height\\": 20,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 226,
\\"x\\": 125,
\\"y\\": 141,
\\"width\\": 14,
\\"height\\": 20,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 227,
\\"x\\": 38,
\\"y\\": 185,
\\"width\\": 14,
\\"height\\": 19,
\\"xoffset\\": 0,
\\"yoffset\\": 7,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 228,
\\"x\\": 104,
\\"y\\": 184,
\\"width\\": 14,
\\"height\\": 18,
\\"xoffset\\": 0,
\\"yoffset\\": 8,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 229,
\\"x\\": 198,
\\"y\\": 53,
\\"width\\": 14,
\\"height\\": 21,
\\"xoffset\\": 0,
\\"yoffset\\": 5,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 230,
\\"x\\": 174,
\\"y\\": 180,
\\"width\\": 24,
\\"height\\": 15,
\\"xoffset\\": 0,
\\"yoffset\\": 11,
\\"xadvance\\": 24,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 231,
\\"x\\": 213,
\\"y\\": 53,
\\"width\\": 13,
\\"height\\": 21,
\\"xoffset\\": 0,
\\"yoffset\\": 11,
\\"xadvance\\": 14,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 232,
\\"x\\": 186,
\\"y\\": 117,
\\"width\\": 15,
\\"height\\": 20,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 233,
\\"x\\": 0,
\\"y\\": 143,
\\"width\\": 15,
\\"height\\": 20,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 234,
\\"x\\": 16,
\\"y\\": 143,
\\"width\\": 15,
\\"height\\": 20,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 235,
\\"x\\": 88,
\\"y\\": 184,
\\"width\\": 15,
\\"height\\": 18,
\\"xoffset\\": 0,
\\"yoffset\\": 8,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 236,
\\"x\\": 0,
\\"y\\": 185,
\\"width\\": 6,
\\"height\\": 20,
\\"xoffset\\": -1,
\\"yoffset\\": 6,
\\"xadvance\\": 6,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 237,
\\"x\\": 248,
\\"y\\": 159,
\\"width\\": 6,
\\"height\\": 20,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 6,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 238,
\\"x\\": 230,
\\"y\\": 159,
\\"width\\": 8,
\\"height\\": 20,
\\"xoffset\\": -1,
\\"yoffset\\": 6,
\\"xadvance\\": 6,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 239,
\\"x\\": 133,
\\"y\\": 183,
\\"width\\": 8,
\\"height\\": 18,
\\"xoffset\\": -1,
\\"yoffset\\": 8,
\\"xadvance\\": 6,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 240,
\\"x\\": 234,
\\"y\\": 117,
\\"width\\": 15,
\\"height\\": 20,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 241,
\\"x\\": 53,
\\"y\\": 185,
\\"width\\": 13,
\\"height\\": 19,
\\"xoffset\\": 1,
\\"yoffset\\": 7,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 242,
\\"x\\": 32,
\\"y\\": 143,
\\"width\\": 15,
\\"height\\": 20,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 243,
\\"x\\": 48,
\\"y\\": 143,
\\"width\\": 15,
\\"height\\": 20,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 244,
\\"x\\": 64,
\\"y\\": 142,
\\"width\\": 15,
\\"height\\": 20,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 245,
\\"x\\": 22,
\\"y\\": 185,
\\"width\\": 15,
\\"height\\": 19,
\\"xoffset\\": 0,
\\"yoffset\\": 7,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 246,
\\"x\\": 72,
\\"y\\": 185,
\\"width\\": 15,
\\"height\\": 18,
\\"xoffset\\": 0,
\\"yoffset\\": 8,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 247,
\\"x\\": 0,
\\"y\\": 222,
\\"width\\": 15,
\\"height\\": 10,
\\"xoffset\\": 0,
\\"yoffset\\": 11,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 248,
\\"x\\": 142,
\\"y\\": 183,
\\"width\\": 15,
\\"height\\": 17,
\\"xoffset\\": 1,
\\"yoffset\\": 10,
\\"xadvance\\": 17,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 249,
\\"x\\": 102,
\\"y\\": 163,
\\"width\\": 13,
\\"height\\": 20,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 250,
\\"x\\": 116,
\\"y\\": 163,
\\"width\\": 13,
\\"height\\": 20,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 251,
\\"x\\": 130,
\\"y\\": 162,
\\"width\\": 13,
\\"height\\": 20,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 252,
\\"x\\": 119,
\\"y\\": 184,
\\"width\\": 13,
\\"height\\": 18,
\\"xoffset\\": 1,
\\"yoffset\\": 8,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 253,
\\"x\\": 171,
\\"y\\": 27,
\\"width\\": 14,
\\"height\\": 25,
\\"xoffset\\": 0,
\\"yoffset\\": 6,
\\"xadvance\\": 14,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 254,
\\"x\\": 141,
\\"y\\": 27,
\\"width\\": 14,
\\"height\\": 25,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 15
}, {
\\"id\\": 255,
\\"x\\": 140,
\\"y\\": 53,
\\"width\\": 14,
\\"height\\": 23,
\\"xoffset\\": 0,
\\"yoffset\\": 8,
\\"xadvance\\": 14,
\\"page\\": 0,
\\"chnl\\": 15
}],
\\"info\\": {
\\"size\\": 32,
\\"smooth\\": 1,
\\"unicode\\": 1,
\\"italic\\": 0,
\\"bold\\": 0,
\\"charset\\": \\"\\",
\\"stretchH\\": 100,
\\"aa\\": 1,
\\"padding\\": [0, 0, 0, 0],
\\"spacing\\": [1, 1],
\\"outline\\": 0,
\\"face\\": \\"Arial\\"
},
\\"common\\": {
\\"lineHeight\\": 32,
\\"base\\": 26,
\\"scaleW\\": 256,
\\"scaleH\\": 256,
\\"pages\\": 1,
\\"packed\\": 0,
\\"alphaChnl\\": 1,
\\"redChnl\\": 0,
\\"greenChnl\\": 0,
\\"blueChnl\\": 0
},
\\"pages\\": [typeof require(\\"./font-bin_0.tga\\") === \\"object\\" && require(\\"./font-bin_0.tga\\") != null && require(\\"./font-bin_0.tga\\").__esModule && {}.hasOwnProperty.call(require(\\"./font-bin_0.tga\\"), \\"default\\") ? require(\\"./font-bin_0.tga\\").default : require(\\"./font-bin_0.tga\\")]
};"
`);
});
test("parseFont - xml", async () => {
expect(await parseFont("fixtures/xml.fnt")).toMatchInlineSnapshot(`
"module.exports = {
\\"pages\\": [typeof require(\\"./sheet.png\\") === \\"object\\" && require(\\"./sheet.png\\") != null && require(\\"./sheet.png\\").__esModule && {}.hasOwnProperty.call(require(\\"./sheet.png\\"), \\"default\\") ? require(\\"./sheet.png\\").default : require(\\"./sheet.png\\")],
\\"chars\\": [{
\\"id\\": 10,
\\"x\\": 281,
\\"y\\": 9,
\\"width\\": 0,
\\"height\\": 0,
\\"xoffset\\": 0,
\\"yoffset\\": 24,
\\"xadvance\\": 8,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 32,
\\"x\\": 0,
\\"y\\": 0,
\\"width\\": 0,
\\"height\\": 0,
\\"xoffset\\": 0,
\\"yoffset\\": 0,
\\"xadvance\\": 9,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 33,
\\"x\\": 739,
\\"y\\": 162,
\\"width\\": 4,
\\"height\\": 23,
\\"xoffset\\": 1,
\\"yoffset\\": 2,
\\"xadvance\\": 6,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 34,
\\"x\\": 288,
\\"y\\": 127,
\\"width\\": 7,
\\"height\\": 8,
\\"xoffset\\": 1,
\\"yoffset\\": 2,
\\"xadvance\\": 10,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 35,
\\"x\\": 771,
\\"y\\": 162,
\\"width\\": 19,
\\"height\\": 22,
\\"xoffset\\": 0,
\\"yoffset\\": 2,
\\"xadvance\\": 20,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 36,
\\"x\\": 350,
\\"y\\": 213,
\\"width\\": 19,
\\"height\\": 29,
\\"xoffset\\": 0,
\\"yoffset\\": -2,
\\"xadvance\\": 20,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 37,
\\"x\\": 745,
\\"y\\": 162,
\\"width\\": 24,
\\"height\\": 23,
\\"xoffset\\": -1,
\\"yoffset\\": 1,
\\"xadvance\\": 23,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 38,
\\"x\\": 792,
\\"y\\": 162,
\\"width\\": 19,
\\"height\\": 22,
\\"xoffset\\": 2,
\\"yoffset\\": 2,
\\"xadvance\\": 23,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 39,
\\"x\\": 245,
\\"y\\": 127,
\\"width\\": 2,
\\"height\\": 8,
\\"xoffset\\": 2,
\\"yoffset\\": 2,
\\"xadvance\\": 7,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 40,
\\"x\\": 223,
\\"y\\": 213,
\\"width\\": 11,
\\"height\\": 29,
\\"xoffset\\": 0,
\\"yoffset\\": -1,
\\"xadvance\\": 12,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 41,
\\"x\\": 236,
\\"y\\": 213,
\\"width\\": 11,
\\"height\\": 29,
\\"xoffset\\": 0,
\\"yoffset\\": -1,
\\"xadvance\\": 11,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 42,
\\"x\\": 385,
\\"y\\": 107,
\\"width\\": 7,
\\"height\\": 6,
\\"xoffset\\": 1,
\\"yoffset\\": 2,
\\"xadvance\\": 9,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 43,
\\"x\\": 876,
\\"y\\": 116,
\\"width\\": 14,
\\"height\\": 12,
\\"xoffset\\": 1,
\\"yoffset\\": 7,
\\"xadvance\\": 16,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 44,
\\"x\\": 361,
\\"y\\": 107,
\\"width\\": 4,
\\"height\\": 6,
\\"xoffset\\": 0,
\\"yoffset\\": 21,
\\"xadvance\\": 6,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 45,
\\"x\\": 445,
\\"y\\": 73,
\\"width\\": 13,
\\"height\\": 2,
\\"xoffset\\": 1,
\\"yoffset\\": 13,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 46,
\\"x\\": 398,
\\"y\\": 73,
\\"width\\": 3,
\\"height\\": 4,
\\"xoffset\\": 1,
\\"yoffset\\": 21,
\\"xadvance\\": 6,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 47,
\\"x\\": 289,
\\"y\\": 213,
\\"width\\": 15,
\\"height\\": 27,
\\"xoffset\\": -1,
\\"yoffset\\": 0,
\\"xadvance\\": 14,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 48,
\\"x\\": 590,
\\"y\\": 244,
\\"width\\": 18,
\\"height\\": 30,
\\"xoffset\\": 1,
\\"yoffset\\": -2,
\\"xadvance\\": 20,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 49,
\\"x\\": 586,
\\"y\\": 162,
\\"width\\": 10,
\\"height\\": 22,
\\"xoffset\\": 0,
\\"yoffset\\": 2,
\\"xadvance\\": 11,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 50,
\\"x\\": 598,
\\"y\\": 162,
\\"width\\": 18,
\\"height\\": 22,
\\"xoffset\\": 1,
\\"yoffset\\": 2,
\\"xadvance\\": 21,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 51,
\\"x\\": 618,
\\"y\\": 162,
\\"width\\": 17,
\\"height\\": 22,
\\"xoffset\\": 1,
\\"yoffset\\": 2,
\\"xadvance\\": 20,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 52,
\\"x\\": 637,
\\"y\\": 162,
\\"width\\": 19,
\\"height\\": 22,
\\"xoffset\\": 0,
\\"yoffset\\": 2,
\\"xadvance\\": 20,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 53,
\\"x\\": 658,
\\"y\\": 162,
\\"width\\": 18,
\\"height\\": 22,
\\"xoffset\\": 1,
\\"yoffset\\": 2,
\\"xadvance\\": 20,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 54,
\\"x\\": 678,
\\"y\\": 162,
\\"width\\": 19,
\\"height\\": 22,
\\"xoffset\\": 1,
\\"yoffset\\": 2,
\\"xadvance\\": 21,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 55,
\\"x\\": 699,
\\"y\\": 162,
\\"width\\": 18,
\\"height\\": 22,
\\"xoffset\\": 0,
\\"yoffset\\": 2,
\\"xadvance\\": 19,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 56,
\\"x\\": 142,
\\"y\\": 187,
\\"width\\": 19,
\\"height\\": 24,
\\"xoffset\\": 1,
\\"yoffset\\": 1,
\\"xadvance\\": 22,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 57,
\\"x\\": 719,
\\"y\\": 162,
\\"width\\": 18,
\\"height\\": 22,
\\"xoffset\\": 1,
\\"yoffset\\": 2,
\\"xadvance\\": 22,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 58,
\\"x\\": 832,
\\"y\\": 116,
\\"width\\": 3,
\\"height\\": 14,
\\"xoffset\\": 2,
\\"yoffset\\": 11,
\\"xadvance\\": 7,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 59,
\\"x\\": 826,
\\"y\\": 116,
\\"width\\": 4,
\\"height\\": 16,
\\"xoffset\\": 1,
\\"yoffset\\": 11,
\\"xadvance\\": 7,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 60,
\\"x\\": 837,
\\"y\\": 116,
\\"width\\": 8,
\\"height\\": 14,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 11,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 61,
\\"x\\": 858,
\\"y\\": 128,
\\"width\\": 13,
\\"height\\": 7,
\\"xoffset\\": 1,
\\"yoffset\\": 10,
\\"xadvance\\": 16,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 62,
\\"x\\": 847,
\\"y\\": 116,
\\"width\\": 9,
\\"height\\": 13,
\\"xoffset\\": 1,
\\"yoffset\\": 7,
\\"xadvance\\": 11,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 63,
\\"x\\": 163,
\\"y\\": 187,
\\"width\\": 18,
\\"height\\": 24,
\\"xoffset\\": 1,
\\"yoffset\\": 2,
\\"xadvance\\": 21,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 64,
\\"x\\": 306,
\\"y\\": 213,
\\"width\\": 25,
\\"height\\": 25,
\\"xoffset\\": 2,
\\"yoffset\\": 2,
\\"xadvance\\": 30,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 65,
\\"x\\": 799,
\\"y\\": 138,
\\"width\\": 23,
\\"height\\": 22,
\\"xoffset\\": -1,
\\"yoffset\\": 2,
\\"xadvance\\": 22,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 66,
\\"x\\": 824,
\\"y\\": 138,
\\"width\\": 18,
\\"height\\": 22,
\\"xoffset\\": 2,
\\"yoffset\\": 2,
\\"xadvance\\": 21,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 67,
\\"x\\": 844,
\\"y\\": 138,
\\"width\\": 20,
\\"height\\": 22,
\\"xoffset\\": 1,
\\"yoffset\\": 2,
\\"xadvance\\": 22,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 68,
\\"x\\": 866,
\\"y\\": 138,
\\"width\\": 19,
\\"height\\": 22,
\\"xoffset\\": 2,
\\"yoffset\\": 2,
\\"xadvance\\": 23,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 69,
\\"x\\": 887,
\\"y\\": 138,
\\"width\\": 16,
\\"height\\": 22,
\\"xoffset\\": 2,
\\"yoffset\\": 2,
\\"xadvance\\": 20,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 70,
\\"x\\": 905,
\\"y\\": 138,
\\"width\\": 16,
\\"height\\": 22,
\\"xoffset\\": 2,
\\"yoffset\\": 2,
\\"xadvance\\": 19,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 71,
\\"x\\": 923,
\\"y\\": 138,
\\"width\\": 20,
\\"height\\": 22,
\\"xoffset\\": 1,
\\"yoffset\\": 2,
\\"xadvance\\": 24,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 72,
\\"x\\": 945,
\\"y\\": 138,
\\"width\\": 18,
\\"height\\": 22,
\\"xoffset\\": 2,
\\"yoffset\\": 2,
\\"xadvance\\": 23,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 73,
\\"x\\": 965,
\\"y\\": 138,
\\"width\\": 2,
\\"height\\": 22,
\\"xoffset\\": 2,
\\"yoffset\\": 2,
\\"xadvance\\": 7,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 74,
\\"x\\": 969,
\\"y\\": 138,
\\"width\\": 18,
\\"height\\": 22,
\\"xoffset\\": 1,
\\"yoffset\\": 2,
\\"xadvance\\": 22,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 75,
\\"x\\": 989,
\\"y\\": 138,
\\"width\\": 16,
\\"height\\": 22,
\\"xoffset\\": 2,
\\"yoffset\\": 2,
\\"xadvance\\": 18,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 76,
\\"x\\": 1007,
\\"y\\": 138,
\\"width\\": 15,
\\"height\\": 22,
\\"xoffset\\": 2,
\\"yoffset\\": 2,
\\"xadvance\\": 18,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 77,
\\"x\\": 127,
\\"y\\": 162,
\\"width\\": 22,
\\"height\\": 22,
\\"xoffset\\": 2,
\\"yoffset\\": 2,
\\"xadvance\\": 26,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 78,
\\"x\\": 151,
\\"y\\": 162,
\\"width\\": 18,
\\"height\\": 22,
\\"xoffset\\": 2,
\\"yoffset\\": 2,
\\"xadvance\\": 23,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 79,
\\"x\\": 171,
\\"y\\": 162,
\\"width\\": 23,
\\"height\\": 22,
\\"xoffset\\": 1,
\\"yoffset\\": 2,
\\"xadvance\\": 26,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 80,
\\"x\\": 196,
\\"y\\": 162,
\\"width\\": 20,
\\"height\\": 22,
\\"xoffset\\": 2,
\\"yoffset\\": 2,
\\"xadvance\\": 21,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 81,
\\"x\\": 218,
\\"y\\": 162,
\\"width\\": 23,
\\"height\\": 22,
\\"xoffset\\": 1,
\\"yoffset\\": 2,
\\"xadvance\\": 25,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 82,
\\"x\\": 243,
\\"y\\": 162,
\\"width\\": 18,
\\"height\\": 22,
\\"xoffset\\": 2,
\\"yoffset\\": 2,
\\"xadvance\\": 21,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 83,
\\"x\\": 263,
\\"y\\": 162,
\\"width\\": 19,
\\"height\\": 22,
\\"xoffset\\": 0,
\\"yoffset\\": 2,
\\"xadvance\\": 20,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 84,
\\"x\\": 284,
\\"y\\": 162,
\\"width\\": 19,
\\"height\\": 22,
\\"xoffset\\": 0,
\\"yoffset\\": 2,
\\"xadvance\\": 19,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 85,
\\"x\\": 187,
\\"y\\": 213,
\\"width\\": 17,
\\"height\\": 26,
\\"xoffset\\": 2,
\\"yoffset\\": 2,
\\"xadvance\\": 22,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 86,
\\"x\\": 305,
\\"y\\": 162,
\\"width\\": 21,
\\"height\\": 22,
\\"xoffset\\": 0,
\\"yoffset\\": 2,
\\"xadvance\\": 22,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 87,
\\"x\\": 328,
\\"y\\": 162,
\\"width\\": 33,
\\"height\\": 22,
\\"xoffset\\": 0,
\\"yoffset\\": 2,
\\"xadvance\\": 33,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 88,
\\"x\\": 363,
\\"y\\": 162,
\\"width\\": 20,
\\"height\\": 22,
\\"xoffset\\": 0,
\\"yoffset\\": 2,
\\"xadvance\\": 21,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 89,
\\"x\\": 385,
\\"y\\": 162,
\\"width\\": 20,
\\"height\\": 22,
\\"xoffset\\": 0,
\\"yoffset\\": 2,
\\"xadvance\\": 20,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 90,
\\"x\\": 407,
\\"y\\": 162,
\\"width\\": 18,
\\"height\\": 22,
\\"xoffset\\": 0,
\\"yoffset\\": 2,
\\"xadvance\\": 19,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 91,
\\"x\\": 249,
\\"y\\": 213,
\\"width\\": 6,
\\"height\\": 29,
\\"xoffset\\": 2,
\\"yoffset\\": -1,
\\"xadvance\\": 9,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 92,
\\"x\\": 333,
\\"y\\": 213,
\\"width\\": 15,
\\"height\\": 27,
\\"xoffset\\": -1,
\\"yoffset\\": 0,
\\"xadvance\\": 14,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 93,
\\"x\\": 257,
\\"y\\": 213,
\\"width\\": 6,
\\"height\\": 29,
\\"xoffset\\": 1,
\\"yoffset\\": -1,
\\"xadvance\\": 10,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 94,
\\"x\\": 858,
\\"y\\": 116,
\\"width\\": 16,
\\"height\\": 10,
\\"xoffset\\": 0,
\\"yoffset\\": 2,
\\"xadvance\\": 17,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 95,
\\"x\\": 151,
\\"y\\": 110,
\\"width\\": 16,
\\"height\\": 2,
\\"xoffset\\": 0,
\\"yoffset\\": 25,
\\"xadvance\\": 16,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 96,
\\"x\\": 434,
\\"y\\": 73,
\\"width\\": 6,
\\"height\\": 4,
\\"xoffset\\": 0,
\\"yoffset\\": 2,
\\"xadvance\\": 7,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 97,
\\"x\\": 584,
\\"y\\": 116,
\\"width\\": 18,
\\"height\\": 16,
\\"xoffset\\": 1,
\\"yoffset\\": 8,
\\"xadvance\\": 19,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 98,
\\"x\\": 427,
\\"y\\": 162,
\\"width\\": 16,
\\"height\\": 22,
\\"xoffset\\": 2,
\\"yoffset\\": 2,
\\"xadvance\\": 20,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 99,
\\"x\\": 604,
\\"y\\": 116,
\\"width\\": 15,
\\"height\\": 16,
\\"xoffset\\": 1,
\\"yoffset\\": 8,
\\"xadvance\\": 16,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 100,
\\"x\\": 445,
\\"y\\": 162,
\\"width\\": 16,
\\"height\\": 22,
\\"xoffset\\": 1,
\\"yoffset\\": 2,
\\"xadvance\\": 20,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 101,
\\"x\\": 621,
\\"y\\": 116,
\\"width\\": 18,
\\"height\\": 16,
\\"xoffset\\": 0,
\\"yoffset\\": 8,
\\"xadvance\\": 19,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 102,
\\"x\\": 463,
\\"y\\": 162,
\\"width\\": 13,
\\"height\\": 22,
\\"xoffset\\": -1,
\\"yoffset\\": 2,
\\"xadvance\\": 12,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 103,
\\"x\\": 206,
\\"y\\": 213,
\\"width\\": 15,
\\"height\\": 27,
\\"xoffset\\": 1,
\\"yoffset\\": 7,
\\"xadvance\\": 17,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 104,
\\"x\\": 478,
\\"y\\": 162,
\\"width\\": 14,
\\"height\\": 22,
\\"xoffset\\": 2,
\\"yoffset\\": 2,
\\"xadvance\\": 18,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 105,
\\"x\\": 494,
\\"y\\": 162,
\\"width\\": 3,
\\"height\\": 23,
\\"xoffset\\": 1,
\\"yoffset\\": 1,
\\"xadvance\\": 6,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 106,
\\"x\\": 580,
\\"y\\": 244,
\\"width\\": 8,
\\"height\\": 30,
\\"xoffset\\": -4,
\\"yoffset\\": 1,
\\"xadvance\\": 6,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 107,
\\"x\\": 499,
\\"y\\": 162,
\\"width\\": 13,
\\"height\\": 22,
\\"xoffset\\": 2,
\\"yoffset\\": 2,
\\"xadvance\\": 14,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 108,
\\"x\\": 514,
\\"y\\": 162,
\\"width\\": 2,
\\"height\\": 22,
\\"xoffset\\": 2,
\\"yoffset\\": 2,
\\"xadvance\\": 6,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 109,
\\"x\\": 641,
\\"y\\": 116,
\\"width\\": 25,
\\"height\\": 17,
\\"xoffset\\": 2,
\\"yoffset\\": 7,
\\"xadvance\\": 29,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 110,
\\"x\\": 668,
\\"y\\": 116,
\\"width\\": 14,
\\"height\\": 16,
\\"xoffset\\": 2,
\\"yoffset\\": 8,
\\"xadvance\\": 18,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 111,
\\"x\\": 684,
\\"y\\": 116,
\\"width\\": 16,
\\"height\\": 16,
\\"xoffset\\": 1,
\\"yoffset\\": 8,
\\"xadvance\\": 19,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 112,
\\"x\\": 518,
\\"y\\": 162,
\\"width\\": 16,
\\"height\\": 23,
\\"xoffset\\": 2,
\\"yoffset\\": 8,
\\"xadvance\\": 20,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 113,
\\"x\\": 536,
\\"y\\": 162,
\\"width\\": 16,
\\"height\\": 23,
\\"xoffset\\": 1,
\\"yoffset\\": 8,
\\"xadvance\\": 20,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 114,
\\"x\\": 702,
\\"y\\": 116,
\\"width\\": 11,
\\"height\\": 16,
\\"xoffset\\": 2,
\\"yoffset\\": 8,
\\"xadvance\\": 13,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 115,
\\"x\\": 715,
\\"y\\": 116,
\\"width\\": 15,
\\"height\\": 16,
\\"xoffset\\": 0,
\\"yoffset\\": 8,
\\"xadvance\\": 16,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 116,
\\"x\\": 554,
\\"y\\": 162,
\\"width\\": 12,
\\"height\\": 21,
\\"xoffset\\": 0,
\\"yoffset\\": 3,
\\"xadvance\\": 13,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 117,
\\"x\\": 732,
\\"y\\": 116,
\\"width\\": 14,
\\"height\\": 16,
\\"xoffset\\": 2,
\\"yoffset\\": 8,
\\"xadvance\\": 18,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 118,
\\"x\\": 748,
\\"y\\": 116,
\\"width\\": 16,
\\"height\\": 16,
\\"xoffset\\": 0,
\\"yoffset\\": 8,
\\"xadvance\\": 16,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 119,
\\"x\\": 766,
\\"y\\": 116,
\\"width\\": 25,
\\"height\\": 16,
\\"xoffset\\": -1,
\\"yoffset\\": 8,
\\"xadvance\\": 24,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 120,
\\"x\\": 793,
\\"y\\": 116,
\\"width\\": 15,
\\"height\\": 16,
\\"xoffset\\": 0,
\\"yoffset\\": 8,
\\"xadvance\\": 16,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 121,
\\"x\\": 568,
\\"y\\": 162,
\\"width\\": 16,
\\"height\\": 23,
\\"xoffset\\": 0,
\\"yoffset\\": 8,
\\"xadvance\\": 17,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 122,
\\"x\\": 810,
\\"y\\": 116,
\\"width\\": 14,
\\"height\\": 16,
\\"xoffset\\": 0,
\\"yoffset\\": 8,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 123,
\\"x\\": 265,
\\"y\\": 213,
\\"width\\": 8,
\\"height\\": 29,
\\"xoffset\\": 1,
\\"yoffset\\": 0,
\\"xadvance\\": 10,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 124,
\\"x\\": 285,
\\"y\\": 213,
\\"width\\": 2,
\\"height\\": 26,
\\"xoffset\\": 3,
\\"yoffset\\": 2,
\\"xadvance\\": 8,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 125,
\\"x\\": 275,
\\"y\\": 213,
\\"width\\": 8,
\\"height\\": 29,
\\"xoffset\\": 1,
\\"yoffset\\": 0,
\\"xadvance\\": 10,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 126,
\\"x\\": 892,
\\"y\\": 116,
\\"width\\": 17,
\\"height\\": 8,
\\"xoffset\\": 0,
\\"yoffset\\": 10,
\\"xadvance\\": 18,
\\"page\\": 0,
\\"chnl\\": 0
}],
\\"kernings\\": [{
\\"first\\": 34,
\\"second\\": 65,
\\"amount\\": -2
}, {
\\"first\\": 34,
\\"second\\": 67,
\\"amount\\": 1
}, {
\\"first\\": 34,
\\"second\\": 74,
\\"amount\\": -2
}, {
\\"first\\": 34,
\\"second\\": 77,
\\"amount\\": 1
}, {
\\"first\\": 34,
\\"second\\": 97,
\\"amount\\": -2
}, {
\\"first\\": 34,
\\"second\\": 102,
\\"amount\\": 1
}, {
\\"first\\": 34,
\\"second\\": 104,
\\"amount\\": 1
}, {
\\"first\\": 34,
\\"second\\": 112,
\\"amount\\": 1
}, {
\\"first\\": 34,
\\"second\\": 116,
\\"amount\\": 1
}, {
\\"first\\": 35,
\\"second\\": 53,
\\"amount\\": 1
}, {
\\"first\\": 35,
\\"second\\": 57,
\\"amount\\": 1
}, {
\\"first\\": 37,
\\"second\\": 49,
\\"amount\\": -2
}, {
\\"first\\": 37,
\\"second\\": 50,
\\"amount\\": 1
}, {
\\"first\\": 37,
\\"second\\": 54,
\\"amount\\": 1
}, {
\\"first\\": 37,
\\"second\\": 56,
\\"amount\\": 1
}, {
\\"first\\": 38,
\\"second\\": 48,
\\"amount\\": -2
}, {
\\"first\\": 38,
\\"second\\": 49,
\\"amount\\": -4
}, {
\\"first\\": 38,
\\"second\\": 50,
\\"amount\\": 1
}, {
\\"first\\": 38,
\\"second\\": 52,
\\"amount\\": -2
}, {
\\"first\\": 38,
\\"second\\": 57,
\\"amount\\": -3
}, {
\\"first\\": 38,
\\"second\\": 67,
\\"amount\\": -2
}, {
\\"first\\": 38,
\\"second\\": 69,
\\"amount\\": 1
}, {
\\"first\\": 38,
\\"second\\": 70,
\\"amount\\": 1
}, {
\\"first\\": 38,
\\"second\\": 79,
\\"amount\\": -2
}, {
\\"first\\": 38,
\\"second\\": 80,
\\"amount\\": -4
}, {
\\"first\\": 38,
\\"second\\": 81,
\\"amount\\": -2
}, {
\\"first\\": 38,
\\"second\\": 82,
\\"amount\\": -4
}, {
\\"first\\": 38,
\\"second\\": 83,
\\"amount\\": -3
}, {
\\"first\\": 38,
\\"second\\": 84,
\\"amount\\": -5
}, {
\\"first\\": 38,
\\"second\\": 85,
\\"amount\\": -4
}, {
\\"first\\": 38,
\\"second\\": 86,
\\"amount\\": 1
}, {
\\"first\\": 38,
\\"second\\": 87,
\\"amount\\": -4
}, {
\\"first\\": 38,
\\"second\\": 89,
\\"amount\\": -6
}, {
\\"first\\": 38,
\\"second\\": 97,
\\"amount\\": 1
}, {
\\"first\\": 38,
\\"second\\": 99,
\\"amount\\": -2
}, {
\\"first\\": 38,
\\"second\\": 103,
\\"amount\\": -2
}, {
\\"first\\": 38,
\\"second\\": 106,
\\"amount\\": 1
}, {
\\"first\\": 38,
\\"second\\": 111,
\\"amount\\": -2
}, {
\\"first\\": 38,
\\"second\\": 113,
\\"amount\\": -2
}, {
\\"first\\": 38,
\\"second\\": 116,
\\"amount\\": -5
}, {
\\"first\\": 38,
\\"second\\": 118,
\\"amount\\": -4
}, {
\\"first\\": 38,
\\"second\\": 119,
\\"amount\\": -4
}, {
\\"first\\": 38,
\\"second\\": 121,
\\"amount\\": -5
}, {
\\"first\\": 39,
\\"second\\": 116,
\\"amount\\": 1
}, {
\\"first\\": 44,
\\"second\\": 90,
\\"amount\\": 1
}, {
\\"first\\": 44,
\\"second\\": 97,
\\"amount\\": 1
}, {
\\"first\\": 44,
\\"second\\": 99,
\\"amount\\": -2
}, {
\\"first\\": 44,
\\"second\\": 100,
\\"amount\\": 1
}, {
\\"first\\": 44,
\\"second\\": 101,
\\"amount\\": 1
}, {
\\"first\\": 44,
\\"second\\": 105,
\\"amount\\": 1
}, {
\\"first\\": 44,
\\"second\\": 106,
\\"amount\\": 1
}, {
\\"first\\": 44,
\\"second\\": 107,
\\"amount\\": 1
}, {
\\"first\\": 44,
\\"second\\": 108,
\\"amount\\": 1
}, {
\\"first\\": 44,
\\"second\\": 122,
\\"amount\\": 1
}, {
\\"first\\": 46,
\\"second\\": 66,
\\"amount\\": 1
}, {
\\"first\\": 46,
\\"second\\": 67,
\\"amount\\": -2
}, {
\\"first\\": 46,
\\"second\\": 84,
\\"amount\\": -3
}, {
\\"first\\": 46,
\\"second\\": 86,
\\"amount\\": 1
}, {
\\"first\\": 46,
\\"second\\": 89,
\\"amount\\": -5
}, {
\\"first\\": 46,
\\"second\\": 90,
\\"amount\\": 1
}, {
\\"first\\": 46,
\\"second\\": 97,
\\"amount\\": 1
}, {
\\"first\\": 46,
\\"second\\": 98,
\\"amount\\": 1
}, {
\\"first\\": 46,
\\"second\\": 100,
\\"amount\\": 1
}, {
\\"first\\": 46,
\\"second\\": 101,
\\"amount\\": 1
}, {
\\"first\\": 46,
\\"second\\": 103,
\\"amount\\": -2
}, {
\\"first\\": 46,
\\"second\\": 104,
\\"amount\\": 1
}, {
\\"first\\": 46,
\\"second\\": 106,
\\"amount\\": 1
}, {
\\"first\\": 46,
\\"second\\": 107,
\\"amount\\": 1
}, {
\\"first\\": 46,
\\"second\\": 108,
\\"amount\\": 1
}, {
\\"first\\": 46,
\\"second\\": 111,
\\"amount\\": -2
}, {
\\"first\\": 46,
\\"second\\": 112,
\\"amount\\": 1
}, {
\\"first\\": 46,
\\"second\\": 113,
\\"amount\\": -2
}, {
\\"first\\": 46,
\\"second\\": 116,
\\"amount\\": -3
}, {
\\"first\\": 46,
\\"second\\": 118,
\\"amount\\": -4
}, {
\\"first\\": 46,
\\"second\\": 119,
\\"amount\\": -2
}, {
\\"first\\": 46,
\\"second\\": 120,
\\"amount\\": 1
}, {
\\"first\\": 46,
\\"second\\": 121,
\\"amount\\": -5
}, {
\\"first\\": 46,
\\"second\\": 122,
\\"amount\\": 1
}, {
\\"first\\": 47,
\\"second\\": 65,
\\"amount\\": -3
}, {
\\"first\\": 47,
\\"second\\": 66,
\\"amount\\": 2
}, {
\\"first\\": 47,
\\"second\\": 77,
\\"amount\\": 2
}, {
\\"first\\": 47,
\\"second\\": 84,
\\"amount\\": 1
}, {
\\"first\\": 47,
\\"second\\": 85,
\\"amount\\": 2
}, {
\\"first\\": 47,
\\"second\\": 86,
\\"amount\\": 2
}, {
\\"first\\": 47,
\\"second\\": 87,
\\"amount\\": 1
}, {
\\"first\\": 47,
\\"second\\": 88,
\\"amount\\": 1
}, {
\\"first\\": 47,
\\"second\\": 89,
\\"amount\\": 2
}, {
\\"first\\": 47,
\\"second\\": 90,
\\"amount\\": 1
}, {
\\"first\\": 47,
\\"second\\": 97,
\\"amount\\": 2
}, {
\\"first\\": 47,
\\"second\\": 98,
\\"amount\\": 1
}, {
\\"first\\": 47,
\\"second\\": 100,
\\"amount\\": 2
}, {
\\"first\\": 47,
\\"second\\": 101,
\\"amount\\": 1
}, {
\\"first\\": 47,
\\"second\\": 102,
\\"amount\\": 1
}, {
\\"first\\": 47,
\\"second\\": 104,
\\"amount\\": 1
}, {
\\"first\\": 47,
\\"second\\": 105,
\\"amount\\": 1
}, {
\\"first\\": 47,
\\"second\\": 107,
\\"amount\\": 1
}, {
\\"first\\": 47,
\\"second\\": 108,
\\"amount\\": 1
}, {
\\"first\\": 47,
\\"second\\": 109,
\\"amount\\": 1
}, {
\\"first\\": 47,
\\"second\\": 112,
\\"amount\\": 1
}, {
\\"first\\": 47,
\\"second\\": 113,
\\"amount\\": -2
}, {
\\"first\\": 47,
\\"second\\": 116,
\\"amount\\": 2
}, {
\\"first\\": 47,
\\"second\\": 117,
\\"amount\\": 1
}, {
\\"first\\": 47,
\\"second\\": 118,
\\"amount\\": 1
}, {
\\"first\\": 47,
\\"second\\": 119,
\\"amount\\": 2
}, {
\\"first\\": 47,
\\"second\\": 120,
\\"amount\\": 1
}, {
\\"first\\": 47,
\\"second\\": 121,
\\"amount\\": 2
}, {
\\"first\\": 47,
\\"second\\": 122,
\\"amount\\": 1
}, {
\\"first\\": 48,
\\"second\\": 50,
\\"amount\\": -2
}, {
\\"first\\": 48,
\\"second\\": 54,
\\"amount\\": 1
}, {
\\"first\\": 48,
\\"second\\": 55,
\\"amount\\": -3
}, {
\\"first\\": 49,
\\"second\\": 51,
\\"amount\\": 1
}, {
\\"first\\": 49,
\\"second\\": 53,
\\"amount\\": 1
}, {
\\"first\\": 49,
\\"second\\": 54,
\\"amount\\": 1
}, {
\\"first\\": 49,
\\"second\\": 56,
\\"amount\\": 1
}, {
\\"first\\": 49,
\\"second\\": 57,
\\"amount\\": 1
}, {
\\"first\\": 50,
\\"second\\": 52,
\\"amount\\": -2
}, {
\\"first\\": 50,
\\"second\\": 55,
\\"amount\\": -2
}, {
\\"first\\": 51,
\\"second\\": 55,
\\"amount\\": -2
}, {
\\"first\\": 51,
\\"second\\": 57,
\\"amount\\": -2
}, {
\\"first\\": 52,
\\"second\\": 55,
\\"amount\\": -3
}, {
\\"first\\": 52,
\\"second\\": 56,
\\"amount\\": 1
}, {
\\"first\\": 53,
\\"second\\": 55,
\\"amount\\": -3
}, {
\\"first\\": 53,
\\"second\\": 57,
\\"amount\\": -2
}, {
\\"first\\": 54,
\\"second\\": 55,
\\"amount\\": -3
}, {
\\"first\\": 55,
\\"second\\": 56,
\\"amount\\": -2
}, {
\\"first\\": 58,
\\"second\\": 85,
\\"amount\\": 1
}, {
\\"first\\": 58,
\\"second\\": 90,
\\"amount\\": 1
}, {
\\"first\\": 58,
\\"second\\": 103,
\\"amount\\": 1
}, {
\\"first\\": 58,
\\"second\\": 115,
\\"amount\\": 1
}, {
\\"first\\": 58,
\\"second\\": 117,
\\"amount\\": 1
}, {
\\"first\\": 58,
\\"second\\": 118,
\\"amount\\": -2
}, {
\\"first\\": 58,
\\"second\\": 121,
\\"amount\\": -2
}, {
\\"first\\": 59,
\\"second\\": 69,
\\"amount\\": 1
}, {
\\"first\\": 59,
\\"second\\": 81,
\\"amount\\": 1
}, {
\\"first\\": 59,
\\"second\\": 84,
\\"amount\\": 1
}, {
\\"first\\": 59,
\\"second\\": 86,
\\"amount\\": 2
}, {
\\"first\\": 59,
\\"second\\": 103,
\\"amount\\": 1
}, {
\\"first\\": 59,
\\"second\\": 121,
\\"amount\\": -2
}, {
\\"first\\": 63,
\\"second\\": 66,
\\"amount\\": 1
}, {
\\"first\\": 63,
\\"second\\": 74,
\\"amount\\": -2
}, {
\\"first\\": 63,
\\"second\\": 97,
\\"amount\\": -2
}, {
\\"first\\": 64,
\\"second\\": 70,
\\"amount\\": -2
}, {
\\"first\\": 64,
\\"second\\": 80,
\\"amount\\": -2
}, {
\\"first\\": 64,
\\"second\\": 84,
\\"amount\\": -2
}, {
\\"first\\": 64,
\\"second\\": 85,
\\"amount\\": -2
}, {
\\"first\\": 64,
\\"second\\": 86,
\\"amount\\": -2
}, {
\\"first\\": 64,
\\"second\\": 97,
\\"amount\\": -2
}, {
\\"first\\": 64,
\\"second\\": 103,
\\"amount\\": -2
}, {
\\"first\\": 64,
\\"second\\": 106,
\\"amount\\": -2
}, {
\\"first\\": 64,
\\"second\\": 112,
\\"amount\\": 1
}, {
\\"first\\": 64,
\\"second\\": 114,
\\"amount\\": 1
}, {
\\"first\\": 65,
\\"second\\": 67,
\\"amount\\": -2
}, {
\\"first\\": 65,
\\"second\\": 68,
\\"amount\\": 1
}, {
\\"first\\": 65,
\\"second\\": 71,
\\"amount\\": -2
}, {
\\"first\\": 65,
\\"second\\": 74,
\\"amount\\": -2
}, {
\\"first\\": 65,
\\"second\\": 76,
\\"amount\\": 1
}, {
\\"first\\": 65,
\\"second\\": 79,
\\"amount\\": -2
}, {
\\"first\\": 65,
\\"second\\": 81,
\\"amount\\": -2
}, {
\\"first\\": 65,
\\"second\\": 84,
\\"amount\\": -4
}, {
\\"first\\": 65,
\\"second\\": 85,
\\"amount\\": -2
}, {
\\"first\\": 65,
\\"second\\": 86,
\\"amount\\": -4
}, {
\\"first\\": 65,
\\"second\\": 87,
\\"amount\\": -4
}, {
\\"first\\": 65,
\\"second\\": 89,
\\"amount\\": -4
}, {
\\"first\\": 65,
\\"second\\": 90,
\\"amount\\": 1
}, {
\\"first\\": 65,
\\"second\\": 100,
\\"amount\\": -2
}, {
\\"first\\": 65,
\\"second\\": 102,
\\"amount\\": -2
}, {
\\"first\\": 65,
\\"second\\": 103,
\\"amount\\": 1
}, {
\\"first\\": 65,
\\"second\\": 113,
\\"amount\\": -2
}, {
\\"first\\": 65,
\\"second\\": 116,
\\"amount\\": -2
}, {
\\"first\\": 65,
\\"second\\": 117,
\\"amount\\": -2
}, {
\\"first\\": 65,
\\"second\\": 118,
\\"amount\\": -3
}, {
\\"first\\": 65,
\\"second\\": 119,
\\"amount\\": -3
}, {
\\"first\\": 65,
\\"second\\": 120,
\\"amount\\": 1
}, {
\\"first\\": 65,
\\"second\\": 121,
\\"amount\\": -2
}, {
\\"first\\": 66,
\\"second\\": 68,
\\"amount\\": 1
}, {
\\"first\\": 66,
\\"second\\": 74,
\\"amount\\": 1
}, {
\\"first\\": 66,
\\"second\\": 81,
\\"amount\\": 1
}, {
\\"first\\": 66,
\\"second\\": 83,
\\"amount\\": 1
}, {
\\"first\\": 66,
\\"second\\": 86,
\\"amount\\": -2
}, {
\\"first\\": 66,
\\"second\\": 87,
\\"amount\\": -2
}, {
\\"first\\": 66,
\\"second\\": 89,
\\"amount\\": -2
}, {
\\"first\\": 67,
\\"second\\": 68,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 69,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 72,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 73,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 75,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 76,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 77,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 79,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 80,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 82,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 83,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 84,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 85,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 90,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 101,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 104,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 108,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 109,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 111,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 116,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 119,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 121,
\\"amount\\": 1
}, {
\\"first\\": 68,
\\"second\\": 70,
\\"amount\\": 1
}, {
\\"first\\": 68,
\\"second\\": 81,
\\"amount\\": 1
}, {
\\"first\\": 68,
\\"second\\": 84,
\\"amount\\": -2
}, {
\\"first\\": 68,
\\"second\\": 87,
\\"amount\\": -2
}, {
\\"first\\": 68,
\\"second\\": 88,
\\"amount\\": -3
}, {
\\"first\\": 68,
\\"second\\": 89,
\\"amount\\": -3
}, {
\\"first\\": 68,
\\"second\\": 90,
\\"amount\\": -2
}, {
\\"first\\": 68,
\\"second\\": 101,
\\"amount\\": 1
}, {
\\"first\\": 68,
\\"second\\": 106,
\\"amount\\": 1
}, {
\\"first\\": 68,
\\"second\\": 109,
\\"amount\\": 1
}, {
\\"first\\": 68,
\\"second\\": 117,
\\"amount\\": 1
}, {
\\"first\\": 68,
\\"second\\": 119,
\\"amount\\": 1
}, {
\\"first\\": 68,
\\"second\\": 121,
\\"amount\\": 1
}, {
\\"first\\": 69,
\\"second\\": 78,
\\"amount\\": 1
}, {
\\"first\\": 69,
\\"second\\": 83,
\\"amount\\": 1
}, {
\\"first\\": 69,
\\"second\\": 84,
\\"amount\\": 1
}, {
\\"first\\": 69,
\\"second\\": 89,
\\"amount\\": 1
}, {
\\"first\\": 69,
\\"second\\": 106,
\\"amount\\": 1
}, {
\\"first\\": 69,
\\"second\\": 120,
\\"amount\\": 1
}, {
\\"first\\": 70,
\\"second\\": 71,
\\"amount\\": 1
}, {
\\"first\\": 70,
\\"second\\": 79,
\\"amount\\": 1
}, {
\\"first\\": 70,
\\"second\\": 84,
\\"amount\\": 1
}, {
\\"first\\": 70,
\\"second\\": 86,
\\"amount\\": 1
}, {
\\"first\\": 70,
\\"second\\": 89,
\\"amount\\": 1
}, {
\\"first\\": 70,
\\"second\\": 102,
\\"amount\\": 1
}, {
\\"first\\": 71,
\\"second\\": 84,
\\"amount\\": -2
}, {
\\"first\\": 71,
\\"second\\": 86,
\\"amount\\": -2
}, {
\\"first\\": 71,
\\"second\\": 87,
\\"amount\\": -2
}, {
\\"first\\": 71,
\\"second\\": 89,
\\"amount\\": -2
}, {
\\"first\\": 73,
\\"second\\": 79,
\\"amount\\": 1
}, {
\\"first\\": 73,
\\"second\\": 83,
\\"amount\\": 1
}, {
\\"first\\": 73,
\\"second\\": 84,
\\"amount\\": 1
}, {
\\"first\\": 73,
\\"second\\": 87,
\\"amount\\": 1
}, {
\\"first\\": 73,
\\"second\\": 90,
\\"amount\\": 1
}, {
\\"first\\": 74,
\\"second\\": 88,
\\"amount\\": -2
}, {
\\"first\\": 74,
\\"second\\": 97,
\\"amount\\": -2
}, {
\\"first\\": 74,
\\"second\\": 103,
\\"amount\\": -2
}, {
\\"first\\": 74,
\\"second\\": 106,
\\"amount\\": -2
}, {
\\"first\\": 75,
\\"second\\": 79,
\\"amount\\": -3
}, {
\\"first\\": 75,
\\"second\\": 81,
\\"amount\\": -2
}, {
\\"first\\": 75,
\\"second\\": 85,
\\"amount\\": -2
}, {
\\"first\\": 75,
\\"second\\": 97,
\\"amount\\": -2
}, {
\\"first\\": 75,
\\"second\\": 99,
\\"amount\\": -2
}, {
\\"first\\": 75,
\\"second\\": 100,
\\"amount\\": -2
}, {
\\"first\\": 75,
\\"second\\": 101,
\\"amount\\": -2
}, {
\\"first\\": 75,
\\"second\\": 103,
\\"amount\\": 1
}, {
\\"first\\": 75,
\\"second\\": 109,
\\"amount\\": -2
}, {
\\"first\\": 75,
\\"second\\": 110,
\\"amount\\": -2
}, {
\\"first\\": 75,
\\"second\\": 111,
\\"amount\\": -2
}, {
\\"first\\": 75,
\\"second\\": 113,
\\"amount\\": -2
}, {
\\"first\\": 75,
\\"second\\": 115,
\\"amount\\": -2
}, {
\\"first\\": 75,
\\"second\\": 116,
\\"amount\\": -2
}, {
\\"first\\": 75,
\\"second\\": 117,
\\"amount\\": -2
}, {
\\"first\\": 75,
\\"second\\": 118,
\\"amount\\": -3
}, {
\\"first\\": 75,
\\"second\\": 119,
\\"amount\\": -3
}, {
\\"first\\": 75,
\\"second\\": 121,
\\"amount\\": -2
}, {
\\"first\\": 75,
\\"second\\": 122,
\\"amount\\": -2
}, {
\\"first\\": 76,
\\"second\\": 79,
\\"amount\\": -2
}, {
\\"first\\": 76,
\\"second\\": 84,
\\"amount\\": -4
}, {
\\"first\\": 76,
\\"second\\": 85,
\\"amount\\": -2
}, {
\\"first\\": 76,
\\"second\\": 86,
\\"amount\\": -4
}, {
\\"first\\": 76,
\\"second\\": 87,
\\"amount\\": -4
}, {
\\"first\\": 76,
\\"second\\": 89,
\\"amount\\": -5
}, {
\\"first\\": 76,
\\"second\\": 90,
\\"amount\\": 1
}, {
\\"first\\": 76,
\\"second\\": 97,
\\"amount\\": 1
}, {
\\"first\\": 76,
\\"second\\": 103,
\\"amount\\": 1
}, {
\\"first\\": 76,
\\"second\\": 121,
\\"amount\\": -2
}, {
\\"first\\": 77,
\\"second\\": 87,
\\"amount\\": -2
}, {
\\"first\\": 79,
\\"second\\": 81,
\\"amount\\": 1
}, {
\\"first\\": 79,
\\"second\\": 83,
\\"amount\\": 1
}, {
\\"first\\": 79,
\\"second\\": 84,
\\"amount\\": -2
}, {
\\"first\\": 79,
\\"second\\": 86,
\\"amount\\": -2
}, {
\\"first\\": 79,
\\"second\\": 87,
\\"amount\\": -2
}, {
\\"first\\": 79,
\\"second\\": 88,
\\"amount\\": -2
}, {
\\"first\\": 79,
\\"second\\": 89,
\\"amount\\": -3
}, {
\\"first\\": 79,
\\"second\\": 90,
\\"amount\\": -2
}, {
\\"first\\": 79,
\\"second\\": 122,
\\"amount\\": -2
}, {
\\"first\\": 80,
\\"second\\": 88,
\\"amount\\": -2
}, {
\\"first\\": 80,
\\"second\\": 97,
\\"amount\\": -2
}, {
\\"first\\": 80,
\\"second\\": 99,
\\"amount\\": -2
}, {
\\"first\\": 80,
\\"second\\": 100,
\\"amount\\": -2
}, {
\\"first\\": 80,
\\"second\\": 101,
\\"amount\\": -2
}, {
\\"first\\": 80,
\\"second\\": 103,
\\"amount\\": -2
}, {
\\"first\\": 80,
\\"second\\": 111,
\\"amount\\": -2
}, {
\\"first\\": 80,
\\"second\\": 113,
\\"amount\\": -2
}, {
\\"first\\": 80,
\\"second\\": 114,
\\"amount\\": -2
}, {
\\"first\\": 80,
\\"second\\": 118,
\\"amount\\": 1
}, {
\\"first\\": 80,
\\"second\\": 119,
\\"amount\\": 1
}, {
\\"first\\": 80,
\\"second\\": 121,
\\"amount\\": 1
}, {
\\"first\\": 81,
\\"second\\": 84,
\\"amount\\": -2
}, {
\\"first\\": 81,
\\"second\\": 86,
\\"amount\\": -2
}, {
\\"first\\": 81,
\\"second\\": 87,
\\"amount\\": -2
}, {
\\"first\\": 81,
\\"second\\": 89,
\\"amount\\": -2
}, {
\\"first\\": 82,
\\"second\\": 83,
\\"amount\\": 1
}, {
\\"first\\": 82,
\\"second\\": 84,
\\"amount\\": 1
}, {
\\"first\\": 82,
\\"second\\": 85,
\\"amount\\": 1
}, {
\\"first\\": 82,
\\"second\\": 106,
\\"amount\\": 1
}, {
\\"first\\": 82,
\\"second\\": 119,
\\"amount\\": 1
}, {
\\"first\\": 82,
\\"second\\": 121,
\\"amount\\": 1
}, {
\\"first\\": 83,
\\"second\\": 89,
\\"amount\\": -2
}, {
\\"first\\": 83,
\\"second\\": 97,
\\"amount\\": 1
}, {
\\"first\\": 83,
\\"second\\": 101,
\\"amount\\": 1
}, {
\\"first\\": 83,
\\"second\\": 103,
\\"amount\\": 1
}, {
\\"first\\": 83,
\\"second\\": 111,
\\"amount\\": 1
}, {
\\"first\\": 83,
\\"second\\": 113,
\\"amount\\": 1
}, {
\\"first\\": 83,
\\"second\\": 114,
\\"amount\\": 1
}, {
\\"first\\": 83,
\\"second\\": 117,
\\"amount\\": 1
}, {
\\"first\\": 83,
\\"second\\": 122,
\\"amount\\": 1
}, {
\\"first\\": 84,
\\"second\\": 46,
\\"amount\\": -3
}, {
\\"first\\": 84,
\\"second\\": 85,
\\"amount\\": 1
}, {
\\"first\\": 84,
\\"second\\": 86,
\\"amount\\": 1
}, {
\\"first\\": 84,
\\"second\\": 87,
\\"amount\\": 1
}, {
\\"first\\": 84,
\\"second\\": 89,
\\"amount\\": 1
}, {
\\"first\\": 84,
\\"second\\": 90,
\\"amount\\": 1
}, {
\\"first\\": 84,
\\"second\\": 97,
\\"amount\\": -5
}, {
\\"first\\": 84,
\\"second\\": 99,
\\"amount\\": -5
}, {
\\"first\\": 84,
\\"second\\": 100,
\\"amount\\": -5
}, {
\\"first\\": 84,
\\"second\\": 101,
\\"amount\\": -5
}, {
\\"first\\": 84,
\\"second\\": 102,
\\"amount\\": -3
}, {
\\"first\\": 84,
\\"second\\": 103,
\\"amount\\": -5
}, {
\\"first\\": 84,
\\"second\\": 109,
\\"amount\\": -5
}, {
\\"first\\": 84,
\\"second\\": 110,
\\"amount\\": -5
}, {
\\"first\\": 84,
\\"second\\": 111,
\\"amount\\": -5
}, {
\\"first\\": 84,
\\"second\\": 112,
\\"amount\\": -5
}, {
\\"first\\": 84,
\\"second\\": 113,
\\"amount\\": -5
}, {
\\"first\\": 84,
\\"second\\": 114,
\\"amount\\": -4
}, {
\\"first\\": 84,
\\"second\\": 115,
\\"amount\\": -5
}, {
\\"first\\": 84,
\\"second\\": 116,
\\"amount\\": -2
}, {
\\"first\\": 84,
\\"second\\": 117,
\\"amount\\": -5
}, {
\\"first\\": 84,
\\"second\\": 118,
\\"amount\\": -4
}, {
\\"first\\": 84,
\\"second\\": 119,
\\"amount\\": -4
}, {
\\"first\\": 84,
\\"second\\": 120,
\\"amount\\": -4
}, {
\\"first\\": 84,
\\"second\\": 121,
\\"amount\\": -4
}, {
\\"first\\": 84,
\\"second\\": 122,
\\"amount\\": -4
}, {
\\"first\\": 85,
\\"second\\": 87,
\\"amount\\": -2
}, {
\\"first\\": 85,
\\"second\\": 88,
\\"amount\\": -2
}, {
\\"first\\": 85,
\\"second\\": 90,
\\"amount\\": -2
}, {
\\"first\\": 85,
\\"second\\": 97,
\\"amount\\": -2
}, {
\\"first\\": 85,
\\"second\\": 100,
\\"amount\\": -2
}, {
\\"first\\": 85,
\\"second\\": 101,
\\"amount\\": -2
}, {
\\"first\\": 85,
\\"second\\": 103,
\\"amount\\": -2
}, {
\\"first\\": 85,
\\"second\\": 111,
\\"amount\\": -2
}, {
\\"first\\": 85,
\\"second\\": 113,
\\"amount\\": -2
}, {
\\"first\\": 85,
\\"second\\": 114,
\\"amount\\": -2
}, {
\\"first\\": 85,
\\"second\\": 120,
\\"amount\\": -2
}, {
\\"first\\": 85,
\\"second\\": 122,
\\"amount\\": -2
}, {
\\"first\\": 86,
\\"second\\": 97,
\\"amount\\": -4
}, {
\\"first\\": 86,
\\"second\\": 99,
\\"amount\\": -4
}, {
\\"first\\": 86,
\\"second\\": 100,
\\"amount\\": -4
}, {
\\"first\\": 86,
\\"second\\": 101,
\\"amount\\": -4
}, {
\\"first\\": 86,
\\"second\\": 102,
\\"amount\\": -2
}, {
\\"first\\": 86,
\\"second\\": 103,
\\"amount\\": -4
}, {
\\"first\\": 86,
\\"second\\": 104,
\\"amount\\": -2
}, {
\\"first\\": 86,
\\"second\\": 105,
\\"amount\\": -2
}, {
\\"first\\": 86,
\\"second\\": 107,
\\"amount\\": -2
}, {
\\"first\\": 86,
\\"second\\": 109,
\\"amount\\": -3
}, {
\\"first\\": 86,
\\"second\\": 110,
\\"amount\\": -3
}, {
\\"first\\": 86,
\\"second\\": 111,
\\"amount\\": -4
}, {
\\"first\\": 86,
\\"second\\": 112,
\\"amount\\": -3
}, {
\\"first\\": 86,
\\"second\\": 113,
\\"amount\\": -4
}, {
\\"first\\": 86,
\\"second\\": 114,
\\"amount\\": -3
}, {
\\"first\\": 86,
\\"second\\": 115,
\\"amount\\": -3
}, {
\\"first\\": 86,
\\"second\\": 116,
\\"amount\\": -2
}, {
\\"first\\": 86,
\\"second\\": 117,
\\"amount\\": -3
}, {
\\"first\\": 86,
\\"second\\": 118,
\\"amount\\": -2
}, {
\\"first\\": 86,
\\"second\\": 119,
\\"amount\\": -2
}, {
\\"first\\": 86,
\\"second\\": 120,
\\"amount\\": -2
}, {
\\"first\\": 86,
\\"second\\": 121,
\\"amount\\": -2
}, {
\\"first\\": 86,
\\"second\\": 122,
\\"amount\\": -3
}, {
\\"first\\": 87,
\\"second\\": 89,
\\"amount\\": 1
}, {
\\"first\\": 87,
\\"second\\": 97,
\\"amount\\": -4
}, {
\\"first\\": 87,
\\"second\\": 99,
\\"amount\\": -4
}, {
\\"first\\": 87,
\\"second\\": 100,
\\"amount\\": -4
}, {
\\"first\\": 87,
\\"second\\": 101,
\\"amount\\": -4
}, {
\\"first\\": 87,
\\"second\\": 103,
\\"amount\\": -4
}, {
\\"first\\": 87,
\\"second\\": 104,
\\"amount\\": -2
}, {
\\"first\\": 87,
\\"second\\": 109,
\\"amount\\": -3
}, {
\\"first\\": 87,
\\"second\\": 110,
\\"amount\\": -3
}, {
\\"first\\": 87,
\\"second\\": 111,
\\"amount\\": -4
}, {
\\"first\\": 87,
\\"second\\": 112,
\\"amount\\": -3
}, {
\\"first\\": 87,
\\"second\\": 113,
\\"amount\\": -4
}, {
\\"first\\": 87,
\\"second\\": 114,
\\"amount\\": -3
}, {
\\"first\\": 87,
\\"second\\": 115,
\\"amount\\": -3
}, {
\\"first\\": 87,
\\"second\\": 116,
\\"amount\\": -2
}, {
\\"first\\": 87,
\\"second\\": 117,
\\"amount\\": -3
}, {
\\"first\\": 87,
\\"second\\": 119,
\\"amount\\": -2
}, {
\\"first\\": 87,
\\"second\\": 120,
\\"amount\\": -2
}, {
\\"first\\": 87,
\\"second\\": 121,
\\"amount\\": -2
}, {
\\"first\\": 87,
\\"second\\": 122,
\\"amount\\": -3
}, {
\\"first\\": 88,
\\"second\\": 100,
\\"amount\\": -2
}, {
\\"first\\": 88,
\\"second\\": 101,
\\"amount\\": -2
}, {
\\"first\\": 88,
\\"second\\": 103,
\\"amount\\": 1
}, {
\\"first\\": 88,
\\"second\\": 106,
\\"amount\\": 2
}, {
\\"first\\": 88,
\\"second\\": 111,
\\"amount\\": -2
}, {
\\"first\\": 88,
\\"second\\": 116,
\\"amount\\": -2
}, {
\\"first\\": 88,
\\"second\\": 118,
\\"amount\\": -2
}, {
\\"first\\": 88,
\\"second\\": 119,
\\"amount\\": -2
}, {
\\"first\\": 88,
\\"second\\": 121,
\\"amount\\": -2
}, {
\\"first\\": 89,
\\"second\\": 97,
\\"amount\\": -5
}, {
\\"first\\": 89,
\\"second\\": 99,
\\"amount\\": -5
}, {
\\"first\\": 89,
\\"second\\": 100,
\\"amount\\": -5
}, {
\\"first\\": 89,
\\"second\\": 101,
\\"amount\\": -5
}, {
\\"first\\": 89,
\\"second\\": 102,
\\"amount\\": -2
}, {
\\"first\\": 89,
\\"second\\": 103,
\\"amount\\": -5
}, {
\\"first\\": 89,
\\"second\\": 104,
\\"amount\\": -2
}, {
\\"first\\": 89,
\\"second\\": 105,
\\"amount\\": -2
}, {
\\"first\\": 89,
\\"second\\": 107,
\\"amount\\": -2
}, {
\\"first\\": 89,
\\"second\\": 109,
\\"amount\\": -4
}, {
\\"first\\": 89,
\\"second\\": 110,
\\"amount\\": -4
}, {
\\"first\\": 89,
\\"second\\": 111,
\\"amount\\": -5
}, {
\\"first\\": 89,
\\"second\\": 112,
\\"amount\\": -4
}, {
\\"first\\": 89,
\\"second\\": 113,
\\"amount\\": -5
}, {
\\"first\\": 89,
\\"second\\": 114,
\\"amount\\": -4
}, {
\\"first\\": 89,
\\"second\\": 115,
\\"amount\\": -4
}, {
\\"first\\": 89,
\\"second\\": 117,
\\"amount\\": -4
}, {
\\"first\\": 89,
\\"second\\": 118,
\\"amount\\": -3
}, {
\\"first\\": 89,
\\"second\\": 119,
\\"amount\\": -3
}, {
\\"first\\": 89,
\\"second\\": 120,
\\"amount\\": -3
}, {
\\"first\\": 89,
\\"second\\": 121,
\\"amount\\": -2
}, {
\\"first\\": 89,
\\"second\\": 122,
\\"amount\\": -4
}, {
\\"first\\": 90,
\\"second\\": 97,
\\"amount\\": 1
}, {
\\"first\\": 90,
\\"second\\": 103,
\\"amount\\": 1
}, {
\\"first\\": 97,
\\"second\\": 106,
\\"amount\\": 1
}, {
\\"first\\": 97,
\\"second\\": 116,
\\"amount\\": -2
}, {
\\"first\\": 97,
\\"second\\": 117,
\\"amount\\": -2
}, {
\\"first\\": 97,
\\"second\\": 118,
\\"amount\\": -2
}, {
\\"first\\": 97,
\\"second\\": 119,
\\"amount\\": -2
}, {
\\"first\\": 97,
\\"second\\": 121,
\\"amount\\": -2
}, {
\\"first\\": 98,
\\"second\\": 116,
\\"amount\\": -2
}, {
\\"first\\": 98,
\\"second\\": 118,
\\"amount\\": -2
}, {
\\"first\\": 98,
\\"second\\": 119,
\\"amount\\": -2
}, {
\\"first\\": 98,
\\"second\\": 121,
\\"amount\\": -2
}, {
\\"first\\": 98,
\\"second\\": 122,
\\"amount\\": -2
}, {
\\"first\\": 99,
\\"second\\": 68,
\\"amount\\": 2
}, {
\\"first\\": 99,
\\"second\\": 101,
\\"amount\\": 1
}, {
\\"first\\": 99,
\\"second\\": 113,
\\"amount\\": 1
}, {
\\"first\\": 100,
\\"second\\": 106,
\\"amount\\": 1
}, {
\\"first\\": 100,
\\"second\\": 119,
\\"amount\\": -2
}, {
\\"first\\": 101,
\\"second\\": 116,
\\"amount\\": -2
}, {
\\"first\\": 101,
\\"second\\": 119,
\\"amount\\": -2
}, {
\\"first\\": 101,
\\"second\\": 121,
\\"amount\\": -2
}, {
\\"first\\": 102,
\\"second\\": 84,
\\"amount\\": 1
}, {
\\"first\\": 102,
\\"second\\": 86,
\\"amount\\": 1
}, {
\\"first\\": 102,
\\"second\\": 87,
\\"amount\\": 1
}, {
\\"first\\": 102,
\\"second\\": 89,
\\"amount\\": 1
}, {
\\"first\\": 102,
\\"second\\": 103,
\\"amount\\": -2
}, {
\\"first\\": 102,
\\"second\\": 110,
\\"amount\\": -2
}, {
\\"first\\": 102,
\\"second\\": 111,
\\"amount\\": -2
}, {
\\"first\\": 102,
\\"second\\": 115,
\\"amount\\": -2
}, {
\\"first\\": 102,
\\"second\\": 117,
\\"amount\\": -2
}, {
\\"first\\": 102,
\\"second\\": 120,
\\"amount\\": -2
}, {
\\"first\\": 103,
\\"second\\": 106,
\\"amount\\": 4
}, {
\\"first\\": 103,
\\"second\\": 120,
\\"amount\\": 1
}, {
\\"first\\": 104,
\\"second\\": 118,
\\"amount\\": -2
}, {
\\"first\\": 104,
\\"second\\": 119,
\\"amount\\": -2
}, {
\\"first\\": 104,
\\"second\\": 121,
\\"amount\\": -2
}, {
\\"first\\": 105,
\\"second\\": 74,
\\"amount\\": 1
}, {
\\"first\\": 105,
\\"second\\": 120,
\\"amount\\": 1
}, {
\\"first\\": 107,
\\"second\\": 111,
\\"amount\\": -2
}, {
\\"first\\": 107,
\\"second\\": 118,
\\"amount\\": 1
}, {
\\"first\\": 107,
\\"second\\": 121,
\\"amount\\": 1
}, {
\\"first\\": 109,
\\"second\\": 116,
\\"amount\\": -2
}, {
\\"first\\": 109,
\\"second\\": 117,
\\"amount\\": -2
}, {
\\"first\\": 109,
\\"second\\": 118,
\\"amount\\": -2
}, {
\\"first\\": 109,
\\"second\\": 119,
\\"amount\\": -2
}, {
\\"first\\": 109,
\\"second\\": 121,
\\"amount\\": -2
}, {
\\"first\\": 110,
\\"second\\": 116,
\\"amount\\": -2
}, {
\\"first\\": 110,
\\"second\\": 117,
\\"amount\\": -2
}, {
\\"first\\": 110,
\\"second\\": 118,
\\"amount\\": -2
}, {
\\"first\\": 110,
\\"second\\": 119,
\\"amount\\": -2
}, {
\\"first\\": 110,
\\"second\\": 121,
\\"amount\\": -2
}, {
\\"first\\": 111,
\\"second\\": 119,
\\"amount\\": -2
}, {
\\"first\\": 111,
\\"second\\": 122,
\\"amount\\": -2
}, {
\\"first\\": 114,
\\"second\\": 116,
\\"amount\\": 1
}, {
\\"first\\": 114,
\\"second\\": 118,
\\"amount\\": 1
}, {
\\"first\\": 114,
\\"second\\": 119,
\\"amount\\": 1
}, {
\\"first\\": 114,
\\"second\\": 120,
\\"amount\\": 1
}, {
\\"first\\": 114,
\\"second\\": 121,
\\"amount\\": 1
}, {
\\"first\\": 118,
\\"second\\": 119,
\\"amount\\": 1
}, {
\\"first\\": 118,
\\"second\\": 120,
\\"amount\\": 1
}, {
\\"first\\": 118,
\\"second\\": 121,
\\"amount\\": 1
}, {
\\"first\\": 119,
\\"second\\": 120,
\\"amount\\": 1
}, {
\\"first\\": 119,
\\"second\\": 122,
\\"amount\\": -2
}, {
\\"first\\": 120,
\\"second\\": 121,
\\"amount\\": 1
}],
\\"common\\": {
\\"lineHeight\\": 32,
\\"base\\": 24,
\\"scaleW\\": 1024,
\\"scaleH\\": 2048,
\\"pages\\": 1,
\\"packed\\": 0,
\\"alphaChnl\\": 0,
\\"redChnl\\": 0,
\\"greenChnl\\": 0,
\\"blueChnl\\": 0
},
\\"info\\": {
\\"face\\": \\"Nexa Light\\",
\\"size\\": 32,
\\"bold\\": 0,
\\"italic\\": 0,
\\"charset\\": \\"\\",
\\"unicode\\": 1,
\\"stretchH\\": 100,
\\"smooth\\": 1,
\\"aa\\": 2,
\\"padding\\": [0, 0, 0, 0],
\\"spacing\\": [0, 0]
}
};"
`);
});
test("parseFont - multipage", async () => {
expect(await parseFont("fixtures/multipage.fnt")).toMatchInlineSnapshot(`
"module.exports = {
\\"pages\\": [typeof require(\\"./sheet_0.png\\") === \\"object\\" && require(\\"./sheet_0.png\\") != null && require(\\"./sheet_0.png\\").__esModule && {}.hasOwnProperty.call(require(\\"./sheet_0.png\\"), \\"default\\") ? require(\\"./sheet_0.png\\").default : require(\\"./sheet_0.png\\"), typeof require(\\"./sheet_1.png\\") === \\"object\\" && require(\\"./sheet_1.png\\") != null && require(\\"./sheet_1.png\\").__esModule && {}.hasOwnProperty.call(require(\\"./sheet_1.png\\"), \\"default\\") ? require(\\"./sheet_1.png\\").default : require(\\"./sheet_1.png\\")],
\\"chars\\": [{
\\"id\\": 10,
\\"x\\": 305,
\\"y\\": 11,
\\"width\\": 0,
\\"height\\": 0,
\\"xoffset\\": 0,
\\"yoffset\\": 24,
\\"xadvance\\": 8,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 32,
\\"x\\": 0,
\\"y\\": 0,
\\"width\\": 0,
\\"height\\": 0,
\\"xoffset\\": 0,
\\"yoffset\\": 0,
\\"xadvance\\": 9,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 33,
\\"x\\": 69,
\\"y\\": 373,
\\"width\\": 4,
\\"height\\": 23,
\\"xoffset\\": 1,
\\"yoffset\\": 2,
\\"xadvance\\": 6,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 34,
\\"x\\": 276,
\\"y\\": 67,
\\"width\\": 7,
\\"height\\": 8,
\\"xoffset\\": 1,
\\"yoffset\\": 2,
\\"xadvance\\": 10,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 35,
\\"x\\": 361,
\\"y\\": 103,
\\"width\\": 19,
\\"height\\": 22,
\\"xoffset\\": 0,
\\"yoffset\\": 2,
\\"xadvance\\": 20,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 36,
\\"x\\": 122,
\\"y\\": 212,
\\"width\\": 19,
\\"height\\": 29,
\\"xoffset\\": 0,
\\"yoffset\\": -2,
\\"xadvance\\": 20,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 37,
\\"x\\": 335,
\\"y\\": 103,
\\"width\\": 24,
\\"height\\": 23,
\\"xoffset\\": -1,
\\"yoffset\\": 1,
\\"xadvance\\": 23,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 38,
\\"x\\": 382,
\\"y\\": 103,
\\"width\\": 19,
\\"height\\": 22,
\\"xoffset\\": 2,
\\"yoffset\\": 2,
\\"xadvance\\": 23,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 39,
\\"x\\": 24,
\\"y\\": 199,
\\"width\\": 2,
\\"height\\": 8,
\\"xoffset\\": 2,
\\"yoffset\\": 2,
\\"xadvance\\": 7,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 40,
\\"x\\": 105,
\\"y\\": 164,
\\"width\\": 11,
\\"height\\": 29,
\\"xoffset\\": 0,
\\"yoffset\\": -1,
\\"xadvance\\": 12,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 41,
\\"x\\": 105,
\\"y\\": 195,
\\"width\\": 11,
\\"height\\": 29,
\\"xoffset\\": 0,
\\"yoffset\\": -1,
\\"xadvance\\": 11,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 42,
\\"x\\": 118,
\\"y\\": 71,
\\"width\\": 7,
\\"height\\": 6,
\\"xoffset\\": 1,
\\"yoffset\\": 2,
\\"xadvance\\": 9,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 43,
\\"x\\": 105,
\\"y\\": 377,
\\"width\\": 14,
\\"height\\": 12,
\\"xoffset\\": 1,
\\"yoffset\\": 7,
\\"xadvance\\": 16,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 44,
\\"x\\": 44,
\\"y\\": 228,
\\"width\\": 4,
\\"height\\": 6,
\\"xoffset\\": 0,
\\"yoffset\\": 21,
\\"xadvance\\": 6,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 45,
\\"x\\": 494,
\\"y\\": 24,
\\"width\\": 13,
\\"height\\": 2,
\\"xoffset\\": 1,
\\"yoffset\\": 13,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 46,
\\"x\\": 508,
\\"y\\": 14,
\\"width\\": 3,
\\"height\\": 4,
\\"xoffset\\": 1,
\\"yoffset\\": 21,
\\"xadvance\\": 6,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 47,
\\"x\\": 105,
\\"y\\": 319,
\\"width\\": 15,
\\"height\\": 27,
\\"xoffset\\": -1,
\\"yoffset\\": 0,
\\"xadvance\\": 14,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 48,
\\"x\\": 122,
\\"y\\": 154,
\\"width\\": 18,
\\"height\\": 30,
\\"xoffset\\": 1,
\\"yoffset\\": -2,
\\"xadvance\\": 20,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 49,
\\"x\\": 93,
\\"y\\": 106,
\\"width\\": 10,
\\"height\\": 22,
\\"xoffset\\": 0,
\\"yoffset\\": 2,
\\"xadvance\\": 11,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 50,
\\"x\\": 176,
\\"y\\": 103,
\\"width\\": 18,
\\"height\\": 22,
\\"xoffset\\": 1,
\\"yoffset\\": 2,
\\"xadvance\\": 21,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 51,
\\"x\\": 196,
\\"y\\": 103,
\\"width\\": 17,
\\"height\\": 22,
\\"xoffset\\": 1,
\\"yoffset\\": 2,
\\"xadvance\\": 20,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 52,
\\"x\\": 215,
\\"y\\": 103,
\\"width\\": 19,
\\"height\\": 22,
\\"xoffset\\": 0,
\\"yoffset\\": 2,
\\"xadvance\\": 20,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 53,
\\"x\\": 236,
\\"y\\": 103,
\\"width\\": 18,
\\"height\\": 22,
\\"xoffset\\": 1,
\\"yoffset\\": 2,
\\"xadvance\\": 20,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 54,
\\"x\\": 256,
\\"y\\": 103,
\\"width\\": 19,
\\"height\\": 22,
\\"xoffset\\": 1,
\\"yoffset\\": 2,
\\"xadvance\\": 21,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 55,
\\"x\\": 277,
\\"y\\": 103,
\\"width\\": 18,
\\"height\\": 22,
\\"xoffset\\": 0,
\\"yoffset\\": 2,
\\"xadvance\\": 19,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 56,
\\"x\\": 122,
\\"y\\": 128,
\\"width\\": 19,
\\"height\\": 24,
\\"xoffset\\": 1,
\\"yoffset\\": 1,
\\"xadvance\\": 22,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 57,
\\"x\\": 297,
\\"y\\": 103,
\\"width\\": 18,
\\"height\\": 22,
\\"xoffset\\": 1,
\\"yoffset\\": 2,
\\"xadvance\\": 22,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 58,
\\"x\\": 46,
\\"y\\": 318,
\\"width\\": 3,
\\"height\\": 14,
\\"xoffset\\": 2,
\\"yoffset\\": 11,
\\"xadvance\\": 7,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 59,
\\"x\\": 45,
\\"y\\": 424,
\\"width\\": 4,
\\"height\\": 16,
\\"xoffset\\": 1,
\\"yoffset\\": 11,
\\"xadvance\\": 7,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 60,
\\"x\\": 502,
\\"y\\": 53,
\\"width\\": 8,
\\"height\\": 14,
\\"xoffset\\": 1,
\\"yoffset\\": 6,
\\"xadvance\\": 11,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 61,
\\"x\\": 369,
\\"y\\": 67,
\\"width\\": 13,
\\"height\\": 7,
\\"xoffset\\": 1,
\\"yoffset\\": 10,
\\"xadvance\\": 16,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 62,
\\"x\\": 93,
\\"y\\": 202,
\\"width\\": 9,
\\"height\\": 13,
\\"xoffset\\": 1,
\\"yoffset\\": 7,
\\"xadvance\\": 11,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 63,
\\"x\\": 122,
\\"y\\": 186,
\\"width\\": 18,
\\"height\\": 24,
\\"xoffset\\": 1,
\\"yoffset\\": 2,
\\"xadvance\\": 21,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 64,
\\"x\\": 143,
\\"y\\": 128,
\\"width\\": 25,
\\"height\\": 25,
\\"xoffset\\": 2,
\\"yoffset\\": 2,
\\"xadvance\\": 30,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 65,
\\"x\\": 396,
\\"y\\": 53,
\\"width\\": 23,
\\"height\\": 22,
\\"xoffset\\": -1,
\\"yoffset\\": 2,
\\"xadvance\\": 22,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 66,
\\"x\\": 421,
\\"y\\": 53,
\\"width\\": 18,
\\"height\\": 22,
\\"xoffset\\": 2,
\\"yoffset\\": 2,
\\"xadvance\\": 21,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 67,
\\"x\\": 441,
\\"y\\": 53,
\\"width\\": 20,
\\"height\\": 22,
\\"xoffset\\": 1,
\\"yoffset\\": 2,
\\"xadvance\\": 22,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 68,
\\"x\\": 463,
\\"y\\": 53,
\\"width\\": 19,
\\"height\\": 22,
\\"xoffset\\": 2,
\\"yoffset\\": 2,
\\"xadvance\\": 23,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 69,
\\"x\\": 484,
\\"y\\": 53,
\\"width\\": 16,
\\"height\\": 22,
\\"xoffset\\": 2,
\\"yoffset\\": 2,
\\"xadvance\\": 20,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 70,
\\"x\\": 75,
\\"y\\": 106,
\\"width\\": 16,
\\"height\\": 22,
\\"xoffset\\": 2,
\\"yoffset\\": 2,
\\"xadvance\\": 19,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 71,
\\"x\\": 75,
\\"y\\": 130,
\\"width\\": 20,
\\"height\\": 22,
\\"xoffset\\": 1,
\\"yoffset\\": 2,
\\"xadvance\\": 24,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 72,
\\"x\\": 75,
\\"y\\": 154,
\\"width\\": 18,
\\"height\\": 22,
\\"xoffset\\": 2,
\\"yoffset\\": 2,
\\"xadvance\\": 23,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 73,
\\"x\\": 24,
\\"y\\": 309,
\\"width\\": 2,
\\"height\\": 22,
\\"xoffset\\": 2,
\\"yoffset\\": 2,
\\"xadvance\\": 7,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 74,
\\"x\\": 75,
\\"y\\": 178,
\\"width\\": 18,
\\"height\\": 22,
\\"xoffset\\": 1,
\\"yoffset\\": 2,
\\"xadvance\\": 22,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 75,
\\"x\\": 75,
\\"y\\": 202,
\\"width\\": 16,
\\"height\\": 22,
\\"xoffset\\": 2,
\\"yoffset\\": 2,
\\"xadvance\\": 18,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 76,
\\"x\\": 75,
\\"y\\": 226,
\\"width\\": 15,
\\"height\\": 22,
\\"xoffset\\": 2,
\\"yoffset\\": 2,
\\"xadvance\\": 18,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 77,
\\"x\\": 75,
\\"y\\": 250,
\\"width\\": 22,
\\"height\\": 22,
\\"xoffset\\": 2,
\\"yoffset\\": 2,
\\"xadvance\\": 26,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 78,
\\"x\\": 75,
\\"y\\": 274,
\\"width\\": 18,
\\"height\\": 22,
\\"xoffset\\": 2,
\\"yoffset\\": 2,
\\"xadvance\\": 23,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 79,
\\"x\\": 75,
\\"y\\": 298,
\\"width\\": 23,
\\"height\\": 22,
\\"xoffset\\": 1,
\\"yoffset\\": 2,
\\"xadvance\\": 26,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 80,
\\"x\\": 75,
\\"y\\": 322,
\\"width\\": 20,
\\"height\\": 22,
\\"xoffset\\": 2,
\\"yoffset\\": 2,
\\"xadvance\\": 21,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 81,
\\"x\\": 75,
\\"y\\": 346,
\\"width\\": 23,
\\"height\\": 22,
\\"xoffset\\": 1,
\\"yoffset\\": 2,
\\"xadvance\\": 25,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 82,
\\"x\\": 75,
\\"y\\": 370,
\\"width\\": 18,
\\"height\\": 22,
\\"xoffset\\": 2,
\\"yoffset\\": 2,
\\"xadvance\\": 21,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 83,
\\"x\\": 75,
\\"y\\": 394,
\\"width\\": 19,
\\"height\\": 22,
\\"xoffset\\": 0,
\\"yoffset\\": 2,
\\"xadvance\\": 20,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 84,
\\"x\\": 75,
\\"y\\": 418,
\\"width\\": 19,
\\"height\\": 22,
\\"xoffset\\": 0,
\\"yoffset\\": 2,
\\"xadvance\\": 19,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 85,
\\"x\\": 75,
\\"y\\": 442,
\\"width\\": 17,
\\"height\\": 26,
\\"xoffset\\": 2,
\\"yoffset\\": 2,
\\"xadvance\\": 22,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 86,
\\"x\\": 75,
\\"y\\": 470,
\\"width\\": 21,
\\"height\\": 22,
\\"xoffset\\": 0,
\\"yoffset\\": 2,
\\"xadvance\\": 22,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 87,
\\"x\\": 105,
\\"y\\": 79,
\\"width\\": 33,
\\"height\\": 22,
\\"xoffset\\": 0,
\\"yoffset\\": 2,
\\"xadvance\\": 33,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 88,
\\"x\\": 140,
\\"y\\": 79,
\\"width\\": 20,
\\"height\\": 22,
\\"xoffset\\": 0,
\\"yoffset\\": 2,
\\"xadvance\\": 21,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 89,
\\"x\\": 162,
\\"y\\": 79,
\\"width\\": 20,
\\"height\\": 22,
\\"xoffset\\": 0,
\\"yoffset\\": 2,
\\"xadvance\\": 20,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 90,
\\"x\\": 184,
\\"y\\": 79,
\\"width\\": 18,
\\"height\\": 22,
\\"xoffset\\": 0,
\\"yoffset\\": 2,
\\"xadvance\\": 19,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 91,
\\"x\\": 105,
\\"y\\": 226,
\\"width\\": 6,
\\"height\\": 29,
\\"xoffset\\": 2,
\\"yoffset\\": -1,
\\"xadvance\\": 9,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 92,
\\"x\\": 105,
\\"y\\": 348,
\\"width\\": 15,
\\"height\\": 27,
\\"xoffset\\": -1,
\\"yoffset\\": 0,
\\"xadvance\\": 14,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 93,
\\"x\\": 113,
\\"y\\": 226,
\\"width\\": 6,
\\"height\\": 29,
\\"xoffset\\": 1,
\\"yoffset\\": -1,
\\"xadvance\\": 10,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 94,
\\"x\\": 317,
\\"y\\": 103,
\\"width\\": 16,
\\"height\\": 10,
\\"xoffset\\": 0,
\\"yoffset\\": 2,
\\"xadvance\\": 17,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 95,
\\"x\\": 100,
\\"y\\": 71,
\\"width\\": 16,
\\"height\\": 2,
\\"xoffset\\": 0,
\\"yoffset\\": 25,
\\"xadvance\\": 16,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 96,
\\"x\\": 137,
\\"y\\": 23,
\\"width\\": 6,
\\"height\\": 4,
\\"xoffset\\": 0,
\\"yoffset\\": 2,
\\"xadvance\\": 7,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 97,
\\"x\\": 75,
\\"y\\": 494,
\\"width\\": 18,
\\"height\\": 16,
\\"xoffset\\": 1,
\\"yoffset\\": 8,
\\"xadvance\\": 19,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 98,
\\"x\\": 204,
\\"y\\": 79,
\\"width\\": 16,
\\"height\\": 22,
\\"xoffset\\": 2,
\\"yoffset\\": 2,
\\"xadvance\\": 20,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 99,
\\"x\\": 222,
\\"y\\": 79,
\\"width\\": 15,
\\"height\\": 16,
\\"xoffset\\": 1,
\\"yoffset\\": 8,
\\"xadvance\\": 16,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 100,
\\"x\\": 239,
\\"y\\": 79,
\\"width\\": 16,
\\"height\\": 22,
\\"xoffset\\": 1,
\\"yoffset\\": 2,
\\"xadvance\\": 20,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 101,
\\"x\\": 257,
\\"y\\": 79,
\\"width\\": 18,
\\"height\\": 16,
\\"xoffset\\": 0,
\\"yoffset\\": 8,
\\"xadvance\\": 19,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 102,
\\"x\\": 277,
\\"y\\": 79,
\\"width\\": 13,
\\"height\\": 22,
\\"xoffset\\": -1,
\\"yoffset\\": 2,
\\"xadvance\\": 12,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 103,
\\"x\\": 105,
\\"y\\": 103,
\\"width\\": 15,
\\"height\\": 27,
\\"xoffset\\": 1,
\\"yoffset\\": 7,
\\"xadvance\\": 17,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 104,
\\"x\\": 292,
\\"y\\": 79,
\\"width\\": 14,
\\"height\\": 22,
\\"xoffset\\": 2,
\\"yoffset\\": 2,
\\"xadvance\\": 18,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 105,
\\"x\\": 46,
\\"y\\": 380,
\\"width\\": 3,
\\"height\\": 23,
\\"xoffset\\": 1,
\\"yoffset\\": 1,
\\"xadvance\\": 6,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 106,
\\"x\\": 105,
\\"y\\": 132,
\\"width\\": 8,
\\"height\\": 30,
\\"xoffset\\": -4,
\\"yoffset\\": 1,
\\"xadvance\\": 6,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 107,
\\"x\\": 308,
\\"y\\": 79,
\\"width\\": 13,
\\"height\\": 22,
\\"xoffset\\": 2,
\\"yoffset\\": 2,
\\"xadvance\\": 14,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 108,
\\"x\\": 47,
\\"y\\": 173,
\\"width\\": 2,
\\"height\\": 22,
\\"xoffset\\": 2,
\\"yoffset\\": 2,
\\"xadvance\\": 6,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 109,
\\"x\\": 323,
\\"y\\": 79,
\\"width\\": 25,
\\"height\\": 17,
\\"xoffset\\": 2,
\\"yoffset\\": 7,
\\"xadvance\\": 29,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 110,
\\"x\\": 350,
\\"y\\": 79,
\\"width\\": 14,
\\"height\\": 16,
\\"xoffset\\": 2,
\\"yoffset\\": 8,
\\"xadvance\\": 18,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 111,
\\"x\\": 366,
\\"y\\": 79,
\\"width\\": 16,
\\"height\\": 16,
\\"xoffset\\": 1,
\\"yoffset\\": 8,
\\"xadvance\\": 19,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 112,
\\"x\\": 122,
\\"y\\": 103,
\\"width\\": 16,
\\"height\\": 23,
\\"xoffset\\": 2,
\\"yoffset\\": 8,
\\"xadvance\\": 20,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 113,
\\"x\\": 140,
\\"y\\": 103,
\\"width\\": 16,
\\"height\\": 23,
\\"xoffset\\": 1,
\\"yoffset\\": 8,
\\"xadvance\\": 20,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 114,
\\"x\\": 92,
\\"y\\": 226,
\\"width\\": 11,
\\"height\\": 16,
\\"xoffset\\": 2,
\\"yoffset\\": 8,
\\"xadvance\\": 13,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 115,
\\"x\\": 384,
\\"y\\": 79,
\\"width\\": 15,
\\"height\\": 16,
\\"xoffset\\": 0,
\\"yoffset\\": 8,
\\"xadvance\\": 16,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 116,
\\"x\\": 401,
\\"y\\": 79,
\\"width\\": 12,
\\"height\\": 21,
\\"xoffset\\": 0,
\\"yoffset\\": 3,
\\"xadvance\\": 13,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 117,
\\"x\\": 415,
\\"y\\": 79,
\\"width\\": 14,
\\"height\\": 16,
\\"xoffset\\": 2,
\\"yoffset\\": 8,
\\"xadvance\\": 18,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 118,
\\"x\\": 431,
\\"y\\": 79,
\\"width\\": 16,
\\"height\\": 16,
\\"xoffset\\": 0,
\\"yoffset\\": 8,
\\"xadvance\\": 16,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 119,
\\"x\\": 449,
\\"y\\": 79,
\\"width\\": 25,
\\"height\\": 16,
\\"xoffset\\": -1,
\\"yoffset\\": 8,
\\"xadvance\\": 24,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 120,
\\"x\\": 476,
\\"y\\": 79,
\\"width\\": 15,
\\"height\\": 16,
\\"xoffset\\": 0,
\\"yoffset\\": 8,
\\"xadvance\\": 16,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 121,
\\"x\\": 158,
\\"y\\": 103,
\\"width\\": 16,
\\"height\\": 23,
\\"xoffset\\": 0,
\\"yoffset\\": 8,
\\"xadvance\\": 17,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 122,
\\"x\\": 493,
\\"y\\": 79,
\\"width\\": 14,
\\"height\\": 16,
\\"xoffset\\": 0,
\\"yoffset\\": 8,
\\"xadvance\\": 15,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 123,
\\"x\\": 105,
\\"y\\": 257,
\\"width\\": 8,
\\"height\\": 29,
\\"xoffset\\": 1,
\\"yoffset\\": 0,
\\"xadvance\\": 10,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 124,
\\"x\\": 69,
\\"y\\": 403,
\\"width\\": 2,
\\"height\\": 26,
\\"xoffset\\": 3,
\\"yoffset\\": 2,
\\"xadvance\\": 8,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 125,
\\"x\\": 105,
\\"y\\": 288,
\\"width\\": 8,
\\"height\\": 29,
\\"xoffset\\": 1,
\\"yoffset\\": 0,
\\"xadvance\\": 10,
\\"page\\": 0,
\\"chnl\\": 0
}, {
\\"id\\": 126,
\\"x\\": 403,
\\"y\\": 103,
\\"width\\": 17,
\\"height\\": 8,
\\"xoffset\\": 0,
\\"yoffset\\": 10,
\\"xadvance\\": 18,
\\"page\\": 0,
\\"chnl\\": 0
}],
\\"kernings\\": [{
\\"first\\": 34,
\\"second\\": 65,
\\"amount\\": -2
}, {
\\"first\\": 34,
\\"second\\": 67,
\\"amount\\": 1
}, {
\\"first\\": 34,
\\"second\\": 74,
\\"amount\\": -2
}, {
\\"first\\": 34,
\\"second\\": 77,
\\"amount\\": 1
}, {
\\"first\\": 34,
\\"second\\": 97,
\\"amount\\": -2
}, {
\\"first\\": 34,
\\"second\\": 102,
\\"amount\\": 1
}, {
\\"first\\": 34,
\\"second\\": 104,
\\"amount\\": 1
}, {
\\"first\\": 34,
\\"second\\": 112,
\\"amount\\": 1
}, {
\\"first\\": 34,
\\"second\\": 116,
\\"amount\\": 1
}, {
\\"first\\": 35,
\\"second\\": 53,
\\"amount\\": 1
}, {
\\"first\\": 35,
\\"second\\": 57,
\\"amount\\": 1
}, {
\\"first\\": 37,
\\"second\\": 49,
\\"amount\\": -2
}, {
\\"first\\": 37,
\\"second\\": 50,
\\"amount\\": 1
}, {
\\"first\\": 37,
\\"second\\": 54,
\\"amount\\": 1
}, {
\\"first\\": 37,
\\"second\\": 56,
\\"amount\\": 1
}, {
\\"first\\": 38,
\\"second\\": 48,
\\"amount\\": -2
}, {
\\"first\\": 38,
\\"second\\": 49,
\\"amount\\": -4
}, {
\\"first\\": 38,
\\"second\\": 50,
\\"amount\\": 1
}, {
\\"first\\": 38,
\\"second\\": 52,
\\"amount\\": -2
}, {
\\"first\\": 38,
\\"second\\": 57,
\\"amount\\": -3
}, {
\\"first\\": 38,
\\"second\\": 67,
\\"amount\\": -2
}, {
\\"first\\": 38,
\\"second\\": 69,
\\"amount\\": 1
}, {
\\"first\\": 38,
\\"second\\": 70,
\\"amount\\": 1
}, {
\\"first\\": 38,
\\"second\\": 79,
\\"amount\\": -2
}, {
\\"first\\": 38,
\\"second\\": 80,
\\"amount\\": -4
}, {
\\"first\\": 38,
\\"second\\": 81,
\\"amount\\": -2
}, {
\\"first\\": 38,
\\"second\\": 82,
\\"amount\\": -4
}, {
\\"first\\": 38,
\\"second\\": 83,
\\"amount\\": -3
}, {
\\"first\\": 38,
\\"second\\": 84,
\\"amount\\": -5
}, {
\\"first\\": 38,
\\"second\\": 85,
\\"amount\\": -4
}, {
\\"first\\": 38,
\\"second\\": 86,
\\"amount\\": 1
}, {
\\"first\\": 38,
\\"second\\": 87,
\\"amount\\": -4
}, {
\\"first\\": 38,
\\"second\\": 89,
\\"amount\\": -6
}, {
\\"first\\": 38,
\\"second\\": 97,
\\"amount\\": 1
}, {
\\"first\\": 38,
\\"second\\": 99,
\\"amount\\": -2
}, {
\\"first\\": 38,
\\"second\\": 103,
\\"amount\\": -2
}, {
\\"first\\": 38,
\\"second\\": 106,
\\"amount\\": 1
}, {
\\"first\\": 38,
\\"second\\": 111,
\\"amount\\": -2
}, {
\\"first\\": 38,
\\"second\\": 113,
\\"amount\\": -2
}, {
\\"first\\": 38,
\\"second\\": 116,
\\"amount\\": -5
}, {
\\"first\\": 38,
\\"second\\": 118,
\\"amount\\": -4
}, {
\\"first\\": 38,
\\"second\\": 119,
\\"amount\\": -4
}, {
\\"first\\": 38,
\\"second\\": 121,
\\"amount\\": -5
}, {
\\"first\\": 39,
\\"second\\": 116,
\\"amount\\": 1
}, {
\\"first\\": 44,
\\"second\\": 90,
\\"amount\\": 1
}, {
\\"first\\": 44,
\\"second\\": 97,
\\"amount\\": 1
}, {
\\"first\\": 44,
\\"second\\": 99,
\\"amount\\": -2
}, {
\\"first\\": 44,
\\"second\\": 100,
\\"amount\\": 1
}, {
\\"first\\": 44,
\\"second\\": 101,
\\"amount\\": 1
}, {
\\"first\\": 44,
\\"second\\": 105,
\\"amount\\": 1
}, {
\\"first\\": 44,
\\"second\\": 106,
\\"amount\\": 1
}, {
\\"first\\": 44,
\\"second\\": 107,
\\"amount\\": 1
}, {
\\"first\\": 44,
\\"second\\": 108,
\\"amount\\": 1
}, {
\\"first\\": 44,
\\"second\\": 122,
\\"amount\\": 1
}, {
\\"first\\": 46,
\\"second\\": 66,
\\"amount\\": 1
}, {
\\"first\\": 46,
\\"second\\": 67,
\\"amount\\": -2
}, {
\\"first\\": 46,
\\"second\\": 84,
\\"amount\\": -3
}, {
\\"first\\": 46,
\\"second\\": 86,
\\"amount\\": 1
}, {
\\"first\\": 46,
\\"second\\": 89,
\\"amount\\": -5
}, {
\\"first\\": 46,
\\"second\\": 90,
\\"amount\\": 1
}, {
\\"first\\": 46,
\\"second\\": 97,
\\"amount\\": 1
}, {
\\"first\\": 46,
\\"second\\": 98,
\\"amount\\": 1
}, {
\\"first\\": 46,
\\"second\\": 100,
\\"amount\\": 1
}, {
\\"first\\": 46,
\\"second\\": 101,
\\"amount\\": 1
}, {
\\"first\\": 46,
\\"second\\": 103,
\\"amount\\": -2
}, {
\\"first\\": 46,
\\"second\\": 104,
\\"amount\\": 1
}, {
\\"first\\": 46,
\\"second\\": 106,
\\"amount\\": 1
}, {
\\"first\\": 46,
\\"second\\": 107,
\\"amount\\": 1
}, {
\\"first\\": 46,
\\"second\\": 108,
\\"amount\\": 1
}, {
\\"first\\": 46,
\\"second\\": 111,
\\"amount\\": -2
}, {
\\"first\\": 46,
\\"second\\": 112,
\\"amount\\": 1
}, {
\\"first\\": 46,
\\"second\\": 113,
\\"amount\\": -2
}, {
\\"first\\": 46,
\\"second\\": 116,
\\"amount\\": -3
}, {
\\"first\\": 46,
\\"second\\": 118,
\\"amount\\": -4
}, {
\\"first\\": 46,
\\"second\\": 119,
\\"amount\\": -2
}, {
\\"first\\": 46,
\\"second\\": 120,
\\"amount\\": 1
}, {
\\"first\\": 46,
\\"second\\": 121,
\\"amount\\": -5
}, {
\\"first\\": 46,
\\"second\\": 122,
\\"amount\\": 1
}, {
\\"first\\": 47,
\\"second\\": 65,
\\"amount\\": -3
}, {
\\"first\\": 47,
\\"second\\": 66,
\\"amount\\": 2
}, {
\\"first\\": 47,
\\"second\\": 77,
\\"amount\\": 2
}, {
\\"first\\": 47,
\\"second\\": 84,
\\"amount\\": 1
}, {
\\"first\\": 47,
\\"second\\": 85,
\\"amount\\": 2
}, {
\\"first\\": 47,
\\"second\\": 86,
\\"amount\\": 2
}, {
\\"first\\": 47,
\\"second\\": 87,
\\"amount\\": 1
}, {
\\"first\\": 47,
\\"second\\": 88,
\\"amount\\": 1
}, {
\\"first\\": 47,
\\"second\\": 89,
\\"amount\\": 2
}, {
\\"first\\": 47,
\\"second\\": 90,
\\"amount\\": 1
}, {
\\"first\\": 47,
\\"second\\": 97,
\\"amount\\": 2
}, {
\\"first\\": 47,
\\"second\\": 98,
\\"amount\\": 1
}, {
\\"first\\": 47,
\\"second\\": 100,
\\"amount\\": 2
}, {
\\"first\\": 47,
\\"second\\": 101,
\\"amount\\": 1
}, {
\\"first\\": 47,
\\"second\\": 102,
\\"amount\\": 1
}, {
\\"first\\": 47,
\\"second\\": 104,
\\"amount\\": 1
}, {
\\"first\\": 47,
\\"second\\": 105,
\\"amount\\": 1
}, {
\\"first\\": 47,
\\"second\\": 107,
\\"amount\\": 1
}, {
\\"first\\": 47,
\\"second\\": 108,
\\"amount\\": 1
}, {
\\"first\\": 47,
\\"second\\": 109,
\\"amount\\": 1
}, {
\\"first\\": 47,
\\"second\\": 112,
\\"amount\\": 1
}, {
\\"first\\": 47,
\\"second\\": 113,
\\"amount\\": -2
}, {
\\"first\\": 47,
\\"second\\": 116,
\\"amount\\": 2
}, {
\\"first\\": 47,
\\"second\\": 117,
\\"amount\\": 1
}, {
\\"first\\": 47,
\\"second\\": 118,
\\"amount\\": 1
}, {
\\"first\\": 47,
\\"second\\": 119,
\\"amount\\": 2
}, {
\\"first\\": 47,
\\"second\\": 120,
\\"amount\\": 1
}, {
\\"first\\": 47,
\\"second\\": 121,
\\"amount\\": 2
}, {
\\"first\\": 47,
\\"second\\": 122,
\\"amount\\": 1
}, {
\\"first\\": 48,
\\"second\\": 50,
\\"amount\\": -2
}, {
\\"first\\": 48,
\\"second\\": 54,
\\"amount\\": 1
}, {
\\"first\\": 48,
\\"second\\": 55,
\\"amount\\": -3
}, {
\\"first\\": 49,
\\"second\\": 51,
\\"amount\\": 1
}, {
\\"first\\": 49,
\\"second\\": 53,
\\"amount\\": 1
}, {
\\"first\\": 49,
\\"second\\": 54,
\\"amount\\": 1
}, {
\\"first\\": 49,
\\"second\\": 56,
\\"amount\\": 1
}, {
\\"first\\": 49,
\\"second\\": 57,
\\"amount\\": 1
}, {
\\"first\\": 50,
\\"second\\": 52,
\\"amount\\": -2
}, {
\\"first\\": 50,
\\"second\\": 55,
\\"amount\\": -2
}, {
\\"first\\": 51,
\\"second\\": 55,
\\"amount\\": -2
}, {
\\"first\\": 51,
\\"second\\": 57,
\\"amount\\": -2
}, {
\\"first\\": 52,
\\"second\\": 55,
\\"amount\\": -3
}, {
\\"first\\": 52,
\\"second\\": 56,
\\"amount\\": 1
}, {
\\"first\\": 53,
\\"second\\": 55,
\\"amount\\": -3
}, {
\\"first\\": 53,
\\"second\\": 57,
\\"amount\\": -2
}, {
\\"first\\": 54,
\\"second\\": 55,
\\"amount\\": -3
}, {
\\"first\\": 55,
\\"second\\": 56,
\\"amount\\": -2
}, {
\\"first\\": 58,
\\"second\\": 85,
\\"amount\\": 1
}, {
\\"first\\": 58,
\\"second\\": 90,
\\"amount\\": 1
}, {
\\"first\\": 58,
\\"second\\": 103,
\\"amount\\": 1
}, {
\\"first\\": 58,
\\"second\\": 115,
\\"amount\\": 1
}, {
\\"first\\": 58,
\\"second\\": 117,
\\"amount\\": 1
}, {
\\"first\\": 58,
\\"second\\": 118,
\\"amount\\": -2
}, {
\\"first\\": 58,
\\"second\\": 121,
\\"amount\\": -2
}, {
\\"first\\": 59,
\\"second\\": 69,
\\"amount\\": 1
}, {
\\"first\\": 59,
\\"second\\": 81,
\\"amount\\": 1
}, {
\\"first\\": 59,
\\"second\\": 84,
\\"amount\\": 1
}, {
\\"first\\": 59,
\\"second\\": 86,
\\"amount\\": 2
}, {
\\"first\\": 59,
\\"second\\": 103,
\\"amount\\": 1
}, {
\\"first\\": 59,
\\"second\\": 121,
\\"amount\\": -2
}, {
\\"first\\": 63,
\\"second\\": 66,
\\"amount\\": 1
}, {
\\"first\\": 63,
\\"second\\": 74,
\\"amount\\": -2
}, {
\\"first\\": 63,
\\"second\\": 97,
\\"amount\\": -2
}, {
\\"first\\": 64,
\\"second\\": 70,
\\"amount\\": -2
}, {
\\"first\\": 64,
\\"second\\": 80,
\\"amount\\": -2
}, {
\\"first\\": 64,
\\"second\\": 84,
\\"amount\\": -2
}, {
\\"first\\": 64,
\\"second\\": 85,
\\"amount\\": -2
}, {
\\"first\\": 64,
\\"second\\": 86,
\\"amount\\": -2
}, {
\\"first\\": 64,
\\"second\\": 97,
\\"amount\\": -2
}, {
\\"first\\": 64,
\\"second\\": 103,
\\"amount\\": -2
}, {
\\"first\\": 64,
\\"second\\": 106,
\\"amount\\": -2
}, {
\\"first\\": 64,
\\"second\\": 112,
\\"amount\\": 1
}, {
\\"first\\": 64,
\\"second\\": 114,
\\"amount\\": 1
}, {
\\"first\\": 65,
\\"second\\": 67,
\\"amount\\": -2
}, {
\\"first\\": 65,
\\"second\\": 68,
\\"amount\\": 1
}, {
\\"first\\": 65,
\\"second\\": 71,
\\"amount\\": -2
}, {
\\"first\\": 65,
\\"second\\": 74,
\\"amount\\": -2
}, {
\\"first\\": 65,
\\"second\\": 76,
\\"amount\\": 1
}, {
\\"first\\": 65,
\\"second\\": 79,
\\"amount\\": -2
}, {
\\"first\\": 65,
\\"second\\": 81,
\\"amount\\": -2
}, {
\\"first\\": 65,
\\"second\\": 84,
\\"amount\\": -4
}, {
\\"first\\": 65,
\\"second\\": 85,
\\"amount\\": -2
}, {
\\"first\\": 65,
\\"second\\": 86,
\\"amount\\": -4
}, {
\\"first\\": 65,
\\"second\\": 87,
\\"amount\\": -4
}, {
\\"first\\": 65,
\\"second\\": 89,
\\"amount\\": -4
}, {
\\"first\\": 65,
\\"second\\": 90,
\\"amount\\": 1
}, {
\\"first\\": 65,
\\"second\\": 100,
\\"amount\\": -2
}, {
\\"first\\": 65,
\\"second\\": 102,
\\"amount\\": -2
}, {
\\"first\\": 65,
\\"second\\": 103,
\\"amount\\": 1
}, {
\\"first\\": 65,
\\"second\\": 113,
\\"amount\\": -2
}, {
\\"first\\": 65,
\\"second\\": 116,
\\"amount\\": -2
}, {
\\"first\\": 65,
\\"second\\": 117,
\\"amount\\": -2
}, {
\\"first\\": 65,
\\"second\\": 118,
\\"amount\\": -3
}, {
\\"first\\": 65,
\\"second\\": 119,
\\"amount\\": -3
}, {
\\"first\\": 65,
\\"second\\": 120,
\\"amount\\": 1
}, {
\\"first\\": 65,
\\"second\\": 121,
\\"amount\\": -2
}, {
\\"first\\": 66,
\\"second\\": 68,
\\"amount\\": 1
}, {
\\"first\\": 66,
\\"second\\": 74,
\\"amount\\": 1
}, {
\\"first\\": 66,
\\"second\\": 81,
\\"amount\\": 1
}, {
\\"first\\": 66,
\\"second\\": 83,
\\"amount\\": 1
}, {
\\"first\\": 66,
\\"second\\": 86,
\\"amount\\": -2
}, {
\\"first\\": 66,
\\"second\\": 87,
\\"amount\\": -2
}, {
\\"first\\": 66,
\\"second\\": 89,
\\"amount\\": -2
}, {
\\"first\\": 67,
\\"second\\": 68,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 69,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 72,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 73,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 75,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 76,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 77,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 79,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 80,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 82,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 83,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 84,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 85,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 90,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 101,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 104,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 108,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 109,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 111,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 116,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 119,
\\"amount\\": 1
}, {
\\"first\\": 67,
\\"second\\": 121,
\\"amount\\": 1
}, {
\\"first\\": 68,
\\"second\\": 70,
\\"amount\\": 1
}, {
\\"first\\": 68,
\\"second\\": 81,
\\"amount\\": 1
}, {
\\"first\\": 68,
\\"second\\": 84,
\\"amount\\": -2
}, {
\\"first\\": 68,
\\"second\\": 87,
\\"amount\\": -2
}, {
\\"first\\": 68,
\\"second\\": 88,
\\"amount\\": -3
}, {
\\"first\\": 68,
\\"second\\": 89,
\\"amount\\": -3
}, {
\\"first\\": 68,
\\"second\\": 90,
\\"amount\\": -2
}, {
\\"first\\": 68,
\\"second\\": 101,
\\"amount\\": 1
}, {
\\"first\\": 68,
\\"second\\": 106,
\\"amount\\": 1
}, {
\\"first\\": 68,
\\"second\\": 109,
\\"amount\\": 1
}, {
\\"first\\": 68,
\\"second\\": 117,
\\"amount\\": 1
}, {
\\"first\\": 68,
\\"second\\": 119,
\\"amount\\": 1
}, {
\\"first\\": 68,
\\"second\\": 121,
\\"amount\\": 1
}, {
\\"first\\": 69,
\\"second\\": 78,
\\"amount\\": 1
}, {
\\"first\\": 69,
\\"second\\": 83,
\\"amount\\": 1
}, {
\\"first\\": 69,
\\"second\\": 84,
\\"amount\\": 1
}, {
\\"first\\": 69,
\\"second\\": 89,
\\"amount\\": 1
}, {
\\"first\\": 69,
\\"second\\": 106,
\\"amount\\": 1
}, {
\\"first\\": 69,
\\"second\\": 120,
\\"amount\\": 1
}, {
\\"first\\": 70,
\\"second\\": 71,
\\"amount\\": 1
}, {
\\"first\\": 70,
\\"second\\": 79,
\\"amount\\": 1
}, {
\\"first\\": 70,
\\"second\\": 84,
\\"amount\\": 1
}, {
\\"first\\": 70,
\\"second\\": 86,
\\"amount\\": 1
}, {
\\"first\\": 70,
\\"second\\": 89,
\\"amount\\": 1
}, {
\\"first\\": 70,
\\"second\\": 102,
\\"amount\\": 1
}, {
\\"first\\": 71,
\\"second\\": 84,
\\"amount\\": -2
}, {
\\"first\\": 71,
\\"second\\": 86,
\\"amount\\": -2
}, {
\\"first\\": 71,
\\"second\\": 87,
\\"amount\\": -2
}, {
\\"first\\": 71,
\\"second\\": 89,
\\"amount\\": -2
}, {
\\"first\\": 73,
\\"second\\": 79,
\\"amount\\": 1
}, {
\\"first\\": 73,
\\"second\\": 83,
\\"amount\\": 1
}, {
\\"first\\": 73,
\\"second\\": 84,
\\"amount\\": 1
}, {
\\"first\\": 73,
\\"second\\": 87,
\\"amount\\": 1
}, {
\\"first\\": 73,
\\"second\\": 90,
\\"amount\\": 1
}, {
\\"first\\": 74,
\\"second\\": 88,
\\"amount\\": -2
}, {
\\"first\\": 74,
\\"second\\": 97,
\\"amount\\": -2
}, {
\\"first\\": 74,
\\"second\\": 103,
\\"amount\\": -2
}, {
\\"first\\": 74,
\\"second\\": 106,
\\"amount\\": -2
}, {
\\"first\\": 75,
\\"second\\": 79,
\\"amount\\": -3
}, {
\\"first\\": 75,
\\"second\\": 81,
\\"amount\\": -2
}, {
\\"first\\": 75,
\\"second\\": 85,
\\"amount\\": -2
}, {
\\"first\\": 75,
\\"second\\": 97,
\\"amount\\": -2
}, {
\\"first\\": 75,
\\"second\\": 99,
\\"amount\\": -2
}, {
\\"first\\": 75,
\\"second\\": 100,
\\"amount\\": -2
}, {
\\"first\\": 75,
\\"second\\": 101,
\\"amount\\": -2
}, {
\\"first\\": 75,
\\"second\\": 103,
\\"amount\\": 1
}, {
\\"first\\": 75,
\\"second\\": 109,
\\"amount\\": -2
}, {
\\"first\\": 75,
\\"second\\": 110,
\\"amount\\": -2
}, {
\\"first\\": 75,
\\"second\\": 111,
\\"amount\\": -2
}, {
\\"first\\": 75,
\\"second\\": 113,
\\"amount\\": -2
}, {
\\"first\\": 75,
\\"second\\": 115,
\\"amount\\": -2
}, {
\\"first\\": 75,
\\"second\\": 116,
\\"amount\\": -2
}, {
\\"first\\": 75,
\\"second\\": 117,
\\"amount\\": -2
}, {
\\"first\\": 75,
\\"second\\": 118,
\\"amount\\": -3
}, {
\\"first\\": 75,
\\"second\\": 119,
\\"amount\\": -3
}, {
\\"first\\": 75,
\\"second\\": 121,
\\"amount\\": -2
}, {
\\"first\\": 75,
\\"second\\": 122,
\\"amount\\": -2
}, {
\\"first\\": 76,
\\"second\\": 79,
\\"amount\\": -2
}, {
\\"first\\": 76,
\\"second\\": 84,
\\"amount\\": -4
}, {
\\"first\\": 76,
\\"second\\": 85,
\\"amount\\": -2
}, {
\\"first\\": 76,
\\"second\\": 86,
\\"amount\\": -4
}, {
\\"first\\": 76,
\\"second\\": 87,
\\"amount\\": -4
}, {
\\"first\\": 76,
\\"second\\": 89,
\\"amount\\": -5
}, {
\\"first\\": 76,
\\"second\\": 90,
\\"amount\\": 1
}, {
\\"first\\": 76,
\\"second\\": 97,
\\"amount\\": 1
}, {
\\"first\\": 76,
\\"second\\": 103,
\\"amount\\": 1
}, {
\\"first\\": 76,
\\"second\\": 121,
\\"amount\\": -2
}, {
\\"first\\": 77,
\\"second\\": 87,
\\"amount\\": -2
}, {
\\"first\\": 79,
\\"second\\": 81,
\\"amount\\": 1
}, {
\\"first\\": 79,
\\"second\\": 83,
\\"amount\\": 1
}, {
\\"first\\": 79,
\\"second\\": 84,
\\"amount\\": -2
}, {
\\"first\\": 79,
\\"second\\": 86,
\\"amount\\": -2
}, {
\\"first\\": 79,
\\"second\\": 87,
\\"amount\\": -2
}, {
\\"first\\": 79,
\\"second\\": 88,
\\"amount\\": -2
}, {
\\"first\\": 79,
\\"second\\": 89,
\\"amount\\": -3
}, {
\\"first\\": 79,
\\"second\\": 90,
\\"amount\\": -2
}, {
\\"first\\": 79,
\\"second\\": 122,
\\"amount\\": -2
}, {
\\"first\\": 80,
\\"second\\": 88,
\\"amount\\": -2
}, {
\\"first\\": 80,
\\"second\\": 97,
\\"amount\\": -2
}, {
\\"first\\": 80,
\\"second\\": 99,
\\"amount\\": -2
}, {
\\"first\\": 80,
\\"second\\": 100,
\\"amount\\": -2
}, {
\\"first\\": 80,
\\"second\\": 101,
\\"amount\\": -2
}, {
\\"first\\": 80,
\\"second\\": 103,
\\"amount\\": -2
}, {
\\"first\\": 80,
\\"second\\": 111,
\\"amount\\": -2
}, {
\\"first\\": 80,
\\"second\\": 113,
\\"amount\\": -2
}, {
\\"first\\": 80,
\\"second\\": 114,
\\"amount\\": -2
}, {
\\"first\\": 80,
\\"second\\": 118,
\\"amount\\": 1
}, {
\\"first\\": 80,
\\"second\\": 119,
\\"amount\\": 1
}, {
\\"first\\": 80,
\\"second\\": 121,
\\"amount\\": 1
}, {
\\"first\\": 81,
\\"second\\": 84,
\\"amount\\": -2
}, {
\\"first\\": 81,
\\"second\\": 86,
\\"amount\\": -2
}, {
\\"first\\": 81,
\\"second\\": 87,
\\"amount\\": -2
}, {
\\"first\\": 81,
\\"second\\": 89,
\\"amount\\": -2
}, {
\\"first\\": 82,
\\"second\\": 83,
\\"amount\\": 1
}, {
\\"first\\": 82,
\\"second\\": 84,
\\"amount\\": 1
}, {
\\"first\\": 82,
\\"second\\": 85,
\\"amount\\": 1
}, {
\\"first\\": 82,
\\"second\\": 106,
\\"amount\\": 1
}, {
\\"first\\": 82,
\\"second\\": 119,
\\"amount\\": 1
}, {
\\"first\\": 82,
\\"second\\": 121,
\\"amount\\": 1
}, {
\\"first\\": 83,
\\"second\\": 89,
\\"amount\\": -2
}, {
\\"first\\": 83,
\\"second\\": 97,
\\"amount\\": 1
}, {
\\"first\\": 83,
\\"second\\": 101,
\\"amount\\": 1
}, {
\\"first\\": 83,
\\"second\\": 103,
\\"amount\\": 1
}, {
\\"first\\": 83,
\\"second\\": 111,
\\"amount\\": 1
}, {
\\"first\\": 83,
\\"second\\": 113,
\\"amount\\": 1
}, {
\\"first\\": 83,
\\"second\\": 114,
\\"amount\\": 1
}, {
\\"first\\": 83,
\\"second\\": 117,
\\"amount\\": 1
}, {
\\"first\\": 83,
\\"second\\": 122,
\\"amount\\": 1
}, {
\\"first\\": 84,
\\"second\\": 46,
\\"amount\\": -3
}, {
\\"first\\": 84,
\\"second\\": 85,
\\"amount\\": 1
}, {
\\"first\\": 84,
\\"second\\": 86,
\\"amount\\": 1
}, {
\\"first\\": 84,
\\"second\\": 87,
\\"amount\\": 1
}, {
\\"first\\": 84,
\\"second\\": 89,
\\"amount\\": 1
}, {
\\"first\\": 84,
\\"second\\": 90,
\\"amount\\": 1
}, {
\\"first\\": 84,
\\"second\\": 97,
\\"amount\\": -5
}, {
\\"first\\": 84,
\\"second\\": 99,
\\"amount\\": -5
}, {
\\"first\\": 84,
\\"second\\": 100,
\\"amount\\": -5
}, {
\\"first\\": 84,
\\"second\\": 101,
\\"amount\\": -5
}, {
\\"first\\": 84,
\\"second\\": 102,
\\"amount\\": -3
}, {
\\"first\\": 84,
\\"second\\": 103,
\\"amount\\": -5
}, {
\\"first\\": 84,
\\"second\\": 109,
\\"amount\\": -5
}, {
\\"first\\": 84,
\\"second\\": 110,
\\"amount\\": -5
}, {
\\"first\\": 84,
\\"second\\": 111,
\\"amount\\": -5
}, {
\\"first\\": 84,
\\"second\\": 112,
\\"amount\\": -5
}, {
\\"first\\": 84,
\\"second\\": 113,
\\"amount\\": -5
}, {
\\"first\\": 84,
\\"second\\": 114,
\\"amount\\": -4
}, {
\\"first\\": 84,
\\"second\\": 115,
\\"amount\\": -5
}, {
\\"first\\": 84,
\\"second\\": 116,
\\"amount\\": -2
}, {
\\"first\\": 84,
\\"second\\": 117,
\\"amount\\": -5
}, {
\\"first\\": 84,
\\"second\\": 118,
\\"amount\\": -4
}, {
\\"first\\": 84,
\\"second\\": 119,
\\"amount\\": -4
}, {
\\"first\\": 84,
\\"second\\": 120,
\\"amount\\": -4
}, {
\\"first\\": 84,
\\"second\\": 121,
\\"amount\\": -4
}, {
\\"first\\": 84,
\\"second\\": 122,
\\"amount\\": -4
}, {
\\"first\\": 85,
\\"second\\": 87,
\\"amount\\": -2
}, {
\\"first\\": 85,
\\"second\\": 88,
\\"amount\\": -2
}, {
\\"first\\": 85,
\\"second\\": 90,
\\"amount\\": -2
}, {
\\"first\\": 85,
\\"second\\": 97,
\\"amount\\": -2
}, {
\\"first\\": 85,
\\"second\\": 100,
\\"amount\\": -2
}, {
\\"first\\": 85,
\\"second\\": 101,
\\"amount\\": -2
}, {
\\"first\\": 85,
\\"second\\": 103,
\\"amount\\": -2
}, {
\\"first\\": 85,
\\"second\\": 111,
\\"amount\\": -2
}, {
\\"first\\": 85,
\\"second\\": 113,
\\"amount\\": -2
}, {
\\"first\\": 85,
\\"second\\": 114,
\\"amount\\": -2
}, {
\\"first\\": 85,
\\"second\\": 120,
\\"amount\\": -2
}, {
\\"first\\": 85,
\\"second\\": 122,
\\"amount\\": -2
}, {
\\"first\\": 86,
\\"second\\": 97,
\\"amount\\": -4
}, {
\\"first\\": 86,
\\"second\\": 99,
\\"amount\\": -4
}, {
\\"first\\": 86,
\\"second\\": 100,
\\"amount\\": -4
}, {
\\"first\\": 86,
\\"second\\": 101,
\\"amount\\": -4
}, {
\\"first\\": 86,
\\"second\\": 102,
\\"amount\\": -2
}, {
\\"first\\": 86,
\\"second\\": 103,
\\"amount\\": -4
}, {
\\"first\\": 86,
\\"second\\": 104,
\\"amount\\": -2
}, {
\\"first\\": 86,
\\"second\\": 105,
\\"amount\\": -2
}, {
\\"first\\": 86,
\\"second\\": 107,
\\"amount\\": -2
}, {
\\"first\\": 86,
\\"second\\": 109,
\\"amount\\": -3
}, {
\\"first\\": 86,
\\"second\\": 110,
\\"amount\\": -3
}, {
\\"first\\": 86,
\\"second\\": 111,
\\"amount\\": -4
}, {
\\"first\\": 86,
\\"second\\": 112,
\\"amount\\": -3
}, {
\\"first\\": 86,
\\"second\\": 113,
\\"amount\\": -4
}, {
\\"first\\": 86,
\\"second\\": 114,
\\"amount\\": -3
}, {
\\"first\\": 86,
\\"second\\": 115,
\\"amount\\": -3
}, {
\\"first\\": 86,
\\"second\\": 116,
\\"amount\\": -2
}, {
\\"first\\": 86,
\\"second\\": 117,
\\"amount\\": -3
}, {
\\"first\\": 86,
\\"second\\": 118,
\\"amount\\": -2
}, {
\\"first\\": 86,
\\"second\\": 119,
\\"amount\\": -2
}, {
\\"first\\": 86,
\\"second\\": 120,
\\"amount\\": -2
}, {
\\"first\\": 86,
\\"second\\": 121,
\\"amount\\": -2
}, {
\\"first\\": 86,
\\"second\\": 122,
\\"amount\\": -3
}, {
\\"first\\": 87,
\\"second\\": 89,
\\"amount\\": 1
}, {
\\"first\\": 87,
\\"second\\": 97,
\\"amount\\": -4
}, {
\\"first\\": 87,
\\"second\\": 99,
\\"amount\\": -4
}, {
\\"first\\": 87,
\\"second\\": 100,
\\"amount\\": -4
}, {
\\"first\\": 87,
\\"second\\": 101,
\\"amount\\": -4
}, {
\\"first\\": 87,
\\"second\\": 103,
\\"amount\\": -4
}, {
\\"first\\": 87,
\\"second\\": 104,
\\"amount\\": -2
}, {
\\"first\\": 87,
\\"second\\": 109,
\\"amount\\": -3
}, {
\\"first\\": 87,
\\"second\\": 110,
\\"amount\\": -3
}, {
\\"first\\": 87,
\\"second\\": 111,
\\"amount\\": -4
}, {
\\"first\\": 87,
\\"second\\": 112,
\\"amount\\": -3
}, {
\\"first\\": 87,
\\"second\\": 113,
\\"amount\\": -4
}, {
\\"first\\": 87,
\\"second\\": 114,
\\"amount\\": -3
}, {
\\"first\\": 87,
\\"second\\": 115,
\\"amount\\": -3
}, {
\\"first\\": 87,
\\"second\\": 116,
\\"amount\\": -2
}, {
\\"first\\": 87,
\\"second\\": 117,
\\"amount\\": -3
}, {
\\"first\\": 87,
\\"second\\": 119,
\\"amount\\": -2
}, {
\\"first\\": 87,
\\"second\\": 120,
\\"amount\\": -2
}, {
\\"first\\": 87,
\\"second\\": 121,
\\"amount\\": -2
}, {
\\"first\\": 87,
\\"second\\": 122,
\\"amount\\": -3
}, {
\\"first\\": 88,
\\"second\\": 100,
\\"amount\\": -2
}, {
\\"first\\": 88,
\\"second\\": 101,
\\"amount\\": -2
}, {
\\"first\\": 88,
\\"second\\": 103,
\\"amount\\": 1
}, {
\\"first\\": 88,
\\"second\\": 106,
\\"amount\\": 2
}, {
\\"first\\": 88,
\\"second\\": 111,
\\"amount\\": -2
}, {
\\"first\\": 88,
\\"second\\": 116,
\\"amount\\": -2
}, {
\\"first\\": 88,
\\"second\\": 118,
\\"amount\\": -2
}, {
\\"first\\": 88,
\\"second\\": 119,
\\"amount\\": -2
}, {
\\"first\\": 88,
\\"second\\": 121,
\\"amount\\": -2
}, {
\\"first\\": 89,
\\"second\\": 97,
\\"amount\\": -5
}, {
\\"first\\": 89,
\\"second\\": 99,
\\"amount\\": -5
}, {
\\"first\\": 89,
\\"second\\": 100,
\\"amount\\": -5
}, {
\\"first\\": 89,
\\"second\\": 101,
\\"amount\\": -5
}, {
\\"first\\": 89,
\\"second\\": 102,
\\"amount\\": -2
}, {
\\"first\\": 89,
\\"second\\": 103,
\\"amount\\": -5
}, {
\\"first\\": 89,
\\"second\\": 104,
\\"amount\\": -2
}, {
\\"first\\": 89,
\\"second\\": 105,
\\"amount\\": -2
}, {
\\"first\\": 89,
\\"second\\": 107,
\\"amount\\": -2
}, {
\\"first\\": 89,
\\"second\\": 109,
\\"amount\\": -4
}, {
\\"first\\": 89,
\\"second\\": 110,
\\"amount\\": -4
}, {
\\"first\\": 89,
\\"second\\": 111,
\\"amount\\": -5
}, {
\\"first\\": 89,
\\"second\\": 112,
\\"amount\\": -4
}, {
\\"first\\": 89,
\\"second\\": 113,
\\"amount\\": -5
}, {
\\"first\\": 89,
\\"second\\": 114,
\\"amount\\": -4
}, {
\\"first\\": 89,
\\"second\\": 115,
\\"amount\\": -4
}, {
\\"first\\": 89,
\\"second\\": 117,
\\"amount\\": -4
}, {
\\"first\\": 89,
\\"second\\": 118,
\\"amount\\": -3
}, {
\\"first\\": 89,
\\"second\\": 119,
\\"amount\\": -3
}, {
\\"first\\": 89,
\\"second\\": 120,
\\"amount\\": -3
}, {
\\"first\\": 89,
\\"second\\": 121,
\\"amount\\": -2
}, {
\\"first\\": 89,
\\"second\\": 122,
\\"amount\\": -4
}, {
\\"first\\": 90,
\\"second\\": 97,
\\"amount\\": 1
}, {
\\"first\\": 90,
\\"second\\": 103,
\\"amount\\": 1
}, {
\\"first\\": 97,
\\"second\\": 106,
\\"amount\\": 1
}, {
\\"first\\": 97,
\\"second\\": 116,
\\"amount\\": -2
}, {
\\"first\\": 97,
\\"second\\": 117,
\\"amount\\": -2
}, {
\\"first\\": 97,
\\"second\\": 118,
\\"amount\\": -2
}, {
\\"first\\": 97,
\\"second\\": 119,
\\"amount\\": -2
}, {
\\"first\\": 97,
\\"second\\": 121,
\\"amount\\": -2
}, {
\\"first\\": 98,
\\"second\\": 116,
\\"amount\\": -2
}, {
\\"first\\": 98,
\\"second\\": 118,
\\"amount\\": -2
}, {
\\"first\\": 98,
\\"second\\": 119,
\\"amount\\": -2
}, {
\\"first\\": 98,
\\"second\\": 121,
\\"amount\\": -2
}, {
\\"first\\": 98,
\\"second\\": 122,
\\"amount\\": -2
}, {
\\"first\\": 99,
\\"second\\": 68,
\\"amount\\": 2
}, {
\\"first\\": 99,
\\"second\\": 101,
\\"amount\\": 1
}, {
\\"first\\": 99,
\\"second\\": 113,
\\"amount\\": 1
}, {
\\"first\\": 100,
\\"second\\": 106,
\\"amount\\": 1
}, {
\\"first\\": 100,
\\"second\\": 119,
\\"amount\\": -2
}, {
\\"first\\": 101,
\\"second\\": 116,
\\"amount\\": -2
}, {
\\"first\\": 101,
\\"second\\": 119,
\\"amount\\": -2
}, {
\\"first\\": 101,
\\"second\\": 121,
\\"amount\\": -2
}, {
\\"first\\": 102,
\\"second\\": 84,
\\"amount\\": 1
}, {
\\"first\\": 102,
\\"second\\": 86,
\\"amount\\": 1
}, {
\\"first\\": 102,
\\"second\\": 87,
\\"amount\\": 1
}, {
\\"first\\": 102,
\\"second\\": 89,
\\"amount\\": 1
}, {
\\"first\\": 102,
\\"second\\": 103,
\\"amount\\": -2
}, {
\\"first\\": 102,
\\"second\\": 110,
\\"amount\\": -2
}, {
\\"first\\": 102,
\\"second\\": 111,
\\"amount\\": -2
}, {
\\"first\\": 102,
\\"second\\": 115,
\\"amount\\": -2
}, {
\\"first\\": 102,
\\"second\\": 117,
\\"amount\\": -2
}, {
\\"first\\": 102,
\\"second\\": 120,
\\"amount\\": -2
}, {
\\"first\\": 103,
\\"second\\": 106,
\\"amount\\": 4
}, {
\\"first\\": 103,
\\"second\\": 120,
\\"amount\\": 1
}, {
\\"first\\": 104,
\\"second\\": 118,
\\"amount\\": -2
}, {
\\"first\\": 104,
\\"second\\": 119,
\\"amount\\": -2
}, {
\\"first\\": 104,
\\"second\\": 121,
\\"amount\\": -2
}, {
\\"first\\": 105,
\\"second\\": 74,
\\"amount\\": 1
}, {
\\"first\\": 105,
\\"second\\": 120,
\\"amount\\": 1
}, {
\\"first\\": 107,
\\"second\\": 111,
\\"amount\\": -2
}, {
\\"first\\": 107,
\\"second\\": 118,
\\"amount\\": 1
}, {
\\"first\\": 107,
\\"second\\": 121,
\\"amount\\": 1
}, {
\\"first\\": 109,
\\"second\\": 116,
\\"amount\\": -2
}, {
\\"first\\": 109,
\\"second\\": 117,
\\"amount\\": -2
}, {
\\"first\\": 109,
\\"second\\": 118,
\\"amount\\": -2
}, {
\\"first\\": 109,
\\"second\\": 119,
\\"amount\\": -2
}, {
\\"first\\": 109,
\\"second\\": 121,
\\"amount\\": -2
}, {
\\"first\\": 110,
\\"second\\": 116,
\\"amount\\": -2
}, {
\\"first\\": 110,
\\"second\\": 117,
\\"amount\\": -2
}, {
\\"first\\": 110,
\\"second\\": 118,
\\"amount\\": -2
}, {
\\"first\\": 110,
\\"second\\": 119,
\\"amount\\": -2
}, {
\\"first\\": 110,
\\"second\\": 121,
\\"amount\\": -2
}, {
\\"first\\": 111,
\\"second\\": 119,
\\"amount\\": -2
}, {
\\"first\\": 111,
\\"second\\": 122,
\\"amount\\": -2
}, {
\\"first\\": 114,
\\"second\\": 116,
\\"amount\\": 1
}, {
\\"first\\": 114,
\\"second\\": 118,
\\"amount\\": 1
}, {
\\"first\\": 114,
\\"second\\": 119,
\\"amount\\": 1
}, {
\\"first\\": 114,
\\"second\\": 120,
\\"amount\\": 1
}, {
\\"first\\": 114,
\\"second\\": 121,
\\"amount\\": 1
}, {
\\"first\\": 118,
\\"second\\": 119,
\\"amount\\": 1
}, {
\\"first\\": 118,
\\"second\\": 120,
\\"amount\\": 1
}, {
\\"first\\": 118,
\\"second\\": 121,
\\"amount\\": 1
}, {
\\"first\\": 119,
\\"second\\": 120,
\\"amount\\": 1
}, {
\\"first\\": 119,
\\"second\\": 122,
\\"amount\\": -2
}, {
\\"first\\": 120,
\\"second\\": 121,
\\"amount\\": 1
}],
\\"info\\": {
\\"face\\": \\"Nexa Light\\",
\\"size\\": 32,
\\"bold\\": 0,
\\"italic\\": 0,
\\"charset\\": \\"\\",
\\"unicode\\": 1,
\\"stretchH\\": 100,
\\"smooth\\": 1,
\\"aa\\": 2,
\\"padding\\": [0, 0, 0, 0],
\\"spacing\\": [0, 0]
},
\\"common\\": {
\\"lineHeight\\": 32,
\\"base\\": 24,
\\"scaleW\\": 512,
\\"scaleH\\": 512,
\\"pages\\": 2,
\\"packed\\": 0,
\\"alphaChnl\\": 0,
\\"redChnl\\": 0,
\\"greenChnl\\": 0,
\\"blueChnl\\": 0
}
};"
`);
});
|
import logging
import os
import base64
import pkg_resources
from pyramid.settings import asbool
from pyramid.config import Configurator
from pyramid.httpexceptions import (
HTTPNotFound,
HTTPNoContent,
HTTPCreated,
HTTPBadRequest,
HTTPGone,
HTTPUnprocessableEntity,
)
from cornice import Service
from cornice.validators import colander_body_validator
from cornice.service import get_services
import colander
from slugify import slugify
from cornice_swagger import CorniceSwagger
import sentry_sdk
from sentry_sdk.integrations.pyramid import PyramidIntegration
from . import services
from . import adapters
from . import exceptions
LOGGER = logging.getLogger(__name__)
VERSION = pkg_resources.get_distribution("scielo-kernel").version
swagger = Service(
name="Kernel API", path="/__api__", description="Kernel API documentation"
)
documents = Service(
name="documents",
path="/documents/{document_id}",
description="Get document at its latest version.",
)
manifest = Service(
name="manifest",
path="/documents/{document_id}/manifest",
description="Get the document's manifest.",
)
assets_list = Service(
name="assets_list",
path="/documents/{document_id}/assets",
description="Get the document's assets.",
)
assets = Service(
name="assets",
path="/documents/{document_id}/assets/{asset_slug}",
description="Set the URL for an document's asset.",
)
diff = Service(
name="diff",
path="/documents/{document_id}/diff",
description="Compare two versions of the same document.",
)
front = Service(
name="front",
path="/documents/{document_id}/front",
description="Front-matter of the document in a normalized schema.",
)
bundles = Service(
name="bundles",
path="/bundles/{bundle_id}",
description="Get documents bundle data.",
)
bundles_documents = Service(
name="bundles_documents",
path="/bundles/{bundle_id}/documents",
description="Update documents of documents bundle.",
)
changes = Service(
name="changes", path="/changes", description="Get changes from all entities"
)
change_details = Service(
name="change_details", path="/changes/{change_id}", description="Get one change."
)
journals = Service(
name="journals",
path="/journals/{journal_id}",
description="Register and retrieve journals' endpoint",
)
journal_issues = Service(
name="journal_issues",
path="/journals/{journal_id}/issues",
description="Issue addition and insertion to journal.",
)
journals_aop = Service(
name="journals_aop",
path="/journals/{journal_id}/aop",
description="Manipulate ahead of print in journal",
)
renditions = Service(
name="renditions",
path="/documents/{document_id}/renditions",
description="All renditions related to the document",
)
class ResponseSchema(colander.MappingSchema):
body = colander.SchemaNode(colander.String(), missing=colander.drop)
class Asset(colander.MappingSchema):
asset_id = colander.SchemaNode(colander.String())
asset_url = colander.SchemaNode(colander.String(), validator=colander.url)
class Assets(colander.SequenceSchema):
asset = Asset()
class RegisterDocumentSchema(colander.MappingSchema):
"""Representa o schema de dados para registro de documentos.
"""
data = colander.SchemaNode(colander.String(), validator=colander.url)
assets = Assets()
class QueryDiffDocumentSchema(colander.MappingSchema):
"""Representa os parâmetros de querystring do schema DiffDocument.
"""
from_when = colander.SchemaNode(colander.String(), missing=colander.drop)
to_when = colander.SchemaNode(colander.String(), missing=colander.drop)
class DiffDocumentSchema(colander.MappingSchema):
"""Representa a diferença entre estados do documento
"""
data = colander.SchemaNode(colander.String(), missing=colander.drop)
querystring = QueryDiffDocumentSchema()
class AssetSchema(colander.MappingSchema):
"""Representa o schema de dados para registro de ativos do documento.
"""
asset_url = colander.SchemaNode(colander.String(), validator=colander.url)
class JournalSchema(colander.MappingSchema):
"""Representa o schema de dados para registro de periódicos.
"""
title = colander.SchemaNode(colander.String(), missing=colander.drop)
@colander.instantiate(missing=colander.drop)
class mission(colander.SequenceSchema):
@colander.instantiate()
class mission(colander.MappingSchema):
language = colander.SchemaNode(colander.String())
value = colander.SchemaNode(colander.String())
title_iso = colander.SchemaNode(colander.String(), missing=colander.drop)
short_title = colander.SchemaNode(colander.String(), missing=colander.drop)
acronym = colander.SchemaNode(colander.String(), missing=colander.drop)
scielo_issn = colander.SchemaNode(colander.String(), missing=colander.drop)
print_issn = colander.SchemaNode(colander.String(), missing=colander.drop)
electronic_issn = colander.SchemaNode(colander.String(), missing=colander.drop)
@colander.instantiate(missing=colander.drop)
class status_history(colander.SequenceSchema):
status = colander.SchemaNode(
colander.Mapping(unknown="preserve"), missing=colander.drop
)
@colander.instantiate(missing=colander.drop)
class subject_areas(colander.SequenceSchema):
name = colander.SchemaNode(colander.String())
@colander.instantiate(missing=colander.drop)
class sponsors(colander.SequenceSchema):
sponsor = colander.SchemaNode(colander.Mapping(unknown="preserve"))
metrics = colander.SchemaNode(
colander.Mapping(unknown="preserve"), missing=colander.drop
)
@colander.instantiate(missing=colander.drop)
class subject_categories(colander.SequenceSchema):
name = colander.SchemaNode(colander.String())
@colander.instantiate(missing=colander.drop)
class institution_responsible_for(colander.SequenceSchema):
@colander.instantiate()
class institution(colander.MappingSchema):
name = colander.SchemaNode(colander.String())
city = colander.SchemaNode(colander.String())
state = colander.SchemaNode(colander.String())
country_code = colander.SchemaNode(colander.String())
country = colander.SchemaNode(colander.String())
online_submission_url = colander.SchemaNode(
colander.String(), validator=colander.url, missing=colander.drop
)
next_journal = colander.SchemaNode(
colander.Mapping(unknown="preserve"), missing=colander.drop
)
previous_journal = colander.SchemaNode(
colander.Mapping(unknown="preserve"), missing=colander.drop
)
contact = colander.SchemaNode(
colander.Mapping(unknown="preserve"), missing=colander.drop
)
class JournalAOPSchema(colander.MappingSchema):
"""Representa o schema de dados para a atualização de AOP em periódico
"""
aop = colander.SchemaNode(colander.String())
class DocumentsBundleSchema(colander.MappingSchema):
"""Representa o schema de dados para registro de Documents Bundle."""
def combined_validator(node, value):
if value.get("month") and value.get("range"):
raise colander.Invalid(
node, "The month and range fields are mutually exclusive."
)
@colander.instantiate(missing=colander.drop, validator=combined_validator)
class publication_months(colander.MappingSchema):
month = colander.SchemaNode(colander.Int(), missing=colander.drop)
@colander.instantiate(missing=colander.drop)
class range(colander.TupleSchema):
start_month = colander.SchemaNode(colander.Int(), missing=colander.drop)
end_month = colander.SchemaNode(colander.Int(), missing=colander.drop)
publication_year = colander.SchemaNode(colander.Int(), missing=colander.drop)
supplement = colander.SchemaNode(colander.String(), missing=colander.drop)
volume = colander.SchemaNode(colander.String(), missing=colander.drop)
number = colander.SchemaNode(colander.String(), missing=colander.drop)
pid = colander.SchemaNode(colander.String(), missing=colander.drop)
@colander.instantiate(missing=colander.drop)
class titles(colander.SequenceSchema):
@colander.instantiate()
class title(colander.MappingSchema):
language = colander.SchemaNode(
colander.String(), validator=colander.Length(2, 2)
)
value = colander.SchemaNode(colander.String(), validator=colander.Length(1))
class DocumentsBundleDocumentsReplaceSchema(colander.SequenceSchema):
"""Representa o schema de dados para registro o relacionamento de documento no
Documents Bundle."""
@colander.instantiate(missing=colander.drop)
class document(colander.MappingSchema):
id = colander.SchemaNode(colander.String())
order = colander.SchemaNode(colander.String())
class QueryChangeSchema(colander.MappingSchema):
"""Representa os parâmetros de querystring do schema change.
"""
limit = colander.SchemaNode(colander.String(), missing=colander.drop)
since = colander.SchemaNode(colander.String(), missing=colander.drop)
class ChangeSchema(colander.MappingSchema):
"""Representa o schema de dados para registro de mudança.
"""
id = colander.SchemaNode(colander.String())
timestamp = colander.SchemaNode(colander.String())
deleted = colander.SchemaNode(colander.Boolean())
querystring = QueryChangeSchema()
class ChangeDetailsSchema(colander.MappingSchema):
"""Representa o schema de dados para os detalhes de um registro de mudança.
"""
data = colander.SchemaNode(colander.String(), missing=colander.drop)
class ManifestSchema(colander.MappingSchema):
"""Representa o schema de dados do registro de Manifest
"""
data = colander.SchemaNode(colander.String(), missing=colander.drop)
class QueryDocumentSchema(colander.MappingSchema):
"""Representa os parâmetros de querystring do schema document.
"""
when = colander.SchemaNode(colander.String(), missing=colander.drop)
class DocumentSchema(colander.MappingSchema):
"""Representa o schema de dados do documento.
"""
data = colander.SchemaNode(colander.String(), missing=colander.drop)
assets = Assets()
querystring = QueryDocumentSchema()
class DeleteDocumentSchema(colander.MappingSchema):
"""Representa o schema de dados front do documento.
"""
data = colander.SchemaNode(colander.String(), missing=colander.drop)
class FrontDocumentSchema(colander.MappingSchema):
"""Representa o schema de dados front do documento.
"""
data = colander.SchemaNode(colander.String(), missing=colander.drop)
class JournalIssueItem(colander.MappingSchema):
"""Schema que representa uma Issue como item a ser relacionado
com um Journal"""
id = colander.SchemaNode(colander.String())
order = colander.SchemaNode(colander.String(), missing=colander.drop)
year = colander.SchemaNode(colander.String())
volume = colander.SchemaNode(colander.String(), missing=colander.drop)
number = colander.SchemaNode(colander.String(), missing=colander.drop)
supplement = colander.SchemaNode(colander.String(), missing=colander.drop)
class JournalIssuesSchema(colander.MappingSchema):
"""Representa o schema de dados de atualização de fascículos de periódico.
"""
issue = JournalIssueItem()
index = colander.SchemaNode(colander.Int(), missing=colander.drop)
class JournalIssuesReplaceSchema(colander.SequenceSchema):
"""Representa o schema de dados utilizado durante a atualização
da lista completa de fascículos de um periódico"""
issue = JournalIssueItem()
class DeleteJournalIssuesSchema(colander.MappingSchema):
"""Representa o schema de dados de deleção de fascículos de periódico.
"""
issue = colander.SchemaNode(colander.String())
class DocumentRenditionsSchema(colander.MappingSchema):
"""Representa o schema de dados da manifestação do documento.
"""
data = colander.SchemaNode(colander.String(), missing=colander.drop)
querystring = QueryDocumentSchema()
class RegisterDocumentRenditionSchema(colander.MappingSchema):
"""Representa o schema de dados para registro de manifestações do documento.
"""
filename = colander.SchemaNode(colander.String())
data_url = colander.SchemaNode(colander.String(), validator=colander.url)
mimetype = colander.SchemaNode(colander.String())
lang = colander.SchemaNode(colander.String())
size_bytes = colander.SchemaNode(colander.Int())
@documents.get(
schema=DocumentSchema(),
response_schemas={
"200": DocumentSchema(description="Obtém o documento"),
"404": DocumentSchema(description="Documento não encontrado"),
},
accept="text/xml",
renderer="xml",
)
def fetch_document_data(request):
"""Obtém o conteúdo do documento representado em XML com todos os
apontamentos para seus ativos digitais contextualizados de acordo com a
versão do documento. Produzirá uma resposta com o código HTTP 404 caso o
documento solicitado não seja conhecido pela aplicação.
"""
when = request.GET.get("when", None)
if when:
version = {"version_at": when}
else:
version = {}
try:
return request.services["fetch_document_data"](
id=request.matchdict["document_id"], **version
)
except (exceptions.DoesNotExist, ValueError) as exc:
raise HTTPNotFound(exc)
except exceptions.DeletedVersion as exc:
raise HTTPGone(exc)
@documents.put(
schema=RegisterDocumentSchema(),
validators=(colander_body_validator,),
response_schemas={
"201": RegisterDocumentSchema(description="Documento criado com sucesso"),
"204": RegisterDocumentSchema(description="Documento atualizado com sucesso"),
},
)
def put_document(request):
"""Adiciona ou atualiza registro de documento. A atualização do documento é
idempotente.
A semântica desta view-function está definida conforme a especificação:
https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.6
Em resumo, ``PUT /documents/:doc_id`` com o payload válido de acordo com o
schema documentado, e para um ``:doc_id`` inédito, resultará no registro do
documento e produzirá uma resposta com o código HTTP 201 Created. Qualquer
requisição subsequente para o mesmo recurso produzirá respostas com o código
HTTP 204 No Content.
"""
data_url = request.validated["data"]
assets = {
asset["asset_id"]: asset["asset_url"]
for asset in request.validated.get("assets", [])
}
try:
request.services["register_document"](
id=request.matchdict["document_id"], data_url=data_url, assets=assets
)
except exceptions.AlreadyExists:
try:
request.services["register_document_version"](
id=request.matchdict["document_id"], data_url=data_url, assets=assets
)
except exceptions.VersionAlreadySet as exc:
LOGGER.info(
'skipping request to add version to "%s": %s',
request.matchdict["document_id"],
exc,
)
return HTTPNoContent("document updated successfully")
else:
return HTTPCreated("document created successfully")
@documents.delete(
schema=DeleteDocumentSchema(),
response_schemas={
"204": DeleteDocumentSchema(description="Documento excluído com sucesso"),
"404": DeleteDocumentSchema(description="Documento não encontrado"),
},
)
def delete_document(request):
"""Adiciona uma nova versão ao documento indicando que o mesmo foi excluído.
"""
try:
request.services["delete_document"](id=request.matchdict["document_id"])
except exceptions.DoesNotExist as exc:
raise HTTPNotFound(exc)
except exceptions.VersionAlreadySet as exc:
LOGGER.info(
'skipping request to add deleted version to "%s": %s',
request.matchdict["document_id"],
exc,
)
raise HTTPNoContent("document deleted successfully")
@manifest.get(
schema=ManifestSchema(),
response_schemas={
"200": ManifestSchema(description="Obtém o manifesto do documento"),
"404": ManifestSchema(description="Manifesto não encontrado"),
},
accept="application/json",
renderer="json",
)
def get_manifest(request):
"""Obtém o manifesto do documento. Produzirá uma resposta com o código
HTTP 404 caso o documento não seja conhecido pela aplicação.
"""
try:
return request.services["fetch_document_manifest"](
id=request.matchdict["document_id"]
)
except exceptions.DoesNotExist as exc:
raise HTTPNotFound(exc)
def slugify_assets_ids(assets, slug_fn=slugify):
return [
{"slug": slug_fn(asset_id), "id": asset_id, "url": asset_url}
for asset_id, asset_url in assets.items()
]
@assets_list.get(
accept="application/json",
renderer="json",
response_schemas={
"200": Assets(description="Lista de ativos"),
"404": Assets(description="Documento não encontrado"),
},
)
def get_assets_list(request):
"""Obtém relação dos ativos associados ao documento em determinada
versão. Produzirá uma resposta com o código HTTP 404 caso o documento não
seja conhecido pela aplicação.
"""
try:
assets = request.services["fetch_assets_list"](
id=request.matchdict["document_id"]
)
except exceptions.DoesNotExist as exc:
raise HTTPNotFound(exc)
assets["assets"] = slugify_assets_ids(assets["assets"])
return assets
@assets.put(
schema=AssetSchema(),
validators=(colander_body_validator,),
response_schemas={
"204": AssetSchema(
description="Adicionado ou atualizado o ativo digital com sucesso"
),
"404": AssetSchema(description="Ativo não encontrado"),
},
)
def put_asset(request):
"""Adiciona ou atualiza registro de ativo do documento. A atualização do
ativo é idempotente.
A semântica desta view-function está definida conforme a especificação:
https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.6
"""
assets_list = get_assets_list(request)
assets_map = {asset["slug"]: asset["id"] for asset in assets_list["assets"]}
asset_slug = request.matchdict["asset_slug"]
try:
asset_id = assets_map[asset_slug]
except KeyError:
raise HTTPNotFound(
'cannot fetch asset with slug "%s": asset does not exist' % asset_slug
)
asset_url = request.validated["asset_url"]
try:
request.services["register_asset_version"](
id=request.matchdict["document_id"], asset_id=asset_id, asset_url=asset_url
)
except exceptions.VersionAlreadySet as exc:
LOGGER.info(
'skipping request to add version to "%s/assets/%s": %s',
request.matchdict["document_id"],
request.matchdict["asset_slug"],
exc,
)
return HTTPNoContent("asset updated successfully")
@diff.get(
schema=DiffDocumentSchema(),
response_schemas={
"200": DiffDocumentSchema(
description="Retorna a diferança do documento, recebe os argumentos `from_when` e `to_when`"
),
"400": DiffDocumentSchema(
description="Erro ao tentar processar a requisição, verifique o valor do parâmetro `from_when`"
),
"404": DiffDocumentSchema(description="Documento não encontrado"),
},
renderer="text",
)
def diff_document_versions(request):
"""Compara duas versões do documento. Se o argumento `to_when` não for
fornecido, será assumido como alvo a versão mais recente.
"""
from_when = request.GET.get("from_when", None)
if from_when is None:
raise HTTPBadRequest("cannot fetch diff: missing attribute from_when")
try:
return request.services["diff_document_versions"](
id=request.matchdict["document_id"],
from_version_at=from_when,
to_version_at=request.GET.get("to_when", None),
)
except (exceptions.DoesNotExist, ValueError) as exc:
raise HTTPNotFound(exc)
except exceptions.DeletedVersion as exc:
raise HTTPGone(exc)
@front.get(
schema=FrontDocumentSchema(),
response_schemas={
"200": FrontDocumentSchema(
description="Retorna o Front do documento (todo os dados do documento exceto o body)"
),
"404": FrontDocumentSchema(description="Front do documento não encontrado"),
},
renderer="json",
)
def fetch_document_front(request):
data = fetch_document_data(request)
return request.services["sanitize_document_front"](data)
@bundles.get(
response_schemas={
"200": DocumentsBundleSchema(
description="Retorna os dados do bundle solicitado"
),
"404": DocumentsBundleSchema(description="Recurso não encontrado"),
"400": DocumentsBundleSchema(
description="Erro ao processar a requisição. Verifique o parâmetro `bundle_id`"
),
},
renderer="json",
)
def fetch_documents_bundle(request):
try:
return request.services["fetch_documents_bundle"](
request.matchdict["bundle_id"]
)
except KeyError:
return HTTPBadRequest("bundle id is mandatory")
except exceptions.DoesNotExist as exc:
return HTTPNotFound(str(exc))
@bundles.put(
schema=DocumentsBundleSchema(),
response_schemas={
"201": DocumentsBundleSchema(
description="Documents Bundle criado com sucesso."
),
"204": DocumentsBundleSchema(
description="Documents Bundle atualizado com sucesso."
),
},
validators=(colander_body_validator,),
accept="application/json",
renderer="json",
)
def put_documents_bundle(request):
try:
request.services["create_documents_bundle"](
request.matchdict["bundle_id"], metadata=request.validated
)
except exceptions.AlreadyExists:
return HTTPNoContent("bundle updated successfully")
else:
return HTTPCreated("bundle created successfully")
@bundles.patch(
schema=DocumentsBundleSchema(),
response_schemas={
"204": DocumentsBundleSchema(
description="Documents Bundle atualizado com sucesso."
),
"404": DocumentsBundleSchema(description="Documents Bundle não encontrado."),
},
validators=(colander_body_validator,),
accept="application/json",
renderer="json",
)
def patch_documents_bundle(request):
try:
request.services["update_documents_bundle_metadata"](
request.matchdict["bundle_id"], metadata=request.validated
)
except exceptions.DoesNotExist as exc:
return HTTPNotFound(str(exc))
else:
return HTTPNoContent("bundle updated successfully")
@bundles_documents.put(
schema=DocumentsBundleDocumentsReplaceSchema(),
validators=(colander_body_validator,),
response_schemas={
"204": DocumentsBundleDocumentsReplaceSchema(
description="Lista de documentos atualizada com sucesso"
),
"422": DocumentsBundleDocumentsReplaceSchema(
description="Erro ao atualizar a lista de documetos. Payload com conteúdo inválido."
),
"404": DocumentsBundleDocumentsReplaceSchema(
description="Fascículo não encontrado"
),
},
accept="application/json",
renderer="json",
)
def put_bundles_documents(request):
try:
request.services["update_documents_in_documents_bundle"](
id=request.matchdict["bundle_id"], docs=request.validated
)
except exceptions.DoesNotExist as exc:
return HTTPNotFound(str(exc))
except exceptions.AlreadyExists as exc:
return HTTPUnprocessableEntity(
explanation="cannot process the request with duplicated items."
)
return HTTPNoContent("documents list updated successfully.")
entity_route_map = {
"Document": {"route": "documents", "marker": "document_id"},
"DocumentRendition": {"route": "renditions", "marker": "document_id"},
"Journal": {"route": "journals", "marker": "journal_id"},
"DocumentsBundle": {"route": "bundles", "marker": "bundle_id"},
}
def _format_change(c, request):
"""Transforma um registro de mudança em algo mais *palatável* para ser
retornado por uma interface restful.
"""
entity = entity_route_map[c["entity"]]
result = {
"id": request.route_path(entity["route"], **{entity["marker"]: c["id"]}),
"timestamp": c["timestamp"],
}
if "_id" in c:
result["change_id"] = str(c["_id"])
if "deleted" in c:
result["deleted"] = c["deleted"]
if "content_gz" in c:
result["content_gz_b64"] = base64.b64encode(c["content_gz"]).decode("ascii")
if "content_type" in c:
result["content_type"] = c["content_type"]
return result
@changes.get(
schema=ChangeSchema(),
response_schemas={
"200": AssetSchema(description="Retorna a lista de mudanças"),
"400": AssetSchema(
description="Erro ao processar a requisição, verifique o parâmetro `limit`"
),
},
accept="application/json",
renderer="json",
)
def fetch_changes(request):
"""Obtém a lista de mudanças, recebe os argumentos `since` e `limit`.
"""
since = request.GET.get("since", "")
try:
limit = int(request.GET.get("limit", 500))
except ValueError:
raise HTTPBadRequest("limit must be integer")
return {
"since": since,
"limit": limit,
"results": [
_format_change(c, request)
for c in request.services["fetch_changes"](since=since, limit=limit)
],
}
@change_details.get(
schema=ChangeDetailsSchema(),
response_schemas={
"200": ChangeDetailsSchema(description="Retorna o registro da mudança"),
"404": ChangeDetailsSchema(description="Registro não encontrado"),
},
accept="application/json",
renderer="json",
)
def fetch_change(request):
"""Obtém um único registro de mudança.
Este endpoint é capaz de retornar o `snapshot` dos dados no momento
imediatamente após sua mudança.
"""
try:
return _format_change(
request.services["fetch_change"](id=request.matchdict["change_id"]), request
)
except exceptions.DoesNotExist as exc:
return HTTPNotFound(exc)
@journals.put(
schema=JournalSchema(),
validators=(colander_body_validator,),
response_schemas={
"201": JournalSchema(description="Periódico criado com sucesso"),
"204": JournalSchema(
description="Não foi realizada alteração para o periódico informado"
),
"400": JournalSchema(
description="Erro ao processar a requisição, por favor verifique os dados informados"
),
},
accept="application/json",
renderer="json",
)
def put_journal(request):
"""Registra um periódico a partir de dados submetidos e
validados por meio do JournalSchema."""
try:
request.services["create_journal"](
id=request.matchdict["journal_id"], metadata=request.validated
)
except exceptions.AlreadyExists:
return HTTPNoContent("journal already exists")
except (TypeError, ValueError) as err:
return HTTPBadRequest(str(err))
else:
return HTTPCreated("journal created successfully")
@journals.get(
schema=JournalSchema(),
response_schemas={
"200": JournalSchema(description="Retorna um periódico"),
"404": JournalSchema(description="Periódico não encontrado"),
},
accept="application/json",
renderer="json",
)
def get_journal(request):
"""Recupera um periódico por meio de seu identificador
"""
try:
return request.services["fetch_journal"](id=request.matchdict["journal_id"])
except exceptions.DoesNotExist:
return HTTPNotFound(
'cannot fetch journal with id "%s"' % request.matchdict["journal_id"]
)
@journals.patch(
schema=JournalSchema,
validators=(colander_body_validator,),
response_schemas={
"204": JournalSchema(description="Periódico atualizado com sucesso"),
"400": JournalSchema(
description="Erro ao tentar processar a requisição, verifique os dados submetidos"
),
"404": JournalSchema(description="Periódico não encontrado"),
},
accept="application/json",
renderer="json",
)
def patch_journal(request):
"""Atualiza um periódico a partir dos dados fornecidos e
validados por meio do JournalSchema.
"""
try:
request.services["update_journal_metadata"](
id=request.matchdict["journal_id"], metadata=request.validated
)
except (TypeError, ValueError) as exc:
return HTTPBadRequest(str(exc))
except exceptions.DoesNotExist:
return HTTPNotFound(
'cannot fetch journal with id "%s"' % request.matchdict["journal_id"]
)
return HTTPNoContent("journal updated successfully")
@journal_issues.patch(
schema=JournalIssuesSchema(),
validators=(colander_body_validator,),
response_schemas={
"204": JournalIssuesSchema(
description="Fascículo adicionado ou inserido em periódico com sucesso"
),
"404": JournalIssuesSchema(description="Periódico não encontrado"),
},
accept="application/json",
renderer="json",
)
def patch_journal_issues(request):
try:
if request.validated.get("index") is not None:
request.services["insert_issue_to_journal"](
id=request.matchdict["journal_id"],
index=request.validated["index"],
issue=request.validated["issue"],
)
else:
request.services["add_issue_to_journal"](
id=request.matchdict["journal_id"], issue=request.validated["issue"]
)
except exceptions.DoesNotExist as exc:
return HTTPNotFound(str(exc))
except exceptions.AlreadyExists as exc:
return HTTPNoContent("issue added to journal successfully.")
else:
return HTTPNoContent("issue added to journal successfully.")
@journal_issues.put(
schema=JournalIssuesReplaceSchema(),
validators=(colander_body_validator,),
response_schemas={
"204": JournalIssuesReplaceSchema(
description="Lista de fascículos atualizada com sucesso"
),
"422": JournalIssuesReplaceSchema(
description="Erro ao atualizar a lista de issues. Payload com conteúdo inválido."
),
"404": JournalIssuesReplaceSchema(description="Periódico não encontrado"),
},
accept="application/json",
renderer="json",
)
def put_journal_issues(request):
try:
request.services["update_issues_in_journal"](
id=request.matchdict["journal_id"], issues=request.validated
)
except exceptions.DoesNotExist as exc:
return HTTPNotFound(str(exc))
except exceptions.AlreadyExists as exc:
return HTTPUnprocessableEntity(
explanation="cannot process the request with duplicated items."
)
return HTTPNoContent("issues list updated successfully.")
@journals_aop.patch(
schema=JournalAOPSchema,
validators=(colander_body_validator,),
response_schemas={
"204": JournalAOPSchema(
description="Ahead of Print adicionado ao periódico com sucesso ao periódico"
),
"404": JournalAOPSchema(description="Periódico não encontrado"),
},
accept="application/json",
renderer="json",
)
def patch_journal_aop(request):
try:
request.services["set_ahead_of_print_bundle_to_journal"](
id=request.matchdict["journal_id"], aop=request.validated["aop"]
)
except exceptions.DoesNotExist:
return HTTPNotFound(
'cannot find journal with id "%s"' % request.matchdict["journal_id"]
)
return HTTPNoContent("aop added to journal successfully")
@journals_aop.delete(
validators=(colander_body_validator,),
response_schemas={
"204": ResponseSchema(
description="Ahead of Print removido do periódico com sucesso"
),
"404": ResponseSchema(description="Periódico não encontrado"),
},
accept="application/json",
renderer="json",
)
def delete_journal_aop(request):
try:
request.services["remove_ahead_of_print_bundle_from_journal"](
id=request.matchdict["journal_id"]
)
except exceptions.DoesNotExist as exc:
return HTTPNotFound(str(exc))
return HTTPNoContent()
@journal_issues.delete(
schema=DeleteJournalIssuesSchema(),
validators=(colander_body_validator,),
response_schemas={
"204": DeleteJournalIssuesSchema(
description="Fascículo removido em periódico com sucesso"
),
"404": DeleteJournalIssuesSchema(
description="Periódico ou fascículo não encontrado"
),
},
accept="application/json",
renderer="json",
)
def delete_journal_issues(request):
try:
request.services["remove_issue_from_journal"](
id=request.matchdict["journal_id"], issue=request.validated["issue"]
)
except exceptions.DoesNotExist as exc:
return HTTPNotFound(str(exc))
else:
return HTTPNoContent("issue removed from journal successfully.")
@renditions.get(
schema=DocumentRenditionsSchema(),
response_schemas={
"200": DocumentRenditionsSchema(
description="Obtém a lista das manifestações do documento"
),
"404": DocumentRenditionsSchema(description="Documento não encontrado"),
},
accept="application/json",
renderer="json",
)
def fetch_document_renditions(request):
"""Obtém uma lista das manifestações associadas à versão do documento.
Produzirá uma resposta com o código HTTP 404 caso o documento solicitado
não exista.
"""
when = request.GET.get("when", None)
if when:
version = {"version_at": when}
else:
version = {}
try:
return request.services["fetch_document_renditions"](
id=request.matchdict["document_id"], **version
)
except (exceptions.DoesNotExist, ValueError) as exc:
raise HTTPNotFound(exc)
@renditions.patch(
schema=RegisterDocumentRenditionSchema(),
validators=(colander_body_validator,),
response_schemas={
"204": RegisterDocumentRenditionSchema(
description="Manifestação registrada com sucesso"
),
"404": RegisterDocumentRenditionSchema(description="Documento não encontrado"),
},
accept="application/json",
renderer="json",
)
def register_rendition_version(request):
try:
request.services["register_rendition_version"](
request.matchdict["document_id"],
request.validated["filename"],
request.validated["data_url"],
request.validated["mimetype"],
request.validated["lang"],
request.validated["size_bytes"],
)
except exceptions.DoesNotExist as exc:
return HTTPNotFound(exc)
except exceptions.VersionAlreadySet as exc:
LOGGER.info(
'skipping request to add new version of rendition "%s" to "%s": %s',
request.validated["filename"],
request.matchdict["document_id"],
exc,
)
return HTTPNoContent("journal updated successfully")
@swagger.get()
def openAPI_spec(request):
doc = CorniceSwagger(get_services())
doc.summary_docstrings = True
return doc.generate("Kernel", "0.1")
class XMLRenderer:
"""Renderizador para dados do tipo ``text/xml``.
Espera que o retorno da view-function seja uma string de bytes pronta para
ser transferida para o cliente. Este renderer apenas define o content-type
da resposta HTTP.
"""
def __init__(self, info):
pass
def __call__(self, value, system):
request = system.get("request")
if request is not None:
request.response.content_type = "text/xml"
return value
class PlainTextRenderer:
"""Renderizador para dados do tipo ``text/plain``.
Espera que o retorno da view-function seja uma string de bytes pronta para
ser transferida para o cliente. Este renderer apenas define o content-type
da resposta HTTP.
"""
def __init__(self, info):
pass
def __call__(self, value, system):
request = system.get("request")
if request is not None:
request.response.content_type = "text/plain"
return value
def split_dsn(dsns):
"""Produz uma lista de DSNs a partir de uma string separada de DSNs separados
por espaços ou quebras de linha. A escolha dos separadores se baseia nas
convenções do framework Pyramid.
"""
return [dsn.strip() for dsn in str(dsns).split() if dsn]
DEFAULT_SETTINGS = [
(
"kernel.app.mongodb.dsn",
"KERNEL_APP_MONGODB_DSN",
split_dsn,
"mongodb://db:27017/",
),
("kernel.app.mongodb.replicaset", "KERNEL_APP_MONGODB_REPLICASET", str, ""),
(
"kernel.app.mongodb.readpreference",
"KERNEL_APP_MONGODB_READPREFERENCE",
str,
"secondaryPreferred",
),
("kernel.app.mongodb.dbname", "KERNEL_APP_MONGODB_DBNAME", str, "document-store"),
("kernel.app.prometheus.enabled", "KERNEL_APP_PROMETHEUS_ENABLED", asbool, True),
("kernel.app.prometheus.port", "KERNEL_APP_PROMETHEUS_PORT", int, 8087),
("kernel.app.sentry.enabled", "KERNEL_APP_SENTRY_ENABLED", asbool, False),
("kernel.app.sentry.dsn", "KERNEL_APP_SENTRY_DSN", str, ""),
("kernel.app.sentry.environment", "KERNEL_APP_SENTRY_ENVIRONMENT", str, ""),
]
def parse_settings(settings, defaults=DEFAULT_SETTINGS):
"""Analisa e retorna as configurações da app com base no arquivo .ini e env.
As variáveis de ambiente possuem precedência em relação aos valores
definidos no arquivo .ini.
O argumento `defaults` deve receber uma lista associativa na forma:
[
(<diretiva de config>, <variável de ambiente>, <função de conversão>, <valor padrão>),
]
"""
parsed = {}
cfg = list(defaults)
for name, envkey, convert, default in cfg:
value = os.environ.get(envkey, settings.get(name, default))
if convert is not None:
value = convert(value)
parsed[name] = value
return parsed
def main(global_config, **settings):
settings.update(parse_settings(settings))
config = Configurator(settings=settings)
config.include("cornice")
config.include("cornice_swagger")
config.include("documentstore.pyramid_prometheus")
config.scan()
config.add_renderer("xml", XMLRenderer)
config.add_renderer("text", PlainTextRenderer)
mongo = adapters.MongoDB(
settings["kernel.app.mongodb.dsn"],
settings["kernel.app.mongodb.dbname"],
options={
"replicaSet": settings["kernel.app.mongodb.replicaset"],
"readPreference": settings["kernel.app.mongodb.readpreference"],
},
)
Session = adapters.Session.partial(mongo)
config.add_request_method(
lambda request: services.get_handlers(Session), "services", reify=True
)
if settings["kernel.app.sentry.enabled"]:
if settings["kernel.app.sentry.dsn"]:
sentry_sdk.init(
dsn=settings["kernel.app.sentry.dsn"],
integrations=[PyramidIntegration(transaction_style="route_pattern")],
release=f"scielo-kernel@{VERSION}",
environment=settings["kernel.app.sentry.environment"],
)
else:
LOGGER.info("cannot setup Sentry: the dsn was not provided")
return config.make_wsgi_app()
|
// All symbols in the `Pe` category as per Unicode v2.0.14:
[
'\x29',
'\x5D',
'\x7D',
'\xBB',
'\u0F3B',
'\u0F3D',
'\u2019',
'\u201D',
'\u203A',
'\u2046',
'\u207E',
'\u208E',
'\u232A',
'\u3009',
'\u300B',
'\u300D',
'\u300F',
'\u3011',
'\u3015',
'\u3017',
'\u3019',
'\u301B',
'\u301E',
'\uFD3F',
'\uFE36',
'\uFE38',
'\uFE3A',
'\uFE3C',
'\uFE3E',
'\uFE40',
'\uFE42',
'\uFE44',
'\uFE5A',
'\uFE5C',
'\uFE5E',
'\uFF09',
'\uFF3D',
'\uFF5D',
'\uFF63'
]; |
#!/usr/bin/env python
# =============================================================================================
# MODULE DOCSTRING
# =============================================================================================
"""
Tests for molecular topology representations
At least one supported cheminformatics toolkit must be installed to run these tests.
Only the tests applicable to that toolkit will be run.
TODO:
- Will the ToolkitWrapper allow us to pare down importing each wrapper directly?
- Add tests comparing RDKit and OpenEye aromaticity perception
- Right now, the test database of TestMolecule is read from mol2, requiring the OE
toolkit. Find a different test set that RDKit can read, or make a database of
serialized OFFMols.
"""
import copy
import os
import pickle
from tempfile import NamedTemporaryFile
import numpy as np
import pytest
try:
from openmm import unit
from openmm.app import element
except ImportError:
from simtk import unit
from simtk.openmm.app import element
from openff.toolkit.tests.create_molecules import (
create_acetaldehyde,
create_benzene_no_aromatic,
create_cis_1_2_dichloroethene,
create_cyclohexane,
create_ethanol,
create_reversed_ethanol,
)
from openff.toolkit.tests.utils import (
has_pkg,
requires_ambertools,
requires_openeye,
requires_pkg,
requires_rdkit,
)
from openff.toolkit.topology import NotBondedError
from openff.toolkit.topology.molecule import (
Atom,
FrozenMolecule,
InvalidConformerError,
Molecule,
SmilesParsingError,
)
from openff.toolkit.utils import get_data_file_path
from openff.toolkit.utils.exceptions import ConformerGenerationError
from openff.toolkit.utils.toolkits import (
AmberToolsToolkitWrapper,
OpenEyeToolkitWrapper,
RDKitToolkitWrapper,
ToolkitRegistry,
)
# =============================================================================================
# TEST UTILITIES
# =============================================================================================
def assert_molecule_is_equal(molecule1, molecule2, msg):
"""Compare whether two Molecule objects are equal
Parameters
----------
molecule1, molecule2 : openff.toolkit.topology.Molecule
Molecules to be compared
msg : str
Message to include if molecules fail to match.
"""
if not (molecule1.is_isomorphic_with(molecule2)):
raise AssertionError(msg)
def is_four_membered_ring_torsion(torsion):
"""Check that three atoms in the given torsion form a four-membered ring."""
# Push a copy of the first and second atom in the end to make the code simpler.
torsion = list(torsion) + [torsion[0], torsion[1]]
is_four_membered_ring = True
for i in range(4):
# The atom is bonded to the next one.
is_four_membered_ring &= torsion[i].is_bonded_to(torsion[i + 1])
# The atom is not bonded to the atom on its diagonal.
is_four_membered_ring &= not torsion[i].is_bonded_to(torsion[i + 2])
return is_four_membered_ring
def is_three_membered_ring_torsion(torsion):
"""Check that three atoms in the given torsion form a three-membered ring.
In order to be 4 atoms with a three-membered ring, there must be
1) A central atom connected to all other atoms.
2) An atom outside the ring connected exclusively to the central atom.
3) Two atoms in the ring connected to the central atom and to each other.
"""
# A set of atom indices for the atoms in the torsion.
torsion_atom_indices = set(a.molecule_atom_index for a in torsion)
# Collect all the bonds involving exclusively atoms in the torsion.
bonds_by_atom_idx = {i: set() for i in torsion_atom_indices}
for atom in torsion:
for bond in atom.bonds:
# Consider the bond only if both atoms are in the torsion.
if (
bond.atom1_index in torsion_atom_indices
and bond.atom2_index in torsion_atom_indices
):
bonds_by_atom_idx[bond.atom1_index].add(bond.atom2_index)
bonds_by_atom_idx[bond.atom2_index].add(bond.atom1_index)
# Find the central atom, which is connected to all other atoms.
atom_indices = [i for i in torsion_atom_indices if len(bonds_by_atom_idx[i]) == 3]
if len(atom_indices) != 1:
return False
central_atom_idx = atom_indices[0]
# Find the atom outside the ring.
atom_indices = [i for i in torsion_atom_indices if len(bonds_by_atom_idx[i]) == 1]
if (
len(atom_indices) != 1
or central_atom_idx not in bonds_by_atom_idx[atom_indices[0]]
):
return False
outside_atom_idx = atom_indices[0]
# Check that the remaining two atoms are non-central atoms in the membered ring.
atom1, atom2 = [
i for i in torsion_atom_indices if i not in [central_atom_idx, outside_atom_idx]
]
# The two atoms are bonded to each other.
if atom2 not in bonds_by_atom_idx[atom1] or atom1 not in bonds_by_atom_idx[atom2]:
return False
# Check that they are both bonded to the central atom and none other.
for atom_idx in [atom1, atom2]:
if (
central_atom_idx not in bonds_by_atom_idx[atom_idx]
or len(bonds_by_atom_idx[atom_idx]) != 2
):
return False
# This is a torsion including a three-membered ring.
return True
# =============================================================================================
# FIXTURES
# =============================================================================================
def mini_drug_bank(xfail_mols=None, wip_mols=None):
"""Load the full MiniDrugBank into Molecule objects.
Parameters
----------
xfail_mols : Dict[str, str or None]
Dictionary mapping the molecule names that are allowed to
failed to the failure reason.
wip_mols : Dict[str, str or None]
Dictionary mapping the molecule names that are work in progress
to the failure reason.
"""
# If we have already loaded the data set, return the cached one.
if mini_drug_bank.molecules is not None:
molecules = mini_drug_bank.molecules
else:
# Load the dataset.
file_path = get_data_file_path("molecules/MiniDrugBank_tripos.mol2")
try:
# We need OpenEye to parse the molecules, but pytest execute this
# whether or not the test class is skipped so if OE is not available
# we just return an empty list of test cases as a workaround.
molecules = Molecule.from_file(file_path, allow_undefined_stereo=True)
except NotImplementedError as e:
assert "No toolkits in registry can read file" in str(e)
mini_drug_bank.molecules = []
return []
else:
mini_drug_bank.molecules = molecules
# Check if we need to mark anything.
if xfail_mols is None and wip_mols is None:
return molecules
# Handle mutable default.
if xfail_mols is None:
xfail_mols = {}
if wip_mols is None:
wip_mols = {}
# There should be no molecule in both dictionaries.
assert len(set(xfail_mols).intersection(set(wip_mols))) == 0
# Don't modify the cached molecules.
molecules = copy.deepcopy(molecules)
for i, mol in enumerate(molecules):
if mol.name in xfail_mols:
marker = pytest.mark.xfail(reason=xfail_mols[mol.name])
elif mol.name in wip_mols:
marker = pytest.mark.wip(reason=wip_mols[mol.name])
else:
marker = None
if marker is not None:
molecules[i] = pytest.param(mol, marks=marker)
return molecules
# Use a "static" variable as a workaround as fixtures cannot be
# used inside pytest.mark.parametrize (see issue #349 in pytest).
mini_drug_bank.molecules = None # type: ignore
# All the molecules that raise UndefinedStereochemistryError when read by OETK()
openeye_drugbank_undefined_stereo_mols = {
"DrugBank_1634",
"DrugBank_1700",
"DrugBank_1962",
"DrugBank_2519",
"DrugBank_2987",
"DrugBank_3502",
"DrugBank_3930",
"DrugBank_4161",
"DrugBank_4162",
"DrugBank_5043",
"DrugBank_5418",
"DrugBank_6531",
}
# All the molecules that raise UndefinedStereochemistryError when read by OETK().
# Note that this list is different from that for OEMol,
# since the toolkits have different definitions of "stereogenic"
rdkit_drugbank_undefined_stereo_mols = {
"DrugBank_1634",
"DrugBank_1962",
"DrugBank_2519",
"DrugBank_3930",
"DrugBank_5043",
"DrugBank_5418",
"DrugBank_7124",
"DrugBank_6865",
}
# Missing stereo in OE but not RDK: 'DrugBank_2987', 'DrugBank_3502', 'DrugBank_4161',
# 'DrugBank_4162', 'DrugBank_6531', 'DrugBank_1700',
drugbank_stereogenic_in_rdkit_but_not_openeye = {
"DrugBank_5329",
"DrugBank_7124",
"DrugBank_6865",
}
# Some molecules are _valid_ in both OETK and RDKit, but will fail if you try
# to convert from one to the other, since OE adds stereo that RDKit doesn't
drugbank_stereogenic_in_oe_but_not_rdkit = {
"DrugBank_1598",
"DrugBank_4346",
"DrugBank_1849",
"DrugBank_2141",
}
# =============================================================================================
# TESTS
# =============================================================================================
class TestAtom:
"""Test Atom class."""
def test_atom_constructor(self):
"""Test Atom creation"""
# Create a non-aromatic carbon atom
atom1 = Atom(6, 0, False)
assert atom1.atomic_number == 6
assert atom1.formal_charge == 0 * unit.elementary_charge
# Create a chiral carbon atom
atom2 = Atom(6, 0, False, stereochemistry="R", name="CT")
assert atom1.stereochemistry != atom2.stereochemistry
# Ensure that formal charge can also be set as a Quantity
atom1 = Atom(6, 1 * unit.elementary_charge, False)
assert atom1.formal_charge == 1 * unit.elementary_charge
def test_atom_properties(self):
"""Test that atom properties are correctly populated and gettable"""
formal_charge = 0 * unit.elementary_charge
is_aromatic = False
# Attempt to create all elements supported by OpenMM
elements = [
getattr(element, name)
for name in dir(element)
if (type(getattr(element, name)) == element.Element)
]
# The above runs into a problem with deuterium (fails name assertion)
elements.remove(element.deuterium)
for this_element in elements:
atom = Atom(
this_element.atomic_number,
formal_charge,
is_aromatic,
name=this_element.name,
)
assert atom.atomic_number == this_element.atomic_number
assert atom.element == this_element
assert atom.mass == this_element.mass
assert atom.formal_charge == formal_charge
assert atom.is_aromatic == is_aromatic
assert atom.name == this_element.name
def test_set_molecule(self):
"""Test appropriately setting a molecule with no errors"""
mol = Molecule.from_smiles("CCO")
atom = Atom(6, 0, False)
atom.molecule = mol
def test_set_molecule_error(self):
"""Test setting molecule for atom with molecule raises error"""
mol = Molecule.from_smiles("CCO")
atom = Atom(6, 0, False)
atom.molecule = mol
with pytest.raises(AssertionError, match="already has an associated molecule"):
atom.molecule = mol
class TestMolecule:
"""Test Molecule class."""
# TODO: Test getstate/setstate
# Test serialization {to|from}_{dict|yaml|toml|json|bson|xml|messagepack|pickle}
@pytest.mark.parametrize("molecule", mini_drug_bank())
def test_dict_serialization(self, molecule):
"""Test serialization of a molecule object to and from dict."""
serialized = molecule.to_dict()
molecule_copy = Molecule.from_dict(serialized)
assert molecule == molecule_copy
assert molecule_copy.n_conformers == molecule.n_conformers
assert np.allclose(molecule_copy.conformers[0], molecule.conformers[0])
@requires_pkg("yaml")
@pytest.mark.parametrize("molecule", mini_drug_bank())
def test_yaml_serialization(self, molecule):
"""Test serialization of a molecule object to and from YAML."""
serialized = molecule.to_yaml()
molecule_copy = Molecule.from_yaml(serialized)
assert molecule == molecule_copy
assert molecule_copy.n_conformers == molecule.n_conformers
assert np.allclose(molecule_copy.conformers[0], molecule.conformers[0])
@requires_pkg("toml")
@pytest.mark.parametrize("molecule", mini_drug_bank())
def test_toml_serialization(self, molecule):
"""Test serialization of a molecule object to and from TOML."""
# TODO: Test round-trip, on mini_drug_bank, when implemented
mol = Molecule.from_smiles("CCO")
with pytest.raises(NotImplementedError):
mol.to_toml()
@requires_pkg("bson")
@pytest.mark.parametrize("molecule", mini_drug_bank())
def test_bson_serialization(self, molecule):
"""Test serialization of a molecule object to and from BSON."""
serialized = molecule.to_bson()
molecule_copy = Molecule.from_bson(serialized)
assert molecule == molecule_copy
assert molecule_copy.n_conformers == molecule.n_conformers
assert np.allclose(molecule_copy.conformers[0], molecule.conformers[0])
@pytest.mark.parametrize("molecule", mini_drug_bank())
def test_json_serialization(self, molecule):
"""Test serialization of a molecule object to and from JSON."""
molecule_copy = Molecule.from_json(molecule.to_json())
assert molecule_copy == molecule
assert molecule_copy.n_conformers == molecule.n_conformers
assert np.allclose(molecule_copy.conformers[0], molecule.conformers[0])
@pytest.mark.parametrize("molecule", mini_drug_bank())
def test_xml_serialization(self, molecule):
"""Test serialization of a molecule object to and from XML."""
# TODO: Test round-trip, on mini_drug_bank, when from_xml is implemented
mol = Molecule.from_smiles("CCO")
serialized = mol.to_xml()
with pytest.raises(NotImplementedError):
Molecule.from_xml(serialized)
@requires_pkg("msgpack")
@pytest.mark.parametrize("molecule", mini_drug_bank())
def test_messagepack_serialization(self, molecule):
"""Test serialization of a molecule object to and from messagepack."""
serialized = molecule.to_messagepack()
molecule_copy = Molecule.from_messagepack(serialized)
assert molecule == molecule_copy
assert molecule_copy.n_conformers == molecule.n_conformers
assert np.allclose(molecule_copy.conformers[0], molecule.conformers[0])
@pytest.mark.parametrize("molecule", mini_drug_bank())
def test_pickle_serialization(self, molecule):
"""Test round-trip pickling of a molecule object."""
serialized = pickle.dumps(molecule)
molecule_copy = pickle.loads(serialized)
assert molecule == molecule_copy
assert molecule_copy.n_conformers == molecule.n_conformers
assert np.allclose(molecule_copy.conformers[0], molecule.conformers[0])
@requires_pkg("yaml")
@requires_pkg("toml")
@requires_pkg("msgpack")
def test_serialization_no_conformers(self):
"""Test round-trip serialization when molecules have no conformers or partial charges."""
mol = Molecule.from_smiles("CCO")
dict_copy = Molecule.from_dict(mol.to_dict())
assert mol == dict_copy
# TODO: yaml_copy = Molecule.from_yaml(mol.to_yaml())
with pytest.raises(NotImplementedError):
mol.to_toml()
bson_copy = Molecule.from_bson(mol.to_bson())
assert mol == bson_copy
json_copy = Molecule.from_json(mol.to_json())
assert mol == json_copy
# TODO: round-trip when from_xml is implemented
mol_as_xml = mol.to_xml()
with pytest.raises(NotImplementedError):
Molecule.from_xml(mol_as_xml)
messagepack_copy = Molecule.from_messagepack(mol.to_messagepack())
assert mol == messagepack_copy
pickle_copy = pickle.loads(pickle.dumps(mol))
assert mol == pickle_copy
def test_json_numpy_roundtrips(self):
"""Ensure that array data survives several round-trips through JSON,
which depends on list serialization instead of bytes."""
mol = Molecule.from_smiles("CCO")
mol.generate_conformers(n_conformers=1)
initial_conformer = mol.conformers[0]
for _ in range(10):
mol = Molecule.from_json(mol.to_json())
assert np.allclose(initial_conformer, mol.conformers[0])
# ----------------------------------------------------
# Test Molecule constructors and conversion utilities.
# ----------------------------------------------------
def test_create_empty(self):
"""Test empty constructor."""
molecule = Molecule()
assert len(molecule.atoms) == 0
assert len(molecule.bonds) == 0
@pytest.mark.parametrize("molecule", mini_drug_bank())
def test_create_copy(self, molecule):
"""Test copy constructor."""
molecule_copy = Molecule(molecule)
assert molecule_copy == molecule
# Test that the "properties" dict of both molecules is unique
# (see https://github.com/openforcefield/openff-toolkit/pull/786)
molecule_copy.properties["aaa"] = "bbb"
assert "aaa" not in molecule.properties
@pytest.mark.skipif(
not (has_pkg("rdkit") and not (has_pkg("openeye"))),
reason="Test requires that RDKit is installed, but OpenEye is not installed",
)
def test_repr_bad_smiles(self):
"""Test that the repr falls back to Hill formula if to_smiles fails."""
assert "bad" not in Molecule.from_smiles("CC").__repr__()
# OpenEye will report a smiles of ClCl(Cl)C without error, so only test with RDKit unless we
# can come up with a molecule that OpenEyeToolkitWrapper.to_smiles() will reliably fail on
molecule = Molecule()
molecule.add_atom(17, 0, False)
molecule.add_atom(17, 0, False)
molecule.add_atom(17, 0, False)
molecule.add_bond(0, 1, 1, False)
molecule.add_bond(0, 2, 1, False)
expected_repr = "Molecule with name '' with bad SMILES and Hill formula 'Cl3'"
assert molecule.__repr__() == expected_repr
@pytest.mark.parametrize("toolkit", [OpenEyeToolkitWrapper, RDKitToolkitWrapper])
@pytest.mark.parametrize("molecule", mini_drug_bank())
def test_to_from_smiles(self, molecule, toolkit):
"""Test round-trip creation from SMILES"""
if not toolkit.is_available():
pytest.skip("Required toolkit is unavailable")
if toolkit == RDKitToolkitWrapper:
# Skip the test if OpenEye assigns stereochemistry but RDKit doesn't (since then, the
# OFF molecule will be loaded, but fail to convert in to_rdkit)
if molecule.name in drugbank_stereogenic_in_oe_but_not_rdkit:
pytest.skip(
"Molecule is stereogenic in OpenEye (which loaded this dataset), but not RDKit, so it "
"is impossible to make a valid RDMol in this test"
)
undefined_stereo_mols = rdkit_drugbank_undefined_stereo_mols
elif toolkit == OpenEyeToolkitWrapper:
undefined_stereo_mols = openeye_drugbank_undefined_stereo_mols
toolkit_wrapper = toolkit()
undefined_stereo = molecule.name in undefined_stereo_mols
# Since OpenEye did the original reading of MiniDrugBank, if OPENEYE doesn't
# think a feature is stereogenic, then "molecule" won't have stereochemistry defined
stereogenic_in_rdk_but_not_openeye = (
molecule.name in drugbank_stereogenic_in_rdkit_but_not_openeye
)
smiles1 = molecule.to_smiles(toolkit_registry=toolkit_wrapper)
if undefined_stereo or (
(toolkit is RDKitToolkitWrapper) and stereogenic_in_rdk_but_not_openeye
):
molecule2 = Molecule.from_smiles(
smiles1, allow_undefined_stereo=True, toolkit_registry=toolkit_wrapper
)
else:
molecule2 = Molecule.from_smiles(smiles1, toolkit_registry=toolkit_wrapper)
smiles2 = molecule2.to_smiles(toolkit_registry=toolkit_wrapper)
assert smiles1 == smiles2
@pytest.mark.parametrize(
"smiles, expected", [("[Cl:1]Cl", {0: 1}), ("[Cl:1][Cl:2]", {0: 1, 1: 2})]
)
@pytest.mark.parametrize(
"toolkit_class", [OpenEyeToolkitWrapper, RDKitToolkitWrapper]
)
def test_from_smiles_with_map(self, smiles, expected, toolkit_class):
if not (toolkit_class.is_available()):
pytest.skip(f"Required toolkit {toolkit_class} is unavailable")
molecule = Molecule.from_smiles(smiles, toolkit_registry=toolkit_class())
assert molecule.properties["atom_map"] == expected
smiles_types = [
{"isomeric": True, "explicit_hydrogens": True, "mapped": True, "error": None},
{"isomeric": False, "explicit_hydrogens": True, "mapped": True, "error": None},
{
"isomeric": True,
"explicit_hydrogens": False,
"mapped": True,
"error": AssertionError,
},
{"isomeric": True, "explicit_hydrogens": True, "mapped": False, "error": None},
{"isomeric": True, "explicit_hydrogens": False, "mapped": False, "error": None},
{"isomeric": False, "explicit_hydrogens": True, "mapped": False, "error": None},
{
"isomeric": False,
"explicit_hydrogens": False,
"mapped": True,
"error": AssertionError,
},
{
"isomeric": False,
"explicit_hydrogens": False,
"mapped": False,
"error": None,
},
]
@pytest.mark.parametrize(
"toolkit_class", [OpenEyeToolkitWrapper, RDKitToolkitWrapper]
)
@pytest.mark.parametrize("data", smiles_types)
def test_smiles_types(self, data, toolkit_class):
"""Test that the toolkit is passing the correct args to the toolkit backends across different combinations."""
if toolkit_class.is_available():
toolkit = toolkit_class()
mol = create_cis_1_2_dichloroethene()
isomeric, explicit_hs, mapped = (
data["isomeric"],
data["explicit_hydrogens"],
data["mapped"],
)
if data["error"] is not None:
with pytest.raises(data["error"]):
mol.to_smiles(
isomeric=isomeric,
explicit_hydrogens=explicit_hs,
mapped=mapped,
toolkit_registry=toolkit,
)
else:
# make the smiles then do some checks on it
output_smiles = mol.to_smiles(
isomeric=isomeric,
explicit_hydrogens=explicit_hs,
mapped=mapped,
toolkit_registry=toolkit,
)
if isomeric:
assert "\\" in output_smiles
if explicit_hs:
assert "H" in output_smiles
if mapped:
for i in range(1, 7):
assert f":{i}" in output_smiles
# if the molecule is mapped make it using the mapping
mol2 = Molecule.from_mapped_smiles(
mapped_smiles=output_smiles,
toolkit_registry=toolkit,
allow_undefined_stereo=not isomeric,
)
else:
# make a molecule from a standard smiles
mol2 = Molecule.from_smiles(
smiles=output_smiles,
allow_undefined_stereo=not isomeric,
toolkit_registry=toolkit,
)
isomorphic, atom_map = Molecule.are_isomorphic(
mol,
mol2,
return_atom_map=True,
aromatic_matching=True,
formal_charge_matching=True,
bond_order_matching=True,
atom_stereochemistry_matching=isomeric,
bond_stereochemistry_matching=isomeric,
)
assert isomorphic is True
if mapped:
assert {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5} == atom_map
else:
pytest.skip(
f"The required toolkit ({toolkit_class.toolkit_name}) is not available."
)
@pytest.mark.parametrize(
"toolkit_class", [OpenEyeToolkitWrapper, RDKitToolkitWrapper]
)
def test_smiles_cache(self, toolkit_class):
"""Make sure that the smiles cache is being used correctly."""
if toolkit_class.is_available():
toolkit = toolkit_class()
# this uses no toolkit back end so no smiles should be saved
mol = create_ethanol()
# now lets populate the cache with a test result
# first we need to make the cache key for the default input
isomeric, explicit_hydrogens, mapped = True, True, False
cache_key = (
toolkit.to_smiles.__qualname__
+ str(isomeric)
+ str(explicit_hydrogens)
+ str(mapped)
)
cache_key += str(mol._properties.get("atom_map", None))
mol._cached_smiles = {cache_key: None}
assert (
mol.to_smiles(
isomeric=isomeric,
toolkit_registry=toolkit,
explicit_hydrogens=explicit_hydrogens,
mapped=mapped,
)
is None
)
# now make sure the cache is not used if we change an input arg
assert (
mol.to_smiles(
isomeric=True,
explicit_hydrogens=True,
mapped=True,
toolkit_registry=toolkit,
)
is not None
)
# now make sure the cache was updated
assert mol._cached_smiles != {cache_key: None}
assert len(mol._cached_smiles) == 2
else:
pytest.skip(
f"The required toolkit ({toolkit_class.toolkit_name}) is not available."
)
mapped_types = [
{"atom_map": None},
{"atom_map": {0: 0}},
{"atom_map": {0: 0, 1: 0, 2: 0, 3: 0}},
{"atom_map": {0: 0, 1: 1, 2: 2, 3: 3}},
{"atom_map": {0: 1, 1: 2, 2: 3, 3: 4}},
]
@pytest.mark.parametrize(
"toolkit_class", [OpenEyeToolkitWrapper, RDKitToolkitWrapper]
)
@pytest.mark.parametrize("data", mapped_types)
def test_partial_mapped_smiles(self, toolkit_class, data):
if toolkit_class.is_available():
toolkit = toolkit_class()
mol = create_cis_1_2_dichloroethene()
mol._properties["atom_map"] = data["atom_map"]
smiles = mol.to_smiles(
isomeric=True,
explicit_hydrogens=True,
mapped=True,
toolkit_registry=toolkit,
)
# now we just need to check the smiles generated
if data["atom_map"] is None:
for i, atom in enumerate(mol.atoms, 1):
assert f"[{atom.element.symbol}:{i}]" in smiles
else:
if 0 in data["atom_map"].values():
increment = True
else:
increment = False
for atom, index in data["atom_map"].items():
assert f"[{mol.atoms[atom].element.symbol}:{index + 1 if increment else index}]"
else:
pytest.skip(
f"The required toolkit ({toolkit_class.toolkit_name}) is not available."
)
@pytest.mark.parametrize("molecule", mini_drug_bank())
def test_unique_atom_names(self, molecule):
"""Test molecules have unique atom names"""
# The dataset we load in has atom names, so let's strip them first
# to ensure that we can fail the uniqueness check
for atom in molecule.atoms:
atom.name = ""
assert not (molecule.has_unique_atom_names)
# Then genreate unique atom names using the built in algorithm
molecule.generate_unique_atom_names()
# Check that the molecule has unique atom names
assert molecule.has_unique_atom_names
# Check molecule.has_unique_atom_names is working correctly
assert (
len(set([atom.name for atom in molecule.atoms])) == molecule.n_atoms
) == molecule.has_unique_atom_names
molecule.atoms[1].name = molecule.atoms[0].name # no longer unique
assert (
len(set([atom.name for atom in molecule.atoms])) == molecule.n_atoms
) == molecule.has_unique_atom_names
assert all("x" in a.name for a in molecule.atoms)
inchi_data = [
{
"molecule": create_ethanol(),
"standard_inchi": "InChI=1S/C2H6O/c1-2-3/h3H,2H2,1H3",
"fixed_hydrogen_inchi": "InChI=1/C2H6O/c1-2-3/h3H,2H2,1H3",
},
{
"molecule": create_reversed_ethanol(),
"standard_inchi": "InChI=1S/C2H6O/c1-2-3/h3H,2H2,1H3",
"fixed_hydrogen_inchi": "InChI=1/C2H6O/c1-2-3/h3H,2H2,1H3",
},
{
"molecule": create_acetaldehyde(),
"standard_inchi": "InChI=1S/C2H4O/c1-2-3/h2H,1H3",
"fixed_hydrogen_inchi": "InChI=1/C2H4O/c1-2-3/h2H,1H3",
},
{
"molecule": create_cyclohexane(),
"standard_inchi": "InChI=1S/C6H12/c1-2-4-6-5-3-1/h1-6H2",
"fixed_hydrogen_inchi": "InChI=1/C6H12/c1-2-4-6-5-3-1/h1-6H2",
},
]
@requires_openeye
@pytest.mark.parametrize("data", inchi_data)
def test_from_inchi(self, data):
"""Test building a molecule from standard and non-standard InChI strings."""
toolkit = OpenEyeToolkitWrapper()
ref_mol = data["molecule"]
# make a molecule from inchi
inchi_mol = Molecule.from_inchi(
data["standard_inchi"], toolkit_registry=toolkit
)
assert inchi_mol.to_inchi(toolkit_registry=toolkit) == data["standard_inchi"]
def compare_mols(ref_mol, inchi_mol):
assert ref_mol.n_atoms == inchi_mol.n_atoms
assert ref_mol.n_bonds == inchi_mol.n_bonds
assert ref_mol.n_angles == inchi_mol.n_angles
assert ref_mol.n_propers == inchi_mol.n_propers
assert ref_mol.is_isomorphic_with(inchi_mol) is True
compare_mols(ref_mol, inchi_mol)
# now make the molecule from the non-standard inchi and compare
nonstandard_inchi_mol = Molecule.from_inchi(
data["fixed_hydrogen_inchi"], toolkit_registry=toolkit
)
assert (
nonstandard_inchi_mol.to_inchi(
fixed_hydrogens=True, toolkit_registry=toolkit
)
== data["fixed_hydrogen_inchi"]
)
compare_mols(ref_mol, nonstandard_inchi_mol)
# TODO: Should there be an equivalent toolkit test and leave this as an integration test?
@requires_openeye
@pytest.mark.slow
def test_create_from_file(self):
"""Test standard constructor taking a filename or file-like object."""
# TODO: Expand test to both openeye and rdkit toolkits
filename = get_data_file_path("molecules/toluene.mol2")
molecule1 = Molecule(filename, allow_undefined_stereo=True)
with open(filename, "r") as infile:
molecule2 = Molecule(
infile, file_format="MOL2", allow_undefined_stereo=True
)
assert molecule1 == molecule2
import gzip
with gzip.GzipFile(filename + ".gz", "r") as infile:
molecule3 = Molecule(
infile, file_format="MOL2", allow_undefined_stereo=True
)
assert molecule3 == molecule1
# Ensure that attempting to initialize a single Molecule from a file
# containing multiple molecules raises a ValueError
with pytest.raises(ValueError) as exc_info:
filename = get_data_file_path("molecules/zinc-subset-tripos.mol2.gz")
molecule = Molecule(filename, allow_undefined_stereo=True)
@pytest.mark.parametrize("molecule", mini_drug_bank())
def test_create_from_serialized(self, molecule):
"""Test standard constructor taking the output of __getstate__()."""
serialized_molecule = molecule.__getstate__()
molecule_copy = Molecule(serialized_molecule)
assert molecule == molecule_copy
@pytest.mark.parametrize("molecule", mini_drug_bank())
def test_to_from_dict(self, molecule):
"""Test that conversion/creation of a molecule to and from a dict is consistent."""
serialized = molecule.to_dict()
molecule_copy = Molecule.from_dict(serialized)
assert molecule == molecule_copy
@pytest.mark.parametrize("molecule", mini_drug_bank())
def test_to_networkx(self, molecule):
"""Test conversion to NetworkX graph."""
graph = molecule.to_networkx()
@requires_rdkit
@pytest.mark.parametrize("molecule", mini_drug_bank())
def test_to_from_rdkit(self, molecule):
"""Test that conversion/creation of a molecule to and from an RDKit rdmol is consistent."""
# import pickle
from openff.toolkit.utils.toolkits import UndefinedStereochemistryError
undefined_stereo = molecule.name in rdkit_drugbank_undefined_stereo_mols
toolkit_wrapper = RDKitToolkitWrapper()
rdmol = molecule.to_rdkit()
molecule_smiles = molecule.to_smiles(toolkit_registry=toolkit_wrapper)
# First test making a molecule using the Molecule(oemol) method
# If this is a known failure, check that it raises UndefinedStereochemistryError
# and proceed with the test ignoring it.
test_mol = None
if undefined_stereo:
with pytest.raises(UndefinedStereochemistryError):
Molecule(rdmol)
test_mol = Molecule(rdmol, allow_undefined_stereo=True)
else:
test_mol = Molecule(rdmol)
test_mol_smiles = test_mol.to_smiles(toolkit_registry=toolkit_wrapper)
assert molecule_smiles == test_mol_smiles
# Check that the two topologies are isomorphic.
assert_molecule_is_equal(
molecule, test_mol, "Molecule.to_rdkit()/Molecule(rdmol) round trip failed"
)
# Second, test making a molecule using the Molecule.from_openeye(oemol) method
# If this is a known failure, check that it raises UndefinedStereochemistryError
# and proceed with the test.
if undefined_stereo:
with pytest.raises(UndefinedStereochemistryError):
Molecule.from_rdkit(rdmol)
test_mol = Molecule.from_rdkit(rdmol, allow_undefined_stereo=True)
else:
test_mol = Molecule.from_rdkit(rdmol)
test_mol_smiles = test_mol.to_smiles(toolkit_registry=toolkit_wrapper)
assert molecule_smiles == test_mol_smiles
# Check that the two topologies are isomorphic.
assert_molecule_is_equal(
molecule, test_mol, "Molecule.to_rdkit()/from_rdkit() round trip failed"
)
@requires_openeye
def test_to_from_iupac(self):
"""
Test basic behavior of the IUPAC conversion functions. More rigorous
testing of the toolkity wrapper behavior is in test_toolkits.py
"""
from openff.toolkit.utils.toolkits import (
InvalidIUPACNameError,
UndefinedStereochemistryError,
)
with pytest.raises(InvalidIUPACNameError):
Molecule.from_iupac(".BETA.-PINENE")
# DrugBank_977, tagged as a problem molecule in earlier tests
bad_stereo_iupac = (
"(~{E},3~{R},5~{S})-7-[4-(4-fluorophenyl)-6-isopropyl-2-"
"[methyl(methylsulfonyl)amino]pyrimidin-5-yl]-3,5-"
"dihydroxy-hept-6-enoic acid"
)
with pytest.raises(UndefinedStereochemistryError):
Molecule.from_iupac(bad_stereo_iupac)
cholesterol = Molecule.from_smiles(
"C[C@H](CCCC(C)C)[C@H]1CC[C@@H]2[C@@]1(CC[C@H]3[C@H]2CC=C4[C@@]3(CC[C@@H](C4)O)C)C"
)
cholesterol_iupac = cholesterol.to_iupac()
assert Molecule.are_isomorphic(
cholesterol, Molecule.from_iupac(cholesterol_iupac)
)
@pytest.mark.parametrize("molecule", mini_drug_bank())
def test_to_from_topology(self, molecule):
"""Test that conversion/creation of a molecule to and from a Topology is consistent."""
topology = molecule.to_topology()
molecule_copy = Molecule.from_topology(topology)
assert molecule == molecule_copy
@requires_openeye
def test_to_multiframe_xyz_openeye(self):
"""
Test writing out a molecule with multiple conformations to an xyz file
This test is backend-specific because of precision/rounding differences between RDKit and OpenEye
"""
from openff.toolkit.utils import OpenEyeToolkitWrapper
tkw = OpenEyeToolkitWrapper()
# load in an SDF of butane with multiple conformers in it
molecules = Molecule.from_file(
get_data_file_path("molecules/butane_multi.sdf"),
"sdf",
toolkit_registry=tkw,
)
# now we want to combine the conformers to one molecule
butane = molecules[0]
for mol in molecules[1:]:
butane.add_conformer(mol._conformers[0])
# make sure we have the 7 conformers
assert butane.n_conformers == 7
with NamedTemporaryFile(suffix=".xyz") as iofile:
# try and write out the xyz file
butane.to_file(iofile.name, "xyz", toolkit_registry=tkw)
# now lets check whats in the file
with open(iofile.name) as xyz_data:
data = xyz_data.readlines()
# make sure we have the correct amount of lines writen
assert len(data) == 112
# make sure all headers and frame data was writen
assert data.count("14\n") == 7
for i in range(1, 8):
assert f"C4H10 Frame {i}\n" in data
# now make sure the first line of the coordinates are correct in every frame
coords = [
"C 1.8902000189 0.0425999984 0.2431000024\n",
"C 1.8976000547 -0.0232999995 0.2845999897\n",
"C -1.8794000149 -0.1792999953 -0.2565000057\n",
"C -1.5205999613 -0.0164999999 0.2786999941\n",
"C -1.4889999628 -0.2619000077 0.4871000051\n",
"C -1.4940999746 -0.2249000072 -0.0957999974\n",
"C -1.8826999664 -0.0372000001 0.1937000006\n",
]
for coord in coords:
assert coord in data
@requires_openeye
def test_to_single_xyz_openeye(self):
"""
Test writing to a single frame xyz file
This test is backend-specific because of precision/rounding differences between RDKit and OpenEye
"""
from openff.toolkit.utils import OpenEyeToolkitWrapper
tkw = OpenEyeToolkitWrapper()
# load a molecule with a single conformation
toluene = Molecule.from_file(
get_data_file_path("molecules/toluene.sdf"), "sdf", toolkit_registry=tkw
)
# make sure it has one conformer
assert toluene.n_conformers == 1
with NamedTemporaryFile(suffix=".xyz") as iofile:
# try and write out the xyz file
toluene.to_file(iofile.name, "xyz", toolkit_registry=tkw)
# now lets check the file contents
with open(iofile.name) as xyz_data:
data = xyz_data.readlines()
# make sure we have the correct amount of lines writen
assert len(data) == 17
# make sure all headers and frame data was writen
assert data.count("15\n") == 1
assert data.count("C7H8\n") == 1
# now check that we can find the first and last coords
coords = [
"C 0.0000000000 0.0000000000 0.0000000000\n",
"H -0.0000000000 3.7604000568 0.0000000000\n",
]
for coord in coords:
assert coord in data
@requires_rdkit
def test_to_multiframe_xyz_rdkit(self):
"""
Test writing out a molecule with multiple conformations to an xyz file
This test is backend-specific because of precision/rounding differences between RDKit and OpenEye
"""
from openff.toolkit.utils import RDKitToolkitWrapper
tkw = RDKitToolkitWrapper()
# load in an SDF of butane with multiple conformers in it
molecules = Molecule.from_file(
get_data_file_path("molecules/butane_multi.sdf"),
"sdf",
toolkit_registry=tkw,
)
# now we want to combine the conformers to one molecule
butane = molecules[0]
for mol in molecules[1:]:
butane.add_conformer(mol._conformers[0])
# make sure we have the 7 conformers
assert butane.n_conformers == 7
with NamedTemporaryFile(suffix=".xyz") as iofile:
# try and write out the xyz file
butane.to_file(iofile.name, "xyz", toolkit_registry=tkw)
# now lets check whats in the file
with open(iofile.name) as xyz_data:
data = xyz_data.readlines()
# make sure we have the correct amount of lines writen
assert len(data) == 112
# make sure all headers and frame data was writen
assert data.count("14\n") == 7
for i in range(1, 8):
assert f"C4H10 Frame {i}\n" in data
# now make sure the first line of the coordinates are correct in every frame
coords = [
"C 1.8902000000 0.0426000000 0.2431000000\n",
"C 1.8976000000 -0.0233000000 0.2846000000\n",
"C -1.8794000000 -0.1793000000 -0.2565000000\n",
"C -1.5206000000 -0.0165000000 0.2787000000\n",
"C -1.4890000000 -0.2619000000 0.4871000000\n",
"C -1.4941000000 -0.2249000000 -0.0958000000\n",
"C -1.8827000000 -0.0372000000 0.1937000000\n",
]
for coord in coords:
assert coord in data
@requires_rdkit
def test_to_single_xyz_rdkit(self):
"""
Test writing to a single frame xyz file
This test is backend-specific because of precision/rounding differences between RDKit and OpenEye
"""
from openff.toolkit.utils import RDKitToolkitWrapper
tkw = RDKitToolkitWrapper()
# load a molecule with a single conformation
toluene = Molecule.from_file(
get_data_file_path("molecules/toluene.sdf"), "sdf", toolkit_registry=tkw
)
# make sure it has one conformer
assert toluene.n_conformers == 1
with NamedTemporaryFile(suffix=".xyz") as iofile:
# try and write out the xyz file
toluene.to_file(iofile.name, "xyz", toolkit_registry=tkw)
# now lets check the file contents
with open(iofile.name) as xyz_data:
data = xyz_data.readlines()
# make sure we have the correct amount of lines writen
assert len(data) == 17
# make sure all headers and frame data was writen
assert data.count("15\n") == 1
assert data.count("C7H8\n") == 1
# now check that we can find the first and last coords
coords = [
"C 0.0000000000 0.0000000000 0.0000000000\n",
"H -0.0000000000 3.7604000000 0.0000000000\n",
]
for coord in coords:
assert coord in data
def test_to_xyz_no_conformers(self):
"""Test writing a molecule out when it has no conformers here all coords should be 0."""
# here we want to make a molecule with no coordinates
ethanol = create_ethanol()
assert ethanol.n_conformers == 0
with NamedTemporaryFile(suffix=".xyz") as iofile:
# try and write out the xyz file
ethanol.to_file(iofile.name, "xyz")
# now lets check the file contents
with open(iofile.name) as xyz_data:
data = xyz_data.readlines()
# make sure we have the correct amount of lines writen
assert len(data) == 11
# make sure all headers and frame data was writen
assert data.count("9\n") == 1
assert data.count("C2H6O\n") == 1
# now check that all coords are 0
coords = ["0.0000000000", "0.0000000000", "0.0000000000"]
for atom_coords in data[2:]:
assert atom_coords.split()[1:] == coords
# TODO: Should there be an equivalent toolkit test and leave this as an integration test?
@pytest.mark.parametrize("molecule", mini_drug_bank())
@pytest.mark.parametrize(
"format",
[
"mol2",
"sdf",
pytest.param(
"pdb",
marks=pytest.mark.wip(
reason="Read from pdb has not been implemented properly yet"
),
),
],
)
def test_to_from_file(self, molecule, format):
"""Test that conversion/creation of a molecule to and from a file is consistent."""
from openff.toolkit.utils.toolkits import UndefinedStereochemistryError
# TODO: Test all file capabilities; the current test is minimal
# TODO: This is only for OE. Expand to both OE and RDKit toolkits.
# Molecules that are known to raise UndefinedStereochemistryError.
undefined_stereo_mols = {
"DrugBank_1700",
"DrugBank_2987",
"DrugBank_3502",
"DrugBank_4161",
"DrugBank_4162",
"DrugBank_6531",
}
undefined_stereo = molecule.name in undefined_stereo_mols
# The file is automatically deleted outside the with-clause.
with NamedTemporaryFile(suffix="." + format) as iofile:
# If this has undefined stereo, check that the exception is raised.
extension = os.path.splitext(iofile.name)[1][1:]
molecule.to_file(iofile.name, extension)
if undefined_stereo:
with pytest.raises(UndefinedStereochemistryError):
Molecule.from_file(iofile.name)
molecule2 = Molecule.from_file(
iofile.name, allow_undefined_stereo=undefined_stereo
)
assert molecule == molecule2
# TODO: Test to make sure properties are preserved?
# NOTE: We can't read pdb files and expect chemical information to be preserved
@requires_openeye
@pytest.mark.parametrize("molecule", mini_drug_bank())
def test_to_from_oemol(self, molecule):
"""Test that conversion/creation of a molecule to and from a OEMol is consistent."""
from openff.toolkit.utils.toolkits import UndefinedStereochemistryError
# Known failures raise an UndefinedStereochemistryError, but
# the round-trip SMILES representation with the OpenEyeToolkit
# doesn't seem to be affected.
# ZINC test set known failures.
# known_failures = {'ZINC05964684', 'ZINC05885163', 'ZINC05543156', 'ZINC17211981',
# 'ZINC17312986', 'ZINC06424847', 'ZINC04963126'}
undefined_stereo = molecule.name in openeye_drugbank_undefined_stereo_mols
toolkit_wrapper = OpenEyeToolkitWrapper()
oemol = molecule.to_openeye()
molecule_smiles = molecule.to_smiles(toolkit_registry=toolkit_wrapper)
# First test making a molecule using the Molecule(oemol) method
# If this is a known failure, check that it raises UndefinedStereochemistryError
# and proceed with the test ignoring it.
test_mol = None
if undefined_stereo:
with pytest.raises(UndefinedStereochemistryError):
Molecule(oemol)
test_mol = Molecule(oemol, allow_undefined_stereo=True)
else:
test_mol = Molecule(oemol)
test_mol_smiles = test_mol.to_smiles(toolkit_registry=toolkit_wrapper)
assert molecule_smiles == test_mol_smiles
# Check that the two topologies are isomorphic.
assert_molecule_is_equal(
molecule,
test_mol,
"Molecule.to_openeye()/Molecule(oemol) round trip failed",
)
# Second, test making a molecule using the Molecule.from_openeye(oemol) method
# If this is a known failure, check that it raises UndefinedStereochemistryError
# and proceed with the test.
if undefined_stereo:
with pytest.raises(UndefinedStereochemistryError):
Molecule.from_openeye(oemol)
test_mol = Molecule.from_openeye(oemol, allow_undefined_stereo=True)
else:
test_mol = Molecule.from_openeye(oemol)
test_mol_smiles = test_mol.to_smiles(toolkit_registry=toolkit_wrapper)
assert molecule_smiles == test_mol_smiles
# Check that the two topologies are isomorphic.
assert_molecule_is_equal(
molecule, test_mol, "Molecule.to_openeye()/from_openeye() round trip failed"
)
# ----------------------------------------------------
# Test properties.
# ----------------------------------------------------
def test_name(self):
"""Test Molecule name property"""
molecule1 = Molecule()
molecule1.name = None
molecule2 = Molecule()
molecule2.name = ""
assert molecule1.name == molecule2.name
name = "benzene"
molecule = Molecule()
molecule.name = name
assert molecule.name == name
def test_hill_formula(self):
"""Test that making the hill formula is consistent between input methods and ordering"""
# make sure smiles match reference
molecule_smiles = create_ethanol()
assert molecule_smiles.hill_formula == "C2H6O"
# make sure is not order dependent
molecule_smiles_reverse = create_reversed_ethanol()
assert molecule_smiles.hill_formula == molecule_smiles_reverse.hill_formula
# make sure single element names are put first
order_mol = Molecule.from_smiles("C(Br)CB")
assert order_mol.hill_formula == "C2H6BBr"
# test molecule with no carbon
no_carb_mol = Molecule.from_smiles("OS(=O)(=O)O")
assert no_carb_mol.hill_formula == "H2O4S"
# test no carbon and hydrogen
br_i = Molecule.from_smiles("BrI")
assert br_i.hill_formula == "BrI"
# make sure files and smiles match
molecule_file = Molecule.from_file(get_data_file_path("molecules/ethanol.sdf"))
assert molecule_smiles.hill_formula == molecule_file.hill_formula
# make sure the topology molecule gives the same formula
from openff.toolkit.topology.topology import Topology, TopologyMolecule
topology = Topology.from_molecules(molecule_smiles)
topmol = TopologyMolecule(molecule_smiles, topology)
assert molecule_smiles.hill_formula == Molecule.to_hill_formula(topmol)
# make sure the networkx matches
assert molecule_smiles.hill_formula == Molecule.to_hill_formula(
molecule_smiles.to_networkx()
)
def test_isomorphic_general(self):
"""Test the matching using different input types"""
# check that hill formula fails are caught
ethanol = create_ethanol()
acetaldehyde = create_acetaldehyde()
assert ethanol.is_isomorphic_with(acetaldehyde) is False
assert acetaldehyde.is_isomorphic_with(ethanol) is False
# check that different orderings work with full matching
ethanol_reverse = create_reversed_ethanol()
assert ethanol.is_isomorphic_with(ethanol_reverse) is True
# check a reference mapping between ethanol and ethanol_reverse matches that calculated
ref_mapping = {0: 8, 1: 7, 2: 6, 3: 3, 4: 4, 5: 5, 6: 1, 7: 2, 8: 0}
assert (
Molecule.are_isomorphic(ethanol, ethanol_reverse, return_atom_map=True)[1]
== ref_mapping
)
# check matching with nx.Graph atomic numbers and connectivity only
assert (
Molecule.are_isomorphic(
ethanol,
ethanol_reverse.to_networkx(),
aromatic_matching=False,
formal_charge_matching=False,
bond_order_matching=False,
atom_stereochemistry_matching=False,
bond_stereochemistry_matching=False,
)[0]
is True
)
# check matching with nx.Graph with full matching
assert ethanol.is_isomorphic_with(ethanol_reverse.to_networkx()) is True
# check matching with a TopologyMolecule class
from openff.toolkit.topology.topology import Topology, TopologyMolecule
topology = Topology.from_molecules(ethanol)
topmol = TopologyMolecule(ethanol, topology)
assert (
Molecule.are_isomorphic(
ethanol,
topmol,
aromatic_matching=False,
formal_charge_matching=False,
bond_order_matching=False,
atom_stereochemistry_matching=False,
bond_stereochemistry_matching=False,
)[0]
is True
)
# test hill formula passes but isomorphic fails
mol1 = Molecule.from_smiles("Fc1ccc(F)cc1")
mol2 = Molecule.from_smiles("Fc1ccccc1F")
assert mol1.is_isomorphic_with(mol2) is False
assert mol2.is_isomorphic_with(mol1) is False
isomorphic_permutations = [
{
"aromatic_matching": True,
"formal_charge_matching": True,
"bond_order_matching": True,
"atom_stereochemistry_matching": True,
"bond_stereochemistry_matching": True,
"result": False,
},
{
"aromatic_matching": False,
"formal_charge_matching": True,
"bond_order_matching": True,
"atom_stereochemistry_matching": True,
"bond_stereochemistry_matching": True,
"result": False,
},
{
"aromatic_matching": True,
"formal_charge_matching": False,
"bond_order_matching": True,
"atom_stereochemistry_matching": True,
"bond_stereochemistry_matching": True,
"result": False,
},
{
"aromatic_matching": True,
"formal_charge_matching": True,
"bond_order_matching": False,
"atom_stereochemistry_matching": True,
"bond_stereochemistry_matching": True,
"result": False,
},
{
"aromatic_matching": True,
"formal_charge_matching": True,
"bond_order_matching": True,
"atom_stereochemistry_matching": False,
"bond_stereochemistry_matching": True,
"result": False,
},
{
"aromatic_matching": True,
"formal_charge_matching": True,
"bond_order_matching": True,
"atom_stereochemistry_matching": True,
"bond_stereochemistry_matching": False,
"result": False,
},
{
"aromatic_matching": False,
"formal_charge_matching": False,
"bond_order_matching": False,
"atom_stereochemistry_matching": False,
"bond_stereochemistry_matching": False,
"result": True,
},
{
"aromatic_matching": False,
"formal_charge_matching": True,
"bond_order_matching": False,
"atom_stereochemistry_matching": True,
"bond_stereochemistry_matching": True,
"result": True,
},
{
"aromatic_matching": False,
"formal_charge_matching": False,
"bond_order_matching": False,
"atom_stereochemistry_matching": True,
"bond_stereochemistry_matching": True,
"result": True,
},
]
@pytest.mark.parametrize("inputs", isomorphic_permutations)
def test_isomorphic_perumtations(self, inputs):
"""Test all of the different combinations of matching levels between benzene with and without the aromatic bonds
defined"""
# get benzene with all aromatic atoms/bonds labeled
benzene = Molecule.from_smiles("c1ccccc1")
# get benzene with no aromatic labels
benzene_no_aromatic = create_benzene_no_aromatic()
# now test all of the variations
assert (
Molecule.are_isomorphic(
benzene,
benzene_no_aromatic,
aromatic_matching=inputs["aromatic_matching"],
formal_charge_matching=inputs["formal_charge_matching"],
bond_order_matching=inputs["bond_order_matching"],
atom_stereochemistry_matching=inputs["atom_stereochemistry_matching"],
bond_stereochemistry_matching=inputs["bond_stereochemistry_matching"],
)[0]
is inputs["result"]
)
@requires_openeye
def test_strip_atom_stereochemistry(self):
"""Test the basic behavior of strip_atom_stereochemistry"""
mol = Molecule.from_smiles("CCC[N@@](C)CC")
nitrogen_idx = [
atom.molecule_atom_index for atom in mol.atoms if atom.element.symbol == "N"
][0]
# TODO: This fails with RDKitToolkitWrapper because it perceives
# the stereochemistry of this nitrogen as None
assert mol.atoms[nitrogen_idx].stereochemistry == "S"
mol.strip_atom_stereochemistry(smarts="[N+0X3:1](-[*])(-[*])(-[*])")
assert mol.atoms[nitrogen_idx].stereochemistry is None
mol = Molecule.from_smiles("CCC[N@@](C)CC")
assert mol.atoms[nitrogen_idx].stereochemistry == "S"
mol.strip_atom_stereochemistry(smarts="[N+0X3:1](-[*])(-[*])(-[*])")
assert mol.atoms[nitrogen_idx].stereochemistry is None
@pytest.mark.parametrize("mol_smiles", [("C[N+](CC)(CC)CC"), ("c1cnc[nH]1")])
def test_do_not_strip_atom_stereochemsitry(self, mol_smiles):
"""
Test special cases in which we do not want nitrogen stereochemistry stripped:
NH in planar rings and tetra-coordinatined N+
"""
mol = Molecule.from_smiles(mol_smiles)
mol_mod = copy.deepcopy(mol)
mol_mod.strip_atom_stereochemistry("[N+0X3:1](-[*])(-[*])(-[*])")
# Inspect each atom's stereochemistry instead of relying on __eq__
for before, after in zip(mol.atoms, mol_mod.atoms):
assert before.stereochemistry == after.stereochemistry
def test_isomorphic_stripped_stereochemistry(self):
"""Test that the equality operator disregards an edge case of nitrogen stereocenters"""
mol1 = Molecule.from_smiles("CCC[N@](C)CC")
mol2 = Molecule.from_smiles("CCC[N@@](C)CC")
# Ensure default value is respected and order does not matter
assert Molecule.are_isomorphic(mol1, mol2, strip_pyrimidal_n_atom_stereo=True)
assert Molecule.are_isomorphic(mol1, mol2)
assert Molecule.are_isomorphic(mol2, mol1)
assert mol1 == mol2
assert Molecule.from_smiles("CCC[N@](C)CC") == Molecule.from_smiles(
"CCC[N@@](C)CC"
)
def test_remap(self):
"""Test the remap function which should return a new molecule in the requested ordering"""
# the order here is CCO
ethanol = create_ethanol()
# get ethanol in reverse order OCC
ethanol_reverse = create_reversed_ethanol()
# get the mapping between the molecules
mapping = Molecule.are_isomorphic(ethanol, ethanol_reverse, True)[1]
atom0, atom1 = list([atom for atom in ethanol.atoms])[:2]
ethanol.add_bond_charge_virtual_site([atom0, atom1], 0.3 * unit.angstrom)
# make sure that molecules with virtual sites raises an error
with pytest.raises(NotImplementedError):
remapped = ethanol.remap(mapping, current_to_new=True)
# remake with no virtual site and remap to match the reversed ordering
ethanol = create_ethanol()
new_ethanol = ethanol.remap(mapping, current_to_new=True)
def assert_molecules_match_after_remap(mol1, mol2):
"""Check all of the attributes in a molecule match after being remapped"""
for atoms in zip(mol1.atoms, mol2.atoms):
assert atoms[0].to_dict() == atoms[1].to_dict()
# bonds will not be in the same order in the molecule and the atom1 and atom2 indecies could be out of order
# make a dict to compare them both
remapped_bonds = dict(
((bond.atom1_index, bond.atom2_index), bond) for bond in mol2.bonds
)
for bond in mol1.bonds:
key = (bond.atom1_index, bond.atom2_index)
if key not in remapped_bonds:
key = tuple(reversed(key))
assert key in remapped_bonds
# now compare each attribute of the bond except the atom indexes
bond_dict = bond.to_dict()
del bond_dict["atom1"]
del bond_dict["atom2"]
remapped_bond_dict = remapped_bonds[key].to_dict()
del remapped_bond_dict["atom1"]
del remapped_bond_dict["atom2"]
assert mol1.n_bonds == mol2.n_bonds
assert mol1.n_angles == mol2.n_angles
assert mol1.n_propers == mol2.n_propers
assert mol1.n_impropers == mol2.n_impropers
assert mol1.total_charge == mol2.total_charge
assert mol1.partial_charges.all() == mol2.partial_charges.all()
# check all of the properties match as well, torsions and impropers will be in a different order
# due to the bonds being out of order
assert_molecules_match_after_remap(new_ethanol, ethanol_reverse)
# test round trip (double remapping a molecule)
new_ethanol = ethanol.remap(mapping, current_to_new=True)
isomorphic, round_trip_mapping = Molecule.are_isomorphic(
new_ethanol, ethanol, return_atom_map=True
)
assert isomorphic is True
round_trip_ethanol = new_ethanol.remap(round_trip_mapping, current_to_new=True)
assert_molecules_match_after_remap(round_trip_ethanol, ethanol)
@requires_openeye
def test_canonical_ordering_openeye(self):
"""Make sure molecules are returned in canonical ordering of openeye"""
from openff.toolkit.utils.toolkits import OpenEyeToolkitWrapper
openeye = OpenEyeToolkitWrapper()
# get ethanol in canonical order
ethanol = create_ethanol()
# get reversed non canonical ethanol
reversed_ethanol = create_reversed_ethanol()
# get the canonical ordering
canonical_ethanol = reversed_ethanol.canonical_order_atoms(openeye)
# make sure the mapping between the ethanol and the openeye ref canonical form is the same
assert (
True,
{0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8},
) == Molecule.are_isomorphic(canonical_ethanol, ethanol, True)
@requires_rdkit
def test_canonical_ordering_rdkit(self):
"""Make sure molecules are returned in canonical ordering of the RDKit"""
from openff.toolkit.utils.toolkits import RDKitToolkitWrapper
rdkit = RDKitToolkitWrapper()
# get ethanol in canonical order
ethanol = create_ethanol()
# get reversed non canonical ethanol
reversed_ethanol = create_reversed_ethanol()
# get the canonical ordering
canonical_ethanol = reversed_ethanol.canonical_order_atoms(rdkit)
# make sure the mapping between the ethanol and the rdkit ref canonical form is the same
assert (
True,
{0: 2, 1: 0, 2: 1, 3: 8, 4: 3, 5: 4, 6: 5, 7: 6, 8: 7},
) == Molecule.are_isomorphic(canonical_ethanol, ethanol, True)
def test_too_small_remap(self):
"""Make sure remap fails if we do not supply enough indexes"""
ethanol = Molecule.from_file(get_data_file_path("molecules/ethanol.sdf"))
# catch mappings that are the wrong size
too_small_mapping = {0: 1}
with pytest.raises(ValueError):
new_ethanol = ethanol.remap(too_small_mapping, current_to_new=True)
def test_wrong_index_mapping(self):
"""Make sure the remap fails when the indexing starts from the wrong value"""
ethanol = Molecule.from_file(get_data_file_path("molecules/ethanol.sdf"))
mapping = {0: 2, 1: 1, 2: 0, 3: 6, 4: 7, 5: 8, 6: 4, 7: 5, 8: 3}
wrong_index_mapping = dict(
(i + 10, new_id) for i, new_id in enumerate(mapping.values())
)
with pytest.raises(IndexError):
new_ethanol = ethanol.remap(wrong_index_mapping, current_to_new=True)
tautomer_data = [
{"molecule": "Oc1c(cccc3)c3nc2ccncc12", "tautomers": 2},
{"molecule": "CN=c1nc[nH]cc1", "tautomers": 2},
{"molecule": "c1[nH]c2c(=O)[nH]c(nc2n1)N", "tautomers": 14},
]
@pytest.mark.parametrize(
"toolkit_class", [OpenEyeToolkitWrapper, RDKitToolkitWrapper]
)
@pytest.mark.parametrize("molecule_data", tautomer_data)
def test_enumerating_tautomers(self, molecule_data, toolkit_class):
"""Test the ability of each toolkit to produce tautomers of an input molecule."""
if toolkit_class.is_available():
toolkit = toolkit_class()
mol = Molecule.from_smiles(
molecule_data["molecule"],
allow_undefined_stereo=True,
toolkit_registry=toolkit,
)
tautomers = mol.enumerate_tautomers(toolkit_registry=toolkit)
assert len(tautomers) == molecule_data["tautomers"]
assert mol not in tautomers
# check that the molecules are not isomorphic of the input
for taut in tautomers:
assert taut.n_conformers == 0
assert mol.is_isomorphic_with(taut) is False
else:
pytest.skip("Required toolkit is unavailable")
@pytest.mark.parametrize(
"toolkit_class", [OpenEyeToolkitWrapper, RDKitToolkitWrapper]
)
def test_enumerating_tautomers_options(self, toolkit_class):
"""Test the enumeration options"""
if toolkit_class.is_available():
toolkit = toolkit_class()
# test the max molecules option
mol = Molecule.from_smiles(
"c1[nH]c2c(=O)[nH]c(nc2n1)N",
toolkit_registry=toolkit,
allow_undefined_stereo=True,
)
tauts_no = 5
tautomers = mol.enumerate_tautomers(
max_states=tauts_no, toolkit_registry=toolkit
)
assert len(tautomers) <= tauts_no
assert mol not in tautomers
@pytest.mark.parametrize(
"toolkit_class", [RDKitToolkitWrapper, OpenEyeToolkitWrapper]
)
def test_enumerating_no_tautomers(self, toolkit_class):
"""Test that the toolkits return an empty list if there are no tautomers to enumerate."""
if toolkit_class.is_available():
toolkit = toolkit_class()
mol = Molecule.from_smiles("CC", toolkit_registry=toolkit)
tautomers = mol.enumerate_tautomers(toolkit_registry=toolkit)
assert tautomers == []
else:
pytest.skip("Required toolkit is unavailable")
@requires_openeye
def test_enumerating_no_protomers(self):
"""Make sure no protomers are returned."""
mol = Molecule.from_smiles("CC")
assert mol.enumerate_protomers() == []
@requires_openeye
def test_enumerating_protomers(self):
"""Test enumerating the formal charges."""
mol = Molecule.from_smiles("Oc2ccc(c1ccncc1)cc2")
# there should be three protomers for this molecule so restrict the output
protomers = mol.enumerate_protomers(max_states=2)
assert mol not in protomers
assert len(protomers) == 2
# now make sure we can generate them all
protomers = mol.enumerate_protomers(max_states=10)
assert mol not in protomers
assert len(protomers) == 3
# make sure each protomer is unique
unique_protomers = set(protomers)
assert len(protomers) == len(unique_protomers)
@pytest.mark.parametrize(
"toolkit_class", [OpenEyeToolkitWrapper, RDKitToolkitWrapper]
)
def test_enumerating_stereobonds(self, toolkit_class):
"""Test the backend toolkits in enumerating the stereo bonds in a molecule."""
if toolkit_class.is_available():
toolkit = toolkit_class()
mol = Molecule.from_smiles(
"ClC=CCl", allow_undefined_stereo=True, toolkit_registry=toolkit
)
# use the default options
isomers = mol.enumerate_stereoisomers()
assert len(isomers) == 2
assert mol not in isomers
# make sure the input molecule is only different by bond stereo
for ismol in isomers:
assert (
Molecule.are_isomorphic(
mol,
ismol,
return_atom_map=False,
bond_stereochemistry_matching=False,
)[0]
is True
)
assert mol.is_isomorphic_with(ismol) is False
# make sure the isomers are different
assert isomers[0].is_isomorphic_with(isomers[1]) is False
else:
pytest.skip("Required toolkit is unavailable")
@pytest.mark.parametrize(
"toolkit_class", [OpenEyeToolkitWrapper, RDKitToolkitWrapper]
)
def test_enumerating_stereocenters(self, toolkit_class):
"""Test the backend toolkits in enumerating the stereo centers in a molecule."""
if toolkit_class.is_available():
toolkit = toolkit_class()
mol = Molecule.from_smiles(
"NC(Cl)(F)O", toolkit_registry=toolkit, allow_undefined_stereo=True
)
isomers = mol.enumerate_stereoisomers(toolkit_registry=toolkit)
assert len(isomers) == 2
# make sure the mol is not in the isomers and that they only differ by stereo chem
assert mol not in isomers
for ismol in isomers:
assert ismol.n_conformers != 0
assert (
Molecule.are_isomorphic(
mol,
ismol,
return_atom_map=False,
atom_stereochemistry_matching=False,
)[0]
is True
)
assert mol.is_isomorphic_with(ismol) is False
# make sure the two isomers are different
assert isomers[0].is_isomorphic_with(isomers[1]) is False
else:
pytest.skip("Required toolkit is unavailable")
@pytest.mark.parametrize(
"toolkit_class", [OpenEyeToolkitWrapper, RDKitToolkitWrapper]
)
def test_enumerating_stereo_options(self, toolkit_class):
"""Test the enumerating stereo chem options"""
if toolkit_class.is_available():
toolkit = toolkit_class()
# test undefined only
mol = Molecule.from_smiles(
"ClC=CCl", toolkit_registry=toolkit, allow_undefined_stereo=True
)
isomers = mol.enumerate_stereoisomers(
undefined_only=True, rationalise=False
)
assert len(isomers) == 2
for isomer in isomers:
assert isomer.n_conformers == 0
mol = Molecule.from_smiles(
"Cl/C=C\Cl", toolkit_registry=toolkit, allow_undefined_stereo=True
)
isomers = mol.enumerate_stereoisomers(
undefined_only=True, rationalise=False
)
assert isomers == []
mol = Molecule.from_smiles(
"Cl/C=C\Cl", toolkit_registry=toolkit, allow_undefined_stereo=True
)
isomers = mol.enumerate_stereoisomers(
undefined_only=False, rationalise=False
)
assert len(isomers) == 1
# test max isomers
mol = Molecule.from_smiles(
"BrC=C[C@H]1OC(C2)(F)C2(Cl)C1",
toolkit_registry=toolkit,
allow_undefined_stereo=True,
)
isomers = mol.enumerate_stereoisomers(
max_isomers=5,
undefined_only=True,
toolkit_registry=toolkit,
rationalise=True,
)
assert len(isomers) <= 5
for isomer in isomers:
assert isomer.n_conformers == 1
else:
pytest.skip("Required toolkit is unavailable")
@pytest.mark.parametrize(
"toolkit_class", [OpenEyeToolkitWrapper, RDKitToolkitWrapper]
)
@pytest.mark.parametrize(
"smiles, undefined_only, expected",
[
(
"FC(Br)(Cl)[C@@H](Br)(Cl)",
False,
[
"F[C@](Br)(Cl)[C@@H](Br)(Cl)",
"F[C@](Br)(Cl)[C@H](Br)(Cl)",
"F[C@@](Br)(Cl)[C@@H](Br)(Cl)",
"F[C@@](Br)(Cl)[C@H](Br)(Cl)",
],
),
(
"FC(Br)(Cl)[C@@H](Br)(Cl)",
True,
["F[C@](Br)(Cl)[C@@H](Br)(Cl)", "F[C@@](Br)(Cl)[C@@H](Br)(Cl)"],
),
("F[C@H](Cl)Br", False, ["F[C@@H](Cl)Br"]),
("F[C@H](Cl)Br", True, []),
],
)
def test_enumerating_stereo_partially_defined(
self, toolkit_class, smiles, undefined_only, expected
):
"""Test the enumerating stereo of molecules with partially defined chirality"""
if not toolkit_class.is_available():
pytest.skip("Required toolkit is unavailable")
toolkit = toolkit_class()
# test undefined only
mol = Molecule.from_smiles(
smiles, toolkit_registry=toolkit, allow_undefined_stereo=True
)
stereoisomers = mol.enumerate_stereoisomers(
undefined_only=undefined_only, rationalise=False
)
# Ensure that the results of the enumeration are what the test expects.
# This roundtrips the expected output from SMILES --> OFFMol --> SMILES,
# since the SMILES for stereoisomers generated in this test may change depending
# on which cheminformatics toolkit is used.
expected = {
Molecule.from_smiles(stereoisomer, allow_undefined_stereo=True).to_smiles(
explicit_hydrogens=True, isomeric=True, mapped=False
)
for stereoisomer in expected
}
actual = {
stereoisomer.to_smiles(explicit_hydrogens=True, isomeric=True, mapped=False)
for stereoisomer in stereoisomers
}
assert expected == actual
@requires_rdkit
def test_from_pdb_and_smiles(self):
"""Test the ability to make a valid molecule using RDKit and SMILES together"""
# try and make a molecule from a pdb and smiles that don't match
with pytest.raises(InvalidConformerError):
mol = Molecule.from_pdb_and_smiles(
get_data_file_path("molecules/toluene.pdb"), "CC"
)
# make a molecule from the toluene pdb file and the correct smiles
mol = Molecule.from_pdb_and_smiles(
get_data_file_path("molecules/toluene.pdb"), "Cc1ccccc1"
)
# make toluene from the sdf file
mol_sdf = Molecule.from_file(get_data_file_path("molecules/toluene.sdf"))
# get the mapping between them and compare the properties
isomorphic, atom_map = Molecule.are_isomorphic(
mol, mol_sdf, return_atom_map=True
)
assert isomorphic is True
for pdb_atom, sdf_atom in atom_map.items():
assert mol.atoms[pdb_atom].to_dict() == mol_sdf.atoms[sdf_atom].to_dict()
# check bonds match, however there order might not
sdf_bonds = dict(
((bond.atom1_index, bond.atom2_index), bond) for bond in mol_sdf.bonds
)
for bond in mol.bonds:
key = (atom_map[bond.atom1_index], atom_map[bond.atom2_index])
if key not in sdf_bonds:
key = tuple(reversed(key))
assert key in sdf_bonds
# now compare the attributes
assert bond.is_aromatic == sdf_bonds[key].is_aromatic
assert bond.stereochemistry == sdf_bonds[key].stereochemistry
@requires_pkg("qcportal")
def test_to_qcschema(self):
"""Test the ability to make and validate qcschema with extras"""
# the molecule has no coordinates so this should fail
ethanol = Molecule.from_smiles("CCO")
with pytest.raises(InvalidConformerError):
qcschema = ethanol.to_qcschema()
# now remake the molecule from the sdf
ethanol = Molecule.from_file(get_data_file_path("molecules/ethanol.sdf"))
# make sure that requests to missing conformers are caught
with pytest.raises(InvalidConformerError):
qcschema = ethanol.to_qcschema(conformer=1)
# now make a valid qcschema and check its properties
qcschema = ethanol.to_qcschema(extras={"test_tag": "test"})
# make sure the properties match
charge = 0
connectivity = [
(0, 1, 1.0),
(0, 4, 1.0),
(0, 5, 1.0),
(0, 6, 1.0),
(1, 2, 1.0),
(1, 7, 1.0),
(1, 8, 1.0),
(2, 3, 1.0),
]
symbols = ["C", "C", "O", "H", "H", "H", "H", "H", "H"]
def assert_check():
assert charge == qcschema.molecular_charge
assert connectivity == qcschema.connectivity
assert symbols == qcschema.symbols.tolist()
assert (
qcschema.geometry.all()
== ethanol.conformers[0].in_units_of(unit.bohr).all()
)
assert_check()
assert qcschema.extras["test_tag"] == "test"
assert qcschema.extras[
"canonical_isomeric_explicit_hydrogen_mapped_smiles"
] == ethanol.to_smiles(mapped=True)
# # now run again with no extras passed, only cmiles entry will be present with fix-720
qcschema = ethanol.to_qcschema()
assert_check()
assert qcschema.extras[
"canonical_isomeric_explicit_hydrogen_mapped_smiles"
] == ethanol.to_smiles(mapped=True)
@requires_pkg("qcportal")
def test_to_qcschema_no_connections(self):
mol = Molecule.from_mapped_smiles("[Br-:1].[K+:2]")
mol.add_conformer(
unit.Quantity(
np.array(
[[0.188518, 0.015684, 0.001562], [0.148794, 0.21268, 0.11992]]
),
unit.nanometers,
)
)
qcschema = mol.to_qcschema()
assert qcschema.connectivity is None
@requires_pkg("qcportal")
def test_from_qcschema_no_client(self):
"""Test the ability to make molecules from QCArchive record instances and dicts"""
import json
# As the method can take a record instance or a dict with JSON encoding test both
# test incomplete dict
example_dict = {"name": "CH4"}
with pytest.raises(KeyError):
mol = Molecule.from_qcschema(example_dict)
# test an object that is not a record
wrong_object = "CH4"
with pytest.raises(AttributeError):
mol = Molecule.from_qcschema(wrong_object)
with open(get_data_file_path("molecules/qcportal_molecules.json")) as json_file:
# test loading the dict representation from a json file
json_mol = json.load(json_file)
mol = Molecule.from_qcschema(json_mol)
# now make a molecule from the canonical smiles and make sure they are isomorphic
can_mol = Molecule.from_smiles(
json_mol["attributes"]["canonical_isomeric_smiles"]
)
assert mol.is_isomorphic_with(can_mol) is True
client_examples = [
{
"dataset": "TorsionDriveDataset",
"name": "Fragment Stability Benchmark",
"index": "CC(=O)Nc1cc2c(cc1OC)nc[n:4][c:3]2[NH:2][c:1]3ccc(c(c3)Cl)F",
},
{
"dataset": "TorsionDriveDataset",
"name": "OpenFF Fragmenter Phenyl Benchmark",
"index": "c1c[ch:1][c:2](cc1)[c:3](=[o:4])o",
},
{
"dataset": "TorsionDriveDataset",
"name": "OpenFF Full TorsionDrive Benchmark 1",
"index": "0",
},
{
"dataset": "TorsionDriveDataset",
"name": "OpenFF Group1 Torsions",
"index": "c1c[ch:1][c:2](cc1)[ch2:3][c:4]2ccccc2",
},
{
"dataset": "OptimizationDataset",
"name": "Kinase Inhibitors: WBO Distributions",
"index": "cc1ccc(cc1nc2nccc(n2)c3cccnc3)nc(=o)c4ccc(cc4)cn5ccn(cc5)c-0",
},
{
"dataset": "OptimizationDataset",
"name": "SMIRNOFF Coverage Set 1",
"index": "coc(o)oc-0",
},
{
"dataset": "GridOptimizationDataset",
"name": "OpenFF Trivalent Nitrogen Set 1",
"index": "b1(c2c(ccs2)-c3ccsc3n1)c4c(c(c(c(c4f)f)f)f)f",
},
{
"dataset": "GridOptimizationDataset",
"name": "OpenFF Trivalent Nitrogen Set 1",
"index": "C(#N)N",
},
]
@requires_pkg("qcportal")
@pytest.mark.parametrize("input_data", client_examples)
def test_from_qcschema_with_client(self, input_data):
"""For each of the examples try and make a offmol using the instance and dict and check they match"""
import qcportal as ptl
client = ptl.FractalClient()
ds = client.get_collection(input_data["dataset"], input_data["name"])
entry = ds.get_entry(input_data["index"])
# now make the molecule from the record instance with and without the geometry
mol_from_dict = Molecule.from_qcschema(entry.dict(encoding="json"))
# make the molecule again with the geometries attached
mol_from_instance = Molecule.from_qcschema(entry, client)
if hasattr(entry, "initial_molecules"):
assert mol_from_instance.n_conformers == len(entry.initial_molecules)
else:
# opt records have one initial molecule
assert mol_from_instance.n_conformers == 1
# now make a molecule from the smiles and make sure they are isomorphic
mol_from_smiles = Molecule.from_smiles(
entry.attributes["canonical_explicit_hydrogen_smiles"], True
)
assert mol_from_dict.is_isomorphic_with(mol_from_smiles) is True
@requires_pkg("qcportal")
def test_qcschema_round_trip(self):
"""Test making a molecule from qcschema then converting back
Checking whether qca_mol and mol created from/to qcschema are the same or not"""
# get a molecule qcschema
import qcportal as ptl
client = ptl.FractalClient()
ds = client.get_collection("OptimizationDataset", "SMIRNOFF Coverage Set 1")
# grab an entry from the optimization data set
entry = ds.get_entry("coc(o)oc-0")
# now make the molecule from the record instance with the geometry
mol = Molecule.from_qcschema(entry, client)
# now grab the initial molecule record
qca_mol = client.query_molecules(id=entry.initial_molecule)[0]
# mow make sure the majority of the qcschema attributes are the same
# note we can not compare the full dict due to qcelemental differences
qcschema = mol.to_qcschema()
assert qcschema.atom_labels.tolist() == qca_mol.atom_labels.tolist()
assert qcschema.symbols.tolist() == qca_mol.symbols.tolist()
# due to conversion using different programs there is a slight difference here
assert qcschema.geometry.flatten().tolist() == pytest.approx(
qca_mol.geometry.flatten().tolist(), rel=1.0e-5
)
assert qcschema.connectivity == qca_mol.connectivity
assert qcschema.atomic_numbers.tolist() == qca_mol.atomic_numbers.tolist()
assert qcschema.fragment_charges == qca_mol.fragment_charges
assert qcschema.fragment_multiplicities == qca_mol.fragment_multiplicities
assert qcschema.fragments[0].tolist() == qca_mol.fragments[0].tolist()
assert qcschema.mass_numbers.tolist() == qca_mol.mass_numbers.tolist()
assert qcschema.name == qca_mol.name
assert qcschema.masses.all() == qca_mol.masses.all()
assert qcschema.molecular_charge == qca_mol.molecular_charge
assert qcschema.molecular_multiplicity == qca_mol.molecular_multiplicity
assert qcschema.real.all() == qca_mol.real.all()
@requires_pkg("qcportal")
def test_qcschema_round_trip_from_to_from(self):
"""Test making a molecule from qca record using from_qcschema,
then converting back to qcschema using to_qcschema,
and then reading that again using from_qcschema"""
# get a molecule qcschema
import qcportal as ptl
client = ptl.FractalClient()
ds = client.get_collection(
"TorsionDriveDataset", "OpenFF-benchmark-ligand-fragments-v1.0"
)
# grab an entry from the torsiondrive data set
entry = ds.get_entry(
"[H]c1[c:1]([c:2](c(c(c1[H])N([H])C(=O)[H])[H])[C:3]2=C(C(=C([S:4]2)[H])OC([H])([H])[H])Br)[H]"
)
# now make the molecule from the record instance with the geometry
mol_qca_record = Molecule.from_qcschema(entry, client)
off_qcschema = mol_qca_record.to_qcschema()
mol_using_from_off_qcschema = Molecule.from_qcschema(off_qcschema)
assert_molecule_is_equal(
mol_qca_record,
mol_using_from_off_qcschema,
"Molecule roundtrip to/from_qcschema failed",
)
@requires_pkg("qcportal")
def test_qcschema_round_trip_raise_error(self):
"""Test making a molecule from qcschema,
reaching inner except block where everything fails"""
# get a molecule qcschema
import qcportal as ptl
client = ptl.FractalClient()
ds = client.get_collection(
"TorsionDriveDataset", "OpenFF-benchmark-ligand-fragments-v1.0"
)
# grab an entry from the torsiondrive data set
entry = ds.get_entry(
"[H]c1[c:1]([c:2](c(c(c1[H])N([H])C(=O)[H])[H])[C:3]2=C(C(=C([S:4]2)[H])OC([H])([H])[H])Br)[H]"
)
del entry.attributes["canonical_isomeric_explicit_hydrogen_mapped_smiles"]
# now make the molecule from the record instance with the geometry
with pytest.raises(KeyError):
mol_qca_record = Molecule.from_qcschema(entry, client)
@requires_pkg("qcportal")
def test_qcschema_molecule_record_round_trip_from_to_from(self):
"""Test making a molecule from qca record using from_qcschema,
then converting back to qcschema using to_qcschema,
and then reading that again using from_qcschema"""
# get a molecule qcschema
import qcportal as ptl
client = ptl.FractalClient()
record = client.query_molecules(molecular_formula="C16H20N3O5")[0]
# now make the molecule from the record instance with the geometry
mol_qca_record = Molecule.from_qcschema(record, client)
off_qcschema = mol_qca_record.to_qcschema()
mol_using_from_off_qcschema = Molecule.from_qcschema(off_qcschema)
assert_molecule_is_equal(
mol_qca_record,
mol_using_from_off_qcschema,
"Molecule roundtrip to/from_qcschema failed",
)
def test_from_mapped_smiles(self):
"""Test making the molecule from issue #412 using both toolkits to ensure the issue
is fixed."""
# there should be no undefined sterochmeistry error when making the molecule
mol = Molecule.from_mapped_smiles(
"[H:14][c:1]1[c:3]([c:7]([c:11]([c:8]([c:4]1[H:17])[H:21])[C:13]([H:24])([H:25])[c:12]2[c:9]([c:5]([c:2]([c:6]([c:10]2[H:23])[H:19])[H:15])[H:18])[H:22])[H:20])[H:16]"
)
assert mol.n_atoms == 25
# make sure the atom map is not exposed
with pytest.raises(KeyError):
mapping = mol._properties["atom_map"]
@pytest.mark.parametrize(
"toolkit_class", [OpenEyeToolkitWrapper, RDKitToolkitWrapper]
)
def test_from_mapped_smiles_partial(self, toolkit_class):
"""Test that creating a molecule from a partially mapped SMILES raises an
exception."""
if not (toolkit_class.is_available()):
pytest.skip(f"Required toolkit {toolkit_class} is unavailable")
with pytest.raises(
SmilesParsingError,
match="The mapped smiles does not contain enough indexes",
):
Molecule.from_mapped_smiles("[Cl:1][Cl]", toolkit_registry=toolkit_class())
@pytest.mark.parametrize("molecule", mini_drug_bank())
def test_n_particles(self, molecule):
"""Test n_particles property"""
n_particles = sum([1 for particle in molecule.particles])
assert n_particles == molecule.n_particles
@pytest.mark.parametrize("molecule", mini_drug_bank())
def test_n_atoms(self, molecule):
"""Test n_atoms property"""
n_atoms = sum([1 for atom in molecule.atoms])
assert n_atoms == molecule.n_atoms
@pytest.mark.parametrize("molecule", mini_drug_bank())
def test_n_virtual_sites(self, molecule):
"""Test n_virtual_sites property"""
n_virtual_sites = sum([1 for virtual_site in molecule.virtual_sites])
assert n_virtual_sites == molecule.n_virtual_sites
@pytest.mark.parametrize("molecule", mini_drug_bank())
def test_n_bonds(self, molecule):
"""Test n_bonds property"""
n_bonds = sum([1 for bond in molecule.bonds])
assert n_bonds == molecule.n_bonds
@pytest.mark.parametrize("molecule", mini_drug_bank())
def test_angles(self, molecule):
"""Test angles property"""
for angle in molecule.angles:
assert angle[0].is_bonded_to(angle[1])
assert angle[1].is_bonded_to(angle[2])
@pytest.mark.parametrize("molecule", mini_drug_bank())
def test_propers(self, molecule):
"""Test propers property"""
for proper in molecule.propers:
# The bonds should be in order 0-1-2-3 unless the
# atoms form a three- or four-membered ring.
is_chain = proper[0].is_bonded_to(proper[1])
is_chain &= proper[1].is_bonded_to(proper[2])
is_chain &= proper[2].is_bonded_to(proper[3])
is_chain &= not proper[0].is_bonded_to(proper[2])
is_chain &= not proper[0].is_bonded_to(proper[3])
is_chain &= not proper[1].is_bonded_to(proper[3])
assert (
is_chain
or is_three_membered_ring_torsion(proper)
or is_four_membered_ring_torsion(proper)
)
@pytest.mark.parametrize("molecule", mini_drug_bank())
def test_impropers(self, molecule):
"""Test impropers property"""
for improper in molecule.impropers:
assert improper[0].is_bonded_to(improper[1])
assert improper[1].is_bonded_to(improper[2])
assert improper[1].is_bonded_to(improper[3])
# The non-central atoms can be connected only if
# the improper atoms form a three-membered ring.
is_not_cyclic = not (
(improper[0].is_bonded_to(improper[2]))
or (improper[0].is_bonded_to(improper[3]))
or (improper[2].is_bonded_to(improper[3]))
)
assert is_not_cyclic or is_three_membered_ring_torsion(improper)
@pytest.mark.parametrize(
("molecule", "n_impropers", "n_pruned"),
[
("C", 24, 0),
("CC", 48, 0),
("N", 6, 6),
],
)
def test_pruned_impropers(self, molecule, n_impropers, n_pruned):
"""Test the amber_impropers and smirnoff_impropers properties"""
mol = Molecule.from_smiles(molecule)
assert mol.n_impropers == n_impropers
assert len(mol.smirnoff_impropers) == n_pruned
assert len(mol.amber_impropers) == n_pruned
# Order not guaranteed, so cannot zip and compare directly
for smirnoff_imp in mol.smirnoff_impropers:
# Convert SMIRNOFF-style improper into AMBER-style
mod_imp = (
smirnoff_imp[1],
smirnoff_imp[0],
smirnoff_imp[2],
smirnoff_imp[3],
)
assert mod_imp in mol.amber_impropers
@pytest.mark.parametrize("molecule", mini_drug_bank())
def test_torsions(self, molecule):
"""Test torsions property"""
# molecule.torsions should be exactly equal to the union of propers and impropers.
assert set(molecule.torsions) == set(molecule.propers) | set(molecule.impropers)
# The intersection of molecule.propers and molecule.impropers should be largely null.
# The only exception is for molecules containing 3-membered rings (e.g., DrugBank_5514).
common_torsions = molecule.propers & molecule.impropers
if len(common_torsions) > 0:
for torsion in common_torsions:
assert is_three_membered_ring_torsion(torsion)
def test_nth_degree_neighbors_basic(self):
benzene = Molecule.from_smiles("c1ccccc1")
with pytest.raises(ValueError, match="0 or fewer atoms"):
benzene.nth_degree_neighbors(n_degrees=0)
with pytest.raises(ValueError, match="0 or fewer atoms"):
benzene.nth_degree_neighbors(n_degrees=-1)
# 3 proper torsions have 1-4 pairs that are duplicates of other torsions, i.e.
# torsions 0-1-2-3 0-5-4-3 where #s are the indices of carbons in the ring
n_14_pairs = len([*benzene.nth_degree_neighbors(n_degrees=3)])
assert n_14_pairs == benzene.n_propers - 3
for pair in benzene.nth_degree_neighbors(n_degrees=3):
assert pair[0].molecule_particle_index < pair[1].molecule_particle_index
@pytest.mark.parametrize(
("smiles", "n_degrees", "num_pairs"),
[
("c1ccccc1", 6, 0),
("c1ccccc1", 5, 3),
("c1ccccc1", 4, 12),
("c1ccccc1", 3, 21),
("N1ONON1", 4, 2),
("N1ONON1", 3, 7),
("C1#CO1", 2, 0),
("C1#CO1", 1, 3),
("C1CO1", 4, 0),
("C1CO1", 2, 10),
("C1=C=C=C=1", 4, 0),
("C1=C=C=C=1", 3, 0),
("C1=C=C=C=1", 2, 2),
],
)
def test_nth_degree_neighbors_rings(self, smiles, n_degrees, num_pairs):
molecule = Molecule.from_smiles(smiles)
num_pairs_found = len([*molecule.nth_degree_neighbors(n_degrees=n_degrees)])
assert num_pairs_found == num_pairs
@pytest.mark.parametrize("molecule", mini_drug_bank())
def test_total_charge(self, molecule):
"""Test total charge"""
charge_sum = 0 * unit.elementary_charge
for atom in molecule.atoms:
charge_sum += atom.formal_charge
assert charge_sum == molecule.total_charge
# ----------------------------------------------------
# Test magic methods.
# ----------------------------------------------------
def test_equality(self):
"""Test equality operator"""
molecules = mini_drug_bank()
nmolecules = len(molecules)
# TODO: Performance improvements should let us un-restrict this test
for i in range(nmolecules):
for j in range(i, min(i + 3, nmolecules)):
assert (molecules[i] == molecules[j]) == (i == j)
# ----------------------
# Test Molecule methods.
# ----------------------
def test_add_conformers(self):
"""Test addition of conformers to a molecule"""
# Define a methane molecule
molecule = Molecule()
molecule.name = "methane"
C = molecule.add_atom(6, 0, False)
H1 = molecule.add_atom(1, 0, False)
H2 = molecule.add_atom(1, 0, False)
H3 = molecule.add_atom(1, 0, False)
H4 = molecule.add_atom(1, 0, False)
molecule.add_bond(C, H1, 1, False)
molecule.add_bond(C, H2, 1, False)
molecule.add_bond(C, H3, 1, False)
molecule.add_bond(C, H4, 1, False)
assert molecule.n_conformers == 0
# Add a conformer that should work
conf1 = unit.Quantity(
np.array(
[
[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0],
[7.0, 8.0, 9.0],
[10.0, 11.0, 12.0],
[13.0, 14.0, 15],
]
),
unit.angstrom,
)
molecule.add_conformer(conf1)
assert molecule.n_conformers == 1
conf2 = unit.Quantity(
np.array(
[
[101.0, 102.0, 103.0],
[104.0, 105.0, 106.0],
[107.0, 108.0, 109.0],
[110.0, 111.0, 112.0],
[113.0, 114.0, 115],
]
),
unit.angstrom,
)
molecule.add_conformer(conf2)
assert molecule.n_conformers == 2
# Add conformers with too few coordinates
conf_missing_z = unit.Quantity(
np.array(
[
[101.0, 102.0, 103.0],
[104.0, 105.0, 106.0],
[107.0, 108.0, 109.0],
[110.0, 111.0, 112.0],
[113.0, 114.0],
]
),
unit.angstrom,
)
with pytest.raises(Exception) as excinfo:
molecule.add_conformer(conf_missing_z)
conf_too_few_atoms = unit.Quantity(
np.array(
[
[101.0, 102.0, 103.0],
[104.0, 105.0, 106.0],
[107.0, 108.0, 109.0],
[110.0, 111.0, 112.0],
]
),
unit.angstrom,
)
with pytest.raises(Exception) as excinfo:
molecule.add_conformer(conf_too_few_atoms)
# Add a conformer with too many coordinates
conf_too_many_atoms = unit.Quantity(
np.array(
[
[101.0, 102.0, 103.0],
[104.0, 105.0, 106.0],
[107.0, 108.0, 109.0],
[110.0, 111.0, 112.0],
[113.0, 114.0, 115.0],
[116.0, 117.0, 118.0],
]
),
unit.angstrom,
)
with pytest.raises(Exception) as excinfo:
molecule.add_conformer(conf_too_many_atoms)
# Add a conformer with no coordinates
conf_no_coordinates = unit.Quantity(np.array([]), unit.angstrom)
with pytest.raises(Exception) as excinfo:
molecule.add_conformer(conf_no_coordinates)
# Add a conforer with units of nanometers
conf3 = unit.Quantity(
np.array(
[
[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0],
[7.0, 8.0, 9.0],
[10.0, 11.0, 12.0],
[13.0, 14.0, 15],
]
),
unit.nanometer,
)
molecule.add_conformer(conf3)
assert molecule.n_conformers == 3
assert molecule.conformers[2][0][0] == 10.0 * unit.angstrom
# Add a conformer with units of nanometers
conf_nonsense_units = unit.Quantity(
np.array(
[
[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0],
[7.0, 8.0, 9.0],
[10.0, 11.0, 12.0],
[13.0, 14.0, 15],
]
),
unit.joule,
)
with pytest.raises(Exception) as excinfo:
molecule.add_conformer(conf_nonsense_units)
# Add a conformer with no units
conf_unitless = np.array(
[
[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0],
[7.0, 8.0, 9.0],
[10.0, 11.0, 12.0],
[13.0, 14.0, 15],
]
)
with pytest.raises(Exception) as excinfo:
molecule.add_conformer(conf_unitless)
@pytest.mark.parametrize("molecule", mini_drug_bank())
def test_add_atoms_and_bonds(self, molecule):
"""Test the creation of a molecule from the addition of atoms and bonds"""
molecule_copy = Molecule()
for atom in molecule.atoms:
molecule_copy.add_atom(
atom.atomic_number,
atom.formal_charge,
atom.is_aromatic,
stereochemistry=atom.stereochemistry,
)
for bond in molecule.bonds:
molecule_copy.add_bond(
bond.atom1_index,
bond.atom2_index,
bond.bond_order,
bond.is_aromatic,
stereochemistry=bond.stereochemistry,
fractional_bond_order=bond.fractional_bond_order,
)
# Try to add the final bond twice, which should raise an Exception
with pytest.raises(Exception) as excinfo:
molecule_copy.add_bond(
bond.atom1_index,
bond.atom2_index,
bond.bond_order,
bond.is_aromatic,
stereochemistry=bond.stereochemistry,
fractional_bond_order=bond.fractional_bond_order,
)
assert molecule == molecule_copy
@pytest.mark.parametrize("molecule", mini_drug_bank())
def test_add_virtual_site_units(self, molecule):
"""
Tests the unit type checking of the VirtualSite base class
"""
# TODO: Should these be using BondChargeVirtualSite, or should we just call the base class (which does the unit checks) directly?
# Prepare values for unit checks
distance_unitless = 0.4
sigma_unitless = 0.1
rmin_half_unitless = 0.2
epsilon_unitless = 0.3
charge_increments_unitless = [0.1, 0.2]
distance = distance_unitless * unit.angstrom
sigma = sigma_unitless * unit.angstrom
rmin_half = rmin_half_unitless * unit.angstrom
epsilon = epsilon_unitless * (unit.kilojoule / unit.mole)
charge_increments = charge_increments_unitless * unit.elementary_charge
# Do not modify the original molecule.
molecule = copy.deepcopy(molecule)
atom1 = molecule.atoms[0]
atom2 = molecule.atoms[1]
atom3 = molecule.atoms[2]
atom4 = molecule.atoms[3]
atoms = (atom1, atom2)
# Try to feed in unitless sigma
with pytest.raises(Exception) as excinfo:
molecule.add_bond_charge_virtual_site(
atoms, distance, epsilon=epsilon, sigma=sigma_unitless, replace=True
)
# Try to feed in unitless rmin_half
with pytest.raises(Exception) as excinfo:
molecule.add_bond_charge_virtual_site(
atoms,
distance,
epsilon=epsilon,
rmin_half=rmin_half_unitless,
replace=True,
)
# Try to feed in unitless epsilon
with pytest.raises(Exception) as excinfo:
molecule.add_bond_charge_virtual_site(
atoms,
distance,
epsilon=epsilon_unitless,
sigma=sigma,
rmin_half=rmin_half,
replace=True,
)
# Try to feed in unitless charges
with pytest.raises(Exception) as excinfo:
molecule.add_bond_charge_virtual_site(
atoms,
distance,
charge_incrtements=charge_increments_unitless,
replace=True,
)
# We shouldn't be able to give both rmin_half and sigma VdW parameters.
with pytest.raises(Exception) as excinfo:
molecule.add_bond_charge_virtual_site(
[atom1, atom2],
distance,
epsilon=epsilon,
sigma=sigma,
rmin_half=rmin_half,
replace=True,
)
# Try creating virtual site from sigma+epsilon; replace=False since this
# should be the first vsite to succeed
vsite1_index = molecule.add_bond_charge_virtual_site(
atoms, distance, epsilon=epsilon, sigma=sigma, replace=False
)
# Try creating virutal site from rmin_half+epsilon
vsite2_index = molecule.add_bond_charge_virtual_site(
atoms, distance, epsilon=epsilon, rmin_half=rmin_half, replace=True
)
# TODO: Test the @property getters for sigma, epsilon, and rmin_half
# We should have to give as many charge increments as atoms (len(charge_increments)) = 4
with pytest.raises(Exception) as excinfo:
molecule.add_bond_charge_virtual_site(
atoms, distance, charge_increments=[0.0], replace=True
)
vsite3_index = molecule.add_bond_charge_virtual_site(
atoms, distance, charge_increments=charge_increments, replace=True
)
def test_virtual_particle(self):
"""Test setter, getters, and methods of VirtualParticle"""
mol = create_ethanol()
# Add a SYMMETRIC (default) VirtualSite, which should have two particles
mol.add_bond_charge_virtual_site(
(mol.atoms[1], mol.atoms[2]),
0.5 * unit.angstrom,
charge_increments=[-0.1, 0.1] * unit.elementary_charge,
)
# Add a NON SYMMETRIC (specified in kwarg) VirtualSite, which should have one particle
mol.add_bond_charge_virtual_site(
(mol.atoms[0], mol.atoms[1]),
0.5 * unit.angstrom,
charge_increments=[-0.1, 0.1] * unit.elementary_charge,
symmetric=False,
)
assert len(mol.virtual_sites) == 2
# Ensure the first vsite has two particles
vps0 = [vp for vp in mol.virtual_sites[0].particles]
assert len(vps0) == 2
assert vps0[0].virtual_site_particle_index == 0
assert vps0[1].virtual_site_particle_index == 1
orientations0 = [vp.orientation for vp in vps0]
assert len(set(orientations0) & {(0, 1), (1, 0)}) == 2
# Ensure the second vsite has one particle
vps1 = [vp for vp in mol.virtual_sites[1].particles]
assert len(vps1) == 1
assert vps1[0].virtual_site_particle_index == 0
orientations1 = [vp.orientation for vp in vps1]
assert len(set(orientations1) & {(0, 1)}) == 1
@pytest.mark.parametrize("molecule", mini_drug_bank())
def test_add_bond_charge_virtual_site(self, molecule):
"""Test the addition of a BondChargeVirtualSite to a molecule.
Also tests many of the inputs of the parent VirtualSite class
"""
# Do not modify the original molecule.
molecule = copy.deepcopy(molecule)
atom1 = molecule.atoms[0]
atom2 = molecule.atoms[1]
atom3 = molecule.atoms[2]
atom4 = molecule.atoms[3]
# Prepare values for unit checks
distance_unitless = 0.4
distance = distance_unitless * unit.angstrom
# Try to feed in a unitless distance
with pytest.raises(AssertionError) as excinfo:
vsite1_index = molecule.add_bond_charge_virtual_site(
[atom1, atom2], distance_unitless
)
vsite1_index = molecule.add_bond_charge_virtual_site([atom1, atom2], distance)
vsite1 = molecule.virtual_sites[vsite1_index]
assert atom1 in vsite1.atoms
assert atom2 in vsite1.atoms
assert vsite1 in atom1.virtual_sites
assert vsite1 in atom2.virtual_sites
assert vsite1.distance == distance
# Make a virtual site using all arguments
vsite2_index = molecule.add_bond_charge_virtual_site(
[atom2, atom3],
distance,
sigma=0.1 * unit.angstrom,
epsilon=1.0 * unit.kilojoule_per_mole,
charge_increments=unit.Quantity(
np.array([0.1, 0.2]), unit.elementary_charge
),
)
vsite2 = molecule.virtual_sites[vsite2_index]
assert atom2 in vsite2.atoms
assert atom3 in vsite2.atoms
assert vsite2 in atom2.virtual_sites
assert vsite2 in atom3.virtual_sites
assert vsite2.distance == distance
# test serialization
molecule_dict = molecule.to_dict()
molecule2 = Molecule.from_dict(molecule_dict)
# test that the molecules are the same
assert molecule.is_isomorphic_with(molecule2)
# lets also make sure that the vsites were constructed correctly
for site1, site2 in zip(molecule.virtual_sites, molecule2.virtual_sites):
assert site1.to_dict() == site2.to_dict()
# TODO: Make a test for to_dict and from_dict for VirtualSites (even though they're currently just unloaded using
# (for example) Molecule._add_bond_virtual_site functions
@pytest.mark.parametrize("molecule", mini_drug_bank())
def test_add_monovalent_lone_pair_virtual_site(self, molecule):
"""Test addition of a MonovalentLonePairVirtualSite to the Molecule"""
# Do not modify the original molecule.
molecule = copy.deepcopy(molecule)
atom1 = molecule.atoms[0]
atom2 = molecule.atoms[1]
atom3 = molecule.atoms[2]
atom4 = molecule.atoms[3]
# Prepare values for unit checks
distance_unitless = 0.3
out_of_plane_angle_unitless = 30
in_plane_angle_unitless = 0.2
distance = distance_unitless * unit.angstrom
out_of_plane_angle = out_of_plane_angle_unitless * unit.degree
in_plane_angle = in_plane_angle_unitless * unit.radian
atoms = (atom1, atom2, atom3)
# Try passing in a unitless distance
with pytest.raises(AssertionError) as excinfo:
vsite1_index = molecule.add_monovalent_lone_pair_virtual_site(
atoms,
distance_unitless,
out_of_plane_angle,
in_plane_angle,
replace=True,
)
# Try passing in a unitless out_of_plane_angle
with pytest.raises(AssertionError) as excinfo:
vsite1_index = molecule.add_monovalent_lone_pair_virtual_site(
atoms,
distance,
out_of_plane_angle_unitless,
in_plane_angle,
replace=True,
)
# Try passing in a unitless in_plane_angle
with pytest.raises(AssertionError) as excinfo:
vsite1_index = molecule.add_monovalent_lone_pair_virtual_site(
atoms,
distance,
out_of_plane_angle,
in_plane_angle_unitless,
replace=True,
)
# Try giving two atoms
with pytest.raises(AssertionError) as excinfo:
vsite1_index = molecule.add_monovalent_lone_pair_virtual_site(
[atom1, atom2],
distance,
out_of_plane_angle,
in_plane_angle,
replace=True,
)
# Successfully make a virtual site; throw exception is already present (replace=False)
vsite1_index = molecule.add_monovalent_lone_pair_virtual_site(
atoms, distance, out_of_plane_angle, in_plane_angle, replace=False
)
# TODO: Check if we get the same values back out from the @properties
molecule_dict = molecule.to_dict()
molecule2 = Molecule.from_dict(molecule_dict)
assert molecule.to_dict() == molecule2.to_dict()
@pytest.mark.parametrize("molecule", mini_drug_bank())
def test_add_divalent_lone_pair_virtual_site(self, molecule):
"""Test addition of a DivalentLonePairVirtualSite to the Molecule"""
# Do not modify the original molecule.
molecule = copy.deepcopy(molecule)
atom1 = molecule.atoms[0]
atom2 = molecule.atoms[1]
atom3 = molecule.atoms[2]
atom4 = molecule.atoms[3]
distance = 0.3 * unit.angstrom
out_of_plane_angle = 30 * unit.degree
vsite1_index = molecule.add_divalent_lone_pair_virtual_site(
[atom1, atom2, atom3],
distance,
out_of_plane_angle,
replace=False,
)
# test giving too few atoms
with pytest.raises(AssertionError) as excinfo:
vsite1_index = molecule.add_divalent_lone_pair_virtual_site(
[atom1, atom2],
distance,
out_of_plane_angle,
replace=False,
)
molecule_dict = molecule.to_dict()
molecule2 = Molecule.from_dict(molecule_dict)
assert molecule_dict == molecule2.to_dict()
@pytest.mark.parametrize("molecule", mini_drug_bank())
def test_add_trivalent_lone_pair_virtual_site(self, molecule):
"""Test addition of a TrivalentLonePairVirtualSite to the Molecule"""
# Do not modify the original molecule.
molecule = copy.deepcopy(molecule)
atom1 = molecule.atoms[0]
atom2 = molecule.atoms[1]
atom3 = molecule.atoms[2]
atom4 = molecule.atoms[3]
distance = 0.3 * unit.angstrom
vsite1_index = molecule.add_trivalent_lone_pair_virtual_site(
[atom1, atom2, atom3, atom4],
distance,
replace=False,
)
# Test for assertion when giving too few atoms
with pytest.raises(AssertionError) as excinfo:
vsite1_index = molecule.add_trivalent_lone_pair_virtual_site(
[atom1, atom2, atom3],
distance,
replace=True,
)
molecule_dict = molecule.to_dict()
molecule2 = Molecule.from_dict(molecule_dict)
assert molecule.to_dict() == molecule2.to_dict()
def test_bond_charge_virtual_site_position_symmetric(self):
"""
Test for expected positions of virtual sites when created through the molecule
API. This uses symmetric, which will add both orientations of the atoms to
create two particles for the vsite.
The order of the positions is the same as the order of the particles as they
appear in the molecule using Molecule.particles
"""
import openff.toolkit.tests.test_forcefield
molecule = openff.toolkit.tests.test_forcefield.create_water()
# molecule = create_water()
# a 90 degree water molecule on the xy plane
molecule.add_conformer(
unit.Quantity(
np.array(
[
[1.0, 0.0, 0.0],
[0.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
]
),
unit.angstrom,
)
)
atom1 = molecule.atoms[0]
atom2 = molecule.atoms[1]
distance = 0.1 * unit.angstrom
vsite1_index = molecule.add_bond_charge_virtual_site(
[atom1, atom2],
distance,
replace=False,
symmetric=True,
)
expected = np.array([[1.1, 0.0, 0.0], [-0.1, 0.0, 0.0]])
vsite_pos = molecule.compute_virtual_site_positions_from_conformer(0)
vsite_pos = vsite_pos / vsite_pos.unit
assert vsite_pos.shape == (2, 3)
assert np.allclose(vsite_pos, expected)
conformer = molecule.conformers[0]
vsite_pos = molecule.compute_virtual_site_positions_from_atom_positions(
conformer
)
vsite_pos = vsite_pos / vsite_pos.unit
assert vsite_pos.shape == (2, 3)
assert np.allclose(vsite_pos, expected)
def test_bond_charge_virtual_site_position(self):
"""
Test for expected positions of virtual sites when created through the molecule
API.
The order of the positions is the same as the order of the particles as they
appear in the molecule using Molecule.particles
"""
import openff.toolkit.tests.test_forcefield
molecule = openff.toolkit.tests.test_forcefield.create_water()
# molecule = create_water()
# a 90 degree water molecule on the xy plane
molecule.add_conformer(
unit.Quantity(
np.array(
[
[1.0, 0.0, 0.0],
[0.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
]
),
unit.angstrom,
)
)
atom1 = molecule.atoms[0]
atom2 = molecule.atoms[1]
distance = 0.1 * unit.angstrom
vsite1_index = molecule.add_bond_charge_virtual_site(
[atom1, atom2],
distance,
replace=False,
symmetric=False,
)
expected = np.array([[1.1, 0.0, 0.0]])
vsite_pos = molecule.compute_virtual_site_positions_from_conformer(0)
vsite_pos = vsite_pos / vsite_pos.unit
assert vsite_pos.shape == (1, 3)
assert np.allclose(vsite_pos, expected)
conformer = molecule.conformers[0]
vsite_pos = molecule.compute_virtual_site_positions_from_atom_positions(
conformer
)
vsite_pos = vsite_pos / vsite_pos.unit
assert vsite_pos.shape == (1, 3)
assert np.allclose(vsite_pos, expected)
def test_monovalent_lone_pair_virtual_site_position_symmetric(self):
"""
Test for expected positions of virtual sites when created through the molecule
API. This uses symmetric, which will add both orientations of the atoms to
create two particles for the vsite.
Note: symmetric with Monovalent is a bit counterintuitive. Since the particles
origin is placed on the first atom, using a "symmetric" definition will flip
the ordering, causing another particle to be placed on the third atom, reflected
on the xy plane between the first particle.
The order of the positions is the same as the order of the particles as they
appear in the molecule using Molecule.particles
"""
import openff.toolkit.tests.test_forcefield
molecule = openff.toolkit.tests.test_forcefield.create_water()
# a 90 degree water molecule on the xy plane
molecule.add_conformer(
unit.Quantity(
np.array(
[
[1.0, 0.0, 0.0],
[0.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
]
),
unit.angstrom,
)
)
atom1 = molecule.atoms[0]
atom2 = molecule.atoms[1]
atom3 = molecule.atoms[2]
distance = 0.2 * unit.angstrom
out_of_plane_angle = 90 * unit.degree
in_plane_angle = 180 * unit.degree
vsite1_index = molecule.add_monovalent_lone_pair_virtual_site(
[atom1, atom2, atom3],
distance,
out_of_plane_angle=out_of_plane_angle,
in_plane_angle=in_plane_angle,
symmetric=True,
)
expected = np.array([[1.0, 0.0, -0.2], [0.0, 1.0, 0.2]])
vsite_pos = molecule.compute_virtual_site_positions_from_conformer(0)
vsite_pos = vsite_pos / vsite_pos.unit
assert vsite_pos.shape == (2, 3)
assert np.allclose(vsite_pos, expected)
conformer = molecule.conformers[0]
vsite_pos = molecule.compute_virtual_site_positions_from_atom_positions(
conformer
)
vsite_pos = vsite_pos / vsite_pos.unit
assert vsite_pos.shape == (2, 3)
assert np.allclose(vsite_pos, expected)
def test_monovalent_lone_pair_virtual_site_position(self):
"""
Test for expected positions of virtual sites when created through the molecule
API.
The order of the positions is the same as the order of the particles as they
appear in the molecule using Molecule.particles
"""
import openff.toolkit.tests.test_forcefield
molecule = openff.toolkit.tests.test_forcefield.create_water()
# a 90 degree water molecule on the xy plane
molecule.add_conformer(
unit.Quantity(
np.array(
[
[1.0, 0.0, 0.0],
[0.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
]
),
unit.angstrom,
)
)
atom1 = molecule.atoms[0]
atom2 = molecule.atoms[1]
atom3 = molecule.atoms[2]
distance = 0.2 * unit.angstrom
out_of_plane_angle = 90 * unit.degree
in_plane_angle = 180 * unit.degree
vsite1_index = molecule.add_monovalent_lone_pair_virtual_site(
[atom1, atom2, atom3],
distance,
out_of_plane_angle=out_of_plane_angle,
in_plane_angle=in_plane_angle,
symmetric=False,
)
expected = np.array([[1.0, 0.0, -0.2]])
vsite_pos = molecule.compute_virtual_site_positions_from_conformer(0)
vsite_pos = vsite_pos / vsite_pos.unit
assert vsite_pos.shape == (1, 3)
assert np.allclose(vsite_pos, expected)
conformer = molecule.conformers[0]
vsite_pos = molecule.compute_virtual_site_positions_from_atom_positions(
conformer
)
vsite_pos = vsite_pos / vsite_pos.unit
assert vsite_pos.shape == (1, 3)
assert np.allclose(vsite_pos, expected)
def test_divalent_lone_pair_virtual_site_position(self):
"""
Test for expected positions of virtual sites when created through the molecule
API.
The order of the positions is the same as the order of the particles as they
appear in the molecule using Molecule.particles
"""
import openff.toolkit.tests.test_forcefield
molecule = openff.toolkit.tests.test_forcefield.create_water()
# a 90 degree water molecule on the xy plane
molecule.add_conformer(
unit.Quantity(
np.array(
[
[1.0, 0.0, 0.0],
[0.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
]
),
unit.angstrom,
)
)
atom1 = molecule.atoms[0]
atom2 = molecule.atoms[1]
atom3 = molecule.atoms[2]
distance = 0.2 * unit.angstrom
out_of_plane_angle = 90 * unit.degree
vsite1_index = molecule.add_divalent_lone_pair_virtual_site(
[atom1, atom2, atom3],
distance,
out_of_plane_angle=out_of_plane_angle,
symmetric=False,
)
expected = np.array([[0.0, 0.0, -0.2]])
vsite_pos = molecule.compute_virtual_site_positions_from_conformer(0)
vsite_pos = vsite_pos / vsite_pos.unit
assert vsite_pos.shape == (1, 3)
assert np.allclose(vsite_pos, expected)
conformer = molecule.conformers[0]
vsite_pos = molecule.compute_virtual_site_positions_from_atom_positions(
conformer
)
vsite_pos = vsite_pos / vsite_pos.unit
assert vsite_pos.shape == (1, 3)
assert np.allclose(vsite_pos, expected)
def test_divalent_lone_pair_virtual_site_position_symmetric(self):
"""
Test for expected positions of virtual sites when created through the molecule
API. This uses symmetric, which will add both orientations of the atoms to
create two particles for the vsite.
Note: symmetric with Monovalent is a bit counterintuitive. Since the particles
origin is placed on the first atom, using a "symmetric" definition will flip
the ordering, causing another particle to be placed on the third atom, reflected
on the xy plane between the first particle.
The order of the positions is the same as the order of the particles as they
appear in the molecule using Molecule.particles
"""
import openff.toolkit.tests.test_forcefield
molecule = openff.toolkit.tests.test_forcefield.create_water()
# a 90 degree water molecule on the xy plane
molecule.add_conformer(
unit.Quantity(
np.array(
[
[1.0, 0.0, 0.0],
[0.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
]
),
unit.angstrom,
)
)
atom1 = molecule.atoms[0]
atom2 = molecule.atoms[1]
atom3 = molecule.atoms[2]
distance = 0.2 * unit.angstrom
out_of_plane_angle = 90 * unit.degree
vsite1_index = molecule.add_divalent_lone_pair_virtual_site(
[atom1, atom2, atom3],
distance,
out_of_plane_angle=out_of_plane_angle,
symmetric=True,
)
expected = np.array([[0.0, 0.0, -0.2], [0.0, 0.0, 0.2]])
vsite_pos = molecule.compute_virtual_site_positions_from_conformer(0)
vsite_pos = vsite_pos / vsite_pos.unit
assert vsite_pos.shape == (2, 3)
assert np.allclose(vsite_pos, expected)
conformer = molecule.conformers[0]
vsite_pos = molecule.compute_virtual_site_positions_from_atom_positions(
conformer
)
vsite_pos = vsite_pos / vsite_pos.unit
assert vsite_pos.shape == (2, 3)
assert np.allclose(vsite_pos, expected)
def test_trivalent_lone_pair_virtual_site_position(self):
"""
Test for expected positions of virtual sites when created through the molecule
API.
The order of the positions is the same as the order of the particles as they
appear in the molecule using Molecule.particles
"""
import openff.toolkit.tests.test_forcefield
molecule = openff.toolkit.tests.test_forcefield.create_ammonia()
# an ammonia; the central nitrogen .5 above the hydrogen, which all lie one
# an xy plane
molecule.add_conformer(
unit.Quantity(
np.array(
[
[1.0, 0.0, 0.0],
[0.0, 0.0, 0.5],
[-0.5, 0.5, 0.0],
[-0.5, -0.5, 0.0],
]
),
unit.angstrom,
)
)
atom1 = molecule.atoms[0]
atom2 = molecule.atoms[1]
atom3 = molecule.atoms[2]
atom4 = molecule.atoms[3]
distance = 1.0 * unit.angstrom
vsite1_index = molecule.add_trivalent_lone_pair_virtual_site(
[atom1, atom2, atom3, atom4], distance, symmetric=False
)
expected = np.array([[0.0, 0.0, 1.5]])
vsite_pos = molecule.compute_virtual_site_positions_from_conformer(0)
vsite_pos = vsite_pos / vsite_pos.unit
assert vsite_pos.shape == (1, 3)
assert np.allclose(vsite_pos, expected)
conformer = molecule.conformers[0]
vsite_pos = molecule.compute_virtual_site_positions_from_atom_positions(
conformer
)
vsite_pos = vsite_pos / vsite_pos.unit
assert vsite_pos.shape == (1, 3)
assert np.allclose(vsite_pos, expected)
@requires_openeye
def test_chemical_environment_matches_OE(self):
"""Test chemical environment matches"""
# TODO: Move this to test_toolkits, test all available toolkits
# Create chiral molecule
toolkit_wrapper = OpenEyeToolkitWrapper()
molecule = Molecule()
atom_C = molecule.add_atom(
element.carbon.atomic_number, 0, False, stereochemistry="R", name="C"
)
atom_H = molecule.add_atom(element.hydrogen.atomic_number, 0, False, name="H")
atom_Cl = molecule.add_atom(element.chlorine.atomic_number, 0, False, name="Cl")
atom_Br = molecule.add_atom(element.bromine.atomic_number, 0, False, name="Br")
atom_F = molecule.add_atom(element.fluorine.atomic_number, 0, False, name="F")
molecule.add_bond(atom_C, atom_H, 1, False)
molecule.add_bond(atom_C, atom_Cl, 1, False)
molecule.add_bond(atom_C, atom_Br, 1, False)
molecule.add_bond(atom_C, atom_F, 1, False)
# Test known cases
matches = molecule.chemical_environment_matches(
"[#6:1]", toolkit_registry=toolkit_wrapper
)
assert (
len(matches) == 1
) # there should be a unique match, so one atom tuple is returned
assert len(matches[0]) == 1 # it should have one tagged atom
assert set(matches[0]) == set([atom_C])
matches = molecule.chemical_environment_matches(
"[#6:1]~[#1:2]", toolkit_registry=toolkit_wrapper
)
assert (
len(matches) == 1
) # there should be a unique match, so one atom tuple is returned
assert len(matches[0]) == 2 # it should have two tagged atoms
assert set(matches[0]) == set([atom_C, atom_H])
matches = molecule.chemical_environment_matches(
"[Cl:1]-[C:2]-[H:3]", toolkit_registry=toolkit_wrapper
)
assert (
len(matches) == 1
) # there should be a unique match, so one atom tuple is returned
assert len(matches[0]) == 3 # it should have three tagged atoms
assert set(matches[0]) == set([atom_Cl, atom_C, atom_H])
matches = molecule.chemical_environment_matches(
"[#6:1]~[*:2]", toolkit_registry=toolkit_wrapper
)
assert len(matches) == 4 # there should be four matches
for match in matches:
assert len(match) == 2 # each match should have two tagged atoms
# Test searching for stereo-specific SMARTS
matches = molecule.chemical_environment_matches(
"[#6@:1](-[F:2])(-[Cl])(-[Br])(-[H])", toolkit_registry=toolkit_wrapper
)
assert len(matches) == 1 # there should be one match
for match in matches:
assert len(match) == 2 # each match should have two tagged atoms
matches = molecule.chemical_environment_matches(
"[#6@@:1](-[F:2])(-[Cl])(-[Br])(-[H])", toolkit_registry=toolkit_wrapper
)
assert (
len(matches) == 0
) # this is the wrong stereochemistry, so there shouldn't be any matches
# TODO: Test forgive undef amide enol stereo
# TODO: test forgive undef phospho linker stereo
# TODO: test forgive undef C=NH stereo
# TODO: test forgive undef phospho stereo
# Potentially better OE stereo check: OEFlipper — Toolkits - - Python
# https: // docs.eyesopen.com / toolkits / python / omegatk / OEConfGenFunctions / OEFlipper.html
@requires_rdkit
def test_chemical_environment_matches_RDKit(self):
"""Test chemical environment matches"""
# Create chiral molecule
toolkit_wrapper = RDKitToolkitWrapper()
molecule = Molecule()
atom_C = molecule.add_atom(
element.carbon.atomic_number, 0, False, stereochemistry="R", name="C"
)
atom_H = molecule.add_atom(element.hydrogen.atomic_number, 0, False, name="H")
atom_Cl = molecule.add_atom(element.chlorine.atomic_number, 0, False, name="Cl")
atom_Br = molecule.add_atom(element.bromine.atomic_number, 0, False, name="Br")
atom_F = molecule.add_atom(element.fluorine.atomic_number, 0, False, name="F")
molecule.add_bond(atom_C, atom_H, 1, False)
molecule.add_bond(atom_C, atom_Cl, 1, False)
molecule.add_bond(atom_C, atom_Br, 1, False)
molecule.add_bond(atom_C, atom_F, 1, False)
# Test known cases
matches = molecule.chemical_environment_matches(
"[#6:1]", toolkit_registry=toolkit_wrapper
)
assert (
len(matches) == 1
) # there should be a unique match, so one atom tuple is returned
assert len(matches[0]) == 1 # it should have one tagged atom
assert set(matches[0]) == set([atom_C])
matches = molecule.chemical_environment_matches(
"[#6:1]~[#1:2]", toolkit_registry=toolkit_wrapper
)
assert (
len(matches) == 1
) # there should be a unique match, so one atom tuple is returned
assert len(matches[0]) == 2 # it should have two tagged atoms
assert set(matches[0]) == set([atom_C, atom_H])
matches = molecule.chemical_environment_matches(
"[Cl:1]-[C:2]-[H:3]", toolkit_registry=toolkit_wrapper
)
assert (
len(matches) == 1
) # there should be a unique match, so one atom tuple is returned
assert len(matches[0]) == 3 # it should have three tagged atoms
assert set(matches[0]) == set([atom_Cl, atom_C, atom_H])
matches = molecule.chemical_environment_matches(
"[#6:1]~[*:2]", toolkit_registry=toolkit_wrapper
)
assert len(matches) == 4 # there should be four matches
for match in matches:
assert len(match) == 2 # each match should have two tagged atoms
# Test searching for stereo-specific SMARTS
matches = molecule.chemical_environment_matches(
"[#6@:1](-[F:2])(-[Cl])(-[Br])(-[H])", toolkit_registry=toolkit_wrapper
)
assert len(matches) == 1 # there should be one match
for match in matches:
assert len(match) == 2 # each match should have two tagged atoms
matches = molecule.chemical_environment_matches(
"[#6@@:1](-[F:2])(-[Cl])(-[Br])(-[H])", toolkit_registry=toolkit_wrapper
)
assert (
len(matches) == 0
) # this is the wrong stereochemistry, so there shouldn't be any matches
@requires_rdkit
@requires_openeye
@pytest.mark.slow
@pytest.mark.parametrize(
("toolkit", "method"),
[
("openeye", "mmff94"),
("openeye", "am1bcc"),
("openeye", "am1-mulliken"),
("openeye", "gasteiger"),
("openeye", "am1bccnosymspt"),
("openeye", "am1elf10"),
("openeye", "am1bccelf10"),
("ambertools", "am1bcc"),
("ambertools", "gasteiger"),
("ambertools", "am1-mulliken"),
],
)
def test_assign_partial_charges(self, toolkit, method):
"""Test computation/retrieval of partial charges"""
# TODO: Test only one molecule for speed?
# TODO: Do we need to deepcopy each molecule, or is setUp called separately for each test method?
# Do not modify original molecules.
# molecules = copy.deepcopy(mini_drug_bank())
# In principle, testing for charge assignment over a wide set of molecules is important, but
# I think that's covered in test_toolkits.py. Here, we should only be concerned with testing the
# Molecule API, and therefore a single molecule should be sufficient
molecule = Molecule.from_smiles("CN1C=NC2=C1C(=O)N(C(=O)N2C)C")
if toolkit == "openeye":
toolkit_registry = ToolkitRegistry(
toolkit_precedence=[OpenEyeToolkitWrapper]
)
elif toolkit == "ambertools":
toolkit_registry = ToolkitRegistry(
toolkit_precedence=[AmberToolsToolkitWrapper]
)
molecule.assign_partial_charges(
partial_charge_method=method,
toolkit_registry=toolkit_registry,
)
initial_charges = molecule._partial_charges
# Make sure everything isn't 0s
assert (abs(initial_charges.value_in_unit(unit.elementary_charge)) > 0.01).any()
# Check total charge
charges_sum_unitless = initial_charges.sum().value_in_unit(
unit.elementary_charge
)
total_charge_unitless = molecule.total_charge.value_in_unit(
unit.elementary_charge
)
# if abs(charges_sum_unitless - total_charge_unitless) > 0.0001:
# print(
# "molecule {} charge_sum {} molecule.total_charge {}".format(
# molecule.name, charges_sum_unitless, total_charge_unitless
# )
# )
np.allclose(charges_sum_unitless, total_charge_unitless, atol=0.002)
# Call should be faster second time due to caching
# TODO: Implement caching
molecule.assign_partial_charges(
partial_charge_method=method, toolkit_registry=toolkit_registry
)
recomputed_charges = molecule._partial_charges
assert np.allclose(initial_charges, recomputed_charges, atol=0.002)
@pytest.mark.parametrize("toolkit", ["openeye", "rdkit"])
def test_apply_elf_conformer_selection(self, toolkit):
"""Test applying the ELF10 method."""
if toolkit == "openeye":
pytest.importorskip("openeye")
toolkit_registry = ToolkitRegistry(
toolkit_precedence=[OpenEyeToolkitWrapper]
)
elif toolkit == "rdkit":
pytest.importorskip("rdkit")
toolkit_registry = ToolkitRegistry(toolkit_precedence=[RDKitToolkitWrapper])
molecule = Molecule.from_file(
get_data_file_path(os.path.join("molecules", "z_3_hydroxy_propenal.sdf")),
"SDF",
)
initial_conformers = [
# Add a conformer with an internal H-bond.
np.array(
[
[0.5477, 0.3297, -0.0621],
[-0.1168, -0.7881, 0.2329],
[-1.4803, -0.8771, 0.1667],
[-0.2158, 1.5206, -0.4772],
[-1.4382, 1.5111, -0.5580],
[1.6274, 0.3962, -0.0089],
[0.3388, -1.7170, 0.5467],
[-1.8612, -0.0347, -0.1160],
[0.3747, 2.4222, -0.7115],
]
)
* unit.angstrom,
# Add a conformer without an internal H-bond.
np.array(
[
[0.5477, 0.3297, -0.0621],
[-0.1168, -0.7881, 0.2329],
[-1.4803, -0.8771, 0.1667],
[-0.2158, 1.5206, -0.4772],
[0.3353, 2.5772, -0.7614],
[1.6274, 0.3962, -0.0089],
[0.3388, -1.7170, 0.5467],
[-1.7743, -1.7634, 0.4166],
[-1.3122, 1.4082, -0.5180],
]
)
* unit.angstrom,
]
molecule._conformers = [*initial_conformers]
# Apply ELF10
molecule.apply_elf_conformer_selection(toolkit_registry=toolkit_registry)
elf10_conformers = molecule.conformers
assert len(elf10_conformers) == 1
assert np.allclose(
elf10_conformers[0].value_in_unit(unit.angstrom),
initial_conformers[1].value_in_unit(unit.angstrom),
)
@requires_openeye
def test_assign_fractional_bond_orders(self):
"""Test assignment of fractional bond orders"""
# TODO: Test only one molecule for speed?
# TODO: Do we need to deepcopy each molecule, or is setUp called separately for each test method?
# Do not modify the original molecules.
molecules = copy.deepcopy(mini_drug_bank())
toolkits_to_bondorder_method = {
(OpenEyeToolkitWrapper,): ["am1-wiberg", "pm3-wiberg"]
}
# Don't test AmberTools here since it takes too long
# (AmberToolsToolkitWrapper, RDKitToolkitWrapper):['am1-wiberg']}
for toolkits in list(toolkits_to_bondorder_method.keys()):
toolkit_registry = ToolkitRegistry(toolkit_precedence=toolkits)
for bond_order_model in toolkits_to_bondorder_method[toolkits]:
for molecule in molecules[
:5
]: # Just test first five molecules for speed
molecule.generate_conformers(toolkit_registry=toolkit_registry)
molecule.assign_fractional_bond_orders(
bond_order_model=bond_order_model,
toolkit_registry=toolkit_registry,
use_conformers=molecule.conformers,
)
fbo1 = [bond.fractional_bond_order for bond in molecule.bonds]
# TODO: Now that the assign_fractional_bond_orders function takes more kwargs,
# how can we meaningfully cache its results?
# # Call should be faster the second time due to caching
# molecule.assign_fractional_bond_orders(bond_order_model=bond_order_model,
# toolkit_registry=toolkit_registry)
# fbo2 = [bond.fractional_bond_order for bond in molecule.bonds]
# np.testing.assert_allclose(fbo1, fbo2, atol=1.e-4)
@requires_ambertools
@requires_openeye
@pytest.mark.slow
@pytest.mark.parametrize("model", ["AM1-Wiberg", "am1-wiberg"])
@pytest.mark.parametrize(
"toolkit", [OpenEyeToolkitWrapper, AmberToolsToolkitWrapper]
)
def test_bond_order_method_passing(self, model, toolkit):
"""Test that different calls to Molecule.assign_fractional_bond_orders do not
produce unexpected errors, but do not asses validity of results"""
mol = Molecule.from_smiles("CCO")
mol.assign_fractional_bond_orders(
bond_order_model=model,
)
mol.assign_fractional_bond_orders(
bond_order_model=model,
toolkit_registry=toolkit(),
)
mol.assign_fractional_bond_orders(
bond_order_model=model,
toolkit_registry=ToolkitRegistry([toolkit()]),
)
def test_get_bond_between(self):
"""Test Molecule.get_bond_between"""
mol = Molecule.from_smiles("C#C")
# Dynamically get atoms in case from_smiles produces different atom order
hydrogens = [a for a in mol.atoms if a.atomic_number == 1]
carbons = [a for a in mol.atoms if a.atomic_number == 6]
bond_from_atoms = mol.get_bond_between(carbons[0], carbons[1])
bond_from_idx = mol.get_bond_between(
carbons[0].molecule_atom_index, carbons[1].molecule_atom_index
)
assert bond_from_idx == bond_from_atoms
with pytest.raises(NotBondedError):
mol.get_bond_between(hydrogens[0], hydrogens[1])
@pytest.mark.parametrize(
("smiles", "n_rings"),
[
("CCO", 0),
("c1ccccc1", 1),
("C1CC2CCC1C2", 2), # This should probably be 3?
("c1ccc(cc1)c2ccccc2", 2),
("c1ccc2ccccc2c1", 2),
("c1ccc2cc3ccccc3cc2c1", 3),
("C1C2C(CCC1)CC5C3C2CCC7C3C4C(CCC6C4C5CCC6)CC7", 7),
],
)
@requires_rdkit
def test_molecule_rings(self, smiles, n_rings):
"""Test the Molecule.rings property"""
assert (
n_rings == Molecule.from_smiles(smiles, allow_undefined_stereo=True).n_rings
)
@pytest.mark.parametrize(
("smiles", "n_atom_rings", "n_bond_rings"),
[
("c1ccc2ccccc2c1", 10, 11),
("c1ccc(cc1)c2ccccc2", 12, 12),
("Cc1ccc(cc1Nc2nccc(n2)c3cccnc3)NC(=O)c4ccc(cc4)CN5CCN(CC5)C", 30, 30),
],
)
@requires_rdkit
def test_is_in_ring(self, smiles, n_atom_rings, n_bond_rings):
"""Test Atom.is_in_ring and Bond.is_in_ring"""
mol = Molecule.from_smiles(smiles)
assert len([atom for atom in mol.atoms if atom.is_in_ring]) == n_atom_rings
assert len([bond for bond in mol.bonds if bond.is_in_ring]) == n_bond_rings
@requires_rdkit
@requires_openeye
def test_conformer_generation_failure(self):
# This test seems possibly redundant, is it needed?
molecule = Molecule.from_smiles("F[U](F)(F)(F)(F)F")
with pytest.raises(ConformerGenerationError, match="Omega conf.*fail"):
molecule.generate_conformers(
n_conformers=1, toolkit_registry=OpenEyeToolkitWrapper()
)
with pytest.raises(ConformerGenerationError, match="RDKit conf.*fail"):
molecule.generate_conformers(
n_conformers=1, toolkit_registry=RDKitToolkitWrapper()
)
with pytest.raises(ValueError) as execption:
molecule.generate_conformers(n_conformers=1)
# pytest's checking of the string representation of this exception does not seem
# to play well with how it's constructed currently, so manually compare contents
exception_as_str = str(exception)
assert (
"No registered toolkits can provide the capability" in exception_as_str
)
assert "generate_conformers" in exception_as_str
assert "OpenEye Omega conformer generation failed" in exception_as_str
assert "RDKit conformer generation failed" in exception_as_str
class TestMoleculeVisualization:
@requires_pkg("IPython")
@requires_rdkit
def test_visualize_rdkit(self):
"""Test that the visualize method returns an expected object when using RDKit to generate a 2-D representation"""
import IPython
mol = Molecule().from_smiles("CCO")
assert isinstance(mol.visualize(backend="rdkit"), IPython.core.display.SVG)
@pytest.mark.skipif(
has_pkg("rdkit"),
reason="Test requires that RDKit is not installed",
)
def test_visualize_fallback(self):
"""Test falling back from RDKit to OpenEye if RDKit is specified but not installed"""
mol = Molecule().from_smiles("CCO")
with pytest.warns(UserWarning):
mol.visualize(backend="rdkit")
@requires_pkg("nglview")
def test_visualize_nglview(self):
"""Test that the visualize method returns an NGLview widget. Note that
nglview is not explicitly a requirement in the test environment, but
is likely to get pulled in with other dependencies."""
try:
import nglview
except ModuleNotFoundError:
pass
# Start with a molecule without conformers
mol = Molecule().from_smiles("CCO")
with pytest.raises(ValueError):
mol.visualize(backend="nglview")
# Add conformers
mol.generate_conformers()
# Ensure an NGLView widget is returned
assert isinstance(mol.visualize(backend="nglview"), nglview.NGLWidget)
# Providing other arguments is an error
with pytest.raises(ValueError):
mol.visualize(backend="nglview", width=100)
with pytest.raises(ValueError):
mol.visualize(backend="nglview", height=100)
with pytest.raises(ValueError):
mol.visualize(backend="nglview", show_all_hydrogens=False)
@requires_pkg("IPython")
@requires_openeye
def test_visualize_openeye(self):
"""Test that the visualize method returns an expected object when using OpenEye to generate a 2-D representation"""
import IPython
mol = Molecule().from_smiles("CCO")
assert isinstance(mol.visualize(backend="openeye"), IPython.core.display.Image)
class MyMol(FrozenMolecule):
"""
Lightweight FrozenMolecule subclass for molecule-subclass tests below
"""
class TestMoleculeSubclass:
"""
Test that the FrozenMolecule class is subclass-able, by ensuring that Molecule.from_X constructors
return objects of the correct types
"""
def test_molecule_subclass_from_smiles(self):
"""Ensure that the right type of object is returned when running MyMol.from_smiles"""
mol = MyMol.from_smiles("CCO")
assert isinstance(mol, MyMol)
def test_molecule_subclass_from_inchi(self):
"""Ensure that the right type of object is returned when running MyMol.from_inchi"""
mol = MyMol.from_inchi("InChI=1S/C2H6O/c1-2-3/h3H,2H2,1H3")
assert isinstance(mol, MyMol)
@requires_openeye
def test_molecule_subclass_from_iupac(self):
"""Ensure that the right type of object is returned when running MyMol.from_iupac"""
mol = MyMol.from_iupac("benzene")
assert isinstance(mol, MyMol)
def test_molecule_subclass_from_file(self):
"""Ensure that the right type of object is returned when running MyMol.from_file"""
mol = MyMol.from_file(get_data_file_path("molecules/ethanol.sdf"))
assert isinstance(mol, MyMol)
def test_molecule_subclass_from_mapped_smiles(self):
"""Ensure that the right type of object is returned when running MyMol.from_mapped_smiles"""
mol = MyMol.from_mapped_smiles("[H:1][C:2]([H:3])([H:4])([H:5])")
assert isinstance(mol, MyMol)
@requires_pkg("qcelemental")
@requires_pkg("qcportal")
def test_molecule_subclass_from_qcschema(self):
"""Ensure that the right type of object is returned when running MyMol.from_qcschema"""
import qcportal as ptl
client = ptl.FractalClient()
ds = client.get_collection(
"TorsionDriveDataset", "Fragment Stability Benchmark"
)
entry = ds.get_entry(
"CC(=O)Nc1cc2c(cc1OC)nc[n:4][c:3]2[NH:2][c:1]3ccc(c(c3)Cl)F"
)
# now make the molecule from the record instance with and without the geometry
mol = MyMol.from_qcschema(entry.dict(encoding="json"))
assert isinstance(mol, MyMol)
# Make from object, which will include geometry
mol = MyMol.from_qcschema(entry, client)
assert isinstance(mol, MyMol)
def test_molecule_subclass_from_topology(self):
"""Ensure that the right type of object is returned when running MyMol.from_topology"""
top = Molecule.from_smiles("CCO").to_topology()
mol = MyMol.from_topology(top)
assert isinstance(mol, MyMol)
@requires_rdkit
def test_molecule_subclass_from_pdb_and_smiles(self):
"""Ensure that the right type of object is returned when running MyMol.from_pdb_and_smiles"""
mol = MyMol.from_pdb_and_smiles(
get_data_file_path("molecules/toluene.pdb"), "Cc1ccccc1"
)
assert isinstance(mol, MyMol)
def test_molecule_copy_constructor_from_other_subclass(self):
"""Ensure that the right type of object is returned when running the MyMol copy constructor"""
normal_mol = MyMol.from_smiles("CCO")
mol = MyMol(normal_mol)
assert isinstance(mol, MyMol)
def test_molecule_subclass_from_dict(self):
"""Ensure that the right type of object is returned when running MyMol.from_dict"""
orig_mol = Molecule.from_smiles("CCO")
mol = MyMol.from_dict(orig_mol.to_dict())
assert isinstance(mol, MyMol)
|
//============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//
// Copyright 2014 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
// Copyright 2014 UT-Battelle, LLC.
// Copyright 2014 Los Alamos National Security.
//
// Under the terms of Contract DE-NA0003525 with NTESS,
// the U.S. Government retains certain rights in this software.
//
// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
// Laboratory (LANL), the U.S. Government retains certain rights in
// this software.
//============================================================================
#ifndef vtk_m_worklet_WorkletMapTopology_h
#define vtk_m_worklet_WorkletMapTopology_h
#include <vtkm/worklet/internal/WorkletBase.h>
#include <vtkm/TopologyElementTag.h>
#include <vtkm/TypeListTag.h>
#include <vtkm/cont/arg/ControlSignatureTagBase.h>
#include <vtkm/cont/arg/TransportTagArrayInOut.h>
#include <vtkm/cont/arg/TransportTagArrayOut.h>
#include <vtkm/cont/arg/TransportTagCellSetIn.h>
#include <vtkm/cont/arg/TransportTagTopologyFieldIn.h>
#include <vtkm/cont/arg/TypeCheckTagArray.h>
#include <vtkm/cont/arg/TypeCheckTagCellSet.h>
#include <vtkm/exec/arg/CellShape.h>
#include <vtkm/exec/arg/FetchTagArrayDirectIn.h>
#include <vtkm/exec/arg/FetchTagArrayDirectInOut.h>
#include <vtkm/exec/arg/FetchTagArrayDirectOut.h>
#include <vtkm/exec/arg/FetchTagArrayTopologyMapIn.h>
#include <vtkm/exec/arg/FetchTagCellSetIn.h>
#include <vtkm/exec/arg/FromCount.h>
#include <vtkm/exec/arg/FromIndices.h>
#include <vtkm/exec/arg/ThreadIndicesTopologyMap.h>
namespace vtkm
{
namespace worklet
{
namespace detail
{
struct WorkletMapTopologyBase : vtkm::worklet::internal::WorkletBase
{
};
} // namespace detail
/// Base class for worklets that do a simple mapping of field arrays. All
/// inputs and outputs are on the same domain. That is, all the arrays are the
/// same size.
///
template <typename FromTopology, typename ToTopology>
class WorkletMapTopology : public detail::WorkletMapTopologyBase
{
public:
using FromTopologyType = FromTopology;
using ToTopologyType = ToTopology;
/// \brief A control signature tag for input fields.
///
/// This tag takes a template argument that is a type list tag that limits
/// the possible value types in the array.
///
template <typename TypeList = AllTypes>
struct FieldInTo : vtkm::cont::arg::ControlSignatureTagBase
{
using TypeCheckTag = vtkm::cont::arg::TypeCheckTagArray<TypeList>;
using TransportTag = vtkm::cont::arg::TransportTagTopologyFieldIn<ToTopologyType>;
using FetchTag = vtkm::exec::arg::FetchTagArrayDirectIn;
};
/// \brief A control signature tag for input connectivity.
///
/// This tag takes a template argument that is a type list tag that limits
/// the possible value types in the array.
///
template <typename TypeList = AllTypes>
struct FieldInFrom : vtkm::cont::arg::ControlSignatureTagBase
{
using TypeCheckTag = vtkm::cont::arg::TypeCheckTagArray<TypeList>;
using TransportTag = vtkm::cont::arg::TransportTagTopologyFieldIn<FromTopologyType>;
using FetchTag = vtkm::exec::arg::FetchTagArrayTopologyMapIn;
};
/// \brief A control signature tag for output fields.
///
/// This tag takes a template argument that is a type list tag that limits
/// the possible value types in the array.
///
template <typename TypeList = AllTypes>
struct FieldOut : vtkm::cont::arg::ControlSignatureTagBase
{
using TypeCheckTag = vtkm::cont::arg::TypeCheckTagArray<TypeList>;
using TransportTag = vtkm::cont::arg::TransportTagArrayOut;
using FetchTag = vtkm::exec::arg::FetchTagArrayDirectOut;
};
/// \brief A control signature tag for input-output (in-place) fields.
///
/// This tag takes a template argument that is a type list tag that limits
/// the possible value types in the array.
///
template <typename TypeList = AllTypes>
struct FieldInOut : vtkm::cont::arg::ControlSignatureTagBase
{
using TypeCheckTag = vtkm::cont::arg::TypeCheckTagArray<TypeList>;
using TransportTag = vtkm::cont::arg::TransportTagArrayInOut;
using FetchTag = vtkm::exec::arg::FetchTagArrayDirectInOut;
};
/// \brief A control signature tag for input connectivity.
///
struct CellSetIn : vtkm::cont::arg::ControlSignatureTagBase
{
using TypeCheckTag = vtkm::cont::arg::TypeCheckTagCellSet;
using TransportTag = vtkm::cont::arg::TransportTagCellSetIn<FromTopologyType, ToTopologyType>;
using FetchTag = vtkm::exec::arg::FetchTagCellSetIn;
};
/// \brief An execution signature tag for getting the cell shape.
///
struct CellShape : vtkm::exec::arg::CellShape
{
};
/// \brief An execution signature tag to get the number of from elements.
///
/// In a topology map, there are \em from and \em to topology elements
/// specified. The scheduling occurs on the \em to elements, and for each \em
/// to element there is some number of incident \em from elements that are
/// accessible. This \c ExecutionSignature tag provides the number of these
/// \em from elements that are accessible.
///
struct FromCount : vtkm::exec::arg::FromCount
{
};
/// \brief An execution signature tag to get the indices of from elements.
///
/// In a topology map, there are \em from and \em to topology elements
/// specified. The scheduling occurs on the \em to elements, and for each \em
/// to element there is some number of incident \em from elements that are
/// accessible. This \c ExecutionSignature tag provides the indices of these
/// \em from elements that are accessible.
///
struct FromIndices : vtkm::exec::arg::FromIndices
{
};
/// Topology map worklets use topology map indices.
///
VTKM_SUPPRESS_EXEC_WARNINGS
template <typename T,
typename OutToInArrayType,
typename VisitArrayType,
typename InputDomainType,
typename G>
VTKM_EXEC vtkm::exec::arg::ThreadIndicesTopologyMap<InputDomainType> GetThreadIndices(
const T& threadIndex,
const OutToInArrayType& outToIn,
const VisitArrayType& visit,
const InputDomainType& connectivity,
const G& globalThreadIndexOffset) const
{
return vtkm::exec::arg::ThreadIndicesTopologyMap<InputDomainType>(
threadIndex, outToIn, visit, connectivity, globalThreadIndexOffset);
}
};
/// Base class for worklets that map from Points to Cells.
///
class WorkletMapPointToCell
: public WorkletMapTopology<vtkm::TopologyElementTagPoint, vtkm::TopologyElementTagCell>
{
public:
template <typename TypeList = AllTypes>
using FieldInPoint = FieldInFrom<TypeList>;
template <typename TypeList = AllTypes>
using FieldInCell = FieldInTo<TypeList>;
template <typename TypeList = AllTypes>
using FieldOutCell = FieldOut<TypeList>;
template <typename TypeList = AllTypes>
using FieldInOutCell = FieldInOut<TypeList>;
using PointCount = FromCount;
using PointIndices = FromIndices;
};
/// Base class for worklets that map from Cells to Points.
///
class WorkletMapCellToPoint
: public WorkletMapTopology<vtkm::TopologyElementTagCell, vtkm::TopologyElementTagPoint>
{
public:
template <typename TypeList = AllTypes>
using FieldInCell = FieldInFrom<TypeList>;
template <typename TypeList = AllTypes>
using FieldInPoint = FieldInTo<TypeList>;
template <typename TypeList = AllTypes>
using FieldOutPoint = FieldOut<TypeList>;
template <typename TypeList = AllTypes>
using FieldInOutPoint = FieldInOut<TypeList>;
using CellCount = FromCount;
using CellIndices = FromIndices;
};
}
} // namespace vtkm::worklet
#endif //vtk_m_worklet_WorkletMapTopology_h
|
"""Quality-time specific types."""
from typing import Any, NewType, Optional
import aiohttp
ErrorMessage = Optional[str]
Job = dict[str, Any]
Jobs = list[Job]
JSON = dict[str, Any]
Namespaces = dict[str, str] # Namespace prefix to Namespace URI mapping
Response = aiohttp.ClientResponse
Responses = list[Response]
URL = NewType("URL", str)
Value = Optional[str]
|
'use strict';
var avisos = require('utils/avisos');
module.exports = function (xhr) {
if (xhr.status === 409) {
avisos.erro('Não foi possível completar esta solicitação. Por favor, recarregue esta página pois existem alterações nesta página.');
return 'conflito_edicao';
}
};
|
import { logger } from "../utils/logger";
export const infoLogger = (req, res, next) => {
const ip = req.get("X-Real-IP") || req.ip;
logger.info(`[${ip}] [${req.method}] ${req.url} `);
next();
};
|
import validator from 'is-my-json-valid';
import topicSchema from '../schemas/bcf/topic';
import viewpointSchema from '../schemas/bcf/viewpoint';
import commentSchema from '../schemas/bcf/comment';
import { DEBUG } from '../config';
const verbose = DEBUG;
const greedy = DEBUG;
function validate(type, schemaValidator, data) {
const valid = schemaValidator(data);
if (!valid) {
const baseMessage = `Invalid ${type} object`;
if (DEBUG) {
throw new Error(`${baseMessage}: ${JSON.stringify(schemaValidator.errors)}`);
} else {
throw new Error(baseMessage);
}
}
}
const validateTopic = validator(topicSchema);
const validateViewpoint = validator(viewpointSchema);
const validateComment = validator(commentSchema);
function checkTopic(topic) {
validate('topic', validateTopic, topic);
}
function checkViewpoint(viewpoint) {
validate('viewpoint', validateViewpoint, viewpoint);
}
function checkComment(comment) {
validate('comment', validateComment, comment);
}
const credentialsSchema = {
required: true,
type: 'object',
properties: {
clientId: { type: 'string', required: true },
accessToken: { type: 'string', required: true },
fluxToken: { type: 'string', required: true },
tokenType: { type: 'string', required: true },
refreshToken: { type: 'string' },
scope: { type: 'string' },
tokenExpiry: { type: 'number' },
clientInfo: {
type: 'object',
required: true,
properties: {
// TODO
ClientId: { type: 'string', required: true },
},
},
idToken: { type: 'object' },
},
};
const credentialsValidator = validator(credentialsSchema, { verbose, greedy });
const userSchema = {
required: true,
type: 'object',
properties: {
credentials: { $ref: '#credentials' },
},
};
const validateUser = validator(userSchema, {
verbose,
greedy,
schemas: { credentials: credentialsSchema },
});
const projectSchema = {
required: true,
type: 'object',
properties: {
id: { type: 'string', required: true },
credentials: { $ref: '#credentials' },
},
};
const validateProject = validator(projectSchema, {
verbose,
greedy,
schemas: { credentials: credentialsSchema },
});
function checkSdk() {
}
function checkCredentials(credentials) {
validate('credentials', credentialsValidator, credentials);
}
function checkUser(user) {
validate('User', validateUser, user);
}
function checkProject(project) {
validate('project', validateProject, project);
}
function checkDataTable() {
}
function checkCell() {
}
export {
checkSdk,
checkCredentials,
checkUser,
checkProject,
checkDataTable,
checkCell,
checkTopic,
checkViewpoint,
checkComment,
};
|
"use strict";
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["exports", "react", "../../@patternfly/patternfly/components/Nav/nav.css.js", "@patternfly/react-styles", "prop-types", "./Nav"], factory);
} else if (typeof exports !== "undefined") {
factory(exports, require("react"), require("../../@patternfly/patternfly/components/Nav/nav.css.js"), require("@patternfly/react-styles"), require("prop-types"), require("./Nav"));
} else {
var mod = {
exports: {}
};
factory(mod.exports, global.react, global.navCss, global.reactStyles, global.propTypes, global.Nav);
global.undefined = mod.exports;
}
})(void 0, function (exports, _react, _navCss, _reactStyles, _propTypes, _Nav) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react2 = _interopRequireDefault(_react);
var _navCss2 = _interopRequireDefault(_navCss);
var _propTypes2 = _interopRequireDefault(_propTypes);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
function _objectWithoutProperties(source, excluded) {
if (source == null) return {};
var target = _objectWithoutPropertiesLoose(source, excluded);
var key, i;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i = 0; i < sourceSymbolKeys.length; i++) {
key = sourceSymbolKeys[i];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
var propTypes = {
/** Content rendered inside the nav item */
children: _propTypes2.default.node,
/** Additional classes added to the nav item */
className: _propTypes2.default.string,
/** Target navigation link */
to: _propTypes2.default.string,
/** Flag indicating whether the item is active */
isActive: _propTypes2.default.bool,
/** Flag indicating whether the item has a horizontal separator below */
isSeparated: _propTypes2.default.bool,
/** Group identifier, will be returned with the onToggle and onSelect callback passed to the Nav component */
groupId: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]),
/** Item identifier, will be returned with the onToggle and onSelect callback passed to the Nav component */
itemId: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]),
/** If true prevents the default anchor link action to occur. Set to true if you want to handle navigation yourself. */
preventDefault: _propTypes2.default.bool,
/** Callback for item click */
onClick: _propTypes2.default.func,
/** Additional props are spread to the container <a> */
'': _propTypes2.default.any
};
var defaultProps = {
children: null,
className: '',
to: '',
isActive: false,
isSeparated: false,
groupId: null,
itemId: null,
preventDefault: false,
onClick: null
};
var NavItem = function NavItem(_ref) {
var className = _ref.className,
children = _ref.children,
to = _ref.to,
isActive = _ref.isActive,
isSeparated = _ref.isSeparated,
groupId = _ref.groupId,
itemId = _ref.itemId,
preventDefault = _ref.preventDefault,
_onClick = _ref.onClick,
rest = _objectWithoutProperties(_ref, ["className", "children", "to", "isActive", "isSeparated", "groupId", "itemId", "preventDefault", "onClick"]);
var defaultLink = _react2.default.createElement(_Nav.NavContext.Consumer, null, function (context) {
return _react2.default.createElement("a", _extends({
href: to,
onClick: function onClick(e) {
return context.onSelect(e, groupId, itemId, to, preventDefault, _onClick);
},
className: (0, _reactStyles.css)(_navCss2.default.navLink, isActive && _navCss2.default.modifiers.current, isSeparated && _navCss2.default.modifiers.separator, className),
"aria-current": isActive ? 'page' : null
}, rest), children);
});
var reactElement = _react2.default.isValidElement(children);
var clonedChild = _react2.default.createElement(_Nav.NavContext.Consumer, null, function (context) {
return _react2.default.cloneElement(children, {
onClick: function onClick(e) {
return context.onSelect(e, groupId, itemId, to, preventDefault, _onClick);
},
className: (0, _reactStyles.css)(_navCss2.default.navLink, isActive && _navCss2.default.modifiers.current, isSeparated && _navCss2.default.modifiers.separator, className),
'aria-current': isActive ? 'page' : null
});
});
return _react2.default.createElement("li", {
className: (0, _reactStyles.css)(_navCss2.default.navItem, className)
}, reactElement ? clonedChild : defaultLink);
};
NavItem.propTypes = propTypes;
NavItem.defaultProps = defaultProps;
NavItem.componentType = 'NavItem';
exports.default = NavItem;
}); |
import React from 'react'
import PropTypes from 'prop-types'
import classnames from 'classnames'
import ContentMenu from '../../elements/ContentMenu/ContentMenu'
import Loader from '../../common/Loader/Loader'
import Breadcrumbs from '../../common/Breadcrumbs/Breadcrumbs'
import PageActionsMenu from '../../common/PageActionsMenu/PageActionsMenu'
import ProjectCard from '../../elements/ProjectCard/ProjectCard'
import NoData from '../../common/NoData/NoData'
import YamlModal from '../../common/YamlModal/YamlModal'
import Notification from '../../common/Notification/Notification'
import Search from '../../common/Search/Search'
import Sort from '../../common/Sort/Sort'
import CreateProjectDialog from './CreateProjectDialog/CreateProjectDialog'
import ConfirmDialog from '../../common/ConfirmDialog/ConfirmDialog'
import { projectsSortOptions, projectsStates } from './projectsData'
import { SECONDARY_BUTTON, TERTIARY_BUTTON } from '../../constants'
import RoundedIcon from '../../common/RoundedIcon/RoundedIcon'
import { ReactComponent as RefreshIcon } from '../../images/refresh.svg'
import './projects.scss'
const ProjectsView = ({
actionsMenu,
closeNewProjectPopUp,
confirmData,
convertedYaml,
convertToYaml,
createProject,
filterByName,
filteredProjects,
filterMatches,
handleCreateProject,
isDescendingOrder,
isNameValid,
match,
projectStore,
refreshProjects,
removeNewProjectError,
selectedProjectsState,
setCreateProject,
setFilterByName,
setFilterMatches,
setIsDescendingOrder,
setNameValid,
setNewProjectDescription,
setNewProjectLabels,
setNewProjectName,
setSelectedProjectsState,
setSortProjectId,
sortProjectId
}) => {
const projectsClassNames = classnames(
'projects',
(createProject || convertedYaml.length > 0) && 'projects-modal_opened'
)
return (
<div className={projectsClassNames}>
{projectStore.loading && <Loader />}
{createProject && (
<CreateProjectDialog
closeNewProjectPopUp={closeNewProjectPopUp}
handleCreateProject={handleCreateProject}
isNameValid={isNameValid}
removeNewProjectError={removeNewProjectError}
setNameValid={setNameValid}
setNewProjectDescription={setNewProjectDescription}
setNewProjectLabels={setNewProjectLabels}
setNewProjectName={setNewProjectName}
/>
)}
{confirmData && (
<ConfirmDialog
cancelButton={{
handler: confirmData.rejectHandler,
label: 'Cancel',
variant: TERTIARY_BUTTON
}}
closePopUp={confirmData.rejectHandler}
confirmButton={{
handler: () => confirmData.confirmHandler(confirmData.item),
label: confirmData.btnConfirmLabel,
variant: confirmData.btnConfirmType
}}
header={confirmData.header}
message={confirmData.message}
/>
)}
<div className="projects__header">
<Breadcrumbs match={match} />
</div>
<div className="projects__wrapper">
<div className="projects-content-header">
<div className="projects-content-header-item">
<ContentMenu
activeTab={selectedProjectsState}
match={match}
screen="active"
tabs={projectsStates}
onClick={setSelectedProjectsState}
/>
<Sort
isDescendingOrder={isDescendingOrder}
onSelectOption={setSortProjectId}
options={projectsSortOptions}
selectedId={sortProjectId}
setIsDescendingOrder={setIsDescendingOrder}
/>
</div>
<div className="projects-content-header-item">
<Search
className="projects-search"
matches={filterMatches}
onChange={setFilterByName}
placeholder="Search projects..."
setMatches={setFilterMatches}
value={filterByName}
/>
<PageActionsMenu
actionsMenuHeader={'New Project'}
onClick={() => setCreateProject(true)}
showActionsMenu
variant={SECONDARY_BUTTON}
/>
<RoundedIcon
onClick={refreshProjects}
className="panel-title__btn_close"
tooltipText="Refresh"
data-testid="pop-up-close-btn"
>
<RefreshIcon />
</RoundedIcon>
</div>
</div>
{projectStore.projects.length > 0 && !projectStore.error ? (
<div className="projects-content">
{filterByName.length > 0 &&
(filterMatches.length === 0 || filteredProjects.length === 0) ? (
<NoData />
) : selectedProjectsState === 'archived' &&
filteredProjects.length === 0 ? (
<div className="no-filtered-data">No archived projects.</div>
) : (
filteredProjects.map(project => {
return (
<ProjectCard
actionsMenu={actionsMenu}
key={project.id || project.metadata.name}
project={project}
projectSummary={projectStore.projectsSummary.data.find(
item => item.name === project.metadata.name
)}
/>
)
})
)}
</div>
) : projectStore.loading ? null : (
<NoData message="Your projects list is empty." />
)}
</div>
{convertedYaml.length > 0 && (
<YamlModal
convertedYaml={convertedYaml}
toggleConvertToYaml={convertToYaml}
/>
)}
<Notification />
</div>
)
}
ProjectsView.defaultProps = {
confirmData: null
}
ProjectsView.propTypes = {
actionsMenu: PropTypes.shape({}).isRequired,
closeNewProjectPopUp: PropTypes.func.isRequired,
confirmData: PropTypes.shape({}),
convertedYaml: PropTypes.string.isRequired,
convertToYaml: PropTypes.func.isRequired,
createProject: PropTypes.bool.isRequired,
filterByName: PropTypes.string.isRequired,
filteredProjects: PropTypes.arrayOf(PropTypes.shape({})).isRequired,
filterMatches: PropTypes.arrayOf(PropTypes.string).isRequired,
handleCreateProject: PropTypes.func.isRequired,
isNameValid: PropTypes.bool.isRequired,
match: PropTypes.shape({}).isRequired,
refreshProjects: PropTypes.func.isRequired,
removeNewProjectError: PropTypes.func.isRequired,
selectedProjectsState: PropTypes.string.isRequired,
setCreateProject: PropTypes.func.isRequired,
setFilterByName: PropTypes.func.isRequired,
setFilterMatches: PropTypes.func.isRequired,
setIsDescendingOrder: PropTypes.func.isRequired,
setNewProjectDescription: PropTypes.func.isRequired,
setNameValid: PropTypes.func.isRequired,
setNewProjectName: PropTypes.func.isRequired,
setSelectedProjectsState: PropTypes.func.isRequired,
setSortProjectId: PropTypes.func.isRequired,
sortProjectId: PropTypes.string.isRequired
}
export default ProjectsView
|
# coding: utf-8
# ==========================================================================
# Copyright (C) 2016-2021 All rights reserved.
#
# filename : Biaffine.py
# origin : yzhangcs
# author : chendian / [email protected]
# date : 2020-12-15
# desc :
# refer : https://github.com/yzhangcs/parser/blob/main/supar/modules/affine.py
# ==========================================================================
import torch
import torch.nn as nn
class Biaffine(nn.Module):
r"""
Biaffine layer for first-order scoring.
This function has a tensor of weights :math:`W` and bias terms if needed.
The score :math:`s(x, y)` of the vector pair :math:`(x, y)` is computed as :math:`x^T W y`,
in which :math:`x` and :math:`y` can be concatenated with bias terms.
References:
- Timothy Dozat and Christopher D. Manning. 2017.
`Deep Biaffine Attention for Neural Dependency Parsing`_.
Args:
n_in (int):
The size of the input feature.
n_out (int):
The number of output channels.
bias_x (bool):
If ``True``, adds a bias term for tensor :math:`x`. Default: ``True``.
bias_y (bool):
If ``True``, adds a bias term for tensor :math:`y`. Default: ``True``.
.. _Deep Biaffine Attention for Neural Dependency Parsing:
https://openreview.net/forum?id=Hk95PK9le
"""
def __init__(self, n_in, n_out=1, bias_x=True, bias_y=True):
super().__init__()
self.n_in = n_in
self.n_out = n_out
self.bias_x = bias_x
self.bias_y = bias_y
self.weight = nn.Parameter(
torch.Tensor(n_out, n_in+bias_x, n_in+bias_y))
self.reset_parameters()
def __repr__(self):
s = f"n_in={self.n_in}, n_out={self.n_out}"
if self.bias_x:
s += f", bias_x={self.bias_x}"
if self.bias_y:
s += f", bias_y={self.bias_y}"
return f"{self.__class__.__name__}({s})"
def reset_parameters(self):
nn.init.zeros_(self.weight)
def forward(self, x, y):
r"""
Args:
x (torch.Tensor): ``[batch_size, seq_len, n_in]``.
y (torch.Tensor): ``[batch_size, seq_len, n_in]``.
Returns:
~torch.Tensor:
A scoring tensor of shape ``[batch_size, n_out, seq_len, seq_len]``.
If ``n_out=1``, the dimension for ``n_out`` will be squeezed automatically.
"""
if self.bias_x:
x = torch.cat((x, torch.ones_like(x[..., :1])), -1)
if self.bias_y:
y = torch.cat((y, torch.ones_like(y[..., :1])), -1)
# [batch_size, n_out, seq_len, seq_len]
s = torch.einsum('bxi,oij,byj->boxy', x, self.weight, y)
# remove dim 1 if n_out == 1
s = s.squeeze(1)
return s
class Triaffine(nn.Module):
r"""
Triaffine layer for second-order scoring.
This function has a tensor of weights :math:`W` and bias terms if needed.
The score :math:`s(x, y, z)` of the vector triple :math:`(x, y, z)` is computed as :math:`x^T z^T W y`.
Usually, :math:`x` and :math:`y` can be concatenated with bias terms.
References:
- Yu Zhang, Zhenghua Li and Min Zhang. 2020.
`Efficient Second-Order TreeCRF for Neural Dependency Parsing`_.
- Xinyu Wang, Jingxian Huang, and Kewei Tu. 2019.
`Second-Order Semantic Dependency Parsing with End-to-End Neural Networks`_.
Args:
n_in (int):
The size of the input feature.
bias_x (bool):
If ``True``, adds a bias term for tensor :math:`x`. Default: ``False``.
bias_y (bool):
If ``True``, adds a bias term for tensor :math:`y`. Default: ``False``.
.. _Efficient Second-Order TreeCRF for Neural Dependency Parsing:
https://www.aclweb.org/anthology/2020.acl-main.302/
.. _Second-Order Semantic Dependency Parsing with End-to-End Neural Networks:
https://www.aclweb.org/anthology/P19-1454/
"""
def __init__(self, n_in, bias_x=False, bias_y=False):
super().__init__()
self.n_in = n_in
self.bias_x = bias_x
self.bias_y = bias_y
self.weight = nn.Parameter(torch.Tensor(n_in+bias_x, n_in, n_in+bias_y))
self.reset_parameters()
def __repr__(self):
s = f"n_in={self.n_in}"
if self.bias_x:
s += f", bias_x={self.bias_x}"
if self.bias_y:
s += f", bias_y={self.bias_y}"
return f"{self.__class__.__name__}({s})"
def reset_parameters(self):
nn.init.zeros_(self.weight)
def forward(self, x, y, z):
r"""
Args:
x (torch.Tensor): ``[batch_size, seq_len, n_in]``.
y (torch.Tensor): ``[batch_size, seq_len, n_in]``.
z (torch.Tensor): ``[batch_size, seq_len, n_in]``.
Returns:
~torch.Tensor:
A scoring tensor of shape ``[batch_size, seq_len, seq_len, seq_len]``.
"""
if self.bias_x:
x = torch.cat((x, torch.ones_like(x[..., :1])), -1)
if self.bias_y:
y = torch.cat((y, torch.ones_like(y[..., :1])), -1)
w = torch.einsum('bzk,ikj->bzij', z, self.weight)
# [batch_size, seq_len, seq_len, seq_len]
s = torch.einsum('bxi,bzij,byj->bzxy', x, w, y)
return s
if __name__ == '__main__':
ba = Biaffine(n_in=128, n_out=1)
|
import React, {Component} from "react";
class Player extends Component {
constructor(props) {
super(props);
this.initials = props.initials;
this.clicks = props.clicks;
}
render() {
return (
<li id={this.initials+this.clicks} className="player">
{this.clicks} **** {this.initials}
</li>
)
}
}
export default Player; |
# vim: tw=100 foldmethod=marker
# MIT License#
# Copyright (c) 2017 - 2019 Karlsruhe Institute of Technology - Steinbuch Centre for Computing
#
# 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.
# pylint
# pylint: disable=bad-continuation, invalid-name, superfluous-parens
# pylint: disable=bad-whitespace, missing-docstring
#
import os
import logging
from flaat import Flaat
from flask import request
from flaat import tokentools
import json
from aiohttp import web
import logsetup
logger = logsetup.setup_logging()
##########
## Basic config
# AIOHTTP
app = web.Application()
routes = web.RouteTableDef()
# FLAAT
flaat = Flaat()
flaat.set_web_framework('aiohttp')
flaat.set_cache_lifetime(120) # seconds; default is 300
flaat.set_trusted_OP_list([
'https://b2access.eudat.eu/oauth2/',
'https://b2access-integration.fz-juelich.de/oauth2',
'https://unity.helmholtz-data-federation.de/oauth2/',
'https://login.helmholtz-data-federation.de/oauth2/',
'https://login-dev.helmholtz.de/oauth2/',
'https://login.helmholtz.de/oauth2/',
'https://unity.eudat-aai.fz-juelich.de/oauth2/',
'https://services.humanbrainproject.eu/oidc/',
'https://accounts.google.com/',
'https://login.elixir-czech.org/oidc/',
'https://iam-test.indigo-datacloud.eu/',
'https://iam.deep-hybrid-datacloud.eu/',
'https://iam.extreme-datacloud.eu/',
'https://aai.egi.eu/oidc/',
'https://aai-demo.egi.eu/oidc',
'https://aai-dev.egi.eu/oidc',
'https://oidc.scc.kit.edu/auth/realms/kit/',
'https://proxy.demo.eduteams.org',
'https://wlcg.cloud.cnaf.infn.it/'
])
# flaat.set_trusted_OP_file('/etc/oidc-agent/issuer.config')
# flaat.set_OP_hint("helmholtz")
# flaat.set_OP_hint("google")
# verbosity:
# 0: No output
# 1: Errors
# 2: More info, including token info
# 3: Max
flaat.set_verbosity(0)
# flaat.set_verify_tls(True)
# # Required for using token introspection endpoint:
# flaat.set_client_id('')
# flaat.set_client_secret('')
def my_failure_callback(message=''):
return 'User define failure callback.\nError Message: "%s"' % message
@routes.get('/')
async def root(request):
text = '''This is an example for useing flaat with AIO. These endpoints are available:
/info General info about the access_token (if provided)
/valid_user Requires a valid user
/valid_user_2 Requires a valid user, uses a custom callback on error
/group_test_kit Requires user to have two "eduperson_scoped_affiliation" of
['[email protected]', '[email protected]', '[email protected]'],
/group_test_iam Requires user to be in the group "KIT-Cloud" transported in "groups"
/group_test_hdf Requires user to be in all groups found in "eduperson_entitlement"
['urn:geant:h-df.de:group:aai-admin', 'urn:geant:h-df.de:group:myExampleColab#unity.helmholtz-data-federation.de']
/group_test_hdf2 Requires user to be in all groups found in "eduperson_entitlement"
['urn:geant:h-df.de:group:myExampleColab#unity.helmholtz-data-federation.de'],
/group_test_hdf3 Requires user to be in all groups found in "eduperson_entitlement"
['urn:geant:h-df.de:group:aai-admin'],
/group_test_hack A hack to use any other field for authorisation
/group_test_wlcg Requires user to be in the '/wlcg' group
'''
return web.Response(text=text)
@routes.get('/info')
async def info(request):
access_token = tokentools.get_access_token_from_request(request)
info = flaat.get_info_thats_in_at(access_token)
# FIXME: Also display info from userinfo endpoint
x = json.dumps(info, sort_keys=True, indent=4, separators=(',', ': '))
return web.Response(text=str(x))
@routes.get('/valid_user')
@flaat.login_required()
async def valid_user(request):
return web.Response(text='This worked: there was a valid login')
@routes.get('/valid_user_2')
@flaat.login_required(on_failure=my_failure_callback)
async def valid_user_own_callback(request):
return web.Response(text='This worked: there was a valid login')
@routes.get('/group_test_kit')
@flaat.group_required(group=['[email protected]', '[email protected]', '[email protected]'],
claim='eduperson_scoped_affiliation', match=2,
on_failure=my_failure_callback)
async def demo_groups_kit(request):
return web.Response(text='This worked: user is member of the requested group')
@routes.get('/group_test_iam')
@flaat.group_required(group='KIT-Cloud', claim='groups')
async def demo_groups_iam(request):
return web.Response(text='This worked: user is member of the requested group')
@routes.get('/group_test_hdf')
@flaat.aarc_g002_group_required(group=['urn:geant:h-df.de:group:m-team:feudal-developers',
'urn:geant:h-df.de:group:MyExampleColab#unity.helmholtz.de'],
claim='eduperson_entitlement', match='all')
async def demo_groups_hdf(request):
return web.Response(text='This worked: user has the required entitlement(s)')
@routes.get('/group_test_hdf2')
@flaat.aarc_g002_group_required(group=['urn:geant:h-df.de:group:MyExampleColab'],
claim='eduperson_entitlement', match='all')
async def demo_groups_hdf2(request):
return web.Response(text='This worked: user has the required entitlement(s)')
@routes.get('/group_test_hdf3')
@flaat.aarc_g002_group_required(group=['urn:geant:h-df.de:group:MyExampleColab',
'urn:geant:h-df.de:group:m-team:feudal-developers'],
claim='eduperson_entitlement', match='all')
async def demo_groups_hdf3(request):
return web.Response(text='This worked: user has the required entitlement(s)')
@routes.get('/group_test_hack')
@flaat.group_required(group=['Hardt'],
claim='family_name', match='all')
async def demo_groups_hack(request):
return web.Response(text="This worked: user has the required Group Membership")
@routes.get('/group_test_wlcg')
@flaat.group_required(group='/wlcg',
claim='wlcg.groups', match='all')
async def demo_groups_wlcg(request):
return web.Response(text="This worked: user has the required Group Membership")
@routes.get('/role_test_egi')
@flaat.aarc_g002_group_required(group=['urn:mace:egi.eu:group:mteam.data.kit.edu:role=member'],
claim='eduperson_entitlement', match='all')
async def demo_role_egi(request):
return web.Response(text='This worked: user is member of the requested group and role')
app.add_routes(routes)
##########
# Main
if __name__ == '__main__':
web.run_app(app, host="0.0.0.0", port=8083)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.