file_name
stringlengths 3
137
| prefix
stringlengths 0
918k
| suffix
stringlengths 0
962k
| middle
stringlengths 0
812k
|
---|---|---|---|
gatorosc.py
|
from collections import namedtuple
import numpy as np
import talib
from jesse.helpers import get_candle_source, np_shift
from jesse.helpers import slice_candles
GATOR = namedtuple('GATOR', ['upper', 'lower', 'upper_change', 'lower_change'])
def gatorosc(candles: np.ndarray, source_type: str = "close", sequential: bool = False) -> GATOR:
"""
Gator Oscillator by Bill M. Williams
:param candles: np.ndarray
:param source_type: str - default: "close"
:param sequential: bool - default: False
|
candles = slice_candles(candles, sequential)
source = get_candle_source(candles, source_type=source_type)
jaw = np_shift(numpy_ewma(source, 13), 8, fill_value=np.nan)
teeth = np_shift(numpy_ewma(source, 8), 5, fill_value=np.nan)
lips = np_shift(numpy_ewma(source, 5), 3, fill_value=np.nan)
upper = np.abs(jaw - teeth)
lower = -np.abs(teeth - lips)
upper_change = talib.MOM(upper, timeperiod=1)
lower_change = -talib.MOM(lower, timeperiod=1)
if sequential:
return GATOR(upper, lower, upper_change, lower_change)
else:
return GATOR(upper[-1], lower[-1], upper_change[-1], lower_change[-1])
def numpy_ewma(data, window):
"""
:param data:
:param window:
:return:
"""
alpha = 1 / window
# scale = 1 / (1 - alpha)
n = data.shape[0]
scale_arr = (1 - alpha) ** (-1 * np.arange(n))
weights = (1 - alpha) ** np.arange(n)
pw0 = (1 - alpha) ** (n - 1)
mult = data * pw0 * scale_arr
cumsums = mult.cumsum()
return cumsums * scale_arr[::-1] / weights.cumsum()
|
:return: GATOR(upper, lower, upper_change, lower_change)
"""
|
main.rs
|
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;
use std::fs::File;
fn main()
|
fn handle_connection(mut stream: TcpStream) {
let mut buffer = [0; 512];
stream.read(&mut buffer).unwrap();
let get = b"GET / HTTP/1.1\r\n";
let (status_line, filename) = if buffer.starts_with(get) {
("HTTP/1.1 200 OK\r\n\r\n{}","sample.html")
} else {
("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html")
};
let mut file = File::open(filename).unwrap();
let mut contents = String::new();
file.read_to_string(&mut contents).unwrap();
let response = format!("{}{}", status_line, contents);
stream.write(response.as_bytes()).unwrap();
stream.flush().unwrap();
println!("Request: {}", String::from_utf8_lossy(&buffer[..]));
}
|
{
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
for stream in listener.incoming() {
let stream = stream.unwrap();
handle_connection(stream);
}
}
|
__init__.py
|
"""
.. module sgsclient
This module contains the client library code. In general, a client should
subclass ``StratumGSClientInstance`` and call the ``main`` function.
"""
import json
import socket
import sys
version = "0.1.0"
class StratumGSClient(object):
def __init__(self, settings, client_instance_constructor):
self._settings = settings
self._socket = None
self._socket_readfile = None
self._socket_writefile = None
self._client_instance_constructor = client_instance_constructor
self._client_instances = {}
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
if self._socket_writefile:
self._socket_writefile.close()
if self._socket_readfile:
self._socket_readfile.close()
if self._socket:
self._socket.close()
def connect(self):
self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
address = (self._settings["host"], self._settings["port"])
try:
self._socket.connect(address)
except ConnectionError:
print("Failed to connect to the specified host {}:{}".format(*address))
sys.exit(1)
self._socket_readfile = self._socket.makefile('rb', 0)
self._socket_writefile = self._socket.makefile('wb', 0)
self.send_obj_to_server({
"type": "connect",
"name": self._settings["name"],
"supported_games": self._settings["supported_games"],
"max_games": self._settings["max_games"]
})
response = self._receive_obj_from_server()
if response["type"] != "name":
print("Invalid response received from server")
sys.exit(1)
self._settings["name"] = response["name"]
print("Connected to server as {}".format(response["name"]))
def run(self):
while True:
obj = self._receive_obj_from_server()
if obj["type"] == "close":
game_id = obj["game_id"]
if game_id in self._client_instances:
self._client_instances[game_id].server_closed_connection()
del self._client_instances[game_id]
elif obj["type"] == "message":
game_id = obj["game_id"]
message = json.loads(obj["payload"])
if game_id in self._client_instances:
self._client_instances[game_id].message_received_from_server(message)
elif obj["type"] == "start":
game_id = obj["game_id"]
client_instance = self._client_instance_constructor(self, game_id)
self._client_instances[game_id] = client_instance
else:
print("Invalid response received from server")
sys.exit(1)
def send_obj_to_server(self, obj):
s = json.dumps(obj) + "\n"
self._socket_writefile.write(s.encode())
def _receive_obj_from_server(self):
b = self._socket_readfile.readline()
return json.loads(b.decode().strip())
class StratumGSClientInstance:
"""
The client instance that is instantiated for each game. This class
should be subclassed, and the methods ``server_closed_connection`` and
``message_received_from_server`` should be implemented.
:param client: The client that spawned this instance.
:type client: :class:`StratumGSClient`
:param game_id: The game id of the new game.
:type game_id: int
"""
def __init__(self, client, game_id):
self._client = client
self._game_id = game_id
def send_message_to_server(self, message):
"""
Send a message to the engine. The message should be a JSON-encodable
object. This method will encode the message, wrap it with the
appropriate message for the server, and send it.
:param message: A JSON-encodable message object for the engine.
"""
self._client.send_obj_to_server({
"type": "message",
"game_id": self._game_id,
"payload": json.dumps(message)
})
def server_closed_connection(self):
"""
**Must be implemented by the subclass.**
Called to notify the client that the server closed the connection.
"""
print("Server closed the connection")
def message_received_from_server(self, message):
"""
**Must be implemented by the subclass.**
Called when a message for this game is received from the server.
Message will be the decoded value of the ``payload`` parameter of
the original message from the server.
:param message: The decoded message.
"""
raise NotImplementedError
def main(client_instance_constructor, **kwargs):
"""
The main run loop for the client. This function parses the command line
arguments, then parses the ``kwargs``.
The following configuration parameters are accepted as keyword
arguments:
- **host**: The host to connect to.
- **port**: The port to connect to.
- **name**: The name to request to connect with.
- **supported_games**: The list of supported games.
- **max_games**: The maximum number of games the client can support.
:param client_instance_constructor: The class to instantiate for client
instances.
"""
settings = {
"host": "localhost",
"port": 8889,
"name": None,
"supported_games": [],
"max_games": 5
}
# parse keyword arg parameters
for key, value in kwargs.items():
if key in settings:
settings[key] = value
# parse command line arg parameters
args = sys.argv[1:]
while args:
try:
arg = args.pop(0)
if arg == "--host":
|
elif arg == "--port":
settings["port"] = int(args.pop(0))
elif arg == "--max-games":
settings["max_games"] = int(args.pop(0))
else:
print("Invalid argument.")
sys.exit(1)
except:
print("Invalid argument format.")
sys.exit(1)
with StratumGSClient(settings, client_instance_constructor) as client:
client.connect()
client.run()
|
settings["host"] = args.pop(0)
|
data.ts
|
import rough from "roughjs/bin/rough";
import { ExcalidrawElement } from "../element/types";
import { getElementAbsoluteCoords } from "../element";
import { renderScene } from "../renderer";
import { AppState } from "../types";
import { ExportType } from "./types";
import nanoid from "nanoid";
const LOCAL_STORAGE_KEY = "excalidraw";
const LOCAL_STORAGE_KEY_STATE = "excalidraw-state";
function saveFile(name: string, data: string) {
// create a temporary <a> elem which we'll use to download the image
const link = document.createElement("a");
link.setAttribute("download", name);
link.setAttribute("href", data);
link.click();
// clean up
link.remove();
}
interface DataState {
|
appState: any;
}
export function saveAsJSON(
elements: readonly ExcalidrawElement[],
name: string
) {
const serialized = JSON.stringify({
version: 1,
source: window.location.origin,
elements: elements.map(({ shape, ...el }) => el)
});
saveFile(
`${name}.json`,
"data:text/plain;charset=utf-8," + encodeURIComponent(serialized)
);
}
export function loadFromJSON() {
const input = document.createElement("input");
const reader = new FileReader();
input.type = "file";
input.accept = ".json";
input.onchange = () => {
if (!input.files!.length) {
alert("A file was not selected.");
return;
}
reader.readAsText(input.files![0], "utf8");
};
input.click();
return new Promise<DataState>(resolve => {
reader.onloadend = () => {
if (reader.readyState === FileReader.DONE) {
let elements = [];
try {
const data = JSON.parse(reader.result as string);
elements = data.elements || [];
} catch (e) {
// Do nothing because elements array is already empty
}
resolve(restore(elements, null));
}
};
});
}
export function getExportCanvasPreview(
elements: readonly ExcalidrawElement[],
{
exportBackground,
exportPadding = 10,
viewBackgroundColor
}: {
exportBackground: boolean;
exportPadding?: number;
viewBackgroundColor: string;
}
) {
// calculate smallest area to fit the contents in
let subCanvasX1 = Infinity;
let subCanvasX2 = 0;
let subCanvasY1 = Infinity;
let subCanvasY2 = 0;
elements.forEach(element => {
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
subCanvasX1 = Math.min(subCanvasX1, x1);
subCanvasY1 = Math.min(subCanvasY1, y1);
subCanvasX2 = Math.max(subCanvasX2, x2);
subCanvasY2 = Math.max(subCanvasY2, y2);
});
function distance(x: number, y: number) {
return Math.abs(x > y ? x - y : y - x);
}
const tempCanvas = document.createElement("canvas");
tempCanvas.width = distance(subCanvasX1, subCanvasX2) + exportPadding * 2;
tempCanvas.height = distance(subCanvasY1, subCanvasY2) + exportPadding * 2;
renderScene(
elements,
rough.canvas(tempCanvas),
tempCanvas,
{
viewBackgroundColor: exportBackground ? viewBackgroundColor : null,
scrollX: 0,
scrollY: 0
},
{
offsetX: -subCanvasX1 + exportPadding,
offsetY: -subCanvasY1 + exportPadding,
renderScrollbars: false,
renderSelection: false
}
);
return tempCanvas;
}
export function exportCanvas(
type: ExportType,
elements: readonly ExcalidrawElement[],
canvas: HTMLCanvasElement,
{
exportBackground,
exportPadding = 10,
viewBackgroundColor,
name
}: {
exportBackground: boolean;
exportPadding?: number;
viewBackgroundColor: string;
scrollX: number;
scrollY: number;
name: string;
}
) {
if (!elements.length) return window.alert("Cannot export empty canvas.");
// calculate smallest area to fit the contents in
let subCanvasX1 = Infinity;
let subCanvasX2 = 0;
let subCanvasY1 = Infinity;
let subCanvasY2 = 0;
elements.forEach(element => {
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
subCanvasX1 = Math.min(subCanvasX1, x1);
subCanvasY1 = Math.min(subCanvasY1, y1);
subCanvasX2 = Math.max(subCanvasX2, x2);
subCanvasY2 = Math.max(subCanvasY2, y2);
});
function distance(x: number, y: number) {
return Math.abs(x > y ? x - y : y - x);
}
const tempCanvas = document.createElement("canvas");
tempCanvas.style.display = "none";
document.body.appendChild(tempCanvas);
tempCanvas.width = distance(subCanvasX1, subCanvasX2) + exportPadding * 2;
tempCanvas.height = distance(subCanvasY1, subCanvasY2) + exportPadding * 2;
renderScene(
elements,
rough.canvas(tempCanvas),
tempCanvas,
{
viewBackgroundColor: exportBackground ? viewBackgroundColor : null,
scrollX: 0,
scrollY: 0
},
{
offsetX: -subCanvasX1 + exportPadding,
offsetY: -subCanvasY1 + exportPadding,
renderScrollbars: false,
renderSelection: false
}
);
if (type === "png") {
saveFile(`${name}.png`, tempCanvas.toDataURL("image/png"));
} else if (type === "clipboard") {
try {
tempCanvas.toBlob(async function(blob) {
try {
await navigator.clipboard.write([
new window.ClipboardItem({ "image/png": blob })
]);
} catch (err) {
window.alert("Couldn't copy to clipboard. Try using Chrome browser.");
}
});
} catch (err) {
window.alert("Couldn't copy to clipboard. Try using Chrome browser.");
}
}
// clean up the DOM
if (tempCanvas !== canvas) tempCanvas.remove();
}
function restore(
savedElements: readonly ExcalidrawElement[],
savedState: any
): DataState {
return {
elements: savedElements.map(element => ({
...element,
id: element.id || nanoid(),
fillStyle: element.fillStyle || "hachure",
strokeWidth: element.strokeWidth || 1,
roughness: element.roughness || 1,
opacity:
element.opacity === null || element.opacity === undefined
? 100
: element.opacity
})),
appState: savedState
};
}
export function restoreFromLocalStorage() {
const savedElements = localStorage.getItem(LOCAL_STORAGE_KEY);
const savedState = localStorage.getItem(LOCAL_STORAGE_KEY_STATE);
let elements = [];
if (savedElements) {
try {
elements = JSON.parse(savedElements).map(
({ shape, ...element }: ExcalidrawElement) => element
);
} catch (e) {
// Do nothing because elements array is already empty
}
}
let appState = null;
if (savedState) {
try {
appState = JSON.parse(savedState);
} catch (e) {
// Do nothing because appState is already null
}
}
return restore(elements, appState);
}
export function saveToLocalStorage(
elements: readonly ExcalidrawElement[],
state: AppState
) {
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(elements));
localStorage.setItem(LOCAL_STORAGE_KEY_STATE, JSON.stringify(state));
}
|
elements: readonly ExcalidrawElement[];
|
error.rs
|
// This file is part of Substrate.
// Copyright (C) 2020-2021 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// 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 3 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, see <https://www.gnu.org/licenses/>.
//! Offchain RPC errors.
use jsonrpc_core as rpc;
/// Offchain RPC Result type.
pub type Result<T> = std::result::Result<T, Error>;
/// Offchain RPC errors.
#[derive(Debug, derive_more::Display, derive_more::From)]
pub enum
|
{
/// Unavailable storage kind error.
#[display(fmt="This storage kind is not available yet.")]
UnavailableStorageKind,
/// Call to an unsafe RPC was denied.
UnsafeRpcCalled(crate::policy::UnsafeRpcError),
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::UnsafeRpcCalled(err) => Some(err),
_ => None,
}
}
}
/// Base error code for all offchain errors.
const BASE_ERROR: i64 = 5000;
impl From<Error> for rpc::Error {
fn from(e: Error) -> Self {
match e {
Error::UnavailableStorageKind => rpc::Error {
code: rpc::ErrorCode::ServerError(BASE_ERROR + 1),
message: "This storage kind is not available yet" .into(),
data: None,
},
Error::UnsafeRpcCalled(e) => e.into(),
}
}
}
|
Error
|
9093-1.py
|
# Stack 활용해서 풀기
N = int(input())
class Node(object):
def __init__(self, value=None, next=None):
self.value = value
self.next = next
class Stack(object):
def __init__(self):
self.head = None
self.count = 0
def is_empty(self):
return not bool(self.head)
def push(self, item):
self.head = Node(item, self.head)
self.count += 1
def pop(self):
if self.count > 0:
node = self.head
self.head = node.next
self.count -= 1
return node.value
else:
print('Stack is empty')
def peek(self):
if self.count > 0:
return self.head.value
else:
print('Stack is empty')
def size(self):
return self.size
def reverse_with_stack(sentence):
s = Stack()
for i in range(len(sentence)):
|
while not s.is_empty():
print(s.peek(), end='')
s.pop()
print(sentence[i], end='')
else:
s.push(sentence[i])
while N:
sentence = input()
sentence += '\n'
reverse_with_stack(sentence)
N-=1
|
if sentence[i] == ' ' or sentence[i]=='\n':
|
rabbitmq_test.go
|
package rabbitmq_test
import (
"context"
"os"
"testing"
micro "github.com/asim/go-micro/v3"
broker "github.com/asim/go-micro/v3/broker"
server "github.com/asim/go-micro/v3/server"
rabbitmq "github.com/asim/go-micro/plugins/broker/rabbitmq/v3"
)
type Example struct{}
func (e *Example) Handler(ctx context.Context, r interface{}) error {
return nil
}
func TestDurable(t *testing.T)
|
{
if tr := os.Getenv("TRAVIS"); len(tr) > 0 {
t.Skip()
}
rabbitmq.DefaultRabbitURL = "amqp://rabbitmq:[email protected]:5672"
brkrSub := broker.NewSubscribeOptions(
broker.Queue("queue.default"),
broker.DisableAutoAck(),
rabbitmq.DurableQueue(),
)
b := rabbitmq.NewBroker()
b.Init()
if err := b.Connect(); err != nil {
t.Logf("cant conect to broker, skip: %v", err)
t.Skip()
}
s := server.NewServer(server.Broker(b))
service := micro.NewService(
micro.Server(s),
micro.Broker(b),
)
h := &Example{}
// Register a subscriber
micro.RegisterSubscriber(
"topic",
service.Server(),
h.Handler,
server.SubscriberContext(brkrSub.Context),
server.SubscriberQueue("queue.default"),
)
//service.Init()
if err := service.Run(); err != nil {
t.Fatal(err)
}
}
|
|
combo_dose.py
|
#! /usr/bin/env python
from __future__ import division, print_function
import argparse
import collections
import logging
import os
import random
import threading
import numpy as np
import pandas as pd
from itertools import cycle, islice
import keras
from keras import backend as K
from keras import optimizers
from keras.models import Model
from keras.layers import Input, Dense, Dropout
from keras.callbacks import Callback, ModelCheckpoint, ReduceLROnPlateau, LearningRateScheduler, TensorBoard
from keras.utils import get_custom_objects
from keras.utils.vis_utils import plot_model
from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error
from sklearn.model_selection import KFold, StratifiedKFold, GroupKFold
from scipy.stats.stats import pearsonr
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import combo
import candle
import NCI60
logger = logging.getLogger(__name__)
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
def set_seed(seed):
os.environ['PYTHONHASHSEED'] = '0'
np.random.seed(seed)
random.seed(seed)
if K.backend() == 'tensorflow':
import tensorflow as tf
tf.set_random_seed(seed)
# session_conf = tf.ConfigProto(intra_op_parallelism_threads=1, inter_op_parallelism_threads=1)
# sess = tf.Session(graph=tf.get_default_graph(), config=session_conf)
# K.set_session(sess)
# Uncommit when running on an optimized tensorflow where NUM_INTER_THREADS and
# NUM_INTRA_THREADS env vars are set.
# session_conf = tf.ConfigProto(inter_op_parallelism_threads=int(os.environ['NUM_INTER_THREADS']),
# intra_op_parallelism_threads=int(os.environ['NUM_INTRA_THREADS']))
# sess = tf.Session(graph=tf.get_default_graph(), config=session_conf)
# K.set_session(sess)
def verify_path(path):
folder = os.path.dirname(path)
if folder and not os.path.exists(folder):
os.makedirs(folder)
def set_up_logger(logfile, verbose):
verify_path(logfile)
fh = logging.FileHandler(logfile)
fh.setFormatter(logging.Formatter("[%(asctime)s %(process)d] %(message)s", datefmt="%Y-%m-%d %H:%M:%S"))
fh.setLevel(logging.DEBUG)
sh = logging.StreamHandler()
sh.setFormatter(logging.Formatter(''))
sh.setLevel(logging.DEBUG if verbose else logging.INFO)
logger.setLevel(logging.DEBUG)
logger.addHandler(fh)
logger.addHandler(sh)
def extension_from_parameters(args):
"""Construct string for saving model with annotation of parameters"""
ext = ''
ext += '.A={}'.format(args.activation)
ext += '.B={}'.format(args.batch_size)
ext += '.E={}'.format(args.epochs)
ext += '.O={}'.format(args.optimizer)
# ext += '.LEN={}'.format(args.maxlen)
ext += '.LR={}'.format(args.learning_rate)
ext += '.CF={}'.format(''.join([x[0] for x in sorted(args.cell_features)]))
ext += '.DF={}'.format(''.join([x[0] for x in sorted(args.drug_features)]))
if args.feature_subsample > 0:
ext += '.FS={}'.format(args.feature_subsample)
if args.dropout > 0:
ext += '.DR={}'.format(args.dropout)
if args.warmup_lr:
ext += '.wu_lr'
if args.reduce_lr:
ext += '.re_lr'
if args.residual:
ext += '.res'
if args.use_landmark_genes:
ext += '.L1000'
if args.gen:
ext += '.gen'
if args.use_combo_score:
ext += '.scr'
for i, n in enumerate(args.dense):
if n > 0:
ext += '.D{}={}'.format(i+1, n)
if args.dense_feature_layers != args.dense:
for i, n in enumerate(args.dense):
if n > 0:
ext += '.FD{}={}'.format(i+1, n)
return ext
def discretize(y, bins=5):
percentiles = [100 / bins * (i + 1) for i in range(bins - 1)]
thresholds = [np.percentile(y, x) for x in percentiles]
classes = np.digitize(y, thresholds)
return classes
class ComboDataLoader(object):
"""Load merged drug response, drug descriptors and cell line essay data
"""
def __init__(self, seed, val_split=0.2, shuffle=True,
cell_features=['expression'], drug_features=['descriptors'],
response_url=None, use_landmark_genes=False, use_combo_score=False,
preprocess_rnaseq=None, exclude_cells=[], exclude_drugs=[],
feature_subsample=None, scaling='std', scramble=False,
cv_partition='overlapping', cv=0):
"""Initialize data merging drug response, drug descriptors and cell line essay.
Shuffle and split training and validation set
Parameters
----------
seed: integer
seed for random generation
val_split : float, optional (default 0.2)
fraction of data to use in validation
cell_features: list of strings from 'expression', 'expression_5platform', 'mirna', 'proteome', 'all', 'categorical' (default ['expression'])
use one or more cell line feature sets: gene expression, microRNA, proteome
use 'all' for ['expression', 'mirna', 'proteome']
use 'categorical' for one-hot encoded cell lines
drug_features: list of strings from 'descriptors', 'latent', 'all', 'categorical', 'noise' (default ['descriptors'])
use dragon7 descriptors, latent representations from Aspuru-Guzik's SMILES autoencoder
trained on NSC drugs, or both; use random features if set to noise
use 'categorical' for one-hot encoded drugs
shuffle : True or False, optional (default True)
if True shuffles the merged data before splitting training and validation sets
scramble: True or False, optional (default False)
if True randomly shuffle dose response data as a control
feature_subsample: None or integer (default None)
number of feature columns to use from cellline expressions and drug descriptors
use_landmark_genes: True or False
only use LINCS1000 landmark genes
use_combo_score: bool (default False)
use combination score in place of percent growth (stored in 'GROWTH' column)
scaling: None, 'std', 'minmax' or 'maxabs' (default 'std')
type of feature scaling: 'maxabs' to [-1,1], 'maxabs' to [-1, 1], 'std' for standard normalization
"""
self.cv_partition = cv_partition
np.random.seed(seed)
df = NCI60.load_combo_dose_response(response_url=response_url, use_combo_score=use_combo_score, fraction=True, exclude_cells=exclude_cells, exclude_drugs=exclude_drugs)
logger.info('Loaded {} unique (CL, D1, D2) response sets.'.format(df.shape[0]))
if 'all' in cell_features:
self.cell_features = ['expression', 'mirna', 'proteome']
else:
self.cell_features = cell_features
if 'all' in drug_features:
self.drug_features = ['descriptors', 'latent']
else:
self.drug_features = drug_features
for fea in self.cell_features:
if fea == 'expression' or fea == 'rnaseq':
self.df_cell_expr = NCI60.load_cell_expression_rnaseq(ncols=feature_subsample, scaling=scaling, use_landmark_genes=use_landmark_genes, preprocess_rnaseq=preprocess_rnaseq)
df = df.merge(self.df_cell_expr[['CELLNAME']], on='CELLNAME')
elif fea == 'expression_u133p2':
self.df_cell_expr = NCI60.load_cell_expression_u133p2(ncols=feature_subsample, scaling=scaling, use_landmark_genes=use_landmark_genes)
df = df.merge(self.df_cell_expr[['CELLNAME']], on='CELLNAME')
elif fea == 'expression_5platform':
self.df_cell_expr = NCI60.load_cell_expression_5platform(ncols=feature_subsample, scaling=scaling, use_landmark_genes=use_landmark_genes)
df = df.merge(self.df_cell_expr[['CELLNAME']], on='CELLNAME')
elif fea == 'mirna':
self.df_cell_mirna = NCI60.load_cell_mirna(ncols=feature_subsample, scaling=scaling)
df = df.merge(self.df_cell_mirna[['CELLNAME']], on='CELLNAME')
elif fea == 'proteome':
self.df_cell_prot = NCI60.load_cell_proteome(ncols=feature_subsample, scaling=scaling)
df = df.merge(self.df_cell_prot[['CELLNAME']], on='CELLNAME')
elif fea == 'categorical':
df_cell_ids = df[['CELLNAME']].drop_duplicates()
cell_ids = df_cell_ids['CELLNAME'].map(lambda x: x.replace(':', '.'))
df_cell_cat = pd.get_dummies(cell_ids)
df_cell_cat.index = df_cell_ids['CELLNAME']
self.df_cell_cat = df_cell_cat.reset_index()
for fea in self.drug_features:
if fea == 'descriptors':
self.df_drug_desc = NCI60.load_drug_descriptors(ncols=feature_subsample, scaling=scaling)
df = df[df['NSC1'].isin(self.df_drug_desc['NSC']) & df['NSC2'].isin(self.df_drug_desc['NSC'])]
elif fea == 'latent':
self.df_drug_auen = NCI60.load_drug_autoencoded_AG(ncols=feature_subsample, scaling=scaling)
df = df[df['NSC1'].isin(self.df_drug_auen['NSC']) & df['NSC2'].isin(self.df_drug_auen['NSC'])]
elif fea == 'categorical':
df_drug_ids = df[['NSC1']].drop_duplicates()
df_drug_ids.columns = ['NSC']
drug_ids = df_drug_ids['NSC']
df_drug_cat = pd.get_dummies(drug_ids)
df_drug_cat.index = df_drug_ids['NSC']
self.df_drug_cat = df_drug_cat.reset_index()
elif fea == 'noise':
ids1 = df[['NSC1']].drop_duplicates().rename(columns={'NSC1':'NSC'})
ids2 = df[['NSC2']].drop_duplicates().rename(columns={'NSC2':'NSC'})
df_drug_ids = pd.concat([ids1, ids2]).drop_duplicates()
noise = np.random.normal(size=(df_drug_ids.shape[0], 500))
df_rand = pd.DataFrame(noise, index=df_drug_ids['NSC'],
columns=['RAND-{:03d}'.format(x) for x in range(500)])
self.df_drug_rand = df_rand.reset_index()
logger.info('Filtered down to {} rows with matching information.'.format(df.shape[0]))
ids1 = df[['NSC1']].drop_duplicates().rename(columns={'NSC1':'NSC'})
ids2 = df[['NSC2']].drop_duplicates().rename(columns={'NSC2':'NSC'})
df_drug_ids = pd.concat([ids1, ids2]).drop_duplicates().reset_index(drop=True)
n_drugs = df_drug_ids.shape[0]
n_val_drugs = int(n_drugs * val_split)
n_train_drugs = n_drugs - n_val_drugs
logger.info('Unique cell lines: {}'.format(df['CELLNAME'].nunique()))
logger.info('Unique drugs: {}'.format(n_drugs))
# df.to_csv('filtered.growth.min.tsv', sep='\t', index=False, float_format='%.4g')
# df.to_csv('filtered.score.max.tsv', sep='\t', index=False, float_format='%.4g')
if shuffle:
df = df.sample(frac=1.0, random_state=seed).reset_index(drop=True)
df_drug_ids = df_drug_ids.sample(frac=1.0, random_state=seed).reset_index(drop=True)
self.df_response = df
self.df_drug_ids = df_drug_ids
self.train_drug_ids = df_drug_ids['NSC'][:n_train_drugs]
self.val_drug_ids = df_drug_ids['NSC'][-n_val_drugs:]
if scramble:
growth = df[['GROWTH']]
random_growth = growth.iloc[np.random.permutation(np.arange(growth.shape[0]))].reset_index()
self.df_response[['GROWTH']] = random_growth['GROWTH']
logger.warn('Randomly shuffled dose response growth values.')
logger.info('Distribution of dose response:')
logger.info(self.df_response[['GROWTH']].describe())
self.total = df.shape[0]
self.n_val = int(self.total * val_split)
self.n_train = self.total - self.n_val
logger.info('Rows in train: {}, val: {}'.format(self.n_train, self.n_val))
self.cell_df_dict = {'expression': 'df_cell_expr',
'expression_5platform': 'df_cell_expr',
'expression_u133p2': 'df_cell_expr',
'rnaseq': 'df_cell_expr',
'mirna': 'df_cell_mirna',
'proteome': 'df_cell_prot',
'categorical': 'df_cell_cat'}
self.drug_df_dict = {'descriptors': 'df_drug_desc',
'latent': 'df_drug_auen',
'categorical': 'df_drug_cat',
'noise': 'df_drug_rand'}
self.input_features = collections.OrderedDict()
self.feature_shapes = {}
for fea in self.cell_features:
feature_type = 'cell.' + fea
feature_name = 'cell.' + fea
df_cell = getattr(self, self.cell_df_dict[fea])
self.input_features[feature_name] = feature_type
self.feature_shapes[feature_type] = (df_cell.shape[1] - 1,)
for drug in ['drug1', 'drug2']:
for fea in self.drug_features:
feature_type = 'drug.' + fea
feature_name = drug + '.' + fea
df_drug = getattr(self, self.drug_df_dict[fea])
self.input_features[feature_name] = feature_type
self.feature_shapes[feature_type] = (df_drug.shape[1] - 1,)
self.feature_shapes['dose'] = (1,)
for dose in ['dose1', 'dose2']:
self.input_features[dose] = 'dose'
logger.info('Input features shapes:')
for k, v in self.input_features.items():
logger.info(' {}: {}'.format(k, self.feature_shapes[v]))
self.input_dim = sum([np.prod(self.feature_shapes[x]) for x in self.input_features.values()])
logger.info('Total input dimensions: {}'.format(self.input_dim))
if cv > 1:
if cv_partition == 'disjoint':
pass
elif cv_partition == 'disjoint_cells':
y = self.df_response['GROWTH'].values
groups = self.df_response['CELLNAME'].values
gkf = GroupKFold(n_splits=cv)
splits = gkf.split(y, groups=groups)
self.cv_train_indexes = []
self.cv_val_indexes = []
for index, (train_index, val_index) in enumerate(splits):
print(index, train_index)
self.cv_train_indexes.append(train_index)
self.cv_val_indexes.append(val_index)
else:
y = self.df_response['GROWTH'].values
# kf = KFold(n_splits=cv)
# splits = kf.split(y)
skf = StratifiedKFold(n_splits=cv, random_state=seed)
splits = skf.split(y, discretize(y, bins=cv))
self.cv_train_indexes = []
self.cv_val_indexes = []
for index, (train_index, val_index) in enumerate(splits):
print(index, train_index)
self.cv_train_indexes.append(train_index)
self.cv_val_indexes.append(val_index)
def load_data_all(self, switch_drugs=False):
df_all = self.df_response
y_all = df_all['GROWTH'].values
x_all_list = []
for fea in self.cell_features:
df_cell = getattr(self, self.cell_df_dict[fea])
df_x_all = pd.merge(df_all[['CELLNAME']], df_cell, on='CELLNAME', how='left')
x_all_list.append(df_x_all.drop(['CELLNAME'], axis=1).values)
# for fea in loader.cell_features:
# df_cell = getattr(loader, loader.cell_df_dict[fea])
# df_x_all = pd.merge(df_all[['CELLNAME']], df_cell, on='CELLNAME', how='left')
# df_x_all[:1000].to_csv('df.{}.1k.csv'.format(fea), index=False, float_format="%g")
drugs = ['NSC1', 'NSC2']
doses = ['pCONC1', 'pCONC2']
if switch_drugs:
drugs = ['NSC2', 'NSC1']
doses = ['pCONC2', 'pCONC1']
for drug in drugs:
for fea in self.drug_features:
df_drug = getattr(self, self.drug_df_dict[fea])
df_x_all = pd.merge(df_all[[drug]], df_drug, left_on=drug, right_on='NSC', how='left')
x_all_list.append(df_x_all.drop([drug, 'NSC'], axis=1).values)
for dose in doses:
x_all_list.append(df_all[dose].values)
# for drug in drugs:
# for fea in loader.drug_features:
# df_drug = getattr(loader, loader.drug_df_dict[fea])
# df_x_all = pd.merge(df_all[[drug]], df_drug, left_on=drug, right_on='NSC', how='left')
# print(df_x_all.shape)
# df_x_all[:1000].drop([drug], axis=1).to_csv('df.{}.{}.1k.csv'.format(drug, fea), index=False, float_format="%g")
# df_all[:1000].to_csv('df.growth.1k.csv', index=False, float_format="%g")
return x_all_list, y_all, df_all
def load_data_by_index(self, train_index, val_index):
x_all_list, y_all, df_all = self.load_data_all()
x_train_list = [x[train_index] for x in x_all_list]
x_val_list = [x[val_index] for x in x_all_list]
y_train = y_all[train_index]
y_val = y_all[val_index]
df_train = df_all.iloc[train_index, :]
df_val = df_all.iloc[val_index, :]
if self.cv_partition == 'disjoint':
logger.info('Training drugs: {}'.format(set(df_train['NSC1'])))
logger.info('Validation drugs: {}'.format(set(df_val['NSC1'])))
elif self.cv_partition == 'disjoint_cells':
logger.info('Training cells: {}'.format(set(df_train['CELLNAME'])))
logger.info('Validation cells: {}'.format(set(df_val['CELLNAME'])))
return x_train_list, y_train, x_val_list, y_val, df_train, df_val
def load_data_cv(self, fold):
train_index = self.cv_train_indexes[fold]
val_index = self.cv_val_indexes[fold]
# print('fold', fold)
# print(train_index[:5])
return self.load_data_by_index(train_index, val_index)
def load_data(self):
if self.cv_partition == 'disjoint':
train_index = self.df_response[(self.df_response['NSC1'].isin(self.train_drug_ids)) & (self.df_response['NSC2'].isin(self.train_drug_ids))].index
val_index = self.df_response[(self.df_response['NSC1'].isin(self.val_drug_ids)) & (self.df_response['NSC2'].isin(self.val_drug_ids))].index
else:
train_index = range(self.n_train)
val_index = range(self.n_train, self.total)
return self.load_data_by_index(train_index, val_index)
def load_data_old(self):
# bad performance (4x slow) possibly due to incontiguous data
df_train = self.df_response.iloc[:self.n_train, :]
df_val = self.df_response.iloc[self.n_train:, :]
y_train = df_train['GROWTH'].values
y_val = df_val['GROWTH'].values
x_train_list = []
x_val_list = []
for fea in self.cell_features:
df_cell = getattr(self, self.cell_df_dict[fea])
df_x_train = pd.merge(df_train[['CELLNAME']], df_cell, on='CELLNAME', how='left')
df_x_val = pd.merge(df_val[['CELLNAME']], df_cell, on='CELLNAME', how='left')
x_train_list.append(df_x_train.drop(['CELLNAME'], axis=1).values)
x_val_list.append(df_x_val.drop(['CELLNAME'], axis=1).values)
for drug in ['NSC1', 'NSC2']:
for fea in self.drug_features:
df_drug = getattr(self, self.drug_df_dict[fea])
df_x_train = pd.merge(df_train[[drug]], df_drug, left_on=drug, right_on='NSC', how='left')
df_x_val = pd.merge(df_val[[drug]], df_drug, left_on=drug, right_on='NSC', how='left')
x_train_list.append(df_x_train.drop([drug, 'NSC'], axis=1).values)
x_val_list.append(df_x_val.drop([drug, 'NSC'], axis=1).values)
return x_train_list, y_train, x_val_list, y_val, df_train, df_val
class ComboDataGenerator(object):
"""Generate training, validation or testing batches from loaded data
"""
def __init__(self, data, partition='train', batch_size=32):
self.lock = threading.Lock()
self.data = data
self.partition = partition
self.batch_size = batch_size
if partition == 'train':
self.cycle = cycle(range(data.n_train))
self.num_data = data.n_train
elif partition == 'val':
self.cycle = cycle(range(data.total)[-data.n_val:])
self.num_data = data.n_val
else:
raise Exception('Data partition "{}" not recognized.'.format(partition))
def flow(self):
"""Keep generating data batches
"""
while 1:
self.lock.acquire()
indices = list(islice(self.cycle, self.batch_size))
self.lock.release()
df = self.data.df_response.iloc[indices, :]
y = df['GROWTH'].values
x_list = []
for fea in self.data.cell_features:
df_cell = getattr(self.data, self.data.cell_df_dict[fea])
df_x = pd.merge(df[['CELLNAME']], df_cell, on='CELLNAME', how='left')
x_list.append(df_x.drop(['CELLNAME'], axis=1).values)
for drug in ['NSC1', 'NSC2']:
for fea in self.data.drug_features:
df_drug = getattr(self.data, self.data.drug_df_dict[fea])
df_x = pd.merge(df[[drug]], df_drug, left_on=drug, right_on='NSC', how='left')
x_list.append(df_x.drop([drug, 'NSC'], axis=1).values)
yield x_list, y
def test_generator(loader):
gen = ComboDataGenerator(loader).flow()
x_list, y = next(gen)
for x in x_list:
print(x.shape)
print(y.shape)
def test_loader(loader):
x_train_list, y_train, x_val_list, y_val = loader.load_data()
print('x_train shapes:')
for x in x_train_list:
print(x.shape)
print('y_train shape:', y_train.shape)
print('x_val shapes:')
for x in x_val_list:
print(x.shape)
print('y_val shape:', y_val.shape)
def r2(y_true, y_pred):
SS_res = K.sum(K.square(y_true - y_pred))
SS_tot = K.sum(K.square(y_true - K.mean(y_true)))
return (1 - SS_res/(SS_tot + K.epsilon()))
def mae(y_true, y_pred):
return keras.metrics.mean_absolute_error(y_true, y_pred)
def evaluate_prediction(y_true, y_pred):
mse = mean_squared_error(y_true, y_pred)
mae = mean_absolute_error(y_true, y_pred)
r2 = r2_score(y_true, y_pred)
corr, _ = pearsonr(y_true, y_pred)
return {'mse': mse, 'mae': mae, 'r2': r2, 'corr': corr}
def log_evaluation(metric_outputs, description='Comparing y_true and y_pred:'):
logger.info(description)
for metric, value in metric_outputs.items():
logger.info(' {}: {:.4f}'.format(metric, value))
def plot_history(out, history, metric='loss', title=None):
title = title or 'model {}'.format(metric)
val_metric = 'val_{}'.format(metric)
plt.figure(figsize=(8, 6))
plt.plot(history.history[metric], marker='o')
plt.plot(history.history[val_metric], marker='d')
plt.title(title)
plt.ylabel(metric)
plt.xlabel('epoch')
plt.legend(['train_{}'.format(metric), 'val_{}'.format(metric)], loc='upper center')
png = '{}.plot.{}.png'.format(out, metric)
plt.savefig(png, bbox_inches='tight')
class LoggingCallback(Callback):
def __init__(self, print_fcn=print):
Callback.__init__(self)
self.print_fcn = print_fcn
def on_epoch_end(self, epoch, logs={}):
msg = "[Epoch: %i] %s" % (epoch, ", ".join("%s: %f" % (k, v) for k, v in sorted(logs.items())))
self.print_fcn(msg)
class PermanentDropout(Dropout):
def __init__(self, rate, **kwargs):
super(PermanentDropout, self).__init__(rate, **kwargs)
self.uses_learning_phase = False
def call(self, x, mask=None):
if 0. < self.rate < 1.:
noise_shape = self._get_noise_shape(x)
x = K.dropout(x, self.rate, noise_shape)
return x
class ModelRecorder(Callback):
def __init__(self, save_all_models=False):
Callback.__init__(self)
self.save_all_models = save_all_models
get_custom_objects()['PermanentDropout'] = PermanentDropout
def on_train_begin(self, logs={}):
self.val_losses = []
self.best_val_loss = np.Inf
self.best_model = None
def on_epoch_end(self, epoch, logs={}):
val_loss = logs.get('val_loss')
self.val_losses.append(val_loss)
if val_loss < self.best_val_loss:
self.best_model = keras.models.clone_model(self.model)
self.best_val_loss = val_loss
def build_feature_model(input_shape, name='', dense_layers=[1000, 1000],
activation='relu', residual=False,
dropout_rate=0, permanent_dropout=True):
x_input = Input(shape=input_shape)
h = x_input
for i, layer in enumerate(dense_layers):
x = h
h = Dense(layer, activation=activation)(h)
if dropout_rate > 0:
if permanent_dropout:
h = PermanentDropout(dropout_rate)(h)
else:
h = Dropout(dropout_rate)(h)
if residual:
try:
h = keras.layers.add([h, x])
except ValueError:
pass
model = Model(x_input, h, name=name)
return model
def build_model(loader, args, verbose=False):
input_models = {}
dropout_rate = args.dropout
permanent_dropout = True
for fea_type, shape in loader.feature_shapes.items():
box = build_feature_model(input_shape=shape, name=fea_type,
dense_layers=args.dense_feature_layers,
dropout_rate=dropout_rate, permanent_dropout=permanent_dropout)
if verbose:
box.summary()
input_models[fea_type] = box
inputs = []
encoded_inputs = []
for fea_name, fea_type in loader.input_features.items():
shape = loader.feature_shapes[fea_type]
fea_input = Input(shape, name='input.'+fea_name)
inputs.append(fea_input)
input_model = input_models[fea_type]
encoded = input_model(fea_input)
encoded_inputs.append(encoded)
merged = keras.layers.concatenate(encoded_inputs)
h = merged
for i, layer in enumerate(args.dense):
x = h
h = Dense(layer, activation=args.activation)(h)
if dropout_rate > 0:
if permanent_dropout:
h = PermanentDropout(dropout_rate)(h)
else:
h = Dropout(dropout_rate)(h)
if args.residual:
try:
h = keras.layers.add([h, x])
except ValueError:
pass
output = Dense(1)(h)
return Model(inputs, output)
def get_combo_parser():
description = 'Build neural network based models to predict tumor response to drug pairs.'
parser = argparse.ArgumentParser(prog='combo_baseline', formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description=description)
return combo.common_parser(parser)
# def initialize_parameters():
# # Get command-line parameters
# parser = get_combo_parser()
# args = parser.parse_args()
# # Get parameters from configuration file
# file_params = combo.read_config_file(args.config_file)
# # Consolidate parameter set. Command-line parameters overwrite file configuration
# params = p1_common.args_overwrite_config(args, file_params)
# # print(params)
# return params
def initialize_parameters():
# Build benchmark object
comboBmk = combo.BenchmarkCombo(combo.file_path, 'combo_default_model.txt', 'keras',
prog='combo_baseline',
desc = 'Build neural network based models to predict tumor response to drug pairs.')
# Initialize parameters
|
gParameters = candle.finalize_parameters(comboBmk)
#combo.logger.info('Params: {}'.format(gParameters))
return gParameters
class Struct:
def __init__(self, **entries):
self.__dict__.update(entries)
def run(params):
args = Struct(**params)
set_seed(args.rng_seed)
ext = extension_from_parameters(args)
prefix = args.save + ext
logfile = args.logfile if args.logfile else prefix+'.log'
set_up_logger(logfile, args.verbose)
logger.info('Params: {}'.format(params))
loader = ComboDataLoader(seed=args.rng_seed,
val_split=args.validation_split,
cell_features=args.cell_features,
drug_features=args.drug_features,
response_url=args.response_url,
use_landmark_genes=args.use_landmark_genes,
preprocess_rnaseq=args.preprocess_rnaseq,
exclude_cells=args.exclude_cells,
exclude_drugs=args.exclude_drugs,
use_combo_score=args.use_combo_score,
cv_partition=args.cv_partition, cv=args.cv)
# test_loader(loader)
# test_generator(loader)
train_gen = ComboDataGenerator(loader, batch_size=args.batch_size).flow()
val_gen = ComboDataGenerator(loader, partition='val', batch_size=args.batch_size).flow()
train_steps = int(loader.n_train / args.batch_size)
val_steps = int(loader.n_val / args.batch_size)
model = build_model(loader, args, verbose=True)
model.summary()
# plot_model(model, to_file=prefix+'.model.png', show_shapes=True)
if args.cp:
model_json = model.to_json()
with open(prefix+'.model.json', 'w') as f:
print(model_json, file=f)
def warmup_scheduler(epoch):
lr = args.learning_rate or base_lr * args.batch_size/100
if epoch <= 5:
K.set_value(model.optimizer.lr, (base_lr * (5-epoch) + lr * epoch) / 5)
logger.debug('Epoch {}: lr={}'.format(epoch, K.get_value(model.optimizer.lr)))
return K.get_value(model.optimizer.lr)
df_pred_list = []
cv_ext = ''
cv = args.cv if args.cv > 1 else 1
fold = 0
while fold < cv:
if args.cv > 1:
logger.info('Cross validation fold {}/{}:'.format(fold+1, cv))
cv_ext = '.cv{}'.format(fold+1)
model = build_model(loader, args)
optimizer = optimizers.deserialize({'class_name': args.optimizer, 'config': {}})
base_lr = args.base_lr or K.get_value(optimizer.lr)
if args.learning_rate:
K.set_value(optimizer.lr, args.learning_rate)
model.compile(loss=args.loss, optimizer=optimizer, metrics=[mae, r2])
# calculate trainable and non-trainable params
# params.update(compute_trainable_params(model))
# candle_monitor = CandleRemoteMonitor(params=params)
# timeout_monitor = TerminateOnTimeOut(params['timeout'])
reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=5, min_lr=0.00001)
warmup_lr = LearningRateScheduler(warmup_scheduler)
checkpointer = ModelCheckpoint(prefix+cv_ext+'.weights.h5', save_best_only=True, save_weights_only=True)
tensorboard = TensorBoard(log_dir="tb/tb{}{}".format(ext, cv_ext))
history_logger = LoggingCallback(logger.debug)
model_recorder = ModelRecorder()
callbacks = [history_logger, model_recorder]
# callbacks = [candle_monitor, timeout_monitor, history_logger, model_recorder]
if args.reduce_lr:
callbacks.append(reduce_lr)
if args.warmup_lr:
callbacks.append(warmup_lr)
if args.cp:
callbacks.append(checkpointer)
if args.tb:
callbacks.append(tensorboard)
if args.gen:
history = model.fit_generator(train_gen, train_steps,
epochs=args.epochs,
callbacks=callbacks,
validation_data=val_gen, validation_steps=val_steps)
else:
if args.cv > 1:
x_train_list, y_train, x_val_list, y_val, df_train, df_val = loader.load_data_cv(fold)
else:
x_train_list, y_train, x_val_list, y_val, df_train, df_val = loader.load_data()
y_shuf = np.random.permutation(y_val)
log_evaluation(evaluate_prediction(y_val, y_shuf),
description='Between random pairs in y_val:')
history = model.fit(x_train_list, y_train,
batch_size=args.batch_size,
shuffle=args.shuffle,
epochs=args.epochs,
callbacks=callbacks,
validation_data=(x_val_list, y_val))
if args.cp:
model.load_weights(prefix+cv_ext+'.weights.h5')
if not args.gen:
y_val_pred = model.predict(x_val_list, batch_size=args.batch_size).flatten()
scores = evaluate_prediction(y_val, y_val_pred)
if args.cv > 1 and scores[args.loss] > args.max_val_loss:
logger.warn('Best val_loss {} is greater than {}; retrain the model...'.format(scores[args.loss], args.max_val_loss))
continue
else:
fold += 1
log_evaluation(scores)
df_val.is_copy = False
df_val['GROWTH_PRED'] = y_val_pred
df_val['GROWTH_ERROR'] = y_val_pred - y_val
df_pred_list.append(df_val)
if args.cp:
# model.save(prefix+'.model.h5')
model_recorder.best_model.save(prefix+'.model.h5')
# test reloadded model prediction
new_model = keras.models.load_model(prefix+'.model.h5')
new_model.load_weights(prefix+cv_ext+'.weights.h5')
new_pred = new_model.predict(x_val_list, batch_size=args.batch_size).flatten()
# print('y_val:', y_val[:10])
# print('old_pred:', y_val_pred[:10])
# print('new_pred:', new_pred[:10])
plot_history(prefix, history, 'loss')
plot_history(prefix, history, 'r2')
if K.backend() == 'tensorflow':
K.clear_session()
pred_fname = prefix + '.predicted.growth.tsv'
if args.use_combo_score:
pred_fname = prefix + '.predicted.score.tsv'
df_pred = pd.concat(df_pred_list)
df_pred.to_csv(pred_fname, sep='\t', index=False, float_format='%.4g')
logger.handlers = []
return history
def main():
params = initialize_parameters()
run(params)
if __name__ == '__main__':
main()
if K.backend() == 'tensorflow':
K.clear_session()
| |
lib.rs
|
#![feature(in_band_lifetimes)]
mod class;
mod method;
mod frame;
mod error;
/// Complex amqp types
pub use frame::base::{Timestamp, ShortStr, LongStr, Decimal, FieldName, FieldValue, FieldArray, FieldTable, BytesArray};
/// Method type and id definitions
pub use method::{AccessMethod, BasicMethod, ChannelMethod, ConnectionMethod, ConfirmMethod, ExchangeMethod, QueueMethod, TxMethod, Method, MethodId};
/// Class type and id definitions
pub use class::Class;
/// Content Header frame properties
pub mod properties {
pub use crate::frame::header::access;
pub use crate::frame::header::basic;
pub use crate::frame::header::channel;
pub use crate::frame::header::connection;
pub use crate::frame::header::confirm;
pub use crate::frame::header::exchange;
pub use crate::frame::header::queue;
pub use crate::frame::header::tx;
}
/// Method frame arguments
pub mod arguments {
pub use crate::frame::method::access;
pub use crate::frame::method::basic;
pub use crate::frame::method::channel;
pub use crate::frame::method::connection;
pub use crate::frame::method::confirm;
pub use crate::frame::method::exchange;
pub use crate::frame::method::queue;
pub use crate::frame::method::tx;
}
/// Decode and Encode frame, also has an tokio frame codec.
pub mod codec {
pub use crate::frame::frame_codec::{DecodedFrame, FrameCodec};
pub use crate::frame::base::{ContentHeaderPayload, HeartbeatPayload, MethodPayload, Payload, Frame, ProtocolHeader, Decode, Encode};
|
/// Frame decode error and amqp protocol error definitions.
pub mod err {
pub use crate::error::FrameDecodeErr;
pub use crate::error::amqp::{AmqpError, AmqpErrorKind};
}
#[cfg(test)]
mod tests {
use crate::{LongStr, FieldValue, FieldTable, FieldName};
use crate::frame::method::connection::ConnectionStart;
use crate::codec::{Decode};
use bytes::{BytesMut, BufMut};
#[test]
fn test_connection_start() {
let mut connection_start = ConnectionStart::default();
connection_start.set_version_major(0);
connection_start.set_version_minor(9);
assert_eq!(connection_start.version_major(), 0);
}
#[test]
fn test_field_table() {
let mut table = FieldTable::new();
table.insert(FieldName::with_bytes(b"hello").unwrap(), FieldValue::from_u32(0x12345678u32));
table.insert(FieldName::with_bytes(b"world").unwrap(), FieldValue::from_long_string(LongStr::with_bytes(b"hello").unwrap()));
let mut ret = BytesMut::with_capacity(128);
ret.put_u8(b'F');
ret.put_u32(27u32);
for (k, _) in &table {
if *k == FieldName::with_bytes(b"hello").unwrap() {
ret.put_u8(5u8);
ret.put_slice(b"hello");
ret.put_u8(b'i');
ret.put_u32(0x12345678u32);
} else {
ret.put_u8(5u8);
ret.put_slice(b"world");
ret.put_u8(b'S');
ret.put_u32(5u32);
ret.put_slice(b"hello");
}
}
if let (_, FieldValue::FieldTable(t)) = FieldValue::decode(&ret).unwrap() {
assert!(matches!(t.get(&FieldName::with_bytes(b"hello").unwrap()).unwrap(), FieldValue::U32(v) if *v == 0x12345678u32));
assert!(matches!(t.get(&FieldName::with_bytes(b"world").unwrap()).unwrap(), FieldValue::LongStr(v) if v.to_string() == String::from("hello")));
} else {
panic!("Expected FieldTable value");
}
}
}
|
}
|
main.rs
|
#[global_allocator]
static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;
use std::sync::Arc;
use std::thread::available_parallelism;
use bytes::BytesMut;
use salvo::http::header::{self, HeaderValue};
use salvo::http::response::Body;
use salvo::prelude::*;
use serde::Serialize;
mod server;
static HELLO_WORLD: &'static [u8] = b"Hello, world!";
#[derive(Serialize)]
pub struct Message {
pub message: &'static str,
}
#[fn_handler]
fn json(res: &mut Response) {
let headers = res.headers_mut();
headers.insert(header::SERVER, HeaderValue::from_static("S"));
headers.insert(header::CONTENT_TYPE, HeaderValue::from_static("application/json"));
let data = serde_json::to_vec(&Message {
message: "Hello, World!",
})
.unwrap();
res.set_body(Body::Bytes(BytesMut::from(data.as_slice())));
}
#[fn_handler]
fn
|
(res: &mut Response) {
let headers = res.headers_mut();
headers.insert(header::SERVER, HeaderValue::from_static("S"));
headers.insert(header::CONTENT_TYPE, HeaderValue::from_static("text/plain"));
res.set_body(Body::Bytes(BytesMut::from(HELLO_WORLD)));
}
fn main() {
let router = Arc::new(
Router::new()
.push(Router::with_path("plaintext").get(plaintext))
.push(Router::with_path("json").get(json)),
);
for _ in 1..available_parallelism().map(|n| n.get()).unwrap_or(16) {
let router = router.clone();
std::thread::spawn(move || {
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
rt.block_on(serve(router));
});
}
println!("Started http server: 127.0.0.1:8080");
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
rt.block_on(serve(router));
}
async fn serve(router: Arc<Router>) {
server::builder()
.http1_pipeline_flush(true)
.serve(Service::new(router))
.await
.unwrap();
}
|
plaintext
|
api_client.py
|
# coding: utf-8
# Copyright 2020. ThingsBoard
# #
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# #
# http://www.apache.org/licenses/LICENSE-2.0
# #
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from __future__ import absolute_import
import datetime
import json
import mimetypes
from multiprocessing.pool import ThreadPool
import os
import re
import tempfile
# python 2 and python 3 compatibility library
import six
from six.moves.urllib.parse import quote
from tb_rest_client.configuration import Configuration
import tb_rest_client.models.models_ce
import tb_rest_client.models.models_pe
from tb_rest_client import rest
class ApiClient(object):
"""
:param configuration: .Configuration object for this client
:param header_name: a header to pass when making calls to the API.
:param header_value: a header value to pass when making calls to
the API.
:param cookie: a cookie to include in the header when making calls
to the API
"""
PRIMITIVE_TYPES = (float, bool, bytes, six.text_type) + six.integer_types
NATIVE_TYPES_MAPPING = {
'int': int,
'long': int if six.PY3 else long, # noqa: F821
'float': float,
'str': str,
'bool': bool,
'date': datetime.date,
'datetime': datetime.datetime,
'object': object,
}
def __init__(self, configuration=None, header_name=None, header_value=None,
cookie=None):
if configuration is None:
configuration = Configuration()
self.configuration = configuration
# Use the pool property to lazily initialize the ThreadPool.
self._pool = None
self.rest_client = rest.RESTClientObject(configuration)
self.default_headers = {}
if header_name is not None:
self.default_headers[header_name] = header_value
self.cookie = cookie
# Set default User-Agent.
self.user_agent = 'Swagger-Codegen/1.0.0/python'
def __del__(self):
if self._pool is not None:
self._pool.close()
self._pool.join()
@property
def pool(self):
if self._pool is None:
self._pool = ThreadPool()
return self._pool
@property
def user_agent(self):
"""User agent for this API client"""
return self.default_headers['User-Agent']
@user_agent.setter
def user_agent(self, value):
self.default_headers['User-Agent'] = value
def set_default_header(self, header_name, header_value):
self.default_headers[header_name] = header_value
def __call_api(
self, resource_path, method, path_params=None,
query_params=None, header_params=None, body=None, post_params=None,
files=None, response_type=None, auth_settings=None,
_return_http_data_only=None, collection_formats=None,
_preload_content=True, _request_timeout=None):
config = self.configuration
# header parameters
header_params = header_params or {}
header_params.update(self.default_headers)
if self.cookie:
header_params['Cookie'] = self.cookie
if header_params:
header_params = self.sanitize_for_serialization(header_params)
header_params = dict(self.parameters_to_tuples(header_params,
collection_formats))
# path parameters
if path_params:
path_params = self.sanitize_for_serialization(path_params)
path_params = self.parameters_to_tuples(path_params,
collection_formats)
for k, v in path_params:
if isinstance(v, dict) and v.get("entityType") is not None and v.get('id') is not None:
v = v["id"]
# specified safe chars, encode everything
if v is not None:
resource_path = resource_path.replace(
'{%s}' % k,
quote(str(v) if v is not None else "", safe=config.safe_chars_for_path_param)
).replace(
'{?%s}' % k,
quote(str("?"+k+"="+v) if v is not None else "", safe=config.safe_chars_for_path_param)
).replace(
'{?%s,' % k,
quote(str("?"+k+"="+v) if v is not None else "", safe=config.safe_chars_for_path_param)
).replace(
',%s' % k,
quote(str("&"+k+"="+v) if v is not None else "", safe=config.safe_chars_for_path_param)
).replace(
',?%s' % k,
quote(str("&"+k+"="+v) if v is not None else "", safe=config.safe_chars_for_path_param)
).replace(
',%s}' % k,
quote("}" + str(v) if v is not None else "", safe=config.safe_chars_for_path_param)
)
# resource_path = resource_path.replace(
# '{%s}' % k,
# quote(str(k+"="+v), safe=config.safe_chars_for_path_param)
# ).replace(
# '{?%s}' % k,
# quote(str("?"+k+"="+v), safe=config.safe_chars_for_path_param)
# ).replace(
# '{?%s,' % k,
# quote(str("?"+k+"="+v) + "{", safe=config.safe_chars_for_path_param)
# ).replace(
# ',%s,' % k,
# quote("}" + str("&"+k+"="+v) + "{", safe=config.safe_chars_for_path_param)
# ).replace(
# ',?%s,' % k,
# quote("}" + str("&"+k+"="+v) + "{", safe=config.safe_chars_for_path_param)
# ).replace(
# ',%s}' % k,
# quote("}" + str(v), safe=config.safe_chars_for_path_param)
# )
# query parameters
if query_params:
query_params = self.sanitize_for_serialization(query_params)
query_params = [param for param in query_params if (isinstance(param, tuple) and len(param) > 1 and param[1] is not None) or not isinstance(param, tuple)]
query_params = self.parameters_to_tuples(query_params,
collection_formats)
# post parameters
if post_params or files:
post_params = self.prepare_post_parameters(post_params, files)
post_params = [param for param in post_params if (isinstance(param, tuple) and len(param) > 1 and param[1] is not None) or not isinstance(param, tuple)]
post_params = self.sanitize_for_serialization(post_params)
post_params = self.parameters_to_tuples(post_params,
collection_formats)
# auth setting
self.update_params_for_auth(header_params, query_params, auth_settings)
# body
if body:
body = self.sanitize_for_serialization(body)
# request url
clean_path = self.sanitize_path(resource_path)
url = self.configuration.host + clean_path
# perform request and return response
response_data = self.request(
method, url, query_params=query_params, headers=header_params,
post_params=post_params, body=body,
_preload_content=_preload_content,
_request_timeout=_request_timeout)
self.last_response = response_data
return_data = response_data
if _preload_content:
# deserialize response data
if response_type:
return_data = self.deserialize(response_data, response_type)
else:
return_data = None
if _return_http_data_only:
return (return_data)
else:
return (return_data, response_data.status,
response_data.getheaders())
def sanitize_path(self, url):
pattern = r'(\{[\?a-zA-Z,]{1,}\})'
matching = re.search(pattern, url)
if matching is not None and len(matching.groups()) > 0:
for match in matching.groups():
clean_url = url.replace(match, "")
else:
clean_url = url
return clean_url
def sanitize_for_serialization(self, obj):
"""Builds a JSON POST object.
If obj is None, return None.
If obj is str, int, long, float, bool, return directly.
If obj is datetime.datetime, datetime.date
convert to string in iso8601 format.
If obj is list, sanitize each element in the list.
If obj is dict, return the dict.
If obj is swagger model, return the properties dict.
:param obj: The data to serialize.
:return: The serialized form of data.
"""
if obj is None:
return None
elif isinstance(obj, self.PRIMITIVE_TYPES):
return obj
elif isinstance(obj, list):
return [self.sanitize_for_serialization(sub_obj)
for sub_obj in obj]
elif isinstance(obj, tuple):
return tuple(self.sanitize_for_serialization(sub_obj)
for sub_obj in obj)
elif isinstance(obj, (datetime.datetime, datetime.date)):
return obj.isoformat()
if isinstance(obj, dict):
obj_dict = obj
else:
# Convert model obj to dict except
# attributes `swagger_types`, `attribute_map`
# and attributes which value is not None.
# Convert attribute name to json key in
# model definition for request.
obj_dict = {obj.attribute_map[attr]: getattr(obj, attr)
for attr, _ in six.iteritems(obj.swagger_types)
if getattr(obj, attr) is not None}
return {key: self.sanitize_for_serialization(val)
for key, val in six.iteritems(obj_dict)}
def deserialize(self, response, response_type):
"""Deserializes response into an object.
:param response: RESTResponse object to be deserialized.
:param response_type: class literal for
deserialized object, or string of class name.
:return: deserialized object.
"""
# handle file downloading
# save response body into a tmp file and return the instance
if response_type == "file":
return self.__deserialize_file(response)
# fetch data from response object
try:
data = json.loads(response.data)
except ValueError:
data = response.data
return self.__deserialize(data, response_type)
def __deserialize(self, data, klass):
"""Deserializes dict, list, str into an object..
:param data: dict, list or str.
:param klass: class literal, or string of class name.
:return: object.
"""
if data is None:
return None
if klass == "DeferredResultResponseEntity":
return self.__deserialize(data, type(data))
#
# elif type(klass) == str:
# # convert str to class
elif klass in self.NATIVE_TYPES_MAPPING:
klass = self.NATIVE_TYPES_MAPPING[klass]
elif klass == list:
return_data = [self.__deserialize(sub_data, type(sub_data))
for sub_data in data]
return return_data
elif klass == dict:
return_data = {k: self.__deserialize(v, type(v))
for k, v in six.iteritems(data)}
return return_data
elif type(klass) == str:
if klass.startswith('list['):
sub_kls = re.match(r'list\[(.*)\]', klass).group(1)
return [self.__deserialize(sub_data, sub_kls)
for sub_data in data]
if klass.startswith('dict('):
sub_kls = re.match(r'dict\(([^,]*), (.*)\)', klass).group(2)
return {k: self.__deserialize(v, sub_kls)
for k, v in six.iteritems(data)}
# convert str to class
if klass in self.NATIVE_TYPES_MAPPING:
klass = self.NATIVE_TYPES_MAPPING[klass]
try:
found_class = getattr(tb_rest_client.models.models_pe, klass)
# if sorted(list(found_class.attribute_map.values())) == sorted(list(data.keys())):
if all(attr in list(found_class.attribute_map.values()) for attr in list(data.keys())):
klass = found_class
else:
found_class = getattr(tb_rest_client.models.models_ce, klass)
# if sorted(list(found_class.attribute_map.values())) == sorted(list(data.keys())):
if all(attr in list(found_class.attribute_map.values()) for attr in list(data.keys())):
klass = found_class
except AttributeError:
found_class = getattr(tb_rest_client.models.models_ce, klass)
if all(attr in list(found_class.attribute_map.values()) for attr in list(data.keys())):
# if sorted(list(found_class.attribute_map.values())) == sorted(list(data.keys())):
klass = found_class
# else:
# return self.__deserialize(data, type(data))
return self.__deserialize_data(data, klass)
def __deserialize_data(self, data, klass):
try:
if klass in self.PRIMITIVE_TYPES:
return self.__deserialize_primitive(data, klass)
elif klass == object:
return self.__deserialize_object(data)
elif klass == datetime.date:
return self.__deserialize_date(data)
elif klass == datetime.datetime:
return self.__deserialize_datatime(data)
else:
return self.__deserialize_model(data, klass)
except Exception as e:
return e
def call_api(self, resource_path, method,
path_params=None, query_params=None, header_params=None,
body=None, post_params=None, files=None,
response_type=None, auth_settings=None, async_req=None,
_return_http_data_only=None, collection_formats=None,
_preload_content=True, _request_timeout=None):
"""Makes the HTTP request (synchronous) and returns deserialized data.
To make an async request, set the async_req parameter.
:param resource_path: Path to method endpoint.
:param method: Method to call.
:param path_params: Path parameters in the url.
:param query_params: Query parameters in the url.
:param header_params: Header parameters to be
placed in the request header.
:param body: Request body.
:param post_params dict: Request post form parameters,
for `application/x-www-form-urlencoded`, `multipart/form-data`.
:param auth_settings list: Auth Settings names for the request.
:param response: Response data type.
:param files dict: key -> filename, value -> filepath,
for `multipart/form-data`.
:param async_req bool: execute request asynchronously
:param _return_http_data_only: response data without head status code
and headers
:param collection_formats: dict of collection formats for path, query,
header, and post parameters.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return:
If async_req parameter is True,
the request will be called asynchronously.
The method will return the request thread.
If parameter async_req is False or missing,
then the method will return the response directly.
"""
if not async_req:
return self.__call_api(resource_path, method,
path_params, query_params, header_params,
body, post_params, files,
response_type, auth_settings,
_return_http_data_only, collection_formats,
_preload_content, _request_timeout)
else:
thread = self.pool.apply_async(self.__call_api, (resource_path,
method, path_params, query_params,
header_params, body,
post_params, files,
response_type, auth_settings,
_return_http_data_only,
collection_formats,
_preload_content, _request_timeout))
return thread
def request(self, method, url, query_params=None, headers=None,
post_params=None, body=None, _preload_content=True,
_request_timeout=None):
"""Makes the HTTP request using RESTClient."""
if method == "GET":
return self.rest_client.GET(url,
query_params=query_params,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
headers=headers)
elif method == "HEAD":
return self.rest_client.HEAD(url,
query_params=query_params,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
headers=headers)
elif method == "OPTIONS":
return self.rest_client.OPTIONS(url,
query_params=query_params,
headers=headers,
post_params=post_params,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
body=body)
elif method == "POST":
return self.rest_client.POST(url,
query_params=query_params,
headers=headers,
post_params=post_params,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
body=body)
elif method == "PUT":
return self.rest_client.PUT(url,
query_params=query_params,
headers=headers,
post_params=post_params,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
body=body)
elif method == "PATCH":
return self.rest_client.PATCH(url,
query_params=query_params,
headers=headers,
post_params=post_params,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
body=body)
elif method == "DELETE":
return self.rest_client.DELETE(url,
query_params=query_params,
headers=headers,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
body=body)
else:
raise ValueError(
"http method must be `GET`, `HEAD`, `OPTIONS`,"
" `POST`, `PATCH`, `PUT` or `DELETE`."
)
def parameters_to_tuples(self, params, collection_formats):
"""Get parameters as list of tuples, formatting collections.
:param params: Parameters as dict or list of two-tuples
:param dict collection_formats: Parameter collection formats
:return: Parameters as list of tuples, collections formatted
"""
new_params = []
if collection_formats is None:
collection_formats = {}
for k, v in six.iteritems(params) if isinstance(params, dict) else params: # noqa: E501
if k in collection_formats:
collection_format = collection_formats[k]
if collection_format == 'multi':
new_params.extend((k, value) for value in v)
else:
if collection_format == 'ssv':
delimiter = ' '
elif collection_format == 'tsv':
delimiter = '\t'
elif collection_format == 'pipes':
delimiter = '|'
else: # csv is the default
delimiter = ','
new_params.append(
(k, delimiter.join(str(value) for value in v)))
else:
new_params.append((k, v))
return new_params
def prepare_post_parameters(self, post_params=None, files=None):
"""Builds form parameters.
:param post_params: Normal form parameters.
:param files: File parameters.
:return: Form parameters with files.
"""
params = []
if post_params:
params = post_params
if files:
for k, v in six.iteritems(files):
if not v:
continue
file_names = v if type(v) is list else [v]
for n in file_names:
with open(n, 'rb') as f:
filename = os.path.basename(f.name)
filedata = f.read()
mimetype = (mimetypes.guess_type(filename)[0] or
'application/octet-stream')
params.append(
tuple([k, tuple([filename, filedata, mimetype])]))
return params
def select_header_accept(self, accepts):
"""Returns `Accept` based on an array of accepts provided.
:param accepts: List of headers.
:return: Accept (e.g. application/json).
"""
if not accepts:
return
accepts = [x.lower() for x in accepts]
if 'application/json' in accepts:
return 'application/json'
else:
return ', '.join(accepts)
def select_header_content_type(self, content_types):
|
def update_params_for_auth(self, headers, querys, auth_settings):
"""Updates header and query params based on authentication setting.
:param headers: Header parameters dict to be updated.
:param querys: Query parameters tuple list to be updated.
:param auth_settings: Authentication setting identifiers list.
"""
if not auth_settings:
return
for auth in auth_settings:
auth_setting = self.configuration.auth_settings().get(auth)
if auth_setting:
if not auth_setting['value']:
continue
elif auth_setting['in'] == 'header':
headers[auth_setting['key']] = auth_setting['value']
elif auth_setting['in'] == 'query':
querys.append((auth_setting['key'], auth_setting['value']))
else:
raise ValueError(
'Authentication token must be in `query` or `header`'
)
def __deserialize_file(self, response):
"""Deserializes body to file
Saves response body into a file in a temporary folder,
using the filename from the `Content-Disposition` header if provided.
:param response: RESTResponse.
:return: file path.
"""
fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path)
os.close(fd)
os.remove(path)
content_disposition = response.getheader("Content-Disposition")
if content_disposition:
filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?',
content_disposition).group(1)
path = os.path.join(os.path.dirname(path), filename)
with open(path, "wb") as f:
f.write(response.data)
return path
def __deserialize_primitive(self, data, klass):
"""Deserializes string to primitive type.
:param data: str.
:param klass: class literal.
:return: int, long, float, str, bool.
"""
try:
return klass(data)
except UnicodeEncodeError:
return six.text_type(data)
except TypeError:
return data
def __deserialize_object(self, value):
"""Return a original value.
:return: object.
"""
return value
def __deserialize_date(self, string):
"""Deserializes string to date.
:param string: str.
:return: date.
"""
try:
from dateutil.parser import parse
return parse(string).date()
except ImportError:
return string
except ValueError:
raise rest.ApiException(
status=0,
reason="Failed to parse `{0}` as date object".format(string)
)
def __deserialize_datatime(self, string):
"""Deserializes string to datetime.
The string should be in iso8601 datetime format.
:param string: str.
:return: datetime.
"""
try:
from dateutil.parser import parse
return parse(string)
except ImportError:
return string
except ValueError:
raise rest.ApiException(
status=0,
reason=(
"Failed to parse `{0}` as datetime object"
.format(string)
)
)
def __hasattr(self, object, name):
return name in object.__class__.__dict__
def __deserialize_model(self, data, klass):
"""Deserializes list or dict to model.
:param data: dict, list.
:param klass: class literal.
:return: model object.
"""
if (not klass.swagger_types and
not self.__hasattr(klass, 'get_real_child_model')):
return data
kwargs = {}
if klass.swagger_types is not None:
for attr, attr_type in six.iteritems(klass.swagger_types):
if (data is not None and
klass.attribute_map[attr] in data and
isinstance(data, (list, dict))):
value = data[klass.attribute_map[attr]]
kwargs[attr] = self.__deserialize(value, attr_type)
instance = klass(**kwargs)
if (isinstance(instance, dict) and
klass.swagger_types is not None and
isinstance(data, dict)):
for key, value in data.items():
if key not in klass.swagger_types:
instance[key] = value
if self.__hasattr(instance, 'get_real_child_model'):
klass_name = instance.get_real_child_model(data)
if klass_name:
instance = self.__deserialize(data, klass_name)
return instance
|
"""Returns `Content-Type` based on an array of content_types provided.
:param content_types: List of content-types.
:return: Content-Type (e.g. application/json).
"""
if not content_types:
return 'application/json'
content_types = [x.lower() for x in content_types]
if 'application/json' in content_types or '*/*' in content_types:
return 'application/json'
else:
return content_types[0]
|
personality.dir.controller.js
|
export class PersonalityDirectiveController {
|
'ngInject';
this.$state = $state;
this.$scope = $scope;
this.character = $scope.character;
}
}
|
constructor($state,$scope) {
|
dummy_workflow.py
|
import time
from celery import chain, chord
from celery.utils.log import get_task_logger
from materializationengine.celery_init import celery
from materializationengine.shared_tasks import fin
celery_logger = get_task_logger(__name__)
@celery.task(name="process:start_test_workflow")
def start_test_workflow(iterator_length: int = 50):
"""Test workflow for exploring scaling in kubernetes
Args:
iterator_length (int): Number of parallel tasks to run. Default = 50
"""
workflow = []
for i in range(0, 3):
test_workflow = chain(
chord(
[chain(dummy_task.si(i)) for i in range(0, iterator_length)], fin.si()
), # return here is required for chords
fin.si(),
) # final task which will process a return status/timing etc...
test_workflow_2 = chain(
chord(
[chain(dummy_task.si(i)) for i in range(0, iterator_length)], fin.si()
), # return here is required for chords
fin.si(),
)
update_roots_and_freeze = chain(
chord([dummy_task.si(i) for i in range(0, iterator_length)], fin.si()),
dummy_task.si(i),
chord(
[chain(dummy_task.si(i)) for i in range(0, iterator_length)], fin.si()
),
fin.si(),
) # final task which will process a return status/timing etc...
test_complete_workflow = chain(
test_workflow, test_workflow_2, update_roots_and_freeze
)
workflow.append(test_complete_workflow)
final_workflow = chord(workflow, final_task.s())
status = final_workflow.apply_async()
return status
@celery.task(
name="process:dummy_task",
bind=True,
acks_late=True,
autoretry_for=(Exception,),
max_retries=3,
)
def dummy_task(self, i):
time.sleep(1)
return True
@celery.task(
name="process:dummy_arg_task",
bind=True,
acks_late=True,
autoretry_for=(Exception,),
max_retries=3,
)
def
|
(self, arg: str = None):
time.sleep(1)
return arg
@celery.task(
name="process:final_task",
bind=True,
acks_late=True,
autoretry_for=(Exception,),
max_retries=3,
)
def final_task(self, *args, **kwargs):
time.sleep(1)
return "FINAL TASK"
|
dummy_arg_task
|
index.stories.js
|
// @flow
import React from 'react'
import {Box} from '../../common-adapters'
import {storiesOf, action} from '../../stories/storybook'
import EditTeamDescription from '.'
const sharedProps = {
description: 'First description',
origDescription: 'First description',
|
}
const load = () => {
storiesOf('Teams/Edit team description', module)
.add('Description unchanged', () => (
<Box style={storyWrapStyle}>
<EditTeamDescription {...sharedProps} />
</Box>
))
.add('Description changed', () => (
<Box style={storyWrapStyle}>
<EditTeamDescription {...sharedProps} description="Second description" />
</Box>
))
}
const storyWrapStyle = {
width: 500,
height: 400,
borderColor: 'black',
borderWidth: 1,
borderStyle: 'solid',
display: 'flex',
}
export default load
|
teamname: 'testteam',
onChangeDescription: action('onChangeDescription'),
onClose: action('onClose'),
onSetDescription: action('onSetDescription'),
|
tokio_postgres.rs
|
//! Run with
//!
//! ```not_rust
//! cargo run --example tokio_postgres
//! ```
use axum::{
async_trait,
extract::{Extension, FromRequest, RequestParts},
prelude::*,
AddExtensionLayer,
};
use bb8::{Pool, PooledConnection};
use bb8_postgres::PostgresConnectionManager;
use http::StatusCode;
use std::net::SocketAddr;
use tokio_postgres::NoTls;
#[tokio::main]
async fn main() {
// Set the RUST_LOG, if it hasn't been explicitly defined
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", "tokio_postgres=debug")
}
tracing_subscriber::fmt::init();
// setup connection pool
let manager =
PostgresConnectionManager::new_from_stringlike("host=localhost user=postgres", NoTls)
.unwrap();
let pool = Pool::builder().build(manager).await.unwrap();
// build our application with some routes
let app = route(
"/",
get(using_connection_pool_extractor).post(using_connection_extractor),
)
.layer(AddExtensionLayer::new(pool));
// run it with hyper
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::debug!("listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
type ConnectionPool = Pool<PostgresConnectionManager<NoTls>>;
// we can exact the connection pool with `Extension`
async fn using_connection_pool_extractor(
Extension(pool): Extension<ConnectionPool>,
) -> Result<String, (StatusCode, String)> {
let conn = pool.get().await.map_err(internal_error)?;
let row = conn
.query_one("select 1 + 1", &[])
.await
.map_err(internal_error)?;
let two: i32 = row.try_get(0).map_err(internal_error)?;
Ok(two.to_string())
}
// we can also write a custom extractor that grabs a connection from the pool
// which setup is appropriate depends on your application
struct DatabaseConnection(PooledConnection<'static, PostgresConnectionManager<NoTls>>);
#[async_trait]
impl<B> FromRequest<B> for DatabaseConnection
where
B: Send,
{
type Rejection = (StatusCode, String);
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
let Extension(pool) = Extension::<ConnectionPool>::from_request(req)
.await
.map_err(internal_error)?;
let conn = pool.get_owned().await.map_err(internal_error)?;
Ok(Self(conn))
}
}
async fn using_connection_extractor(
DatabaseConnection(conn): DatabaseConnection,
) -> Result<String, (StatusCode, String)> {
let row = conn
.query_one("select 1 + 1", &[])
.await
.map_err(internal_error)?;
let two: i32 = row.try_get(0).map_err(internal_error)?;
Ok(two.to_string())
}
/// Utility function for mapping any error into a `500 Internal Server Error`
/// response.
fn internal_error<E>(err: E) -> (StatusCode, String)
where
E: std::error::Error,
|
{
(StatusCode::INTERNAL_SERVER_ERROR, err.to_string())
}
|
|
render_texture.rs
|
use crate::{
ffi::{self as ffi, sfBool},
graphics::{
CircleShape, Color, ConvexShape, CustomShape, Drawable, IntRect, PrimitiveType,
RectangleShape, RenderStates, RenderTarget, Sprite, Text, Texture, Vertex, VertexBuffer,
View,
},
sf_bool_ext::SfBoolExt,
system::{Vector2f, Vector2i, Vector2u},
window::ContextSettings,
};
/// Target for off-screen 2D rendering into a texture
#[derive(Debug)]
pub struct RenderTexture {
render_texture: *mut ffi::sfRenderTexture,
}
impl RenderTexture {
/// Construct a new render texture
///
/// # Arguments
/// * width - Width of the render texture
/// * height - Height of the render texture
/// * depthBuffer - Do you want a depth-buffer attached?
/// (useful only if you're doing 3D OpenGL on the rendertexture)
///
/// Returns `None` if creation fails.
#[must_use]
pub fn new(width: u32, height: u32) -> Option<RenderTexture> {
Self::with_settings(width, height, &ContextSettings::default())
}
/// Create a `RenderTexture` with the given `ContextSettings`.
///
/// Useful if you want to enable multi-sampling or use the render-texture for
/// OpenGL rendering that requires a depth or stencil buffer.
/// Otherwise it is unnecessary, and you should call [`RenderTexture::new`].
///
/// # Parameters
/// * width - Width of the render-texture
/// * height - Height of the render-texture
/// * settings - Additional settings for the underlying OpenGL texture and context
///
/// Returns `None` if creation fails.
#[must_use]
pub fn with_settings(width: u32, height: u32, settings: &ContextSettings) -> Option<Self> {
let tex = unsafe { ffi::sfRenderTexture_createWithSettings(width, height, &settings.0) };
if tex.is_null() {
None
} else {
Some(Self {
render_texture: tex,
})
}
}
/// Update the contents of the target texture
pub fn display(&self) {
unsafe { ffi::sfRenderTexture_display(self.render_texture) }
}
/// Activate or deactivate a render texture as the current target for rendering
///
/// # Arguments
/// * active - true to activate, false to deactivate
pub fn set_active(&mut self, active: bool) -> bool {
unsafe { ffi::sfRenderTexture_setActive(self.render_texture, sfBool::from_bool(active)) }
.into_bool()
}
/// Get the target texture of a render texture
///
/// Return the target texture
#[must_use]
pub fn texture(&self) -> &Texture {
let tex = unsafe { ffi::sfRenderTexture_getTexture(self.render_texture) };
assert!(!tex.is_null(), "sfRenderTexture_getTexture failed");
unsafe { &*(tex as *const Texture) }
}
/// Enable or disable the smooth filter on a render texture
///
/// # Arguments
/// * smooth - true to enable smoothing, false to disable it
pub fn set_smooth(&mut self, smooth: bool) {
unsafe { ffi::sfRenderTexture_setSmooth(self.render_texture, sfBool::from_bool(smooth)) }
}
/// Tell whether the smooth filter is enabled or not for a render texture
///
/// Return true if smoothing is enabled, false if it is disabled
#[must_use]
pub fn is_smooth(&self) -> bool {
unsafe { ffi::sfRenderTexture_isSmooth(self.render_texture) }.into_bool()
}
/// Enable or disable texture repeating.
///
/// This function is similar to `Texture::setRepeated`. This parameter is disabled by default.
pub fn set_repeated(&mut self, repeated: bool) {
unsafe {
ffi::sfRenderTexture_setRepeated(self.render_texture, SfBoolExt::from_bool(repeated))
}
}
/// Tell whether the texture is repeated or not.
#[must_use]
pub fn is_repeated(&self) -> bool {
unsafe { ffi::sfRenderTexture_isRepeated(self.render_texture).into_bool() }
}
/// Generate a mipmap using the current texture data.
///
/// This function is similar to [`Texture::generate_mipmap`] and
/// operates on the texture used as the target for drawing.
///
/// # Safety
///
/// Be aware that any draw operation may modify the base level image data.
/// For this reason, calling this function only makes sense after all drawing is
/// completed and display has been called. Not calling display after subsequent drawing
/// will lead to __undefined behavior__ if a mipmap had been previously generated.
pub unsafe fn generate_mipmap(&mut self) -> bool {
ffi::sfRenderTexture_generateMipmap(self.render_texture).into_bool()
}
/// Get the maximum anti-aliasing level supported by the system.
#[must_use]
pub fn maximum_antialiasing_level() -> u32 {
unsafe { ffi::sfRenderTexture_getMaximumAntialiasingLevel() }
}
}
impl RenderTarget for RenderTexture {
fn size(&self) -> Vector2u {
unsafe { Vector2u::from_raw(ffi::sfRenderTexture_getSize(self.render_texture)) }
}
fn clear(&mut self, color: Color) {
unsafe { ffi::sfRenderTexture_clear(self.render_texture, color.0) }
}
fn set_view(&mut self, view: &View) {
unsafe { ffi::sfRenderTexture_setView(self.render_texture, view.raw()) }
}
fn view(&self) -> &View {
unsafe { &*(ffi::sfRenderTexture_getView(self.render_texture) as *const View) }
}
fn default_view(&self) -> &View {
unsafe { &*(ffi::sfRenderTexture_getDefaultView(self.render_texture) as *const View) }
}
fn viewport(&self, view: &View) -> IntRect {
unsafe {
IntRect::from_raw(ffi::sfRenderTexture_getViewport(
self.render_texture,
view.raw(),
))
}
}
fn map_pixel_to_coords(&self, point: Vector2i, view: &View) -> Vector2f {
unsafe {
Vector2f::from_raw(ffi::sfRenderTexture_mapPixelToCoords(
self.render_texture,
point.raw(),
view.raw(),
))
}
}
fn map_pixel_to_coords_current_view(&self, point: Vector2i) -> Vector2f {
let view = unsafe { ffi::sfRenderTexture_getView(self.render_texture) };
unsafe {
Vector2f::from_raw(ffi::sfRenderTexture_mapPixelToCoords(
self.render_texture,
point.raw(),
view,
))
}
}
fn map_coords_to_pixel(&self, point: Vector2f, view: &View) -> Vector2i {
unsafe {
Vector2i::from_raw(ffi::sfRenderTexture_mapCoordsToPixel(
self.render_texture,
point.raw(),
view.raw(),
))
}
}
fn map_coords_to_pixel_current_view(&self, point: Vector2f) -> Vector2i {
let view = unsafe { ffi::sfRenderTexture_getView(self.render_texture) };
unsafe {
Vector2i::from_raw(ffi::sfRenderTexture_mapCoordsToPixel(
self.render_texture,
point.raw(),
view,
))
}
}
fn draw(&mut self, object: &dyn Drawable) {
object.draw(self, &RenderStates::DEFAULT);
|
}
fn draw_text(&self, text: &Text, rs: &RenderStates) {
unsafe { ffi::sfRenderTexture_drawText(self.render_texture, text.raw(), rs.raw_ref()) }
}
fn draw_shape(&self, shape: &CustomShape, rs: &RenderStates) {
unsafe { ffi::sfRenderTexture_drawShape(self.render_texture, shape.raw(), rs.raw_ref()) }
}
fn draw_sprite(&self, sprite: &Sprite, rs: &RenderStates) {
unsafe { ffi::sfRenderTexture_drawSprite(self.render_texture, sprite.raw(), rs.raw_ref()) }
}
fn draw_circle_shape(&self, circle_shape: &CircleShape, rs: &RenderStates) {
unsafe {
ffi::sfRenderTexture_drawCircleShape(
self.render_texture,
circle_shape.raw(),
rs.raw_ref(),
)
}
}
fn draw_rectangle_shape(&self, rectangle_shape: &RectangleShape, rs: &RenderStates) {
unsafe {
ffi::sfRenderTexture_drawRectangleShape(
self.render_texture,
rectangle_shape.raw(),
rs.raw_ref(),
)
}
}
fn draw_convex_shape(&self, convex_shape: &ConvexShape, rs: &RenderStates) {
unsafe {
ffi::sfRenderTexture_drawConvexShape(
self.render_texture,
convex_shape.raw(),
rs.raw_ref(),
)
}
}
fn draw_vertex_buffer(&self, vertex_buffer: &VertexBuffer, rs: &RenderStates) {
unsafe {
ffi::sfRenderTexture_drawVertexBuffer(
self.render_texture,
vertex_buffer.raw(),
rs.raw_ref(),
)
}
}
fn draw_primitives(&self, vertices: &[Vertex], ty: PrimitiveType, rs: &RenderStates) {
let len = vertices.len();
unsafe {
ffi::sfRenderTexture_drawPrimitives(
self.render_texture,
vertices.as_ptr() as *const _,
len,
ty.0,
rs.raw_ref(),
);
}
}
fn push_gl_states(&mut self) {
unsafe { ffi::sfRenderTexture_pushGLStates(self.render_texture) }
}
fn pop_gl_states(&mut self) {
unsafe { ffi::sfRenderTexture_popGLStates(self.render_texture) }
}
fn reset_gl_states(&mut self) {
unsafe { ffi::sfRenderTexture_resetGLStates(self.render_texture) }
}
}
impl Drop for RenderTexture {
fn drop(&mut self) {
unsafe { ffi::sfRenderTexture_destroy(self.render_texture) }
}
}
|
}
fn draw_with_renderstates(&mut self, object: &dyn Drawable, render_states: &RenderStates) {
object.draw(self, render_states);
|
errors.go
|
// Copyright 2018 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
package autoid
import (
"github.com/pingcap/parser/mysql"
"github.com/pingcap/parser/terror"
"github.com/pingcap/tidb/trace_util_0"
)
// Error instances.
var (
ErrAutoincReadFailed = terror.ClassAutoid.New(mysql.ErrAutoincReadFailed, mysql.MySQLErrName[mysql.ErrAutoincReadFailed])
)
func
|
() {
trace_util_0.Count(_errors_00000, 0)
// Map error codes to mysql error codes.
tableMySQLErrCodes := map[terror.ErrCode]uint16{
mysql.ErrAutoincReadFailed: mysql.ErrAutoincReadFailed,
}
terror.ErrClassToMySQLCodes[terror.ClassAutoid] = tableMySQLErrCodes
}
var _errors_00000 = "meta/autoid/errors.go"
|
init
|
gen_proposalid.go
|
// This file was automatically generated by genny.
// Any changes will be lost if this file is regenerated.
// see https://github.com/cheekybits/genny
package types
import (
"fmt"
"github.com/gkany/cocos-go/logging"
"github.com/gkany/cocos-go/util"
"github.com/juju/errors"
)
type ProposalID struct {
ObjectID
}
func (p ProposalID) Marshal(enc *util.TypeEncoder) error {
n, err := enc.EncodeUVarintByByte(uint64(p.Instance()))
if err != nil
|
for i := 0; i < 8-n; i++ {
if err := enc.EncodeUVarint(uint64(0)); err != nil {
return errors.Annotate(err, "encode zero")
}
}
return nil
}
func (p *ProposalID) Unmarshal(dec *util.TypeDecoder) error {
var instance uint64
if err := dec.DecodeUVarint(&instance); err != nil {
return errors.Annotate(err, "decode instance")
}
p.number = UInt64((uint64(SpaceTypeProtocol) << 56) | (uint64(ObjectTypeProposal) << 48) | instance)
return nil
}
type ProposalIDs []ProposalID
func (p ProposalIDs) Marshal(enc *util.TypeEncoder) error {
if err := enc.EncodeUVarint(uint64(len(p))); err != nil {
return errors.Annotate(err, "encode length")
}
for _, ex := range p {
if err := enc.Encode(ex); err != nil {
return errors.Annotate(err, "encode ProposalID")
}
}
return nil
}
func ProposalIDFromObject(ob GrapheneObject) ProposalID {
id, ok := ob.(*ProposalID)
if ok {
return *id
}
p := ProposalID{}
p.MustFromObject(ob)
if p.ObjectType() != ObjectTypeProposal {
panic(fmt.Sprintf("invalid ObjectType: %q has no ObjectType 'ObjectTypeProposal'", p.ID()))
}
return p
}
//NewProposalID creates an new ProposalID object
func NewProposalID(id string) GrapheneObject {
gid := new(ProposalID)
if err := gid.Parse(id); err != nil {
logging.Errorf(
"ProposalID parser error %v",
errors.Annotate(err, "Parse"),
)
return nil
}
if gid.ObjectType() != ObjectTypeProposal {
logging.Errorf(
"ProposalID parser error %s",
fmt.Sprintf("%q has no ObjectType 'ObjectTypeProposal'", id),
)
return nil
}
return gid
}
|
{
return errors.Annotate(err, "encode instance")
}
|
delete_admission_plugin_responses.go
|
// Code generated by go-swagger; DO NOT EDIT.
package admin
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"fmt"
"io"
"github.com/go-openapi/runtime"
"github.com/go-openapi/strfmt"
"github.com/maltejk/metakube-go-client/pkg/models"
)
// DeleteAdmissionPluginReader is a Reader for the DeleteAdmissionPlugin structure.
type DeleteAdmissionPluginReader struct {
formats strfmt.Registry
}
// ReadResponse reads a server response into the received o.
func (o *DeleteAdmissionPluginReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
switch response.Code() {
case 200:
result := NewDeleteAdmissionPluginOK()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return result, nil
case 401:
result := NewDeleteAdmissionPluginUnauthorized()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return nil, result
case 403:
result := NewDeleteAdmissionPluginForbidden()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return nil, result
default:
result := NewDeleteAdmissionPluginDefault(response.Code())
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
if response.Code()/100 == 2 {
return result, nil
}
return nil, result
}
}
// NewDeleteAdmissionPluginOK creates a DeleteAdmissionPluginOK with default headers values
func NewDeleteAdmissionPluginOK() *DeleteAdmissionPluginOK {
return &DeleteAdmissionPluginOK{}
}
/* DeleteAdmissionPluginOK describes a response with status code 200, with default header values.
EmptyResponse is a empty response
*/
type DeleteAdmissionPluginOK struct {
}
func (o *DeleteAdmissionPluginOK) Error() string {
return fmt.Sprintf("[DELETE /api/v1/admin/admission/plugins/{name}][%d] deleteAdmissionPluginOK ", 200)
}
func (o *DeleteAdmissionPluginOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
return nil
}
// NewDeleteAdmissionPluginUnauthorized creates a DeleteAdmissionPluginUnauthorized with default headers values
func NewDeleteAdmissionPluginUnauthorized() *DeleteAdmissionPluginUnauthorized
|
/* DeleteAdmissionPluginUnauthorized describes a response with status code 401, with default header values.
EmptyResponse is a empty response
*/
type DeleteAdmissionPluginUnauthorized struct {
}
func (o *DeleteAdmissionPluginUnauthorized) Error() string {
return fmt.Sprintf("[DELETE /api/v1/admin/admission/plugins/{name}][%d] deleteAdmissionPluginUnauthorized ", 401)
}
func (o *DeleteAdmissionPluginUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
return nil
}
// NewDeleteAdmissionPluginForbidden creates a DeleteAdmissionPluginForbidden with default headers values
func NewDeleteAdmissionPluginForbidden() *DeleteAdmissionPluginForbidden {
return &DeleteAdmissionPluginForbidden{}
}
/* DeleteAdmissionPluginForbidden describes a response with status code 403, with default header values.
EmptyResponse is a empty response
*/
type DeleteAdmissionPluginForbidden struct {
}
func (o *DeleteAdmissionPluginForbidden) Error() string {
return fmt.Sprintf("[DELETE /api/v1/admin/admission/plugins/{name}][%d] deleteAdmissionPluginForbidden ", 403)
}
func (o *DeleteAdmissionPluginForbidden) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
return nil
}
// NewDeleteAdmissionPluginDefault creates a DeleteAdmissionPluginDefault with default headers values
func NewDeleteAdmissionPluginDefault(code int) *DeleteAdmissionPluginDefault {
return &DeleteAdmissionPluginDefault{
_statusCode: code,
}
}
/* DeleteAdmissionPluginDefault describes a response with status code -1, with default header values.
errorResponse
*/
type DeleteAdmissionPluginDefault struct {
_statusCode int
Payload *models.ErrorResponse
}
// Code gets the status code for the delete admission plugin default response
func (o *DeleteAdmissionPluginDefault) Code() int {
return o._statusCode
}
func (o *DeleteAdmissionPluginDefault) Error() string {
return fmt.Sprintf("[DELETE /api/v1/admin/admission/plugins/{name}][%d] deleteAdmissionPlugin default %+v", o._statusCode, o.Payload)
}
func (o *DeleteAdmissionPluginDefault) GetPayload() *models.ErrorResponse {
return o.Payload
}
func (o *DeleteAdmissionPluginDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
o.Payload = new(models.ErrorResponse)
// response payload
if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
return err
}
return nil
}
|
{
return &DeleteAdmissionPluginUnauthorized{}
}
|
cl_progress.py
|
#!/usr/bin/env python
# encoding:utf-8
#
# Copyright 2015-2017 Yoshihiro Tanaka
# 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.
__Author__ = "Yoshihiro Tanaka"
__date__ = "2015-02-02"
def progress(sent, flag):
import sys, commands
_SUC = '[SUCCEED]'
_FAL = '[FAILED]'
# ref. http://d.hatena.ne.jp/heavenshell/20090909/1252509749
colors = {'clear': '\033[0m', 'red': '\033[31m', 'green': '\033[32m'}
width = int(commands.getoutput('stty size').split()[1])
if flag:
result = _SUC
color = 'green'
else:
result = _FAL
color = 'red'
spaces = width - (len(sent) + len(result))
sys.stdout.write('%s%s' % (colors['clear'], sent + (' ' * spaces)))
sys.stdout.write('%s%s%s\n' % (colors[color], result, colors['clear']))
| |
serviceprofile.go
|
/*
Copyright The Kubernetes Authors.
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.
*/
// Code generated by informer-gen. DO NOT EDIT.
package v1alpha1
import (
time "time"
serviceprofilev1alpha1 "github.com/linkerd/linkerd2/controller/gen/apis/serviceprofile/v1alpha1"
versioned "github.com/linkerd/linkerd2/controller/gen/client/clientset/versioned"
internalinterfaces "github.com/linkerd/linkerd2/controller/gen/client/informers/externalversions/internalinterfaces"
v1alpha1 "github.com/linkerd/linkerd2/controller/gen/client/listers/serviceprofile/v1alpha1"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
runtime "k8s.io/apimachinery/pkg/runtime"
watch "k8s.io/apimachinery/pkg/watch"
cache "k8s.io/client-go/tools/cache"
)
// ServiceProfileInformer provides access to a shared informer and lister for
// ServiceProfiles.
type ServiceProfileInformer interface {
Informer() cache.SharedIndexInformer
Lister() v1alpha1.ServiceProfileLister
}
type serviceProfileInformer struct {
factory internalinterfaces.SharedInformerFactory
tweakListOptions internalinterfaces.TweakListOptionsFunc
|
// Always prefer using an informer factory to get a shared informer instead of getting an independent
// one. This reduces memory footprint and number of connections to the server.
func NewServiceProfileInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {
return NewFilteredServiceProfileInformer(client, namespace, resyncPeriod, indexers, nil)
}
// NewFilteredServiceProfileInformer constructs a new informer for ServiceProfile type.
// Always prefer using an informer factory to get a shared informer instead of getting an independent
// one. This reduces memory footprint and number of connections to the server.
func NewFilteredServiceProfileInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {
return cache.NewSharedIndexInformer(
&cache.ListWatch{
ListFunc: func(options v1.ListOptions) (runtime.Object, error) {
if tweakListOptions != nil {
tweakListOptions(&options)
}
return client.LinkerdV1alpha1().ServiceProfiles(namespace).List(options)
},
WatchFunc: func(options v1.ListOptions) (watch.Interface, error) {
if tweakListOptions != nil {
tweakListOptions(&options)
}
return client.LinkerdV1alpha1().ServiceProfiles(namespace).Watch(options)
},
},
&serviceprofilev1alpha1.ServiceProfile{},
resyncPeriod,
indexers,
)
}
func (f *serviceProfileInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {
return NewFilteredServiceProfileInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)
}
func (f *serviceProfileInformer) Informer() cache.SharedIndexInformer {
return f.factory.InformerFor(&serviceprofilev1alpha1.ServiceProfile{}, f.defaultInformer)
}
func (f *serviceProfileInformer) Lister() v1alpha1.ServiceProfileLister {
return v1alpha1.NewServiceProfileLister(f.Informer().GetIndexer())
}
|
namespace string
}
// NewServiceProfileInformer constructs a new informer for ServiceProfile type.
|
map_test.go
|
// Copyright 2018 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.
package types
import (
"github.com/google/cel-go/common/types/traits"
"testing"
)
func
|
(t *testing.T) {
mapValue := NewDynamicMap(map[string]map[int32]float32{
"nested": {1: -1.0, 2: 2.0},
"empty": {}}).(traits.Mapper)
if mapValue.Equal(mapValue) != True {
t.Error("Map value was not equal to itself")
}
if nestedVal := mapValue.Get(String("nested")); IsError(nestedVal) {
t.Error(nestedVal)
} else if mapValue.Equal(nestedVal) == True ||
nestedVal.Equal(mapValue) == True {
t.Error("Same length, but different key names")
}
}
func TestMapValue_Get(t *testing.T) {
mapValue := NewDynamicMap(map[string]map[int32]float32{
"nested": {1: -1.0, 2: 2.0},
"empty": {}}).(traits.Mapper)
if nestedVal := mapValue.Get(String("nested")); IsError(nestedVal) {
t.Error(nestedVal)
} else if floatVal := nestedVal.(traits.Indexer).Get(Int(1)); IsError(floatVal) {
t.Error(floatVal)
} else if floatVal.Equal(Double(-1.0)) != True {
t.Error("Nested map access of float property not float64")
}
}
func TestMapValue_Iterator(t *testing.T) {
mapValue := NewDynamicMap(map[string]map[int32]float32{
"nested": {1: -1.0, 2: 2.0},
"empty": {}}).(traits.Mapper)
it := mapValue.Iterator()
var i = 0
var fieldNames []interface{}
for ; it.HasNext() == True; i++ {
if value := mapValue.Get(it.Next()); IsError(value) {
t.Error(value)
} else {
fieldNames = append(fieldNames, value)
}
}
if len(fieldNames) != 2 {
t.Errorf("Did not find the correct number of fields: %v", fieldNames)
}
if it.Next() != nil {
t.Error("Iterator ran off the end of the field names")
}
}
|
TestMapValue_Equal
|
assets.go
|
package assets
import (
"github.com/Oppodelldog/go-simple-webapp-template/config"
"github.com/go-playground/statics/static"
)
var Templates *static.Files
var Styles *static.Files
var Icons *static.Files
var Javascript *static.Files
func init()
|
{
var err error
cfg := &static.Config{
UseStaticFiles: config.UseStaticFiles,
FallbackToDisk: false,
AbsPkgPath: config.AbsoluteAssetsPath,
}
Templates, err = newStaticTemplates(cfg)
if err != nil {
panic(err)
}
Styles, err = newStaticStyles(cfg)
if err != nil {
panic(err)
}
Icons, err = newStaticIcons(cfg)
if err != nil {
panic(err)
}
Javascript, err = newStaticJavascript(cfg)
if err != nil {
panic(err)
}
}
|
|
aws.go
|
package aws
// <!-- START clutchdoc -->
// description: Locates resources in the Amazon Web Services (AWS) cloud.
// <!-- END clutchdoc -->
import (
"context"
"errors"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/ptypes/any"
"github.com/uber-go/tally"
"go.uber.org/zap"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
dynamodbv1api "github.com/lyft/clutch/backend/api/aws/dynamodb/v1"
ec2v1api "github.com/lyft/clutch/backend/api/aws/ec2/v1"
kinesisv1api "github.com/lyft/clutch/backend/api/aws/kinesis/v1"
awsv1resolver "github.com/lyft/clutch/backend/api/resolver/aws/v1"
resolverv1 "github.com/lyft/clutch/backend/api/resolver/v1"
"github.com/lyft/clutch/backend/gateway/meta"
"github.com/lyft/clutch/backend/resolver"
"github.com/lyft/clutch/backend/service"
"github.com/lyft/clutch/backend/service/aws"
"github.com/lyft/clutch/backend/service/topology"
)
const Name = "clutch.resolver.aws"
// Output types (want).
var typeURLInstance = meta.TypeURL((*ec2v1api.Instance)(nil))
var typeURLAutoscalingGroup = meta.TypeURL((*ec2v1api.AutoscalingGroup)(nil))
var typeURLKinesisStream = meta.TypeURL((*kinesisv1api.Stream)(nil))
var typeURLDynamodbTable = meta.TypeURL((*dynamodbv1api.Table)(nil))
var typeSchemas = resolver.TypeURLToSchemaMessagesMap{
typeURLInstance: {
(*awsv1resolver.InstanceID)(nil),
},
typeURLAutoscalingGroup: {
(*awsv1resolver.AutoscalingGroupName)(nil),
},
typeURLKinesisStream: {
(*awsv1resolver.KinesisStreamName)(nil),
},
typeURLDynamodbTable: {
(*awsv1resolver.DynamodbTableName)(nil),
},
}
func makeRegionOptions(regions []string) []*resolverv1.Option {
ret := make([]*resolverv1.Option, len(regions))
for i, region := range regions {
ret[i] = &resolverv1.Option{
Value: &resolverv1.Option_StringValue{StringValue: region},
}
}
return ret
}
func New(cfg *any.Any, logger *zap.Logger, scope tally.Scope) (resolver.Resolver, error) {
awsClient, ok := service.Registry["clutch.service.aws"]
if !ok {
return nil, errors.New("could not find service")
}
c, ok := awsClient.(aws.Client)
if !ok {
return nil, errors.New("service was not the correct type")
}
var topologyService topology.Service
if svc, ok := service.Registry[topology.Name]; ok {
topologyService, ok = svc.(topology.Service)
if !ok
|
logger.Debug("enabling autocomplete api for the aws resolver")
}
schemas, err := resolver.InputsToSchemas(typeSchemas)
if err != nil {
return nil, err
}
resolver.HydrateDynamicOptions(schemas, map[string][]*resolverv1.Option{
"regions": makeRegionOptions(c.Regions()),
})
r := &res{
client: c,
topology: topologyService,
schemas: schemas,
}
return r, nil
}
type res struct {
client aws.Client
topology topology.Service
schemas resolver.TypeURLToSchemasMap
}
func (r *res) determineRegionsForOption(option string) []string {
var regions []string
switch option {
case resolver.OptionAll:
regions = r.client.Regions()
default:
regions = []string{option}
}
return regions
}
func (r *res) Schemas() resolver.TypeURLToSchemasMap { return r.schemas }
func (r *res) Resolve(ctx context.Context, wantTypeURL string, input proto.Message, limit uint32) (*resolver.Results, error) {
switch wantTypeURL {
case typeURLInstance:
return r.resolveInstancesForInput(ctx, input)
case typeURLAutoscalingGroup:
return r.resolveAutoscalingGroupsForInput(ctx, input)
case typeURLKinesisStream:
return r.resolveKinesisStreamForInput(ctx, input)
case typeURLDynamodbTable:
return r.resolveDynamodbTableForInput(ctx, input)
default:
return nil, status.Errorf(codes.Internal, "resolver for '%s' not implemented", wantTypeURL)
}
}
func (r *res) Search(ctx context.Context, typeURL, query string, limit uint32) (*resolver.Results, error) {
switch typeURL {
case typeURLInstance:
patternValues, ok, err := meta.ExtractPatternValuesFromString((*ec2v1api.Instance)(nil), query)
if err != nil {
return nil, err
}
if ok {
return r.instanceResults(ctx, patternValues["region"], []string{patternValues["instance_id"]}, limit)
}
id, err := normalizeInstanceID(query)
if err != nil {
return nil, err
}
return r.instanceResults(ctx, resolver.OptionAll, []string{id}, limit)
case typeURLAutoscalingGroup:
patternValues, ok, err := meta.ExtractPatternValuesFromString((*ec2v1api.AutoscalingGroup)(nil), query)
if err != nil {
return nil, err
}
if ok {
return r.autoscalingGroupResults(ctx, patternValues["region"], []string{patternValues["name"]}, limit)
}
return r.autoscalingGroupResults(ctx, resolver.OptionAll, []string{query}, limit)
case typeURLKinesisStream:
patternValues, ok, err := meta.ExtractPatternValuesFromString((*kinesisv1api.Stream)(nil), query)
if err != nil {
return nil, err
}
if ok {
return r.kinesisResults(ctx, patternValues["region"], patternValues["stream_name"], limit)
}
return r.kinesisResults(ctx, resolver.OptionAll, query, limit)
case typeURLDynamodbTable:
patternValues, ok, err := meta.ExtractPatternValuesFromString((*dynamodbv1api.Table)(nil), query)
if err != nil {
return nil, err
}
if ok {
return r.dynamodbResults(ctx, patternValues["region"], patternValues["name"], limit)
}
return r.dynamodbResults(ctx, resolver.OptionAll, query, limit)
default:
return nil, status.Errorf(codes.Internal, "resolver search for '%s' not implemented", typeURL)
}
}
func (r *res) Autocomplete(ctx context.Context, typeURL, search string, limit uint64) ([]*resolverv1.AutocompleteResult, error) {
if r.topology == nil {
return nil, status.Error(codes.FailedPrecondition, "topology service must be enabled to use the AWS autocomplete API")
}
var resultLimit uint64 = resolver.DefaultAutocompleteLimit
if limit > 0 {
resultLimit = limit
}
results, err := r.topology.Autocomplete(ctx, typeURL, search, resultLimit)
if err != nil {
return nil, err
}
autoCompleteValue := make([]*resolverv1.AutocompleteResult, len(results))
for i, r := range results {
autoCompleteValue[i] = &resolverv1.AutocompleteResult{
Id: r.Id,
// TODO (mcutalo): Add more detailed information to the label
// the labels value will vary based on resource
Label: "",
}
}
return autoCompleteValue, nil
}
|
{
return nil, errors.New("incorrect topology service type")
}
|
quicksort.go
|
package main
import (
"fmt"
)
func partition(a []int, lo, hi int) int {
p := a[hi]
for j := lo; j < hi; j++ {
if a[j] < p {
a[j], a[lo] = a[lo], a[j]
lo++
}
}
a[lo], a[hi] = a[hi], a[lo]
return lo
}
func quickSort(a []int, lo, hi int) {
if lo > hi {
return
}
p := partition(a, lo, hi)
quickSort(a, lo, p-1)
quickSort(a, p+1, hi)
}
func
|
() {
list := []int{55, 90, 74, 20, 16, 46, 43, 59, 2, 99, 79, 10, 73, 1, 68, 56, 3, 87, 40, 78, 14, 18, 51, 24, 57, 89, 4, 62, 53, 23, 93, 41, 95, 84, 88}
quickSort(list, 0, len(list)-1)
fmt.Println(list)
}
|
main
|
alpine.go
|
package provision
import (
"fmt"
"github.com/docker/machine/libmachine/auth"
"github.com/docker/machine/libmachine/drivers"
"github.com/docker/machine/libmachine/engine"
"github.com/docker/machine/libmachine/log"
"github.com/docker/machine/libmachine/mcnutils"
"github.com/docker/machine/libmachine/provision/pkgaction"
"github.com/docker/machine/libmachine/provision/serviceaction"
"github.com/docker/machine/libmachine/swarm"
)
func init() {
Register("Alpine", &RegisteredProvisioner{
New: NewAlpineProvisioner,
})
}
func
|
(d drivers.Driver) Provisioner {
return &AlpineProvisioner{
GenericProvisioner{
SSHCommander: GenericSSHCommander{Driver: d},
DockerOptionsDir: "/etc/docker",
DaemonOptionsFile: "/etc/conf.d/docker",
OsReleaseID: "alpine",
Packages: []string{
"curl",
},
Driver: d,
},
}
}
type AlpineProvisioner struct {
GenericProvisioner
}
func (provisioner *AlpineProvisioner) String() string {
return "alpine"
}
func (provisioner *AlpineProvisioner) CompatibleWithHost() bool {
return provisioner.OsReleaseInfo.ID == provisioner.OsReleaseID || provisioner.OsReleaseInfo.IDLike == provisioner.OsReleaseID
}
func (provisioner *AlpineProvisioner) Package(name string, action pkgaction.PackageAction) error {
var packageAction string
switch action {
case pkgaction.Install, pkgaction.Upgrade:
packageAction = "add"
case pkgaction.Remove:
packageAction = "remove"
}
switch name {
case "docker-engine":
name = "docker"
case "docker":
name = "docker"
}
command := fmt.Sprintf("sudo apk %s %s", packageAction, name)
log.Debugf("package: action=%s name=%s", action.String(), name)
if _, err := provisioner.SSHCommand(command); err != nil {
return err
}
return nil
}
func (provisioner *AlpineProvisioner) dockerDaemonResponding() bool {
log.Debug("checking docker daemon")
if out, err := provisioner.SSHCommand("sudo docker version"); err != nil {
log.Warnf("Error getting SSH command to check if the daemon is up: %s", err)
log.Debugf("'sudo docker version' output:\n%s", out)
return false
}
// The daemon is up if the command worked. Carry on.
return true
}
func (provisioner *AlpineProvisioner) Service(name string, action serviceaction.ServiceAction) error {
var command string
switch action {
case serviceaction.Start, serviceaction.Restart, serviceaction.Stop:
command = fmt.Sprintf("sudo rc-service %s %s", name, action.String())
case serviceaction.DaemonReload:
command = fmt.Sprintf("sudo rc-service restart %s", name)
case serviceaction.Enable:
command = fmt.Sprintf("sudo rc-update add %s boot", name)
case serviceaction.Disable:
command = fmt.Sprintf("sudo rc-update del %s boot", name)
}
if _, err := provisioner.SSHCommand(command); err != nil {
return err
}
return nil
}
func (provisioner *AlpineProvisioner) Provision(swarmOptions swarm.Options, authOptions auth.Options, engineOptions engine.Options) error {
provisioner.SwarmOptions = swarmOptions
provisioner.AuthOptions = authOptions
provisioner.EngineOptions = engineOptions
swarmOptions.Env = engineOptions.Env
storageDriver, err := decideStorageDriver(provisioner, "overlay", engineOptions.StorageDriver)
if err != nil {
return err
}
provisioner.EngineOptions.StorageDriver = storageDriver
// HACK: since Alpine does not come with sudo by default we install
log.Debug("Installing sudo")
if _, err := provisioner.SSHCommand("if ! type sudo; then apk add sudo; fi"); err != nil {
return err
}
log.Debug("Setting hostname")
if err := provisioner.SetHostname(provisioner.Driver.GetMachineName()); err != nil {
return err
}
log.Debug("Installing base packages")
for _, pkg := range provisioner.Packages {
if err := provisioner.Package(pkg, pkgaction.Install); err != nil {
return err
}
}
log.Debug("Installing docker")
if err := provisioner.Package("docker", pkgaction.Install); err != nil {
return err
}
log.Debug("Starting docker service")
if err := provisioner.Service("docker", serviceaction.Start); err != nil {
return err
}
log.Debug("Waiting for docker daemon")
if err := mcnutils.WaitFor(provisioner.dockerDaemonResponding); err != nil {
return err
}
provisioner.AuthOptions = setRemoteAuthOptions(provisioner)
log.Debug("Configuring auth")
if err := ConfigureAuth(provisioner); err != nil {
return err
}
log.Debug("Configuring swarm")
if err := configureSwarm(provisioner, swarmOptions, provisioner.AuthOptions); err != nil {
return err
}
// enable service
log.Debug("Enabling docker service")
if err := provisioner.Service("docker", serviceaction.Enable); err != nil {
return err
}
return nil
}
|
NewAlpineProvisioner
|
planificacion-reforzamiento.component_20200409180625.ts
|
import { Component, OnInit } from '@angular/core';
import { PersonalDataService } from 'app/services/personal-data.service';
import { RestService} from 'app/service/rest.service';
import { TutoriaConstants } from 'app/constants/constants';
import { FormGroup } from '@angular/forms';
import { ToastrService } from 'ngx-toastr';
import { formatDate } from "@angular/common";
const format = 'dd/MM/yyyy';
const myDate = Date.now();
const locale = 'en-US';
const formattedDate = formatDate(myDate, format, locale);
@Component({
selector: 'app-planificacion-reforzamiento',
templateUrl: './planificacion-reforzamiento.component.html',
styleUrls: ['./planificacion-reforzamiento.component.scss']
})
export class PlanificacionReforzamientoComponent implements OnInit {
titleDocente= TutoriaConstants.DATOSDOCENTE;
titleTutoria= TutoriaConstants.DATOSTUTORIA;
titleRegistro= TutoriaConstants.DATOSREGISTRO;
constructor(private service: PersonalDataService, private restService: RestService, public toast: ToastrService) { }
options: any = {
toastLife: 3000,
dismiss: "auto",
showCloseButton: true
};
nrc1: any = {
id: ""
}
datosGuardar: any;
ncr: any;
nrcs: any
spidem = 334571;
cedula = "1725412306";
campus1 = "10";
dia1 = "SZARPGN_CAMPVA10";
hora_INICIO = "0715";
hora_FIN = "0915";
dia: any;
aulas: any;
horario: any;
horariosSelected: any;
ngOnInit() {
this.listarNrc();
this
}
id:any
procesaPropagar(data) {
this.id = data[0].pidm
//console.log(data[0].pidm)
}
tema: any = {
tema: ""
}
public observaciones: any = {
observacion: "",
fecha: Date.now(),
}
nrc: any;
codigo: any;
asignatura: any;
campus: any;
periodo: any;
inicio: any;
fin: any;
actualizar(nrc: number, codigo, asignatura, campus, periodo, inicio, fin) {
this.nrc = nrc;
this.codigo = codigo;
this.asignatura = asignatura;
this.campus = campus;
this.periodo = periodo;
this.inicio = inicio;
this.fin = fin;
}
listarNrc() {
this.restService.findDataById("planificaionReforzamiento/", this.spidem).subscribe(
|
)
}
ActualizarTutoria() {
this.datosGuardar = {
codigoFormularios: "2",
interacion: "0",
fechaFormulario: formattedDate,
tipoPersona: "ESTUDIANTE",
tipoTutoria: "REFORZAMIENTO",
spridenPidm: this.id,
tema: this.tema.tema,
observacion: this.observaciones.observacion,
estado: "A",
nrc: this.nrc,
periodo: this.periodo,
inicio: this.inicio,
fin: this.fin,
campCode: this.campus,
asignatura: this.asignatura,
codAsignatura: this.codigo
}
this.restService.UpData(this.datosGuardar,"segu").subscribe(
data => {
if(data){
this.toast.success(data.mensaje, "El Formulario", this.options);
this.tema = [];
this.observaciones.observacion= "";
this.nrcs = []
}else{
this.toast.error("No se creo");
}
}
)
}
listarHorario() {
this.restService.findDataByHorarioReforzamiento("horarioPlanificacion/", this.campus1,"/", this.dia1,"/",this.hora_INICIO,"/",this.hora_FIN).subscribe(
data => {
if (data) {
console.log('datos2', data)
this.aulas = data;
console.log("se listo" + this.aulas);
}
}
)
}
expressType: string;
typeExpress: string[] = [ 'Si', 'No'];
radioOptions: FormGroup;
expressType2: string;
typeExpress2: string[] = [ 'AULA', 'LUGAR'];
radioOptions2: FormGroup;
}
|
data => {
this.nrcs = data
//console.log(this.nrcs)
}
|
quick_test.py
|
#!python
"""Unittesting for the pyross module. Run as python -m unittest pyross.test."""
import sys
#remove pwd from path that tries to import .pyx files
for i in sys.path:
if 'pyross' in i or i == '':
sys.path.remove(i)
# print(sys.path)
import pyross
import unittest
import inspect
import numpy as np
import scipy as sp
class DeterministicTest(unittest.TestCase):
"""testing deterministic.pyx."""
N = np.asarray([10000], dtype=np.float64)
M = 1
alpha = 0
beta = 0.0071
gIa = 0.008
gIs = 0.008
gI = 0.008
gE = 0.007
gIc = 0.1
gIhp= 0.1
gIsp= 0.1
gIcp= 0.1
gIh = 0.1
gA = 0
tE = 0
tIa = 0
tIs = 0
Tf = 100
Nf = 1000
fsa = 0
fh = 1
sa = 0
iaa = 0
hh = 0
cc = 0
mm = 0
tE = 0
tA = 0
tIa = 0
tIs = 0
kI = 1
kE = 1
k = 1
ep = 0
parameters = {'N': N, 'M': M, 'alpha': alpha,
'beta': beta, 'gIa': gIa, 'gIs': gIs,
'gIsp':gIsp,'gIhp':gIhp,'gIcp':gIcp,
'gI': gI, 'iaa': iaa,
'gE': gE, 'gA': gA, 'tE': tE,
'gIc': gIc, 'gIh': gIh, 'fh': fh,
'tIa': tIa, 'tIs': tIs, 'fsa': fsa,
'sa': sa, 'hh': hh, 'cc': cc,
'mm': mm, 'tA': tA, 'tE': tE,
'tIa': tIa, 'tIs': tIs, 'kI': kI,
'kE': kE, 'ep': ep, 'k': k}
def __init__(self, *args, **kwargs):
super(DeterministicTest, self).__init__(*args, **kwargs)
# self.parameters = self.parameters
def contactMatrix(self, t): return np.identity(self.M)
def test_decay(self):
"""
Exponential decay from infected to recovered. Paths agree within .1%.
"""
SIR = pyross.deterministic.SIR(self.parameters, self.M, self.N)
sim = SIR.simulate(np.zeros(1), np.zeros(1), self.N,
self.contactMatrix, self.Tf,
self.Nf, integrator='solve_ivp')
time_points = np.linspace(0, self.Tf, self.Nf)
exp_decay = sp.integrate.solve_ivp(lambda t, y: -self.gIs * y,
(0, self.Tf), self.N,
t_eval=time_points)
diff = (sim['X'][:, 2] - exp_decay.y)/self.N
self.assertTrue((diff < 0.001).all(), msg="paths differ > .1%")
def test_integrators(self):
"""
All integration methods produce paths which agree within .1%
"""
integrators = ['solve_ivp', 'odeint', 'odespy',
'odespy-rkf45', 'odespy-rk4']
paths = []
model = pyross.deterministic.SIR(self.parameters, self.M, self.N)
for integrator in integrators:
try:
data = model.simulate(np.zeros(1), np.zeros(1), self.N,
self.contactMatrix, self.Tf,
self.Nf, integrator=integrator)
except ImportError:
print(f"{integrator} is not installed, skipping...")
pass
paths.append(data['X'])
for i in range(len(paths)):
for j in range(len(paths)):
if i != j:
diff = (paths[i]-paths[j])/self.N
self.assertTrue((np.asarray(diff) < 0.001).all(),
msg=f"path {i} not equal to path {j}")
def test_SIRS(self):
"""Test to make sure SIRS collapses down to SIR"""
self.parameters['ep'] = 0
self.parameters['sa'] = 0
self.parameters['iaa'] = 0
SIR = pyross.deterministic.SIR(self.parameters, self.M, self.N)
SIRS = pyross.deterministic.SIRS(self.parameters, self.M, self.N)
SIRdata = SIR.simulate(self.N, np.ones(1), np.zeros(1),
self.contactMatrix, self.Tf,
self.Nf)['X']
SIRSdata = SIRS.simulate(self.N, np.ones(1), np.zeros(1),
self.contactMatrix, self.Tf,
self.Nf)['X']
self.assertTrue((SIRdata-SIRSdata[:, 0:3] < 0.001).all(),
msg="paths differ > .1%")
def test_init_models(self):
"""Test initialisation of deterministic models"""
deterministic_models = dict(inspect.getmembers(pyross.deterministic,
inspect.isclass))
for name, model in deterministic_models.items():
if name.startswith('S') and not 'Spp':
m = model(self.parameters, self.M, self.N)
def test_run_models(self):
|
class StochasticTest(unittest.TestCase):
"""testing stochastic.pyx"""
nloops=10
iinfec = 3000
Tf = 10
def __init__(self, *args, **kwargs):
super(StochasticTest, self).__init__(*args, **kwargs)
self.parameters = DeterministicTest.parameters
self.stochastic_models = dict(inspect.getmembers(pyross.stochastic,
inspect.isclass))
def contactMatrix(self, t): return np.identity(self.parameters['M'])
def test_init_models(self):
"""Initializes all stochastic models"""
traj_dict={}
for name, model in self.stochastic_models.items():
if name.startswith('S'):
params, M, N = self.parameters, self.parameters['M'], self.parameters['N']
m = model(params, M, N)
# x0 = np.array([*self.N, *np.ones(self.M),
# *np.zeros(m.nClass -2)], dtype=np.float64).reshape((m.nClass,1))
# traj_dict[name] = m.simulate(*x0, self.contactMatrix, 100, 100)
def test_run_models(self):
"""Runs all stochastic models"""
traj_dict={}
for name, model in self.stochastic_models.items():
if name.startswith('S'):
params, M, N = self.parameters, self.parameters['M'], self.parameters['N']
m = model(params, M, N + M*10)
x0 = np.array([*self.parameters['N'],
*np.ones(self.parameters['M'])*10,
*np.zeros(m.nClass -2)],
dtype=np.float64).reshape((m.nClass,1))
traj_dict[name] = m.simulate(*x0, self.contactMatrix, 100, 100)
def test_stochastic_mean_gillespie(self):
"""Runs stochastic models a few times and compares mean to
deterministic"""
deterministic_models = dict(inspect.getmembers(pyross.deterministic,
inspect.isclass))
params, M, N = self.parameters, self.parameters['M'], self.parameters['N']
for name, model in self.stochastic_models.items():
if name.startswith('S'):
mS = model(params, M, N + M*self.iinfec)
# print(mS.kk)
mD = deterministic_models[name](params, M, N + M*self.iinfec)
x0 = np.array([*self.parameters['N'],
*np.ones(self.parameters['M'])*self.iinfec,
*np.zeros(mS.nClass -2)],
dtype=np.float64).reshape((mS.nClass,1))
trajectories = []
for i in range(self.nloops):
traj = mS.simulate(*x0, self.contactMatrix, self.Tf, self.Tf)['X']
trajectories.append(traj)
traj_mean = np.mean(trajectories, axis=0)[:-1]
mean = mD.simulate(*x0, self.contactMatrix, self.Tf, self.Tf)['X']
absdiff = np.abs(traj_mean -mean)/(N*self.Tf)
# print(name, np.sum(absdiff[:,:-1]))
self.assertTrue(np.sum(absdiff[:,:-1])<0.01,
msg=f"{name} model disagreement")
def test_stochastic_mean_tau(self):
"""Runs stochastic models a few times and compares mean to
deterministic using tau leaping"""
deterministic_models = dict(inspect.getmembers(pyross.deterministic,
inspect.isclass))
params, M, N = self.parameters, self.parameters['M'], self.parameters['N']
for name, model in self.stochastic_models.items():
if name.startswith('S'):
mS = model(params, M, N + M*self.iinfec)
# print(mS.kk)
mD = deterministic_models[name](params, M, N + M*self.iinfec)
x0 = np.array([*self.parameters['N'],
*np.ones(self.parameters['M'])*self.iinfec,
*np.zeros(mS.nClass -2)],
dtype=np.float64).reshape((mS.nClass,1))
trajectories = []
for i in range(self.nloops):
traj = mS.simulate(*x0, self.contactMatrix, self.Tf, self.Tf,
method='tau_leaping')['X']
trajectories.append(traj)
traj_mean = np.mean(trajectories, axis=0)[:-1]
mean = mD.simulate(*x0, self.contactMatrix, self.Tf, self.Tf)['X']
absdiff = np.abs(traj_mean -mean)/(N*self.Tf)
# print(name, np.sum(absdiff[:,:-1]))
self.assertTrue(np.sum(absdiff[:,:-1])<0.01,
msg=f"{name} model disagreement")
def test_stochastic_integrators(self):
"""Compare tau leaping to Gillespie.
This will fail because there is a problem with SIkR
Also, difference is an order of magnitude greater than
Gillespie from the mean.
"""
self.nloops=10
params, M, N = self.parameters, self.parameters['M'], self.parameters['N']
for name, model in self.stochastic_models.items():
if name.startswith('S'):
mS = model(params, M, N + M*self.iinfec)
x0 = np.array([*self.parameters['N'],
*np.ones(self.parameters['M'])*self.iinfec,
*np.zeros(mS.nClass -2)],
dtype=np.float64).reshape((mS.nClass,1))
gtraj = []
tautraj = []
for i in range(self.nloops):
gtraj.append(mS.simulate(*x0, self.contactMatrix, self.Tf, self.Tf,
method='gillespie')['X'])
tautraj.append(mS.simulate(*x0, self.contactMatrix, self.Tf, self.Tf,
method='tau_leaping', epsilon=1E-3)['X'])
gmean = np.sum(gtraj, axis=0)
taumean= np.sum(tautraj, axis=0)
absdiff = np.abs(gmean - taumean)/(N*self.Tf)
# print(name, np.sum(absdiff), np.shape(gmean), np.shape(taumean))
self.assertTrue(np.sum(absdiff)<.1, msg=f"{name} model disagreement")
class ControlTest(unittest.TestCase):
"""testing control.pyx"""
def __init__(self, *args, **kwargs):
super(ControlTest, self).__init__(*args, **kwargs)
self.parameters = DeterministicTest.parameters
self.control_models = dict(inspect.getmembers(pyross.control,
inspect.isclass))
def contactMatrix(self, t): return np.identity(self.parameters['M'])
def test_init_models(self):
"""Initializes all control models"""
for name, model in self.control_models.items():
if name.startswith('S'):
params, M, N = self.parameters, self.parameters['M'], self.parameters['N']
m = model(params, M, N)
class InferenceTest(unittest.TestCase):
"""testing inference.pyx"""
def __init__(self, *args, **kwargs):
super(InferenceTest, self).__init__(*args, **kwargs)
self.parameters = DeterministicTest.parameters
self.control_models = dict(inspect.getmembers(pyross.inference,
inspect.isclass))
def contactMatrix(self, t): return np.identity(self.parameters['M'])
def test_init_models(self):
"""Initializes all inference models"""
for name, model in self.control_models.items():
if name.startswith('S') and name != "SIR_type":
params, M, Ni = self.parameters, self.parameters['M'], self.parameters['N']
N = int(np.sum(Ni))
fi = Ni/N
steps = 1
m = model(params, M, fi, N, steps)
class ForecastTest(unittest.TestCase):
"""testing forcast.pyx"""
def __init__(self, *args, **kwargs):
super(ForecastTest, self).__init__(*args, **kwargs)
self.parameters = DeterministicTest.parameters
self.control_models = dict(inspect.getmembers(pyross.forecast,
inspect.isclass))
self.parameters['cov'] = np.identity(2)
def contactMatrix(self, t): return np.identity(self.parameters['M'])
def test_init_models(self):
"""Initializes all forcast models"""
for name, model in self.control_models.items():
if name.startswith('S') and name != "SIR_type":
params, M, Ni = self.parameters, self.parameters['M'], self.parameters['N']
N = int(np.sum(Ni))
fi = Ni/N
steps = 1
m = model(params, M, Ni)
class UtilsPythonTest(unittest.TestCase):
"""Testing the minimization function in utils_python.py"""
def __init__(self, *args, **kwargs):
super(UtilsPythonTest, self).__init__(*args, **kwargs)
def test_minimization(self):
"""Test the minimization(...) function in utils_python.py with a few simple examples"""
# A simple example
f1 = lambda x, grad=0: 1 + np.linalg.norm(x)**2
# A multi-modal example
f2 = lambda x, grad=0: 1 + np.linalg.norm(x)**2 + 0.1*np.abs(np.sin(4*np.pi*np.linalg.norm(x)))
# Test global optimisation
guess = np.array([1.0, 1.0])
bounds = np.array([[-2.0, 2.0], [-2.0, 2.0]])
x, y = pyross.utils_python.minimization(f1, guess, bounds, enable_global=True, enable_local=False,
ftol=1e-4, cma_random_seed=1, verbose=False)
self.assertTrue(np.abs(y - 1.0) < 1e-3)
x, y = pyross.utils_python.minimization(f2, guess, bounds, enable_global=True, enable_local=False,
ftol=1e-4, verbose=False, cma_random_seed=2)
self.assertTrue(np.abs(y - 1.0) < 1e-3)
# Test local optimisation
guess = np.array([2.0, 2.0])
bounds = np.array([[-5.0, 5.0], [-5.0, 5.0]])
x, y = pyross.utils_python.minimization(f1, guess, bounds, enable_global=False, enable_local=True,
ftol=1e-5, verbose=False)
self.assertTrue(np.abs(y - 1.0) < 1e-4)
# And now combined
x, y = pyross.utils_python.minimization(f2, guess, bounds, enable_global=True, enable_local=True,
ftol=1e-5, global_ftol_factor=100, verbose=False, cma_random_seed=4)
self.assertTrue(np.abs(y - 1.0) < 1e-4)
if __name__ == '__main__':
unittest.main()
|
"""Runs all deterministic models"""
deterministic_models = dict(inspect.getmembers(pyross.deterministic,
inspect.isclass))
traj_dict={}
for name, model in deterministic_models.items():
if name.startswith('S') and not 'Spp':
m = model(self.parameters, self.M, self.N)
x0 = np.array([*self.N, *np.ones(self.M),
*np.zeros(m.nClass -2)], dtype=np.float64).reshape((m.nClass,1))
traj_dict[name] = m.simulate(*x0, self.contactMatrix, 100, 100)
|
user.entity.ts
|
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column({ unique: true })
email: string;
@Column({ default: true })
isActive: boolean;
@Column()
password: string;
}
|
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
@Entity()
export class User {
|
|
vehicle_keyboard_teleop.py
|
#!/usr/bin/env python
# Copyright (c) 2016 The UUV Simulator Authors.
# All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
import os
import time
import sys, select, termios, tty
import rospy
import numpy as np
from std_msgs.msg import Bool
from geometry_msgs.msg import Twist, Accel, Vector3
class KeyBoardVehicleTeleop:
|
if __name__ == '__main__':
# Wait for 5 seconds, so the instructions are the last thing to print in terminal
time.sleep(5)
# Start the node
node_name = os.path.splitext(os.path.basename(__file__))[0]
rospy.init_node(node_name)
rospy.loginfo('Starting [%s] node' % node_name)
teleop = KeyBoardVehicleTeleop()
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, settings)
rospy.loginfo('Shutting down [%s] node' % node_name)
|
def __init__(self):
# Class Variables
self.settings = termios.tcgetattr(sys.stdin)
# Speed setting
self.speed = 1 # 1 = Slow, 2 = Fast
self.l = Vector3(0, 0, 0) # Linear Velocity for Publish
self.a = Vector3(0, 0, 0) # Angular Velocity for publishing
self.linear_increment = 0.05 # How much to increment linear velocities by, to avoid jerkyness
self.linear_limit = 0.2 # Linear velocity limit = self.linear_limit * self.speed
self.angular_increment = 0.05
self.angular_limit = 0.25
# User Interface
self.msg = """
Control Your Vehicle!
---------------------------
Moving around:
W/S: X-Axis
A/D: Y-Axis
X/Z: Z-Axis
Q/E: Yaw
I/K: Pitch
J/L: Roll
Slow / Fast: 1 / 2
CTRL-C to quit
"""
# Default message remains as twist
self._msg_type = 'twist'
if rospy.has_param('~type'):
self._msg_type = rospy.get_param('~type')
if self._msg_type not in ['twist', 'accel']:
raise rospy.ROSException('Teleoperation output must be either '
'twist or accel')
# Name Publisher topics accordingly
if self._msg_type == 'twist':
self._output_pub = rospy.Publisher('output', Twist, queue_size=1)
# self._output_pub = rospy.Publisher('/rexrov2/cmd_vel', Twist, queue_size=1)
else:
self._output_pub = rospy.Publisher('output', Accel, queue_size=1)
print(self.msg)
# Ros Spin
rate = rospy.Rate(50) # 50hz
while not rospy.is_shutdown():
rate.sleep()
self._parse_keyboard()
# Every spin this function will return the key being pressed
# Only works for one key per spin currently, thus limited control exploring alternative methods
def _get_key(self):
tty.setraw(sys.stdin.fileno())
rlist, _, _ = select.select([sys.stdin], [], [], 0.1)
if rlist:
key = sys.stdin.read(1)
else:
key = ''
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, self.settings)
return key
# Function to gradually build up the speed and avoid jerkyness #
def _speed_windup(self, speed, increment, limit, reverse):
if reverse == True:
speed -= increment * self.speed
if speed < -limit * self.speed:
speed = -limit * self.speed
else:
speed += increment * self.speed
if speed > limit * self.speed:
speed = limit * self.speed
return speed
def _parse_keyboard(self):
# Save key peing pressed
key_press = self._get_key()
# Set Vehicle Speed #
if key_press == "1":
self.speed = 1
if key_press == "2":
self.speed = 2
# Choose ros message accordingly
if self._msg_type == 'twist':
cmd = Twist()
else:
cmd = Accel()
# If a key is pressed assign relevent linear / angular vel
if key_press!='':
# Linear velocities:
# Forward
if key_press == "w":
self.l.x = self._speed_windup(self.l.x, self.linear_increment, self.linear_limit, False)
# Backwards
if key_press == "s":
self.l.x = self._speed_windup(self.l.x, self.linear_increment, self.linear_limit, True)
# Left
if key_press == "a":
self.l.y = self._speed_windup(self.l.y, self.linear_increment, self.linear_limit, False)
# Right
if key_press == "d":
self.l.y = self._speed_windup(self.l.y, self.linear_increment, self.linear_limit, True)
# Up
if key_press == "x":
self.l.z = self._speed_windup(self.l.z, self.linear_increment, self.linear_limit, False)
# Down
if key_press == "z":
self.l.z = self._speed_windup(self.l.z, self.linear_increment, self.linear_limit, True)
# Angular Velocities
# Roll Left
if key_press == "j":
self.a.x = self._speed_windup(self.a.x, self.linear_increment, self.linear_limit, True)
# Roll Right
if key_press == "l":
self.a.x = self._speed_windup(self.a.x, self.linear_increment, self.linear_limit, False)
# Pitch Down
if key_press == "i":
self.a.y = self._speed_windup(self.a.y, self.linear_increment, self.linear_limit, False)
# Pitch Up
if key_press == "k":
self.a.y = self._speed_windup(self.a.y, self.linear_increment, self.linear_limit, True)
# Yaw Left
if key_press == "q":
self.a.z = self._speed_windup(self.a.z, self.angular_increment, self.angular_limit, False)
# Yaw Right
if key_press == "e":
self.a.z = self._speed_windup(self.a.z, self.angular_increment, self.angular_limit, True)
else:
# If no button is pressed reset velocities to 0
self.l = Vector3(0, 0, 0)
self.a = Vector3(0, 0, 0)
# Store velocity message into Twist format
cmd.angular = self.a
cmd.linear = self.l
# If ctrl+c kill node
if (key_press == '\x03'):
rospy.loginfo('Keyboard Interrupt Pressed')
rospy.loginfo('Shutting down [%s] node' % node_name)
# Set twists to 0
cmd.angular = Vector3(0, 0, 0)
cmd.linear = Vector3(0, 0, 0)
self._output_pub.publish(cmd)
exit(-1)
# Publish message
self._output_pub.publish(cmd)
|
metric_test.go
|
package statsd
import (
"testing"
)
func TestSimpleCount(t *testing.T) {
result := (&Metric{
Name: "test",
Value: 1,
Type: Counter,
}).String()
if expected := "test:1|c"; expected != result {
t.Errorf("metric string is different.\nExpected: \"%s\".\n Got: \"%s\"", expected, result)
}
}
func TestCountWithSample(t *testing.T) {
result := (&Metric{
Name: "test",
Value: 1.11111,
Type: Counter,
SampleRate: 0.33,
}).String()
if expected := "test:1.11111|c|@0.33"; expected != result
|
}
func TestCountWithTag(t *testing.T) {
result := (&Metric{
Name: "test",
Value: 1.11111,
Type: Counter,
SampleRate: 0.33,
Tags: []Tag{
{
Key: "oneKey",
Value: "oneValue",
},
},
}).String()
if expected := "test:1.11111|c|@0.33|#oneKey:oneValue"; expected != result {
t.Errorf("metric string is different.\nExpected: \"%s\".\n Got: \"%s\"", expected, result)
}
}
func TestCountWithMultipleTags(t *testing.T) {
result := (&Metric{
Name: "test",
Value: 1,
Type: Counter,
Tags: []Tag{
{
Key: "oneKey",
Value: "oneValue",
},
{
Key: "twoKey",
Value: "twoValue",
},
},
}).String()
if expected := "test:1|c|#oneKey:oneValue,twoKey:twoValue"; expected != result {
t.Errorf("metric string is different.\nExpected: \"%s\".\n Got: \"%s\"", expected, result)
}
}
|
{
t.Errorf("metric string is different.\nExpected: \"%s\".\n Got: \"%s\"", expected, result)
}
|
random.rs
|
use std::ops::ControlFlow::{self, *};
use super::{rng::Rng, ParseError, Result};
use crate::lex::token::Token;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum ClauseState {
Random(u32),
If(bool),
}
pub struct RandomParser<R> {
rng: R,
random_stack: Vec<ClauseState>,
}
impl<R: Rng> RandomParser<R> {
pub fn
|
(rng: R) -> Self {
Self {
rng,
random_stack: vec![],
}
}
pub fn parse(&mut self, token: &Token) -> ControlFlow<Result<()>> {
match *token {
Token::If(rand_target) => {
if let Some(&ClauseState::Random(rand)) = self.random_stack.last() {
self.random_stack.push(ClauseState::If(rand_target == rand));
Break(Ok(()))
} else {
Break(Err(ParseError::SyntaxError(
"#IF command must be in #RANDOM - #ENDRANDOM block".into(),
)))
}
}
Token::ElseIf(rand_target) => {
if let Some(ClauseState::If(_)) = self.random_stack.last() {
self.random_stack.pop();
let rand = match self.random_stack.last().unwrap() {
&ClauseState::Random(rand) => rand,
ClauseState::If(_) => unreachable!(),
};
self.random_stack.push(ClauseState::If(rand_target == rand));
Break(Ok(()))
} else {
Break(Err(ParseError::SyntaxError(
"#ELSEIF command must come after #IF block".into(),
)))
}
}
Token::EndIf => {
if let Some(ClauseState::If(_)) = self.random_stack.last() {
self.random_stack.pop();
Break(Ok(()))
} else {
Break(Err(ParseError::SyntaxError(
"#ENDIF command must come after #IF or #ELSEIF block".into(),
)))
}
}
Token::Random(rand_max) => {
if let Some(&ClauseState::Random(_)) = self.random_stack.last() {
Break(Err(ParseError::SyntaxError(
"#RANDOM command must come in root or #IF block".into(),
)))
} else if let Some(ClauseState::If(false)) = self.random_stack.last() {
self.random_stack.push(ClauseState::Random(0));
Break(Ok(()))
} else {
self.random_stack
.push(ClauseState::Random(self.rng.gen(1..=rand_max)));
Break(Ok(()))
}
}
Token::EndRandom => {
if let Some(&ClauseState::Random(_)) = self.random_stack.last() {
self.random_stack.pop();
Break(Ok(()))
} else {
Break(Err(ParseError::SyntaxError(
"#ENDRANDOM command must come after #RANDOM block".into(),
)))
}
}
_ => {
if let Some(ClauseState::Random(_) | ClauseState::If(false)) =
self.random_stack.last()
{
Break(Ok(()))
} else {
Continue(())
}
}
}
}
}
|
new
|
matcher.py
|
#
# Copyright (C) 2013-2015 eNovance SAS <[email protected]>
#
# Author: Frederic Lepied <[email protected]>
#
# 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.
'''Functions to match according to a requirement specification.'''
import ipaddress
import logging
import re
import sys
LOG = logging.getLogger('hardware.matcher')
def _adder(array, index, value):
'Auxiliary function to add a value to an array.'
array[index] = value
def
|
(array, index, value):
'Auxiliary function to append a value to an array.'
try:
array[index].append(value)
except KeyError:
array[index] = [value, ]
def _range(elt, minval, maxval):
'Helper for match_spec.'
return float(elt) >= float(minval) and float(elt) <= float(maxval)
def _gt(left, right):
'Helper for match_spec.'
return float(left) > float(right)
def _ge(left, right):
'Helper for match_spec.'
return float(left) >= float(right)
def _lt(left, right):
'Helper for match_spec.'
return float(left) < float(right)
def _le(left, right):
'Helper for match_spec.'
return float(left) <= float(right)
def _not(_, right):
'Helper for match_spec.'
return not right
def _and(_, left, right):
'Helper for match_spec.'
return left and right
def _or(_, left, right):
'Helper for match_spec.'
return left or right
def _network(left, right):
'Helper for match_spec.'
return ipaddress.IPv4Address(left) in ipaddress.IPv4Network(right)
def _regexp(left, right):
'Helper for match_spec.'
return re.search(right, left) is not None
def _in(elt, *lst):
'Helper for match_spec.'
return elt in lst
_FUNC_REGEXP = re.compile(r'^([^(]+)' # function name
r'\(\s*([^,]+)' # first argument
r'(?:\s*,\s*(.+))?' # remaining optional arguments
r'\)$') # last parenthesis
def _call_func(func, implicit, res):
'Helper function for extract_result and match_spec'
args = [implicit, res.group(2)]
# split the optional arguments if we have some
if res.group(3):
args = args + re.split(r'\s*,\s*', res.group(3))
# remove strings delimiters
args = [x.strip('\'"') for x in args]
# call function
args = [_extract_result(implicit, x) for x in args]
return func(*args)
def _extract_result(implicit, expr):
'Helper function for match_spec'
res = _FUNC_REGEXP.search(expr)
if res:
func_name = '_' + res.group(1)
if func_name in globals():
return _call_func(globals()[func_name], implicit, res)
else:
return expr
else:
return expr
def match_spec(spec, lines, arr, adder=_adder):
'Match a line according to a spec and store variables in <var>.'
# match a line without variable
for idx in range(len(lines)):
if lines[idx] == spec:
res = lines[idx]
del lines[idx]
return res
# match a line with a variable, a function or both
for lidx in range(len(lines)):
line = lines[lidx]
varidx = []
for idx in range(4):
# try to split the variable and function parts if we have both
if spec[idx][0] == '$':
parts = spec[idx].split('=')
if len(parts) == 2:
var, func = parts
matched = False
else:
var = func = spec[idx]
else:
var = func = spec[idx]
# Match a function
if func[-1] == ')':
res = _FUNC_REGEXP.search(func)
if res:
func_name = '_' + res.group(1)
if func_name in globals():
if not _call_func(globals()[func_name],
line[idx], res):
if var == func:
break
else:
if var == func:
continue
matched = True
else:
if var == func:
break
# Match a variable
if ((var == func) or (var != func and matched)) and var[0] == '$':
if adder == _adder and var[1:] in arr:
if arr[var[1:]] != line[idx]:
break
varidx.append((idx, var[1:]))
# Match the full string
elif line[idx] != spec[idx]:
break
else:
for i, var in varidx:
adder(arr, var, line[i])
res = lines[lidx]
del lines[lidx]
return res
return False
def match_all(lines, specs, arr, arr2, debug=False, level=0):
'''Match all lines according to a spec.
Store variables starting with a $ in <arr>. Variables starting with
2 $ like $$vda are stored in arr and arr2.
'''
# Work on a copy of lines to avoid changing the real lines because
# match_spec removes the matched line to not match it again on next
# calls.
lines = list(lines)
specs = list(specs)
copy_arr = dict(arr)
points = []
# Prevent infinit loops
if level == 50:
return False
# Match lines using specs
while len(specs) > 0:
copy_specs = list(specs)
spec = specs.pop(0)
line = match_spec(spec, lines, arr)
if debug:
sys.stderr.write('match_spec: %s %s\n' % (line, spec))
# No match
if not line:
# Backtrack on the backtracking points
while len(points) > 0:
lines, specs, new_arr = points.pop()
if debug:
sys.stderr.write('retrying with: %s\n' %
(new_arr,))
if match_all(lines, specs, new_arr, arr2, debug, level + 1):
# Copy arr back
for k in new_arr:
arr[k] = new_arr[k]
if debug:
sys.stderr.write('success: %d\n' % level)
return True
if level == 0 and debug:
sys.stderr.write('spec: %s not matched\n' % str(spec))
return False
else:
# Store backtraking points when we find a new variable
if arr != copy_arr:
copy_lines = list(lines)
# Put the matching line at the end of the lines
copy_lines.append(line)
points.append((copy_lines, copy_specs, copy_arr))
copy_arr = dict(arr)
if debug:
sys.stderr.write('new var: %s %s\n' % (arr, line))
# Manage $$ variables
for key in arr:
if key[0] == '$':
nkey = key[1:]
arr[nkey] = arr[key]
arr2[nkey] = arr[key]
del arr[key]
return True
def match_multiple(lines, spec, arr):
'Use spec to find all the matching lines and gather variables.'
ret = False
lines = list(lines)
while match_spec(spec, lines, arr, adder=_appender):
ret = True
return ret
def generate_filename_and_macs(items):
'''Generate a file name for a hardware using DMI information.
(product name and version) then if the DMI serial number is
available we use it unless we lookup the first mac address.
As a result, we do have a filename like :
<dmi_product_name>-<dmi_product_version>-{dmi_serial_num|mac_address}
'''
# Duplicate items as it will be modified by match_* functions
hw_items = list(items)
sysvars = {}
sysvars['sysname'] = ''
if match_spec(('system', 'product', 'vendor', '$sysprodvendor'),
hw_items, sysvars):
sysvars['sysname'] += (re.sub(r'\W+', '', sysvars['sysprodvendor']) +
'-')
if match_spec(('system', 'product', 'name', '$sysprodname'),
hw_items, sysvars):
sysvars['sysname'] = re.sub(r'\W+', '', sysvars['sysprodname']) + '-'
# Let's use any existing DMI serial number or take the first mac address
if match_spec(('system', 'product', 'serial', '$sysserial'),
hw_items, sysvars):
sysvars['sysname'] += re.sub(r'\W+', '', sysvars['sysserial']) + '-'
# we always need to have the mac addresses for pxemngr
if match_multiple(hw_items,
('network', '$eth', 'serial', '$serial'),
sysvars):
sysvars['sysname'] += sysvars['serial'][0].replace(':', '-')
else:
LOG.warning('unable to detect network macs')
return sysvars
# matcher.py ends here
|
_appender
|
config.pb.go
|
package blackhole
import (
fmt "fmt"
math "math"
proto "github.com/golang/protobuf/proto"
serial "v2ray.com/core/common/serial"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
type NoneResponse struct {
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *NoneResponse) Reset() { *m = NoneResponse{} }
func (m *NoneResponse) String() string { return proto.CompactTextString(m) }
func (*NoneResponse) ProtoMessage() {}
func (*NoneResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_8c8b37c8ae1bdfea, []int{0}
}
func (m *NoneResponse) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_NoneResponse.Unmarshal(m, b)
}
func (m *NoneResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_NoneResponse.Marshal(b, m, deterministic)
}
func (m *NoneResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_NoneResponse.Merge(m, src)
}
func (m *NoneResponse) XXX_Size() int {
return xxx_messageInfo_NoneResponse.Size(m)
}
func (m *NoneResponse) XXX_DiscardUnknown() {
xxx_messageInfo_NoneResponse.DiscardUnknown(m)
}
var xxx_messageInfo_NoneResponse proto.InternalMessageInfo
type HTTPResponse struct {
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *HTTPResponse) Reset() { *m = HTTPResponse{} }
func (m *HTTPResponse) String() string { return proto.CompactTextString(m) }
func (*HTTPResponse) ProtoMessage() {}
func (*HTTPResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_8c8b37c8ae1bdfea, []int{1}
}
func (m *HTTPResponse) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_HTTPResponse.Unmarshal(m, b)
}
func (m *HTTPResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_HTTPResponse.Marshal(b, m, deterministic)
}
func (m *HTTPResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_HTTPResponse.Merge(m, src)
}
func (m *HTTPResponse) XXX_Size() int {
return xxx_messageInfo_HTTPResponse.Size(m)
}
func (m *HTTPResponse) XXX_DiscardUnknown() {
xxx_messageInfo_HTTPResponse.DiscardUnknown(m)
}
var xxx_messageInfo_HTTPResponse proto.InternalMessageInfo
type Config struct {
Response *serial.TypedMessage `protobuf:"bytes,1,opt,name=response,proto3" json:"response,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *Config) Reset() { *m = Config{} }
func (m *Config) String() string { return proto.CompactTextString(m) }
func (*Config) ProtoMessage() {}
func (*Config) Descriptor() ([]byte, []int) {
return fileDescriptor_8c8b37c8ae1bdfea, []int{2}
}
func (m *Config) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_Config.Unmarshal(m, b)
}
func (m *Config) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_Config.Marshal(b, m, deterministic)
}
func (m *Config) XXX_Merge(src proto.Message) {
xxx_messageInfo_Config.Merge(m, src)
}
func (m *Config) XXX_Size() int {
return xxx_messageInfo_Config.Size(m)
}
func (m *Config) XXX_DiscardUnknown() {
xxx_messageInfo_Config.DiscardUnknown(m)
}
var xxx_messageInfo_Config proto.InternalMessageInfo
func (m *Config) GetResponse() *serial.TypedMessage {
if m != nil {
return m.Response
}
return nil
}
func init()
|
func init() {
proto.RegisterFile("v2ray.com/core/proxy/blackhole/config.proto", fileDescriptor_8c8b37c8ae1bdfea)
}
var fileDescriptor_8c8b37c8ae1bdfea = []byte{
// 217 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xd2, 0x2e, 0x33, 0x2a, 0x4a,
0xac, 0xd4, 0x4b, 0xce, 0xcf, 0xd5, 0x4f, 0xce, 0x2f, 0x4a, 0xd5, 0x2f, 0x28, 0xca, 0xaf, 0xa8,
0xd4, 0x4f, 0xca, 0x49, 0x4c, 0xce, 0xce, 0xc8, 0xcf, 0x49, 0xd5, 0x4f, 0xce, 0xcf, 0x4b, 0xcb,
0x4c, 0xd7, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x92, 0x82, 0x29, 0x2e, 0x4a, 0xd5, 0x03, 0x2b,
0xd4, 0x83, 0x2b, 0x94, 0x32, 0x40, 0x33, 0x28, 0x39, 0x3f, 0x37, 0x37, 0x3f, 0x4f, 0xbf, 0x38,
0xb5, 0x28, 0x33, 0x31, 0x47, 0xbf, 0xa4, 0xb2, 0x20, 0x35, 0x25, 0x3e, 0x37, 0xb5, 0xb8, 0x38,
0x31, 0x3d, 0x15, 0x62, 0x9a, 0x12, 0x1f, 0x17, 0x8f, 0x5f, 0x7e, 0x5e, 0x6a, 0x50, 0x6a, 0x71,
0x41, 0x7e, 0x5e, 0x71, 0x2a, 0x88, 0xef, 0x11, 0x12, 0x12, 0x00, 0xe7, 0xfb, 0x70, 0xb1, 0x39,
0x83, 0x6d, 0x17, 0x72, 0xe2, 0xe2, 0x28, 0x82, 0x8a, 0x4a, 0x30, 0x2a, 0x30, 0x6a, 0x70, 0x1b,
0xa9, 0xe9, 0x21, 0x39, 0x05, 0x62, 0x95, 0x1e, 0xc4, 0x2a, 0xbd, 0x10, 0x90, 0x55, 0xbe, 0x10,
0x9b, 0x82, 0xe0, 0xfa, 0x9c, 0xbc, 0xb8, 0xe4, 0x92, 0xf3, 0x73, 0xf5, 0x70, 0xfb, 0x20, 0x80,
0x31, 0x8a, 0x13, 0xce, 0x59, 0xc5, 0x24, 0x15, 0x66, 0x14, 0x94, 0x58, 0xa9, 0xe7, 0x0c, 0x52,
0x19, 0x00, 0x56, 0xe9, 0x04, 0x93, 0x4c, 0x62, 0x03, 0x7b, 0xc0, 0x18, 0x10, 0x00, 0x00, 0xff,
0xff, 0xb6, 0x3c, 0xef, 0x4f, 0x3d, 0x01, 0x00, 0x00,
}
|
{
proto.RegisterType((*NoneResponse)(nil), "v2ray.core.proxy.blackhole.NoneResponse")
proto.RegisterType((*HTTPResponse)(nil), "v2ray.core.proxy.blackhole.HTTPResponse")
proto.RegisterType((*Config)(nil), "v2ray.core.proxy.blackhole.Config")
}
|
route_handlers.go
|
package tokens
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/rancher/norman/httperror"
"github.com/rancher/norman/types"
"github.com/rancher/norman/types/convert"
"github.com/rancher/types/apis/management.cattle.io/v3"
"github.com/rancher/rancher/pkg/auth/model"
"github.com/rancher/rancher/pkg/auth/util"
)
const (
CookieName = "R_SESS"
AuthHeaderName = "Authorization"
AuthValuePrefix = "Bearer"
BasicAuthPrefix = "Basic"
)
func TokenActionHandler(actionName string, action *types.Action, request *types.APIContext) error {
logrus.Debugf("TokenActionHandler called for action %v", actionName)
if actionName == "login" {
return tokenServer.login(actionName, action, request)
} else if actionName == "logout" {
return tokenServer.logout(actionName, action, request)
}
return nil
}
func TokenCreateHandler(request *types.APIContext) error {
logrus.Debugf("TokenCreateHandler called")
return tokenServer.deriveToken(request)
}
func TokenListHandler(request *types.APIContext) error {
logrus.Debugf("TokenListHandler called")
if request.ID != "" {
return tokenServer.getToken(request)
}
return tokenServer.listTokens(request)
}
func TokenDeleteHandler(request *types.APIContext) error {
logrus.Debugf("TokenDeleteHandler called")
return tokenServer.removeToken(request)
}
//login is a handler for route /tokens?action=login and returns the jwt token after authenticating the user
func (s *tokenAPIServer) login(actionName string, action *types.Action, request *types.APIContext) error {
r := request.Request
w := request.Response
bytes, err := ioutil.ReadAll(r.Body)
if err != nil {
logrus.Errorf("login failed with error: %v", err)
return httperror.NewAPIError(httperror.InvalidBodyContent, fmt.Sprintf("Error reading input json data: %v", err))
}
jsonInput := v3.LoginInput{}
err = json.Unmarshal(bytes, &jsonInput)
if err != nil {
logrus.Errorf("unmarshal failed with error: %v", err)
return httperror.NewAPIError(httperror.InvalidBodyContent, fmt.Sprintf("Error unmarshaling input json data: %v", err))
}
var token v3.Token
var status int
token, status, err = s.createLoginToken(jsonInput)
if err != nil {
logrus.Errorf("Login failed with error: %v", err)
if status == 0 {
status = http.StatusInternalServerError
}
return httperror.NewAPIErrorLong(status, util.GetHTTPErrorCode(status), fmt.Sprintf("%v", err))
}
if jsonInput.ResponseType == "cookie" {
tokenCookie := &http.Cookie{
Name: CookieName,
Value: token.ObjectMeta.Name + ":" + token.Token,
Secure: true,
Path: "/",
HttpOnly: true,
}
http.SetCookie(w, tokenCookie)
} else {
tokenData, err := convertTokenResource(request, token)
if err != nil {
return err
}
tokenData["token"] = token.ObjectMeta.Name + ":" + token.Token
request.WriteResponse(http.StatusCreated, tokenData)
}
return nil
}
func (s *tokenAPIServer) deriveToken(request *types.APIContext) error {
r := request.Request
tokenAuthValue := GetTokenAuthFromRequest(r)
if tokenAuthValue == "" {
// no cookie or auth header, cannot authenticate
return httperror.NewAPIErrorLong(http.StatusUnauthorized, util.GetHTTPErrorCode(http.StatusUnauthorized), "No valid token cookie or auth header")
}
bytes, err := ioutil.ReadAll(r.Body)
if err != nil {
logrus.Errorf("GetToken failed with error: %v", err)
}
jsonInput := v3.Token{}
err = json.Unmarshal(bytes, &jsonInput)
if err != nil {
logrus.Errorf("unmarshal failed with error: %v", err)
}
var token v3.Token
var status int
// create derived token
token, status, err = s.createDerivedToken(jsonInput, tokenAuthValue)
if err != nil {
logrus.Errorf("deriveToken failed with error: %v", err)
if status == 0 {
status = http.StatusInternalServerError
}
return httperror.NewAPIErrorLong(status, util.GetHTTPErrorCode(status), fmt.Sprintf("%v", err))
}
tokenData, err := convertTokenResource(request, token)
if err != nil {
return err
}
tokenData["token"] = token.ObjectMeta.Name + ":" + token.Token
request.WriteResponse(http.StatusCreated, tokenData)
return nil
}
func (s *tokenAPIServer) listTokens(request *types.APIContext) error {
r := request.Request
// TODO switch to X-API-UserId header
tokenAuthValue := GetTokenAuthFromRequest(r)
if tokenAuthValue == "" {
// no cookie or auth header, cannot authenticate
return httperror.NewAPIErrorLong(http.StatusUnauthorized, util.GetHTTPErrorCode(http.StatusUnauthorized), "No valid token cookie or auth header")
}
//getToken
tokens, status, err := s.getTokens(tokenAuthValue)
if err != nil {
logrus.Errorf("GetToken failed with error: %v", err)
if status == 0 {
status = http.StatusInternalServerError
}
return httperror.NewAPIErrorLong(status, util.GetHTTPErrorCode(status), fmt.Sprintf("%v", err))
}
tokensFromStore := make([]map[string]interface{}, len(tokens))
for _, token := range tokens {
tokenData, err := convertTokenResource(request, token)
if err != nil {
return err
}
tokensFromStore = append(tokensFromStore, tokenData)
}
request.WriteResponse(http.StatusOK, tokensFromStore)
return nil
}
func (s *tokenAPIServer) logout(actionName string, action *types.Action, request *types.APIContext) error {
r := request.Request
w := request.Response
tokenAuthValue := GetTokenAuthFromRequest(r)
if tokenAuthValue == "" {
// no cookie or auth header, cannot authenticate
return httperror.NewAPIErrorLong(http.StatusUnauthorized, util.GetHTTPErrorCode(http.StatusUnauthorized), "No valid token cookie or auth header")
}
isSecure := false
if r.URL.Scheme == "https" {
isSecure = true
}
tokenCookie := &http.Cookie{
Name: CookieName,
Value: "",
Secure: isSecure,
Path: "/",
HttpOnly: true,
MaxAge: -1,
Expires: time.Date(1982, time.February, 10, 23, 0, 0, 0, time.UTC),
}
http.SetCookie(w, tokenCookie)
//getToken
status, err := s.deleteToken(tokenAuthValue)
if err != nil {
logrus.Errorf("DeleteToken failed with error: %v", err)
if status == 0 {
status = http.StatusInternalServerError
}
return httperror.NewAPIErrorLong(status, util.GetHTTPErrorCode(status), fmt.Sprintf("%v", err))
}
return nil
}
func (s *tokenAPIServer) getToken(request *types.APIContext) error {
// TODO switch to X-API-UserId header
r := request.Request
tokenAuthValue := GetTokenAuthFromRequest(r)
if tokenAuthValue == "" {
// no cookie or auth header, cannot authenticate
return httperror.NewAPIErrorLong(http.StatusUnauthorized, util.GetHTTPErrorCode(http.StatusUnauthorized), "No valid token cookie or auth header")
}
tokenID := request.ID
//getToken
token, status, err := s.getTokenByID(tokenAuthValue, tokenID)
if err != nil {
logrus.Errorf("GetToken failed with error: %v", err)
if status == 0 {
status = http.StatusInternalServerError
} else if status == 410 {
status = http.StatusNotFound
}
return httperror.NewAPIErrorLong(status, util.GetHTTPErrorCode(status), fmt.Sprintf("%v", err))
}
tokenData, err := convertTokenResource(request, token)
if err != nil {
return err
}
request.WriteResponse(http.StatusOK, tokenData)
return nil
}
func (s *tokenAPIServer) removeToken(request *types.APIContext) error {
// TODO switch to X-API-UserId header
r := request.Request
tokenAuthValue := GetTokenAuthFromRequest(r)
if tokenAuthValue == "" {
// no cookie or auth header, cannot authenticate
return httperror.NewAPIErrorLong(http.StatusUnauthorized, util.GetHTTPErrorCode(http.StatusUnauthorized), "No valid token cookie or auth header")
}
tokenID := request.ID
//getToken
_, status, err := s.getTokenByID(tokenAuthValue, tokenID)
if err != nil {
if status != 410 {
logrus.Errorf("DeleteToken Failed to fetch the token to delete with error: %v", err)
if status == 0 {
status = http.StatusInternalServerError
}
return httperror.NewAPIErrorLong(status, util.GetHTTPErrorCode(status), fmt.Sprintf("%v", err))
}
}
tokenData, err := deleteTokenUsingStore(request, tokenID)
if err != nil {
return err
}
request.WriteResponse(http.StatusOK, tokenData)
return nil
}
func getTokenFromStore(request *types.APIContext, tokenID string) (map[string]interface{}, error) {
store := request.Schema.Store
if store == nil {
return nil, errors.New("no token store available")
}
tokenData, err := store.ByID(request, request.Schema, tokenID)
if err != nil {
return nil, err
}
return tokenData, nil
}
func convertTokenResource(request *types.APIContext, token v3.Token) (map[string]interface{}, error) {
tokenData, err := convert.EncodeToMap(token)
if err != nil {
return nil, err
}
mapper := request.Schema.Mapper
if mapper == nil {
return nil, errors.New("no schema mapper available")
}
mapper.FromInternal(tokenData)
return tokenData, nil
}
func
|
(request *types.APIContext, tokenID string) (map[string]interface{}, error) {
store := request.Schema.Store
if store == nil {
return nil, errors.New("no token store available")
}
tokenData, err := store.Delete(request, request.Schema, tokenID)
if err != nil {
return nil, err
}
return tokenData, nil
}
func (s *tokenAPIServer) authConfigs(w http.ResponseWriter, r *http.Request) {
var authConfigs []model.AuthConfig
authConfigs = append(authConfigs, model.DefaultGithubConfig())
authConfigs = append(authConfigs, model.DefaultLocalConfig())
w.Header().Set("Content-Type", "application/json")
enc := json.NewEncoder(w)
enc.SetEscapeHTML(false)
enc.Encode(authConfigs)
}
|
deleteTokenUsingStore
|
batch_handling.py
|
"""
Functions to help with calculating batch properties for experiments objects.
"""
from __future__ import annotations
import logging
from dials.array_family import flex
logger = logging.getLogger("dials")
class batch_manager:
def __init__(self, batches, batch_params):
# batch params is a list of dicts with "id" and "range" - used to be
# a 'scope extract' object
self.batch_params = sorted(batch_params, key=lambda b: b["range"][0])
self.batches = batches
self.reduced_batches, self._batch_increments = self._reduce()
def _reduce(self):
reduced_batches = flex.int(self.batches)
batch_increments = []
incr = 0
for batch in self.batch_params:
sel = (reduced_batches >= batch["range"][0]) & (
reduced_batches <= batch["range"][1]
)
reduced_batches.set_selected(
sel, reduced_batches.select(sel) - (batch["range"][0] - incr) + 1
)
batch_increments.append(incr)
incr += batch["range"][1] - batch["range"][0] + 1
assert len(set(reduced_batches)) == len(reduced_batches)
return list(reduced_batches), batch_increments
def batch_plot_shapes_and_annotations(self):
light_grey = "#d3d3d3"
grey = "#808080"
shapes = []
annotations = []
batches = flex.int(self.batches)
text = flex.std_string(batches.size())
for i, batch in enumerate(self.batch_params):
fillcolor = [light_grey, grey][i % 2] # alternate colours
shapes.append(
{
"type": "rect",
# x-reference is assigned to the x-values
"xref": "x",
# y-reference is assigned to the plot paper [0,1]
"yref": "paper",
"x0": self._batch_increments[i],
"y0": 0,
"x1": self._batch_increments[i]
+ (batch["range"][1] - batch["range"][0]),
"y1": 1,
"fillcolor": fillcolor,
"opacity": 0.2,
"line": {"width": 0},
}
)
annotations.append(
{
# x-reference is assigned to the x-values
"xref": "x",
# y-reference is assigned to the plot paper [0,1]
"yref": "paper",
"x": self._batch_increments[i]
+ (batch["range"][1] - batch["range"][0]) / 2,
"y": 1,
"text": f"{batch['id']}",
"showarrow": False,
"yshift": 20,
# 'arrowhead': 7,
# 'ax': 0,
# 'ay': -40
}
)
sel = (batches >= batch["range"][0]) & (batches <= batch["range"][1])
text.set_selected(
sel,
flex.std_string(
[
f"{batch['id']}: {j - batch['range'][0] + 1}"
for j in batches.select(sel)
]
),
)
return shapes, annotations, list(text)
def assign_batches_to_reflections(reflections, batch_offsets):
"""Assign a 'batch' column to the reflection table"""
for batch_offset, refl in zip(batch_offsets, reflections):
xdet, ydet, zdet = [flex.double(x) for x in refl["xyzobs.px.value"].parts()]
# compute BATCH values - floor() to get (fortran) image captured within
# +1 because FORTRAN counting; zdet+1=image_index
# +off because image_index+o=batch
refl["batch"] = (flex.floor(zdet).iround() + 1) + batch_offset
return reflections
def get_batch_ranges(experiments, batch_offsets):
"""Get batch ranges for a list of experiments and offsets"""
batch_ranges = []
assert len(experiments) == len(batch_offsets)
image_ranges = get_image_ranges(experiments)
for batch_offset, image_range in zip(batch_offsets, image_ranges):
batch_ranges.append(
(image_range[0] + batch_offset, image_range[1] + batch_offset)
)
return batch_ranges
def get_image_ranges(experiments):
"""Get image ranges for a list of experiments (including scanless exp.)"""
# Note, if set to 1,1,for scanless experiments then first batch offset in
# _calculate_batch_offsets is zero below, bad!
return [e.scan.get_image_range() if e.scan else (0, 0) for e in experiments]
def calculate_batch_offsets(experiment_list):
"""Take a list of experiments and resolve and return the batch offsets.
First adds an image_range property as not all experiments have scans."""
image_ranges = get_image_ranges(experiment_list)
offsets = _calculate_batch_offsets(image_ranges)
return offsets
def set_batch_offsets(experiment_list, batch_offsets):
"""Set batch offsets in scan objects. Don't need to set anything for
scanless experiments, as these are not used with the batch system."""
for exp, offset in zip(experiment_list, batch_offsets):
if exp.scan:
exp.scan.set_batch_offset(offset)
def _calculate_batch_offsets(image_ranges):
|
def _next_epoch(val):
"""Find the next number above the existing value that ends in 1, that is
not consecutive with the current value."""
if val % 100 == 99:
return val + 2
elif val % 100 == 0:
return val + 101
else:
rem = val % 100
return val - rem + 101
|
"""Take a list of (modified) experiments and resolve and return the batch
offsets.
This is the number added to the image number to give the
batch number, such that:
- Each experiment has a unique, nonoverlapping, nonconsecutive range
- None are zero
- Image number ranges are kept if at all possible
"""
experiments_to_shift = []
existing_ranges = set()
maximum_batch_number = 0
batch_offsets = [0] * len(image_ranges)
# Handle zeroth shifts and kept ranges
for i, image_range in enumerate(image_ranges):
ilow, ihigh = image_range
# Check assumptions
assert ilow <= ihigh, "Inverted image order!?"
assert ilow >= 0, "Negative image indices are not expected"
# Don't emit zero: Causes problems with C/fortran number conversion
if ilow == 0:
ilow, ihigh = ilow + 1, ihigh + 1
# If we overlap with anything, then process later
if any(ilow < high + 1 and ihigh >= low - 1 for low, high in existing_ranges):
experiments_to_shift.append((i, image_range))
else:
batch_offsets[i] = ilow - image_range[0]
existing_ranges.add((ilow, ihigh))
maximum_batch_number = max(maximum_batch_number, ihigh)
# Now handle all the experiments that overlapped by pushing them higher
for i, image_range in experiments_to_shift:
start_number = _next_epoch(maximum_batch_number)
range_width = image_range[1] - image_range[0] + 1
end_number = start_number + range_width - 1
batch_offsets[i] = start_number - image_range[0]
maximum_batch_number = end_number
return batch_offsets
|
index.js
|
import React from 'react'
import { FinalTextPassword, FINAL_TEXT_PASSWORD } from './FinalTextPassword'
import {
signUpPasswordValidation,
passwordPopoverMessages,
signInPasswordValidation,
stopUndefined,
} from 'utils'
// components
import { Exports } from 'component_c_Molecules'
const { LabelForm } = stopUndefined(Exports)
const FinalTextPasswordPropedSignUp = props => {
return (
<FinalTextPassword
validation={signUpPasswordValidation}
popoverMessages={passwordPopoverMessages}
{...props}
/>
)
}
const FinalTextPasswordPropedSignIn = props => {
return (
<FinalTextPassword
validation={signInPasswordValidation}
hideSuccess
{...props}
/>
)
}
const FinalTextPasswordPropedAccount = props => {
return (
|
validation={signUpPasswordValidation}
hideSuccess
onlyShowErrorAfterSubmit
{...props}
/>
</LabelForm>
)
}
export {
FinalTextPasswordPropedSignUp,
FinalTextPasswordPropedSignIn,
FinalTextPasswordPropedAccount,
FINAL_TEXT_PASSWORD,
}
|
<LabelForm label='Email' htmlFor={FINAL_TEXT_PASSWORD}>
<FinalTextPassword
|
prefix.rs
|
use super::{Int, ParseError};
use std::{fmt, str::FromStr};
#[rustfmt::skip]
#[derive(Eq, Ord, Copy, Clone, Debug, PartialEq, PartialOrd)]
pub enum UnitPrefix {
Kilo, Kibi,
Mega, Mebi,
Giga, Gibi,
Tera, Tebi,
Peta, Pebi,
Exa , Exbi,
#[cfg(feature = "u128")] Zetta,
#[cfg(feature = "u128")] Zebi ,
#[cfg(feature = "u128")] Yotta,
#[cfg(feature = "u128")] Yobi ,
}
use UnitPrefix::*;
impl UnitPrefix {
#[rustfmt::skip]
pub const DECIMAL: [UnitPrefix; {
#[cfg(feature = "u128")] { 8 }
#[cfg(not(feature = "u128"))] { 6 }
}] = [
Kilo, Mega, Giga, Tera, Peta, Exa,
#[cfg(feature = "u128")] Zetta,
#[cfg(feature = "u128")] Yotta,
];
#[rustfmt::skip]
pub const BINARY: [UnitPrefix; {
#[cfg(feature = "u128")] { 8 }
#[cfg(not(feature = "u128"))] { 6 }
}] = [
Kibi, Mebi, Gibi, Tebi, Pebi, Exbi,
#[cfg(feature = "u128")] Zebi,
#[cfg(feature = "u128")] Yobi,
];
#[rustfmt::skip]
pub const ALL: [UnitPrefix; {
#[cfg(feature = "u128")] { 16 }
#[cfg(not(feature = "u128"))] { 12 }
}] = [
Kilo, Kibi, Mega, Mebi, Giga, Gibi,
Tera, Tebi, Peta, Pebi, Exa, Exbi,
#[cfg(feature = "u128")] Zetta,
#[cfg(feature = "u128")] Zebi,
#[cfg(feature = "u128")] Yotta,
#[cfg(feature = "u128")] Yobi,
];
pub const MIN: UnitPrefix = Kilo;
#[rustfmt::skip]
pub const MAX: UnitPrefix = {
#[cfg(feature = "u128")] { Yobi }
#[cfg(not(feature = "u128"))] { Exbi }
};
pub const fn is_decimal(&self) -> bool {
((*self as u8) & 1) == 0
}
pub const fn is_binary(&self) -> bool {
((*self as u8) & 1) == 1
}
pub const fn index(&self) -> usize {
(*self as usize) / 2
}
pub const fn decimal(&self) -> Self {
if self.is_binary() {
return Self::DECIMAL[self.index()];
}
*self
}
pub const fn binary(&self) -> Self {
if self.is_decimal() {
return Self::BINARY[self.index()];
}
*self
}
#[rustfmt::skip]
#[inline(always)]
pub const fn effective_value(&self) -> Int {
match self {
Kibi => 1 << 10, Kilo => 1000,
Mebi => 1 << 20, Mega => 1000000,
Gibi => 1 << 30, Giga => 1000000000,
Tebi => 1 << 40, Tera => 1000000000000,
Pebi => 1 << 50, Peta => 1000000000000000,
Exbi => 1 << 60, Exa => 1000000000000000000,
#[cfg(feature = "u128")] Zebi => 1 << 70,
#[cfg(feature = "u128")] Yobi => 1 << 80,
#[cfg(feature = "u128")] Zetta => 1000000000000000000000,
#[cfg(feature = "u128")] Yotta => 1000000000000000000000000,
}
}
#[rustfmt::skip]
pub const fn symbol(&self) -> &'static str {
match self {
Kilo => "K", Kibi => "Ki",
Mega => "M", Mebi => "Mi",
Giga => "G", Gibi => "Gi",
Tera => "T", Tebi => "Ti",
Peta => "P", Pebi => "Pi",
Exa => "E", Exbi => "Ei",
#[cfg(feature = "u128")] Zetta => "Z" ,
#[cfg(feature = "u128")] Yotta => "Y" ,
#[cfg(feature = "u128")] Zebi => "Zi",
#[cfg(feature = "u128")] Yobi => "Yi",
}
}
#[rustfmt::skip]
pub const fn symbol_long(&self) -> &'static str {
match self {
Kilo => "Kilo", Kibi => "Kibi",
Mega => "Mega", Mebi => "Mebi",
Giga => "Giga", Gibi => "Gibi",
Tera => "Tera", Tebi => "Tebi",
Peta => "Peta", Pebi => "Pebi",
Exa => "Exa" , Exbi => "Exbi",
#[cfg(feature = "u128")] Zetta => "Zetta",
#[cfg(feature = "u128")] Yotta => "Yotta",
#[cfg(feature = "u128")] Zebi => "Zebi" ,
#[cfg(feature = "u128")] Yobi => "Yobi" ,
}
}
#[rustfmt::skip]
pub const fn symbol_initials(&self) -> &'static str {
match self {
Kilo | Kibi => "K",
Mega | Mebi => "M",
Giga | Gibi => "G",
Tera | Tebi => "T",
Peta | Pebi => "P",
Exa | Exbi => "E",
#[cfg(feature = "u128")] Zetta | Zebi => "Z",
#[cfg(feature = "u128")] Yotta | Yobi => "Y",
}
}
}
impl fmt::Display for UnitPrefix {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let unit = if f.sign_minus() {
self.symbol_initials()
} else if f.sign_plus() {
self.symbol_long()
} else {
self.symbol()
};
f.write_str(unit)
}
}
impl FromStr for UnitPrefix {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
#[rustfmt::skip]
let unit = match &{
#[cfg(not(feature = "case-insensitive"))] { s }
#[cfg(feature = "case-insensitive")] {
if !s.is_empty() {
let (first, rest) = s.split_at(1);
format!("{}{}", first.to_uppercase(), rest.to_lowercase())
} else {
s.to_string()
}
}
}[..] {
"" => return Err(ParseError::EmptyInput),
// https://web.archive.org/web/20150324153922/https://pacoup.com/2009/05/26/kb-kb-kib-whats-up-with-that/
"k" | "K" => Kilo, "Ki" => Kibi,
"M" => Mega, "Mi" => Mebi,
"G" => Giga, "Gi" => Gibi,
"T" => Tera, "Ti" => Tebi,
"P" => Peta, "Pi" => Pebi,
"E" => Exa , "Ei" => Exbi,
#[cfg(feature = "u128")] "Z" => Zetta,
#[cfg(feature = "u128")] "Y" => Yotta,
#[cfg(feature = "u128")] "Zi" => Zebi ,
#[cfg(feature = "u128")] "Yi" => Yobi ,
#[cfg(not(feature = "case-insensitive"))]
s if (
matches!(s,
"m" | "g" | "t" | "p" | "e" | "ki" | "mi" | "gi" | "ti" | "pi" | "ei"
) || (cfg!(feature = "u128") && matches!(s, "z" | "y" | "zi" | "yi"))
) => return Err(ParseError::InvalidPrefixCaseFormat),
s => match s.to_lowercase().as_str() {
"kilo" => Kilo, "kibi" => Kibi,
"mega" => Mega, "mebi" => Mebi,
"giga" => Giga, "gibi" => Gibi,
"tera" => Tera, "tebi" => Tebi,
"peta" => Peta, "pebi" => Pebi,
"exa" => Exa , "exbi" => Exbi,
#[cfg(feature = "u128")] "zetta" => Zetta,
#[cfg(feature = "u128")] "yotta" => Yotta,
#[cfg(feature = "u128")] "zebi" => Zebi ,
#[cfg(feature = "u128")] "yobi" => Yobi ,
_ => return Err(ParseError::InvalidPrefix),
}
};
Ok(unit)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn decimal() {
#[rustfmt::skip]
let lhs = [
Kilo, Mega, Giga, Tera, Peta, Exa,
#[cfg(feature = "u128")] Zetta,
#[cfg(feature = "u128")] Yotta
];
for (index, unit) in lhs.iter().enumerate() {
assert_eq!(unit, &UnitPrefix::DECIMAL[index]);
assert_ne!(unit, &UnitPrefix::BINARY[index]);
}
}
#[test]
fn binary()
|
#[test]
#[rustfmt::skip]
fn cmp() {
assert!(Kilo < Kibi && Kibi > Kilo);
assert!(Kibi < Mega && Mega > Kibi);
assert!(Mega < Mebi && Mebi > Mega);
assert!(Mebi < Giga && Giga > Mebi);
assert!(Giga < Gibi && Gibi > Giga);
assert!(Gibi < Tera && Tera > Gibi);
assert!(Tera < Tebi && Tebi > Tera);
assert!(Tebi < Peta && Peta > Tebi);
assert!(Peta < Pebi && Pebi > Peta);
assert!(Pebi < Exa && Exa > Pebi);
assert!(Exa < Exbi && Exbi > Exa );
#[cfg(feature = "u128")] assert!(Exbi < Zetta && Zetta > Exbi );
#[cfg(feature = "u128")] assert!(Zetta < Zebi && Zebi > Zetta);
#[cfg(feature = "u128")] assert!(Zebi < Yotta && Yotta > Zebi );
#[cfg(feature = "u128")] assert!(Yotta < Yobi && Yobi > Yotta);
}
#[test]
fn const_prefix_sorted() {
fn is_sorted(prefix: &mut [UnitPrefix]) -> bool {
let a = prefix.windows(2).all(|lr| lr[0] < lr[1]);
prefix.reverse();
let b = prefix.windows(2).all(|lr| lr[0] > lr[1]);
a && b
}
assert!(is_sorted(&mut { UnitPrefix::DECIMAL }));
assert!(is_sorted(&mut { UnitPrefix::BINARY }));
assert!(is_sorted(&mut { UnitPrefix::ALL }));
}
#[test]
fn is_decimal() {
for unit in UnitPrefix::DECIMAL.iter() {
assert!(unit.is_decimal())
}
for unit in UnitPrefix::BINARY.iter() {
assert!(!unit.is_decimal())
}
}
#[test]
fn is_binary() {
for unit in UnitPrefix::BINARY.iter() {
assert!(unit.is_binary())
}
for unit in UnitPrefix::DECIMAL.iter() {
assert!(!unit.is_binary())
}
}
#[test]
fn index() {
#[rustfmt::skip]
let map = [
(Kilo, 0), (Kibi, 0),
(Mega, 1), (Mebi, 1),
(Giga, 2), (Gibi, 2),
(Tera, 3), (Tebi, 3),
(Peta, 4), (Pebi, 4),
(Exa , 5), (Exbi, 5),
#[cfg(feature = "u128")] (Zetta, 6),
#[cfg(feature = "u128")] (Yotta, 7),
#[cfg(feature = "u128")] (Zebi , 6),
#[cfg(feature = "u128")] (Yobi , 7),
];
for (unit, index) in map.iter() {
assert_eq!(
*index,
unit.index(),
"expected [{:?}] to have the index {}",
unit,
index
);
}
}
#[test]
fn to_decimal() {
#[rustfmt::skip]
let map = [
(Kilo, Kilo), (Kibi, Kilo),
(Mega, Mega), (Mebi, Mega),
(Giga, Giga), (Gibi, Giga),
(Tera, Tera), (Tebi, Tera),
(Peta, Peta), (Pebi, Peta),
(Exa , Exa ), (Exbi, Exa ),
#[cfg(feature = "u128")] (Zetta, Zetta),
#[cfg(feature = "u128")] (Yotta, Yotta),
#[cfg(feature = "u128")] (Zebi , Zetta),
#[cfg(feature = "u128")] (Yobi , Yotta),
];
for (unit, expected) in map.iter() {
assert_eq!(
*expected,
unit.decimal(),
"expected [{:?}] to be represented as [{:?}] in decimal",
unit,
expected
);
}
}
#[test]
fn to_binary() {
#[rustfmt::skip]
let map = [
(Kilo, Kibi), (Kibi, Kibi),
(Mega, Mebi), (Mebi, Mebi),
(Giga, Gibi), (Gibi, Gibi),
(Tera, Tebi), (Tebi, Tebi),
(Peta, Pebi), (Pebi, Pebi),
(Exa , Exbi), (Exbi, Exbi),
#[cfg(feature = "u128")] (Zetta, Zebi),
#[cfg(feature = "u128")] (Yotta, Yobi),
#[cfg(feature = "u128")] (Zebi , Zebi),
#[cfg(feature = "u128")] (Yobi , Yobi),
];
for (unit, expected) in map.iter() {
assert_eq!(
*expected,
unit.binary(),
"expected [{:?}] to be represented as [{:?}] in binary",
unit,
expected
);
}
}
#[test]
fn format_and_display_symbol() {
#[rustfmt::skip]
let map = [
(Kilo, "K"), (Kibi, "Ki"),
(Mega, "M"), (Mebi, "Mi"),
(Giga, "G"), (Gibi, "Gi"),
(Tera, "T"), (Tebi, "Ti"),
(Peta, "P"), (Pebi, "Pi"),
(Exa , "E"), (Exbi, "Ei"),
#[cfg(feature = "u128")] (Zetta, "Z" ),
#[cfg(feature = "u128")] (Yotta, "Y" ),
#[cfg(feature = "u128")] (Zebi , "Zi"),
#[cfg(feature = "u128")] (Yobi , "Yi"),
];
for (unit, repr) in map.iter() {
assert_eq!(
*repr,
unit.symbol(),
"expected [{:?}] to be represented as {}",
unit,
repr
);
assert_eq!(
*repr,
format!("{}", unit),
"expected [{:?}] to be represented as {}",
unit,
repr
);
}
}
#[test]
fn format_and_display_symbol_long() {
#[rustfmt::skip]
let map = [
(Kilo, "Kilo"), (Kibi, "Kibi"),
(Mega, "Mega"), (Mebi, "Mebi"),
(Giga, "Giga"), (Gibi, "Gibi"),
(Tera, "Tera"), (Tebi, "Tebi"),
(Peta, "Peta"), (Pebi, "Pebi"),
(Exa , "Exa" ), (Exbi, "Exbi"),
#[cfg(feature = "u128")] (Zetta, "Zetta"),
#[cfg(feature = "u128")] (Yotta, "Yotta"),
#[cfg(feature = "u128")] (Zebi , "Zebi" ),
#[cfg(feature = "u128")] (Yobi , "Yobi" ),
];
for (unit, repr) in map.iter() {
assert_eq!(
*repr,
unit.symbol_long(),
"expected [{:?}] to be represented in long form as {}",
unit,
repr
);
assert_eq!(
*repr,
format!("{:+}", unit),
"expected [{:?}] to be represented in long form as {}",
unit,
repr
);
}
}
#[test]
fn format_and_display_symbol_initials() {
#[rustfmt::skip]
let map = [
(Kilo, "K"), (Kibi, "K"),
(Mega, "M"), (Mebi, "M"),
(Giga, "G"), (Gibi, "G"),
(Tera, "T"), (Tebi, "T"),
(Peta, "P"), (Pebi, "P"),
(Exa , "E"), (Exbi, "E"),
#[cfg(feature = "u128")] (Zetta, "Z"),
#[cfg(feature = "u128")] (Yotta, "Y"),
#[cfg(feature = "u128")] (Zebi , "Z"),
#[cfg(feature = "u128")] (Yobi , "Y"),
];
for (unit, repr) in map.iter() {
assert_eq!(
*repr,
unit.symbol_initials(),
"expected [{:?}] to be represented in short form as {}",
unit,
repr
);
assert_eq!(
*repr,
format!("{:-}", unit),
"expected [{:?}] to be represented in short form as {}",
unit,
repr
);
}
}
#[test]
fn str_parse() {
#[rustfmt::skip]
let map = [
("k" , Ok(Kilo)),
("K" , Ok(Kilo)), ("Ki" , Ok(Kibi)),
("M" , Ok(Mega)), ("Mi" , Ok(Mebi)),
("G" , Ok(Giga)), ("Gi" , Ok(Gibi)),
("T" , Ok(Tera)), ("Ti" , Ok(Tebi)),
("P" , Ok(Peta)), ("Pi" , Ok(Pebi)),
("E" , Ok(Exa )), ("Ei" , Ok(Exbi)),
#[cfg(feature = "u128")] ("Z" , Ok(Zetta)),
#[cfg(feature = "u128")] ("Y" , Ok(Yotta)),
#[cfg(feature = "u128")] ("Zi", Ok(Zebi )),
#[cfg(feature = "u128")] ("Yi", Ok(Yobi )),
#[cfg(feature = "case-insensitive")] ("k" , Ok(Kilo)),
#[cfg(feature = "case-insensitive")] ("ki", Ok(Kibi)),
#[cfg(feature = "case-insensitive")] ("m" , Ok(Mega)),
#[cfg(feature = "case-insensitive")] ("mi", Ok(Mebi)),
#[cfg(feature = "case-insensitive")] ("g" , Ok(Giga)),
#[cfg(feature = "case-insensitive")] ("gi", Ok(Gibi)),
#[cfg(feature = "case-insensitive")] ("t" , Ok(Tera)),
#[cfg(feature = "case-insensitive")] ("ti", Ok(Tebi)),
#[cfg(feature = "case-insensitive")] ("p" , Ok(Peta)),
#[cfg(feature = "case-insensitive")] ("pi", Ok(Pebi)),
#[cfg(feature = "case-insensitive")] ("e" , Ok(Exa )),
#[cfg(feature = "case-insensitive")] ("ei", Ok(Exbi)),
#[cfg(feature = "case-insensitive")] #[cfg(feature = "u128")] ("z" , Ok(Zetta)),
#[cfg(feature = "case-insensitive")] #[cfg(feature = "u128")] ("y" , Ok(Yotta)),
#[cfg(feature = "case-insensitive")] #[cfg(feature = "u128")] ("zi", Ok(Zebi )),
#[cfg(feature = "case-insensitive")] #[cfg(feature = "u128")] ("yi", Ok(Yobi )),
#[cfg(feature = "case-insensitive")] ("kI", Ok(Kibi)),
#[cfg(feature = "case-insensitive")] ("KI", Ok(Kibi)),
#[cfg(feature = "case-insensitive")] ("mI", Ok(Mebi)),
#[cfg(feature = "case-insensitive")] ("MI", Ok(Mebi)),
#[cfg(feature = "case-insensitive")] ("gI", Ok(Gibi)),
#[cfg(feature = "case-insensitive")] ("GI", Ok(Gibi)),
#[cfg(feature = "case-insensitive")] ("tI", Ok(Tebi)),
#[cfg(feature = "case-insensitive")] ("TI", Ok(Tebi)),
#[cfg(feature = "case-insensitive")] ("pI", Ok(Pebi)),
#[cfg(feature = "case-insensitive")] ("PI", Ok(Pebi)),
#[cfg(feature = "case-insensitive")] ("eI", Ok(Exbi)),
#[cfg(feature = "case-insensitive")] ("EI", Ok(Exbi)),
#[cfg(feature = "case-insensitive")] #[cfg(feature = "u128")] ("zI", Ok(Zebi)),
#[cfg(feature = "case-insensitive")] #[cfg(feature = "u128")] ("ZI", Ok(Zebi)),
#[cfg(feature = "case-insensitive")] #[cfg(feature = "u128")] ("yI", Ok(Yobi)),
#[cfg(feature = "case-insensitive")] #[cfg(feature = "u128")] ("YI", Ok(Yobi)),
];
assert_eq!(Err(ParseError::EmptyInput), "".parse::<UnitPrefix>());
for (value, unit) in map.iter() {
assert_eq!(*unit, value.parse::<UnitPrefix>());
}
#[cfg(not(feature = "case-insensitive"))]
{
#[rustfmt::skip]
let invalid_formats = [
"ki", "m", "mi", "g", "gi",
"t", "ti", "p", "pi", "e", "ei",
#[cfg(feature = "u128")] "z" ,
#[cfg(feature = "u128")] "zi",
#[cfg(feature = "u128")] "y" ,
#[cfg(feature = "u128")] "yi",
];
for value in invalid_formats.iter() {
assert_eq!(
Err(ParseError::InvalidPrefixCaseFormat),
value.parse::<UnitPrefix>()
);
}
#[rustfmt::skip]
let invalid_prefixes = [
"kI", "KI", "mI", "MI", "gI", "GI",
"tI", "TI", "pI", "PI", "eI", "EI",
#[cfg(feature = "u128")] "zI" ,
#[cfg(feature = "u128")] "ZI",
#[cfg(feature = "u128")] "yI" ,
#[cfg(feature = "u128")] "YI",
];
for value in invalid_prefixes.iter() {
assert_eq!(Err(ParseError::InvalidPrefix), value.parse::<UnitPrefix>());
}
}
}
#[test]
fn effective_value() {
#[rustfmt::skip]
let map = [
(Kilo, 1000), (Kibi, 1024),
(Mega, 1000000), (Mebi, 1048576),
(Giga, 1000000000), (Gibi, 1073741824),
(Tera, 1000000000000), (Tebi, 1099511627776),
(Peta, 1000000000000000), (Pebi, 1125899906842624),
(Exa , 1000000000000000000), (Exbi, 1152921504606846976),
#[cfg(feature = "u128")] (Zetta, 1000000000000000000000),
#[cfg(feature = "u128")] (Yotta, 1000000000000000000000000),
#[cfg(feature = "u128")] (Zebi , 1180591620717411303424),
#[cfg(feature = "u128")] (Yobi , 1208925819614629174706176)
];
for (prefix, value) in map.iter() {
assert_eq!(
*value,
prefix.effective_value(),
"expected [{:?}] to have the value [{}]",
prefix,
value
);
}
}
#[test]
fn min_max() {
assert_eq!(Kilo, UnitPrefix::MIN);
#[cfg(feature = "u128")]
assert_eq!(Yobi, UnitPrefix::MAX);
#[cfg(not(feature = "u128"))]
assert_eq!(Exbi, UnitPrefix::MAX);
}
}
|
{
#[rustfmt::skip]
let lhs = [
Kibi, Mebi, Gibi, Tebi, Pebi, Exbi,
#[cfg(feature = "u128")] Zebi,
#[cfg(feature = "u128")] Yobi
];
for (index, unit) in lhs.iter().enumerate() {
assert_eq!(unit, &UnitPrefix::BINARY[index]);
assert_ne!(unit, &UnitPrefix::DECIMAL[index]);
}
}
|
switch.go
|
components {
id: "switch"
component: "/game/objects/switch.script"
position {
x: 0.0
y: 0.0
z: 0.0
}
rotation {
x: 0.0
y: 0.0
z: 0.0
w: 1.0
}
}
embedded_components {
id: "co"
type: "collisionobject"
data: "collision_shape: \"\"\n"
"type: COLLISION_OBJECT_TYPE_TRIGGER\n"
"mass: 0.0\n"
"friction: 0.1\n"
"restitution: 0.5\n"
"group: \"block\"\n"
"mask: \"player\"\n"
"mask: \"block\"\n"
"embedded_collision_shape {\n"
" shapes {\n"
" shape_type: TYPE_BOX\n"
" position {\n"
" x: 0.0\n"
" y: -6.5\n"
" z: 0.0\n"
" }\n"
" rotation {\n"
" x: 0.0\n"
" y: 0.0\n"
" z: 0.0\n"
" w: 1.0\n"
" }\n"
" index: 0\n"
" count: 3\n"
|
"}\n"
"linear_damping: 0.0\n"
"angular_damping: 0.0\n"
"locked_rotation: false\n"
""
position {
x: 0.0
y: 0.0
z: 0.0
}
rotation {
x: 0.0
y: 0.0
z: 0.0
w: 1.0
}
}
embedded_components {
id: "sprite"
type: "sprite"
data: "tile_set: \"/assets/1bit.tilesource\"\n"
"default_animation: \"switch_open\"\n"
"material: \"/builtins/materials/sprite.material\"\n"
"blend_mode: BLEND_MODE_ALPHA\n"
""
position {
x: 0.0
y: 0.0
z: 0.0
}
rotation {
x: 0.0
y: 0.0
z: 0.0
w: 1.0
}
}
embedded_components {
id: "waterfall"
type: "factory"
data: "prototype: \"/game/objects/waterfall.go\"\n"
"load_dynamically: false\n"
""
position {
x: 0.0
y: 0.0
z: 0.0
}
rotation {
x: 0.0
y: 0.0
z: 0.0
w: 1.0
}
}
|
" }\n"
" data: 6.0\n"
" data: 1.5\n"
" data: 10.0\n"
|
mapping.py
|
# -*- coding: utf-8 -*-
"""
@author: Thorsten
"""
import numpy as np
from numba import jit
import os
import sys
nb_dir = os.path.split(os.getcwd())[0]
if nb_dir not in sys.path:
sys.path.append(nb_dir)
from lib import bresenham
@jit
def addMeasurement(grid, x, y, pos_sensor, offset, resolution, l_occupied, l_free, l_min, l_max):
for i in range(x.size):
# round points to cells
xi=int( (x[i,0]-offset[0]) / resolution )
yi=int( (y[i,0]-offset[1]) / resolution )
# set beam endpoint-cells as occupied
grid[xi,yi] += l_occupied
# value > threshold? -> clamping
if grid[xi,yi] > l_max:
grid[xi,yi] = l_max
# calculate cells between sensor and endpoint as free
path = bresenham.bresenham2D( ((pos_sensor-offset)/resolution).astype(int), np.array([[xi,yi]]))
|
# set cells between sensor and endpoint as free
updateFree(path,grid,l_free,l_min)
@jit(nopython=True)
def updateFree(path,grid,l_free,l_min):
for nr in range(path.shape[0]):
path_x = int(path[nr,0])
path_y = int(path[nr,1])
grid[path_x, path_y] += l_free
# value < threshold? -> clamping
if grid[path_x, path_y] < l_min:
grid[path_x, path_y] = l_min
@jit(nopython=True)
def scan2mapDistance(grid,pcl,offset,resolution):
distance = 0;
for i in range(pcl.shape[0]):
# round points to cells
xi = int ( (pcl[i,0]-offset[0]) / resolution )
yi = int ( (pcl[i,1]-offset[1]) / resolution )
distance += grid[xi,yi]
return distance
| |
interpreting_executor.rs
|
use super::{pipeline::QueryPipeline, QueryExecutor};
use crate::{Operation, QueryGraphBuilder, QueryInterpreter, QuerySchemaRef, ResponseData};
use async_trait::async_trait;
use connector::{Connection, ConnectionLike, Connector};
use futures::future;
/// Central query executor and main entry point into the query core.
pub struct InterpretingExecutor<C> {
/// The loaded connector
connector: C,
/// Flag that forces individual operations to run in a transaction.
/// Does _not_ force batches to use transactions.
force_transactions: bool,
}
impl<C> InterpretingExecutor<C>
where
C: Connector + Send + Sync,
{
pub fn new(connector: C, force_transactions: bool) -> Self {
InterpretingExecutor {
connector,
force_transactions,
}
}
/// Async wrapper for executing an individual operation to allow code sharing with `execute_batch`.
async fn execute_single_operation(
operation: Operation,
conn: Box<dyn Connection>,
force_transactions: bool,
query_schema: QuerySchemaRef,
) -> crate::Result<ResponseData> {
// Parse, validate, and extract query graph from query document.
let (query_graph, serializer) = QueryGraphBuilder::new(query_schema).build(operation)?;
let is_transactional = force_transactions || query_graph.needs_transaction();
if is_transactional {
let tx = conn.start_transaction().await?;
let interpreter = QueryInterpreter::new(ConnectionLike::Transaction(tx.as_ref()));
let result = QueryPipeline::new(query_graph, interpreter, serializer).execute().await;
if result.is_ok() {
tx.commit().await?;
} else {
tx.rollback().await?;
}
result
} else
|
}
}
#[async_trait]
impl<C> QueryExecutor for InterpretingExecutor<C>
where
C: Connector + Send + Sync + 'static,
{
/// Executes a batch of operations.
///
/// If the batch is to be executed transactionally:
/// All operations are evaluated in sequence and the entire batch is rolled back if one operation fails,
/// returning the error.
///
/// If the batch is not transactional:
/// All operations are fanned out onto as many connections as possible and executed independently.
/// A failing operation does not fail the batch, instead, an error is returned alongside other responses.
/// Note that individual operations executed in non-transactional mode can still be transactions in themselves
/// if the query (e.g. a write op) requires it.
async fn execute_batch(
&self,
operations: Vec<Operation>,
transactional: bool,
query_schema: QuerySchemaRef,
) -> crate::Result<Vec<crate::Result<ResponseData>>> {
if transactional {
let queries = operations
.into_iter()
.map(|op| QueryGraphBuilder::new(query_schema.clone()).build(op))
.collect::<std::result::Result<Vec<_>, _>>()?;
let conn = self.connector.get_connection().await?;
let tx = conn.start_transaction().await?;
let mut results = Vec::with_capacity(queries.len());
for (query, info) in queries {
let interpreter = QueryInterpreter::new(ConnectionLike::Transaction(tx.as_ref()));
let result = QueryPipeline::new(query, interpreter, info).execute().await;
if result.is_err() {
tx.rollback().await?;
}
results.push(Ok(result?));
}
tx.commit().await?;
Ok(results)
} else {
let mut futures = Vec::with_capacity(operations.len());
for operation in operations {
let conn = self.connector.get_connection().await?;
futures.push(tokio::spawn(Self::execute_single_operation(
operation,
conn,
self.force_transactions,
query_schema.clone(),
)));
}
let responses: Vec<_> = future::join_all(futures)
.await
.into_iter()
.map(|res| res.expect("IO Error in tokio::spawn"))
.collect();
Ok(responses)
}
}
/// Executes a single operation. Execution will be inside of a transaction or not depending on the needs of the query.
async fn execute(&self, operation: Operation, query_schema: QuerySchemaRef) -> crate::Result<ResponseData> {
let conn = self.connector.get_connection().await?;
Self::execute_single_operation(operation, conn, self.force_transactions, query_schema.clone()).await
}
fn primary_connector(&self) -> &dyn Connector {
&self.connector
}
}
|
{
let interpreter = QueryInterpreter::new(ConnectionLike::Connection(conn.as_ref()));
QueryPipeline::new(query_graph, interpreter, serializer).execute().await
}
|
test_drf_urls.py
|
"""App drf url tests.
"""
from unittest import mock
import pytest
from django.urls import resolve, reverse
from .factories import ProjectFactory
pytestmark = pytest.mark.django_db
@pytest.mark.fast
@mock.patch(
"vision_on_edge.azure_projects.models.Project.validate",
mock.MagicMock(return_value=True),
)
def
|
():
"""test_project_detail.
Args:
project (Project): project
"""
project = ProjectFactory()
assert (
reverse("api:project-detail", kwargs={"pk": project.id})
== f"/api/projects/{project.id}"
)
assert resolve(f"/api/projects/{project.id}").view_name == "api:project-detail"
@pytest.mark.fast
def test_project_list():
"""test_project_list."""
assert reverse("api:project-list") == "/api/projects"
assert resolve("/api/projects").view_name == "api:project-list"
|
test_project_detail
|
rename_test.go
|
package osrename_test
import (
"bytes"
rn "gx/ipfs/QmaeRR9SpXumU5tYLRkq6x6pfMe8qKzxn4ujBpsTJ2zQG7/go-os-rename"
"io/ioutil"
"os"
"testing"
)
func tempdir(t testing.TB) (path string, cleanup func()) {
path, err := ioutil.TempDir("", "test-windows-rename")
if err != nil {
t.Fatalf("cannot create temp directory: %v", err)
}
cleanup = func() {
if err := os.RemoveAll(path); err != nil {
t.Errorf("tempdir cleanup failed: %v", err)
}
}
return path, cleanup
}
func TestAtomicRename(t *testing.T) {
dirBase, cleanup := tempdir(t)
defer cleanup()
// Create base file
origFilePath := dirBase + "original.txt"
err := ioutil.WriteFile(origFilePath, []byte("tests"), 0644)
if err != nil {
t.Fatalf("Could not write original test file")
}
// Create secondary file
tempFilePath := dirBase + "newTempFile.txt"
err = ioutil.WriteFile(tempFilePath, []byte("success"), 0644)
if err != nil {
t.Fatalf("Could not write temp file")
}
// Execute our magic rename function
err = rn.Rename(tempFilePath, origFilePath)
if err != nil
|
// Let's read the renamed file and ensure that we get data
renamedFileBytes, err := ioutil.ReadFile(origFilePath)
if err != nil {
t.Fatalf("Could not read renamed file")
}
// Let's compare the bytes of the renamed file
if bytes.Compare(renamedFileBytes, []byte("success")) != 0 {
t.Fatalf("Did not find expected bytes in renamed file %d vs %d", renamedFileBytes, []byte("success"))
}
}
|
{
t.Fatalf("Could not rename temp file")
}
|
ui.datepicker.js
|
/*
* jQuery UI Datepicker 1.7.3
*
* Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* http://docs.jquery.com/UI/Datepicker
*
* Depends:
* ui.core.js
*/
(function($) { // hide the namespace
$.extend($.ui, { datepicker: { version: "1.7.3" } });
var PROP_NAME = 'datepicker';
/* Date picker manager.
Use the singleton instance of this class, $.datepicker, to interact with the date picker.
Settings for (groups of) date pickers are maintained in an instance object,
allowing multiple different settings on the same page. */
function Datepicker() {
this.debug = false; // Change this to true to start debugging
this._curInst = null; // The current instance in use
this._keyEvent = false; // If the last event was a key event
this._disabledInputs = []; // List of date picker inputs that have been disabled
this._datepickerShowing = false; // True if the popup picker is showing , false if not
this._inDialog = false; // True if showing within a "dialog", false if not
this._mainDivId = 'ui-datepicker-div'; // The ID of the main datepicker division
this._inlineClass = 'ui-datepicker-inline'; // The name of the inline marker class
this._appendClass = 'ui-datepicker-append'; // The name of the append marker class
this._triggerClass = 'ui-datepicker-trigger'; // The name of the trigger marker class
this._dialogClass = 'ui-datepicker-dialog'; // The name of the dialog marker class
this._disableClass = 'ui-datepicker-disabled'; // The name of the disabled covering marker class
this._unselectableClass = 'ui-datepicker-unselectable'; // The name of the unselectable cell marker class
this._currentClass = 'ui-datepicker-current-day'; // The name of the current day marker class
this._dayOverClass = 'ui-datepicker-days-cell-over'; // The name of the day hover marker class
this.regional = []; // Available regional settings, indexed by language code
this.regional[''] = { // Default regional settings
closeText: 'Done', // Display text for close link
prevText: 'Prev', // Display text for previous month link
nextText: 'Next', // Display text for next month link
currentText: 'Today', // Display text for current month link
monthNames: ['January','February','March','April','May','June',
'July','August','September','October','November','December'], // Names of months for drop-down and formatting
monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], // For formatting
dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], // For formatting
dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], // For formatting
dayNamesMin: ['Su','Mo','Tu','We','Th','Fr','Sa'], // Column headings for days starting at Sunday
dateFormat: 'mm/dd/yy', // See format options on parseDate
firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
isRTL: false // True if right-to-left language, false if left-to-right
};
this._defaults = { // Global defaults for all the date picker instances
showOn: 'focus', // 'focus' for popup on focus,
// 'button' for trigger button, or 'both' for either
showAnim: 'show', // Name of jQuery animation for popup
showOptions: {}, // Options for enhanced animations
defaultDate: null, // Used when field is blank: actual date,
// +/-number for offset from today, null for today
appendText: '', // Display text following the input box, e.g. showing the format
buttonText: '...', // Text for trigger button
buttonImage: '', // URL for trigger button image
buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
hideIfNoPrevNext: false, // True to hide next/previous month links
// if not applicable, false to just disable them
navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links
gotoCurrent: false, // True if today link goes back to current selection instead
changeMonth: false, // True if month can be selected directly, false if only prev/next
changeYear: false, // True if year can be selected directly, false if only prev/next
showMonthAfterYear: false, // True if the year select precedes month, false for month then year
yearRange: '-10:+10', // Range of years to display in drop-down,
// either relative to current year (-nn:+nn) or absolute (nnnn:nnnn)
showOtherMonths: false, // True to show dates in other months, false to leave blank
calculateWeek: this.iso8601Week, // How to calculate the week of the year,
// takes a Date and returns the number of the week for it
shortYearCutoff: '+10', // Short year values < this are in the current century,
// > this are in the previous century,
// string value starting with '+' for current year + value
minDate: null, // The earliest selectable date, or null for no limit
maxDate: null, // The latest selectable date, or null for no limit
duration: 'normal', // Duration of display/closure
beforeShowDay: null, // Function that takes a date and returns an array with
// [0] = true if selectable, false if not, [1] = custom CSS class name(s) or '',
// [2] = cell title (optional), e.g. $.datepicker.noWeekends
beforeShow: null, // Function that takes an input field and
// returns a set of custom settings for the date picker
onSelect: null, // Define a callback function when a date is selected
onChangeMonthYear: null, // Define a callback function when the month or year is changed
onClose: null, // Define a callback function when the datepicker is closed
numberOfMonths: 1, // Number of months to show at a time
showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0)
stepMonths: 1, // Number of months to step back/forward
stepBigMonths: 12, // Number of months to step back/forward for the big links
altField: '', // Selector for an alternate field to store selected dates into
altFormat: '', // The date format to use for the alternate field
constrainInput: true, // The input is constrained by the current date format
showButtonPanel: false // True to show button panel, false to not show it
};
$.extend(this._defaults, this.regional['']);
this.dpDiv = $('<div id="' + this._mainDivId + '" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all ui-helper-hidden-accessible"></div>');
}
$.extend(Datepicker.prototype, {
/* Class name added to elements to indicate already configured with a date picker. */
markerClassName: 'hasDatepicker',
/* Debug logging (if enabled). */
log: function () {
if (this.debug)
console.log.apply('', arguments);
},
/* Override the default settings for all instances of the date picker.
@param settings object - the new settings to use as defaults (anonymous object)
@return the manager object */
setDefaults: function(settings) {
extendRemove(this._defaults, settings || {});
return this;
},
/* Attach the date picker to a jQuery selection.
@param target element - the target input field or division or span
@param settings object - the new settings to use for this date picker instance (anonymous) */
_attachDatepicker: function(target, settings) {
// check for settings on the control itself - in namespace 'date:'
var inlineSettings = null;
for (var attrName in this._defaults) {
var attrValue = target.getAttribute('date:' + attrName);
if (attrValue) {
inlineSettings = inlineSettings || {};
try {
inlineSettings[attrName] = eval(attrValue);
} catch (err) {
inlineSettings[attrName] = attrValue;
}
}
}
var nodeName = target.nodeName.toLowerCase();
var inline = (nodeName == 'div' || nodeName == 'span');
if (!target.id)
target.id = 'dp' + (++this.uuid);
var inst = this._newInst($(target), inline);
inst.settings = $.extend({}, settings || {}, inlineSettings || {});
if (nodeName == 'input') {
this._connectDatepicker(target, inst);
} else if (inline) {
this._inlineDatepicker(target, inst);
}
},
/* Create a new instance object. */
_newInst: function(target, inline) {
var id = target[0].id.replace(/([:\[\]\.])/g, '\\\\$1'); // escape jQuery meta chars
return {id: id, input: target, // associated target
selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection
drawMonth: 0, drawYear: 0, // month being drawn
inline: inline, // is datepicker inline or not
dpDiv: (!inline ? this.dpDiv : // presentation div
$('<div class="' + this._inlineClass + ' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>'))};
},
/* Attach the date picker to an input field. */
_connectDatepicker: function(target, inst) {
var input = $(target);
inst.append = $([]);
inst.trigger = $([]);
if (input.hasClass(this.markerClassName))
return;
var appendText = this._get(inst, 'appendText');
var isRTL = this._get(inst, 'isRTL');
if (appendText) {
inst.append = $('<span class="' + this._appendClass + '">' + appendText + '</span>');
input[isRTL ? 'before' : 'after'](inst.append);
}
var showOn = this._get(inst, 'showOn');
if (showOn == 'focus' || showOn == 'both') // pop-up date picker when in the marked field
input.focus(this._showDatepicker);
if (showOn == 'button' || showOn == 'both') { // pop-up date picker when button clicked
var buttonText = this._get(inst, 'buttonText');
var buttonImage = this._get(inst, 'buttonImage');
inst.trigger = $(this._get(inst, 'buttonImageOnly') ?
$('<img/>').addClass(this._triggerClass).
attr({ src: buttonImage, alt: buttonText, title: buttonText }) :
$('<button type="button"></button>').addClass(this._triggerClass).
html(buttonImage == '' ? buttonText : $('<img/>').attr(
{ src:buttonImage, alt:buttonText, title:buttonText })));
input[isRTL ? 'before' : 'after'](inst.trigger);
inst.trigger.click(function() {
if ($.datepicker._datepickerShowing && $.datepicker._lastInput == target)
$.datepicker._hideDatepicker();
else
$.datepicker._showDatepicker(target);
return false;
});
}
input.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).
bind("setData.datepicker", function(event, key, value) {
inst.settings[key] = value;
}).bind("getData.datepicker", function(event, key) {
return this._get(inst, key);
});
$.data(target, PROP_NAME, inst);
},
/* Attach an inline date picker to a div. */
_inlineDatepicker: function(target, inst) {
var divSpan = $(target);
if (divSpan.hasClass(this.markerClassName))
return;
divSpan.addClass(this.markerClassName).append(inst.dpDiv).
bind("setData.datepicker", function(event, key, value){
inst.settings[key] = value;
}).bind("getData.datepicker", function(event, key){
return this._get(inst, key);
});
$.data(target, PROP_NAME, inst);
this._setDate(inst, this._getDefaultDate(inst));
this._updateDatepicker(inst);
this._updateAlternate(inst);
},
/* Pop-up the date picker in a "dialog" box.
@param input element - ignored
@param dateText string - the initial date to display (in the current format)
@param onSelect function - the function(dateText) to call when a date is selected
@param settings object - update the dialog date picker instance's settings (anonymous object)
@param pos int[2] - coordinates for the dialog's position within the screen or
event - with x/y coordinates or
leave empty for default (screen centre)
@return the manager object */
_dialogDatepicker: function(input, dateText, onSelect, settings, pos) {
var inst = this._dialogInst; // internal instance
if (!inst) {
var id = 'dp' + (++this.uuid);
this._dialogInput = $('<input type="text" id="' + id +
'" size="1" style="position: absolute; top: -100px;"/>');
this._dialogInput.keydown(this._doKeyDown);
$('body').append(this._dialogInput);
inst = this._dialogInst = this._newInst(this._dialogInput, false);
inst.settings = {};
$.data(this._dialogInput[0], PROP_NAME, inst);
}
extendRemove(inst.settings, settings || {});
this._dialogInput.val(dateText);
this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null);
if (!this._pos) {
var browserWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var browserHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
this._pos = // should use actual width/height below
[(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY];
}
// move input on screen for focus, but hidden behind dialog
this._dialogInput.css('left', this._pos[0] + 'px').css('top', this._pos[1] + 'px');
inst.settings.onSelect = onSelect;
this._inDialog = true;
this.dpDiv.addClass(this._dialogClass);
this._showDatepicker(this._dialogInput[0]);
if ($.blockUI)
$.blockUI(this.dpDiv);
$.data(this._dialogInput[0], PROP_NAME, inst);
return this;
},
/* Detach a datepicker from its control.
@param target element - the target input field or division or span */
_destroyDatepicker: function(target) {
var $target = $(target);
var inst = $.data(target, PROP_NAME);
if (!$target.hasClass(this.markerClassName)) {
return;
}
var nodeName = target.nodeName.toLowerCase();
$.removeData(target, PROP_NAME);
if (nodeName == 'input') {
inst.append.remove();
inst.trigger.remove();
$target.removeClass(this.markerClassName).
unbind('focus', this._showDatepicker).
unbind('keydown', this._doKeyDown).
unbind('keypress', this._doKeyPress);
} else if (nodeName == 'div' || nodeName == 'span')
$target.removeClass(this.markerClassName).empty();
},
/* Enable the date picker to a jQuery selection.
@param target element - the target input field or division or span */
_enableDatepicker: function(target) {
var $target = $(target);
var inst = $.data(target, PROP_NAME);
if (!$target.hasClass(this.markerClassName)) {
return;
}
var nodeName = target.nodeName.toLowerCase();
if (nodeName == 'input') {
target.disabled = false;
inst.trigger.filter('button').
each(function() { this.disabled = false; }).end().
filter('img').css({opacity: '1.0', cursor: ''});
}
else if (nodeName == 'div' || nodeName == 'span') {
var inline = $target.children('.' + this._inlineClass);
inline.children().removeClass('ui-state-disabled');
}
this._disabledInputs = $.map(this._disabledInputs,
function(value) { return (value == target ? null : value); }); // delete entry
},
/* Disable the date picker to a jQuery selection.
@param target element - the target input field or division or span */
_disableDatepicker: function(target) {
var $target = $(target);
var inst = $.data(target, PROP_NAME);
if (!$target.hasClass(this.markerClassName)) {
return;
}
var nodeName = target.nodeName.toLowerCase();
if (nodeName == 'input') {
target.disabled = true;
inst.trigger.filter('button').
each(function() { this.disabled = true; }).end().
filter('img').css({opacity: '0.5', cursor: 'default'});
}
else if (nodeName == 'div' || nodeName == 'span') {
var inline = $target.children('.' + this._inlineClass);
inline.children().addClass('ui-state-disabled');
}
this._disabledInputs = $.map(this._disabledInputs,
function(value) { return (value == target ? null : value); }); // delete entry
this._disabledInputs[this._disabledInputs.length] = target;
},
/* Is the first field in a jQuery collection disabled as a datepicker?
@param target element - the target input field or division or span
@return boolean - true if disabled, false if enabled */
_isDisabledDatepicker: function(target) {
if (!target) {
return false;
}
for (var i = 0; i < this._disabledInputs.length; i++) {
if (this._disabledInputs[i] == target)
return true;
}
return false;
},
/* Retrieve the instance data for the target control.
@param target element - the target input field or division or span
@return object - the associated instance data
@throws error if a jQuery problem getting data */
_getInst: function(target) {
try {
return $.data(target, PROP_NAME);
}
catch (err) {
throw 'Missing instance data for this datepicker';
}
},
/* Update or retrieve the settings for a date picker attached to an input field or division.
@param target element - the target input field or division or span
@param name object - the new settings to update or
string - the name of the setting to change or retrieve,
when retrieving also 'all' for all instance settings or
'defaults' for all global defaults
@param value any - the new value for the setting
(omit if above is an object or to retrieve a value) */
_optionDatepicker: function(target, name, value) {
var inst = this._getInst(target);
if (arguments.length == 2 && typeof name == 'string') {
return (name == 'defaults' ? $.extend({}, $.datepicker._defaults) :
(inst ? (name == 'all' ? $.extend({}, inst.settings) :
this._get(inst, name)) : null));
}
var settings = name || {};
if (typeof name == 'string') {
settings = {};
settings[name] = value;
}
if (inst) {
if (this._curInst == inst) {
this._hideDatepicker(null);
}
var date = this._getDateDatepicker(target);
extendRemove(inst.settings, settings);
this._setDateDatepicker(target, date);
this._updateDatepicker(inst);
}
},
// change method deprecated
_changeDatepicker: function(target, name, value) {
this._optionDatepicker(target, name, value);
},
/* Redraw the date picker attached to an input field or division.
@param target element - the target input field or division or span */
_refreshDatepicker: function(target) {
var inst = this._getInst(target);
if (inst) {
this._updateDatepicker(inst);
}
},
/* Set the dates for a jQuery selection.
@param target element - the target input field or division or span
@param date Date - the new date
@param endDate Date - the new end date for a range (optional) */
_setDateDatepicker: function(target, date, endDate) {
var inst = this._getInst(target);
if (inst) {
this._setDate(inst, date, endDate);
this._updateDatepicker(inst);
this._updateAlternate(inst);
}
},
/* Get the date(s) for the first entry in a jQuery selection.
@param target element - the target input field or division or span
@return Date - the current date or
Date[2] - the current dates for a range */
_getDateDatepicker: function(target) {
var inst = this._getInst(target);
if (inst && !inst.inline)
this._setDateFromField(inst);
return (inst ? this._getDate(inst) : null);
},
/* Handle keystrokes. */
_doKeyDown: function(event) {
var inst = $.datepicker._getInst(event.target);
var handled = true;
var isRTL = inst.dpDiv.is('.ui-datepicker-rtl');
inst._keyEvent = true;
if ($.datepicker._datepickerShowing)
switch (event.keyCode) {
case 9: $.datepicker._hideDatepicker(null, '');
break; // hide on tab out
case 13: var sel = $('td.' + $.datepicker._dayOverClass +
', td.' + $.datepicker._currentClass, inst.dpDiv);
if (sel[0])
$.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]);
else
$.datepicker._hideDatepicker(null, $.datepicker._get(inst, 'duration'));
return false; // don't submit the form
break; // select the value on enter
case 27: $.datepicker._hideDatepicker(null, $.datepicker._get(inst, 'duration'));
break; // hide on escape
case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
-$.datepicker._get(inst, 'stepBigMonths') :
-$.datepicker._get(inst, 'stepMonths')), 'M');
break; // previous month/year on page up/+ ctrl
case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
+$.datepicker._get(inst, 'stepBigMonths') :
+$.datepicker._get(inst, 'stepMonths')), 'M');
break; // next month/year on page down/+ ctrl
case 35: if (event.ctrlKey || event.metaKey) $.datepicker._clearDate(event.target);
handled = event.ctrlKey || event.metaKey;
break; // clear on ctrl or command +end
case 36: if (event.ctrlKey || event.metaKey) $.datepicker._gotoToday(event.target);
handled = event.ctrlKey || event.metaKey;
break; // current on ctrl or command +home
case 37: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), 'D');
handled = event.ctrlKey || event.metaKey;
// -1 day on ctrl or command +left
if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ?
-$.datepicker._get(inst, 'stepBigMonths') :
-$.datepicker._get(inst, 'stepMonths')), 'M');
// next month/year on alt +left on Mac
break;
case 38: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, -7, 'D');
handled = event.ctrlKey || event.metaKey;
break; // -1 week on ctrl or command +up
case 39: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), 'D');
handled = event.ctrlKey || event.metaKey;
// +1 day on ctrl or command +right
if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ?
+$.datepicker._get(inst, 'stepBigMonths') :
+$.datepicker._get(inst, 'stepMonths')), 'M');
// next month/year on alt +right
break;
case 40: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, +7, 'D');
handled = event.ctrlKey || event.metaKey;
break; // +1 week on ctrl or command +down
default: handled = false;
}
else if (event.keyCode == 36 && event.ctrlKey) // display the date picker on ctrl+home
$.datepicker._showDatepicker(this);
else {
handled = false;
}
if (handled) {
event.preventDefault();
event.stopPropagation();
}
},
/* Filter entered characters - based on date format. */
_doKeyPress: function(event) {
var inst = $.datepicker._getInst(event.target);
if ($.datepicker._get(inst, 'constrainInput')) {
var chars = $.datepicker._possibleChars($.datepicker._get(inst, 'dateFormat'));
var chr = String.fromCharCode(event.charCode == undefined ? event.keyCode : event.charCode);
return event.ctrlKey || (chr < ' ' || !chars || chars.indexOf(chr) > -1);
}
},
/* Pop-up the date picker for a given input field.
@param input element - the input field attached to the date picker or
event - if triggered by focus */
_showDatepicker: function(input) {
input = input.target || input;
if (input.nodeName.toLowerCase() != 'input') // find from button/image trigger
input = $('input', input.parentNode)[0];
if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput == input) // already here
return;
var inst = $.datepicker._getInst(input);
var beforeShow = $.datepicker._get(inst, 'beforeShow');
extendRemove(inst.settings, (beforeShow ? beforeShow.apply(input, [input, inst]) : {}));
$.datepicker._hideDatepicker(null, '');
$.datepicker._lastInput = input;
$.datepicker._setDateFromField(inst);
if ($.datepicker._inDialog) // hide cursor
input.value = '';
if (!$.datepicker._pos) { // position below input
$.datepicker._pos = $.datepicker._findPos(input);
$.datepicker._pos[1] += input.offsetHeight; // add the height
}
var isFixed = false;
$(input).parents().each(function() {
isFixed |= $(this).css('position') == 'fixed';
return !isFixed;
});
if (isFixed && $.browser.opera) { // correction for Opera when fixed and scrolled
$.datepicker._pos[0] -= document.documentElement.scrollLeft;
$.datepicker._pos[1] -= document.documentElement.scrollTop;
}
var offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]};
$.datepicker._pos = null;
inst.rangeStart = null;
// determine sizing offscreen
inst.dpDiv.css({position: 'absolute', display: 'block', top: '-1000px'});
$.datepicker._updateDatepicker(inst);
// fix width for dynamic number of date pickers
// and adjust position before showing
offset = $.datepicker._checkOffset(inst, offset, isFixed);
inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ?
'static' : (isFixed ? 'fixed' : 'absolute')), display: 'none',
left: offset.left + 'px', top: offset.top + 'px'});
if (!inst.inline) {
var showAnim = $.datepicker._get(inst, 'showAnim') || 'show';
var duration = $.datepicker._get(inst, 'duration');
var postProcess = function() {
$.datepicker._datepickerShowing = true;
if ($.browser.msie && parseInt($.browser.version,10) < 7) // fix IE < 7 select problems
$('iframe.ui-datepicker-cover').css({width: inst.dpDiv.width() + 4,
height: inst.dpDiv.height() + 4});
};
if ($.effects && $.effects[showAnim])
inst.dpDiv.show(showAnim, $.datepicker._get(inst, 'showOptions'), duration, postProcess);
else
inst.dpDiv[showAnim](duration, postProcess);
if (duration == '')
postProcess();
if (inst.input[0].type != 'hidden')
inst.input[0].focus();
$.datepicker._curInst = inst;
}
},
/* Generate the date picker content. */
_updateDatepicker: function(inst) {
var dims = {width: inst.dpDiv.width() + 4,
height: inst.dpDiv.height() + 4};
var self = this;
inst.dpDiv.empty().append(this._generateHTML(inst))
.find('iframe.ui-datepicker-cover').
css({width: dims.width, height: dims.height})
.end()
.find('button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a')
.bind('mouseout', function(){
$(this).removeClass('ui-state-hover');
if(this.className.indexOf('ui-datepicker-prev') != -1) $(this).removeClass('ui-datepicker-prev-hover');
if(this.className.indexOf('ui-datepicker-next') != -1) $(this).removeClass('ui-datepicker-next-hover');
})
.bind('mouseover', function(){
if (!self._isDisabledDatepicker( inst.inline ? inst.dpDiv.parent()[0] : inst.input[0])) {
$(this).parents('.ui-datepicker-calendar').find('a').removeClass('ui-state-hover');
$(this).addClass('ui-state-hover');
if(this.className.indexOf('ui-datepicker-prev') != -1) $(this).addClass('ui-datepicker-prev-hover');
if(this.className.indexOf('ui-datepicker-next') != -1) $(this).addClass('ui-datepicker-next-hover');
}
})
.end()
.find('.' + this._dayOverClass + ' a')
.trigger('mouseover')
.end();
var numMonths = this._getNumberOfMonths(inst);
var cols = numMonths[1];
var width = 17;
if (cols > 1) {
inst.dpDiv.addClass('ui-datepicker-multi-' + cols).css('width', (width * cols) + 'em');
} else {
inst.dpDiv.removeClass('ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4').width('');
}
inst.dpDiv[(numMonths[0] != 1 || numMonths[1] != 1 ? 'add' : 'remove') +
'Class']('ui-datepicker-multi');
inst.dpDiv[(this._get(inst, 'isRTL') ? 'add' : 'remove') +
'Class']('ui-datepicker-rtl');
if (inst.input && inst.input[0].type != 'hidden' && inst == $.datepicker._curInst)
$(inst.input[0]).focus();
},
/* Check positioning to remain on screen. */
_checkOffset: function(inst, offset, isFixed) {
var dpWidth = inst.dpDiv.outerWidth();
var dpHeight = inst.dpDiv.outerHeight();
var inputWidth = inst.input ? inst.input.outerWidth() : 0;
var inputHeight = inst.input ? inst.input.outerHeight() : 0;
var viewWidth = (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth) + $(document).scrollLeft();
var viewHeight = (window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight) + $(document).scrollTop();
offset.left -= (this._get(inst, 'isRTL') ? (dpWidth - inputWidth) : 0);
offset.left -= (isFixed && offset.left == inst.input.offset().left) ? $(document).scrollLeft() : 0;
offset.top -= (isFixed && offset.top == (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0;
// now check if datepicker is showing outside window viewport - move to a better place if so.
offset.left -= (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ? Math.abs(offset.left + dpWidth - viewWidth) : 0;
offset.top -= (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ? Math.abs(offset.top + dpHeight + inputHeight*2 - viewHeight) : 0;
return offset;
},
/* Find an object's position on the screen. */
_findPos: function(obj) {
while (obj && (obj.type == 'hidden' || obj.nodeType != 1)) {
obj = obj.nextSibling;
}
var position = $(obj).offset();
return [position.left, position.top];
},
/* Hide the date picker from view.
@param input element - the input field attached to the date picker
@param duration string - the duration over which to close the date picker */
_hideDatepicker: function(input, duration) {
var inst = this._curInst;
if (!inst || (input && inst != $.data(input, PROP_NAME)))
return;
if (inst.stayOpen)
this._selectDate('#' + inst.id, this._formatDate(inst,
inst.currentDay, inst.currentMonth, inst.currentYear));
inst.stayOpen = false;
if (this._datepickerShowing) {
duration = (duration != null ? duration : this._get(inst, 'duration'));
var showAnim = this._get(inst, 'showAnim');
var postProcess = function() {
$.datepicker._tidyDialog(inst);
};
if (duration != '' && $.effects && $.effects[showAnim])
inst.dpDiv.hide(showAnim, $.datepicker._get(inst, 'showOptions'),
duration, postProcess);
else
inst.dpDiv[(duration == '' ? 'hide' : (showAnim == 'slideDown' ? 'slideUp' :
(showAnim == 'fadeIn' ? 'fadeOut' : 'hide')))](duration, postProcess);
if (duration == '')
this._tidyDialog(inst);
var onClose = this._get(inst, 'onClose');
if (onClose)
onClose.apply((inst.input ? inst.input[0] : null),
[(inst.input ? inst.input.val() : ''), inst]); // trigger custom callback
this._datepickerShowing = false;
this._lastInput = null;
if (this._inDialog) {
this._dialogInput.css({ position: 'absolute', left: '0', top: '-100px' });
if ($.blockUI) {
$.unblockUI();
$('body').append(this.dpDiv);
}
}
this._inDialog = false;
}
this._curInst = null;
},
/* Tidy up after a dialog display. */
_tidyDialog: function(inst) {
inst.dpDiv.removeClass(this._dialogClass).unbind('.ui-datepicker-calendar');
},
/* Close date picker if clicked elsewhere. */
_checkExternalClick: function(event) {
if (!$.datepicker._curInst)
return;
var $target = $(event.target);
if (($target.parents('#' + $.datepicker._mainDivId).length == 0) &&
!$target.hasClass($.datepicker.markerClassName) &&
!$target.hasClass($.datepicker._triggerClass) &&
$.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI))
$.datepicker._hideDatepicker(null, '');
},
/* Adjust one of the date sub-fields. */
_adjustDate: function(id, offset, period) {
var target = $(id);
var inst = this._getInst(target[0]);
if (this._isDisabledDatepicker(target[0])) {
return;
}
this._adjustInstDate(inst, offset +
(period == 'M' ? this._get(inst, 'showCurrentAtPos') : 0), // undo positioning
period);
this._updateDatepicker(inst);
},
/* Action for current link. */
_gotoToday: function(id) {
var target = $(id);
var inst = this._getInst(target[0]);
if (this._get(inst, 'gotoCurrent') && inst.currentDay) {
inst.selectedDay = inst.currentDay;
inst.drawMonth = inst.selectedMonth = inst.currentMonth;
inst.drawYear = inst.selectedYear = inst.currentYear;
}
else {
var date = new Date();
inst.selectedDay = date.getDate();
inst.drawMonth = inst.selectedMonth = date.getMonth();
inst.drawYear = inst.selectedYear = date.getFullYear();
}
this._notifyChange(inst);
this._adjustDate(target);
},
/* Action for selecting a new month/year. */
_selectMonthYear: function(id, select, period) {
var target = $(id);
var inst = this._getInst(target[0]);
inst._selectingMonthYear = false;
inst['selected' + (period == 'M' ? 'Month' : 'Year')] =
inst['draw' + (period == 'M' ? 'Month' : 'Year')] =
parseInt(select.options[select.selectedIndex].value,10);
this._notifyChange(inst);
this._adjustDate(target);
},
/* Restore input focus after not changing month/year. */
_clickMonthYear: function(id) {
var target = $(id);
var inst = this._getInst(target[0]);
if (inst.input && inst._selectingMonthYear && !$.browser.msie)
inst.input[0].focus();
inst._selectingMonthYear = !inst._selectingMonthYear;
},
/* Action for selecting a day. */
_selectDay: function(id, month, year, td) {
var target = $(id);
if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) {
return;
}
var inst = this._getInst(target[0]);
inst.selectedDay = inst.currentDay = $('a', td).html();
inst.selectedMonth = inst.currentMonth = month;
inst.selectedYear = inst.currentYear = year;
if (inst.stayOpen) {
inst.endDay = inst.endMonth = inst.endYear = null;
}
this._selectDate(id, this._formatDate(inst,
inst.currentDay, inst.currentMonth, inst.currentYear));
if (inst.stayOpen) {
inst.rangeStart = this._daylightSavingAdjust(
new Date(inst.currentYear, inst.currentMonth, inst.currentDay));
this._updateDatepicker(inst);
}
},
/* Erase the input field and hide the date picker. */
_clearDate: function(id) {
var target = $(id);
var inst = this._getInst(target[0]);
inst.stayOpen = false;
inst.endDay = inst.endMonth = inst.endYear = inst.rangeStart = null;
this._selectDate(target, '');
},
/* Update the input field with the selected date. */
_selectDate: function(id, dateStr) {
var target = $(id);
var inst = this._getInst(target[0]);
dateStr = (dateStr != null ? dateStr : this._formatDate(inst));
if (inst.input)
inst.input.val(dateStr);
this._updateAlternate(inst);
var onSelect = this._get(inst, 'onSelect');
if (onSelect)
onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); // trigger custom callback
else if (inst.input)
inst.input.trigger('change'); // fire the change event
if (inst.inline)
this._updateDatepicker(inst);
else if (!inst.stayOpen) {
this._hideDatepicker(null, this._get(inst, 'duration'));
this._lastInput = inst.input[0];
if (typeof(inst.input[0]) != 'object')
inst.input[0].focus(); // restore focus
this._lastInput = null;
}
},
/* Update any alternate field to synchronise with the main field. */
_updateAlternate: function(inst) {
var altField = this._get(inst, 'altField');
if (altField) { // update alternate field too
var altFormat = this._get(inst, 'altFormat') || this._get(inst, 'dateFormat');
var date = this._getDate(inst);
dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst));
$(altField).each(function() { $(this).val(dateStr); });
}
},
/* Set as beforeShowDay function to prevent selection of weekends.
@param date Date - the date to customise
@return [boolean, string] - is this date selectable?, what is its CSS class? */
noWeekends: function(date) {
var day = date.getDay();
return [(day > 0 && day < 6), ''];
},
/* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
@param date Date - the date to get the week for
@return number - the number of the week within the year that contains this date */
iso8601Week: function(date) {
var checkDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
var firstMon = new Date(checkDate.getFullYear(), 1 - 1, 4); // First week always contains 4 Jan
var firstDay = firstMon.getDay() || 7; // Day of week: Mon = 1, ..., Sun = 7
firstMon.setDate(firstMon.getDate() + 1 - firstDay); // Preceding Monday
if (firstDay < 4 && checkDate < firstMon) { // Adjust first three days in year if necessary
checkDate.setDate(checkDate.getDate() - 3); // Generate for previous year
return $.datepicker.iso8601Week(checkDate);
} else if (checkDate > new Date(checkDate.getFullYear(), 12 - 1, 28)) { // Check last three days in year
firstDay = new Date(checkDate.getFullYear() + 1, 1 - 1, 4).getDay() || 7;
if (firstDay > 4 && (checkDate.getDay() || 7) < firstDay - 3) { // Adjust if necessary
return 1;
}
}
return Math.floor(((checkDate - firstMon) / 86400000) / 7) + 1; // Weeks to given date
},
/* Parse a string value into a date object.
See formatDate below for the possible formats.
@param format string - the expected format of the date
@param value string - the date in the above format
@param settings Object - attributes include:
shortYearCutoff number - the cutoff year for determining the century (optional)
dayNamesShort string[7] - abbreviated names of the days from Sunday (optional)
dayNames string[7] - names of the days from Sunday (optional)
monthNamesShort string[12] - abbreviated names of the months (optional)
monthNames string[12] - names of the months (optional)
@return Date - the extracted date value or null if value is blank */
parseDate: function (format, value, settings) {
if (format == null || value == null)
throw 'Invalid arguments';
value = (typeof value == 'object' ? value.toString() : value + '');
if (value == '')
return null;
var shortYearCutoff = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff;
var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort;
var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames;
var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort;
var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames;
var year = -1;
var month = -1;
var day = -1;
var doy = -1;
var literal = false;
// Check whether a format character is doubled
var lookAhead = function(match) {
var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match);
if (matches)
iFormat++;
return matches;
};
// Extract a number from the string value
var getNumber = function(match) {
lookAhead(match);
var origSize = (match == '@' ? 14 : (match == 'y' ? 4 : (match == 'o' ? 3 : 2)));
var size = origSize;
var num = 0;
while (size > 0 && iValue < value.length &&
value.charAt(iValue) >= '0' && value.charAt(iValue) <= '9') {
num = num * 10 + parseInt(value.charAt(iValue++),10);
size--;
}
if (size == origSize)
throw 'Missing number at position ' + iValue;
return num;
};
// Extract a name from the string value and convert to an index
var getName = function(match, shortNames, longNames) {
var names = (lookAhead(match) ? longNames : shortNames);
var size = 0;
for (var j = 0; j < names.length; j++)
size = Math.max(size, names[j].length);
var name = '';
var iInit = iValue;
while (size > 0 && iValue < value.length) {
name += value.charAt(iValue++);
for (var i = 0; i < names.length; i++)
if (name == names[i])
return i + 1;
size--;
}
throw 'Unknown name at position ' + iInit;
};
// Confirm that a literal character matches the string value
var checkLiteral = function() {
if (value.charAt(iValue) != format.charAt(iFormat))
throw 'Unexpected literal at position ' + iValue;
iValue++;
};
var iValue = 0;
for (var iFormat = 0; iFormat < format.length; iFormat++) {
if (literal)
if (format.charAt(iFormat) == "'" && !lookAhead("'"))
literal = false;
else
checkLiteral();
else
switch (format.charAt(iFormat)) {
case 'd':
day = getNumber('d');
break;
case 'D':
getName('D', dayNamesShort, dayNames);
break;
case 'o':
doy = getNumber('o');
break;
case 'm':
month = getNumber('m');
break;
case 'M':
month = getName('M', monthNamesShort, monthNames);
break;
case 'y':
year = getNumber('y');
break;
case '@':
var date = new Date(getNumber('@'));
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
break;
case "'":
if (lookAhead("'"))
checkLiteral();
else
literal = true;
break;
default:
checkLiteral();
|
if (year == -1)
year = new Date().getFullYear();
else if (year < 100)
year += new Date().getFullYear() - new Date().getFullYear() % 100 +
(year <= shortYearCutoff ? 0 : -100);
if (doy > -1) {
month = 1;
day = doy;
do {
var dim = this._getDaysInMonth(year, month - 1);
if (day <= dim)
break;
month++;
day -= dim;
} while (true);
}
var date = this._daylightSavingAdjust(new Date(year, month - 1, day));
if (date.getFullYear() != year || date.getMonth() + 1 != month || date.getDate() != day)
throw 'Invalid date'; // E.g. 31/02/*
return date;
},
/* Standard date formats. */
ATOM: 'yy-mm-dd', // RFC 3339 (ISO 8601)
COOKIE: 'D, dd M yy',
ISO_8601: 'yy-mm-dd',
RFC_822: 'D, d M y',
RFC_850: 'DD, dd-M-y',
RFC_1036: 'D, d M y',
RFC_1123: 'D, d M yy',
RFC_2822: 'D, d M yy',
RSS: 'D, d M y', // RFC 822
TIMESTAMP: '@',
W3C: 'yy-mm-dd', // ISO 8601
/* Format a date object into a string value.
The format can be combinations of the following:
d - day of month (no leading zero)
dd - day of month (two digit)
o - day of year (no leading zeros)
oo - day of year (three digit)
D - day name short
DD - day name long
m - month of year (no leading zero)
mm - month of year (two digit)
M - month name short
MM - month name long
y - year (two digit)
yy - year (four digit)
@ - Unix timestamp (ms since 01/01/1970)
'...' - literal text
'' - single quote
@param format string - the desired format of the date
@param date Date - the date value to format
@param settings Object - attributes include:
dayNamesShort string[7] - abbreviated names of the days from Sunday (optional)
dayNames string[7] - names of the days from Sunday (optional)
monthNamesShort string[12] - abbreviated names of the months (optional)
monthNames string[12] - names of the months (optional)
@return string - the date in the above format */
formatDate: function (format, date, settings) {
if (!date)
return '';
var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort;
var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames;
var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort;
var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames;
// Check whether a format character is doubled
var lookAhead = function(match) {
var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match);
if (matches)
iFormat++;
return matches;
};
// Format a number, with leading zero if necessary
var formatNumber = function(match, value, len) {
var num = '' + value;
if (lookAhead(match))
while (num.length < len)
num = '0' + num;
return num;
};
// Format a name, short or long as requested
var formatName = function(match, value, shortNames, longNames) {
return (lookAhead(match) ? longNames[value] : shortNames[value]);
};
var output = '';
var literal = false;
if (date)
for (var iFormat = 0; iFormat < format.length; iFormat++) {
if (literal)
if (format.charAt(iFormat) == "'" && !lookAhead("'"))
literal = false;
else
output += format.charAt(iFormat);
else
switch (format.charAt(iFormat)) {
case 'd':
output += formatNumber('d', date.getDate(), 2);
break;
case 'D':
output += formatName('D', date.getDay(), dayNamesShort, dayNames);
break;
case 'o':
var doy = date.getDate();
for (var m = date.getMonth() - 1; m >= 0; m--)
doy += this._getDaysInMonth(date.getFullYear(), m);
output += formatNumber('o', doy, 3);
break;
case 'm':
output += formatNumber('m', date.getMonth() + 1, 2);
break;
case 'M':
output += formatName('M', date.getMonth(), monthNamesShort, monthNames);
break;
case 'y':
output += (lookAhead('y') ? date.getFullYear() :
(date.getYear() % 100 < 10 ? '0' : '') + date.getYear() % 100);
break;
case '@':
output += date.getTime();
break;
case "'":
if (lookAhead("'"))
output += "'";
else
literal = true;
break;
default:
output += format.charAt(iFormat);
}
}
return output;
},
/* Extract all possible characters from the date format. */
_possibleChars: function (format) {
var chars = '';
var literal = false;
for (var iFormat = 0; iFormat < format.length; iFormat++)
if (literal)
if (format.charAt(iFormat) == "'" && !lookAhead("'"))
literal = false;
else
chars += format.charAt(iFormat);
else
switch (format.charAt(iFormat)) {
case 'd': case 'm': case 'y': case '@':
chars += '0123456789';
break;
case 'D': case 'M':
return null; // Accept anything
case "'":
if (lookAhead("'"))
chars += "'";
else
literal = true;
break;
default:
chars += format.charAt(iFormat);
}
return chars;
},
/* Get a setting value, defaulting if necessary. */
_get: function(inst, name) {
return inst.settings[name] !== undefined ?
inst.settings[name] : this._defaults[name];
},
/* Parse existing date and initialise date picker. */
_setDateFromField: function(inst) {
var dateFormat = this._get(inst, 'dateFormat');
var dates = inst.input ? inst.input.val() : null;
inst.endDay = inst.endMonth = inst.endYear = null;
var date = defaultDate = this._getDefaultDate(inst);
var settings = this._getFormatConfig(inst);
try {
date = this.parseDate(dateFormat, dates, settings) || defaultDate;
} catch (event) {
this.log(event);
date = defaultDate;
}
inst.selectedDay = date.getDate();
inst.drawMonth = inst.selectedMonth = date.getMonth();
inst.drawYear = inst.selectedYear = date.getFullYear();
inst.currentDay = (dates ? date.getDate() : 0);
inst.currentMonth = (dates ? date.getMonth() : 0);
inst.currentYear = (dates ? date.getFullYear() : 0);
this._adjustInstDate(inst);
},
/* Retrieve the default date shown on opening. */
_getDefaultDate: function(inst) {
var date = this._determineDate(this._get(inst, 'defaultDate'), new Date());
var minDate = this._getMinMaxDate(inst, 'min', true);
var maxDate = this._getMinMaxDate(inst, 'max');
date = (minDate && date < minDate ? minDate : date);
date = (maxDate && date > maxDate ? maxDate : date);
return date;
},
/* A date may be specified as an exact value or a relative one. */
_determineDate: function(date, defaultDate) {
var offsetNumeric = function(offset) {
var date = new Date();
date.setDate(date.getDate() + offset);
return date;
};
var offsetString = function(offset, getDaysInMonth) {
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth();
var day = date.getDate();
var pattern = /([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g;
var matches = pattern.exec(offset);
while (matches) {
switch (matches[2] || 'd') {
case 'd' : case 'D' :
day += parseInt(matches[1],10); break;
case 'w' : case 'W' :
day += parseInt(matches[1],10) * 7; break;
case 'm' : case 'M' :
month += parseInt(matches[1],10);
day = Math.min(day, getDaysInMonth(year, month));
break;
case 'y': case 'Y' :
year += parseInt(matches[1],10);
day = Math.min(day, getDaysInMonth(year, month));
break;
}
matches = pattern.exec(offset);
}
return new Date(year, month, day);
};
date = (date == null ? defaultDate :
(typeof date == 'string' ? offsetString(date, this._getDaysInMonth) :
(typeof date == 'number' ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : date)));
date = (date && date.toString() == 'Invalid Date' ? defaultDate : date);
if (date) {
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
}
return this._daylightSavingAdjust(date);
},
/* Handle switch to/from daylight saving.
Hours may be non-zero on daylight saving cut-over:
> 12 when midnight changeover, but then cannot generate
midnight datetime, so jump to 1AM, otherwise reset.
@param date (Date) the date to check
@return (Date) the corrected date */
_daylightSavingAdjust: function(date) {
if (!date) return null;
date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0);
return date;
},
/* Set the date(s) directly. */
_setDate: function(inst, date, endDate) {
var clear = !(date);
var origMonth = inst.selectedMonth;
var origYear = inst.selectedYear;
date = this._determineDate(date, new Date());
inst.selectedDay = inst.currentDay = date.getDate();
inst.drawMonth = inst.selectedMonth = inst.currentMonth = date.getMonth();
inst.drawYear = inst.selectedYear = inst.currentYear = date.getFullYear();
if (origMonth != inst.selectedMonth || origYear != inst.selectedYear)
this._notifyChange(inst);
this._adjustInstDate(inst);
if (inst.input) {
inst.input.val(clear ? '' : this._formatDate(inst));
}
},
/* Retrieve the date(s) directly. */
_getDate: function(inst) {
var startDate = (!inst.currentYear || (inst.input && inst.input.val() == '') ? null :
this._daylightSavingAdjust(new Date(
inst.currentYear, inst.currentMonth, inst.currentDay)));
return startDate;
},
/* Generate the HTML for the current state of the date picker. */
_generateHTML: function(inst) {
var today = new Date();
today = this._daylightSavingAdjust(
new Date(today.getFullYear(), today.getMonth(), today.getDate())); // clear time
var isRTL = this._get(inst, 'isRTL');
var showButtonPanel = this._get(inst, 'showButtonPanel');
var hideIfNoPrevNext = this._get(inst, 'hideIfNoPrevNext');
var navigationAsDateFormat = this._get(inst, 'navigationAsDateFormat');
var numMonths = this._getNumberOfMonths(inst);
var showCurrentAtPos = this._get(inst, 'showCurrentAtPos');
var stepMonths = this._get(inst, 'stepMonths');
var stepBigMonths = this._get(inst, 'stepBigMonths');
var isMultiMonth = (numMonths[0] != 1 || numMonths[1] != 1);
var currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) :
new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
var minDate = this._getMinMaxDate(inst, 'min', true);
var maxDate = this._getMinMaxDate(inst, 'max');
var drawMonth = inst.drawMonth - showCurrentAtPos;
var drawYear = inst.drawYear;
if (drawMonth < 0) {
drawMonth += 12;
drawYear--;
}
if (maxDate) {
var maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(),
maxDate.getMonth() - numMonths[1] + 1, maxDate.getDate()));
maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw);
while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) {
drawMonth--;
if (drawMonth < 0) {
drawMonth = 11;
drawYear--;
}
}
}
inst.drawMonth = drawMonth;
inst.drawYear = drawYear;
var prevText = this._get(inst, 'prevText');
prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText,
this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)),
this._getFormatConfig(inst)));
var prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ?
'<a class="ui-datepicker-prev ui-corner-all" onclick="DP_jQuery.datepicker._adjustDate(\'#' + inst.id + '\', -' + stepMonths + ', \'M\');"' +
' title="' + prevText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>' :
(hideIfNoPrevNext ? '' : '<a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="'+ prevText +'"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>'));
var nextText = this._get(inst, 'nextText');
nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText,
this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)),
this._getFormatConfig(inst)));
var next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ?
'<a class="ui-datepicker-next ui-corner-all" onclick="DP_jQuery.datepicker._adjustDate(\'#' + inst.id + '\', +' + stepMonths + ', \'M\');"' +
' title="' + nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>' :
(hideIfNoPrevNext ? '' : '<a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="'+ nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>'));
var currentText = this._get(inst, 'currentText');
var gotoDate = (this._get(inst, 'gotoCurrent') && inst.currentDay ? currentDate : today);
currentText = (!navigationAsDateFormat ? currentText :
this.formatDate(currentText, gotoDate, this._getFormatConfig(inst)));
var controls = (!inst.inline ? '<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" onclick="DP_jQuery.datepicker._hideDatepicker();">' + this._get(inst, 'closeText') + '</button>' : '');
var buttonPanel = (showButtonPanel) ? '<div class="ui-datepicker-buttonpane ui-widget-content">' + (isRTL ? controls : '') +
(this._isInRange(inst, gotoDate) ? '<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" onclick="DP_jQuery.datepicker._gotoToday(\'#' + inst.id + '\');"' +
'>' + currentText + '</button>' : '') + (isRTL ? '' : controls) + '</div>' : '';
var firstDay = parseInt(this._get(inst, 'firstDay'),10);
firstDay = (isNaN(firstDay) ? 0 : firstDay);
var dayNames = this._get(inst, 'dayNames');
var dayNamesShort = this._get(inst, 'dayNamesShort');
var dayNamesMin = this._get(inst, 'dayNamesMin');
var monthNames = this._get(inst, 'monthNames');
var monthNamesShort = this._get(inst, 'monthNamesShort');
var beforeShowDay = this._get(inst, 'beforeShowDay');
var showOtherMonths = this._get(inst, 'showOtherMonths');
var calculateWeek = this._get(inst, 'calculateWeek') || this.iso8601Week;
var endDate = inst.endDay ? this._daylightSavingAdjust(
new Date(inst.endYear, inst.endMonth, inst.endDay)) : currentDate;
var defaultDate = this._getDefaultDate(inst);
var html = '';
for (var row = 0; row < numMonths[0]; row++) {
var group = '';
for (var col = 0; col < numMonths[1]; col++) {
var selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay));
var cornerClass = ' ui-corner-all';
var calender = '';
if (isMultiMonth) {
calender += '<div class="ui-datepicker-group ui-datepicker-group-';
switch (col) {
case 0: calender += 'first'; cornerClass = ' ui-corner-' + (isRTL ? 'right' : 'left'); break;
case numMonths[1]-1: calender += 'last'; cornerClass = ' ui-corner-' + (isRTL ? 'left' : 'right'); break;
default: calender += 'middle'; cornerClass = ''; break;
}
calender += '">';
}
calender += '<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix' + cornerClass + '">' +
(/all|left/.test(cornerClass) && row == 0 ? (isRTL ? next : prev) : '') +
(/all|right/.test(cornerClass) && row == 0 ? (isRTL ? prev : next) : '') +
this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate,
selectedDate, row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers
'</div><table class="ui-datepicker-calendar"><thead>' +
'<tr>';
var thead = '';
for (var dow = 0; dow < 7; dow++) { // days of the week
var day = (dow + firstDay) % 7;
thead += '<th' + ((dow + firstDay + 6) % 7 >= 5 ? ' class="ui-datepicker-week-end"' : '') + '>' +
'<span title="' + dayNames[day] + '">' + dayNamesMin[day] + '</span></th>';
}
calender += thead + '</tr></thead><tbody>';
var daysInMonth = this._getDaysInMonth(drawYear, drawMonth);
if (drawYear == inst.selectedYear && drawMonth == inst.selectedMonth)
inst.selectedDay = Math.min(inst.selectedDay, daysInMonth);
var leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7;
var numRows = (isMultiMonth ? 6 : Math.ceil((leadDays + daysInMonth) / 7)); // calculate the number of rows to generate
var printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays));
for (var dRow = 0; dRow < numRows; dRow++) { // create date picker rows
calender += '<tr>';
var tbody = '';
for (var dow = 0; dow < 7; dow++) { // create date picker days
var daySettings = (beforeShowDay ?
beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, '']);
var otherMonth = (printDate.getMonth() != drawMonth);
var unselectable = otherMonth || !daySettings[0] ||
(minDate && printDate < minDate) || (maxDate && printDate > maxDate);
tbody += '<td class="' +
((dow + firstDay + 6) % 7 >= 5 ? ' ui-datepicker-week-end' : '') + // highlight weekends
(otherMonth ? ' ui-datepicker-other-month' : '') + // highlight days from other months
((printDate.getTime() == selectedDate.getTime() && drawMonth == inst.selectedMonth && inst._keyEvent) || // user pressed key
(defaultDate.getTime() == printDate.getTime() && defaultDate.getTime() == selectedDate.getTime()) ?
// or defaultDate is current printedDate and defaultDate is selectedDate
' ' + this._dayOverClass : '') + // highlight selected day
(unselectable ? ' ' + this._unselectableClass + ' ui-state-disabled': '') + // highlight unselectable days
(otherMonth && !showOtherMonths ? '' : ' ' + daySettings[1] + // highlight custom dates
(printDate.getTime() >= currentDate.getTime() && printDate.getTime() <= endDate.getTime() ? // in current range
' ' + this._currentClass : '') + // highlight selected day
(printDate.getTime() == today.getTime() ? ' ui-datepicker-today' : '')) + '"' + // highlight today (if different)
((!otherMonth || showOtherMonths) && daySettings[2] ? ' title="' + daySettings[2] + '"' : '') + // cell title
(unselectable ? '' : ' onclick="DP_jQuery.datepicker._selectDay(\'#' +
inst.id + '\',' + drawMonth + ',' + drawYear + ', this);return false;"') + '>' + // actions
(otherMonth ? (showOtherMonths ? printDate.getDate() : ' ') : // display for other months
(unselectable ? '<span class="ui-state-default">' + printDate.getDate() + '</span>' : '<a class="ui-state-default' +
(printDate.getTime() == today.getTime() ? ' ui-state-highlight' : '') +
(printDate.getTime() >= currentDate.getTime() && printDate.getTime() <= endDate.getTime() ? // in current range
' ui-state-active' : '') + // highlight selected day
'" href="#">' + printDate.getDate() + '</a>')) + '</td>'; // display for this month
printDate.setDate(printDate.getDate() + 1);
printDate = this._daylightSavingAdjust(printDate);
}
calender += tbody + '</tr>';
}
drawMonth++;
if (drawMonth > 11) {
drawMonth = 0;
drawYear++;
}
calender += '</tbody></table>' + (isMultiMonth ? '</div>' +
((numMonths[0] > 0 && col == numMonths[1]-1) ? '<div class="ui-datepicker-row-break"></div>' : '') : '');
group += calender;
}
html += group;
}
html += buttonPanel + ($.browser.msie && parseInt($.browser.version,10) < 7 && !inst.inline ?
'<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>' : '');
inst._keyEvent = false;
return html;
},
/* Generate the month and year header. */
_generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate,
selectedDate, secondary, monthNames, monthNamesShort) {
minDate = (inst.rangeStart && minDate && selectedDate < minDate ? selectedDate : minDate);
var changeMonth = this._get(inst, 'changeMonth');
var changeYear = this._get(inst, 'changeYear');
var showMonthAfterYear = this._get(inst, 'showMonthAfterYear');
var html = '<div class="ui-datepicker-title">';
var monthHtml = '';
// month selection
if (secondary || !changeMonth)
monthHtml += '<span class="ui-datepicker-month">' + monthNames[drawMonth] + '</span> ';
else {
var inMinYear = (minDate && minDate.getFullYear() == drawYear);
var inMaxYear = (maxDate && maxDate.getFullYear() == drawYear);
monthHtml += '<select class="ui-datepicker-month" ' +
'onchange="DP_jQuery.datepicker._selectMonthYear(\'#' + inst.id + '\', this, \'M\');" ' +
'onclick="DP_jQuery.datepicker._clickMonthYear(\'#' + inst.id + '\');"' +
'>';
for (var month = 0; month < 12; month++) {
if ((!inMinYear || month >= minDate.getMonth()) &&
(!inMaxYear || month <= maxDate.getMonth()))
monthHtml += '<option value="' + month + '"' +
(month == drawMonth ? ' selected="selected"' : '') +
'>' + monthNamesShort[month] + '</option>';
}
monthHtml += '</select>';
}
if (!showMonthAfterYear)
html += monthHtml + ((secondary || changeMonth || changeYear) && (!(changeMonth && changeYear)) ? ' ' : '');
// year selection
if (secondary || !changeYear)
html += '<span class="ui-datepicker-year">' + drawYear + '</span>';
else {
// determine range of years to display
var years = this._get(inst, 'yearRange').split(':');
var year = 0;
var endYear = 0;
if (years.length != 2) {
year = drawYear - 10;
endYear = drawYear + 10;
} else if (years[0].charAt(0) == '+' || years[0].charAt(0) == '-') {
year = drawYear + parseInt(years[0], 10);
endYear = drawYear + parseInt(years[1], 10);
} else {
year = parseInt(years[0], 10);
endYear = parseInt(years[1], 10);
}
year = (minDate ? Math.max(year, minDate.getFullYear()) : year);
endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear);
html += '<select class="ui-datepicker-year" ' +
'onchange="DP_jQuery.datepicker._selectMonthYear(\'#' + inst.id + '\', this, \'Y\');" ' +
'onclick="DP_jQuery.datepicker._clickMonthYear(\'#' + inst.id + '\');"' +
'>';
for (; year <= endYear; year++) {
html += '<option value="' + year + '"' +
(year == drawYear ? ' selected="selected"' : '') +
'>' + year + '</option>';
}
html += '</select>';
}
if (showMonthAfterYear)
html += (secondary || changeMonth || changeYear ? ' ' : '') + monthHtml;
html += '</div>'; // Close datepicker_header
return html;
},
/* Adjust one of the date sub-fields. */
_adjustInstDate: function(inst, offset, period) {
var year = inst.drawYear + (period == 'Y' ? offset : 0);
var month = inst.drawMonth + (period == 'M' ? offset : 0);
var day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) +
(period == 'D' ? offset : 0);
var date = this._daylightSavingAdjust(new Date(year, month, day));
// ensure it is within the bounds set
var minDate = this._getMinMaxDate(inst, 'min', true);
var maxDate = this._getMinMaxDate(inst, 'max');
date = (minDate && date < minDate ? minDate : date);
date = (maxDate && date > maxDate ? maxDate : date);
inst.selectedDay = date.getDate();
inst.drawMonth = inst.selectedMonth = date.getMonth();
inst.drawYear = inst.selectedYear = date.getFullYear();
if (period == 'M' || period == 'Y')
this._notifyChange(inst);
},
/* Notify change of month/year. */
_notifyChange: function(inst) {
var onChange = this._get(inst, 'onChangeMonthYear');
if (onChange)
onChange.apply((inst.input ? inst.input[0] : null),
[inst.selectedYear, inst.selectedMonth + 1, inst]);
},
/* Determine the number of months to show. */
_getNumberOfMonths: function(inst) {
var numMonths = this._get(inst, 'numberOfMonths');
return (numMonths == null ? [1, 1] : (typeof numMonths == 'number' ? [1, numMonths] : numMonths));
},
/* Determine the current maximum date - ensure no time components are set - may be overridden for a range. */
_getMinMaxDate: function(inst, minMax, checkRange) {
var date = this._determineDate(this._get(inst, minMax + 'Date'), null);
return (!checkRange || !inst.rangeStart ? date :
(!date || inst.rangeStart > date ? inst.rangeStart : date));
},
/* Find the number of days in a given month. */
_getDaysInMonth: function(year, month) {
return 32 - new Date(year, month, 32).getDate();
},
/* Find the day of the week of the first of a month. */
_getFirstDayOfMonth: function(year, month) {
return new Date(year, month, 1).getDay();
},
/* Determines if we should allow a "next/prev" month display change. */
_canAdjustMonth: function(inst, offset, curYear, curMonth) {
var numMonths = this._getNumberOfMonths(inst);
var date = this._daylightSavingAdjust(new Date(
curYear, curMonth + (offset < 0 ? offset : numMonths[1]), 1));
if (offset < 0)
date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth()));
return this._isInRange(inst, date);
},
/* Is the given date in the accepted range? */
_isInRange: function(inst, date) {
// during range selection, use minimum of selected date and range start
var newMinDate = (!inst.rangeStart ? null : this._daylightSavingAdjust(
new Date(inst.selectedYear, inst.selectedMonth, inst.selectedDay)));
newMinDate = (newMinDate && inst.rangeStart < newMinDate ? inst.rangeStart : newMinDate);
var minDate = newMinDate || this._getMinMaxDate(inst, 'min');
var maxDate = this._getMinMaxDate(inst, 'max');
return ((!minDate || date >= minDate) && (!maxDate || date <= maxDate));
},
/* Provide the configuration settings for formatting/parsing. */
_getFormatConfig: function(inst) {
var shortYearCutoff = this._get(inst, 'shortYearCutoff');
shortYearCutoff = (typeof shortYearCutoff != 'string' ? shortYearCutoff :
new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10));
return {shortYearCutoff: shortYearCutoff,
dayNamesShort: this._get(inst, 'dayNamesShort'), dayNames: this._get(inst, 'dayNames'),
monthNamesShort: this._get(inst, 'monthNamesShort'), monthNames: this._get(inst, 'monthNames')};
},
/* Format the given date for display. */
_formatDate: function(inst, day, month, year) {
if (!day) {
inst.currentDay = inst.selectedDay;
inst.currentMonth = inst.selectedMonth;
inst.currentYear = inst.selectedYear;
}
var date = (day ? (typeof day == 'object' ? day :
this._daylightSavingAdjust(new Date(year, month, day))) :
this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
return this.formatDate(this._get(inst, 'dateFormat'), date, this._getFormatConfig(inst));
}
});
/* jQuery extend now ignores nulls! */
function extendRemove(target, props) {
$.extend(target, props);
for (var name in props)
if (props[name] == null || props[name] == undefined)
target[name] = props[name];
return target;
};
/* Determine whether an object is an array. */
function isArray(a) {
return (a && (($.browser.safari && typeof a == 'object' && a.length) ||
(a.constructor && a.constructor.toString().match(/\Array\(\)/))));
};
/* Invoke the datepicker functionality.
@param options string - a command, optionally followed by additional parameters or
Object - settings for attaching new datepicker functionality
@return jQuery object */
$.fn.datepicker = function(options){
/* Initialise the date picker. */
if (!$.datepicker.initialized) {
$(document).mousedown($.datepicker._checkExternalClick).
find('body').append($.datepicker.dpDiv);
$.datepicker.initialized = true;
}
var otherArgs = Array.prototype.slice.call(arguments, 1);
if (typeof options == 'string' && (options == 'isDisabled' || options == 'getDate'))
return $.datepicker['_' + options + 'Datepicker'].
apply($.datepicker, [this[0]].concat(otherArgs));
if (options == 'option' && arguments.length == 2 && typeof arguments[1] == 'string')
return $.datepicker['_' + options + 'Datepicker'].
apply($.datepicker, [this[0]].concat(otherArgs));
return this.each(function() {
typeof options == 'string' ?
$.datepicker['_' + options + 'Datepicker'].
apply($.datepicker, [this].concat(otherArgs)) :
$.datepicker._attachDatepicker(this, options);
});
};
$.datepicker = new Datepicker(); // singleton instance
$.datepicker.initialized = false;
$.datepicker.uuid = new Date().getTime();
$.datepicker.version = "1.7.3";
// Workaround for #4055
// Add another global to avoid noConflict issues with inline event handlers
window.DP_jQuery = $;
})(jQuery);
|
}
}
|
country.repository.ts
|
import { EntityRepository, Repository } from 'typeorm';
import { Country } from './country.entity';
|
@EntityRepository(Country)
export class CountryRepository extends Repository<Country> {}
|
|
volume_test.go
|
// Code generated by "go generate gonum.org/v1/gonum/unit; DO NOT EDIT.
// Copyright ©2019 The Gonum Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package unit
import (
"fmt"
"testing"
)
func T
|
t *testing.T) {
for _, test := range []struct {
value Volume
format string
want string
}{
{1.23456789, "%v", "1.23456789 m^3"},
{1.23456789, "%.1v", "1 m^3"},
{1.23456789, "%20.1v", " 1 m^3"},
{1.23456789, "%20v", " 1.23456789 m^3"},
{1.23456789, "%1v", "1.23456789 m^3"},
{1.23456789, "%#v", "unit.Volume(1.23456789)"},
{1.23456789, "%s", "%!s(unit.Volume=1.23456789 m^3)"},
} {
got := fmt.Sprintf(test.format, test.value)
if got != test.want {
t.Errorf("Format %q %v: got: %q want: %q", test.format, float64(test.value), got, test.want)
}
}
}
|
estVolumeFormat(
|
views.py
|
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from .models import UserProfile
from .forms import ProfileForm
def profile(request, pk):
profile = UserProfile.objects.get(id=pk)
context = {
'profile': profile
}
return render(request, 'account/profile.html', context)
def
|
(request, pk):
profile = UserProfile.objects.get(id=pk)
forms = ProfileForm(instance=profile)
if request.method == 'POST':
forms = ProfileForm(request.POST, request.FILES, instance=profile)
if forms.is_valid():
forms.save()
return redirect('home')
context = {
'forms': forms
}
return render(request, 'account/update-profile.html', context)
|
update_profile
|
blobs.rs
|
/*
Copyright 2021 JFrog 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.
*/
use crate::artifact_service::handlers::get_artifact;
use crate::artifact_service::storage::ArtifactStorage;
use crate::docker::error_util::{RegistryError, RegistryErrorCode};
use crate::network::client::Client;
use crate::transparency_log::log::TransparencyLog;
use futures::lock::Mutex;
use log::debug;
use std::result::Result;
use std::sync::Arc;
use warp::{http::StatusCode, Rejection, Reply};
pub async fn handle_get_blobs(
transparency_log: Arc<Mutex<TransparencyLog>>,
p2p_client: Client,
artifact_storage: ArtifactStorage,
hash: String,
) -> Result<impl Reply, Rejection> {
debug!("Getting blob with hash : {:?}", hash);
let blob_content = get_artifact(
transparency_log,
p2p_client,
&artifact_storage,
&get_namespace_specific_id(&hash),
)
.await
.map_err(|_| {
warp::reject::custom(RegistryError {
code: RegistryErrorCode::BlobUnknown,
})
})?;
Ok(warp::http::response::Builder::new()
.header("Content-Type", "application/octet-stream")
.status(StatusCode::OK)
.body(blob_content.to_vec())
.unwrap())
}
fn get_namespace_specific_id(hash: &str) -> String {
format!("DOCKER::BLOB::{}", hash)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::artifact_service::service::{Hash, HashAlgorithm};
use crate::util::test_util;
use anyhow::Context;
use futures::channel::mpsc;
use hyper::header::HeaderValue;
use libp2p::identity::Keypair;
use std::borrow::Borrow;
use std::fs::File;
use std::path::PathBuf;
const VALID_ARTIFACT_HASH: [u8; 32] = [
0x86, 0x5c, 0x8d, 0x98, 0x8b, 0xe4, 0x66, 0x9f, 0x3e, 0x48, 0xf7, 0x3b, 0x98, 0xf9, 0xbc,
0x25, 0x7, 0xbe, 0x2, 0x46, 0xea, 0x35, 0xe0, 0x9, 0x8c, 0xf6, 0x5, 0x4d, 0x36, 0x44, 0xc1,
0x4f,
];
#[test]
fn test_get_namespace_specific_id() {
let hash = "hash";
assert_eq!(
get_namespace_specific_id(hash),
format!("DOCKER::BLOB::{}", hash)
);
}
#[tokio::test]
async fn test_handle_get_blobs_unknown_in_artifact_service() {
let tmp_dir = test_util::tests::setup();
let hash = "7300a197d7deb39371d4683d60f60f2fbbfd7541837ceb2278c12014e94e657b";
let namespace_specific_id = format!("DOCKER::BLOB::{}", hash);
let transparency_log = Arc::new(Mutex::new(TransparencyLog::new(&tmp_dir).unwrap()));
transparency_log
.lock()
.await
.add_artifact(&namespace_specific_id, hash)
.unwrap();
let (sender, _) = mpsc::channel(1);
let p2p_client = Client {
sender,
local_peer_id: Keypair::generate_ed25519().public().to_peer_id(),
};
let artifact_storage = ArtifactStorage::new(&tmp_dir).unwrap();
let result = handle_get_blobs(
transparency_log,
p2p_client,
artifact_storage,
hash.to_string(),
)
.await;
assert!(result.is_err());
let rejection = result.err().unwrap();
let registry_error = rejection.find::<RegistryError>().unwrap().borrow();
assert_eq!(
*registry_error,
RegistryError {
code: RegistryErrorCode::BlobUnknown,
}
);
test_util::tests::teardown(tmp_dir);
}
#[tokio::test]
async fn test_handle_get_blobs() {
let tmp_dir = test_util::tests::setup();
let hash = "865c8d988be4669f3e48f73b98f9bc2507be0246ea35e0098cf6054d3644c14f";
let namespace_specific_id = format!("DOCKER::BLOB::{}", hash);
let transparency_log = Arc::new(Mutex::new(TransparencyLog::new(&tmp_dir).unwrap()));
transparency_log
.lock()
.await
.add_artifact(&namespace_specific_id, hash)
.unwrap();
let (sender, _) = mpsc::channel(1);
let p2p_client = Client {
sender,
local_peer_id: Keypair::generate_ed25519().public().to_peer_id(),
};
let artifact_storage = ArtifactStorage::new(&tmp_dir).unwrap();
create_artifact(&artifact_storage).unwrap();
let result = handle_get_blobs(
transparency_log,
p2p_client,
artifact_storage,
hash.to_string(),
)
.await;
assert!(result.is_ok());
let response = result.unwrap().into_response();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(
response.headers().get("Content-Type"),
Some(&HeaderValue::from_static("application/octet-stream"))
);
test_util::tests::teardown(tmp_dir);
}
fn get_file_reader() -> Result<File, anyhow::Error>
|
fn create_artifact(artifact_storage: &ArtifactStorage) -> Result<(), anyhow::Error> {
let hash = Hash::new(HashAlgorithm::SHA256, &VALID_ARTIFACT_HASH)?;
artifact_storage
.push_artifact(&mut get_file_reader()?, &hash)
.context("Error while pushing artifact")
}
}
|
{
// test artifact file in resources/test dir
let mut curr_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
curr_dir.push("tests/resources/artifact_test.json");
let path = String::from(curr_dir.to_string_lossy());
let reader = File::open(path.as_str()).unwrap();
Ok(reader)
}
|
conversion.rs
|
// Copyright 2018 The Exonum Team
// Copyright 2020 Locha Inc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use jni::objects::JString;
use jni::sys::{jbyteArray, jobjectArray};
use jni::JNIEnv;
use std::ptr;
use crate::JniResult;
/// Converts JNI `JString` into Rust `String`.
pub fn
|
<'e, V>(env: &JNIEnv<'e>, val: V) -> JniResult<String>
where
V: Into<JString<'e>>,
{
Ok(env.get_string(val.into())?.into())
}
/// Converts array of Java bytes arrays (`byte[][]`) to the vector of Rust array representation.
pub fn java_arrays_to_rust<T, F>(
env: &JNIEnv,
array: jobjectArray,
to_rust_array: F,
) -> JniResult<Vec<T>>
where
F: Fn(&JNIEnv, jbyteArray) -> JniResult<T>,
{
let num_elements = env.get_array_length(array)?;
let mut result = Vec::with_capacity(num_elements as usize);
for i in 0..num_elements {
let array_element =
env.auto_local(env.get_object_array_element(array, i)?);
let array = to_rust_array(&env, array_element.as_obj().into_inner())?;
result.push(array);
}
Ok(result)
}
/// Converts optional array of bytes into `jbyteArray`.
///
/// If `None` passed, returns null.
pub fn optional_array_to_java<B: AsRef<[u8]>>(
env: &JNIEnv,
slice: Option<B>,
) -> JniResult<jbyteArray> {
slice.map_or(Ok(ptr::null_mut() as *mut _), |slice| {
env.byte_array_from_slice(slice.as_ref())
})
}
|
convert_to_string
|
logic.go
|
package controllers
import (
"context"
"github.com/google/uuid"
crownlabsv1alpha2 "github.com/netgroup-polito/CrownLabs/operators/api/v1alpha2"
"github.com/netgroup-polito/CrownLabs/operators/pkg/instance-creation"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"time"
)
func (r *LabInstanceReconciler) CreateEnvironment(labInstance *crownlabsv1alpha2.Instance, labTemplate *crownlabsv1alpha2.Template, namespace string, name string, VMstart time.Time) error {
var user, password string
// this is added so that all resources created for this Instance are destroyed when the Instance is deleted
b := true
labiOwnerRef := []metav1.OwnerReference{
{
APIVersion: labInstance.APIVersion,
Kind: labInstance.Kind,
Name: labInstance.Name,
UID: labInstance.UID,
BlockOwnerDeletion: &b,
},
}
log := r.Log
ctx := context.TODO()
err := instance_creation.GetWebdavCredentials(r.Client, ctx, log, r.WebdavSecretName, labInstance.Namespace, &user, &password)
if err != nil {
log.Error(err, "unable to get Webdav Credentials")
} else {
log.Info("Webdav secrets obtained. Building cloud-init script." + labInstance.Name)
}
secret := instance_creation.CreateCloudInitSecret(name, namespace, user, password, r.NextcloudBaseUrl)
secret.SetOwnerReferences(labiOwnerRef)
if err := instance_creation.CreateOrUpdate(r.Client, ctx, log, secret); err != nil {
setLabInstanceStatus(r, ctx, log, "Could not create secret "+secret.Name+" in namespace "+secret.Namespace, "Warning", "SecretNotCreated", labInstance, "", "")
} else {
setLabInstanceStatus(r, ctx, log, "Secret "+secret.Name+" correctly created in namespace "+secret.Namespace, "Normal", "SecretCreated", labInstance, "", "")
}
// create Service to expose the vm
service := instance_creation.CreateService(name, namespace)
service.SetOwnerReferences(labiOwnerRef)
if err := instance_creation.CreateOrUpdate(r.Client, ctx, log, service); err != nil {
setLabInstanceStatus(r, ctx, log, "Could not create service "+service.Name+" in namespace "+service.Namespace, "Warning", "ServiceNotCreated", labInstance, "", "")
return err
} else {
setLabInstanceStatus(r, ctx, log, "Service "+service.Name+" correctly created in namespace "+service.Namespace, "Normal", "ServiceCreated", labInstance, "", "")
|
// create Ingress to manage the service
ingress := instance_creation.CreateIngress(name, namespace, service, urlUUID, r.WebsiteBaseUrl)
ingress.SetOwnerReferences(labiOwnerRef)
if err := instance_creation.CreateOrUpdate(r.Client, ctx, log, ingress); err != nil {
setLabInstanceStatus(r, ctx, log, "Could not create ingress "+ingress.Name+" in namespace "+ingress.Namespace, "Warning", "IngressNotCreated", labInstance, "", "")
return err
} else {
setLabInstanceStatus(r, ctx, log, "Ingress "+ingress.Name+" correctly created in namespace "+ingress.Namespace, "Normal", "IngressCreated", labInstance, "", "")
}
if err := r.createOAUTHLogic(name, labInstance, namespace, labiOwnerRef, urlUUID); err != nil {
return err
}
// create VirtualMachineInstance
vmi, err := instance_creation.CreateVirtualMachineInstance(name, namespace, labTemplate.Spec.EnvironmentList[0], labInstance.Name, secret.Name)
if err != nil {
return err
}
vmi.SetOwnerReferences(labiOwnerRef)
if err := instance_creation.CreateOrUpdate(r.Client, ctx, log, vmi); err != nil {
setLabInstanceStatus(r, ctx, log, "Could not create vmi "+vmi.Name+" in namespace "+vmi.Namespace, "Warning", "VmiNotCreated", labInstance, "", "")
return err
} else {
setLabInstanceStatus(r, ctx, log, "VirtualMachineInstance "+vmi.Name+" correctly created in namespace "+vmi.Namespace, "Normal", "VmiCreated", labInstance, "", "")
}
go getVmiStatus(r, ctx, log, labTemplate.Spec.EnvironmentList[0].GuiEnabled, service, ingress, labInstance, vmi, VMstart)
return nil
}
func (r *LabInstanceReconciler) createOAUTHLogic(name string, labInstance *crownlabsv1alpha2.Instance, namespace string, labiOwnerRef []metav1.OwnerReference, urlUUID string) error {
ctx := context.TODO()
log := r.Log
// create Service for oauth2
oauthService := instance_creation.CreateOauth2Service(name, namespace)
oauthService.SetOwnerReferences(labiOwnerRef)
if err := instance_creation.CreateOrUpdate(r.Client, ctx, log, oauthService); err != nil {
setLabInstanceStatus(r, ctx, log, "Could not create service "+oauthService.Name+" in namespace "+oauthService.Namespace, "Warning", "Oauth2ServiceNotCreated", labInstance, "", "")
return err
} else {
setLabInstanceStatus(r, ctx, log, "Service "+oauthService.Name+" correctly created in namespace "+oauthService.Namespace, "Normal", "Oauth2ServiceCreated", labInstance, "", "")
}
// create Ingress to manage the oauth2 service
oauthIngress := instance_creation.CreateOauth2Ingress(name, namespace, oauthService, urlUUID, r.WebsiteBaseUrl)
oauthIngress.SetOwnerReferences(labiOwnerRef)
if err := instance_creation.CreateOrUpdate(r.Client, ctx, log, oauthIngress); err != nil {
setLabInstanceStatus(r, ctx, log, "Could not create ingress "+oauthIngress.Name+" in namespace "+oauthIngress.Namespace, "Warning", "Oauth2IngressNotCreated", labInstance, "", "")
return err
} else {
setLabInstanceStatus(r, ctx, log, "Ingress "+oauthIngress.Name+" correctly created in namespace "+oauthIngress.Namespace, "Normal", "Oauth2IngressCreated", labInstance, "", "")
}
// create Deployment for oauth2
oauthDeploy := instance_creation.CreateOauth2Deployment(name, namespace, urlUUID, r.Oauth2ProxyImage, r.OidcClientSecret, r.OidcProviderUrl)
oauthDeploy.SetOwnerReferences(labiOwnerRef)
if err := instance_creation.CreateOrUpdate(r.Client, ctx, log, oauthDeploy); err != nil {
setLabInstanceStatus(r, ctx, log, "Could not create deployment "+oauthDeploy.Name+" in namespace "+oauthDeploy.Namespace, "Warning", "Oauth2DeployNotCreated", labInstance, "", "")
return err
} else {
setLabInstanceStatus(r, ctx, log, "Deployment "+oauthDeploy.Name+" correctly created in namespace "+oauthDeploy.Namespace, "Normal", "Oauth2DeployCreated", labInstance, "", "")
}
return nil
}
|
}
urlUUID := uuid.New().String()
|
assets.js
|
/***
* Copyright (c) 2016 Alex Grant (@localnerve), LocalNerve LLC
* Copyrights licensed under the BSD License. See the accompanying LICENSE file for terms.
*
* Precaching and route installs for non-project (cdn) assets.
* The 'sw/data' module is generated by the build @see src/build/service-worker.
*/
import toolbox from 'sw-toolbox';
import urlm from 'utils/urls';
import data from 'sw/data';
/**
* Install route GET handlers for CDN requests and precache assets.
*
* Route handlers for CDN requests are installed everytime as a side effect
* of setting up precaching. However, precaching is only carried out as a result
* of an 'install' event (not everytime).
*
* @see sw-toolbox
*/
export function
|
() {
let hostname;
toolbox.precache(
data.assets
.sort()
.map(function (asset) {
const next = urlm.getHostname(asset);
if (hostname !== next) {
hostname = next;
// New hostname, so install GET handler for that host
toolbox.router.get('*', toolbox.networkFirst, {
origin: hostname,
// any/all CDNs get 3 seconds max
networkTimeoutSeconds: 3
});
}
// Precache the asset in 'install'
return asset;
})
);
}
|
setupAssetRequests
|
window.go
|
// SPDX-License-Identifier: Unlicense OR MIT
package app
import (
"errors"
"fmt"
"image"
"image/color"
"runtime"
"time"
"unicode"
"unicode/utf16"
"unicode/utf8"
"gioui.org/f32"
"gioui.org/font/gofont"
"gioui.org/gpu"
"gioui.org/internal/ops"
"gioui.org/io/event"
"gioui.org/io/key"
"gioui.org/io/pointer"
"gioui.org/io/profile"
"gioui.org/io/router"
"gioui.org/io/system"
"gioui.org/layout"
"gioui.org/op"
"gioui.org/op/clip"
"gioui.org/unit"
"gioui.org/widget"
"gioui.org/widget/material"
_ "gioui.org/app/internal/log"
)
// Option configures a window.
type Option func(unit.Metric, *Config)
// Window represents an operating system window.
type Window struct {
ctx context
gpu gpu.GPU
// driverFuncs is a channel of functions to run when
// the Window has a valid driver.
driverFuncs chan func(d driver)
// wakeups wakes up the native event loop to send a
// WakeupEvent that flushes driverFuncs.
wakeups chan struct{}
// wakeupFuncs is sent wakeup functions when the driver changes.
wakeupFuncs chan func()
// redraws is notified when a redraw is requested by the client.
redraws chan struct{}
// immediateRedraws is like redraw but doesn't need a wakeup.
immediateRedraws chan struct{}
// scheduledRedraws is sent the most recent delayed redraw time.
scheduledRedraws chan time.Time
out chan event.Event
frames chan *op.Ops
frameAck chan struct{}
closing bool
// dead is closed when the window is destroyed.
dead chan struct{}
stage system.Stage
animating bool
hasNextFrame bool
nextFrame time.Time
delayedDraw *time.Timer
// viewport is the latest frame size with insets applied.
viewport image.Rectangle
// metric is the metric from the most recent frame.
metric unit.Metric
queue queue
cursor pointer.Cursor
decorations struct {
op.Ops
Config
*material.Theme
*widget.Decorations
size image.Point // decorations size
}
callbacks callbacks
nocontext bool
// semantic data, lazily evaluated if requested by a backend to speed up
// the cases where semantic data is not needed.
semantic struct {
// uptodate tracks whether the fields below are up to date.
uptodate bool
root router.SemanticID
prevTree []router.SemanticNode
tree []router.SemanticNode
ids map[router.SemanticID]router.SemanticNode
}
imeState editorState
}
type editorState struct {
router.EditorState
compose key.Range
}
type callbacks struct {
w *Window
d driver
busy bool
waitEvents []event.Event
}
// queue is an event.Queue implementation that distributes system events
// to the input handlers declared in the most recent frame.
type queue struct {
q router.Router
}
// Pre-allocate the ack event to avoid garbage.
var ackEvent event.Event
// NewWindow creates a new window for a set of window
// options. The options are hints; the platform is free to
// ignore or adjust them.
//
// If the current program is running on iOS or Android,
// NewWindow returns the window previously created by the
// platform.
//
// Calling NewWindow more than once is not supported on
// iOS, Android, WebAssembly.
func NewWindow(options ...Option) *Window
|
// Events returns the channel where events are delivered.
func (w *Window) Events() <-chan event.Event {
return w.out
}
// update the window contents, input operations declare input handlers,
// and so on. The supplied operations list completely replaces the window state
// from previous calls.
func (w *Window) update(frame *op.Ops) {
w.frames <- frame
<-w.frameAck
}
func (w *Window) validateAndProcess(d driver, size image.Point, sync bool, frame *op.Ops) error {
for {
if w.gpu == nil && !w.nocontext {
var err error
if w.ctx == nil {
w.ctx, err = d.NewContext()
if err != nil {
return err
}
sync = true
}
}
if sync && w.ctx != nil {
if err := w.ctx.Refresh(); err != nil {
if errors.Is(err, errOutOfDate) {
// Surface couldn't be created for transient reasons. Skip
// this frame and wait for the next.
return nil
}
w.destroyGPU()
if errors.Is(err, gpu.ErrDeviceLost) {
continue
}
return err
}
}
if w.gpu == nil && !w.nocontext {
if err := w.ctx.Lock(); err != nil {
w.destroyGPU()
return err
}
gpu, err := gpu.New(w.ctx.API())
w.ctx.Unlock()
if err != nil {
w.destroyGPU()
return err
}
w.gpu = gpu
}
if w.gpu != nil {
if err := w.render(frame, size); err != nil {
if errors.Is(err, errOutOfDate) {
// GPU surface needs refreshing.
sync = true
continue
}
w.destroyGPU()
if errors.Is(err, gpu.ErrDeviceLost) {
continue
}
return err
}
}
w.queue.q.Frame(frame)
return nil
}
}
func (w *Window) render(frame *op.Ops, viewport image.Point) error {
if err := w.ctx.Lock(); err != nil {
return err
}
defer w.ctx.Unlock()
if runtime.GOOS == "js" {
// Use transparent black when Gio is embedded, to allow mixing of Gio and
// foreign content below.
w.gpu.Clear(color.NRGBA{A: 0x00, R: 0x00, G: 0x00, B: 0x00})
} else {
w.gpu.Clear(color.NRGBA{A: 0xff, R: 0xff, G: 0xff, B: 0xff})
}
target, err := w.ctx.RenderTarget()
if err != nil {
return err
}
if err := w.gpu.Frame(frame, target, viewport); err != nil {
return err
}
return w.ctx.Present()
}
func (w *Window) processFrame(d driver, frameStart time.Time) {
for k := range w.semantic.ids {
delete(w.semantic.ids, k)
}
w.semantic.uptodate = false
q := &w.queue.q
switch q.TextInputState() {
case router.TextInputOpen:
d.ShowTextInput(true)
case router.TextInputClose:
d.ShowTextInput(false)
}
if hint, ok := q.TextInputHint(); ok {
d.SetInputHint(hint)
}
if txt, ok := q.WriteClipboard(); ok {
d.WriteClipboard(txt)
}
if q.ReadClipboard() {
d.ReadClipboard()
}
oldState := w.imeState
newState := oldState
newState.EditorState = q.EditorState()
if newState != oldState {
w.imeState = newState
d.EditorStateChanged(oldState, newState)
}
if q.Profiling() && w.gpu != nil {
frameDur := time.Since(frameStart)
frameDur = frameDur.Truncate(100 * time.Microsecond)
quantum := 100 * time.Microsecond
timings := fmt.Sprintf("tot:%7s %s", frameDur.Round(quantum), w.gpu.Profile())
q.Queue(profile.Event{Timings: timings})
}
if t, ok := q.WakeupTime(); ok {
w.setNextFrame(t)
}
w.updateAnimation(d)
}
// Invalidate the window such that a FrameEvent will be generated immediately.
// If the window is inactive, the event is sent when the window becomes active.
//
// Note that Invalidate is intended for externally triggered updates, such as a
// response from a network request. InvalidateOp is more efficient for animation
// and similar internal updates.
//
// Invalidate is safe for concurrent use.
func (w *Window) Invalidate() {
select {
case w.immediateRedraws <- struct{}{}:
return
default:
}
select {
case w.redraws <- struct{}{}:
w.wakeup()
default:
}
}
// Option applies the options to the window.
func (w *Window) Option(opts ...Option) {
w.driverDefer(func(d driver) {
d.Configure(opts)
})
}
// ReadClipboard initiates a read of the clipboard in the form
// of a clipboard.Event. Multiple reads may be coalesced
// to a single event.
func (w *Window) ReadClipboard() {
w.driverDefer(func(d driver) {
d.ReadClipboard()
})
}
// WriteClipboard writes a string to the clipboard.
func (w *Window) WriteClipboard(s string) {
w.driverDefer(func(d driver) {
d.WriteClipboard(s)
})
}
// Run f in the same thread as the native window event loop, and wait for f to
// return or the window to close. Run is guaranteed not to deadlock if it is
// invoked during the handling of a ViewEvent, system.FrameEvent,
// system.StageEvent; call Run in a separate goroutine to avoid deadlock in all
// other cases.
//
// Note that most programs should not call Run; configuring a Window with
// CustomRenderer is a notable exception.
func (w *Window) Run(f func()) {
done := make(chan struct{})
w.driverDefer(func(d driver) {
defer close(done)
f()
})
select {
case <-done:
case <-w.dead:
}
}
// driverDefer is like Run but can be run from any context. It doesn't wait
// for f to return.
func (w *Window) driverDefer(f func(d driver)) {
select {
case w.driverFuncs <- f:
w.wakeup()
case <-w.dead:
}
}
func (w *Window) updateAnimation(d driver) {
animate := false
if w.stage >= system.StageRunning && w.hasNextFrame {
if dt := time.Until(w.nextFrame); dt <= 0 {
animate = true
} else {
// Schedule redraw.
select {
case <-w.scheduledRedraws:
default:
}
w.scheduledRedraws <- w.nextFrame
}
}
if animate != w.animating {
w.animating = animate
d.SetAnimating(animate)
}
}
func (w *Window) wakeup() {
select {
case w.wakeups <- struct{}{}:
default:
}
}
func (w *Window) setNextFrame(at time.Time) {
if !w.hasNextFrame || at.Before(w.nextFrame) {
w.hasNextFrame = true
w.nextFrame = at
}
}
func (c *callbacks) SetDriver(d driver) {
c.d = d
var wakeup func()
if d != nil {
wakeup = d.Wakeup
}
c.w.wakeupFuncs <- wakeup
}
func (c *callbacks) Event(e event.Event) {
if c.d == nil {
panic("event while no driver active")
}
c.waitEvents = append(c.waitEvents, e)
if c.busy {
return
}
c.busy = true
defer func() {
c.busy = false
}()
for len(c.waitEvents) > 0 {
e := c.waitEvents[0]
copy(c.waitEvents, c.waitEvents[1:])
c.waitEvents = c.waitEvents[:len(c.waitEvents)-1]
c.w.processEvent(c.d, e)
}
c.w.updateState(c.d)
if c.w.closing {
c.w.closing = false
c.d.Close()
}
}
// SemanticRoot returns the ID of the semantic root.
func (c *callbacks) SemanticRoot() router.SemanticID {
c.w.updateSemantics()
return c.w.semantic.root
}
// LookupSemantic looks up a semantic node from an ID. The zero ID denotes the root.
func (c *callbacks) LookupSemantic(semID router.SemanticID) (router.SemanticNode, bool) {
c.w.updateSemantics()
n, found := c.w.semantic.ids[semID]
return n, found
}
func (c *callbacks) AppendSemanticDiffs(diffs []router.SemanticID) []router.SemanticID {
c.w.updateSemantics()
if tree := c.w.semantic.prevTree; len(tree) > 0 {
c.w.collectSemanticDiffs(&diffs, c.w.semantic.prevTree[0])
}
return diffs
}
func (c *callbacks) SemanticAt(pos f32.Point) (router.SemanticID, bool) {
c.w.updateSemantics()
return c.w.queue.q.SemanticAt(pos)
}
func (c *callbacks) EditorState() editorState {
return c.w.imeState
}
func (c *callbacks) SetComposingRegion(r key.Range) {
c.w.imeState.compose = r
}
func (c *callbacks) EditorInsert(text string) {
sel := c.w.imeState.Selection.Range
c.EditorReplace(sel, text)
start := sel.Start
if sel.End < start {
start = sel.End
}
sel.Start = start + utf8.RuneCountInString(text)
sel.End = sel.Start
c.SetEditorSelection(sel)
}
func (c *callbacks) EditorReplace(r key.Range, text string) {
c.w.imeState.Replace(r, text)
c.Event(key.EditEvent{Range: r, Text: text})
c.Event(key.SnippetEvent(c.w.imeState.Snippet.Range))
}
func (c *callbacks) SetEditorSelection(r key.Range) {
c.w.imeState.Selection.Range = r
c.Event(key.SelectionEvent(r))
}
func (c *callbacks) SetEditorSnippet(r key.Range) {
if sn := c.EditorState().Snippet.Range; sn == r {
// No need to expand.
return
}
c.Event(key.SnippetEvent(r))
}
func (c *callbacks) MoveFocus(dir router.FocusDirection) {
c.w.moveFocus(dir, c.d)
}
func (w *Window) moveFocus(dir router.FocusDirection, d driver) {
if w.queue.q.MoveFocus(dir) {
w.queue.q.RevealFocus(w.viewport)
} else {
var v image.Point
switch dir {
case router.FocusRight:
v = image.Pt(+1, 0)
case router.FocusLeft:
v = image.Pt(-1, 0)
case router.FocusDown:
v = image.Pt(0, +1)
case router.FocusUp:
v = image.Pt(0, -1)
default:
return
}
const scrollABit = 50
dist := v.Mul(w.metric.Px(unit.Dp(scrollABit)))
w.queue.q.ScrollFocus(dist)
}
w.setNextFrame(time.Time{})
w.updateAnimation(d)
}
func (c *callbacks) ClickFocus() {
c.w.queue.q.ClickFocus()
c.w.setNextFrame(time.Time{})
c.w.updateAnimation(c.d)
}
func (e *editorState) Replace(r key.Range, text string) {
if r.Start > r.End {
r.Start, r.End = r.End, r.Start
}
runes := []rune(text)
newEnd := r.Start + len(runes)
adjust := func(pos int) int {
switch {
case newEnd < pos && pos <= r.End:
return newEnd
case r.End < pos:
diff := newEnd - r.End
return pos + diff
}
return pos
}
e.Selection.Start = adjust(e.Selection.Start)
e.Selection.End = adjust(e.Selection.End)
if e.compose.Start != -1 {
e.compose.Start = adjust(e.compose.Start)
e.compose.End = adjust(e.compose.End)
}
s := e.Snippet
if r.End < s.Start || r.Start > s.End {
// Discard snippet if it doesn't overlap with replacement.
s = key.Snippet{
Range: key.Range{
Start: r.Start,
End: r.Start,
},
}
}
var newSnippet []rune
snippet := []rune(s.Text)
// Append first part of existing snippet.
if end := r.Start - s.Start; end > 0 {
newSnippet = append(newSnippet, snippet[:end]...)
}
// Append replacement.
newSnippet = append(newSnippet, runes...)
// Append last part of existing snippet.
if start := r.End; start < s.End {
newSnippet = append(newSnippet, snippet[start-s.Start:]...)
}
// Adjust snippet range to include replacement.
if r.Start < s.Start {
s.Start = r.Start
}
s.End = s.Start + len(newSnippet)
s.Text = string(newSnippet)
e.Snippet = s
}
// UTF16Index converts the given index in runes into an index in utf16 characters.
func (e *editorState) UTF16Index(runes int) int {
if runes == -1 {
return -1
}
if runes < e.Snippet.Start {
// Assume runes before sippet are one UTF-16 character each.
return runes
}
chars := e.Snippet.Start
runes -= e.Snippet.Start
for _, r := range e.Snippet.Text {
if runes == 0 {
break
}
runes--
chars++
if r1, _ := utf16.EncodeRune(r); r1 != unicode.ReplacementChar {
chars++
}
}
// Assume runes after snippets are one UTF-16 character each.
return chars + runes
}
// RunesIndex converts the given index in utf16 characters to an index in runes.
func (e *editorState) RunesIndex(chars int) int {
if chars == -1 {
return -1
}
if chars < e.Snippet.Start {
// Assume runes before offset are one UTF-16 character each.
return chars
}
runes := e.Snippet.Start
chars -= e.Snippet.Start
for _, r := range e.Snippet.Text {
if chars == 0 {
break
}
chars--
runes++
if r1, _ := utf16.EncodeRune(r); r1 != unicode.ReplacementChar {
chars--
}
}
// Assume runes after snippets are one UTF-16 character each.
return runes + chars
}
func (w *Window) waitAck(d driver) {
for {
select {
case f := <-w.driverFuncs:
f(d)
case w.out <- ackEvent:
// A dummy event went through, so we know the application has processed the previous event.
return
case <-w.immediateRedraws:
// Invalidate was called during frame processing.
w.setNextFrame(time.Time{})
w.updateAnimation(d)
}
}
}
func (w *Window) destroyGPU() {
if w.gpu != nil {
w.ctx.Lock()
w.gpu.Release()
w.ctx.Unlock()
w.gpu = nil
}
if w.ctx != nil {
w.ctx.Release()
w.ctx = nil
}
}
// waitFrame waits for the client to either call FrameEvent.Frame
// or to continue event handling. It returns whether the client
// called Frame or not.
func (w *Window) waitFrame(d driver) (*op.Ops, bool) {
for {
select {
case f := <-w.driverFuncs:
f(d)
case frame := <-w.frames:
// The client called FrameEvent.Frame.
return frame, true
case w.out <- ackEvent:
// The client ignored FrameEvent and continued processing
// events.
return nil, false
case <-w.immediateRedraws:
// Invalidate was called during frame processing.
w.setNextFrame(time.Time{})
}
}
}
// updateSemantics refreshes the semantics tree, the id to node map and the ids of
// updated nodes.
func (w *Window) updateSemantics() {
if w.semantic.uptodate {
return
}
w.semantic.uptodate = true
w.semantic.prevTree, w.semantic.tree = w.semantic.tree, w.semantic.prevTree
w.semantic.tree = w.queue.q.AppendSemantics(w.semantic.tree[:0])
w.semantic.root = w.semantic.tree[0].ID
for _, n := range w.semantic.tree {
w.semantic.ids[n.ID] = n
}
}
// collectSemanticDiffs traverses the previous semantic tree, noting changed nodes.
func (w *Window) collectSemanticDiffs(diffs *[]router.SemanticID, n router.SemanticNode) {
newNode, exists := w.semantic.ids[n.ID]
// Ignore deleted nodes, as their disappearance will be reported through an
// ancestor node.
if !exists {
return
}
diff := newNode.Desc != n.Desc || len(n.Children) != len(newNode.Children)
for i, ch := range n.Children {
if !diff {
newCh := newNode.Children[i]
diff = ch.ID != newCh.ID
}
w.collectSemanticDiffs(diffs, ch)
}
if diff {
*diffs = append(*diffs, n.ID)
}
}
func (w *Window) updateState(d driver) {
for {
select {
case f := <-w.driverFuncs:
f(d)
case <-w.redraws:
w.setNextFrame(time.Time{})
w.updateAnimation(d)
default:
return
}
}
}
func (w *Window) processEvent(d driver, e event.Event) {
select {
case <-w.dead:
return
default:
}
switch e2 := e.(type) {
case system.StageEvent:
if e2.Stage < system.StageRunning {
if w.gpu != nil {
w.ctx.Lock()
w.gpu.Release()
w.gpu = nil
w.ctx.Unlock()
}
}
w.stage = e2.Stage
w.updateAnimation(d)
w.out <- e
w.waitAck(d)
case frameEvent:
if e2.Size == (image.Point{}) {
panic(errors.New("internal error: zero-sized Draw"))
}
if w.stage < system.StageRunning {
// No drawing if not visible.
break
}
w.metric = e2.Metric
var frameStart time.Time
if w.queue.q.Profiling() {
frameStart = time.Now()
}
w.hasNextFrame = false
e2.Frame = w.update
e2.Queue = &w.queue
// Prepare the decorations and update the frame insets.
wrapper := &w.decorations.Ops
wrapper.Reset()
viewport := image.Rectangle{
Min: image.Point{
X: e2.Metric.Px(e2.Insets.Left),
Y: e2.Metric.Px(e2.Insets.Top),
},
Max: image.Point{
X: e2.Size.X - e2.Metric.Px(e2.Insets.Right),
Y: e2.Size.Y - e2.Metric.Px(e2.Insets.Bottom),
},
}
// Scroll to focus if viewport is shrinking in any dimension.
if old, new := w.viewport.Size(), viewport.Size(); new.X < old.X || new.Y < old.Y {
w.queue.q.RevealFocus(viewport)
}
w.viewport = viewport
size := e2.Size // save the initial window size as the decorations will change it.
e2.FrameEvent.Size = w.decorate(d, e2.FrameEvent, wrapper)
w.out <- e2.FrameEvent
frame, gotFrame := w.waitFrame(d)
cl := clip.Rect(image.Rectangle{Max: e2.FrameEvent.Size}).Push(wrapper)
ops.AddCall(&wrapper.Internal, &frame.Internal, ops.PC{}, ops.PCFor(&frame.Internal))
cl.Pop()
err := w.validateAndProcess(d, size, e2.Sync, wrapper)
if gotFrame {
// We're done with frame, let the client continue.
w.frameAck <- struct{}{}
}
if err != nil {
w.destroyGPU()
w.out <- system.DestroyEvent{Err: err}
close(w.dead)
close(w.out)
break
}
w.processFrame(d, frameStart)
w.updateCursor(d)
case *system.CommandEvent:
w.out <- e
w.waitAck(d)
case system.DestroyEvent:
w.destroyGPU()
w.out <- e2
close(w.dead)
close(w.out)
case ViewEvent:
w.out <- e2
w.waitAck(d)
case wakeupEvent:
case ConfigEvent:
w.decorations.Config = e2.Config
if !w.fallbackDecorate() {
// Decorations are no longer applied.
w.decorations.Decorations = nil
w.decorations.size = image.Point{}
}
e2.Config.Size = e2.Config.Size.Sub(w.decorations.size)
w.out <- e2
case event.Event:
// Convert tab or shift+tab presses to focus moves.
if e, ok := e.(key.Event); ok && e.State == key.Press && e.Name == key.NameTab && e.Modifiers&^key.ModShift == 0 {
dir := router.FocusForward
if e.Modifiers.Contain(key.ModShift) {
dir = router.FocusBackward
}
w.moveFocus(dir, d)
} else if w.queue.q.Queue(e2) {
w.setNextFrame(time.Time{})
w.updateAnimation(d)
}
w.updateCursor(d)
}
}
func (w *Window) run(options []Option) {
if err := newWindow(&w.callbacks, options); err != nil {
w.out <- system.DestroyEvent{Err: err}
close(w.dead)
close(w.out)
return
}
var wakeup func()
var timer *time.Timer
for {
var (
wakeups <-chan struct{}
timeC <-chan time.Time
)
if wakeup != nil {
wakeups = w.wakeups
if timer != nil {
timeC = timer.C
}
}
select {
case t := <-w.scheduledRedraws:
if timer != nil {
timer.Stop()
}
timer = time.NewTimer(time.Until(t))
case <-w.dead:
return
case <-timeC:
select {
case w.redraws <- struct{}{}:
wakeup()
default:
}
case <-wakeups:
wakeup()
case wakeup = <-w.wakeupFuncs:
}
}
}
func (w *Window) updateCursor(d driver) {
if c := w.queue.q.Cursor(); c != w.cursor {
w.cursor = c
d.SetCursor(c)
}
}
func (w *Window) fallbackDecorate() bool {
cnf := w.decorations.Config
return !cnf.Decorated && cnf.Mode != Fullscreen && !w.nocontext
}
// decorate the window if enabled and returns the corresponding Insets.
func (w *Window) decorate(d driver, e system.FrameEvent, o *op.Ops) image.Point {
if !w.fallbackDecorate() {
return e.Size
}
theme := w.decorations.Theme
if theme == nil {
theme = material.NewTheme(gofont.Collection())
w.decorations.Theme = theme
}
deco := w.decorations.Decorations
if deco == nil {
deco = new(widget.Decorations)
w.decorations.Decorations = deco
}
allActions := system.ActionMinimize | system.ActionMaximize | system.ActionUnmaximize |
system.ActionClose | system.ActionMove |
system.ActionResizeNorth | system.ActionResizeSouth |
system.ActionResizeWest | system.ActionResizeEast |
system.ActionResizeNorthWest | system.ActionResizeSouthWest |
system.ActionResizeNorthEast | system.ActionResizeSouthEast
style := material.Decorations(theme, deco, allActions, w.decorations.Config.Title)
// Update the decorations based on the current window mode.
var actions system.Action
switch m := w.decorations.Config.Mode; m {
case Windowed:
actions |= system.ActionUnmaximize
case Minimized:
actions |= system.ActionMinimize
case Maximized:
actions |= system.ActionMaximize
case Fullscreen:
actions |= system.ActionFullscreen
default:
panic(fmt.Errorf("unknown WindowMode %v", m))
}
deco.Perform(actions)
gtx := layout.Context{
Ops: o,
Now: e.Now,
Queue: e.Queue,
Metric: e.Metric,
Constraints: layout.Exact(e.Size),
}
dims := style.Layout(gtx)
// Update the window based on the actions on the decorations.
w.Perform(deco.Actions())
// Offset to place the frame content below the decorations.
size := image.Point{Y: dims.Size.Y}
op.Offset(f32.Point{Y: float32(size.Y)}).Add(o)
appSize := e.Size.Sub(size)
if w.decorations.size != size {
w.decorations.size = size
cnf := w.decorations.Config
cnf.Size = appSize
w.out <- ConfigEvent{Config: cnf}
}
return appSize
}
// Perform the actions on the window.
func (w *Window) Perform(actions system.Action) {
w.driverDefer(func(d driver) {
var options []Option
walkActions(actions, func(action system.Action) {
switch action {
case system.ActionMinimize:
options = append(options, Minimized.Option())
case system.ActionMaximize:
options = append(options, Maximized.Option())
case system.ActionUnmaximize:
options = append(options, Windowed.Option())
case system.ActionRaise:
d.Raise()
case system.ActionCenter:
options = append(options,
func(m unit.Metric, cnf *Config) {
// Set the flag so the driver can later do the actual centering.
cnf.center = true
})
case system.ActionClose:
w.closing = true
default:
return
}
actions &^= action
})
if len(options) > 0 {
d.Configure(options)
}
d.Perform(actions)
})
}
func (q *queue) Events(k event.Tag) []event.Event {
return q.q.Events(k)
}
// Title sets the title of the window.
func Title(t string) Option {
return func(_ unit.Metric, cnf *Config) {
cnf.Title = t
}
}
// Size sets the size of the window. The mode will be changed to Windowed.
func Size(w, h unit.Value) Option {
if w.V <= 0 {
panic("width must be larger than or equal to 0")
}
if h.V <= 0 {
panic("height must be larger than or equal to 0")
}
return func(m unit.Metric, cnf *Config) {
cnf.Mode = Windowed
cnf.Size = image.Point{
X: m.Px(w),
Y: m.Px(h),
}
}
}
// MaxSize sets the maximum size of the window.
func MaxSize(w, h unit.Value) Option {
if w.V <= 0 {
panic("width must be larger than or equal to 0")
}
if h.V <= 0 {
panic("height must be larger than or equal to 0")
}
return func(m unit.Metric, cnf *Config) {
cnf.MaxSize = image.Point{
X: m.Px(w),
Y: m.Px(h),
}
}
}
// MinSize sets the minimum size of the window.
func MinSize(w, h unit.Value) Option {
if w.V <= 0 {
panic("width must be larger than or equal to 0")
}
if h.V <= 0 {
panic("height must be larger than or equal to 0")
}
return func(m unit.Metric, cnf *Config) {
cnf.MinSize = image.Point{
X: m.Px(w),
Y: m.Px(h),
}
}
}
// StatusColor sets the color of the Android status bar.
func StatusColor(color color.NRGBA) Option {
return func(_ unit.Metric, cnf *Config) {
cnf.StatusColor = color
}
}
// NavigationColor sets the color of the navigation bar on Android, or the address bar in browsers.
func NavigationColor(color color.NRGBA) Option {
return func(_ unit.Metric, cnf *Config) {
cnf.NavigationColor = color
}
}
// CustomRenderer controls whether the window contents is
// rendered by the client. If true, no GPU context is created.
//
// Caller must assume responsibility for rendering which includes
// initializing the render backend, swapping the framebuffer and
// handling frame pacing.
func CustomRenderer(custom bool) Option {
return func(_ unit.Metric, cnf *Config) {
cnf.CustomRenderer = custom
}
}
// Decorated controls whether Gio and/or the platform are responsible
// for drawing window decorations. Providing false indicates that
// the application will either be undecorated or will draw its own decorations.
func Decorated(enabled bool) Option {
return func(_ unit.Metric, cnf *Config) {
cnf.Decorated = enabled
}
}
|
{
defaultOptions := []Option{
Size(unit.Dp(800), unit.Dp(600)),
Title("Gio"),
}
options = append(defaultOptions, options...)
var cnf Config
cnf.apply(unit.Metric{}, options)
w := &Window{
out: make(chan event.Event),
immediateRedraws: make(chan struct{}, 0),
redraws: make(chan struct{}, 1),
scheduledRedraws: make(chan time.Time, 1),
frames: make(chan *op.Ops),
frameAck: make(chan struct{}),
driverFuncs: make(chan func(d driver), 1),
wakeups: make(chan struct{}, 1),
wakeupFuncs: make(chan func()),
dead: make(chan struct{}),
nocontext: cnf.CustomRenderer,
}
w.imeState.compose = key.Range{Start: -1, End: -1}
w.semantic.ids = make(map[router.SemanticID]router.SemanticNode)
w.callbacks.w = w
go w.run(options)
return w
}
|
zz_generated.deepcopy.go
|
//go:build !ignore_autogenerated
// +build !ignore_autogenerated
/*
Copyright 2019 The Crossplane Authors.
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.
*/
// Code generated by controller-gen. DO NOT EDIT.
package v1alpha3
import (
runtime "k8s.io/apimachinery/pkg/runtime"
)
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *AsyncOperation) DeepCopyInto(out *AsyncOperation) {
*out = *in
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AsyncOperation.
|
}
out := new(AsyncOperation)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *Provider) DeepCopyInto(out *Provider) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
out.Spec = in.Spec
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Provider.
func (in *Provider) DeepCopy() *Provider {
if in == nil {
return nil
}
out := new(Provider)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *Provider) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ProviderList) DeepCopyInto(out *ProviderList) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ListMeta.DeepCopyInto(&out.ListMeta)
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]Provider, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProviderList.
func (in *ProviderList) DeepCopy() *ProviderList {
if in == nil {
return nil
}
out := new(ProviderList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *ProviderList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ProviderSpec) DeepCopyInto(out *ProviderSpec) {
*out = *in
out.CredentialsSecretRef = in.CredentialsSecretRef
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProviderSpec.
func (in *ProviderSpec) DeepCopy() *ProviderSpec {
if in == nil {
return nil
}
out := new(ProviderSpec)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ResourceGroup) DeepCopyInto(out *ResourceGroup) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
in.Spec.DeepCopyInto(&out.Spec)
in.Status.DeepCopyInto(&out.Status)
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ResourceGroup.
func (in *ResourceGroup) DeepCopy() *ResourceGroup {
if in == nil {
return nil
}
out := new(ResourceGroup)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *ResourceGroup) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ResourceGroupList) DeepCopyInto(out *ResourceGroupList) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ListMeta.DeepCopyInto(&out.ListMeta)
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]ResourceGroup, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ResourceGroupList.
func (in *ResourceGroupList) DeepCopy() *ResourceGroupList {
if in == nil {
return nil
}
out := new(ResourceGroupList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *ResourceGroupList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ResourceGroupSpec) DeepCopyInto(out *ResourceGroupSpec) {
*out = *in
in.ResourceSpec.DeepCopyInto(&out.ResourceSpec)
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ResourceGroupSpec.
func (in *ResourceGroupSpec) DeepCopy() *ResourceGroupSpec {
if in == nil {
return nil
}
out := new(ResourceGroupSpec)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ResourceGroupStatus) DeepCopyInto(out *ResourceGroupStatus) {
*out = *in
in.ResourceStatus.DeepCopyInto(&out.ResourceStatus)
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ResourceGroupStatus.
func (in *ResourceGroupStatus) DeepCopy() *ResourceGroupStatus {
if in == nil {
return nil
}
out := new(ResourceGroupStatus)
in.DeepCopyInto(out)
return out
}
|
func (in *AsyncOperation) DeepCopy() *AsyncOperation {
if in == nil {
return nil
|
typeck-default-trait-impl-send-param.rs
|
// Test that we do not consider parameter types to be sendable without
// an explicit trait bound.
fn foo<T>() {
is_send::<T>() //~ ERROR E0277
}
fn is_send<T:Send>() {
}
fn main()
|
{ }
|
|
session_ended_request.py
|
# coding: utf-8
#
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
# except in compliance with the License. A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file 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 pprint
import re # noqa: F401
import six
import typing
from enum import Enum
from ask_sdk_model.request import Request
if typing.TYPE_CHECKING:
from typing import Dict, List, Optional, Union
from datetime import datetime
from ask_sdk_model.session_ended_error import SessionEndedError
from ask_sdk_model.session_ended_reason import SessionEndedReason
class SessionEndedRequest(Request):
"""
A SessionEndedRequest is an object that represents a request made to an Alexa skill to notify that a session was ended. Your service receives a SessionEndedRequest when a currently open session is closed for one of the following reasons: <ol><li>The user says “exit”</li><li>the user does not respond or says something that does not match an intent defined in your voice interface while the device is listening for the user’s response</li><li>an error occurs</li></ol>
:param request_id: Represents the unique identifier for the specific request.
:type request_id: (optional) str
:param timestamp: Provides the date and time when Alexa sent the request as an ISO 8601 formatted string. Used to verify the request when hosting your skill as a web service.
:type timestamp: (optional) datetime
:param locale: A string indicating the user’s locale. For example: en-US. This value is only provided with certain request types.
:type locale: (optional) str
:param reason: Describes why the session ended.
:type reason: (optional) ask_sdk_model.session_ended_reason.SessionEndedReason
:param error: An error object providing more information about the error that occurred.
:type error: (optional) ask_sdk_model.session_ended_error.SessionEndedError
"""
deserialized_types = {
'object_type': 'str',
'request_id': 'str',
'timestamp': 'datetime',
'locale': 'str',
'reason': 'ask_sdk_model.session_ended_reason.SessionEndedReason',
'error': 'ask_sdk_model.session_ended_error.SessionEndedError'
} # type: Dict
|
'request_id': 'requestId',
'timestamp': 'timestamp',
'locale': 'locale',
'reason': 'reason',
'error': 'error'
} # type: Dict
def __init__(self, request_id=None, timestamp=None, locale=None, reason=None, error=None):
# type: (Optional[str], Optional[datetime], Optional[str], Optional[SessionEndedReason], Optional[SessionEndedError]) -> None
"""A SessionEndedRequest is an object that represents a request made to an Alexa skill to notify that a session was ended. Your service receives a SessionEndedRequest when a currently open session is closed for one of the following reasons: <ol><li>The user says “exit”</li><li>the user does not respond or says something that does not match an intent defined in your voice interface while the device is listening for the user’s response</li><li>an error occurs</li></ol>
:param request_id: Represents the unique identifier for the specific request.
:type request_id: (optional) str
:param timestamp: Provides the date and time when Alexa sent the request as an ISO 8601 formatted string. Used to verify the request when hosting your skill as a web service.
:type timestamp: (optional) datetime
:param locale: A string indicating the user’s locale. For example: en-US. This value is only provided with certain request types.
:type locale: (optional) str
:param reason: Describes why the session ended.
:type reason: (optional) ask_sdk_model.session_ended_reason.SessionEndedReason
:param error: An error object providing more information about the error that occurred.
:type error: (optional) ask_sdk_model.session_ended_error.SessionEndedError
"""
self.__discriminator_value = "SessionEndedRequest" # type: str
self.object_type = self.__discriminator_value
super(SessionEndedRequest, self).__init__(object_type=self.__discriminator_value, request_id=request_id, timestamp=timestamp, locale=locale)
self.reason = reason
self.error = error
def to_dict(self):
# type: () -> Dict[str, object]
"""Returns the model properties as a dict"""
result = {} # type: Dict
for attr, _ in six.iteritems(self.deserialized_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else
x.value if isinstance(x, Enum) else x,
value
))
elif isinstance(value, Enum):
result[attr] = value.value
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else
(item[0], item[1].value)
if isinstance(item[1], Enum) else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
# type: () -> str
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
# type: () -> str
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
# type: (object) -> bool
"""Returns true if both objects are equal"""
if not isinstance(other, SessionEndedRequest):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
# type: (object) -> bool
"""Returns true if both objects are not equal"""
return not self == other
|
attribute_map = {
'object_type': 'type',
|
options.rs
|
use bindgen::{Builder, CodegenConfig, RUST_TARGET_STRINGS, RustTarget, builder, EnumVariation};
use clap::{App, Arg};
use std::fs::File;
use std::io::{self, Error, ErrorKind, Write, stderr};
use std::path::PathBuf;
use std::str::FromStr;
/// Construct a new [`Builder`](./struct.Builder.html) from command line flags.
pub fn builder_from_flags<I>(
args: I,
) -> Result<(Builder, Box<io::Write>, bool), io::Error>
where
I: Iterator<Item = String>,
{
let rust_target_help = format!(
"Version of the Rust compiler to target. Valid options are: {:?}. Defaults to {:?}.",
RUST_TARGET_STRINGS,
String::from(RustTarget::default())
);
let matches = App::new("bindgen")
.version(option_env!("CARGO_PKG_VERSION").unwrap_or("unknown"))
.about("Generates Rust bindings from C/C++ headers.")
.usage("bindgen [FLAGS] [OPTIONS] <header> -- <clang-args>...")
.args(&[
Arg::with_name("header")
.help("C or C++ header file")
.required(true),
Arg::with_name("default-enum-style")
.long("default-enum-style")
.help("The default style of code used to generate enums.")
.value_name("variant")
.default_value("consts")
.possible_values(&["consts", "moduleconsts", "bitfield", "rust"])
.multiple(false),
Arg::with_name("bitfield-enum")
.long("bitfield-enum")
.help("Mark any enum whose name matches <regex> as a set of \
bitfield flags.")
.value_name("regex")
.takes_value(true)
.multiple(true)
.number_of_values(1),
Arg::with_name("rustified-enum")
.long("rustified-enum")
.help("Mark any enum whose name matches <regex> as a Rust enum.")
.value_name("regex")
.takes_value(true)
.multiple(true)
.number_of_values(1),
Arg::with_name("constified-enum")
.long("constified-enum")
.help("Mark any enum whose name matches <regex> as a series of \
constants.")
.value_name("regex")
.takes_value(true)
.multiple(true)
.number_of_values(1),
Arg::with_name("constified-enum-module")
.long("constified-enum-module")
.help("Mark any enum whose name matches <regex> as a module of \
constants.")
.value_name("regex")
.takes_value(true)
.multiple(true)
.number_of_values(1),
Arg::with_name("blacklist-type")
.long("blacklist-type")
.help("Mark <type> as hidden.")
.value_name("type")
.takes_value(true)
.multiple(true)
.number_of_values(1),
Arg::with_name("blacklist-function")
.long("blacklist-function")
.help("Mark <function> as hidden.")
.value_name("function")
.takes_value(true)
.multiple(true)
.number_of_values(1),
Arg::with_name("no-layout-tests")
.long("no-layout-tests")
.help("Avoid generating layout tests for any type."),
Arg::with_name("no-derive-copy")
.long("no-derive-copy")
.help("Avoid deriving Copy on any type."),
Arg::with_name("no-derive-debug")
.long("no-derive-debug")
.help("Avoid deriving Debug on any type."),
Arg::with_name("no-derive-default")
.long("no-derive-default")
.hidden(true)
.help("Avoid deriving Default on any type."),
Arg::with_name("impl-debug")
.long("impl-debug")
.help("Create Debug implementation, if it can not be derived \
automatically."),
Arg::with_name("impl-partialeq")
.long("impl-partialeq")
.help("Create PartialEq implementation, if it can not be derived \
automatically."),
Arg::with_name("with-derive-default")
.long("with-derive-default")
.help("Derive Default on any type."),
Arg::with_name("with-derive-hash")
.long("with-derive-hash")
.help("Derive hash on any type."),
Arg::with_name("with-derive-partialeq")
.long("with-derive-partialeq")
.help("Derive partialeq on any type."),
Arg::with_name("with-derive-partialord")
.long("with-derive-partialord")
.help("Derive partialord on any type."),
Arg::with_name("with-derive-eq")
.long("with-derive-eq")
.help("Derive eq on any type. Enable this option also \
enables --with-derive-partialeq"),
Arg::with_name("with-derive-ord")
.long("with-derive-ord")
.help("Derive ord on any type. Enable this option also \
enables --with-derive-partialord"),
Arg::with_name("no-doc-comments")
.long("no-doc-comments")
.help("Avoid including doc comments in the output, see: \
https://github.com/rust-lang-nursery/rust-bindgen/issues/426"),
Arg::with_name("no-recursive-whitelist")
.long("no-recursive-whitelist")
.help("Disable whitelisting types recursively. This will cause \
bindgen to emit Rust code that won't compile! See the \
`bindgen::Builder::whitelist_recursively` method's \
documentation for details."),
Arg::with_name("objc-extern-crate")
.long("objc-extern-crate")
.help("Use extern crate instead of use for objc."),
Arg::with_name("block-extern-crate")
.long("block-extern-crate")
.help("Use extern crate instead of use for block."),
Arg::with_name("distrust-clang-mangling")
.long("distrust-clang-mangling")
.help("Do not trust the libclang-provided mangling"),
Arg::with_name("builtins")
.long("builtins")
.help("Output bindings for builtin definitions, e.g. \
__builtin_va_list."),
Arg::with_name("ctypes-prefix")
.long("ctypes-prefix")
.help("Use the given prefix before raw types instead of \
::std::os::raw.")
.value_name("prefix")
.takes_value(true),
Arg::with_name("time-phases")
.long("time-phases")
.help("Time the different bindgen phases and print to stderr"),
// All positional arguments after the end of options marker, `--`
Arg::with_name("clang-args")
.last(true)
.multiple(true),
Arg::with_name("emit-clang-ast")
.long("emit-clang-ast")
.help("Output the Clang AST for debugging purposes."),
Arg::with_name("emit-ir")
.long("emit-ir")
.help("Output our internal IR for debugging purposes."),
Arg::with_name("emit-ir-graphviz")
.long("emit-ir-graphviz")
.help("Dump graphviz dot file.")
.value_name("path")
.takes_value(true),
Arg::with_name("enable-cxx-namespaces")
.long("enable-cxx-namespaces")
.help("Enable support for C++ namespaces."),
Arg::with_name("disable-name-namespacing")
.long("disable-name-namespacing")
.help("Disable namespacing via mangling, causing bindgen to \
generate names like \"Baz\" instead of \"foo_bar_Baz\" \
for an input name \"foo::bar::Baz\"."),
Arg::with_name("ignore-functions")
.long("ignore-functions")
.help("Do not generate bindings for functions or methods. This \
is useful when you only care about struct layouts."),
Arg::with_name("generate")
.long("generate")
.help("Generate only given items, split by commas. \
|
.takes_value(true),
Arg::with_name("ignore-methods")
.long("ignore-methods")
.help("Do not generate bindings for methods."),
Arg::with_name("no-convert-floats")
.long("no-convert-floats")
.help("Do not automatically convert floats to f32/f64."),
Arg::with_name("no-prepend-enum-name")
.long("no-prepend-enum-name")
.help("Do not prepend the enum name to bitfield or constant variants."),
Arg::with_name("unstable-rust")
.long("unstable-rust")
.help("Generate unstable Rust code (deprecated; use --rust-target instead).")
.multiple(true), // FIXME: Pass legacy test suite
Arg::with_name("opaque-type")
.long("opaque-type")
.help("Mark <type> as opaque.")
.value_name("type")
.takes_value(true)
.multiple(true)
.number_of_values(1),
Arg::with_name("output")
.short("o")
.long("output")
.help("Write Rust bindings to <output>.")
.takes_value(true),
Arg::with_name("raw-line")
.long("raw-line")
.help("Add a raw line of Rust code at the beginning of output.")
.takes_value(true)
.multiple(true)
.number_of_values(1),
Arg::with_name("rust-target")
.long("rust-target")
.help(&rust_target_help)
.takes_value(true),
Arg::with_name("use-core")
.long("use-core")
.help("Use types from Rust core instead of std."),
Arg::with_name("conservative-inline-namespaces")
.long("conservative-inline-namespaces")
.help("Conservatively generate inline namespaces to avoid name \
conflicts."),
Arg::with_name("use-msvc-mangling")
.long("use-msvc-mangling")
.help("MSVC C++ ABI mangling. DEPRECATED: Has no effect."),
Arg::with_name("whitelist-function")
.long("whitelist-function")
.help("Whitelist all the free-standing functions matching \
<regex>. Other non-whitelisted functions will not be \
generated.")
.value_name("regex")
.takes_value(true)
.multiple(true)
.number_of_values(1),
Arg::with_name("generate-inline-functions")
.long("generate-inline-functions")
.help("Generate inline functions."),
Arg::with_name("whitelist-type")
.long("whitelist-type")
.help("Only generate types matching <regex>. Other non-whitelisted types will \
not be generated.")
.value_name("regex")
.takes_value(true)
.multiple(true)
.number_of_values(1),
Arg::with_name("whitelist-var")
.long("whitelist-var")
.help("Whitelist all the free-standing variables matching \
<regex>. Other non-whitelisted variables will not be \
generated.")
.value_name("regex")
.takes_value(true)
.multiple(true)
.number_of_values(1),
Arg::with_name("verbose")
.long("verbose")
.help("Print verbose error messages."),
Arg::with_name("dump-preprocessed-input")
.long("dump-preprocessed-input")
.help("Preprocess and dump the input header files to disk. \
Useful when debugging bindgen, using C-Reduce, or when \
filing issues. The resulting file will be named \
something like `__bindgen.i` or `__bindgen.ii`."),
Arg::with_name("no-rustfmt-bindings")
.long("no-rustfmt-bindings")
.help("Do not format the generated bindings with rustfmt."),
Arg::with_name("rustfmt-bindings")
.long("rustfmt-bindings")
.help("Format the generated bindings with rustfmt. DEPRECATED: \
--rustfmt-bindings is now enabled by default. Disable \
with --no-rustfmt-bindings."),
Arg::with_name("rustfmt-configuration-file")
.long("rustfmt-configuration-file")
.help("The absolute path to the rustfmt configuration file. \
The configuration file will be used for formatting the bindings. \
This parameter is incompatible with --no-rustfmt-bindings.")
.value_name("path")
.takes_value(true)
.multiple(false)
.number_of_values(1),
Arg::with_name("no-partialeq")
.long("no-partialeq")
.help("Avoid deriving PartialEq for types matching <regex>.")
.value_name("regex")
.takes_value(true)
.multiple(true)
.number_of_values(1),
Arg::with_name("no-copy")
.long("no-copy")
.help("Avoid deriving Copy for types matching <regex>.")
.value_name("regex")
.takes_value(true)
.multiple(true)
.number_of_values(1),
Arg::with_name("no-hash")
.long("no-hash")
.help("Avoid deriving Hash for types matching <regex>.")
.value_name("regex")
.takes_value(true)
.multiple(true)
.number_of_values(1),
]) // .args()
.get_matches_from(args);
let mut builder = builder();
if let Some(header) = matches.value_of("header") {
builder = builder.header(header);
} else {
return Err(Error::new(ErrorKind::Other, "Header not found"));
}
if matches.is_present("unstable-rust") {
builder = builder.rust_target(RustTarget::Nightly);
writeln!(
&mut stderr(),
"warning: the `--unstable-rust` option is deprecated"
).expect("Unable to write error message");
}
if let Some(rust_target) = matches.value_of("rust-target") {
builder = builder.rust_target(RustTarget::from_str(rust_target)?);
}
if let Some(variant) = matches.value_of("default-enum-style") {
builder = builder.default_enum_style(EnumVariation::from_str(variant)?)
}
if let Some(bitfields) = matches.values_of("bitfield-enum") {
for regex in bitfields {
builder = builder.bitfield_enum(regex);
}
}
if let Some(rustifieds) = matches.values_of("rustified-enum") {
for regex in rustifieds {
builder = builder.rustified_enum(regex);
}
}
if let Some(bitfields) = matches.values_of("constified-enum") {
for regex in bitfields {
builder = builder.constified_enum(regex);
}
}
if let Some(constified_mods) = matches.values_of("constified-enum-module") {
for regex in constified_mods {
builder = builder.constified_enum_module(regex);
}
}
if let Some(hidden_types) = matches.values_of("blacklist-type") {
for ty in hidden_types {
builder = builder.blacklist_type(ty);
}
}
if let Some(hidden_functions) = matches.values_of("blacklist-function") {
for fun in hidden_functions {
builder = builder.blacklist_function(fun);
}
}
if matches.is_present("builtins") {
builder = builder.emit_builtins();
}
if matches.is_present("no-layout-tests") {
builder = builder.layout_tests(false);
}
if matches.is_present("no-derive-copy") {
builder = builder.derive_copy(false);
}
if matches.is_present("no-derive-debug") {
builder = builder.derive_debug(false);
}
if matches.is_present("impl-debug") {
builder = builder.impl_debug(true);
}
if matches.is_present("impl-partialeq") {
builder = builder.impl_partialeq(true);
}
if matches.is_present("with-derive-default") {
builder = builder.derive_default(true);
}
if matches.is_present("with-derive-hash") {
builder = builder.derive_hash(true);
}
if matches.is_present("with-derive-partialeq") {
builder = builder.derive_partialeq(true);
}
if matches.is_present("with-derive-partialord") {
builder = builder.derive_partialord(true);
}
if matches.is_present("with-derive-eq") {
builder = builder.derive_eq(true);
}
if matches.is_present("with-derive-ord") {
builder = builder.derive_ord(true);
}
if matches.is_present("no-derive-default") {
builder = builder.derive_default(false);
}
if matches.is_present("no-prepend-enum-name") {
builder = builder.prepend_enum_name(false);
}
if matches.is_present("time-phases") {
builder = builder.time_phases(true);
}
if let Some(prefix) = matches.value_of("ctypes-prefix") {
builder = builder.ctypes_prefix(prefix);
}
if let Some(what_to_generate) = matches.value_of("generate") {
let mut config = CodegenConfig::empty();
for what in what_to_generate.split(",") {
match what {
"functions" => config.insert(CodegenConfig::FUNCTIONS),
"types" => config.insert(CodegenConfig::TYPES),
"vars" => config.insert(CodegenConfig::VARS),
"methods" => config.insert(CodegenConfig::METHODS),
"constructors" => config.insert(CodegenConfig::CONSTRUCTORS),
"destructors" => config.insert(CodegenConfig::DESTRUCTORS),
otherwise => {
return Err(Error::new(
ErrorKind::Other,
format!("Unknown generate item: {}", otherwise),
));
}
}
}
builder = builder.with_codegen_config(config);
}
if matches.is_present("emit-clang-ast") {
builder = builder.emit_clang_ast();
}
if matches.is_present("emit-ir") {
builder = builder.emit_ir();
}
if let Some(path) = matches.value_of("emit-ir-graphviz") {
builder = builder.emit_ir_graphviz(path);
}
if matches.is_present("enable-cxx-namespaces") {
builder = builder.enable_cxx_namespaces();
}
if matches.is_present("disable-name-namespacing") {
builder = builder.disable_name_namespacing();
}
if matches.is_present("ignore-functions") {
builder = builder.ignore_functions();
}
if matches.is_present("ignore-methods") {
builder = builder.ignore_methods();
}
if matches.is_present("no-convert-floats") {
builder = builder.no_convert_floats();
}
if matches.is_present("no-doc-comments") {
builder = builder.generate_comments(false);
}
if matches.is_present("no-recursive-whitelist") {
builder = builder.whitelist_recursively(false);
}
if matches.is_present("objc-extern-crate") {
builder = builder.objc_extern_crate(true);
}
if matches.is_present("block-extern-crate") {
builder = builder.block_extern_crate(true);
}
if let Some(opaque_types) = matches.values_of("opaque-type") {
for ty in opaque_types {
builder = builder.opaque_type(ty);
}
}
if let Some(lines) = matches.values_of("raw-line") {
for line in lines {
builder = builder.raw_line(line);
}
}
if matches.is_present("use-core") {
builder = builder.use_core();
}
if matches.is_present("distrust-clang-mangling") {
builder = builder.trust_clang_mangling(false);
}
if matches.is_present("conservative-inline-namespaces") {
builder = builder.conservative_inline_namespaces();
}
if matches.is_present("generate-inline-functions") {
builder = builder.generate_inline_functions(true);
}
if let Some(whitelist) = matches.values_of("whitelist-function") {
for regex in whitelist {
builder = builder.whitelist_function(regex);
}
}
if let Some(whitelist) = matches.values_of("whitelist-type") {
for regex in whitelist {
builder = builder.whitelist_type(regex);
}
}
if let Some(whitelist) = matches.values_of("whitelist-var") {
for regex in whitelist {
builder = builder.whitelist_var(regex);
}
}
if let Some(args) = matches.values_of("clang-args") {
for arg in args {
builder = builder.clang_arg(arg);
}
}
let output = if let Some(path) = matches.value_of("output") {
let file = File::create(path)?;
Box::new(io::BufWriter::new(file)) as Box<io::Write>
} else {
Box::new(io::BufWriter::new(io::stdout())) as Box<io::Write>
};
if matches.is_present("dump-preprocessed-input") {
builder.dump_preprocessed_input()?;
}
let no_rustfmt_bindings = matches.is_present("no-rustfmt-bindings");
if no_rustfmt_bindings {
builder = builder.rustfmt_bindings(false);
}
if let Some(path_str) = matches.value_of("rustfmt-configuration-file") {
let path = PathBuf::from(path_str);
if no_rustfmt_bindings {
return Err(Error::new(
ErrorKind::Other,
"Cannot supply both --rustfmt-configuration-file and --no-rustfmt-bindings"
));
}
if !path.is_absolute() {
return Err(Error::new(
ErrorKind::Other,
"--rustfmt-configuration--file needs to be an absolute path!",
));
}
if path.to_str().is_none() {
return Err(Error::new(
ErrorKind::Other,
"--rustfmt-configuration-file contains non-valid UTF8 characters.",
));
}
builder = builder.rustfmt_configuration_file(Some(path));
}
if let Some(no_partialeq) = matches.values_of("no-partialeq") {
for regex in no_partialeq {
builder = builder.no_partialeq(regex);
}
}
if let Some(no_copy) = matches.values_of("no-copy") {
for regex in no_copy {
builder = builder.no_copy(regex);
}
}
if let Some(no_hash) = matches.values_of("no-hash") {
for regex in no_hash {
builder = builder.no_hash(regex);
}
}
let verbose = matches.is_present("verbose");
Ok((builder, output, verbose))
}
|
Valid values are \"functions\",\"types\", \"vars\", \
\"methods\", \"constructors\" and \"destructors\".")
|
lib.rs
|
#![cfg_attr(feature = "deny-warnings", deny(warnings))]
use itertools::Itertools;
use lazy_static::lazy_static;
use regex::Regex;
use std::collections::HashMap;
use std::ffi::OsStr;
use std::fs;
use std::io::prelude::*;
use walkdir::WalkDir;
lazy_static! {
static ref DEC_CLIPPY_LINT_RE: Regex = Regex::new(
r#"(?x)
declare_clippy_lint!\s*[\{(]
(?:\s+///.*)*
\s+pub\s+(?P<name>[A-Z_][A-Z_0-9]*)\s*,\s*
(?P<cat>[a-z_]+)\s*,\s*
"(?P<desc>(?:[^"\\]+|\\(?s).(?-s))*)"\s*[})]
"#
)
.unwrap();
static ref DEC_DEPRECATED_LINT_RE: Regex = Regex::new(
r#"(?x)
declare_deprecated_lint!\s*[{(]\s*
(?:\s+///.*)*
\s+pub\s+(?P<name>[A-Z_][A-Z_0-9]*)\s*,\s*
"(?P<desc>(?:[^"\\]+|\\(?s).(?-s))*)"\s*[})]
"#
)
.unwrap();
static ref NL_ESCAPE_RE: Regex = Regex::new(r#"\\\n\s*"#).unwrap();
pub static ref DOCS_LINK: String = "https://rust-lang.github.io/rust-clippy/master/index.html".to_string();
}
/// Lint data parsed from the Clippy source code.
#[derive(Clone, PartialEq, Debug)]
pub struct Lint {
pub name: String,
pub group: String,
pub desc: String,
pub deprecation: Option<String>,
pub module: String,
}
impl Lint {
#[must_use]
pub fn new(name: &str, group: &str, desc: &str, deprecation: Option<&str>, module: &str) -> Self {
Self {
name: name.to_lowercase(),
group: group.to_string(),
desc: NL_ESCAPE_RE.replace(&desc.replace("\\\"", "\""), "").to_string(),
deprecation: deprecation.map(std::string::ToString::to_string),
module: module.to_string(),
}
}
/// Returns all non-deprecated lints and non-internal lints
pub fn usable_lints(lints: impl Iterator<Item = Self>) -> impl Iterator<Item = Self> {
lints.filter(|l| l.deprecation.is_none() && !l.is_internal())
}
/// Returns the lints in a `HashMap`, grouped by the different lint groups
#[must_use]
pub fn by_lint_group(lints: &[Self]) -> HashMap<String, Vec<Self>> {
lints
.iter()
.map(|lint| (lint.group.to_string(), lint.clone()))
.into_group_map()
}
#[must_use]
pub fn is_internal(&self) -> bool {
self.group.starts_with("internal")
}
}
/// Generates the Vec items for `register_lint_group` calls in `clippy_lints/src/lib.rs`.
#[must_use]
pub fn gen_lint_group_list(lints: Vec<Lint>) -> Vec<String> {
lints
.into_iter()
.filter_map(|l| {
if l.is_internal() || l.deprecation.is_some() {
None
} else {
Some(format!(" LintId::of(&{}::{}),", l.module, l.name.to_uppercase()))
}
})
.sorted()
.collect::<Vec<String>>()
}
/// Generates the `pub mod module_name` list in `clippy_lints/src/lib.rs`.
#[must_use]
pub fn gen_modules_list(lints: Vec<Lint>) -> Vec<String> {
lints
.into_iter()
.filter_map(|l| {
if l.is_internal() || l.deprecation.is_some() {
None
} else {
Some(l.module)
}
})
.unique()
.map(|module| format!("pub mod {};", module))
.sorted()
.collect::<Vec<String>>()
}
/// Generates the list of lint links at the bottom of the README
#[must_use]
pub fn gen_changelog_lint_list(lints: Vec<Lint>) -> Vec<String> {
let mut lint_list_sorted: Vec<Lint> = lints;
lint_list_sorted.sort_by_key(|l| l.name.clone());
lint_list_sorted
.iter()
.filter_map(|l| {
if l.is_internal() {
None
} else {
Some(format!("[`{}`]: {}#{}", l.name, DOCS_LINK.clone(), l.name))
}
})
.collect()
}
/// Generates the `register_removed` code in `./clippy_lints/src/lib.rs`.
#[must_use]
pub fn gen_deprecated(lints: &[Lint]) -> Vec<String> {
lints
.iter()
.filter_map(|l| {
l.clone().deprecation.map(|depr_text| {
vec![
" store.register_removed(".to_string(),
format!(" \"clippy::{}\",", l.name),
format!(" \"{}\",", depr_text),
" );".to_string(),
]
})
})
.flatten()
.collect::<Vec<String>>()
}
#[must_use]
pub fn gen_register_lint_list(lints: &[Lint]) -> Vec<String> {
let pre = " store.register_lints(&[".to_string();
let post = " ]);".to_string();
let mut inner = lints
.iter()
.filter_map(|l| {
if !l.is_internal() && l.deprecation.is_none() {
Some(format!(" &{}::{},", l.module, l.name.to_uppercase()))
} else {
None
}
})
.sorted()
.collect::<Vec<String>>();
inner.insert(0, pre);
inner.push(post);
inner
}
/// Gathers all files in `src/clippy_lints` and gathers all lints inside
pub fn gather_all() -> impl Iterator<Item = Lint> {
lint_files().flat_map(|f| gather_from_file(&f))
}
fn gather_from_file(dir_entry: &walkdir::DirEntry) -> impl Iterator<Item = Lint> {
let mut file = fs::File::open(dir_entry.path()).unwrap();
let mut content = String::new();
file.read_to_string(&mut content).unwrap();
let mut filename = dir_entry.path().file_stem().unwrap().to_str().unwrap();
// If the lints are stored in mod.rs, we get the module name from
// the containing directory:
if filename == "mod" {
filename = dir_entry
.path()
.parent()
.unwrap()
.file_stem()
.unwrap()
.to_str()
.unwrap()
}
parse_contents(&content, filename)
}
fn parse_contents(content: &str, filename: &str) -> impl Iterator<Item = Lint> {
let lints = DEC_CLIPPY_LINT_RE
.captures_iter(content)
.map(|m| Lint::new(&m["name"], &m["cat"], &m["desc"], None, filename));
let deprecated = DEC_DEPRECATED_LINT_RE
.captures_iter(content)
.map(|m| Lint::new(&m["name"], "Deprecated", &m["desc"], Some(&m["desc"]), filename));
// Removing the `.collect::<Vec<Lint>>().into_iter()` causes some lifetime issues due to the map
lints.chain(deprecated).collect::<Vec<Lint>>().into_iter()
}
/// Collects all .rs files in the `clippy_lints/src` directory
fn lint_files() -> impl Iterator<Item = walkdir::DirEntry> {
// We use `WalkDir` instead of `fs::read_dir` here in order to recurse into subdirectories.
// Otherwise we would not collect all the lints, for example in `clippy_lints/src/methods/`.
WalkDir::new("../clippy_lints/src")
.into_iter()
.filter_map(std::result::Result::ok)
.filter(|f| f.path().extension() == Some(OsStr::new("rs")))
}
/// Whether a file has had its text changed or not
#[derive(PartialEq, Debug)]
pub struct FileChange {
pub changed: bool,
pub new_lines: String,
}
/// Replaces a region in a file delimited by two lines matching regexes.
///
/// `path` is the relative path to the file on which you want to perform the replacement.
///
/// See `replace_region_in_text` for documentation of the other options.
#[allow(clippy::expect_fun_call)]
pub fn replace_region_in_file<F>(
path: &str,
start: &str,
end: &str,
replace_start: bool,
write_back: bool,
replacements: F,
) -> FileChange
where
F: Fn() -> Vec<String>,
{
let mut f = fs::File::open(path).expect(&format!("File not found: {}", path));
let mut contents = String::new();
f.read_to_string(&mut contents)
.expect("Something went wrong reading the file");
let file_change = replace_region_in_text(&contents, start, end, replace_start, replacements);
if write_back {
let mut f = fs::File::create(path).expect(&format!("File not found: {}", path));
f.write_all(file_change.new_lines.as_bytes())
.expect("Unable to write file");
// Ensure we write the changes with a trailing newline so that
// the file has the proper line endings.
f.write_all(b"\n").expect("Unable to write file");
}
file_change
}
/// Replaces a region in a text delimited by two lines matching regexes.
///
/// * `text` is the input text on which you want to perform the replacement
/// * `start` is a `&str` that describes the delimiter line before the region you want to replace.
/// As the `&str` will be converted to a `Regex`, this can contain regex syntax, too.
/// * `end` is a `&str` that describes the delimiter line until where the replacement should happen.
/// As the `&str` will be converted to a `Regex`, this can contain regex syntax, too.
/// * If `replace_start` is true, the `start` delimiter line is replaced as well. The `end`
/// delimiter line is never replaced.
/// * `replacements` is a closure that has to return a `Vec<String>` which contains the new text.
///
/// If you want to perform the replacement on files instead of already parsed text,
/// use `replace_region_in_file`.
///
/// # Example
///
/// ```
/// let the_text = "replace_start\nsome text\nthat will be replaced\nreplace_end";
/// let result = clippy_dev::replace_region_in_text(the_text, r#"replace_start"#, r#"replace_end"#, false, || {
/// vec!["a different".to_string(), "text".to_string()]
/// })
/// .new_lines;
/// assert_eq!("replace_start\na different\ntext\nreplace_end", result);
/// ```
pub fn replace_region_in_text<F>(text: &str, start: &str, end: &str, replace_start: bool, replacements: F) -> FileChange
where
F: Fn() -> Vec<String>,
{
let lines = text.lines();
let mut in_old_region = false;
let mut found = false;
let mut new_lines = vec![];
let start = Regex::new(start).unwrap();
let end = Regex::new(end).unwrap();
for line in lines.clone() {
if in_old_region {
if end.is_match(&line) {
in_old_region = false;
new_lines.extend(replacements());
new_lines.push(line.to_string());
}
} else if start.is_match(&line) {
if !replace_start {
new_lines.push(line.to_string());
}
in_old_region = true;
found = true;
} else {
new_lines.push(line.to_string());
}
}
if !found {
// This happens if the provided regex in `clippy_dev/src/main.rs` is not found in the
// given text or file. Most likely this is an error on the programmer's side and the Regex
// is incorrect.
eprintln!("error: regex `{:?}` not found. You may have to update it.", start);
}
FileChange {
changed: lines.ne(new_lines.clone()),
new_lines: new_lines.join("\n"),
}
}
#[test]
fn test_parse_contents() {
let result: Vec<Lint> = parse_contents(
r#"
declare_clippy_lint! {
pub PTR_ARG,
style,
"really long \
text"
}
declare_clippy_lint!{
pub DOC_MARKDOWN,
pedantic,
"single line"
}
/// some doc comment
declare_deprecated_lint! {
pub SHOULD_ASSERT_EQ,
"`assert!()` will be more flexible with RFC 2011"
}
"#,
"module_name",
)
.collect();
let expected = vec![
Lint::new("ptr_arg", "style", "really long text", None, "module_name"),
Lint::new("doc_markdown", "pedantic", "single line", None, "module_name"),
Lint::new(
"should_assert_eq",
"Deprecated",
"`assert!()` will be more flexible with RFC 2011",
Some("`assert!()` will be more flexible with RFC 2011"),
"module_name",
),
];
assert_eq!(expected, result);
}
#[test]
fn test_replace_region() {
let text = "\nabc\n123\n789\ndef\nghi";
let expected = FileChange {
changed: true,
new_lines: "\nabc\nhello world\ndef\nghi".to_string(),
};
let result = replace_region_in_text(text, r#"^\s*abc$"#, r#"^\s*def"#, false, || {
vec!["hello world".to_string()]
});
assert_eq!(expected, result);
}
#[test]
fn test_replace_region_with_start() {
let text = "\nabc\n123\n789\ndef\nghi";
let expected = FileChange {
changed: true,
new_lines: "\nhello world\ndef\nghi".to_string(),
};
let result = replace_region_in_text(text, r#"^\s*abc$"#, r#"^\s*def"#, true, || {
vec!["hello world".to_string()]
});
assert_eq!(expected, result);
}
#[test]
fn test_replace_region_no_changes() {
let text = "123\n456\n789";
let expected = FileChange {
changed: false,
new_lines: "123\n456\n789".to_string(),
};
let result = replace_region_in_text(text, r#"^\s*123$"#, r#"^\s*456"#, false, || vec![]);
assert_eq!(expected, result);
}
#[test]
fn test_usable_lints() {
let lints = vec![
Lint::new("should_assert_eq", "Deprecated", "abc", Some("Reason"), "module_name"),
Lint::new("should_assert_eq2", "Not Deprecated", "abc", None, "module_name"),
Lint::new("should_assert_eq2", "internal", "abc", None, "module_name"),
Lint::new("should_assert_eq2", "internal_style", "abc", None, "module_name"),
];
let expected = vec![Lint::new(
"should_assert_eq2",
"Not Deprecated",
"abc",
None,
"module_name",
)];
assert_eq!(expected, Lint::usable_lints(lints.into_iter()).collect::<Vec<Lint>>());
}
#[test]
fn test_by_lint_group() {
let lints = vec![
Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
Lint::new("should_assert_eq2", "group2", "abc", None, "module_name"),
Lint::new("incorrect_match", "group1", "abc", None, "module_name"),
];
let mut expected: HashMap<String, Vec<Lint>> = HashMap::new();
expected.insert(
"group1".to_string(),
vec![
Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
Lint::new("incorrect_match", "group1", "abc", None, "module_name"),
],
);
expected.insert(
"group2".to_string(),
vec![Lint::new("should_assert_eq2", "group2", "abc", None, "module_name")],
);
assert_eq!(expected, Lint::by_lint_group(&lints));
}
#[test]
fn test_gen_changelog_lint_list()
|
#[test]
fn test_gen_deprecated() {
let lints = vec![
Lint::new(
"should_assert_eq",
"group1",
"abc",
Some("has been superseded by should_assert_eq2"),
"module_name",
),
Lint::new(
"another_deprecated",
"group2",
"abc",
Some("will be removed"),
"module_name",
),
Lint::new("should_assert_eq2", "group2", "abc", None, "module_name"),
];
let expected: Vec<String> = vec![
" store.register_removed(",
" \"clippy::should_assert_eq\",",
" \"has been superseded by should_assert_eq2\",",
" );",
" store.register_removed(",
" \"clippy::another_deprecated\",",
" \"will be removed\",",
" );",
]
.into_iter()
.map(String::from)
.collect();
assert_eq!(expected, gen_deprecated(&lints));
}
#[test]
fn test_gen_modules_list() {
let lints = vec![
Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
Lint::new("should_assert_eq2", "group2", "abc", Some("abc"), "deprecated"),
Lint::new("incorrect_stuff", "group3", "abc", None, "another_module"),
Lint::new("incorrect_internal", "internal_style", "abc", None, "module_name"),
];
let expected = vec![
"pub mod another_module;".to_string(),
"pub mod module_name;".to_string(),
];
assert_eq!(expected, gen_modules_list(lints));
}
#[test]
fn test_gen_lint_group_list() {
let lints = vec![
Lint::new("abc", "group1", "abc", None, "module_name"),
Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
Lint::new("should_assert_eq2", "group2", "abc", Some("abc"), "deprecated"),
Lint::new("incorrect_internal", "internal_style", "abc", None, "module_name"),
];
let expected = vec![
" LintId::of(&module_name::ABC),".to_string(),
" LintId::of(&module_name::SHOULD_ASSERT_EQ),".to_string(),
];
assert_eq!(expected, gen_lint_group_list(lints));
}
|
{
let lints = vec![
Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
Lint::new("should_assert_eq2", "group2", "abc", None, "module_name"),
Lint::new("incorrect_internal", "internal_style", "abc", None, "module_name"),
];
let expected = vec![
format!("[`should_assert_eq`]: {}#should_assert_eq", DOCS_LINK.to_string()),
format!("[`should_assert_eq2`]: {}#should_assert_eq2", DOCS_LINK.to_string()),
];
assert_eq!(expected, gen_changelog_lint_list(lints));
}
|
run.rs
|
use crate::cli::{self, ParseResult};
use crate::init;
use anyhow::Result;
pub fn run() -> Result<()> {
cli::print_args();
let options = match cli::parse_args() {
|
};
let engine = init::init(options)?;
engine.run()?;
Ok(())
}
|
ParseResult::Ok(options) => options,
ParseResult::Err(err) => return Err(err.into()),
ParseResult::Help | ParseResult::Version => return Ok(()),
|
mempool_persist.py
|
#!/usr/bin/env python3
# Copyright (c) 2014-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or https://www.opensource.org/licenses/mit-license.php.
"""Test mempool persistence.
By default, bitcoind will dump mempool on shutdown and
then reload it on startup. This can be overridden with
the -persistmempool=false command line option.
Test is as follows:
- start node0, node1 and node2. node1 has -persistmempool=false
- create 5 transactions on node2 to its own address. Note that these
are not sent to node0 or node1 addresses because we don't want
them to be saved in the wallet.
- check that node0 and node1 have 5 transactions in their mempools
- shutdown all nodes.
- startup node0. Verify that it still has 5 transactions
in its mempool. Shutdown node0. This tests that by default the
mempool is persistent.
- startup node1. Verify that its mempool is empty. Shutdown node1.
This tests that with -persistmempool=false, the mempool is not
dumped to disk when the node is shut down.
- Restart node0 with -persistmempool=false. Verify that its mempool is
empty. Shutdown node0. This tests that with -persistmempool=false,
the mempool is not loaded from disk on start up.
- Restart node0 with -persistmempool=true. Verify that it has 5
transactions in its mempool. This tests that -persistmempool=false
does not overwrite a previously valid mempool stored on disk.
"""
from decimal import Decimal
import os
from test_framework.test_framework import SurgeTestFramework
from test_framework.util import (
assert_equal,
wait_until,
)
class MempoolPersistTest(SurgeTestFramework):
def set_test_params(self):
|
def run_test(self):
chain_height = self.nodes[0].getblockcount()
assert_equal(chain_height, 200)
self.log.debug("Mine a single block to get out of IBD")
self.nodes[0].generate(1)
self.sync_all()
self.log.debug("Send 5 transactions from node2 (to its own address)")
for i in range(5):
self.nodes[2].sendtoaddress(self.nodes[2].getnewaddress(), Decimal("10"))
node2_balance = self.nodes[2].getbalance()
self.sync_all()
self.log.debug("Verify that node0 and node1 have 5 transactions in their mempools")
assert_equal(len(self.nodes[0].getrawmempool()), 5)
assert_equal(len(self.nodes[1].getrawmempool()), 5)
self.log.debug("Stop-start node0 and node1. Verify that node0 has the transactions in its mempool and node1 does not.")
self.stop_nodes()
# Give this node a head-start, so we can be "extra-sure" that it didn't load anything later
# Also don't store the mempool, to keep the datadir clean
self.start_node(1, extra_args=["-persistmempool=0"])
self.start_node(0)
self.start_node(2)
assert self.nodes[0].getmempoolinfo()["loaded"] # start_node is blocking on the mempool being loaded
assert self.nodes[2].getmempoolinfo()["loaded"]
assert_equal(len(self.nodes[0].getrawmempool()), 5)
assert_equal(len(self.nodes[2].getrawmempool()), 5)
# The others have loaded their mempool. If node_1 loaded anything, we'd probably notice by now:
assert_equal(len(self.nodes[1].getrawmempool()), 0)
# Verify accounting of mempool transactions after restart is correct
self.nodes[2].syncwithvalidationinterfacequeue() # Flush mempool to wallet
assert_equal(node2_balance, self.nodes[2].getbalance())
self.log.debug("Stop-start node0 with -persistmempool=0. Verify that it doesn't load its mempool.dat file.")
self.stop_nodes()
self.start_node(0, extra_args=["-persistmempool=0"])
assert self.nodes[0].getmempoolinfo()["loaded"]
assert_equal(len(self.nodes[0].getrawmempool()), 0)
self.log.debug("Stop-start node0. Verify that it has the transactions in its mempool.")
self.stop_nodes()
self.start_node(0)
assert self.nodes[0].getmempoolinfo()["loaded"]
assert_equal(len(self.nodes[0].getrawmempool()), 5)
# Following code is ahead of our current repository state. Future back port.
'''
mempooldat0 = os.path.join(self.nodes[0].datadir, 'regtest', 'mempool.dat')
mempooldat1 = os.path.join(self.nodes[1].datadir, 'regtest', 'mempool.dat')
self.log.debug("Remove the mempool.dat file. Verify that savemempool to disk via RPC re-creates it")
os.remove(mempooldat0)
self.nodes[0].savemempool()
assert os.path.isfile(mempooldat0)
self.log.debug("Stop nodes, make node1 use mempool.dat from node0. Verify it has 5 transactions")
os.rename(mempooldat0, mempooldat1)
self.stop_nodes()
self.start_node(1, extra_args=[])
assert self.nodes[0].getmempoolinfo()["loaded"]
assert_equal(len(self.nodes[1].getrawmempool()), 5)
self.log.debug("Prevent bitcoind from writing mempool.dat to disk. Verify that `savemempool` fails")
# to test the exception we are creating a tmp folder called mempool.dat.new
# which is an implementation detail that could change and break this test
mempooldotnew1 = mempooldat1 + '.new'
os.mkdir(mempooldotnew1)
assert_raises_rpc_error(-1, "Unable to dump mempool to disk", self.nodes[1].savemempool)
os.rmdir(mempooldotnew1)
'''
if __name__ == '__main__':
MempoolPersistTest().main()
|
self.num_nodes = 3
self.extra_args = [[], ["-persistmempool=0"], []]
|
mod.rs
|
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
pub use self::Variance::*;
pub use self::DtorKind::*;
pub use self::AssociatedItemContainer::*;
pub use self::BorrowKind::*;
pub use self::IntVarValue::*;
pub use self::LvaluePreference::*;
pub use self::fold::TypeFoldable;
use dep_graph::{self, DepNode};
use hir::map as ast_map;
use middle;
use hir::def::{Def, CtorKind, PathResolution, ExportMap};
use hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
use middle::lang_items::{FnTraitLangItem, FnMutTraitLangItem, FnOnceTraitLangItem};
use middle::region::{CodeExtent, ROOT_CODE_EXTENT};
use mir::Mir;
use traits;
use ty;
use ty::subst::{Subst, Substs};
use ty::walk::TypeWalker;
use util::common::MemoizationMap;
use util::nodemap::NodeSet;
use util::nodemap::{FxHashMap, FxHashSet};
use serialize::{self, Encodable, Encoder};
use std::borrow::Cow;
use std::cell::{Cell, RefCell, Ref};
use std::hash::{Hash, Hasher};
use std::iter;
use std::ops::Deref;
use std::rc::Rc;
use std::slice;
use std::vec::IntoIter;
use std::mem;
use syntax::ast::{self, Name, NodeId};
use syntax::attr;
use syntax::symbol::{Symbol, InternedString};
use syntax_pos::{DUMMY_SP, Span};
use rustc_const_math::ConstInt;
use rustc_data_structures::accumulate_vec::IntoIter as AccIntoIter;
use hir;
use hir::itemlikevisit::ItemLikeVisitor;
pub use self::sty::{Binder, DebruijnIndex};
pub use self::sty::{BuiltinBound, BuiltinBounds};
pub use self::sty::{BareFnTy, FnSig, PolyFnSig};
pub use self::sty::{ClosureTy, InferTy, ParamTy, ProjectionTy, TraitObject};
pub use self::sty::{ClosureSubsts, TypeAndMut};
pub use self::sty::{TraitRef, TypeVariants, PolyTraitRef};
pub use self::sty::{ExistentialTraitRef, PolyExistentialTraitRef};
pub use self::sty::{ExistentialProjection, PolyExistentialProjection};
pub use self::sty::{BoundRegion, EarlyBoundRegion, FreeRegion, Region};
pub use self::sty::Issue32330;
pub use self::sty::{TyVid, IntVid, FloatVid, RegionVid, SkolemizedRegionVid};
pub use self::sty::BoundRegion::*;
pub use self::sty::InferTy::*;
pub use self::sty::Region::*;
pub use self::sty::TypeVariants::*;
pub use self::sty::BuiltinBound::Send as BoundSend;
pub use self::sty::BuiltinBound::Sized as BoundSized;
pub use self::sty::BuiltinBound::Copy as BoundCopy;
pub use self::sty::BuiltinBound::Sync as BoundSync;
pub use self::contents::TypeContents;
pub use self::context::{TyCtxt, tls};
pub use self::context::{CtxtArenas, Lift, Tables};
pub use self::trait_def::{TraitDef, TraitFlags};
pub mod adjustment;
pub mod cast;
pub mod error;
pub mod fast_reject;
pub mod fold;
pub mod item_path;
pub mod layout;
pub mod _match;
pub mod maps;
pub mod outlives;
pub mod relate;
pub mod subst;
pub mod trait_def;
pub mod walk;
pub mod wf;
pub mod util;
mod contents;
mod context;
mod flags;
mod ivar;
mod structural_impls;
mod sty;
pub type Disr = ConstInt;
// Data types
/// The complete set of all analyses described in this module. This is
/// produced by the driver and fed to trans and later passes.
#[derive(Clone)]
pub struct CrateAnalysis<'a> {
pub export_map: ExportMap,
pub access_levels: middle::privacy::AccessLevels,
pub reachable: NodeSet,
pub name: &'a str,
pub glob_map: Option<hir::GlobMap>,
}
#[derive(Copy, Clone)]
pub enum DtorKind {
NoDtor,
TraitDtor
}
impl DtorKind {
pub fn is_present(&self) -> bool {
match *self {
TraitDtor => true,
_ => false
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum AssociatedItemContainer {
TraitContainer(DefId),
ImplContainer(DefId),
}
impl AssociatedItemContainer {
pub fn id(&self) -> DefId {
match *self {
TraitContainer(id) => id,
ImplContainer(id) => id,
}
}
}
/// The "header" of an impl is everything outside the body: a Self type, a trait
/// ref (in the case of a trait impl), and a set of predicates (from the
/// bounds/where clauses).
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct ImplHeader<'tcx> {
pub impl_def_id: DefId,
pub self_ty: Ty<'tcx>,
pub trait_ref: Option<TraitRef<'tcx>>,
pub predicates: Vec<Predicate<'tcx>>,
}
impl<'a, 'gcx, 'tcx> ImplHeader<'tcx> {
pub fn with_fresh_ty_vars(selcx: &mut traits::SelectionContext<'a, 'gcx, 'tcx>,
impl_def_id: DefId)
-> ImplHeader<'tcx>
{
let tcx = selcx.tcx();
let impl_substs = selcx.infcx().fresh_substs_for_item(DUMMY_SP, impl_def_id);
let header = ImplHeader {
impl_def_id: impl_def_id,
self_ty: tcx.item_type(impl_def_id),
trait_ref: tcx.impl_trait_ref(impl_def_id),
predicates: tcx.item_predicates(impl_def_id).predicates
}.subst(tcx, impl_substs);
let traits::Normalized { value: mut header, obligations } =
traits::normalize(selcx, traits::ObligationCause::dummy(), &header);
header.predicates.extend(obligations.into_iter().map(|o| o.predicate));
header
}
}
#[derive(Copy, Clone, Debug)]
pub struct AssociatedItem {
pub def_id: DefId,
pub name: Name,
pub kind: AssociatedKind,
pub vis: Visibility,
pub defaultness: hir::Defaultness,
pub container: AssociatedItemContainer,
/// Whether this is a method with an explicit self
/// as its first argument, allowing method calls.
pub method_has_self_argument: bool,
}
#[derive(Copy, Clone, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable)]
pub enum AssociatedKind {
Const,
Method,
Type
}
impl AssociatedItem {
pub fn def(&self) -> Def {
match self.kind {
AssociatedKind::Const => Def::AssociatedConst(self.def_id),
AssociatedKind::Method => Def::Method(self.def_id),
AssociatedKind::Type => Def::AssociatedTy(self.def_id),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Copy, RustcEncodable, RustcDecodable)]
pub enum Visibility {
/// Visible everywhere (including in other crates).
Public,
/// Visible only in the given crate-local module.
Restricted(NodeId),
/// Not visible anywhere in the local crate. This is the visibility of private external items.
PrivateExternal,
}
pub trait NodeIdTree {
fn is_descendant_of(&self, node: NodeId, ancestor: NodeId) -> bool;
}
impl<'a> NodeIdTree for ast_map::Map<'a> {
fn is_descendant_of(&self, node: NodeId, ancestor: NodeId) -> bool {
let mut node_ancestor = node;
while node_ancestor != ancestor {
let node_ancestor_parent = self.get_module_parent(node_ancestor);
if node_ancestor_parent == node_ancestor {
return false;
}
node_ancestor = node_ancestor_parent;
}
true
}
}
impl Visibility {
pub fn from_hir(visibility: &hir::Visibility, id: NodeId, tcx: TyCtxt) -> Self {
match *visibility {
hir::Public => Visibility::Public,
hir::Visibility::Crate => Visibility::Restricted(ast::CRATE_NODE_ID),
hir::Visibility::Restricted { id, .. } => match tcx.expect_def(id) {
// If there is no resolution, `resolve` will have already reported an error, so
// assume that the visibility is public to avoid reporting more privacy errors.
Def::Err => Visibility::Public,
def => Visibility::Restricted(tcx.map.as_local_node_id(def.def_id()).unwrap()),
},
hir::Inherited => Visibility::Restricted(tcx.map.get_module_parent(id)),
}
}
/// Returns true if an item with this visibility is accessible from the given block.
pub fn is_accessible_from<T: NodeIdTree>(self, block: NodeId, tree: &T) -> bool {
let restriction = match self {
// Public items are visible everywhere.
Visibility::Public => return true,
// Private items from other crates are visible nowhere.
Visibility::PrivateExternal => return false,
// Restricted items are visible in an arbitrary local module.
Visibility::Restricted(module) => module,
};
tree.is_descendant_of(block, restriction)
}
/// Returns true if this visibility is at least as accessible as the given visibility
pub fn is_at_least<T: NodeIdTree>(self, vis: Visibility, tree: &T) -> bool {
let vis_restriction = match vis {
Visibility::Public => return self == Visibility::Public,
Visibility::PrivateExternal => return true,
Visibility::Restricted(module) => module,
};
self.is_accessible_from(vis_restriction, tree)
}
}
#[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Copy)]
pub enum Variance {
Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
}
#[derive(Clone, Copy, Debug, RustcDecodable, RustcEncodable)]
pub struct MethodCallee<'tcx> {
/// Impl method ID, for inherent methods, or trait method ID, otherwise.
pub def_id: DefId,
pub ty: Ty<'tcx>,
pub substs: &'tcx Substs<'tcx>
}
/// With method calls, we store some extra information in
/// side tables (i.e method_map). We use
/// MethodCall as a key to index into these tables instead of
/// just directly using the expression's NodeId. The reason
/// for this being that we may apply adjustments (coercions)
/// with the resulting expression also needing to use the
/// side tables. The problem with this is that we don't
/// assign a separate NodeId to this new expression
/// and so it would clash with the base expression if both
/// needed to add to the side tables. Thus to disambiguate
/// we also keep track of whether there's an adjustment in
/// our key.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct MethodCall {
pub expr_id: NodeId,
pub autoderef: u32
}
impl MethodCall {
pub fn expr(id: NodeId) -> MethodCall {
MethodCall {
expr_id: id,
autoderef: 0
}
}
pub fn autoderef(expr_id: NodeId, autoderef: u32) -> MethodCall {
MethodCall {
expr_id: expr_id,
autoderef: 1 + autoderef
}
}
}
// maps from an expression id that corresponds to a method call to the details
// of the method to be invoked
pub type MethodMap<'tcx> = FxHashMap<MethodCall, MethodCallee<'tcx>>;
// Contains information needed to resolve types and (in the future) look up
// the types of AST nodes.
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
pub struct CReaderCacheKey {
pub cnum: CrateNum,
pub pos: usize,
}
/// Describes the fragment-state associated with a NodeId.
///
/// Currently only unfragmented paths have entries in the table,
/// but longer-term this enum is expected to expand to also
/// include data for fragmented paths.
#[derive(Copy, Clone, Debug)]
pub enum FragmentInfo {
Moved { var: NodeId, move_expr: NodeId },
Assigned { var: NodeId, assign_expr: NodeId, assignee_id: NodeId },
}
// Flags that we track on types. These flags are propagated upwards
// through the type during type construction, so that we can quickly
// check whether the type has various kinds of types in it without
// recursing over the type itself.
bitflags! {
flags TypeFlags: u32 {
const HAS_PARAMS = 1 << 0,
const HAS_SELF = 1 << 1,
const HAS_TY_INFER = 1 << 2,
const HAS_RE_INFER = 1 << 3,
const HAS_RE_SKOL = 1 << 4,
const HAS_RE_EARLY_BOUND = 1 << 5,
const HAS_FREE_REGIONS = 1 << 6,
const HAS_TY_ERR = 1 << 7,
const HAS_PROJECTION = 1 << 8,
const HAS_TY_CLOSURE = 1 << 9,
// true if there are "names" of types and regions and so forth
// that are local to a particular fn
const HAS_LOCAL_NAMES = 1 << 10,
// Present if the type belongs in a local type context.
// Only set for TyInfer other than Fresh.
const KEEP_IN_LOCAL_TCX = 1 << 11,
// Is there a projection that does not involve a bound region?
// Currently we can't normalize projections w/ bound regions.
const HAS_NORMALIZABLE_PROJECTION = 1 << 12,
const NEEDS_SUBST = TypeFlags::HAS_PARAMS.bits |
TypeFlags::HAS_SELF.bits |
TypeFlags::HAS_RE_EARLY_BOUND.bits,
// Flags representing the nominal content of a type,
// computed by FlagsComputation. If you add a new nominal
// flag, it should be added here too.
const NOMINAL_FLAGS = TypeFlags::HAS_PARAMS.bits |
TypeFlags::HAS_SELF.bits |
TypeFlags::HAS_TY_INFER.bits |
TypeFlags::HAS_RE_INFER.bits |
TypeFlags::HAS_RE_SKOL.bits |
TypeFlags::HAS_RE_EARLY_BOUND.bits |
TypeFlags::HAS_FREE_REGIONS.bits |
TypeFlags::HAS_TY_ERR.bits |
TypeFlags::HAS_PROJECTION.bits |
TypeFlags::HAS_TY_CLOSURE.bits |
TypeFlags::HAS_LOCAL_NAMES.bits |
TypeFlags::KEEP_IN_LOCAL_TCX.bits,
// Caches for type_is_sized, type_moves_by_default
const SIZEDNESS_CACHED = 1 << 16,
const IS_SIZED = 1 << 17,
const MOVENESS_CACHED = 1 << 18,
const MOVES_BY_DEFAULT = 1 << 19,
}
}
pub struct TyS<'tcx> {
pub sty: TypeVariants<'tcx>,
pub flags: Cell<TypeFlags>,
// the maximal depth of any bound regions appearing in this type.
region_depth: u32,
}
impl<'tcx> PartialEq for TyS<'tcx> {
#[inline]
fn eq(&self, other: &TyS<'tcx>) -> bool {
// (self as *const _) == (other as *const _)
(self as *const TyS<'tcx>) == (other as *const TyS<'tcx>)
}
}
impl<'tcx> Eq for TyS<'tcx> {}
impl<'tcx> Hash for TyS<'tcx> {
fn hash<H: Hasher>(&self, s: &mut H) {
(self as *const TyS).hash(s)
}
}
pub type Ty<'tcx> = &'tcx TyS<'tcx>;
impl<'tcx> serialize::UseSpecializedEncodable for Ty<'tcx> {}
impl<'tcx> serialize::UseSpecializedDecodable for Ty<'tcx> {}
/// A wrapper for slices with the additional invariant
/// that the slice is interned and no other slice with
/// the same contents can exist in the same context.
/// This means we can use pointer + length for both
/// equality comparisons and hashing.
#[derive(Debug, RustcEncodable)]
pub struct Slice<T>([T]);
impl<T> PartialEq for Slice<T> {
#[inline]
fn eq(&self, other: &Slice<T>) -> bool {
(&self.0 as *const [T]) == (&other.0 as *const [T])
}
}
impl<T> Eq for Slice<T> {}
impl<T> Hash for Slice<T> {
fn hash<H: Hasher>(&self, s: &mut H) {
(self.as_ptr(), self.len()).hash(s)
}
}
impl<T> Deref for Slice<T> {
type Target = [T];
fn deref(&self) -> &[T] {
&self.0
}
}
impl<'a, T> IntoIterator for &'a Slice<T> {
type Item = &'a T;
type IntoIter = <&'a [T] as IntoIterator>::IntoIter;
fn into_iter(self) -> Self::IntoIter {
self[..].iter()
}
}
impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Slice<Ty<'tcx>> {}
impl<T> Slice<T> {
pub fn empty<'a>() -> &'a Slice<T> {
unsafe {
mem::transmute(slice::from_raw_parts(0x1 as *const T, 0))
}
}
}
/// Upvars do not get their own node-id. Instead, we use the pair of
/// the original var id (that is, the root variable that is referenced
/// by the upvar) and the id of the closure expression.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct UpvarId {
pub var_id: NodeId,
pub closure_expr_id: NodeId,
}
#[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable, Copy)]
pub enum BorrowKind {
/// Data must be immutable and is aliasable.
ImmBorrow,
/// Data must be immutable but not aliasable. This kind of borrow
/// cannot currently be expressed by the user and is used only in
/// implicit closure bindings. It is needed when you the closure
/// is borrowing or mutating a mutable referent, e.g.:
///
/// let x: &mut isize = ...;
/// let y = || *x += 5;
///
/// If we were to try to translate this closure into a more explicit
/// form, we'd encounter an error with the code as written:
///
/// struct Env { x: & &mut isize }
/// let x: &mut isize = ...;
/// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
/// fn fn_ptr(env: &mut Env) { **env.x += 5; }
///
/// This is then illegal because you cannot mutate a `&mut` found
/// in an aliasable location. To solve, you'd have to translate with
/// an `&mut` borrow:
///
/// struct Env { x: & &mut isize }
/// let x: &mut isize = ...;
/// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
/// fn fn_ptr(env: &mut Env) { **env.x += 5; }
///
/// Now the assignment to `**env.x` is legal, but creating a
/// mutable pointer to `x` is not because `x` is not mutable. We
/// could fix this by declaring `x` as `let mut x`. This is ok in
/// user code, if awkward, but extra weird for closures, since the
/// borrow is hidden.
///
/// So we introduce a "unique imm" borrow -- the referent is
/// immutable, but not aliasable. This solves the problem. For
/// simplicity, we don't give users the way to express this
/// borrow, it's just used when translating closures.
UniqueImmBorrow,
/// Data is mutable and not aliasable.
MutBorrow
}
/// Information describing the capture of an upvar. This is computed
/// during `typeck`, specifically by `regionck`.
#[derive(PartialEq, Clone, Debug, Copy, RustcEncodable, RustcDecodable)]
pub enum UpvarCapture<'tcx> {
/// Upvar is captured by value. This is always true when the
/// closure is labeled `move`, but can also be true in other cases
/// depending on inference.
ByValue,
/// Upvar is captured by reference.
ByRef(UpvarBorrow<'tcx>),
}
#[derive(PartialEq, Clone, Copy, RustcEncodable, RustcDecodable)]
pub struct UpvarBorrow<'tcx> {
/// The kind of borrow: by-ref upvars have access to shared
/// immutable borrows, which are not part of the normal language
/// syntax.
pub kind: BorrowKind,
/// Region of the resulting reference.
pub region: &'tcx ty::Region,
}
pub type UpvarCaptureMap<'tcx> = FxHashMap<UpvarId, UpvarCapture<'tcx>>;
#[derive(Copy, Clone)]
pub struct ClosureUpvar<'tcx> {
pub def: Def,
pub span: Span,
pub ty: Ty<'tcx>,
}
#[derive(Clone, Copy, PartialEq)]
pub enum IntVarValue {
IntType(ast::IntTy),
UintType(ast::UintTy),
}
/// Default region to use for the bound of objects that are
/// supplied as the value for this type parameter. This is derived
/// from `T:'a` annotations appearing in the type definition. If
/// this is `None`, then the default is inherited from the
/// surrounding context. See RFC #599 for details.
#[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
pub enum ObjectLifetimeDefault<'tcx> {
/// Require an explicit annotation. Occurs when multiple
/// `T:'a` constraints are found.
Ambiguous,
/// Use the base default, typically 'static, but in a fn body it is a fresh variable
BaseDefault,
/// Use the given region as the default.
Specific(&'tcx Region),
}
#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct TypeParameterDef<'tcx> {
pub name: Name,
pub def_id: DefId,
pub index: u32,
pub default_def_id: DefId, // for use in error reporing about defaults
pub default: Option<Ty<'tcx>>,
pub object_lifetime_default: ObjectLifetimeDefault<'tcx>,
/// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
/// on generic parameter `T`, asserts data behind the parameter
/// `T` won't be accessed during the parent type's `Drop` impl.
pub pure_wrt_drop: bool,
}
#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct RegionParameterDef<'tcx> {
pub name: Name,
pub def_id: DefId,
pub index: u32,
pub bounds: Vec<&'tcx ty::Region>,
/// `pure_wrt_drop`, set by the (unsafe) `#[may_dangle]` attribute
/// on generic parameter `'a`, asserts data of lifetime `'a`
/// won't be accessed during the parent type's `Drop` impl.
pub pure_wrt_drop: bool,
}
impl<'tcx> RegionParameterDef<'tcx> {
pub fn to_early_bound_region(&self) -> ty::Region {
ty::ReEarlyBound(self.to_early_bound_region_data())
}
pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
ty::EarlyBoundRegion {
index: self.index,
name: self.name,
}
}
pub fn to_bound_region(&self) -> ty::BoundRegion {
// this is an early bound region, so unaffected by #32330
ty::BoundRegion::BrNamed(self.def_id, self.name, Issue32330::WontChange)
}
}
/// Information about the formal type/lifetime parameters associated
/// with an item or method. Analogous to hir::Generics.
#[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
pub struct Generics<'tcx> {
pub parent: Option<DefId>,
pub parent_regions: u32,
pub parent_types: u32,
pub regions: Vec<RegionParameterDef<'tcx>>,
pub types: Vec<TypeParameterDef<'tcx>>,
pub has_self: bool,
}
impl<'tcx> Generics<'tcx> {
pub fn parent_count(&self) -> usize {
self.parent_regions as usize + self.parent_types as usize
}
pub fn own_count(&self) -> usize {
self.regions.len() + self.types.len()
}
pub fn count(&self) -> usize {
self.parent_count() + self.own_count()
}
pub fn region_param(&self, param: &EarlyBoundRegion) -> &RegionParameterDef<'tcx> {
&self.regions[param.index as usize - self.has_self as usize]
}
pub fn type_param(&self, param: &ParamTy) -> &TypeParameterDef<'tcx> {
&self.types[param.idx as usize - self.has_self as usize - self.regions.len()]
}
}
/// Bounds on generics.
#[derive(Clone)]
pub struct GenericPredicates<'tcx> {
pub parent: Option<DefId>,
pub predicates: Vec<Predicate<'tcx>>,
}
impl<'tcx> serialize::UseSpecializedEncodable for GenericPredicates<'tcx> {}
impl<'tcx> serialize::UseSpecializedDecodable for GenericPredicates<'tcx> {}
impl<'a, 'gcx, 'tcx> GenericPredicates<'tcx> {
pub fn instantiate(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, substs: &Substs<'tcx>)
-> InstantiatedPredicates<'tcx> {
let mut instantiated = InstantiatedPredicates::empty();
self.instantiate_into(tcx, &mut instantiated, substs);
instantiated
}
pub fn instantiate_own(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, substs: &Substs<'tcx>)
-> InstantiatedPredicates<'tcx> {
InstantiatedPredicates {
predicates: self.predicates.subst(tcx, substs)
}
}
fn instantiate_into(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
instantiated: &mut InstantiatedPredicates<'tcx>,
substs: &Substs<'tcx>) {
if let Some(def_id) = self.parent {
tcx.item_predicates(def_id).instantiate_into(tcx, instantiated, substs);
}
instantiated.predicates.extend(self.predicates.iter().map(|p| p.subst(tcx, substs)))
}
pub fn instantiate_supertrait(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
poly_trait_ref: &ty::PolyTraitRef<'tcx>)
-> InstantiatedPredicates<'tcx>
{
assert_eq!(self.parent, None);
InstantiatedPredicates {
predicates: self.predicates.iter().map(|pred| {
pred.subst_supertrait(tcx, poly_trait_ref)
}).collect()
}
}
}
#[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
pub enum Predicate<'tcx> {
/// Corresponds to `where Foo : Bar<A,B,C>`. `Foo` here would be
/// the `Self` type of the trait reference and `A`, `B`, and `C`
/// would be the type parameters.
Trait(PolyTraitPredicate<'tcx>),
/// where `T1 == T2`.
Equate(PolyEquatePredicate<'tcx>),
/// where 'a : 'b
RegionOutlives(PolyRegionOutlivesPredicate<'tcx>),
/// where T : 'a
TypeOutlives(PolyTypeOutlivesPredicate<'tcx>),
/// where <T as TraitRef>::Name == X, approximately.
/// See `ProjectionPredicate` struct for details.
Projection(PolyProjectionPredicate<'tcx>),
/// no syntax: T WF
WellFormed(Ty<'tcx>),
/// trait must be object-safe
ObjectSafe(DefId),
/// No direct syntax. May be thought of as `where T : FnFoo<...>`
/// for some substitutions `...` and T being a closure type.
/// Satisfied (or refuted) once we know the closure's kind.
ClosureKind(DefId, ClosureKind),
}
impl<'a, 'gcx, 'tcx> Predicate<'tcx> {
/// Performs a substitution suitable for going from a
/// poly-trait-ref to supertraits that must hold if that
/// poly-trait-ref holds. This is slightly different from a normal
/// substitution in terms of what happens with bound regions. See
/// lengthy comment below for details.
pub fn subst_supertrait(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
trait_ref: &ty::PolyTraitRef<'tcx>)
-> ty::Predicate<'tcx>
{
// The interaction between HRTB and supertraits is not entirely
// obvious. Let me walk you (and myself) through an example.
//
// Let's start with an easy case. Consider two traits:
//
// trait Foo<'a> : Bar<'a,'a> { }
// trait Bar<'b,'c> { }
//
// Now, if we have a trait reference `for<'x> T : Foo<'x>`, then
// we can deduce that `for<'x> T : Bar<'x,'x>`. Basically, if we
// knew that `Foo<'x>` (for any 'x) then we also know that
// `Bar<'x,'x>` (for any 'x). This more-or-less falls out from
// normal substitution.
//
// In terms of why this is sound, the idea is that whenever there
// is an impl of `T:Foo<'a>`, it must show that `T:Bar<'a,'a>`
// holds. So if there is an impl of `T:Foo<'a>` that applies to
// all `'a`, then we must know that `T:Bar<'a,'a>` holds for all
// `'a`.
//
// Another example to be careful of is this:
//
// trait Foo1<'a> : for<'b> Bar1<'a,'b> { }
// trait Bar1<'b,'c> { }
//
// Here, if we have `for<'x> T : Foo1<'x>`, then what do we know?
// The answer is that we know `for<'x,'b> T : Bar1<'x,'b>`. The
// reason is similar to the previous example: any impl of
// `T:Foo1<'x>` must show that `for<'b> T : Bar1<'x, 'b>`. So
// basically we would want to collapse the bound lifetimes from
// the input (`trait_ref`) and the supertraits.
//
// To achieve this in practice is fairly straightforward. Let's
// consider the more complicated scenario:
//
// - We start out with `for<'x> T : Foo1<'x>`. In this case, `'x`
// has a De Bruijn index of 1. We want to produce `for<'x,'b> T : Bar1<'x,'b>`,
// where both `'x` and `'b` would have a DB index of 1.
// The substitution from the input trait-ref is therefore going to be
// `'a => 'x` (where `'x` has a DB index of 1).
// - The super-trait-ref is `for<'b> Bar1<'a,'b>`, where `'a` is an
// early-bound parameter and `'b' is a late-bound parameter with a
// DB index of 1.
// - If we replace `'a` with `'x` from the input, it too will have
// a DB index of 1, and thus we'll have `for<'x,'b> Bar1<'x,'b>`
// just as we wanted.
//
// There is only one catch. If we just apply the substitution `'a
// => 'x` to `for<'b> Bar1<'a,'b>`, the substitution code will
// adjust the DB index because we substituting into a binder (it
// tries to be so smart...) resulting in `for<'x> for<'b>
// Bar1<'x,'b>` (we have no syntax for this, so use your
// imagination). Basically the 'x will have DB index of 2 and 'b
// will have DB index of 1. Not quite what we want. So we apply
// the substitution to the *contents* of the trait reference,
// rather than the trait reference itself (put another way, the
// substitution code expects equal binding levels in the values
// from the substitution and the value being substituted into, and
// this trick achieves that).
let substs = &trait_ref.0.substs;
match *self {
Predicate::Trait(ty::Binder(ref data)) =>
Predicate::Trait(ty::Binder(data.subst(tcx, substs))),
Predicate::Equate(ty::Binder(ref data)) =>
Predicate::Equate(ty::Binder(data.subst(tcx, substs))),
Predicate::RegionOutlives(ty::Binder(ref data)) =>
Predicate::RegionOutlives(ty::Binder(data.subst(tcx, substs))),
Predicate::TypeOutlives(ty::Binder(ref data)) =>
Predicate::TypeOutlives(ty::Binder(data.subst(tcx, substs))),
Predicate::Projection(ty::Binder(ref data)) =>
Predicate::Projection(ty::Binder(data.subst(tcx, substs))),
Predicate::WellFormed(data) =>
Predicate::WellFormed(data.subst(tcx, substs)),
Predicate::ObjectSafe(trait_def_id) =>
Predicate::ObjectSafe(trait_def_id),
Predicate::ClosureKind(closure_def_id, kind) =>
Predicate::ClosureKind(closure_def_id, kind),
}
}
}
#[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
pub struct TraitPredicate<'tcx> {
pub trait_ref: TraitRef<'tcx>
}
pub type PolyTraitPredicate<'tcx> = ty::Binder<TraitPredicate<'tcx>>;
impl<'tcx> TraitPredicate<'tcx> {
pub fn def_id(&self) -> DefId {
self.trait_ref.def_id
}
/// Creates the dep-node for selecting/evaluating this trait reference.
fn dep_node(&self) -> DepNode<DefId> {
// Ideally, the dep-node would just have all the input types
// in it. But they are limited to including def-ids. So as an
// approximation we include the def-ids for all nominal types
// found somewhere. This means that we will e.g. conflate the
// dep-nodes for `u32: SomeTrait` and `u64: SomeTrait`, but we
// would have distinct dep-nodes for `Vec<u32>: SomeTrait`,
// `Rc<u32>: SomeTrait`, and `(Vec<u32>, Rc<u32>): SomeTrait`.
// Note that it's always sound to conflate dep-nodes, it just
// leads to more recompilation.
let def_ids: Vec<_> =
self.input_types()
.flat_map(|t| t.walk())
.filter_map(|t| match t.sty {
ty::TyAdt(adt_def, _) =>
Some(adt_def.did),
_ =>
None
})
.chain(iter::once(self.def_id()))
.collect();
DepNode::TraitSelect(def_ids)
}
pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
self.trait_ref.input_types()
}
pub fn self_ty(&self) -> Ty<'tcx> {
self.trait_ref.self_ty()
}
}
impl<'tcx> PolyTraitPredicate<'tcx> {
pub fn def_id(&self) -> DefId {
// ok to skip binder since trait def-id does not care about regions
self.0.def_id()
}
pub fn dep_node(&self) -> DepNode<DefId> {
// ok to skip binder since depnode does not care about regions
self.0.dep_node()
}
}
#[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
pub struct EquatePredicate<'tcx>(pub Ty<'tcx>, pub Ty<'tcx>); // `0 == 1`
pub type PolyEquatePredicate<'tcx> = ty::Binder<EquatePredicate<'tcx>>;
#[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
pub struct OutlivesPredicate<A,B>(pub A, pub B); // `A : B`
pub type PolyOutlivesPredicate<A,B> = ty::Binder<OutlivesPredicate<A,B>>;
pub type PolyRegionOutlivesPredicate<'tcx> = PolyOutlivesPredicate<&'tcx ty::Region,
&'tcx ty::Region>;
pub type PolyTypeOutlivesPredicate<'tcx> = PolyOutlivesPredicate<Ty<'tcx>, &'tcx ty::Region>;
/// This kind of predicate has no *direct* correspondent in the
/// syntax, but it roughly corresponds to the syntactic forms:
///
/// 1. `T : TraitRef<..., Item=Type>`
/// 2. `<T as TraitRef<...>>::Item == Type` (NYI)
///
/// In particular, form #1 is "desugared" to the combination of a
/// normal trait predicate (`T : TraitRef<...>`) and one of these
/// predicates. Form #2 is a broader form in that it also permits
/// equality between arbitrary types. Processing an instance of Form
/// #2 eventually yields one of these `ProjectionPredicate`
/// instances to normalize the LHS.
#[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
pub struct ProjectionPredicate<'tcx> {
pub projection_ty: ProjectionTy<'tcx>,
pub ty: Ty<'tcx>,
}
pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>;
impl<'tcx> PolyProjectionPredicate<'tcx> {
pub fn item_name(&self) -> Name {
self.0.projection_ty.item_name // safe to skip the binder to access a name
}
}
pub trait ToPolyTraitRef<'tcx> {
fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>;
}
impl<'tcx> ToPolyTraitRef<'tcx> for TraitRef<'tcx> {
fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
assert!(!self.has_escaping_regions());
ty::Binder(self.clone())
}
}
impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> {
fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
self.map_bound_ref(|trait_pred| trait_pred.trait_ref)
}
}
impl<'tcx> ToPolyTraitRef<'tcx> for PolyProjectionPredicate<'tcx> {
fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> {
// Note: unlike with TraitRef::to_poly_trait_ref(),
// self.0.trait_ref is permitted to have escaping regions.
// This is because here `self` has a `Binder` and so does our
// return value, so we are preserving the number of binding
// levels.
ty::Binder(self.0.projection_ty.trait_ref)
}
}
pub trait ToPredicate<'tcx> {
fn to_predicate(&self) -> Predicate<'tcx>;
}
impl<'tcx> ToPredicate<'tcx> for TraitRef<'tcx> {
fn to_predicate(&self) -> Predicate<'tcx> {
// we're about to add a binder, so let's check that we don't
// accidentally capture anything, or else that might be some
// weird debruijn accounting.
assert!(!self.has_escaping_regions());
ty::Predicate::Trait(ty::Binder(ty::TraitPredicate {
trait_ref: self.clone()
}))
}
}
impl<'tcx> ToPredicate<'tcx> for PolyTraitRef<'tcx> {
fn to_predicate(&self) -> Predicate<'tcx> {
ty::Predicate::Trait(self.to_poly_trait_predicate())
}
}
impl<'tcx> ToPredicate<'tcx> for PolyEquatePredicate<'tcx> {
fn to_predicate(&self) -> Predicate<'tcx> {
Predicate::Equate(self.clone())
}
}
impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> {
fn to_predicate(&self) -> Predicate<'tcx> {
Predicate::RegionOutlives(self.clone())
}
}
impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> {
fn to_predicate(&self) -> Predicate<'tcx> {
Predicate::TypeOutlives(self.clone())
}
}
impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> {
fn to_predicate(&self) -> Predicate<'tcx> {
Predicate::Projection(self.clone())
}
}
impl<'tcx> Predicate<'tcx> {
/// Iterates over the types in this predicate. Note that in all
/// cases this is skipping over a binder, so late-bound regions
/// with depth 0 are bound by the predicate.
pub fn walk_tys(&self) -> IntoIter<Ty<'tcx>> {
let vec: Vec<_> = match *self {
ty::Predicate::Trait(ref data) => {
data.skip_binder().input_types().collect()
}
ty::Predicate::Equate(ty::Binder(ref data)) => {
vec![data.0, data.1]
}
ty::Predicate::TypeOutlives(ty::Binder(ref data)) => {
vec![data.0]
}
ty::Predicate::RegionOutlives(..) => {
vec![]
}
ty::Predicate::Projection(ref data) => {
let trait_inputs = data.0.projection_ty.trait_ref.input_types();
trait_inputs.chain(Some(data.0.ty)).collect()
}
ty::Predicate::WellFormed(data) => {
vec![data]
}
ty::Predicate::ObjectSafe(_trait_def_id) => {
vec![]
}
ty::Predicate::ClosureKind(_closure_def_id, _kind) => {
vec![]
}
};
// The only reason to collect into a vector here is that I was
// too lazy to make the full (somewhat complicated) iterator
// type that would be needed here. But I wanted this fn to
// return an iterator conceptually, rather than a `Vec`, so as
// to be closer to `Ty::walk`.
vec.into_iter()
}
pub fn to_opt_poly_trait_ref(&self) -> Option<PolyTraitRef<'tcx>> {
match *self {
Predicate::Trait(ref t) => {
Some(t.to_poly_trait_ref())
}
Predicate::Projection(..) |
Predicate::Equate(..) |
Predicate::RegionOutlives(..) |
Predicate::WellFormed(..) |
Predicate::ObjectSafe(..) |
Predicate::ClosureKind(..) |
Predicate::TypeOutlives(..) => {
None
}
}
}
}
/// Represents the bounds declared on a particular set of type
/// parameters. Should eventually be generalized into a flag list of
/// where clauses. You can obtain a `InstantiatedPredicates` list from a
/// `GenericPredicates` by using the `instantiate` method. Note that this method
/// reflects an important semantic invariant of `InstantiatedPredicates`: while
/// the `GenericPredicates` are expressed in terms of the bound type
/// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
/// represented a set of bounds for some particular instantiation,
/// meaning that the generic parameters have been substituted with
/// their values.
///
/// Example:
///
/// struct Foo<T,U:Bar<T>> { ... }
///
/// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
/// `[[], [U:Bar<T>]]`. Now if there were some particular reference
/// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
/// [usize:Bar<isize>]]`.
#[derive(Clone)]
pub struct InstantiatedPredicates<'tcx> {
pub predicates: Vec<Predicate<'tcx>>,
}
impl<'tcx> InstantiatedPredicates<'tcx> {
pub fn empty() -> InstantiatedPredicates<'tcx> {
InstantiatedPredicates { predicates: vec![] }
}
pub fn is_empty(&self) -> bool {
self.predicates.is_empty()
}
}
impl<'tcx> TraitRef<'tcx> {
pub fn new(def_id: DefId, substs: &'tcx Substs<'tcx>) -> TraitRef<'tcx> {
TraitRef { def_id: def_id, substs: substs }
}
pub fn self_ty(&self) -> Ty<'tcx> {
self.substs.type_at(0)
}
pub fn input_types<'a>(&'a self) -> impl DoubleEndedIterator<Item=Ty<'tcx>> + 'a {
// Select only the "input types" from a trait-reference. For
// now this is all the types that appear in the
// trait-reference, but it should eventually exclude
// associated types.
self.substs.types()
}
}
/// When type checking, we use the `ParameterEnvironment` to track
/// details about the type/lifetime parameters that are in scope.
/// It primarily stores the bounds information.
///
/// Note: This information might seem to be redundant with the data in
/// `tcx.ty_param_defs`, but it is not. That table contains the
/// parameter definitions from an "outside" perspective, but this
/// struct will contain the bounds for a parameter as seen from inside
/// the function body. Currently the only real distinction is that
/// bound lifetime parameters are replaced with free ones, but in the
/// future I hope to refine the representation of types so as to make
/// more distinctions clearer.
#[derive(Clone)]
pub struct ParameterEnvironment<'tcx> {
/// See `construct_free_substs` for details.
pub free_substs: &'tcx Substs<'tcx>,
/// Each type parameter has an implicit region bound that
/// indicates it must outlive at least the function body (the user
/// may specify stronger requirements). This field indicates the
/// region of the callee.
pub implicit_region_bound: &'tcx ty::Region,
/// Obligations that the caller must satisfy. This is basically
/// the set of bounds on the in-scope type parameters, translated
/// into Obligations, and elaborated and normalized.
pub caller_bounds: Vec<ty::Predicate<'tcx>>,
/// Scope that is attached to free regions for this scope. This
/// is usually the id of the fn body, but for more abstract scopes
/// like structs we often use the node-id of the struct.
///
/// FIXME(#3696). It would be nice to refactor so that free
/// regions don't have this implicit scope and instead introduce
/// relationships in the environment.
pub free_id_outlive: CodeExtent,
/// A cache for `moves_by_default`.
pub is_copy_cache: RefCell<FxHashMap<Ty<'tcx>, bool>>,
/// A cache for `type_is_sized`
pub is_sized_cache: RefCell<FxHashMap<Ty<'tcx>, bool>>,
}
impl<'a, 'tcx> ParameterEnvironment<'tcx> {
pub fn with_caller_bounds(&self,
caller_bounds: Vec<ty::Predicate<'tcx>>)
-> ParameterEnvironment<'tcx>
{
ParameterEnvironment {
free_substs: self.free_substs,
implicit_region_bound: self.implicit_region_bound,
caller_bounds: caller_bounds,
free_id_outlive: self.free_id_outlive,
is_copy_cache: RefCell::new(FxHashMap()),
is_sized_cache: RefCell::new(FxHashMap()),
}
}
/// Construct a parameter environment given an item, impl item, or trait item
pub fn for_item(tcx: TyCtxt<'a, 'tcx, 'tcx>, id: NodeId)
-> ParameterEnvironment<'tcx> {
match tcx.map.find(id) {
Some(ast_map::NodeImplItem(ref impl_item)) => {
match impl_item.node {
hir::ImplItemKind::Type(_) | hir::ImplItemKind::Const(..) => {
// associated types don't have their own entry (for some reason),
// so for now just grab environment for the impl
let impl_id = tcx.map.get_parent(id);
let impl_def_id = tcx.map.local_def_id(impl_id);
tcx.construct_parameter_environment(impl_item.span,
impl_def_id,
tcx.region_maps.item_extent(id))
}
hir::ImplItemKind::Method(_, ref body) => {
tcx.construct_parameter_environment(
impl_item.span,
tcx.map.local_def_id(id),
tcx.region_maps.call_site_extent(id, body.id))
}
}
}
Some(ast_map::NodeTraitItem(trait_item)) => {
match trait_item.node {
hir::TypeTraitItem(..) | hir::ConstTraitItem(..) => {
// associated types don't have their own entry (for some reason),
// so for now just grab environment for the trait
let trait_id = tcx.map.get_parent(id);
let trait_def_id = tcx.map.local_def_id(trait_id);
tcx.construct_parameter_environment(trait_item.span,
trait_def_id,
tcx.region_maps.item_extent(id))
}
hir::MethodTraitItem(_, ref body) => {
// Use call-site for extent (unless this is a
// trait method with no default; then fallback
// to the method id).
let extent = if let Some(ref body) = *body {
// default impl: use call_site extent as free_id_outlive bound.
tcx.region_maps.call_site_extent(id, body.id)
} else {
// no default impl: use item extent as free_id_outlive bound.
tcx.region_maps.item_extent(id)
};
tcx.construct_parameter_environment(
trait_item.span,
tcx.map.local_def_id(id),
extent)
}
}
}
Some(ast_map::NodeItem(item)) => {
match item.node {
hir::ItemFn(.., ref body) => {
// We assume this is a function.
let fn_def_id = tcx.map.local_def_id(id);
tcx.construct_parameter_environment(
item.span,
fn_def_id,
tcx.region_maps.call_site_extent(id, body.id))
}
hir::ItemEnum(..) |
hir::ItemStruct(..) |
hir::ItemUnion(..) |
hir::ItemTy(..) |
hir::ItemImpl(..) |
hir::ItemConst(..) |
hir::ItemStatic(..) => {
let def_id = tcx.map.local_def_id(id);
tcx.construct_parameter_environment(item.span,
def_id,
tcx.region_maps.item_extent(id))
}
hir::ItemTrait(..) => {
let def_id = tcx.map.local_def_id(id);
tcx.construct_parameter_environment(item.span,
def_id,
tcx.region_maps.item_extent(id))
}
_ => {
span_bug!(item.span,
"ParameterEnvironment::for_item():
can't create a parameter \
environment for this kind of item")
}
}
}
Some(ast_map::NodeExpr(expr)) => {
// This is a convenience to allow closures to work.
if let hir::ExprClosure(..) = expr.node {
ParameterEnvironment::for_item(tcx, tcx.map.get_parent(id))
} else {
tcx.empty_parameter_environment()
}
}
Some(ast_map::NodeForeignItem(item)) => {
let def_id = tcx.map.local_def_id(id);
tcx.construct_parameter_environment(item.span,
def_id,
ROOT_CODE_EXTENT)
}
_ => {
bug!("ParameterEnvironment::from_item(): \
`{}` is not an item",
tcx.map.node_to_string(id))
}
}
}
}
bitflags! {
flags AdtFlags: u32 {
const NO_ADT_FLAGS = 0,
const IS_ENUM = 1 << 0,
const IS_DTORCK = 1 << 1, // is this a dtorck type?
const IS_DTORCK_VALID = 1 << 2,
const IS_PHANTOM_DATA = 1 << 3,
const IS_SIMD = 1 << 4,
const IS_FUNDAMENTAL = 1 << 5,
const IS_UNION = 1 << 6,
}
}
pub type AdtDef<'tcx> = &'tcx AdtDefData<'tcx, 'static>;
pub type VariantDef<'tcx> = &'tcx VariantDefData<'tcx, 'static>;
pub type FieldDef<'tcx> = &'tcx FieldDefData<'tcx, 'static>;
// See comment on AdtDefData for explanation
pub type AdtDefMaster<'tcx> = &'tcx AdtDefData<'tcx, 'tcx>;
pub type VariantDefMaster<'tcx> = &'tcx VariantDefData<'tcx, 'tcx>;
pub type FieldDefMaster<'tcx> = &'tcx FieldDefData<'tcx, 'tcx>;
pub struct VariantDefData<'tcx, 'container: 'tcx> {
/// The variant's DefId. If this is a tuple-like struct,
/// this is the DefId of the struct's ctor.
pub did: DefId,
pub name: Name, // struct's name if this is a struct
pub disr_val: Disr,
pub fields: Vec<FieldDefData<'tcx, 'container>>,
pub ctor_kind: CtorKind,
}
pub struct FieldDefData<'tcx, 'container: 'tcx> {
pub did: DefId,
pub name: Name,
pub vis: Visibility,
/// TyIVar is used here to allow for variance (see the doc at
/// AdtDefData).
///
/// Note: direct accesses to `ty` must also add dep edges.
ty: ivar::TyIVar<'tcx, 'container>
}
/// The definition of an abstract data type - a struct or enum.
///
/// These are all interned (by intern_adt_def) into the adt_defs
/// table.
///
/// Because of the possibility of nested tcx-s, this type
/// needs 2 lifetimes: the traditional variant lifetime ('tcx)
/// bounding the lifetime of the inner types is of course necessary.
/// However, it is not sufficient - types from a child tcx must
/// not be leaked into the master tcx by being stored in an AdtDefData.
///
/// The 'container lifetime ensures that by outliving the container
/// tcx and preventing shorter-lived types from being inserted. When
/// write access is not needed, the 'container lifetime can be
/// erased to 'static, which can be done by the AdtDef wrapper.
pub struct AdtDefData<'tcx, 'container: 'tcx> {
pub did: DefId,
pub variants: Vec<VariantDefData<'tcx, 'container>>,
destructor: Cell<Option<DefId>>,
flags: Cell<AdtFlags>,
sized_constraint: ivar::TyIVar<'tcx, 'container>,
}
impl<'tcx, 'container> PartialEq for AdtDefData<'tcx, 'container> {
// AdtDefData are always interned and this is part of TyS equality
#[inline]
fn eq(&self, other: &Self) -> bool { self as *const _ == other as *const _ }
}
impl<'tcx, 'container> Eq for AdtDefData<'tcx, 'container> {}
impl<'tcx, 'container> Hash for AdtDefData<'tcx, 'container> {
#[inline]
fn hash<H: Hasher>(&self, s: &mut H) {
(self as *const AdtDefData).hash(s)
}
}
impl<'tcx> serialize::UseSpecializedEncodable for AdtDef<'tcx> {
fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
self.did.encode(s)
}
}
impl<'tcx> serialize::UseSpecializedDecodable for AdtDef<'tcx> {}
impl<'a, 'gcx, 'tcx> AdtDefData<'tcx, 'static> {
#[inline]
pub fn is_uninhabited_recurse(&'tcx self,
visited: &mut FxHashSet<(DefId, &'tcx Substs<'tcx>)>,
block: Option<NodeId>,
cx: TyCtxt<'a, 'gcx, 'tcx>,
substs: &'tcx Substs<'tcx>) -> bool {
if !visited.insert((self.did, substs)) {
return false;
};
self.variants.iter().all(|v| {
v.is_uninhabited_recurse(visited, block, cx, substs, self.is_union())
})
}
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum AdtKind { Struct, Union, Enum }
impl<'a, 'gcx, 'tcx, 'container> AdtDefData<'gcx, 'container> {
fn new(tcx: TyCtxt<'a, 'gcx, 'tcx>,
did: DefId,
kind: AdtKind,
variants: Vec<VariantDefData<'gcx, 'container>>) -> Self {
let mut flags = AdtFlags::NO_ADT_FLAGS;
let attrs = tcx.get_attrs(did);
if attr::contains_name(&attrs, "fundamental") {
flags = flags | AdtFlags::IS_FUNDAMENTAL;
}
if tcx.lookup_simd(did) {
flags = flags | AdtFlags::IS_SIMD;
}
if Some(did) == tcx.lang_items.phantom_data() {
flags = flags | AdtFlags::IS_PHANTOM_DATA;
}
match kind {
AdtKind::Enum => flags = flags | AdtFlags::IS_ENUM,
AdtKind::Union => flags = flags | AdtFlags::IS_UNION,
AdtKind::Struct => {}
}
AdtDefData {
did: did,
variants: variants,
flags: Cell::new(flags),
destructor: Cell::new(None),
sized_constraint: ivar::TyIVar::new(),
}
}
fn calculate_dtorck(&'gcx self, tcx: TyCtxt) {
if tcx.is_adt_dtorck(self) {
self.flags.set(self.flags.get() | AdtFlags::IS_DTORCK);
}
self.flags.set(self.flags.get() | AdtFlags::IS_DTORCK_VALID)
}
#[inline]
pub fn is_struct(&self) -> bool {
!self.is_union() && !self.is_enum()
}
#[inline]
pub fn is_union(&self) -> bool {
self.flags.get().intersects(AdtFlags::IS_UNION)
}
#[inline]
pub fn is_enum(&self) -> bool {
self.flags.get().intersects(AdtFlags::IS_ENUM)
}
/// Returns the kind of the ADT - Struct or Enum.
#[inline]
pub fn adt_kind(&self) -> AdtKind {
if self.is_enum() {
AdtKind::Enum
} else if self.is_union() {
AdtKind::Union
} else {
AdtKind::Struct
}
}
pub fn descr(&self) -> &'static str {
match self.adt_kind() {
AdtKind::Struct => "struct",
AdtKind::Union => "union",
AdtKind::Enum => "enum",
}
}
pub fn variant_descr(&self) -> &'static str {
match self.adt_kind() {
AdtKind::Struct => "struct",
AdtKind::Union => "union",
AdtKind::Enum => "variant",
}
}
/// Returns whether this is a dtorck type. If this returns
/// true, this type being safe for destruction requires it to be
/// alive; Otherwise, only the contents are required to be.
#[inline]
pub fn is_dtorck(&'gcx self, tcx: TyCtxt) -> bool {
if !self.flags.get().intersects(AdtFlags::IS_DTORCK_VALID) {
self.calculate_dtorck(tcx)
}
self.flags.get().intersects(AdtFlags::IS_DTORCK)
}
/// Returns whether this type is #[fundamental] for the purposes
/// of coherence checking.
#[inline]
pub fn is_fundamental(&self) -> bool {
self.flags.get().intersects(AdtFlags::IS_FUNDAMENTAL)
}
#[inline]
pub fn is_simd(&self) -> bool {
self.flags.get().intersects(AdtFlags::IS_SIMD)
}
/// Returns true if this is PhantomData<T>.
#[inline]
pub fn is_phantom_data(&self) -> bool {
self.flags.get().intersects(AdtFlags::IS_PHANTOM_DATA)
}
/// Returns whether this type has a destructor.
pub fn has_dtor(&self) -> bool {
self.dtor_kind().is_present()
}
/// Asserts this is a struct and returns the struct's unique
/// variant.
pub fn struct_variant(&self) -> &VariantDefData<'gcx, 'container> {
assert!(!self.is_enum());
&self.variants[0]
}
#[inline]
pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> GenericPredicates<'gcx> {
tcx.item_predicates(self.did)
}
/// Returns an iterator over all fields contained
/// by this ADT.
#[inline]
pub fn all_fields(&self) ->
iter::FlatMap<
slice::Iter<VariantDefData<'gcx, 'container>>,
slice::Iter<FieldDefData<'gcx, 'container>>,
for<'s> fn(&'s VariantDefData<'gcx, 'container>)
-> slice::Iter<'s, FieldDefData<'gcx, 'container>>
> {
self.variants.iter().flat_map(VariantDefData::fields_iter)
}
#[inline]
pub fn is_univariant(&self) -> bool {
self.variants.len() == 1
}
pub fn is_payloadfree(&self) -> bool {
!self.variants.is_empty() &&
self.variants.iter().all(|v| v.fields.is_empty())
}
pub fn variant_with_id(&self, vid: DefId) -> &VariantDefData<'gcx, 'container> {
self.variants
.iter()
.find(|v| v.did == vid)
.expect("variant_with_id: unknown variant")
}
pub fn variant_index_with_id(&self, vid: DefId) -> usize {
self.variants
.iter()
.position(|v| v.did == vid)
.expect("variant_index_with_id: unknown variant")
}
pub fn variant_of_def(&self, def: Def) -> &VariantDefData<'gcx, 'container> {
match def {
Def::Variant(vid) | Def::VariantCtor(vid, ..) => self.variant_with_id(vid),
Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => self.struct_variant(),
_ => bug!("unexpected def {:?} in variant_of_def", def)
}
}
pub fn
|
(&self) -> Option<DefId> {
self.destructor.get()
}
pub fn set_destructor(&self, dtor: DefId) {
self.destructor.set(Some(dtor));
}
pub fn dtor_kind(&self) -> DtorKind {
match self.destructor.get() {
Some(_) => TraitDtor,
None => NoDtor,
}
}
}
impl<'a, 'gcx, 'tcx, 'container> AdtDefData<'tcx, 'container> {
/// Returns a simpler type such that `Self: Sized` if and only
/// if that type is Sized, or `TyErr` if this type is recursive.
///
/// HACK: instead of returning a list of types, this function can
/// return a tuple. In that case, the result is Sized only if
/// all elements of the tuple are Sized.
///
/// This is generally the `struct_tail` if this is a struct, or a
/// tuple of them if this is an enum.
///
/// Oddly enough, checking that the sized-constraint is Sized is
/// actually more expressive than checking all members:
/// the Sized trait is inductive, so an associated type that references
/// Self would prevent its containing ADT from being Sized.
///
/// Due to normalization being eager, this applies even if
/// the associated type is behind a pointer, e.g. issue #31299.
pub fn sized_constraint(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
match self.sized_constraint.get(DepNode::SizedConstraint(self.did)) {
None => {
let global_tcx = tcx.global_tcx();
let this = global_tcx.lookup_adt_def_master(self.did);
this.calculate_sized_constraint_inner(global_tcx, &mut Vec::new());
self.sized_constraint(tcx)
}
Some(ty) => ty
}
}
}
impl<'a, 'tcx> AdtDefData<'tcx, 'tcx> {
/// Calculates the Sized-constraint.
///
/// As the Sized-constraint of enums can be a *set* of types,
/// the Sized-constraint may need to be a set also. Because introducing
/// a new type of IVar is currently a complex affair, the Sized-constraint
/// may be a tuple.
///
/// In fact, there are only a few options for the constraint:
/// - `bool`, if the type is always Sized
/// - an obviously-unsized type
/// - a type parameter or projection whose Sizedness can't be known
/// - a tuple of type parameters or projections, if there are multiple
/// such.
/// - a TyError, if a type contained itself. The representability
/// check should catch this case.
fn calculate_sized_constraint_inner(&'tcx self,
tcx: TyCtxt<'a, 'tcx, 'tcx>,
stack: &mut Vec<AdtDefMaster<'tcx>>)
{
let dep_node = || DepNode::SizedConstraint(self.did);
// Follow the memoization pattern: push the computation of
// DepNode::SizedConstraint as our current task.
let _task = tcx.dep_graph.in_task(dep_node());
if self.sized_constraint.untracked_get().is_some() {
// ---------------
// can skip the dep-graph read since we just pushed the task
return;
}
if stack.contains(&self) {
debug!("calculate_sized_constraint: {:?} is recursive", self);
// This should be reported as an error by `check_representable`.
//
// Consider the type as Sized in the meanwhile to avoid
// further errors.
self.sized_constraint.fulfill(dep_node(), tcx.types.err);
return;
}
stack.push(self);
let tys : Vec<_> =
self.variants.iter().flat_map(|v| {
v.fields.last()
}).flat_map(|f| {
self.sized_constraint_for_ty(tcx, stack, f.unsubst_ty())
}).collect();
let self_ = stack.pop().unwrap();
assert_eq!(self_, self);
let ty = match tys.len() {
_ if tys.references_error() => tcx.types.err,
0 => tcx.types.bool,
1 => tys[0],
_ => tcx.intern_tup(&tys[..])
};
match self.sized_constraint.get(dep_node()) {
Some(old_ty) => {
debug!("calculate_sized_constraint: {:?} recurred", self);
assert_eq!(old_ty, tcx.types.err)
}
None => {
debug!("calculate_sized_constraint: {:?} => {:?}", self, ty);
self.sized_constraint.fulfill(dep_node(), ty)
}
}
}
fn sized_constraint_for_ty(
&'tcx self,
tcx: TyCtxt<'a, 'tcx, 'tcx>,
stack: &mut Vec<AdtDefMaster<'tcx>>,
ty: Ty<'tcx>
) -> Vec<Ty<'tcx>> {
let result = match ty.sty {
TyBool | TyChar | TyInt(..) | TyUint(..) | TyFloat(..) |
TyBox(..) | TyRawPtr(..) | TyRef(..) | TyFnDef(..) | TyFnPtr(_) |
TyArray(..) | TyClosure(..) | TyNever => {
vec![]
}
TyStr | TyTrait(..) | TySlice(_) | TyError => {
// these are never sized - return the target type
vec![ty]
}
TyTuple(ref tys) => {
match tys.last() {
None => vec![],
Some(ty) => self.sized_constraint_for_ty(tcx, stack, ty)
}
}
TyAdt(adt, substs) => {
// recursive case
let adt = tcx.lookup_adt_def_master(adt.did);
adt.calculate_sized_constraint_inner(tcx, stack);
let adt_ty =
adt.sized_constraint
.unwrap(DepNode::SizedConstraint(adt.did))
.subst(tcx, substs);
debug!("sized_constraint_for_ty({:?}) intermediate = {:?}",
ty, adt_ty);
if let ty::TyTuple(ref tys) = adt_ty.sty {
tys.iter().flat_map(|ty| {
self.sized_constraint_for_ty(tcx, stack, ty)
}).collect()
} else {
self.sized_constraint_for_ty(tcx, stack, adt_ty)
}
}
TyProjection(..) | TyAnon(..) => {
// must calculate explicitly.
// FIXME: consider special-casing always-Sized projections
vec![ty]
}
TyParam(..) => {
// perf hack: if there is a `T: Sized` bound, then
// we know that `T` is Sized and do not need to check
// it on the impl.
let sized_trait = match tcx.lang_items.sized_trait() {
Some(x) => x,
_ => return vec![ty]
};
let sized_predicate = Binder(TraitRef {
def_id: sized_trait,
substs: tcx.mk_substs_trait(ty, &[])
}).to_predicate();
let predicates = tcx.item_predicates(self.did).predicates;
if predicates.into_iter().any(|p| p == sized_predicate) {
vec![]
} else {
vec![ty]
}
}
TyInfer(..) => {
bug!("unexpected type `{:?}` in sized_constraint_for_ty",
ty)
}
};
debug!("sized_constraint_for_ty({:?}) = {:?}", ty, result);
result
}
}
impl<'tcx, 'container> VariantDefData<'tcx, 'container> {
#[inline]
fn fields_iter(&self) -> slice::Iter<FieldDefData<'tcx, 'container>> {
self.fields.iter()
}
#[inline]
pub fn find_field_named(&self,
name: ast::Name)
-> Option<&FieldDefData<'tcx, 'container>> {
self.fields.iter().find(|f| f.name == name)
}
#[inline]
pub fn index_of_field_named(&self,
name: ast::Name)
-> Option<usize> {
self.fields.iter().position(|f| f.name == name)
}
#[inline]
pub fn field_named(&self, name: ast::Name) -> &FieldDefData<'tcx, 'container> {
self.find_field_named(name).unwrap()
}
}
impl<'a, 'gcx, 'tcx> VariantDefData<'tcx, 'static> {
#[inline]
pub fn is_uninhabited_recurse(&'tcx self,
visited: &mut FxHashSet<(DefId, &'tcx Substs<'tcx>)>,
block: Option<NodeId>,
cx: TyCtxt<'a, 'gcx, 'tcx>,
substs: &'tcx Substs<'tcx>,
is_union: bool) -> bool {
if is_union {
self.fields.iter().all(|f| f.is_uninhabited_recurse(visited, block, cx, substs))
} else {
self.fields.iter().any(|f| f.is_uninhabited_recurse(visited, block, cx, substs))
}
}
}
impl<'a, 'gcx, 'tcx, 'container> FieldDefData<'tcx, 'container> {
pub fn new(did: DefId,
name: Name,
vis: Visibility) -> Self {
FieldDefData {
did: did,
name: name,
vis: vis,
ty: ivar::TyIVar::new()
}
}
pub fn ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, subst: &Substs<'tcx>) -> Ty<'tcx> {
self.unsubst_ty().subst(tcx, subst)
}
pub fn unsubst_ty(&self) -> Ty<'tcx> {
self.ty.unwrap(DepNode::FieldTy(self.did))
}
pub fn fulfill_ty(&self, ty: Ty<'container>) {
self.ty.fulfill(DepNode::FieldTy(self.did), ty);
}
}
impl<'a, 'gcx, 'tcx> FieldDefData<'tcx, 'static> {
#[inline]
pub fn is_uninhabited_recurse(&'tcx self,
visited: &mut FxHashSet<(DefId, &'tcx Substs<'tcx>)>,
block: Option<NodeId>,
tcx: TyCtxt<'a, 'gcx, 'tcx>,
substs: &'tcx Substs<'tcx>) -> bool {
block.map_or(true, |b| self.vis.is_accessible_from(b, &tcx.map)) &&
self.ty(tcx, substs).is_uninhabited_recurse(visited, block, tcx)
}
}
/// Records the substitutions used to translate the polytype for an
/// item into the monotype of an item reference.
#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct ItemSubsts<'tcx> {
pub substs: &'tcx Substs<'tcx>,
}
#[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
pub enum ClosureKind {
// Warning: Ordering is significant here! The ordering is chosen
// because the trait Fn is a subtrait of FnMut and so in turn, and
// hence we order it so that Fn < FnMut < FnOnce.
Fn,
FnMut,
FnOnce,
}
impl<'a, 'tcx> ClosureKind {
pub fn trait_did(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> DefId {
let result = match *self {
ClosureKind::Fn => tcx.lang_items.require(FnTraitLangItem),
ClosureKind::FnMut => {
tcx.lang_items.require(FnMutTraitLangItem)
}
ClosureKind::FnOnce => {
tcx.lang_items.require(FnOnceTraitLangItem)
}
};
match result {
Ok(trait_did) => trait_did,
Err(err) => tcx.sess.fatal(&err[..]),
}
}
/// True if this a type that impls this closure kind
/// must also implement `other`.
pub fn extends(self, other: ty::ClosureKind) -> bool {
match (self, other) {
(ClosureKind::Fn, ClosureKind::Fn) => true,
(ClosureKind::Fn, ClosureKind::FnMut) => true,
(ClosureKind::Fn, ClosureKind::FnOnce) => true,
(ClosureKind::FnMut, ClosureKind::FnMut) => true,
(ClosureKind::FnMut, ClosureKind::FnOnce) => true,
(ClosureKind::FnOnce, ClosureKind::FnOnce) => true,
_ => false,
}
}
}
impl<'tcx> TyS<'tcx> {
/// Iterator that walks `self` and any types reachable from
/// `self`, in depth-first order. Note that just walks the types
/// that appear in `self`, it does not descend into the fields of
/// structs or variants. For example:
///
/// ```notrust
/// isize => { isize }
/// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
/// [isize] => { [isize], isize }
/// ```
pub fn walk(&'tcx self) -> TypeWalker<'tcx> {
TypeWalker::new(self)
}
/// Iterator that walks the immediate children of `self`. Hence
/// `Foo<Bar<i32>, u32>` yields the sequence `[Bar<i32>, u32]`
/// (but not `i32`, like `walk`).
pub fn walk_shallow(&'tcx self) -> AccIntoIter<walk::TypeWalkerArray<'tcx>> {
walk::walk_shallow(self)
}
/// Walks `ty` and any types appearing within `ty`, invoking the
/// callback `f` on each type. If the callback returns false, then the
/// children of the current type are ignored.
///
/// Note: prefer `ty.walk()` where possible.
pub fn maybe_walk<F>(&'tcx self, mut f: F)
where F : FnMut(Ty<'tcx>) -> bool
{
let mut walker = self.walk();
while let Some(ty) = walker.next() {
if !f(ty) {
walker.skip_current_subtree();
}
}
}
}
impl<'tcx> ItemSubsts<'tcx> {
pub fn is_noop(&self) -> bool {
self.substs.is_noop()
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum LvaluePreference {
PreferMutLvalue,
NoPreference
}
impl LvaluePreference {
pub fn from_mutbl(m: hir::Mutability) -> Self {
match m {
hir::MutMutable => PreferMutLvalue,
hir::MutImmutable => NoPreference,
}
}
}
/// Helper for looking things up in the various maps that are populated during
/// typeck::collect (e.g., `tcx.associated_items`, `tcx.types`, etc). All of
/// these share the pattern that if the id is local, it should have been loaded
/// into the map by the `typeck::collect` phase. If the def-id is external,
/// then we have to go consult the crate loading code (and cache the result for
/// the future).
fn lookup_locally_or_in_crate_store<M, F>(descr: &str,
def_id: DefId,
map: &M,
load_external: F)
-> M::Value where
M: MemoizationMap<Key=DefId>,
F: FnOnce() -> M::Value,
{
map.memoize(def_id, || {
if def_id.is_local() {
bug!("No def'n found for {:?} in tcx.{}", def_id, descr);
}
load_external()
})
}
impl BorrowKind {
pub fn from_mutbl(m: hir::Mutability) -> BorrowKind {
match m {
hir::MutMutable => MutBorrow,
hir::MutImmutable => ImmBorrow,
}
}
/// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
/// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
/// mutability that is stronger than necessary so that it at least *would permit* the borrow in
/// question.
pub fn to_mutbl_lossy(self) -> hir::Mutability {
match self {
MutBorrow => hir::MutMutable,
ImmBorrow => hir::MutImmutable,
// We have no type corresponding to a unique imm borrow, so
// use `&mut`. It gives all the capabilities of an `&uniq`
// and hence is a safe "over approximation".
UniqueImmBorrow => hir::MutMutable,
}
}
pub fn to_user_str(&self) -> &'static str {
match *self {
MutBorrow => "mutable",
ImmBorrow => "immutable",
UniqueImmBorrow => "uniquely immutable",
}
}
}
impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
pub fn tables(self) -> Ref<'a, Tables<'gcx>> {
self.tables.borrow()
}
pub fn expr_span(self, id: NodeId) -> Span {
match self.map.find(id) {
Some(ast_map::NodeExpr(e)) => {
e.span
}
Some(f) => {
bug!("Node id {} is not an expr: {:?}", id, f);
}
None => {
bug!("Node id {} is not present in the node map", id);
}
}
}
pub fn local_var_name_str(self, id: NodeId) -> InternedString {
match self.map.find(id) {
Some(ast_map::NodeLocal(pat)) => {
match pat.node {
hir::PatKind::Binding(_, ref path1, _) => path1.node.as_str(),
_ => {
bug!("Variable id {} maps to {:?}, not local", id, pat);
},
}
},
r => bug!("Variable id {} maps to {:?}, not local", id, r),
}
}
pub fn expr_is_lval(self, expr: &hir::Expr) -> bool {
match expr.node {
hir::ExprPath(..) => {
// This function can be used during type checking when not all paths are
// fully resolved. Partially resolved paths in expressions can only legally
// refer to associated items which are always rvalues.
match self.expect_resolution(expr.id).base_def {
Def::Local(..) | Def::Upvar(..) | Def::Static(..) | Def::Err => true,
_ => false,
}
}
hir::ExprType(ref e, _) => {
self.expr_is_lval(e)
}
hir::ExprUnary(hir::UnDeref, _) |
hir::ExprField(..) |
hir::ExprTupField(..) |
hir::ExprIndex(..) => {
true
}
hir::ExprCall(..) |
hir::ExprMethodCall(..) |
hir::ExprStruct(..) |
hir::ExprTup(..) |
hir::ExprIf(..) |
hir::ExprMatch(..) |
hir::ExprClosure(..) |
hir::ExprBlock(..) |
hir::ExprRepeat(..) |
hir::ExprArray(..) |
hir::ExprBreak(..) |
hir::ExprAgain(..) |
hir::ExprRet(..) |
hir::ExprWhile(..) |
hir::ExprLoop(..) |
hir::ExprAssign(..) |
hir::ExprInlineAsm(..) |
hir::ExprAssignOp(..) |
hir::ExprLit(_) |
hir::ExprUnary(..) |
hir::ExprBox(..) |
hir::ExprAddrOf(..) |
hir::ExprBinary(..) |
hir::ExprCast(..) => {
false
}
}
}
pub fn provided_trait_methods(self, id: DefId) -> Vec<AssociatedItem> {
self.associated_items(id)
.filter(|item| item.kind == AssociatedKind::Method && item.defaultness.has_value())
.collect()
}
pub fn trait_impl_polarity(self, id: DefId) -> hir::ImplPolarity {
if let Some(id) = self.map.as_local_node_id(id) {
match self.map.expect_item(id).node {
hir::ItemImpl(_, polarity, ..) => polarity,
ref item => bug!("trait_impl_polarity: {:?} not an impl", item)
}
} else {
self.sess.cstore.impl_polarity(id)
}
}
pub fn custom_coerce_unsized_kind(self, did: DefId) -> adjustment::CustomCoerceUnsized {
self.custom_coerce_unsized_kinds.memoize(did, || {
let (kind, src) = if did.krate != LOCAL_CRATE {
(self.sess.cstore.custom_coerce_unsized_kind(did), "external")
} else {
(None, "local")
};
match kind {
Some(kind) => kind,
None => {
bug!("custom_coerce_unsized_kind: \
{} impl `{}` is missing its kind",
src, self.item_path_str(did));
}
}
})
}
pub fn associated_item(self, def_id: DefId) -> AssociatedItem {
self.associated_items.memoize(def_id, || {
if !def_id.is_local() {
return self.sess.cstore.associated_item(self.global_tcx(), def_id)
.expect("missing AssociatedItem in metadata");
}
// When the user asks for a given associated item, we
// always go ahead and convert all the associated items in
// the container. Note that we are also careful only to
// ever register a read on the *container* of the assoc
// item, not the assoc item itself. This prevents changes
// in the details of an item (for example, the type to
// which an associated type is bound) from contaminating
// those tasks that just need to scan the names of items
// and so forth.
let id = self.map.as_local_node_id(def_id).unwrap();
let parent_id = self.map.get_parent(id);
let parent_def_id = self.map.local_def_id(parent_id);
let parent_item = self.map.expect_item(parent_id);
match parent_item.node {
hir::ItemImpl(.., ref impl_trait_ref, _, ref impl_item_refs) => {
for impl_item_ref in impl_item_refs {
let assoc_item =
self.associated_item_from_impl_item_ref(parent_def_id,
impl_trait_ref.is_some(),
impl_item_ref);
self.associated_items.borrow_mut().insert(assoc_item.def_id, assoc_item);
}
}
hir::ItemTrait(.., ref trait_items) => {
for trait_item in trait_items {
let assoc_item =
self.associated_item_from_trait_item_ref(parent_def_id, trait_item);
self.associated_items.borrow_mut().insert(assoc_item.def_id, assoc_item);
}
}
ref r => {
panic!("unexpected container of associated items: {:?}", r)
}
}
// memoize wants us to return something, so return
// the one we generated for this def-id
*self.associated_items.borrow().get(&def_id).unwrap()
})
}
fn associated_item_from_trait_item_ref(self,
parent_def_id: DefId,
trait_item: &hir::TraitItem)
-> AssociatedItem {
let def_id = self.map.local_def_id(trait_item.id);
let (kind, has_self, has_value) = match trait_item.node {
hir::MethodTraitItem(ref sig, ref body) => {
(AssociatedKind::Method, sig.decl.get_self().is_some(),
body.is_some())
}
hir::ConstTraitItem(_, ref value) => {
(AssociatedKind::Const, false, value.is_some())
}
hir::TypeTraitItem(_, ref ty) => {
(AssociatedKind::Type, false, ty.is_some())
}
};
AssociatedItem {
name: trait_item.name,
kind: kind,
vis: Visibility::from_hir(&hir::Inherited, trait_item.id, self),
defaultness: hir::Defaultness::Default { has_value: has_value },
def_id: def_id,
container: TraitContainer(parent_def_id),
method_has_self_argument: has_self
}
}
fn associated_item_from_impl_item_ref(self,
parent_def_id: DefId,
from_trait_impl: bool,
impl_item_ref: &hir::ImplItemRef)
-> AssociatedItem {
let def_id = self.map.local_def_id(impl_item_ref.id.node_id);
let (kind, has_self) = match impl_item_ref.kind {
hir::AssociatedItemKind::Const => (ty::AssociatedKind::Const, false),
hir::AssociatedItemKind::Method { has_self } => {
(ty::AssociatedKind::Method, has_self)
}
hir::AssociatedItemKind::Type => (ty::AssociatedKind::Type, false),
};
// Trait impl items are always public.
let public = hir::Public;
let vis = if from_trait_impl { &public } else { &impl_item_ref.vis };
ty::AssociatedItem {
name: impl_item_ref.name,
kind: kind,
vis: ty::Visibility::from_hir(vis, impl_item_ref.id.node_id, self),
defaultness: impl_item_ref.defaultness,
def_id: def_id,
container: ImplContainer(parent_def_id),
method_has_self_argument: has_self
}
}
pub fn associated_item_def_ids(self, def_id: DefId) -> Rc<Vec<DefId>> {
self.associated_item_def_ids.memoize(def_id, || {
if !def_id.is_local() {
return Rc::new(self.sess.cstore.associated_item_def_ids(def_id));
}
let id = self.map.as_local_node_id(def_id).unwrap();
let item = self.map.expect_item(id);
let vec: Vec<_> = match item.node {
hir::ItemTrait(.., ref trait_items) => {
trait_items.iter()
.map(|trait_item| trait_item.id)
.map(|id| self.map.local_def_id(id))
.collect()
}
hir::ItemImpl(.., ref impl_item_refs) => {
impl_item_refs.iter()
.map(|impl_item_ref| impl_item_ref.id)
.map(|id| self.map.local_def_id(id.node_id))
.collect()
}
_ => span_bug!(item.span, "associated_item_def_ids: not impl or trait")
};
Rc::new(vec)
})
}
#[inline] // FIXME(#35870) Avoid closures being unexported due to impl Trait.
pub fn associated_items(self, def_id: DefId)
-> impl Iterator<Item = ty::AssociatedItem> + 'a {
let def_ids = self.associated_item_def_ids(def_id);
(0..def_ids.len()).map(move |i| self.associated_item(def_ids[i]))
}
/// Returns the trait-ref corresponding to a given impl, or None if it is
/// an inherent impl.
pub fn impl_trait_ref(self, id: DefId) -> Option<TraitRef<'gcx>> {
lookup_locally_or_in_crate_store(
"impl_trait_refs", id, &self.impl_trait_refs,
|| self.sess.cstore.impl_trait_ref(self.global_tcx(), id))
}
/// Returns a path resolution for node id if it exists, panics otherwise.
pub fn expect_resolution(self, id: NodeId) -> PathResolution {
*self.def_map.borrow().get(&id).expect("no def-map entry for node id")
}
/// Returns a fully resolved definition for node id if it exists, panics otherwise.
pub fn expect_def(self, id: NodeId) -> Def {
self.expect_resolution(id).full_def()
}
/// Returns a fully resolved definition for node id if it exists, or none if no
/// definition exists, panics on partial resolutions to catch errors.
pub fn expect_def_or_none(self, id: NodeId) -> Option<Def> {
self.def_map.borrow().get(&id).map(|resolution| resolution.full_def())
}
// Returns `ty::VariantDef` if `def` refers to a struct,
// or variant or their constructors, panics otherwise.
pub fn expect_variant_def(self, def: Def) -> VariantDef<'tcx> {
match def {
Def::Variant(did) | Def::VariantCtor(did, ..) => {
let enum_did = self.parent_def_id(did).unwrap();
self.lookup_adt_def(enum_did).variant_with_id(did)
}
Def::Struct(did) | Def::Union(did) => {
self.lookup_adt_def(did).struct_variant()
}
Def::StructCtor(ctor_did, ..) => {
let did = self.parent_def_id(ctor_did).expect("struct ctor has no parent");
self.lookup_adt_def(did).struct_variant()
}
_ => bug!("expect_variant_def used with unexpected def {:?}", def)
}
}
pub fn def_key(self, id: DefId) -> ast_map::DefKey {
if id.is_local() {
self.map.def_key(id)
} else {
self.sess.cstore.def_key(id)
}
}
/// Convert a `DefId` into its fully expanded `DefPath` (every
/// `DefId` is really just an interned def-path).
///
/// Note that if `id` is not local to this crate -- or is
/// inlined into this crate -- the result will be a non-local
/// `DefPath`.
///
/// This function is only safe to use when you are sure that the
/// full def-path is accessible. Examples that are known to be
/// safe are local def-ids or items; see `opt_def_path` for more
/// details.
pub fn def_path(self, id: DefId) -> ast_map::DefPath {
self.opt_def_path(id).unwrap_or_else(|| {
bug!("could not load def-path for {:?}", id)
})
}
/// Convert a `DefId` into its fully expanded `DefPath` (every
/// `DefId` is really just an interned def-path).
///
/// When going across crates, we do not save the full info for
/// every cross-crate def-id, and hence we may not always be able
/// to create a def-path. Therefore, this returns
/// `Option<DefPath>` to cover that possibility. It will always
/// return `Some` for local def-ids, however, as well as for
/// items. The problems arise with "minor" def-ids like those
/// associated with a pattern, `impl Trait`, or other internal
/// detail to a fn.
///
/// Note that if `id` is not local to this crate -- or is
/// inlined into this crate -- the result will be a non-local
/// `DefPath`.
pub fn opt_def_path(self, id: DefId) -> Option<ast_map::DefPath> {
if id.is_local() {
Some(self.map.def_path(id))
} else {
self.sess.cstore.relative_def_path(id)
}
}
pub fn item_name(self, id: DefId) -> ast::Name {
if let Some(id) = self.map.as_local_node_id(id) {
self.map.name(id)
} else if id.index == CRATE_DEF_INDEX {
self.sess.cstore.original_crate_name(id.krate)
} else {
let def_key = self.sess.cstore.def_key(id);
// The name of a StructCtor is that of its struct parent.
if let ast_map::DefPathData::StructCtor = def_key.disambiguated_data.data {
self.item_name(DefId {
krate: id.krate,
index: def_key.parent.unwrap()
})
} else {
def_key.disambiguated_data.data.get_opt_name().unwrap_or_else(|| {
bug!("item_name: no name for {:?}", self.def_path(id));
})
}
}
}
// If the given item is in an external crate, looks up its type and adds it to
// the type cache. Returns the type parameters and type.
pub fn item_type(self, did: DefId) -> Ty<'gcx> {
lookup_locally_or_in_crate_store(
"item_types", did, &self.item_types,
|| self.sess.cstore.item_type(self.global_tcx(), did))
}
/// Given the did of a trait, returns its canonical trait ref.
pub fn lookup_trait_def(self, did: DefId) -> &'gcx TraitDef<'gcx> {
lookup_locally_or_in_crate_store(
"trait_defs", did, &self.trait_defs,
|| self.alloc_trait_def(self.sess.cstore.trait_def(self.global_tcx(), did))
)
}
/// Given the did of an ADT, return a master reference to its
/// definition. Unless you are planning on fulfilling the ADT's fields,
/// use lookup_adt_def instead.
pub fn lookup_adt_def_master(self, did: DefId) -> AdtDefMaster<'gcx> {
lookup_locally_or_in_crate_store(
"adt_defs", did, &self.adt_defs,
|| self.sess.cstore.adt_def(self.global_tcx(), did)
)
}
/// Given the did of an ADT, return a reference to its definition.
pub fn lookup_adt_def(self, did: DefId) -> AdtDef<'gcx> {
// when reverse-variance goes away, a transmute::<AdtDefMaster,AdtDef>
// would be needed here.
self.lookup_adt_def_master(did)
}
/// Given the did of an item, returns its generics.
pub fn item_generics(self, did: DefId) -> &'gcx Generics<'gcx> {
lookup_locally_or_in_crate_store(
"generics", did, &self.generics,
|| self.alloc_generics(self.sess.cstore.item_generics(self.global_tcx(), did)))
}
/// Given the did of an item, returns its full set of predicates.
pub fn item_predicates(self, did: DefId) -> GenericPredicates<'gcx> {
lookup_locally_or_in_crate_store(
"predicates", did, &self.predicates,
|| self.sess.cstore.item_predicates(self.global_tcx(), did))
}
/// Given the did of a trait, returns its superpredicates.
pub fn item_super_predicates(self, did: DefId) -> GenericPredicates<'gcx> {
lookup_locally_or_in_crate_store(
"super_predicates", did, &self.super_predicates,
|| self.sess.cstore.item_super_predicates(self.global_tcx(), did))
}
/// Given the did of an item, returns its MIR, borrowed immutably.
pub fn item_mir(self, did: DefId) -> Ref<'gcx, Mir<'gcx>> {
lookup_locally_or_in_crate_store("mir_map", did, &self.mir_map, || {
let mir = self.sess.cstore.get_item_mir(self.global_tcx(), did);
let mir = self.alloc_mir(mir);
// Perma-borrow MIR from extern crates to prevent mutation.
mem::forget(mir.borrow());
mir
}).borrow()
}
/// If `type_needs_drop` returns true, then `ty` is definitely
/// non-copy and *might* have a destructor attached; if it returns
/// false, then `ty` definitely has no destructor (i.e. no drop glue).
///
/// (Note that this implies that if `ty` has a destructor attached,
/// then `type_needs_drop` will definitely return `true` for `ty`.)
pub fn type_needs_drop_given_env(self,
ty: Ty<'gcx>,
param_env: &ty::ParameterEnvironment<'gcx>) -> bool {
// Issue #22536: We first query type_moves_by_default. It sees a
// normalized version of the type, and therefore will definitely
// know whether the type implements Copy (and thus needs no
// cleanup/drop/zeroing) ...
let tcx = self.global_tcx();
let implements_copy = !ty.moves_by_default(tcx, param_env, DUMMY_SP);
if implements_copy { return false; }
// ... (issue #22536 continued) but as an optimization, still use
// prior logic of asking if the `needs_drop` bit is set; we need
// not zero non-Copy types if they have no destructor.
// FIXME(#22815): Note that calling `ty::type_contents` is a
// conservative heuristic; it may report that `needs_drop` is set
// when actual type does not actually have a destructor associated
// with it. But since `ty` absolutely did not have the `Copy`
// bound attached (see above), it is sound to treat it as having a
// destructor (e.g. zero its memory on move).
let contents = ty.type_contents(tcx);
debug!("type_needs_drop ty={:?} contents={:?}", ty, contents);
contents.needs_drop(tcx)
}
/// Get the attributes of a definition.
pub fn get_attrs(self, did: DefId) -> Cow<'gcx, [ast::Attribute]> {
if let Some(id) = self.map.as_local_node_id(did) {
Cow::Borrowed(self.map.attrs(id))
} else {
Cow::Owned(self.sess.cstore.item_attrs(did))
}
}
/// Determine whether an item is annotated with an attribute
pub fn has_attr(self, did: DefId, attr: &str) -> bool {
self.get_attrs(did).iter().any(|item| item.check_name(attr))
}
/// Determine whether an item is annotated with `#[repr(packed)]`
pub fn lookup_packed(self, did: DefId) -> bool {
self.lookup_repr_hints(did).contains(&attr::ReprPacked)
}
/// Determine whether an item is annotated with `#[simd]`
pub fn lookup_simd(self, did: DefId) -> bool {
self.has_attr(did, "simd")
|| self.lookup_repr_hints(did).contains(&attr::ReprSimd)
}
pub fn item_variances(self, item_id: DefId) -> Rc<Vec<ty::Variance>> {
lookup_locally_or_in_crate_store(
"item_variance_map", item_id, &self.item_variance_map,
|| Rc::new(self.sess.cstore.item_variances(item_id)))
}
pub fn trait_has_default_impl(self, trait_def_id: DefId) -> bool {
self.populate_implementations_for_trait_if_necessary(trait_def_id);
let def = self.lookup_trait_def(trait_def_id);
def.flags.get().intersects(TraitFlags::HAS_DEFAULT_IMPL)
}
/// Records a trait-to-implementation mapping.
pub fn record_trait_has_default_impl(self, trait_def_id: DefId) {
let def = self.lookup_trait_def(trait_def_id);
def.flags.set(def.flags.get() | TraitFlags::HAS_DEFAULT_IMPL)
}
/// Populates the type context with all the inherent implementations for
/// the given type if necessary.
pub fn populate_inherent_implementations_for_type_if_necessary(self,
type_id: DefId) {
if type_id.is_local() {
return
}
// The type is not local, hence we are reading this out of
// metadata and don't need to track edges.
let _ignore = self.dep_graph.in_ignore();
if self.populated_external_types.borrow().contains(&type_id) {
return
}
debug!("populate_inherent_implementations_for_type_if_necessary: searching for {:?}",
type_id);
let inherent_impls = self.sess.cstore.inherent_implementations_for_type(type_id);
self.inherent_impls.borrow_mut().insert(type_id, inherent_impls);
self.populated_external_types.borrow_mut().insert(type_id);
}
/// Populates the type context with all the implementations for the given
/// trait if necessary.
pub fn populate_implementations_for_trait_if_necessary(self, trait_id: DefId) {
if trait_id.is_local() {
return
}
// The type is not local, hence we are reading this out of
// metadata and don't need to track edges.
let _ignore = self.dep_graph.in_ignore();
let def = self.lookup_trait_def(trait_id);
if def.flags.get().intersects(TraitFlags::IMPLS_VALID) {
return;
}
debug!("populate_implementations_for_trait_if_necessary: searching for {:?}", def);
if self.sess.cstore.is_defaulted_trait(trait_id) {
self.record_trait_has_default_impl(trait_id);
}
for impl_def_id in self.sess.cstore.implementations_of_trait(Some(trait_id)) {
let trait_ref = self.impl_trait_ref(impl_def_id).unwrap();
// Record the trait->implementation mapping.
let parent = self.sess.cstore.impl_parent(impl_def_id).unwrap_or(trait_id);
def.record_remote_impl(self, impl_def_id, trait_ref, parent);
}
def.flags.set(def.flags.get() | TraitFlags::IMPLS_VALID);
}
pub fn closure_kind(self, def_id: DefId) -> ty::ClosureKind {
// If this is a local def-id, it should be inserted into the
// tables by typeck; else, it will be retreived from
// the external crate metadata.
if let Some(&kind) = self.tables.borrow().closure_kinds.get(&def_id) {
return kind;
}
let kind = self.sess.cstore.closure_kind(def_id);
self.tables.borrow_mut().closure_kinds.insert(def_id, kind);
kind
}
pub fn closure_type(self,
def_id: DefId,
substs: ClosureSubsts<'tcx>)
-> ty::ClosureTy<'tcx>
{
// If this is a local def-id, it should be inserted into the
// tables by typeck; else, it will be retreived from
// the external crate metadata.
if let Some(ty) = self.tables.borrow().closure_tys.get(&def_id) {
return ty.subst(self, substs.substs);
}
let ty = self.sess.cstore.closure_ty(self.global_tcx(), def_id);
self.tables.borrow_mut().closure_tys.insert(def_id, ty.clone());
ty.subst(self, substs.substs)
}
/// Given the def_id of an impl, return the def_id of the trait it implements.
/// If it implements no trait, return `None`.
pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
self.impl_trait_ref(def_id).map(|tr| tr.def_id)
}
/// If the given def ID describes a method belonging to an impl, return the
/// ID of the impl that the method belongs to. Otherwise, return `None`.
pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
if def_id.krate != LOCAL_CRATE {
return self.sess.cstore.associated_item(self.global_tcx(), def_id)
.and_then(|item| {
match item.container {
TraitContainer(_) => None,
ImplContainer(def_id) => Some(def_id),
}
});
}
match self.associated_items.borrow().get(&def_id).cloned() {
Some(trait_item) => {
match trait_item.container {
TraitContainer(_) => None,
ImplContainer(def_id) => Some(def_id),
}
}
None => None
}
}
/// If the given def ID describes an item belonging to a trait,
/// return the ID of the trait that the trait item belongs to.
/// Otherwise, return `None`.
pub fn trait_of_item(self, def_id: DefId) -> Option<DefId> {
if def_id.krate != LOCAL_CRATE {
return self.sess.cstore.trait_of_item(def_id);
}
match self.associated_items.borrow().get(&def_id) {
Some(associated_item) => {
match associated_item.container {
TraitContainer(def_id) => Some(def_id),
ImplContainer(_) => None
}
}
None => None
}
}
/// Construct a parameter environment suitable for static contexts or other contexts where there
/// are no free type/lifetime parameters in scope.
pub fn empty_parameter_environment(self) -> ParameterEnvironment<'tcx> {
// for an empty parameter environment, there ARE no free
// regions, so it shouldn't matter what we use for the free id
let free_id_outlive = self.region_maps.node_extent(ast::DUMMY_NODE_ID);
ty::ParameterEnvironment {
free_substs: self.intern_substs(&[]),
caller_bounds: Vec::new(),
implicit_region_bound: self.mk_region(ty::ReEmpty),
free_id_outlive: free_id_outlive,
is_copy_cache: RefCell::new(FxHashMap()),
is_sized_cache: RefCell::new(FxHashMap()),
}
}
/// Constructs and returns a substitution that can be applied to move from
/// the "outer" view of a type or method to the "inner" view.
/// In general, this means converting from bound parameters to
/// free parameters. Since we currently represent bound/free type
/// parameters in the same way, this only has an effect on regions.
pub fn construct_free_substs(self, def_id: DefId,
free_id_outlive: CodeExtent)
-> &'gcx Substs<'gcx> {
let substs = Substs::for_item(self.global_tcx(), def_id, |def, _| {
// map bound 'a => free 'a
self.global_tcx().mk_region(ReFree(FreeRegion {
scope: free_id_outlive,
bound_region: def.to_bound_region()
}))
}, |def, _| {
// map T => T
self.global_tcx().mk_param_from_def(def)
});
debug!("construct_parameter_environment: {:?}", substs);
substs
}
/// See `ParameterEnvironment` struct def'n for details.
/// If you were using `free_id: NodeId`, you might try `self.region_maps.item_extent(free_id)`
/// for the `free_id_outlive` parameter. (But note that this is not always quite right.)
pub fn construct_parameter_environment(self,
span: Span,
def_id: DefId,
free_id_outlive: CodeExtent)
-> ParameterEnvironment<'gcx>
{
//
// Construct the free substs.
//
let free_substs = self.construct_free_substs(def_id, free_id_outlive);
//
// Compute the bounds on Self and the type parameters.
//
let tcx = self.global_tcx();
let generic_predicates = tcx.item_predicates(def_id);
let bounds = generic_predicates.instantiate(tcx, free_substs);
let bounds = tcx.liberate_late_bound_regions(free_id_outlive, &ty::Binder(bounds));
let predicates = bounds.predicates;
// Finally, we have to normalize the bounds in the environment, in
// case they contain any associated type projections. This process
// can yield errors if the put in illegal associated types, like
// `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
// report these errors right here; this doesn't actually feel
// right to me, because constructing the environment feels like a
// kind of a "idempotent" action, but I'm not sure where would be
// a better place. In practice, we construct environments for
// every fn once during type checking, and we'll abort if there
// are any errors at that point, so after type checking you can be
// sure that this will succeed without errors anyway.
//
let unnormalized_env = ty::ParameterEnvironment {
free_substs: free_substs,
implicit_region_bound: tcx.mk_region(ty::ReScope(free_id_outlive)),
caller_bounds: predicates,
free_id_outlive: free_id_outlive,
is_copy_cache: RefCell::new(FxHashMap()),
is_sized_cache: RefCell::new(FxHashMap()),
};
let cause = traits::ObligationCause::misc(span, free_id_outlive.node_id(&self.region_maps));
traits::normalize_param_env_or_error(tcx, unnormalized_env, cause)
}
pub fn node_scope_region(self, id: NodeId) -> &'tcx Region {
self.mk_region(ty::ReScope(self.region_maps.node_extent(id)))
}
pub fn visit_all_item_likes_in_krate<V,F>(self,
dep_node_fn: F,
visitor: &mut V)
where F: FnMut(DefId) -> DepNode<DefId>, V: ItemLikeVisitor<'gcx>
{
dep_graph::visit_all_item_likes_in_krate(self.global_tcx(), dep_node_fn, visitor);
}
/// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
/// with the name of the crate containing the impl.
pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
if impl_did.is_local() {
let node_id = self.map.as_local_node_id(impl_did).unwrap();
Ok(self.map.span(node_id))
} else {
Err(self.sess.cstore.crate_name(impl_did.krate))
}
}
}
impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
pub fn with_freevars<T, F>(self, fid: NodeId, f: F) -> T where
F: FnOnce(&[hir::Freevar]) -> T,
{
match self.freevars.borrow().get(&fid) {
None => f(&[]),
Some(d) => f(&d[..])
}
}
}
|
destructor
|
headers_policy_test.go
|
// Copyright Project Contour Authors
// 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.
//go:build e2e
// +build e2e
package ingress
import (
"context"
. "github.com/onsi/ginkgo/v2"
"github.com/projectcontour/contour/test/e2e"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
networkingv1 "k8s.io/api/networking/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
func testGlobalHeadersPolicy(applyToIngress bool) e2e.NamespacedTestBody {
return func(namespace string) {
var text string
if applyToIngress {
text = "global headers policy is applied to ingress objects"
} else {
text = "global headers policy is not applied to ingress objects"
}
Specify(text, func() {
t := f.T()
f.Fixtures.Echo.Deploy(namespace, "echo")
var host string
if applyToIngress {
host = "global-headers-policy-apply-to-ingress-false.ingress.projectcontour.io"
} else {
host = "global-headers-policy-apply-to-ingress-true.ingress.projectcontour.io"
}
|
Namespace: namespace,
Name: "global-headers-policy",
},
Spec: networkingv1.IngressSpec{
Rules: []networkingv1.IngressRule{
{
Host: host,
IngressRuleValue: networkingv1.IngressRuleValue{
HTTP: &networkingv1.HTTPIngressRuleValue{
Paths: []networkingv1.HTTPIngressPath{
{
PathType: e2e.IngressPathTypePtr(networkingv1.PathTypePrefix),
Path: "/",
Backend: networkingv1.IngressBackend{
Service: &networkingv1.IngressServiceBackend{
Name: "echo",
Port: networkingv1.ServiceBackendPort{
Number: 80,
},
},
},
},
},
},
},
},
},
},
}
require.NoError(f.T(), f.Client.Create(context.Background(), i))
res, ok := f.HTTP.RequestUntil(&e2e.HTTPRequestOpts{
Host: i.Spec.Rules[0].Host,
Condition: e2e.HasStatusCode(200),
})
require.NotNil(t, res, "request never succeeded")
require.Truef(t, ok, "expected 200 response code, got %d", res.StatusCode)
if applyToIngress {
assert.Equal(t, "foo", f.GetEchoResponseBody(res.Body).RequestHeaders.Get("X-Contour-GlobalRequestHeader"))
assert.Equal(t, "bar", res.Headers.Get("X-Contour-GlobalResponseHeader"))
} else {
assert.Equal(t, "", f.GetEchoResponseBody(res.Body).RequestHeaders.Get("X-Contour-GlobalRequestHeader"))
assert.Equal(t, "", res.Headers.Get("X-Contour-GlobalResponseHeader"))
}
})
}
}
|
i := &networkingv1.Ingress{
ObjectMeta: metav1.ObjectMeta{
|
message.rs
|
use crate::antispam::{AntiSpam, ChannelAndMessageId};
use crate::database::Database;
use crate::utilities::logging::log;
use serenity::client::Context;
use serenity::model::channel::Message;
use serenity::model::id::{ChannelId, MessageId};
use serenity::model::Permissions;
use std::collections::HashMap;
pub async fn message(ctx: Context, msg: Message) {
if msg.author.bot || msg.is_private() {
return;
}
let mut is_spamming: bool = false;
let mut messages_to_delete: Option<Vec<ChannelAndMessageId>> = None;
let mut alert_only: bool = false;
let mut alert_channel_id: u64 = 0;
{
let data = ctx.data.read().await;
if let Some(db_mutex) = data.get::<Database>() {
let db = db_mutex.lock().unwrap();
match db.get_guild_configuration(msg.guild_id.unwrap().0) {
Ok((a, b, _, _)) => {
alert_only = a;
alert_channel_id = b;
()
}
Err(e) => {
eprintln!("[{}] Failed to retrieve guild configuration: {}", msg.guild_id.unwrap().0, e.to_string());
()
}
}
}
if let Some(anti_spam_mutex) = data.get::<AntiSpam>() {
let mut anti_spam = anti_spam_mutex.lock().unwrap();
is_spamming = anti_spam.check_if_spamming(msg.guild_id.unwrap().0, msg.author.id.0, msg.channel_id.0, msg.id.0);
if is_spamming {
if let Some(channel_and_message_ids) = anti_spam.get_recent_message_ids(msg.guild_id.unwrap().0, msg.author.id.0) {
messages_to_delete = Some(channel_and_message_ids.to_vec());
}
anti_spam.delete_recent_message_ids(msg.guild_id.unwrap().0, msg.author.id.0);
}
}
}
if is_spamming {
handle_spammer(&ctx, &msg, &mut messages_to_delete, alert_only, alert_channel_id).await;
return;
}
// Ignore short messages, unlikely to be noteworthy
if msg.content.len() < 15 {
return;
}
let message_content = msg.content.to_lowercase();
let mut contains_forbidden_word: bool = false;
{
let data = ctx.data.read().await;
if let Some(mutex) = data.get::<Database>() {
let db = mutex.lock().unwrap();
contains_forbidden_word = match db.contains_word_in_word_blocklist(message_content.to_string()) {
Ok(b) => b,
Err(e) => {
log(&ctx, &msg, format!("Failed to check if message contained forbidden word: {}", e.to_string()));
false
}
};
}
}
if contains_forbidden_word {
let bot_user = ctx.cache.current_user().await;
let bot_member = ctx.cache.member(msg.guild_id.unwrap().0, bot_user.id).await;
let action: String;
if !alert_only {
if bot_member.unwrap().permissions(&ctx).await.unwrap().contains(Permissions::MANAGE_MESSAGES) {
action = " and the message has been deleted".to_string();
let _ = msg.delete(&ctx).await;
} else {
action = ", but it was not deleted due to missing MANAGE_MESSAGES permission".into();
}
} else {
action = ", but no action was taken due to being in alert-only mode".into();
}
log(&ctx, &msg, format!("User {} ({}) posted a message containing a forbidden word{}: {}", msg.author.tag(), msg.author.id.0, action, message_content));
if alert_channel_id != 0 {
let _ = ChannelId(alert_channel_id)
.send_message(&ctx, |m| {
m.add_embed(|e| {
e.description(format!(
"<@{0}> posted a [message](https://discord.com/channels/{1}/{2}/{3}) in <#{2}> containing a forbidden word{4}: ```{5}```",
msg.author.id.0,
msg.guild_id.unwrap().0,
msg.channel_id.0,
msg.id.0,
action,
message_content
))
})
})
.await;
} else {
log(&ctx, &msg, "WARNING: Guild does not have alert_channel_id configured".into());
}
} else if message_content.contains("http")
&& (message_content.contains("free") || message_content.contains("nitro") || message_content.contains("skin") || message_content.contains("win"))
{
log(&ctx, &msg, format!("⚠ {} ({}) sent a potentially suspicious message: {}", msg.author.name, msg.author.id.0, msg.content.to_string()));
}
}
async fn handle_spammer(ctx: &Context, msg: &Message, messages_to_delete: &mut Option<Vec<ChannelAndMessageId>>, alert_only: bool, alert_channel_id: u64) {
|
log(&ctx, &msg, format!("⚠ {} ({}) is spamming: {}", msg.author.name, msg.author.id.0, msg.content.to_string()));
if alert_only {
if alert_channel_id != 0 {
let alert_description = format!("<@{0}> is currently spamming, but their messages will not be deleted due to `alert_only` being set to `true`", msg.author.id.0);
let _ = ChannelId(alert_channel_id).send_message(&ctx, |m| m.add_embed(|e| e.description(&alert_description))).await;
log(&ctx, &msg, format!("⚠ Message sent: {}", &alert_description));
}
} else {
log(&ctx, &msg, format!("⚠ Attempting to delete recent spam messages from user {} ({})", msg.author.name, msg.author.id.0));
let bot_user = ctx.cache.current_user().await;
let bot_member = ctx.cache.member(msg.guild_id.unwrap().0, bot_user.id).await;
if !bot_member.unwrap().permissions(&ctx).await.unwrap().contains(Permissions::MANAGE_MESSAGES) {
if alert_channel_id != 0 {
let alert_description = format!("<@{0}> is spamming, but I cannot delete their recent messages because I lack MANAGE_MESSAGES permissions", msg.author.id.0);
let _ = ChannelId(alert_channel_id).send_message(&ctx, |m| m.add_embed(|e| e.description(&alert_description))).await;
log(&ctx, &msg, format!("⚠ Message sent: {0}", &alert_description));
}
return;
}
if let Some(messages) = messages_to_delete {
let mut messages_by_channel: HashMap<u64, Vec<MessageId>> = HashMap::new();
// split messages by channel so we can bulk delete them
for message_to_delete in messages {
if messages_by_channel.contains_key(&message_to_delete.channel_id) {
if let Some(messages_in_channel) = messages_by_channel.get_mut(&message_to_delete.channel_id) {
messages_in_channel.push(MessageId(message_to_delete.message_id));
}
} else {
messages_by_channel.insert(message_to_delete.channel_id, vec![MessageId(message_to_delete.message_id)]);
}
}
for (channel_id, message_ids) in messages_by_channel.into_iter() {
//println!("{} {}", channel_id, message_ids.to_vec().into_iter().map(|i| i.to_string()).collect::<String>());
match ChannelId(channel_id).delete_messages(&ctx, message_ids).await {
Ok(_) => (),
Err(e) => eprintln!("Failed to delete messages: {}", e.to_string()),
}
}
}
if alert_channel_id != 0 {
let alert_description = format!("<@{0}> was spamming, so their recent messages were automatically deleted", msg.author.id.0);
let _ = ChannelId(alert_channel_id).send_message(&ctx, |m| m.add_embed(|e| e.description(&alert_description))).await;
log(&ctx, &msg, format!("⚠ Message sent: {0}", &alert_description));
}
}
}
|
|
main_page_data.rs
|
// MainPageData: contains data sent to main page
//
use super::country_name_link::CountryNameLink;
#[derive(Debug, Clone, RustcEncodable)]
pub struct
|
{
pub countries: Vec<CountryNameLink>,
}
|
MainPageData
|
user.controller.ts
|
import { Body, Controller, Get, Post, Query, Request } from '@nestjs/common';
@Controller('user')
export class
|
{
@Get()
index(): string {
return '用户首页';
}
// 通过@Query装饰器获取get传值 //http://localhost:3000/user/add?id=3&name=zhangxianhong
@Get('add')
addData(@Query() query): any {
// return '增加用户数据';
console.log(query); //{ id: '3', name: 'zhangxianhong' }
return query;
}
// 通过@Request装饰器获取Get传值 //http://localhost:3000/user/edit?name=zhangsan&password=123456
// 装饰器就相当于是一个方法
@Get('edit')
editData(@Request() req) {
console.log(req);
console.log(req.query); //{ name: 'zhangsan', password: '123456' }
return '通过Request获取get传值';
}
// post方法在Postman工具中进行模拟
@Post('create')
create() {
console.log('触发了Post方法');
return '我是Post方法';
}
// 获取Post传值————通过@Body装饰器获取
// http://localhost:3000/user/creates
@Post('creates')
creates(@Body() body) {
console.log('触发了post方法');//{ type: 'pop', page: '1', name: 'zhangsan', age: '20' }
console.log(body);
return '我是Post方法';
}
}
|
UserController
|
sqlite2del.py
|
"""
Copyright 2019 Faisal Thaheem
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 argparse
import os
import sys
import sqlite3
import time
import pprint
import traceback
import logging
import csv
import cv2
from objclass import getObjectClass
from tqdm import tqdm
ap = argparse.ArgumentParser()
ap.add_argument("-ln", "--lite.names", required=True,
help="comma seperated list of sqlite db files to look up image info from")
ap.add_argument("-dp", "--data.path", required=True,
help="comma seperated list of folders containing images to process")
args = vars(ap.parse_args())
#create logger
logger = logging.getLogger('sqlite2del')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler('sqlite2del.log')
fh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
# add the handlers to the logger
logger.addHandler(fh)
logger.addHandler(ch)
sqlitedbs = args["lite.names"].split(',')
datapaths = args["data.path"].split(',')
logger.info("Will be looking up following databases for info...")
logger.info(str(sqlitedbs))
logger.info("And, will be deleting files from..")
logger.info(str(datapaths))
dbconns = {}
dbcursors = {}
def loadsqlitedbs():
logger.info("Instantiating sqlite dbs")
for db in sqlitedbs:
logger.info("Opening database " + db)
if os.path.exists(db):
conn = sqlite3.connect(db)
dbconns[db] = conn
cursor = conn.cursor()
dbcursors[db] = cursor
logger.info("database [{}] opened".format(db))
else:
logger.warn("database [{}] does not exist, skipping".format(db))
dbcursors[db] = None
dbconns[db] = None
logger.info("dbs opened")
def closedbs():
logger.info("Closing dbs")
for db in sqlitedbs:
if dbcursors[db] is not None:
dbcursors[db].close()
if dbconns[db] is not None:
dbconns[db].close()
logger.info("DBs closed")
def lookupFile(nameWithoutExtension, filePath):
y1,x1,y2,x2,width,height,classId,className = None,None,None,None,None,None,None,None
global targetWidth, targetHeight, crop_height, crop_width, crop_enabled
for db in sqlitedbs:
try:
cursor = dbcursors[db]
if cursor is not None:
#look up plate information for the requested name
query = "SELECT y1,x1,y2,x2,width,height,imheight,imwidth FROM plates WHERE filename = '{}' and isdeleted = 0".format(nameWithoutExtension)
cursor.execute(query)
row = cursor.fetchone()
if row is not None:
y1,x1,y2,x2,width,height,imheight,imwidth = int(row[0]),int(row[1]),int(row[2]),int(row[3]),int(row[4]),int(row[5]),int(row[6]),int(row[7])
break
except:
logger.error(traceback.format_exc())
return y1,x1,y2,x2,width,height,classId,className
def processDataDir(datapath):
logger.error("Processing data path [{}]".format(datapath))
for root, dirs, files in os.walk(datapath):
totalFiles = len(files)
logger.error("Processing [{}] file(s) in root [{}]".format(totalFiles, root))
for i in tqdm(range(0,totalFiles)):
fileName = files[i]
filePath = os.path.join(root,fileName)
#logger.info("Processing.. {} [{} of {}]".format(filePath, i, totalFiles))
#y1,x1,y2,x2,width,height = lookupFile(os.path.splitext(fileName)[0])
y1,x1,y2,x2,width,height,classId,className = lookupFile(fileName, filePath)
if y1 is None:
logger.warn("Could not get information for [{}] @ [{}]".format(fileName,filePath))
continue
try:
pass
except:
logger.error(traceback.format_exc())
|
for path in datapaths:
processDataDir(path)
#clean up part
closedbs()
time_end = time.time()
logger.info("Took [{}] s to process request".format(time_end-time_start))
|
time_start = time.time()
loadsqlitedbs()
|
expr-if-fail.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn test_if_fail() { let x = if false
|
else { 10 }; assert!((x == 10)); }
fn test_else_fail() {
let x = if true { 10 } else { fail!() };
assert_eq!(x, 10);
}
fn test_elseif_fail() {
let x = if false { 0 } else if false { fail!() } else { 10 };
assert_eq!(x, 10);
}
pub fn main() { test_if_fail(); test_else_fail(); test_elseif_fail(); }
|
{ fail!() }
|
index.js
|
$(document).ready(function() {
AttachTaskListeners();
AttachProjectIndexListeners();
AttachSearchListener();
});
function AttachTaskListeners () {
var tasks = $('.todo li');
for (var i=0; i<tasks.length; i++) {
var task = $(tasks[i]);
$(task).on("click", function (e) {
if (!$(e.target).hasClass("fui-document")) {
$(e.target.closest("li")).toggleClass("todo-done");
}
});
}
}
function AttachProjectIndexListeners () {
var projects = $('.project-index li');
for (var i=0; i<projects.length; i++) {
var project = $(projects[i]);
$(project).on("click", function (e) {
SwitchProject($(e.target));
})
}
}
function SwitchProject (project) {
var name = project.html();
console.log(name);
var headers = $('.project-header');
for (var i=0; i<headers.length; i++) {
var header = $(headers[i]);
if (header.html() != name && name != "All") {
header.closest('.project').slideUp();
}
else header.closest('.project').slideDown();
}
}
|
});
}
function FilterTasks (filter) {
var tasks = $('.task');
for (var i=0; i<tasks.length; i++) {
var task = $(tasks[i]);
var name = $(task.find('.todo-name')).html();
if (ContainsString(name, filter)) task.show();
else task.hide();
}
}
function ContainsString (string, substring) {
return string.toLowerCase().indexOf(substring.toLowerCase()) >= 0;
}
|
function AttachSearchListener () {
$('.todo-search-field').on("keyup", function(e) {
var input = e.target.value;
FilterTasks(input);
|
test_class.py
|
import subprocess
EXPECT_FAIL_65 = [
'prefix_operator',
'grouping',
'infix_operator',
'to_this',
'inherit_self',
'local_inherit_self',
'return_value',
'parenthesized_superclass',
'missing_argument',
'var_in_body',
'fun_in_body',
'class_in_body',
'trailing_dot',
'leading_dot',
'decimal_point_at_eof',
'use_nil_as_var',
'use_local_in_initializer',
'use_this_as_var',
'duplicate_local',
'duplicate_parameter',
'collide_with_parameter',
'use_false_as_var',
'unterminated',
'parenthesized',
'no_superclass_bind',
'super_without_dot',
'super_at_top_level',
'no_reuse_constants',
'super_without_name',
'no_superclass_call',
'super_in_top_level_function',
'too_many_constants',
'too_many_upvalues',
'too_many_locals',
'loop_too_large',
'trees',
'this_at_top_level',
'this_in_top_level_function',
'statement_initializer',
'statement_increment',
'statement_condition',
'gunexpected_character',
'too_many_arguments',
'too_many_parameters',
'missing_comma_in_parameters',
'fun_in_then',
'fun_in_else',
'var_in_else',
'class_in_then',
'body_must_be_block',
'class_in_else',
'var_in_then',
'at_top_level',
]
EXPECT_FAIL_70 = [
'undefined',
'object',
'bool',
'nil',
'string',
'num',
'extra_arguments',
'missing_arguments',
'default_arguments',
'get_on_string',
'no_superclass_method',
'error_after_multiline',
'undefined_local',
'undefined_global',
'less_nonnum_num',
'multiply_num_nonnum',
'add_bool_num',
'add_bool_nil',
'greater_or_equal_num_nonnum',
'greater_or_equal_nonnum_num',
'less_num_nonnum',
'add_nil_nil',
'less_or_equal_nonnum_num',
'negate_nonnum',
'less_or_equal_num_nonnum',
'add_bool_string',
'subtract_num_nonnum',
'multiply_nonnum_num',
'add_string_nil',
'subtract_nonnum_num',
'divide_num_nonnum',
'add_num_nil',
'divide_nonnum_num',
'greater_num_nonnum',
'greater_nonnum_num',
'inherit_from_function',
'refer_to_name',
'local_mutual_recursion',
'not_found',
'stack_overflow',
'inherit_from_number',
'inherit_from_nil',
'set_on_class',
'get_on_function',
'call_nonfunction_field',
'get_on_nil',
'set_on_num',
'set_on_string',
'get_on_bool',
'get_on_class',
'set_on_bool',
'set_evaluation_order',
'get_on_num',
'set_on_nil',
'set_on_function',
]
def
|
():
test_file = '/mnt/projects/csdiy/compilers-8/bradfield/loxPy/tests/class/inherit_self.lox' # noqa: E501
resultp = subprocess.run(['python3', 'lox.py', test_file], capture_output=True)
resultj = subprocess.run(['../craftinginterpreters/jlox', test_file], capture_output=True)
assert resultp.returncode == resultj.returncode
def test_local_inherit_self():
test_file = '/mnt/projects/csdiy/compilers-8/bradfield/loxPy/tests/class/local_inherit_self.lox' # noqa: E501
resultp = subprocess.run(['python3', 'lox.py', test_file], capture_output=True)
resultj = subprocess.run(['../craftinginterpreters/jlox', test_file], capture_output=True)
assert resultp.returncode == resultj.returncode
def test_local_inherit_other():
test_file = '/mnt/projects/csdiy/compilers-8/bradfield/loxPy/tests/class/local_inherit_other.lox' # noqa: E501
resultp = subprocess.run(['python3', 'lox.py', test_file], capture_output=True)
resultj = subprocess.run(['../craftinginterpreters/jlox', test_file], capture_output=True)
assert resultp.returncode == resultj.returncode
def test_reference_self():
test_file = '/mnt/projects/csdiy/compilers-8/bradfield/loxPy/tests/class/reference_self.lox' # noqa: E501
resultp = subprocess.run(['python3', 'lox.py', test_file], capture_output=True)
resultj = subprocess.run(['../craftinginterpreters/jlox', test_file], capture_output=True)
assert resultp.returncode == resultj.returncode
def test_empty():
test_file = '/mnt/projects/csdiy/compilers-8/bradfield/loxPy/tests/class/empty.lox' # noqa: E501
resultp = subprocess.run(['python3', 'lox.py', test_file], capture_output=True)
resultj = subprocess.run(['../craftinginterpreters/jlox', test_file], capture_output=True)
assert resultp.returncode == resultj.returncode
def test_local_reference_self():
test_file = '/mnt/projects/csdiy/compilers-8/bradfield/loxPy/tests/class/local_reference_self.lox' # noqa: E501
resultp = subprocess.run(['python3', 'lox.py', test_file], capture_output=True)
resultj = subprocess.run(['../craftinginterpreters/jlox', test_file], capture_output=True)
assert resultp.returncode == resultj.returncode
def test_inherited_method():
test_file = '/mnt/projects/csdiy/compilers-8/bradfield/loxPy/tests/class/inherited_method.lox' # noqa: E501
resultp = subprocess.run(['python3', 'lox.py', test_file], capture_output=True)
resultj = subprocess.run(['../craftinginterpreters/jlox', test_file], capture_output=True)
assert resultp.returncode == resultj.returncode
|
test_inherit_self
|
rest-api.service.ts
|
import { Injectable } from "@angular/core";
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { Observable, throwError } from "rxjs";
import { MagicMirrorPackage } from "src/app/interfaces/interfaces";
import { retry, catchError } from "rxjs/operators";
import { URLS } from "src/app/utils/urls";
const httpOptions = (httpHeaders: object = {}) => new HttpHeaders({
"Content-Type": "application/json",
...httpHeaders
});
@Injectable({
providedIn: "root"
})
export class
|
{
constructor(private http: HttpClient) {}
private route(path: string): string {
return `http://${window.location.hostname}:7890/api${path}`;
}
public retrieve(path: string): Promise<any> {
return this.http.get<any>(
this.route(path), {
headers: httpOptions()
}).pipe(retry(1), catchError(this.handleError)).toPromise();
}
public getFile(url: string): Promise<any> {
return this.http.get(
this.route(url),
{
headers: httpOptions(),
responseType: "text"
}).pipe(retry(1), catchError(this.handleError)).toPromise();
}
private postWithSelectedPackages(url: string, selectedPackages: MagicMirrorPackage[]): Promise<any> {
return this.http.post(
this.route(url),
{
"selected-packages": selectedPackages
},
{
headers: httpOptions({
"Content-Type": "application/x-www-form-urlencoded"
}),
responseType: "text",
reportProgress: true
}).pipe(retry(1), catchError(this.handleError)).toPromise();
}
public packagesInstall(selectedPackages: MagicMirrorPackage[]): Promise<any> {
return this.postWithSelectedPackages(URLS.POST.PACKAGES.INSTALL, selectedPackages);
}
public packagesUpgrade(selectedPackages: MagicMirrorPackage[]): Promise<any> {
return this.postWithSelectedPackages(URLS.POST.PACKAGES.UPGRADE, selectedPackages);
}
public packagesRemove(selectedPackages: MagicMirrorPackage[]): Promise<any> {
return this.postWithSelectedPackages(URLS.POST.PACKAGES.REMOVE, selectedPackages);
}
public getLogFiles(): Promise<any> {
return this.http.get(this.route(URLS.GET.MMPM.DOWNLOAD_LOGS), {
headers: httpOptions({
"Content-Type": "application/zip",
}),
reportProgress: true,
responseType: "arraybuffer"
}).pipe(retry(1), catchError(this.handleError)).toPromise();
}
public updateMagicMirrorConfig(url: string, code: string): Observable<Response> {
return this.http.post<any>(
this.route(url),
{
code
},
{
headers: httpOptions({
"Content-Type": "application/x-www-form-urlencoded"
})
}).pipe(retry(1), catchError(this.handleError));
}
public addExternalPackage(externalSource: MagicMirrorPackage): Promise<any> {
return this.http.post<any>(
this.route(URLS.POST.EXTERNAL_PACKAGES.ADD),
{
"external-package": externalSource
},
{
headers: httpOptions({
"Content-Type": "application/x-www-form-urlencoded"
})
}).pipe(retry(1), catchError(this.handleError)).toPromise();
}
public rotateRaspberryPiScreen(degrees: number): Promise<boolean> {
return this.http.post<boolean>(
this.route(URLS.POST.RASPBERRYPI.ROTATE_SCREEN),
{
"degrees": String(degrees)
},
{
headers: httpOptions({
"Content-Type": "application/x-www-form-urlencoded"
})
}).pipe(retry(1), catchError(this.handleError)).toPromise();
}
public removeExternalPackage(externalSources: MagicMirrorPackage[]): Promise<any> {
return this.http.request(
"DELETE",
this.route(URLS.DELETE.EXTERNAL_PACKAGES.REMOVE),
{
body: {
"external-packages": externalSources
},
headers: httpOptions({
"Content-Type": "text/plain"
})
}).pipe(retry(1), catchError(this.handleError)).toPromise();
}
public upgradeMagicMirror(): Promise<any> {
return this.retrieve(URLS.GET.MAGICMIRROR.UPGRADE);
}
public handleError(error: any): Promise<any> {
const errorMessage = error.error instanceof ErrorEvent ?
error.error.message : `Error Code: ${error.status}\nMessage: ${error.message}`;
window.alert(errorMessage);
return throwError(errorMessage).toPromise();
}
}
|
RestApiService
|
encryption.rs
|
// Copyright 2020. The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
use aes_gcm::{
aead::{generic_array::GenericArray, Aead, Error as AeadError},
Aes256Gcm,
};
use rand::{rngs::OsRng, RngCore};
pub const AES_NONCE_BYTES: usize = 12;
pub const AES_KEY_BYTES: usize = 32;
pub trait Encryptable<C> {
fn encrypt(&mut self, cipher: &C) -> Result<(), String>;
fn decrypt(&mut self, cipher: &C) -> Result<(), String>;
}
pub fn
|
(cipher: &Aes256Gcm, ciphertext: Vec<u8>) -> Result<Vec<u8>, String> {
if ciphertext.len() < AES_NONCE_BYTES {
return Err(AeadError.to_string());
}
let (nonce, cipher_text) = ciphertext.split_at(AES_NONCE_BYTES);
let nonce = GenericArray::from_slice(nonce);
cipher.decrypt(nonce, cipher_text.as_ref()).map_err(|e| e.to_string())
}
pub fn encrypt_bytes_integral_nonce(cipher: &Aes256Gcm, plaintext: Vec<u8>) -> Result<Vec<u8>, String> {
let mut nonce = [0u8; AES_NONCE_BYTES];
OsRng.fill_bytes(&mut nonce);
let nonce_ga = GenericArray::from_slice(&nonce);
let mut ciphertext = cipher
.encrypt(nonce_ga, plaintext.as_ref())
.map_err(|e| e.to_string())?;
let mut ciphertext_integral_nonce = nonce.to_vec();
ciphertext_integral_nonce.append(&mut ciphertext);
Ok(ciphertext_integral_nonce)
}
#[cfg(test)]
mod test {
use aes_gcm::{
aead::{generic_array::GenericArray, NewAead},
Aes256Gcm,
};
use crate::util::encryption::{decrypt_bytes_integral_nonce, encrypt_bytes_integral_nonce};
#[test]
fn test_encrypt_decrypt() {
let plaintext = b"The quick brown fox was annoying".to_vec();
let key = GenericArray::from_slice(b"an example very very secret key.");
let cipher = Aes256Gcm::new(key);
let cipher_text = encrypt_bytes_integral_nonce(&cipher, plaintext.clone()).unwrap();
let decrypted_text = decrypt_bytes_integral_nonce(&cipher, cipher_text).unwrap();
assert_eq!(decrypted_text, plaintext);
}
}
|
decrypt_bytes_integral_nonce
|
archive.go
|
// Copyright 2020 Chaos Mesh Authors.
//
// 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package archive
import (
"context"
"fmt"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
"github.com/chaos-mesh/chaos-mesh/api/v1alpha1"
"github.com/chaos-mesh/chaos-mesh/pkg/apiserver/utils"
"github.com/chaos-mesh/chaos-mesh/pkg/config"
"github.com/chaos-mesh/chaos-mesh/pkg/core"
)
// Service defines a handler service for archive experiments.
type Service struct {
archive core.ExperimentStore
event core.EventStore
conf *config.ChaosDashboardConfig
}
// NewService returns an archive experiment service instance.
func NewService(
archive core.ExperimentStore,
event core.EventStore,
conf *config.ChaosDashboardConfig,
) *Service {
return &Service{
archive: archive,
event: event,
conf: conf,
}
}
// StatusResponse defines a common status struct.
type StatusResponse struct {
Status string `json:"status"`
}
// Register mounts our HTTP handler on the mux.
func
|
(r *gin.RouterGroup, s *Service) {
endpoint := r.Group("/archives")
endpoint.Use(func(c *gin.Context) {
utils.AuthRequired(c, s.conf.ClusterScoped, s.conf.TargetNamespace)
})
endpoint.GET("", s.list)
endpoint.GET("/detail", s.detail)
endpoint.GET("/report", s.report)
endpoint.DELETE("/:uid", s.delete)
endpoint.DELETE("/", s.batchDelete)
}
// Archive defines the basic information of an archive.
type Archive struct {
UID string `json:"uid"`
Kind string `json:"kind"`
Namespace string `json:"namespace"`
Name string `json:"name"`
Action string `json:"action"`
StartTime time.Time `json:"start_time"`
FinishTime time.Time `json:"finish_time"`
}
// Detail represents an archive instance.
type Detail struct {
Archive
KubeObject core.KubeObjectDesc `json:"kube_object"`
}
// Report defines the report of archive experiments.
type Report struct {
Meta *Archive `json:"meta"`
Events []*core.Event `json:"events"`
TotalTime string `json:"total_time"`
TotalFaultTime string `json:"total_fault_time"`
}
// @Summary Get archived chaos experiments.
// @Description Get archived chaos experiments.
// @Tags archives
// @Produce json
// @Param namespace query string false "namespace"
// @Param name query string false "name"
// @Param kind query string false "kind" Enums(PodChaos, IoChaos, NetworkChaos, TimeChaos, KernelChaos, StressChaos)
// @Success 200 {array} Archive
// @Router /archives [get]
// @Failure 500 {object} utils.APIError
func (s *Service) list(c *gin.Context) {
kind := c.Query("kind")
name := c.Query("name")
ns := c.Query("namespace")
if len(ns) == 0 && !s.conf.ClusterScoped &&
len(s.conf.TargetNamespace) != 0 {
ns = s.conf.TargetNamespace
}
metas, err := s.archive.ListMeta(context.Background(), kind, ns, name, true)
if err != nil {
c.Status(http.StatusInternalServerError)
_ = c.Error(utils.ErrInternalServer.NewWithNoMessage())
return
}
archives := make([]Archive, 0)
for _, meta := range metas {
archives = append(archives, Archive{
UID: meta.UID,
Kind: meta.Kind,
Namespace: meta.Namespace,
Name: meta.Name,
Action: meta.Action,
StartTime: meta.StartTime,
FinishTime: meta.FinishTime,
})
}
c.JSON(http.StatusOK, archives)
}
// @Summary Get the detail of an archived chaos experiment.
// @Description Get the detail of an archived chaos experiment.
// @Tags archives
// @Produce json
// @Param uid query string true "uid"
// @Success 200 {object} Detail
// @Router /archives/detail [get]
// @Failure 500 {object} utils.APIError
func (s *Service) detail(c *gin.Context) {
var (
err error
kubeObject core.KubeObjectDesc
detail Detail
)
uid := c.Query("uid")
namespace := c.Query("namespace")
if len(namespace) == 0 && !s.conf.ClusterScoped &&
len(s.conf.TargetNamespace) != 0 {
namespace = s.conf.TargetNamespace
}
if uid == "" {
c.Status(http.StatusBadRequest)
_ = c.Error(utils.ErrInvalidRequest.New("uid cannot be empty"))
return
}
exp, err := s.archive.FindByUID(context.Background(), uid)
if err != nil {
if gorm.IsRecordNotFoundError(err) {
c.Status(http.StatusInternalServerError)
_ = c.Error(utils.ErrInvalidRequest.New("the archive is not found"))
} else {
c.Status(http.StatusInternalServerError)
_ = c.Error(utils.ErrInternalServer.NewWithNoMessage())
}
return
}
if len(namespace) != 0 && exp.Namespace != namespace {
c.Status(http.StatusBadRequest)
_ = c.Error(utils.ErrInvalidRequest.New("exp %s belong to namespace %s but not namespace %s", uid, exp.Namespace, namespace))
return
}
switch exp.Kind {
case v1alpha1.KindPodChaos:
kubeObject, err = exp.ParsePodChaos()
case v1alpha1.KindIoChaos:
kubeObject, err = exp.ParseIOChaos()
case v1alpha1.KindNetworkChaos:
kubeObject, err = exp.ParseNetworkChaos()
case v1alpha1.KindTimeChaos:
kubeObject, err = exp.ParseTimeChaos()
case v1alpha1.KindKernelChaos:
kubeObject, err = exp.ParseKernelChaos()
case v1alpha1.KindStressChaos:
kubeObject, err = exp.ParseStressChaos()
case v1alpha1.KindDNSChaos:
kubeObject, err = exp.ParseDNSChaos()
case v1alpha1.KindAwsChaos:
kubeObject, err = exp.ParseAwsChaos()
case v1alpha1.KindGcpChaos:
kubeObject, err = exp.ParseGcpChaos()
default:
err = fmt.Errorf("kind %s is not support", exp.Kind)
}
if err != nil {
c.Status(http.StatusInternalServerError)
_ = c.Error(utils.ErrInternalServer.WrapWithNoMessage(err))
return
}
detail = Detail{
Archive: Archive{
UID: exp.UID,
Kind: exp.Kind,
Name: exp.Name,
Namespace: exp.Namespace,
Action: exp.Action,
StartTime: exp.StartTime,
FinishTime: exp.FinishTime,
},
KubeObject: kubeObject,
}
c.JSON(http.StatusOK, detail)
}
// @Summary Get the report of an archived chaos experiment.
// @Description Get the report of an archived chaos experiment.
// @Tags archives
// @Produce json
// @Param uid query string true "uid"
// @Success 200 {array} Report
// @Router /archives/report [get]
// @Failure 500 {object} utils.APIError
func (s *Service) report(c *gin.Context) {
var (
err error
report Report
)
uid := c.Query("uid")
namespace := c.Query("namespace")
if len(namespace) == 0 && !s.conf.ClusterScoped &&
len(s.conf.TargetNamespace) != 0 {
namespace = s.conf.TargetNamespace
}
if uid == "" {
c.Status(http.StatusBadRequest)
_ = c.Error(utils.ErrInvalidRequest.New("uid cannot be empty"))
return
}
meta, err := s.archive.FindMetaByUID(context.Background(), uid)
if err != nil {
if gorm.IsRecordNotFoundError(err) {
c.Status(http.StatusInternalServerError)
_ = c.Error(utils.ErrInvalidRequest.New("the archive is not found"))
} else {
c.Status(http.StatusInternalServerError)
_ = c.Error(utils.ErrInternalServer.NewWithNoMessage())
}
return
}
if len(namespace) != 0 && meta.Namespace != namespace {
c.Status(http.StatusBadRequest)
_ = c.Error(utils.ErrInvalidRequest.New("exp %s belong to namespace %s but not namespace %s", uid, meta.Namespace, namespace))
return
}
report.Meta = &Archive{
UID: meta.UID,
Kind: meta.Kind,
Namespace: meta.Namespace,
Name: meta.Name,
Action: meta.Action,
StartTime: meta.StartTime,
FinishTime: meta.FinishTime,
}
report.Events, err = s.event.ListByUID(context.TODO(), uid)
if err != nil {
c.Status(http.StatusInternalServerError)
_ = c.Error(utils.ErrInternalServer.NewWithNoMessage())
return
}
report.TotalTime = report.Meta.FinishTime.Sub(report.Meta.StartTime).String()
timeNow := time.Now()
timeAfter := timeNow
for _, et := range report.Events {
timeAfter = timeAfter.Add(et.FinishTime.Sub(*et.StartTime))
}
report.TotalFaultTime = timeAfter.Sub(timeNow).String()
c.JSON(http.StatusOK, report)
}
// @Summary Delete the specified archived experiment.
// @Description Delete the specified archived experiment.
// @Tags archives
// @Produce json
// @Param uid path string true "uid"
// @Success 200 {object} StatusResponse
// @Failure 500 {object} utils.APIError
// @Router /archives/{uid} [delete]
func (s *Service) delete(c *gin.Context) {
var (
err error
exp *core.Experiment
)
uid := c.Param("uid")
if exp, err = s.archive.FindByUID(context.Background(), uid); err != nil {
if gorm.IsRecordNotFoundError(err) {
c.Status(http.StatusInternalServerError)
_ = c.Error(utils.ErrInvalidRequest.New("the archived experiment is not found"))
} else {
c.Status(http.StatusInternalServerError)
_ = c.Error(utils.ErrInternalServer.WrapWithNoMessage(err))
}
return
}
if err = s.archive.Delete(context.Background(), exp); err != nil {
c.Status(http.StatusInternalServerError)
_ = c.Error(utils.ErrInternalServer.WrapWithNoMessage(err))
} else {
if err = s.event.DeleteByUID(context.Background(), uid); err != nil {
c.Status(http.StatusInternalServerError)
_ = c.Error(utils.ErrInternalServer.WrapWithNoMessage(err))
} else {
c.JSON(http.StatusOK, StatusResponse{Status: "success"})
}
}
}
// @Summary Delete the specified archived experiment.
// @Description Delete the specified archived experiment.
// @Tags archives
// @Produce json
// @Param uids query string true "uids"
// @Success 200 {object} StatusResponse
// @Failure 500 {object} utils.APIError
// @Router /archives [delete]
func (s *Service) batchDelete(c *gin.Context) {
var (
err error
uidSlice []string
)
uids := c.Query("uids")
if uids == "" {
c.Status(http.StatusBadRequest)
_ = c.Error(utils.ErrInternalServer.WrapWithNoMessage(fmt.Errorf("uids cannot be empty")))
return
}
uidSlice = strings.Split(uids, ",")
if err = s.archive.DeleteByUIDs(context.Background(), uidSlice); err != nil {
_ = c.Error(utils.ErrInternalServer.WrapWithNoMessage(err))
c.Status(http.StatusInternalServerError)
return
}
if err = s.event.DeleteByUIDs(context.Background(), uidSlice); err != nil {
_ = c.Error(utils.ErrInternalServer.WrapWithNoMessage(err))
c.Status(http.StatusInternalServerError)
return
}
c.JSON(http.StatusOK, StatusResponse{Status: "success"})
}
|
Register
|
train.py
|
import numpy as np
import random
import json
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
from nltk_utils import bag_of_words, tokenize, stem
from model import NeuralNet
with open('intents.json', 'r') as f:
intents = json.load(f)
all_words = []
tags = []
xy = []
# loop through each sentence in our intents patterns
for intent in intents['intents']:
tag = intent['tag']
# add to tag list
tags.append(tag)
for pattern in intent['patterns']:
# tokenize each word in the sentence
w = tokenize(pattern)
# add to our words list
all_words.extend(w)
# add to xy pair
xy.append((w, tag))
# stem and lower each word
ignore_words = ['?', '.', '!']
all_words = [stem(w) for w in all_words if w not in ignore_words]
# remove duplicates and sort
all_words = sorted(set(all_words))
tags = sorted(set(tags))
print(len(xy), "patterns")
print(len(tags), "tags:", tags)
print(len(all_words), "unique stemmed words:", all_words)
# create training data
X_train = []
y_train = []
for (pattern_sentence, tag) in xy:
# X: bag of words for each pattern_sentence
bag = bag_of_words(pattern_sentence, all_words)
X_train.append(bag)
# y: PyTorch CrossEntropyLoss needs only class labels, not one-hot
label = tags.index(tag)
y_train.append(label)
X_train = np.array(X_train)
y_train = np.array(y_train)
# Hyper-parameters
num_epochs = 1000
batch_size = 8
learning_rate = 0.001
input_size = len(X_train[0])
hidden_size = 8
output_size = len(tags)
print(input_size, output_size)
class ChatDataset(Dataset):
def
|
(self):
self.n_samples = len(X_train)
self.x_data = X_train
self.y_data = y_train
# support indexing such that dataset[i] can be used to get i-th sample
def __getitem__(self, index):
return self.x_data[index], self.y_data[index]
# we can call len(dataset) to return the size
def __len__(self):
return self.n_samples
dataset = ChatDataset()
train_loader = DataLoader(dataset=dataset,
batch_size=batch_size,
shuffle=True,
num_workers=0)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = NeuralNet(input_size, hidden_size, output_size).to(device)
# Loss and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
# Train the model
for epoch in range(num_epochs):
for (words, labels) in train_loader:
words = words.to(device)
labels = labels.to(dtype=torch.long).to(device)
# Forward pass
outputs = model(words)
# if y would be one-hot, we must apply
# labels = torch.max(labels, 1)[1]
loss = criterion(outputs, labels)
# Backward and optimize
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (epoch+1) % 100 == 0:
print (f'Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item():.4f}')
print(f'final loss: {loss.item():.4f}')
data = {
"model_state": model.state_dict(),
"input_size": input_size,
"hidden_size": hidden_size,
"output_size": output_size,
"all_words": all_words,
"tags": tags
}
FILE = "data.pth"
torch.save(data, FILE)
print(f'training complete. file saved to {FILE}')
|
__init__
|
avx2.rs
|
mod helpers;
use self::helpers::*;
#[derive(Copy, Clone)]
struct Initialized {
p: Aligned4x130,
m: SpacedMultiplier4x130,
r4: PrecomputedMultiplier,
}
#[derive(Clone)]
pub(crate) struct State {
k: AdditionKey,
r1: PrecomputedMultiplier,
r2: PrecomputedMultiplier,
initialized: Option<Initialized>,
cached_blocks: [Block; 4],
num_cached_blocks: usize,
partial_block: Option<Block>,
}
impl State {
pub(crate) fn new(key: &Key) -> Self {
let (k, r1) = unsafe { prepare_keys(key) };
let r2 = (r1 * r1).reduce();
State {
k,
r1,
r2: r2.into(),
initialized: None,
cached_blocks: [Block::default(); 4],
num_cached_blocks: 0,
partial_block: None,
}
}
pub(crate) fn reset(&mut self) {
self.initialized = None;
self.num_cached_blocks = 0;
}
#[target_feature(enable = "avx2")]
pub(crate) unsafe fn compute_block(&mut self, block: &Block, partial: bool) {
if partial {
assert!(self.partial_block.is_none());
self.partial_block = Some(*block);
return;
}
self.cached_blocks[self.num_cached_blocks].copy_from_slice(block);
if self.num_cached_blocks < 3 {
self.num_cached_blocks += 1;
return;
} else {
self.num_cached_blocks = 0;
}
if let Some(inner) = &mut self.initialized {
inner.p =
(&inner.p * inner.r4).reduce() + Aligned4x130::from_blocks(&self.cached_blocks);
} else {
let p = Aligned4x130::from_blocks(&self.cached_blocks);
let (m, r4) = SpacedMultiplier4x130::new(self.r1, self.r2);
self.initialized = Some(Initialized { p, m, r4 })
}
}
#[target_feature(enable = "avx2")]
pub(crate) unsafe fn finalize(&mut self) -> Tag {
assert!(self.num_cached_blocks < 4);
let mut data = &self.cached_blocks[..];
let mut p = self
.initialized
.take()
.map(|inner| (inner.p * inner.m).sum().reduce());
if self.num_cached_blocks >= 2 {
let mut c = Aligned2x130::from_blocks(data[..2].try_into().unwrap());
if let Some(p) = p {
c = c + p;
}
p = Some(c.mul_and_sum(self.r1, self.r2).reduce());
data = &data[2..];
self.num_cached_blocks -= 2;
}
if self.num_cached_blocks == 1 {
let mut c = Aligned130::from_block(&data[0]);
if let Some(p) = p {
c = c + p;
}
p = Some((c * self.r1).reduce());
self.num_cached_blocks -= 1;
}
if let Some(block) = &self.partial_block {
let mut c = Aligned130::from_partial_block(block);
if let Some(p) = p {
c = c + p;
}
p = Some((c * self.r1).reduce());
}
let mut tag = GenericArray::<u8, _>::default();
let tag_int = if let Some(p) = p {
self.k + p
} else {
self.k.into()
};
tag_int.write(tag.as_mut_slice());
Tag::new(tag)
}
}
|
use universal_hash::generic_array::GenericArray;
use crate::{Block, Key, Tag};
|
|
get.go
|
/*
Copyright 2020 The KubeEdge Authors.
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.
*/
package debug
import (
"context"
"encoding/json"
"fmt"
"io"
"os"
"strings"
"github.com/astaxie/beego/orm"
"github.com/spf13/cobra"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/cli-runtime/pkg/printers"
"k8s.io/klog/v2"
api "k8s.io/kubernetes/pkg/apis/core"
k8s_v1_api "k8s.io/kubernetes/pkg/apis/core/v1"
k8sprinters "k8s.io/kubernetes/pkg/printers"
printersinternal "k8s.io/kubernetes/pkg/printers/internalversion"
"k8s.io/kubernetes/pkg/printers/storage"
"github.com/kubeedge/beehive/pkg/common/util"
"github.com/kubeedge/beehive/pkg/core/model"
"github.com/kubeedge/kubeedge/common/constants"
"github.com/kubeedge/kubeedge/edge/pkg/common/dbm"
"github.com/kubeedge/kubeedge/edge/pkg/metamanager/dao"
edgecoreCfg "github.com/kubeedge/kubeedge/pkg/apis/componentconfig/edgecore/v1alpha1"
)
const (
// DefaultErrorExitCode defines exit the code for failed action generally
DefaultErrorExitCode = 1
// ResourceTypeAll defines resource type all
ResourceTypeAll = "all"
// FormatTypeWIDE defines output format wide
FormatTypeWIDE = "wide"
)
var (
debugGetLong = `
Prints a table of the most important information about the specified resource from the local database of the edge node.`
debugGetExample = `
# List all pod in namespace test
keadm debug get pod -n test
# List a single configmap with specified NAME
keadm debug get configmap web -n default
# List the complete information of the configmap with the specified name in the yaml output format
keadm debug get configmap web -n default -o yaml
# List the complete information of all available resources of edge nodes using the specified format (default: yaml)
keadm debug get all -o yaml`
// availableResources Convert flag to currently supports available Resource types in EdgeCore database.
availableResources = map[string]string{
"all": ResourceTypeAll,
"po": model.ResourceTypePod,
"pod": model.ResourceTypePod,
"pods": model.ResourceTypePod,
"no": model.ResourceTypeNode,
"node": model.ResourceTypeNode,
"nodes": model.ResourceTypeNode,
"svc": constants.ResourceTypeService,
"service": constants.ResourceTypeService,
"services": constants.ResourceTypeService,
"secret": model.ResourceTypeSecret,
"secrets": model.ResourceTypeSecret,
"cm": model.ResourceTypeConfigmap,
"configmap": model.ResourceTypeConfigmap,
"configmaps": model.ResourceTypeConfigmap,
"ep": constants.ResourceTypeEndpoints,
"endpoint": constants.ResourceTypeEndpoints,
"endpoints": constants.ResourceTypeEndpoints,
}
)
// NewCmdDebugGet returns keadm debug get command.
func NewCmdDebugGet(out io.Writer, getOption *GetOptions) *cobra.Command {
if getOption == nil {
getOption = NewGetOptions()
}
cmd := &cobra.Command{
Use: "get",
Short: "Display one or many resources",
Long: debugGetLong,
Example: debugGetExample,
Run: func(cmd *cobra.Command, args []string) {
if err := getOption.Validate(args); err != nil {
CheckErr(err, fatal)
}
if err := getOption.Run(args, out); err != nil {
CheckErr(err, fatal)
}
},
}
addGetOtherFlags(cmd, getOption)
return cmd
}
// fatal prints the message if set and then exits.
func fatal(msg string, code int) {
if len(msg) > 0 {
// add newline if needed
if !strings.HasSuffix(msg, "\n") {
msg += "\n"
}
fmt.Fprint(os.Stderr, msg)
}
os.Exit(code)
}
// CheckErr formats a given error as a string and calls the passed handleErr
// func with that string and an exit code.
func CheckErr(err error, handleErr func(string, int)) {
switch err.(type) {
case nil:
return
default:
handleErr(err.Error(), DefaultErrorExitCode)
}
}
// addGetOtherFlags
func addGetOtherFlags(cmd *cobra.Command, getOption *GetOptions) {
cmd.Flags().StringVarP(&getOption.Namespace, "namespace", "n", getOption.Namespace, "List the requested object(s) in specified namespaces")
cmd.Flags().StringVarP(getOption.PrintFlags.OutputFormat, "output", "o", *getOption.PrintFlags.OutputFormat, "Indicate the output format. Currently supports formats such as yaml|json|wide")
cmd.Flags().StringVarP(&getOption.LabelSelector, "selector", "l", getOption.LabelSelector, "Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2)")
cmd.Flags().StringVarP(&getOption.DataPath, "edgedb-path", "p", getOption.DataPath, "Indicate the edge node database path, the default path is \"/var/lib/kubeedge/edgecore.db\"")
cmd.Flags().BoolVarP(&getOption.AllNamespace, "all-namespaces", "A", getOption.AllNamespace, "List the requested object(s) across all namespaces")
}
// NewGetOptions returns a GetOptions with default EdgeCore database source.
func NewGetOptions() *GetOptions {
opts := &GetOptions{
Namespace: "default",
DataPath: edgecoreCfg.DataBaseDataSource,
PrintFlags: NewGetPrintFlags(),
}
return opts
}
// GetOptions contains the input to the get command.
type GetOptions struct {
AllNamespace bool
Namespace string
LabelSelector string
DataPath string
PrintFlags *PrintFlags
}
// Run performs the get operation.
func (g *GetOptions) Run(args []string, out io.Writer) error {
resType := args[0]
resNames := args[1:]
results, err := g.queryDataFromDatabase(availableResources[resType], resNames)
if err != nil {
return err
}
if len(g.LabelSelector) > 0 {
results, err = FilterSelector(results, g.LabelSelector)
if err != nil {
return err
}
}
if g.AllNamespace {
if err := g.PrintFlags.EnsureWithNamespace(); err != nil {
return err
}
}
printer, err := g.PrintFlags.ToPrinter()
if err != nil {
return err
}
if len(results) == 0 {
if _, err := fmt.Fprintf(out, "No resources found in %v namespace.\n", g.Namespace); err != nil {
return err
}
return nil
}
if *g.PrintFlags.OutputFormat == "" || *g.PrintFlags.OutputFormat == FormatTypeWIDE {
return HumanReadablePrint(results, printer, out)
}
return JSONYamlPrint(results, printer, out)
}
// IsAllowedFormat verification support format
func (g *GetOptions) IsAllowedFormat(f string) bool {
allowedFormats := g.PrintFlags.AllowedFormats()
for _, v := range allowedFormats {
if f == v {
return true
}
}
return false
}
// Validate checks the set of flags provided by the user.
func (g *GetOptions) Validate(args []string) error {
if len(args) == 0 {
return fmt.Errorf("You must specify the type of resource to get. ")
}
if !isAvailableResources(args[0]) {
return fmt.Errorf("Unrecognized resource type: %v. ", args[0])
}
if len(g.DataPath) == 0 {
fmt.Printf("Not specified the EdgeCore database path, use the default path: %v. ", g.DataPath)
}
if !isFileExist(g.DataPath) {
return fmt.Errorf("EdgeCore database file %v not exist. ", g.DataPath)
}
if err := InitDB(edgecoreCfg.DataBaseDriverName, edgecoreCfg.DataBaseAliasName, g.DataPath); err != nil {
return fmt.Errorf("Failed to initialize database: %v ", err)
}
if len(*g.PrintFlags.OutputFormat) > 0 {
format := strings.ToLower(*g.PrintFlags.OutputFormat)
g.PrintFlags.OutputFormat = &format
if !g.IsAllowedFormat(*g.PrintFlags.OutputFormat) {
return fmt.Errorf("Invalid output format: %v, currently supports formats such as yaml|json|wide. ", *g.PrintFlags.OutputFormat)
}
}
if args[0] == ResourceTypeAll && len(args) >= 2 {
return fmt.Errorf("You must specify only one resource. ")
}
return nil
}
func (g *GetOptions) queryDataFromDatabase(resType string, resNames []string) ([]dao.Meta, error) {
var result []dao.Meta
switch resType {
case model.ResourceTypePod:
pods, err := g.getPodsFromDatabase(g.Namespace, resNames)
if err != nil {
return nil, err
}
result = append(result, pods...)
case model.ResourceTypeNode:
node, err := g.getNodeFromDatabase(g.Namespace, resNames)
if err != nil {
return nil, err
}
result = append(result, node...)
case model.ResourceTypeConfigmap, model.ResourceTypeSecret, constants.ResourceTypeEndpoints, constants.ResourceTypeService:
value, err := g.getResourceFromDatabase(g.Namespace, resNames, resType)
if err != nil {
return nil, err
}
result = append(result, value...)
case ResourceTypeAll:
pods, err := g.getPodsFromDatabase(g.Namespace, resNames)
if err != nil {
return nil, err
}
result = append(result, pods...)
resTypes := []string{model.ResourceTypeConfigmap, model.ResourceTypeSecret, constants.ResourceTypeEndpoints, constants.ResourceTypeService}
for _, v := range resTypes {
value, err := g.getResourceFromDatabase(g.Namespace, resNames, v)
if err != nil {
return nil, err
}
result = append(result, value...)
}
default:
return nil, fmt.Errorf("Query resource type: %v in namespaces: %v failed. ", resType, g.Namespace)
}
return result, nil
}
func (g *GetOptions) getPodsFromDatabase(resNS string, resNames []string) ([]dao.Meta, error) {
var results []dao.Meta
podJSON := make(map[string]interface{})
podStatusJSON := make(map[string]interface{})
podRecords, err := dao.QueryAllMeta("type", model.ResourceTypePod)
if err != nil {
return nil, err
}
for _, v := range *podRecords {
namespaceParsed, _, _, _ := util.ParseResourceEdge(v.Key, model.QueryOperation)
if namespaceParsed != resNS && !g.AllNamespace {
continue
}
if len(resNames) > 0 && !isExistName(resNames, v.Key) {
continue
}
podKey := strings.Replace(v.Key, constants.ResourceSep+model.ResourceTypePod+constants.ResourceSep,
constants.ResourceSep+model.ResourceTypePodStatus+constants.ResourceSep, 1)
podStatusRecords, err := dao.QueryMeta("key", podKey)
if err != nil {
return nil, err
}
if len(*podStatusRecords) <= 0 {
results = append(results, v)
continue
}
if err := json.Unmarshal([]byte(v.Value), &podJSON); err != nil {
return nil, err
}
if err := json.Unmarshal([]byte((*podStatusRecords)[0]), &podStatusJSON); err != nil {
return nil, err
}
podJSON["status"] = podStatusJSON["Status"]
data, err := json.Marshal(podJSON)
if err != nil {
return nil, err
}
v.Value = string(data)
results = append(results, v)
}
return results, nil
}
func (g *GetOptions) getNodeFromDatabase(resNS string, resNames []string) ([]dao.Meta, error) {
var results []dao.Meta
nodeJSON := make(map[string]interface{})
nodeStatusJSON := make(map[string]interface{})
nodeRecords, err := dao.QueryAllMeta("type", model.ResourceTypeNode)
if err != nil {
return nil, err
}
for _, v := range *nodeRecords {
namespaceParsed, _, _, _ := util.ParseResourceEdge(v.Key, model.QueryOperation)
if namespaceParsed != resNS && !g.AllNamespace {
continue
}
if len(resNames) > 0 && !isExistName(resNames, v.Key) {
continue
}
nodeKey := strings.Replace(v.Key, constants.ResourceSep+model.ResourceTypeNode+constants.ResourceSep,
constants.ResourceSep+model.ResourceTypeNodeStatus+constants.ResourceSep, 1)
nodeStatusRecords, err := dao.QueryMeta("key", nodeKey)
if err != nil {
return nil, err
}
if len(*nodeStatusRecords) <= 0 {
results = append(results, v)
continue
}
if err := json.Unmarshal([]byte(v.Value), &nodeJSON); err != nil {
return nil, err
}
if err := json.Unmarshal([]byte((*nodeStatusRecords)[0]), &nodeStatusJSON); err != nil {
return nil, err
}
nodeJSON["status"] = nodeStatusJSON["Status"]
data, err := json.Marshal(nodeJSON)
if err != nil {
return nil, err
}
v.Value = string(data)
results = append(results, v)
}
return results, nil
}
func (g *GetOptions) getResourceFromDatabase(resNS string, resNames []string, resType string) ([]dao.Meta, error) {
var results []dao.Meta
resRecords, err := dao.QueryAllMeta("type", resType)
if err != nil {
return nil, err
}
for _, v := range *resRecords {
namespaceParsed, _, _, _ := util.ParseResourceEdge(v.Key, model.QueryOperation)
if namespaceParsed != resNS && !g.AllNamespace {
continue
}
if len(resNames) > 0 && !isExistName(resNames, v.Key) {
continue
}
results = append(results, v)
}
return results, nil
}
// FilterSelector filter resource by selector
func FilterSelector(data []dao.Meta, selector string) ([]dao.Meta, error) {
var results []dao.Meta
var jsonValue = make(map[string]interface{})
selectors, err := SplitSelectorParameters(selector)
if err != nil {
return nil, err
}
for _, v := range data {
err := json.Unmarshal([]byte(v.Value), &jsonValue)
if err != nil {
return nil, err
}
labels := jsonValue["metadata"].(map[string]interface{})["labels"]
if labels == nil {
results = append(results, v)
continue
}
flag := true
for _, v := range selectors {
if !v.Exist {
flag = flag && labels.(map[string]interface{})[v.Key] != v.Value
continue
}
flag = flag && (labels.(map[string]interface{})[v.Key] == v.Value)
}
if flag {
results = append(results, v)
}
}
return results, nil
}
// IsAvailableResources verification support resource type
func isAvailableResources(rsT string) bool
|
// IsFileExist check file is exist
func isFileExist(path string) bool {
_, err := os.Stat(path)
return err == nil || os.IsExist(err)
}
// InitDB Init DB info
func InitDB(driverName, dbName, dataSource string) error {
if err := orm.RegisterDriver(driverName, orm.DRSqlite); err != nil {
return fmt.Errorf("Failed to register driver: %v ", err)
}
if err := orm.RegisterDataBase(
dbName,
driverName,
dataSource); err != nil {
return fmt.Errorf("Failed to register db: %v ", err)
}
orm.RegisterModel(new(dao.Meta))
// create orm
dbm.DBAccess = orm.NewOrm()
if err := dbm.DBAccess.Using(dbName); err != nil {
return fmt.Errorf("Using db access error %v ", err)
}
return nil
}
// IsExistName verify the filed in the resNames exists in the name
func isExistName(resNames []string, name string) bool {
value := false
for _, v := range resNames {
if strings.Contains(name, v) {
value = true
}
}
return value
}
// Selector filter structure
type Selector struct {
Key string
Value string
Exist bool
}
// SplitSelectorParameters Split selector args (flag: -l)
func SplitSelectorParameters(args string) ([]Selector, error) {
var results = make([]Selector, 0)
var sel Selector
labels := strings.Split(args, ",")
for _, label := range labels {
if strings.Contains(label, "==") {
labs := strings.Split(label, "==")
if len(labs) != 2 {
return nil, fmt.Errorf("Arguments in selector form may not have more than one \"==\". ")
}
sel.Key = labs[0]
sel.Value = labs[1]
sel.Exist = true
results = append(results, sel)
continue
}
if strings.Contains(label, "!=") {
labs := strings.Split(label, "!=")
if len(labs) != 2 {
return nil, fmt.Errorf("Arguments in selector form may not have more than one \"!=\". ")
}
sel.Key = labs[0]
sel.Value = labs[1]
sel.Exist = false
results = append(results, sel)
continue
}
if strings.Contains(label, "=") {
labs := strings.Split(label, "=")
if len(labs) != 2 {
return nil, fmt.Errorf("Arguments in selector may not have more than one \"=\". ")
}
sel.Key = labs[0]
sel.Value = labs[1]
sel.Exist = true
results = append(results, sel)
}
}
return results, nil
}
func HumanReadablePrint(results []dao.Meta, printer printers.ResourcePrinter, out io.Writer) error {
res, err := ParseMetaToAPIList(results)
if err != nil {
klog.Fatal(err)
}
for _, r := range res {
table, err := ConvertDataToTable(r)
if err != nil {
klog.Fatal(err)
}
if err := printer.PrintObj(table, out); err != nil {
klog.Fatal(err)
}
if _, err := fmt.Fprintln(out); err != nil {
klog.Fatal(err)
}
}
return nil
}
// xParseMetaToAPIList Convert the data to the corresponding list type according to the apiserver usage type
// Only use this type definition to get the table header processing handle,
// and automatically obtain the ColumnDefinitions of the table according to the type
// Only used by HumanReadablePrint.
func ParseMetaToAPIList(metas []dao.Meta) (res []runtime.Object, err error) {
var (
podList api.PodList
serviceList api.ServiceList
secretList api.SecretList
configMapList api.ConfigMapList
endPointsList api.EndpointsList
nodeList api.NodeList
)
for _, v := range metas {
switch v.Type {
case model.ResourceTypePod:
var pod v1.Pod
var apiPod api.Pod
if err = json.Unmarshal([]byte(v.Value), &pod); err != nil {
return nil, err
}
if err := k8s_v1_api.Convert_v1_Pod_To_core_Pod(&pod, &apiPod, nil); err != nil {
return nil, err
}
podList.Items = append(podList.Items, apiPod)
case constants.ResourceTypeService:
var svc v1.Service
var apiSvc api.Service
if err = json.Unmarshal([]byte(v.Value), &svc); err != nil {
return nil, err
}
if err := k8s_v1_api.Convert_v1_Service_To_core_Service(&svc, &apiSvc, nil); err != nil {
return nil, err
}
serviceList.Items = append(serviceList.Items, apiSvc)
case model.ResourceTypeSecret:
var secret v1.Secret
var apiSecret api.Secret
if err = json.Unmarshal([]byte(v.Value), &secret); err != nil {
return nil, err
}
if err := k8s_v1_api.Convert_v1_Secret_To_core_Secret(&secret, &apiSecret, nil); err != nil {
return nil, err
}
secretList.Items = append(secretList.Items, apiSecret)
case model.ResourceTypeConfigmap:
var cm v1.ConfigMap
var apiCm api.ConfigMap
if err = json.Unmarshal([]byte(v.Value), &cm); err != nil {
return nil, err
}
if err := k8s_v1_api.Convert_v1_ConfigMap_To_core_ConfigMap(&cm, &apiCm, nil); err != nil {
return nil, err
}
configMapList.Items = append(configMapList.Items, apiCm)
case constants.ResourceTypeEndpoints:
var ep v1.Endpoints
var apiEp api.Endpoints
if err = json.Unmarshal([]byte(v.Value), &ep); err != nil {
return nil, err
}
if err := k8s_v1_api.Convert_v1_Endpoints_To_core_Endpoints(&ep, &apiEp, nil); err != nil {
return nil, err
}
endPointsList.Items = append(endPointsList.Items, apiEp)
case model.ResourceTypeNode:
var no v1.Node
var apiNo api.Node
if err = json.Unmarshal([]byte(v.Value), &no); err != nil {
return nil, err
}
if err := k8s_v1_api.Convert_v1_Node_To_core_Node(&no, &apiNo, nil); err != nil {
return nil, err
}
nodeList.Items = append(nodeList.Items, apiNo)
}
}
res = append(res, &podList, &serviceList, &secretList, &configMapList, &endPointsList, &nodeList)
return
}
// ConvertDataToTable Convert the data into table kind to simulate the data sent by api-server
func ConvertDataToTable(obj runtime.Object) (runtime.Object, error) {
to := metav1.TableOptions{}
tc := storage.TableConvertor{TableGenerator: k8sprinters.NewTableGenerator().With(printersinternal.AddHandlers)}
return tc.ConvertToTable(context.TODO(), obj, &to)
}
// JSONYamlPrint Output the data in json|yaml format
func JSONYamlPrint(results []dao.Meta, printer printers.ResourcePrinter, out io.Writer) error {
var obj runtime.Object
list := v1.List{
TypeMeta: metav1.TypeMeta{
Kind: "List",
APIVersion: "v1",
},
ListMeta: metav1.ListMeta{},
}
objectList, err := ParseMetaToV1List(results)
if err != nil {
return err
}
if len(objectList) != 1 {
for _, info := range objectList {
if info == nil {
continue
}
o := info.DeepCopyObject()
list.Items = append(list.Items, runtime.RawExtension{Object: o})
}
listData, err := json.Marshal(list)
if err != nil {
return err
}
converted, err := runtime.Decode(unstructured.UnstructuredJSONScheme, listData)
if err != nil {
return err
}
obj = converted
} else {
obj = objectList[0]
}
if err := PrintGeneric(printer, obj, out); err != nil {
return err
}
return nil
}
// ParseMetaToV1List Convert the data to the corresponding list type
// The type definition used by apiserver does not have the omitempty definition of json, will introduce a lot of useless null information
// Use v1 type definition to get data here
// Only used by JSONYamlPrint.
func ParseMetaToV1List(results []dao.Meta) ([]runtime.Object, error) {
value := make(map[string]interface{})
list := make([]runtime.Object, 0)
for _, v := range results {
if err := json.Unmarshal([]byte(v.Value), &value); err != nil {
return nil, err
}
metadata, err := json.Marshal(value["metadata"])
if err != nil {
return nil, err
}
switch v.Type {
case model.ResourceTypePod:
pod := v1.Pod{}
status, err := json.Marshal(value["status"])
if err != nil {
return nil, err
}
spec, err := json.Marshal(value["spec"])
if err != nil {
return nil, err
}
if err := json.Unmarshal(metadata, &pod.ObjectMeta); err != nil {
return nil, err
}
if err := json.Unmarshal(spec, &pod.Spec); err != nil {
return nil, err
}
if err := json.Unmarshal(status, &pod.Status); err != nil {
return nil, err
}
pod.APIVersion = "v1"
pod.Kind = v.Type
list = append(list, pod.DeepCopyObject())
case constants.ResourceTypeService:
svc := v1.Service{}
status, err := json.Marshal(value["status"])
if err != nil {
return nil, err
}
spec, err := json.Marshal(value["spec"])
if err != nil {
return nil, err
}
if err := json.Unmarshal(metadata, &svc.ObjectMeta); err != nil {
return nil, err
}
if err := json.Unmarshal(spec, &svc.Spec); err != nil {
return nil, err
}
if err := json.Unmarshal(status, &svc.Status); err != nil {
return nil, err
}
svc.APIVersion = "v1"
svc.Kind = v.Type
list = append(list, svc.DeepCopyObject())
case model.ResourceTypeSecret:
secret := v1.Secret{}
data, err := json.Marshal(value["data"])
if err != nil {
return nil, err
}
typeTmp, err := json.Marshal(value["type"])
if err != nil {
return nil, err
}
if err := json.Unmarshal(metadata, &secret.ObjectMeta); err != nil {
return nil, err
}
if err := json.Unmarshal(data, &secret.Data); err != nil {
return nil, err
}
if err := json.Unmarshal(typeTmp, &secret.Type); err != nil {
return nil, err
}
secret.APIVersion = "v1"
secret.Kind = v.Type
list = append(list, secret.DeepCopyObject())
case model.ResourceTypeConfigmap:
cmp := v1.ConfigMap{}
data, err := json.Marshal(value["data"])
if err != nil {
return nil, err
}
if err := json.Unmarshal(metadata, &cmp.ObjectMeta); err != nil {
return nil, err
}
if err := json.Unmarshal(data, &cmp.Data); err != nil {
return nil, err
}
cmp.APIVersion = "v1"
cmp.Kind = v.Type
list = append(list, cmp.DeepCopyObject())
case constants.ResourceTypeEndpoints:
ep := v1.Endpoints{}
if err := json.Unmarshal([]byte(v.Value), &value); err != nil {
return nil, err
}
metadata, err := json.Marshal(value["metadata"])
if err != nil {
return nil, err
}
subsets, err := json.Marshal(value["subsets"])
if err != nil {
return nil, err
}
if err := json.Unmarshal(metadata, &ep.ObjectMeta); err != nil {
return nil, err
}
if err := json.Unmarshal(subsets, &ep.Subsets); err != nil {
return nil, err
}
ep.APIVersion = "v1"
ep.Kind = v.Type
list = append(list, ep.DeepCopyObject())
case model.ResourceTypeNode:
node := v1.Node{}
status, err := json.Marshal(value["status"])
if err != nil {
return nil, err
}
spec, err := json.Marshal(value["spec"])
if err != nil {
return nil, err
}
if err := json.Unmarshal(metadata, &node.ObjectMeta); err != nil {
return nil, err
}
if err := json.Unmarshal(status, &node.Status); err != nil {
return nil, err
}
if err := json.Unmarshal(spec, &node.Spec); err != nil {
return nil, err
}
node.APIVersion = "v1"
node.Kind = v.Type
list = append(list, node.DeepCopyObject())
default:
return nil, fmt.Errorf("Parsing failed, unrecognized type: %v. ", v.Type)
}
}
return list, nil
}
// PrintGeneric Output object data to out stream through printer
func PrintGeneric(printer printers.ResourcePrinter, obj runtime.Object, out io.Writer) error {
isList := meta.IsListType(obj)
if isList {
items, err := meta.ExtractList(obj)
if err != nil {
return err
}
// take the items and create a new list for display
list := &unstructured.UnstructuredList{
Object: map[string]interface{}{
"kind": "List",
"apiVersion": "v1",
"metadata": map[string]interface{}{},
},
}
if listMeta, err := meta.ListAccessor(obj); err == nil {
list.Object["metadata"] = map[string]interface{}{
"selfLink": listMeta.GetSelfLink(),
"resourceVersion": listMeta.GetResourceVersion(),
}
}
for _, item := range items {
list.Items = append(list.Items, *item.(*unstructured.Unstructured))
}
if err := printer.PrintObj(list, out); err != nil {
return err
}
} else {
var value map[string]interface{}
data, err := json.Marshal(obj)
if err != nil {
return err
}
if err := json.Unmarshal(data, &value); err != nil {
return err
}
if err := printer.PrintObj(&unstructured.Unstructured{Object: value}, out); err != nil {
return err
}
}
return nil
}
|
{
_, ok := availableResources[rsT]
return ok
}
|
experiment_2_algorithm_settings.py
|
"""
Evaluating index's fluence on performance to achieve certain recall.
Note: if using perf to profile the program, use sudo to run the commands (already
hardcoded in this script), make sure the user have sudo access
Example Usage:
python experiment_2_algorithm_settings.py --dbname SIFT1000M --topK 100 --recall_goal 0.95 --qbs 10000 --repeat_time 1 \
--cpp_bin_dir /data/faiss-cpu-profiling/build/demos/bigann_search \
--index_parent_dir /data/Faiss_experiments/trained_CPU_indexes/ \
--gt_parent_dir /data/Faiss_experiments/bigann/gnd/ \
--nprobe_dict_dir '../recall_info/cpu_recall_index_nprobe_pairs_SIFT1000M.pkl' --perf_enable 1
"""
from __future__ import print_function
import os
import sys
import time
import re
import pickle
import getpass
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--dbname', type=str, default='SIFT1000M', help="dataset name, e.g., SIFT100M")
parser.add_argument('--topK', type=int, default=10, help="return topK most similar vector, related to recall, e.g., R@10=50perc or R@100=80perc")
parser.add_argument('--recall_goal', type=float, default=0.8, help="recall goal 0~1")
parser.add_argument('--qbs', type=int, default=10000, help="batch size")
parser.add_argument('--repeat_time', type=int, default=1, help="repeat_time of the 10000 queries, higher repeat time typically has a better stability")
parser.add_argument('--cpp_bin_dir', type=str, default='/data/faiss-cpu-profiling/build/demos/bigann_search', help="c++ search binary")
parser.add_argument('--index_parent_dir', type=str, default='/data/Faiss_experiments/trained_CPU_indexes/', help="parent directory of index storage")
parser.add_argument('--gt_parent_dir', type=str, default='/data/Faiss_experiments/bigann/gnd/', help="parent directory of ground truth")
parser.add_argument('--nprobe_dict_dir', type=str, default='../recall_info/cpu_recall_index_nprobe_pairs_SIFT1000M.pkl', help="recall dictionary, stores the min nprobe to achieve certain recall")
parser.add_argument('--perf_enable', type=int, default=1, help="whether to profile by perf")
args = parser.parse_args()
dbname = args.dbname
topK = args.topK
recall_goal = args.recall_goal
qbs = args.qbs
repeat_time = args.repeat_time
cpp_bin_dir = args.cpp_bin_dir
index_parent_dir = args.index_parent_dir
gt_parent_dir = args.gt_parent_dir
nprobe_dict_dir = args.nprobe_dict_dir
perf_enable = args.perf_enable
assert qbs == 10000, "Currently the c++ search program only support batch size = 10000"
# dictionary format: d_nprobes[dbname][index_key][topK][recall_goal] = min_nprobe
d_nprobes = None
if os.path.exists(nprobe_dict_dir):
with open(nprobe_dict_dir, 'rb') as f:
d_nprobes = pickle.load(f)
else:
print("ERROR! input dictionary does not exists")
raise ValueError
out_dir = "result_experiment_2_algorithm_settings"
if not os.path.exists(out_dir):
os.mkdir(out_dir)
logname = "./{out_dir}/out_{dbname}_R@{topK}={recall_goal}_qbs_{qbs}".format(
out_dir=out_dir, dbname=dbname, topK=topK, recall_goal=recall_goal, qbs=qbs)
if os.path.exists(logname):
os.remove(logname)
gt_dir = None
|
gt_dir = os.path.join(gt_parent_dir, 'idx_1M.ivecs')
elif dbname == 'SIFT10M':
gt_dir = os.path.join(gt_parent_dir, 'idx_10M.ivecs')
elif dbname == 'SIFT100M':
gt_dir = os.path.join(gt_parent_dir, 'idx_100M.ivecs')
elif dbname == 'SIFT1000M':
gt_dir = os.path.join(gt_parent_dir, 'idx_1000M.ivecs')
else:
print("ERROR: unknown dataset")
raise ValueError
index_keys = ['IVF1024,PQ16', 'IVF2048,PQ16', 'IVF4096,PQ16', 'IVF8192,PQ16', 'IVF16384,PQ16', 'IVF32768,PQ16', 'IVF65536,PQ16', 'IVF131072,PQ16', 'IVF262144,PQ16', \
'OPQ16,IVF1024,PQ16', 'OPQ16,IVF2048,PQ16', 'OPQ16,IVF4096,PQ16', 'OPQ16,IVF8192,PQ16', 'OPQ16,IVF16384,PQ16', 'OPQ16,IVF32768,PQ16', 'OPQ16,IVF65536,PQ16', 'OPQ16,IVF131072,PQ16', 'OPQ16,IVF262144,PQ16']
for index_key in index_keys:
nprobe = d_nprobes[dbname][index_key][topK][recall_goal]
if nprobe is None:
continue
os.system('echo ==== {index_key} ==== >> {logname}'.format(index_key=index_key, logname=logname))
index_sub_dir = 'bench_cpu_{dbname}_{index_key}/{dbname}_{index_key}_populated.index'.format(dbname=dbname, index_key=index_key)
index_dir = os.path.join(index_parent_dir, index_sub_dir)
# Usage: ./binary index_dir gt_dir topK nprobe
cmd = "{cpp_bin_dir} {index_dir} {gt_dir} {topK} {nprobe} {repeat_time} >> {logname}".format(
cpp_bin_dir=cpp_bin_dir, index_dir=index_dir, gt_dir=gt_dir, topK=topK, nprobe=nprobe, repeat_time=repeat_time, logname=logname)
if not perf_enable:
print(cmd)
os.system(cmd)
else:
cmd_prefix = "perf record -v -g -F 99 "
cmd_prof = "sudo " + cmd_prefix + cmd
print(cmd_prof)
os.system(cmd_prof)
# generate the perf.out, i.e., the trace of each sample
reportname = "./{out_dir}/perf.out_{dbname}_{index_key}_R@{topK}={recall_goal}_nprobe_{nprobe}_qbs_{qbs}".format(
out_dir=out_dir, dbname=dbname, index_key=index_key, topK=topK, recall_goal=recall_goal, nprobe=nprobe,qbs=qbs)
cmd_stats = "sudo perf script > {reportname}".format(reportname=reportname)
os.system(cmd_stats)
username = getpass.getuser()
os.system("sudo chown {username} {reportname}".format(username=username, reportname=reportname))
os.system("sudo rm perf.data perf.data.old")
|
if dbname == 'SIFT1M':
|
command_runner.rs
|
use crate::remote::{Computer, Connector, Command, PsExec, PsRemote, Ssh, Rdp, Wmi, Local};
use std::path::{Path, PathBuf};
use std::fs::File;
use crate::command_utils::parse_command;
use std::time::Duration;
pub struct CommandRunner<'a> {
local_store_directory: &'a Path,
pub(crate) connector: Box<dyn Connector>,
run_implicit: bool,
}
impl<'a> CommandRunner<'a> {
pub fn psexec(
remote_computer: Computer,
local_store_directory: &'a Path,
remote_temp_storage: PathBuf,
custom_share_folder: Option<String>
) -> CommandRunner<'a> {
CommandRunner {
local_store_directory,
connector: Box::new(PsExec::paexec(remote_computer, remote_temp_storage, custom_share_folder)),
run_implicit: true,
}
}
pub fn wmi(
remote_computer: Computer,
local_store_directory: &'a Path,
remote_temp_storage: PathBuf
) -> CommandRunner<'a> {
CommandRunner {
local_store_directory,
connector: Box::new(Wmi { computer: remote_computer, remote_temp_storage}),
run_implicit: true,
}
}
pub fn local(
username: String,
local_store_directory: &'a Path,
) -> CommandRunner<'a>
|
pub fn psremote(
remote_computer: Computer,
local_store_directory: &'a Path,
remote_temp_storage: PathBuf,
custom_share_folder: Option<String>
) -> CommandRunner<'a> {
CommandRunner {
local_store_directory,
connector: Box::new(PsRemote::new(remote_computer, remote_temp_storage, custom_share_folder)),
run_implicit: true,
}
}
pub fn rdp(
remote_computer: Computer,
local_store_directory: &'a Path,
nla: bool,
remote_temp_storage: PathBuf
) -> CommandRunner<'a> {
CommandRunner {
local_store_directory,
connector: Box::new(Rdp {
computer: remote_computer,
nla,
remote_temp_storage
}),
run_implicit: true,
}
}
pub fn ssh(
remote_computer: Computer,
local_store_directory: &'a Path,
key_file: Option<PathBuf>,
) -> CommandRunner<'a> {
CommandRunner {
local_store_directory,
connector: Box::new(Ssh { key_file, computer: remote_computer }),
run_implicit: false,
}
}
pub fn run_commands(
&self,
command_file: &Path,
timeout: Option<Duration>
) {
let file = match File::open(command_file) {
Ok(file) => file,
Err(err) => {
error!("{}", err);
return;
}
};
let reader = std::io::BufReader::new(file);
use std::io::BufRead;
for one_command in reader.lines().filter_map(|item| item.ok()) {
if one_command.starts_with("#") {
continue;
}
if one_command.is_empty() {
continue;
}
debug!("Running remote command {}", one_command);
let command = parse_command(&one_command);
let first_arg = command[0].to_ascii_lowercase();
let command = if first_arg.starts_with(":") {
let method_name = self.connector.connect_method_name().to_ascii_lowercase();
if first_arg.contains(&method_name) {
command[1..].to_vec()
} else {
continue;
}
} else if self.run_implicit {
command
} else {
continue;
};
let elevated =
first_arg.contains(":admin") || first_arg.contains(":sudo");
let command_joined: String = command.join("-");
let command_joined = if command_joined.len() > 100 {
command_joined[..100].to_string()
} else {
command_joined
};
let command_joined = command_joined
.replace(" ", "-")
.replace("\"", "")
.replace("/", "")
.replace("\\", "")
.replace(":", "-");
let report_filename_prefix = format!("custom-{}", command_joined);
let remote_connection = Command::new(
command,
Some(&self.local_store_directory),
&report_filename_prefix,
elevated,
);
if let Err(err) = self.connector.connect_and_run_command(
remote_connection,
timeout
) {
error!("{}", err)
};
}
}
}
|
{
CommandRunner {
local_store_directory,
connector: Box::new(Local::new(username, local_store_directory.to_path_buf())),
run_implicit: true,
}
}
|
themes.ts
|
// Copyright 2019-2021 @polkadot/extension-ui authors & contributors
// SPDX-License-Identifier: Apache-2.0
const darkTheme = {
accountBackground: '#1A1B20',
|
backButtonBackground: '#3A3B41',
backButtonBackgroundHover: '#3a3b41ad',
backButtonTextColor: '#FFFFFF',
background: '#26272C',
bodyColor: '#20222A',
borderRadius: '4px',
boxBorderColor: '#303030',
boxMargin: '0.75rem 0',
boxPadding: '0 0.25rem',
boxShadow: 'rgba(0, 0, 0, 0.86)',
buttonBackground: '#E86F00',
buttonBackgroundDanger: '#AF1111',
buttonBackgroundDangerHover: '#D93B3B',
buttonBackgroundHover: '#ED9329',
buttonTextColor: '#FFFFFF',
errorBorderColor: '#7E3530',
errorColor: '#E42F2F',
fontFamily: 'Nunito, sans-serif',
fontSize: '16px',
highlightedAreaBackground: '#212226',
iconDangerColor: '#AF1111',
iconNeutralColor: '#8E8E8E',
iconWarningColor: '#FF7D01',
id: 'dark',
identiconBackground: '#F4F5F8',
inputBackground: '#111218',
inputBorderColor: '#43444B',
inputLabelFontSize: '10px',
labelColor: '#9F9E99',
labelFontSize: '13px',
labelLineHeight: '18px',
lineHeight: '26px',
parentLabelColor: '#4A7463',
popupBackground: '#38393F',
primaryColor: '#FF7D01',
readonlyInputBackground: '#1A1B20',
subTextColor: '#DDD',
textColor: '#FFFFFF',
textColorDanger: '#FF8686'
};
export declare type Theme = typeof darkTheme;
const lightTheme: Theme = {
...darkTheme,
accountBackground: '#FFFFFF',
addAccountImageBackground: '#FFF',
backButtonBackground: '#D7D7D7',
backButtonBackgroundHover: '#d7d7d7ad',
backButtonTextColor: '#454545',
background: '#FAFAFA',
bodyColor: '#FFFFFF',
boxBorderColor: '#DADFEA',
boxShadow: 'rgba(0, 0, 0, 0.3)',
buttonBackgroundDanger: '#DC2222',
errorBorderColor: '#E42F2F',
highlightedAreaBackground: '#EFEFEF',
iconDangerColor: '#DC2222',
iconNeutralColor: '#939CB1',
id: 'light',
inputBackground: '#FFFFFF',
inputBorderColor: '#DDE1EB',
labelColor: '#333333',
parentLabelColor: '#215B4F',
popupBackground: '#FFFFFF',
readonlyInputBackground: '#FFF',
subTextColor: '#454545',
textColor: '#242529',
textColorDanger: '#F24A4A'
};
export const themes = {
dark: darkTheme,
light: lightTheme
};
export declare type AvailableThemes = keyof typeof themes;
export function chooseTheme (): AvailableThemes {
const preferredTheme = localStorage.getItem('theme');
if (preferredTheme) {
return preferredTheme === 'dark'
? 'dark'
: 'light';
}
return window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches
? 'light'
: 'dark';
}
|
accountDotsIconColor: '#8E8E8E',
addAccountImageBackground: '#1A1B20',
|
views.py
|
# Copyright (C) 2010-2013 Yaco Sistemas (http://www.yaco.es)
# Copyright (C) 2009 Lorenzo Gil Sanchez <[email protected]>
#
# 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 base64
import logging
from django.conf import settings
from django.contrib import auth
from django.contrib.auth.decorators import login_required
try:
from django.contrib.auth.views import LogoutView
django_logout = LogoutView.as_view()
except ImportError:
from django.contrib.auth.views import logout as django_logout
from django.core.exceptions import PermissionDenied, SuspiciousOperation
from django.http import Http404, HttpResponse
from django.http import HttpResponseRedirect # 30x
from django.http import HttpResponseBadRequest # 40x
from django.http import HttpResponseServerError # 50x
from django.views.decorators.http import require_POST
from django.shortcuts import render
from django.template import TemplateDoesNotExist
from django.utils.six import text_type, binary_type, PY3
from django.views.decorators.csrf import csrf_exempt
from saml2 import BINDING_HTTP_REDIRECT, BINDING_HTTP_POST
from saml2.config import SP_ARGS, SPEC
from saml2.metadata import entity_descriptor
from saml2.ident import code, decode
from saml2.sigver import MissingKey
from saml2.s_utils import UnsupportedBinding
from saml2.response import (
StatusError, StatusAuthnFailed, SignatureError, StatusRequestDenied,
UnsolicitedResponse,
)
from saml2.validate import ResponseLifetimeExceed, ToEarly
# support for SHA1 is required by spec
from saml2.xmldsig import SIG_RSA_SHA1, SIG_RSA_SHA256, DIGEST_SHA256, DIGEST_SHA1
from djangosaml2.cache import IdentityCache, OutstandingQueriesCache
from djangosaml2.cache import StateCache
from djangosaml2.conf import get_config
from djangosaml2.overrides import Saml2Client
from djangosaml2.signals import post_authenticated
from djangosaml2.utils import (
available_idps, fail_acs_response, get_custom_setting,
get_idp_sso_supported_bindings, get_location, is_safe_url_compat,
)
# Monkey patch
if 'authn_requests_signed_alg' not in SP_ARGS:
SP_ARGS += ['authn_requests_signed_alg']
SPEC['sp'] += ['authn_requests_signed_alg']
if 'authn_requests_digest_alg' not in SP_ARGS:
SP_ARGS += ['authn_requests_digest_alg']
SPEC['sp'] += ['authn_requests_digest_alg']
logger = logging.getLogger('djangosaml2')
def _set_subject_id(session, subject_id):
session['_saml2_subject_id'] = code(subject_id)
def _get_subject_id(session):
try:
return decode(session['_saml2_subject_id'])
except KeyError:
return None
def callable_bool(value):
""" A compatibility wrapper for pre Django 1.10 User model API that used
is_authenticated() and is_anonymous() methods instead of attributes
"""
if callable(value):
return value()
else:
return value
def login(request,
config_loader_path=None,
wayf_template='djangosaml2/wayf.html',
authorization_error_template='djangosaml2/auth_error.html',
post_binding_form_template='djangosaml2/post_binding_form.html'):
"""SAML Authorization Request initiator
This view initiates the SAML2 Authorization handshake
using the pysaml2 library to create the AuthnRequest.
It uses the SAML 2.0 Http Redirect protocol binding.
* post_binding_form_template - path to a template containing HTML form with
hidden input elements, used to send the SAML message data when HTTP POST
binding is being used. You can customize this template to include custom
branding and/or text explaining the automatic redirection process. Please
see the example template in
templates/djangosaml2/example_post_binding_form.html
If set to None or nonexistent template, default form from the saml2 library
will be rendered.
"""
logger.debug('Login process started')
came_from = request.GET.get('next', settings.LOGIN_REDIRECT_URL)
if not came_from:
logger.warning('The next parameter exists but is empty')
came_from = settings.LOGIN_REDIRECT_URL
# Ensure the user-originating redirection url is safe.
if not is_safe_url_compat(url=came_from, allowed_hosts={request.get_host()}):
came_from = settings.LOGIN_REDIRECT_URL
# if the user is already authenticated that maybe because of two reasons:
# A) He has this URL in two browser windows and in the other one he
# has already initiated the authenticated session.
# B) He comes from a view that (incorrectly) send him here because
# he does not have enough permissions. That view should have shown
# an authorization error in the first place.
# We can only make one thing here and that is configurable with the
# SAML_IGNORE_AUTHENTICATED_USERS_ON_LOGIN setting. If that setting
# is True (default value) we will redirect him to the came_from view.
# Otherwise, we will show an (configurable) authorization error.
if callable_bool(request.user.is_authenticated):
redirect_authenticated_user = getattr(settings, 'SAML_IGNORE_AUTHENTICATED_USERS_ON_LOGIN', True)
if redirect_authenticated_user:
return HttpResponseRedirect(came_from)
else:
logger.debug('User is already logged in')
return render(request, authorization_error_template, {
'came_from': came_from,
})
selected_idp = request.GET.get('idp', None)
conf = get_config(config_loader_path, request)
# is a embedded wayf needed?
idps = available_idps(conf)
if selected_idp is None and len(idps) > 1:
logger.debug('A discovery process is needed')
return render(request, wayf_template, {
'available_idps': idps.items(),
'came_from': came_from,
})
# choose a binding to try first
sign_requests = getattr(conf, '_sp_authn_requests_signed', False)
binding = BINDING_HTTP_POST if sign_requests else BINDING_HTTP_REDIRECT
logger.debug('Trying binding %s for IDP %s', binding, selected_idp)
# ensure our selected binding is supported by the IDP
supported_bindings = get_idp_sso_supported_bindings(selected_idp, config=conf)
if binding not in supported_bindings:
logger.debug('Binding %s not in IDP %s supported bindings: %s',
binding, selected_idp, supported_bindings)
if binding == BINDING_HTTP_POST:
logger.warning('IDP %s does not support %s, trying %s',
selected_idp, binding, BINDING_HTTP_REDIRECT)
binding = BINDING_HTTP_REDIRECT
else:
logger.warning('IDP %s does not support %s, trying %s',
selected_idp, binding, BINDING_HTTP_POST)
binding = BINDING_HTTP_POST
# if switched binding still not supported, give up
if binding not in supported_bindings:
raise UnsupportedBinding('IDP %s does not support %s or %s',
selected_idp, BINDING_HTTP_POST, BINDING_HTTP_REDIRECT)
client = Saml2Client(conf)
http_response = None
# do not sign the xml itself, instead use the sigalg to
# generate the signature as a URL param
sig_alg_option_map = {'sha1': SIG_RSA_SHA1,
'sha256': SIG_RSA_SHA256}
sig_alg_option = getattr(conf, '_sp_authn_requests_signed_alg', 'sha1')
sigalg = sig_alg_option_map[sig_alg_option] if sign_requests else None
dig_alg_option_map = {'sha1': DIGEST_SHA1,
'sha256': DIGEST_SHA256}
dig_alg_option = getattr(conf, '_sp_authn_requests_digest_alg', 'sha1')
digalg = dig_alg_option_map[dig_alg_option]
logger.debug('Redirecting user to the IdP via %s binding.', binding)
if binding == BINDING_HTTP_REDIRECT:
try:
nsprefix = get_namespace_prefixes()
session_id, result = client.prepare_for_authenticate(
entityid=selected_idp, relay_state=came_from,
binding=binding, sign=False, sign_alg=sigalg, digest_alg=digalg,
nsprefix=nsprefix)
except TypeError as e:
logger.error('Unable to know which IdP to use')
return HttpResponse(text_type(e))
else:
http_response = HttpResponseRedirect(get_location(result))
elif binding == BINDING_HTTP_POST:
if post_binding_form_template:
# get request XML to build our own html based on the template
try:
location = client.sso_location(selected_idp, binding)
except TypeError as e:
logger.error('Unable to know which IdP to use')
return HttpResponse(text_type(e))
session_id, request_xml = client.create_authn_request(
location,
binding=binding,
sign_alg=sigalg,
digest_alg=digalg)
try:
if PY3:
saml_request = base64.b64encode(binary_type(request_xml, 'UTF-8'))
else:
saml_request = base64.b64encode(binary_type(request_xml))
http_response = render(request, post_binding_form_template, {
'target_url': location,
'params': {
'SAMLRequest': saml_request,
'RelayState': came_from,
},
})
except TemplateDoesNotExist:
pass
if not http_response:
# use the html provided by pysaml2 if no template was specified or it didn't exist
try:
session_id, result = client.prepare_for_authenticate(
entityid=selected_idp, relay_state=came_from,
binding=binding, sign_alg=sigalg, digest_alg=digalg)
except TypeError as e:
logger.error('Unable to know which IdP to use')
return HttpResponse(text_type(e))
else:
http_response = HttpResponse(result['data'])
else:
raise UnsupportedBinding('Unsupported binding: %s', binding)
# success, so save the session ID and return our response
logger.debug('Saving the session_id in the OutstandingQueries cache')
oq_cache = OutstandingQueriesCache(request.session)
oq_cache.set(session_id, came_from)
return http_response
@require_POST
@csrf_exempt
def assertion_consumer_service(request,
config_loader_path=None,
attribute_mapping=None,
create_unknown_user=None):
"""SAML Authorization Response endpoint
The IdP will send its response to this view, which
will process it with pysaml2 help and log the user
in using the custom Authorization backend
djangosaml2.backends.Saml2Backend that should be
enabled in the settings.py
"""
attribute_mapping = attribute_mapping or get_custom_setting('SAML_ATTRIBUTE_MAPPING', {'uid': ('username', )})
create_unknown_user = create_unknown_user if create_unknown_user is not None else \
get_custom_setting('SAML_CREATE_UNKNOWN_USER', True)
conf = get_config(config_loader_path, request)
try:
xmlstr = request.POST['SAMLResponse']
except KeyError:
logger.warning('Missing "SAMLResponse" parameter in POST data.')
raise SuspiciousOperation
client = Saml2Client(conf, identity_cache=IdentityCache(request.session))
oq_cache = OutstandingQueriesCache(request.session)
outstanding_queries = oq_cache.outstanding_queries()
try:
response = client.parse_authn_request_response(xmlstr, BINDING_HTTP_POST, outstanding_queries)
except (StatusError, ToEarly):
logger.exception("Error processing SAML Assertion.")
return fail_acs_response(request)
except ResponseLifetimeExceed:
logger.info("SAML Assertion is no longer valid. Possibly caused by network delay or replay attack.", exc_info=True)
return fail_acs_response(request)
except SignatureError:
logger.info("Invalid or malformed SAML Assertion.", exc_info=True)
return fail_acs_response(request)
except StatusAuthnFailed:
logger.info("Authentication denied for user by IdP.", exc_info=True)
return fail_acs_response(request)
except StatusRequestDenied:
logger.warning("Authentication interrupted at IdP.", exc_info=True)
return fail_acs_response(request)
except MissingKey:
logger.exception("SAML Identity Provider is not configured correctly: certificate key is missing!")
return fail_acs_response(request)
except UnsolicitedResponse:
logger.exception("Received SAMLResponse when no request has been made.")
|
logger.warning("Invalid SAML Assertion received (unknown error).")
return fail_acs_response(request, status=400, exc_class=SuspiciousOperation)
session_id = response.session_id()
oq_cache.delete(session_id)
# authenticate the remote user
session_info = response.session_info()
if callable(attribute_mapping):
attribute_mapping = attribute_mapping()
if callable(create_unknown_user):
create_unknown_user = create_unknown_user()
logger.debug('Trying to authenticate the user. Session info: %s', session_info)
user = auth.authenticate(request=request,
session_info=session_info,
attribute_mapping=attribute_mapping,
create_unknown_user=create_unknown_user)
if user is None:
logger.warning("Could not authenticate user received in SAML Assertion. Session info: %s", session_info)
raise PermissionDenied
auth.login(request, user)
_set_subject_id(request.session, session_info['name_id'])
logger.debug("User %s authenticated via SSO.", user)
logger.debug('Sending the post_authenticated signal')
post_authenticated.send_robust(sender=user, session_info=session_info)
# redirect the user to the view where he came from
default_relay_state = get_custom_setting('ACS_DEFAULT_REDIRECT_URL',
settings.LOGIN_REDIRECT_URL)
relay_state = request.POST.get('RelayState', default_relay_state)
if not relay_state:
logger.warning('The RelayState parameter exists but is empty')
relay_state = default_relay_state
if not is_safe_url_compat(url=relay_state, allowed_hosts={request.get_host()}):
relay_state = settings.LOGIN_REDIRECT_URL
logger.debug('Redirecting to the RelayState: %s', relay_state)
return HttpResponseRedirect(relay_state)
@login_required
def echo_attributes(request,
config_loader_path=None,
template='djangosaml2/echo_attributes.html'):
"""Example view that echo the SAML attributes of an user"""
state = StateCache(request.session)
conf = get_config(config_loader_path, request)
client = Saml2Client(conf, state_cache=state,
identity_cache=IdentityCache(request.session))
subject_id = _get_subject_id(request.session)
try:
identity = client.users.get_identity(subject_id,
check_not_on_or_after=False)
except AttributeError:
return HttpResponse("No active SAML identity found. Are you sure you have logged in via SAML?")
return render(request, template, {'attributes': identity[0]})
@login_required
def logout(request, config_loader_path=None):
"""SAML Logout Request initiator
This view initiates the SAML2 Logout request
using the pysaml2 library to create the LogoutRequest.
"""
state = StateCache(request.session)
conf = get_config(config_loader_path, request)
client = Saml2Client(conf, state_cache=state,
identity_cache=IdentityCache(request.session))
subject_id = _get_subject_id(request.session)
if subject_id is None:
logger.warning(
'The session does not contain the subject id for user %s',
request.user)
result = client.global_logout(subject_id)
state.sync()
if not result:
logger.error("Looks like the user %s is not logged in any IdP/AA", subject_id)
return HttpResponseBadRequest("You are not logged in any IdP/AA")
if len(result) > 1:
logger.error('Sorry, I do not know how to logout from several sources. I will logout just from the first one')
for entityid, logout_info in result.items():
if isinstance(logout_info, tuple):
binding, http_info = logout_info
if binding == BINDING_HTTP_POST:
logger.debug('Returning form to the IdP to continue the logout process')
body = ''.join(http_info['data'])
return HttpResponse(body)
elif binding == BINDING_HTTP_REDIRECT:
logger.debug('Redirecting to the IdP to continue the logout process')
return HttpResponseRedirect(get_location(http_info))
else:
logger.error('Unknown binding: %s', binding)
return HttpResponseServerError('Failed to log out')
else:
# We must have had a soap logout
return finish_logout(request, logout_info)
logger.error('Could not logout because there only the HTTP_REDIRECT is supported')
return HttpResponseServerError('Logout Binding not supported')
def logout_service(request, *args, **kwargs):
return do_logout_service(request, request.GET, BINDING_HTTP_REDIRECT, *args, **kwargs)
@csrf_exempt
def logout_service_post(request, *args, **kwargs):
return do_logout_service(request, request.POST, BINDING_HTTP_POST, *args, **kwargs)
def do_logout_service(request, data, binding, config_loader_path=None, next_page=None,
logout_error_template='djangosaml2/logout_error.html'):
"""SAML Logout Response endpoint
The IdP will send the logout response to this view,
which will process it with pysaml2 help and log the user
out.
Note that the IdP can request a logout even when
we didn't initiate the process as a single logout
request started by another SP.
"""
logger.debug('Logout service started')
conf = get_config(config_loader_path, request)
state = StateCache(request.session)
client = Saml2Client(conf, state_cache=state,
identity_cache=IdentityCache(request.session))
if 'SAMLResponse' in data: # we started the logout
logger.debug('Receiving a logout response from the IdP')
response = client.parse_logout_request_response(data['SAMLResponse'], binding)
state.sync()
return finish_logout(request, response, next_page=next_page)
elif 'SAMLRequest' in data: # logout started by the IdP
logger.debug('Receiving a logout request from the IdP')
subject_id = _get_subject_id(request.session)
if subject_id is None:
logger.warning(
'The session does not contain the subject id for user %s. Performing local logout',
request.user)
auth.logout(request)
return render(request, logout_error_template, status=403)
else:
http_info = client.handle_logout_request(
data['SAMLRequest'],
subject_id,
binding,
relay_state=data.get('RelayState', ''))
state.sync()
auth.logout(request)
return HttpResponseRedirect(get_location(http_info))
else:
logger.error('No SAMLResponse or SAMLRequest parameter found')
raise Http404('No SAMLResponse or SAMLRequest parameter found')
def finish_logout(request, response, next_page=None):
if response and response.status_ok():
if next_page is None and hasattr(settings, 'LOGOUT_REDIRECT_URL'):
next_page = settings.LOGOUT_REDIRECT_URL
logger.debug('Performing django logout with a next_page of %s',
next_page)
return django_logout(request, next_page=next_page)
else:
logger.error('Unknown error during the logout')
return render(request, "djangosaml2/logout_error.html", {})
def metadata(request, config_loader_path=None, valid_for=None):
"""Returns an XML with the SAML 2.0 metadata for this
SP as configured in the settings.py file.
"""
conf = get_config(config_loader_path, request)
metadata = entity_descriptor(conf)
return HttpResponse(content=text_type(metadata).encode('utf-8'),
content_type="text/xml; charset=utf8")
def get_namespace_prefixes():
from saml2 import md, saml, samlp
try:
from saml2 import xmlenc
from saml2 import xmldsig
except ImportError:
import xmlenc
import xmldsig
return {'saml': saml.NAMESPACE,
'samlp': samlp.NAMESPACE,
'md': md.NAMESPACE,
'ds': xmldsig.NAMESPACE,
'xenc': xmlenc.NAMESPACE}
|
return fail_acs_response(request)
if response is None:
|
pathselection.py
|
# -*- coding: utf-8 -*-
import logging
from math import floor
from PyQt5.QtCore import (
QPointF,
QRectF,
Qt
)
from PyQt5.QtGui import (
QPainterPath,
QKeyEvent,
QMouseEvent
)
from PyQt5.QtWidgets import (
QGraphicsItem,
QGraphicsItemGroup,
QGraphicsPathItem,
QGraphicsSceneMouseEvent,
)
from cadnano.gui.palette import getPenObj
from cadnano.views.pathview import pathstyles as styles
from cadnano.views.pathview import (
PathRootItemT,
)
from cadnano.cntypes import (
Vec2T,
DocT
)
logging.basicConfig(format='%(asctime)s %(message)s', level=logging.DEBUG)
logger = logging.getLogger(__name__)
class SelectionItemGroup(QGraphicsItemGroup):
"""SelectionItemGroup
Attributes:
getR (TYPE): Description
selectionbox (TYPE): SelectionBox
translateR (TYPE): Description
viewroot: Description
"""
def __init__(self, boxtype: QGraphicsItem,
constraint: str,
viewroot: PathRootItemT):
"""
Args:
boxtype: :class:`EndpointHandleSelectionBox` or
:class:`VirtualHelixHandleSelectionBox` instance
constraint: ``x`` or ``y``. Default to ``y`` (up and down)
viewroot: view root item and object parent
"""
super(SelectionItemGroup, self).__init__(viewroot)
self.viewroot: PathRootItemT = viewroot
self.setFiltersChildEvents(True)
# LOOK at Qt Source for deprecated code to replace this behavior
# self.setHandlesChildEvents(True) # commented out NC
self.setFlag(QGraphicsItem.ItemIsSelectable)
self.setFlag(QGraphicsItem.ItemIsFocusable) # for keyPressEvents
self.setFlag(QGraphicsItem.ItemHasNoContents)
self._rect = QRectF()
self._PEN = getPenObj(styles.BLUE_STROKE,
styles.PATH_SELECTBOX_STROKE_WIDTH)
self.selectionbox = boxtype(self)
self._drag_enable = False
self._dragged = False
self._r0 = 0 # save original mousedown
self._r = 0 # latest position for moving
# self._lastKid = 0
# this keeps track of mousePressEvents within the class
# to aid in intellignetly removing items from the group
self._added_to_press_list = False
self._pending_to_add_dict = {}
if constraint == 'y':
self.getR = self.selectionbox.getY
self.translateR = self.selectionbox.translateY
else:
self.getR = self.selectionbox.getX
self.translateR = self.selectionbox.translateX
self._normal_select = True
self.setZValue(styles.ZPATHSELECTION)
# end def
# def paint(self, painter, option, widget):
# painter.drawRect(self.boundingRect())
# # end def
def pendToAdd(self, item):
"""
Args:
item (TYPE): Description
"""
self._pending_to_add_dict[item] = True
# end def
def isPending(self, item):
"""
Args:
item (TYPE): Description
Returns:
TYPE: Description
"""
return item in self._pending_to_add_dict
# end def
def document(self) -> DocT:
"""
Returns:
:class:`Document`
"""
return self.viewroot.document()
# end def
def pendToRemove(self, item):
"""
Args:
item (TYPE): Description
"""
if item in self._pending_to_add_dict:
del self._pending_to_add_dict[item]
# end def
def setNormalSelect(self, bool_val: bool):
"""
Args:
bool_val: Description
"""
self._normal_select = bool_val
# end def
def isNormalSelect(self) -> bool:
"""
Returns:
is it normal select?
"""
return self._normal_select
# end def
def processPendingToAddList(self):
"""
Adds to the local selection and the document if required
"""
doc = self.document()
p2add = self._pending_to_add_dict
# logger.debug("processPendingToAddList")
if len(p2add) > 0:
plist = list(self._pending_to_add_dict.keys())
for item in plist:
if p2add[item]:
p2add[item] = False
# logger.debug("just checking1", item, item.group(), item.parentItem())
self.addToGroup(item)
item.modelSelect(doc)
# end for
# logger.debug('finished')
self._pending_to_add_dict = {}
doc.updateStrandSelection()
# end def
def selectionLock(self):
"""
Returns:
TYPE: Description
"""
return self.viewroot.selectionLock()
# end def
def setSelectionLock(self, selection_group):
"""
Args:
selection_group (TYPE): Description
"""
self.viewroot.setSelectionLock(selection_group)
# end def
def keyPressEvent(self, event: QKeyEvent):
"""
Must intercept invalid input events. Make changes here
Args:
event (TYPE): Description
"""
key = event.key()
if key in [Qt.Key_Backspace, Qt.Key_Delete]:
self.selectionbox.deleteSelection()
self.clearSelection(False)
return QGraphicsItemGroup.keyPressEvent(self, event)
else:
return QGraphicsItemGroup.keyPressEvent(self, event)
# end def
def mousePressEvent(self, event: QGraphicsSceneMouseEvent):
"""Handler for user mouse press.
Args:
event: Contains item, scene, and screen
coordinates of the the event, and previous event.
"""
# self.show()
if event.button() != Qt.LeftButton:
return QGraphicsItemGroup.mousePressEvent(self, event)
else:
self._drag_enable = True
# required to get the itemChanged event to work
# correctly for this
|
self.selectionbox.resetPosition()
self.selectionbox.refreshPath()
# self.selectionbox.resetTransform()
self.selectionbox.resetPosition()
self.selectionbox.show()
# for some reason we need to skip the first mouseMoveEvent
self._dragged = False
if self._added_to_press_list is False:
self._added_to_press_list = True
self.scene().views()[0].addToPressList(self)
return QGraphicsItemGroup.mousePressEvent(self, event)
# end def
def mouseMoveEvent(self, event: QGraphicsSceneMouseEvent):
"""
Args:
event: Description
"""
if self._drag_enable is True:
# map the item to the scene coordinates
# to help keep coordinates uniform
rf = self.getR(self.mapFromScene(QPointF(event.scenePos())))
# for some reason we need to skip the first mouseMoveEvent
if self._dragged is False:
self._dragged = True
self._r0 = rf
# end if
else:
delta = self.selectionbox.delta(rf, self._r0)
self.translateR(delta)
# logger.debug('mouse move path selectionbox', delta, rf, self._r0)
# end else
self._r = rf
# end if
else:
QGraphicsItemGroup.mouseMoveEvent(self, event)
# end else
# end def
def customMouseRelease(self, event: QMouseEvent):
"""
Args:
event: Description
"""
self.selectionbox.setParentItem(self.viewroot)
self.selectionbox.hide()
self.selectionbox.resetTransform()
self._drag_enable = False
# now do stuff
if not (self._r0 == 0 and self._r == 0):
modifiers = event.modifiers()
self.selectionbox.processSelectedItems(self._r0, self._r, modifiers)
# end if
self._r0 = 0 # reset
self._r = 0 # reset
self.setFocus() # needed to get keyPresses post a move
self._added_to_press_list = False
# end def
def resetSelection(self):
"""Summary
Returns:
TYPE: Description
"""
self._pending_to_add_dict = {}
self._added_to_press_list = False
self.clearSelection(False)
self.setSelectionLock(None)
self.selectionbox.setParentItem(self.viewroot)
self.setParentItem(self.viewroot)
# end def
def clearSelection(self, value):
"""value is for keyPressEvents
Arguments:
value (QVariant): resolves in Python as an integer
"""
if value == False: # noqa
self.selectionbox.hide()
self.selectionbox.resetPosition()
self.removeSelectedItems()
self.viewroot.setSelectionLock(None)
self.clearFocus() # this is to disable delete keyPressEvents
self.prepareGeometryChange()
self._rect.setWidth(0)
# self._rect = QRectF()
# end if
else:
self.setFocus() # this is to get delete keyPressEvents
self.update(self.boundingRect())
# end def
def itemChange(self, change, value):
"""docstring for itemChange
Arguments:
change (GraphicsItemChange): see http://doc.qt.io/qt-5/qgraphicsitem.html#GraphicsItemChange-enum
value (QVariant): resolves in Python as an integer
"""
# logger.debug("ps itemChange")
if change == QGraphicsItem.ItemSelectedChange:
# logger.debug("isc", value)
if value == False: # noqa
self.clearSelection(False)
return False
else:
return True
elif change == QGraphicsItem.ItemChildAddedChange:
# logger.debug("icac")
if self._added_to_press_list is False:
# logger.debug("kid added")
self.setFocus() # this is to get delete keyPressEvents
self.selectionbox.boxParent()
# self.setParentItem(self.selectionbox.boxParent())
self._added_to_press_list = True
self.scene().views()[0].addToPressList(self)
return
return QGraphicsItemGroup.itemChange(self, change, value)
# end def
def removeChild(self, child):
"""
remove only the child and ask it to
restore it's original parent
Args:
child (TYPE): Description
"""
doc = self.document()
self.removeFromGroup(child)
child.modelDeselect(doc)
# end def
def removeSelectedItems(self):
"""docstring for removeSelectedItems
"""
doc = self.document()
for item in self.childItems():
self.removeFromGroup(item)
item.modelDeselect(doc)
# end for
doc.updateStrandSelection()
# end def
def setBoundingRect(self, rect):
"""Summary
Args:
rect (TYPE): Description
Returns:
TYPE: Description
"""
self.prepareGeometryChange()
self._rect = rect
# end def
def boundingRect(self):
"""Summary
Returns:
TYPE: Description
"""
return self._rect
# end class
class VirtualHelixHandleSelectionBox(QGraphicsPathItem):
"""
docstring for VirtualHelixHandleSelectionBox
"""
_HELIX_HEIGHT = styles.PATH_HELIX_HEIGHT + styles.PATH_HELIX_PADDING
_RADIUS = styles.VIRTUALHELIXHANDLEITEM_RADIUS
_PEN_WIDTH = styles.SELECTIONBOX_PEN_WIDTH
_BOX_PEN = getPenObj(styles.BLUE_STROKE, _PEN_WIDTH)
def __init__(self, item_group: SelectionItemGroup):
"""
The item_group.parentItem() is expected to be a partItem
Args:
item_group (TYPE): Description
"""
super(VirtualHelixHandleSelectionBox, self).__init__(item_group.parentItem())
self._item_group = item_group
self._rect = item_group.boundingRect()
self.hide()
self.setPen(self._BOX_PEN)
self.setZValue(styles.ZPATHSELECTION)
self._bounds = None
self._pos0 = QPointF()
# end def
def getY(self, pos):
"""Summary
Args:
pos (TYPE): Description
Returns:
TYPE: Description
"""
pos = self._item_group.mapToScene(QPointF(pos))
return pos.y()
# end def
def translateY(self, delta):
"""Summary
Args:
delta (TYPE): Description
Returns:
TYPE: Description
"""
self.setY(delta)
# end def
def refreshPath(self):
"""Summary
Returns:
TYPE: Description
"""
self.prepareGeometryChange()
self.setPath(self.painterPath())
self._pos0 = self.pos()
# end def
def painterPath(self):
"""Summary
Returns:
TYPE: Description
"""
i_g = self._item_group
# the childrenBoundingRect is necessary to get this to work
rect = self.mapRectFromItem(i_g, i_g.childrenBoundingRect())
radius = self._RADIUS
path = QPainterPath()
path.addRoundedRect(rect, radius, radius)
path.moveTo(rect.right(), rect.center().y())
path.lineTo(rect.right() + radius / 2, rect.center().y())
return path
# end def
def processSelectedItems(self, r_start, r_end, modifiers):
"""docstring for processSelectedItems
Args:
r_start (TYPE): Description
r_end (TYPE): Description
modifiers (TYPE): Description
"""
margin = styles.VIRTUALHELIXHANDLEITEM_RADIUS
delta = (r_end - r_start) # r delta
mid_height = (self.boundingRect().height()) / 2 - margin
helix_height = self._HELIX_HEIGHT
if abs(delta) < mid_height: # move is too short for reordering
return
if delta > 0: # moved down, delta is positive
indexDelta = int((delta - mid_height) / helix_height)
else: # moved up, delta is negative
indexDelta = int((delta + mid_height) / helix_height)
# sort on y to determine the extremes of the selection group
items = sorted(self._item_group.childItems(), key=lambda vhhi: vhhi.y())
part_item = items[0].partItem()
part_item.reorderHelices([item.idNum() for item in items],
indexDelta)
# part_item.reorderHelices(items[0].idNum(),
# items[-1].idNum(),
# indexDelta)
part_item.updateStatusBar("")
# end def
def boxParent(self):
"""Summary
Returns:
TYPE: Description
"""
temp = self._item_group.childItems()[0].partItem()
self.setParentItem(temp)
return temp
# end def
def deleteSelection(self):
"""
Delete selection operates outside of the documents a virtual helices
are not actually selected in the model
"""
vh_handle_items = self._item_group.childItems()
u_s = self._item_group.document().undoStack()
u_s.beginMacro("delete Virtual Helices")
for vhhi in vh_handle_items:
part = vhhi.part()
part.removeVirtualHelix(vhhi.idNum())
u_s.endMacro()
# end def
def bounds(self):
"""Summary
Returns:
TYPE: Description
"""
return self._bounds
# end def
def delta(self, yf, y0):
"""Summary
Args:
yf (TYPE): Description
y0 (TYPE): Description
Returns:
TYPE: Description
"""
return yf - y0
# end def
def resetPosition(self):
"""Summary
Returns:
TYPE: Description
"""
self.setPos(self._pos0)
# end def
# end class
class EndpointHandleSelectionBox(QGraphicsPathItem):
"""Summary
"""
_PEN_WIDTH = styles.SELECTIONBOX_PEN_WIDTH
_BOX_PEN = getPenObj(styles.SELECTED_COLOR, _PEN_WIDTH)
_BASE_WIDTH = styles.PATH_BASE_WIDTH
def __init__(self, item_group: SelectionItemGroup):
"""The item_group.parentItem() is expected to be a partItem
Args:
item_group: Description
"""
super(EndpointHandleSelectionBox, self).__init__(item_group.parentItem())
self._item_group = item_group
self._rect = item_group.boundingRect()
self.hide()
self.setPen(self._BOX_PEN)
self.setZValue(styles.ZPATHSELECTION)
self._bounds = (0, 0)
self._pos0 = QPointF()
# end def
def getX(self, pos: QPointF) -> float:
"""
Args:
pos: Description
Returns:
``x`` position
"""
return pos.x()
# end def
def translateX(self, delta: float):
"""
Args:
delta: Description
"""
children = self._item_group.childItems()
if children:
p_i = children[0].partItem()
str = "+%d" % delta if delta >= 0 else "%d" % delta
p_i.updateStatusBar(str)
self.setX(self._BASE_WIDTH * delta)
# end def
def resetPosition(self):
"""
"""
self.setPos(self._pos0)
def delta(self, xf: float, x0: float) -> float:
"""
Args:
xf: Description
x0: Description
Returns:
change distance
"""
bound_l, bound_h = self._bounds
delta = int(floor((xf - x0) / self._BASE_WIDTH))
if delta > 0 and delta > bound_h:
delta = bound_h
elif delta < 0 and abs(delta) > bound_l:
delta = -bound_l
return delta
def refreshPath(self):
"""
"""
temp_low, temp_high = self._item_group.viewroot.document().getSelectionBounds()
self._bounds = (temp_low, temp_high)
# logger.debug("rp:", self._bounds)
self.prepareGeometryChange()
self.setPath(self.painterPath())
self._pos0 = self.pos()
# end def
def painterPath(self) -> QPainterPath:
"""
Returns:
:class:`QPainterPath`
"""
bw = self._BASE_WIDTH
i_g = self._item_group
# the childrenBoundingRect is necessary to get this to work
rect_IG = i_g.childrenBoundingRect()
rect = self.mapRectFromItem(i_g, rect_IG)
if rect.width() < bw:
rect.adjust(-bw / 4, 0, bw / 2, 0)
path = QPainterPath()
path.addRect(rect)
self._item_group.setBoundingRect(rect_IG)
# path.addRoundedRect(rect, radius, radius)
# path.moveTo(rect.right(),\
# rect.center().y())
# path.lineTo(rect.right() + radius / 2,\
# rect.center().y())
return path
# end def
def processSelectedItems(self, r_start: float, r_end: float, modifiers):
"""
Args:
r_start: Description
r_end: Description
modifiers (TYPE): Description
"""
delta = self.delta(r_end, r_start)
# TODO reenable do_maximize?????
# if modifiers & Qt.AltModifier:
# do_maximize = True
# else:
# do_maximize = False
self._item_group.viewroot.document().resizeSelection(delta)
# end def
def deleteSelection(self):
"""Summary
Returns:
TYPE: Description
"""
self._item_group.document().deleteStrandSelection()
def boxParent(self) -> QGraphicsItem:
"""Get the parent :class:`ProxyParentItem`
Returns:
:class:`ProxyParentItem`
"""
temp = self._item_group.childItems()[0].partItem().proxy()
self.setParentItem(temp)
return temp
# end def
def bounds(self) -> Vec2T:
"""
Returns:
the bounds
"""
return self._bounds
# end def
# end class
|
self.setSelected(True)
# self.selectionbox.resetTransform()
|
lib.rs
|
// =================================================================
//
// * WARNING *
//
// This file is generated!
//
// Changes made to this file will be overwritten. If changes are
// required to the generated code, the service_crategen project
// must be updated to generate the changes.
//
// =================================================================
#![doc(html_logo_url = "https://raw.githubusercontent.com/rusoto/rusoto/master/assets/logo-square.png")]
//! <p>With Application Auto Scaling, you can configure automatic scaling for the following resources:</p> <ul> <li> <p>Amazon ECS services</p> </li> <li> <p>Amazon EC2 Spot Fleet requests</p> </li> <li> <p>Amazon EMR clusters</p> </li> <li> <p>Amazon AppStream 2.0 fleets </p> </li> <li> <p>Amazon DynamoDB tables and global secondary indexes throughput capacity</p> </li> <li> <p>Amazon Aurora Replicas</p> </li> <li> <p>Amazon SageMaker endpoint variants</p> </li> <li> <p>Custom resources provided by your own applications or services</p> </li> </ul> <p> <b>API Summary</b> </p> <p>The Application Auto Scaling service API includes three key sets of actions: </p> <ul> <li> <p>Register and manage scalable targets - Register AWS or custom resources as scalable targets (a resource that Application Auto Scaling can scale), set minimum and maximum capacity limits, and retrieve information on existing scalable targets.</p> </li> <li> <p>Configure and manage automatic scaling - Define scaling policies to dynamically scale your resources in response to CloudWatch alarms, schedule one-time or recurring scaling actions, and retrieve your recent scaling activity history.</p> </li> <li> <p>Suspend and resume scaling - Temporarily suspend and later resume automatic scaling by calling the <a>RegisterScalableTarget</a> action for any Application Auto Scaling scalable target. You can suspend and resume, individually or in combination, scale-out activities triggered by a scaling policy, scale-in activities triggered by a scaling policy, and scheduled scaling. </p> </li> </ul> <p>To learn more about Application Auto Scaling, including information about granting IAM users required permissions for Application Auto Scaling actions, see the <a href="https://docs.aws.amazon.com/autoscaling/application/userguide/what-is-application-auto-scaling.html">Application Auto Scaling User Guide</a>.</p>
//!
//! If you're using the service, you're probably looking for [ApplicationAutoScalingClient](struct.ApplicationAutoScalingClient.html) and [ApplicationAutoScaling](trait.ApplicationAutoScaling.html).
extern crate bytes;
extern crate futures;
extern crate rusoto_core;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
mod generated;
mod custom;
|
pub use crate::generated::*;
pub use crate::custom::*;
|
|
task-06.js
|
function
|
(object, propertyPath) {
let objectValue = object;
let path = propertyPath;
path = path.split('.');
const nestingLevel = path.length;
for (let index = 0; index < nestingLevel; index += 1) {
if (objectValue !== undefined) {
objectValue = objectValue[path[index]];
}
}
if (objectValue !== undefined) {
return objectValue;
}
return undefined;
}
module.exports = getProperty;
|
getProperty
|
cpuid.go
|
// Copyright (c) 2015 Klaus Post, released under MIT License. See LICENSE file.
// Package cpuid provides information about the CPU running the current program.
//
// CPU features are detected on startup, and kept for fast access through the life of the application.
// Currently x86 / x64 (AMD64) as well as arm64 is supported.
//
// You can access the CPU information by accessing the shared CPU variable of the cpuid library.
//
// Package home: https://github.com/klauspost/cpuid
package cpuid
import (
"math"
"strings"
)
// AMD refererence: https://www.amd.com/system/files/TechDocs/25481.pdf
// and Processor Programming Reference (PPR)
// Vendor is a representation of a CPU vendor.
type Vendor int
const (
Other Vendor = iota
Intel
AMD
VIA
Transmeta
NSC
KVM // Kernel-based Virtual Machine
MSVM // Microsoft Hyper-V or Windows Virtual PC
VMware
XenHVM
Bhyve
Hygon
SiS
RDC
)
const (
CMOV = iota // i686 CMOV
NX // NX (No-Execute) bit
AMD3DNOW // AMD 3DNOW
AMD3DNOWEXT // AMD 3DNowExt
MMX // standard MMX
MMXEXT // SSE integer functions or AMD MMX ext
SSE // SSE functions
SSE2 // P4 SSE functions
SSE3 // Prescott SSE3 functions
SSSE3 // Conroe SSSE3 functions
SSE4 // Penryn SSE4.1 functions
SSE4A // AMD Barcelona microarchitecture SSE4a instructions
SSE42 // Nehalem SSE4.2 functions
AVX // AVX functions
AVX2 // AVX2 functions
FMA3 // Intel FMA 3
FMA4 // Bulldozer FMA4 functions
XOP // Bulldozer XOP functions
F16C // Half-precision floating-point conversion
BMI1 // Bit Manipulation Instruction Set 1
BMI2 // Bit Manipulation Instruction Set 2
TBM // AMD Trailing Bit Manipulation
LZCNT // LZCNT instruction
POPCNT // POPCNT instruction
AESNI // Advanced Encryption Standard New Instructions
CLMUL // Carry-less Multiplication
HTT // Hyperthreading (enabled)
HLE // Hardware Lock Elision
RTM // Restricted Transactional Memory
RDRAND // RDRAND instruction is available
RDSEED // RDSEED instruction is available
ADX // Intel ADX (Multi-Precision Add-Carry Instruction Extensions)
SHA // Intel SHA Extensions
AVX512F // AVX-512 Foundation
AVX512DQ // AVX-512 Doubleword and Quadword Instructions
AVX512IFMA // AVX-512 Integer Fused Multiply-Add Instructions
AVX512PF // AVX-512 Prefetch Instructions
AVX512ER // AVX-512 Exponential and Reciprocal Instructions
AVX512CD // AVX-512 Conflict Detection Instructions
AVX512BW // AVX-512 Byte and Word Instructions
AVX512VL // AVX-512 Vector Length Extensions
AVX512VBMI // AVX-512 Vector Bit Manipulation Instructions
AVX512VBMI2 // AVX-512 Vector Bit Manipulation Instructions, Version 2
AVX512VNNI // AVX-512 Vector Neural Network Instructions
AVX512VPOPCNTDQ // AVX-512 Vector Population Count Doubleword and Quadword
GFNI // Galois Field New Instructions
VAES // Vector AES
AVX512BITALG // AVX-512 Bit Algorithms
VPCLMULQDQ // Carry-Less Multiplication Quadword
AVX512BF16 // AVX-512 BFLOAT16 Instructions
AVX512VP2INTERSECT // AVX-512 Intersect for D/Q
MPX // Intel MPX (Memory Protection Extensions)
ERMS // Enhanced REP MOVSB/STOSB
RDTSCP // RDTSCP Instruction
CX16 // CMPXCHG16B Instruction
SGX // Software Guard Extensions
SGXLC // Software Guard Extensions Launch Control
IBPB // Indirect Branch Restricted Speculation (IBRS) and Indirect Branch Predictor Barrier (IBPB)
STIBP // Single Thread Indirect Branch Predictors
VMX // Virtual Machine Extensions
// Performance indicators
SSE2SLOW // SSE2 is supported, but usually not faster
SSE3SLOW // SSE3 is supported, but usually not faster
ATOM // Atom processor, some SSSE3 instructions are slower
AMXBF16 // Tile computational operations on BFLOAT16 numbers
AMXTILE // Tile architecture
AMXINT8 // Tile computational operations on 8-bit integers
HYPERVISOR // This bit has been reserved by Intel & AMD for use by hypervisors
WAITPKG // TPAUSE, UMONITOR, UMWAIT
SERIALIZE // Serialize Instruction Execution
TSXLDTRK // Intel TSX Suspend Load Address Tracking
WBNOINVD // Write Back and Do Not Invalidate Cache
MOVDIRI // Move Doubleword as Direct Store
MOVDIR64B // Move 64 Bytes as Direct Store
ENQCMD // Enqueue Command
CLDEMOTE // Cache Line Demote
// Keep it last. It automatically defines the size of []FlagSet
LASTID
)
var flagNames = map[Flags]string{
CMOV: "CMOV", // i686 CMOV
NX: "NX", // NX (No-Execute) bit
AMD3DNOW: "AMD3DNOW", // AMD 3DNOW
AMD3DNOWEXT: "AMD3DNOWEXT", // AMD 3DNowExt
MMX: "MMX", // Standard MMX
MMXEXT: "MMXEXT", // SSE integer functions or AMD MMX ext
SSE: "SSE", // SSE functions
SSE2: "SSE2", // P4 SSE2 functions
SSE3: "SSE3", // Prescott SSE3 functions
SSSE3: "SSSE3", // Conroe SSSE3 functions
SSE4: "SSE4.1", // Penryn SSE4.1 functions
SSE4A: "SSE4A", // AMD Barcelona microarchitecture SSE4a instructions
SSE42: "SSE4.2", // Nehalem SSE4.2 functions
AVX: "AVX", // AVX functions
AVX2: "AVX2", // AVX functions
FMA3: "FMA3", // Intel FMA 3
FMA4: "FMA4", // Bulldozer FMA4 functions
XOP: "XOP", // Bulldozer XOP functions
F16C: "F16C", // Half-precision floating-point conversion
BMI1: "BMI1", // Bit Manipulation Instruction Set 1
BMI2: "BMI2", // Bit Manipulation Instruction Set 2
TBM: "TBM", // AMD Trailing Bit Manipulation
LZCNT: "LZCNT", // LZCNT instruction
POPCNT: "POPCNT", // POPCNT instruction
AESNI: "AESNI", // Advanced Encryption Standard New Instructions
CLMUL: "CLMUL", // Carry-less Multiplication
HTT: "HTT", // Hyperthreading (enabled)
HLE: "HLE", // Hardware Lock Elision
RTM: "RTM", // Restricted Transactional Memory
RDRAND: "RDRAND", // RDRAND instruction is available
RDSEED: "RDSEED", // RDSEED instruction is available
ADX: "ADX", // Intel ADX (Multi-Precision Add-Carry Instruction Extensions)
SHA: "SHA", // Intel SHA Extensions
AVX512F: "AVX512F", // AVX-512 Foundation
AVX512DQ: "AVX512DQ", // AVX-512 Doubleword and Quadword Instructions
AVX512IFMA: "AVX512IFMA", // AVX-512 Integer Fused Multiply-Add Instructions
AVX512PF: "AVX512PF", // AVX-512 Prefetch Instructions
AVX512ER: "AVX512ER", // AVX-512 Exponential and Reciprocal Instructions
AVX512CD: "AVX512CD", // AVX-512 Conflict Detection Instructions
AVX512BW: "AVX512BW", // AVX-512 Byte and Word Instructions
AVX512VL: "AVX512VL", // AVX-512 Vector Length Extensions
AVX512VBMI: "AVX512VBMI", // AVX-512 Vector Bit Manipulation Instructions
AVX512VBMI2: "AVX512VBMI2", // AVX-512 Vector Bit Manipulation Instructions, Version 2
AVX512VNNI: "AVX512VNNI", // AVX-512 Vector Neural Network Instructions
AVX512VPOPCNTDQ: "AVX512VPOPCNTDQ", // AVX-512 Vector Population Count Doubleword and Quadword
GFNI: "GFNI", // Galois Field New Instructions
VAES: "VAES", // Vector AES
AVX512BITALG: "AVX512BITALG", // AVX-512 Bit Algorithms
VPCLMULQDQ: "VPCLMULQDQ", // Carry-Less Multiplication Quadword
AVX512BF16: "AVX512BF16", // AVX-512 BFLOAT16 Instruction
AVX512VP2INTERSECT: "AVX512VP2INTERSECT", // AVX-512 Intersect for D/Q
MPX: "MPX", // Intel MPX (Memory Protection Extensions)
ERMS: "ERMS", // Enhanced REP MOVSB/STOSB
RDTSCP: "RDTSCP", // RDTSCP Instruction
CX16: "CX16", // CMPXCHG16B Instruction
SGX: "SGX", // Software Guard Extensions
SGXLC: "SGXLC", // Software Guard Extensions Launch Control
IBPB: "IBPB", // Indirect Branch Restricted Speculation and Indirect Branch Predictor Barrier
STIBP: "STIBP", // Single Thread Indirect Branch Predictors
VMX: "VMX", // Virtual Machine Extensions
// Performance indicators
SSE2SLOW: "SSE2SLOW", // SSE2 supported, but usually not faster
SSE3SLOW: "SSE3SLOW", // SSE3 supported, but usually not faster
ATOM: "ATOM", // Atom processor, some SSSE3 instructions are slower
AMXBF16: "AMXBF16", // Tile computational operations on BFLOAT16 numbers
AMXTILE: "AMXTILE", // Tile architecture
AMXINT8: "AMXINT8", // Tile computational operations on 8-bit integers
HYPERVISOR: "HYPERVISOR", // This bit has been reserved by Intel & AMD for use by hypervisors
WAITPKG: "WAITPKG", // TPAUSE, UMONITOR, UMWAIT
SERIALIZE: "SERIALIZE", // Serialize Instruction Execution
TSXLDTRK: "TSXLDTRK", // Intel TSX Suspend Load Address Tracking
WBNOINVD: "WBNOINVD", // Write Back and Do Not Invalidate Cache
MOVDIRI: "MOVDIRI", // Move Doubleword as Direct Store
MOVDIR64B: "MOVDIR64B", // Move 64 Bytes as Direct Store
ENQCMD: "ENQCMD", // Enqueue Command
CLDEMOTE: "CLDEMOTE", // Cache Line Demote
}
/* all special features for arm64 should be defined here */
const (
/* extension instructions */
FP ArmFlags = 1 << iota
ASIMD
EVTSTRM
AES
PMULL
SHA1
SHA2
CRC32
ATOMICS
FPHP
ASIMDHP
ARMCPUID
ASIMDRDM
JSCVT
FCMA
LRCPC
DCPOP
SHA3
SM3
SM4
ASIMDDP
SHA512
SVE
GPA
)
var flagNamesArm = map[ArmFlags]string{
FP: "FP", // Single-precision and double-precision floating point
ASIMD: "ASIMD", // Advanced SIMD
EVTSTRM: "EVTSTRM", // Generic timer
AES: "AES", // AES instructions
PMULL: "PMULL", // Polynomial Multiply instructions (PMULL/PMULL2)
SHA1: "SHA1", // SHA-1 instructions (SHA1C, etc)
SHA2: "SHA2", // SHA-2 instructions (SHA256H, etc)
CRC32: "CRC32", // CRC32/CRC32C instructions
ATOMICS: "ATOMICS", // Large System Extensions (LSE)
FPHP: "FPHP", // Half-precision floating point
ASIMDHP: "ASIMDHP", // Advanced SIMD half-precision floating point
ARMCPUID: "CPUID", // Some CPU ID registers readable at user-level
ASIMDRDM: "ASIMDRDM", // Rounding Double Multiply Accumulate/Subtract (SQRDMLAH/SQRDMLSH)
JSCVT: "JSCVT", // Javascript-style double->int convert (FJCVTZS)
FCMA: "FCMA", // Floatin point complex number addition and multiplication
LRCPC: "LRCPC", // Weaker release consistency (LDAPR, etc)
DCPOP: "DCPOP", // Data cache clean to Point of Persistence (DC CVAP)
SHA3: "SHA3", // SHA-3 instructions (EOR3, RAXI, XAR, BCAX)
SM3: "SM3", // SM3 instructions
SM4: "SM4", // SM4 instructions
ASIMDDP: "ASIMDDP", // SIMD Dot Product
SHA512: "SHA512", // SHA512 instructions
SVE: "SVE", // Scalable Vector Extension
GPA: "GPA", // Generic Pointer Authentication
}
// CPUInfo contains information about the detected system CPU.
type CPUInfo struct {
BrandName string // Brand name reported by the CPU
VendorID Vendor // Comparable CPU vendor ID
VendorString string // Raw vendor string.
Features Flags // Features of the CPU (x64) (deprecated)
featureSet FlagSet // Features of the CPU
Arm ArmFlags // Features of the CPU (arm)
PhysicalCores int // Number of physical processor cores in your CPU. Will be 0 if undetectable.
ThreadsPerCore int // Number of threads per physical core. Will be 1 if undetectable.
LogicalCores int // Number of physical cores times threads that can run on each core through the use of hyperthreading. Will be 0 if undetectable.
Family int // CPU family number
Model int // CPU model number
CacheLine int // Cache line size in bytes. Will be 0 if undetectable.
Hz int64 // Clock speed, if known
Cache struct {
L1I int // L1 Instruction Cache (per core or shared). Will be -1 if undetected
L1D int // L1 Data Cache (per core or shared). Will be -1 if undetected
L2 int // L2 Cache (per core or shared). Will be -1 if undetected
L3 int // L3 Cache (per core, per ccx or shared). Will be -1 if undetected
}
SGX SGXSupport
maxFunc uint32
maxExFunc uint32
}
var cpuid func(op uint32) (eax, ebx, ecx, edx uint32)
var cpuidex func(op, op2 uint32) (eax, ebx, ecx, edx uint32)
var xgetbv func(index uint32) (eax, edx uint32)
var rdtscpAsm func() (eax, ebx, ecx, edx uint32)
// CPU contains information about the CPU as detected on startup,
// or when Detect last was called.
//
// Use this as the primary entry point to you data.
var CPU CPUInfo
func init() {
initCPU()
Detect()
}
// Detect will re-detect current CPU info.
// This will replace the content of the exported CPU variable.
//
// Unless you expect the CPU to change while you are running your program
// you should not need to call this function.
// If you call this, you must ensure that no other goroutine is accessing the
// exported CPU variable.
func Detect() {
// Set defaults
CPU.ThreadsPerCore = 1
CPU.Cache.L1I = -1
CPU.Cache.L1D = -1
CPU.Cache.L2 = -1
CPU.Cache.L3 = -1
addInfo(&CPU)
}
// Generated here: http://play.golang.org/p/BxFH2Gdc0G
// Cmov indicates support of CMOV instructions
func (c CPUInfo) Cmov() bool {
return c.featureSet.inSet(CMOV)
}
// Amd3dnow indicates support of AMD 3DNOW! instructions
func (c CPUInfo) Amd3dnow() bool {
return c.featureSet.inSet(AMD3DNOW)
}
// Amd3dnowExt indicates support of AMD 3DNOW! Extended instructions
func (c CPUInfo) Amd3dnowExt() bool {
return c.featureSet.inSet(AMD3DNOWEXT)
}
// VMX indicates support of VMX
func (c CPUInfo) VMX() bool {
return c.featureSet.inSet(VMX)
}
// MMX indicates support of MMX instructions
func (c CPUInfo) MMX() bool {
return c.featureSet.inSet(MMX)
}
// MMXExt indicates support of MMXEXT instructions
// (SSE integer functions or AMD MMX ext)
func (c CPUInfo) MMXExt() bool {
return c.featureSet.inSet(MMXEXT)
}
// SSE indicates support of SSE instructions
func (c CPUInfo) SSE() bool {
return c.featureSet.inSet(SSE)
}
// SSE2 indicates support of SSE 2 instructions
func (c CPUInfo) SSE2() bool {
return c.featureSet.inSet(SSE2)
}
// SSE3 indicates support of SSE 3 instructions
func (c CPUInfo) SSE3() bool {
return c.featureSet.inSet(SSE3)
}
// SSSE3 indicates support of SSSE 3 instructions
func (c CPUInfo) SSSE3() bool {
return c.featureSet.inSet(SSSE3)
}
// SSE4 indicates support of SSE 4 (also called SSE 4.1) instructions
func (c CPUInfo) SSE4() bool {
return c.featureSet.inSet(SSE4)
}
// SSE42 indicates support of SSE4.2 instructions
func (c CPUInfo) SSE42() bool {
return c.featureSet.inSet(SSE42)
}
// AVX indicates support of AVX instructions
// and operating system support of AVX instructions
func (c CPUInfo) AVX() bool {
return c.featureSet.inSet(AVX)
}
// AVX2 indicates support of AVX2 instructions
func (c CPUInfo) AVX2() bool {
return c.featureSet.inSet(AVX2)
}
// FMA3 indicates support of FMA3 instructions
func (c CPUInfo) FMA3() bool {
return c.featureSet.inSet(FMA3)
}
// FMA4 indicates support of FMA4 instructions
func (c CPUInfo) FMA4() bool {
return c.featureSet.inSet(FMA4)
}
// XOP indicates support of XOP instructions
func (c CPUInfo) XOP() bool {
return c.featureSet.inSet(XOP)
}
// F16C indicates support of F16C instructions
func (c CPUInfo) F16C() bool {
return c.featureSet.inSet(F16C)
}
// BMI1 indicates support of BMI1 instructions
func (c CPUInfo) BMI1() bool {
return c.featureSet.inSet(BMI1)
}
// BMI2 indicates support of BMI2 instructions
func (c CPUInfo) BMI2() bool {
return c.featureSet.inSet(BMI2)
}
// TBM indicates support of TBM instructions
// (AMD Trailing Bit Manipulation)
func (c CPUInfo) TBM() bool {
return c.featureSet.inSet(TBM)
}
// Lzcnt indicates support of LZCNT instruction
func (c CPUInfo) Lzcnt() bool {
return c.featureSet.inSet(LZCNT)
}
// Popcnt indicates support of POPCNT instruction
func (c CPUInfo) Popcnt() bool {
return c.featureSet.inSet(POPCNT)
}
// HTT indicates the processor has Hyperthreading enabled
func (c CPUInfo) HTT() bool {
return c.featureSet.inSet(HTT)
}
// SSE2Slow indicates that SSE2 may be slow on this processor
func (c CPUInfo) SSE2Slow() bool {
return c.featureSet.inSet(SSE2SLOW)
}
// SSE3Slow indicates that SSE3 may be slow on this processor
func (c CPUInfo) SSE3Slow() bool {
return c.featureSet.inSet(SSE3SLOW)
}
// AesNi indicates support of AES-NI instructions
// (Advanced Encryption Standard New Instructions)
func (c CPUInfo) AesNi() bool {
return c.featureSet.inSet(AESNI)
}
// Clmul indicates support of CLMUL instructions
// (Carry-less Multiplication)
func (c CPUInfo) Clmul() bool {
return c.featureSet.inSet(CLMUL)
}
// NX indicates support of NX (No-Execute) bit
func (c CPUInfo) NX() bool {
return c.featureSet.inSet(NX)
}
// SSE4A indicates support of AMD Barcelona microarchitecture SSE4a instructions
func (c CPUInfo) SSE4A() bool {
return c.featureSet.inSet(SSE4A)
}
// HLE indicates support of Hardware Lock Elision
func (c CPUInfo) HLE() bool {
return c.featureSet.inSet(HLE)
}
// RTM indicates support of Restricted Transactional Memory
func (c CPUInfo) RTM() bool {
return c.featureSet.inSet(RTM)
}
// Rdrand indicates support of RDRAND instruction is available
func (c CPUInfo) Rdrand() bool {
return c.featureSet.inSet(RDRAND)
}
// Rdseed indicates support of RDSEED instruction is available
func (c CPUInfo) Rdseed() bool {
return c.featureSet.inSet(RDSEED)
}
// ADX indicates support of Intel ADX (Multi-Precision Add-Carry Instruction Extensions)
func (c CPUInfo) ADX() bool {
return c.featureSet.inSet(ADX)
}
// SHA indicates support of Intel SHA Extensions
func (c CPUInfo) SHA() bool {
return c.featureSet.inSet(SHA)
}
// AVX512F indicates support of AVX-512 Foundation
func (c CPUInfo) AVX512F() bool {
return c.featureSet.inSet(AVX512F)
}
// AVX512DQ indicates support of AVX-512 Doubleword and Quadword Instructions
func (c CPUInfo) AVX512DQ() bool {
return c.featureSet.inSet(AVX512DQ)
}
// AVX512IFMA indicates support of AVX-512 Integer Fused Multiply-Add Instructions
func (c CPUInfo) AVX512IFMA() bool {
return c.featureSet.inSet(AVX512IFMA)
}
// AVX512PF indicates support of AVX-512 Prefetch Instructions
func (c CPUInfo) AVX512PF() bool {
return c.featureSet.inSet(AVX512PF)
}
// AVX512ER indicates support of AVX-512 Exponential and Reciprocal Instructions
func (c CPUInfo) AVX512ER() bool {
return c.featureSet.inSet(AVX512ER)
}
// AVX512CD indicates support of AVX-512 Conflict Detection Instructions
func (c CPUInfo) AVX512CD() bool {
return c.featureSet.inSet(AVX512CD)
}
// AVX512BW indicates support of AVX-512 Byte and Word Instructions
func (c CPUInfo) AVX512BW() bool {
return c.featureSet.inSet(AVX512BW)
}
// AVX512VL indicates support of AVX-512 Vector Length Extensions
func (c CPUInfo) AVX512VL() bool {
return c.featureSet.inSet(AVX512VL)
}
// AVX512VBMI indicates support of AVX-512 Vector Bit Manipulation Instructions
func (c CPUInfo) AVX512VBMI() bool {
return c.featureSet.inSet(AVX512VBMI)
}
// AVX512VBMI2 indicates support of AVX-512 Vector Bit Manipulation Instructions, Version 2
func (c CPUInfo) AVX512VBMI2() bool {
return c.featureSet.inSet(AVX512VBMI2)
}
// AVX512VNNI indicates support of AVX-512 Vector Neural Network Instructions
func (c CPUInfo) AVX512VNNI() bool {
return c.featureSet.inSet(AVX512VNNI)
}
// AVX512VPOPCNTDQ indicates support of AVX-512 Vector Population Count Doubleword and Quadword
func (c CPUInfo) AVX512VPOPCNTDQ() bool {
return c.featureSet.inSet(AVX512VPOPCNTDQ)
}
// GFNI indicates support of Galois Field New Instructions
func (c CPUInfo) GFNI() bool {
return c.featureSet.inSet(GFNI)
}
// VAES indicates support of Vector AES
func (c CPUInfo) VAES() bool {
return c.featureSet.inSet(VAES)
}
// AVX512BITALG indicates support of AVX-512 Bit Algorithms
func (c CPUInfo) AVX512BITALG() bool {
return c.featureSet.inSet(AVX512BITALG)
}
// VPCLMULQDQ indicates support of Carry-Less Multiplication Quadword
func (c CPUInfo) VPCLMULQDQ() bool {
return c.featureSet.inSet(VPCLMULQDQ)
}
// AVX512BF16 indicates support of AVX-512 BFLOAT16 Instruction
func (c CPUInfo) AVX512BF16() bool {
return c.featureSet.inSet(AVX512BF16)
}
// AVX512VP2INTERSECT indicates support of AVX-512 Intersect for D/Q
func (c CPUInfo) AVX512VP2INTERSECT() bool {
return c.featureSet.inSet(AVX512VP2INTERSECT)
}
// AMXBF16 indicates support of Tile computational operations on BFLOAT16 numbers
func (c CPUInfo) AMXBF16() bool {
return c.featureSet.inSet(AMXBF16)
}
// AMXTILE indicates support of Tile architecture
func (c CPUInfo) AMXTILE() bool {
return c.featureSet.inSet(AMXTILE)
}
// AMXINT8 indicates support of Tile computational operations on 8-bit integers
func (c CPUInfo) AMXINT8() bool {
return c.featureSet.inSet(AMXINT8)
}
// WAITPKG indicates support of TPAUSE, UMONITOR, UMWAIT
func (c CPUInfo) WAITPKG() bool {
return c.featureSet.inSet(WAITPKG)
}
// SERIALIZE indicates support of Serialize Instruction Execution
func (c CPUInfo) SERIALIZE() bool {
return c.featureSet.inSet(SERIALIZE)
}
// TSXLDTRK indicates support of Intel TSX Suspend Load Address Tracking
func (c CPUInfo) TSXLDTRK() bool {
return c.featureSet.inSet(TSXLDTRK)
}
// WBNOINVD indicates support of Write Back and Do Not Invalidate Cache
func (c CPUInfo) WBNOINVD() bool {
return c.featureSet.inSet(WBNOINVD)
}
// MOVDIRI indicates support of Move Doubleword as Direct Store
func (c CPUInfo) MOVDIRI() bool {
return c.featureSet.inSet(MOVDIRI)
}
// MOVDIR64B indicates support of Move 64 Bytes as Direct Store
func (c CPUInfo) MOVDIR64B() bool {
return c.featureSet.inSet(MOVDIR64B)
}
// ENQCMD indicates support of Enqueue Command
func (c CPUInfo) ENQCMD() bool {
return c.featureSet.inSet(ENQCMD)
}
// CLDEMOTE indicates support of Cache Line Demote
func (c CPUInfo) CLDEMOTE() bool {
return c.featureSet.inSet(CLDEMOTE)
}
// MPX indicates support of Intel MPX (Memory Protection Extensions)
func (c CPUInfo) MPX() bool {
return c.featureSet.inSet(MPX)
}
// ERMS indicates support of Enhanced REP MOVSB/STOSB
func (c CPUInfo) ERMS() bool {
return c.featureSet.inSet(ERMS)
}
// RDTSCP Instruction is available.
func (c CPUInfo) RDTSCP() bool {
return c.featureSet.inSet(RDTSCP)
}
// CX16 indicates if CMPXCHG16B instruction is available.
func (c CPUInfo) CX16() bool {
return c.featureSet.inSet(CX16)
}
// TSX is split into HLE (Hardware Lock Elision) and RTM (Restricted Transactional Memory) detection.
// So TSX simply checks that.
func (c CPUInfo) TSX() bool {
return c.featureSet.inSet(HLE) && c.featureSet.inSet(RTM)
}
// Atom indicates an Atom processor
func (c CPUInfo) Atom() bool {
return c.featureSet.inSet(ATOM)
}
// Intel returns true if vendor is recognized as Intel
func (c CPUInfo) Intel() bool {
return c.VendorID == Intel
}
// AMD returns true if vendor is recognized as AMD
func (c CPUInfo) AMD() bool {
return c.VendorID == AMD
}
// Hygon returns true if vendor is recognized as Hygon
func (c CPUInfo) Hygon() bool {
return c.VendorID == Hygon
}
// Transmeta returns true if vendor is recognized as Transmeta
func (c CPUInfo) Transmeta() bool {
return c.VendorID == Transmeta
}
// NSC returns true if vendor is recognized as National Semiconductor
func (c CPUInfo) NSC() bool {
return c.VendorID == NSC
}
// VIA returns true if vendor is recognized as VIA
func (c CPUInfo) VIA() bool {
return c.VendorID == VIA
}
func (c CPUInfo) FeatureSet() []string {
s := make([]string, 0)
for _, f := range c.featureSet.Strings() {
s = append(s, f)
}
return s
}
// RTCounter returns the 64-bit time-stamp counter
// Uses the RDTSCP instruction. The value 0 is returned
// if the CPU does not support the instruction.
func (c CPUInfo) RTCounter() uint64 {
if !c.RDTSCP() {
return 0
}
a, _, _, d := rdtscpAsm()
return uint64(a) | (uint64(d) << 32)
}
// Ia32TscAux returns the IA32_TSC_AUX part of the RDTSCP.
// This variable is OS dependent, but on Linux contains information
// about the current cpu/core the code is running on.
// If the RDTSCP instruction isn't supported on the CPU, the value 0 is returned.
func (c CPUInfo) Ia32TscAux() uint32 {
if !c.RDTSCP() {
return 0
}
_, _, ecx, _ := rdtscpAsm()
return ecx
}
// LogicalCPU will return the Logical CPU the code is currently executing on.
// This is likely to change when the OS re-schedules the running thread
// to another CPU.
// If the current core cannot be detected, -1 will be returned.
func (c CPUInfo) LogicalCPU() int {
if c.maxFunc < 1 {
return -1
}
_, ebx, _, _ := cpuid(1)
return int(ebx >> 24)
}
// hertz tries to compute the clock speed of the CPU. If leaf 15 is
// supported, use it, otherwise parse the brand string. Yes, really.
func hertz(model string) int64 {
mfi := maxFunctionID()
if mfi >= 0x15 {
eax, ebx, ecx, _ := cpuid(0x15)
if eax != 0 && ebx != 0 && ecx != 0 {
return int64((int64(ecx) * int64(ebx)) / int64(eax))
}
}
// computeHz determines the official rated speed of a CPU from its brand
// string. This insanity is *actually the official documented way to do
// this according to Intel*, prior to leaf 0x15 existing. The official
// documentation only shows this working for exactly `x.xx` or `xxxx`
// cases, e.g., `2.50GHz` or `1300MHz`; this parser will accept other
// sizes.
hz := strings.LastIndex(model, "Hz")
if hz < 3 {
return -1
}
var multiplier int64
switch model[hz-1] {
case 'M':
multiplier = 1000 * 1000
case 'G':
multiplier = 1000 * 1000 * 1000
case 'T':
multiplier = 1000 * 1000 * 1000 * 1000
}
if multiplier == 0 {
return -1
}
freq := int64(0)
divisor := int64(0)
decimalShift := int64(1)
var i int
for i = hz - 2; i >= 0 && model[i] != ' '; i-- {
if model[i] >= '0' && model[i] <= '9' {
freq += int64(model[i]-'0') * decimalShift
decimalShift *= 10
} else if model[i] == '.' {
if divisor != 0 {
return -1
}
divisor = decimalShift
} else {
return -1
}
}
// we didn't find a space
if i < 0 {
return -1
}
if divisor != 0 {
return (freq * multiplier) / divisor
}
return freq * multiplier
}
// VM Will return true if the cpu id indicates we are in
// a virtual machine.
func (c CPUInfo) VM() bool {
return CPU.featureSet.inSet(HYPERVISOR)
}
// Flags contains detected cpu features and characteristics
type Flags uint64
// ArmFlags contains detected ARM cpu features and characteristics
type ArmFlags uint64
// FlagSet contains detected cpu features and characteristics in an array of Flags
type FlagSet []Flags
// String returns a string representation of the detected
// CPU features.
func (f Flags) String() string {
return strings.Join(f.Strings(), ",")
}
func (s FlagSet) inSet(offset uint) bool {
if len(s) == 0 {
return false
}
return s[offset>>6]&(1<<(offset&63)) != 0
}
func (s FlagSet) set(offset uint) {
if len(s) == 0 {
return
}
s[offset>>6] |= 1 << (offset & 63)
}
// Strings returns an array of the detected features.
func (f Flags) Strings() []string {
s := FlagSet{f}
return s.Strings()
}
// Strings returns an array of the detected features for FlagsSet.
func (s FlagSet) Strings() []string {
if len(s) == 0 {
return []string{""}
}
bits := uint(len(s) * 64)
r := make([]string, 0, bits)
for i := uint(0); i < bits; i++ {
if s.inSet(i) {
r = append(r, flagNames[Flags(i)])
}
}
return r
}
// String returns a string representation of the detected
// CPU features.
func (f ArmFlags) String() string {
return strings.Join(f.Strings(), ",")
}
// Strings returns an array of the detected features.
func (f ArmFlags) Strings() []string {
r := make([]string, 0, 20)
for i := uint(0); i < 64; i++ {
key := ArmFlags(1 << i)
val := flagNamesArm[key]
if f&key != 0 {
r = append(r, val)
}
}
return r
}
func maxExtendedFunction() uint32 {
eax, _, _, _ := cpuid(0x80000000)
return eax
}
func maxFunctionID() uint32 {
a, _, _, _ := cpuid(0)
return a
}
func brandName() string {
if maxExtendedFunction() >= 0x80000004 {
v := make([]uint32, 0, 48)
for i := uint32(0); i < 3; i++ {
a, b, c, d := cpuid(0x80000002 + i)
v = append(v, a, b, c, d)
}
return strings.Trim(string(valAsString(v...)), " ")
}
return "unknown"
}
func threadsPerCore() int {
mfi := maxFunctionID()
vend, _ := vendorID()
if mfi < 0x4 || (vend != Intel && vend != AMD) {
return 1
}
if mfi < 0xb {
if vend != Intel {
return 1
}
_, b, _, d := cpuid(1)
if (d & (1 << 28)) != 0 {
// v will contain logical core count
v := (b >> 16) & 255
if v > 1 {
a4, _, _, _ := cpuid(4)
// physical cores
v2 := (a4 >> 26) + 1
if v2 > 0 {
return int(v) / int(v2)
}
}
}
return 1
}
_, b, _, _ := cpuidex(0xb, 0)
if b&0xffff == 0 {
return 1
}
return int(b & 0xffff)
}
func logicalCores() int {
mfi := maxFunctionID()
v, _ := vendorID()
switch v {
case Intel:
// Use this on old Intel processors
if mfi < 0xb {
if mfi < 1 {
return 0
}
// CPUID.1:EBX[23:16] represents the maximum number of addressable IDs (initial APIC ID)
// that can be assigned to logical processors in a physical package.
// The value may not be the same as the number of logical processors that are present in the hardware of a physical package.
_, ebx, _, _ := cpuid(1)
logical := (ebx >> 16) & 0xff
return int(logical)
}
_, b, _, _ := cpuidex(0xb, 1)
return int(b & 0xffff)
case AMD, Hygon:
_, b, _, _ := cpuid(1)
return int((b >> 16) & 0xff)
default:
return 0
}
}
func familyModel() (int, int) {
if maxFunctionID() < 0x1 {
return 0, 0
}
eax, _, _, _ := cpuid(1)
family := ((eax >> 8) & 0xf) + ((eax >> 20) & 0xff)
model := ((eax >> 4) & 0xf) + ((eax >> 12) & 0xf0)
return int(family), int(model)
}
func physicalCores() int {
v, _ := vendorID()
switch v {
case Intel:
return logicalCores() / threadsPerCore()
case AMD, Hygon:
lc := logicalCores()
tpc := threadsPerCore()
if lc > 0 && tpc > 0 {
return lc / tpc
}
// The following is inaccurate on AMD EPYC 7742 64-Core Processor
if maxExtendedFunction() >= 0x80000008 {
_, _, c, _ := cpuid(0x80000008)
return int(c&0xff) + 1
}
}
return 0
}
// Except from http://en.wikipedia.org/wiki/CPUID#EAX.3D0:_Get_vendor_ID
var vendorMapping = map[string]Vendor{
"AMDisbetter!": AMD,
"AuthenticAMD": AMD,
"CentaurHauls": VIA,
"GenuineIntel": Intel,
"TransmetaCPU": Transmeta,
"GenuineTMx86": Transmeta,
"Geode by NSC": NSC,
"VIA VIA VIA ": VIA,
"KVMKVMKVMKVM": KVM,
"Microsoft Hv": MSVM,
"VMwareVMware": VMware,
"XenVMMXenVMM": XenHVM,
"bhyve bhyve ": Bhyve,
"HygonGenuine": Hygon,
"Vortex86 SoC": SiS,
"SiS SiS SiS ": SiS,
"RiseRiseRise": SiS,
"Genuine RDC": RDC,
}
func vendorID() (Vendor, string) {
_, b, c, d := cpuid(0)
v := string(valAsString(b, d, c))
vend, ok := vendorMapping[v]
if !ok {
return Other, v
}
return vend, v
}
func cacheLine() int {
if maxFunctionID() < 0x1 {
return 0
}
_, ebx, _, _ := cpuid(1)
cache := (ebx & 0xff00) >> 5 // cflush size
if cache == 0 && maxExtendedFunction() >= 0x80000006 {
_, _, ecx, _ := cpuid(0x80000006)
cache = ecx & 0xff // cacheline size
}
// TODO: Read from Cache and TLB Information
return int(cache)
}
func (c *CPUInfo) cacheSize() {
c.Cache.L1D = -1
c.Cache.L1I = -1
c.Cache.L2 = -1
c.Cache.L3 = -1
vendor, _ := vendorID()
switch vendor {
case Intel:
if maxFunctionID() < 4 {
return
}
for i := uint32(0); ; i++ {
eax, ebx, ecx, _ := cpuidex(4, i)
cacheType := eax & 15
if cacheType == 0 {
break
}
cacheLevel := (eax >> 5) & 7
coherency := int(ebx&0xfff) + 1
partitions := int((ebx>>12)&0x3ff) + 1
associativity := int((ebx>>22)&0x3ff) + 1
sets := int(ecx) + 1
size := associativity * partitions * coherency * sets
switch cacheLevel {
case 1:
if cacheType == 1 {
// 1 = Data Cache
c.Cache.L1D = size
} else if cacheType == 2 {
// 2 = Instruction Cache
c.Cache.L1I = size
} else {
if c.Cache.L1D < 0 {
c.Cache.L1I = size
}
if c.Cache.L1I < 0 {
c.Cache.L1I = size
}
}
case 2:
c.Cache.L2 = size
case 3:
c.Cache.L3 = size
}
}
case AMD, Hygon:
// Untested.
if maxExtendedFunction() < 0x80000005 {
return
}
_, _, ecx, edx := cpuid(0x80000005)
c.Cache.L1D = int(((ecx >> 24) & 0xFF) * 1024)
c.Cache.L1I = int(((edx >> 24) & 0xFF) * 1024)
|
return
}
_, _, ecx, _ = cpuid(0x80000006)
c.Cache.L2 = int(((ecx >> 16) & 0xFFFF) * 1024)
// CPUID Fn8000_001D_EAX_x[N:0] Cache Properties
if maxExtendedFunction() < 0x8000001D {
return
}
for i := uint32(0); i < math.MaxUint32; i++ {
eax, ebx, ecx, _ := cpuidex(0x8000001D, i)
level := (eax >> 5) & 7
cacheNumSets := ecx + 1
cacheLineSize := 1 + (ebx & 2047)
cachePhysPartitions := 1 + ((ebx >> 12) & 511)
cacheNumWays := 1 + ((ebx >> 22) & 511)
typ := eax & 15
size := int(cacheNumSets * cacheLineSize * cachePhysPartitions * cacheNumWays)
if typ == 0 {
return
}
switch level {
case 1:
switch typ {
case 1:
// Data cache
c.Cache.L1D = size
case 2:
// Inst cache
c.Cache.L1I = size
default:
if c.Cache.L1D < 0 {
c.Cache.L1I = size
}
if c.Cache.L1I < 0 {
c.Cache.L1I = size
}
}
case 2:
c.Cache.L2 = size
case 3:
c.Cache.L3 = size
}
}
}
return
}
type SGXEPCSection struct {
BaseAddress uint64
EPCSize uint64
}
type SGXSupport struct {
Available bool
LaunchControl bool
SGX1Supported bool
SGX2Supported bool
MaxEnclaveSizeNot64 int64
MaxEnclaveSize64 int64
EPCSections []SGXEPCSection
}
func hasSGX(available, lc bool) (rval SGXSupport) {
rval.Available = available
if !available {
return
}
rval.LaunchControl = lc
a, _, _, d := cpuidex(0x12, 0)
rval.SGX1Supported = a&0x01 != 0
rval.SGX2Supported = a&0x02 != 0
rval.MaxEnclaveSizeNot64 = 1 << (d & 0xFF) // pow 2
rval.MaxEnclaveSize64 = 1 << ((d >> 8) & 0xFF) // pow 2
rval.EPCSections = make([]SGXEPCSection, 0)
for subleaf := uint32(2); subleaf < 2+8; subleaf++ {
eax, ebx, ecx, edx := cpuidex(0x12, subleaf)
leafType := eax & 0xf
if leafType == 0 {
// Invalid subleaf, stop iterating
break
} else if leafType == 1 {
// EPC Section subleaf
baseAddress := uint64(eax&0xfffff000) + (uint64(ebx&0x000fffff) << 32)
size := uint64(ecx&0xfffff000) + (uint64(edx&0x000fffff) << 32)
section := SGXEPCSection{BaseAddress: baseAddress, EPCSize: size}
rval.EPCSections = append(rval.EPCSections, section)
}
}
return
}
func support() FlagSet {
mfi := maxFunctionID()
vend, _ := vendorID()
if mfi < 0x1 {
return nil
}
fs := make(FlagSet, LASTID/64+1)
_, _, c, d := cpuid(1)
if (d & (1 << 15)) != 0 {
fs.set(CMOV)
}
if (d & (1 << 23)) != 0 {
fs.set(MMX)
}
if (d & (1 << 25)) != 0 {
fs.set(MMXEXT)
}
if (d & (1 << 25)) != 0 {
fs.set(SSE)
}
if (d & (1 << 26)) != 0 {
fs.set(SSE2)
}
if (c & 1) != 0 {
fs.set(SSE3)
}
if (c & (1 << 5)) != 0 {
fs.set(VMX)
}
if (c & 0x00000200) != 0 {
fs.set(SSSE3)
}
if (c & 0x00080000) != 0 {
fs.set(SSE4)
}
if (c & 0x00100000) != 0 {
fs.set(SSE42)
}
if (c & (1 << 25)) != 0 {
fs.set(AESNI)
}
if (c & (1 << 1)) != 0 {
fs.set(CLMUL)
}
if c&(1<<23) != 0 {
fs.set(POPCNT)
}
if c&(1<<30) != 0 {
fs.set(RDRAND)
}
// This bit has been reserved by Intel & AMD for use by hypervisors,
// and indicates the presence of a hypervisor.
if c&(1<<31) != 0 {
fs.set(HYPERVISOR)
}
if c&(1<<29) != 0 {
fs.set(F16C)
}
if c&(1<<13) != 0 {
fs.set(CX16)
}
if vend == Intel && (d&(1<<28)) != 0 && mfi >= 4 {
if threadsPerCore() > 1 {
fs.set(HTT)
}
}
if vend == AMD && (d&(1<<28)) != 0 && mfi >= 4 {
if threadsPerCore() > 1 {
fs.set(HTT)
}
}
// Check XGETBV, OXSAVE and AVX bits
if c&(1<<26) != 0 && c&(1<<27) != 0 && c&(1<<28) != 0 {
// Check for OS support
eax, _ := xgetbv(0)
if (eax & 0x6) == 0x6 {
fs.set(AVX)
if (c & 0x00001000) != 0 {
fs.set(FMA3)
}
}
}
// Check AVX2, AVX2 requires OS support, but BMI1/2 don't.
if mfi >= 7 {
_, ebx, ecx, edx := cpuidex(7, 0)
eax1, _, _, _ := cpuidex(7, 1)
if fs.inSet(AVX) && (ebx&0x00000020) != 0 {
fs.set(AVX2)
}
// CPUID.(EAX=7, ECX=0).EBX
if (ebx & 0x00000008) != 0 {
fs.set(BMI1)
if (ebx & 0x00000100) != 0 {
fs.set(BMI2)
}
}
if ebx&(1<<2) != 0 {
fs.set(SGX)
}
if ebx&(1<<4) != 0 {
fs.set(HLE)
}
if ebx&(1<<9) != 0 {
fs.set(ERMS)
}
if ebx&(1<<11) != 0 {
fs.set(RTM)
}
if ebx&(1<<14) != 0 {
fs.set(MPX)
}
if ebx&(1<<18) != 0 {
fs.set(RDSEED)
}
if ebx&(1<<19) != 0 {
fs.set(ADX)
}
if ebx&(1<<29) != 0 {
fs.set(SHA)
}
// CPUID.(EAX=7, ECX=0).ECX
if ecx&(1<<5) != 0 {
fs.set(WAITPKG)
}
if ecx&(1<<25) != 0 {
fs.set(CLDEMOTE)
}
if ecx&(1<<27) != 0 {
fs.set(MOVDIRI)
}
if ecx&(1<<28) != 0 {
fs.set(MOVDIR64B)
}
if ecx&(1<<29) != 0 {
fs.set(ENQCMD)
}
if ecx&(1<<30) != 0 {
fs.set(SGXLC)
}
// CPUID.(EAX=7, ECX=0).EDX
if edx&(1<<14) != 0 {
fs.set(SERIALIZE)
}
if edx&(1<<16) != 0 {
fs.set(TSXLDTRK)
}
if edx&(1<<26) != 0 {
fs.set(IBPB)
}
if edx&(1<<27) != 0 {
fs.set(STIBP)
}
// Only detect AVX-512 features if XGETBV is supported
if c&((1<<26)|(1<<27)) == (1<<26)|(1<<27) {
// Check for OS support
eax, _ := xgetbv(0)
// Verify that XCR0[7:5] = ‘111b’ (OPMASK state, upper 256-bit of ZMM0-ZMM15 and
// ZMM16-ZMM31 state are enabled by OS)
/// and that XCR0[2:1] = ‘11b’ (XMM state and YMM state are enabled by OS).
if (eax>>5)&7 == 7 && (eax>>1)&3 == 3 {
if ebx&(1<<16) != 0 {
fs.set(AVX512F)
}
if ebx&(1<<17) != 0 {
fs.set(AVX512DQ)
}
if ebx&(1<<21) != 0 {
fs.set(AVX512IFMA)
}
if ebx&(1<<26) != 0 {
fs.set(AVX512PF)
}
if ebx&(1<<27) != 0 {
fs.set(AVX512ER)
}
if ebx&(1<<28) != 0 {
fs.set(AVX512CD)
}
if ebx&(1<<30) != 0 {
fs.set(AVX512BW)
}
if ebx&(1<<31) != 0 {
fs.set(AVX512VL)
}
// ecx
if ecx&(1<<1) != 0 {
fs.set(AVX512VBMI)
}
if ecx&(1<<6) != 0 {
fs.set(AVX512VBMI2)
}
if ecx&(1<<8) != 0 {
fs.set(GFNI)
}
if ecx&(1<<9) != 0 {
fs.set(VAES)
}
if ecx&(1<<10) != 0 {
fs.set(VPCLMULQDQ)
}
if ecx&(1<<11) != 0 {
fs.set(AVX512VNNI)
}
if ecx&(1<<12) != 0 {
fs.set(AVX512BITALG)
}
if ecx&(1<<14) != 0 {
fs.set(AVX512VPOPCNTDQ)
}
// edx
if edx&(1<<8) != 0 {
fs.set(AVX512VP2INTERSECT)
}
if edx&(1<<22) != 0 {
fs.set(AMXBF16)
}
if edx&(1<<24) != 0 {
fs.set(AMXTILE)
}
if edx&(1<<25) != 0 {
fs.set(AMXINT8)
}
// eax1 = CPUID.(EAX=7, ECX=1).EAX
if eax1&(1<<5) != 0 {
fs.set(AVX512BF16)
}
}
}
}
if maxExtendedFunction() >= 0x80000001 {
_, _, c, d := cpuid(0x80000001)
if (c & (1 << 5)) != 0 {
fs.set(LZCNT)
fs.set(POPCNT)
}
if (d & (1 << 31)) != 0 {
fs.set(AMD3DNOW)
}
if (d & (1 << 30)) != 0 {
fs.set(AMD3DNOWEXT)
}
if (d & (1 << 23)) != 0 {
fs.set(MMX)
}
if (d & (1 << 22)) != 0 {
fs.set(MMXEXT)
}
if (c & (1 << 6)) != 0 {
fs.set(SSE4A)
}
if d&(1<<20) != 0 {
fs.set(NX)
}
if d&(1<<27) != 0 {
fs.set(RDTSCP)
}
/* Allow for selectively disabling SSE2 functions on AMD processors
with SSE2 support but not SSE4a. This includes Athlon64, some
Opteron, and some Sempron processors. MMX, SSE, or 3DNow! are faster
than SSE2 often enough to utilize this special-case flag.
AV_CPU_FLAG_SSE2 and AV_CPU_FLAG_SSE2SLOW are both set in this case
so that SSE2 is used unless explicitly disabled by checking
AV_CPU_FLAG_SSE2SLOW. */
if vend != Intel &&
fs.inSet(SSE2) && (c&0x00000040) == 0 {
fs.set(SSE2SLOW)
}
/* XOP and FMA4 use the AVX instruction coding scheme, so they can't be
* used unless the OS has AVX support. */
if fs.inSet(AVX) {
if (c & 0x00000800) != 0 {
fs.set(XOP)
}
if (c & 0x00010000) != 0 {
fs.set(FMA4)
}
}
if vend == Intel {
family, model := familyModel()
if family == 6 && (model == 9 || model == 13 || model == 14) {
/* 6/9 (pentium-m "banias"), 6/13 (pentium-m "dothan"), and
* 6/14 (core1 "yonah") theoretically support sse2, but it's
* usually slower than mmx. */
if fs.inSet(SSE2) {
fs.set(SSE2SLOW)
}
if fs.inSet(SSE3) {
fs.set(SSE3SLOW)
}
}
/* The Atom processor has SSSE3 support, which is useful in many cases,
* but sometimes the SSSE3 version is slower than the SSE2 equivalent
* on the Atom, but is generally faster on other processors supporting
* SSSE3. This flag allows for selectively disabling certain SSSE3
* functions on the Atom. */
if family == 6 && model == 28 {
fs.set(ATOM)
}
}
}
if maxExtendedFunction() >= 0x80000008 {
_, b, _, _ := cpuid(0x80000008)
if (b & (1 << 9)) != 0 {
fs.set(WBNOINVD)
}
}
return fs
}
func valAsString(values ...uint32) []byte {
r := make([]byte, 4*len(values))
for i, v := range values {
dst := r[i*4:]
dst[0] = byte(v & 0xff)
dst[1] = byte((v >> 8) & 0xff)
dst[2] = byte((v >> 16) & 0xff)
dst[3] = byte((v >> 24) & 0xff)
switch {
case dst[0] == 0:
return r[:i*4]
case dst[1] == 0:
return r[:i*4+1]
case dst[2] == 0:
return r[:i*4+2]
case dst[3] == 0:
return r[:i*4+3]
}
}
return r
}
// Single-precision and double-precision floating point
func (c CPUInfo) ArmFP() bool {
return c.Arm&FP != 0
}
// Advanced SIMD
func (c CPUInfo) ArmASIMD() bool {
return c.Arm&ASIMD != 0
}
// Generic timer
func (c CPUInfo) ArmEVTSTRM() bool {
return c.Arm&EVTSTRM != 0
}
// AES instructions
func (c CPUInfo) ArmAES() bool {
return c.Arm&AES != 0
}
// Polynomial Multiply instructions (PMULL/PMULL2)
func (c CPUInfo) ArmPMULL() bool {
return c.Arm&PMULL != 0
}
// SHA-1 instructions (SHA1C, etc)
func (c CPUInfo) ArmSHA1() bool {
return c.Arm&SHA1 != 0
}
// SHA-2 instructions (SHA256H, etc)
func (c CPUInfo) ArmSHA2() bool {
return c.Arm&SHA2 != 0
}
// CRC32/CRC32C instructions
func (c CPUInfo) ArmCRC32() bool {
return c.Arm&CRC32 != 0
}
// Large System Extensions (LSE)
func (c CPUInfo) ArmATOMICS() bool {
return c.Arm&ATOMICS != 0
}
// Half-precision floating point
func (c CPUInfo) ArmFPHP() bool {
return c.Arm&FPHP != 0
}
// Advanced SIMD half-precision floating point
func (c CPUInfo) ArmASIMDHP() bool {
return c.Arm&ASIMDHP != 0
}
// Rounding Double Multiply Accumulate/Subtract (SQRDMLAH/SQRDMLSH)
func (c CPUInfo) ArmASIMDRDM() bool {
return c.Arm&ASIMDRDM != 0
}
// Javascript-style double->int convert (FJCVTZS)
func (c CPUInfo) ArmJSCVT() bool {
return c.Arm&JSCVT != 0
}
// Floatin point complex number addition and multiplication
func (c CPUInfo) ArmFCMA() bool {
return c.Arm&FCMA != 0
}
// Weaker release consistency (LDAPR, etc)
func (c CPUInfo) ArmLRCPC() bool {
return c.Arm&LRCPC != 0
}
// Data cache clean to Point of Persistence (DC CVAP)
func (c CPUInfo) ArmDCPOP() bool {
return c.Arm&DCPOP != 0
}
// SHA-3 instructions (EOR3, RAXI, XAR, BCAX)
func (c CPUInfo) ArmSHA3() bool {
return c.Arm&SHA3 != 0
}
// SM3 instructions
func (c CPUInfo) ArmSM3() bool {
return c.Arm&SM3 != 0
}
// SM4 instructions
func (c CPUInfo) ArmSM4() bool {
return c.Arm&SM4 != 0
}
// SIMD Dot Product
func (c CPUInfo) ArmASIMDDP() bool {
return c.Arm&ASIMDDP != 0
}
// SHA512 instructions
func (c CPUInfo) ArmSHA512() bool {
return c.Arm&SHA512 != 0
}
// Scalable Vector Extension
func (c CPUInfo) ArmSVE() bool {
return c.Arm&SVE != 0
}
// Generic Pointer Authentication
func (c CPUInfo) ArmGPA() bool {
return c.Arm&GPA != 0
}
|
if maxExtendedFunction() < 0x80000006 {
|
resource.py
|
# -*- coding: utf-8 -*-
"""
shellstreaming.util.resource
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:synopsis: Reports HW resource info
"""
# standard modules
import time
# 3rd party moduels
import psutil
_cpu_percent_called = False
def avail_cores():
"""Return number of available cores on the node"""
# Since :func:`psutil.cpu_percent()` is implemented to compare cpu time of current & previous call,
# 1st result of this function is not necessarily relavant to shellstreaming itself.
global _cpu_percent_called
if not _cpu_percent_called:
psutil.cpu_percent(interval=0, percpu=True)
_cpu_percent_called = True
time.sleep(0.1)
ret = 0
for core_usage in psutil.cpu_percent(interval=0, percpu=True):
if core_usage < 20.0: # [todo] - change parameter to calc available cores?
ret += 1
return ret
def
|
():
# [todo] - after implementing memory controller (which evicts data into disk sometimes),
# [todo] - file cache would be important. Then `free` is better to use than `available`
return psutil.virtual_memory().available
|
avail_memory_byte
|
delete_backend_switching_rule_parameters.go
|
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 2019 HAProxy Technologies
//
// 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.
//
package backend_switching_rule
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"net/http"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/go-openapi/runtime/middleware"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
"github.com/go-openapi/validate"
)
// NewDeleteBackendSwitchingRuleParams creates a new DeleteBackendSwitchingRuleParams object
// with the default values initialized.
func
|
() DeleteBackendSwitchingRuleParams {
var (
// initialize parameters with default values
forceReloadDefault = bool(false)
)
return DeleteBackendSwitchingRuleParams{
ForceReload: &forceReloadDefault,
}
}
// DeleteBackendSwitchingRuleParams contains all the bound params for the delete backend switching rule operation
// typically these are obtained from a http.Request
//
// swagger:parameters deleteBackendSwitchingRule
type DeleteBackendSwitchingRuleParams struct {
// HTTP Request Object
HTTPRequest *http.Request `json:"-"`
/*If set, do a force reload, do not wait for the configured reload-delay. Cannot be used when transaction is specified, as changes in transaction are not applied directly to configuration.
In: query
Default: false
*/
ForceReload *bool
/*Frontend name
Required: true
In: query
*/
Frontend string
/*Switching Rule Index
Required: true
In: path
*/
Index int64
/*ID of the transaction where we want to add the operation. Cannot be used when version is specified.
In: query
*/
TransactionID *string
/*Version used for checking configuration version. Cannot be used when transaction is specified, transaction has it's own version.
In: query
*/
Version *int64
}
// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls.
//
// To ensure default values, the struct must have been initialized with NewDeleteBackendSwitchingRuleParams() beforehand.
func (o *DeleteBackendSwitchingRuleParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error {
var res []error
o.HTTPRequest = r
qs := runtime.Values(r.URL.Query())
qForceReload, qhkForceReload, _ := qs.GetOK("force_reload")
if err := o.bindForceReload(qForceReload, qhkForceReload, route.Formats); err != nil {
res = append(res, err)
}
qFrontend, qhkFrontend, _ := qs.GetOK("frontend")
if err := o.bindFrontend(qFrontend, qhkFrontend, route.Formats); err != nil {
res = append(res, err)
}
rIndex, rhkIndex, _ := route.Params.GetOK("index")
if err := o.bindIndex(rIndex, rhkIndex, route.Formats); err != nil {
res = append(res, err)
}
qTransactionID, qhkTransactionID, _ := qs.GetOK("transaction_id")
if err := o.bindTransactionID(qTransactionID, qhkTransactionID, route.Formats); err != nil {
res = append(res, err)
}
qVersion, qhkVersion, _ := qs.GetOK("version")
if err := o.bindVersion(qVersion, qhkVersion, route.Formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
// bindForceReload binds and validates parameter ForceReload from query.
func (o *DeleteBackendSwitchingRuleParams) bindForceReload(rawData []string, hasKey bool, formats strfmt.Registry) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
// Required: false
// AllowEmptyValue: false
if raw == "" { // empty values pass all other validations
// Default values have been previously initialized by NewDeleteBackendSwitchingRuleParams()
return nil
}
value, err := swag.ConvertBool(raw)
if err != nil {
return errors.InvalidType("force_reload", "query", "bool", raw)
}
o.ForceReload = &value
return nil
}
// bindFrontend binds and validates parameter Frontend from query.
func (o *DeleteBackendSwitchingRuleParams) bindFrontend(rawData []string, hasKey bool, formats strfmt.Registry) error {
if !hasKey {
return errors.Required("frontend", "query")
}
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
// Required: true
// AllowEmptyValue: false
if err := validate.RequiredString("frontend", "query", raw); err != nil {
return err
}
o.Frontend = raw
return nil
}
// bindIndex binds and validates parameter Index from path.
func (o *DeleteBackendSwitchingRuleParams) bindIndex(rawData []string, hasKey bool, formats strfmt.Registry) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
// Required: true
// Parameter is provided by construction from the route
value, err := swag.ConvertInt64(raw)
if err != nil {
return errors.InvalidType("index", "path", "int64", raw)
}
o.Index = value
return nil
}
// bindTransactionID binds and validates parameter TransactionID from query.
func (o *DeleteBackendSwitchingRuleParams) bindTransactionID(rawData []string, hasKey bool, formats strfmt.Registry) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
// Required: false
// AllowEmptyValue: false
if raw == "" { // empty values pass all other validations
return nil
}
o.TransactionID = &raw
return nil
}
// bindVersion binds and validates parameter Version from query.
func (o *DeleteBackendSwitchingRuleParams) bindVersion(rawData []string, hasKey bool, formats strfmt.Registry) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
// Required: false
// AllowEmptyValue: false
if raw == "" { // empty values pass all other validations
return nil
}
value, err := swag.ConvertInt64(raw)
if err != nil {
return errors.InvalidType("version", "query", "int64", raw)
}
o.Version = &value
return nil
}
|
NewDeleteBackendSwitchingRuleParams
|
last-use-in-cap-clause.rs
|
// Make sure #1399 stays fixed
#[allow(dead_code)]
struct A { a: Box<isize> }
fn foo() -> Box<FnMut() -> isize + 'static>
|
pub fn main() {
assert_eq!(foo()(), 22);
}
|
{
let k: Box<_> = Box::new(22);
let _u = A {a: k.clone()};
let result = || 22;
Box::new(result)
}
|
models.py
|
#
# Copyright (c) 2017 Electronic Arts Inc. All Rights Reserved
#
from __future__ import unicode_literals
import datetime
from django.db import models
from django.utils import timezone
from model_utils.fields import MonitorField, StatusField
from model_utils.models import TimeStampedModel
from model_utils import Choices
from archive.models import Take, StaticScanAsset, TrackingAsset
class FarmNodeGroup(models.Model):
name = models.CharField(max_length=200)
|
def __str__(self):
return '%s' % (self.name)
class FarmNode(models.Model):
# Fields
ip_address = models.CharField(max_length=200)
machine_name = models.CharField(max_length=200)
last_seen = models.DateTimeField('last seen', auto_now_add=True)
code_version = models.IntegerField(default=1)
req_restart = models.BooleanField(default=False)
active = models.BooleanField(default=True) # Server-side active switch, set to false to prevent jobs from being dispatched to this node
system = models.CharField(max_length=80, null=True)
system_bits = models.IntegerField(null=True)
cpu_brand = models.CharField(max_length=80, null=True)
cpu_cores = models.IntegerField(null=True)
gpu_count = models.IntegerField(null=True)
cpu_percent = models.FloatField(default=0.0)
STATUS = Choices('offline', 'accepting') # Client-side status, reported by the node itself
status = StatusField()
group = models.ForeignKey(FarmNodeGroup, on_delete=models.SET_NULL, null=True, blank=True, related_name='nodes')
# TODO Add Features (string comma separated keywords)
def has_write_access(self, user):
# TODO Access rights
return user.is_superuser
def running_jobs(self):
return self.jobs.filter(status='running')
def actual_status(self):
if not self.is_active():
return 'offline'
return self.status
def is_active(self):
return self.status=='accepting' and self.last_seen >= timezone.now() - datetime.timedelta(seconds=90)
def __str__(self):
return '%s' % (self.machine_name)
class FarmJob(TimeStampedModel):
# Fields
job_class = models.CharField(max_length=200)
created_by = models.CharField(max_length=200)
params = models.TextField(null=True, blank=True)
exception = models.CharField(max_length=800, null=True, blank=True)
node = models.ForeignKey(FarmNode, on_delete=models.CASCADE, null=True, blank=True, related_name='jobs')
progress = models.CharField(max_length=200, null=True, blank=True)
req_version = models.IntegerField(default=1)
req_gpu = models.BooleanField(default=True)
priority = models.IntegerField(default=50)
# Relationships
parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children')
dependencies = models.ManyToManyField('self', related_name='dependants', blank=True, symmetrical=False)
# Job Status
STATUS = Choices('created', 'ready', 'reserved', 'running', 'failed', 'success', 'waiting', 'terminating')
status = StatusField()
status.db_index = True
status_changed = MonitorField(monitor='status', db_index=True)
# Start/end time for the 'running' status
start_time = models.DateTimeField('start time', null=True, blank=True)
end_time = models.DateTimeField('end time', null=True, blank=True)
# External Relationships
ext_take = models.ForeignKey(Take, on_delete=models.SET_NULL, null=True, blank=True, related_name='ext_jobs')
ext_scan_assets = models.ForeignKey(StaticScanAsset, on_delete=models.SET_NULL, null=True, blank=True, related_name='ext_jobs')
ext_tracking_assets = models.ForeignKey(TrackingAsset, on_delete=models.SET_NULL, null=True, blank=True, related_name='ext_jobs')
image_filename = models.CharField(max_length=250, null=True, blank=True)
# TODO Requirements (must match Node Features) (string comma separated keywords)
# TODO Start/stop time, duration
# TODO Status change log ?
def has_write_access(self, user):
# TODO Access rights
return self.created_by == user.username or user.is_superuser
def __str__(self):
return '#%d (%s) %s' % (self.id, self.job_class, self.status)
def get_absolute_url(self):
return "/static/d/index.html#/app/job_details/%i" % self.id
| |
lib.rs
|
use std::io::{BufRead, BufReader, Read, Write};
use std::process::{Child, ChildStdin, Command, ExitStatus, Stdio};
use std::sync::{mpsc, Arc, Mutex};
use std::thread;
use std::time::Duration;
pub mod utils;
// Const to share among the library to manage how fast everything is updated witouth overloading the system
pub const MILLISEC_PAUSE: u64 = 100;
/// Struct containing the necessary to manage the process
pub struct RunningProcess {
process: Child,
stdout_pipe: Option<Arc<Mutex<Vec<mpsc::Sender<String>>>>>,
handle_output: Option<thread::JoinHandle<()>>,
stderr_pipe: Option<Arc<Mutex<Vec<mpsc::Sender<String>>>>>,
handle_error: Option<thread::JoinHandle<()>>,
stdin_pipe: Option<mpsc::Sender<String>>,
handle_input: Option<thread::JoinHandle<()>>,
// shared state about the current state of the process life
is_alive: Arc<Mutex<bool>>,
}
impl RunningProcess {
/* Launch the specified process
* args are optional thats why they are an option
* TODO: manage the std err
* TODO: description
*/
pub fn new(
path: String,
args: Option<Vec<String>>,
) -> Result<RunningProcess, Box<dyn std::error::Error>> {
// Creating the setup for the process
let mut setup_p = Command::new(path);
// Setup stdio
setup_p
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.stdin(Stdio::piped());
// Add args if present
if let Some(x) = args {
setup_p.args(x);
}
// startiung the process
let p = setup_p.spawn();
let mut child = match p {
Err(e) => return Err(Box::new(e)), // TODO: return Error, not panic
Ok(p) => p,
}; // returned error: std::io::Error
/* Passing the stdout of the process to a thread whose sole purpose is to gather it and send it in the channel that it was given
* This is done because the output has a limited buffer and, upon overflow, it will cause a crash of the application
* If for any reason the stdout is also needed elsewhere, it can always be implemented in the struct RunninProcess and borrowed from there
* In case te process hasn't returned stdout, just return none TODO: should be an error
* */
let (out_recieve, handle_out) = match child.stdout.take() {
None => (None, None), // TODO: return Error, not None
Some(stdout) => {
let out_send: Arc<Mutex<Vec<mpsc::Sender<String>>>> =
Arc::new(Mutex::new(Vec::new()));
let out_send_arc = Arc::clone(&out_send);
let handle_out = thread::spawn(move || {
gather_output(stdout, out_send);
});
(Some(out_send_arc), Some(handle_out))
}
};
/* Passing the stderr of the process to a thread whose sole purpose is to gather it and send it in the channel that it was given
* This is done because the stderr has a limited buffer and, upon overflow, it will cause a crash of the application
* If for any reason the stderr is also needed elsewhere, it can always be implemented in the struct RunninProcess and borrowed from there
* In case te process hasn't returned stdout, just return none TODO: should be an error
* */
let (err_recieve, handle_err) = match child.stderr.take() {
None => (None, None), // TODO: return Error, not None
Some(stderr) => {
let err_send: Arc<Mutex<Vec<mpsc::Sender<String>>>> =
Arc::new(Mutex::new(Vec::new()));
let err_send_out = Arc::clone(&err_send);
let handle_err = thread::spawn(move || {
gather_output(stderr, err_send);
});
(Some(err_send_out), Some(handle_err))
}
};
/* Passing the stdin of the process to a thread whose sole purpose is to recive the stdin from a channel that it was given
* This is done to make sure it's always possible for the process to recive the input it needs
* If for any reason the stdin is also needed elsewhere, it can always be implemented in the struct RunninProcess and borrowed from there
* In case te process hasn't returned stdout, just return none TODO: should be an error
* */
let is_alive = Arc::new(Mutex::new(true));
let is_alive_link = Arc::clone(&is_alive);
let (in_send, handle_in) = match child.stdin.take() {
None => (None, None), // TODO: return Error, not panic
Some(stdin) => {
let (in_send, in_recieve) = mpsc::channel();
let handle_in = thread::spawn(move || {
send_input(stdin, in_recieve, is_alive_link);
});
(Some(in_send), Some(handle_in))
}
};
// TODO: implement a check that waits for the input and output trhead to be ready
// Returning struct
Ok(RunningProcess {
process: child,
stdout_pipe: out_recieve,
handle_output: handle_out,
stderr_pipe: err_recieve,
handle_error: handle_err,
stdin_pipe: in_send,
handle_input: handle_in,
is_alive: is_alive,
})
} // new
/// Kills the process if it's still running
pub fn kill(&mut self) -> Result<(), Box<dyn std::error::Error>> {
// TODO: manage lock
let mut is_alive = self.is_alive.lock().unwrap();
*is_alive = false;
Ok(self.process.kill()?)
}
/// Return the OS-identifier associated with this child
pub fn id(&self) -> u32 {
self.process.id()
}
/// Attempt to return the exit status of the child if it has already exited
pub fn is_alive(&mut self) -> Result<Option<ExitStatus>, Box<dyn std::error::Error>> {
match self.process.try_wait() {
Err(e) => panic!(Box::new(e)), //TODO: bad panic
Ok(some) => Ok(some),
}
}
/// Wait for the process to end, return the exit code
pub fn wait(&mut self) -> std::io::Result<ExitStatus>
|
/// Return a pointer Arc to the stdin pipe
pub fn input_pipe(&self) -> Result<mpsc::Sender<String>, Box<dyn std::error::Error>> {
match self.stdin_pipe {
None => panic!("No input pipe"),
Some(ref pipe) => Ok(pipe.clone()),
}
}
/// Return a pointer Arc to the stdout pipe
pub fn output_pipe(&mut self) -> Result<mpsc::Receiver<String>, Box<dyn std::error::Error>> {
match &self.stdout_pipe {
None => panic!("No out pipe"),
Some(locked_vec) => {
let (new_sender, new_reciever) = mpsc::channel();
match locked_vec.lock() {
Err(_) => panic!("No locked"),
Ok(mut vec) => {
vec.push(new_sender);
Ok(new_reciever)
}
}
}
}
}
/// Return a pointer Arc to the stderr pipe
pub fn err_pipe(&mut self) -> Result<mpsc::Receiver<String>, Box<dyn std::error::Error>> {
match &self.stderr_pipe {
None => panic!("No out pipe"),
Some(locked_vec) => {
let (new_sender, new_reciever) = mpsc::channel();
match locked_vec.lock() {
Err(_) => panic!("No locked"),
Ok(mut vec) => {
vec.push(new_sender);
Ok(new_reciever)
}
}
}
}
}
} // impl RunninProcess
// Implementing what happen when the struct is removed from the memory
impl Drop for RunningProcess {
fn drop(&mut self) {
// If they exist, close the pipes
match self.stdin_pipe.take() {
Some(pipe) => drop(pipe),
None => println!("no input pipe to close"),
}
match self.stdout_pipe.take() {
Some(pipe) => drop(pipe),
None => println!("no output pipe to close"),
}
match self.stderr_pipe.take() {
Some(pipe) => drop(pipe),
None => println!("no err pipe to close"),
}
// The guard will release the access only when it goes out of scope
// This code is inside a block because we need to free the gurad
{
let mut is_alive = self.is_alive.lock().unwrap();
*is_alive = false;
}
// Use the handles to wait for the end of each thread
match self.handle_input.take() {
Some(handle) => {
println!("Joining input");
match handle.join() {
Ok(_) => println!("Input thread stopped"),
Err(_) => println!("Could not join the input thread"),
};
}
None => (),
}
match self.handle_output.take() {
Some(handle) => {
println!("Joining output");
match handle.join() {
Ok(_) => println!("Output thread stopped"),
Err(_) => println!("Could not join the output thread"),
};
}
None => (),
}
match self.handle_error.take() {
Some(handle) => {
println!("Joining error");
match handle.join() {
Ok(_) => println!("Input thread stopped"),
Err(_) => println!("Could not join the error thread"),
};
}
None => (),
}
}
} // Drop
/// Collect all the stdout/stderr of a process and place it in the channel sender it has recived
/// It's meant to be executed by a thread
// TODO: mange errors
fn gather_output<T: Read>(std: T, pipes_send: Arc<Mutex<Vec<mpsc::Sender<String>>>>) {
for line in BufReader::new(std).lines() {
// Catching all lines
match line {
// Managing if there was a problem reading a line
Err(_) => (), // TODO: manage this possible error
Ok(l) => {
match pipes_send.lock() {
Err(e) => panic!("Cant' get lock: {}", e),
Ok(mut pipes) => {
let mut erase: Vec<usize> = Vec::new();
for i in 0..pipes.len() {
match pipes[i].send(l.clone()) {
Ok(_) => (),
Err(e) => {
erase.push(i);
}
};
}
for i in erase {
pipes.remove(i);
}
}
};
}
};
} // end for
}
/// Recieve all the input that has to be feed to the stdin of the process via a mpsc::Reciever
/// It's meant to be executed by a thread
fn send_input(
mut stdin: ChildStdin,
in_recieve: mpsc::Receiver<String>,
is_alive: Arc<Mutex<bool>>,
) {
loop {
match in_recieve.try_recv() {
Ok(recieved) => {
match stdin.write_all(recieved.as_bytes()) {
// TODO: need to manages errors
Err(_) => (),
Ok(_) => (),
};
}
Err(e) => {
// Exit the loop if the other end of the channel hab been closed
if e == mpsc::TryRecvError::Disconnected {
break;
};
} // TODO: manage errors
}
// Check if the process is alive
// Checking if the reciving pipe is open is not enought because the recieving pipe isn't always closed
match is_alive.try_lock() {
Err(_) => (),
Ok(is_alive) => {
if !*is_alive {
break;
}
}
}
// Don't want to overcumber the system with too many requests
thread::sleep(Duration::from_millis(MILLISEC_PAUSE));
} // loop
} // send_input
////////////////////////////////////////////////////////////////////////////////////////////////////
// Tests
////////////////////////////////////////////////////////////////////////////////////////////////////
/*#[cfg(test)]
mod test {
use super::*;
// Test over a program that repeat int's input
#[test]
fn parrot_test() {
let cmd = String::from("./parrot");
let mut rn = RunningProcess::new(cmd, None).unwrap();
// Words to feed to the parrot
let mut parrot_words: Vec<String> = vec![String::from("hello"), String::from("ciao")];
parrot_words.push(String::from("stop")); // key word to stop the parrot
// Sending some words to the parrot
let parrot_ear = rn.stdin.take().unwrap();
for word in parrot_words.clone() {
match parrot_ear.send(format!("{}\r\n", word)) {
Err(e) => println!("Sending error: {}", e),
Ok(_) => (),
};
}
// Recieving and checking the parrots output
let mut i = 0;
let parrot_voice = rn.stdout.take().unwrap();
for recieved in parrot_voice {
assert_eq!(recieved, parrot_words[i]);
i = i + 1;
}
} // parrot_test
#[test]
fn echo_test() {
// echo comands
let cmd = String::from("echo");
// echo args
let mut args: Vec<String> = Vec::new();
args.push(String::from("hello"));
args.push(String::from("world"));
let mut rn = RunningProcess::new(cmd, Some(args)).unwrap();
let reciever = rn.stdout.take().unwrap();
for recieved in reciever {
assert_eq!(String::from("hello world"), recieved);
}
} // echo_test
} // Tests
*/
|
{
let result = self.process.wait();
// Need to update is alive for the stdin
// TODO: bad panic
match self.is_alive.lock() {
Err(e) => panic!("Can't lock: {}", e),
Ok(mut guard) => *guard = false,
};
result
}
|
distfit.py
|
import scipy.stats as stats
import numpy as np
import warnings
from ecdfgof import adtest, kstest
warnings.filterwarnings("ignore")
_long = [
("alpha", stats.alpha),
("anglit", stats.anglit),
("arcsine", stats.arcsine),
("argus", stats.argus),
("beta", stats.beta),
("betaprime", stats.betaprime),
("bradford", stats.bradford),
("burr", stats.burr),
("burr12", stats.burr12),
("cauchy", stats.cauchy),
("chi", stats.chi),
("chi2", stats.chi2),
("cosine", stats.cosine),
("crystalball", stats.crystalball),
("dgamma", stats.dgamma),
("dweibull", stats.dweibull),
# ("erlang", stats.erlang),
("expon", stats.expon),
("exponnorm", stats.exponnorm),
("exponweib", stats.exponweib),
("exponpow", stats.exponpow),
("f", stats.f),
("fatiguelife", stats.fatiguelife),
("fisk", stats.fisk),
("foldcauchy", stats.foldcauchy),
("foldnorm", stats.foldnorm),
# ("frechet_r", stats.frechet_r),
# ("frechet_l", stats.frechet_l),
("genlogistic", stats.genlogistic),
("gennorm", stats.gennorm),
("genpareto", stats.genpareto),
("genexpon", stats.genexpon),
("genextreme", stats.genextreme),
("gausshyper", stats.gausshyper),
("gamma", stats.gamma),
("gengamma", stats.gengamma),
("genhalflogistic", stats.genhalflogistic),
("gilbrat", stats.gilbrat),
("gompertz", stats.gompertz),
("gumbel_r", stats.gumbel_r),
("gumbel_l", stats.gumbel_l),
("halfcauchy", stats.halfcauchy),
("halflogistic", stats.halflogistic),
|
("halfnorm", stats.halfnorm),
("halfgennorm", stats.halfgennorm),
("hypsecant", stats.hypsecant),
("invgamma", stats.invgamma),
("invgauss", stats.invgauss),
("invweibull", stats.invweibull),
("johnsonsb", stats.johnsonsb),
("johnsonsu", stats.johnsonsu),
("kappa4", stats.kappa4),
("kappa3", stats.kappa3),
("ksone", stats.ksone),
("kstwobign", stats.kstwobign),
("laplace", stats.laplace),
("levy", stats.levy),
("levy_l", stats.levy_l),
("levy_stable", stats.levy_stable),
("logistic", stats.logistic),
("loggamma", stats.loggamma),
("loglaplace", stats.loglaplace),
("lognorm", stats.lognorm),
("lomax", stats.lomax),
("maxwell", stats.maxwell),
("mielke", stats.mielke),
("moyal", stats.moyal),
("nakagami", stats.nakagami),
("ncx2", stats.ncx2),
("ncf", stats.ncf),
("nct", stats.nct),
("norm", stats.norm),
("norminvgauss", stats.norminvgauss),
("pareto", stats.pareto),
("pearson3", stats.pearson3),
("powerlaw", stats.powerlaw),
("powerlognorm", stats.powerlognorm),
("powernorm", stats.powernorm),
# ("rdist", stats.rdist),
# ("reciprocal", stats.reciprocal),
("rayleigh", stats.rayleigh),
("rice", stats.rice),
("recipinvgauss", stats.recipinvgauss),
("semicircular", stats.semicircular),
("skewnorm", stats.skewnorm),
("t", stats.t),
("trapz", stats.trapz),
("triang", stats.triang),
("truncexpon", stats.truncexpon),
# ("truncnorm", stats.truncnorm),
("tukeylambda", stats.tukeylambda),
("uniform", stats.uniform),
# ("vonmises", stats.vonmises),
("vonmises_line", stats.vonmises_line),
("wald", stats.wald),
("weibull_min", stats.weibull_min),
("weibull_max", stats.weibull_max),
# ("wrapcauchy", stats.wrapcauchy),
]
_short = [
("alpha", stats.alpha),
("beta", stats.beta),
("cauchy", stats.cauchy),
("chi2", stats.chi2),
# ("cosine", stats.cosine),
("expon", stats.expon),
("exponnorm", stats.exponnorm),
("f", stats.f),
("gamma", stats.gamma),
("laplace", stats.laplace),
("levy", stats.levy),
("levy_stable", stats.levy_stable),
("logistic", stats.logistic),
("loggamma", stats.loggamma),
("loglaplace", stats.loglaplace),
("lognorm", stats.lognorm),
("norm", stats.norm),
("pareto", stats.pareto),
("powerlaw", stats.powerlaw),
("t", stats.t),
("triang", stats.triang),
("uniform", stats.uniform),
("weibull_min", stats.weibull_min),
("weibull_max", stats.weibull_max),
]
def fit(data, scipydist, name=None):
# fit distribution using maximum likelihood
params = scipydist.fit(data)
# create a "frozen" distribution object
dist = scipydist(*params)
# calculate log likelihood function and info criteria
loglike = dist.logpdf(data).sum()
bic = np.log(len(data)) * len(params) - 2.0 * loglike # Schwarz
aic = 2.0 * len(params) - 2.0 * loglike # Akaike
# p-values for GOF tests
ad_pval = adtest(data, dist)[1] # Anderson-Darling
ks_pval = kstest(data, dist)[1] # Kolmogorov-Smirnov
return {"bic": bic, "aic": aic, "ad_pval": ad_pval,
"ks_pval": ks_pval, "dist": dist, "name": name}
def _fit_all(data, dist_list):
results = list(map(lambda x: fit(data, x[1], x[0]), dist_list))
return sorted(results, key=lambda r: r["bic"]) # lowest BIC to highest
def _fstr(value):
return ("%.3f" % value).rjust(8)
def _result_line(r, header=False):
if header is True:
return " distribution, BIC, AIC, KS p-val, AD p-val\n"
else:
return ("%s, %s, %s, %s, %s\n" %
(r["name"].rjust(15), _fstr(r["bic"]), _fstr(r["aic"]),
_fstr(r["ks_pval"]), _fstr(r["ad_pval"])))
def compare(data, long=False):
dist_list = _long if long is True else _short
results = _fit_all(data, dist_list)
lines = [_result_line(None, header=True)] + list(map(_result_line, results))
return "".join(lines)
| |
state.rs
|
//! Small tracked parts of the application state. Includes [**window**](mod.window.html),
//! [**keys**](mod.keys.html), [**mouse**](mod.mouse.html), [**time**](mod.mouse.html) - each of
//! which are stored in the **App**.
pub use self::keys::Keys;
pub use self::mouse::Mouse;
pub use self::time::Time;
pub use self::window::Window;
/// Tracked state related to the focused window.
pub mod window {
use crate::geom;
use crate::window;
/// The default scalar value used for window positioning and sizing.
pub type DefaultScalar = geom::scalar::Default;
/// State of the window in focus.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Window {
/// ID of the window currently in focus.
pub id: Option<window::Id>,
}
impl Window {
/// Initialise the window state.
pub fn new() -> Self {
Window { id: None }
}
/// Expects that there will be a `window::Id` (the common case) and **panic!**s otherwise.
pub fn id(&self) -> window::Id {
self.id.unwrap()
}
}
}
/// Tracked state related to the keyboard.
pub mod keys {
use crate::event::{Key, ModifiersState};
use std::collections::HashSet;
use std::ops::Deref;
/// The state of the keyboard.
#[derive(Clone, Debug, Default)]
pub struct Keys {
/// The state of the modifier keys as last indicated by winit.
pub mods: ModifiersState,
/// The state of all keys as tracked via the nannou App event handling.
pub down: Down,
}
/// The set of keys that are currently pressed.
#[derive(Clone, Debug, Default)]
pub struct Down {
pub(crate) keys: HashSet<Key>,
}
impl Deref for Down {
type Target = HashSet<Key>;
fn deref(&self) -> &Self::Target {
&self.keys
}
}
}
/// Tracked state related to the mouse.
pub mod mouse {
use crate::geom::{self, Point2};
use crate::math::BaseFloat;
use crate::window;
use std;
/// The default scalar value used for positions.
pub type DefaultScalar = geom::scalar::Default;
#[doc(inline)]
pub use crate::event::MouseButton as Button;
/// The max total number of buttons on a mouse.
pub const NUM_BUTTONS: usize = 9;
/// The state of the `Mouse` at a single moment in time.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Mouse<S = DefaultScalar> {
/// The ID of the last window currently in focus.
pub window: Option<window::Id>,
/// *x* position relative to the middle of `window`.
pub x: S,
/// *y* position relative to the middle of `window`.
pub y: S,
/// A map describing the state of each mouse button.
pub buttons: ButtonMap,
}
/// Whether the button is up or down.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum ButtonPosition<S = DefaultScalar> {
/// The button is up (i.e. pressed).
Up,
/// The button is down and was originally pressed down at the given `Point2`.
Down(Point2<S>),
}
/// Stores the state of all mouse buttons.
///
/// If the mouse button is down, it stores the position of the mouse when the button was pressed
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct ButtonMap<S = DefaultScalar> {
buttons: [ButtonPosition<S>; NUM_BUTTONS],
}
/// An iterator yielding all pressed buttons.
#[derive(Clone)]
pub struct PressedButtons<'a, S: 'a = DefaultScalar> {
buttons: std::iter::Enumerate<std::slice::Iter<'a, ButtonPosition<S>>>,
}
impl<S> Mouse<S>
where
S: BaseFloat,
{
/// Construct a new default `Mouse`.
pub fn new() -> Self {
Mouse {
window: None,
buttons: ButtonMap::new(),
x: S::zero(),
y: S::zero(),
}
}
/// The position of the mouse relative to the middle of the window in focus..
pub fn position(&self) -> Point2<S> {
Point2 {
x: self.x,
y: self.y,
}
}
}
impl<S> ButtonPosition<S>
where
S: BaseFloat,
{
/// If the mouse button is down, return a new one with position relative to the given `xy`.
pub fn relative_to(self, xy: Point2<S>) -> Self {
match self {
ButtonPosition::Down(pos) => {
let rel_p = pos - xy;
ButtonPosition::Down(Point2 {
x: rel_p.x,
y: rel_p.y,
})
}
button_pos => button_pos,
}
}
/// Is the `ButtonPosition` down.
pub fn is_down(&self) -> bool {
match *self {
ButtonPosition::Down(_) => true,
_ => false,
}
}
/// Is the `ButtonPosition` up.
pub fn
|
(&self) -> bool {
match *self {
ButtonPosition::Up => true,
_ => false,
}
}
/// Returns the position at which the button was pressed.
pub fn if_down(&self) -> Option<Point2<S>> {
match *self {
ButtonPosition::Down(xy) => Some(xy),
_ => None,
}
}
}
impl<S> ButtonMap<S>
where
S: BaseFloat,
{
/// Returns a new button map with all states set to `None`
pub fn new() -> Self {
ButtonMap {
buttons: [ButtonPosition::Up; NUM_BUTTONS],
}
}
/// Returns a copy of the ButtonMap relative to the given `Point`
pub fn relative_to(self, xy: Point2<S>) -> Self {
self.buttons
.iter()
.enumerate()
.fold(ButtonMap::new(), |mut map, (idx, button_pos)| {
map.buttons[idx] = button_pos.relative_to(xy);
map
})
}
/// The state of the left mouse button.
pub fn left(&self) -> &ButtonPosition<S> {
&self[Button::Left]
}
/// The state of the middle mouse button.
pub fn middle(&self) -> &ButtonPosition<S> {
&self[Button::Middle]
}
/// The state of the right mouse button.
pub fn right(&self) -> &ButtonPosition<S> {
&self[Button::Right]
}
/// Sets the `Button` in the `Down` position.
pub fn press(&mut self, button: Button, xy: Point2<S>) {
self.buttons[button_to_idx(button)] = ButtonPosition::Down(xy);
}
/// Set's the `Button` in the `Up` position.
pub fn release(&mut self, button: Button) {
self.buttons[button_to_idx(button)] = ButtonPosition::Up;
}
/// An iterator yielding all pressed mouse buttons along with the location at which they
/// were originally pressed.
pub fn pressed(&self) -> PressedButtons<S> {
PressedButtons {
buttons: self.buttons.iter().enumerate(),
}
}
}
impl<S> std::ops::Index<Button> for ButtonMap<S> {
type Output = ButtonPosition<S>;
fn index(&self, button: Button) -> &Self::Output {
&self.buttons[button_to_idx(button)]
}
}
impl<'a, S> Iterator for PressedButtons<'a, S>
where
S: BaseFloat,
{
type Item = (Button, Point2<S>);
fn next(&mut self) -> Option<Self::Item> {
while let Some((idx, button_pos)) = self.buttons.next() {
if let ButtonPosition::Down(xy) = *button_pos {
return Some((idx_to_button(idx), xy));
}
}
None
}
}
fn idx_to_button(i: usize) -> Button {
match i {
n @ 0..=5 => Button::Other(n as u8),
6 => Button::Left,
7 => Button::Right,
8 => Button::Middle,
_ => Button::Other(std::u8::MAX),
}
}
fn button_to_idx(button: Button) -> usize {
match button {
Button::Other(n) => n as usize,
Button::Left => 6,
Button::Right => 7,
Button::Middle => 8,
}
}
}
/// Tracked durations related to the App.
pub mod time {
/// The state of time tracked by the App.
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Hash)]
pub struct Time {
/// The duration since the app started running.
pub since_start: std::time::Duration,
/// The duration since the previous update.
pub since_prev_update: std::time::Duration,
}
impl Time {
/// The number of updates per second if `since_prev_update` were to remain constant
pub fn updates_per_second(&self) -> f32 {
if self.since_prev_update.as_secs() > 0 {
return 0.0;
}
let millis = self.since_prev_update.subsec_millis() as f32;
if millis == 0.0 {
return std::f32::MAX;
}
1000.0 / millis
}
}
}
|
is_up
|
lib.rs
|
//! Traits for wrapping up signed and/or time-bound objects
//!
//! # Overview
//!
//! Frequently (for testing reasons or otherwise), we want to ensure
//! that an object can only be used if a signature is valid, or if
//! some timestamp is recent enough.
//!
//! As an example, consider a self-signed cretificate. You can parse
//! it cheaply enough (and find its key by doing so), but you probably
//! want to make sure that nobody will use that certificate unless its
//! signature is correct and its timestamps are not expired.
//!
//! With the tor-checkable crate, you can instead return an object
//! that represents the certificate in its unchecked state. The
//! caller can access the certificate, but only after checking the
//! signature and the time.
//!
//! This crate is part of
//! [Arti](https://gitlab.torproject.org/tpo/core/arti/), a project to
//! implement [Tor](https://www.torproject.org/) in Rust.
//! Many other crates in Arti depend on it, but it should be generally
//! useful outside of Arti.
//!
//! ## Design notes and alternatives
//!
//! The types in this crate provide functions to return the underlying
//! objects without checking them. This is very convenient for testing,
//! though you wouldn't want to do it in production code. To prevent
//! mistakes, these functions all begin with the word `dangerously`.
//!
//! Another approach you might take is to put signature and timeliness
//! checks inside your parsing function. But if you do that, it will
//! get hard to test your code: you will only be able to parse
//! certificates that are valid when the parser is running. And if
//! you want to test parsing a new kind of certificate, you'll need to
//! make sure to put a valid signature on it. (And all of this
//! signature parsing will slow down any attempts to fuzz your
//! parser.)
//!
//! You could have your parser take a flag to tell it whether to check
//! signatures and timeliness, but that could be error prone: if anybody
//! sets the flag wrong, they will skip doing the checks.
#![deny(missing_docs)]
#![warn(noop_method_call)]
#![deny(unreachable_pub)]
#![deny(clippy::await_holding_lock)]
#![deny(clippy::cargo_common_metadata)]
#![warn(clippy::clone_on_ref_ptr)]
#![warn(clippy::cognitive_complexity)]
#![deny(clippy::debug_assert_with_mut_call)]
#![deny(clippy::exhaustive_enums)]
#![deny(clippy::exhaustive_structs)]
#![deny(clippy::expl_impl_clone_on_copy)]
#![deny(clippy::fallible_impl_from)]
#![deny(clippy::large_stack_arrays)]
#![warn(clippy::manual_ok_or)]
#![deny(clippy::missing_docs_in_private_items)]
#![warn(clippy::needless_borrow)]
#![warn(clippy::needless_pass_by_value)]
#![warn(clippy::option_option)]
#![warn(clippy::rc_buffer)]
#![deny(clippy::ref_option_ref)]
#![warn(clippy::trait_duplication_in_bounds)]
#![warn(clippy::unseparated_literal_suffix)]
use std::time;
use thiserror::Error;
pub mod signed;
pub mod timed;
/// An error that can occur when checking whether a Timebound object is
/// currently valid.
#[derive(Debug, Clone, Error, PartialEq, Eq)]
#[non_exhaustive]
pub enum TimeValidityError {
/// The object is not yet valid
#[error("will not be valid for {0:?}")]
NotYetValid(time::Duration),
/// The object is expired
#[error("has been expired for {0:?}")]
Expired(time::Duration),
/// The object isn't timely, and we don't know why, or won't say.
#[error("is not currently valid")]
Unspecified,
}
/// A Timebound object is one that is only valid for a given range of time.
///
/// It's better to wrap things in a TimeBound than to give them an is_valid()
/// valid method, so that you can make sure that nobody uses the object before
/// checking it.
pub trait Timebound<T>: Sized {
/// An error type that's returned when the object is _not_ timely.
type Error;
/// Check whether this object is valid at a given time.
///
/// Return Ok if the object is valid, and an error if the object is not.
fn is_valid_at(&self, t: &time::SystemTime) -> Result<(), Self::Error>;
/// Return the underlying object without checking whether it's valid.
fn dangerously_assume_timely(self) -> T;
/// Unwrap this Timebound object if it is valid at a given time.
fn check_valid_at(self, t: &time::SystemTime) -> Result<T, Self::Error> {
self.is_valid_at(t)?;
Ok(self.dangerously_assume_timely())
}
/// Unwrap this Timebound object if it is valid now.
fn check_valid_now(self) -> Result<T, Self::Error> {
self.check_valid_at(&time::SystemTime::now())
}
/// Unwrap this object if it is valid at the provided time t.
/// If no time is provided, check the object at the current time.
fn check_valid_at_opt(self, t: Option<time::SystemTime>) -> Result<T, Self::Error> {
match t {
Some(when) => self.check_valid_at(&when),
None => self.check_valid_now(),
}
}
}
/// A cryptographically signed object that can be validated without
/// additional public keys.
///
/// It's better to wrap things in a SelfSigned than to give them an is_valid()
/// method, so that you can make sure that nobody uses the object before
/// checking it. It's better to wrap things in a SelfSigned than to check
/// them immediately, since you might want to defer the signature checking
/// operation to another thread.
pub trait SelfSigned<T>: Sized {
/// An error type that's returned when the object is _not_ well-signed.
type Error;
/// Check the signature on this object
fn is_well_signed(&self) -> Result<(), Self::Error>;
/// Return the underlying object without checking its signature.
fn dangerously_assume_wellsigned(self) -> T;
/// Unwrap this object if the signature is valid
fn check_signature(self) -> Result<T, Self::Error> {
self.is_well_signed()?;
Ok(self.dangerously_assume_wellsigned())
}
}
/// A cryptographically signed object that needs an external public
/// key to validate it.
pub trait ExternallySigned<T>: Sized {
/// The type of the public key object.
///
/// You can use a tuple or a vector here if the object is signed
/// with multiple keys.
type Key: ?Sized;
/// A type that describes what keys are missing for this object.
type KeyHint;
/// An error type that's returned when the object is _not_ well-signed.
type Error;
/// Check whether k is the right key for this object. If not, return
/// an error describing what key would be right.
///
/// This function is allowed to return 'true' for a bad key, but never
/// 'false' for a good key.
fn key_is_correct(&self, k: &Self::Key) -> Result<(), Self::KeyHint>;
/// Check the signature on this object
fn is_well_signed(&self, k: &Self::Key) -> Result<(), Self::Error>;
/// Unwrap this object without checking any signatures on it.
fn dangerously_assume_wellsigned(self) -> T;
/// Unwrap this object if it's correctly signed by a provided key.
fn
|
(self, k: &Self::Key) -> Result<T, Self::Error> {
self.is_well_signed(k)?;
Ok(self.dangerously_assume_wellsigned())
}
}
|
check_signature
|
problem011_test.go
|
package problem011
import (
"testing"
)
func Test_case(t *testing.T) {
res, _ := Pow(0, 0)
if res == 1 {
t.Log("Pass")
} else {
t.Error("Failed")
}
res, _ = Pow(2, -1)
if res == 0.5 {
t.Log("Pass")
} else {
t.Error("Failed value: ")
}
res, _ = Pow(2, 3)
if res == 8 {
t.Log("Pass")
} else {
t.Error("Failed")
}
res, _ = Pow(2, -2)
if res == 0.25 {
t.Log("Pass")
} else {
t.Error("Failed")
}
|
t.Log("Pass")
} else {
t.Error("Failed")
}
}
|
res, err := Pow(0, -2)
if err != nil {
|
util.py
|
'''
Utility functions.
'''
import argparse
import functools
import itertools
import os
import sqlite3 as sql
from contextlib import closing
from copy import deepcopy
from itertools import repeat
import numpy as np
import pandas as pd
import scipy as sp
import scipy.fftpack
import scipy.signal
from cnld import abstract
from scipy.spatial.distance import cdist
''' GEOMETRY-RELATED FUNCTIONS '''
def meshview(v1, v2, v3, mode='cartesian', as_list=True):
'''
'''
if mode.lower() in ('cart', 'cartesian'):
x, y, z = np.meshgrid(v1, v2, v3, indexing='ij')
elif mode.lower() in ('sph', 'spherical'):
r, theta, phi = np.meshgrid(v1, np.deg2rad(v2), np.deg2rad(v3), indexing='ij')
x, y, z = sph2cart(r, theta, phi)
elif mode.lower() in ('sec', 'sector'):
r, alpha, beta = np.meshgrid(v1, np.deg2rad(v2), np.deg2rad(v3), indexing='ij')
x, y, z = sec2cart(r, alpha, beta)
elif mode.lower() in ('dp', 'dpolar'):
r, alpha, beta = np.meshgrid(v1, np.deg2rad(v2), np.deg2rad(v3), indexing='ij')
x, y, z = dp2cart(r, alpha, beta)
if as_list:
return np.c_[x.ravel('F'), y.ravel('F'), z.ravel('F')]
else:
return x, y, z
def sec2cart(r, alpha, beta):
'''
'''
z = r / np.sqrt(np.tan(alpha)**2 + np.tan(beta)**2 + 1)
x = z * np.tan(alpha)
y = z * np.tan(beta)
# alpha_p = np.arctan(np.tan(alpha) * np.cos(beta))
# x = np.sin(alpha_p) * r
# y = -np.sin(beta) * r * np.cos(alpha_p)
# z = np.sqrt(r**2 - x**2 - y**2)
# px = -px
# pyp = np.arctan(np.cos(px) * np.sin(py) / np.cos(py))
# x = r * np.sin(pyp)
# y = -r * np.cos(pyp) * np.sin(px)
# z = r * np.cos(px) * np.cos(pyp)
return x, y, z
def cart2sec(x, y, z):
'''
'''
r = np.sqrt(x**2 + y**2 + z**2)
alpha = np.arccos(z / (np.sqrt(x**2 + z**2))) * np.sign(x)
beta = np.arccos(z / (np.sqrt(y**2 + z**2))) * np.sign(y)
# r = np.sqrt(x**2 + y**2 + z**2)
# alpha_p = np.arcsin(x / r)
# beta = -np.arcsin(-y / r / np.cos(alpha_p))
# alpha = np.arctan(np.tan(alpha_p) / np.cos(beta))
return r, alpha, beta
def sph2cart(r, theta, phi):
'''
'''
x = r * np.cos(theta) * np.sin(phi)
y = r * np.sin(theta) * np.sin(phi)
z = r * np.cos(phi)
return x, y, z
def cart2sph(x, y, z):
'''
'''
r = np.sqrt(x**2 + y**2 + z**2)
theta = np.arctan(y / x)
phi = np.arccos(z / r)
return r, theta, phi
def cart2dp(x, y, z):
'''
'''
r = np.sqrt(x**2 + y**2 + z**2)
alpha = np.arccos((np.sqrt(y**2 + z**2) / r))
beta = np.arccos((np.sqrt(x**2 + z**2) / r))
return r, alpha, beta
def dp2cart(r, alpha, beta):
'''
'''
z = r * (1 - np.sin(alpha)**2 - np.sin(beta)**2)
x = r * np.sin(alpha)
y = r * np.sin(beta)
return x, y, z
def rotation_matrix(vec, angle):
'''
'''
if isinstance(vec, str):
string = vec.lower()
if string == 'x':
vec = [1, 0, 0]
elif string == '-x':
vec = [-1, 0, 0]
elif string == 'y':
vec = [0, 1, 0]
elif string == '-y':
vec = [0, -1, 0]
elif string == 'z':
vec = [0, 0, 1]
elif string == '-x':
vec = [0, 0, -1]
x, y, z = vec
a = angle
r = np.zeros((3, 3))
r[0, 0] = np.cos(a) + x**2 * (1 - np.cos(a))
r[0, 1] = x * y * (1 - np.cos(a)) - z * np.sin(a)
r[0, 2] = x * z * (1 - np.cos(a)) + y * np.sin(a)
r[1, 0] = y * x * (1 - np.cos(a)) + z * np.sin(a)
r[1, 1] = np.cos(a) + y**2 * (1 - np.cos(a))
r[1, 2] = y * z * (1 - np.cos(a)) - x * np.sin(a)
r[2, 0] = z * x * (1 - np.cos(a)) - z * np.sin(a)
r[2, 1] = z * y * (1 - np.cos(a)) + x * np.sin(a)
r[2, 2] = np.cos(a) + z**2 * (1 - np.cos(a))
return r
def rotate_nodes(nodes, vec, angle):
'''
'''
rmatrix = rotation_matrix(vec, angle)
return rmatrix.dot(nodes.T).T
def distance(*args):
'''
'''
return cdist(*np.atleast_2d(*args))
''' SIGNAL PROCESSING AND RF DATA FUNCTIONS '''
def gausspulse(fc, fbw, fs):
'''
'''
cutoff = scipy.signal.gausspulse('cutoff', fc=fc, bw=fbw, tpr=-100, bwr=-3)
adj_cutoff = np.ceil(cutoff * fs) / fs
t = np.arange(-adj_cutoff, adj_cutoff + 1 / fs, 1 / fs)
pulse, _ = sp.signal.gausspulse(t, fc=fc, bw=fbw, retquad=True, bwr=-3)
return pulse, t
def nextpow2(n):
'''
'''
return 2**int(np.ceil(np.log2(n)))
def envelope(rf_data, N=None, axis=-1):
'''
'''
return np.abs(scipy.signal.hilbert(np.atleast_2d(rf_data), N, axis=axis))
def qbutter(x, fn, fs=1, btype='lowpass', n=4, plot=False, axis=-1):
'''
'''
wn = fn / (fs / 2.)
b, a = sp.signal.butter(n, wn, btype)
fx = sp.signal.lfilter(b, a, x, axis=axis)
return fx
def qfirwin(x,
fn,
fs=1,
btype='lowpass',
ntaps=80,
plot=False,
axis=-1,
window='hamming'):
'''
'''
if btype.lower() in ('lowpass', 'low'):
pass_zero = 1
elif btype.lower() in ('bandpass', 'band'):
pass_zero = 0
elif btype.lower() in ('highpass', 'high'):
pass_zero = 0
wn = fn / (fs / 2.)
b = sp.signal.firwin(ntaps, wn, pass_zero=pass_zero, window=window)
fx = np.apply_along_axis(lambda x: np.convolve(x, b), axis, x)
return fx
def qfft(s, nfft=None, fs=1, dr=100, fig=None, **kwargs):
'''
Quick FFT plot. Returns frequency bins and FFT in dB.
'''
s = np.atleast_2d(s)
nsig, nsample = s.shape
if nfft is None:
nfft = nsample
# if fig is None:
# fig = plt.figure(tight_layout=1)
# ax = fig.add_subplot(111)
# else:
# ax = fig.get_axes()[0]
if nfft > nsample:
s = np.pad(s, ((0, 0), (0, nfft - nsample)), mode='constant')
elif nfft < nsample:
s = s[:, :nfft]
ft = sp.fftpack.fft(s, axis=1)
freqs = sp.fftpack.fftfreq(nfft, 1 / fs)
ftdb = 20 * np.log10(np.abs(ft) / (np.max(np.abs(ft), axis=1)[..., None]))
ftdb[ftdb < -dr] = -dr
cutoff = (nfft + 1) // 2
# ax.plot(freqs[:cutoff], ftdb[:, :cutoff].T, **kwargs)
# ax.set_xlabel('Frequency (Hz)')
# ax.set_ylabel('Magnitude (dB re max)')
# fig.show()
return freqs[:cutoff], ftdb[:, :cutoff]
''' JOB-RELATED FUNCTIONS '''
def chunks(iterable, n):
res = []
for el in iterable:
res.append(el)
if len(res) == n:
yield res
res = []
if res:
yield res
def create_jobs(*args, mode='zip', is_complete=None):
'''
Convenience function for creating jobs (sets of input arguments) for
multiprocessing Pool. Supports zip and product combinations, and automatic chunking
of iterables.
'''
static_args = list()
static_idx = list()
iterable_args = list()
iterable_idx = list()
for arg_no, arg in enumerate(args):
if isinstance(arg, (tuple, list)):
iterable, chunksize = arg
if chunksize == 1:
iterable_args.append(iterable)
else:
iterable_args.append(chunks(iterable, chunksize))
iterable_idx.append(arg_no)
else:
static_args.append(itertools.repeat(arg))
static_idx.append(arg_no)
if not iterable_args and not static_args:
return
if not iterable_args:
yield 1, tuple(args[i] for i in static_idx)
if not static_args:
repeats = itertools.repeat(())
else:
repeats = zip(*static_args)
if mode.lower() == 'product':
combos = itertools.product(*iterable_args)
elif mode.lower() == 'zip':
combos = zip(*iterable_args)
elif mode.lower() == 'zip_longest':
combos = itertools.zip_longest(*iterable_args)
for job_id, (r, p) in enumerate(zip(repeats, combos)):
# skip jobs that have been completed
if is_complete is not None and is_complete[job_id]:
continue
res = r + p
# reorder vals according to input order
yield job_id + 1, tuple(res[i] for i in np.argsort(static_idx + iterable_idx))
''' DATABASE FUNCTIONS '''
def open_db(f):
def decorator(firstarg, *args, **kwargs):
if isinstance(firstarg, sql.Connection):
return f(firstarg, *args, **kwargs)
else:
# if os.path.isfile(firstarg):
with closing(sql.connect(firstarg)) as con:
return f(con, *args, **kwargs)
# else:
# raise IOError
return decorator
def read_db(f):
def decorator(firstarg, *args, **kwargs):
if isinstance(firstarg, sql.Connection):
return f(firstarg, *args, **kwargs)
else:
if os.path.isfile(firstarg):
with closing(sql.connect(firstarg)) as con:
return f(con, *args, **kwargs)
else:
raise IOError('File does not exist')
return decorator
@open_db
def table_exists(con, name):
query = '''SELECT count(*) FROM sqlite_master WHERE type='table' and name=?'''
return con.execute(query, (name, )).fetchone()[0] != 0
@open_db
def create_metadata_table(con, **kwargs):
table = [[str(v) for v in list(kwargs.values())]]
columns = list(kwargs.keys())
pd.DataFrame(table, columns=columns, dtype=str).to_sql('metadata',
con,
if_exists='replace',
index=False)
@open_db
def create_progress_table(con, njobs):
with con:
# create table
con.execute(
'CREATE TABLE progress (job_id INTEGER PRIMARY KEY, is_complete boolean)')
# insert values
con.executemany('INSERT INTO progress (is_complete) VALUES (?)',
repeat((False, ), njobs))
@open_db
def get_progress(con):
table = pd.read_sql('SELECT is_complete FROM progress ORDER BY job_id', con)
is_complete = np.array(table).squeeze()
ijob = sum(is_complete) + 1
return is_complete, ijob
@open_db
def update_progress(con, job_id):
with con:
con.execute('UPDATE progress SET is_complete=1 WHERE job_id=?', [
job_id,
])
''' SCRIPTING FUNCTIONS '''
def script_parser(main, config_def):
'''
General script command-line interface with 'config' and 'run' subcommands.
'''
if isinstance(config_def, dict):
# create config abstract type based on supplied dict
Config = abstract.register_type('Config', config_def)
else:
# config abstract type already defined
Config = config_def
# config subcommand generates a default configuration template
def config(args):
if args.file:
abstract.dump(Config(), args.file)
else:
print(Config())
# run subcommand will load the config file and pass to main
def run(args):
if args.config:
cfg = Config(**abstract.load(args.config))
else:
cfg = Config()
return main(cfg, args)
# create argument parser
parser = argparse.ArgumentParser()
# define config subparser
subparsers = parser.add_subparsers(help='sub-command help')
config_parser = subparsers.add_parser('config', help='config_help')
config_parser.add_argument('-f', '--file', nargs='?')
config_parser.set_defaults(func=config)
# define run subparser
run_parser = subparsers.add_parser('run', help='run_help')
run_parser.add_argument('config', nargs='?')
run_parser.add_argument('-f', '--file', nargs='?')
run_parser.add_argument('-t', '--threads', nargs='?', type=int)
run_parser.add_argument('-w', '--write-over', action='store_true')
run_parser.set_defaults(func=run)
return parser, run_parser
def script_parser2(main, config_def):
'''
General script command-line interface with 'config' and 'run' subcommands.
'''
if isinstance(config_def, dict):
# create config abstract type based on supplied dict
Config = abstract.register_type('Config', config_def)
else:
# config abstract type already defined
Config = config_def
# run
def run(args):
if args.show_config:
|
if args.generate_config:
abstract.dump(Config(), args.generate_config)
return
if args.file:
if args.config:
cfg = Config(**abstract.load(args.config))
else:
cfg = Config()
return main(cfg, args)
# create argument parser
parser = argparse.ArgumentParser()
parser.add_argument('-g', '--generate-config')
parser.add_argument('-s', '--show-config', action='store_true')
parser.add_argument('file', nargs='?')
parser.add_argument('-c', '--config')
parser.add_argument('-t', '--threads', type=int)
parser.add_argument('-w', '--write-over', action='store_true')
parser.set_defaults(func=run)
return parser
''' MISC FUNCTIONS '''
def memoize_old(func):
'''
Simple memoizer to cache repeated function calls.
'''
def ishashable(obj):
try:
hash(obj)
except TypeError:
return False
return True
def make_hashable(obj):
if not ishashable(obj):
# use tostring on ndarray since str returns truncated output
if isinstance(obj, np.ndarray):
return obj.tostring()
return str(obj)
# round float arguments to avoid round-off error affecting cache
if isinstance(obj, float):
return round(obj, 18)
return obj
memo = {}
@functools.wraps(func)
def decorator(*args, **kwargs):
# key = tuple(make_hashable(a) for a in args)
key = (tuple(make_hashable(a) for a in args),
tuple((k, make_hashable(v)) for k, v in sorted(kwargs.items())))
if key not in memo:
memo[key] = func(*args, **kwargs)
# return a deep copy to avoid issues with mutable return objects
return deepcopy(memo[key])
return decorator
def memoize(func, maxsize=20):
'''
Simple memoizer to cache repeated function calls.
'''
def ishashable(obj):
try:
hash(obj)
except TypeError:
return False
return True
def make_hashable(obj):
if hasattr(obj, '_memoize'):
return obj._memoize()
if not ishashable(obj):
# use tostring on ndarray since str returns truncated output
if isinstance(obj, np.ndarray):
return obj.tostring()
return str(obj)
# round float arguments to avoid round-off error affecting cache
if isinstance(obj, float):
return round(obj, 18)
return obj
func.memo = {}
@functools.wraps(func)
def decorator(*args, **kwargs):
# key = tuple(make_hashable(a) for a in args)
key = (tuple(make_hashable(a) for a in args),
tuple((k, make_hashable(v)) for k, v in sorted(kwargs.items())))
if key not in func.memo:
if len(func.memo) > maxsize:
return func(*args, **kwargs)
else:
func.memo[key] = func(*args, **kwargs)
# return a deep copy to avoid issues with mutable return objects
return deepcopy(func.memo[key])
return decorator
class Counter:
def __init__(self):
self.count = 0
def increment(self, *args, **kwargs):
self.count += 1
def decrement(self, *args, **kwargs):
self.count -= 1
|
print(Config())
return
|
endpoint.py
|
from vivid.common import ParametersMixin
class Endpoint(ParametersMixin, object):
"""
Descriptor that describes an attribute which acts
as a function making an HTTP request. Return a
bound endpoint attached to this and the base API.
"""
def __init__(self, method, path, *parameters):
"""
Save relevant data at init; this includes the
path component of the URL we want, as well as
the HTTP method, and any endpoint-specific vars.
"""
self.method = method
self.path = path
self.parameters = parameters
super(Endpoint, self).__init__()
def __get__(self, instance, _owner):
"""
Return a bound endpoint object tied to both this
object and to the parent BaseApiClient instance.
"""
return BoundEndpoint(self, instance)
class BoundEndpoint(object):
def __init__(self, endpoint, api_instance):
|
def __call__(self, **kwargs):
"""
Handle being called like a function
"""
request = {
'method': self.endpoint.method,
'url': self.full_url
}
request_kwargs = self.get_base_kwargs()
request_kwargs.update(kwargs)
self.apply_parameters(request, request_kwargs)
return self.api_instance.request(request)
def apply_parameters(self, request, request_kwargs):
"""
Apply endpoint- and client-defined parameters to the request
"""
self.api_instance.apply_parameters(request, request_kwargs)
self.endpoint.apply_parameters(request, request_kwargs)
self.finalize(request)
def get_base_kwargs(self):
"""
Get the base kwargs from the instance
"""
return self.api_instance.base_kwargs.copy()
@property
def full_url(self):
"""
Build a complete URL for the bound endpoint
"""
return self.api_instance.root + self.endpoint.path
def finalize(self, request):
"""
Do any followup/cleanup work that any variables requested.
"""
followup_work = request.pop('followup', {})
for item in followup_work.values():
item(request)
|
"""
Store links to both the unbound endpoint and the
API client instance we're bound to
"""
self.endpoint = endpoint
self.api_instance = api_instance
|
Resource_LoadBalancerSubnetSpec.generated_test.go
|
package schemas
import (
"testing"
"github.com/google/go-cmp/cmp"
"k8s.io/kops/pkg/apis/kops"
)
func TestExpandResourceLoadBalancerSubnetSpec(t *testing.T) {
_default := kops.LoadBalancerSubnetSpec{}
type args struct {
in map[string]interface{}
}
tests := []struct {
name string
args args
want kops.LoadBalancerSubnetSpec
}{
{
name: "default",
args: args{
in: map[string]interface{}{
"name": "",
"private_ipv4_address": nil,
"allocation_id": nil,
},
},
want: _default,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := ExpandResourceLoadBalancerSubnetSpec(tt.args.in)
if diff := cmp.Diff(tt.want, got); diff != "" {
t.Errorf("ExpandResourceLoadBalancerSubnetSpec() mismatch (-want +got):\n%s", diff)
}
})
}
}
func TestFlattenResourceLoadBalancerSubnetSpecInto(t *testing.T) {
_default := map[string]interface{}{
"name": "",
"private_ipv4_address": nil,
"allocation_id": nil,
}
type args struct {
in kops.LoadBalancerSubnetSpec
}
tests := []struct {
name string
args args
want map[string]interface{}
}{
{
name: "default",
args: args{
in: kops.LoadBalancerSubnetSpec{},
},
want: _default,
},
{
name: "Name - default",
args: args{
in: func() kops.LoadBalancerSubnetSpec {
subject := kops.LoadBalancerSubnetSpec{}
subject.Name = ""
return subject
}(),
},
want: _default,
},
{
name: "PrivateIpv4Address - default",
args: args{
in: func() kops.LoadBalancerSubnetSpec {
subject := kops.LoadBalancerSubnetSpec{}
subject.PrivateIPv4Address = nil
return subject
}(),
},
want: _default,
},
{
name: "AllocationID - default",
args: args{
in: func() kops.LoadBalancerSubnetSpec {
subject := kops.LoadBalancerSubnetSpec{}
subject.AllocationID = nil
return subject
}(),
},
want: _default,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := map[string]interface{}{}
FlattenResourceLoadBalancerSubnetSpecInto(tt.args.in, got)
if diff := cmp.Diff(tt.want, got); diff != "" {
t.Errorf("FlattenResourceLoadBalancerSubnetSpec() mismatch (-want +got):\n%s", diff)
}
})
}
}
func TestFlattenResourceLoadBalancerSubnetSpec(t *testing.T)
|
{
_default := map[string]interface{}{
"name": "",
"private_ipv4_address": nil,
"allocation_id": nil,
}
type args struct {
in kops.LoadBalancerSubnetSpec
}
tests := []struct {
name string
args args
want map[string]interface{}
}{
{
name: "default",
args: args{
in: kops.LoadBalancerSubnetSpec{},
},
want: _default,
},
{
name: "Name - default",
args: args{
in: func() kops.LoadBalancerSubnetSpec {
subject := kops.LoadBalancerSubnetSpec{}
subject.Name = ""
return subject
}(),
},
want: _default,
},
{
name: "PrivateIpv4Address - default",
args: args{
in: func() kops.LoadBalancerSubnetSpec {
subject := kops.LoadBalancerSubnetSpec{}
subject.PrivateIPv4Address = nil
return subject
}(),
},
want: _default,
},
{
name: "AllocationID - default",
args: args{
in: func() kops.LoadBalancerSubnetSpec {
subject := kops.LoadBalancerSubnetSpec{}
subject.AllocationID = nil
return subject
}(),
},
want: _default,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := FlattenResourceLoadBalancerSubnetSpec(tt.args.in)
if diff := cmp.Diff(tt.want, got); diff != "" {
t.Errorf("FlattenResourceLoadBalancerSubnetSpec() mismatch (-want +got):\n%s", diff)
}
})
}
}
|
|
uuidutil.go
|
// Copyright 2020-2021 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package uuidutil
import (
"fmt"
"github.com/gofrs/uuid"
)
// New returns a new random UUIDv4.
func New() (uuid.UUID, error)
|
// ToDashless returns the uuid without dashes.
func ToDashless(id uuid.UUID) (string, error) {
s := id.String()
if s[8] != '-' {
return "", fmt.Errorf("expected - at char 9: %q", s)
}
if s[13] != '-' {
return "", fmt.Errorf("expected - at char 14: %q", s)
}
if s[18] != '-' {
return "", fmt.Errorf("expected - at char 19: %q", s)
}
if s[23] != '-' {
return "", fmt.Errorf("expected - at char 24: %q", s)
}
return s[0:8] + s[9:13] + s[14:18] + s[19:23] + s[24:], nil
}
// FromString returns the uuid from the string.
//
// As opposed to uuid.FromString, this only accepts uuids with dashes.
// Always use this instead of uuid.FromString.
func FromString(s string) (uuid.UUID, error) {
if len(s) != 36 {
return uuid.Nil, fmt.Errorf("expected uuid to be of length 36 but was %d: %s", len(s), s)
}
return uuid.FromString(s)
}
// FromDashless returns the dashless uuid with dashes.
func FromDashless(dashless string) (uuid.UUID, error) {
if len(dashless) != 32 {
return uuid.Nil, fmt.Errorf("expected dashless uuid to be of length 32 but was %d: %s", len(dashless), dashless)
}
// FromString accepts both dashless and regular, we do this because we need to add our own FromString that does not accept dashless
return FromString(dashless[0:8] + "-" + dashless[8:12] + "-" + dashless[12:16] + "-" + dashless[16:20] + "-" + dashless[20:])
}
// Validate determines if the given UUID string is valid.
func Validate(s string) error {
_, err := FromString(s)
return err
}
// ValidateDashless validates the dashless uuid is valid.
func ValidateDashless(dashless string) error {
_, err := FromDashless(dashless)
return err
}
|
{
id, err := uuid.NewV4()
if err != nil {
return uuid.Nil, err
}
return id, nil
}
|
index.js
|
module.exports =
/******/ (function(modules, runtime) { // webpackBootstrap
/******/ "use strict";
/******/ // 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
/******/ var threw = true;
/******/ try {
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ threw = false;
/******/ } finally {
/******/ if(threw) delete installedModules[moduleId];
/******/ }
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ __webpack_require__.ab = __dirname + "/";
/******/
/******/ // the startup function
/******/ function startup() {
/******/ // Load entry module and return exports
/******/ return __webpack_require__(198);
/******/ };
/******/
/******/ // run startup
/******/ return startup();
/******/ })
/************************************************************************/
/******/ ({
/***/ 5:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"use strict";
/* eslint-disable @typescript-eslint/no-non-null-assertion */
/**
* Spawns git blame and parses results into JSON, via stream (so, no problem on huge files)
*/
Object.defineProperty(exports, "__esModule", { value: true });
const child_process_1 = __webpack_require__(129);
const readline_1 = __webpack_require__(58);
const camel_case_1 = __webpack_require__(947);
async function blame(filename, options = {}, gitPath = 'git') {
var _a, _b, _c, _d;
/**
* @see {@link https://git-scm.com/docs/git-blame#_options}
*/
const args = ['--no-pager', 'blame', '--line-porcelain'];
if (typeof options.workTree === 'string') {
args.unshift(`--work-tree=${options.workTree}`);
}
if (typeof options.gitDir === 'string') {
args.unshift(`--git-dir=${options.gitDir}`);
}
if (typeof options.ignoreWhitespace === 'boolean') {
args.push('-w');
}
if (typeof options.range === 'string') {
args.push(`-L${options.range}`);
}
if (typeof options.rev === 'string') {
args.push(options.rev);
}
const git = child_process_1.spawn(gitPath, [...args, '--', filename], {
windowsHide: true,
});
const readline = readline_1.createInterface({ input: git.stdout });
let currentLine;
const linesMap = new Map();
for await (const line of readline) {
// https://git-scm.com/docs/git-blame#_the_porcelain_format
// Each blame entry always starts with a line of:
// <40-byte hex sha1> <sourceline> <resultline> <num_lines>
// like: 49790775624c422f67057f7bb936f35df920e391 94 120 3
const parsedLine = /^(?<hash>[a-f0-9]{40,40})\s(?<sourceline>\d+)\s(?<resultLine>\d+)\s(?<numLines>\d+)$/.exec(line);
if ((_a = parsedLine) === null || _a === void 0 ? void 0 : _a.groups) {
// this is a new line info
const sourceLine = parseInt(parsedLine.groups.sourceline, 10);
const resultLine = parseInt((_b = parsedLine) === null || _b === void 0 ? void 0 : _b.groups.resultLine, 10);
const numberOfLines = parseInt((_c = parsedLine) === null || _c === void 0 ? void 0 : _c.groups.numLines, 10);
currentLine = {
hash: parsedLine.groups.hash,
sourceLine,
resultLine,
numberOfLines,
};
// set for all lines
for (let i = resultLine; i < resultLine + numberOfLines; i++)
linesMap.set(i, currentLine);
}
else {
if (currentLine) {
const commitInfo = /^(?<token>[a-z]+(-(?<subtoken>[a-z]+))?)\s(?<data>.+)$/.exec(line);
if ((_d = commitInfo) === null || _d === void 0 ? void 0 : _d.groups) {
const property = camel_case_1.camelCase(commitInfo.groups.token);
let value = commitInfo.groups.data;
switch (commitInfo.groups.subtoken) {
case 'mail':
// remove <> from email
value = value.slice(1, -1);
break;
case 'time':
// parse datestamp into number
value = parseInt(value, 10);
break;
}
currentLine[property] = value;
}
}
}
}
return linesMap;
}
exports.blame = blame;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 11:
/***/ (function(module) {
// Returns a wrapper function that returns a wrapped callback
// The wrapper function should do some stuff, and return a
// presumably different callback function.
// This makes sure that own properties are retained, so that
// decorations and such are not lost along the way.
module.exports = wrappy
function wrappy (fn, cb) {
if (fn && cb) return wrappy(fn)(cb)
if (typeof fn !== 'function')
throw new TypeError('need wrapper function')
Object.keys(fn).forEach(function (k) {
wrapper[k] = fn[k]
})
return wrapper
function wrapper() {
var args = new Array(arguments.length)
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i]
}
var ret = fn.apply(this, args)
var cb = args[args.length-1]
if (typeof ret === 'function' && ret !== cb) {
Object.keys(cb).forEach(function (k) {
ret[k] = cb[k]
})
}
return ret
}
}
/***/ }),
/***/ 16:
/***/ (function(module) {
module.exports = require("tls");
/***/ }),
/***/ 49:
/***/ (function(module, __unusedexports, __webpack_require__) {
var wrappy = __webpack_require__(11)
module.exports = wrappy(once)
module.exports.strict = wrappy(onceStrict)
once.proto = once(function () {
Object.defineProperty(Function.prototype, 'once', {
value: function () {
return once(this)
},
configurable: true
})
Object.defineProperty(Function.prototype, 'onceStrict', {
value: function () {
return onceStrict(this)
},
configurable: true
})
})
function once (fn) {
var f = function () {
if (f.called) return f.value
f.called = true
return f.value = fn.apply(this, arguments)
}
f.called = false
return f
}
function onceStrict (fn) {
var f = function () {
if (f.called)
throw new Error(f.onceError)
f.called = true
return f.value = fn.apply(this, arguments)
}
var name = fn.name || 'Function wrapped with `once`'
f.onceError = name + " shouldn't be called more than once"
f.called = false
return f
}
/***/ }),
/***/ 58:
/***/ (function(module) {
module.exports = require("readline");
/***/ }),
/***/ 87:
/***/ (function(module) {
module.exports = require("os");
/***/ }),
/***/ 105:
/***/ (function(module) {
module.exports = [["0","\u0000",128],["a1","。",62],["8140"," 、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈",9,"+-±×"],["8180","÷=≠<>≦≧∞∴♂♀°′″℃¥$¢£%#&*@§☆★○●◎◇◆□■△▲▽▼※〒→←↑↓〓"],["81b8","∈∋⊆⊇⊂⊃∪∩"],["81c8","∧∨¬⇒⇔∀∃"],["81da","∠⊥⌒∂∇≡≒≪≫√∽∝∵∫∬"],["81f0","ʼn♯♭♪†‡¶"],["81fc","◯"],["824f","0",9],["8260","A",25],["8281","a",25],["829f","ぁ",82],["8340","ァ",62],["8380","ム",22],["839f","Α",16,"Σ",6],["83bf","α",16,"σ",6],["8440","А",5,"ЁЖ",25],["8470","а",5,"ёж",7],["8480","о",17],["849f","─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂"],["8740","①",19,"Ⅰ",9],["875f","㍉㌔㌢㍍㌘㌧㌃㌶㍑㍗㌍㌦㌣㌫㍊㌻㎜㎝㎞㎎㎏㏄㎡"],["877e","㍻"],["8780","〝〟№㏍℡㊤",4,"㈱㈲㈹㍾㍽㍼≒≡∫∮∑√⊥∠∟⊿∵∩∪"],["889f","亜唖娃阿哀愛挨姶逢葵茜穐悪握渥旭葦芦鯵梓圧斡扱宛姐虻飴絢綾鮎或粟袷安庵按暗案闇鞍杏以伊位依偉囲夷委威尉惟意慰易椅為畏異移維緯胃萎衣謂違遺医井亥域育郁磯一壱溢逸稲茨芋鰯允印咽員因姻引飲淫胤蔭"],["8940","院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円"],["8980","園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改"],["8a40","魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫"],["8a80","橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄"],["8b40","機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救"],["8b80","朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈"],["8c40","掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨"],["8c80","劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向"],["8d40","后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降"],["8d80","項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷"],["8e40","察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止"],["8e80","死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周"],["8f40","宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳"],["8f80","準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾"],["9040","拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨"],["9080","逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線"],["9140","繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻"],["9180","操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只"],["9240","叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄"],["9280","逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓"],["9340","邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬"],["9380","凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入"],["9440","如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅"],["9480","楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美"],["9540","鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷"],["9580","斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋"],["9640","法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆"],["9680","摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒"],["9740","諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲"],["9780","沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯"],["9840","蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕"],["989f","弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲"],["9940","僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭"],["9980","凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨"],["9a40","咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸"],["9a80","噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩"],["9b40","奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀"],["9b80","它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏"],["9c40","廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠"],["9c80","怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛"],["9d40","戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫"],["9d80","捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼"],["9e40","曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎"],["9e80","梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣"],["9f40","檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯"],["9f80","麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌"],["e040","漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝"],["e080","烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱"],["e140","瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿"],["e180","痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬"],["e240","磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰"],["e280","窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆"],["e340","紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷"],["e380","縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋"],["e440","隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤"],["e480","艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈"],["e540","蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬"],["e580","蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞"],["e640","襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧"],["e680","諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊"],["e740","蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜"],["e780","轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮"],["e840","錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙"],["e880","閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰"],["e940","顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃"],["e980","騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈"],["ea40","鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯"],["ea80","黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠堯槇遙瑤凜熙"],["ed40","纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏"],["ed80","塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱"],["ee40","犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙"],["ee80","蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"],["eeef","ⅰ",9,"¬¦'""],["f040","",62],["f080","",124],["f140","",62],["f180","",124],["f240","",62],["f280","",124],["f340","",62],["f380","",124],["f440","",62],["f480","",124],["f540","",62],["f580","",124],["f640","",62],["f680","",124],["f740","",62],["f780","",124],["f840","",62],["f880","",124],["f940",""],["fa40","ⅰ",9,"Ⅰ",9,"¬¦'"㈱№℡∵纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊"],["fa80","兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯"],["fb40","涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神"],["fb80","祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙"],["fc40","髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"]];
/***/ }),
/***/ 127:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"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 (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getApiBaseUrl = exports.getProxyAgent = exports.getAuthString = void 0;
const httpClient = __importStar(__webpack_require__(539));
function getAuthString(token, options) {
if (!token && !options.auth) {
throw new Error('Parameter token or opts.auth is required');
}
else if (token && options.auth) {
throw new Error('Parameters token and opts.auth may not both be specified');
}
return typeof options.auth === 'string' ? options.auth : `token ${token}`;
}
exports.getAuthString = getAuthString;
function getProxyAgent(destinationUrl) {
const hc = new httpClient.HttpClient();
return hc.getAgent(destinationUrl);
}
exports.getProxyAgent = getProxyAgent;
function getApiBaseUrl() {
return process.env['GITHUB_API_URL'] || 'https://api.github.com';
}
exports.getApiBaseUrl = getApiBaseUrl;
//# sourceMappingURL=utils.js.map
/***/ }),
/***/ 129:
/***/ (function(module) {
module.exports = require("child_process");
/***/ }),
/***/ 141:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"use strict";
var net = __webpack_require__(631);
var tls = __webpack_require__(16);
var http = __webpack_require__(605);
var https = __webpack_require__(211);
var events = __webpack_require__(614);
var assert = __webpack_require__(357);
var util = __webpack_require__(669);
exports.httpOverHttp = httpOverHttp;
exports.httpsOverHttp = httpsOverHttp;
exports.httpOverHttps = httpOverHttps;
exports.httpsOverHttps = httpsOverHttps;
function httpOverHttp(options) {
var agent = new TunnelingAgent(options);
agent.request = http.request;
return agent;
}
function httpsOverHttp(options) {
var agent = new TunnelingAgent(options);
agent.request = http.request;
agent.createSocket = createSecureSocket;
agent.defaultPort = 443;
return agent;
}
function httpOverHttps(options) {
var agent = new TunnelingAgent(options);
agent.request = https.request;
return agent;
}
function httpsOverHttps(options) {
var agent = new TunnelingAgent(options);
agent.request = https.request;
agent.createSocket = createSecureSocket;
agent.defaultPort = 443;
return agent;
}
function TunnelingAgent(options) {
var self = this;
self.options = options || {};
self.proxyOptions = self.options.proxy || {};
self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets;
self.requests = [];
self.sockets = [];
self.on('free', function onFree(socket, host, port, localAddress) {
var options = toOptions(host, port, localAddress);
for (var i = 0, len = self.requests.length; i < len; ++i) {
var pending = self.requests[i];
if (pending.host === options.host && pending.port === options.port) {
// Detect the request to connect same origin server,
// reuse the connection.
self.requests.splice(i, 1);
pending.request.onSocket(socket);
return;
}
}
socket.destroy();
self.removeSocket(socket);
});
}
util.inherits(TunnelingAgent, events.EventEmitter);
TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) {
var self = this;
var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress));
if (self.sockets.length >= this.maxSockets) {
// We are over limit so we'll add it to the queue.
self.requests.push(options);
return;
}
// If we are under maxSockets create a new one.
self.createSocket(options, function(socket) {
socket.on('free', onFree);
socket.on('close', onCloseOrRemove);
socket.on('agentRemove', onCloseOrRemove);
req.onSocket(socket);
function onFree() {
self.emit('free', socket, options);
}
function onCloseOrRemove(err) {
self.removeSocket(socket);
socket.removeListener('free', onFree);
socket.removeListener('close', onCloseOrRemove);
socket.removeListener('agentRemove', onCloseOrRemove);
}
});
};
TunnelingAgent.prototype.createSocket = function createSocket(options, cb) {
var self = this;
var placeholder = {};
self.sockets.push(placeholder);
var connectOptions = mergeOptions({}, self.proxyOptions, {
method: 'CONNECT',
path: options.host + ':' + options.port,
agent: false,
headers: {
host: options.host + ':' + options.port
}
});
if (options.localAddress) {
connectOptions.localAddress = options.localAddress;
}
if (connectOptions.proxyAuth) {
connectOptions.headers = connectOptions.headers || {};
connectOptions.headers['Proxy-Authorization'] = 'Basic ' +
new Buffer(connectOptions.proxyAuth).toString('base64');
}
debug('making CONNECT request');
var connectReq = self.request(connectOptions);
connectReq.useChunkedEncodingByDefault = false; // for v0.6
connectReq.once('response', onResponse); // for v0.6
connectReq.once('upgrade', onUpgrade); // for v0.6
connectReq.once('connect', onConnect); // for v0.7 or later
connectReq.once('error', onError);
connectReq.end();
function onResponse(res) {
// Very hacky. This is necessary to avoid http-parser leaks.
res.upgrade = true;
}
function onUpgrade(res, socket, head) {
// Hacky.
process.nextTick(function() {
onConnect(res, socket, head);
});
}
function onConnect(res, socket, head) {
connectReq.removeAllListeners();
socket.removeAllListeners();
if (res.statusCode !== 200) {
debug('tunneling socket could not be established, statusCode=%d',
res.statusCode);
socket.destroy();
var error = new Error('tunneling socket could not be established, ' +
'statusCode=' + res.statusCode);
error.code = 'ECONNRESET';
options.request.emit('error', error);
self.removeSocket(placeholder);
return;
}
if (head.length > 0) {
debug('got illegal response body from proxy');
socket.destroy();
var error = new Error('got illegal response body from proxy');
error.code = 'ECONNRESET';
options.request.emit('error', error);
self.removeSocket(placeholder);
return;
}
debug('tunneling connection has established');
self.sockets[self.sockets.indexOf(placeholder)] = socket;
return cb(socket);
}
function onError(cause) {
connectReq.removeAllListeners();
debug('tunneling socket could not be established, cause=%s\n',
cause.message, cause.stack);
var error = new Error('tunneling socket could not be established, ' +
'cause=' + cause.message);
error.code = 'ECONNRESET';
options.request.emit('error', error);
self.removeSocket(placeholder);
}
};
TunnelingAgent.prototype.removeSocket = function removeSocket(socket) {
var pos = this.sockets.indexOf(socket)
if (pos === -1) {
return;
}
this.sockets.splice(pos, 1);
var pending = this.requests.shift();
if (pending) {
// If we have pending requests and a socket gets closed a new one
// needs to be created to take over in the pool for the one that closed.
this.createSocket(pending, function(socket) {
pending.request.onSocket(socket);
});
}
};
function createSecureSocket(options, cb) {
var self = this;
TunnelingAgent.prototype.createSocket.call(self, options, function(socket) {
var hostHeader = options.request.getHeader('host');
var tlsOptions = mergeOptions({}, self.options, {
socket: socket,
servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host
});
// 0 is dummy port for v0.6
var secureSocket = tls.connect(0, tlsOptions);
self.sockets[self.sockets.indexOf(socket)] = secureSocket;
cb(secureSocket);
});
}
function toOptions(host, port, localAddress) {
if (typeof host === 'string') { // since v0.10
return {
host: host,
port: port,
localAddress: localAddress
};
}
return host; // for v0.11 or later
}
function mergeOptions(target) {
for (var i = 1, len = arguments.length; i < len; ++i) {
var overrides = arguments[i];
if (typeof overrides === 'object') {
var keys = Object.keys(overrides);
for (var j = 0, keyLen = keys.length; j < keyLen; ++j) {
var k = keys[j];
if (overrides[k] !== undefined) {
target[k] = overrides[k];
}
}
}
}
return target;
}
var debug;
if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) {
debug = function() {
var args = Array.prototype.slice.call(arguments);
if (typeof args[0] === 'string') {
args[0] = 'TUNNEL: ' + args[0];
} else {
args.unshift('TUNNEL:');
}
console.error.apply(console, args);
}
} else {
debug = function() {};
}
exports.debug = debug; // for test
/***/ }),
/***/ 142:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"use strict";
var Buffer = __webpack_require__(643).Buffer;
// UTF-7 codec, according to https://tools.ietf.org/html/rfc2152
// See also below a UTF-7-IMAP codec, according to http://tools.ietf.org/html/rfc3501#section-5.1.3
exports.utf7 = Utf7Codec;
exports.unicode11utf7 = 'utf7'; // Alias UNICODE-1-1-UTF-7
function Utf7Codec(codecOptions, iconv) {
this.iconv = iconv;
};
Utf7Codec.prototype.encoder = Utf7Encoder;
Utf7Codec.prototype.decoder = Utf7Decoder;
Utf7Codec.prototype.bomAware = true;
// -- Encoding
var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g;
function Utf7Encoder(options, codec) {
this.iconv = codec.iconv;
}
Utf7Encoder.prototype.write = function(str) {
// Naive implementation.
// Non-direct chars are encoded as "+<base64>-"; single "+" char is encoded as "+-".
return Buffer.from(str.replace(nonDirectChars, function(chunk) {
return "+" + (chunk === '+' ? '' :
this.iconv.encode(chunk, 'utf16-be').toString('base64').replace(/=+$/, ''))
+ "-";
}.bind(this)));
}
Utf7Encoder.prototype.end = function() {
}
// -- Decoding
function Utf7Decoder(options, codec) {
this.iconv = codec.iconv;
this.inBase64 = false;
this.base64Accum = '';
}
var base64Regex = /[A-Za-z0-9\/+]/;
var base64Chars = [];
for (var i = 0; i < 256; i++)
base64Chars[i] = base64Regex.test(String.fromCharCode(i));
var plusChar = '+'.charCodeAt(0),
minusChar = '-'.charCodeAt(0),
andChar = '&'.charCodeAt(0);
Utf7Decoder.prototype.write = function(buf) {
var res = "", lastI = 0,
inBase64 = this.inBase64,
base64Accum = this.base64Accum;
// The decoder is more involved as we must handle chunks in stream.
for (var i = 0; i < buf.length; i++) {
if (!inBase64) { // We're in direct mode.
// Write direct chars until '+'
if (buf[i] == plusChar) {
res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars.
lastI = i+1;
inBase64 = true;
}
} else { // We decode base64.
if (!base64Chars[buf[i]]) { // Base64 ended.
if (i == lastI && buf[i] == minusChar) {// "+-" -> "+"
res += "+";
} else {
var b64str = base64Accum + this.iconv.decode(buf.slice(lastI, i), "ascii");
res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be");
}
if (buf[i] != minusChar) // Minus is absorbed after base64.
i--;
lastI = i+1;
inBase64 = false;
base64Accum = '';
}
}
}
if (!inBase64) {
res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars.
} else {
var b64str = base64Accum + this.iconv.decode(buf.slice(lastI), "ascii");
var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars.
base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future.
b64str = b64str.slice(0, canBeDecoded);
res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be");
}
this.inBase64 = inBase64;
this.base64Accum = base64Accum;
return res;
}
Utf7Decoder.prototype.end = function() {
var res = "";
if (this.inBase64 && this.base64Accum.length > 0)
res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be");
this.inBase64 = false;
this.base64Accum = '';
return res;
}
// UTF-7-IMAP codec.
// RFC3501 Sec. 5.1.3 Modified UTF-7 (http://tools.ietf.org/html/rfc3501#section-5.1.3)
// Differences:
// * Base64 part is started by "&" instead of "+"
// * Direct characters are 0x20-0x7E, except "&" (0x26)
// * In Base64, "," is used instead of "/"
// * Base64 must not be used to represent direct characters.
// * No implicit shift back from Base64 (should always end with '-')
// * String must end in non-shifted position.
// * "-&" while in base64 is not allowed.
exports.utf7imap = Utf7IMAPCodec;
function Utf7IMAPCodec(codecOptions, iconv) {
this.iconv = iconv;
};
Utf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder;
Utf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder;
Utf7IMAPCodec.prototype.bomAware = true;
// -- Encoding
function Utf7IMAPEncoder(options, codec) {
this.iconv = codec.iconv;
this.inBase64 = false;
this.base64Accum = Buffer.alloc(6);
this.base64AccumIdx = 0;
}
Utf7IMAPEncoder.prototype.write = function(str) {
var inBase64 = this.inBase64,
base64Accum = this.base64Accum,
base64AccumIdx = this.base64AccumIdx,
buf = Buffer.alloc(str.length*5 + 10), bufIdx = 0;
for (var i = 0; i < str.length; i++) {
var uChar = str.charCodeAt(i);
if (0x20 <= uChar && uChar <= 0x7E) { // Direct character or '&'.
if (inBase64) {
if (base64AccumIdx > 0) {
bufIdx += buf.write(base64Accum.slice(0, base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx);
base64AccumIdx = 0;
}
buf[bufIdx++] = minusChar; // Write '-', then go to direct mode.
inBase64 = false;
}
if (!inBase64) {
buf[bufIdx++] = uChar; // Write direct character
if (uChar === andChar) // Ampersand -> '&-'
buf[bufIdx++] = minusChar;
}
} else { // Non-direct character
if (!inBase64) {
buf[bufIdx++] = andChar; // Write '&', then go to base64 mode.
inBase64 = true;
}
if (inBase64) {
base64Accum[base64AccumIdx++] = uChar >> 8;
base64Accum[base64AccumIdx++] = uChar & 0xFF;
if (base64AccumIdx == base64Accum.length) {
bufIdx += buf.write(base64Accum.toString('base64').replace(/\//g, ','), bufIdx);
base64AccumIdx = 0;
}
}
}
}
this.inBase64 = inBase64;
this.base64AccumIdx = base64AccumIdx;
return buf.slice(0, bufIdx);
}
Utf7IMAPEncoder.prototype.end = function() {
var buf = Buffer.alloc(10), bufIdx = 0;
if (this.inBase64) {
if (this.base64AccumIdx > 0) {
bufIdx += buf.write(this.base64Accum.slice(0, this.base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx);
this.base64AccumIdx = 0;
}
buf[bufIdx++] = minusChar; // Write '-', then go to direct mode.
this.inBase64 = false;
}
return buf.slice(0, bufIdx);
}
// -- Decoding
function Utf7IMAPDecoder(options, codec) {
this.iconv = codec.iconv;
this.inBase64 = false;
this.base64Accum = '';
}
var base64IMAPChars = base64Chars.slice();
base64IMAPChars[','.charCodeAt(0)] = true;
Utf7IMAPDecoder.prototype.write = function(buf) {
var res = "", lastI = 0,
inBase64 = this.inBase64,
base64Accum = this.base64Accum;
// The decoder is more involved as we must handle chunks in stream.
// It is forgiving, closer to standard UTF-7 (for example, '-' is optional at the end).
for (var i = 0; i < buf.length; i++) {
if (!inBase64) { // We're in direct mode.
// Write direct chars until '&'
if (buf[i] == andChar) {
res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars.
lastI = i+1;
inBase64 = true;
}
} else { // We decode base64.
if (!base64IMAPChars[buf[i]]) { // Base64 ended.
if (i == lastI && buf[i] == minusChar) { // "&-" -> "&"
res += "&";
} else {
var b64str = base64Accum + this.iconv.decode(buf.slice(lastI, i), "ascii").replace(/,/g, '/');
res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be");
}
if (buf[i] != minusChar) // Minus may be absorbed after base64.
i--;
lastI = i+1;
inBase64 = false;
base64Accum = '';
}
}
}
if (!inBase64) {
res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars.
} else {
var b64str = base64Accum + this.iconv.decode(buf.slice(lastI), "ascii").replace(/,/g, '/');
var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars.
base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future.
b64str = b64str.slice(0, canBeDecoded);
res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be");
}
this.inBase64 = inBase64;
this.base64Accum = base64Accum;
return res;
}
Utf7IMAPDecoder.prototype.end = function() {
var res = "";
if (this.inBase64 && this.base64Accum.length > 0)
res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be");
this.inBase64 = false;
this.base64Accum = '';
return res;
}
/***/ }),
/***/ 160:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"use strict";
/**
* Launches phpCs and returns results as JSON
*/
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const path = __importStar(__webpack_require__(622));
const util_1 = __webpack_require__(669);
const child_process_1 = __webpack_require__(129);
const assert = __importStar(__webpack_require__(357));
const execAsync = util_1.promisify(child_process_1.exec);
const EXECUTABLE_VERSIONS = new Map();
const DEFAULT_EXECUTABLE_PATH = path.resolve(__dirname, '../node_modules/php_codesniffer_master/bin/phpcs');
const DEFAULT_OPTIONS = {
encoding: 'UTF-8',
standard: 'PEAR',
};
/**
* Launches phpCs and returns current version
*/
async function version(executablePath = DEFAULT_EXECUTABLE_PATH) {
var _a, _b;
if (EXECUTABLE_VERSIONS.has(executablePath))
return EXECUTABLE_VERSIONS.get(executablePath);
const { stdout } = await execAsync(`${executablePath} --version`, {
windowsHide: true,
timeout: 5000,
});
const ver = (_b = (_a = /^PHP_CodeSniffer version (?<ver>\d+\.\d+\.\d+)/i.exec(stdout.trim())) === null || _a === void 0 ? void 0 : _a.groups) === null || _b === void 0 ? void 0 : _b.ver;
if (!ver)
throw new ReferenceError(`Unknown version or invalid executable of phpcs, returned: "${stdout}"`);
EXECUTABLE_VERSIONS.set(executablePath, ver);
return ver;
}
exports.version = version;
async function lint(filenames, executablePath = DEFAULT_EXECUTABLE_PATH, options = DEFAULT_OPTIONS) {
var _a, _b;
try {
const ver = await version(executablePath);
assert.ok(ver >= '2.6', `This library requires phpcs version 2.6 or later, received ${ver}`);
// we use promisified version, so, should not set exit code or it will throw
const args = [
'--report=json',
'-q',
`--encoding=${options.encoding}`,
`--standard=${options.standard}`,
'--runtime-set ignore_errors_on_exit 1',
'--runtime-set ignore_warnings_on_exit 1',
];
const { stdout } = await execAsync(`${executablePath} ${args.join(' ')} ${Array.isArray(filenames) ? filenames.join(' ') : filenames}`, {
windowsHide: true,
timeout: 15000,
});
return JSON.parse(stdout);
}
catch (err) {
if ('stdout' in err) {
// Determine whether we have an error in stdout.
const error = (_b = (_a = /^ERROR:\s?(?<error>.*)/i.exec(err.stdout)) === null || _a === void 0 ? void 0 : _a.groups) === null || _b === void 0 ? void 0 : _b.error;
if (error)
throw new Error(error.trim());
}
throw err;
}
}
exports.lint = lint;
//# sourceMappingURL=linter.js.map
/***/ }),
/***/ 175:
/***/ (function(__unusedmodule, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Source: ftp://ftp.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
*/
var SUPPORTED_LOCALE = {
tr: {
regexp: /\u0130|\u0049|\u0049\u0307/g,
map: {
İ: "\u0069",
I: "\u0131",
İ: "\u0069"
}
},
az: {
regexp: /\u0130/g,
map: {
İ: "\u0069",
I: "\u0131",
İ: "\u0069"
}
},
lt: {
regexp: /\u0049|\u004A|\u012E|\u00CC|\u00CD|\u0128/g,
map: {
I: "\u0069\u0307",
J: "\u006A\u0307",
Į: "\u012F\u0307",
Ì: "\u0069\u0307\u0300",
Í: "\u0069\u0307\u0301",
Ĩ: "\u0069\u0307\u0303"
}
}
};
/**
* Localized lower case.
*/
function localeLowerCase(str, locale) {
var lang = SUPPORTED_LOCALE[locale.toLowerCase()];
if (lang)
return lowerCase(str.replace(lang.regexp, function (m) { return lang.map[m]; }));
return lowerCase(str);
}
exports.localeLowerCase = localeLowerCase;
/**
* Lower case as a function.
*/
function lowerCase(str) {
return str.toLowerCase();
}
exports.lowerCase = lowerCase;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 177:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"use strict";
var Buffer = __webpack_require__(643).Buffer;
// Note: UTF16-LE (or UCS2) codec is Node.js native. See encodings/internal.js
// == UTF16-BE codec. ==========================================================
exports.utf16be = Utf16BECodec;
function Utf16BECodec() {
}
Utf16BECodec.prototype.encoder = Utf16BEEncoder;
Utf16BECodec.prototype.decoder = Utf16BEDecoder;
Utf16BECodec.prototype.bomAware = true;
// -- Encoding
function Utf16BEEncoder() {
}
Utf16BEEncoder.prototype.write = function(str) {
var buf = Buffer.from(str, 'ucs2');
for (var i = 0; i < buf.length; i += 2) {
var tmp = buf[i]; buf[i] = buf[i+1]; buf[i+1] = tmp;
}
return buf;
}
Utf16BEEncoder.prototype.end = function() {
}
// -- Decoding
function Utf16BEDecoder() {
this.overflowByte = -1;
}
Utf16BEDecoder.prototype.write = function(buf) {
if (buf.length == 0)
return '';
var buf2 = Buffer.alloc(buf.length + 1),
i = 0, j = 0;
if (this.overflowByte !== -1) {
buf2[0] = buf[0];
buf2[1] = this.overflowByte;
i = 1; j = 2;
}
for (; i < buf.length-1; i += 2, j+= 2) {
buf2[j] = buf[i+1];
buf2[j+1] = buf[i];
}
this.overflowByte = (i == buf.length-1) ? buf[buf.length-1] : -1;
return buf2.slice(0, j).toString('ucs2');
}
Utf16BEDecoder.prototype.end = function() {
this.overflowByte = -1;
}
// == UTF-16 codec =============================================================
// Decoder chooses automatically from UTF-16LE and UTF-16BE using BOM and space-based heuristic.
// Defaults to UTF-16LE, as it's prevalent and default in Node.
// http://en.wikipedia.org/wiki/UTF-16 and http://encoding.spec.whatwg.org/#utf-16le
// Decoder default can be changed: iconv.decode(buf, 'utf16', {defaultEncoding: 'utf-16be'});
// Encoder uses UTF-16LE and prepends BOM (which can be overridden with addBOM: false).
exports.utf16 = Utf16Codec;
function Utf16Codec(codecOptions, iconv) {
this.iconv = iconv;
}
Utf16Codec.prototype.encoder = Utf16Encoder;
Utf16Codec.prototype.decoder = Utf16Decoder;
// -- Encoding (pass-through)
function Utf16Encoder(options, codec) {
options = options || {};
if (options.addBOM === undefined)
options.addBOM = true;
this.encoder = codec.iconv.getEncoder('utf-16le', options);
}
Utf16Encoder.prototype.write = function(str) {
return this.encoder.write(str);
}
Utf16Encoder.prototype.end = function() {
return this.encoder.end();
}
// -- Decoding
function Utf16Decoder(options, codec) {
this.decoder = null;
this.initialBufs = [];
this.initialBufsLen = 0;
this.options = options || {};
this.iconv = codec.iconv;
}
Utf16Decoder.prototype.write = function(buf) {
if (!this.decoder) {
// Codec is not chosen yet. Accumulate initial bytes.
this.initialBufs.push(buf);
this.initialBufsLen += buf.length;
if (this.initialBufsLen < 16) // We need more bytes to use space heuristic (see below)
return '';
// We have enough bytes -> detect endianness.
var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding);
this.decoder = this.iconv.getDecoder(encoding, this.options);
var resStr = '';
for (var i = 0; i < this.initialBufs.length; i++)
resStr += this.decoder.write(this.initialBufs[i]);
this.initialBufs.length = this.initialBufsLen = 0;
return resStr;
}
return this.decoder.write(buf);
}
Utf16Decoder.prototype.end = function() {
if (!this.decoder) {
var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding);
this.decoder = this.iconv.getDecoder(encoding, this.options);
var resStr = '';
for (var i = 0; i < this.initialBufs.length; i++)
resStr += this.decoder.write(this.initialBufs[i]);
var trail = this.decoder.end();
if (trail)
resStr += trail;
this.initialBufs.length = this.initialBufsLen = 0;
return resStr;
}
return this.decoder.end();
}
function detectEncoding(bufs, defaultEncoding) {
var b = [];
var charsProcessed = 0;
var asciiCharsLE = 0, asciiCharsBE = 0; // Number of ASCII chars when decoded as LE or BE.
outer_loop:
for (var i = 0; i < bufs.length; i++) {
var buf = bufs[i];
for (var j = 0; j < buf.length; j++) {
b.push(buf[j]);
if (b.length === 2) {
if (charsProcessed === 0) {
// Check BOM first.
if (b[0] === 0xFF && b[1] === 0xFE) return 'utf-16le';
if (b[0] === 0xFE && b[1] === 0xFF) return 'utf-16be';
}
if (b[0] === 0 && b[1] !== 0) asciiCharsBE++;
if (b[0] !== 0 && b[1] === 0) asciiCharsLE++;
b.length = 0;
charsProcessed++;
if (charsProcessed >= 100) {
break outer_loop;
}
}
}
}
// Make decisions.
// Most of the time, the content has ASCII chars (U+00**), but the opposite (U+**00) is uncommon.
// So, we count ASCII as if it was LE or BE, and decide from that.
if (asciiCharsBE > asciiCharsLE) return 'utf-16be';
if (asciiCharsBE < asciiCharsLE) return 'utf-16le';
// Couldn't decide (likely all zeros or not enough data).
return defaultEncoding || 'utf-16le';
}
/***/ }),
/***/ 198:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"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.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const path = __importStar(__webpack_require__(622));
const core = __importStar(__webpack_require__(470));
const get_changed_file_1 = __webpack_require__(942);
const run_on_files_1 = __webpack_require__(303);
const run_on_blame_1 = __webpack_require__(400);
async function run() {
try {
const files = await get_changed_file_1.getChangedFiles();
core.info(JSON.stringify(files, null, 2));
if (!files.added.length && !files.modified.length) {
core.warning('No files to check, exiting...');
return;
}
/**
* Adding problem matcher to annotate files without token
* @see {@link https://github.com/actions/setup-node/blob/a47b2f66c61e623b503818d97a63ce0fe087f700/src/setup-node.ts#L36}
*/
const matchersPath = path.join(__dirname, '..', '.github');
console.log(`##[add-matcher]${path.join(matchersPath, 'phpcs-matcher.json')}`);
// run on complete files when they added or scope=files
const scope = core.getInput('scope', { required: true });
if (files.added.length || scope === 'files')
run_on_files_1.runOnCompleteFiles(scope === 'files' ? [...files.added, ...files.modified] : files.added);
else if (files.modified.length && scope === 'blame') {
// run on blame
await run_on_blame_1.runOnBlame(files.modified);
}
}
catch (error) {
// core.setFailed(error);
}
}
void run();
/***/ }),
/***/ 199:
/***/ (function(module, __unusedexports, __webpack_require__) {
"use strict";
const path = __webpack_require__(622);
const WIN_SLASH = '\\\\/';
const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
/**
* Posix glob regex
*/
const DOT_LITERAL = '\\.';
const PLUS_LITERAL = '\\+';
const QMARK_LITERAL = '\\?';
const SLASH_LITERAL = '\\/';
const ONE_CHAR = '(?=.)';
const QMARK = '[^/]';
const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
const NO_DOT = `(?!${DOT_LITERAL})`;
const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
const STAR = `${QMARK}*?`;
const POSIX_CHARS = {
DOT_LITERAL,
PLUS_LITERAL,
QMARK_LITERAL,
SLASH_LITERAL,
ONE_CHAR,
QMARK,
END_ANCHOR,
DOTS_SLASH,
NO_DOT,
NO_DOTS,
NO_DOT_SLASH,
NO_DOTS_SLASH,
QMARK_NO_DOT,
STAR,
START_ANCHOR
};
/**
* Windows glob regex
*/
const WINDOWS_CHARS = {
...POSIX_CHARS,
SLASH_LITERAL: `[${WIN_SLASH}]`,
QMARK: WIN_NO_SLASH,
STAR: `${WIN_NO_SLASH}*?`,
DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
NO_DOT: `(?!${DOT_LITERAL})`,
NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
};
/**
* POSIX Bracket Regex
*/
const POSIX_REGEX_SOURCE = {
alnum: 'a-zA-Z0-9',
alpha: 'a-zA-Z',
ascii: '\\x00-\\x7F',
blank: ' \\t',
cntrl: '\\x00-\\x1F\\x7F',
digit: '0-9',
graph: '\\x21-\\x7E',
lower: 'a-z',
print: '\\x20-\\x7E ',
punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
space: ' \\t\\r\\n\\v\\f',
upper: 'A-Z',
word: 'A-Za-z0-9_',
xdigit: 'A-Fa-f0-9'
};
module.exports = {
MAX_LENGTH: 1024 * 64,
POSIX_REGEX_SOURCE,
// regular expressions
REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
// Replace globs with equivalent patterns to reduce parsing time.
REPLACEMENTS: {
'***': '*',
'**/**': '**',
'**/**/**': '**'
},
// Digits
CHAR_0: 48, /* 0 */
CHAR_9: 57, /* 9 */
// Alphabet chars.
CHAR_UPPERCASE_A: 65, /* A */
CHAR_LOWERCASE_A: 97, /* a */
CHAR_UPPERCASE_Z: 90, /* Z */
CHAR_LOWERCASE_Z: 122, /* z */
CHAR_LEFT_PARENTHESES: 40, /* ( */
CHAR_RIGHT_PARENTHESES: 41, /* ) */
CHAR_ASTERISK: 42, /* * */
// Non-alphabetic chars.
CHAR_AMPERSAND: 38, /* & */
CHAR_AT: 64, /* @ */
CHAR_BACKWARD_SLASH: 92, /* \ */
CHAR_CARRIAGE_RETURN: 13, /* \r */
CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
CHAR_COLON: 58, /* : */
CHAR_COMMA: 44, /* , */
CHAR_DOT: 46, /* . */
CHAR_DOUBLE_QUOTE: 34, /* " */
CHAR_EQUAL: 61, /* = */
CHAR_EXCLAMATION_MARK: 33, /* ! */
CHAR_FORM_FEED: 12, /* \f */
CHAR_FORWARD_SLASH: 47, /* / */
CHAR_GRAVE_ACCENT: 96, /* ` */
CHAR_HASH: 35, /* # */
CHAR_HYPHEN_MINUS: 45, /* - */
CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
CHAR_LEFT_CURLY_BRACE: 123, /* { */
CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
CHAR_LINE_FEED: 10, /* \n */
CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
CHAR_PERCENT: 37, /* % */
CHAR_PLUS: 43, /* + */
CHAR_QUESTION_MARK: 63, /* ? */
CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
CHAR_RIGHT_CURLY_BRACE: 125, /* } */
CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
CHAR_SEMICOLON: 59, /* ; */
CHAR_SINGLE_QUOTE: 39, /* ' */
CHAR_SPACE: 32, /* */
CHAR_TAB: 9, /* \t */
CHAR_UNDERSCORE: 95, /* _ */
CHAR_VERTICAL_LINE: 124, /* | */
CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
SEP: path.sep,
/**
* Create EXTGLOB_CHARS
*/
extglobChars(chars) {
return {
'!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
'?': { type: 'qmark', open: '(?:', close: ')?' },
'+': { type: 'plus', open: '(?:', close: ')+' },
'*': { type: 'star', open: '(?:', close: ')*' },
'@': { type: 'at', open: '(?:', close: ')' }
};
},
/**
* Create GLOB_CHARS
*/
globChars(win32) {
return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
}
};
/***/ }),
/***/ 211:
/***/ (function(module) {
module.exports = require("https");
/***/ }),
/***/ 262:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Context = void 0;
const fs_1 = __webpack_require__(747);
const os_1 = __webpack_require__(87);
class Context {
/**
* Hydrate the context from the environment
*/
constructor() {
this.payload = {};
if (process.env.GITHUB_EVENT_PATH) {
if (fs_1.existsSync(process.env.GITHUB_EVENT_PATH)) {
this.payload = JSON.parse(fs_1.readFileSync(process.env.GITHUB_EVENT_PATH, { encoding: 'utf8' }));
}
else {
const path = process.env.GITHUB_EVENT_PATH;
process.stdout.write(`GITHUB_EVENT_PATH ${path} does not exist${os_1.EOL}`);
}
}
this.eventName = process.env.GITHUB_EVENT_NAME;
this.sha = process.env.GITHUB_SHA;
this.ref = process.env.GITHUB_REF;
this.workflow = process.env.GITHUB_WORKFLOW;
this.action = process.env.GITHUB_ACTION;
this.actor = process.env.GITHUB_ACTOR;
this.job = process.env.GITHUB_JOB;
this.runNumber = parseInt(process.env.GITHUB_RUN_NUMBER, 10);
this.runId = parseInt(process.env.GITHUB_RUN_ID, 10);
}
get issue() {
const payload = this.payload;
return Object.assign(Object.assign({}, this.repo), { number: (payload.issue || payload.pull_request || payload).number });
}
get repo() {
if (process.env.GITHUB_REPOSITORY) {
const [owner, repo] = process.env.GITHUB_REPOSITORY.split('/');
return { owner, repo };
}
if (this.payload.repository) {
return {
owner: this.payload.repository.owner.login,
repo: this.payload.repository.name
};
}
throw new Error("context.repo requires a GITHUB_REPOSITORY environment variable like 'owner/repo'");
}
}
exports.Context = Context;
//# sourceMappingURL=context.js.map
/***/ }),
/***/ 265:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"use strict";
const path = __webpack_require__(622);
const win32 = process.platform === 'win32';
const {
REGEX_BACKSLASH,
REGEX_REMOVE_BACKSLASH,
REGEX_SPECIAL_CHARS,
REGEX_SPECIAL_CHARS_GLOBAL
} = __webpack_require__(199);
exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
exports.removeBackslashes = str => {
return str.replace(REGEX_REMOVE_BACKSLASH, match => {
return match === '\\' ? '' : match;
});
};
exports.supportsLookbehinds = () => {
const segs = process.version.slice(1).split('.').map(Number);
if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) {
return true;
}
return false;
};
exports.isWindows = options => {
if (options && typeof options.windows === 'boolean') {
return options.windows;
}
return win32 === true || path.sep === '\\';
};
exports.escapeLast = (input, char, lastIdx) => {
const idx = input.lastIndexOf(char, lastIdx);
if (idx === -1) return input;
if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
return `${input.slice(0, idx)}\\${input.slice(idx)}`;
};
exports.removePrefix = (input, state = {}) => {
let output = input;
if (output.startsWith('./')) {
output = output.slice(2);
state.prefix = './';
}
return output;
};
exports.wrapOutput = (input, state = {}, options = {}) => {
const prepend = options.contains ? '' : '^';
const append = options.contains ? '' : '$';
let output = `${prepend}(?:${input})${append}`;
if (state.negated === true) {
output = `(?:^(?!${output}).*$)`;
}
return output;
};
/***/ }),
/***/ 280:
/***/ (function(module) {
module.exports = register
function register (state, name, method, options) {
if (typeof method !== 'function') {
throw new Error('method for before hook must be a function')
}
if (!options) {
options = {}
}
if (Array.isArray(name)) {
return name.reverse().reduce(function (callback, name) {
return register.bind(null, state, name, callback, options)
}, method)()
}
return Promise.resolve()
.then(function () {
if (!state.registry[name]) {
return method(options)
}
return (state.registry[name]).reduce(function (method, registered) {
return registered.hook.bind(null, method, options)
}, method)()
})
}
/***/ }),
/***/ 293:
/***/ (function(module) {
module.exports = require("buffer");
/***/ }),
/***/ 299:
/***/ (function(__unusedmodule, exports) {
"use strict";
Object.defineProperty(exports, '__esModule', { value: true });
const VERSION = "2.3.0";
/**
* Some “list” response that can be paginated have a different response structure
*
* They have a `total_count` key in the response (search also has `incomplete_results`,
* /installation/repositories also has `repository_selection`), as well as a key with
* the list of the items which name varies from endpoint to endpoint.
*
* Octokit normalizes these responses so that paginated results are always returned following
* the same structure. One challenge is that if the list response has only one page, no Link
* header is provided, so this header alone is not sufficient to check wether a response is
* paginated or not.
*
* We check if a "total_count" key is present in the response data, but also make sure that
* a "url" property is not, as the "Get the combined status for a specific ref" endpoint would
* otherwise match: https://developer.github.com/v3/repos/statuses/#get-the-combined-status-for-a-specific-ref
*/
function normalizePaginatedListResponse(response) {
const responseNeedsNormalization = "total_count" in response.data && !("url" in response.data);
if (!responseNeedsNormalization) return response; // keep the additional properties intact as there is currently no other way
// to retrieve the same information.
const incompleteResults = response.data.incomplete_results;
const repositorySelection = response.data.repository_selection;
const totalCount = response.data.total_count;
delete response.data.incomplete_results;
delete response.data.repository_selection;
delete response.data.total_count;
const namespaceKey = Object.keys(response.data)[0];
const data = response.data[namespaceKey];
response.data = data;
if (typeof incompleteResults !== "undefined") {
response.data.incomplete_results = incompleteResults;
}
if (typeof repositorySelection !== "undefined") {
response.data.repository_selection = repositorySelection;
}
response.data.total_count = totalCount;
return response;
}
function iterator(octokit, route, parameters) {
const options = typeof route === "function" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters);
const requestMethod = typeof route === "function" ? route : octokit.request;
const method = options.method;
const headers = options.headers;
let url = options.url;
return {
[Symbol.asyncIterator]: () => ({
next() {
if (!url) {
return Promise.resolve({
done: true
});
}
return requestMethod({
method,
url,
headers
}).then(normalizePaginatedListResponse).then(response => {
// `response.headers.link` format:
// '<https://api.github.com/users/aseemk/followers?page=2>; rel="next", <https://api.github.com/users/aseemk/followers?page=2>; rel="last"'
// sets `url` to undefined if "next" URL is not present or `link` header is not set
url = ((response.headers.link || "").match(/<([^>]+)>;\s*rel="next"/) || [])[1];
return {
value: response
};
});
}
})
};
}
function paginate(octokit, route, parameters, mapFn) {
if (typeof parameters === "function") {
mapFn = parameters;
parameters = undefined;
}
return gather(octokit, [], iterator(octokit, route, parameters)[Symbol.asyncIterator](), mapFn);
}
function gather(octokit, results, iterator, mapFn) {
return iterator.next().then(result => {
if (result.done) {
return results;
}
let earlyExit = false;
function done() {
earlyExit = true;
}
results = results.concat(mapFn ? mapFn(result.value, done) : result.value.data);
if (earlyExit) {
return results;
}
return gather(octokit, results, iterator, mapFn);
});
}
/**
* @param octokit Octokit instance
* @param options Options passed to Octokit constructor
*/
function paginateRest(octokit) {
return {
paginate: Object.assign(paginate.bind(null, octokit), {
iterator: iterator.bind(null, octokit)
})
};
}
paginateRest.VERSION = VERSION;
exports.paginateRest = paginateRest;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 301:
/***/ (function(module) {
module.exports = [["a140","",62],["a180","",32],["a240","",62],["a280","",32],["a2ab","",5],["a2e3","€"],["a2ef",""],["a2fd",""],["a340","",62],["a380","",31," "],["a440","",62],["a480","",32],["a4f4","",10],["a540","",62],["a580","",32],["a5f7","",7],["a640","",62],["a680","",32],["a6b9","",7],["a6d9","",6],["a6ec",""],["a6f3",""],["a6f6","",8],["a740","",62],["a780","",32],["a7c2","",14],["a7f2","",12],["a896","",10],["a8bc","ḿ"],["a8bf","ǹ"],["a8c1",""],["a8ea","",20],["a958",""],["a95b",""],["a95d",""],["a989","〾⿰",11],["a997","",12],["a9f0","",14],["aaa1","",93],["aba1","",93],["aca1","",93],["ada1","",93],["aea1","",93],["afa1","",93],["d7fa","",4],["f8a1","",93],["f9a1","",93],["faa1","",93],["fba1","",93],["fca1","",93],["fda1","",93],["fe50","⺁⺄㑳㑇⺈⺋㖞㘚㘎⺌⺗㥮㤘㧏㧟㩳㧐㭎㱮㳠⺧⺪䁖䅟⺮䌷⺳⺶⺷䎱䎬⺻䏝䓖䙡䙌"],["fe80","䜣䜩䝼䞍⻊䥇䥺䥽䦂䦃䦅䦆䦟䦛䦷䦶䲣䲟䲠䲡䱷䲢䴓",6,"䶮",93],["8135f437",""]];
/***/ }),
/***/ 303:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"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.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.runOnCompleteFiles = void 0;
const child_process_1 = __webpack_require__(129);
const core = __importStar(__webpack_require__(470));
/**
* Executes phpcs on whole files and let's errors to be picked by problem matcher
* @param files
*/
function runOnCompleteFiles(files) {
const phpcs = core.getInput('phpcs_path', { required: true });
const args = ['--report=checkstyle'];
const standard = core.getInput('standard');
if (standard)
args.push(`--standard=${standard}`);
const failOnError = core.getInput('fail_on_errors');
if (failOnError == 'false' || failOnError === 'off') {
args.push('--runtime-set ignore_errors_on_exit 1');
}
const failOnWarning = core.getInput('fail_on_warnings');
if (failOnWarning == 'false' || failOnWarning === 'off') {
args.push('--runtime-set ignore_warnings_on_exit 1');
}
try {
child_process_1.execSync(`${phpcs} ${args.join(' ')} ${files.join(' ')}`, {
stdio: 'inherit',
timeout: 20000,
});
return 0;
}
catch (err) {
core.debug(err);
// core.setFailed(err);
return 1;
}
}
exports.runOnCompleteFiles = runOnCompleteFiles;
/***/ }),
/***/ 304:
/***/ (function(module) {
module.exports = require("string_decoder");
/***/ }),
/***/ 357:
/***/ (function(module) {
module.exports = require("assert");
/***/ }),
/***/ 366:
/***/ (function(module, __unusedexports, __webpack_require__) {
"use strict";
const path = __webpack_require__(622);
const scan = __webpack_require__(537);
const parse = __webpack_require__(806);
const utils = __webpack_require__(265);
const constants = __webpack_require__(199);
const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
/**
* Creates a matcher function from one or more glob patterns. The
* returned function takes a string to match as its first argument,
* and returns true if the string is a match. The returned matcher
* function also takes a boolean as the second argument that, when true,
* returns an object with additional information.
*
* ```js
* const picomatch = require('picomatch');
* // picomatch(glob[, options]);
*
* const isMatch = picomatch('*.!(*a)');
* console.log(isMatch('a.a')); //=> false
* console.log(isMatch('a.b')); //=> true
* ```
* @name picomatch
* @param {String|Array} `globs` One or more glob patterns.
* @param {Object=} `options`
* @return {Function=} Returns a matcher function.
* @api public
*/
const picomatch = (glob, options, returnState = false) => {
if (Array.isArray(glob)) {
const fns = glob.map(input => picomatch(input, options, returnState));
const arrayMatcher = str => {
for (const isMatch of fns) {
const state = isMatch(str);
if (state) return state;
}
return false;
};
return arrayMatcher;
}
const isState = isObject(glob) && glob.tokens && glob.input;
if (glob === '' || (typeof glob !== 'string' && !isState)) {
throw new TypeError('Expected pattern to be a non-empty string');
}
const opts = options || {};
const posix = utils.isWindows(options);
const regex = isState
? picomatch.compileRe(glob, options)
: picomatch.makeRe(glob, options, false, true);
const state = regex.state;
delete regex.state;
let isIgnored = () => false;
if (opts.ignore) {
const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
}
const matcher = (input, returnObject = false) => {
const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });
const result = { glob, state, regex, posix, input, output, match, isMatch };
if (typeof opts.onResult === 'function') {
opts.onResult(result);
}
if (isMatch === false) {
result.isMatch = false;
return returnObject ? result : false;
}
if (isIgnored(input)) {
if (typeof opts.onIgnore === 'function') {
opts.onIgnore(result);
}
result.isMatch = false;
return returnObject ? result : false;
}
if (typeof opts.onMatch === 'function') {
opts.onMatch(result);
}
return returnObject ? result : true;
};
if (returnState) {
matcher.state = state;
}
return matcher;
};
/**
* Test `input` with the given `regex`. This is used by the main
* `picomatch()` function to test the input string.
*
* ```js
* const picomatch = require('picomatch');
* // picomatch.test(input, regex[, options]);
*
* console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
* // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
* ```
* @param {String} `input` String to test.
* @param {RegExp} `regex`
* @return {Object} Returns an object with matching info.
* @api public
*/
picomatch.test = (input, regex, options, { glob, posix } = {}) => {
if (typeof input !== 'string') {
throw new TypeError('Expected input to be a string');
}
if (input === '') {
return { isMatch: false, output: '' };
}
const opts = options || {};
const format = opts.format || (posix ? utils.toPosixSlashes : null);
let match = input === glob;
let output = (match && format) ? format(input) : input;
if (match === false) {
output = format ? format(input) : input;
match = output === glob;
}
if (match === false || opts.capture === true) {
if (opts.matchBase === true || opts.basename === true) {
match = picomatch.matchBase(input, regex, options, posix);
} else {
match = regex.exec(output);
}
}
return { isMatch: Boolean(match), match, output };
};
/**
* Match the basename of a filepath.
*
* ```js
* const picomatch = require('picomatch');
* // picomatch.matchBase(input, glob[, options]);
* console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
* ```
* @param {String} `input` String to test.
* @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
* @return {Boolean}
* @api public
*/
picomatch.matchBase = (input, glob, options, posix = utils.isWindows(options)) => {
const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
return regex.test(path.basename(input));
};
/**
* Returns true if **any** of the given glob `patterns` match the specified `string`.
*
* ```js
* const picomatch = require('picomatch');
* // picomatch.isMatch(string, patterns[, options]);
*
* console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
* console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
* ```
* @param {String|Array} str The string to test.
* @param {String|Array} patterns One or more glob patterns to use for matching.
* @param {Object} [options] See available [options](#options).
* @return {Boolean} Returns true if any patterns match `str`
* @api public
*/
picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
/**
* Parse a glob pattern to create the source string for a regular
* expression.
*
* ```js
* const picomatch = require('picomatch');
* const result = picomatch.parse(pattern[, options]);
* ```
* @param {String} `pattern`
* @param {Object} `options`
* @return {Object} Returns an object with useful properties and output to be used as a regex source string.
* @api public
*/
picomatch.parse = (pattern, options) => {
if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
return parse(pattern, { ...options, fastpaths: false });
};
/**
* Scan a glob pattern to separate the pattern into segments.
*
* ```js
* const picomatch = require('picomatch');
* // picomatch.scan(input[, options]);
*
* const result = picomatch.scan('!./foo/*.js');
* console.log(result);
* { prefix: '!./',
* input: '!./foo/*.js',
* start: 3,
* base: 'foo',
* glob: '*.js',
* isBrace: false,
* isBracket: false,
* isGlob: true,
* isExtglob: false,
* isGlobstar: false,
* negated: true }
* ```
* @param {String} `input` Glob pattern to scan.
* @param {Object} `options`
* @return {Object} Returns an object with
* @api public
*/
picomatch.scan = (input, options) => scan(input, options);
/**
* Create a regular expression from a parsed glob pattern.
*
* ```js
* const picomatch = require('picomatch');
* const state = picomatch.parse('*.js');
* // picomatch.compileRe(state[, options]);
*
* console.log(picomatch.compileRe(state));
* //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
* ```
* @param {String} `state` The object returned from the `.parse` method.
* @param {Object} `options`
* @return {RegExp} Returns a regex created from the given pattern.
* @api public
*/
picomatch.compileRe = (parsed, options, returnOutput = false, returnState = false) => {
if (returnOutput === true) {
return parsed.output;
}
const opts = options || {};
const prepend = opts.contains ? '' : '^';
const append = opts.contains ? '' : '$';
let source = `${prepend}(?:${parsed.output})${append}`;
if (parsed && parsed.negated === true) {
source = `^(?!${source}).*$`;
}
const regex = picomatch.toRegex(source, options);
if (returnState === true) {
regex.state = parsed;
}
return regex;
};
picomatch.makeRe = (input, options, returnOutput = false, returnState = false) => {
if (!input || typeof input !== 'string') {
throw new TypeError('Expected a non-empty string');
}
const opts = options || {};
let parsed = { negated: false, fastpaths: true };
let prefix = '';
let output;
if (input.startsWith('./')) {
input = input.slice(2);
prefix = parsed.prefix = './';
}
if (opts.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
output = parse.fastpaths(input, options);
}
if (output === undefined) {
parsed = parse(input, options);
parsed.prefix = prefix + (parsed.prefix || '');
} else {
parsed.output = output;
}
return picomatch.compileRe(parsed, options, returnOutput, returnState);
};
/**
* Create a regular expression from the given regex source string.
*
* ```js
* const picomatch = require('picomatch');
* // picomatch.toRegex(source[, options]);
*
* const { output } = picomatch.parse('*.js');
* console.log(picomatch.toRegex(output));
* //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
* ```
* @param {String} `source` Regular expression source string.
* @param {Object} `options`
* @return {RegExp}
* @api public
*/
picomatch.toRegex = (source, options) => {
try {
const opts = options || {};
return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
} catch (err) {
if (options && options.debug === true) throw err;
return /$^/;
}
};
/**
* Picomatch constants.
* @return {Object}
*/
picomatch.constants = constants;
/**
* Expose "picomatch"
*/
module.exports = picomatch;
/***/ }),
/***/ 378:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"use strict";
var Buffer = __webpack_require__(643).Buffer;
// Multibyte codec. In this scheme, a character is represented by 1 or more bytes.
// Our codec supports UTF-16 surrogates, extensions for GB18030 and unicode sequences.
// To save memory and loading time, we read table files only when requested.
exports._dbcs = DBCSCodec;
var UNASSIGNED = -1,
GB18030_CODE = -2,
SEQ_START = -10,
NODE_START = -1000,
UNASSIGNED_NODE = new Array(0x100),
DEF_CHAR = -1;
for (var i = 0; i < 0x100; i++)
UNASSIGNED_NODE[i] = UNASSIGNED;
// Class DBCSCodec reads and initializes mapping tables.
function DBCSCodec(codecOptions, iconv) {
this.encodingName = codecOptions.encodingName;
if (!codecOptions)
throw new Error("DBCS codec is called without the data.")
if (!codecOptions.table)
throw new Error("Encoding '" + this.encodingName + "' has no data.");
// Load tables.
var mappingTable = codecOptions.table();
// Decode tables: MBCS -> Unicode.
// decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256.
// Trie root is decodeTables[0].
// Values: >= 0 -> unicode character code. can be > 0xFFFF
// == UNASSIGNED -> unknown/unassigned sequence.
// == GB18030_CODE -> this is the end of a GB18030 4-byte sequence.
// <= NODE_START -> index of the next node in our trie to process next byte.
// <= SEQ_START -> index of the start of a character code sequence, in decodeTableSeq.
this.decodeTables = [];
this.decodeTables[0] = UNASSIGNED_NODE.slice(0); // Create root node.
// Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here.
this.decodeTableSeq = [];
// Actual mapping tables consist of chunks. Use them to fill up decode tables.
for (var i = 0; i < mappingTable.length; i++)
this._addDecodeChunk(mappingTable[i]);
// Load & create GB18030 tables when needed.
if (typeof codecOptions.gb18030 === 'function') {
this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges.
// Add GB18030 common decode nodes.
var commonThirdByteNodeIdx = this.decodeTables.length;
this.decodeTables.push(UNASSIGNED_NODE.slice(0));
var commonFourthByteNodeIdx = this.decodeTables.length;
this.decodeTables.push(UNASSIGNED_NODE.slice(0));
// Fill out the tree
var firstByteNode = this.decodeTables[0];
for (var i = 0x81; i <= 0xFE; i++) {
var secondByteNode = this.decodeTables[NODE_START - firstByteNode[i]];
for (var j = 0x30; j <= 0x39; j++) {
if (secondByteNode[j] === UNASSIGNED) {
secondByteNode[j] = NODE_START - commonThirdByteNodeIdx;
} else if (secondByteNode[j] > NODE_START) {
throw new Error("gb18030 decode tables conflict at byte 2");
}
var thirdByteNode = this.decodeTables[NODE_START - secondByteNode[j]];
for (var k = 0x81; k <= 0xFE; k++) {
if (thirdByteNode[k] === UNASSIGNED) {
thirdByteNode[k] = NODE_START - commonFourthByteNodeIdx;
} else if (thirdByteNode[k] === NODE_START - commonFourthByteNodeIdx) {
continue;
} else if (thirdByteNode[k] > NODE_START) {
throw new Error("gb18030 decode tables conflict at byte 3");
}
var fourthByteNode = this.decodeTables[NODE_START - thirdByteNode[k]];
for (var l = 0x30; l <= 0x39; l++) {
if (fourthByteNode[l] === UNASSIGNED)
fourthByteNode[l] = GB18030_CODE;
}
}
}
}
}
this.defaultCharUnicode = iconv.defaultCharUnicode;
// Encode tables: Unicode -> DBCS.
// `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance.
// Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null.
// Values: >= 0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.).
// == UNASSIGNED -> no conversion found. Output a default char.
// <= SEQ_START -> it's an index in encodeTableSeq, see below. The character starts a sequence.
this.encodeTable = [];
// `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of
// objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key
// means end of sequence (needed when one sequence is a strict subsequence of another).
// Objects are kept separately from encodeTable to increase performance.
this.encodeTableSeq = [];
// Some chars can be decoded, but need not be encoded.
var skipEncodeChars = {};
if (codecOptions.encodeSkipVals)
for (var i = 0; i < codecOptions.encodeSkipVals.length; i++) {
var val = codecOptions.encodeSkipVals[i];
if (typeof val === 'number')
skipEncodeChars[val] = true;
else
for (var j = val.from; j <= val.to; j++)
skipEncodeChars[j] = true;
}
// Use decode trie to recursively fill out encode tables.
this._fillEncodeTable(0, 0, skipEncodeChars);
// Add more encoding pairs when needed.
if (codecOptions.encodeAdd) {
for (var uChar in codecOptions.encodeAdd)
if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar))
this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]);
}
this.defCharSB = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)];
if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]['?'];
if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0);
}
DBCSCodec.prototype.encoder = DBCSEncoder;
DBCSCodec.prototype.decoder = DBCSDecoder;
// Decoder helpers
DBCSCodec.prototype._getDecodeTrieNode = function(addr) {
var bytes = [];
for (; addr > 0; addr >>>= 8)
bytes.push(addr & 0xFF);
if (bytes.length == 0)
bytes.push(0);
var node = this.decodeTables[0];
for (var i = bytes.length-1; i > 0; i--) { // Traverse nodes deeper into the trie.
var val = node[bytes[i]];
if (val == UNASSIGNED) { // Create new node.
node[bytes[i]] = NODE_START - this.decodeTables.length;
this.decodeTables.push(node = UNASSIGNED_NODE.slice(0));
}
else if (val <= NODE_START) { // Existing node.
node = this.decodeTables[NODE_START - val];
}
else
throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16));
}
return node;
}
DBCSCodec.prototype._addDecodeChunk = function(chunk) {
// First element of chunk is the hex mbcs code where we start.
var curAddr = parseInt(chunk[0], 16);
// Choose the decoding node where we'll write our chars.
var writeTable = this._getDecodeTrieNode(curAddr);
curAddr = curAddr & 0xFF;
// Write all other elements of the chunk to the table.
for (var k = 1; k < chunk.length; k++) {
var part = chunk[k];
if (typeof part === "string") { // String, write as-is.
for (var l = 0; l < part.length;) {
var code = part.charCodeAt(l++);
if (0xD800 <= code && code < 0xDC00) { // Decode surrogate
var codeTrail = part.charCodeAt(l++);
if (0xDC00 <= codeTrail && codeTrail < 0xE000)
writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00);
else
throw new Error("Incorrect surrogate pair in " + this.encodingName + " at chunk " + chunk[0]);
}
else if (0x0FF0 < code && code <= 0x0FFF) { // Character sequence (our own encoding used)
var len = 0xFFF - code + 2;
var seq = [];
for (var m = 0; m < len; m++)
seq.push(part.charCodeAt(l++)); // Simple variation: don't support surrogates or subsequences in seq.
writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length;
this.decodeTableSeq.push(seq);
}
else
writeTable[curAddr++] = code; // Basic char
}
}
else if (typeof part === "number") { // Integer, meaning increasing sequence starting with prev character.
var charCode = writeTable[curAddr - 1] + 1;
for (var l = 0; l < part; l++)
writeTable[curAddr++] = charCode++;
}
else
throw new Error("Incorrect type '" + typeof part + "' given in " + this.encodingName + " at chunk " + chunk[0]);
}
if (curAddr > 0xFF)
throw new Error("Incorrect chunk in " + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr);
}
// Encoder helpers
DBCSCodec.prototype._getEncodeBucket = function(uCode) {
var high = uCode >> 8; // This could be > 0xFF because of astral characters.
if (this.encodeTable[high] === undefined)
this.encodeTable[high] = UNASSIGNED_NODE.slice(0); // Create bucket on demand.
return this.encodeTable[high];
}
DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) {
var bucket = this._getEncodeBucket(uCode);
var low = uCode & 0xFF;
if (bucket[low] <= SEQ_START)
this.encodeTableSeq[SEQ_START-bucket[low]][DEF_CHAR] = dbcsCode; // There's already a sequence, set a single-char subsequence of it.
else if (bucket[low] == UNASSIGNED)
bucket[low] = dbcsCode;
}
DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) {
// Get the root of character tree according to first character of the sequence.
var uCode = seq[0];
var bucket = this._getEncodeBucket(uCode);
var low = uCode & 0xFF;
var node;
if (bucket[low] <= SEQ_START) {
// There's already a sequence with - use it.
node = this.encodeTableSeq[SEQ_START-bucket[low]];
}
else {
// There was no sequence object - allocate a new one.
node = {};
if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; // If a char was set before - make it a single-char subsequence.
bucket[low] = SEQ_START - this.encodeTableSeq.length;
this.encodeTableSeq.push(node);
}
// Traverse the character tree, allocating new nodes as needed.
for (var j = 1; j < seq.length-1; j++) {
var oldVal = node[uCode];
if (typeof oldVal === 'object')
node = oldVal;
else {
node = node[uCode] = {}
if (oldVal !== undefined)
node[DEF_CHAR] = oldVal
}
}
// Set the leaf to given dbcsCode.
uCode = seq[seq.length-1];
node[uCode] = dbcsCode;
}
DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) {
var node = this.decodeTables[nodeIdx];
var hasValues = false;
var subNodeEmpty = {};
for (var i = 0; i < 0x100; i++) {
var uCode = node[i];
var mbCode = prefix + i;
if (skipEncodeChars[mbCode])
continue;
if (uCode >= 0) {
this._setEncodeChar(uCode, mbCode);
hasValues = true;
} else if (uCode <= NODE_START) {
var subNodeIdx = NODE_START - uCode;
if (!subNodeEmpty[subNodeIdx]) { // Skip empty subtrees (they are too large in gb18030).
var newPrefix = (mbCode << 8) >>> 0; // NOTE: '>>> 0' keeps 32-bit num positive.
if (this._fillEncodeTable(subNodeIdx, newPrefix, skipEncodeChars))
hasValues = true;
else
subNodeEmpty[subNodeIdx] = true;
}
} else if (uCode <= SEQ_START) {
this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode);
hasValues = true;
}
}
return hasValues;
}
// == Encoder ==================================================================
function DBCSEncoder(options, codec) {
// Encoder state
this.leadSurrogate = -1;
this.seqObj = undefined;
// Static data
this.encodeTable = codec.encodeTable;
this.encodeTableSeq = codec.encodeTableSeq;
this.defaultCharSingleByte = codec.defCharSB;
this.gb18030 = codec.gb18030;
}
DBCSEncoder.prototype.write = function(str) {
var newBuf = Buffer.alloc(str.length * (this.gb18030 ? 4 : 3)),
leadSurrogate = this.leadSurrogate,
seqObj = this.seqObj, nextChar = -1,
i = 0, j = 0;
while (true) {
// 0. Get next character.
if (nextChar === -1) {
if (i == str.length) break;
var uCode = str.charCodeAt(i++);
}
else {
var uCode = nextChar;
nextChar = -1;
}
// 1. Handle surrogates.
if (0xD800 <= uCode && uCode < 0xE000) { // Char is one of surrogates.
if (uCode < 0xDC00) { // We've got lead surrogate.
if (leadSurrogate === -1) {
leadSurrogate = uCode;
continue;
} else {
leadSurrogate = uCode;
// Double lead surrogate found.
uCode = UNASSIGNED;
}
} else { // We've got trail surrogate.
if (leadSurrogate !== -1) {
uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00);
leadSurrogate = -1;
} else {
// Incomplete surrogate pair - only trail surrogate found.
uCode = UNASSIGNED;
}
}
}
else if (leadSurrogate !== -1) {
// Incomplete surrogate pair - only lead surrogate found.
nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char.
leadSurrogate = -1;
}
// 2. Convert uCode character.
var dbcsCode = UNASSIGNED;
if (seqObj !== undefined && uCode != UNASSIGNED) { // We are in the middle of the sequence
var resCode = seqObj[uCode];
if (typeof resCode === 'object') { // Sequence continues.
seqObj = resCode;
continue;
} else if (typeof resCode == 'number') { // Sequence finished. Write it.
dbcsCode = resCode;
} else if (resCode == undefined) { // Current character is not part of the sequence.
// Try default character for this sequence
resCode = seqObj[DEF_CHAR];
if (resCode !== undefined) {
dbcsCode = resCode; // Found. Write it.
nextChar = uCode; // Current character will be written too in the next iteration.
} else {
// TODO: What if we have no default? (resCode == undefined)
// Then, we should write first char of the sequence as-is and try the rest recursively.
// Didn't do it for now because no encoding has this situation yet.
// Currently, just skip the sequence and write current char.
}
}
seqObj = undefined;
}
else if (uCode >= 0) { // Regular character
var subtable = this.encodeTable[uCode >> 8];
if (subtable !== undefined)
dbcsCode = subtable[uCode & 0xFF];
if (dbcsCode <= SEQ_START) { // Sequence start
seqObj = this.encodeTableSeq[SEQ_START-dbcsCode];
continue;
}
if (dbcsCode == UNASSIGNED && this.gb18030) {
// Use GB18030 algorithm to find character(s) to write.
var idx = findIdx(this.gb18030.uChars, uCode);
if (idx != -1) {
var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]);
newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); dbcsCode = dbcsCode % 12600;
newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); dbcsCode = dbcsCode % 1260;
newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); dbcsCode = dbcsCode % 10;
newBuf[j++] = 0x30 + dbcsCode;
continue;
}
}
}
// 3. Write dbcsCode character.
if (dbcsCode === UNASSIGNED)
dbcsCode = this.defaultCharSingleByte;
if (dbcsCode < 0x100) {
newBuf[j++] = dbcsCode;
}
else if (dbcsCode < 0x10000) {
newBuf[j++] = dbcsCode >> 8; // high byte
newBuf[j++] = dbcsCode & 0xFF; // low byte
}
else if (dbcsCode < 0x1000000) {
newBuf[j++] = dbcsCode >> 16;
newBuf[j++] = (dbcsCode >> 8) & 0xFF;
newBuf[j++] = dbcsCode & 0xFF;
} else {
newBuf[j++] = dbcsCode >>> 24;
newBuf[j++] = (dbcsCode >>> 16) & 0xFF;
newBuf[j++] = (dbcsCode >>> 8) & 0xFF;
newBuf[j++] = dbcsCode & 0xFF;
}
}
this.seqObj = seqObj;
this.leadSurrogate = leadSurrogate;
return newBuf.slice(0, j);
}
DBCSEncoder.prototype.end = function() {
if (this.leadSurrogate === -1 && this.seqObj === undefined)
return; // All clean. Most often case.
var newBuf = Buffer.alloc(10), j = 0;
if (this.seqObj) { // We're in the sequence.
var dbcsCode = this.seqObj[DEF_CHAR];
if (dbcsCode !== undefined) { // Write beginning of the sequence.
if (dbcsCode < 0x100) {
newBuf[j++] = dbcsCode;
}
else {
newBuf[j++] = dbcsCode >> 8; // high byte
newBuf[j++] = dbcsCode & 0xFF; // low byte
}
} else {
// See todo above.
}
this.seqObj = undefined;
}
if (this.leadSurrogate !== -1) {
// Incomplete surrogate pair - only lead surrogate found.
newBuf[j++] = this.defaultCharSingleByte;
this.leadSurrogate = -1;
}
return newBuf.slice(0, j);
}
// Export for testing
DBCSEncoder.prototype.findIdx = findIdx;
// == Decoder ==================================================================
function DBCSDecoder(options, codec) {
// Decoder state
this.nodeIdx = 0;
this.prevBytes = [];
// Static data
this.decodeTables = codec.decodeTables;
this.decodeTableSeq = codec.decodeTableSeq;
this.defaultCharUnicode = codec.defaultCharUnicode;
this.gb18030 = codec.gb18030;
}
DBCSDecoder.prototype.write = function(buf) {
var newBuf = Buffer.alloc(buf.length*2),
nodeIdx = this.nodeIdx,
prevBytes = this.prevBytes, prevOffset = this.prevBytes.length,
seqStart = -this.prevBytes.length, // idx of the start of current parsed sequence.
uCode;
for (var i = 0, j = 0; i < buf.length; i++) {
var curByte = (i >= 0) ? buf[i] : prevBytes[i + prevOffset];
// Lookup in current trie node.
var uCode = this.decodeTables[nodeIdx][curByte];
if (uCode >= 0) {
// Normal character, just use it.
}
else if (uCode === UNASSIGNED) { // Unknown char.
// TODO: Callback with seq.
uCode = this.defaultCharUnicode.charCodeAt(0);
i = seqStart; // Skip one byte ('i' will be incremented by the for loop) and try to parse again.
}
else if (uCode === GB18030_CODE) {
if (i >= 3) {
var ptr = (buf[i-3]-0x81)*12600 + (buf[i-2]-0x30)*1260 + (buf[i-1]-0x81)*10 + (curByte-0x30);
} else {
var ptr = (prevBytes[i-3+prevOffset]-0x81)*12600 +
(((i-2 >= 0) ? buf[i-2] : prevBytes[i-2+prevOffset])-0x30)*1260 +
(((i-1 >= 0) ? buf[i-1] : prevBytes[i-1+prevOffset])-0x81)*10 +
(curByte-0x30);
}
var idx = findIdx(this.gb18030.gbChars, ptr);
uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx];
}
else if (uCode <= NODE_START) { // Go to next trie node.
nodeIdx = NODE_START - uCode;
continue;
}
else if (uCode <= SEQ_START) { // Output a sequence of chars.
var seq = this.decodeTableSeq[SEQ_START - uCode];
for (var k = 0; k < seq.length - 1; k++) {
uCode = seq[k];
newBuf[j++] = uCode & 0xFF;
newBuf[j++] = uCode >> 8;
}
uCode = seq[seq.length-1];
}
else
throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte);
// Write the character to buffer, handling higher planes using surrogate pair.
if (uCode >= 0x10000) {
uCode -= 0x10000;
var uCodeLead = 0xD800 | (uCode >> 10);
newBuf[j++] = uCodeLead & 0xFF;
newBuf[j++] = uCodeLead >> 8;
uCode = 0xDC00 | (uCode & 0x3FF);
}
newBuf[j++] = uCode & 0xFF;
newBuf[j++] = uCode >> 8;
// Reset trie node.
nodeIdx = 0; seqStart = i+1;
}
this.nodeIdx = nodeIdx;
this.prevBytes = (seqStart >= 0)
? Array.prototype.slice.call(buf, seqStart)
: prevBytes.slice(seqStart + prevOffset).concat(Array.prototype.slice.call(buf));
return newBuf.slice(0, j).toString('ucs2');
}
DBCSDecoder.prototype.end = function() {
var ret = '';
// Try to parse all remaining chars.
while (this.prevBytes.length > 0) {
// Skip 1 character in the buffer.
ret += this.defaultCharUnicode;
var bytesArr = this.prevBytes.slice(1);
// Parse remaining as usual.
this.prevBytes = [];
this.nodeIdx = 0;
if (bytesArr.length > 0)
ret += this.write(bytesArr);
}
this.prevBytes = [];
this.nodeIdx = 0;
return ret;
}
// Binary search for GB18030. Returns largest i such that table[i] <= val.
function findIdx(table, val) {
if (table[0] > val)
return -1;
var l = 0, r = table.length;
while (l < r-1) { // always table[l] <= val < table[r]
var mid = l + ((r-l+1) >> 1);
if (table[mid] <= val)
l = mid;
else
r = mid;
}
return l;
}
/***/ }),
/***/ 385:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var isPlainObject = _interopDefault(__webpack_require__(626));
var universalUserAgent = __webpack_require__(796);
function lowercaseKeys(object) {
if (!object) {
return {};
}
return Object.keys(object).reduce((newObj, key) => {
newObj[key.toLowerCase()] = object[key];
return newObj;
}, {});
}
function mergeDeep(defaults, options) {
const result = Object.assign({}, defaults);
Object.keys(options).forEach(key => {
if (isPlainObject(options[key])) {
if (!(key in defaults)) Object.assign(result, {
[key]: options[key]
});else result[key] = mergeDeep(defaults[key], options[key]);
} else {
Object.assign(result, {
[key]: options[key]
});
}
});
return result;
}
function merge(defaults, route, options) {
if (typeof route === "string") {
let [method, url] = route.split(" ");
options = Object.assign(url ? {
method,
url
} : {
url: method
}, options);
} else {
options = Object.assign({}, route);
} // lowercase header names before merging with defaults to avoid duplicates
options.headers = lowercaseKeys(options.headers);
const mergedOptions = mergeDeep(defaults || {}, options); // mediaType.previews arrays are merged, instead of overwritten
if (defaults && defaults.mediaType.previews.length) {
mergedOptions.mediaType.previews = defaults.mediaType.previews.filter(preview => !mergedOptions.mediaType.previews.includes(preview)).concat(mergedOptions.mediaType.previews);
}
mergedOptions.mediaType.previews = mergedOptions.mediaType.previews.map(preview => preview.replace(/-preview/, ""));
return mergedOptions;
}
function addQueryParameters(url, parameters) {
const separator = /\?/.test(url) ? "&" : "?";
const names = Object.keys(parameters);
if (names.length === 0) {
return url;
}
return url + separator + names.map(name => {
if (name === "q") {
return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+");
}
return `${name}=${encodeURIComponent(parameters[name])}`;
}).join("&");
}
const urlVariableRegex = /\{[^}]+\}/g;
function removeNonChars(variableName) {
return variableName.replace(/^\W+|\W+$/g, "").split(/,/);
}
function extractUrlVariableNames(url) {
const matches = url.match(urlVariableRegex);
if (!matches) {
return [];
}
return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []);
}
function omit(object, keysToOmit) {
return Object.keys(object).filter(option => !keysToOmit.includes(option)).reduce((obj, key) => {
obj[key] = object[key];
return obj;
}, {});
}
// Based on https://github.com/bramstein/url-template, licensed under BSD
// TODO: create separate package.
//
// Copyright (c) 2012-2014, Bram Stein
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products
// derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
// EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/* istanbul ignore file */
function encodeReserved(str) {
return str.split(/(%[0-9A-Fa-f]{2})/g).map(function (part) {
if (!/%[0-9A-Fa-f]/.test(part)) {
part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]");
}
return part;
}).join("");
}
function encodeUnreserved(str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function (c) {
return "%" + c.charCodeAt(0).toString(16).toUpperCase();
});
}
function encodeValue(operator, value, key) {
value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value);
if (key) {
return encodeUnreserved(key) + "=" + value;
} else {
return value;
}
}
function isDefined(value) {
return value !== undefined && value !== null;
}
function isKeyOperator(operator) {
return operator === ";" || operator === "&" || operator === "?";
}
function getValues(context, operator, key, modifier) {
var value = context[key],
result = [];
if (isDefined(value) && value !== "") {
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
value = value.toString();
if (modifier && modifier !== "*") {
value = value.substring(0, parseInt(modifier, 10));
}
result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : ""));
} else {
if (modifier === "*") {
if (Array.isArray(value)) {
value.filter(isDefined).forEach(function (value) {
result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : ""));
});
} else {
Object.keys(value).forEach(function (k) {
if (isDefined(value[k])) {
result.push(encodeValue(operator, value[k], k));
}
});
}
} else {
const tmp = [];
if (Array.isArray(value)) {
value.filter(isDefined).forEach(function (value) {
tmp.push(encodeValue(operator, value));
});
} else {
Object.keys(value).forEach(function (k) {
if (isDefined(value[k])) {
tmp.push(encodeUnreserved(k));
tmp.push(encodeValue(operator, value[k].toString()));
}
});
}
if (isKeyOperator(operator)) {
result.push(encodeUnreserved(key) + "=" + tmp.join(","));
} else if (tmp.length !== 0) {
result.push(tmp.join(","));
}
}
}
} else {
if (operator === ";") {
if (isDefined(value)) {
result.push(encodeUnreserved(key));
}
} else if (value === "" && (operator === "&" || operator === "?")) {
result.push(encodeUnreserved(key) + "=");
} else if (value === "") {
result.push("");
}
}
return result;
}
function parseUrl(template) {
return {
expand: expand.bind(null, template)
};
}
function expand(template, context) {
var operators = ["+", "#", ".", "/", ";", "?", "&"];
return template.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g, function (_, expression, literal) {
if (expression) {
let operator = "";
const values = [];
if (operators.indexOf(expression.charAt(0)) !== -1) {
operator = expression.charAt(0);
expression = expression.substr(1);
}
expression.split(/,/g).forEach(function (variable) {
var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable);
values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3]));
});
if (operator && operator !== "+") {
var separator = ",";
if (operator === "?") {
separator = "&";
} else if (operator !== "#") {
separator = operator;
}
return (values.length !== 0 ? operator : "") + values.join(separator);
} else {
return values.join(",");
}
} else {
return encodeReserved(literal);
}
});
}
function parse(options) {
// https://fetch.spec.whatwg.org/#methods
let method = options.method.toUpperCase(); // replace :varname with {varname} to make it RFC 6570 compatible
let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{+$1}");
let headers = Object.assign({}, options.headers);
let body;
let parameters = omit(options, ["method", "baseUrl", "url", "headers", "request", "mediaType"]); // extract variable names from URL to calculate remaining variables later
const urlVariableNames = extractUrlVariableNames(url);
url = parseUrl(url).expand(parameters);
if (!/^http/.test(url)) {
url = options.baseUrl + url;
}
const omittedParameters = Object.keys(options).filter(option => urlVariableNames.includes(option)).concat("baseUrl");
const remainingParameters = omit(parameters, omittedParameters);
const isBinaryRequset = /application\/octet-stream/i.test(headers.accept);
if (!isBinaryRequset) {
if (options.mediaType.format) {
// e.g. application/vnd.github.v3+json => application/vnd.github.v3.raw
headers.accept = headers.accept.split(/,/).map(preview => preview.replace(/application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, `application/vnd$1$2.${options.mediaType.format}`)).join(",");
}
if (options.mediaType.previews.length) {
const previewsFromAcceptHeader = headers.accept.match(/[\w-]+(?=-preview)/g) || [];
headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map(preview => {
const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json";
return `application/vnd.github.${preview}-preview${format}`;
}).join(",");
}
} // for GET/HEAD requests, set URL query parameters from remaining parameters
// for PATCH/POST/PUT/DELETE requests, set request body from remaining parameters
if (["GET", "HEAD"].includes(method)) {
url = addQueryParameters(url, remainingParameters);
} else {
if ("data" in remainingParameters) {
body = remainingParameters.data;
} else {
if (Object.keys(remainingParameters).length) {
body = remainingParameters;
} else {
headers["content-length"] = 0;
}
}
} // default content-type for JSON if body is set
if (!headers["content-type"] && typeof body !== "undefined") {
headers["content-type"] = "application/json; charset=utf-8";
} // GitHub expects 'content-length: 0' header for PUT/PATCH requests without body.
// fetch does not allow to set `content-length` header, but we can set body to an empty string
if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") {
body = "";
} // Only return body/request keys if present
return Object.assign({
method,
url,
headers
}, typeof body !== "undefined" ? {
body
} : null, options.request ? {
request: options.request
} : null);
}
function endpointWithDefaults(defaults, route, options) {
return parse(merge(defaults, route, options));
}
function withDefaults(oldDefaults, newDefaults) {
const DEFAULTS = merge(oldDefaults, newDefaults);
const endpoint = endpointWithDefaults.bind(null, DEFAULTS);
return Object.assign(endpoint, {
DEFAULTS,
defaults: withDefaults.bind(null, DEFAULTS),
merge: merge.bind(null, DEFAULTS),
parse
});
}
const VERSION = "6.0.5";
const userAgent = `octokit-endpoint.js/${VERSION} ${universalUserAgent.getUserAgent()}`; // DEFAULTS has all properties set that EndpointOptions has, except url.
// So we use RequestParameters and add method as additional required property.
const DEFAULTS = {
method: "GET",
baseUrl: "https://api.github.com",
headers: {
accept: "application/vnd.github.v3+json",
"user-agent": userAgent
},
mediaType: {
format: "",
previews: []
}
};
const endpoint = withDefaults(null, DEFAULTS);
exports.endpoint = endpoint;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 400:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"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.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.runOnBlame = void 0;
const php_codesniffer_1 = __webpack_require__(160);
const child_process_1 = __webpack_require__(129);
const git_blame_json_1 = __webpack_require__(5);
const path = __importStar(__webpack_require__(622));
const core = __importStar(__webpack_require__(470));
const github = __importStar(__webpack_require__(469));
//import * as Webhooks from '@octokit/webhooks';
async function runOnBlame(files) {
var _a;
try {
const options = {};
const standard = core.getInput('standard');
if (standard)
options.standard = standard;
const lintResults = await php_codesniffer_1.lint(files, core.getInput('phpcs_path', { required: true }));
const dontFailOnError = core.getInput('fail_on_errors') == 'false' ||
core.getInput('fail_on_errors') === 'off';
const dontFailOnWarning = core.getInput('fail_on_warnings') == 'false' ||
core.getInput('fail_on_warnings') === 'off';
if (!lintResults.totals.errors) {
if (dontFailOnWarning)
return;
if (!lintResults.totals.warnings)
return;
}
// blame files and output relevant errors
// get email of author of first commit in PR
const authorEmail = child_process_1.execFileSync('git', ['--no-pager', 'log', '--format=%ae', `${github.context.sha}^!`], { encoding: 'utf8', windowsHide: true, timeout: 5000 }).trim();
console.log('PR author email: %s', authorEmail);
for (const [file, results] of Object.entries(lintResults.files)) {
const blameMap = await git_blame_json_1.blame(file);
let headerPrinted = false;
for (const message of results.messages) {
if (((_a = blameMap.get(message.line)) === null || _a === void 0 ? void 0 : _a.authorMail) === authorEmail) {
// that's our line
// we simulate checkstyle output to be picked up by problem matched
if (!headerPrinted) {
console.log(`<file name="${path.relative(process.cwd(), file)}">`);
headerPrinted = true;
}
// output the problem
console.log('<error line="%d" column="%d" severity="%s" message="%s" source="%s"/>', message.line, message.column, message.type.toLowerCase(), message.message, message.source);
// fail
/*if (message.type === 'WARNING' && !dontFailOnWarning)
core.setFailed(message.message);
else if (message.type === 'ERROR' && !dontFailOnError)
core.setFailed(message.message);*/
}
}
}
}
catch (err) {
core.debug(err);
// core.setFailed(err);
}
}
exports.runOnBlame = runOnBlame;
/***/ }),
/***/ 413:
/***/ (function(module, __unusedexports, __webpack_require__) {
module.exports = __webpack_require__(141);
/***/ }),
/***/ 420:
/***/ (function(module) {
module.exports = [["8740","䏰䰲䘃䖦䕸𧉧䵷䖳𧲱䳢𧳅㮕䜶䝄䱇䱀𤊿𣘗𧍒𦺋𧃒䱗𪍑䝏䗚䲅𧱬䴇䪤䚡𦬣爥𥩔𡩣𣸆𣽡晍囻"],["8767","綕夝𨮹㷴霴𧯯寛𡵞媤㘥𩺰嫑宷峼杮薓𩥅瑡璝㡵𡵓𣚞𦀡㻬"],["87a1","𥣞㫵竼龗𤅡𨤍𣇪𠪊𣉞䌊蒄龖鐯䤰蘓墖靊鈘秐稲晠権袝瑌篅枂稬剏遆㓦珄𥶹瓆鿇垳䤯呌䄱𣚎堘穲𧭥讏䚮𦺈䆁𥶙箮𢒼鿈𢓁𢓉𢓌鿉蔄𣖻䂴鿊䓡𪷿拁灮鿋"],["8840","㇀",4,"𠄌㇅𠃑𠃍㇆㇇𠃋𡿨㇈𠃊㇉㇊㇋㇌𠄎㇍㇎ĀÁǍÀĒÉĚÈŌÓǑÒÊ̄ẾÊ̌ỀÊāáǎàɑēéěèīíǐìōóǒòūúǔùǖǘǚ"],["88a1","ǜüê̄ếê̌ềêɡ⏚⏛"],["8940","𪎩𡅅"],["8943","攊"],["8946","丽滝鵎釟"],["894c","𧜵撑会伨侨兖兴农凤务动医华发变团声处备夲头学实実岚庆总斉柾栄桥济炼电纤纬纺织经统缆缷艺苏药视设询车轧轮"],["89a1","琑糼緍楆竉刧"],["89ab","醌碸酞肼"],["89b0","贋胶𠧧"],["89b5","肟黇䳍鷉鸌䰾𩷶𧀎鸊𪄳㗁"],["89c1","溚舾甙"],["89c5","䤑马骏龙禇𨑬𡷊𠗐𢫦两亁亀亇亿仫伷㑌侽㹈倃傈㑽㒓㒥円夅凛凼刅争剹劐匧㗇厩㕑厰㕓参吣㕭㕲㚁咓咣咴咹哐哯唘唣唨㖘唿㖥㖿嗗㗅"],["8a40","𧶄唥"],["8a43","𠱂𠴕𥄫喐𢳆㧬𠍁蹆𤶸𩓥䁓𨂾睺𢰸㨴䟕𨅝𦧲𤷪擝𠵼𠾴𠳕𡃴撍蹾𠺖𠰋𠽤𢲩𨉖𤓓"],["8a64","𠵆𩩍𨃩䟴𤺧𢳂骲㩧𩗴㿭㔆𥋇𩟔𧣈𢵄鵮頕"],["8a76","䏙𦂥撴哣𢵌𢯊𡁷㧻𡁯"],["8aa1","𦛚𦜖𧦠擪𥁒𠱃蹨𢆡𨭌𠜱"],["8aac","䠋𠆩㿺塳𢶍"],["8ab2","𤗈𠓼𦂗𠽌𠶖啹䂻䎺"],["8abb","䪴𢩦𡂝膪飵𠶜捹㧾𢝵跀嚡摼㹃"],["8ac9","𪘁𠸉𢫏𢳉"],["8ace","𡃈𣧂㦒㨆𨊛㕸𥹉𢃇噒𠼱𢲲𩜠㒼氽𤸻"],["8adf","𧕴𢺋𢈈𪙛𨳍𠹺𠰴𦠜羓𡃏𢠃𢤹㗻𥇣𠺌𠾍𠺪㾓𠼰𠵇𡅏𠹌"],["8af6","𠺫𠮩𠵈𡃀𡄽㿹𢚖搲𠾭"],["8b40","𣏴𧘹𢯎𠵾𠵿𢱑𢱕㨘𠺘𡃇𠼮𪘲𦭐𨳒𨶙𨳊閪哌苄喹"],["8b55","𩻃鰦骶𧝞𢷮煀腭胬尜𦕲脴㞗卟𨂽醶𠻺𠸏𠹷𠻻㗝𤷫㘉𠳖嚯𢞵𡃉𠸐𠹸𡁸𡅈𨈇𡑕𠹹𤹐𢶤婔𡀝𡀞𡃵𡃶垜𠸑"],["8ba1","𧚔𨋍𠾵𠹻𥅾㜃𠾶𡆀𥋘𪊽𤧚𡠺𤅷𨉼墙剨㘚𥜽箲孨䠀䬬鼧䧧鰟鮍𥭴𣄽嗻㗲嚉丨夂𡯁屮靑𠂆乛亻㔾尣彑忄㣺扌攵歺氵氺灬爫丬犭𤣩罒礻糹罓𦉪㓁"],["8bde","𦍋耂肀𦘒𦥑卝衤见𧢲讠贝钅镸长门𨸏韦页风飞饣𩠐鱼鸟黄歯龜丷𠂇阝户钢"],["8c40","倻淾𩱳龦㷉袏𤅎灷峵䬠𥇍㕙𥴰愢𨨲辧釶熑朙玺𣊁𪄇㲋𡦀䬐磤琂冮𨜏䀉橣𪊺䈣蘏𠩯稪𩥇𨫪靕灍匤𢁾鏴盙𨧣龧矝亣俰傼丯众龨吴綋墒壐𡶶庒庙忂𢜒斋"],["8ca1","𣏹椙橃𣱣泿"],["8ca7","爀𤔅玌㻛𤨓嬕璹讃𥲤𥚕窓篬糃繬苸薗龩袐龪躹龫迏蕟駠鈡龬𨶹𡐿䁱䊢娚"],["8cc9","顨杫䉶圽"],["8cce","藖𤥻芿𧄍䲁𦵴嵻𦬕𦾾龭龮宖龯曧繛湗秊㶈䓃𣉖𢞖䎚䔶"],["8ce6","峕𣬚諹屸㴒𣕑嵸龲煗䕘𤃬𡸣䱷㥸㑊𠆤𦱁諌侴𠈹妿腬顖𩣺弻"],["8d40","𠮟"],["8d42","𢇁𨥭䄂䚻𩁹㼇龳𪆵䃸㟖䛷𦱆䅼𨚲𧏿䕭㣔𥒚䕡䔛䶉䱻䵶䗪㿈𤬏㙡䓞䒽䇭崾嵈嵖㷼㠏嶤嶹㠠㠸幂庽弥徃㤈㤔㤿㥍惗愽峥㦉憷憹懏㦸戬抐拥挘㧸嚱"],["8da1","㨃揢揻搇摚㩋擀崕嘡龟㪗斆㪽旿晓㫲暒㬢朖㭂枤栀㭘桊梄㭲㭱㭻椉楃牜楤榟榅㮼槖㯝橥橴橱檂㯬檙㯲檫檵櫔櫶殁毁毪汵沪㳋洂洆洦涁㳯涤涱渕渘温溆𨧀溻滢滚齿滨滩漤漴㵆𣽁澁澾㵪㵵熷岙㶊瀬㶑灐灔灯灿炉𠌥䏁㗱𠻘"],["8e40","𣻗垾𦻓焾𥟠㙎榢𨯩孴穉𥣡𩓙穥穽𥦬窻窰竂竃燑𦒍䇊竚竝竪䇯咲𥰁笋筕笩𥌎𥳾箢筯莜𥮴𦱿篐萡箒箸𥴠㶭𥱥蒒篺簆簵𥳁籄粃𤢂粦晽𤕸糉糇糦籴糳糵糎"],["8ea1","繧䔝𦹄絝𦻖璍綉綫焵綳緒𤁗𦀩緤㴓緵𡟹緥𨍭縝𦄡𦅚繮纒䌫鑬縧罀罁罇礶𦋐駡羗𦍑羣𡙡𠁨䕜𣝦䔃𨌺翺𦒉者耈耝耨耯𪂇𦳃耻耼聡𢜔䦉𦘦𣷣𦛨朥肧𨩈脇脚墰𢛶汿𦒘𤾸擧𡒊舘𡡞橓𤩥𤪕䑺舩𠬍𦩒𣵾俹𡓽蓢荢𦬊𤦧𣔰𡝳𣷸芪椛芳䇛"],["8f40","蕋苐茚𠸖𡞴㛁𣅽𣕚艻苢茘𣺋𦶣𦬅𦮗𣗎㶿茝嗬莅䔋𦶥莬菁菓㑾𦻔橗蕚㒖𦹂𢻯葘𥯤葱㷓䓤檧葊𣲵祘蒨𦮖𦹷𦹃蓞萏莑䒠蒓蓤𥲑䉀𥳀䕃蔴嫲𦺙䔧蕳䔖枿蘖"],["8fa1","𨘥𨘻藁𧂈蘂𡖂𧃍䕫䕪蘨㙈𡢢号𧎚虾蝱𪃸蟮𢰧螱蟚蠏噡虬桖䘏衅衆𧗠𣶹𧗤衞袜䙛袴袵揁装睷𧜏覇覊覦覩覧覼𨨥觧𧤤𧪽誜瞓釾誐𧩙竩𧬺𣾏䜓𧬸煼謌謟𥐰𥕥謿譌譍誩𤩺讐讛誯𡛟䘕衏貛𧵔𧶏貫㜥𧵓賖𧶘𧶽贒贃𡤐賛灜贑𤳉㻐起"],["9040","趩𨀂𡀔𤦊㭼𨆼𧄌竧躭躶軃鋔輙輭𨍥𨐒辥錃𪊟𠩐辳䤪𨧞𨔽𣶻廸𣉢迹𪀔𨚼𨔁𢌥㦀𦻗逷𨔼𧪾遡𨕬𨘋邨𨜓郄𨛦邮都酧㫰醩釄粬𨤳𡺉鈎沟鉁鉢𥖹銹𨫆𣲛𨬌𥗛"],["90a1","𠴱錬鍫𨫡𨯫炏嫃𨫢𨫥䥥鉄𨯬𨰹𨯿鍳鑛躼閅閦鐦閠濶䊹𢙺𨛘𡉼𣸮䧟氜陻隖䅬隣𦻕懚隶磵𨫠隽双䦡𦲸𠉴𦐐𩂯𩃥𤫑𡤕𣌊霱虂霶䨏䔽䖅𤫩灵孁霛靜𩇕靗孊𩇫靟鐥僐𣂷𣂼鞉鞟鞱鞾韀韒韠𥑬韮琜𩐳響韵𩐝𧥺䫑頴頳顋顦㬎𧅵㵑𠘰𤅜"],["9140","𥜆飊颷飈飇䫿𦴧𡛓喰飡飦飬鍸餹𤨩䭲𩡗𩤅駵騌騻騐驘𥜥㛄𩂱𩯕髠髢𩬅髴䰎鬔鬭𨘀倴鬴𦦨㣃𣁽魐魀𩴾婅𡡣鮎𤉋鰂鯿鰌𩹨鷔𩾷𪆒𪆫𪃡𪄣𪇟鵾鶃𪄴鸎梈"],["91a1","鷄𢅛𪆓𪈠𡤻𪈳鴹𪂹𪊴麐麕麞麢䴴麪麯𤍤黁㭠㧥㴝伲㞾𨰫鼂鼈䮖鐤𦶢鼗鼖鼹嚟嚊齅馸𩂋韲葿齢齩竜龎爖䮾𤥵𤦻煷𤧸𤍈𤩑玞𨯚𡣺禟𨥾𨸶鍩鏳𨩄鋬鎁鏋𨥬𤒹爗㻫睲穃烐𤑳𤏸煾𡟯炣𡢾𣖙㻇𡢅𥐯𡟸㜢𡛻𡠹㛡𡝴𡣑𥽋㜣𡛀坛𤨥𡏾𡊨"],["9240","𡏆𡒶蔃𣚦蔃葕𤦔𧅥𣸱𥕜𣻻𧁒䓴𣛮𩦝𦼦柹㜳㰕㷧塬𡤢栐䁗𣜿𤃡𤂋𤄏𦰡哋嚞𦚱嚒𠿟𠮨𠸍鏆𨬓鎜仸儫㠙𤐶亼𠑥𠍿佋侊𥙑婨𠆫𠏋㦙𠌊𠐔㐵伩𠋀𨺳𠉵諚𠈌亘"],["92a1","働儍侢伃𤨎𣺊佂倮偬傁俌俥偘僼兙兛兝兞湶𣖕𣸹𣺿浲𡢄𣺉冨凃𠗠䓝𠒣𠒒𠒑赺𨪜𠜎剙劤𠡳勡鍮䙺熌𤎌𠰠𤦬𡃤槑𠸝瑹㻞璙琔瑖玘䮎𤪼𤂍叐㖄爏𤃉喴𠍅响𠯆圝鉝雴鍦埝垍坿㘾壋媙𨩆𡛺𡝯𡜐娬妸銏婾嫏娒𥥆𡧳𡡡𤊕㛵洅瑃娡𥺃"],["9340","媁𨯗𠐓鏠璌𡌃焅䥲鐈𨧻鎽㞠尞岞幞幈𡦖𡥼𣫮廍孏𡤃𡤄㜁𡢠㛝𡛾㛓脪𨩇𡶺𣑲𨦨弌弎𡤧𡞫婫𡜻孄蘔𧗽衠恾𢡠𢘫忛㺸𢖯𢖾𩂈𦽳懀𠀾𠁆𢘛憙憘恵𢲛𢴇𤛔𩅍"],["93a1","摱𤙥𢭪㨩𢬢𣑐𩣪𢹸挷𪑛撶挱揑𤧣𢵧护𢲡搻敫楲㯴𣂎𣊭𤦉𣊫唍𣋠𡣙𩐿曎𣊉𣆳㫠䆐𥖄𨬢𥖏𡛼𥕛𥐥磮𣄃𡠪𣈴㑤𣈏𣆂𤋉暎𦴤晫䮓昰𧡰𡷫晣𣋒𣋡昞𥡲㣑𣠺𣞼㮙𣞢𣏾瓐㮖枏𤘪梶栞㯄檾㡣𣟕𤒇樳橒櫉欅𡤒攑梘橌㯗橺歗𣿀𣲚鎠鋲𨯪𨫋"],["9440","銉𨀞𨧜鑧涥漋𤧬浧𣽿㶏渄𤀼娽渊塇洤硂焻𤌚𤉶烱牐犇犔𤞏𤜥兹𤪤𠗫瑺𣻸𣙟𤩊𤤗𥿡㼆㺱𤫟𨰣𣼵悧㻳瓌琼鎇琷䒟𦷪䕑疃㽣𤳙𤴆㽘畕癳𪗆㬙瑨𨫌𤦫𤦎㫻"],["94a1","㷍𤩎㻿𤧅𤣳釺圲鍂𨫣𡡤僟𥈡𥇧睸𣈲眎眏睻𤚗𣞁㩞𤣰琸璛㺿𤪺𤫇䃈𤪖𦆮錇𥖁砞碍碈磒珐祙𧝁𥛣䄎禛蒖禥樭𣻺稺秴䅮𡛦䄲鈵秱𠵌𤦌𠊙𣶺𡝮㖗啫㕰㚪𠇔𠰍竢婙𢛵𥪯𥪜娍𠉛磰娪𥯆竾䇹籝籭䈑𥮳𥺼𥺦糍𤧹𡞰粎籼粮檲緜縇緓罎𦉡"],["9540","𦅜𧭈綗𥺂䉪𦭵𠤖柖𠁎𣗏埄𦐒𦏸𤥢翝笧𠠬𥫩𥵃笌𥸎駦虅驣樜𣐿㧢𤧷𦖭騟𦖠蒀𧄧𦳑䓪脷䐂胆脉腂𦞴飃𦩂艢艥𦩑葓𦶧蘐𧈛媆䅿𡡀嬫𡢡嫤𡣘蚠蜨𣶏蠭𧐢娂"],["95a1","衮佅袇袿裦襥襍𥚃襔𧞅𧞄𨯵𨯙𨮜𨧹㺭蒣䛵䛏㟲訽訜𩑈彍鈫𤊄旔焩烄𡡅鵭貟賩𧷜妚矃姰䍮㛔踪躧𤰉輰轊䋴汘澻𢌡䢛潹溋𡟚鯩㚵𤤯邻邗啱䤆醻鐄𨩋䁢𨫼鐧𨰝𨰻蓥訫閙閧閗閖𨴴瑅㻂𤣿𤩂𤏪㻧𣈥随𨻧𨹦𨹥㻌𤧭𤩸𣿮琒瑫㻼靁𩂰"],["9640","桇䨝𩂓𥟟靝鍨𨦉𨰦𨬯𦎾銺嬑譩䤼珹𤈛鞛靱餸𠼦巁𨯅𤪲頟𩓚鋶𩗗釥䓀𨭐𤩧𨭤飜𨩅㼀鈪䤥萔餻饍𧬆㷽馛䭯馪驜𨭥𥣈檏騡嫾騯𩣱䮐𩥈馼䮽䮗鍽塲𡌂堢𤦸"],["96a1","𡓨硄𢜟𣶸棅㵽鑘㤧慐𢞁𢥫愇鱏鱓鱻鰵鰐魿鯏𩸭鮟𪇵𪃾鴡䲮𤄄鸘䲰鴌𪆴𪃭𪃳𩤯鶥蒽𦸒𦿟𦮂藼䔳𦶤𦺄𦷰萠藮𦸀𣟗𦁤秢𣖜𣙀䤭𤧞㵢鏛銾鍈𠊿碹鉷鑍俤㑀遤𥕝砽硔碶硋𡝗𣇉𤥁㚚佲濚濙瀞瀞吔𤆵垻壳垊鴖埗焴㒯𤆬燫𦱀𤾗嬨𡞵𨩉"],["9740","愌嫎娋䊼𤒈㜬䭻𨧼鎻鎸𡣖𠼝葲𦳀𡐓𤋺𢰦𤏁妔𣶷𦝁綨𦅛𦂤𤦹𤦋𨧺鋥珢㻩璴𨭣𡢟㻡𤪳櫘珳珻㻖𤨾𤪔𡟙𤩦𠎧𡐤𤧥瑈𤤖炥𤥶銄珦鍟𠓾錱𨫎𨨖鎆𨯧𥗕䤵𨪂煫"],["97a1","𤥃𠳿嚤𠘚𠯫𠲸唂秄𡟺緾𡛂𤩐𡡒䔮鐁㜊𨫀𤦭妰𡢿𡢃𧒄媡㛢𣵛㚰鉟婹𨪁𡡢鍴㳍𠪴䪖㦊僴㵩㵌𡎜煵䋻𨈘渏𩃤䓫浗𧹏灧沯㳖𣿭𣸭渂漌㵯𠏵畑㚼㓈䚀㻚䡱姄鉮䤾轁𨰜𦯀堒埈㛖𡑒烾𤍢𤩱𢿣𡊰𢎽梹楧𡎘𣓥𧯴𣛟𨪃𣟖𣏺𤲟樚𣚭𦲷萾䓟䓎"],["9840","𦴦𦵑𦲂𦿞漗𧄉茽𡜺菭𦲀𧁓𡟛妉媂𡞳婡婱𡤅𤇼㜭姯𡜼㛇熎鎐暚𤊥婮娫𤊓樫𣻹𧜶𤑛𤋊焝𤉙𨧡侰𦴨峂𤓎𧹍𤎽樌𤉖𡌄炦焳𤏩㶥泟勇𤩏繥姫崯㷳彜𤩝𡟟綤萦"],["98a1","咅𣫺𣌀𠈔坾𠣕𠘙㿥𡾞𪊶瀃𩅛嵰玏糓𨩙𩐠俈翧狍猐𧫴猸猹𥛶獁獈㺩𧬘遬燵𤣲珡臶㻊県㻑沢国琙琞琟㻢㻰㻴㻺瓓㼎㽓畂畭畲疍㽼痈痜㿀癍㿗癴㿜発𤽜熈嘣覀塩䀝睃䀹条䁅㗛瞘䁪䁯属瞾矋売砘点砜䂨砹硇硑硦葈𥔵礳栃礲䄃"],["9940","䄉禑禙辻稆込䅧窑䆲窼艹䇄竏竛䇏両筢筬筻簒簛䉠䉺类粜䊌粸䊔糭输烀𠳏総緔緐緽羮羴犟䎗耠耥笹耮耱联㷌垴炠肷胩䏭脌猪脎脒畠脔䐁㬹腖腙腚"],["99a1","䐓堺腼膄䐥膓䐭膥埯臁臤艔䒏芦艶苊苘苿䒰荗险榊萅烵葤惣蒈䔄蒾蓡蓸蔐蔸蕒䔻蕯蕰藠䕷虲蚒蚲蛯际螋䘆䘗袮裿褤襇覑𧥧訩訸誔誴豑賔賲贜䞘塟跃䟭仮踺嗘坔蹱嗵躰䠷軎転軤軭軲辷迁迊迌逳駄䢭飠鈓䤞鈨鉘鉫銱銮銿"],["9a40","鋣鋫鋳鋴鋽鍃鎄鎭䥅䥑麿鐗匁鐝鐭鐾䥪鑔鑹锭関䦧间阳䧥枠䨤靀䨵鞲韂噔䫤惨颹䬙飱塄餎餙冴餜餷饂饝饢䭰駅䮝騼鬏窃魩鮁鯝鯱鯴䱭鰠㝯𡯂鵉鰺"],["9aa1","黾噐鶓鶽鷀鷼银辶鹻麬麱麽黆铜黢黱黸竈齄𠂔𠊷𠎠椚铃妬𠓗塀铁㞹𠗕𠘕𠙶𡚺块煳𠫂𠫍𠮿呪吆𠯋咞𠯻𠰻𠱓𠱥𠱼惧𠲍噺𠲵𠳝𠳭𠵯𠶲𠷈楕鰯螥𠸄𠸎𠻗𠾐𠼭𠹳尠𠾼帋𡁜𡁏𡁶朞𡁻𡂈𡂖㙇𡂿𡃓𡄯𡄻卤蒭𡋣𡍵𡌶讁𡕷𡘙𡟃𡟇乸炻𡠭𡥪"],["9b40","𡨭𡩅𡰪𡱰𡲬𡻈拃𡻕𡼕熘桕𢁅槩㛈𢉼𢏗𢏺𢜪𢡱𢥏苽𢥧𢦓𢫕覥𢫨辠𢬎鞸𢬿顇骽𢱌"],["9b62","𢲈𢲷𥯨𢴈𢴒𢶷𢶕𢹂𢽴𢿌𣀳𣁦𣌟𣏞徱晈暿𧩹𣕧𣗳爁𤦺矗𣘚𣜖纇𠍆墵朎"],["9ba1","椘𣪧𧙗𥿢𣸑𣺹𧗾𢂚䣐䪸𤄙𨪚𤋮𤌍𤀻𤌴𤎖𤩅𠗊凒𠘑妟𡺨㮾𣳿𤐄𤓖垈𤙴㦛𤜯𨗨𩧉㝢𢇃譞𨭎駖𤠒𤣻𤨕爉𤫀𠱸奥𤺥𤾆𠝹軚𥀬劏圿煱𥊙𥐙𣽊𤪧喼𥑆𥑮𦭒釔㑳𥔿𧘲𥕞䜘𥕢𥕦𥟇𤤿𥡝偦㓻𣏌惞𥤃䝼𨥈𥪮𥮉𥰆𡶐垡煑澶𦄂𧰒遖𦆲𤾚譢𦐂𦑊"],["9c40","嵛𦯷輶𦒄𡤜諪𤧶𦒈𣿯𦔒䯀𦖿𦚵𢜛鑥𥟡憕娧晉侻嚹𤔡𦛼乪𤤴陖涏𦲽㘘襷𦞙𦡮𦐑𦡞營𦣇筂𩃀𠨑𦤦鄄𦤹穅鷰𦧺騦𦨭㙟𦑩𠀡禃𦨴𦭛崬𣔙菏𦮝䛐𦲤画补𦶮墶"],["9ca1","㜜𢖍𧁋𧇍㱔𧊀𧊅銁𢅺𧊋錰𧋦𤧐氹钟𧑐𠻸蠧裵𢤦𨑳𡞱溸𤨪𡠠㦤㚹尐秣䔿暶𩲭𩢤襃𧟌𧡘囖䃟𡘊㦡𣜯𨃨𡏅熭荦𧧝𩆨婧䲷𧂯𨦫𧧽𧨊𧬋𧵦𤅺筃祾𨀉澵𪋟樃𨌘厢𦸇鎿栶靝𨅯𨀣𦦵𡏭𣈯𨁈嶅𨰰𨂃圕頣𨥉嶫𤦈斾槕叒𤪥𣾁㰑朶𨂐𨃴𨄮𡾡𨅏"],["9d40","𨆉𨆯𨈚𨌆𨌯𨎊㗊𨑨𨚪䣺揦𨥖砈鉕𨦸䏲𨧧䏟𨧨𨭆𨯔姸𨰉輋𨿅𩃬筑𩄐𩄼㷷𩅞𤫊运犏嚋𩓧𩗩𩖰𩖸𩜲𩣑𩥉𩥪𩧃𩨨𩬎𩵚𩶛纟𩻸𩼣䲤镇𪊓熢𪋿䶑递𪗋䶜𠲜达嗁"],["9da1","辺𢒰边𤪓䔉繿潖檱仪㓤𨬬𧢝㜺躀𡟵𨀤𨭬𨮙𧨾𦚯㷫𧙕𣲷𥘵𥥖亚𥺁𦉘嚿𠹭踎孭𣺈𤲞揞拐𡟶𡡻攰嘭𥱊吚𥌑㷆𩶘䱽嘢嘞罉𥻘奵𣵀蝰东𠿪𠵉𣚺脗鵞贘瘻鱅癎瞹鍅吲腈苷嘥脲萘肽嗪祢噃吖𠺝㗎嘅嗱曱𨋢㘭甴嗰喺咗啲𠱁𠲖廐𥅈𠹶𢱢"],["9e40","𠺢麫絚嗞𡁵抝靭咔賍燶酶揼掹揾啩𢭃鱲𢺳冚㓟𠶧冧呍唞唓癦踭𦢊疱肶蠄螆裇膶萜𡃁䓬猄𤜆宐茋𦢓噻𢛴𧴯𤆣𧵳𦻐𧊶酰𡇙鈈𣳼𪚩𠺬𠻹牦𡲢䝎𤿂𧿹𠿫䃺"],["9ea1","鱝攟𢶠䣳𤟠𩵼𠿬𠸊恢𧖣𠿭"],["9ead","𦁈𡆇熣纎鵐业丄㕷嬍沲卧㚬㧜卽㚥𤘘墚𤭮舭呋垪𥪕𠥹"],["9ec5","㩒𢑥獴𩺬䴉鯭𣳾𩼰䱛𤾩𩖞𩿞葜𣶶𧊲𦞳𣜠挮紥𣻷𣸬㨪逈勌㹴㙺䗩𠒎癀嫰𠺶硺𧼮墧䂿噼鮋嵴癔𪐴麅䳡痹㟻愙𣃚𤏲"],["9ef5","噝𡊩垧𤥣𩸆刴𧂮㖭汊鵼"],["9f40","籖鬹埞𡝬屓擓𩓐𦌵𧅤蚭𠴨𦴢𤫢𠵱"],["9f4f","凾𡼏嶎霃𡷑麁遌笟鬂峑箣扨挵髿篏鬪籾鬮籂粆鰕篼鬉鼗鰛𤤾齚啳寃俽麘俲剠㸆勑坧偖妷帒韈鶫轜呩鞴饀鞺匬愰"],["9fa1","椬叚鰊鴂䰻陁榀傦畆𡝭駚剳"],["9fae","酙隁酜"],["9fb2","酑𨺗捿𦴣櫊嘑醎畺抅𠏼獏籰𥰡𣳽"],["9fc1","𤤙盖鮝个𠳔莾衂"],["9fc9","届槀僭坺刟巵从氱𠇲伹咜哚劚趂㗾弌㗳"],["9fdb","歒酼龥鮗頮颴骺麨麄煺笔"],["9fe7","毺蠘罸"],["9feb","嘠𪙊蹷齓"],["9ff0","跔蹏鸜踁抂𨍽踨蹵竓𤩷稾磘泪詧瘇"],["a040","𨩚鼦泎蟖痃𪊲硓咢贌狢獱謭猂瓱賫𤪻蘯徺袠䒷"],["a055","𡠻𦸅"],["a058","詾𢔛"],["a05b","惽癧髗鵄鍮鮏蟵"],["a063","蠏賷猬霡鮰㗖犲䰇籑饊𦅙慙䰄麖慽"],["a073","坟慯抦戹拎㩜懢厪𣏵捤栂㗒"],["a0a1","嵗𨯂迚𨸹"],["a0a6","僙𡵆礆匲阸𠼻䁥"],["a0ae","矾"],["a0b0","糂𥼚糚稭聦聣絍甅瓲覔舚朌聢𧒆聛瓰脃眤覉𦟌畓𦻑螩蟎臈螌詉貭譃眫瓸蓚㘵榲趦"],["a0d4","覩瑨涹蟁𤀑瓧㷛煶悤憜㳑煢恷"],["a0e2","罱𨬭牐惩䭾删㰘𣳇𥻗𧙖𥔱𡥄𡋾𩤃𦷜𧂭峁𦆭𨨏𣙷𠃮𦡆𤼎䕢嬟𦍌齐麦𦉫"],["a3c0","␀",31,"␡"],["c6a1","①",9,"⑴",9,"ⅰ",9,"丶丿亅亠冂冖冫勹匸卩厶夊宀巛⼳广廴彐彡攴无疒癶辵隶¨ˆヽヾゝゞ〃仝々〆〇ー[]✽ぁ",23],["c740","す",58,"ァアィイ"],["c7a1","ゥ",81,"А",5,"ЁЖ",4],["c840","Л",26,"ёж",25,"⇧↸↹㇏𠃌乚𠂊刂䒑"],["c8a1","龰冈龱𧘇"],["c8cd","¬¦'"㈱№℡゛゜⺀⺄⺆⺇⺈⺊⺌⺍⺕⺜⺝⺥⺧⺪⺬⺮⺶⺼⺾⻆⻊⻌⻍⻏⻖⻗⻞⻣"],["c8f5","ʃɐɛɔɵœøŋʊɪ"],["f9fe","■"],["fa40","𠕇鋛𠗟𣿅蕌䊵珯况㙉𤥂𨧤鍄𡧛苮𣳈砼杄拟𤤳𨦪𠊠𦮳𡌅侫𢓭倈𦴩𧪄𣘀𤪱𢔓倩𠍾徤𠎀𠍇滛𠐟偽儁㑺儎顬㝃萖𤦤𠒇兠𣎴兪𠯿𢃼𠋥𢔰𠖎𣈳𡦃宂蝽𠖳𣲙冲冸"],["faa1","鴴凉减凑㳜凓𤪦决凢卂凭菍椾𣜭彻刋刦刼劵剗劔効勅簕蕂勠蘍𦬓包𨫞啉滙𣾀𠥔𣿬匳卄𠯢泋𡜦栛珕恊㺪㣌𡛨燝䒢卭却𨚫卾卿𡖖𡘓矦厓𨪛厠厫厮玧𥝲㽙玜叁叅汉义埾叙㪫𠮏叠𣿫𢶣叶𠱷吓灹唫晗浛呭𦭓𠵴啝咏咤䞦𡜍𠻝㶴𠵍"],["fb40","𨦼𢚘啇䳭启琗喆喩嘅𡣗𤀺䕒𤐵暳𡂴嘷曍𣊊暤暭噍噏磱囱鞇叾圀囯园𨭦㘣𡉏坆𤆥汮炋坂㚱𦱾埦𡐖堃𡑔𤍣堦𤯵塜墪㕡壠壜𡈼壻寿坃𪅐𤉸鏓㖡够梦㛃湙"],["fba1","𡘾娤啓𡚒蔅姉𠵎𦲁𦴪𡟜姙𡟻𡞲𦶦浱𡠨𡛕姹𦹅媫婣㛦𤦩婷㜈媖瑥嫓𦾡𢕔㶅𡤑㜲𡚸広勐孶斈孼𧨎䀄䡝𠈄寕慠𡨴𥧌𠖥寳宝䴐尅𡭄尓珎尔𡲥𦬨屉䣝岅峩峯嶋𡷹𡸷崐崘嵆𡺤岺巗苼㠭𤤁𢁉𢅳芇㠶㯂帮檊幵幺𤒼𠳓厦亷廐厨𡝱帉廴𨒂"],["fc40","廹廻㢠廼栾鐛弍𠇁弢㫞䢮𡌺强𦢈𢏐彘𢑱彣鞽𦹮彲鍀𨨶徧嶶㵟𥉐𡽪𧃸𢙨釖𠊞𨨩怱暅𡡷㥣㷇㘹垐𢞴祱㹀悞悤悳𤦂𤦏𧩓璤僡媠慤萤慂慈𦻒憁凴𠙖憇宪𣾷"],["fca1","𢡟懓𨮝𩥝懐㤲𢦀𢣁怣慜攞掋𠄘担𡝰拕𢸍捬𤧟㨗搸揸𡎎𡟼撐澊𢸶頔𤂌𥜝擡擥鑻㩦携㩗敍漖𤨨𤨣斅敭敟𣁾斵𤥀䬷旑䃘𡠩无旣忟𣐀昘𣇷𣇸晄𣆤𣆥晋𠹵晧𥇦晳晴𡸽𣈱𨗴𣇈𥌓矅𢣷馤朂𤎜𤨡㬫槺𣟂杞杧杢𤇍𩃭柗䓩栢湐鈼栁𣏦𦶠桝"],["fd40","𣑯槡樋𨫟楳棃𣗍椁椀㴲㨁𣘼㮀枬楡𨩊䋼椶榘㮡𠏉荣傐槹𣙙𢄪橅𣜃檝㯳枱櫈𩆜㰍欝𠤣惞欵歴𢟍溵𣫛𠎵𡥘㝀吡𣭚毡𣻼毜氷𢒋𤣱𦭑汚舦汹𣶼䓅𣶽𤆤𤤌𤤀"],["fda1","𣳉㛥㳫𠴲鮃𣇹𢒑羏样𦴥𦶡𦷫涖浜湼漄𤥿𤂅𦹲蔳𦽴凇沜渝萮𨬡港𣸯瑓𣾂秌湏媑𣁋濸㜍澝𣸰滺𡒗𤀽䕕鏰潄潜㵎潴𩅰㴻澟𤅄濓𤂑𤅕𤀹𣿰𣾴𤄿凟𤅖𤅗𤅀𦇝灋灾炧炁烌烕烖烟䄄㷨熴熖𤉷焫煅媈煊煮岜𤍥煏鍢𤋁焬𤑚𤨧𤨢熺𨯨炽爎"],["fe40","鑂爕夑鑃爤鍁𥘅爮牀𤥴梽牕牗㹕𣁄栍漽犂猪猫𤠣𨠫䣭𨠄猨献珏玪𠰺𦨮珉瑉𤇢𡛧𤨤昣㛅𤦷𤦍𤧻珷琕椃𤨦琹𠗃㻗瑜𢢭瑠𨺲瑇珤瑶莹瑬㜰瑴鏱樬璂䥓𤪌"],["fea1","𤅟𤩹𨮏孆𨰃𡢞瓈𡦈甎瓩甞𨻙𡩋寗𨺬鎅畍畊畧畮𤾂㼄𤴓疎瑝疞疴瘂瘬癑癏癯癶𦏵皐臯㟸𦤑𦤎皡皥皷盌𦾟葢𥂝𥅽𡸜眞眦着撯𥈠睘𣊬瞯𨥤𨥨𡛁矴砉𡍶𤨒棊碯磇磓隥礮𥗠磗礴碱𧘌辸袄𨬫𦂃𢘜禆褀椂禀𥡗禝𧬹礼禩渪𧄦㺨秆𩄍秔"]];
/***/ }),
/***/ 422:
/***/ (function(module) {
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global global, define, System, Reflect, Promise */
var __extends;
var __assign;
var __rest;
var __decorate;
var __param;
var __metadata;
var __awaiter;
var __generator;
var __exportStar;
var __values;
var __read;
var __spread;
var __spreadArrays;
var __await;
var __asyncGenerator;
var __asyncDelegator;
var __asyncValues;
var __makeTemplateObject;
var __importStar;
var __importDefault;
(function (factory) {
var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {};
if (typeof define === "function" && define.amd) {
define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); });
}
else if ( true && typeof module.exports === "object") {
factory(createExporter(root, createExporter(module.exports)));
}
else {
factory(createExporter(root));
}
function createExporter(exports, previous) {
if (exports !== root) {
if (typeof Object.create === "function") {
Object.defineProperty(exports, "__esModule", { value: true });
}
else {
exports.__esModule = true;
}
}
return function (id, v) { return exports[id] = previous ? previous(id, v) : v; };
}
})
(function (exporter) {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
__extends = function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
__assign = Object.assign || function (t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
__rest = function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
__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;
};
__param = function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
__metadata = function (metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
};
__awaiter = function (thisArg, _arguments, P, generator) {
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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
__generator = function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
__exportStar = function (m, exports) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
};
__values = function (o) {
var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
if (m) return m.call(o);
return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
};
__read = function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
__spread = function () {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
};
__spreadArrays = function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
__await = function (v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
};
__asyncGenerator = function (thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
};
__asyncDelegator = function (o) {
var i, p;
return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
};
__asyncValues = function (o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};
__makeTemplateObject = function (cooked, raw) {
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
return cooked;
};
__importStar = function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
__importDefault = function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
exporter("__extends", __extends);
exporter("__assign", __assign);
exporter("__rest", __rest);
exporter("__decorate", __decorate);
exporter("__param", __param);
exporter("__metadata", __metadata);
exporter("__awaiter", __awaiter);
exporter("__generator", __generator);
exporter("__exportStar", __exportStar);
exporter("__values", __values);
exporter("__read", __read);
exporter("__spread", __spread);
exporter("__spreadArrays", __spreadArrays);
exporter("__await", __await);
exporter("__asyncGenerator", __asyncGenerator);
exporter("__asyncDelegator", __asyncDelegator);
exporter("__asyncValues", __asyncValues);
exporter("__makeTemplateObject", __makeTemplateObject);
exporter("__importStar", __importStar);
exporter("__importDefault", __importDefault);
});
/***/ }),
/***/ 426:
/***/ (function(module) {
module.exports = [["0","\u0000",127,"€"],["8140","丂丄丅丆丏丒丗丟丠両丣並丩丮丯丱丳丵丷丼乀乁乂乄乆乊乑乕乗乚乛乢乣乤乥乧乨乪",5,"乲乴",9,"乿",6,"亇亊"],["8180","亐亖亗亙亜亝亞亣亪亯亰亱亴亶亷亸亹亼亽亾仈仌仏仐仒仚仛仜仠仢仦仧仩仭仮仯仱仴仸仹仺仼仾伀伂",6,"伋伌伒",4,"伜伝伡伣伨伩伬伭伮伱伳伵伷伹伻伾",4,"佄佅佇",5,"佒佔佖佡佢佦佨佪佫佭佮佱佲併佷佸佹佺佽侀侁侂侅來侇侊侌侎侐侒侓侕侖侘侙侚侜侞侟価侢"],["8240","侤侫侭侰",4,"侶",8,"俀俁係俆俇俈俉俋俌俍俒",4,"俙俛俠俢俤俥俧俫俬俰俲俴俵俶俷俹俻俼俽俿",11],["8280","個倎倐們倓倕倖倗倛倝倞倠倢倣値倧倫倯",10,"倻倽倿偀偁偂偄偅偆偉偊偋偍偐",4,"偖偗偘偙偛偝",7,"偦",5,"偭",8,"偸偹偺偼偽傁傂傃傄傆傇傉傊傋傌傎",20,"傤傦傪傫傭",4,"傳",6,"傼"],["8340","傽",17,"僐",5,"僗僘僙僛",10,"僨僩僪僫僯僰僱僲僴僶",4,"僼",9,"儈"],["8380","儉儊儌",5,"儓",13,"儢",28,"兂兇兊兌兎兏児兒兓兗兘兙兛兝",4,"兣兤兦內兩兪兯兲兺兾兿冃冄円冇冊冋冎冏冐冑冓冔冘冚冝冞冟冡冣冦",4,"冭冮冴冸冹冺冾冿凁凂凃凅凈凊凍凎凐凒",5],["8440","凘凙凚凜凞凟凢凣凥",5,"凬凮凱凲凴凷凾刄刅刉刋刌刏刐刓刔刕刜刞刟刡刢刣別刦刧刪刬刯刱刲刴刵刼刾剄",5,"剋剎剏剒剓剕剗剘"],["8480","剙剚剛剝剟剠剢剣剤剦剨剫剬剭剮剰剱剳",9,"剾劀劃",4,"劉",6,"劑劒劔",6,"劜劤劥劦劧劮劯劰労",9,"勀勁勂勄勅勆勈勊勌勍勎勏勑勓勔動勗務",5,"勠勡勢勣勥",10,"勱",7,"勻勼勽匁匂匃匄匇匉匊匋匌匎"],["8540","匑匒匓匔匘匛匜匞匟匢匤匥匧匨匩匫匬匭匯",9,"匼匽區卂卄卆卋卌卍卐協単卙卛卝卥卨卪卬卭卲卶卹卻卼卽卾厀厁厃厇厈厊厎厏"],["8580","厐",4,"厖厗厙厛厜厞厠厡厤厧厪厫厬厭厯",6,"厷厸厹厺厼厽厾叀參",4,"収叏叐叒叓叕叚叜叝叞叡叢叧叴叺叾叿吀吂吅吇吋吔吘吙吚吜吢吤吥吪吰吳吶吷吺吽吿呁呂呄呅呇呉呌呍呎呏呑呚呝",4,"呣呥呧呩",7,"呴呹呺呾呿咁咃咅咇咈咉咊咍咑咓咗咘咜咞咟咠咡"],["8640","咢咥咮咰咲咵咶咷咹咺咼咾哃哅哊哋哖哘哛哠",4,"哫哬哯哰哱哴",5,"哻哾唀唂唃唄唅唈唊",4,"唒唓唕",5,"唜唝唞唟唡唥唦"],["8680","唨唩唫唭唲唴唵唶唸唹唺唻唽啀啂啅啇啈啋",4,"啑啒啓啔啗",4,"啝啞啟啠啢啣啨啩啫啯",5,"啹啺啽啿喅喆喌喍喎喐喒喓喕喖喗喚喛喞喠",6,"喨",8,"喲喴営喸喺喼喿",4,"嗆嗇嗈嗊嗋嗎嗏嗐嗕嗗",4,"嗞嗠嗢嗧嗩嗭嗮嗰嗱嗴嗶嗸",4,"嗿嘂嘃嘄嘅"],["8740","嘆嘇嘊嘋嘍嘐",7,"嘙嘚嘜嘝嘠嘡嘢嘥嘦嘨嘩嘪嘫嘮嘯嘰嘳嘵嘷嘸嘺嘼嘽嘾噀",11,"噏",4,"噕噖噚噛噝",4],["8780","噣噥噦噧噭噮噯噰噲噳噴噵噷噸噹噺噽",7,"嚇",6,"嚐嚑嚒嚔",14,"嚤",10,"嚰",6,"嚸嚹嚺嚻嚽",12,"囋",8,"囕囖囘囙囜団囥",5,"囬囮囯囲図囶囷囸囻囼圀圁圂圅圇國",6],["8840","園",9,"圝圞圠圡圢圤圥圦圧圫圱圲圴",4,"圼圽圿坁坃坄坅坆坈坉坋坒",4,"坘坙坢坣坥坧坬坮坰坱坲坴坵坸坹坺坽坾坿垀"],["8880","垁垇垈垉垊垍",4,"垔",6,"垜垝垞垟垥垨垪垬垯垰垱垳垵垶垷垹",8,"埄",6,"埌埍埐埑埓埖埗埛埜埞埡埢埣埥",7,"埮埰埱埲埳埵埶執埻埼埾埿堁堃堄堅堈堉堊堌堎堏堐堒堓堔堖堗堘堚堛堜堝堟堢堣堥",4,"堫",4,"報堲堳場堶",7],["8940","堾",5,"塅",6,"塎塏塐塒塓塕塖塗塙",4,"塟",5,"塦",4,"塭",16,"塿墂墄墆墇墈墊墋墌"],["8980","墍",4,"墔",4,"墛墜墝墠",7,"墪",17,"墽墾墿壀壂壃壄壆",10,"壒壓壔壖",13,"壥",5,"壭壯壱売壴壵壷壸壺",7,"夃夅夆夈",4,"夎夐夑夒夓夗夘夛夝夞夠夡夢夣夦夨夬夰夲夳夵夶夻"],["8a40","夽夾夿奀奃奅奆奊奌奍奐奒奓奙奛",4,"奡奣奤奦",12,"奵奷奺奻奼奾奿妀妅妉妋妌妎妏妐妑妔妕妘妚妛妜妝妟妠妡妢妦"],["8a80","妧妬妭妰妱妳",5,"妺妼妽妿",6,"姇姈姉姌姍姎姏姕姖姙姛姞",4,"姤姦姧姩姪姫姭",11,"姺姼姽姾娀娂娊娋娍娎娏娐娒娔娕娖娗娙娚娛娝娞娡娢娤娦娧娨娪",6,"娳娵娷",4,"娽娾娿婁",4,"婇婈婋",9,"婖婗婘婙婛",5],["8b40","婡婣婤婥婦婨婩婫",8,"婸婹婻婼婽婾媀",17,"媓",6,"媜",13,"媫媬"],["8b80","媭",4,"媴媶媷媹",4,"媿嫀嫃",5,"嫊嫋嫍",4,"嫓嫕嫗嫙嫚嫛嫝嫞嫟嫢嫤嫥嫧嫨嫪嫬",4,"嫲",22,"嬊",11,"嬘",25,"嬳嬵嬶嬸",7,"孁",6],["8c40","孈",7,"孒孖孞孠孡孧孨孫孭孮孯孲孴孶孷學孹孻孼孾孿宂宆宊宍宎宐宑宒宔宖実宧宨宩宬宭宮宯宱宲宷宺宻宼寀寁寃寈寉寊寋寍寎寏"],["8c80","寑寔",8,"寠寢寣實寧審",4,"寯寱",6,"寽対尀専尃尅將專尋尌對導尐尒尓尗尙尛尞尟尠尡尣尦尨尩尪尫尭尮尯尰尲尳尵尶尷屃屄屆屇屌屍屒屓屔屖屗屘屚屛屜屝屟屢層屧",6,"屰屲",6,"屻屼屽屾岀岃",4,"岉岊岋岎岏岒岓岕岝",4,"岤",4],["8d40","岪岮岯岰岲岴岶岹岺岻岼岾峀峂峃峅",5,"峌",5,"峓",5,"峚",6,"峢峣峧峩峫峬峮峯峱",9,"峼",4],["8d80","崁崄崅崈",5,"崏",4,"崕崗崘崙崚崜崝崟",4,"崥崨崪崫崬崯",4,"崵",7,"崿",7,"嵈嵉嵍",10,"嵙嵚嵜嵞",10,"嵪嵭嵮嵰嵱嵲嵳嵵",12,"嶃",21,"嶚嶛嶜嶞嶟嶠"],["8e40","嶡",21,"嶸",12,"巆",6,"巎",12,"巜巟巠巣巤巪巬巭"],["8e80","巰巵巶巸",4,"巿帀帄帇帉帊帋帍帎帒帓帗帞",7,"帨",4,"帯帰帲",4,"帹帺帾帿幀幁幃幆",5,"幍",6,"幖",4,"幜幝幟幠幣",14,"幵幷幹幾庁庂広庅庈庉庌庍庎庒庘庛庝庡庢庣庤庨",4,"庮",4,"庴庺庻庼庽庿",6],["8f40","廆廇廈廋",5,"廔廕廗廘廙廚廜",11,"廩廫",8,"廵廸廹廻廼廽弅弆弇弉弌弍弎弐弒弔弖弙弚弜弝弞弡弢弣弤"],["8f80","弨弫弬弮弰弲",6,"弻弽弾弿彁",14,"彑彔彙彚彛彜彞彟彠彣彥彧彨彫彮彯彲彴彵彶彸彺彽彾彿徃徆徍徎徏徑従徔徖徚徛徝從徟徠徢",5,"復徫徬徯",5,"徶徸徹徺徻徾",4,"忇忈忊忋忎忓忔忕忚忛応忞忟忢忣忥忦忨忩忬忯忰忲忳忴忶忷忹忺忼怇"],["9040","怈怉怋怌怐怑怓怗怘怚怞怟怢怣怤怬怭怮怰",4,"怶",4,"怽怾恀恄",6,"恌恎恏恑恓恔恖恗恘恛恜恞恟恠恡恥恦恮恱恲恴恵恷恾悀"],["9080","悁悂悅悆悇悈悊悋悎悏悐悑悓悕悗悘悙悜悞悡悢悤悥悧悩悪悮悰悳悵悶悷悹悺悽",7,"惇惈惉惌",4,"惒惓惔惖惗惙惛惞惡",4,"惪惱惲惵惷惸惻",4,"愂愃愄愅愇愊愋愌愐",4,"愖愗愘愙愛愜愝愞愡愢愥愨愩愪愬",18,"慀",6],["9140","慇慉態慍慏慐慒慓慔慖",6,"慞慟慠慡慣慤慥慦慩",6,"慱慲慳慴慶慸",18,"憌憍憏",4,"憕"],["9180","憖",6,"憞",8,"憪憫憭",9,"憸",5,"憿懀懁懃",4,"應懌",4,"懓懕",16,"懧",13,"懶",8,"戀",5,"戇戉戓戔戙戜戝戞戠戣戦戧戨戩戫戭戯戰戱戲戵戶戸",4,"扂扄扅扆扊"],["9240","扏扐払扖扗扙扚扜",6,"扤扥扨扱扲扴扵扷扸扺扻扽抁抂抃抅抆抇抈抋",5,"抔抙抜抝択抣抦抧抩抪抭抮抯抰抲抳抴抶抷抸抺抾拀拁"],["9280","拃拋拏拑拕拝拞拠拡拤拪拫拰拲拵拸拹拺拻挀挃挄挅挆挊挋挌挍挏挐挒挓挔挕挗挘挙挜挦挧挩挬挭挮挰挱挳",5,"挻挼挾挿捀捁捄捇捈捊捑捒捓捔捖",7,"捠捤捥捦捨捪捫捬捯捰捲捳捴捵捸捹捼捽捾捿掁掃掄掅掆掋掍掑掓掔掕掗掙",6,"採掤掦掫掯掱掲掵掶掹掻掽掿揀"],["9340","揁揂揃揅揇揈揊揋揌揑揓揔揕揗",6,"揟揢揤",4,"揫揬揮揯揰揱揳揵揷揹揺揻揼揾搃搄搆",4,"損搎搑搒搕",5,"搝搟搢搣搤"],["9380","搥搧搨搩搫搮",5,"搵",4,"搻搼搾摀摂摃摉摋",6,"摓摕摖摗摙",4,"摟",7,"摨摪摫摬摮",9,"摻",6,"撃撆撈",8,"撓撔撗撘撚撛撜撝撟",4,"撥撦撧撨撪撫撯撱撲撳撴撶撹撻撽撾撿擁擃擄擆",6,"擏擑擓擔擕擖擙據"],["9440","擛擜擝擟擠擡擣擥擧",24,"攁",7,"攊",7,"攓",4,"攙",8],["9480","攢攣攤攦",4,"攬攭攰攱攲攳攷攺攼攽敀",4,"敆敇敊敋敍敎敐敒敓敔敗敘敚敜敟敠敡敤敥敧敨敩敪敭敮敯敱敳敵敶數",14,"斈斉斊斍斎斏斒斔斕斖斘斚斝斞斠斢斣斦斨斪斬斮斱",7,"斺斻斾斿旀旂旇旈旉旊旍旐旑旓旔旕旘",7,"旡旣旤旪旫"],["9540","旲旳旴旵旸旹旻",4,"昁昄昅昇昈昉昋昍昐昑昒昖昗昘昚昛昜昞昡昢昣昤昦昩昪昫昬昮昰昲昳昷",4,"昽昿晀時晄",6,"晍晎晐晑晘"],["9580","晙晛晜晝晞晠晢晣晥晧晩",4,"晱晲晳晵晸晹晻晼晽晿暀暁暃暅暆暈暉暊暋暍暎暏暐暒暓暔暕暘",4,"暞",8,"暩",4,"暯",4,"暵暶暷暸暺暻暼暽暿",25,"曚曞",7,"曧曨曪",5,"曱曵曶書曺曻曽朁朂會"],["9640","朄朅朆朇朌朎朏朑朒朓朖朘朙朚朜朞朠",5,"朧朩朮朰朲朳朶朷朸朹朻朼朾朿杁杄杅杇杊杋杍杒杔杕杗",4,"杝杢杣杤杦杧杫杬杮東杴杶"],["9680","杸杹杺杻杽枀枂枃枅枆枈枊枌枍枎枏枑枒枓枔枖枙枛枟枠枡枤枦枩枬枮枱枲枴枹",7,"柂柅",9,"柕柖柗柛柟柡柣柤柦柧柨柪柫柭柮柲柵",7,"柾栁栂栃栄栆栍栐栒栔栕栘",4,"栞栟栠栢",6,"栫",6,"栴栵栶栺栻栿桇桋桍桏桒桖",5],["9740","桜桝桞桟桪桬",7,"桵桸",8,"梂梄梇",7,"梐梑梒梔梕梖梘",9,"梣梤梥梩梪梫梬梮梱梲梴梶梷梸"],["9780","梹",6,"棁棃",5,"棊棌棎棏棐棑棓棔棖棗棙棛",4,"棡棢棤",9,"棯棲棳棴棶棷棸棻棽棾棿椀椂椃椄椆",4,"椌椏椑椓",11,"椡椢椣椥",7,"椮椯椱椲椳椵椶椷椸椺椻椼椾楀楁楃",16,"楕楖楘楙楛楜楟"],["9840","楡楢楤楥楧楨楩楪楬業楯楰楲",4,"楺楻楽楾楿榁榃榅榊榋榌榎",5,"榖榗榙榚榝",9,"榩榪榬榮榯榰榲榳榵榶榸榹榺榼榽"],["9880","榾榿槀槂",7,"構槍槏槑槒槓槕",5,"槜槝槞槡",11,"槮槯槰槱槳",9,"槾樀",9,"樋",11,"標",5,"樠樢",5,"権樫樬樭樮樰樲樳樴樶",6,"樿",4,"橅橆橈",7,"橑",6,"橚"],["9940","橜",4,"橢橣橤橦",10,"橲",6,"橺橻橽橾橿檁檂檃檅",8,"檏檒",4,"檘",7,"檡",5],["9980","檧檨檪檭",114,"欥欦欨",6],["9a40","欯欰欱欳欴欵欶欸欻欼欽欿歀歁歂歄歅歈歊歋歍",11,"歚",7,"歨歩歫",13,"歺歽歾歿殀殅殈"],["9a80","殌殎殏殐殑殔殕殗殘殙殜",4,"殢",7,"殫",7,"殶殸",6,"毀毃毄毆",4,"毌毎毐毑毘毚毜",4,"毢",7,"毬毭毮毰毱毲毴毶毷毸毺毻毼毾",6,"氈",4,"氎氒気氜氝氞氠氣氥氫氬氭氱氳氶氷氹氺氻氼氾氿汃汄汅汈汋",4,"汑汒汓汖汘"],["9b40","汙汚汢汣汥汦汧汫",4,"汱汳汵汷汸決汻汼汿沀沄沇沊沋沍沎沑沒沕沖沗沘沚沜沝沞沠沢沨沬沯沰沴沵沶沷沺泀況泂泃泆泇泈泋泍泎泏泑泒泘"],["9b80","泙泚泜泝泟泤泦泧泩泬泭泲泴泹泿洀洂洃洅洆洈洉洊洍洏洐洑洓洔洕洖洘洜洝洟",5,"洦洨洩洬洭洯洰洴洶洷洸洺洿浀浂浄浉浌浐浕浖浗浘浛浝浟浡浢浤浥浧浨浫浬浭浰浱浲浳浵浶浹浺浻浽",4,"涃涄涆涇涊涋涍涏涐涒涖",4,"涜涢涥涬涭涰涱涳涴涶涷涹",5,"淁淂淃淈淉淊"],["9c40","淍淎淏淐淒淓淔淕淗淚淛淜淟淢淣淥淧淨淩淪淭淯淰淲淴淵淶淸淺淽",7,"渆渇済渉渋渏渒渓渕渘渙減渜渞渟渢渦渧渨渪測渮渰渱渳渵"],["9c80","渶渷渹渻",7,"湅",7,"湏湐湑湒湕湗湙湚湜湝湞湠",10,"湬湭湯",14,"満溁溂溄溇溈溊",4,"溑",6,"溙溚溛溝溞溠溡溣溤溦溨溩溫溬溭溮溰溳溵溸溹溼溾溿滀滃滄滅滆滈滉滊滌滍滎滐滒滖滘滙滛滜滝滣滧滪",5],["9d40","滰滱滲滳滵滶滷滸滺",7,"漃漄漅漇漈漊",4,"漐漑漒漖",9,"漡漢漣漥漦漧漨漬漮漰漲漴漵漷",6,"漿潀潁潂"],["9d80","潃潄潅潈潉潊潌潎",9,"潙潚潛潝潟潠潡潣潤潥潧",5,"潯潰潱潳潵潶潷潹潻潽",6,"澅澆澇澊澋澏",12,"澝澞澟澠澢",4,"澨",10,"澴澵澷澸澺",5,"濁濃",5,"濊",6,"濓",10,"濟濢濣濤濥"],["9e40","濦",7,"濰",32,"瀒",7,"瀜",6,"瀤",6],["9e80","瀫",9,"瀶瀷瀸瀺",17,"灍灎灐",13,"灟",11,"灮灱灲灳灴灷灹灺灻災炁炂炃炄炆炇炈炋炌炍炏炐炑炓炗炘炚炛炞",12,"炰炲炴炵炶為炾炿烄烅烆烇烉烋",12,"烚"],["9f40","烜烝烞烠烡烢烣烥烪烮烰",6,"烸烺烻烼烾",10,"焋",4,"焑焒焔焗焛",10,"焧",7,"焲焳焴"],["9f80","焵焷",13,"煆煇煈煉煋煍煏",12,"煝煟",4,"煥煩",4,"煯煰煱煴煵煶煷煹煻煼煾",5,"熅",4,"熋熌熍熎熐熑熒熓熕熖熗熚",4,"熡",6,"熩熪熫熭",5,"熴熶熷熸熺",8,"燄",9,"燏",4],["a040","燖",9,"燡燢燣燤燦燨",5,"燯",9,"燺",11,"爇",19],["a080","爛爜爞",9,"爩爫爭爮爯爲爳爴爺爼爾牀",6,"牉牊牋牎牏牐牑牓牔牕牗牘牚牜牞牠牣牤牥牨牪牫牬牭牰牱牳牴牶牷牸牻牼牽犂犃犅",4,"犌犎犐犑犓",11,"犠",11,"犮犱犲犳犵犺",6,"狅狆狇狉狊狋狌狏狑狓狔狕狖狘狚狛"],["a1a1"," 、。·ˉˇ¨〃々—~‖…‘’“”〔〕〈",7,"〖〗【】±×÷∶∧∨∑∏∪∩∈∷√⊥∥∠⌒⊙∫∮≡≌≈∽∝≠≮≯≤≥∞∵∴♂♀°′″℃$¤¢£‰§№☆★○●◎◇◆□■△▲※→←↑↓〓"],["a2a1","ⅰ",9],["a2b1","⒈",19,"⑴",19,"①",9],["a2e5","㈠",9],["a2f1","Ⅰ",11],["a3a1","!"#¥%",88," ̄"],["a4a1","ぁ",82],["a5a1","ァ",85],["a6a1","Α",16,"Σ",6],["a6c1","α",16,"σ",6],["a6e0","︵︶︹︺︿﹀︽︾﹁﹂﹃﹄"],["a6ee","︻︼︷︸︱"],["a6f4","︳︴"],["a7a1","А",5,"ЁЖ",25],["a7d1","а",5,"ёж",25],["a840","ˊˋ˙–―‥‵℅℉↖↗↘↙∕∟∣≒≦≧⊿═",35,"▁",6],["a880","█",7,"▓▔▕▼▽◢◣◤◥☉⊕〒〝〞"],["a8a1","āáǎàēéěèīíǐìōóǒòūúǔùǖǘǚǜüêɑ"],["a8bd","ńň"],["a8c0","ɡ"],["a8c5","ㄅ",36],["a940","〡",8,"㊣㎎㎏㎜㎝㎞㎡㏄㏎㏑㏒㏕︰¬¦"],["a959","℡㈱"],["a95c","‐"],["a960","ー゛゜ヽヾ〆ゝゞ﹉",9,"﹔﹕﹖﹗﹙",8],["a980","﹢",4,"﹨﹩﹪﹫"],["a996","〇"],["a9a4","─",75],["aa40","狜狝狟狢",5,"狪狫狵狶狹狽狾狿猀猂猄",5,"猋猌猍猏猐猑猒猔猘猙猚猟猠猣猤猦猧猨猭猯猰猲猳猵猶猺猻猼猽獀",8],["aa80","獉獊獋獌獎獏獑獓獔獕獖獘",7,"獡",10,"獮獰獱"],["ab40","獲",11,"獿",4,"玅玆玈玊玌玍玏玐玒玓玔玕玗玘玙玚玜玝玞玠玡玣",5,"玪玬玭玱玴玵玶玸玹玼玽玾玿珁珃",4],["ab80","珋珌珎珒",6,"珚珛珜珝珟珡珢珣珤珦珨珪珫珬珮珯珰珱珳",4],["ac40","珸",10,"琄琇琈琋琌琍琎琑",8,"琜",5,"琣琤琧琩琫琭琯琱琲琷",4,"琽琾琿瑀瑂",11],["ac80","瑎",6,"瑖瑘瑝瑠",12,"瑮瑯瑱",4,"瑸瑹瑺"],["ad40","瑻瑼瑽瑿璂璄璅璆璈璉璊璌璍璏璑",10,"璝璟",7,"璪",15,"璻",12],["ad80","瓈",9,"瓓",8,"瓝瓟瓡瓥瓧",6,"瓰瓱瓲"],["ae40","瓳瓵瓸",6,"甀甁甂甃甅",7,"甎甐甒甔甕甖甗甛甝甞甠",4,"甦甧甪甮甴甶甹甼甽甿畁畂畃畄畆畇畉畊畍畐畑畒畓畕畖畗畘"],["ae80","畝",7,"畧畨畩畫",6,"畳畵當畷畺",4,"疀疁疂疄疅疇"],["af40","疈疉疊疌疍疎疐疓疕疘疛疜疞疢疦",4,"疭疶疷疺疻疿痀痁痆痋痌痎痏痐痑痓痗痙痚痜痝痟痠痡痥痩痬痭痮痯痲痳痵痶痷痸痺痻痽痾瘂瘄瘆瘇"],["af80","瘈瘉瘋瘍瘎瘏瘑瘒瘓瘔瘖瘚瘜瘝瘞瘡瘣瘧瘨瘬瘮瘯瘱瘲瘶瘷瘹瘺瘻瘽癁療癄"],["b040","癅",6,"癎",5,"癕癗",4,"癝癟癠癡癢癤",6,"癬癭癮癰",7,"癹発發癿皀皁皃皅皉皊皌皍皏皐皒皔皕皗皘皚皛"],["b080","皜",7,"皥",8,"皯皰皳皵",9,"盀盁盃啊阿埃挨哎唉哀皑癌蔼矮艾碍爱隘鞍氨安俺按暗岸胺案肮昂盎凹敖熬翱袄傲奥懊澳芭捌扒叭吧笆八疤巴拔跋靶把耙坝霸罢爸白柏百摆佰败拜稗斑班搬扳般颁板版扮拌伴瓣半办绊邦帮梆榜膀绑棒磅蚌镑傍谤苞胞包褒剥"],["b140","盄盇盉盋盌盓盕盙盚盜盝盞盠",4,"盦",7,"盰盳盵盶盷盺盻盽盿眀眂眃眅眆眊県眎",10,"眛眜眝眞眡眣眤眥眧眪眫"],["b180","眬眮眰",4,"眹眻眽眾眿睂睄睅睆睈",7,"睒",7,"睜薄雹保堡饱宝抱报暴豹鲍爆杯碑悲卑北辈背贝钡倍狈备惫焙被奔苯本笨崩绷甭泵蹦迸逼鼻比鄙笔彼碧蓖蔽毕毙毖币庇痹闭敝弊必辟壁臂避陛鞭边编贬扁便变卞辨辩辫遍标彪膘表鳖憋别瘪彬斌濒滨宾摈兵冰柄丙秉饼炳"],["b240","睝睞睟睠睤睧睩睪睭",11,"睺睻睼瞁瞂瞃瞆",5,"瞏瞐瞓",11,"瞡瞣瞤瞦瞨瞫瞭瞮瞯瞱瞲瞴瞶",4],["b280","瞼瞾矀",12,"矎",8,"矘矙矚矝",4,"矤病并玻菠播拨钵波博勃搏铂箔伯帛舶脖膊渤泊驳捕卜哺补埠不布步簿部怖擦猜裁材才财睬踩采彩菜蔡餐参蚕残惭惨灿苍舱仓沧藏操糙槽曹草厕策侧册测层蹭插叉茬茶查碴搽察岔差诧拆柴豺搀掺蝉馋谗缠铲产阐颤昌猖"],["b340","矦矨矪矯矰矱矲矴矵矷矹矺矻矼砃",5,"砊砋砎砏砐砓砕砙砛砞砠砡砢砤砨砪砫砮砯砱砲砳砵砶砽砿硁硂硃硄硆硈硉硊硋硍硏硑硓硔硘硙硚"],["b380","硛硜硞",11,"硯",7,"硸硹硺硻硽",6,"场尝常长偿肠厂敞畅唱倡超抄钞朝嘲潮巢吵炒车扯撤掣彻澈郴臣辰尘晨忱沉陈趁衬撑称城橙成呈乘程惩澄诚承逞骋秤吃痴持匙池迟弛驰耻齿侈尺赤翅斥炽充冲虫崇宠抽酬畴踌稠愁筹仇绸瞅丑臭初出橱厨躇锄雏滁除楚"],["b440","碄碅碆碈碊碋碏碐碒碔碕碖碙碝碞碠碢碤碦碨",7,"碵碶碷碸確碻碼碽碿磀磂磃磄磆磇磈磌磍磎磏磑磒磓磖磗磘磚",9],["b480","磤磥磦磧磩磪磫磭",4,"磳磵磶磸磹磻",5,"礂礃礄礆",6,"础储矗搐触处揣川穿椽传船喘串疮窗幢床闯创吹炊捶锤垂春椿醇唇淳纯蠢戳绰疵茨磁雌辞慈瓷词此刺赐次聪葱囱匆从丛凑粗醋簇促蹿篡窜摧崔催脆瘁粹淬翠村存寸磋撮搓措挫错搭达答瘩打大呆歹傣戴带殆代贷袋待逮"],["b540","礍",5,"礔",9,"礟",4,"礥",14,"礵",4,"礽礿祂祃祄祅祇祊",8,"祔祕祘祙祡祣"],["b580","祤祦祩祪祫祬祮祰",6,"祹祻",4,"禂禃禆禇禈禉禋禌禍禎禐禑禒怠耽担丹单郸掸胆旦氮但惮淡诞弹蛋当挡党荡档刀捣蹈倒岛祷导到稻悼道盗德得的蹬灯登等瞪凳邓堤低滴迪敌笛狄涤翟嫡抵底地蒂第帝弟递缔颠掂滇碘点典靛垫电佃甸店惦奠淀殿碉叼雕凋刁掉吊钓调跌爹碟蝶迭谍叠"],["b640","禓",6,"禛",11,"禨",10,"禴",4,"禼禿秂秄秅秇秈秊秌秎秏秐秓秔秖秗秙",5,"秠秡秢秥秨秪"],["b680","秬秮秱",6,"秹秺秼秾秿稁稄稅稇稈稉稊稌稏",4,"稕稖稘稙稛稜丁盯叮钉顶鼎锭定订丢东冬董懂动栋侗恫冻洞兜抖斗陡豆逗痘都督毒犊独读堵睹赌杜镀肚度渡妒端短锻段断缎堆兑队对墩吨蹲敦顿囤钝盾遁掇哆多夺垛躲朵跺舵剁惰堕蛾峨鹅俄额讹娥恶厄扼遏鄂饿恩而儿耳尔饵洱二"],["b740","稝稟稡稢稤",14,"稴稵稶稸稺稾穀",5,"穇",9,"穒",4,"穘",16],["b780","穩",6,"穱穲穳穵穻穼穽穾窂窅窇窉窊窋窌窎窏窐窓窔窙窚窛窞窡窢贰发罚筏伐乏阀法珐藩帆番翻樊矾钒繁凡烦反返范贩犯饭泛坊芳方肪房防妨仿访纺放菲非啡飞肥匪诽吠肺废沸费芬酚吩氛分纷坟焚汾粉奋份忿愤粪丰封枫蜂峰锋风疯烽逢冯缝讽奉凤佛否夫敷肤孵扶拂辐幅氟符伏俘服"],["b840","窣窤窧窩窪窫窮",4,"窴",10,"竀",10,"竌",9,"竗竘竚竛竜竝竡竢竤竧",5,"竮竰竱竲竳"],["b880","竴",4,"竻竼竾笀笁笂笅笇笉笌笍笎笐笒笓笖笗笘笚笜笝笟笡笢笣笧笩笭浮涪福袱弗甫抚辅俯釜斧脯腑府腐赴副覆赋复傅付阜父腹负富讣附妇缚咐噶嘎该改概钙盖溉干甘杆柑竿肝赶感秆敢赣冈刚钢缸肛纲岗港杠篙皋高膏羔糕搞镐稿告哥歌搁戈鸽胳疙割革葛格蛤阁隔铬个各给根跟耕更庚羹"],["b940","笯笰笲笴笵笶笷笹笻笽笿",5,"筆筈筊筍筎筓筕筗筙筜筞筟筡筣",10,"筯筰筳筴筶筸筺筼筽筿箁箂箃箄箆",6,"箎箏"],["b980","箑箒箓箖箘箙箚箛箞箟箠箣箤箥箮箯箰箲箳箵箶箷箹",7,"篂篃範埂耿梗工攻功恭龚供躬公宫弓巩汞拱贡共钩勾沟苟狗垢构购够辜菇咕箍估沽孤姑鼓古蛊骨谷股故顾固雇刮瓜剐寡挂褂乖拐怪棺关官冠观管馆罐惯灌贯光广逛瑰规圭硅归龟闺轨鬼诡癸桂柜跪贵刽辊滚棍锅郭国果裹过哈"],["ba40","篅篈築篊篋篍篎篏篐篒篔",4,"篛篜篞篟篠篢篣篤篧篨篩篫篬篭篯篰篲",4,"篸篹篺篻篽篿",7,"簈簉簊簍簎簐",5,"簗簘簙"],["ba80","簚",4,"簠",5,"簨簩簫",12,"簹",5,"籂骸孩海氦亥害骇酣憨邯韩含涵寒函喊罕翰撼捍旱憾悍焊汗汉夯杭航壕嚎豪毫郝好耗号浩呵喝荷菏核禾和何合盒貉阂河涸赫褐鹤贺嘿黑痕很狠恨哼亨横衡恒轰哄烘虹鸿洪宏弘红喉侯猴吼厚候后呼乎忽瑚壶葫胡蝴狐糊湖"],["bb40","籃",9,"籎",36,"籵",5,"籾",9],["bb80","粈粊",6,"粓粔粖粙粚粛粠粡粣粦粧粨粩粫粬粭粯粰粴",4,"粺粻弧虎唬护互沪户花哗华猾滑画划化话槐徊怀淮坏欢环桓还缓换患唤痪豢焕涣宦幻荒慌黄磺蝗簧皇凰惶煌晃幌恍谎灰挥辉徽恢蛔回毁悔慧卉惠晦贿秽会烩汇讳诲绘荤昏婚魂浑混豁活伙火获或惑霍货祸击圾基机畸稽积箕"],["bc40","粿糀糂糃糄糆糉糋糎",6,"糘糚糛糝糞糡",6,"糩",5,"糰",7,"糹糺糼",13,"紋",5],["bc80","紑",14,"紡紣紤紥紦紨紩紪紬紭紮細",6,"肌饥迹激讥鸡姬绩缉吉极棘辑籍集及急疾汲即嫉级挤几脊己蓟技冀季伎祭剂悸济寄寂计记既忌际妓继纪嘉枷夹佳家加荚颊贾甲钾假稼价架驾嫁歼监坚尖笺间煎兼肩艰奸缄茧检柬碱硷拣捡简俭剪减荐槛鉴践贱见键箭件"],["bd40","紷",54,"絯",7],["bd80","絸",32,"健舰剑饯渐溅涧建僵姜将浆江疆蒋桨奖讲匠酱降蕉椒礁焦胶交郊浇骄娇嚼搅铰矫侥脚狡角饺缴绞剿教酵轿较叫窖揭接皆秸街阶截劫节桔杰捷睫竭洁结解姐戒藉芥界借介疥诫届巾筋斤金今津襟紧锦仅谨进靳晋禁近烬浸"],["be40","継",12,"綧",6,"綯",42],["be80","線",32,"尽劲荆兢茎睛晶鲸京惊精粳经井警景颈静境敬镜径痉靖竟竞净炯窘揪究纠玖韭久灸九酒厩救旧臼舅咎就疚鞠拘狙疽居驹菊局咀矩举沮聚拒据巨具距踞锯俱句惧炬剧捐鹃娟倦眷卷绢撅攫抉掘倔爵觉决诀绝均菌钧军君峻"],["bf40","緻",62],["bf80","縺縼",4,"繂",4,"繈",21,"俊竣浚郡骏喀咖卡咯开揩楷凯慨刊堪勘坎砍看康慷糠扛抗亢炕考拷烤靠坷苛柯棵磕颗科壳咳可渴克刻客课肯啃垦恳坑吭空恐孔控抠口扣寇枯哭窟苦酷库裤夸垮挎跨胯块筷侩快宽款匡筐狂框矿眶旷况亏盔岿窥葵奎魁傀"],["c040","繞",35,"纃",23,"纜纝纞"],["c080","纮纴纻纼绖绤绬绹缊缐缞缷缹缻",6,"罃罆",9,"罒罓馈愧溃坤昆捆困括扩廓阔垃拉喇蜡腊辣啦莱来赖蓝婪栏拦篮阑兰澜谰揽览懒缆烂滥琅榔狼廊郎朗浪捞劳牢老佬姥酪烙涝勒乐雷镭蕾磊累儡垒擂肋类泪棱楞冷厘梨犁黎篱狸离漓理李里鲤礼莉荔吏栗丽厉励砾历利傈例俐"],["c140","罖罙罛罜罝罞罠罣",4,"罫罬罭罯罰罳罵罶罷罸罺罻罼罽罿羀羂",7,"羋羍羏",4,"羕",4,"羛羜羠羢羣羥羦羨",6,"羱"],["c180","羳",4,"羺羻羾翀翂翃翄翆翇翈翉翋翍翏",4,"翖翗翙",5,"翢翣痢立粒沥隶力璃哩俩联莲连镰廉怜涟帘敛脸链恋炼练粮凉梁粱良两辆量晾亮谅撩聊僚疗燎寥辽潦了撂镣廖料列裂烈劣猎琳林磷霖临邻鳞淋凛赁吝拎玲菱零龄铃伶羚凌灵陵岭领另令溜琉榴硫馏留刘瘤流柳六龙聋咙笼窿"],["c240","翤翧翨翪翫翬翭翯翲翴",6,"翽翾翿耂耇耈耉耊耎耏耑耓耚耛耝耞耟耡耣耤耫",5,"耲耴耹耺耼耾聀聁聄聅聇聈聉聎聏聐聑聓聕聖聗"],["c280","聙聛",13,"聫",5,"聲",11,"隆垄拢陇楼娄搂篓漏陋芦卢颅庐炉掳卤虏鲁麓碌露路赂鹿潞禄录陆戮驴吕铝侣旅履屡缕虑氯律率滤绿峦挛孪滦卵乱掠略抡轮伦仑沦纶论萝螺罗逻锣箩骡裸落洛骆络妈麻玛码蚂马骂嘛吗埋买麦卖迈脉瞒馒蛮满蔓曼慢漫"],["c340","聾肁肂肅肈肊肍",5,"肔肕肗肙肞肣肦肧肨肬肰肳肵肶肸肹肻胅胇",4,"胏",6,"胘胟胠胢胣胦胮胵胷胹胻胾胿脀脁脃脄脅脇脈脋"],["c380","脌脕脗脙脛脜脝脟",12,"脭脮脰脳脴脵脷脹",4,"脿谩芒茫盲氓忙莽猫茅锚毛矛铆卯茂冒帽貌贸么玫枚梅酶霉煤没眉媒镁每美昧寐妹媚门闷们萌蒙檬盟锰猛梦孟眯醚靡糜迷谜弥米秘觅泌蜜密幂棉眠绵冕免勉娩缅面苗描瞄藐秒渺庙妙蔑灭民抿皿敏悯闽明螟鸣铭名命谬摸"],["c440","腀",5,"腇腉腍腎腏腒腖腗腘腛",4,"腡腢腣腤腦腨腪腫腬腯腲腳腵腶腷腸膁膃",4,"膉膋膌膍膎膐膒",5,"膙膚膞",4,"膤膥"],["c480","膧膩膫",7,"膴",5,"膼膽膾膿臄臅臇臈臉臋臍",6,"摹蘑模膜磨摩魔抹末莫墨默沫漠寞陌谋牟某拇牡亩姆母墓暮幕募慕木目睦牧穆拿哪呐钠那娜纳氖乃奶耐奈南男难囊挠脑恼闹淖呢馁内嫩能妮霓倪泥尼拟你匿腻逆溺蔫拈年碾撵捻念娘酿鸟尿捏聂孽啮镊镍涅您柠狞凝宁"],["c540","臔",14,"臤臥臦臨臩臫臮",4,"臵",5,"臽臿舃與",4,"舎舏舑舓舕",5,"舝舠舤舥舦舧舩舮舲舺舼舽舿"],["c580","艀艁艂艃艅艆艈艊艌艍艎艐",7,"艙艛艜艝艞艠",7,"艩拧泞牛扭钮纽脓浓农弄奴努怒女暖虐疟挪懦糯诺哦欧鸥殴藕呕偶沤啪趴爬帕怕琶拍排牌徘湃派攀潘盘磐盼畔判叛乓庞旁耪胖抛咆刨炮袍跑泡呸胚培裴赔陪配佩沛喷盆砰抨烹澎彭蓬棚硼篷膨朋鹏捧碰坯砒霹批披劈琵毗"],["c640","艪艫艬艭艱艵艶艷艸艻艼芀芁芃芅芆芇芉芌芐芓芔芕芖芚芛芞芠芢芣芧芲芵芶芺芻芼芿苀苂苃苅苆苉苐苖苙苚苝苢苧苨苩苪苬苭苮苰苲苳苵苶苸"],["c680","苺苼",4,"茊茋茍茐茒茓茖茘茙茝",9,"茩茪茮茰茲茷茻茽啤脾疲皮匹痞僻屁譬篇偏片骗飘漂瓢票撇瞥拼频贫品聘乒坪苹萍平凭瓶评屏坡泼颇婆破魄迫粕剖扑铺仆莆葡菩蒲埔朴圃普浦谱曝瀑期欺栖戚妻七凄漆柒沏其棋奇歧畦崎脐齐旗祈祁骑起岂乞企启契砌器气迄弃汽泣讫掐"],["c740","茾茿荁荂荄荅荈荊",4,"荓荕",4,"荝荢荰",6,"荹荺荾",6,"莇莈莊莋莌莍莏莐莑莔莕莖莗莙莚莝莟莡",6,"莬莭莮"],["c780","莯莵莻莾莿菂菃菄菆菈菉菋菍菎菐菑菒菓菕菗菙菚菛菞菢菣菤菦菧菨菫菬菭恰洽牵扦钎铅千迁签仟谦乾黔钱钳前潜遣浅谴堑嵌欠歉枪呛腔羌墙蔷强抢橇锹敲悄桥瞧乔侨巧鞘撬翘峭俏窍切茄且怯窃钦侵亲秦琴勤芹擒禽寝沁青轻氢倾卿清擎晴氰情顷请庆琼穷秋丘邱球求囚酋泅趋区蛆曲躯屈驱渠"],["c840","菮華菳",4,"菺菻菼菾菿萀萂萅萇萈萉萊萐萒",5,"萙萚萛萞",5,"萩",7,"萲",5,"萹萺萻萾",7,"葇葈葉"],["c880","葊",6,"葒",4,"葘葝葞葟葠葢葤",4,"葪葮葯葰葲葴葷葹葻葼取娶龋趣去圈颧权醛泉全痊拳犬券劝缺炔瘸却鹊榷确雀裙群然燃冉染瓤壤攘嚷让饶扰绕惹热壬仁人忍韧任认刃妊纫扔仍日戎茸蓉荣融熔溶容绒冗揉柔肉茹蠕儒孺如辱乳汝入褥软阮蕊瑞锐闰润若弱撒洒萨腮鳃塞赛三叁"],["c940","葽",4,"蒃蒄蒅蒆蒊蒍蒏",7,"蒘蒚蒛蒝蒞蒟蒠蒢",12,"蒰蒱蒳蒵蒶蒷蒻蒼蒾蓀蓂蓃蓅蓆蓇蓈蓋蓌蓎蓏蓒蓔蓕蓗"],["c980","蓘",4,"蓞蓡蓢蓤蓧",4,"蓭蓮蓯蓱",10,"蓽蓾蔀蔁蔂伞散桑嗓丧搔骚扫嫂瑟色涩森僧莎砂杀刹沙纱傻啥煞筛晒珊苫杉山删煽衫闪陕擅赡膳善汕扇缮墒伤商赏晌上尚裳梢捎稍烧芍勺韶少哨邵绍奢赊蛇舌舍赦摄射慑涉社设砷申呻伸身深娠绅神沈审婶甚肾慎渗声生甥牲升绳"],["ca40","蔃",8,"蔍蔎蔏蔐蔒蔔蔕蔖蔘蔙蔛蔜蔝蔞蔠蔢",8,"蔭",9,"蔾",4,"蕄蕅蕆蕇蕋",10],["ca80","蕗蕘蕚蕛蕜蕝蕟",4,"蕥蕦蕧蕩",8,"蕳蕵蕶蕷蕸蕼蕽蕿薀薁省盛剩胜圣师失狮施湿诗尸虱十石拾时什食蚀实识史矢使屎驶始式示士世柿事拭誓逝势是嗜噬适仕侍释饰氏市恃室视试收手首守寿授售受瘦兽蔬枢梳殊抒输叔舒淑疏书赎孰熟薯暑曙署蜀黍鼠属术述树束戍竖墅庶数漱"],["cb40","薂薃薆薈",6,"薐",10,"薝",6,"薥薦薧薩薫薬薭薱",5,"薸薺",6,"藂",6,"藊",4,"藑藒"],["cb80","藔藖",5,"藝",6,"藥藦藧藨藪",14,"恕刷耍摔衰甩帅栓拴霜双爽谁水睡税吮瞬顺舜说硕朔烁斯撕嘶思私司丝死肆寺嗣四伺似饲巳松耸怂颂送宋讼诵搜艘擞嗽苏酥俗素速粟僳塑溯宿诉肃酸蒜算虽隋随绥髓碎岁穗遂隧祟孙损笋蓑梭唆缩琐索锁所塌他它她塔"],["cc40","藹藺藼藽藾蘀",4,"蘆",10,"蘒蘓蘔蘕蘗",15,"蘨蘪",13,"蘹蘺蘻蘽蘾蘿虀"],["cc80","虁",11,"虒虓處",4,"虛虜虝號虠虡虣",7,"獭挞蹋踏胎苔抬台泰酞太态汰坍摊贪瘫滩坛檀痰潭谭谈坦毯袒碳探叹炭汤塘搪堂棠膛唐糖倘躺淌趟烫掏涛滔绦萄桃逃淘陶讨套特藤腾疼誊梯剔踢锑提题蹄啼体替嚏惕涕剃屉天添填田甜恬舔腆挑条迢眺跳贴铁帖厅听烃"],["cd40","虭虯虰虲",6,"蚃",6,"蚎",4,"蚔蚖",5,"蚞",4,"蚥蚦蚫蚭蚮蚲蚳蚷蚸蚹蚻",4,"蛁蛂蛃蛅蛈蛌蛍蛒蛓蛕蛖蛗蛚蛜"],["cd80","蛝蛠蛡蛢蛣蛥蛦蛧蛨蛪蛫蛬蛯蛵蛶蛷蛺蛻蛼蛽蛿蜁蜄蜅蜆蜋蜌蜎蜏蜐蜑蜔蜖汀廷停亭庭挺艇通桐酮瞳同铜彤童桶捅筒统痛偷投头透凸秃突图徒途涂屠土吐兔湍团推颓腿蜕褪退吞屯臀拖托脱鸵陀驮驼椭妥拓唾挖哇蛙洼娃瓦袜歪外豌弯湾玩顽丸烷完碗挽晚皖惋宛婉万腕汪王亡枉网往旺望忘妄威"],["ce40","蜙蜛蜝蜟蜠蜤蜦蜧蜨蜪蜫蜬蜭蜯蜰蜲蜳蜵蜶蜸蜹蜺蜼蜽蝀",6,"蝊蝋蝍蝏蝐蝑蝒蝔蝕蝖蝘蝚",5,"蝡蝢蝦",7,"蝯蝱蝲蝳蝵"],["ce80","蝷蝸蝹蝺蝿螀螁螄螆螇螉螊螌螎",4,"螔螕螖螘",6,"螠",4,"巍微危韦违桅围唯惟为潍维苇萎委伟伪尾纬未蔚味畏胃喂魏位渭谓尉慰卫瘟温蚊文闻纹吻稳紊问嗡翁瓮挝蜗涡窝我斡卧握沃巫呜钨乌污诬屋无芜梧吾吴毋武五捂午舞伍侮坞戊雾晤物勿务悟误昔熙析西硒矽晰嘻吸锡牺"],["cf40","螥螦螧螩螪螮螰螱螲螴螶螷螸螹螻螼螾螿蟁",4,"蟇蟈蟉蟌",4,"蟔",6,"蟜蟝蟞蟟蟡蟢蟣蟤蟦蟧蟨蟩蟫蟬蟭蟯",9],["cf80","蟺蟻蟼蟽蟿蠀蠁蠂蠄",5,"蠋",7,"蠔蠗蠘蠙蠚蠜",4,"蠣稀息希悉膝夕惜熄烯溪汐犀檄袭席习媳喜铣洗系隙戏细瞎虾匣霞辖暇峡侠狭下厦夏吓掀锨先仙鲜纤咸贤衔舷闲涎弦嫌显险现献县腺馅羡宪陷限线相厢镶香箱襄湘乡翔祥详想响享项巷橡像向象萧硝霄削哮嚣销消宵淆晓"],["d040","蠤",13,"蠳",5,"蠺蠻蠽蠾蠿衁衂衃衆",5,"衎",5,"衕衖衘衚",6,"衦衧衪衭衯衱衳衴衵衶衸衹衺"],["d080","衻衼袀袃袆袇袉袊袌袎袏袐袑袓袔袕袗",4,"袝",4,"袣袥",5,"小孝校肖啸笑效楔些歇蝎鞋协挟携邪斜胁谐写械卸蟹懈泄泻谢屑薪芯锌欣辛新忻心信衅星腥猩惺兴刑型形邢行醒幸杏性姓兄凶胸匈汹雄熊休修羞朽嗅锈秀袖绣墟戌需虚嘘须徐许蓄酗叙旭序畜恤絮婿绪续轩喧宣悬旋玄"],["d140","袬袮袯袰袲",4,"袸袹袺袻袽袾袿裀裃裄裇裈裊裋裌裍裏裐裑裓裖裗裚",4,"裠裡裦裧裩",6,"裲裵裶裷裺裻製裿褀褁褃",5],["d180","褉褋",4,"褑褔",4,"褜",4,"褢褣褤褦褧褨褩褬褭褮褯褱褲褳褵褷选癣眩绚靴薛学穴雪血勋熏循旬询寻驯巡殉汛训讯逊迅压押鸦鸭呀丫芽牙蚜崖衙涯雅哑亚讶焉咽阉烟淹盐严研蜒岩延言颜阎炎沿奄掩眼衍演艳堰燕厌砚雁唁彦焰宴谚验殃央鸯秧杨扬佯疡羊洋阳氧仰痒养样漾邀腰妖瑶"],["d240","褸",8,"襂襃襅",24,"襠",5,"襧",19,"襼"],["d280","襽襾覀覂覄覅覇",26,"摇尧遥窑谣姚咬舀药要耀椰噎耶爷野冶也页掖业叶曳腋夜液一壹医揖铱依伊衣颐夷遗移仪胰疑沂宜姨彝椅蚁倚已乙矣以艺抑易邑屹亿役臆逸肄疫亦裔意毅忆义益溢诣议谊译异翼翌绎茵荫因殷音阴姻吟银淫寅饮尹引隐"],["d340","覢",30,"觃觍觓觔觕觗觘觙觛觝觟觠觡觢觤觧觨觩觪觬觭觮觰觱觲觴",6],["d380","觻",4,"訁",5,"計",21,"印英樱婴鹰应缨莹萤营荧蝇迎赢盈影颖硬映哟拥佣臃痈庸雍踊蛹咏泳涌永恿勇用幽优悠忧尤由邮铀犹油游酉有友右佑釉诱又幼迂淤于盂榆虞愚舆余俞逾鱼愉渝渔隅予娱雨与屿禹宇语羽玉域芋郁吁遇喻峪御愈欲狱育誉"],["d440","訞",31,"訿",8,"詉",21],["d480","詟",25,"詺",6,"浴寓裕预豫驭鸳渊冤元垣袁原援辕园员圆猿源缘远苑愿怨院曰约越跃钥岳粤月悦阅耘云郧匀陨允运蕴酝晕韵孕匝砸杂栽哉灾宰载再在咱攒暂赞赃脏葬遭糟凿藻枣早澡蚤躁噪造皂灶燥责择则泽贼怎增憎曾赠扎喳渣札轧"],["d540","誁",7,"誋",7,"誔",46],["d580","諃",32,"铡闸眨栅榨咋乍炸诈摘斋宅窄债寨瞻毡詹粘沾盏斩辗崭展蘸栈占战站湛绽樟章彰漳张掌涨杖丈帐账仗胀瘴障招昭找沼赵照罩兆肇召遮折哲蛰辙者锗蔗这浙珍斟真甄砧臻贞针侦枕疹诊震振镇阵蒸挣睁征狰争怔整拯正政"],["d640","諤",34,"謈",27],["d680","謤謥謧",30,"帧症郑证芝枝支吱蜘知肢脂汁之织职直植殖执值侄址指止趾只旨纸志挚掷至致置帜峙制智秩稚质炙痔滞治窒中盅忠钟衷终种肿重仲众舟周州洲诌粥轴肘帚咒皱宙昼骤珠株蛛朱猪诸诛逐竹烛煮拄瞩嘱主著柱助蛀贮铸筑"],["d740","譆",31,"譧",4,"譭",25],["d780","讇",24,"讬讱讻诇诐诪谉谞住注祝驻抓爪拽专砖转撰赚篆桩庄装妆撞壮状椎锥追赘坠缀谆准捉拙卓桌琢茁酌啄着灼浊兹咨资姿滋淄孜紫仔籽滓子自渍字鬃棕踪宗综总纵邹走奏揍租足卒族祖诅阻组钻纂嘴醉最罪尊遵昨左佐柞做作坐座"],["d840","谸",8,"豂豃豄豅豈豊豋豍",7,"豖豗豘豙豛",5,"豣",6,"豬",6,"豴豵豶豷豻",6,"貃貄貆貇"],["d880","貈貋貍",6,"貕貖貗貙",20,"亍丌兀丐廿卅丕亘丞鬲孬噩丨禺丿匕乇夭爻卮氐囟胤馗毓睾鼗丶亟鼐乜乩亓芈孛啬嘏仄厍厝厣厥厮靥赝匚叵匦匮匾赜卦卣刂刈刎刭刳刿剀剌剞剡剜蒯剽劂劁劐劓冂罔亻仃仉仂仨仡仫仞伛仳伢佤仵伥伧伉伫佞佧攸佚佝"],["d940","貮",62],["d980","賭",32,"佟佗伲伽佶佴侑侉侃侏佾佻侪佼侬侔俦俨俪俅俚俣俜俑俟俸倩偌俳倬倏倮倭俾倜倌倥倨偾偃偕偈偎偬偻傥傧傩傺僖儆僭僬僦僮儇儋仝氽佘佥俎龠汆籴兮巽黉馘冁夔勹匍訇匐凫夙兕亠兖亳衮袤亵脔裒禀嬴蠃羸冫冱冽冼"],["da40","贎",14,"贠赑赒赗赟赥赨赩赪赬赮赯赱赲赸",8,"趂趃趆趇趈趉趌",4,"趒趓趕",9,"趠趡"],["da80","趢趤",12,"趲趶趷趹趻趽跀跁跂跅跇跈跉跊跍跐跒跓跔凇冖冢冥讠讦讧讪讴讵讷诂诃诋诏诎诒诓诔诖诘诙诜诟诠诤诨诩诮诰诳诶诹诼诿谀谂谄谇谌谏谑谒谔谕谖谙谛谘谝谟谠谡谥谧谪谫谮谯谲谳谵谶卩卺阝阢阡阱阪阽阼陂陉陔陟陧陬陲陴隈隍隗隰邗邛邝邙邬邡邴邳邶邺"],["db40","跕跘跙跜跠跡跢跥跦跧跩跭跮跰跱跲跴跶跼跾",6,"踆踇踈踋踍踎踐踑踒踓踕",7,"踠踡踤",4,"踫踭踰踲踳踴踶踷踸踻踼踾"],["db80","踿蹃蹅蹆蹌",4,"蹓",5,"蹚",11,"蹧蹨蹪蹫蹮蹱邸邰郏郅邾郐郄郇郓郦郢郜郗郛郫郯郾鄄鄢鄞鄣鄱鄯鄹酃酆刍奂劢劬劭劾哿勐勖勰叟燮矍廴凵凼鬯厶弁畚巯坌垩垡塾墼壅壑圩圬圪圳圹圮圯坜圻坂坩垅坫垆坼坻坨坭坶坳垭垤垌垲埏垧垴垓垠埕埘埚埙埒垸埴埯埸埤埝"],["dc40","蹳蹵蹷",4,"蹽蹾躀躂躃躄躆躈",6,"躑躒躓躕",6,"躝躟",11,"躭躮躰躱躳",6,"躻",7],["dc80","軃",10,"軏",21,"堋堍埽埭堀堞堙塄堠塥塬墁墉墚墀馨鼙懿艹艽艿芏芊芨芄芎芑芗芙芫芸芾芰苈苊苣芘芷芮苋苌苁芩芴芡芪芟苄苎芤苡茉苷苤茏茇苜苴苒苘茌苻苓茑茚茆茔茕苠苕茜荑荛荜茈莒茼茴茱莛荞茯荏荇荃荟荀茗荠茭茺茳荦荥"],["dd40","軥",62],["dd80","輤",32,"荨茛荩荬荪荭荮莰荸莳莴莠莪莓莜莅荼莶莩荽莸荻莘莞莨莺莼菁萁菥菘堇萘萋菝菽菖萜萸萑萆菔菟萏萃菸菹菪菅菀萦菰菡葜葑葚葙葳蒇蒈葺蒉葸萼葆葩葶蒌蒎萱葭蓁蓍蓐蓦蒽蓓蓊蒿蒺蓠蒡蒹蒴蒗蓥蓣蔌甍蔸蓰蔹蔟蔺"],["de40","轅",32,"轪辀辌辒辝辠辡辢辤辥辦辧辪辬辭辮辯農辳辴辵辷辸辺辻込辿迀迃迆"],["de80","迉",4,"迏迒迖迗迚迠迡迣迧迬迯迱迲迴迵迶迺迻迼迾迿逇逈逌逎逓逕逘蕖蔻蓿蓼蕙蕈蕨蕤蕞蕺瞢蕃蕲蕻薤薨薇薏蕹薮薜薅薹薷薰藓藁藜藿蘧蘅蘩蘖蘼廾弈夼奁耷奕奚奘匏尢尥尬尴扌扪抟抻拊拚拗拮挢拶挹捋捃掭揶捱捺掎掴捭掬掊捩掮掼揲揸揠揿揄揞揎摒揆掾摅摁搋搛搠搌搦搡摞撄摭撖"],["df40","這逜連逤逥逧",5,"逰",4,"逷逹逺逽逿遀遃遅遆遈",4,"過達違遖遙遚遜",5,"遤遦遧適遪遫遬遯",4,"遶",6,"遾邁"],["df80","還邅邆邇邉邊邌",4,"邒邔邖邘邚邜邞邟邠邤邥邧邨邩邫邭邲邷邼邽邿郀摺撷撸撙撺擀擐擗擤擢攉攥攮弋忒甙弑卟叱叽叩叨叻吒吖吆呋呒呓呔呖呃吡呗呙吣吲咂咔呷呱呤咚咛咄呶呦咝哐咭哂咴哒咧咦哓哔呲咣哕咻咿哌哙哚哜咩咪咤哝哏哞唛哧唠哽唔哳唢唣唏唑唧唪啧喏喵啉啭啁啕唿啐唼"],["e040","郂郃郆郈郉郋郌郍郒郔郕郖郘郙郚郞郟郠郣郤郥郩郪郬郮郰郱郲郳郵郶郷郹郺郻郼郿鄀鄁鄃鄅",19,"鄚鄛鄜"],["e080","鄝鄟鄠鄡鄤",10,"鄰鄲",6,"鄺",8,"酄唷啖啵啶啷唳唰啜喋嗒喃喱喹喈喁喟啾嗖喑啻嗟喽喾喔喙嗪嗷嗉嘟嗑嗫嗬嗔嗦嗝嗄嗯嗥嗲嗳嗌嗍嗨嗵嗤辔嘞嘈嘌嘁嘤嘣嗾嘀嘧嘭噘嘹噗嘬噍噢噙噜噌噔嚆噤噱噫噻噼嚅嚓嚯囔囗囝囡囵囫囹囿圄圊圉圜帏帙帔帑帱帻帼"],["e140","酅酇酈酑酓酔酕酖酘酙酛酜酟酠酦酧酨酫酭酳酺酻酼醀",4,"醆醈醊醎醏醓",6,"醜",5,"醤",5,"醫醬醰醱醲醳醶醷醸醹醻"],["e180","醼",10,"釈釋釐釒",9,"針",8,"帷幄幔幛幞幡岌屺岍岐岖岈岘岙岑岚岜岵岢岽岬岫岱岣峁岷峄峒峤峋峥崂崃崧崦崮崤崞崆崛嵘崾崴崽嵬嵛嵯嵝嵫嵋嵊嵩嵴嶂嶙嶝豳嶷巅彳彷徂徇徉後徕徙徜徨徭徵徼衢彡犭犰犴犷犸狃狁狎狍狒狨狯狩狲狴狷猁狳猃狺"],["e240","釦",62],["e280","鈥",32,"狻猗猓猡猊猞猝猕猢猹猥猬猸猱獐獍獗獠獬獯獾舛夥飧夤夂饣饧",5,"饴饷饽馀馄馇馊馍馐馑馓馔馕庀庑庋庖庥庠庹庵庾庳赓廒廑廛廨廪膺忄忉忖忏怃忮怄忡忤忾怅怆忪忭忸怙怵怦怛怏怍怩怫怊怿怡恸恹恻恺恂"],["e340","鉆",45,"鉵",16],["e380","銆",7,"銏",24,"恪恽悖悚悭悝悃悒悌悛惬悻悱惝惘惆惚悴愠愦愕愣惴愀愎愫慊慵憬憔憧憷懔懵忝隳闩闫闱闳闵闶闼闾阃阄阆阈阊阋阌阍阏阒阕阖阗阙阚丬爿戕氵汔汜汊沣沅沐沔沌汨汩汴汶沆沩泐泔沭泷泸泱泗沲泠泖泺泫泮沱泓泯泾"],["e440","銨",5,"銯",24,"鋉",31],["e480","鋩",32,"洹洧洌浃浈洇洄洙洎洫浍洮洵洚浏浒浔洳涑浯涞涠浞涓涔浜浠浼浣渚淇淅淞渎涿淠渑淦淝淙渖涫渌涮渫湮湎湫溲湟溆湓湔渲渥湄滟溱溘滠漭滢溥溧溽溻溷滗溴滏溏滂溟潢潆潇漤漕滹漯漶潋潴漪漉漩澉澍澌潸潲潼潺濑"],["e540","錊",51,"錿",10],["e580","鍊",31,"鍫濉澧澹澶濂濡濮濞濠濯瀚瀣瀛瀹瀵灏灞宀宄宕宓宥宸甯骞搴寤寮褰寰蹇謇辶迓迕迥迮迤迩迦迳迨逅逄逋逦逑逍逖逡逵逶逭逯遄遑遒遐遨遘遢遛暹遴遽邂邈邃邋彐彗彖彘尻咫屐屙孱屣屦羼弪弩弭艴弼鬻屮妁妃妍妩妪妣"],["e640","鍬",34,"鎐",27],["e680","鎬",29,"鏋鏌鏍妗姊妫妞妤姒妲妯姗妾娅娆姝娈姣姘姹娌娉娲娴娑娣娓婀婧婊婕娼婢婵胬媪媛婷婺媾嫫媲嫒嫔媸嫠嫣嫱嫖嫦嫘嫜嬉嬗嬖嬲嬷孀尕尜孚孥孳孑孓孢驵驷驸驺驿驽骀骁骅骈骊骐骒骓骖骘骛骜骝骟骠骢骣骥骧纟纡纣纥纨纩"],["e740","鏎",7,"鏗",54],["e780","鐎",32,"纭纰纾绀绁绂绉绋绌绐绔绗绛绠绡绨绫绮绯绱绲缍绶绺绻绾缁缂缃缇缈缋缌缏缑缒缗缙缜缛缟缡",6,"缪缫缬缭缯",4,"缵幺畿巛甾邕玎玑玮玢玟珏珂珑玷玳珀珉珈珥珙顼琊珩珧珞玺珲琏琪瑛琦琥琨琰琮琬"],["e840","鐯",14,"鐿",43,"鑬鑭鑮鑯"],["e880","鑰",20,"钑钖钘铇铏铓铔铚铦铻锜锠琛琚瑁瑜瑗瑕瑙瑷瑭瑾璜璎璀璁璇璋璞璨璩璐璧瓒璺韪韫韬杌杓杞杈杩枥枇杪杳枘枧杵枨枞枭枋杷杼柰栉柘栊柩枰栌柙枵柚枳柝栀柃枸柢栎柁柽栲栳桠桡桎桢桄桤梃栝桕桦桁桧桀栾桊桉栩梵梏桴桷梓桫棂楮棼椟椠棹"],["e940","锧锳锽镃镈镋镕镚镠镮镴镵長",7,"門",42],["e980","閫",32,"椤棰椋椁楗棣椐楱椹楠楂楝榄楫榀榘楸椴槌榇榈槎榉楦楣楹榛榧榻榫榭槔榱槁槊槟榕槠榍槿樯槭樗樘橥槲橄樾檠橐橛樵檎橹樽樨橘橼檑檐檩檗檫猷獒殁殂殇殄殒殓殍殚殛殡殪轫轭轱轲轳轵轶轸轷轹轺轼轾辁辂辄辇辋"],["ea40","闌",27,"闬闿阇阓阘阛阞阠阣",6,"阫阬阭阯阰阷阸阹阺阾陁陃陊陎陏陑陒陓陖陗"],["ea80","陘陙陚陜陝陞陠陣陥陦陫陭",4,"陳陸",12,"隇隉隊辍辎辏辘辚軎戋戗戛戟戢戡戥戤戬臧瓯瓴瓿甏甑甓攴旮旯旰昊昙杲昃昕昀炅曷昝昴昱昶昵耆晟晔晁晏晖晡晗晷暄暌暧暝暾曛曜曦曩贲贳贶贻贽赀赅赆赈赉赇赍赕赙觇觊觋觌觎觏觐觑牮犟牝牦牯牾牿犄犋犍犏犒挈挲掰"],["eb40","隌階隑隒隓隕隖隚際隝",9,"隨",7,"隱隲隴隵隷隸隺隻隿雂雃雈雊雋雐雑雓雔雖",9,"雡",6,"雫"],["eb80","雬雭雮雰雱雲雴雵雸雺電雼雽雿霂霃霅霊霋霌霐霑霒霔霕霗",4,"霝霟霠搿擘耄毪毳毽毵毹氅氇氆氍氕氘氙氚氡氩氤氪氲攵敕敫牍牒牖爰虢刖肟肜肓肼朊肽肱肫肭肴肷胧胨胩胪胛胂胄胙胍胗朐胝胫胱胴胭脍脎胲胼朕脒豚脶脞脬脘脲腈腌腓腴腙腚腱腠腩腼腽腭腧塍媵膈膂膑滕膣膪臌朦臊膻"],["ec40","霡",8,"霫霬霮霯霱霳",4,"霺霻霼霽霿",18,"靔靕靗靘靚靜靝靟靣靤靦靧靨靪",7],["ec80","靲靵靷",4,"靽",7,"鞆",4,"鞌鞎鞏鞐鞓鞕鞖鞗鞙",4,"臁膦欤欷欹歃歆歙飑飒飓飕飙飚殳彀毂觳斐齑斓於旆旄旃旌旎旒旖炀炜炖炝炻烀炷炫炱烨烊焐焓焖焯焱煳煜煨煅煲煊煸煺熘熳熵熨熠燠燔燧燹爝爨灬焘煦熹戾戽扃扈扉礻祀祆祉祛祜祓祚祢祗祠祯祧祺禅禊禚禧禳忑忐"],["ed40","鞞鞟鞡鞢鞤",6,"鞬鞮鞰鞱鞳鞵",46],["ed80","韤韥韨韮",4,"韴韷",23,"怼恝恚恧恁恙恣悫愆愍慝憩憝懋懑戆肀聿沓泶淼矶矸砀砉砗砘砑斫砭砜砝砹砺砻砟砼砥砬砣砩硎硭硖硗砦硐硇硌硪碛碓碚碇碜碡碣碲碹碥磔磙磉磬磲礅磴礓礤礞礴龛黹黻黼盱眄眍盹眇眈眚眢眙眭眦眵眸睐睑睇睃睚睨"],["ee40","頏",62],["ee80","顎",32,"睢睥睿瞍睽瞀瞌瞑瞟瞠瞰瞵瞽町畀畎畋畈畛畲畹疃罘罡罟詈罨罴罱罹羁罾盍盥蠲钅钆钇钋钊钌钍钏钐钔钗钕钚钛钜钣钤钫钪钭钬钯钰钲钴钶",4,"钼钽钿铄铈",6,"铐铑铒铕铖铗铙铘铛铞铟铠铢铤铥铧铨铪"],["ef40","顯",5,"颋颎颒颕颙颣風",37,"飏飐飔飖飗飛飜飝飠",4],["ef80","飥飦飩",30,"铩铫铮铯铳铴铵铷铹铼铽铿锃锂锆锇锉锊锍锎锏锒",4,"锘锛锝锞锟锢锪锫锩锬锱锲锴锶锷锸锼锾锿镂锵镄镅镆镉镌镎镏镒镓镔镖镗镘镙镛镞镟镝镡镢镤",8,"镯镱镲镳锺矧矬雉秕秭秣秫稆嵇稃稂稞稔"],["f040","餈",4,"餎餏餑",28,"餯",26],["f080","饊",9,"饖",12,"饤饦饳饸饹饻饾馂馃馉稹稷穑黏馥穰皈皎皓皙皤瓞瓠甬鸠鸢鸨",4,"鸲鸱鸶鸸鸷鸹鸺鸾鹁鹂鹄鹆鹇鹈鹉鹋鹌鹎鹑鹕鹗鹚鹛鹜鹞鹣鹦",6,"鹱鹭鹳疒疔疖疠疝疬疣疳疴疸痄疱疰痃痂痖痍痣痨痦痤痫痧瘃痱痼痿瘐瘀瘅瘌瘗瘊瘥瘘瘕瘙"],["f140","馌馎馚",10,"馦馧馩",47],["f180","駙",32,"瘛瘼瘢瘠癀瘭瘰瘿瘵癃瘾瘳癍癞癔癜癖癫癯翊竦穸穹窀窆窈窕窦窠窬窨窭窳衤衩衲衽衿袂袢裆袷袼裉裢裎裣裥裱褚裼裨裾裰褡褙褓褛褊褴褫褶襁襦襻疋胥皲皴矜耒耔耖耜耠耢耥耦耧耩耨耱耋耵聃聆聍聒聩聱覃顸颀颃"],["f240","駺",62],["f280","騹",32,"颉颌颍颏颔颚颛颞颟颡颢颥颦虍虔虬虮虿虺虼虻蚨蚍蚋蚬蚝蚧蚣蚪蚓蚩蚶蛄蚵蛎蚰蚺蚱蚯蛉蛏蚴蛩蛱蛲蛭蛳蛐蜓蛞蛴蛟蛘蛑蜃蜇蛸蜈蜊蜍蜉蜣蜻蜞蜥蜮蜚蜾蝈蜴蜱蜩蜷蜿螂蜢蝽蝾蝻蝠蝰蝌蝮螋蝓蝣蝼蝤蝙蝥螓螯螨蟒"],["f340","驚",17,"驲骃骉骍骎骔骕骙骦骩",6,"骲骳骴骵骹骻骽骾骿髃髄髆",4,"髍髎髏髐髒體髕髖髗髙髚髛髜"],["f380","髝髞髠髢髣髤髥髧髨髩髪髬髮髰",8,"髺髼",6,"鬄鬅鬆蟆螈螅螭螗螃螫蟥螬螵螳蟋蟓螽蟑蟀蟊蟛蟪蟠蟮蠖蠓蟾蠊蠛蠡蠹蠼缶罂罄罅舐竺竽笈笃笄笕笊笫笏筇笸笪笙笮笱笠笥笤笳笾笞筘筚筅筵筌筝筠筮筻筢筲筱箐箦箧箸箬箝箨箅箪箜箢箫箴篑篁篌篝篚篥篦篪簌篾篼簏簖簋"],["f440","鬇鬉",5,"鬐鬑鬒鬔",10,"鬠鬡鬢鬤",10,"鬰鬱鬳",7,"鬽鬾鬿魀魆魊魋魌魎魐魒魓魕",5],["f480","魛",32,"簟簪簦簸籁籀臾舁舂舄臬衄舡舢舣舭舯舨舫舸舻舳舴舾艄艉艋艏艚艟艨衾袅袈裘裟襞羝羟羧羯羰羲籼敉粑粝粜粞粢粲粼粽糁糇糌糍糈糅糗糨艮暨羿翎翕翥翡翦翩翮翳糸絷綦綮繇纛麸麴赳趄趔趑趱赧赭豇豉酊酐酎酏酤"],["f540","魼",62],["f580","鮻",32,"酢酡酰酩酯酽酾酲酴酹醌醅醐醍醑醢醣醪醭醮醯醵醴醺豕鹾趸跫踅蹙蹩趵趿趼趺跄跖跗跚跞跎跏跛跆跬跷跸跣跹跻跤踉跽踔踝踟踬踮踣踯踺蹀踹踵踽踱蹉蹁蹂蹑蹒蹊蹰蹶蹼蹯蹴躅躏躔躐躜躞豸貂貊貅貘貔斛觖觞觚觜"],["f640","鯜",62],["f680","鰛",32,"觥觫觯訾謦靓雩雳雯霆霁霈霏霎霪霭霰霾龀龃龅",5,"龌黾鼋鼍隹隼隽雎雒瞿雠銎銮鋈錾鍪鏊鎏鐾鑫鱿鲂鲅鲆鲇鲈稣鲋鲎鲐鲑鲒鲔鲕鲚鲛鲞",5,"鲥",4,"鲫鲭鲮鲰",7,"鲺鲻鲼鲽鳄鳅鳆鳇鳊鳋"],["f740","鰼",62],["f780","鱻鱽鱾鲀鲃鲄鲉鲊鲌鲏鲓鲖鲗鲘鲙鲝鲪鲬鲯鲹鲾",4,"鳈鳉鳑鳒鳚鳛鳠鳡鳌",4,"鳓鳔鳕鳗鳘鳙鳜鳝鳟鳢靼鞅鞑鞒鞔鞯鞫鞣鞲鞴骱骰骷鹘骶骺骼髁髀髅髂髋髌髑魅魃魇魉魈魍魑飨餍餮饕饔髟髡髦髯髫髻髭髹鬈鬏鬓鬟鬣麽麾縻麂麇麈麋麒鏖麝麟黛黜黝黠黟黢黩黧黥黪黯鼢鼬鼯鼹鼷鼽鼾齄"],["f840","鳣",62],["f880","鴢",32],["f940","鵃",62],["f980","鶂",32],["fa40","鶣",62],["fa80","鷢",32],["fb40","鸃",27,"鸤鸧鸮鸰鸴鸻鸼鹀鹍鹐鹒鹓鹔鹖鹙鹝鹟鹠鹡鹢鹥鹮鹯鹲鹴",9,"麀"],["fb80","麁麃麄麅麆麉麊麌",5,"麔",8,"麞麠",5,"麧麨麩麪"],["fc40","麫",8,"麵麶麷麹麺麼麿",4,"黅黆黇黈黊黋黌黐黒黓黕黖黗黙黚點黡黣黤黦黨黫黬黭黮黰",8,"黺黽黿",6],["fc80","鼆",4,"鼌鼏鼑鼒鼔鼕鼖鼘鼚",5,"鼡鼣",8,"鼭鼮鼰鼱"],["fd40","鼲",4,"鼸鼺鼼鼿",4,"齅",10,"齒",38],["fd80","齹",5,"龁龂龍",11,"龜龝龞龡",4,"郎凉秊裏隣"],["fe40","兀嗀﨎﨏﨑﨓﨔礼﨟蘒﨡﨣﨤﨧﨨﨩"]];
/***/ }),
/***/ 431:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const os = __importStar(__webpack_require__(87));
/**
* Commands
*
* Command Format:
* ::name key=value,key=value::message
*
* Examples:
* ::warning::This is the message
* ::set-env name=MY_VAR::some value
*/
function issueCommand(command, properties, message) {
const cmd = new Command(command, properties, message);
process.stdout.write(cmd.toString() + os.EOL);
}
exports.issueCommand = issueCommand;
function issue(name, message = '') {
issueCommand(name, {}, message);
}
exports.issue = issue;
const CMD_STRING = '::';
class Command {
constructor(command, properties, message) {
if (!command) {
command = 'missing.command';
}
this.command = command;
this.properties = properties;
this.message = message;
}
toString() {
let cmdStr = CMD_STRING + this.command;
if (this.properties && Object.keys(this.properties).length > 0) {
cmdStr += ' ';
let first = true;
for (const key in this.properties) {
if (this.properties.hasOwnProperty(key)) {
const val = this.properties[key];
if (val) {
if (first) {
first = false;
}
else {
cmdStr += ',';
}
cmdStr += `${key}=${escapeProperty(val)}`;
}
}
}
}
cmdStr += `${CMD_STRING}${escapeData(this.message)}`;
return cmdStr;
}
}
/**
* Sanitizes an input into a string so it can be passed into issueCommand safely
* @param input input to sanitize into a string
*/
function toCommandValue(input) {
if (input === null || input === undefined) {
return '';
}
else if (typeof input === 'string' || input instanceof String) {
return input;
}
return JSON.stringify(input);
}
exports.toCommandValue = toCommandValue;
function escapeData(s) {
return toCommandValue(s)
.replace(/%/g, '%25')
.replace(/\r/g, '%0D')
.replace(/\n/g, '%0A');
}
function escapeProperty(s) {
return toCommandValue(s)
.replace(/%/g, '%25')
.replace(/\r/g, '%0D')
.replace(/\n/g, '%0A')
.replace(/:/g, '%3A')
.replace(/,/g, '%2C');
}
//# sourceMappingURL=command.js.map
/***/ }),
/***/ 448:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, '__esModule', { value: true });
var universalUserAgent = __webpack_require__(796);
var beforeAfterHook = __webpack_require__(523);
var request = __webpack_require__(753);
var graphql = __webpack_require__(898);
var authToken = __webpack_require__(813);
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys(Object(source), true).forEach(function (key) {
_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
}
return target;
}
const VERSION = "3.1.1";
class Octokit {
constructor(options = {}) {
const hook = new beforeAfterHook.Collection();
const requestDefaults = {
baseUrl: request.request.endpoint.DEFAULTS.baseUrl,
headers: {},
request: Object.assign({}, options.request, {
hook: hook.bind(null, "request")
}),
mediaType: {
previews: [],
format: ""
}
}; // prepend default user agent with `options.userAgent` if set
requestDefaults.headers["user-agent"] = [options.userAgent, `octokit-core.js/${VERSION} ${universalUserAgent.getUserAgent()}`].filter(Boolean).join(" ");
if (options.baseUrl) {
requestDefaults.baseUrl = options.baseUrl;
}
if (options.previews) {
requestDefaults.mediaType.previews = options.previews;
}
if (options.timeZone) {
requestDefaults.headers["time-zone"] = options.timeZone;
}
this.request = request.request.defaults(requestDefaults);
this.graphql = graphql.withCustomRequest(this.request).defaults(_objectSpread2(_objectSpread2({}, requestDefaults), {}, {
baseUrl: requestDefaults.baseUrl.replace(/\/api\/v3$/, "/api")
}));
this.log = Object.assign({
debug: () => {},
info: () => {},
warn: console.warn.bind(console),
error: console.error.bind(console)
}, options.log);
this.hook = hook; // (1) If neither `options.authStrategy` nor `options.auth` are set, the `octokit` instance
// is unauthenticated. The `this.auth()` method is a no-op and no request hook is registred.
// (2) If only `options.auth` is set, use the default token authentication strategy.
// (3) If `options.authStrategy` is set then use it and pass in `options.auth`. Always pass own request as many strategies accept a custom request instance.
// TODO: type `options.auth` based on `options.authStrategy`.
if (!options.authStrategy) {
if (!options.auth) {
// (1)
this.auth = async () => ({
type: "unauthenticated"
});
} else {
// (2)
const auth = authToken.createTokenAuth(options.auth); // @ts-ignore ¯\_(ツ)_/¯
hook.wrap("request", auth.hook);
this.auth = auth;
}
} else {
const auth = options.authStrategy(Object.assign({
request: this.request
}, options.auth)); // @ts-ignore ¯\_(ツ)_/¯
hook.wrap("request", auth.hook);
this.auth = auth;
} // apply plugins
// https://stackoverflow.com/a/16345172
const classConstructor = this.constructor;
classConstructor.plugins.forEach(plugin => {
Object.assign(this, plugin(this, options));
});
}
static defaults(defaults) {
const OctokitWithDefaults = class extends this {
constructor(...args) {
const options = args[0] || {};
if (typeof defaults === "function") {
super(defaults(options));
return;
}
super(Object.assign({}, defaults, options, options.userAgent && defaults.userAgent ? {
userAgent: `${options.userAgent} ${defaults.userAgent}`
} : null));
}
};
return OctokitWithDefaults;
}
/**
* Attach a plugin (or many) to your Octokit instance.
*
* @example
* const API = Octokit.plugin(plugin1, plugin2, plugin3, ...)
*/
static plugin(...newPlugins) {
var _a;
const currentPlugins = this.plugins;
const NewOctokit = (_a = class extends this {}, _a.plugins = currentPlugins.concat(newPlugins.filter(plugin => !currentPlugins.includes(plugin))), _a);
return NewOctokit;
}
}
Octokit.VERSION = VERSION;
Octokit.plugins = [];
exports.Octokit = Octokit;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 454:
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var Stream = _interopDefault(__webpack_require__(794));
var http = _interopDefault(__webpack_require__(605));
var Url = _interopDefault(__webpack_require__(835));
var https = _interopDefault(__webpack_require__(211));
var zlib = _interopDefault(__webpack_require__(761));
// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js
// fix for "Readable" isn't a named export issue
const Readable = Stream.Readable;
const BUFFER = Symbol('buffer');
const TYPE = Symbol('type');
class Blob {
constructor() {
this[TYPE] = '';
const blobParts = arguments[0];
const options = arguments[1];
const buffers = [];
let size = 0;
if (blobParts) {
const a = blobParts;
const length = Number(a.length);
for (let i = 0; i < length; i++) {
const element = a[i];
let buffer;
if (element instanceof Buffer) {
buffer = element;
} else if (ArrayBuffer.isView(element)) {
buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength);
} else if (element instanceof ArrayBuffer) {
buffer = Buffer.from(element);
} else if (element instanceof Blob) {
buffer = element[BUFFER];
} else {
buffer = Buffer.from(typeof element === 'string' ? element : String(element));
}
size += buffer.length;
buffers.push(buffer);
}
}
this[BUFFER] = Buffer.concat(buffers);
let type = options && options.type !== undefined && String(options.type).toLowerCase();
if (type && !/[^\u0020-\u007E]/.test(type)) {
this[TYPE] = type;
}
}
get size() {
return this[BUFFER].length;
}
get type() {
return this[TYPE];
}
text() {
return Promise.resolve(this[BUFFER].toString());
}
arrayBuffer() {
const buf = this[BUFFER];
const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
return Promise.resolve(ab);
}
stream() {
const readable = new Readable();
readable._read = function () {};
readable.push(this[BUFFER]);
readable.push(null);
return readable;
}
toString() {
return '[object Blob]';
}
slice() {
const size = this.size;
const start = arguments[0];
const end = arguments[1];
let relativeStart, relativeEnd;
if (start === undefined) {
relativeStart = 0;
} else if (start < 0) {
relativeStart = Math.max(size + start, 0);
} else {
relativeStart = Math.min(start, size);
}
if (end === undefined) {
relativeEnd = size;
} else if (end < 0) {
relativeEnd = Math.max(size + end, 0);
} else {
relativeEnd = Math.min(end, size);
}
const span = Math.max(relativeEnd - relativeStart, 0);
const buffer = this[BUFFER];
const slicedBuffer = buffer.slice(relativeStart, relativeStart + span);
const blob = new Blob([], { type: arguments[2] });
blob[BUFFER] = slicedBuffer;
return blob;
}
}
Object.defineProperties(Blob.prototype, {
size: { enumerable: true },
type: { enumerable: true },
slice: { enumerable: true }
});
Object.defineProperty(Blob.prototype, Symbol.toStringTag, {
value: 'Blob',
writable: false,
enumerable: false,
configurable: true
});
/**
* fetch-error.js
*
* FetchError interface for operational errors
*/
/**
* Create FetchError instance
*
* @param String message Error message for human
* @param String type Error type for machine
* @param String systemError For Node.js system error
* @return FetchError
*/
function FetchError(message, type, systemError) {
Error.call(this, message);
this.message = message;
this.type = type;
// when err.type is `system`, err.code contains system error code
if (systemError) {
this.code = this.errno = systemError.code;
}
// hide custom error implementation details from end-users
Error.captureStackTrace(this, this.constructor);
}
FetchError.prototype = Object.create(Error.prototype);
FetchError.prototype.constructor = FetchError;
FetchError.prototype.name = 'FetchError';
let convert;
try {
convert = __webpack_require__(798).convert;
} catch (e) {}
const INTERNALS = Symbol('Body internals');
// fix an issue where "PassThrough" isn't a named export for node <10
const PassThrough = Stream.PassThrough;
/**
* Body mixin
*
* Ref: https://fetch.spec.whatwg.org/#body
*
* @param Stream body Readable stream
* @param Object opts Response options
* @return Void
*/
function Body(body) {
var _this = this;
var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
_ref$size = _ref.size;
let size = _ref$size === undefined ? 0 : _ref$size;
var _ref$timeout = _ref.timeout;
let timeout = _ref$timeout === undefined ? 0 : _ref$timeout;
if (body == null) {
// body is undefined or null
body = null;
} else if (isURLSearchParams(body)) {
// body is a URLSearchParams
body = Buffer.from(body.toString());
} else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {
// body is ArrayBuffer
body = Buffer.from(body);
} else if (ArrayBuffer.isView(body)) {
// body is ArrayBufferView
body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
} else if (body instanceof Stream) ; else {
// none of the above
// coerce to string then buffer
body = Buffer.from(String(body));
}
this[INTERNALS] = {
body,
disturbed: false,
error: null
};
this.size = size;
this.timeout = timeout;
if (body instanceof Stream) {
body.on('error', function (err) {
const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err);
_this[INTERNALS].error = error;
});
}
}
Body.prototype = {
get body() {
return this[INTERNALS].body;
},
get bodyUsed() {
return this[INTERNALS].disturbed;
},
/**
* Decode response as ArrayBuffer
*
* @return Promise
*/
arrayBuffer() {
return consumeBody.call(this).then(function (buf) {
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
});
},
/**
* Return raw response as Blob
*
* @return Promise
*/
blob() {
let ct = this.headers && this.headers.get('content-type') || '';
return consumeBody.call(this).then(function (buf) {
return Object.assign(
// Prevent copying
new Blob([], {
type: ct.toLowerCase()
}), {
[BUFFER]: buf
});
});
},
/**
* Decode response as json
*
* @return Promise
*/
json() {
var _this2 = this;
return consumeBody.call(this).then(function (buffer) {
try {
return JSON.parse(buffer.toString());
} catch (err) {
return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json'));
}
});
},
/**
* Decode response as text
*
* @return Promise
*/
text() {
return consumeBody.call(this).then(function (buffer) {
return buffer.toString();
});
},
/**
* Decode response as buffer (non-spec api)
*
* @return Promise
*/
buffer() {
return consumeBody.call(this);
},
/**
* Decode response as text, while automatically detecting the encoding and
* trying to decode to UTF-8 (non-spec api)
*
* @return Promise
*/
textConverted() {
var _this3 = this;
return consumeBody.call(this).then(function (buffer) {
return convertBody(buffer, _this3.headers);
});
}
};
// In browsers, all properties are enumerable.
Object.defineProperties(Body.prototype, {
body: { enumerable: true },
bodyUsed: { enumerable: true },
arrayBuffer: { enumerable: true },
blob: { enumerable: true },
json: { enumerable: true },
text: { enumerable: true }
});
Body.mixIn = function (proto) {
for (const name of Object.getOwnPropertyNames(Body.prototype)) {
// istanbul ignore else: future proof
if (!(name in proto)) {
const desc = Object.getOwnPropertyDescriptor(Body.prototype, name);
Object.defineProperty(proto, name, desc);
}
}
};
/**
* Consume and convert an entire Body to a Buffer.
*
* Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body
*
* @return Promise
*/
function consumeBody() {
var _this4 = this;
if (this[INTERNALS].disturbed) {
return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));
}
this[INTERNALS].disturbed = true;
if (this[INTERNALS].error) {
return Body.Promise.reject(this[INTERNALS].error);
}
let body = this.body;
// body is null
if (body === null) {
return Body.Promise.resolve(Buffer.alloc(0));
}
// body is blob
if (isBlob(body)) {
body = body.stream();
}
// body is buffer
if (Buffer.isBuffer(body)) {
return Body.Promise.resolve(body);
}
// istanbul ignore if: should never happen
if (!(body instanceof Stream)) {
return Body.Promise.resolve(Buffer.alloc(0));
}
// body is stream
// get ready to actually consume the body
let accum = [];
let accumBytes = 0;
let abort = false;
return new Body.Promise(function (resolve, reject) {
let resTimeout;
// allow timeout on slow response body
if (_this4.timeout) {
resTimeout = setTimeout(function () {
abort = true;
reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));
}, _this4.timeout);
}
// handle stream errors
body.on('error', function (err) {
if (err.name === 'AbortError') {
// if the request was aborted, reject with this Error
abort = true;
reject(err);
} else {
// other errors, such as incorrect content-encoding
reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));
}
});
body.on('data', function (chunk) {
if (abort || chunk === null) {
return;
}
if (_this4.size && accumBytes + chunk.length > _this4.size) {
abort = true;
reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));
return;
}
accumBytes += chunk.length;
accum.push(chunk);
});
body.on('end', function () {
if (abort) {
return;
}
clearTimeout(resTimeout);
try {
resolve(Buffer.concat(accum, accumBytes));
} catch (err) {
// handle streams that have accumulated too much data (issue #414)
reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));
}
});
});
}
/**
* Detect buffer encoding and convert to target encoding
* ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding
*
* @param Buffer buffer Incoming buffer
* @param String encoding Target encoding
* @return String
*/
function convertBody(buffer, headers) {
if (typeof convert !== 'function') {
throw new Error('The package `encoding` must be installed to use the textConverted() function');
}
const ct = headers.get('content-type');
let charset = 'utf-8';
let res, str;
// header
if (ct) {
res = /charset=([^;]*)/i.exec(ct);
}
// no charset in content type, peek at response body for at most 1024 bytes
str = buffer.slice(0, 1024).toString();
// html5
if (!res && str) {
res = /<meta.+?charset=(['"])(.+?)\1/i.exec(str);
}
// html4
if (!res && str) {
res = /<meta[\s]+?http-equiv=(['"])content-type\1[\s]+?content=(['"])(.+?)\2/i.exec(str);
if (res) {
res = /charset=(.*)/i.exec(res.pop());
}
}
// xml
if (!res && str) {
res = /<\?xml.+?encoding=(['"])(.+?)\1/i.exec(str);
}
// found charset
if (res) {
charset = res.pop();
// prevent decode issues when sites use incorrect encoding
// ref: https://hsivonen.fi/encoding-menu/
if (charset === 'gb2312' || charset === 'gbk') {
charset = 'gb18030';
}
}
// turn raw buffers into a single utf-8 buffer
return convert(buffer, 'UTF-8', charset).toString();
}
/**
* Detect a URLSearchParams object
* ref: https://github.com/bitinn/node-fetch/issues/296#issuecomment-307598143
*
* @param Object obj Object to detect by type or brand
* @return String
*/
function isURLSearchParams(obj) {
// Duck-typing as a necessary condition.
if (typeof obj !== 'object' || typeof obj.append !== 'function' || typeof obj.delete !== 'function' || typeof obj.get !== 'function' || typeof obj.getAll !== 'function' || typeof obj.has !== 'function' || typeof obj.set !== 'function') {
return false;
}
// Brand-checking and more duck-typing as optional condition.
return obj.constructor.name === 'URLSearchParams' || Object.prototype.toString.call(obj) === '[object URLSearchParams]' || typeof obj.sort === 'function';
}
/**
* Check if `obj` is a W3C `Blob` object (which `File` inherits from)
* @param {*} obj
* @return {boolean}
*/
function isBlob(obj) {
return typeof obj === 'object' && typeof obj.arrayBuffer === 'function' && typeof obj.type === 'string' && typeof obj.stream === 'function' && typeof obj.constructor === 'function' && typeof obj.constructor.name === 'string' && /^(Blob|File)$/.test(obj.constructor.name) && /^(Blob|File)$/.test(obj[Symbol.toStringTag]);
}
/**
* Clone body given Res/Req instance
*
* @param Mixed instance Response or Request instance
* @return Mixed
*/
function clone(instance) {
let p1, p2;
let body = instance.body;
// don't allow cloning a used body
if (instance.bodyUsed) {
throw new Error('cannot clone body after it is used');
}
// check that body is a stream and not form-data object
// note: we can't clone the form-data object without having it as a dependency
if (body instanceof Stream && typeof body.getBoundary !== 'function') {
// tee instance body
p1 = new PassThrough();
p2 = new PassThrough();
body.pipe(p1);
body.pipe(p2);
// set instance body to teed body and return the other teed body
instance[INTERNALS].body = p1;
body = p2;
}
return body;
}
/**
* Performs the operation "extract a `Content-Type` value from |object|" as
* specified in the specification:
* https://fetch.spec.whatwg.org/#concept-bodyinit-extract
*
* This function assumes that instance.body is present.
*
* @param Mixed instance Any options.body input
*/
function extractContentType(body) {
if (body === null) {
// body is null
return null;
} else if (typeof body === 'string') {
// body is string
return 'text/plain;charset=UTF-8';
} else if (isURLSearchParams(body)) {
// body is a URLSearchParams
return 'application/x-www-form-urlencoded;charset=UTF-8';
} else if (isBlob(body)) {
// body is blob
return body.type || null;
} else if (Buffer.isBuffer(body)) {
// body is buffer
return null;
} else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {
// body is ArrayBuffer
return null;
} else if (ArrayBuffer.isView(body)) {
// body is ArrayBufferView
return null;
} else if (typeof body.getBoundary === 'function') {
// detect form data input from form-data module
return `multipart/form-data;boundary=${body.getBoundary()}`;
} else if (body instanceof Stream) {
// body is stream
// can't really do much about this
return null;
} else {
// Body constructor defaults other things to string
return 'text/plain;charset=UTF-8';
}
}
/**
* The Fetch Standard treats this as if "total bytes" is a property on the body.
* For us, we have to explicitly get it with a function.
*
* ref: https://fetch.spec.whatwg.org/#concept-body-total-bytes
*
* @param Body instance Instance of Body
* @return Number? Number of bytes, or null if not possible
*/
function getTotalBytes(instance) {
const body = instance.body;
if (body === null) {
// body is null
return 0;
} else if (isBlob(body)) {
return body.size;
} else if (Buffer.isBuffer(body)) {
// body is buffer
return body.length;
} else if (body && typeof body.getLengthSync === 'function') {
// detect form data input from form-data module
if (body._lengthRetrievers && body._lengthRetrievers.length == 0 || // 1.x
body.hasKnownLength && body.hasKnownLength()) {
// 2.x
return body.getLengthSync();
}
return null;
} else {
// body is stream
return null;
}
}
/**
* Write a Body to a Node.js WritableStream (e.g. http.Request) object.
*
* @param Body instance Instance of Body
* @return Void
*/
function writeToStream(dest, instance) {
const body = instance.body;
if (body === null) {
// body is null
dest.end();
} else if (isBlob(body)) {
body.stream().pipe(dest);
} else if (Buffer.isBuffer(body)) {
// body is buffer
dest.write(body);
dest.end();
} else {
// body is stream
body.pipe(dest);
}
}
// expose Promise
Body.Promise = global.Promise;
/**
* headers.js
*
* Headers class offers convenient helpers
*/
const invalidTokenRegex = /[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/;
const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/;
function validateName(name) {
name = `${name}`;
if (invalidTokenRegex.test(name) || name === '') {
throw new TypeError(`${name} is not a legal HTTP header name`);
}
}
function validateValue(value) {
value = `${value}`;
if (invalidHeaderCharRegex.test(value)) {
throw new TypeError(`${value} is not a legal HTTP header value`);
}
}
/**
* Find the key in the map object given a header name.
*
* Returns undefined if not found.
*
* @param String name Header name
* @return String|Undefined
*/
function find(map, name) {
name = name.toLowerCase();
for (const key in map) {
if (key.toLowerCase() === name) {
return key;
}
}
return undefined;
}
const MAP = Symbol('map');
class Headers {
/**
* Headers class
*
* @param Object headers Response headers
* @return Void
*/
constructor() {
let init = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined;
this[MAP] = Object.create(null);
if (init instanceof Headers) {
const rawHeaders = init.raw();
const headerNames = Object.keys(rawHeaders);
for (const headerName of headerNames) {
for (const value of rawHeaders[headerName]) {
this.append(headerName, value);
}
}
return;
}
// We don't worry about converting prop to ByteString here as append()
// will handle it.
if (init == null) ; else if (typeof init === 'object') {
const method = init[Symbol.iterator];
if (method != null) {
if (typeof method !== 'function') {
throw new TypeError('Header pairs must be iterable');
}
// sequence<sequence<ByteString>>
// Note: per spec we have to first exhaust the lists then process them
const pairs = [];
for (const pair of init) {
if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') {
throw new TypeError('Each header pair must be iterable');
}
pairs.push(Array.from(pair));
}
for (const pair of pairs) {
if (pair.length !== 2) {
throw new TypeError('Each header pair must be a name/value tuple');
}
this.append(pair[0], pair[1]);
}
} else {
// record<ByteString, ByteString>
for (const key of Object.keys(init)) {
const value = init[key];
this.append(key, value);
}
}
} else {
throw new TypeError('Provided initializer must be an object');
}
}
/**
* Return combined header value given name
*
* @param String name Header name
* @return Mixed
*/
get(name) {
name = `${name}`;
validateName(name);
const key = find(this[MAP], name);
if (key === undefined) {
return null;
}
return this[MAP][key].join(', ');
}
/**
* Iterate over all headers
*
* @param Function callback Executed for each item with parameters (value, name, thisArg)
* @param Boolean thisArg `this` context for callback function
* @return Void
*/
forEach(callback) {
let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
let pairs = getHeaders(this);
let i = 0;
while (i < pairs.length) {
var _pairs$i = pairs[i];
const name = _pairs$i[0],
value = _pairs$i[1];
callback.call(thisArg, value, name, this);
pairs = getHeaders(this);
i++;
}
}
/**
* Overwrite header values given name
*
* @param String name Header name
* @param String value Header value
* @return Void
*/
set(name, value) {
name = `${name}`;
value = `${value}`;
validateName(name);
validateValue(value);
const key = find(this[MAP], name);
this[MAP][key !== undefined ? key : name] = [value];
}
/**
* Append a value onto existing header
*
* @param String name Header name
* @param String value Header value
* @return Void
*/
append(name, value) {
name = `${name}`;
value = `${value}`;
validateName(name);
validateValue(value);
const key = find(this[MAP], name);
if (key !== undefined) {
this[MAP][key].push(value);
} else {
this[MAP][name] = [value];
}
}
/**
* Check for header name existence
*
* @param String name Header name
* @return Boolean
*/
has(name) {
name = `${name}`;
validateName(name);
return find(this[MAP], name) !== undefined;
}
/**
* Delete all header values given name
*
* @param String name Header name
* @return Void
*/
delete(name) {
name = `${name}`;
validateName(name);
const key = find(this[MAP], name);
if (key !== undefined) {
delete this[MAP][key];
}
}
/**
* Return raw headers (non-spec api)
*
* @return Object
*/
raw() {
return this[MAP];
}
/**
* Get an iterator on keys.
*
* @return Iterator
*/
keys() {
return createHeadersIterator(this, 'key');
}
/**
* Get an iterator on values.
*
* @return Iterator
*/
values() {
return createHeadersIterator(this, 'value');
}
/**
* Get an iterator on entries.
*
* This is the default iterator of the Headers object.
*
* @return Iterator
*/
[Symbol.iterator]() {
return createHeadersIterator(this, 'key+value');
}
}
Headers.prototype.entries = Headers.prototype[Symbol.iterator];
Object.defineProperty(Headers.prototype, Symbol.toStringTag, {
value: 'Headers',
writable: false,
enumerable: false,
configurable: true
});
Object.defineProperties(Headers.prototype, {
get: { enumerable: true },
forEach: { enumerable: true },
set: { enumerable: true },
append: { enumerable: true },
has: { enumerable: true },
delete: { enumerable: true },
keys: { enumerable: true },
values: { enumerable: true },
entries: { enumerable: true }
});
function getHeaders(headers) {
let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value';
const keys = Object.keys(headers[MAP]).sort();
return keys.map(kind === 'key' ? function (k) {
return k.toLowerCase();
} : kind === 'value' ? function (k) {
return headers[MAP][k].join(', ');
} : function (k) {
return [k.toLowerCase(), headers[MAP][k].join(', ')];
});
}
const INTERNAL = Symbol('internal');
function createHeadersIterator(target, kind) {
const iterator = Object.create(HeadersIteratorPrototype);
iterator[INTERNAL] = {
target,
kind,
index: 0
};
return iterator;
}
const HeadersIteratorPrototype = Object.setPrototypeOf({
next() {
// istanbul ignore if
if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) {
throw new TypeError('Value of `this` is not a HeadersIterator');
}
var _INTERNAL = this[INTERNAL];
const target = _INTERNAL.target,
kind = _INTERNAL.kind,
index = _INTERNAL.index;
const values = getHeaders(target, kind);
const len = values.length;
if (index >= len) {
return {
value: undefined,
done: true
};
}
this[INTERNAL].index = index + 1;
return {
value: values[index],
done: false
};
}
}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));
Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, {
value: 'HeadersIterator',
writable: false,
enumerable: false,
configurable: true
});
/**
* Export the Headers object in a form that Node.js can consume.
*
* @param Headers headers
* @return Object
*/
function exportNodeCompatibleHeaders(headers) {
const obj = Object.assign({ __proto__: null }, headers[MAP]);
// http.request() only supports string as Host header. This hack makes
// specifying custom Host header possible.
const hostHeaderKey = find(headers[MAP], 'Host');
if (hostHeaderKey !== undefined) {
obj[hostHeaderKey] = obj[hostHeaderKey][0];
}
return obj;
}
/**
* Create a Headers object from an object of headers, ignoring those that do
* not conform to HTTP grammar productions.
*
* @param Object obj Object of headers
* @return Headers
*/
function createHeadersLenient(obj) {
const headers = new Headers();
for (const name of Object.keys(obj)) {
if (invalidTokenRegex.test(name)) {
continue;
}
if (Array.isArray(obj[name])) {
for (const val of obj[name]) {
if (invalidHeaderCharRegex.test(val)) {
continue;
}
if (headers[MAP][name] === undefined) {
headers[MAP][name] = [val];
} else {
headers[MAP][name].push(val);
}
}
} else if (!invalidHeaderCharRegex.test(obj[name])) {
headers[MAP][name] = [obj[name]];
}
}
return headers;
}
const INTERNALS$1 = Symbol('Response internals');
// fix an issue where "STATUS_CODES" aren't a named export for node <10
const STATUS_CODES = http.STATUS_CODES;
/**
* Response class
*
* @param Stream body Readable stream
* @param Object opts Response options
* @return Void
*/
class Response {
constructor() {
let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
Body.call(this, body, opts);
const status = opts.status || 200;
const headers = new Headers(opts.headers);
if (body != null && !headers.has('Content-Type')) {
const contentType = extractContentType(body);
if (contentType) {
headers.append('Content-Type', contentType);
}
}
this[INTERNALS$1] = {
url: opts.url,
status,
statusText: opts.statusText || STATUS_CODES[status],
headers,
counter: opts.counter
};
}
get url() {
return this[INTERNALS$1].url || '';
}
get status() {
return this[INTERNALS$1].status;
}
/**
* Convenience property representing if the request ended normally
*/
get ok() {
return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300;
}
get redirected() {
return this[INTERNALS$1].counter > 0;
}
get statusText() {
return this[INTERNALS$1].statusText;
}
get headers() {
return this[INTERNALS$1].headers;
}
/**
* Clone this response
*
* @return Response
*/
clone() {
return new Response(clone(this), {
url: this.url,
status: this.status,
statusText: this.statusText,
headers: this.headers,
ok: this.ok,
redirected: this.redirected
});
}
}
Body.mixIn(Response.prototype);
Object.defineProperties(Response.prototype, {
url: { enumerable: true },
status: { enumerable: true },
ok: { enumerable: true },
redirected: { enumerable: true },
statusText: { enumerable: true },
headers: { enumerable: true },
clone: { enumerable: true }
});
Object.defineProperty(Response.prototype, Symbol.toStringTag, {
value: 'Response',
writable: false,
enumerable: false,
configurable: true
});
const INTERNALS$2 = Symbol('Request internals');
// fix an issue where "format", "parse" aren't a named export for node <10
const parse_url = Url.parse;
const format_url = Url.format;
const streamDestructionSupported = 'destroy' in Stream.Readable.prototype;
/**
* Check if a value is an instance of Request.
*
* @param Mixed input
* @return Boolean
*/
function isRequest(input) {
return typeof input === 'object' && typeof input[INTERNALS$2] === 'object';
}
function isAbortSignal(signal) {
const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal);
return !!(proto && proto.constructor.name === 'AbortSignal');
}
/**
* Request class
*
* @param Mixed input Url or Request instance
* @param Object init Custom options
* @return Void
*/
class Request {
constructor(input) {
let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
let parsedURL;
// normalize input
if (!isRequest(input)) {
if (input && input.href) {
// in order to support Node.js' Url objects; though WHATWG's URL objects
// will fall into this branch also (since their `toString()` will return
// `href` property anyway)
parsedURL = parse_url(input.href);
} else {
// coerce input to a string before attempting to parse
parsedURL = parse_url(`${input}`);
}
input = {};
} else {
parsedURL = parse_url(input.url);
}
let method = init.method || input.method || 'GET';
method = method.toUpperCase();
if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) {
throw new TypeError('Request with GET/HEAD method cannot have body');
}
let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null;
Body.call(this, inputBody, {
timeout: init.timeout || input.timeout || 0,
size: init.size || input.size || 0
});
const headers = new Headers(init.headers || input.headers || {});
if (inputBody != null && !headers.has('Content-Type')) {
const contentType = extractContentType(inputBody);
if (contentType) {
headers.append('Content-Type', contentType);
}
}
let signal = isRequest(input) ? input.signal : null;
if ('signal' in init) signal = init.signal;
if (signal != null && !isAbortSignal(signal)) {
throw new TypeError('Expected signal to be an instanceof AbortSignal');
}
this[INTERNALS$2] = {
method,
redirect: init.redirect || input.redirect || 'follow',
headers,
parsedURL,
signal
};
// node-fetch-only options
this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20;
this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true;
this.counter = init.counter || input.counter || 0;
this.agent = init.agent || input.agent;
}
get method() {
return this[INTERNALS$2].method;
}
get url() {
return format_url(this[INTERNALS$2].parsedURL);
}
get headers() {
return this[INTERNALS$2].headers;
}
get redirect() {
return this[INTERNALS$2].redirect;
}
get signal() {
return this[INTERNALS$2].signal;
}
/**
* Clone this request
*
* @return Request
*/
clone() {
return new Request(this);
}
}
Body.mixIn(Request.prototype);
Object.defineProperty(Request.prototype, Symbol.toStringTag, {
value: 'Request',
writable: false,
enumerable: false,
configurable: true
});
Object.defineProperties(Request.prototype, {
method: { enumerable: true },
url: { enumerable: true },
headers: { enumerable: true },
redirect: { enumerable: true },
clone: { enumerable: true },
signal: { enumerable: true }
});
/**
* Convert a Request to Node.js http request options.
*
* @param Request A Request instance
* @return Object The options object to be passed to http.request
*/
function getNodeRequestOptions(request) {
const parsedURL = request[INTERNALS$2].parsedURL;
const headers = new Headers(request[INTERNALS$2].headers);
// fetch step 1.3
if (!headers.has('Accept')) {
headers.set('Accept', '*/*');
}
// Basic fetch
if (!parsedURL.protocol || !parsedURL.hostname) {
throw new TypeError('Only absolute URLs are supported');
}
if (!/^https?:$/.test(parsedURL.protocol)) {
throw new TypeError('Only HTTP(S) protocols are supported');
}
if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) {
throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8');
}
// HTTP-network-or-cache fetch steps 2.4-2.7
let contentLengthValue = null;
if (request.body == null && /^(POST|PUT)$/i.test(request.method)) {
contentLengthValue = '0';
}
if (request.body != null) {
const totalBytes = getTotalBytes(request);
if (typeof totalBytes === 'number') {
contentLengthValue = String(totalBytes);
}
}
if (contentLengthValue) {
headers.set('Content-Length', contentLengthValue);
}
// HTTP-network-or-cache fetch step 2.11
if (!headers.has('User-Agent')) {
headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)');
}
// HTTP-network-or-cache fetch step 2.15
if (request.compress && !headers.has('Accept-Encoding')) {
headers.set('Accept-Encoding', 'gzip,deflate');
}
let agent = request.agent;
if (typeof agent === 'function') {
agent = agent(parsedURL);
}
if (!headers.has('Connection') && !agent) {
headers.set('Connection', 'close');
}
// HTTP-network fetch step 4.2
// chunked encoding is handled by Node.js
return Object.assign({}, parsedURL, {
method: request.method,
headers: exportNodeCompatibleHeaders(headers),
agent
});
}
/**
* abort-error.js
*
* AbortError interface for cancelled requests
*/
/**
* Create AbortError instance
*
* @param String message Error message for human
* @return AbortError
*/
function AbortError(message) {
Error.call(this, message);
this.type = 'aborted';
this.message = message;
// hide custom error implementation details from end-users
Error.captureStackTrace(this, this.constructor);
}
AbortError.prototype = Object.create(Error.prototype);
AbortError.prototype.constructor = AbortError;
AbortError.prototype.name = 'AbortError';
// fix an issue where "PassThrough", "resolve" aren't a named export for node <10
const PassThrough$1 = Stream.PassThrough;
const resolve_url = Url.resolve;
/**
* Fetch function
*
* @param Mixed url Absolute url or Request instance
* @param Object opts Fetch options
* @return Promise
*/
function fetch(url, opts) {
// allow custom promise
if (!fetch.Promise) {
throw new Error('native promise missing, set fetch.Promise to your favorite alternative');
}
Body.Promise = fetch.Promise;
// wrap http.request into fetch
return new fetch.Promise(function (resolve, reject) {
// build request object
const request = new Request(url, opts);
const options = getNodeRequestOptions(request);
const send = (options.protocol === 'https:' ? https : http).request;
const signal = request.signal;
let response = null;
const abort = function abort() {
let error = new AbortError('The user aborted a request.');
reject(error);
if (request.body && request.body instanceof Stream.Readable) {
request.body.destroy(error);
}
if (!response || !response.body) return;
response.body.emit('error', error);
};
if (signal && signal.aborted) {
abort();
return;
}
const abortAndFinalize = function abortAndFinalize() {
abort();
finalize();
};
// send request
const req = send(options);
let reqTimeout;
if (signal) {
signal.addEventListener('abort', abortAndFinalize);
}
function finalize() {
req.abort();
if (signal) signal.removeEventListener('abort', abortAndFinalize);
clearTimeout(reqTimeout);
}
if (request.timeout) {
req.once('socket', function (socket) {
reqTimeout = setTimeout(function () {
reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout'));
finalize();
}, request.timeout);
});
}
req.on('error', function (err) {
reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));
finalize();
});
req.on('response', function (res) {
clearTimeout(reqTimeout);
const headers = createHeadersLenient(res.headers);
// HTTP fetch step 5
if (fetch.isRedirect(res.statusCode)) {
// HTTP fetch step 5.2
const location = headers.get('Location');
// HTTP fetch step 5.3
const locationURL = location === null ? null : resolve_url(request.url, location);
// HTTP fetch step 5.5
switch (request.redirect) {
case 'error':
reject(new FetchError(`redirect mode is set to error: ${request.url}`, 'no-redirect'));
finalize();
return;
case 'manual':
// node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL.
if (locationURL !== null) {
// handle corrupted header
try {
headers.set('Location', locationURL);
} catch (err) {
// istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request
reject(err);
}
}
break;
case 'follow':
// HTTP-redirect fetch step 2
if (locationURL === null) {
break;
}
// HTTP-redirect fetch step 5
if (request.counter >= request.follow) {
reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect'));
finalize();
return;
}
// HTTP-redirect fetch step 6 (counter increment)
// Create a new Request object.
const requestOpts = {
headers: new Headers(request.headers),
follow: request.follow,
counter: request.counter + 1,
agent: request.agent,
compress: request.compress,
method: request.method,
body: request.body,
signal: request.signal,
timeout: request.timeout
};
// HTTP-redirect fetch step 9
if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) {
reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect'));
finalize();
return;
}
// HTTP-redirect fetch step 11
if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') {
requestOpts.method = 'GET';
requestOpts.body = undefined;
requestOpts.headers.delete('content-length');
}
// HTTP-redirect fetch step 15
resolve(fetch(new Request(locationURL, requestOpts)));
finalize();
return;
}
}
// prepare response
res.once('end', function () {
if (signal) signal.removeEventListener('abort', abortAndFinalize);
});
let body = res.pipe(new PassThrough$1());
const response_options = {
url: request.url,
status: res.statusCode,
statusText: res.statusMessage,
headers: headers,
size: request.size,
timeout: request.timeout,
counter: request.counter
};
// HTTP-network fetch step 12.1.1.3
const codings = headers.get('Content-Encoding');
// HTTP-network fetch step 12.1.1.4: handle content codings
// in following scenarios we ignore compression support
// 1. compression support is disabled
// 2. HEAD request
// 3. no Content-Encoding header
// 4. no content response (204)
// 5. content not modified response (304)
if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) {
response = new Response(body, response_options);
resolve(response);
return;
}
// For Node v6+
// Be less strict when decoding compressed responses, since sometimes
// servers send slightly invalid responses that are still accepted
// by common browsers.
// Always using Z_SYNC_FLUSH is what cURL does.
const zlibOptions = {
flush: zlib.Z_SYNC_FLUSH,
finishFlush: zlib.Z_SYNC_FLUSH
};
// for gzip
if (codings == 'gzip' || codings == 'x-gzip') {
body = body.pipe(zlib.createGunzip(zlibOptions));
response = new Response(body, response_options);
resolve(response);
return;
}
// for deflate
if (codings == 'deflate' || codings == 'x-deflate') {
// handle the infamous raw deflate response from old servers
// a hack for old IIS and Apache servers
const raw = res.pipe(new PassThrough$1());
raw.once('data', function (chunk) {
// see http://stackoverflow.com/questions/37519828
if ((chunk[0] & 0x0F) === 0x08) {
body = body.pipe(zlib.createInflate());
} else {
body = body.pipe(zlib.createInflateRaw());
}
response = new Response(body, response_options);
resolve(response);
});
return;
}
// for br
if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') {
body = body.pipe(zlib.createBrotliDecompress());
response = new Response(body, response_options);
resolve(response);
return;
}
// otherwise, use response as-is
response = new Response(body, response_options);
resolve(response);
});
writeToStream(req, request);
});
}
/**
* Redirect code matching
*
* @param Number code Status code
* @return Boolean
*/
fetch.isRedirect = function (code) {
return code === 301 || code === 302 || code === 303 || code === 307 || code === 308;
};
// expose Promise
fetch.Promise = global.Promise;
module.exports = exports = fetch;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = exports;
exports.Headers = Headers;
exports.Request = Request;
exports.Response = Response;
exports.FetchError = FetchError;
/***/ }),
/***/ 463:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var deprecation = __webpack_require__(692);
var once = _interopDefault(__webpack_require__(49));
const logOnce = once(deprecation => console.warn(deprecation));
/**
* Error with extra properties to help with debugging
*/
class RequestError extends Error {
constructor(message, statusCode, options) {
super(message); // Maintains proper stack trace (only available on V8)
/* istanbul ignore next */
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
this.name = "HttpError";
this.status = statusCode;
Object.defineProperty(this, "code", {
get() {
logOnce(new deprecation.Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`."));
return statusCode;
}
});
this.headers = options.headers || {}; // redact request credentials without mutating original request options
const requestCopy = Object.assign({}, options.request);
if (options.request.headers.authorization) {
requestCopy.headers = Object.assign({}, options.request.headers, {
authorization: options.request.headers.authorization.replace(/ .*$/, " [REDACTED]")
});
}
requestCopy.url = requestCopy.url // client_id & client_secret can be passed as URL query parameters to increase rate limit
// see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications
.replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]") // OAuth tokens can be passed as URL query parameters, although it is not recommended
// see https://developer.github.com/v3/#oauth2-token-sent-in-a-header
.replace(/\baccess_token=\w+/g, "access_token=[REDACTED]");
this.request = requestCopy;
}
}
exports.RequestError = RequestError;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 469:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"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 (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getOctokit = exports.context = void 0;
const Context = __importStar(__webpack_require__(262));
const utils_1 = __webpack_require__(521);
exports.context = new Context.Context();
/**
* Returns a hydrated octokit ready to use for GitHub Actions
*
* @param token the repo PAT or GITHUB_TOKEN
* @param options other options to set
*/
function getOctokit(token, options) {
return new utils_1.GitHub(utils_1.getOctokitOptions(token, options));
}
exports.getOctokit = getOctokit;
//# sourceMappingURL=github.js.map
/***/ }),
/***/ 470:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (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());
});
};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const command_1 = __webpack_require__(431);
const os = __importStar(__webpack_require__(87));
const path = __importStar(__webpack_require__(622));
/**
* The code to exit an action
*/
var ExitCode;
(function (ExitCode) {
/**
* A code indicating that the action was successful
*/
ExitCode[ExitCode["Success"] = 0] = "Success";
/**
* A code indicating that the action was a failure
*/
ExitCode[ExitCode["Failure"] = 1] = "Failure";
})(ExitCode = exports.ExitCode || (exports.ExitCode = {}));
//-----------------------------------------------------------------------
// Variables
//-----------------------------------------------------------------------
/**
* Sets env variable for this action and future actions in the job
* @param name the name of the variable to set
* @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function exportVariable(name, val) {
const convertedVal = command_1.toCommandValue(val);
process.env[name] = convertedVal;
command_1.issueCommand('set-env', { name }, convertedVal);
}
exports.exportVariable = exportVariable;
/**
* Registers a secret which will get masked from logs
* @param secret value of the secret
*/
function setSecret(secret) {
command_1.issueCommand('add-mask', {}, secret);
}
exports.setSecret = setSecret;
/**
* Prepends inputPath to the PATH (for this action and future actions)
* @param inputPath
*/
function addPath(inputPath) {
command_1.issueCommand('add-path', {}, inputPath);
process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`;
}
exports.addPath = addPath;
/**
* Gets the value of an input. The value is also trimmed.
*
* @param name name of the input to get
* @param options optional. See InputOptions.
* @returns string
*/
function getInput(name, options) {
const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || '';
if (options && options.required && !val) {
throw new Error(`Input required and not supplied: ${name}`);
}
return val.trim();
}
exports.getInput = getInput;
/**
* Sets the value of an output.
*
* @param name name of the output to set
* @param value value to store. Non-string values will be converted to a string via JSON.stringify
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function setOutput(name, value) {
command_1.issueCommand('set-output', { name }, value);
}
exports.setOutput = setOutput;
/**
* Enables or disables the echoing of commands into stdout for the rest of the step.
* Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set.
*
*/
function setCommandEcho(enabled) {
command_1.issue('echo', enabled ? 'on' : 'off');
}
exports.setCommandEcho = setCommandEcho;
//-----------------------------------------------------------------------
// Results
//-----------------------------------------------------------------------
/**
* Sets the action status to failed.
* When the action exits it will be with an exit code of 1
* @param message add error issue message
*/
function setFailed(message) {
process.exitCode = ExitCode.Failure;
error(message);
}
exports.setFailed = setFailed;
//-----------------------------------------------------------------------
// Logging Commands
//-----------------------------------------------------------------------
/**
* Gets whether Actions Step Debug is on or not
*/
function isDebug() {
return process.env['RUNNER_DEBUG'] === '1';
}
exports.isDebug = isDebug;
/**
* Writes debug message to user log
* @param message debug message
*/
function debug(message) {
command_1.issueCommand('debug', {}, message);
}
exports.debug = debug;
/**
* Adds an error issue
* @param message error issue message. Errors will be converted to string via toString()
*/
function error(message) {
command_1.issue('error', message instanceof Error ? message.toString() : message);
}
exports.error = error;
/**
* Adds an warning issue
* @param message warning issue message. Errors will be converted to string via toString()
*/
function warning(message) {
command_1.issue('warning', message instanceof Error ? message.toString() : message);
}
exports.warning = warning;
/**
* Writes info to log with console.log.
* @param message info message
*/
function info(message) {
process.stdout.write(message + os.EOL);
}
exports.info = info;
/**
* Begin an output group.
*
* Output until the next `groupEnd` will be foldable in this group
*
* @param name The name of the output group
*/
function startGroup(name) {
command_1.issue('group', name);
}
exports.startGroup = startGroup;
/**
* End an output group.
*/
function endGroup() {
command_1.issue('endgroup');
}
exports.endGroup = endGroup;
/**
* Wrap an asynchronous function call in a group.
*
* Returns the same type as the function itself.
*
* @param name The name of the group
* @param fn The function to wrap in the group
*/
function group(name, fn) {
return __awaiter(this, void 0, void 0, function* () {
startGroup(name);
let result;
try {
result = yield fn();
}
finally {
endGroup();
}
return result;
});
}
exports.group = group;
//-----------------------------------------------------------------------
// Wrapper action state
//-----------------------------------------------------------------------
/**
* Saves state for current action, the state can only be retrieved by this action's post job execution.
*
* @param name name of the state to store
* @param value value to store. Non-string values will be converted to a string via JSON.stringify
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function saveState(name, value) {
command_1.issueCommand('save-state', { name }, value);
}
exports.saveState = saveState;
/**
* Gets the value of an state set by this action's main execution.
*
* @param name name of the state to get
* @returns string
*/
function getState(name) {
return process.env[`STATE_${name}`] || '';
}
exports.getState = getState;
//# sourceMappingURL=core.js.map
/***/ }),
/***/ 510:
/***/ (function(module) {
module.exports = addHook
function addHook (state, kind, name, hook) {
var orig = hook
if (!state.registry[name]) {
state.registry[name] = []
}
if (kind === 'before') {
hook = function (method, options) {
return Promise.resolve()
.then(orig.bind(null, options))
.then(method.bind(null, options))
}
}
if (kind === 'after') {
hook = function (method, options) {
var result
return Promise.resolve()
.then(method.bind(null, options))
.then(function (result_) {
result = result_
return orig(result, options)
})
.then(function () {
return result
})
}
}
if (kind === 'error') {
hook = function (method, options) {
return Promise.resolve()
.then(method.bind(null, options))
.catch(function (error) {
return orig(error, options)
})
}
}
state.registry[name].push({
hook: hook,
orig: orig
})
}
/***/ }),
/***/ 518:
/***/ (function(module) {
"use strict";
// Manually added data to be used by sbcs codec in addition to generated one.
module.exports = {
// Not supported by iconv, not sure why.
"10029": "maccenteuro",
"maccenteuro": {
"type": "_sbcs",
"chars": "ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ"
},
"808": "cp808",
"ibm808": "cp808",
"cp808": {
"type": "_sbcs",
"chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№€■ "
},
"mik": {
"type": "_sbcs",
"chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя└┴┬├─┼╣║╚╔╩╦╠═╬┐░▒▓│┤№§╗╝┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
},
"cp720": {
"type": "_sbcs",
"chars": "\x80\x81éâ\x84à\x86çêëèïî\x8d\x8e\x8f\x90\u0651\u0652ô¤ـûùءآأؤ£إئابةتثجحخدذرزسشص«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ضطظعغفµقكلمنهوىي≡\u064b\u064c\u064d\u064e\u064f\u0650≈°∙·√ⁿ²■\u00a0"
},
// Aliases of generated encodings.
"ascii8bit": "ascii",
"usascii": "ascii",
"ansix34": "ascii",
"ansix341968": "ascii",
"ansix341986": "ascii",
"csascii": "ascii",
"cp367": "ascii",
"ibm367": "ascii",
"isoir6": "ascii",
"iso646us": "ascii",
"iso646irv": "ascii",
"us": "ascii",
"latin1": "iso88591",
"latin2": "iso88592",
"latin3": "iso88593",
"latin4": "iso88594",
"latin5": "iso88599",
"latin6": "iso885910",
"latin7": "iso885913",
"latin8": "iso885914",
"latin9": "iso885915",
"latin10": "iso885916",
"csisolatin1": "iso88591",
"csisolatin2": "iso88592",
"csisolatin3": "iso88593",
"csisolatin4": "iso88594",
"csisolatincyrillic": "iso88595",
"csisolatinarabic": "iso88596",
"csisolatingreek" : "iso88597",
"csisolatinhebrew": "iso88598",
"csisolatin5": "iso88599",
"csisolatin6": "iso885910",
"l1": "iso88591",
"l2": "iso88592",
"l3": "iso88593",
"l4": "iso88594",
"l5": "iso88599",
"l6": "iso885910",
"l7": "iso885913",
"l8": "iso885914",
"l9": "iso885915",
"l10": "iso885916",
"isoir14": "iso646jp",
"isoir57": "iso646cn",
"isoir100": "iso88591",
"isoir101": "iso88592",
"isoir109": "iso88593",
"isoir110": "iso88594",
"isoir144": "iso88595",
"isoir127": "iso88596",
"isoir126": "iso88597",
"isoir138": "iso88598",
"isoir148": "iso88599",
"isoir157": "iso885910",
"isoir166": "tis620",
"isoir179": "iso885913",
"isoir199": "iso885914",
"isoir203": "iso885915",
"isoir226": "iso885916",
"cp819": "iso88591",
"ibm819": "iso88591",
"cyrillic": "iso88595",
"arabic": "iso88596",
"arabic8": "iso88596",
"ecma114": "iso88596",
"asmo708": "iso88596",
"greek" : "iso88597",
"greek8" : "iso88597",
"ecma118" : "iso88597",
"elot928" : "iso88597",
"hebrew": "iso88598",
"hebrew8": "iso88598",
"turkish": "iso88599",
"turkish8": "iso88599",
"thai": "iso885911",
"thai8": "iso885911",
"celtic": "iso885914",
"celtic8": "iso885914",
"isoceltic": "iso885914",
"tis6200": "tis620",
"tis62025291": "tis620",
"tis62025330": "tis620",
"10000": "macroman",
"10006": "macgreek",
"10007": "maccyrillic",
"10079": "maciceland",
"10081": "macturkish",
"cspc8codepage437": "cp437",
"cspc775baltic": "cp775",
"cspc850multilingual": "cp850",
"cspcp852": "cp852",
"cspc862latinhebrew": "cp862",
"cpgr": "cp869",
"msee": "cp1250",
"mscyrl": "cp1251",
"msansi": "cp1252",
"msgreek": "cp1253",
"msturk": "cp1254",
"mshebr": "cp1255",
"msarab": "cp1256",
"winbaltrim": "cp1257",
"cp20866": "koi8r",
"20866": "koi8r",
"ibm878": "koi8r",
"cskoi8r": "koi8r",
"cp21866": "koi8u",
"21866": "koi8u",
"ibm1168": "koi8u",
"strk10482002": "rk1048",
"tcvn5712": "tcvn",
"tcvn57121": "tcvn",
"gb198880": "iso646cn",
"cn": "iso646cn",
"csiso14jisc6220ro": "iso646jp",
"jisc62201969ro": "iso646jp",
"jp": "iso646jp",
"cshproman8": "hproman8",
"r8": "hproman8",
"roman8": "hproman8",
"xroman8": "hproman8",
"ibm1051": "hproman8",
"mac": "macintosh",
"csmacintosh": "macintosh",
};
/***/ }),
/***/ 521:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"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 (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getOctokitOptions = exports.GitHub = exports.context = void 0;
const Context = __importStar(__webpack_require__(262));
const Utils = __importStar(__webpack_require__(127));
// octokit + plugins
const core_1 = __webpack_require__(448);
const plugin_rest_endpoint_methods_1 = __webpack_require__(842);
const plugin_paginate_rest_1 = __webpack_require__(299);
exports.context = new Context.Context();
const baseUrl = Utils.getApiBaseUrl();
const defaults = {
baseUrl,
request: {
agent: Utils.getProxyAgent(baseUrl)
}
};
exports.GitHub = core_1.Octokit.plugin(plugin_rest_endpoint_methods_1.restEndpointMethods, plugin_paginate_rest_1.paginateRest).defaults(defaults);
/**
* Convience function to correctly format Octokit Options to pass into the constructor.
*
* @param token the repo PAT or GITHUB_TOKEN
* @param options other options to set
*/
function getOctokitOptions(token, options) {
const opts = Object.assign({}, options || {}); // Shallow clone - don't mutate the object provided by the caller
// Auth
const auth = Utils.getAuthString(token, opts);
if (auth) {
opts.auth = auth;
}
return opts;
}
exports.getOctokitOptions = getOctokitOptions;
//# sourceMappingURL=utils.js.map
/***/ }),
/***/ 523:
/***/ (function(module, __unusedexports, __webpack_require__) {
var register = __webpack_require__(280)
var addHook = __webpack_require__(510)
var removeHook = __webpack_require__(866)
// bind with array of arguments: https://stackoverflow.com/a/21792913
var bind = Function.bind
var bindable = bind.bind(bind)
function bindApi (hook, state, name) {
var removeHookRef = bindable(removeHook, null).apply(null, name ? [state, name] : [state])
hook.api = { remove: removeHookRef }
hook.remove = removeHookRef
;['before', 'error', 'after', 'wrap'].forEach(function (kind) {
var args = name ? [state, kind, name] : [state, kind]
hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args)
})
}
function HookSingular () {
var singularHookName = 'h'
var singularHookState = {
registry: {}
}
var singularHook = register.bind(null, singularHookState, singularHookName)
bindApi(singularHook, singularHookState, singularHookName)
return singularHook
}
function HookCollection () {
var state = {
registry: {}
}
var hook = register.bind(null, state)
bindApi(hook, state)
return hook
}
var collectionHookDeprecationMessageDisplayed = false
function Hook () {
if (!collectionHookDeprecationMessageDisplayed) {
console.warn('[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4')
collectionHookDeprecationMessageDisplayed = true
}
return HookCollection()
}
Hook.Singular = HookSingular.bind()
Hook.Collection = HookCollection.bind()
module.exports = Hook
// expose constructors as a named property for TypeScript
module.exports.Hook = Hook
module.exports.Singular = Hook.Singular
module.exports.Collection = Hook.Collection
/***/ }),
/***/ 537:
/***/ (function(module, __unusedexports, __webpack_require__) {
"use strict";
const utils = __webpack_require__(265);
const {
CHAR_ASTERISK, /* * */
CHAR_AT, /* @ */
CHAR_BACKWARD_SLASH, /* \ */
CHAR_COMMA, /* , */
CHAR_DOT, /* . */
CHAR_EXCLAMATION_MARK, /* ! */
CHAR_FORWARD_SLASH, /* / */
CHAR_LEFT_CURLY_BRACE, /* { */
CHAR_LEFT_PARENTHESES, /* ( */
CHAR_LEFT_SQUARE_BRACKET, /* [ */
CHAR_PLUS, /* + */
CHAR_QUESTION_MARK, /* ? */
CHAR_RIGHT_CURLY_BRACE, /* } */
CHAR_RIGHT_PARENTHESES, /* ) */
CHAR_RIGHT_SQUARE_BRACKET /* ] */
} = __webpack_require__(199);
const isPathSeparator = code => {
return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
};
const depth = token => {
if (token.isPrefix !== true) {
token.depth = token.isGlobstar ? Infinity : 1;
}
};
/**
* Quickly scans a glob pattern and returns an object with a handful of
* useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
* `glob` (the actual pattern), and `negated` (true if the path starts with `!`).
*
* ```js
* const pm = require('picomatch');
* console.log(pm.scan('foo/bar/*.js'));
* { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
* ```
* @param {String} `str`
* @param {Object} `options`
* @return {Object} Returns an object with tokens and regex source string.
* @api public
*/
const scan = (input, options) => {
const opts = options || {};
const length = input.length - 1;
const scanToEnd = opts.parts === true || opts.scanToEnd === true;
const slashes = [];
const tokens = [];
const parts = [];
let str = input;
let index = -1;
let start = 0;
let lastIndex = 0;
let isBrace = false;
let isBracket = false;
let isGlob = false;
let isExtglob = false;
let isGlobstar = false;
let braceEscaped = false;
let backslashes = false;
let negated = false;
let finished = false;
let braces = 0;
let prev;
let code;
let token = { value: '', depth: 0, isGlob: false };
const eos = () => index >= length;
const peek = () => str.charCodeAt(index + 1);
const advance = () => {
prev = code;
return str.charCodeAt(++index);
};
while (index < length) {
code = advance();
let next;
if (code === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
code = advance();
if (code === CHAR_LEFT_CURLY_BRACE) {
braceEscaped = true;
}
continue;
}
if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
braces++;
while (eos() !== true && (code = advance())) {
if (code === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
advance();
continue;
}
if (code === CHAR_LEFT_CURLY_BRACE) {
braces++;
continue;
}
if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
isBrace = token.isBrace = true;
isGlob = token.isGlob = true;
finished = true;
if (scanToEnd === true) {
continue;
}
break;
}
if (braceEscaped !== true && code === CHAR_COMMA) {
isBrace = token.isBrace = true;
isGlob = token.isGlob = true;
finished = true;
if (scanToEnd === true) {
continue;
}
break;
}
if (code === CHAR_RIGHT_CURLY_BRACE) {
braces--;
if (braces === 0) {
braceEscaped = false;
isBrace = token.isBrace = true;
finished = true;
break;
}
}
}
if (scanToEnd === true) {
continue;
}
break;
}
if (code === CHAR_FORWARD_SLASH) {
slashes.push(index);
tokens.push(token);
token = { value: '', depth: 0, isGlob: false };
if (finished === true) continue;
if (prev === CHAR_DOT && index === (start + 1)) {
start += 2;
continue;
}
lastIndex = index + 1;
continue;
}
if (opts.noext !== true) {
const isExtglobChar = code === CHAR_PLUS
|| code === CHAR_AT
|| code === CHAR_ASTERISK
|| code === CHAR_QUESTION_MARK
|| code === CHAR_EXCLAMATION_MARK;
if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
isGlob = token.isGlob = true;
isExtglob = token.isExtglob = true;
finished = true;
if (scanToEnd === true) {
while (eos() !== true && (code = advance())) {
if (code === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
code = advance();
continue;
}
if (code === CHAR_RIGHT_PARENTHESES) {
isGlob = token.isGlob = true;
finished = true;
break;
}
}
continue;
}
break;
}
}
if (code === CHAR_ASTERISK) {
if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
isGlob = token.isGlob = true;
finished = true;
if (scanToEnd === true) {
continue;
}
break;
}
if (code === CHAR_QUESTION_MARK) {
isGlob = token.isGlob = true;
finished = true;
if (scanToEnd === true) {
continue;
}
break;
}
if (code === CHAR_LEFT_SQUARE_BRACKET) {
while (eos() !== true && (next = advance())) {
if (next === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
advance();
continue;
}
if (next === CHAR_RIGHT_SQUARE_BRACKET) {
isBracket = token.isBracket = true;
isGlob = token.isGlob = true;
finished = true;
if (scanToEnd === true) {
continue;
}
break;
}
}
}
if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
negated = token.negated = true;
start++;
continue;
}
if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
isGlob = token.isGlob = true;
if (scanToEnd === true) {
while (eos() !== true && (code = advance())) {
if (code === CHAR_LEFT_PARENTHESES) {
backslashes = token.backslashes = true;
code = advance();
continue;
}
if (code === CHAR_RIGHT_PARENTHESES) {
finished = true;
break;
}
}
continue;
}
break;
}
if (isGlob === true) {
finished = true;
if (scanToEnd === true) {
continue;
}
break;
}
}
if (opts.noext === true) {
isExtglob = false;
isGlob = false;
}
let base = str;
let prefix = '';
let glob = '';
if (start > 0) {
prefix = str.slice(0, start);
str = str.slice(start);
lastIndex -= start;
}
if (base && isGlob === true && lastIndex > 0) {
base = str.slice(0, lastIndex);
glob = str.slice(lastIndex);
} else if (isGlob === true) {
base = '';
glob = str;
} else {
base = str;
}
if (base && base !== '' && base !== '/' && base !== str) {
if (isPathSeparator(base.charCodeAt(base.length - 1))) {
base = base.slice(0, -1);
}
}
if (opts.unescape === true) {
if (glob) glob = utils.removeBackslashes(glob);
if (base && backslashes === true) {
base = utils.removeBackslashes(base);
}
}
const state = {
prefix,
input,
start,
base,
glob,
isBrace,
isBracket,
isGlob,
isExtglob,
isGlobstar,
negated
};
if (opts.tokens === true) {
state.maxDepth = 0;
if (!isPathSeparator(code)) {
tokens.push(token);
}
state.tokens = tokens;
}
if (opts.parts === true || opts.tokens === true) {
let prevIndex;
for (let idx = 0; idx < slashes.length; idx++) {
const n = prevIndex ? prevIndex + 1 : start;
const i = slashes[idx];
const value = input.slice(n, i);
if (opts.tokens) {
if (idx === 0 && start !== 0) {
tokens[idx].isPrefix = true;
tokens[idx].value = prefix;
} else {
tokens[idx].value = value;
}
depth(tokens[idx]);
state.maxDepth += tokens[idx].depth;
}
if (idx !== 0 || value !== '') {
parts.push(value);
}
prevIndex = i;
}
if (prevIndex && prevIndex + 1 < input.length) {
const value = input.slice(prevIndex + 1);
parts.push(value);
if (opts.tokens) {
tokens[tokens.length - 1].value = value;
depth(tokens[tokens.length - 1]);
state.maxDepth += tokens[tokens.length - 1].depth;
}
}
state.slashes = slashes;
state.parts = parts;
}
return state;
};
module.exports = scan;
/***/ }),
/***/ 539:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const url = __webpack_require__(835);
const http = __webpack_require__(605);
const https = __webpack_require__(211);
const pm = __webpack_require__(950);
let tunnel;
var HttpCodes;
(function (HttpCodes) {
HttpCodes[HttpCodes["OK"] = 200] = "OK";
HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices";
HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently";
HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved";
HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther";
HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified";
HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy";
HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy";
HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect";
HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect";
HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest";
HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized";
HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired";
HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden";
HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound";
HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed";
HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable";
HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";
HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout";
HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict";
HttpCodes[HttpCodes["Gone"] = 410] = "Gone";
HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests";
HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError";
HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented";
HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway";
HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable";
HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout";
})(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {}));
var Headers;
(function (Headers) {
Headers["Accept"] = "accept";
Headers["ContentType"] = "content-type";
})(Headers = exports.Headers || (exports.Headers = {}));
var MediaTypes;
(function (MediaTypes) {
MediaTypes["ApplicationJson"] = "application/json";
})(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {}));
/**
* Returns the proxy URL, depending upon the supplied url and proxy environment variables.
* @param serverUrl The server URL where the request will be sent. For example, https://api.github.com
*/
function getProxyUrl(serverUrl) {
let proxyUrl = pm.getProxyUrl(url.parse(serverUrl));
return proxyUrl ? proxyUrl.href : '';
}
exports.getProxyUrl = getProxyUrl;
const HttpRedirectCodes = [
HttpCodes.MovedPermanently,
HttpCodes.ResourceMoved,
HttpCodes.SeeOther,
HttpCodes.TemporaryRedirect,
HttpCodes.PermanentRedirect
];
const HttpResponseRetryCodes = [
HttpCodes.BadGateway,
HttpCodes.ServiceUnavailable,
HttpCodes.GatewayTimeout
];
const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD'];
const ExponentialBackoffCeiling = 10;
const ExponentialBackoffTimeSlice = 5;
class HttpClientResponse {
constructor(message) {
this.message = message;
}
readBody() {
return new Promise(async (resolve, reject) => {
let output = Buffer.alloc(0);
this.message.on('data', (chunk) => {
output = Buffer.concat([output, chunk]);
});
this.message.on('end', () => {
resolve(output.toString());
});
});
}
}
exports.HttpClientResponse = HttpClientResponse;
function isHttps(requestUrl) {
let parsedUrl = url.parse(requestUrl);
return parsedUrl.protocol === 'https:';
}
exports.isHttps = isHttps;
class HttpClient {
constructor(userAgent, handlers, requestOptions) {
this._ignoreSslError = false;
this._allowRedirects = true;
this._allowRedirectDowngrade = false;
this._maxRedirects = 50;
this._allowRetries = false;
this._maxRetries = 1;
this._keepAlive = false;
this._disposed = false;
this.userAgent = userAgent;
this.handlers = handlers || [];
this.requestOptions = requestOptions;
if (requestOptions) {
if (requestOptions.ignoreSslError != null) {
this._ignoreSslError = requestOptions.ignoreSslError;
}
this._socketTimeout = requestOptions.socketTimeout;
if (requestOptions.allowRedirects != null) {
this._allowRedirects = requestOptions.allowRedirects;
}
if (requestOptions.allowRedirectDowngrade != null) {
this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade;
}
if (requestOptions.maxRedirects != null) {
this._maxRedirects = Math.max(requestOptions.maxRedirects, 0);
}
if (requestOptions.keepAlive != null) {
this._keepAlive = requestOptions.keepAlive;
}
if (requestOptions.allowRetries != null) {
this._allowRetries = requestOptions.allowRetries;
}
if (requestOptions.maxRetries != null) {
this._maxRetries = requestOptions.maxRetries;
}
}
}
options(requestUrl, additionalHeaders) {
return this.request('OPTIONS', requestUrl, null, additionalHeaders || {});
}
get(requestUrl, additionalHeaders) {
return this.request('GET', requestUrl, null, additionalHeaders || {});
}
del(requestUrl, additionalHeaders) {
return this.request('DELETE', requestUrl, null, additionalHeaders || {});
}
post(requestUrl, data, additionalHeaders) {
return this.request('POST', requestUrl, data, additionalHeaders || {});
}
patch(requestUrl, data, additionalHeaders) {
return this.request('PATCH', requestUrl, data, additionalHeaders || {});
}
put(requestUrl, data, additionalHeaders) {
return this.request('PUT', requestUrl, data, additionalHeaders || {});
}
head(requestUrl, additionalHeaders) {
return this.request('HEAD', requestUrl, null, additionalHeaders || {});
}
sendStream(verb, requestUrl, stream, additionalHeaders) {
return this.request(verb, requestUrl, stream, additionalHeaders);
}
/**
* Gets a typed object from an endpoint
* Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise
*/
async getJson(requestUrl, additionalHeaders = {}) {
additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
let res = await this.get(requestUrl, additionalHeaders);
return this._processResponse(res, this.requestOptions);
}
async postJson(requestUrl, obj, additionalHeaders = {}) {
let data = JSON.stringify(obj, null, 2);
additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);
let res = await this.post(requestUrl, data, additionalHeaders);
return this._processResponse(res, this.requestOptions);
}
async putJson(requestUrl, obj, additionalHeaders = {}) {
let data = JSON.stringify(obj, null, 2);
additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);
let res = await this.put(requestUrl, data, additionalHeaders);
return this._processResponse(res, this.requestOptions);
}
async patchJson(requestUrl, obj, additionalHeaders = {}) {
let data = JSON.stringify(obj, null, 2);
additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);
let res = await this.patch(requestUrl, data, additionalHeaders);
return this._processResponse(res, this.requestOptions);
}
/**
* Makes a raw http request.
* All other methods such as get, post, patch, and request ultimately call this.
* Prefer get, del, post and patch
*/
async request(verb, requestUrl, data, headers) {
if (this._disposed) {
throw new Error('Client has already been disposed.');
}
let parsedUrl = url.parse(requestUrl);
let info = this._prepareRequest(verb, parsedUrl, headers);
// Only perform retries on reads since writes may not be idempotent.
let maxTries = this._allowRetries && RetryableHttpVerbs.indexOf(verb) != -1
? this._maxRetries + 1
: 1;
let numTries = 0;
let response;
while (numTries < maxTries) {
response = await this.requestRaw(info, data);
// Check if it's an authentication challenge
if (response &&
response.message &&
response.message.statusCode === HttpCodes.Unauthorized) {
let authenticationHandler;
for (let i = 0; i < this.handlers.length; i++) {
if (this.handlers[i].canHandleAuthentication(response)) {
authenticationHandler = this.handlers[i];
break;
}
}
if (authenticationHandler) {
return authenticationHandler.handleAuthentication(this, info, data);
}
else {
// We have received an unauthorized response but have no handlers to handle it.
// Let the response return to the caller.
return response;
}
}
let redirectsRemaining = this._maxRedirects;
while (HttpRedirectCodes.indexOf(response.message.statusCode) != -1 &&
this._allowRedirects &&
redirectsRemaining > 0) {
const redirectUrl = response.message.headers['location'];
if (!redirectUrl) {
// if there's no location to redirect to, we won't
break;
}
let parsedRedirectUrl = url.parse(redirectUrl);
if (parsedUrl.protocol == 'https:' &&
parsedUrl.protocol != parsedRedirectUrl.protocol &&
!this._allowRedirectDowngrade) {
throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.');
}
// we need to finish reading the response before reassigning response
// which will leak the open socket.
await response.readBody();
// strip authorization header if redirected to a different hostname
if (parsedRedirectUrl.hostname !== parsedUrl.hostname) {
for (let header in headers) {
// header names are case insensitive
if (header.toLowerCase() === 'authorization') {
delete headers[header];
}
}
}
// let's make the request with the new redirectUrl
info = this._prepareRequest(verb, parsedRedirectUrl, headers);
response = await this.requestRaw(info, data);
redirectsRemaining--;
}
if (HttpResponseRetryCodes.indexOf(response.message.statusCode) == -1) {
// If not a retry code, return immediately instead of retrying
return response;
}
numTries += 1;
if (numTries < maxTries) {
await response.readBody();
await this._performExponentialBackoff(numTries);
}
}
return response;
}
/**
* Needs to be called if keepAlive is set to true in request options.
*/
dispose() {
if (this._agent) {
this._agent.destroy();
}
this._disposed = true;
}
/**
* Raw request.
* @param info
* @param data
*/
requestRaw(info, data) {
return new Promise((resolve, reject) => {
let callbackForResult = function (err, res) {
if (err) {
reject(err);
}
resolve(res);
};
this.requestRawWithCallback(info, data, callbackForResult);
});
}
/**
* Raw request with callback.
* @param info
* @param data
* @param onResult
*/
requestRawWithCallback(info, data, onResult) {
let socket;
if (typeof data === 'string') {
info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8');
}
let callbackCalled = false;
let handleResult = (err, res) => {
if (!callbackCalled) {
callbackCalled = true;
onResult(err, res);
}
};
let req = info.httpModule.request(info.options, (msg) => {
let res = new HttpClientResponse(msg);
handleResult(null, res);
});
req.on('socket', sock => {
socket = sock;
});
// If we ever get disconnected, we want the socket to timeout eventually
req.setTimeout(this._socketTimeout || 3 * 60000, () => {
if (socket) {
socket.end();
}
handleResult(new Error('Request timeout: ' + info.options.path), null);
});
req.on('error', function (err) {
// err has statusCode property
// res should have headers
handleResult(err, null);
});
if (data && typeof data === 'string') {
req.write(data, 'utf8');
}
if (data && typeof data !== 'string') {
data.on('close', function () {
req.end();
});
data.pipe(req);
}
else {
req.end();
}
}
/**
* Gets an http agent. This function is useful when you need an http agent that handles
* routing through a proxy server - depending upon the url and proxy environment variables.
* @param serverUrl The server URL where the request will be sent. For example, https://api.github.com
*/
getAgent(serverUrl) {
let parsedUrl = url.parse(serverUrl);
return this._getAgent(parsedUrl);
}
_prepareRequest(method, requestUrl, headers) {
const info = {};
info.parsedUrl = requestUrl;
const usingSsl = info.parsedUrl.protocol === 'https:';
info.httpModule = usingSsl ? https : http;
const defaultPort = usingSsl ? 443 : 80;
info.options = {};
info.options.host = info.parsedUrl.hostname;
info.options.port = info.parsedUrl.port
? parseInt(info.parsedUrl.port)
: defaultPort;
info.options.path =
(info.parsedUrl.pathname || '') + (info.parsedUrl.search || '');
info.options.method = method;
info.options.headers = this._mergeHeaders(headers);
if (this.userAgent != null) {
info.options.headers['user-agent'] = this.userAgent;
}
info.options.agent = this._getAgent(info.parsedUrl);
// gives handlers an opportunity to participate
if (this.handlers) {
this.handlers.forEach(handler => {
handler.prepareRequest(info.options);
});
}
return info;
}
_mergeHeaders(headers) {
const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {});
if (this.requestOptions && this.requestOptions.headers) {
return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers));
}
return lowercaseKeys(headers || {});
}
_getExistingOrDefaultHeader(additionalHeaders, header, _default) {
const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {});
let clientHeader;
if (this.requestOptions && this.requestOptions.headers) {
clientHeader = lowercaseKeys(this.requestOptions.headers)[header];
}
return additionalHeaders[header] || clientHeader || _default;
}
_getAgent(parsedUrl) {
let agent;
let proxyUrl = pm.getProxyUrl(parsedUrl);
let useProxy = proxyUrl && proxyUrl.hostname;
if (this._keepAlive && useProxy) {
agent = this._proxyAgent;
}
if (this._keepAlive && !useProxy) {
agent = this._agent;
}
// if agent is already assigned use that agent.
if (!!agent) {
return agent;
}
const usingSsl = parsedUrl.protocol === 'https:';
let maxSockets = 100;
if (!!this.requestOptions) {
maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets;
}
if (useProxy) {
// If using proxy, need tunnel
if (!tunnel) {
tunnel = __webpack_require__(413);
}
const agentOptions = {
maxSockets: maxSockets,
keepAlive: this._keepAlive,
proxy: {
proxyAuth: proxyUrl.auth,
host: proxyUrl.hostname,
port: proxyUrl.port
}
};
let tunnelAgent;
const overHttps = proxyUrl.protocol === 'https:';
if (usingSsl) {
tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp;
}
else {
tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp;
}
agent = tunnelAgent(agentOptions);
this._proxyAgent = agent;
}
// if reusing agent across request and tunneling agent isn't assigned create a new agent
if (this._keepAlive && !agent) {
const options = { keepAlive: this._keepAlive, maxSockets: maxSockets };
agent = usingSsl ? new https.Agent(options) : new http.Agent(options);
this._agent = agent;
}
// if not using private agent and tunnel agent isn't setup then use global agent
if (!agent) {
agent = usingSsl ? https.globalAgent : http.globalAgent;
}
if (usingSsl && this._ignoreSslError) {
// we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process
// http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options
// we have to cast it to any and change it directly
agent.options = Object.assign(agent.options || {}, {
rejectUnauthorized: false
});
}
return agent;
}
_performExponentialBackoff(retryNumber) {
retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber);
const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber);
return new Promise(resolve => setTimeout(() => resolve(), ms));
}
static dateTimeDeserializer(key, value) {
if (typeof value === 'string') {
let a = new Date(value);
if (!isNaN(a.valueOf())) {
return a;
}
}
return value;
}
async _processResponse(res, options) {
return new Promise(async (resolve, reject) => {
const statusCode = res.message.statusCode;
const response = {
statusCode: statusCode,
result: null,
headers: {}
};
// not found leads to null obj returned
if (statusCode == HttpCodes.NotFound) {
resolve(response);
}
let obj;
let contents;
// get the result from the body
try {
contents = await res.readBody();
if (contents && contents.length > 0) {
if (options && options.deserializeDates) {
obj = JSON.parse(contents, HttpClient.dateTimeDeserializer);
}
else {
obj = JSON.parse(contents);
}
response.result = obj;
}
response.headers = res.message.headers;
}
catch (err) {
// Invalid resource (contents not json); leaving result obj null
}
// note that 3xx redirects are handled by the http layer.
if (statusCode > 299) {
let msg;
// if exception/error in body, attempt to get better error
if (obj && obj.message) {
msg = obj.message;
}
else if (contents && contents.length > 0) {
// it may be the case that the exception is in the body message as string
msg = contents;
}
else {
msg = 'Failed request: (' + statusCode + ')';
}
let err = new Error(msg);
// attach statusCode and body obj (if available) to the error object
err['statusCode'] = statusCode;
if (response.result) {
err['result'] = response.result;
}
reject(err);
}
else {
resolve(response);
}
});
}
}
exports.HttpClient = HttpClient;
/***/ }),
/***/ 548:
/***/ (function(module) {
"use strict";
/*!
* is-plain-object <https://github.com/jonschlinkert/is-plain-object>
*
* Copyright (c) 2014-2017, Jon Schlinkert.
* Released under the MIT License.
*/
function isObject(o) {
return Object.prototype.toString.call(o) === '[object Object]';
}
function isPlainObject(o) {
var ctor,prot;
if (isObject(o) === false) return false;
// If has modified constructor
ctor = o.constructor;
if (ctor === undefined) return true;
// If has modified prototype
prot = ctor.prototype;
if (isObject(prot) === false) return false;
// If constructor does not have an Object-specific method
if (prot.hasOwnProperty('isPrototypeOf') === false) {
return false;
}
// Most likely a plain Object
return true;
}
module.exports = isPlainObject;
/***/ }),
/***/ 555:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var lower_case_1 = __webpack_require__(175);
// Support camel case ("camelCase" -> "camel Case" and "CAMELCase" -> "CAMEL Case").
var DEFAULT_SPLIT_REGEXP = [/([a-z0-9])([A-Z])/g, /([A-Z])([A-Z][a-z])/g];
// Remove all non-word characters.
var DEFAULT_STRIP_REGEXP = /[^A-Z0-9]+/gi;
/**
* Normalize the string into something other libraries can manipulate easier.
*/
function noCase(input, options) {
if (options === void 0) { options = {}; }
var _a = options.splitRegexp, splitRegexp = _a === void 0 ? DEFAULT_SPLIT_REGEXP : _a, _b = options.stripRegexp, stripRegexp = _b === void 0 ? DEFAULT_STRIP_REGEXP : _b, _c = options.transform, transform = _c === void 0 ? lower_case_1.lowerCase : _c, _d = options.delimiter, delimiter = _d === void 0 ? " " : _d;
var result = replace(replace(input, splitRegexp, "$1\0$2"), stripRegexp, "\0");
var start = 0;
var end = result.length;
// Trim the delimiter from around the output string.
while (result.charAt(start) === "\0")
start++;
while (result.charAt(end - 1) === "\0")
end--;
// Transform each token independently.
return result
.slice(start, end)
.split("\0")
.map(transform)
.join(delimiter);
}
exports.noCase = noCase;
/**
* Replace `re` in the input string with the replacement value.
*/
function replace(input, re, value) {
if (re instanceof RegExp)
return input.replace(re, value);
return re.reduce(function (input, re) { return input.replace(re, value); }, input);
}
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 605:
/***/ (function(module) {
module.exports = require("http");
/***/ }),
/***/ 614:
/***/ (function(module) {
module.exports = require("events");
/***/ }),
/***/ 617:
/***/ (function(module, __unusedexports, __webpack_require__) {
"use strict";
var Buffer = __webpack_require__(643).Buffer;
// Export Node.js internal encodings.
module.exports = {
// Encodings
utf8: { type: "_internal", bomAware: true},
cesu8: { type: "_internal", bomAware: true},
unicode11utf8: "utf8",
ucs2: { type: "_internal", bomAware: true},
utf16le: "ucs2",
binary: { type: "_internal" },
base64: { type: "_internal" },
hex: { type: "_internal" },
// Codec.
_internal: InternalCodec,
};
//------------------------------------------------------------------------------
function InternalCodec(codecOptions, iconv) {
this.enc = codecOptions.encodingName;
this.bomAware = codecOptions.bomAware;
if (this.enc === "base64")
this.encoder = InternalEncoderBase64;
else if (this.enc === "cesu8") {
this.enc = "utf8"; // Use utf8 for decoding.
this.encoder = InternalEncoderCesu8;
// Add decoder for versions of Node not supporting CESU-8
if (Buffer.from('eda0bdedb2a9', 'hex').toString() !== '💩') {
this.decoder = InternalDecoderCesu8;
this.defaultCharUnicode = iconv.defaultCharUnicode;
}
}
}
InternalCodec.prototype.encoder = InternalEncoder;
InternalCodec.prototype.decoder = InternalDecoder;
//------------------------------------------------------------------------------
// We use node.js internal decoder. Its signature is the same as ours.
var StringDecoder = __webpack_require__(304).StringDecoder;
if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method.
StringDecoder.prototype.end = function() {};
function InternalDecoder(options, codec) {
this.decoder = new StringDecoder(codec.enc);
}
InternalDecoder.prototype.write = function(buf) {
if (!Buffer.isBuffer(buf)) {
buf = Buffer.from(buf);
}
return this.decoder.write(buf);
}
InternalDecoder.prototype.end = function() {
return this.decoder.end();
}
//------------------------------------------------------------------------------
// Encoder is mostly trivial
function InternalEncoder(options, codec) {
this.enc = codec.enc;
}
InternalEncoder.prototype.write = function(str) {
return Buffer.from(str, this.enc);
}
InternalEncoder.prototype.end = function() {
}
//------------------------------------------------------------------------------
// Except base64 encoder, which must keep its state.
function InternalEncoderBase64(options, codec) {
this.prevStr = '';
}
InternalEncoderBase64.prototype.write = function(str) {
str = this.prevStr + str;
var completeQuads = str.length - (str.length % 4);
this.prevStr = str.slice(completeQuads);
str = str.slice(0, completeQuads);
return Buffer.from(str, "base64");
}
InternalEncoderBase64.prototype.end = function() {
return Buffer.from(this.prevStr, "base64");
}
//------------------------------------------------------------------------------
// CESU-8 encoder is also special.
function InternalEncoderCesu8(options, codec) {
}
InternalEncoderCesu8.prototype.write = function(str) {
var buf = Buffer.alloc(str.length * 3), bufIdx = 0;
for (var i = 0; i < str.length; i++) {
var charCode = str.charCodeAt(i);
// Naive implementation, but it works because CESU-8 is especially easy
// to convert from UTF-16 (which all JS strings are encoded in).
if (charCode < 0x80)
buf[bufIdx++] = charCode;
else if (charCode < 0x800) {
buf[bufIdx++] = 0xC0 + (charCode >>> 6);
buf[bufIdx++] = 0x80 + (charCode & 0x3f);
}
else { // charCode will always be < 0x10000 in javascript.
buf[bufIdx++] = 0xE0 + (charCode >>> 12);
buf[bufIdx++] = 0x80 + ((charCode >>> 6) & 0x3f);
buf[bufIdx++] = 0x80 + (charCode & 0x3f);
}
}
return buf.slice(0, bufIdx);
}
InternalEncoderCesu8.prototype.end = function() {
}
//------------------------------------------------------------------------------
// CESU-8 decoder is not implemented in Node v4.0+
function InternalDecoderCesu8(options, codec) {
this.acc = 0;
this.contBytes = 0;
this.accBytes = 0;
this.defaultCharUnicode = codec.defaultCharUnicode;
}
InternalDecoderCesu8.prototype.write = function(buf) {
var acc = this.acc, contBytes = this.contBytes, accBytes = this.accBytes,
res = '';
for (var i = 0; i < buf.length; i++) {
var curByte = buf[i];
if ((curByte & 0xC0) !== 0x80) { // Leading byte
if (contBytes > 0) { // Previous code is invalid
res += this.defaultCharUnicode;
contBytes = 0;
}
if (curByte < 0x80) { // Single-byte code
res += String.fromCharCode(curByte);
} else if (curByte < 0xE0) { // Two-byte code
acc = curByte & 0x1F;
contBytes = 1; accBytes = 1;
} else if (curByte < 0xF0) { // Three-byte code
acc = curByte & 0x0F;
contBytes = 2; accBytes = 1;
} else { // Four or more are not supported for CESU-8.
res += this.defaultCharUnicode;
}
} else { // Continuation byte
if (contBytes > 0) { // We're waiting for it.
acc = (acc << 6) | (curByte & 0x3f);
contBytes--; accBytes++;
if (contBytes === 0) {
// Check for overlong encoding, but support Modified UTF-8 (encoding NULL as C0 80)
if (accBytes === 2 && acc < 0x80 && acc > 0)
res += this.defaultCharUnicode;
else if (accBytes === 3 && acc < 0x800)
res += this.defaultCharUnicode;
else
// Actually add character.
res += String.fromCharCode(acc);
}
} else { // Unexpected continuation byte
res += this.defaultCharUnicode;
}
}
}
this.acc = acc; this.contBytes = contBytes; this.accBytes = accBytes;
return res;
}
InternalDecoderCesu8.prototype.end = function() {
var res = 0;
if (this.contBytes > 0)
res += this.defaultCharUnicode;
return res;
}
/***/ }),
/***/ 622:
/***/ (function(module) {
module.exports = require("path");
/***/ }),
/***/ 626:
/***/ (function(module) {
"use strict";
/*!
* is-plain-object <https://github.com/jonschlinkert/is-plain-object>
*
* Copyright (c) 2014-2017, Jon Schlinkert.
* Released under the MIT License.
*/
function isObject(o) {
return Object.prototype.toString.call(o) === '[object Object]';
}
function isPlainObject(o) {
var ctor,prot;
if (isObject(o) === false) return false;
// If has modified constructor
ctor = o.constructor;
if (ctor === undefined) return true;
// If has modified prototype
prot = ctor.prototype;
if (isObject(prot) === false) return false;
// If constructor does not have an Object-specific method
if (prot.hasOwnProperty('isPrototypeOf') === false) {
return false;
}
// Most likely a plain Object
return true;
}
module.exports = isPlainObject;
/***/ }),
/***/ 631:
/***/ (function(module) {
module.exports = require("net");
/***/ }),
/***/ 643:
/***/ (function(module, __unusedexports, __webpack_require__) {
"use strict";
/* eslint-disable node/no-deprecated-api */
var buffer = __webpack_require__(293)
var Buffer = buffer.Buffer
var safer = {}
var key
for (key in buffer) {
if (!buffer.hasOwnProperty(key)) continue
if (key === 'SlowBuffer' || key === 'Buffer') continue
safer[key] = buffer[key]
}
var Safer = safer.Buffer = {}
for (key in Buffer) {
if (!Buffer.hasOwnProperty(key)) continue
if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue
Safer[key] = Buffer[key]
}
safer.Buffer.prototype = Buffer.prototype
if (!Safer.from || Safer.from === Uint8Array.from) {
Safer.from = function (value, encodingOrOffset, length) {
if (typeof value === 'number') {
throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value)
}
if (value && typeof value.length === 'undefined') {
throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value)
}
return Buffer(value, encodingOrOffset, length)
}
}
if (!Safer.alloc) {
Safer.alloc = function (size, fill, encoding) {
if (typeof size !== 'number') {
throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size)
}
if (size < 0 || size >= 2 * (1 << 30)) {
throw new RangeError('The value "' + size + '" is invalid for option "size"')
}
var buf = Buffer(size)
if (!fill || fill.length === 0) {
buf.fill(0)
} else if (typeof encoding === 'string') {
buf.fill(fill, encoding)
} else {
buf.fill(fill)
}
return buf
}
}
if (!safer.kStringMaxLength) {
try {
safer.kStringMaxLength = process.binding('buffer').kStringMaxLength
} catch (e) {
// we can't determine kStringMaxLength in environments where process.binding
// is unsupported, so let's not set it
}
}
if (!safer.constants) {
safer.constants = {
MAX_LENGTH: safer.kMaxLength
}
if (safer.kStringMaxLength) {
safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength
}
}
module.exports = safer
/***/ }),
/***/ 658:
/***/ (function(module, __unusedexports, __webpack_require__) {
"use strict";
// Description of supported double byte encodings and aliases.
// Tables are not require()-d until they are needed to speed up library load.
// require()-s are direct to support Browserify.
module.exports = {
// == Japanese/ShiftJIS ====================================================
// All japanese encodings are based on JIS X set of standards:
// JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF.
// JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes.
// Has several variations in 1978, 1983, 1990 and 1997.
// JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead.
// JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233.
// 2 planes, first is superset of 0208, second - revised 0212.
// Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx)
// Byte encodings are:
// * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte
// encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC.
// Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI.
// * EUC-JP: Up to 3 bytes per character. Used mostly on *nixes.
// 0x00-0x7F - lower part of 0201
// 0x8E, 0xA1-0xDF - upper part of 0201
// (0xA1-0xFE)x2 - 0208 plane (94x94).
// 0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94).
// * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon.
// Used as-is in ISO2022 family.
// * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII,
// 0201-1976 Roman, 0208-1978, 0208-1983.
// * ISO2022-JP-1: Adds esc seq for 0212-1990.
// * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7.
// * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2.
// * ISO2022-JP-2004: Adds 0213-2004 Plane 1.
//
// After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes.
//
// Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html
'shiftjis': {
type: '_dbcs',
table: function() { return __webpack_require__(105) },
encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E},
encodeSkipVals: [{from: 0xED40, to: 0xF940}],
},
'csshiftjis': 'shiftjis',
'mskanji': 'shiftjis',
'sjis': 'shiftjis',
'windows31j': 'shiftjis',
'ms31j': 'shiftjis',
'xsjis': 'shiftjis',
'windows932': 'shiftjis',
'ms932': 'shiftjis',
'932': 'shiftjis',
'cp932': 'shiftjis',
'eucjp': {
type: '_dbcs',
table: function() { return __webpack_require__(685) },
encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E},
},
// TODO: KDDI extension to Shift_JIS
// TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes.
// TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars.
// == Chinese/GBK ==========================================================
// http://en.wikipedia.org/wiki/GBK
// We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder
// Oldest GB2312 (1981, ~7600 chars) is a subset of CP936
'gb2312': 'cp936',
'gb231280': 'cp936',
'gb23121980': 'cp936',
'csgb2312': 'cp936',
'csiso58gb231280': 'cp936',
'euccn': 'cp936',
// Microsoft's CP936 is a subset and approximation of GBK.
'windows936': 'cp936',
'ms936': 'cp936',
'936': 'cp936',
'cp936': {
type: '_dbcs',
table: function() { return __webpack_require__(426) },
},
// GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other.
'gbk': {
type: '_dbcs',
table: function() { return __webpack_require__(426).concat(__webpack_require__(301)) },
},
'xgbk': 'gbk',
'isoir58': 'gbk',
// GB18030 is an algorithmic extension of GBK.
// Main source: https://www.w3.org/TR/encoding/#gbk-encoder
// http://icu-project.org/docs/papers/gb18030.html
// http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml
// http://www.khngai.com/chinese/charmap/tblgbk.php?page=0
'gb18030': {
type: '_dbcs',
table: function() { return __webpack_require__(426).concat(__webpack_require__(301)) },
gb18030: function() { return __webpack_require__(686) },
encodeSkipVals: [0x80],
encodeAdd: {'€': 0xA2E3},
},
'chinese': 'gb18030',
// == Korean ===============================================================
// EUC-KR, KS_C_5601 and KS X 1001 are exactly the same.
'windows949': 'cp949',
'ms949': 'cp949',
'949': 'cp949',
'cp949': {
type: '_dbcs',
table: function() { return __webpack_require__(927) },
},
'cseuckr': 'cp949',
'csksc56011987': 'cp949',
'euckr': 'cp949',
'isoir149': 'cp949',
'korean': 'cp949',
'ksc56011987': 'cp949',
'ksc56011989': 'cp949',
'ksc5601': 'cp949',
// == Big5/Taiwan/Hong Kong ================================================
// There are lots of tables for Big5 and cp950. Please see the following links for history:
// http://moztw.org/docs/big5/ http://www.haible.de/bruno/charsets/conversion-tables/Big5.html
// Variations, in roughly number of defined chars:
// * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT
// * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/
// * Big5-2003 (Taiwan standard) almost superset of cp950.
// * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers.
// * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard.
// many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years.
// Plus, it has 4 combining sequences.
// Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299
// because big5-hkscs is the only encoding to include astral characters in non-algorithmic way.
// Implementations are not consistent within browsers; sometimes labeled as just big5.
// MS Internet Explorer switches from big5 to big5-hkscs when a patch applied.
// Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31
// In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s.
// Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt
// http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt
//
// Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder
// Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong.
'windows950': 'cp950',
'ms950': 'cp950',
'950': 'cp950',
'cp950': {
type: '_dbcs',
table: function() { return __webpack_require__(932) },
},
// Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus.
'big5': 'big5hkscs',
'big5hkscs': {
type: '_dbcs',
table: function() { return __webpack_require__(932).concat(__webpack_require__(420)) },
encodeSkipVals: [0xa2cc],
},
'cnbig5': 'big5hkscs',
'csbig5': 'big5hkscs',
'xxbig5': 'big5hkscs',
};
/***/ }),
/***/ 669:
/***/ (function(module) {
module.exports = require("util");
/***/ }),
/***/ 681:
/***/ (function(module, __unusedexports, __webpack_require__) {
"use strict";
var Buffer = __webpack_require__(643).Buffer;
var bomHandling = __webpack_require__(807),
iconv = module.exports;
// All codecs and aliases are kept here, keyed by encoding name/alias.
// They are lazy loaded in `iconv.getCodec` from `encodings/index.js`.
iconv.encodings = null;
// Characters emitted in case of error.
iconv.defaultCharUnicode = '�';
iconv.defaultCharSingleByte = '?';
// Public API.
iconv.encode = function encode(str, encoding, options) {
str = "" + (str || ""); // Ensure string.
var encoder = iconv.getEncoder(encoding, options);
var res = encoder.write(str);
var trail = encoder.end();
return (trail && trail.length > 0) ? Buffer.concat([res, trail]) : res;
}
iconv.decode = function decode(buf, encoding, options) {
if (typeof buf === 'string') {
if (!iconv.skipDecodeWarning) {
console.error('Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding');
iconv.skipDecodeWarning = true;
}
buf = Buffer.from("" + (buf || ""), "binary"); // Ensure buffer.
}
var decoder = iconv.getDecoder(encoding, options);
var res = decoder.write(buf);
var trail = decoder.end();
return trail ? (res + trail) : res;
}
iconv.encodingExists = function encodingExists(enc) {
try {
iconv.getCodec(enc);
return true;
} catch (e) {
return false;
}
}
// Legacy aliases to convert functions
iconv.toEncoding = iconv.encode;
iconv.fromEncoding = iconv.decode;
// Search for a codec in iconv.encodings. Cache codec data in iconv._codecDataCache.
iconv._codecDataCache = {};
iconv.getCodec = function getCodec(encoding) {
if (!iconv.encodings)
iconv.encodings = __webpack_require__(696); // Lazy load all encoding definitions.
// Canonicalize encoding name: strip all non-alphanumeric chars and appended year.
var enc = iconv._canonicalizeEncoding(encoding);
// Traverse iconv.encodings to find actual codec.
var codecOptions = {};
while (true) {
var codec = iconv._codecDataCache[enc];
if (codec)
return codec;
var codecDef = iconv.encodings[enc];
switch (typeof codecDef) {
case "string": // Direct alias to other encoding.
enc = codecDef;
break;
case "object": // Alias with options. Can be layered.
for (var key in codecDef)
codecOptions[key] = codecDef[key];
if (!codecOptions.encodingName)
codecOptions.encodingName = enc;
enc = codecDef.type;
break;
case "function": // Codec itself.
if (!codecOptions.encodingName)
codecOptions.encodingName = enc;
// The codec function must load all tables and return object with .encoder and .decoder methods.
// It'll be called only once (for each different options object).
codec = new codecDef(codecOptions, iconv);
iconv._codecDataCache[codecOptions.encodingName] = codec; // Save it to be reused later.
return codec;
default:
throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')");
}
}
}
iconv._canonicalizeEncoding = function(encoding) {
// Canonicalize encoding name: strip all non-alphanumeric chars and appended year.
return (''+encoding).toLowerCase().replace(/:\d{4}$|[^0-9a-z]/g, "");
}
iconv.getEncoder = function getEncoder(encoding, options) {
var codec = iconv.getCodec(encoding),
encoder = new codec.encoder(options, codec);
if (codec.bomAware && options && options.addBOM)
encoder = new bomHandling.PrependBOM(encoder, options);
return encoder;
}
iconv.getDecoder = function getDecoder(encoding, options) {
var codec = iconv.getCodec(encoding),
decoder = new codec.decoder(options, codec);
if (codec.bomAware && !(options && options.stripBOM === false))
decoder = new bomHandling.StripBOM(decoder, options);
return decoder;
}
// Streaming API
// NOTE: Streaming API naturally depends on 'stream' module from Node.js. Unfortunately in browser environments this module can add
// up to 100Kb to the output bundle. To avoid unnecessary code bloat, we don't enable Streaming API in browser by default.
// If you would like to enable it explicitly, please add the following code to your app:
// > iconv.enableStreamingAPI(require('stream'));
iconv.enableStreamingAPI = function enableStreamingAPI(stream_module) {
if (iconv.supportsStreams)
return;
// Dependency-inject stream module to create IconvLite stream classes.
var streams = __webpack_require__(986)(stream_module);
// Not public API yet, but expose the stream classes.
iconv.IconvLiteEncoderStream = streams.IconvLiteEncoderStream;
iconv.IconvLiteDecoderStream = streams.IconvLiteDecoderStream;
// Streaming API.
iconv.encodeStream = function encodeStream(encoding, options) {
return new iconv.IconvLiteEncoderStream(iconv.getEncoder(encoding, options), options);
}
iconv.decodeStream = function decodeStream(encoding, options) {
return new iconv.IconvLiteDecoderStream(iconv.getDecoder(encoding, options), options);
}
iconv.supportsStreams = true;
}
// Enable Streaming API automatically if 'stream' module is available and non-empty (the majority of environments).
var stream_module;
try {
stream_module = __webpack_require__(794);
} catch (e) {}
if (stream_module && stream_module.Transform) {
iconv.enableStreamingAPI(stream_module);
} else {
// In rare cases where 'stream' module is not available by default, throw a helpful exception.
iconv.encodeStream = iconv.decodeStream = function() {
throw new Error("iconv-lite Streaming API is not enabled. Use iconv.enableStreamingAPI(require('stream')); to enable it.");
};
}
if (false) {}
/***/ }),
/***/ 685:
/***/ (function(module) {
module.exports = [["0","\u0000",127],["8ea1","。",62],["a1a1"," 、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈",9,"+-±×÷=≠<>≦≧∞∴♂♀°′″℃¥$¢£%#&*@§☆★○●◎◇"],["a2a1","◆□■△▲▽▼※〒→←↑↓〓"],["a2ba","∈∋⊆⊇⊂⊃∪∩"],["a2ca","∧∨¬⇒⇔∀∃"],["a2dc","∠⊥⌒∂∇≡≒≪≫√∽∝∵∫∬"],["a2f2","ʼn♯♭♪†‡¶"],["a2fe","◯"],["a3b0","0",9],["a3c1","A",25],["a3e1","a",25],["a4a1","ぁ",82],["a5a1","ァ",85],["a6a1","Α",16,"Σ",6],["a6c1","α",16,"σ",6],["a7a1","А",5,"ЁЖ",25],["a7d1","а",5,"ёж",25],["a8a1","─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂"],["ada1","①",19,"Ⅰ",9],["adc0","㍉㌔㌢㍍㌘㌧㌃㌶㍑㍗㌍㌦㌣㌫㍊㌻㎜㎝㎞㎎㎏㏄㎡"],["addf","㍻〝〟№㏍℡㊤",4,"㈱㈲㈹㍾㍽㍼≒≡∫∮∑√⊥∠∟⊿∵∩∪"],["b0a1","亜唖娃阿哀愛挨姶逢葵茜穐悪握渥旭葦芦鯵梓圧斡扱宛姐虻飴絢綾鮎或粟袷安庵按暗案闇鞍杏以伊位依偉囲夷委威尉惟意慰易椅為畏異移維緯胃萎衣謂違遺医井亥域育郁磯一壱溢逸稲茨芋鰯允印咽員因姻引飲淫胤蔭"],["b1a1","院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応"],["b2a1","押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改"],["b3a1","魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱"],["b4a1","粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄"],["b5a1","機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京"],["b6a1","供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈"],["b7a1","掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲"],["b8a1","検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向"],["b9a1","后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込"],["baa1","此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷"],["bba1","察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時"],["bca1","次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周"],["bda1","宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償"],["bea1","勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾"],["bfa1","拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾"],["c0a1","澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線"],["c1a1","繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎"],["c2a1","臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只"],["c3a1","叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵"],["c4a1","帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓"],["c5a1","邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到"],["c6a1","董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入"],["c7a1","如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦"],["c8a1","函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美"],["c9a1","鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服"],["caa1","福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋"],["cba1","法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満"],["cca1","漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒"],["cda1","諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃"],["cea1","痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯"],["cfa1","蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕"],["d0a1","弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲"],["d1a1","僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨"],["d2a1","辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨"],["d3a1","咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉"],["d4a1","圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩"],["d5a1","奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓"],["d6a1","屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏"],["d7a1","廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚"],["d8a1","悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛"],["d9a1","戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼"],["daa1","據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼"],["dba1","曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍"],["dca1","棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣"],["dda1","檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾"],["dea1","沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌"],["dfa1","漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼"],["e0a1","燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱"],["e1a1","瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰"],["e2a1","癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬"],["e3a1","磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐"],["e4a1","筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆"],["e5a1","紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺"],["e6a1","罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋"],["e7a1","隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙"],["e8a1","茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈"],["e9a1","蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙"],["eaa1","蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞"],["eba1","襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫"],["eca1","譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊"],["eda1","蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸"],["eea1","遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮"],["efa1","錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞"],["f0a1","陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰"],["f1a1","顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷"],["f2a1","髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈"],["f3a1","鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠"],["f4a1","堯槇遙瑤凜熙"],["f9a1","纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德"],["faa1","忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱"],["fba1","犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚"],["fca1","釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"],["fcf1","ⅰ",9,"¬¦'""],["8fa2af","˘ˇ¸˙˝¯˛˚~΄΅"],["8fa2c2","¡¦¿"],["8fa2eb","ºª©®™¤№"],["8fa6e1","ΆΈΉΊΪ"],["8fa6e7","Ό"],["8fa6e9","ΎΫ"],["8fa6ec","Ώ"],["8fa6f1","άέήίϊΐόςύϋΰώ"],["8fa7c2","Ђ",10,"ЎЏ"],["8fa7f2","ђ",10,"ўџ"],["8fa9a1","ÆĐ"],["8fa9a4","Ħ"],["8fa9a6","IJ"],["8fa9a8","ŁĿ"],["8fa9ab","ŊØŒ"],["8fa9af","ŦÞ"],["8fa9c1","æđðħıijĸłŀʼnŋøœßŧþ"],["8faaa1","ÁÀÄÂĂǍĀĄÅÃĆĈČÇĊĎÉÈËÊĚĖĒĘ"],["8faaba","ĜĞĢĠĤÍÌÏÎǏİĪĮĨĴĶĹĽĻŃŇŅÑÓÒÖÔǑŐŌÕŔŘŖŚŜŠŞŤŢÚÙÜÛŬǓŰŪŲŮŨǗǛǙǕŴÝŸŶŹŽŻ"],["8faba1","áàäâăǎāąåãćĉčçċďéèëêěėēęǵĝğ"],["8fabbd","ġĥíìïîǐ"],["8fabc5","īįĩĵķĺľļńňņñóòöôǒőōõŕřŗśŝšşťţúùüûŭǔűūųůũǘǜǚǖŵýÿŷźžż"],["8fb0a1","丂丄丅丌丒丟丣两丨丫丮丯丰丵乀乁乄乇乑乚乜乣乨乩乴乵乹乿亍亖亗亝亯亹仃仐仚仛仠仡仢仨仯仱仳仵份仾仿伀伂伃伈伋伌伒伕伖众伙伮伱你伳伵伷伹伻伾佀佂佈佉佋佌佒佔佖佘佟佣佪佬佮佱佷佸佹佺佽佾侁侂侄"],["8fb1a1","侅侉侊侌侎侐侒侓侔侗侙侚侞侟侲侷侹侻侼侽侾俀俁俅俆俈俉俋俌俍俏俒俜俠俢俰俲俼俽俿倀倁倄倇倊倌倎倐倓倗倘倛倜倝倞倢倧倮倰倲倳倵偀偁偂偅偆偊偌偎偑偒偓偗偙偟偠偢偣偦偧偪偭偰偱倻傁傃傄傆傊傎傏傐"],["8fb2a1","傒傓傔傖傛傜傞",4,"傪傯傰傹傺傽僀僃僄僇僌僎僐僓僔僘僜僝僟僢僤僦僨僩僯僱僶僺僾儃儆儇儈儋儌儍儎僲儐儗儙儛儜儝儞儣儧儨儬儭儯儱儳儴儵儸儹兂兊兏兓兕兗兘兟兤兦兾冃冄冋冎冘冝冡冣冭冸冺冼冾冿凂"],["8fb3a1","凈减凑凒凓凕凘凞凢凥凮凲凳凴凷刁刂刅划刓刕刖刘刢刨刱刲刵刼剅剉剕剗剘剚剜剟剠剡剦剮剷剸剹劀劂劅劊劌劓劕劖劗劘劚劜劤劥劦劧劯劰劶劷劸劺劻劽勀勄勆勈勌勏勑勔勖勛勜勡勥勨勩勪勬勰勱勴勶勷匀匃匊匋"],["8fb4a1","匌匑匓匘匛匜匞匟匥匧匨匩匫匬匭匰匲匵匼匽匾卂卌卋卙卛卡卣卥卬卭卲卹卾厃厇厈厎厓厔厙厝厡厤厪厫厯厲厴厵厷厸厺厽叀叅叏叒叓叕叚叝叞叠另叧叵吂吓吚吡吧吨吪启吱吴吵呃呄呇呍呏呞呢呤呦呧呩呫呭呮呴呿"],["8fb5a1","咁咃咅咈咉咍咑咕咖咜咟咡咦咧咩咪咭咮咱咷咹咺咻咿哆哊响哎哠哪哬哯哶哼哾哿唀唁唅唈唉唌唍唎唕唪唫唲唵唶唻唼唽啁啇啉啊啍啐啑啘啚啛啞啠啡啤啦啿喁喂喆喈喎喏喑喒喓喔喗喣喤喭喲喿嗁嗃嗆嗉嗋嗌嗎嗑嗒"],["8fb6a1","嗓嗗嗘嗛嗞嗢嗩嗶嗿嘅嘈嘊嘍",5,"嘙嘬嘰嘳嘵嘷嘹嘻嘼嘽嘿噀噁噃噄噆噉噋噍噏噔噞噠噡噢噣噦噩噭噯噱噲噵嚄嚅嚈嚋嚌嚕嚙嚚嚝嚞嚟嚦嚧嚨嚩嚫嚬嚭嚱嚳嚷嚾囅囉囊囋囏囐囌囍囙囜囝囟囡囤",4,"囱囫园"],["8fb7a1","囶囷圁圂圇圊圌圑圕圚圛圝圠圢圣圤圥圩圪圬圮圯圳圴圽圾圿坅坆坌坍坒坢坥坧坨坫坭",4,"坳坴坵坷坹坺坻坼坾垁垃垌垔垗垙垚垜垝垞垟垡垕垧垨垩垬垸垽埇埈埌埏埕埝埞埤埦埧埩埭埰埵埶埸埽埾埿堃堄堈堉埡"],["8fb8a1","堌堍堛堞堟堠堦堧堭堲堹堿塉塌塍塏塐塕塟塡塤塧塨塸塼塿墀墁墇墈墉墊墌墍墏墐墔墖墝墠墡墢墦墩墱墲壄墼壂壈壍壎壐壒壔壖壚壝壡壢壩壳夅夆夋夌夒夓夔虁夝夡夣夤夨夯夰夳夵夶夿奃奆奒奓奙奛奝奞奟奡奣奫奭"],["8fb9a1","奯奲奵奶她奻奼妋妌妎妒妕妗妟妤妧妭妮妯妰妳妷妺妼姁姃姄姈姊姍姒姝姞姟姣姤姧姮姯姱姲姴姷娀娄娌娍娎娒娓娞娣娤娧娨娪娭娰婄婅婇婈婌婐婕婞婣婥婧婭婷婺婻婾媋媐媓媖媙媜媞媟媠媢媧媬媱媲媳媵媸媺媻媿"],["8fbaa1","嫄嫆嫈嫏嫚嫜嫠嫥嫪嫮嫵嫶嫽嬀嬁嬈嬗嬴嬙嬛嬝嬡嬥嬭嬸孁孋孌孒孖孞孨孮孯孼孽孾孿宁宄宆宊宎宐宑宓宔宖宨宩宬宭宯宱宲宷宺宼寀寁寍寏寖",4,"寠寯寱寴寽尌尗尞尟尣尦尩尫尬尮尰尲尵尶屙屚屜屢屣屧屨屩"],["8fbba1","屭屰屴屵屺屻屼屽岇岈岊岏岒岝岟岠岢岣岦岪岲岴岵岺峉峋峒峝峗峮峱峲峴崁崆崍崒崫崣崤崦崧崱崴崹崽崿嵂嵃嵆嵈嵕嵑嵙嵊嵟嵠嵡嵢嵤嵪嵭嵰嵹嵺嵾嵿嶁嶃嶈嶊嶒嶓嶔嶕嶙嶛嶟嶠嶧嶫嶰嶴嶸嶹巃巇巋巐巎巘巙巠巤"],["8fbca1","巩巸巹帀帇帍帒帔帕帘帟帠帮帨帲帵帾幋幐幉幑幖幘幛幜幞幨幪",4,"幰庀庋庎庢庤庥庨庪庬庱庳庽庾庿廆廌廋廎廑廒廔廕廜廞廥廫异弆弇弈弎弙弜弝弡弢弣弤弨弫弬弮弰弴弶弻弽弿彀彄彅彇彍彐彔彘彛彠彣彤彧"],["8fbda1","彯彲彴彵彸彺彽彾徉徍徏徖徜徝徢徧徫徤徬徯徰徱徸忄忇忈忉忋忐",4,"忞忡忢忨忩忪忬忭忮忯忲忳忶忺忼怇怊怍怓怔怗怘怚怟怤怭怳怵恀恇恈恉恌恑恔恖恗恝恡恧恱恾恿悂悆悈悊悎悑悓悕悘悝悞悢悤悥您悰悱悷"],["8fbea1","悻悾惂惄惈惉惊惋惎惏惔惕惙惛惝惞惢惥惲惵惸惼惽愂愇愊愌愐",4,"愖愗愙愜愞愢愪愫愰愱愵愶愷愹慁慅慆慉慞慠慬慲慸慻慼慿憀憁憃憄憋憍憒憓憗憘憜憝憟憠憥憨憪憭憸憹憼懀懁懂懎懏懕懜懝懞懟懡懢懧懩懥"],["8fbfa1","懬懭懯戁戃戄戇戓戕戜戠戢戣戧戩戫戹戽扂扃扄扆扌扐扑扒扔扖扚扜扤扭扯扳扺扽抍抎抏抐抦抨抳抶抷抺抾抿拄拎拕拖拚拪拲拴拼拽挃挄挊挋挍挐挓挖挘挩挪挭挵挶挹挼捁捂捃捄捆捊捋捎捒捓捔捘捛捥捦捬捭捱捴捵"],["8fc0a1","捸捼捽捿掂掄掇掊掐掔掕掙掚掞掤掦掭掮掯掽揁揅揈揎揑揓揔揕揜揠揥揪揬揲揳揵揸揹搉搊搐搒搔搘搞搠搢搤搥搩搪搯搰搵搽搿摋摏摑摒摓摔摚摛摜摝摟摠摡摣摭摳摴摻摽撅撇撏撐撑撘撙撛撝撟撡撣撦撨撬撳撽撾撿"],["8fc1a1","擄擉擊擋擌擎擐擑擕擗擤擥擩擪擭擰擵擷擻擿攁攄攈攉攊攏攓攔攖攙攛攞攟攢攦攩攮攱攺攼攽敃敇敉敐敒敔敟敠敧敫敺敽斁斅斊斒斕斘斝斠斣斦斮斲斳斴斿旂旈旉旎旐旔旖旘旟旰旲旴旵旹旾旿昀昄昈昉昍昑昒昕昖昝"],["8fc2a1","昞昡昢昣昤昦昩昪昫昬昮昰昱昳昹昷晀晅晆晊晌晑晎晗晘晙晛晜晠晡曻晪晫晬晾晳晵晿晷晸晹晻暀晼暋暌暍暐暒暙暚暛暜暟暠暤暭暱暲暵暻暿曀曂曃曈曌曎曏曔曛曟曨曫曬曮曺朅朇朎朓朙朜朠朢朳朾杅杇杈杌杔杕杝"],["8fc3a1","杦杬杮杴杶杻极构枎枏枑枓枖枘枙枛枰枱枲枵枻枼枽柹柀柂柃柅柈柉柒柗柙柜柡柦柰柲柶柷桒栔栙栝栟栨栧栬栭栯栰栱栳栻栿桄桅桊桌桕桗桘桛桫桮",4,"桵桹桺桻桼梂梄梆梈梖梘梚梜梡梣梥梩梪梮梲梻棅棈棌棏"],["8fc4a1","棐棑棓棖棙棜棝棥棨棪棫棬棭棰棱棵棶棻棼棽椆椉椊椐椑椓椖椗椱椳椵椸椻楂楅楉楎楗楛楣楤楥楦楨楩楬楰楱楲楺楻楿榀榍榒榖榘榡榥榦榨榫榭榯榷榸榺榼槅槈槑槖槗槢槥槮槯槱槳槵槾樀樁樃樏樑樕樚樝樠樤樨樰樲"],["8fc5a1","樴樷樻樾樿橅橆橉橊橎橐橑橒橕橖橛橤橧橪橱橳橾檁檃檆檇檉檋檑檛檝檞檟檥檫檯檰檱檴檽檾檿櫆櫉櫈櫌櫐櫔櫕櫖櫜櫝櫤櫧櫬櫰櫱櫲櫼櫽欂欃欆欇欉欏欐欑欗欛欞欤欨欫欬欯欵欶欻欿歆歊歍歒歖歘歝歠歧歫歮歰歵歽"],["8fc6a1","歾殂殅殗殛殟殠殢殣殨殩殬殭殮殰殸殹殽殾毃毄毉毌毖毚毡毣毦毧毮毱毷毹毿氂氄氅氉氍氎氐氒氙氟氦氧氨氬氮氳氵氶氺氻氿汊汋汍汏汒汔汙汛汜汫汭汯汴汶汸汹汻沅沆沇沉沔沕沗沘沜沟沰沲沴泂泆泍泏泐泑泒泔泖"],["8fc7a1","泚泜泠泧泩泫泬泮泲泴洄洇洊洎洏洑洓洚洦洧洨汧洮洯洱洹洼洿浗浞浟浡浥浧浯浰浼涂涇涑涒涔涖涗涘涪涬涴涷涹涽涿淄淈淊淎淏淖淛淝淟淠淢淥淩淯淰淴淶淼渀渄渞渢渧渲渶渹渻渼湄湅湈湉湋湏湑湒湓湔湗湜湝湞"],["8fc8a1","湢湣湨湳湻湽溍溓溙溠溧溭溮溱溳溻溿滀滁滃滇滈滊滍滎滏滫滭滮滹滻滽漄漈漊漌漍漖漘漚漛漦漩漪漯漰漳漶漻漼漭潏潑潒潓潗潙潚潝潞潡潢潨潬潽潾澃澇澈澋澌澍澐澒澓澔澖澚澟澠澥澦澧澨澮澯澰澵澶澼濅濇濈濊"],["8fc9a1","濚濞濨濩濰濵濹濼濽瀀瀅瀆瀇瀍瀗瀠瀣瀯瀴瀷瀹瀼灃灄灈灉灊灋灔灕灝灞灎灤灥灬灮灵灶灾炁炅炆炔",4,"炛炤炫炰炱炴炷烊烑烓烔烕烖烘烜烤烺焃",4,"焋焌焏焞焠焫焭焯焰焱焸煁煅煆煇煊煋煐煒煗煚煜煞煠"],["8fcaa1","煨煹熀熅熇熌熒熚熛熠熢熯熰熲熳熺熿燀燁燄燋燌燓燖燙燚燜燸燾爀爇爈爉爓爗爚爝爟爤爫爯爴爸爹牁牂牃牅牎牏牐牓牕牖牚牜牞牠牣牨牫牮牯牱牷牸牻牼牿犄犉犍犎犓犛犨犭犮犱犴犾狁狇狉狌狕狖狘狟狥狳狴狺狻"],["8fcba1","狾猂猄猅猇猋猍猒猓猘猙猞猢猤猧猨猬猱猲猵猺猻猽獃獍獐獒獖獘獝獞獟獠獦獧獩獫獬獮獯獱獷獹獼玀玁玃玅玆玎玐玓玕玗玘玜玞玟玠玢玥玦玪玫玭玵玷玹玼玽玿珅珆珉珋珌珏珒珓珖珙珝珡珣珦珧珩珴珵珷珹珺珻珽"],["8fcca1","珿琀琁琄琇琊琑琚琛琤琦琨",9,"琹瑀瑃瑄瑆瑇瑋瑍瑑瑒瑗瑝瑢瑦瑧瑨瑫瑭瑮瑱瑲璀璁璅璆璇璉璏璐璑璒璘璙璚璜璟璠璡璣璦璨璩璪璫璮璯璱璲璵璹璻璿瓈瓉瓌瓐瓓瓘瓚瓛瓞瓟瓤瓨瓪瓫瓯瓴瓺瓻瓼瓿甆"],["8fcda1","甒甖甗甠甡甤甧甩甪甯甶甹甽甾甿畀畃畇畈畎畐畒畗畞畟畡畯畱畹",5,"疁疅疐疒疓疕疙疜疢疤疴疺疿痀痁痄痆痌痎痏痗痜痟痠痡痤痧痬痮痯痱痹瘀瘂瘃瘄瘇瘈瘊瘌瘏瘒瘓瘕瘖瘙瘛瘜瘝瘞瘣瘥瘦瘩瘭瘲瘳瘵瘸瘹"],["8fcea1","瘺瘼癊癀癁癃癄癅癉癋癕癙癟癤癥癭癮癯癱癴皁皅皌皍皕皛皜皝皟皠皢",6,"皪皭皽盁盅盉盋盌盎盔盙盠盦盨盬盰盱盶盹盼眀眆眊眎眒眔眕眗眙眚眜眢眨眭眮眯眴眵眶眹眽眾睂睅睆睊睍睎睏睒睖睗睜睞睟睠睢"],["8fcfa1","睤睧睪睬睰睲睳睴睺睽瞀瞄瞌瞍瞔瞕瞖瞚瞟瞢瞧瞪瞮瞯瞱瞵瞾矃矉矑矒矕矙矞矟矠矤矦矪矬矰矱矴矸矻砅砆砉砍砎砑砝砡砢砣砭砮砰砵砷硃硄硇硈硌硎硒硜硞硠硡硣硤硨硪确硺硾碊碏碔碘碡碝碞碟碤碨碬碭碰碱碲碳"],["8fd0a1","碻碽碿磇磈磉磌磎磒磓磕磖磤磛磟磠磡磦磪磲磳礀磶磷磺磻磿礆礌礐礚礜礞礟礠礥礧礩礭礱礴礵礻礽礿祄祅祆祊祋祏祑祔祘祛祜祧祩祫祲祹祻祼祾禋禌禑禓禔禕禖禘禛禜禡禨禩禫禯禱禴禸离秂秄秇秈秊秏秔秖秚秝秞"],["8fd1a1","秠秢秥秪秫秭秱秸秼稂稃稇稉稊稌稑稕稛稞稡稧稫稭稯稰稴稵稸稹稺穄穅穇穈穌穕穖穙穜穝穟穠穥穧穪穭穵穸穾窀窂窅窆窊窋窐窑窔窞窠窣窬窳窵窹窻窼竆竉竌竎竑竛竨竩竫竬竱竴竻竽竾笇笔笟笣笧笩笪笫笭笮笯笰"],["8fd2a1","笱笴笽笿筀筁筇筎筕筠筤筦筩筪筭筯筲筳筷箄箉箎箐箑箖箛箞箠箥箬箯箰箲箵箶箺箻箼箽篂篅篈篊篔篖篗篙篚篛篨篪篲篴篵篸篹篺篼篾簁簂簃簄簆簉簋簌簎簏簙簛簠簥簦簨簬簱簳簴簶簹簺籆籊籕籑籒籓籙",5],["8fd3a1","籡籣籧籩籭籮籰籲籹籼籽粆粇粏粔粞粠粦粰粶粷粺粻粼粿糄糇糈糉糍糏糓糔糕糗糙糚糝糦糩糫糵紃紇紈紉紏紑紒紓紖紝紞紣紦紪紭紱紼紽紾絀絁絇絈絍絑絓絗絙絚絜絝絥絧絪絰絸絺絻絿綁綂綃綅綆綈綋綌綍綑綖綗綝"],["8fd4a1","綞綦綧綪綳綶綷綹緂",4,"緌緍緎緗緙縀緢緥緦緪緫緭緱緵緶緹緺縈縐縑縕縗縜縝縠縧縨縬縭縯縳縶縿繄繅繇繎繐繒繘繟繡繢繥繫繮繯繳繸繾纁纆纇纊纍纑纕纘纚纝纞缼缻缽缾缿罃罄罇罏罒罓罛罜罝罡罣罤罥罦罭"],["8fd5a1","罱罽罾罿羀羋羍羏羐羑羖羗羜羡羢羦羪羭羴羼羿翀翃翈翎翏翛翟翣翥翨翬翮翯翲翺翽翾翿耇耈耊耍耎耏耑耓耔耖耝耞耟耠耤耦耬耮耰耴耵耷耹耺耼耾聀聄聠聤聦聭聱聵肁肈肎肜肞肦肧肫肸肹胈胍胏胒胔胕胗胘胠胭胮"],["8fd6a1","胰胲胳胶胹胺胾脃脋脖脗脘脜脞脠脤脧脬脰脵脺脼腅腇腊腌腒腗腠腡腧腨腩腭腯腷膁膐膄膅膆膋膎膖膘膛膞膢膮膲膴膻臋臃臅臊臎臏臕臗臛臝臞臡臤臫臬臰臱臲臵臶臸臹臽臿舀舃舏舓舔舙舚舝舡舢舨舲舴舺艃艄艅艆"],["8fd7a1","艋艎艏艑艖艜艠艣艧艭艴艻艽艿芀芁芃芄芇芉芊芎芑芔芖芘芚芛芠芡芣芤芧芨芩芪芮芰芲芴芷芺芼芾芿苆苐苕苚苠苢苤苨苪苭苯苶苷苽苾茀茁茇茈茊茋荔茛茝茞茟茡茢茬茭茮茰茳茷茺茼茽荂荃荄荇荍荎荑荕荖荗荰荸"],["8fd8a1","荽荿莀莂莄莆莍莒莔莕莘莙莛莜莝莦莧莩莬莾莿菀菇菉菏菐菑菔菝荓菨菪菶菸菹菼萁萆萊萏萑萕萙莭萯萹葅葇葈葊葍葏葑葒葖葘葙葚葜葠葤葥葧葪葰葳葴葶葸葼葽蒁蒅蒒蒓蒕蒞蒦蒨蒩蒪蒯蒱蒴蒺蒽蒾蓀蓂蓇蓈蓌蓏蓓"],["8fd9a1","蓜蓧蓪蓯蓰蓱蓲蓷蔲蓺蓻蓽蔂蔃蔇蔌蔎蔐蔜蔞蔢蔣蔤蔥蔧蔪蔫蔯蔳蔴蔶蔿蕆蕏",4,"蕖蕙蕜",6,"蕤蕫蕯蕹蕺蕻蕽蕿薁薅薆薉薋薌薏薓薘薝薟薠薢薥薧薴薶薷薸薼薽薾薿藂藇藊藋藎薭藘藚藟藠藦藨藭藳藶藼"],["8fdaa1","藿蘀蘄蘅蘍蘎蘐蘑蘒蘘蘙蘛蘞蘡蘧蘩蘶蘸蘺蘼蘽虀虂虆虒虓虖虗虘虙虝虠",4,"虩虬虯虵虶虷虺蚍蚑蚖蚘蚚蚜蚡蚦蚧蚨蚭蚱蚳蚴蚵蚷蚸蚹蚿蛀蛁蛃蛅蛑蛒蛕蛗蛚蛜蛠蛣蛥蛧蚈蛺蛼蛽蜄蜅蜇蜋蜎蜏蜐蜓蜔蜙蜞蜟蜡蜣"],["8fdba1","蜨蜮蜯蜱蜲蜹蜺蜼蜽蜾蝀蝃蝅蝍蝘蝝蝡蝤蝥蝯蝱蝲蝻螃",6,"螋螌螐螓螕螗螘螙螞螠螣螧螬螭螮螱螵螾螿蟁蟈蟉蟊蟎蟕蟖蟙蟚蟜蟟蟢蟣蟤蟪蟫蟭蟱蟳蟸蟺蟿蠁蠃蠆蠉蠊蠋蠐蠙蠒蠓蠔蠘蠚蠛蠜蠞蠟蠨蠭蠮蠰蠲蠵"],["8fdca1","蠺蠼衁衃衅衈衉衊衋衎衑衕衖衘衚衜衟衠衤衩衱衹衻袀袘袚袛袜袟袠袨袪袺袽袾裀裊",4,"裑裒裓裛裞裧裯裰裱裵裷褁褆褍褎褏褕褖褘褙褚褜褠褦褧褨褰褱褲褵褹褺褾襀襂襅襆襉襏襒襗襚襛襜襡襢襣襫襮襰襳襵襺"],["8fdda1","襻襼襽覉覍覐覔覕覛覜覟覠覥覰覴覵覶覷覼觔",4,"觥觩觫觭觱觳觶觹觽觿訄訅訇訏訑訒訔訕訞訠訢訤訦訫訬訯訵訷訽訾詀詃詅詇詉詍詎詓詖詗詘詜詝詡詥詧詵詶詷詹詺詻詾詿誀誃誆誋誏誐誒誖誗誙誟誧誩誮誯誳"],["8fdea1","誶誷誻誾諃諆諈諉諊諑諓諔諕諗諝諟諬諰諴諵諶諼諿謅謆謋謑謜謞謟謊謭謰謷謼譂",4,"譈譒譓譔譙譍譞譣譭譶譸譹譼譾讁讄讅讋讍讏讔讕讜讞讟谸谹谽谾豅豇豉豋豏豑豓豔豗豘豛豝豙豣豤豦豨豩豭豳豵豶豻豾貆"],["8fdfa1","貇貋貐貒貓貙貛貜貤貹貺賅賆賉賋賏賖賕賙賝賡賨賬賯賰賲賵賷賸賾賿贁贃贉贒贗贛赥赩赬赮赿趂趄趈趍趐趑趕趞趟趠趦趫趬趯趲趵趷趹趻跀跅跆跇跈跊跎跑跔跕跗跙跤跥跧跬跰趼跱跲跴跽踁踄踅踆踋踑踔踖踠踡踢"],["8fe0a1","踣踦踧踱踳踶踷踸踹踽蹀蹁蹋蹍蹎蹏蹔蹛蹜蹝蹞蹡蹢蹩蹬蹭蹯蹰蹱蹹蹺蹻躂躃躉躐躒躕躚躛躝躞躢躧躩躭躮躳躵躺躻軀軁軃軄軇軏軑軔軜軨軮軰軱軷軹軺軭輀輂輇輈輏輐輖輗輘輞輠輡輣輥輧輨輬輭輮輴輵輶輷輺轀轁"],["8fe1a1","轃轇轏轑",4,"轘轝轞轥辝辠辡辤辥辦辵辶辸达迀迁迆迊迋迍运迒迓迕迠迣迤迨迮迱迵迶迻迾适逄逈逌逘逛逨逩逯逪逬逭逳逴逷逿遃遄遌遛遝遢遦遧遬遰遴遹邅邈邋邌邎邐邕邗邘邙邛邠邡邢邥邰邲邳邴邶邽郌邾郃"],["8fe2a1","郄郅郇郈郕郗郘郙郜郝郟郥郒郶郫郯郰郴郾郿鄀鄄鄅鄆鄈鄍鄐鄔鄖鄗鄘鄚鄜鄞鄠鄥鄢鄣鄧鄩鄮鄯鄱鄴鄶鄷鄹鄺鄼鄽酃酇酈酏酓酗酙酚酛酡酤酧酭酴酹酺酻醁醃醅醆醊醎醑醓醔醕醘醞醡醦醨醬醭醮醰醱醲醳醶醻醼醽醿"],["8fe3a1","釂釃釅釓釔釗釙釚釞釤釥釩釪釬",5,"釷釹釻釽鈀鈁鈄鈅鈆鈇鈉鈊鈌鈐鈒鈓鈖鈘鈜鈝鈣鈤鈥鈦鈨鈮鈯鈰鈳鈵鈶鈸鈹鈺鈼鈾鉀鉂鉃鉆鉇鉊鉍鉎鉏鉑鉘鉙鉜鉝鉠鉡鉥鉧鉨鉩鉮鉯鉰鉵",4,"鉻鉼鉽鉿銈銉銊銍銎銒銗"],["8fe4a1","銙銟銠銤銥銧銨銫銯銲銶銸銺銻銼銽銿",4,"鋅鋆鋇鋈鋋鋌鋍鋎鋐鋓鋕鋗鋘鋙鋜鋝鋟鋠鋡鋣鋥鋧鋨鋬鋮鋰鋹鋻鋿錀錂錈錍錑錔錕錜錝錞錟錡錤錥錧錩錪錳錴錶錷鍇鍈鍉鍐鍑鍒鍕鍗鍘鍚鍞鍤鍥鍧鍩鍪鍭鍯鍰鍱鍳鍴鍶"],["8fe5a1","鍺鍽鍿鎀鎁鎂鎈鎊鎋鎍鎏鎒鎕鎘鎛鎞鎡鎣鎤鎦鎨鎫鎴鎵鎶鎺鎩鏁鏄鏅鏆鏇鏉",4,"鏓鏙鏜鏞鏟鏢鏦鏧鏹鏷鏸鏺鏻鏽鐁鐂鐄鐈鐉鐍鐎鐏鐕鐖鐗鐟鐮鐯鐱鐲鐳鐴鐻鐿鐽鑃鑅鑈鑊鑌鑕鑙鑜鑟鑡鑣鑨鑫鑭鑮鑯鑱鑲钄钃镸镹"],["8fe6a1","镾閄閈閌閍閎閝閞閟閡閦閩閫閬閴閶閺閽閿闆闈闉闋闐闑闒闓闙闚闝闞闟闠闤闦阝阞阢阤阥阦阬阱阳阷阸阹阺阼阽陁陒陔陖陗陘陡陮陴陻陼陾陿隁隂隃隄隉隑隖隚隝隟隤隥隦隩隮隯隳隺雊雒嶲雘雚雝雞雟雩雯雱雺霂"],["8fe7a1","霃霅霉霚霛霝霡霢霣霨霱霳靁靃靊靎靏靕靗靘靚靛靣靧靪靮靳靶靷靸靻靽靿鞀鞉鞕鞖鞗鞙鞚鞞鞟鞢鞬鞮鞱鞲鞵鞶鞸鞹鞺鞼鞾鞿韁韄韅韇韉韊韌韍韎韐韑韔韗韘韙韝韞韠韛韡韤韯韱韴韷韸韺頇頊頙頍頎頔頖頜頞頠頣頦"],["8fe8a1","頫頮頯頰頲頳頵頥頾顄顇顊顑顒顓顖顗顙顚顢顣顥顦顪顬颫颭颮颰颴颷颸颺颻颿飂飅飈飌飡飣飥飦飧飪飳飶餂餇餈餑餕餖餗餚餛餜餟餢餦餧餫餱",4,"餹餺餻餼饀饁饆饇饈饍饎饔饘饙饛饜饞饟饠馛馝馟馦馰馱馲馵"],["8fe9a1","馹馺馽馿駃駉駓駔駙駚駜駞駧駪駫駬駰駴駵駹駽駾騂騃騄騋騌騐騑騖騞騠騢騣騤騧騭騮騳騵騶騸驇驁驄驊驋驌驎驑驔驖驝骪骬骮骯骲骴骵骶骹骻骾骿髁髃髆髈髎髐髒髕髖髗髛髜髠髤髥髧髩髬髲髳髵髹髺髽髿",4],["8feaa1","鬄鬅鬈鬉鬋鬌鬍鬎鬐鬒鬖鬙鬛鬜鬠鬦鬫鬭鬳鬴鬵鬷鬹鬺鬽魈魋魌魕魖魗魛魞魡魣魥魦魨魪",4,"魳魵魷魸魹魿鮀鮄鮅鮆鮇鮉鮊鮋鮍鮏鮐鮔鮚鮝鮞鮦鮧鮩鮬鮰鮱鮲鮷鮸鮻鮼鮾鮿鯁鯇鯈鯎鯐鯗鯘鯝鯟鯥鯧鯪鯫鯯鯳鯷鯸"],["8feba1","鯹鯺鯽鯿鰀鰂鰋鰏鰑鰖鰘鰙鰚鰜鰞鰢鰣鰦",4,"鰱鰵鰶鰷鰽鱁鱃鱄鱅鱉鱊鱎鱏鱐鱓鱔鱖鱘鱛鱝鱞鱟鱣鱩鱪鱜鱫鱨鱮鱰鱲鱵鱷鱻鳦鳲鳷鳹鴋鴂鴑鴗鴘鴜鴝鴞鴯鴰鴲鴳鴴鴺鴼鵅鴽鵂鵃鵇鵊鵓鵔鵟鵣鵢鵥鵩鵪鵫鵰鵶鵷鵻"],["8feca1","鵼鵾鶃鶄鶆鶊鶍鶎鶒鶓鶕鶖鶗鶘鶡鶪鶬鶮鶱鶵鶹鶼鶿鷃鷇鷉鷊鷔鷕鷖鷗鷚鷞鷟鷠鷥鷧鷩鷫鷮鷰鷳鷴鷾鸊鸂鸇鸎鸐鸑鸒鸕鸖鸙鸜鸝鹺鹻鹼麀麂麃麄麅麇麎麏麖麘麛麞麤麨麬麮麯麰麳麴麵黆黈黋黕黟黤黧黬黭黮黰黱黲黵"],["8feda1","黸黿鼂鼃鼉鼏鼐鼑鼒鼔鼖鼗鼙鼚鼛鼟鼢鼦鼪鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃",4,"齓齕齖齗齘齚齝齞齨齩齭",4,"齳齵齺齽龏龐龑龒龔龖龗龞龡龢龣龥"]];
/***/ }),
/***/ 686:
/***/ (function(module) {
module.exports = {"uChars":[128,165,169,178,184,216,226,235,238,244,248,251,253,258,276,284,300,325,329,334,364,463,465,467,469,471,473,475,477,506,594,610,712,716,730,930,938,962,970,1026,1104,1106,8209,8215,8218,8222,8231,8241,8244,8246,8252,8365,8452,8454,8458,8471,8482,8556,8570,8596,8602,8713,8720,8722,8726,8731,8737,8740,8742,8748,8751,8760,8766,8777,8781,8787,8802,8808,8816,8854,8858,8870,8896,8979,9322,9372,9548,9588,9616,9622,9634,9652,9662,9672,9676,9680,9702,9735,9738,9793,9795,11906,11909,11913,11917,11928,11944,11947,11951,11956,11960,11964,11979,12284,12292,12312,12319,12330,12351,12436,12447,12535,12543,12586,12842,12850,12964,13200,13215,13218,13253,13263,13267,13270,13384,13428,13727,13839,13851,14617,14703,14801,14816,14964,15183,15471,15585,16471,16736,17208,17325,17330,17374,17623,17997,18018,18212,18218,18301,18318,18760,18811,18814,18820,18823,18844,18848,18872,19576,19620,19738,19887,40870,59244,59336,59367,59413,59417,59423,59431,59437,59443,59452,59460,59478,59493,63789,63866,63894,63976,63986,64016,64018,64021,64025,64034,64037,64042,65074,65093,65107,65112,65127,65132,65375,65510,65536],"gbChars":[0,36,38,45,50,81,89,95,96,100,103,104,105,109,126,133,148,172,175,179,208,306,307,308,309,310,311,312,313,341,428,443,544,545,558,741,742,749,750,805,819,820,7922,7924,7925,7927,7934,7943,7944,7945,7950,8062,8148,8149,8152,8164,8174,8236,8240,8262,8264,8374,8380,8381,8384,8388,8390,8392,8393,8394,8396,8401,8406,8416,8419,8424,8437,8439,8445,8482,8485,8496,8521,8603,8936,8946,9046,9050,9063,9066,9076,9092,9100,9108,9111,9113,9131,9162,9164,9218,9219,11329,11331,11334,11336,11346,11361,11363,11366,11370,11372,11375,11389,11682,11686,11687,11692,11694,11714,11716,11723,11725,11730,11736,11982,11989,12102,12336,12348,12350,12384,12393,12395,12397,12510,12553,12851,12962,12973,13738,13823,13919,13933,14080,14298,14585,14698,15583,15847,16318,16434,16438,16481,16729,17102,17122,17315,17320,17402,17418,17859,17909,17911,17915,17916,17936,17939,17961,18664,18703,18814,18962,19043,33469,33470,33471,33484,33485,33490,33497,33501,33505,33513,33520,33536,33550,37845,37921,37948,38029,38038,38064,38065,38066,38069,38075,38076,38078,39108,39109,39113,39114,39115,39116,39265,39394,189000]};
/***/ }),
/***/ 692:
/***/ (function(__unusedmodule, exports) {
"use strict";
Object.defineProperty(exports, '__esModule', { value: true });
class Deprecation extends Error {
constructor(message) {
super(message); // Maintains proper stack trace (only available on V8)
/* istanbul ignore next */
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
this.name = 'Deprecation';
}
}
exports.Deprecation = Deprecation;
/***/ }),
/***/ 696:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"use strict";
// Update this array if you add/rename/remove files in this directory.
// We support Browserify by skipping automatic module discovery and requiring modules directly.
var modules = [
__webpack_require__(617),
__webpack_require__(766),
__webpack_require__(177),
__webpack_require__(142),
__webpack_require__(749),
__webpack_require__(518),
__webpack_require__(748),
__webpack_require__(378),
__webpack_require__(658),
];
// Put all encoding/alias/codec definitions to single object and export it.
for (var i = 0; i < modules.length; i++) {
var module = modules[i];
for (var enc in module)
if (Object.prototype.hasOwnProperty.call(module, enc))
exports[enc] = module[enc];
}
/***/ }),
/***/ 747:
/***/ (function(module) {
module.exports = require("fs");
/***/ }),
/***/ 748:
/***/ (function(module) {
"use strict";
// Generated data for sbcs codec. Don't edit manually. Regenerate using generation/gen-sbcs.js script.
module.exports = {
"437": "cp437",
"737": "cp737",
"775": "cp775",
"850": "cp850",
"852": "cp852",
"855": "cp855",
"856": "cp856",
"857": "cp857",
"858": "cp858",
"860": "cp860",
"861": "cp861",
"862": "cp862",
"863": "cp863",
"864": "cp864",
"865": "cp865",
"866": "cp866",
"869": "cp869",
"874": "windows874",
"922": "cp922",
"1046": "cp1046",
"1124": "cp1124",
"1125": "cp1125",
"1129": "cp1129",
"1133": "cp1133",
"1161": "cp1161",
"1162": "cp1162",
"1163": "cp1163",
"1250": "windows1250",
"1251": "windows1251",
"1252": "windows1252",
"1253": "windows1253",
"1254": "windows1254",
"1255": "windows1255",
"1256": "windows1256",
"1257": "windows1257",
"1258": "windows1258",
"28591": "iso88591",
"28592": "iso88592",
"28593": "iso88593",
"28594": "iso88594",
"28595": "iso88595",
"28596": "iso88596",
"28597": "iso88597",
"28598": "iso88598",
"28599": "iso88599",
"28600": "iso885910",
"28601": "iso885911",
"28603": "iso885913",
"28604": "iso885914",
"28605": "iso885915",
"28606": "iso885916",
"windows874": {
"type": "_sbcs",
"chars": "€����…�����������‘’“”•–—�������� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"
},
"win874": "windows874",
"cp874": "windows874",
"windows1250": {
"type": "_sbcs",
"chars": "€�‚�„…†‡�‰Š‹ŚŤŽŹ�‘’“”•–—�™š›śťžź ˇ˘Ł¤Ą¦§¨©Ş«¬®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙"
},
"win1250": "windows1250",
"cp1250": "windows1250",
"windows1251": {
"type": "_sbcs",
"chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋЏђ‘’“”•–—�™љ›њќћџ ЎўЈ¤Ґ¦§Ё©Є«¬®Ї°±Ііґµ¶·ё№є»јЅѕїАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя"
},
"win1251": "windows1251",
"cp1251": "windows1251",
"windows1252": {
"type": "_sbcs",
"chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
},
"win1252": "windows1252",
"cp1252": "windows1252",
"windows1253": {
"type": "_sbcs",
"chars": "€�‚ƒ„…†‡�‰�‹�����‘’“”•–—�™�›���� ΅Ά£¤¥¦§¨©�«¬®―°±²³΄µ¶·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�"
},
"win1253": "windows1253",
"cp1253": "windows1253",
"windows1254": {
"type": "_sbcs",
"chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ����‘’“”•–—˜™š›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ"
},
"win1254": "windows1254",
"cp1254": "windows1254",
"windows1255": {
"type": "_sbcs",
"chars": "€�‚ƒ„…†‡ˆ‰�‹�����‘’“”•–—˜™�›���� ¡¢£₪¥¦§¨©×«¬®¯°±²³´µ¶·¸¹÷»¼½¾¿ְֱֲֳִֵֶַָֹֺֻּֽ־ֿ׀ׁׂ׃װױײ׳״�������אבגדהוזחטיךכלםמןנסעףפץצקרשת���"
},
"win1255": "windows1255",
"cp1255": "windows1255",
"windows1256": {
"type": "_sbcs",
"chars": "€پ‚ƒ„…†‡ˆ‰ٹ‹Œچژڈگ‘’“”•–—ک™ڑ›œں ،¢£¤¥¦§¨©ھ«¬®¯°±²³´µ¶·¸¹؛»¼½¾؟ہءآأؤإئابةتثجحخدذرزسشصض×طظعغـفقكàلâمنهوçèéêëىيîïًٌٍَôُِ÷ّùْûüے"
},
"win1256": "windows1256",
"cp1256": "windows1256",
"windows1257": {
"type": "_sbcs",
"chars": "€�‚�„…†‡�‰�‹�¨ˇ¸�‘’“”•–—�™�›�¯˛� �¢£¤�¦§Ø©Ŗ«¬®Æ°±²³´µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙"
},
"win1257": "windows1257",
"cp1257": "windows1257",
"windows1258": {
"type": "_sbcs",
"chars": "€�‚ƒ„…†‡ˆ‰�‹Œ����‘’“”•–—˜™�›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ"
},
"win1258": "windows1258",
"cp1258": "windows1258",
"iso88591": {
"type": "_sbcs",
"chars": "
¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
},
"cp28591": "iso88591",
"iso88592": {
"type": "_sbcs",
"chars": "
Ą˘Ł¤ĽŚ§¨ŠŞŤŹŽŻ°ą˛ł´ľśˇ¸šşťź˝žżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙"
},
"cp28592": "iso88592",
"iso88593": {
"type": "_sbcs",
"chars": "
Ħ˘£¤�Ĥ§¨İŞĞĴ�ݰħ²³´µĥ·¸ışğĵ½�żÀÁÂ�ÄĊĈÇÈÉÊËÌÍÎÏ�ÑÒÓÔĠÖ×ĜÙÚÛÜŬŜßàáâ�äċĉçèéêëìíîï�ñòóôġö÷ĝùúûüŭŝ˙"
},
"cp28593": "iso88593",
"iso88594": {
"type": "_sbcs",
"chars": "
ĄĸŖ¤Ĩϧ¨ŠĒĢŦޝ°ą˛ŗ´ĩšēģŧŊžŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎĪĐŅŌĶÔÕÖרŲÚÛÜŨŪßāáâãäåæįčéęëėíîīđņōķôõö÷øųúûüũū˙"
},
"cp28594": "iso88594",
"iso88595": {
"type": "_sbcs",
"chars": "
ЁЂЃЄЅІЇЈЉЊЋЌЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђѓєѕіїјљњћќ§ўџ"
},
"cp28595": "iso88595",
"iso88596": {
"type": "_sbcs",
"chars": "
���¤�������،�������������؛���؟�ءآأؤإئابةتثجحخدذرزسشصضطظعغ�����ـفقكلمنهوىيًٌٍَُِّْ�������������"
},
"cp28596": "iso88596",
"iso88597": {
"type": "_sbcs",
"chars": "
‘’£€₯¦§¨©ͺ«¬�―°±²³΄΅Ά·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�"
},
"cp28597": "iso88597",
"iso88598": {
"type": "_sbcs",
"chars": "
�¢£¤¥¦§¨©×«¬®¯°±²³´µ¶·¸¹÷»¼½¾��������������������������������‗אבגדהוזחטיךכלםמןנסעףפץצקרשת���"
},
"cp28598": "iso88598",
"iso88599": {
"type": "_sbcs",
"chars": "
¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ"
},
"cp28599": "iso88599",
"iso885910": {
"type": "_sbcs",
"chars": "
ĄĒĢĪĨͧĻĐŠŦŽŪŊ°ąēģīĩķ·ļđšŧž―ūŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎÏÐŅŌÓÔÕÖŨØŲÚÛÜÝÞßāáâãäåæįčéęëėíîïðņōóôõöũøųúûüýþĸ"
},
"cp28600": "iso885910",
"iso885911": {
"type": "_sbcs",
"chars": "
กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"
},
"cp28601": "iso885911",
"iso885913": {
"type": "_sbcs",
"chars": "
”¢£¤„¦§Ø©Ŗ«¬®Æ°±²³“µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž’"
},
"cp28603": "iso885913",
"iso885914": {
"type": "_sbcs",
"chars": "
Ḃḃ£ĊċḊ§Ẁ©ẂḋỲ®ŸḞḟĠġṀṁ¶ṖẁṗẃṠỳẄẅṡÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŴÑÒÓÔÕÖṪØÙÚÛÜÝŶßàáâãäåæçèéêëìíîïŵñòóôõöṫøùúûüýŷÿ"
},
"cp28604": "iso885914",
"iso885915": {
"type": "_sbcs",
"chars": "
¡¢£€¥Š§š©ª«¬®¯°±²³Žµ¶·ž¹º»ŒœŸ¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
},
"cp28605": "iso885915",
"iso885916": {
"type": "_sbcs",
"chars": "
ĄąŁ€„Чš©Ș«ŹźŻ°±ČłŽ”¶·žčș»ŒœŸżÀÁÂĂÄĆÆÇÈÉÊËÌÍÎÏĐŃÒÓÔŐÖŚŰÙÚÛÜĘȚßàáâăäćæçèéêëìíîïđńòóôőöśűùúûüęțÿ"
},
"cp28606": "iso885916",
"cp437": {
"type": "_sbcs",
"chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
},
"ibm437": "cp437",
"csibm437": "cp437",
"cp737": {
"type": "_sbcs",
"chars": "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρσςτυφχψ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ωάέήϊίόύϋώΆΈΉΊΌΎΏ±≥≤ΪΫ÷≈°∙·√ⁿ²■ "
},
"ibm737": "cp737",
"csibm737": "cp737",
"cp775": {
"type": "_sbcs",
"chars": "ĆüéāäģåćłēŖŗīŹÄÅÉæÆōöĢ¢ŚśÖÜø£Ø×¤ĀĪóŻżź”¦©®¬½¼Ł«»░▒▓│┤ĄČĘĖ╣║╗╝ĮŠ┐└┴┬├─┼ŲŪ╚╔╩╦╠═╬Žąčęėįšųūž┘┌█▄▌▐▀ÓßŌŃõÕµńĶķĻļņĒŅ’±“¾¶§÷„°∙·¹³²■ "
},
"ibm775": "cp775",
"csibm775": "cp775",
"cp850": {
"type": "_sbcs",
"chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈıÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´±‗¾¶§÷¸°¨·¹³²■ "
},
"ibm850": "cp850",
"csibm850": "cp850",
"cp852": {
"type": "_sbcs",
"chars": "ÇüéâäůćçłëŐőîŹÄĆÉĹĺôöĽľŚśÖÜŤťŁ×čáíóúĄąŽžĘ꬟Ⱥ«»░▒▓│┤ÁÂĚŞ╣║╗╝Żż┐└┴┬├─┼Ăă╚╔╩╦╠═╬¤đĐĎËďŇÍÎě┘┌█▄ŢŮ▀ÓßÔŃńňŠšŔÚŕŰýÝţ´˝˛ˇ˘§÷¸°¨˙űŘř■ "
},
"ibm852": "cp852",
"csibm852": "cp852",
"cp855": {
"type": "_sbcs",
"chars": "ђЂѓЃёЁєЄѕЅіІїЇјЈљЉњЊћЋќЌўЎџЏюЮъЪаАбБцЦдДеЕфФгГ«»░▒▓│┤хХиИ╣║╗╝йЙ┐└┴┬├─┼кК╚╔╩╦╠═╬¤лЛмМнНоОп┘┌█▄Пя▀ЯрРсСтТуУжЖвВьЬ№ыЫзЗшШэЭщЩчЧ§■ "
},
"ibm855": "cp855",
"csibm855": "cp855",
"cp856": {
"type": "_sbcs",
"chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת�£�×����������®¬½¼�«»░▒▓│┤���©╣║╗╝¢¥┐└┴┬├─┼��╚╔╩╦╠═╬¤���������┘┌█▄¦�▀������µ�������¯´±‗¾¶§÷¸°¨·¹³²■ "
},
"ibm856": "cp856",
"csibm856": "cp856",
"cp857": {
"type": "_sbcs",
"chars": "ÇüéâäàåçêëèïîıÄÅÉæÆôöòûùİÖÜø£ØŞşáíóúñÑĞ𿮬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ºªÊËÈ�ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµ�×ÚÛÙìÿ¯´±�¾¶§÷¸°¨·¹³²■ "
},
"ibm857": "cp857",
"csibm857": "cp857",
"cp858": {
"type": "_sbcs",
"chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈ€ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´±‗¾¶§÷¸°¨·¹³²■ "
},
"ibm858": "cp858",
"csibm858": "cp858",
"cp860": {
"type": "_sbcs",
"chars": "ÇüéâãàÁçêÊèÍÔìÃÂÉÀÈôõòÚùÌÕÜ¢£Ù₧ÓáíóúñѪº¿Ò¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
},
"ibm860": "cp860",
"csibm860": "cp860",
"cp861": {
"type": "_sbcs",
"chars": "ÇüéâäàåçêëèÐðÞÄÅÉæÆôöþûÝýÖÜø£Ø₧ƒáíóúÁÍÓÚ¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
},
"ibm861": "cp861",
"csibm861": "cp861",
"cp862": {
"type": "_sbcs",
"chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
},
"ibm862": "cp862",
"csibm862": "cp862",
"cp863": {
"type": "_sbcs",
"chars": "ÇüéâÂà¶çêëèïî‗À§ÉÈÊôËÏûù¤ÔÜ¢£ÙÛƒ¦´óú¨¸³¯Î⌐¬½¼¾«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
},
"ibm863": "cp863",
"csibm863": "cp863",
"cp864": {
"type": "_sbcs",
"chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$٪&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~°·∙√▒─│┼┤┬├┴┐┌└┘β∞φ±½¼≈«»ﻷﻸ��ﻻﻼ� ﺂ£¤ﺄ��ﺎﺏﺕﺙ،ﺝﺡﺥ٠١٢٣٤٥٦٧٨٩ﻑ؛ﺱﺵﺹ؟¢ﺀﺁﺃﺅﻊﺋﺍﺑﺓﺗﺛﺟﺣﺧﺩﺫﺭﺯﺳﺷﺻﺿﻁﻅﻋﻏ¦¬÷×ﻉـﻓﻗﻛﻟﻣﻧﻫﻭﻯﻳﺽﻌﻎﻍﻡﹽّﻥﻩﻬﻰﻲﻐﻕﻵﻶﻝﻙﻱ■�"
},
"ibm864": "cp864",
"csibm864": "cp864",
"cp865": {
"type": "_sbcs",
"chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø₧ƒáíóúñѪº¿⌐¬½¼¡«¤░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
},
"ibm865": "cp865",
"csibm865": "cp865",
"cp866": {
"type": "_sbcs",
"chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■ "
},
"ibm866": "cp866",
"csibm866": "cp866",
"cp869": {
"type": "_sbcs",
"chars": "������Ά�·¬¦‘’Έ―ΉΊΪΌ��ΎΫ©Ώ²³ά£έήίϊΐόύΑΒΓΔΕΖΗ½ΘΙ«»░▒▓│┤ΚΛΜΝ╣║╗╝ΞΟ┐└┴┬├─┼ΠΡ╚╔╩╦╠═╬ΣΤΥΦΧΨΩαβγ┘┌█▄δε▀ζηθικλμνξοπρσςτ΄±υφχ§ψ΅°¨ωϋΰώ■ "
},
"ibm869": "cp869",
"csibm869": "cp869",
"cp922": {
"type": "_sbcs",
"chars": "
¡¢£¤¥¦§¨©ª«¬®‾°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŠÑÒÓÔÕÖרÙÚÛÜÝŽßàáâãäåæçèéêëìíîïšñòóôõö÷øùúûüýžÿ"
},
"ibm922": "cp922",
"csibm922": "cp922",
"cp1046": {
"type": "_sbcs",
"chars": "ﺈ×÷ﹱ■│─┐┌└┘ﹹﹻﹽﹿﹷﺊﻰﻳﻲﻎﻏﻐﻶﻸﻺﻼ ¤ﺋﺑﺗﺛﺟﺣ،ﺧﺳ٠١٢٣٤٥٦٧٨٩ﺷ؛ﺻﺿﻊ؟ﻋءآأؤإئابةتثجحخدذرزسشصضطﻇعغﻌﺂﺄﺎﻓـفقكلمنهوىيًٌٍَُِّْﻗﻛﻟﻵﻷﻹﻻﻣﻧﻬﻩ�"
},
"ibm1046": "cp1046",
"csibm1046": "cp1046",
"cp1124": {
"type": "_sbcs",
"chars": "
ЁЂҐЄЅІЇЈЉЊЋЌЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђґєѕіїјљњћќ§ўџ"
},
"ibm1124": "cp1124",
"csibm1124": "cp1124",
"cp1125": {
"type": "_sbcs",
"chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёҐґЄєІіЇї·√№¤■ "
},
"ibm1125": "cp1125",
"csibm1125": "cp1125",
"cp1129": {
"type": "_sbcs",
"chars": "
¡¢£¤¥¦§œ©ª«¬®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ"
},
"ibm1129": "cp1129",
"csibm1129": "cp1129",
"cp1133": {
"type": "_sbcs",
"chars": "
ກຂຄງຈສຊຍດຕຖທນບປຜຝພຟມຢຣລວຫອຮ���ຯະາຳິີຶືຸູຼັົຽ���ເແໂໃໄ່້໊໋໌ໍໆ�ໜໝ₭����������������໐໑໒໓໔໕໖໗໘໙��¢¬¦�"
},
"ibm1133": "cp1133",
"csibm1133": "cp1133",
"cp1161": {
"type": "_sbcs",
"chars": "��������������������������������่กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู้๊๋€฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛¢¬¦ "
},
"ibm1161": "cp1161",
"csibm1161": "cp1161",
"cp1162": {
"type": "_sbcs",
"chars": "€…‘’“”•–— กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"
},
"ibm1162": "cp1162",
"csibm1162": "cp1162",
"cp1163": {
"type": "_sbcs",
"chars": "
¡¢£€¥¦§œ©ª«¬®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ"
},
"ibm1163": "cp1163",
"csibm1163": "cp1163",
"maccroatian": {
"type": "_sbcs",
"chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈ƫȅ ÀÃÕŒœĐ—“”‘’÷◊�©⁄¤‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ"
},
"maccyrillic": {
"type": "_sbcs",
"chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°¢£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµ∂ЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤"
},
"macgreek": {
"type": "_sbcs",
"chars": "Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ�"
},
"maciceland": {
"type": "_sbcs",
"chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüݰ¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"
},
"macroman": {
"type": "_sbcs",
"chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"
},
"macromania": {
"type": "_sbcs",
"chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂŞ∞±≤≥¥µ∂∑∏π∫ªºΩăş¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›Ţţ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"
},
"macthai": {
"type": "_sbcs",
"chars": "«»…“”�•‘’� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู–—฿เแโใไๅๆ็่้๊๋์ํ™๏๐๑๒๓๔๕๖๗๘๙®©����"
},
"macturkish": {
"type": "_sbcs",
"chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙ�ˆ˜¯˘˙˚¸˝˛ˇ"
},
"macukraine": {
"type": "_sbcs",
"chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤"
},
"koi8r": {
"type": "_sbcs",
"chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ё╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡Ё╢╣╤╥╦╧╨╩╪╫╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ"
},
"koi8u": {
"type": "_sbcs",
"chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґ╝╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪Ґ╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ"
},
"koi8ru": {
"type": "_sbcs",
"chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґў╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪ҐЎ©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ"
},
"koi8t": {
"type": "_sbcs",
"chars": "қғ‚Ғ„…†‡�‰ҳ‹ҲҷҶ�Қ‘’“”•–—�™�›�����ӯӮё¤ӣ¦§���«¬®�°±²Ё�Ӣ¶·�№�»���©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ"
},
"armscii8": {
"type": "_sbcs",
"chars": "
�և։)(»«—.՝,-֊…՜՛՞ԱաԲբԳգԴդԵեԶզԷէԸըԹթԺժԻիԼլԽխԾծԿկՀհՁձՂղՃճՄմՅյՆնՇշՈոՉչՊպՋջՌռՍսՎվՏտՐրՑցՒւՓփՔքՕօՖֆ՚�"
},
"rk1048": {
"type": "_sbcs",
"chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊҚҺЏђ‘’“”•–—�™љ›њқһџ ҰұӘ¤Ө¦§Ё©Ғ«¬®Ү°±Ііөµ¶·ё№ғ»әҢңүАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя"
},
"tcvn": {
"type": "_sbcs",
"chars": "\u0000ÚỤ\u0003ỪỬỮ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010ỨỰỲỶỸÝỴ\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ÀẢÃÁẠẶẬÈẺẼÉẸỆÌỈĨÍỊÒỎÕÓỌỘỜỞỠỚỢÙỦŨ ĂÂÊÔƠƯĐăâêôơưđẶ̀̀̉̃́àảãáạẲằẳẵắẴẮẦẨẪẤỀặầẩẫấậèỂẻẽéẹềểễếệìỉỄẾỒĩíịòỔỏõóọồổỗốộờởỡớợùỖủũúụừửữứựỳỷỹýỵỐ"
},
"georgianacademy": {
"type": "_sbcs",
"chars": "‚ƒ„…†‡ˆ‰Š‹Œ‘’“”•–—˜™š›œŸ ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰჱჲჳჴჵჶçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
},
"georgianps": {
"type": "_sbcs",
"chars": "‚ƒ„…†‡ˆ‰Š‹Œ‘’“”•–—˜™š›œŸ ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზჱთიკლმნჲოპჟრსტჳუფქღყშჩცძწჭხჴჯჰჵæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
},
"pt154": {
"type": "_sbcs",
"chars": "ҖҒӮғ„…ҶҮҲүҠӢҢҚҺҸҗ‘’“”•–—ҳҷҡӣңқһҹ ЎўЈӨҘҰ§Ё©Ә«¬ӯ®Ҝ°ұІіҙө¶·ё№ә»јҪҫҝАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя"
},
"viscii": {
"type": "_sbcs",
"chars": "\u0000\u0001Ẳ\u0003\u0004ẴẪ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013Ỷ\u0015\u0016\u0017\u0018Ỹ\u001a\u001b\u001c\u001dỴ\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ẠẮẰẶẤẦẨẬẼẸẾỀỂỄỆỐỒỔỖỘỢỚỜỞỊỎỌỈỦŨỤỲÕắằặấầẩậẽẹếềểễệốồổỗỠƠộờởịỰỨỪỬơớƯÀÁÂÃẢĂẳẵÈÉÊẺÌÍĨỳĐứÒÓÔạỷừửÙÚỹỵÝỡưàáâãảăữẫèéêẻìíĩỉđựòóôõỏọụùúũủýợỮ"
},
"iso646cn": {
"type": "_sbcs",
"chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#¥%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������"
},
"iso646jp": {
"type": "_sbcs",
"chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[¥]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������"
},
"hproman8": {
"type": "_sbcs",
"chars": "
ÀÂÈÊËÎÏ´ˋˆ¨˜ÙÛ₤¯Ýý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÁÃãÐðÍÌÓÒÕõŠšÚŸÿÞþ·µ¶¾—¼½ªº«■»±�"
},
"macintosh": {
"type": "_sbcs",
"chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"
},
"ascii": {
"type": "_sbcs",
"chars": "��������������������������������������������������������������������������������������������������������������������������������"
},
"tis620": {
"type": "_sbcs",
"chars": "���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"
}
}
/***/ }),
/***/ 749:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"use strict";
var Buffer = __webpack_require__(643).Buffer;
// Single-byte codec. Needs a 'chars' string parameter that contains 256 or 128 chars that
// correspond to encoded bytes (if 128 - then lower half is ASCII).
exports._sbcs = SBCSCodec;
function SBCSCodec(codecOptions, iconv) {
if (!codecOptions)
throw new Error("SBCS codec is called without the data.")
// Prepare char buffer for decoding.
if (!codecOptions.chars || (codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256))
throw new Error("Encoding '"+codecOptions.type+"' has incorrect 'chars' (must be of len 128 or 256)");
if (codecOptions.chars.length === 128) {
var asciiString = "";
for (var i = 0; i < 128; i++)
asciiString += String.fromCharCode(i);
codecOptions.chars = asciiString + codecOptions.chars;
}
this.decodeBuf = Buffer.from(codecOptions.chars, 'ucs2');
// Encoding buffer.
var encodeBuf = Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0));
for (var i = 0; i < codecOptions.chars.length; i++)
encodeBuf[codecOptions.chars.charCodeAt(i)] = i;
this.encodeBuf = encodeBuf;
}
SBCSCodec.prototype.encoder = SBCSEncoder;
SBCSCodec.prototype.decoder = SBCSDecoder;
function SBCSEncoder(options, codec) {
this.encodeBuf = codec.encodeBuf;
}
SBCSEncoder.prototype.write = function(str) {
var buf = Buffer.alloc(str.length);
for (var i = 0; i < str.length; i++)
buf[i] = this.encodeBuf[str.charCodeAt(i)];
return buf;
}
SBCSEncoder.prototype.end = function() {
}
function SBCSDecoder(options, codec) {
this.decodeBuf = codec.decodeBuf;
}
SBCSDecoder.prototype.write = function(buf) {
// Strings are immutable in JS -> we use ucs2 buffer to speed up computations.
var decodeBuf = this.decodeBuf;
var newBuf = Buffer.alloc(buf.length*2);
var idx1 = 0, idx2 = 0;
for (var i = 0; i < buf.length; i++) {
idx1 = buf[i]*2; idx2 = i*2;
newBuf[idx2] = decodeBuf[idx1];
newBuf[idx2+1] = decodeBuf[idx1+1];
}
return newBuf.toString('ucs2');
}
SBCSDecoder.prototype.end = function() {
}
/***/ }),
/***/ 753:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var endpoint = __webpack_require__(385);
var universalUserAgent = __webpack_require__(796);
var isPlainObject = _interopDefault(__webpack_require__(548));
var nodeFetch = _interopDefault(__webpack_require__(454));
var requestError = __webpack_require__(463);
const VERSION = "5.4.7";
function getBufferResponse(response) {
return response.arrayBuffer();
}
function fetchWrapper(requestOptions) {
if (isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) {
requestOptions.body = JSON.stringify(requestOptions.body);
}
let headers = {};
let status;
let url;
const fetch = requestOptions.request && requestOptions.request.fetch || nodeFetch;
return fetch(requestOptions.url, Object.assign({
method: requestOptions.method,
body: requestOptions.body,
headers: requestOptions.headers,
redirect: requestOptions.redirect
}, requestOptions.request)).then(response => {
url = response.url;
status = response.status;
for (const keyAndValue of response.headers) {
headers[keyAndValue[0]] = keyAndValue[1];
}
if (status === 204 || status === 205) {
return;
} // GitHub API returns 200 for HEAD requests
if (requestOptions.method === "HEAD") {
if (status < 400) {
return;
}
throw new requestError.RequestError(response.statusText, status, {
headers,
request: requestOptions
});
}
if (status === 304) {
throw new requestError.RequestError("Not modified", status, {
headers,
request: requestOptions
});
}
if (status >= 400) {
return response.text().then(message => {
const error = new requestError.RequestError(message, status, {
headers,
request: requestOptions
});
try {
let responseBody = JSON.parse(error.message);
Object.assign(error, responseBody);
let errors = responseBody.errors; // Assumption `errors` would always be in Array format
error.message = error.message + ": " + errors.map(JSON.stringify).join(", ");
} catch (e) {// ignore, see octokit/rest.js#684
}
throw error;
});
}
const contentType = response.headers.get("content-type");
if (/application\/json/.test(contentType)) {
return response.json();
}
|
return response.text();
}
return getBufferResponse(response);
}).then(data => {
return {
status,
url,
headers,
data
};
}).catch(error => {
if (error instanceof requestError.RequestError) {
throw error;
}
throw new requestError.RequestError(error.message, 500, {
headers,
request: requestOptions
});
});
}
function withDefaults(oldEndpoint, newDefaults) {
const endpoint = oldEndpoint.defaults(newDefaults);
const newApi = function (route, parameters) {
const endpointOptions = endpoint.merge(route, parameters);
if (!endpointOptions.request || !endpointOptions.request.hook) {
return fetchWrapper(endpoint.parse(endpointOptions));
}
const request = (route, parameters) => {
return fetchWrapper(endpoint.parse(endpoint.merge(route, parameters)));
};
Object.assign(request, {
endpoint,
defaults: withDefaults.bind(null, endpoint)
});
return endpointOptions.request.hook(request, endpointOptions);
};
return Object.assign(newApi, {
endpoint,
defaults: withDefaults.bind(null, endpoint)
});
}
const request = withDefaults(endpoint.endpoint, {
headers: {
"user-agent": `octokit-request.js/${VERSION} ${universalUserAgent.getUserAgent()}`
}
});
exports.request = request;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 761:
/***/ (function(module) {
module.exports = require("zlib");
/***/ }),
/***/ 766:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"use strict";
var Buffer = __webpack_require__(643).Buffer;
// == UTF32-LE/BE codec. ==========================================================
exports._utf32 = Utf32Codec;
function Utf32Codec(codecOptions, iconv) {
this.iconv = iconv;
this.bomAware = true;
this.isLE = codecOptions.isLE;
}
exports.utf32le = { type: '_utf32', isLE: true };
exports.utf32be = { type: '_utf32', isLE: false };
// Aliases
exports.ucs4le = 'utf32le';
exports.ucs4be = 'utf32be';
Utf32Codec.prototype.encoder = Utf32Encoder;
Utf32Codec.prototype.decoder = Utf32Decoder;
// -- Encoding
function Utf32Encoder(options, codec) {
this.isLE = codec.isLE;
this.highSurrogate = 0;
}
Utf32Encoder.prototype.write = function(str) {
var src = Buffer.from(str, 'ucs2');
var dst = Buffer.alloc(src.length * 2);
var write32 = this.isLE ? dst.writeUInt32LE : dst.writeUInt32BE;
var offset = 0;
for (var i = 0; i < src.length; i += 2) {
var code = src.readUInt16LE(i);
var isHighSurrogate = (0xD800 <= code && code < 0xDC00);
var isLowSurrogate = (0xDC00 <= code && code < 0xE000);
if (this.highSurrogate) {
if (isHighSurrogate || !isLowSurrogate) {
// There shouldn't be two high surrogates in a row, nor a high surrogate which isn't followed by a low
// surrogate. If this happens, keep the pending high surrogate as a stand-alone semi-invalid character
// (technically wrong, but expected by some applications, like Windows file names).
write32.call(dst, this.highSurrogate, offset);
offset += 4;
}
else {
// Create 32-bit value from high and low surrogates;
var codepoint = (((this.highSurrogate - 0xD800) << 10) | (code - 0xDC00)) + 0x10000;
write32.call(dst, codepoint, offset);
offset += 4;
this.highSurrogate = 0;
continue;
}
}
if (isHighSurrogate)
this.highSurrogate = code;
else {
// Even if the current character is a low surrogate, with no previous high surrogate, we'll
// encode it as a semi-invalid stand-alone character for the same reasons expressed above for
// unpaired high surrogates.
write32.call(dst, code, offset);
offset += 4;
this.highSurrogate = 0;
}
}
if (offset < dst.length)
dst = dst.slice(0, offset);
return dst;
};
Utf32Encoder.prototype.end = function() {
// Treat any leftover high surrogate as a semi-valid independent character.
if (!this.highSurrogate)
return;
var buf = Buffer.alloc(4);
if (this.isLE)
buf.writeUInt32LE(this.highSurrogate, 0);
else
buf.writeUInt32BE(this.highSurrogate, 0);
this.highSurrogate = 0;
return buf;
};
// -- Decoding
function Utf32Decoder(options, codec) {
this.isLE = codec.isLE;
this.badChar = codec.iconv.defaultCharUnicode.charCodeAt(0);
this.overflow = [];
}
Utf32Decoder.prototype.write = function(src) {
if (src.length === 0)
return '';
var i = 0;
var codepoint = 0;
var dst = Buffer.alloc(src.length + 4);
var offset = 0;
var isLE = this.isLE;
var overflow = this.overflow;
var badChar = this.badChar;
if (overflow.length > 0) {
for (; i < src.length && overflow.length < 4; i++)
overflow.push(src[i]);
if (overflow.length === 4) {
// NOTE: codepoint is a signed int32 and can be negative.
// NOTE: We copied this block from below to help V8 optimize it (it works with array, not buffer).
if (isLE) {
codepoint = overflow[i] | (overflow[i+1] << 8) | (overflow[i+2] << 16) | (overflow[i+3] << 24);
} else {
codepoint = overflow[i+3] | (overflow[i+2] << 8) | (overflow[i+1] << 16) | (overflow[i] << 24);
}
overflow.length = 0;
offset = _writeCodepoint(dst, offset, codepoint, badChar);
}
}
// Main loop. Should be as optimized as possible.
for (; i < src.length - 3; i += 4) {
// NOTE: codepoint is a signed int32 and can be negative.
if (isLE) {
codepoint = src[i] | (src[i+1] << 8) | (src[i+2] << 16) | (src[i+3] << 24);
} else {
codepoint = src[i+3] | (src[i+2] << 8) | (src[i+1] << 16) | (src[i] << 24);
}
offset = _writeCodepoint(dst, offset, codepoint, badChar);
}
// Keep overflowing bytes.
for (; i < src.length; i++) {
overflow.push(src[i]);
}
return dst.slice(0, offset).toString('ucs2');
};
function _writeCodepoint(dst, offset, codepoint, badChar) {
// NOTE: codepoint is signed int32 and can be negative. We keep it that way to help V8 with optimizations.
if (codepoint < 0 || codepoint > 0x10FFFF) {
// Not a valid Unicode codepoint
codepoint = badChar;
}
// Ephemeral Planes: Write high surrogate.
if (codepoint >= 0x10000) {
codepoint -= 0x10000;
var high = 0xD800 | (codepoint >> 10);
dst[offset++] = high & 0xff;
dst[offset++] = high >> 8;
// Low surrogate is written below.
var codepoint = 0xDC00 | (codepoint & 0x3FF);
}
// Write BMP char or low surrogate.
dst[offset++] = codepoint & 0xff;
dst[offset++] = codepoint >> 8;
return offset;
};
Utf32Decoder.prototype.end = function() {
this.overflow.length = 0;
};
// == UTF-32 Auto codec =============================================================
// Decoder chooses automatically from UTF-32LE and UTF-32BE using BOM and space-based heuristic.
// Defaults to UTF-32LE. http://en.wikipedia.org/wiki/UTF-32
// Encoder/decoder default can be changed: iconv.decode(buf, 'utf32', {defaultEncoding: 'utf-32be'});
// Encoder prepends BOM (which can be overridden with (addBOM: false}).
exports.utf32 = Utf32AutoCodec;
exports.ucs4 = 'utf32';
function Utf32AutoCodec(options, iconv) {
this.iconv = iconv;
}
Utf32AutoCodec.prototype.encoder = Utf32AutoEncoder;
Utf32AutoCodec.prototype.decoder = Utf32AutoDecoder;
// -- Encoding
function Utf32AutoEncoder(options, codec) {
options = options || {};
if (options.addBOM === undefined)
options.addBOM = true;
this.encoder = codec.iconv.getEncoder(options.defaultEncoding || 'utf-32le', options);
}
Utf32AutoEncoder.prototype.write = function(str) {
return this.encoder.write(str);
};
Utf32AutoEncoder.prototype.end = function() {
return this.encoder.end();
};
// -- Decoding
function Utf32AutoDecoder(options, codec) {
this.decoder = null;
this.initialBufs = [];
this.initialBufsLen = 0;
this.options = options || {};
this.iconv = codec.iconv;
}
Utf32AutoDecoder.prototype.write = function(buf) {
if (!this.decoder) {
// Codec is not chosen yet. Accumulate initial bytes.
this.initialBufs.push(buf);
this.initialBufsLen += buf.length;
if (this.initialBufsLen < 32) // We need more bytes to use space heuristic (see below)
return '';
// We have enough bytes -> detect endianness.
var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding);
this.decoder = this.iconv.getDecoder(encoding, this.options);
var resStr = '';
for (var i = 0; i < this.initialBufs.length; i++)
resStr += this.decoder.write(this.initialBufs[i]);
this.initialBufs.length = this.initialBufsLen = 0;
return resStr;
}
return this.decoder.write(buf);
};
Utf32AutoDecoder.prototype.end = function() {
if (!this.decoder) {
var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding);
this.decoder = this.iconv.getDecoder(encoding, this.options);
var resStr = '';
for (var i = 0; i < this.initialBufs.length; i++)
resStr += this.decoder.write(this.initialBufs[i]);
var trail = this.decoder.end();
if (trail)
resStr += trail;
this.initialBufs.length = this.initialBufsLen = 0;
return resStr;
}
return this.decoder.end();
};
function detectEncoding(bufs, defaultEncoding) {
var b = [];
var charsProcessed = 0;
var invalidLE = 0, invalidBE = 0; // Number of invalid chars when decoded as LE or BE.
var bmpCharsLE = 0, bmpCharsBE = 0; // Number of BMP chars when decoded as LE or BE.
outer_loop:
for (var i = 0; i < bufs.length; i++) {
var buf = bufs[i];
for (var j = 0; j < buf.length; j++) {
b.push(buf[j]);
if (b.length === 4) {
if (charsProcessed === 0) {
// Check BOM first.
if (b[0] === 0xFF && b[1] === 0xFE && b[2] === 0 && b[3] === 0) {
return 'utf-32le';
}
if (b[0] === 0 && b[1] === 0 && b[2] === 0xFE && b[3] === 0xFF) {
return 'utf-32be';
}
}
if (b[0] !== 0 || b[1] > 0x10) invalidBE++;
if (b[3] !== 0 || b[2] > 0x10) invalidLE++;
if (b[0] === 0 && b[1] === 0 && (b[2] !== 0 || b[3] !== 0)) bmpCharsBE++;
if ((b[0] !== 0 || b[1] !== 0) && b[2] === 0 && b[3] === 0) bmpCharsLE++;
b.length = 0;
charsProcessed++;
if (charsProcessed >= 100) {
break outer_loop;
}
}
}
}
// Make decisions.
if (bmpCharsBE - invalidBE > bmpCharsLE - invalidLE) return 'utf-32be';
if (bmpCharsBE - invalidBE < bmpCharsLE - invalidLE) return 'utf-32le';
// Couldn't decide (likely all zeros or not enough data).
return defaultEncoding || 'utf-32le';
}
/***/ }),
/***/ 794:
/***/ (function(module) {
module.exports = require("stream");
/***/ }),
/***/ 796:
/***/ (function(__unusedmodule, exports) {
"use strict";
Object.defineProperty(exports, '__esModule', { value: true });
function getUserAgent() {
if (typeof navigator === "object" && "userAgent" in navigator) {
return navigator.userAgent;
}
if (typeof process === "object" && "version" in process) {
return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`;
}
return "<environment undetectable>";
}
exports.getUserAgent = getUserAgent;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 798:
/***/ (function(module, __unusedexports, __webpack_require__) {
"use strict";
var iconvLite = __webpack_require__(681);
// Expose to the world
module.exports.convert = convert;
/**
* Convert encoding of an UTF-8 string or a buffer
*
* @param {String|Buffer} str String to be converted
* @param {String} to Encoding to be converted to
* @param {String} [from='UTF-8'] Encoding to be converted from
* @return {Buffer} Encoded string
*/
function convert(str, to, from) {
from = checkEncoding(from || 'UTF-8');
to = checkEncoding(to || 'UTF-8');
str = str || '';
var result;
if (from !== 'UTF-8' && typeof str === 'string') {
str = Buffer.from(str, 'binary');
}
if (from === to) {
if (typeof str === 'string') {
result = Buffer.from(str);
} else {
result = str;
}
} else {
try {
result = convertIconvLite(str, to, from);
} catch (E) {
console.error(E);
result = str;
}
}
if (typeof result === 'string') {
result = Buffer.from(result, 'utf-8');
}
return result;
}
/**
* Convert encoding of astring with iconv-lite
*
* @param {String|Buffer} str String to be converted
* @param {String} to Encoding to be converted to
* @param {String} [from='UTF-8'] Encoding to be converted from
* @return {Buffer} Encoded string
*/
function convertIconvLite(str, to, from) {
if (to === 'UTF-8') {
return iconvLite.decode(str, from);
} else if (from === 'UTF-8') {
return iconvLite.encode(str, to);
} else {
return iconvLite.encode(iconvLite.decode(str, from), to);
}
}
/**
* Converts charset name if needed
*
* @param {String} name Character set
* @return {String} Character set name
*/
function checkEncoding(name) {
return (name || '')
.toString()
.trim()
.replace(/^latin[\-_]?(\d+)$/i, 'ISO-8859-$1')
.replace(/^win(?:dows)?[\-_]?(\d+)$/i, 'WINDOWS-$1')
.replace(/^utf[\-_]?(\d+)$/i, 'UTF-$1')
.replace(/^ks_c_5601\-1987$/i, 'CP949')
.replace(/^us[\-_]?ascii$/i, 'ASCII')
.toUpperCase();
}
/***/ }),
/***/ 806:
/***/ (function(module, __unusedexports, __webpack_require__) {
"use strict";
const constants = __webpack_require__(199);
const utils = __webpack_require__(265);
/**
* Constants
*/
const {
MAX_LENGTH,
POSIX_REGEX_SOURCE,
REGEX_NON_SPECIAL_CHARS,
REGEX_SPECIAL_CHARS_BACKREF,
REPLACEMENTS
} = constants;
/**
* Helpers
*/
const expandRange = (args, options) => {
if (typeof options.expandRange === 'function') {
return options.expandRange(...args, options);
}
args.sort();
const value = `[${args.join('-')}]`;
try {
/* eslint-disable-next-line no-new */
new RegExp(value);
} catch (ex) {
return args.map(v => utils.escapeRegex(v)).join('..');
}
return value;
};
/**
* Create the message for a syntax error
*/
const syntaxError = (type, char) => {
return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
};
/**
* Parse the given input string.
* @param {String} input
* @param {Object} options
* @return {Object}
*/
const parse = (input, options) => {
if (typeof input !== 'string') {
throw new TypeError('Expected a string');
}
input = REPLACEMENTS[input] || input;
const opts = { ...options };
const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
let len = input.length;
if (len > max) {
throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
}
const bos = { type: 'bos', value: '', output: opts.prepend || '' };
const tokens = [bos];
const capture = opts.capture ? '' : '?:';
const win32 = utils.isWindows(options);
// create constants based on platform, for windows or posix
const PLATFORM_CHARS = constants.globChars(win32);
const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS);
const {
DOT_LITERAL,
PLUS_LITERAL,
SLASH_LITERAL,
ONE_CHAR,
DOTS_SLASH,
NO_DOT,
NO_DOT_SLASH,
NO_DOTS_SLASH,
QMARK,
QMARK_NO_DOT,
STAR,
START_ANCHOR
} = PLATFORM_CHARS;
const globstar = (opts) => {
return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
};
const nodot = opts.dot ? '' : NO_DOT;
const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
let star = opts.bash === true ? globstar(opts) : STAR;
if (opts.capture) {
star = `(${star})`;
}
// minimatch options support
if (typeof opts.noext === 'boolean') {
opts.noextglob = opts.noext;
}
const state = {
input,
index: -1,
start: 0,
dot: opts.dot === true,
consumed: '',
output: '',
prefix: '',
backtrack: false,
negated: false,
brackets: 0,
braces: 0,
parens: 0,
quotes: 0,
globstar: false,
tokens
};
input = utils.removePrefix(input, state);
len = input.length;
const extglobs = [];
const braces = [];
const stack = [];
let prev = bos;
let value;
/**
* Tokenizing helpers
*/
const eos = () => state.index === len - 1;
const peek = state.peek = (n = 1) => input[state.index + n];
const advance = state.advance = () => input[++state.index];
const remaining = () => input.slice(state.index + 1);
const consume = (value = '', num = 0) => {
state.consumed += value;
state.index += num;
};
const append = token => {
state.output += token.output != null ? token.output : token.value;
consume(token.value);
};
const negate = () => {
let count = 1;
while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
advance();
state.start++;
count++;
}
if (count % 2 === 0) {
return false;
}
state.negated = true;
state.start++;
return true;
};
const increment = type => {
state[type]++;
stack.push(type);
};
const decrement = type => {
state[type]--;
stack.pop();
};
/**
* Push tokens onto the tokens array. This helper speeds up
* tokenizing by 1) helping us avoid backtracking as much as possible,
* and 2) helping us avoid creating extra tokens when consecutive
* characters are plain text. This improves performance and simplifies
* lookbehinds.
*/
const push = tok => {
if (prev.type === 'globstar') {
const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
state.output = state.output.slice(0, -prev.output.length);
prev.type = 'star';
prev.value = '*';
prev.output = star;
state.output += prev.output;
}
}
if (extglobs.length && tok.type !== 'paren' && !EXTGLOB_CHARS[tok.value]) {
extglobs[extglobs.length - 1].inner += tok.value;
}
if (tok.value || tok.output) append(tok);
if (prev && prev.type === 'text' && tok.type === 'text') {
prev.value += tok.value;
prev.output = (prev.output || '') + tok.value;
return;
}
tok.prev = prev;
tokens.push(tok);
prev = tok;
};
const extglobOpen = (type, value) => {
const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
token.prev = prev;
token.parens = state.parens;
token.output = state.output;
const output = (opts.capture ? '(' : '') + token.open;
increment('parens');
push({ type, value, output: state.output ? '' : ONE_CHAR });
push({ type: 'paren', extglob: true, value: advance(), output });
extglobs.push(token);
};
const extglobClose = token => {
let output = token.close + (opts.capture ? ')' : '');
if (token.type === 'negate') {
let extglobStar = star;
if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
extglobStar = globstar(opts);
}
if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
output = token.close = `)$))${extglobStar}`;
}
if (token.prev.type === 'bos' && eos()) {
state.negatedExtglob = true;
}
}
push({ type: 'paren', extglob: true, value, output });
decrement('parens');
};
/**
* Fast paths
*/
if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
let backslashes = false;
let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
if (first === '\\') {
backslashes = true;
return m;
}
if (first === '?') {
if (esc) {
return esc + first + (rest ? QMARK.repeat(rest.length) : '');
}
if (index === 0) {
return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
}
return QMARK.repeat(chars.length);
}
if (first === '.') {
return DOT_LITERAL.repeat(chars.length);
}
if (first === '*') {
if (esc) {
return esc + first + (rest ? star : '');
}
return star;
}
return esc ? m : `\\${m}`;
});
if (backslashes === true) {
if (opts.unescape === true) {
output = output.replace(/\\/g, '');
} else {
output = output.replace(/\\+/g, m => {
return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
});
}
}
if (output === input && opts.contains === true) {
state.output = input;
return state;
}
state.output = utils.wrapOutput(output, state, options);
return state;
}
/**
* Tokenize input until we reach end-of-string
*/
while (!eos()) {
value = advance();
if (value === '\u0000') {
continue;
}
/**
* Escaped characters
*/
if (value === '\\') {
const next = peek();
if (next === '/' && opts.bash !== true) {
continue;
}
if (next === '.' || next === ';') {
continue;
}
if (!next) {
value += '\\';
push({ type: 'text', value });
continue;
}
// collapse slashes to reduce potential for exploits
const match = /^\\+/.exec(remaining());
let slashes = 0;
if (match && match[0].length > 2) {
slashes = match[0].length;
state.index += slashes;
if (slashes % 2 !== 0) {
value += '\\';
}
}
if (opts.unescape === true) {
value = advance() || '';
} else {
value += advance() || '';
}
if (state.brackets === 0) {
push({ type: 'text', value });
continue;
}
}
/**
* If we're inside a regex character class, continue
* until we reach the closing bracket.
*/
if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
if (opts.posix !== false && value === ':') {
const inner = prev.value.slice(1);
if (inner.includes('[')) {
prev.posix = true;
if (inner.includes(':')) {
const idx = prev.value.lastIndexOf('[');
const pre = prev.value.slice(0, idx);
const rest = prev.value.slice(idx + 2);
const posix = POSIX_REGEX_SOURCE[rest];
if (posix) {
prev.value = pre + posix;
state.backtrack = true;
advance();
if (!bos.output && tokens.indexOf(prev) === 1) {
bos.output = ONE_CHAR;
}
continue;
}
}
}
}
if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
value = `\\${value}`;
}
if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
value = `\\${value}`;
}
if (opts.posix === true && value === '!' && prev.value === '[') {
value = '^';
}
prev.value += value;
append({ value });
continue;
}
/**
* If we're inside a quoted string, continue
* until we reach the closing double quote.
*/
if (state.quotes === 1 && value !== '"') {
value = utils.escapeRegex(value);
prev.value += value;
append({ value });
continue;
}
/**
* Double quotes
*/
if (value === '"') {
state.quotes = state.quotes === 1 ? 0 : 1;
if (opts.keepQuotes === true) {
push({ type: 'text', value });
}
continue;
}
/**
* Parentheses
*/
if (value === '(') {
increment('parens');
push({ type: 'paren', value });
continue;
}
if (value === ')') {
if (state.parens === 0 && opts.strictBrackets === true) {
throw new SyntaxError(syntaxError('opening', '('));
}
const extglob = extglobs[extglobs.length - 1];
if (extglob && state.parens === extglob.parens + 1) {
extglobClose(extglobs.pop());
continue;
}
push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
decrement('parens');
continue;
}
/**
* Square brackets
*/
if (value === '[') {
if (opts.nobracket === true || !remaining().includes(']')) {
if (opts.nobracket !== true && opts.strictBrackets === true) {
throw new SyntaxError(syntaxError('closing', ']'));
}
value = `\\${value}`;
} else {
increment('brackets');
}
push({ type: 'bracket', value });
continue;
}
if (value === ']') {
if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
push({ type: 'text', value, output: `\\${value}` });
continue;
}
if (state.brackets === 0) {
if (opts.strictBrackets === true) {
throw new SyntaxError(syntaxError('opening', '['));
}
push({ type: 'text', value, output: `\\${value}` });
continue;
}
decrement('brackets');
const prevValue = prev.value.slice(1);
if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
value = `/${value}`;
}
prev.value += value;
append({ value });
// when literal brackets are explicitly disabled
// assume we should match with a regex character class
if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) {
continue;
}
const escaped = utils.escapeRegex(prev.value);
state.output = state.output.slice(0, -prev.value.length);
// when literal brackets are explicitly enabled
// assume we should escape the brackets to match literal characters
if (opts.literalBrackets === true) {
state.output += escaped;
prev.value = escaped;
continue;
}
// when the user specifies nothing, try to match both
prev.value = `(${capture}${escaped}|${prev.value})`;
state.output += prev.value;
continue;
}
/**
* Braces
*/
if (value === '{' && opts.nobrace !== true) {
increment('braces');
const open = {
type: 'brace',
value,
output: '(',
outputIndex: state.output.length,
tokensIndex: state.tokens.length
};
braces.push(open);
push(open);
continue;
}
if (value === '}') {
const brace = braces[braces.length - 1];
if (opts.nobrace === true || !brace) {
push({ type: 'text', value, output: value });
continue;
}
let output = ')';
if (brace.dots === true) {
const arr = tokens.slice();
const range = [];
for (let i = arr.length - 1; i >= 0; i--) {
tokens.pop();
if (arr[i].type === 'brace') {
break;
}
if (arr[i].type !== 'dots') {
range.unshift(arr[i].value);
}
}
output = expandRange(range, opts);
state.backtrack = true;
}
if (brace.comma !== true && brace.dots !== true) {
const out = state.output.slice(0, brace.outputIndex);
const toks = state.tokens.slice(brace.tokensIndex);
brace.value = brace.output = '\\{';
value = output = '\\}';
state.output = out;
for (const t of toks) {
state.output += (t.output || t.value);
}
}
push({ type: 'brace', value, output });
decrement('braces');
braces.pop();
continue;
}
/**
* Pipes
*/
if (value === '|') {
if (extglobs.length > 0) {
extglobs[extglobs.length - 1].conditions++;
}
push({ type: 'text', value });
continue;
}
/**
* Commas
*/
if (value === ',') {
let output = value;
const brace = braces[braces.length - 1];
if (brace && stack[stack.length - 1] === 'braces') {
brace.comma = true;
output = '|';
}
push({ type: 'comma', value, output });
continue;
}
/**
* Slashes
*/
if (value === '/') {
// if the beginning of the glob is "./", advance the start
// to the current index, and don't add the "./" characters
// to the state. This greatly simplifies lookbehinds when
// checking for BOS characters like "!" and "." (not "./")
if (prev.type === 'dot' && state.index === state.start + 1) {
state.start = state.index + 1;
state.consumed = '';
state.output = '';
tokens.pop();
prev = bos; // reset "prev" to the first token
continue;
}
push({ type: 'slash', value, output: SLASH_LITERAL });
continue;
}
/**
* Dots
*/
if (value === '.') {
if (state.braces > 0 && prev.type === 'dot') {
if (prev.value === '.') prev.output = DOT_LITERAL;
const brace = braces[braces.length - 1];
prev.type = 'dots';
prev.output += value;
prev.value += value;
brace.dots = true;
continue;
}
if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
push({ type: 'text', value, output: DOT_LITERAL });
continue;
}
push({ type: 'dot', value, output: DOT_LITERAL });
continue;
}
/**
* Question marks
*/
if (value === '?') {
const isGroup = prev && prev.value === '(';
if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
extglobOpen('qmark', value);
continue;
}
if (prev && prev.type === 'paren') {
const next = peek();
let output = value;
if (next === '<' && !utils.supportsLookbehinds()) {
throw new Error('Node.js v10 or higher is required for regex lookbehinds');
}
if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
output = `\\${value}`;
}
push({ type: 'text', value, output });
continue;
}
if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
push({ type: 'qmark', value, output: QMARK_NO_DOT });
continue;
}
push({ type: 'qmark', value, output: QMARK });
continue;
}
/**
* Exclamation
*/
if (value === '!') {
if (opts.noextglob !== true && peek() === '(') {
if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
extglobOpen('negate', value);
continue;
}
}
if (opts.nonegate !== true && state.index === 0) {
negate();
continue;
}
}
/**
* Plus
*/
if (value === '+') {
if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
extglobOpen('plus', value);
continue;
}
if ((prev && prev.value === '(') || opts.regex === false) {
push({ type: 'plus', value, output: PLUS_LITERAL });
continue;
}
if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
push({ type: 'plus', value });
continue;
}
push({ type: 'plus', value: PLUS_LITERAL });
continue;
}
/**
* Plain text
*/
if (value === '@') {
if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
push({ type: 'at', extglob: true, value, output: '' });
continue;
}
push({ type: 'text', value });
continue;
}
/**
* Plain text
*/
if (value !== '*') {
if (value === '$' || value === '^') {
value = `\\${value}`;
}
const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
if (match) {
value += match[0];
state.index += match[0].length;
}
push({ type: 'text', value });
continue;
}
/**
* Stars
*/
if (prev && (prev.type === 'globstar' || prev.star === true)) {
prev.type = 'star';
prev.star = true;
prev.value += value;
prev.output = star;
state.backtrack = true;
state.globstar = true;
consume(value);
continue;
}
let rest = remaining();
if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
extglobOpen('star', value);
continue;
}
if (prev.type === 'star') {
if (opts.noglobstar === true) {
consume(value);
continue;
}
const prior = prev.prev;
const before = prior.prev;
const isStart = prior.type === 'slash' || prior.type === 'bos';
const afterStar = before && (before.type === 'star' || before.type === 'globstar');
if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
push({ type: 'star', value, output: '' });
continue;
}
const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
push({ type: 'star', value, output: '' });
continue;
}
// strip consecutive `/**/`
while (rest.slice(0, 3) === '/**') {
const after = input[state.index + 4];
if (after && after !== '/') {
break;
}
rest = rest.slice(3);
consume('/**', 3);
}
if (prior.type === 'bos' && eos()) {
prev.type = 'globstar';
prev.value += value;
prev.output = globstar(opts);
state.output = prev.output;
state.globstar = true;
consume(value);
continue;
}
if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
state.output = state.output.slice(0, -(prior.output + prev.output).length);
prior.output = `(?:${prior.output}`;
prev.type = 'globstar';
prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
prev.value += value;
state.globstar = true;
state.output += prior.output + prev.output;
consume(value);
continue;
}
if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
const end = rest[1] !== void 0 ? '|$' : '';
state.output = state.output.slice(0, -(prior.output + prev.output).length);
prior.output = `(?:${prior.output}`;
prev.type = 'globstar';
prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
prev.value += value;
state.output += prior.output + prev.output;
state.globstar = true;
consume(value + advance());
push({ type: 'slash', value: '/', output: '' });
continue;
}
if (prior.type === 'bos' && rest[0] === '/') {
prev.type = 'globstar';
prev.value += value;
prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
state.output = prev.output;
state.globstar = true;
consume(value + advance());
push({ type: 'slash', value: '/', output: '' });
continue;
}
// remove single star from output
state.output = state.output.slice(0, -prev.output.length);
// reset previous token to globstar
prev.type = 'globstar';
prev.output = globstar(opts);
prev.value += value;
// reset output with globstar
state.output += prev.output;
state.globstar = true;
consume(value);
continue;
}
const token = { type: 'star', value, output: star };
if (opts.bash === true) {
token.output = '.*?';
if (prev.type === 'bos' || prev.type === 'slash') {
token.output = nodot + token.output;
}
push(token);
continue;
}
if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
token.output = value;
push(token);
continue;
}
if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
if (prev.type === 'dot') {
state.output += NO_DOT_SLASH;
prev.output += NO_DOT_SLASH;
} else if (opts.dot === true) {
state.output += NO_DOTS_SLASH;
prev.output += NO_DOTS_SLASH;
} else {
state.output += nodot;
prev.output += nodot;
}
if (peek() !== '*') {
state.output += ONE_CHAR;
prev.output += ONE_CHAR;
}
}
push(token);
}
while (state.brackets > 0) {
if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
state.output = utils.escapeLast(state.output, '[');
decrement('brackets');
}
while (state.parens > 0) {
if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
state.output = utils.escapeLast(state.output, '(');
decrement('parens');
}
while (state.braces > 0) {
if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
state.output = utils.escapeLast(state.output, '{');
decrement('braces');
}
if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
}
// rebuild the output if we had to backtrack at any point
if (state.backtrack === true) {
state.output = '';
for (const token of state.tokens) {
state.output += token.output != null ? token.output : token.value;
if (token.suffix) {
state.output += token.suffix;
}
}
}
return state;
};
/**
* Fast paths for creating regular expressions for common glob patterns.
* This can significantly speed up processing and has very little downside
* impact when none of the fast paths match.
*/
parse.fastpaths = (input, options) => {
const opts = { ...options };
const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
const len = input.length;
if (len > max) {
throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
}
input = REPLACEMENTS[input] || input;
const win32 = utils.isWindows(options);
// create constants based on platform, for windows or posix
const {
DOT_LITERAL,
SLASH_LITERAL,
ONE_CHAR,
DOTS_SLASH,
NO_DOT,
NO_DOTS,
NO_DOTS_SLASH,
STAR,
START_ANCHOR
} = constants.globChars(win32);
const nodot = opts.dot ? NO_DOTS : NO_DOT;
const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
const capture = opts.capture ? '' : '?:';
const state = { negated: false, prefix: '' };
let star = opts.bash === true ? '.*?' : STAR;
if (opts.capture) {
star = `(${star})`;
}
const globstar = (opts) => {
if (opts.noglobstar === true) return star;
return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
};
const create = str => {
switch (str) {
case '*':
return `${nodot}${ONE_CHAR}${star}`;
case '.*':
return `${DOT_LITERAL}${ONE_CHAR}${star}`;
case '*.*':
return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
case '*/*':
return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
case '**':
return nodot + globstar(opts);
case '**/*':
return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
case '**/*.*':
return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
case '**/.*':
return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
default: {
const match = /^(.*?)\.(\w+)$/.exec(str);
if (!match) return;
const source = create(match[1]);
if (!source) return;
return source + DOT_LITERAL + match[2];
}
}
};
const output = utils.removePrefix(input, state);
let source = create(output);
if (source && opts.strictSlashes !== true) {
source += `${SLASH_LITERAL}?`;
}
return source;
};
module.exports = parse;
/***/ }),
/***/ 807:
/***/ (function(__unusedmodule, exports) {
"use strict";
var BOMChar = '\uFEFF';
exports.PrependBOM = PrependBOMWrapper
function PrependBOMWrapper(encoder, options) {
this.encoder = encoder;
this.addBOM = true;
}
PrependBOMWrapper.prototype.write = function(str) {
if (this.addBOM) {
str = BOMChar + str;
this.addBOM = false;
}
return this.encoder.write(str);
}
PrependBOMWrapper.prototype.end = function() {
return this.encoder.end();
}
//------------------------------------------------------------------------------
exports.StripBOM = StripBOMWrapper;
function StripBOMWrapper(decoder, options) {
this.decoder = decoder;
this.pass = false;
this.options = options || {};
}
StripBOMWrapper.prototype.write = function(buf) {
var res = this.decoder.write(buf);
if (this.pass || !res)
return res;
if (res[0] === BOMChar) {
res = res.slice(1);
if (typeof this.options.stripBOM === 'function')
this.options.stripBOM();
}
this.pass = true;
return res;
}
StripBOMWrapper.prototype.end = function() {
return this.decoder.end();
}
/***/ }),
/***/ 813:
/***/ (function(__unusedmodule, exports) {
"use strict";
Object.defineProperty(exports, '__esModule', { value: true });
async function auth(token) {
const tokenType = token.split(/\./).length === 3 ? "app" : /^v\d+\./.test(token) ? "installation" : "oauth";
return {
type: "token",
token: token,
tokenType
};
}
/**
* Prefix token for usage in the Authorization header
*
* @param token OAuth token or JSON Web Token
*/
function withAuthorizationPrefix(token) {
if (token.split(/\./).length === 3) {
return `bearer ${token}`;
}
return `token ${token}`;
}
async function hook(token, request, route, parameters) {
const endpoint = request.endpoint.merge(route, parameters);
endpoint.headers.authorization = withAuthorizationPrefix(token);
return request(endpoint);
}
const createTokenAuth = function createTokenAuth(token) {
if (!token) {
throw new Error("[@octokit/auth-token] No token passed to createTokenAuth");
}
if (typeof token !== "string") {
throw new Error("[@octokit/auth-token] Token passed to createTokenAuth is not a string");
}
token = token.replace(/^(token|bearer) +/i, "");
return Object.assign(auth.bind(null, token), {
hook: hook.bind(null, token)
});
};
exports.createTokenAuth = createTokenAuth;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 827:
/***/ (function(module, __unusedexports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(366);
/***/ }),
/***/ 835:
/***/ (function(module) {
module.exports = require("url");
/***/ }),
/***/ 842:
/***/ (function(__unusedmodule, exports) {
"use strict";
Object.defineProperty(exports, '__esModule', { value: true });
const Endpoints = {
actions: {
addSelectedRepoToOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"],
cancelWorkflowRun: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel"],
createOrUpdateOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}"],
createOrUpdateRepoSecret: ["PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}"],
createRegistrationTokenForOrg: ["POST /orgs/{org}/actions/runners/registration-token"],
createRegistrationTokenForRepo: ["POST /repos/{owner}/{repo}/actions/runners/registration-token"],
createRemoveTokenForOrg: ["POST /orgs/{org}/actions/runners/remove-token"],
createRemoveTokenForRepo: ["POST /repos/{owner}/{repo}/actions/runners/remove-token"],
createWorkflowDispatch: ["POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches"],
deleteArtifact: ["DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"],
deleteOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}"],
deleteRepoSecret: ["DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}"],
deleteSelfHostedRunnerFromOrg: ["DELETE /orgs/{org}/actions/runners/{runner_id}"],
deleteSelfHostedRunnerFromRepo: ["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}"],
deleteWorkflowRun: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}"],
deleteWorkflowRunLogs: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs"],
downloadArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}"],
downloadJobLogsForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs"],
downloadWorkflowRunLogs: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs"],
getArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"],
getJobForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"],
getOrgPublicKey: ["GET /orgs/{org}/actions/secrets/public-key"],
getOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}"],
getRepoPublicKey: ["GET /repos/{owner}/{repo}/actions/secrets/public-key"],
getRepoSecret: ["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}"],
getSelfHostedRunnerForOrg: ["GET /orgs/{org}/actions/runners/{runner_id}"],
getSelfHostedRunnerForRepo: ["GET /repos/{owner}/{repo}/actions/runners/{runner_id}"],
getWorkflow: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"],
getWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}"],
getWorkflowRunUsage: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing"],
getWorkflowUsage: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing"],
listArtifactsForRepo: ["GET /repos/{owner}/{repo}/actions/artifacts"],
listJobsForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs"],
listOrgSecrets: ["GET /orgs/{org}/actions/secrets"],
listRepoSecrets: ["GET /repos/{owner}/{repo}/actions/secrets"],
listRepoWorkflows: ["GET /repos/{owner}/{repo}/actions/workflows"],
listRunnerApplicationsForOrg: ["GET /orgs/{org}/actions/runners/downloads"],
listRunnerApplicationsForRepo: ["GET /repos/{owner}/{repo}/actions/runners/downloads"],
listSelectedReposForOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}/repositories"],
listSelfHostedRunnersForOrg: ["GET /orgs/{org}/actions/runners"],
listSelfHostedRunnersForRepo: ["GET /repos/{owner}/{repo}/actions/runners"],
listWorkflowRunArtifacts: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts"],
listWorkflowRuns: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs"],
listWorkflowRunsForRepo: ["GET /repos/{owner}/{repo}/actions/runs"],
reRunWorkflow: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun"],
removeSelectedRepoFromOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"],
setSelectedReposForOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories"]
},
activity: {
checkRepoIsStarredByAuthenticatedUser: ["GET /user/starred/{owner}/{repo}"],
deleteRepoSubscription: ["DELETE /repos/{owner}/{repo}/subscription"],
deleteThreadSubscription: ["DELETE /notifications/threads/{thread_id}/subscription"],
getFeeds: ["GET /feeds"],
getRepoSubscription: ["GET /repos/{owner}/{repo}/subscription"],
getThread: ["GET /notifications/threads/{thread_id}"],
getThreadSubscriptionForAuthenticatedUser: ["GET /notifications/threads/{thread_id}/subscription"],
listEventsForAuthenticatedUser: ["GET /users/{username}/events"],
listNotificationsForAuthenticatedUser: ["GET /notifications"],
listOrgEventsForAuthenticatedUser: ["GET /users/{username}/events/orgs/{org}"],
listPublicEvents: ["GET /events"],
listPublicEventsForRepoNetwork: ["GET /networks/{owner}/{repo}/events"],
listPublicEventsForUser: ["GET /users/{username}/events/public"],
listPublicOrgEvents: ["GET /orgs/{org}/events"],
listReceivedEventsForUser: ["GET /users/{username}/received_events"],
listReceivedPublicEventsForUser: ["GET /users/{username}/received_events/public"],
listRepoEvents: ["GET /repos/{owner}/{repo}/events"],
listRepoNotificationsForAuthenticatedUser: ["GET /repos/{owner}/{repo}/notifications"],
listReposStarredByAuthenticatedUser: ["GET /user/starred"],
listReposStarredByUser: ["GET /users/{username}/starred"],
listReposWatchedByUser: ["GET /users/{username}/subscriptions"],
listStargazersForRepo: ["GET /repos/{owner}/{repo}/stargazers"],
listWatchedReposForAuthenticatedUser: ["GET /user/subscriptions"],
listWatchersForRepo: ["GET /repos/{owner}/{repo}/subscribers"],
markNotificationsAsRead: ["PUT /notifications"],
markRepoNotificationsAsRead: ["PUT /repos/{owner}/{repo}/notifications"],
markThreadAsRead: ["PATCH /notifications/threads/{thread_id}"],
setRepoSubscription: ["PUT /repos/{owner}/{repo}/subscription"],
setThreadSubscription: ["PUT /notifications/threads/{thread_id}/subscription"],
starRepoForAuthenticatedUser: ["PUT /user/starred/{owner}/{repo}"],
unstarRepoForAuthenticatedUser: ["DELETE /user/starred/{owner}/{repo}"]
},
apps: {
addRepoToInstallation: ["PUT /user/installations/{installation_id}/repositories/{repository_id}", {
mediaType: {
previews: ["machine-man"]
}
}],
checkToken: ["POST /applications/{client_id}/token"],
createContentAttachment: ["POST /content_references/{content_reference_id}/attachments", {
mediaType: {
previews: ["corsair"]
}
}],
createFromManifest: ["POST /app-manifests/{code}/conversions"],
createInstallationAccessToken: ["POST /app/installations/{installation_id}/access_tokens", {
mediaType: {
previews: ["machine-man"]
}
}],
deleteAuthorization: ["DELETE /applications/{client_id}/grant"],
deleteInstallation: ["DELETE /app/installations/{installation_id}", {
mediaType: {
previews: ["machine-man"]
}
}],
deleteToken: ["DELETE /applications/{client_id}/token"],
getAuthenticated: ["GET /app", {
mediaType: {
previews: ["machine-man"]
}
}],
getBySlug: ["GET /apps/{app_slug}", {
mediaType: {
previews: ["machine-man"]
}
}],
getInstallation: ["GET /app/installations/{installation_id}", {
mediaType: {
previews: ["machine-man"]
}
}],
getOrgInstallation: ["GET /orgs/{org}/installation", {
mediaType: {
previews: ["machine-man"]
}
}],
getRepoInstallation: ["GET /repos/{owner}/{repo}/installation", {
mediaType: {
previews: ["machine-man"]
}
}],
getSubscriptionPlanForAccount: ["GET /marketplace_listing/accounts/{account_id}"],
getSubscriptionPlanForAccountStubbed: ["GET /marketplace_listing/stubbed/accounts/{account_id}"],
getUserInstallation: ["GET /users/{username}/installation", {
mediaType: {
previews: ["machine-man"]
}
}],
listAccountsForPlan: ["GET /marketplace_listing/plans/{plan_id}/accounts"],
listAccountsForPlanStubbed: ["GET /marketplace_listing/stubbed/plans/{plan_id}/accounts"],
listInstallationReposForAuthenticatedUser: ["GET /user/installations/{installation_id}/repositories", {
mediaType: {
previews: ["machine-man"]
}
}],
listInstallations: ["GET /app/installations", {
mediaType: {
previews: ["machine-man"]
}
}],
listInstallationsForAuthenticatedUser: ["GET /user/installations", {
mediaType: {
previews: ["machine-man"]
}
}],
listPlans: ["GET /marketplace_listing/plans"],
listPlansStubbed: ["GET /marketplace_listing/stubbed/plans"],
listReposAccessibleToInstallation: ["GET /installation/repositories", {
mediaType: {
previews: ["machine-man"]
}
}],
listSubscriptionsForAuthenticatedUser: ["GET /user/marketplace_purchases"],
listSubscriptionsForAuthenticatedUserStubbed: ["GET /user/marketplace_purchases/stubbed"],
removeRepoFromInstallation: ["DELETE /user/installations/{installation_id}/repositories/{repository_id}", {
mediaType: {
previews: ["machine-man"]
}
}],
resetToken: ["PATCH /applications/{client_id}/token"],
revokeInstallationAccessToken: ["DELETE /installation/token"],
suspendInstallation: ["PUT /app/installations/{installation_id}/suspended"],
unsuspendInstallation: ["DELETE /app/installations/{installation_id}/suspended"]
},
billing: {
getGithubActionsBillingOrg: ["GET /orgs/{org}/settings/billing/actions"],
getGithubActionsBillingUser: ["GET /users/{username}/settings/billing/actions"],
getGithubPackagesBillingOrg: ["GET /orgs/{org}/settings/billing/packages"],
getGithubPackagesBillingUser: ["GET /users/{username}/settings/billing/packages"],
getSharedStorageBillingOrg: ["GET /orgs/{org}/settings/billing/shared-storage"],
getSharedStorageBillingUser: ["GET /users/{username}/settings/billing/shared-storage"]
},
checks: {
create: ["POST /repos/{owner}/{repo}/check-runs", {
mediaType: {
previews: ["antiope"]
}
}],
createSuite: ["POST /repos/{owner}/{repo}/check-suites", {
mediaType: {
previews: ["antiope"]
}
}],
get: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}", {
mediaType: {
previews: ["antiope"]
}
}],
getSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}", {
mediaType: {
previews: ["antiope"]
}
}],
listAnnotations: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations", {
mediaType: {
previews: ["antiope"]
}
}],
listForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-runs", {
mediaType: {
previews: ["antiope"]
}
}],
listForSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs", {
mediaType: {
previews: ["antiope"]
}
}],
listSuitesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-suites", {
mediaType: {
previews: ["antiope"]
}
}],
rerequestSuite: ["POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest", {
mediaType: {
previews: ["antiope"]
}
}],
setSuitesPreferences: ["PATCH /repos/{owner}/{repo}/check-suites/preferences", {
mediaType: {
previews: ["antiope"]
}
}],
update: ["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}", {
mediaType: {
previews: ["antiope"]
}
}]
},
codeScanning: {
getAlert: ["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_id}"],
listAlertsForRepo: ["GET /repos/{owner}/{repo}/code-scanning/alerts"]
},
codesOfConduct: {
getAllCodesOfConduct: ["GET /codes_of_conduct", {
mediaType: {
previews: ["scarlet-witch"]
}
}],
getConductCode: ["GET /codes_of_conduct/{key}", {
mediaType: {
previews: ["scarlet-witch"]
}
}],
getForRepo: ["GET /repos/{owner}/{repo}/community/code_of_conduct", {
mediaType: {
previews: ["scarlet-witch"]
}
}]
},
emojis: {
get: ["GET /emojis"]
},
gists: {
checkIsStarred: ["GET /gists/{gist_id}/star"],
create: ["POST /gists"],
createComment: ["POST /gists/{gist_id}/comments"],
delete: ["DELETE /gists/{gist_id}"],
deleteComment: ["DELETE /gists/{gist_id}/comments/{comment_id}"],
fork: ["POST /gists/{gist_id}/forks"],
get: ["GET /gists/{gist_id}"],
getComment: ["GET /gists/{gist_id}/comments/{comment_id}"],
getRevision: ["GET /gists/{gist_id}/{sha}"],
list: ["GET /gists"],
listComments: ["GET /gists/{gist_id}/comments"],
listCommits: ["GET /gists/{gist_id}/commits"],
listForUser: ["GET /users/{username}/gists"],
listForks: ["GET /gists/{gist_id}/forks"],
listPublic: ["GET /gists/public"],
listStarred: ["GET /gists/starred"],
star: ["PUT /gists/{gist_id}/star"],
unstar: ["DELETE /gists/{gist_id}/star"],
update: ["PATCH /gists/{gist_id}"],
updateComment: ["PATCH /gists/{gist_id}/comments/{comment_id}"]
},
git: {
createBlob: ["POST /repos/{owner}/{repo}/git/blobs"],
createCommit: ["POST /repos/{owner}/{repo}/git/commits"],
createRef: ["POST /repos/{owner}/{repo}/git/refs"],
createTag: ["POST /repos/{owner}/{repo}/git/tags"],
createTree: ["POST /repos/{owner}/{repo}/git/trees"],
deleteRef: ["DELETE /repos/{owner}/{repo}/git/refs/{ref}"],
getBlob: ["GET /repos/{owner}/{repo}/git/blobs/{file_sha}"],
getCommit: ["GET /repos/{owner}/{repo}/git/commits/{commit_sha}"],
getRef: ["GET /repos/{owner}/{repo}/git/ref/{ref}"],
getTag: ["GET /repos/{owner}/{repo}/git/tags/{tag_sha}"],
getTree: ["GET /repos/{owner}/{repo}/git/trees/{tree_sha}"],
listMatchingRefs: ["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"],
updateRef: ["PATCH /repos/{owner}/{repo}/git/refs/{ref}"]
},
gitignore: {
getAllTemplates: ["GET /gitignore/templates"],
getTemplate: ["GET /gitignore/templates/{name}"]
},
interactions: {
getRestrictionsForOrg: ["GET /orgs/{org}/interaction-limits", {
mediaType: {
previews: ["sombra"]
}
}],
getRestrictionsForRepo: ["GET /repos/{owner}/{repo}/interaction-limits", {
mediaType: {
previews: ["sombra"]
}
}],
removeRestrictionsForOrg: ["DELETE /orgs/{org}/interaction-limits", {
mediaType: {
previews: ["sombra"]
}
}],
removeRestrictionsForRepo: ["DELETE /repos/{owner}/{repo}/interaction-limits", {
mediaType: {
previews: ["sombra"]
}
}],
setRestrictionsForOrg: ["PUT /orgs/{org}/interaction-limits", {
mediaType: {
previews: ["sombra"]
}
}],
setRestrictionsForRepo: ["PUT /repos/{owner}/{repo}/interaction-limits", {
mediaType: {
previews: ["sombra"]
}
}]
},
issues: {
addAssignees: ["POST /repos/{owner}/{repo}/issues/{issue_number}/assignees"],
addLabels: ["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"],
checkUserCanBeAssigned: ["GET /repos/{owner}/{repo}/assignees/{assignee}"],
create: ["POST /repos/{owner}/{repo}/issues"],
createComment: ["POST /repos/{owner}/{repo}/issues/{issue_number}/comments"],
createLabel: ["POST /repos/{owner}/{repo}/labels"],
createMilestone: ["POST /repos/{owner}/{repo}/milestones"],
deleteComment: ["DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}"],
deleteLabel: ["DELETE /repos/{owner}/{repo}/labels/{name}"],
deleteMilestone: ["DELETE /repos/{owner}/{repo}/milestones/{milestone_number}"],
get: ["GET /repos/{owner}/{repo}/issues/{issue_number}"],
getComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}"],
getEvent: ["GET /repos/{owner}/{repo}/issues/events/{event_id}"],
getLabel: ["GET /repos/{owner}/{repo}/labels/{name}"],
getMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}"],
list: ["GET /issues"],
listAssignees: ["GET /repos/{owner}/{repo}/assignees"],
listComments: ["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"],
listCommentsForRepo: ["GET /repos/{owner}/{repo}/issues/comments"],
listEvents: ["GET /repos/{owner}/{repo}/issues/{issue_number}/events"],
listEventsForRepo: ["GET /repos/{owner}/{repo}/issues/events"],
listEventsForTimeline: ["GET /repos/{owner}/{repo}/issues/{issue_number}/timeline", {
mediaType: {
previews: ["mockingbird"]
}
}],
listForAuthenticatedUser: ["GET /user/issues"],
listForOrg: ["GET /orgs/{org}/issues"],
listForRepo: ["GET /repos/{owner}/{repo}/issues"],
listLabelsForMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels"],
listLabelsForRepo: ["GET /repos/{owner}/{repo}/labels"],
listLabelsOnIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/labels"],
listMilestones: ["GET /repos/{owner}/{repo}/milestones"],
lock: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/lock"],
removeAllLabels: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels"],
removeAssignees: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees"],
removeLabel: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}"],
setLabels: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels"],
unlock: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock"],
update: ["PATCH /repos/{owner}/{repo}/issues/{issue_number}"],
updateComment: ["PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}"],
updateLabel: ["PATCH /repos/{owner}/{repo}/labels/{name}"],
updateMilestone: ["PATCH /repos/{owner}/{repo}/milestones/{milestone_number}"]
},
licenses: {
get: ["GET /licenses/{license}"],
getAllCommonlyUsed: ["GET /licenses"],
getForRepo: ["GET /repos/{owner}/{repo}/license"]
},
markdown: {
render: ["POST /markdown"],
renderRaw: ["POST /markdown/raw", {
headers: {
"content-type": "text/plain; charset=utf-8"
}
}]
},
meta: {
get: ["GET /meta"]
},
migrations: {
cancelImport: ["DELETE /repos/{owner}/{repo}/import"],
deleteArchiveForAuthenticatedUser: ["DELETE /user/migrations/{migration_id}/archive", {
mediaType: {
previews: ["wyandotte"]
}
}],
deleteArchiveForOrg: ["DELETE /orgs/{org}/migrations/{migration_id}/archive", {
mediaType: {
previews: ["wyandotte"]
}
}],
downloadArchiveForOrg: ["GET /orgs/{org}/migrations/{migration_id}/archive", {
mediaType: {
previews: ["wyandotte"]
}
}],
getArchiveForAuthenticatedUser: ["GET /user/migrations/{migration_id}/archive", {
mediaType: {
previews: ["wyandotte"]
}
}],
getCommitAuthors: ["GET /repos/{owner}/{repo}/import/authors"],
getImportStatus: ["GET /repos/{owner}/{repo}/import"],
getLargeFiles: ["GET /repos/{owner}/{repo}/import/large_files"],
getStatusForAuthenticatedUser: ["GET /user/migrations/{migration_id}", {
mediaType: {
previews: ["wyandotte"]
}
}],
getStatusForOrg: ["GET /orgs/{org}/migrations/{migration_id}", {
mediaType: {
previews: ["wyandotte"]
}
}],
listForAuthenticatedUser: ["GET /user/migrations", {
mediaType: {
previews: ["wyandotte"]
}
}],
listForOrg: ["GET /orgs/{org}/migrations", {
mediaType: {
previews: ["wyandotte"]
}
}],
listReposForOrg: ["GET /orgs/{org}/migrations/{migration_id}/repositories", {
mediaType: {
previews: ["wyandotte"]
}
}],
listReposForUser: ["GET /user/migrations/{migration_id}/repositories", {
mediaType: {
previews: ["wyandotte"]
}
}],
mapCommitAuthor: ["PATCH /repos/{owner}/{repo}/import/authors/{author_id}"],
setLfsPreference: ["PATCH /repos/{owner}/{repo}/import/lfs"],
startForAuthenticatedUser: ["POST /user/migrations"],
startForOrg: ["POST /orgs/{org}/migrations"],
startImport: ["PUT /repos/{owner}/{repo}/import"],
unlockRepoForAuthenticatedUser: ["DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock", {
mediaType: {
previews: ["wyandotte"]
}
}],
unlockRepoForOrg: ["DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock", {
mediaType: {
previews: ["wyandotte"]
}
}],
updateImport: ["PATCH /repos/{owner}/{repo}/import"]
},
orgs: {
blockUser: ["PUT /orgs/{org}/blocks/{username}"],
checkBlockedUser: ["GET /orgs/{org}/blocks/{username}"],
checkMembershipForUser: ["GET /orgs/{org}/members/{username}"],
checkPublicMembershipForUser: ["GET /orgs/{org}/public_members/{username}"],
convertMemberToOutsideCollaborator: ["PUT /orgs/{org}/outside_collaborators/{username}"],
createInvitation: ["POST /orgs/{org}/invitations"],
createWebhook: ["POST /orgs/{org}/hooks"],
deleteWebhook: ["DELETE /orgs/{org}/hooks/{hook_id}"],
get: ["GET /orgs/{org}"],
getMembershipForAuthenticatedUser: ["GET /user/memberships/orgs/{org}"],
getMembershipForUser: ["GET /orgs/{org}/memberships/{username}"],
getWebhook: ["GET /orgs/{org}/hooks/{hook_id}"],
list: ["GET /organizations"],
listAppInstallations: ["GET /orgs/{org}/installations", {
mediaType: {
previews: ["machine-man"]
}
}],
listBlockedUsers: ["GET /orgs/{org}/blocks"],
listForAuthenticatedUser: ["GET /user/orgs"],
listForUser: ["GET /users/{username}/orgs"],
listInvitationTeams: ["GET /orgs/{org}/invitations/{invitation_id}/teams"],
listMembers: ["GET /orgs/{org}/members"],
listMembershipsForAuthenticatedUser: ["GET /user/memberships/orgs"],
listOutsideCollaborators: ["GET /orgs/{org}/outside_collaborators"],
listPendingInvitations: ["GET /orgs/{org}/invitations"],
listPublicMembers: ["GET /orgs/{org}/public_members"],
listWebhooks: ["GET /orgs/{org}/hooks"],
pingWebhook: ["POST /orgs/{org}/hooks/{hook_id}/pings"],
removeMember: ["DELETE /orgs/{org}/members/{username}"],
removeMembershipForUser: ["DELETE /orgs/{org}/memberships/{username}"],
removeOutsideCollaborator: ["DELETE /orgs/{org}/outside_collaborators/{username}"],
removePublicMembershipForAuthenticatedUser: ["DELETE /orgs/{org}/public_members/{username}"],
setMembershipForUser: ["PUT /orgs/{org}/memberships/{username}"],
setPublicMembershipForAuthenticatedUser: ["PUT /orgs/{org}/public_members/{username}"],
unblockUser: ["DELETE /orgs/{org}/blocks/{username}"],
update: ["PATCH /orgs/{org}"],
updateMembershipForAuthenticatedUser: ["PATCH /user/memberships/orgs/{org}"],
updateWebhook: ["PATCH /orgs/{org}/hooks/{hook_id}"]
},
projects: {
addCollaborator: ["PUT /projects/{project_id}/collaborators/{username}", {
mediaType: {
previews: ["inertia"]
}
}],
createCard: ["POST /projects/columns/{column_id}/cards", {
mediaType: {
previews: ["inertia"]
}
}],
createColumn: ["POST /projects/{project_id}/columns", {
mediaType: {
previews: ["inertia"]
}
}],
createForAuthenticatedUser: ["POST /user/projects", {
mediaType: {
previews: ["inertia"]
}
}],
createForOrg: ["POST /orgs/{org}/projects", {
mediaType: {
previews: ["inertia"]
}
}],
createForRepo: ["POST /repos/{owner}/{repo}/projects", {
mediaType: {
previews: ["inertia"]
}
}],
delete: ["DELETE /projects/{project_id}", {
mediaType: {
previews: ["inertia"]
}
}],
deleteCard: ["DELETE /projects/columns/cards/{card_id}", {
mediaType: {
previews: ["inertia"]
}
}],
deleteColumn: ["DELETE /projects/columns/{column_id}", {
mediaType: {
previews: ["inertia"]
}
}],
get: ["GET /projects/{project_id}", {
mediaType: {
previews: ["inertia"]
}
}],
getCard: ["GET /projects/columns/cards/{card_id}", {
mediaType: {
previews: ["inertia"]
}
}],
getColumn: ["GET /projects/columns/{column_id}", {
mediaType: {
previews: ["inertia"]
}
}],
getPermissionForUser: ["GET /projects/{project_id}/collaborators/{username}/permission", {
mediaType: {
previews: ["inertia"]
}
}],
listCards: ["GET /projects/columns/{column_id}/cards", {
mediaType: {
previews: ["inertia"]
}
}],
listCollaborators: ["GET /projects/{project_id}/collaborators", {
mediaType: {
previews: ["inertia"]
}
}],
listColumns: ["GET /projects/{project_id}/columns", {
mediaType: {
previews: ["inertia"]
}
}],
listForOrg: ["GET /orgs/{org}/projects", {
mediaType: {
previews: ["inertia"]
}
}],
listForRepo: ["GET /repos/{owner}/{repo}/projects", {
mediaType: {
previews: ["inertia"]
}
}],
listForUser: ["GET /users/{username}/projects", {
mediaType: {
previews: ["inertia"]
}
}],
moveCard: ["POST /projects/columns/cards/{card_id}/moves", {
mediaType: {
previews: ["inertia"]
}
}],
moveColumn: ["POST /projects/columns/{column_id}/moves", {
mediaType: {
previews: ["inertia"]
}
}],
removeCollaborator: ["DELETE /projects/{project_id}/collaborators/{username}", {
mediaType: {
previews: ["inertia"]
}
}],
update: ["PATCH /projects/{project_id}", {
mediaType: {
previews: ["inertia"]
}
}],
updateCard: ["PATCH /projects/columns/cards/{card_id}", {
mediaType: {
previews: ["inertia"]
}
}],
updateColumn: ["PATCH /projects/columns/{column_id}", {
mediaType: {
previews: ["inertia"]
}
}]
},
pulls: {
checkIfMerged: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"],
create: ["POST /repos/{owner}/{repo}/pulls"],
createReplyForReviewComment: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies"],
createReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews"],
createReviewComment: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments"],
deletePendingReview: ["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"],
deleteReviewComment: ["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}"],
dismissReview: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals"],
get: ["GET /repos/{owner}/{repo}/pulls/{pull_number}"],
getReview: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"],
getReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}"],
list: ["GET /repos/{owner}/{repo}/pulls"],
listCommentsForReview: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments"],
listCommits: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"],
listFiles: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"],
listRequestedReviewers: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"],
listReviewComments: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/comments"],
listReviewCommentsForRepo: ["GET /repos/{owner}/{repo}/pulls/comments"],
listReviews: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"],
merge: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge"],
removeRequestedReviewers: ["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"],
requestReviewers: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"],
submitReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events"],
update: ["PATCH /repos/{owner}/{repo}/pulls/{pull_number}"],
updateBranch: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch", {
mediaType: {
previews: ["lydian"]
}
}],
updateReview: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"],
updateReviewComment: ["PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}"]
},
rateLimit: {
get: ["GET /rate_limit"]
},
reactions: {
createForCommitComment: ["POST /repos/{owner}/{repo}/comments/{comment_id}/reactions", {
mediaType: {
previews: ["squirrel-girl"]
}
}],
createForIssue: ["POST /repos/{owner}/{repo}/issues/{issue_number}/reactions", {
mediaType: {
previews: ["squirrel-girl"]
}
}],
createForIssueComment: ["POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", {
mediaType: {
previews: ["squirrel-girl"]
}
}],
createForPullRequestReviewComment: ["POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", {
mediaType: {
previews: ["squirrel-girl"]
}
}],
createForTeamDiscussionCommentInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", {
mediaType: {
previews: ["squirrel-girl"]
}
}],
createForTeamDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", {
mediaType: {
previews: ["squirrel-girl"]
}
}],
deleteForCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}", {
mediaType: {
previews: ["squirrel-girl"]
}
}],
deleteForIssue: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}", {
mediaType: {
previews: ["squirrel-girl"]
}
}],
deleteForIssueComment: ["DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}", {
mediaType: {
previews: ["squirrel-girl"]
}
}],
deleteForPullRequestComment: ["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}", {
mediaType: {
previews: ["squirrel-girl"]
}
}],
deleteForTeamDiscussion: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}", {
mediaType: {
previews: ["squirrel-girl"]
}
}],
deleteForTeamDiscussionComment: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}", {
mediaType: {
previews: ["squirrel-girl"]
}
}],
deleteLegacy: ["DELETE /reactions/{reaction_id}", {
mediaType: {
previews: ["squirrel-girl"]
}
}, {
deprecated: "octokit.reactions.deleteLegacy() is deprecated, see https://developer.github.com/v3/reactions/#delete-a-reaction-legacy"
}],
listForCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}/reactions", {
mediaType: {
previews: ["squirrel-girl"]
}
}],
listForIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions", {
mediaType: {
previews: ["squirrel-girl"]
}
}],
listForIssueComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", {
mediaType: {
previews: ["squirrel-girl"]
}
}],
listForPullRequestReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", {
mediaType: {
previews: ["squirrel-girl"]
}
}],
listForTeamDiscussionCommentInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", {
mediaType: {
previews: ["squirrel-girl"]
}
}],
listForTeamDiscussionInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", {
mediaType: {
previews: ["squirrel-girl"]
}
}]
},
repos: {
acceptInvitation: ["PATCH /user/repository_invitations/{invitation_id}"],
addAppAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, {
mapToData: "apps"
}],
addCollaborator: ["PUT /repos/{owner}/{repo}/collaborators/{username}"],
addStatusCheckContexts: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, {
mapToData: "contexts"
}],
addTeamAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, {
mapToData: "teams"
}],
addUserAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, {
mapToData: "users"
}],
checkCollaborator: ["GET /repos/{owner}/{repo}/collaborators/{username}"],
checkVulnerabilityAlerts: ["GET /repos/{owner}/{repo}/vulnerability-alerts", {
mediaType: {
previews: ["dorian"]
}
}],
compareCommits: ["GET /repos/{owner}/{repo}/compare/{base}...{head}"],
createCommitComment: ["POST /repos/{owner}/{repo}/commits/{commit_sha}/comments"],
createCommitSignatureProtection: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures", {
mediaType: {
previews: ["zzzax"]
}
}],
createCommitStatus: ["POST /repos/{owner}/{repo}/statuses/{sha}"],
createDeployKey: ["POST /repos/{owner}/{repo}/keys"],
createDeployment: ["POST /repos/{owner}/{repo}/deployments"],
createDeploymentStatus: ["POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"],
createDispatchEvent: ["POST /repos/{owner}/{repo}/dispatches"],
createForAuthenticatedUser: ["POST /user/repos"],
createFork: ["POST /repos/{owner}/{repo}/forks"],
createInOrg: ["POST /orgs/{org}/repos"],
createOrUpdateFileContents: ["PUT /repos/{owner}/{repo}/contents/{path}"],
createPagesSite: ["POST /repos/{owner}/{repo}/pages", {
mediaType: {
previews: ["switcheroo"]
}
}],
createRelease: ["POST /repos/{owner}/{repo}/releases"],
createUsingTemplate: ["POST /repos/{template_owner}/{template_repo}/generate", {
mediaType: {
previews: ["baptiste"]
}
}],
createWebhook: ["POST /repos/{owner}/{repo}/hooks"],
declineInvitation: ["DELETE /user/repository_invitations/{invitation_id}"],
delete: ["DELETE /repos/{owner}/{repo}"],
deleteAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"],
deleteAdminBranchProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"],
deleteBranchProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection"],
deleteCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}"],
deleteCommitSignatureProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures", {
mediaType: {
previews: ["zzzax"]
}
}],
deleteDeployKey: ["DELETE /repos/{owner}/{repo}/keys/{key_id}"],
deleteDeployment: ["DELETE /repos/{owner}/{repo}/deployments/{deployment_id}"],
deleteFile: ["DELETE /repos/{owner}/{repo}/contents/{path}"],
deleteInvitation: ["DELETE /repos/{owner}/{repo}/invitations/{invitation_id}"],
deletePagesSite: ["DELETE /repos/{owner}/{repo}/pages", {
mediaType: {
previews: ["switcheroo"]
}
}],
deletePullRequestReviewProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"],
deleteRelease: ["DELETE /repos/{owner}/{repo}/releases/{release_id}"],
deleteReleaseAsset: ["DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}"],
deleteWebhook: ["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"],
disableAutomatedSecurityFixes: ["DELETE /repos/{owner}/{repo}/automated-security-fixes", {
mediaType: {
previews: ["london"]
}
}],
disableVulnerabilityAlerts: ["DELETE /repos/{owner}/{repo}/vulnerability-alerts", {
mediaType: {
previews: ["dorian"]
}
}],
downloadArchive: ["GET /repos/{owner}/{repo}/{archive_format}/{ref}"],
enableAutomatedSecurityFixes: ["PUT /repos/{owner}/{repo}/automated-security-fixes", {
mediaType: {
previews: ["london"]
}
}],
enableVulnerabilityAlerts: ["PUT /repos/{owner}/{repo}/vulnerability-alerts", {
mediaType: {
previews: ["dorian"]
}
}],
get: ["GET /repos/{owner}/{repo}"],
getAccessRestrictions: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"],
getAdminBranchProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"],
getAllStatusCheckContexts: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts"],
getAllTopics: ["GET /repos/{owner}/{repo}/topics", {
mediaType: {
previews: ["mercy"]
}
}],
getAppsWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps"],
getBranch: ["GET /repos/{owner}/{repo}/branches/{branch}"],
getBranchProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection"],
getClones: ["GET /repos/{owner}/{repo}/traffic/clones"],
getCodeFrequencyStats: ["GET /repos/{owner}/{repo}/stats/code_frequency"],
getCollaboratorPermissionLevel: ["GET /repos/{owner}/{repo}/collaborators/{username}/permission"],
getCombinedStatusForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/status"],
getCommit: ["GET /repos/{owner}/{repo}/commits/{ref}"],
getCommitActivityStats: ["GET /repos/{owner}/{repo}/stats/commit_activity"],
getCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}"],
getCommitSignatureProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures", {
mediaType: {
previews: ["zzzax"]
}
}],
getCommunityProfileMetrics: ["GET /repos/{owner}/{repo}/community/profile", {
mediaType: {
previews: ["black-panther"]
}
}],
getContent: ["GET /repos/{owner}/{repo}/contents/{path}"],
getContributorsStats: ["GET /repos/{owner}/{repo}/stats/contributors"],
getDeployKey: ["GET /repos/{owner}/{repo}/keys/{key_id}"],
getDeployment: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}"],
getDeploymentStatus: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}"],
getLatestPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/latest"],
getLatestRelease: ["GET /repos/{owner}/{repo}/releases/latest"],
getPages: ["GET /repos/{owner}/{repo}/pages"],
getPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/{build_id}"],
getParticipationStats: ["GET /repos/{owner}/{repo}/stats/participation"],
getPullRequestReviewProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"],
getPunchCardStats: ["GET /repos/{owner}/{repo}/stats/punch_card"],
getReadme: ["GET /repos/{owner}/{repo}/readme"],
getRelease: ["GET /repos/{owner}/{repo}/releases/{release_id}"],
getReleaseAsset: ["GET /repos/{owner}/{repo}/releases/assets/{asset_id}"],
getReleaseByTag: ["GET /repos/{owner}/{repo}/releases/tags/{tag}"],
getStatusChecksProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"],
getTeamsWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams"],
getTopPaths: ["GET /repos/{owner}/{repo}/traffic/popular/paths"],
getTopReferrers: ["GET /repos/{owner}/{repo}/traffic/popular/referrers"],
getUsersWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users"],
getViews: ["GET /repos/{owner}/{repo}/traffic/views"],
getWebhook: ["GET /repos/{owner}/{repo}/hooks/{hook_id}"],
listBranches: ["GET /repos/{owner}/{repo}/branches"],
listBranchesForHeadCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head", {
mediaType: {
previews: ["groot"]
}
}],
listCollaborators: ["GET /repos/{owner}/{repo}/collaborators"],
listCommentsForCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/comments"],
listCommitCommentsForRepo: ["GET /repos/{owner}/{repo}/comments"],
listCommitStatusesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/statuses"],
listCommits: ["GET /repos/{owner}/{repo}/commits"],
listContributors: ["GET /repos/{owner}/{repo}/contributors"],
listDeployKeys: ["GET /repos/{owner}/{repo}/keys"],
listDeploymentStatuses: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"],
listDeployments: ["GET /repos/{owner}/{repo}/deployments"],
listForAuthenticatedUser: ["GET /user/repos"],
listForOrg: ["GET /orgs/{org}/repos"],
listForUser: ["GET /users/{username}/repos"],
listForks: ["GET /repos/{owner}/{repo}/forks"],
listInvitations: ["GET /repos/{owner}/{repo}/invitations"],
listInvitationsForAuthenticatedUser: ["GET /user/repository_invitations"],
listLanguages: ["GET /repos/{owner}/{repo}/languages"],
listPagesBuilds: ["GET /repos/{owner}/{repo}/pages/builds"],
listPublic: ["GET /repositories"],
listPullRequestsAssociatedWithCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls", {
mediaType: {
previews: ["groot"]
}
}],
listReleaseAssets: ["GET /repos/{owner}/{repo}/releases/{release_id}/assets"],
listReleases: ["GET /repos/{owner}/{repo}/releases"],
listTags: ["GET /repos/{owner}/{repo}/tags"],
listTeams: ["GET /repos/{owner}/{repo}/teams"],
listWebhooks: ["GET /repos/{owner}/{repo}/hooks"],
merge: ["POST /repos/{owner}/{repo}/merges"],
pingWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"],
removeAppAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, {
mapToData: "apps"
}],
removeCollaborator: ["DELETE /repos/{owner}/{repo}/collaborators/{username}"],
removeStatusCheckContexts: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, {
mapToData: "contexts"
}],
removeStatusCheckProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"],
removeTeamAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, {
mapToData: "teams"
}],
removeUserAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, {
mapToData: "users"
}],
replaceAllTopics: ["PUT /repos/{owner}/{repo}/topics", {
mediaType: {
previews: ["mercy"]
}
}],
requestPagesBuild: ["POST /repos/{owner}/{repo}/pages/builds"],
setAdminBranchProtection: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"],
setAppAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, {
mapToData: "apps"
}],
setStatusCheckContexts: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, {
mapToData: "contexts"
}],
setTeamAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, {
mapToData: "teams"
}],
setUserAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, {
mapToData: "users"
}],
testPushWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests"],
transfer: ["POST /repos/{owner}/{repo}/transfer"],
update: ["PATCH /repos/{owner}/{repo}"],
updateBranchProtection: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection"],
updateCommitComment: ["PATCH /repos/{owner}/{repo}/comments/{comment_id}"],
updateInformationAboutPagesSite: ["PUT /repos/{owner}/{repo}/pages"],
updateInvitation: ["PATCH /repos/{owner}/{repo}/invitations/{invitation_id}"],
updatePullRequestReviewProtection: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"],
updateRelease: ["PATCH /repos/{owner}/{repo}/releases/{release_id}"],
updateReleaseAsset: ["PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}"],
updateStatusCheckPotection: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"],
updateWebhook: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"],
uploadReleaseAsset: ["POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}", {
baseUrl: "https://uploads.github.com"
}]
},
search: {
code: ["GET /search/code"],
commits: ["GET /search/commits", {
mediaType: {
previews: ["cloak"]
}
}],
issuesAndPullRequests: ["GET /search/issues"],
labels: ["GET /search/labels"],
repos: ["GET /search/repositories"],
topics: ["GET /search/topics", {
mediaType: {
previews: ["mercy"]
}
}],
users: ["GET /search/users"]
},
teams: {
addOrUpdateMembershipForUserInOrg: ["PUT /orgs/{org}/teams/{team_slug}/memberships/{username}"],
addOrUpdateProjectPermissionsInOrg: ["PUT /orgs/{org}/teams/{team_slug}/projects/{project_id}", {
mediaType: {
previews: ["inertia"]
}
}],
addOrUpdateRepoPermissionsInOrg: ["PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"],
checkPermissionsForProjectInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects/{project_id}", {
mediaType: {
previews: ["inertia"]
}
}],
checkPermissionsForRepoInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"],
create: ["POST /orgs/{org}/teams"],
createDiscussionCommentInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"],
createDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions"],
deleteDiscussionCommentInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"],
deleteDiscussionInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"],
deleteInOrg: ["DELETE /orgs/{org}/teams/{team_slug}"],
getByName: ["GET /orgs/{org}/teams/{team_slug}"],
getDiscussionCommentInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"],
getDiscussionInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"],
getMembershipForUserInOrg: ["GET /orgs/{org}/teams/{team_slug}/memberships/{username}"],
list: ["GET /orgs/{org}/teams"],
listChildInOrg: ["GET /orgs/{org}/teams/{team_slug}/teams"],
listDiscussionCommentsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"],
listDiscussionsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions"],
listForAuthenticatedUser: ["GET /user/teams"],
listMembersInOrg: ["GET /orgs/{org}/teams/{team_slug}/members"],
listPendingInvitationsInOrg: ["GET /orgs/{org}/teams/{team_slug}/invitations"],
listProjectsInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects", {
mediaType: {
previews: ["inertia"]
}
}],
listReposInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos"],
removeMembershipForUserInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}"],
removeProjectInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/projects/{project_id}"],
removeRepoInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"],
updateDiscussionCommentInOrg: ["PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"],
updateDiscussionInOrg: ["PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"],
updateInOrg: ["PATCH /orgs/{org}/teams/{team_slug}"]
},
users: {
addEmailForAuthenticated: ["POST /user/emails"],
block: ["PUT /user/blocks/{username}"],
checkBlocked: ["GET /user/blocks/{username}"],
checkFollowingForUser: ["GET /users/{username}/following/{target_user}"],
checkPersonIsFollowedByAuthenticated: ["GET /user/following/{username}"],
createGpgKeyForAuthenticated: ["POST /user/gpg_keys"],
createPublicSshKeyForAuthenticated: ["POST /user/keys"],
deleteEmailForAuthenticated: ["DELETE /user/emails"],
deleteGpgKeyForAuthenticated: ["DELETE /user/gpg_keys/{gpg_key_id}"],
deletePublicSshKeyForAuthenticated: ["DELETE /user/keys/{key_id}"],
follow: ["PUT /user/following/{username}"],
getAuthenticated: ["GET /user"],
getByUsername: ["GET /users/{username}"],
getContextForUser: ["GET /users/{username}/hovercard"],
getGpgKeyForAuthenticated: ["GET /user/gpg_keys/{gpg_key_id}"],
getPublicSshKeyForAuthenticated: ["GET /user/keys/{key_id}"],
list: ["GET /users"],
listBlockedByAuthenticated: ["GET /user/blocks"],
listEmailsForAuthenticated: ["GET /user/emails"],
listFollowedByAuthenticated: ["GET /user/following"],
listFollowersForAuthenticatedUser: ["GET /user/followers"],
listFollowersForUser: ["GET /users/{username}/followers"],
listFollowingForUser: ["GET /users/{username}/following"],
listGpgKeysForAuthenticated: ["GET /user/gpg_keys"],
listGpgKeysForUser: ["GET /users/{username}/gpg_keys"],
listPublicEmailsForAuthenticated: ["GET /user/public_emails"],
listPublicKeysForUser: ["GET /users/{username}/keys"],
listPublicSshKeysForAuthenticated: ["GET /user/keys"],
setPrimaryEmailVisibilityForAuthenticated: ["PATCH /user/email/visibility"],
unblock: ["DELETE /user/blocks/{username}"],
unfollow: ["DELETE /user/following/{username}"],
updateAuthenticated: ["PATCH /user"]
}
};
const VERSION = "4.1.2";
function endpointsToMethods(octokit, endpointsMap) {
const newMethods = {};
for (const [scope, endpoints] of Object.entries(endpointsMap)) {
for (const [methodName, endpoint] of Object.entries(endpoints)) {
const [route, defaults, decorations] = endpoint;
const [method, url] = route.split(/ /);
const endpointDefaults = Object.assign({
method,
url
}, defaults);
if (!newMethods[scope]) {
newMethods[scope] = {};
}
const scopeMethods = newMethods[scope];
if (decorations) {
scopeMethods[methodName] = decorate(octokit, scope, methodName, endpointDefaults, decorations);
continue;
}
scopeMethods[methodName] = octokit.request.defaults(endpointDefaults);
}
}
return newMethods;
}
function decorate(octokit, scope, methodName, defaults, decorations) {
const requestWithDefaults = octokit.request.defaults(defaults);
/* istanbul ignore next */
function withDecorations(...args) {
// @ts-ignore https://github.com/microsoft/TypeScript/issues/25488
let options = requestWithDefaults.endpoint.merge(...args); // There are currently no other decorations than `.mapToData`
if (decorations.mapToData) {
options = Object.assign({}, options, {
data: options[decorations.mapToData],
[decorations.mapToData]: undefined
});
return requestWithDefaults(options);
}
if (decorations.renamed) {
const [newScope, newMethodName] = decorations.renamed;
octokit.log.warn(`octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()`);
}
if (decorations.deprecated) {
octokit.log.warn(decorations.deprecated);
}
if (decorations.renamedParameters) {
// @ts-ignore https://github.com/microsoft/TypeScript/issues/25488
const options = requestWithDefaults.endpoint.merge(...args);
for (const [name, alias] of Object.entries(decorations.renamedParameters)) {
if (name in options) {
octokit.log.warn(`"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead`);
if (!(alias in options)) {
options[alias] = options[name];
}
delete options[name];
}
}
return requestWithDefaults(options);
} // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488
return requestWithDefaults(...args);
}
return Object.assign(withDecorations, requestWithDefaults);
}
/**
* This plugin is a 1:1 copy of internal @octokit/rest plugins. The primary
* goal is to rebuild @octokit/rest on top of @octokit/core. Once that is
* done, we will remove the registerEndpoints methods and return the methods
* directly as with the other plugins. At that point we will also remove the
* legacy workarounds and deprecations.
*
* See the plan at
* https://github.com/octokit/plugin-rest-endpoint-methods.js/pull/1
*/
function restEndpointMethods(octokit) {
return endpointsToMethods(octokit, Endpoints);
}
restEndpointMethods.VERSION = VERSION;
exports.restEndpointMethods = restEndpointMethods;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 857:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = __webpack_require__(422);
var no_case_1 = __webpack_require__(555);
function pascalCaseTransform(input, index) {
var firstChar = input.charAt(0);
var lowerChars = input.substr(1).toLowerCase();
if (index > 0 && firstChar >= "0" && firstChar <= "9") {
return "_" + firstChar + lowerChars;
}
return "" + firstChar.toUpperCase() + lowerChars;
}
exports.pascalCaseTransform = pascalCaseTransform;
function pascalCaseTransformMerge(input) {
return input.charAt(0).toUpperCase() + input.slice(1).toLowerCase();
}
exports.pascalCaseTransformMerge = pascalCaseTransformMerge;
function pascalCase(input, options) {
if (options === void 0) { options = {}; }
return no_case_1.noCase(input, tslib_1.__assign({ delimiter: "", transform: pascalCaseTransform }, options));
}
exports.pascalCase = pascalCase;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 866:
/***/ (function(module) {
module.exports = removeHook
function removeHook (state, name, method) {
if (!state.registry[name]) {
return
}
var index = state.registry[name]
.map(function (registered) { return registered.orig })
.indexOf(method)
if (index === -1) {
return
}
state.registry[name].splice(index, 1)
}
/***/ }),
/***/ 898:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, '__esModule', { value: true });
var request = __webpack_require__(753);
var universalUserAgent = __webpack_require__(796);
const VERSION = "4.5.3";
class GraphqlError extends Error {
constructor(request, response) {
const message = response.data.errors[0].message;
super(message);
Object.assign(this, response.data);
Object.assign(this, {
headers: response.headers
});
this.name = "GraphqlError";
this.request = request; // Maintains proper stack trace (only available on V8)
/* istanbul ignore next */
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}
}
const NON_VARIABLE_OPTIONS = ["method", "baseUrl", "url", "headers", "request", "query", "mediaType"];
function graphql(request, query, options) {
options = typeof query === "string" ? options = Object.assign({
query
}, options) : options = query;
const requestOptions = Object.keys(options).reduce((result, key) => {
if (NON_VARIABLE_OPTIONS.includes(key)) {
result[key] = options[key];
return result;
}
if (!result.variables) {
result.variables = {};
}
result.variables[key] = options[key];
return result;
}, {});
return request(requestOptions).then(response => {
if (response.data.errors) {
const headers = {};
for (const key of Object.keys(response.headers)) {
headers[key] = response.headers[key];
}
throw new GraphqlError(requestOptions, {
headers,
data: response.data
});
}
return response.data.data;
});
}
function withDefaults(request$1, newDefaults) {
const newRequest = request$1.defaults(newDefaults);
const newApi = (query, options) => {
return graphql(newRequest, query, options);
};
return Object.assign(newApi, {
defaults: withDefaults.bind(null, newRequest),
endpoint: request.request.endpoint
});
}
const graphql$1 = withDefaults(request.request, {
headers: {
"user-agent": `octokit-graphql.js/${VERSION} ${universalUserAgent.getUserAgent()}`
},
method: "POST",
url: "/graphql"
});
function withCustomRequest(customRequest) {
return withDefaults(customRequest, {
method: "POST",
url: "/graphql"
});
}
exports.graphql = graphql$1;
exports.withCustomRequest = withCustomRequest;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 927:
/***/ (function(module) {
module.exports = [["0","\u0000",127],["8141","갂갃갅갆갋",4,"갘갞갟갡갢갣갥",6,"갮갲갳갴"],["8161","갵갶갷갺갻갽갾갿걁",9,"걌걎",5,"걕"],["8181","걖걗걙걚걛걝",18,"걲걳걵걶걹걻",4,"겂겇겈겍겎겏겑겒겓겕",6,"겞겢",5,"겫겭겮겱",6,"겺겾겿곀곂곃곅곆곇곉곊곋곍",7,"곖곘",7,"곢곣곥곦곩곫곭곮곲곴곷",4,"곾곿괁괂괃괅괇",4,"괎괐괒괓"],["8241","괔괕괖괗괙괚괛괝괞괟괡",7,"괪괫괮",5],["8261","괶괷괹괺괻괽",6,"굆굈굊",5,"굑굒굓굕굖굗"],["8281","굙",7,"굢굤",7,"굮굯굱굲굷굸굹굺굾궀궃",4,"궊궋궍궎궏궑",10,"궞",5,"궥",17,"궸",7,"귂귃귅귆귇귉",6,"귒귔",7,"귝귞귟귡귢귣귥",18],["8341","귺귻귽귾긂",5,"긊긌긎",5,"긕",7],["8361","긝",18,"긲긳긵긶긹긻긼"],["8381","긽긾긿깂깄깇깈깉깋깏깑깒깓깕깗",4,"깞깢깣깤깦깧깪깫깭깮깯깱",6,"깺깾",5,"꺆",5,"꺍",46,"꺿껁껂껃껅",6,"껎껒",5,"껚껛껝",8],["8441","껦껧껩껪껬껮",5,"껵껶껷껹껺껻껽",8],["8461","꼆꼉꼊꼋꼌꼎꼏꼑",18],["8481","꼤",7,"꼮꼯꼱꼳꼵",6,"꼾꽀꽄꽅꽆꽇꽊",5,"꽑",10,"꽞",5,"꽦",18,"꽺",5,"꾁꾂꾃꾅꾆꾇꾉",6,"꾒꾓꾔꾖",5,"꾝",26,"꾺꾻꾽꾾"],["8541","꾿꿁",5,"꿊꿌꿏",4,"꿕",6,"꿝",4],["8561","꿢",5,"꿪",5,"꿲꿳꿵꿶꿷꿹",6,"뀂뀃"],["8581","뀅",6,"뀍뀎뀏뀑뀒뀓뀕",6,"뀞",9,"뀩",26,"끆끇끉끋끍끏끐끑끒끖끘끚끛끜끞",29,"끾끿낁낂낃낅",6,"낎낐낒",5,"낛낝낞낣낤"],["8641","낥낦낧낪낰낲낶낷낹낺낻낽",6,"냆냊",5,"냒"],["8661","냓냕냖냗냙",6,"냡냢냣냤냦",10],["8681","냱",22,"넊넍넎넏넑넔넕넖넗넚넞",4,"넦넧넩넪넫넭",6,"넶넺",5,"녂녃녅녆녇녉",6,"녒녓녖녗녙녚녛녝녞녟녡",22,"녺녻녽녾녿놁놃",4,"놊놌놎놏놐놑놕놖놗놙놚놛놝"],["8741","놞",9,"놩",15],["8761","놹",18,"뇍뇎뇏뇑뇒뇓뇕"],["8781","뇖",5,"뇞뇠",7,"뇪뇫뇭뇮뇯뇱",7,"뇺뇼뇾",5,"눆눇눉눊눍",6,"눖눘눚",5,"눡",18,"눵",6,"눽",26,"뉙뉚뉛뉝뉞뉟뉡",6,"뉪",4],["8841","뉯",4,"뉶",5,"뉽",6,"늆늇늈늊",4],["8861","늏늒늓늕늖늗늛",4,"늢늤늧늨늩늫늭늮늯늱늲늳늵늶늷"],["8881","늸",15,"닊닋닍닎닏닑닓",4,"닚닜닞닟닠닡닣닧닩닪닰닱닲닶닼닽닾댂댃댅댆댇댉",6,"댒댖",5,"댝",54,"덗덙덚덝덠덡덢덣"],["8941","덦덨덪덬덭덯덲덳덵덶덷덹",6,"뎂뎆",5,"뎍"],["8961","뎎뎏뎑뎒뎓뎕",10,"뎢",5,"뎩뎪뎫뎭"],["8981","뎮",21,"돆돇돉돊돍돏돑돒돓돖돘돚돜돞돟돡돢돣돥돦돧돩",18,"돽",18,"됑",6,"됙됚됛됝됞됟됡",6,"됪됬",7,"됵",15],["8a41","둅",10,"둒둓둕둖둗둙",6,"둢둤둦"],["8a61","둧",4,"둭",18,"뒁뒂"],["8a81","뒃",4,"뒉",19,"뒞",5,"뒥뒦뒧뒩뒪뒫뒭",7,"뒶뒸뒺",5,"듁듂듃듅듆듇듉",6,"듑듒듓듔듖",5,"듞듟듡듢듥듧",4,"듮듰듲",5,"듹",26,"딖딗딙딚딝"],["8b41","딞",5,"딦딫",4,"딲딳딵딶딷딹",6,"땂땆"],["8b61","땇땈땉땊땎땏땑땒땓땕",6,"땞땢",8],["8b81","땫",52,"떢떣떥떦떧떩떬떭떮떯떲떶",4,"떾떿뗁뗂뗃뗅",6,"뗎뗒",5,"뗙",18,"뗭",18],["8c41","똀",15,"똒똓똕똖똗똙",4],["8c61","똞",6,"똦",5,"똭",6,"똵",5],["8c81","똻",12,"뙉",26,"뙥뙦뙧뙩",50,"뚞뚟뚡뚢뚣뚥",5,"뚭뚮뚯뚰뚲",16],["8d41","뛃",16,"뛕",8],["8d61","뛞",17,"뛱뛲뛳뛵뛶뛷뛹뛺"],["8d81","뛻",4,"뜂뜃뜄뜆",33,"뜪뜫뜭뜮뜱",6,"뜺뜼",7,"띅띆띇띉띊띋띍",6,"띖",9,"띡띢띣띥띦띧띩",6,"띲띴띶",5,"띾띿랁랂랃랅",6,"랎랓랔랕랚랛랝랞"],["8e41","랟랡",6,"랪랮",5,"랶랷랹",8],["8e61","럂",4,"럈럊",19],["8e81","럞",13,"럮럯럱럲럳럵",6,"럾렂",4,"렊렋렍렎렏렑",6,"렚렜렞",5,"렦렧렩렪렫렭",6,"렶렺",5,"롁롂롃롅",11,"롒롔",7,"롞롟롡롢롣롥",6,"롮롰롲",5,"롹롺롻롽",7],["8f41","뢅",7,"뢎",17],["8f61","뢠",7,"뢩",6,"뢱뢲뢳뢵뢶뢷뢹",4],["8f81","뢾뢿룂룄룆",5,"룍룎룏룑룒룓룕",7,"룞룠룢",5,"룪룫룭룮룯룱",6,"룺룼룾",5,"뤅",18,"뤙",6,"뤡",26,"뤾뤿륁륂륃륅",6,"륍륎륐륒",5],["9041","륚륛륝륞륟륡",6,"륪륬륮",5,"륶륷륹륺륻륽"],["9061","륾",5,"릆릈릋릌릏",15],["9081","릟",12,"릮릯릱릲릳릵",6,"릾맀맂",5,"맊맋맍맓",4,"맚맜맟맠맢맦맧맩맪맫맭",6,"맶맻",4,"먂",5,"먉",11,"먖",33,"먺먻먽먾먿멁멃멄멅멆"],["9141","멇멊멌멏멐멑멒멖멗멙멚멛멝",6,"멦멪",5],["9161","멲멳멵멶멷멹",9,"몆몈몉몊몋몍",5],["9181","몓",20,"몪몭몮몯몱몳",4,"몺몼몾",5,"뫅뫆뫇뫉",14,"뫚",33,"뫽뫾뫿묁묂묃묅",7,"묎묐묒",5,"묙묚묛묝묞묟묡",6],["9241","묨묪묬",7,"묷묹묺묿",4,"뭆뭈뭊뭋뭌뭎뭑뭒"],["9261","뭓뭕뭖뭗뭙",7,"뭢뭤",7,"뭭",4],["9281","뭲",21,"뮉뮊뮋뮍뮎뮏뮑",18,"뮥뮦뮧뮩뮪뮫뮭",6,"뮵뮶뮸",7,"믁믂믃믅믆믇믉",6,"믑믒믔",35,"믺믻믽믾밁"],["9341","밃",4,"밊밎밐밒밓밙밚밠밡밢밣밦밨밪밫밬밮밯밲밳밵"],["9361","밶밷밹",6,"뱂뱆뱇뱈뱊뱋뱎뱏뱑",8],["9381","뱚뱛뱜뱞",37,"벆벇벉벊벍벏",4,"벖벘벛",4,"벢벣벥벦벩",6,"벲벶",5,"벾벿볁볂볃볅",7,"볎볒볓볔볖볗볙볚볛볝",22,"볷볹볺볻볽"],["9441","볾",5,"봆봈봊",5,"봑봒봓봕",8],["9461","봞",5,"봥",6,"봭",12],["9481","봺",5,"뵁",6,"뵊뵋뵍뵎뵏뵑",6,"뵚",9,"뵥뵦뵧뵩",22,"붂붃붅붆붋",4,"붒붔붖붗붘붛붝",6,"붥",10,"붱",6,"붹",24],["9541","뷒뷓뷖뷗뷙뷚뷛뷝",11,"뷪",5,"뷱"],["9561","뷲뷳뷵뷶뷷뷹",6,"븁븂븄븆",5,"븎븏븑븒븓"],["9581","븕",6,"븞븠",35,"빆빇빉빊빋빍빏",4,"빖빘빜빝빞빟빢빣빥빦빧빩빫",4,"빲빶",4,"빾빿뺁뺂뺃뺅",6,"뺎뺒",5,"뺚",13,"뺩",14],["9641","뺸",23,"뻒뻓"],["9661","뻕뻖뻙",6,"뻡뻢뻦",5,"뻭",8],["9681","뻶",10,"뼂",5,"뼊",13,"뼚뼞",33,"뽂뽃뽅뽆뽇뽉",6,"뽒뽓뽔뽖",44],["9741","뾃",16,"뾕",8],["9761","뾞",17,"뾱",7],["9781","뾹",11,"뿆",5,"뿎뿏뿑뿒뿓뿕",6,"뿝뿞뿠뿢",89,"쀽쀾쀿"],["9841","쁀",16,"쁒",5,"쁙쁚쁛"],["9861","쁝쁞쁟쁡",6,"쁪",15],["9881","쁺",21,"삒삓삕삖삗삙",6,"삢삤삦",5,"삮삱삲삷",4,"삾샂샃샄샆샇샊샋샍샎샏샑",6,"샚샞",5,"샦샧샩샪샫샭",6,"샶샸샺",5,"섁섂섃섅섆섇섉",6,"섑섒섓섔섖",5,"섡섢섥섨섩섪섫섮"],["9941","섲섳섴섵섷섺섻섽섾섿셁",6,"셊셎",5,"셖셗"],["9961","셙셚셛셝",6,"셦셪",5,"셱셲셳셵셶셷셹셺셻"],["9981","셼",8,"솆",5,"솏솑솒솓솕솗",4,"솞솠솢솣솤솦솧솪솫솭솮솯솱",11,"솾",5,"쇅쇆쇇쇉쇊쇋쇍",6,"쇕쇖쇙",6,"쇡쇢쇣쇥쇦쇧쇩",6,"쇲쇴",7,"쇾쇿숁숂숃숅",6,"숎숐숒",5,"숚숛숝숞숡숢숣"],["9a41","숤숥숦숧숪숬숮숰숳숵",16],["9a61","쉆쉇쉉",6,"쉒쉓쉕쉖쉗쉙",6,"쉡쉢쉣쉤쉦"],["9a81","쉧",4,"쉮쉯쉱쉲쉳쉵",6,"쉾슀슂",5,"슊",5,"슑",6,"슙슚슜슞",5,"슦슧슩슪슫슮",5,"슶슸슺",33,"싞싟싡싢싥",5,"싮싰싲싳싴싵싷싺싽싾싿쌁",6,"쌊쌋쌎쌏"],["9b41","쌐쌑쌒쌖쌗쌙쌚쌛쌝",6,"쌦쌧쌪",8],["9b61","쌳",17,"썆",7],["9b81","썎",25,"썪썫썭썮썯썱썳",4,"썺썻썾",5,"쎅쎆쎇쎉쎊쎋쎍",50,"쏁",22,"쏚"],["9c41","쏛쏝쏞쏡쏣",4,"쏪쏫쏬쏮",5,"쏶쏷쏹",5],["9c61","쏿",8,"쐉",6,"쐑",9],["9c81","쐛",8,"쐥",6,"쐭쐮쐯쐱쐲쐳쐵",6,"쐾",9,"쑉",26,"쑦쑧쑩쑪쑫쑭",6,"쑶쑷쑸쑺",5,"쒁",18,"쒕",6,"쒝",12],["9d41","쒪",13,"쒹쒺쒻쒽",8],["9d61","쓆",25],["9d81","쓠",8,"쓪",5,"쓲쓳쓵쓶쓷쓹쓻쓼쓽쓾씂",9,"씍씎씏씑씒씓씕",6,"씝",10,"씪씫씭씮씯씱",6,"씺씼씾",5,"앆앇앋앏앐앑앒앖앚앛앜앟앢앣앥앦앧앩",6,"앲앶",5,"앾앿얁얂얃얅얆얈얉얊얋얎얐얒얓얔"],["9e41","얖얙얚얛얝얞얟얡",7,"얪",9,"얶"],["9e61","얷얺얿",4,"엋엍엏엒엓엕엖엗엙",6,"엢엤엦엧"],["9e81","엨엩엪엫엯엱엲엳엵엸엹엺엻옂옃옄옉옊옋옍옎옏옑",6,"옚옝",6,"옦옧옩옪옫옯옱옲옶옸옺옼옽옾옿왂왃왅왆왇왉",6,"왒왖",5,"왞왟왡",10,"왭왮왰왲",5,"왺왻왽왾왿욁",6,"욊욌욎",5,"욖욗욙욚욛욝",6,"욦"],["9f41","욨욪",5,"욲욳욵욶욷욻",4,"웂웄웆",5,"웎"],["9f61","웏웑웒웓웕",6,"웞웟웢",5,"웪웫웭웮웯웱웲"],["9f81","웳",4,"웺웻웼웾",5,"윆윇윉윊윋윍",6,"윖윘윚",5,"윢윣윥윦윧윩",6,"윲윴윶윸윹윺윻윾윿읁읂읃읅",4,"읋읎읐읙읚읛읝읞읟읡",6,"읩읪읬",7,"읶읷읹읺읻읿잀잁잂잆잋잌잍잏잒잓잕잙잛",4,"잢잧",4,"잮잯잱잲잳잵잶잷"],["a041","잸잹잺잻잾쟂",5,"쟊쟋쟍쟏쟑",6,"쟙쟚쟛쟜"],["a061","쟞",5,"쟥쟦쟧쟩쟪쟫쟭",13],["a081","쟻",4,"젂젃젅젆젇젉젋",4,"젒젔젗",4,"젞젟젡젢젣젥",6,"젮젰젲",5,"젹젺젻젽젾젿졁",6,"졊졋졎",5,"졕",26,"졲졳졵졶졷졹졻",4,"좂좄좈좉좊좎",5,"좕",7,"좞좠좢좣좤"],["a141","좥좦좧좩",18,"좾좿죀죁"],["a161","죂죃죅죆죇죉죊죋죍",6,"죖죘죚",5,"죢죣죥"],["a181","죦",14,"죶",5,"죾죿줁줂줃줇",4,"줎 、。·‥…¨〃―∥\∼‘’“”〔〕〈",9,"±×÷≠≤≥∞∴°′″℃Å¢£¥♂♀∠⊥⌒∂∇≡≒§※☆★○●◎◇◆□■△▲▽▼→←↑↓↔〓≪≫√∽∝∵∫∬∈∋⊆⊇⊂⊃∪∩∧∨¬"],["a241","줐줒",5,"줙",18],["a261","줭",6,"줵",18],["a281","쥈",7,"쥒쥓쥕쥖쥗쥙",6,"쥢쥤",7,"쥭쥮쥯⇒⇔∀∃´~ˇ˘˝˚˙¸˛¡¿ː∮∑∏¤℉‰◁◀▷▶♤♠♡♥♧♣⊙◈▣◐◑▒▤▥▨▧▦▩♨☏☎☜☞¶†‡↕↗↙↖↘♭♩♪♬㉿㈜№㏇™㏂㏘℡€®"],["a341","쥱쥲쥳쥵",6,"쥽",10,"즊즋즍즎즏"],["a361","즑",6,"즚즜즞",16],["a381","즯",16,"짂짃짅짆짉짋",4,"짒짔짗짘짛!",58,"₩]",32," ̄"],["a441","짞짟짡짣짥짦짨짩짪짫짮짲",5,"짺짻짽짾짿쨁쨂쨃쨄"],["a461","쨅쨆쨇쨊쨎",5,"쨕쨖쨗쨙",12],["a481","쨦쨧쨨쨪",28,"ㄱ",93],["a541","쩇",4,"쩎쩏쩑쩒쩓쩕",6,"쩞쩢",5,"쩩쩪"],["a561","쩫",17,"쩾",5,"쪅쪆"],["a581","쪇",16,"쪙",14,"ⅰ",9],["a5b0","Ⅰ",9],["a5c1","Α",16,"Σ",6],["a5e1","α",16,"σ",6],["a641","쪨",19,"쪾쪿쫁쫂쫃쫅"],["a661","쫆",5,"쫎쫐쫒쫔쫕쫖쫗쫚",5,"쫡",6],["a681","쫨쫩쫪쫫쫭",6,"쫵",18,"쬉쬊─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂┒┑┚┙┖┕┎┍┞┟┡┢┦┧┩┪┭┮┱┲┵┶┹┺┽┾╀╁╃",7],["a741","쬋",4,"쬑쬒쬓쬕쬖쬗쬙",6,"쬢",7],["a761","쬪",22,"쭂쭃쭄"],["a781","쭅쭆쭇쭊쭋쭍쭎쭏쭑",6,"쭚쭛쭜쭞",5,"쭥",7,"㎕㎖㎗ℓ㎘㏄㎣㎤㎥㎦㎙",9,"㏊㎍㎎㎏㏏㎈㎉㏈㎧㎨㎰",9,"㎀",4,"㎺",5,"㎐",4,"Ω㏀㏁㎊㎋㎌㏖㏅㎭㎮㎯㏛㎩㎪㎫㎬㏝㏐㏓㏃㏉㏜㏆"],["a841","쭭",10,"쭺",14],["a861","쮉",18,"쮝",6],["a881","쮤",19,"쮹",11,"ÆÐªĦ"],["a8a6","IJ"],["a8a8","ĿŁØŒºÞŦŊ"],["a8b1","㉠",27,"ⓐ",25,"①",14,"½⅓⅔¼¾⅛⅜⅝⅞"],["a941","쯅",14,"쯕",10],["a961","쯠쯡쯢쯣쯥쯦쯨쯪",18],["a981","쯽",14,"찎찏찑찒찓찕",6,"찞찟찠찣찤æđðħıijĸŀłøœßþŧŋʼn㈀",27,"⒜",25,"⑴",14,"¹²³⁴ⁿ₁₂₃₄"],["aa41","찥찦찪찫찭찯찱",6,"찺찿",4,"챆챇챉챊챋챍챎"],["aa61","챏",4,"챖챚",5,"챡챢챣챥챧챩",6,"챱챲"],["aa81","챳챴챶",29,"ぁ",82],["ab41","첔첕첖첗첚첛첝첞첟첡",6,"첪첮",5,"첶첷첹"],["ab61","첺첻첽",6,"쳆쳈쳊",5,"쳑쳒쳓쳕",5],["ab81","쳛",8,"쳥",6,"쳭쳮쳯쳱",12,"ァ",85],["ac41","쳾쳿촀촂",5,"촊촋촍촎촏촑",6,"촚촜촞촟촠"],["ac61","촡촢촣촥촦촧촩촪촫촭",11,"촺",4],["ac81","촿",28,"쵝쵞쵟А",5,"ЁЖ",25],["acd1","а",5,"ёж",25],["ad41","쵡쵢쵣쵥",6,"쵮쵰쵲",5,"쵹",7],["ad61","춁",6,"춉",10,"춖춗춙춚춛춝춞춟"],["ad81","춠춡춢춣춦춨춪",5,"춱",18,"췅"],["ae41","췆",5,"췍췎췏췑",16],["ae61","췢",5,"췩췪췫췭췮췯췱",6,"췺췼췾",4],["ae81","츃츅츆츇츉츊츋츍",6,"츕츖츗츘츚",5,"츢츣츥츦츧츩츪츫"],["af41","츬츭츮츯츲츴츶",19],["af61","칊",13,"칚칛칝칞칢",5,"칪칬"],["af81","칮",5,"칶칷칹칺칻칽",6,"캆캈캊",5,"캒캓캕캖캗캙"],["b041","캚",5,"캢캦",5,"캮",12],["b061","캻",5,"컂",19],["b081","컖",13,"컦컧컩컪컭",6,"컶컺",5,"가각간갇갈갉갊감",7,"같",4,"갠갤갬갭갯갰갱갸갹갼걀걋걍걔걘걜거걱건걷걸걺검겁것겄겅겆겉겊겋게겐겔겜겝겟겠겡겨격겪견겯결겸겹겻겼경곁계곈곌곕곗고곡곤곧골곪곬곯곰곱곳공곶과곽관괄괆"],["b141","켂켃켅켆켇켉",6,"켒켔켖",5,"켝켞켟켡켢켣"],["b161","켥",6,"켮켲",5,"켹",11],["b181","콅",14,"콖콗콙콚콛콝",6,"콦콨콪콫콬괌괍괏광괘괜괠괩괬괭괴괵괸괼굄굅굇굉교굔굘굡굣구국군굳굴굵굶굻굼굽굿궁궂궈궉권궐궜궝궤궷귀귁귄귈귐귑귓규균귤그극근귿글긁금급긋긍긔기긱긴긷길긺김깁깃깅깆깊까깍깎깐깔깖깜깝깟깠깡깥깨깩깬깰깸"],["b241","콭콮콯콲콳콵콶콷콹",6,"쾁쾂쾃쾄쾆",5,"쾍"],["b261","쾎",18,"쾢",5,"쾩"],["b281","쾪",5,"쾱",18,"쿅",6,"깹깻깼깽꺄꺅꺌꺼꺽꺾껀껄껌껍껏껐껑께껙껜껨껫껭껴껸껼꼇꼈꼍꼐꼬꼭꼰꼲꼴꼼꼽꼿꽁꽂꽃꽈꽉꽐꽜꽝꽤꽥꽹꾀꾄꾈꾐꾑꾕꾜꾸꾹꾼꿀꿇꿈꿉꿋꿍꿎꿔꿜꿨꿩꿰꿱꿴꿸뀀뀁뀄뀌뀐뀔뀜뀝뀨끄끅끈끊끌끎끓끔끕끗끙"],["b341","쿌",19,"쿢쿣쿥쿦쿧쿩"],["b361","쿪",5,"쿲쿴쿶",5,"쿽쿾쿿퀁퀂퀃퀅",5],["b381","퀋",5,"퀒",5,"퀙",19,"끝끼끽낀낄낌낍낏낑나낙낚난낟날낡낢남납낫",4,"낱낳내낵낸낼냄냅냇냈냉냐냑냔냘냠냥너넉넋넌널넒넓넘넙넛넜넝넣네넥넨넬넴넵넷넸넹녀녁년녈념녑녔녕녘녜녠노녹논놀놂놈놉놋농높놓놔놘놜놨뇌뇐뇔뇜뇝"],["b441","퀮",5,"퀶퀷퀹퀺퀻퀽",6,"큆큈큊",5],["b461","큑큒큓큕큖큗큙",6,"큡",10,"큮큯"],["b481","큱큲큳큵",6,"큾큿킀킂",18,"뇟뇨뇩뇬뇰뇹뇻뇽누눅눈눋눌눔눕눗눙눠눴눼뉘뉜뉠뉨뉩뉴뉵뉼늄늅늉느늑는늘늙늚늠늡늣능늦늪늬늰늴니닉닌닐닒님닙닛닝닢다닥닦단닫",4,"닳담답닷",4,"닿대댁댄댈댐댑댓댔댕댜더덕덖던덛덜덞덟덤덥"],["b541","킕",14,"킦킧킩킪킫킭",5],["b561","킳킶킸킺",5,"탂탃탅탆탇탊",5,"탒탖",4],["b581","탛탞탟탡탢탣탥",6,"탮탲",5,"탹",11,"덧덩덫덮데덱덴델뎀뎁뎃뎄뎅뎌뎐뎔뎠뎡뎨뎬도독돈돋돌돎돐돔돕돗동돛돝돠돤돨돼됐되된될됨됩됫됴두둑둔둘둠둡둣둥둬뒀뒈뒝뒤뒨뒬뒵뒷뒹듀듄듈듐듕드득든듣들듦듬듭듯등듸디딕딘딛딜딤딥딧딨딩딪따딱딴딸"],["b641","턅",7,"턎",17],["b661","턠",15,"턲턳턵턶턷턹턻턼턽턾"],["b681","턿텂텆",5,"텎텏텑텒텓텕",6,"텞텠텢",5,"텩텪텫텭땀땁땃땄땅땋때땍땐땔땜땝땟땠땡떠떡떤떨떪떫떰떱떳떴떵떻떼떽뗀뗄뗌뗍뗏뗐뗑뗘뗬또똑똔똘똥똬똴뙈뙤뙨뚜뚝뚠뚤뚫뚬뚱뛔뛰뛴뛸뜀뜁뜅뜨뜩뜬뜯뜰뜸뜹뜻띄띈띌띔띕띠띤띨띰띱띳띵라락란랄람랍랏랐랑랒랖랗"],["b741","텮",13,"텽",6,"톅톆톇톉톊"],["b761","톋",20,"톢톣톥톦톧"],["b781","톩",6,"톲톴톶톷톸톹톻톽톾톿퇁",14,"래랙랜랠램랩랫랬랭랴략랸럇량러럭런럴럼럽럿렀렁렇레렉렌렐렘렙렛렝려력련렬렴렵렷렸령례롄롑롓로록론롤롬롭롯롱롸롼뢍뢨뢰뢴뢸룀룁룃룅료룐룔룝룟룡루룩룬룰룸룹룻룽뤄뤘뤠뤼뤽륀륄륌륏륑류륙륜률륨륩"],["b841","퇐",7,"퇙",17],["b861","퇫",8,"퇵퇶퇷퇹",13],["b881","툈툊",5,"툑",24,"륫륭르륵른를름릅릇릉릊릍릎리릭린릴림립릿링마막만많",4,"맘맙맛망맞맡맣매맥맨맬맴맵맷맸맹맺먀먁먈먕머먹먼멀멂멈멉멋멍멎멓메멕멘멜멤멥멧멨멩며멱면멸몃몄명몇몌모목몫몬몰몲몸몹못몽뫄뫈뫘뫙뫼"],["b941","툪툫툮툯툱툲툳툵",6,"툾퉀퉂",5,"퉉퉊퉋퉌"],["b961","퉍",14,"퉝",6,"퉥퉦퉧퉨"],["b981","퉩",22,"튂튃튅튆튇튉튊튋튌묀묄묍묏묑묘묜묠묩묫무묵묶문묻물묽묾뭄뭅뭇뭉뭍뭏뭐뭔뭘뭡뭣뭬뮈뮌뮐뮤뮨뮬뮴뮷므믄믈믐믓미믹민믿밀밂밈밉밋밌밍및밑바",4,"받",4,"밤밥밧방밭배백밴밸뱀뱁뱃뱄뱅뱉뱌뱍뱐뱝버벅번벋벌벎범법벗"],["ba41","튍튎튏튒튓튔튖",5,"튝튞튟튡튢튣튥",6,"튭"],["ba61","튮튯튰튲",5,"튺튻튽튾틁틃",4,"틊틌",5],["ba81","틒틓틕틖틗틙틚틛틝",6,"틦",9,"틲틳틵틶틷틹틺벙벚베벡벤벧벨벰벱벳벴벵벼벽변별볍볏볐병볕볘볜보복볶본볼봄봅봇봉봐봔봤봬뵀뵈뵉뵌뵐뵘뵙뵤뵨부북분붇불붉붊붐붑붓붕붙붚붜붤붰붸뷔뷕뷘뷜뷩뷰뷴뷸븀븃븅브븍븐블븜븝븟비빅빈빌빎빔빕빗빙빚빛빠빡빤"],["bb41","틻",4,"팂팄팆",5,"팏팑팒팓팕팗",4,"팞팢팣"],["bb61","팤팦팧팪팫팭팮팯팱",6,"팺팾",5,"퍆퍇퍈퍉"],["bb81","퍊",31,"빨빪빰빱빳빴빵빻빼빽뺀뺄뺌뺍뺏뺐뺑뺘뺙뺨뻐뻑뻔뻗뻘뻠뻣뻤뻥뻬뼁뼈뼉뼘뼙뼛뼜뼝뽀뽁뽄뽈뽐뽑뽕뾔뾰뿅뿌뿍뿐뿔뿜뿟뿡쀼쁑쁘쁜쁠쁨쁩삐삑삔삘삠삡삣삥사삭삯산삳살삵삶삼삽삿샀상샅새색샌샐샘샙샛샜생샤"],["bc41","퍪",17,"퍾퍿펁펂펃펅펆펇"],["bc61","펈펉펊펋펎펒",5,"펚펛펝펞펟펡",6,"펪펬펮"],["bc81","펯",4,"펵펶펷펹펺펻펽",6,"폆폇폊",5,"폑",5,"샥샨샬샴샵샷샹섀섄섈섐섕서",4,"섣설섦섧섬섭섯섰성섶세섹센셀셈셉셋셌셍셔셕션셜셤셥셧셨셩셰셴셸솅소속솎손솔솖솜솝솟송솥솨솩솬솰솽쇄쇈쇌쇔쇗쇘쇠쇤쇨쇰쇱쇳쇼쇽숀숄숌숍숏숑수숙순숟술숨숩숫숭"],["bd41","폗폙",7,"폢폤",7,"폮폯폱폲폳폵폶폷"],["bd61","폸폹폺폻폾퐀퐂",5,"퐉",13],["bd81","퐗",5,"퐞",25,"숯숱숲숴쉈쉐쉑쉔쉘쉠쉥쉬쉭쉰쉴쉼쉽쉿슁슈슉슐슘슛슝스슥슨슬슭슴습슷승시식신싣실싫심십싯싱싶싸싹싻싼쌀쌈쌉쌌쌍쌓쌔쌕쌘쌜쌤쌥쌨쌩썅써썩썬썰썲썸썹썼썽쎄쎈쎌쏀쏘쏙쏜쏟쏠쏢쏨쏩쏭쏴쏵쏸쐈쐐쐤쐬쐰"],["be41","퐸",7,"푁푂푃푅",14],["be61","푔",7,"푝푞푟푡푢푣푥",7,"푮푰푱푲"],["be81","푳",4,"푺푻푽푾풁풃",4,"풊풌풎",5,"풕",8,"쐴쐼쐽쑈쑤쑥쑨쑬쑴쑵쑹쒀쒔쒜쒸쒼쓩쓰쓱쓴쓸쓺쓿씀씁씌씐씔씜씨씩씬씰씸씹씻씽아악안앉않알앍앎앓암압앗았앙앝앞애액앤앨앰앱앳앴앵야약얀얄얇얌얍얏양얕얗얘얜얠얩어억언얹얻얼얽얾엄",6,"엌엎"],["bf41","풞",10,"풪",14],["bf61","풹",18,"퓍퓎퓏퓑퓒퓓퓕"],["bf81","퓖",5,"퓝퓞퓠",7,"퓩퓪퓫퓭퓮퓯퓱",6,"퓹퓺퓼에엑엔엘엠엡엣엥여역엮연열엶엷염",5,"옅옆옇예옌옐옘옙옛옜오옥온올옭옮옰옳옴옵옷옹옻와왁완왈왐왑왓왔왕왜왝왠왬왯왱외왹왼욀욈욉욋욍요욕욘욜욤욥욧용우욱운울욹욺움웁웃웅워웍원월웜웝웠웡웨"],["c041","퓾",5,"픅픆픇픉픊픋픍",6,"픖픘",5],["c061","픞",25],["c081","픸픹픺픻픾픿핁핂핃핅",6,"핎핐핒",5,"핚핛핝핞핟핡핢핣웩웬웰웸웹웽위윅윈윌윔윕윗윙유육윤율윰윱윳융윷으윽은을읊음읍읏응",7,"읜읠읨읫이익인일읽읾잃임입잇있잉잊잎자작잔잖잗잘잚잠잡잣잤장잦재잭잰잴잼잽잿쟀쟁쟈쟉쟌쟎쟐쟘쟝쟤쟨쟬저적전절젊"],["c141","핤핦핧핪핬핮",5,"핶핷핹핺핻핽",6,"햆햊햋"],["c161","햌햍햎햏햑",19,"햦햧"],["c181","햨",31,"점접젓정젖제젝젠젤젬젭젯젱져젼졀졈졉졌졍졔조족존졸졺좀좁좃종좆좇좋좌좍좔좝좟좡좨좼좽죄죈죌죔죕죗죙죠죡죤죵주죽준줄줅줆줌줍줏중줘줬줴쥐쥑쥔쥘쥠쥡쥣쥬쥰쥴쥼즈즉즌즐즘즙즛증지직진짇질짊짐집짓"],["c241","헊헋헍헎헏헑헓",4,"헚헜헞",5,"헦헧헩헪헫헭헮"],["c261","헯",4,"헶헸헺",5,"혂혃혅혆혇혉",6,"혒"],["c281","혖",5,"혝혞혟혡혢혣혥",7,"혮",9,"혺혻징짖짙짚짜짝짠짢짤짧짬짭짯짰짱째짹짼쨀쨈쨉쨋쨌쨍쨔쨘쨩쩌쩍쩐쩔쩜쩝쩟쩠쩡쩨쩽쪄쪘쪼쪽쫀쫄쫌쫍쫏쫑쫓쫘쫙쫠쫬쫴쬈쬐쬔쬘쬠쬡쭁쭈쭉쭌쭐쭘쭙쭝쭤쭸쭹쮜쮸쯔쯤쯧쯩찌찍찐찔찜찝찡찢찧차착찬찮찰참찹찻"],["c341","혽혾혿홁홂홃홄홆홇홊홌홎홏홐홒홓홖홗홙홚홛홝",4],["c361","홢",4,"홨홪",5,"홲홳홵",11],["c381","횁횂횄횆",5,"횎횏횑횒횓횕",7,"횞횠횢",5,"횩횪찼창찾채책챈챌챔챕챗챘챙챠챤챦챨챰챵처척천철첨첩첫첬청체첵첸첼쳄쳅쳇쳉쳐쳔쳤쳬쳰촁초촉촌촐촘촙촛총촤촨촬촹최쵠쵤쵬쵭쵯쵱쵸춈추축춘출춤춥춧충춰췄췌췐취췬췰췸췹췻췽츄츈츌츔츙츠측츤츨츰츱츳층"],["c441","횫횭횮횯횱",7,"횺횼",7,"훆훇훉훊훋"],["c461","훍훎훏훐훒훓훕훖훘훚",5,"훡훢훣훥훦훧훩",4],["c481","훮훯훱훲훳훴훶",5,"훾훿휁휂휃휅",11,"휒휓휔치칙친칟칠칡침칩칫칭카칵칸칼캄캅캇캉캐캑캔캘캠캡캣캤캥캬캭컁커컥컨컫컬컴컵컷컸컹케켁켄켈켐켑켓켕켜켠켤켬켭켯켰켱켸코콕콘콜콤콥콧콩콰콱콴콸쾀쾅쾌쾡쾨쾰쿄쿠쿡쿤쿨쿰쿱쿳쿵쿼퀀퀄퀑퀘퀭퀴퀵퀸퀼"],["c541","휕휖휗휚휛휝휞휟휡",6,"휪휬휮",5,"휶휷휹"],["c561","휺휻휽",6,"흅흆흈흊",5,"흒흓흕흚",4],["c581","흟흢흤흦흧흨흪흫흭흮흯흱흲흳흵",6,"흾흿힀힂",5,"힊힋큄큅큇큉큐큔큘큠크큭큰클큼큽킁키킥킨킬킴킵킷킹타탁탄탈탉탐탑탓탔탕태택탠탤탬탭탯탰탱탸턍터턱턴털턺텀텁텃텄텅테텍텐텔템텝텟텡텨텬텼톄톈토톡톤톨톰톱톳통톺톼퇀퇘퇴퇸툇툉툐투툭툰툴툼툽툿퉁퉈퉜"],["c641","힍힎힏힑",6,"힚힜힞",5],["c6a1","퉤튀튁튄튈튐튑튕튜튠튤튬튱트특튼튿틀틂틈틉틋틔틘틜틤틥티틱틴틸팀팁팃팅파팍팎판팔팖팜팝팟팠팡팥패팩팬팰팸팹팻팼팽퍄퍅퍼퍽펀펄펌펍펏펐펑페펙펜펠펨펩펫펭펴편펼폄폅폈평폐폘폡폣포폭폰폴폼폽폿퐁"],["c7a1","퐈퐝푀푄표푠푤푭푯푸푹푼푿풀풂품풉풋풍풔풩퓌퓐퓔퓜퓟퓨퓬퓰퓸퓻퓽프픈플픔픕픗피픽핀필핌핍핏핑하학한할핥함합핫항해핵핸핼햄햅햇했행햐향허헉헌헐헒험헙헛헝헤헥헨헬헴헵헷헹혀혁현혈혐협혓혔형혜혠"],["c8a1","혤혭호혹혼홀홅홈홉홋홍홑화확환활홧황홰홱홴횃횅회획횐횔횝횟횡효횬횰횹횻후훅훈훌훑훔훗훙훠훤훨훰훵훼훽휀휄휑휘휙휜휠휨휩휫휭휴휵휸휼흄흇흉흐흑흔흖흗흘흙흠흡흣흥흩희흰흴흼흽힁히힉힌힐힘힙힛힝"],["caa1","伽佳假價加可呵哥嘉嫁家暇架枷柯歌珂痂稼苛茄街袈訶賈跏軻迦駕刻却各恪慤殼珏脚覺角閣侃刊墾奸姦干幹懇揀杆柬桿澗癎看磵稈竿簡肝艮艱諫間乫喝曷渴碣竭葛褐蝎鞨勘坎堪嵌感憾戡敢柑橄減甘疳監瞰紺邯鑑鑒龕"],["cba1","匣岬甲胛鉀閘剛堈姜岡崗康强彊慷江畺疆糠絳綱羌腔舡薑襁講鋼降鱇介价個凱塏愷愾慨改槪漑疥皆盖箇芥蓋豈鎧開喀客坑更粳羹醵倨去居巨拒据據擧渠炬祛距踞車遽鉅鋸乾件健巾建愆楗腱虔蹇鍵騫乞傑杰桀儉劍劒檢"],["cca1","瞼鈐黔劫怯迲偈憩揭擊格檄激膈覡隔堅牽犬甄絹繭肩見譴遣鵑抉決潔結缺訣兼慊箝謙鉗鎌京俓倞傾儆勁勍卿坰境庚徑慶憬擎敬景暻更梗涇炅烱璟璥瓊痙硬磬竟競絅經耕耿脛莖警輕逕鏡頃頸驚鯨係啓堺契季屆悸戒桂械"],["cda1","棨溪界癸磎稽系繫繼計誡谿階鷄古叩告呱固姑孤尻庫拷攷故敲暠枯槁沽痼皐睾稿羔考股膏苦苽菰藁蠱袴誥賈辜錮雇顧高鼓哭斛曲梏穀谷鵠困坤崑昆梱棍滾琨袞鯤汨滑骨供公共功孔工恐恭拱控攻珙空蚣貢鞏串寡戈果瓜"],["cea1","科菓誇課跨過鍋顆廓槨藿郭串冠官寬慣棺款灌琯瓘管罐菅觀貫關館刮恝括适侊光匡壙廣曠洸炚狂珖筐胱鑛卦掛罫乖傀塊壞怪愧拐槐魁宏紘肱轟交僑咬喬嬌嶠巧攪敎校橋狡皎矯絞翹膠蕎蛟較轎郊餃驕鮫丘久九仇俱具勾"],["cfa1","區口句咎嘔坵垢寇嶇廐懼拘救枸柩構歐毆毬求溝灸狗玖球瞿矩究絿耉臼舅舊苟衢謳購軀逑邱鉤銶駒驅鳩鷗龜國局菊鞠鞫麴君窘群裙軍郡堀屈掘窟宮弓穹窮芎躬倦券勸卷圈拳捲權淃眷厥獗蕨蹶闕机櫃潰詭軌饋句晷歸貴"],["d0a1","鬼龜叫圭奎揆槻珪硅窺竅糾葵規赳逵閨勻均畇筠菌鈞龜橘克剋劇戟棘極隙僅劤勤懃斤根槿瑾筋芹菫覲謹近饉契今妗擒昑檎琴禁禽芩衾衿襟金錦伋及急扱汲級給亘兢矜肯企伎其冀嗜器圻基埼夔奇妓寄岐崎己幾忌技旗旣"],["d1a1","朞期杞棋棄機欺氣汽沂淇玘琦琪璂璣畸畿碁磯祁祇祈祺箕紀綺羈耆耭肌記譏豈起錡錤飢饑騎騏驥麒緊佶吉拮桔金喫儺喇奈娜懦懶拏拿癩",5,"那樂",4,"諾酪駱亂卵暖欄煖爛蘭難鸞捏捺南嵐枏楠湳濫男藍襤拉"],["d2a1","納臘蠟衲囊娘廊",4,"乃來內奈柰耐冷女年撚秊念恬拈捻寧寗努勞奴弩怒擄櫓爐瑙盧",5,"駑魯",10,"濃籠聾膿農惱牢磊腦賂雷尿壘",7,"嫩訥杻紐勒",5,"能菱陵尼泥匿溺多茶"],["d3a1","丹亶但單團壇彖斷旦檀段湍短端簞緞蛋袒鄲鍛撻澾獺疸達啖坍憺擔曇淡湛潭澹痰聃膽蕁覃談譚錟沓畓答踏遝唐堂塘幢戇撞棠當糖螳黨代垈坮大對岱帶待戴擡玳臺袋貸隊黛宅德悳倒刀到圖堵塗導屠島嶋度徒悼挑掉搗桃"],["d4a1","棹櫂淘渡滔濤燾盜睹禱稻萄覩賭跳蹈逃途道都鍍陶韜毒瀆牘犢獨督禿篤纛讀墩惇敦旽暾沌焞燉豚頓乭突仝冬凍動同憧東桐棟洞潼疼瞳童胴董銅兜斗杜枓痘竇荳讀豆逗頭屯臀芚遁遯鈍得嶝橙燈登等藤謄鄧騰喇懶拏癩羅"],["d5a1","蘿螺裸邏樂洛烙珞絡落諾酪駱丹亂卵欄欒瀾爛蘭鸞剌辣嵐擥攬欖濫籃纜藍襤覽拉臘蠟廊朗浪狼琅瑯螂郞來崍徠萊冷掠略亮倆兩凉梁樑粮粱糧良諒輛量侶儷勵呂廬慮戾旅櫚濾礪藜蠣閭驢驪麗黎力曆歷瀝礫轢靂憐戀攣漣"],["d6a1","煉璉練聯蓮輦連鍊冽列劣洌烈裂廉斂殮濂簾獵令伶囹寧岺嶺怜玲笭羚翎聆逞鈴零靈領齡例澧禮醴隷勞怒撈擄櫓潞瀘爐盧老蘆虜路輅露魯鷺鹵碌祿綠菉錄鹿麓論壟弄朧瀧瓏籠聾儡瀨牢磊賂賚賴雷了僚寮廖料燎療瞭聊蓼"],["d7a1","遼鬧龍壘婁屢樓淚漏瘻累縷蔞褸鏤陋劉旒柳榴流溜瀏琉瑠留瘤硫謬類六戮陸侖倫崙淪綸輪律慄栗率隆勒肋凜凌楞稜綾菱陵俚利厘吏唎履悧李梨浬犁狸理璃異痢籬罹羸莉裏裡里釐離鯉吝潾燐璘藺躪隣鱗麟林淋琳臨霖砬"],["d8a1","立笠粒摩瑪痲碼磨馬魔麻寞幕漠膜莫邈万卍娩巒彎慢挽晩曼滿漫灣瞞萬蔓蠻輓饅鰻唜抹末沫茉襪靺亡妄忘忙望網罔芒茫莽輞邙埋妹媒寐昧枚梅每煤罵買賣邁魅脈貊陌驀麥孟氓猛盲盟萌冪覓免冕勉棉沔眄眠綿緬面麵滅"],["d9a1","蔑冥名命明暝椧溟皿瞑茗蓂螟酩銘鳴袂侮冒募姆帽慕摸摹暮某模母毛牟牡瑁眸矛耗芼茅謀謨貌木沐牧目睦穆鶩歿沒夢朦蒙卯墓妙廟描昴杳渺猫竗苗錨務巫憮懋戊拇撫无楙武毋無珷畝繆舞茂蕪誣貿霧鵡墨默們刎吻問文"],["daa1","汶紊紋聞蚊門雯勿沕物味媚尾嵋彌微未梶楣渼湄眉米美薇謎迷靡黴岷悶愍憫敏旻旼民泯玟珉緡閔密蜜謐剝博拍搏撲朴樸泊珀璞箔粕縛膊舶薄迫雹駁伴半反叛拌搬攀斑槃泮潘班畔瘢盤盼磐磻礬絆般蟠返頒飯勃拔撥渤潑"],["dba1","發跋醱鉢髮魃倣傍坊妨尨幇彷房放方旁昉枋榜滂磅紡肪膀舫芳蒡蚌訪謗邦防龐倍俳北培徘拜排杯湃焙盃背胚裴裵褙賠輩配陪伯佰帛柏栢白百魄幡樊煩燔番磻繁蕃藩飜伐筏罰閥凡帆梵氾汎泛犯範范法琺僻劈壁擘檗璧癖"],["dca1","碧蘗闢霹便卞弁變辨辯邊別瞥鱉鼈丙倂兵屛幷昞昺柄棅炳甁病秉竝輧餠騈保堡報寶普步洑湺潽珤甫菩補褓譜輔伏僕匐卜宓復服福腹茯蔔複覆輹輻馥鰒本乶俸奉封峯峰捧棒烽熢琫縫蓬蜂逢鋒鳳不付俯傅剖副否咐埠夫婦"],["dda1","孚孵富府復扶敷斧浮溥父符簿缶腐腑膚艀芙莩訃負賦賻赴趺部釜阜附駙鳧北分吩噴墳奔奮忿憤扮昐汾焚盆粉糞紛芬賁雰不佛弗彿拂崩朋棚硼繃鵬丕備匕匪卑妃婢庇悲憊扉批斐枇榧比毖毗毘沸泌琵痺砒碑秕秘粃緋翡肥"],["dea1","脾臂菲蜚裨誹譬費鄙非飛鼻嚬嬪彬斌檳殯浜濱瀕牝玭貧賓頻憑氷聘騁乍事些仕伺似使俟僿史司唆嗣四士奢娑寫寺射巳師徙思捨斜斯柶査梭死沙泗渣瀉獅砂社祀祠私篩紗絲肆舍莎蓑蛇裟詐詞謝賜赦辭邪飼駟麝削數朔索"],["dfa1","傘刪山散汕珊産疝算蒜酸霰乷撒殺煞薩三參杉森渗芟蔘衫揷澁鈒颯上傷像償商喪嘗孀尙峠常床庠廂想桑橡湘爽牀狀相祥箱翔裳觴詳象賞霜塞璽賽嗇塞穡索色牲生甥省笙墅壻嶼序庶徐恕抒捿敍暑曙書栖棲犀瑞筮絮緖署"],["e0a1","胥舒薯西誓逝鋤黍鼠夕奭席惜昔晳析汐淅潟石碩蓆釋錫仙僊先善嬋宣扇敾旋渲煽琁瑄璇璿癬禪線繕羨腺膳船蘚蟬詵跣選銑鐥饍鮮卨屑楔泄洩渫舌薛褻設說雪齧剡暹殲纖蟾贍閃陝攝涉燮葉城姓宬性惺成星晟猩珹盛省筬"],["e1a1","聖聲腥誠醒世勢歲洗稅笹細說貰召嘯塑宵小少巢所掃搔昭梳沼消溯瀟炤燒甦疏疎瘙笑篠簫素紹蔬蕭蘇訴逍遡邵銷韶騷俗屬束涑粟續謖贖速孫巽損蓀遜飡率宋悚松淞訟誦送頌刷殺灑碎鎖衰釗修受嗽囚垂壽嫂守岫峀帥愁"],["e2a1","戍手授搜收數樹殊水洙漱燧狩獸琇璲瘦睡秀穗竪粹綏綬繡羞脩茱蒐蓚藪袖誰讐輸遂邃酬銖銹隋隧隨雖需須首髓鬚叔塾夙孰宿淑潚熟琡璹肅菽巡徇循恂旬栒楯橓殉洵淳珣盾瞬筍純脣舜荀蓴蕣詢諄醇錞順馴戌術述鉥崇崧"],["e3a1","嵩瑟膝蝨濕拾習褶襲丞乘僧勝升承昇繩蠅陞侍匙嘶始媤尸屎屍市弑恃施是時枾柴猜矢示翅蒔蓍視試詩諡豕豺埴寔式息拭植殖湜熄篒蝕識軾食飾伸侁信呻娠宸愼新晨燼申神紳腎臣莘薪藎蜃訊身辛辰迅失室實悉審尋心沁"],["e4a1","沈深瀋甚芯諶什十拾雙氏亞俄兒啞娥峨我牙芽莪蛾衙訝阿雅餓鴉鵝堊岳嶽幄惡愕握樂渥鄂鍔顎鰐齷安岸按晏案眼雁鞍顔鮟斡謁軋閼唵岩巖庵暗癌菴闇壓押狎鴨仰央怏昻殃秧鴦厓哀埃崖愛曖涯碍艾隘靄厄扼掖液縊腋額"],["e5a1","櫻罌鶯鸚也倻冶夜惹揶椰爺耶若野弱掠略約若葯蒻藥躍亮佯兩凉壤孃恙揚攘敭暘梁楊樣洋瀁煬痒瘍禳穰糧羊良襄諒讓釀陽量養圄御於漁瘀禦語馭魚齬億憶抑檍臆偃堰彦焉言諺孼蘖俺儼嚴奄掩淹嶪業円予余勵呂女如廬"],["e6a1","旅歟汝濾璵礖礪與艅茹輿轝閭餘驪麗黎亦力域役易曆歷疫繹譯轢逆驛嚥堧姸娟宴年延憐戀捐挻撚椽沇沿涎涓淵演漣烟然煙煉燃燕璉硏硯秊筵緣練縯聯衍軟輦蓮連鉛鍊鳶列劣咽悅涅烈熱裂說閱厭廉念捻染殮炎焰琰艶苒"],["e7a1","簾閻髥鹽曄獵燁葉令囹塋寧嶺嶸影怜映暎楹榮永泳渶潁濚瀛瀯煐營獰玲瑛瑩瓔盈穎纓羚聆英詠迎鈴鍈零霙靈領乂倪例刈叡曳汭濊猊睿穢芮藝蘂禮裔詣譽豫醴銳隸霓預五伍俉傲午吾吳嗚塢墺奧娛寤悟惡懊敖旿晤梧汚澳"],["e8a1","烏熬獒筽蜈誤鰲鼇屋沃獄玉鈺溫瑥瘟穩縕蘊兀壅擁瓮甕癰翁邕雍饔渦瓦窩窪臥蛙蝸訛婉完宛梡椀浣玩琓琬碗緩翫脘腕莞豌阮頑曰往旺枉汪王倭娃歪矮外嵬巍猥畏了僚僥凹堯夭妖姚寥寮尿嶢拗搖撓擾料曜樂橈燎燿瑤療"],["e9a1","窈窯繇繞耀腰蓼蟯要謠遙遼邀饒慾欲浴縟褥辱俑傭冗勇埇墉容庸慂榕涌湧溶熔瑢用甬聳茸蓉踊鎔鏞龍于佑偶優又友右宇寓尤愚憂旴牛玗瑀盂祐禑禹紆羽芋藕虞迂遇郵釪隅雨雩勖彧旭昱栯煜稶郁頊云暈橒殞澐熉耘芸蕓"],["eaa1","運隕雲韻蔚鬱亐熊雄元原員圓園垣媛嫄寃怨愿援沅洹湲源爰猿瑗苑袁轅遠阮院願鴛月越鉞位偉僞危圍委威尉慰暐渭爲瑋緯胃萎葦蔿蝟衛褘謂違韋魏乳侑儒兪劉唯喩孺宥幼幽庾悠惟愈愉揄攸有杻柔柚柳楡楢油洧流游溜"],["eba1","濡猶猷琉瑜由留癒硫紐維臾萸裕誘諛諭踰蹂遊逾遺酉釉鍮類六堉戮毓肉育陸倫允奫尹崙淪潤玧胤贇輪鈗閏律慄栗率聿戎瀜絨融隆垠恩慇殷誾銀隱乙吟淫蔭陰音飮揖泣邑凝應膺鷹依倚儀宜意懿擬椅毅疑矣義艤薏蟻衣誼"],["eca1","議醫二以伊利吏夷姨履已弛彛怡易李梨泥爾珥理異痍痢移罹而耳肄苡荑裏裡貽貳邇里離飴餌匿溺瀷益翊翌翼謚人仁刃印吝咽因姻寅引忍湮燐璘絪茵藺蚓認隣靭靷鱗麟一佚佾壹日溢逸鎰馹任壬妊姙恁林淋稔臨荏賃入卄"],["eda1","立笠粒仍剩孕芿仔刺咨姉姿子字孜恣慈滋炙煮玆瓷疵磁紫者自茨蔗藉諮資雌作勺嚼斫昨灼炸爵綽芍酌雀鵲孱棧殘潺盞岑暫潛箴簪蠶雜丈仗匠場墻壯奬將帳庄張掌暲杖樟檣欌漿牆狀獐璋章粧腸臟臧莊葬蔣薔藏裝贓醬長"],["eea1","障再哉在宰才材栽梓渽滓災縡裁財載齋齎爭箏諍錚佇低儲咀姐底抵杵楮樗沮渚狙猪疽箸紵苧菹著藷詛貯躇這邸雎齟勣吊嫡寂摘敵滴狄炙的積笛籍績翟荻謫賊赤跡蹟迪迹適鏑佃佺傳全典前剪塡塼奠專展廛悛戰栓殿氈澱"],["efa1","煎琠田甸畑癲筌箋箭篆纏詮輾轉鈿銓錢鐫電顚顫餞切截折浙癤竊節絶占岾店漸点粘霑鮎點接摺蝶丁井亭停偵呈姃定幀庭廷征情挺政整旌晶晸柾楨檉正汀淀淨渟湞瀞炡玎珽町睛碇禎程穽精綎艇訂諪貞鄭酊釘鉦鋌錠霆靖"],["f0a1","靜頂鼎制劑啼堤帝弟悌提梯濟祭第臍薺製諸蹄醍除際霽題齊俎兆凋助嘲弔彫措操早晁曺曹朝條棗槽漕潮照燥爪璪眺祖祚租稠窕粗糟組繰肇藻蚤詔調趙躁造遭釣阻雕鳥族簇足鏃存尊卒拙猝倧宗從悰慫棕淙琮種終綜縱腫"],["f1a1","踪踵鍾鐘佐坐左座挫罪主住侏做姝胄呪周嗾奏宙州廚晝朱柱株注洲湊澍炷珠疇籌紂紬綢舟蛛註誅走躊輳週酎酒鑄駐竹粥俊儁准埈寯峻晙樽浚準濬焌畯竣蠢逡遵雋駿茁中仲衆重卽櫛楫汁葺增憎曾拯烝甑症繒蒸證贈之只"],["f2a1","咫地址志持指摯支旨智枝枳止池沚漬知砥祉祗紙肢脂至芝芷蜘誌識贄趾遲直稙稷織職唇嗔塵振搢晉晋桭榛殄津溱珍瑨璡畛疹盡眞瞋秦縉縝臻蔯袗診賑軫辰進鎭陣陳震侄叱姪嫉帙桎瓆疾秩窒膣蛭質跌迭斟朕什執潗緝輯"],["f3a1","鏶集徵懲澄且侘借叉嗟嵯差次此磋箚茶蹉車遮捉搾着窄錯鑿齪撰澯燦璨瓚竄簒纂粲纘讚贊鑽餐饌刹察擦札紮僭參塹慘慙懺斬站讒讖倉倡創唱娼廠彰愴敞昌昶暢槍滄漲猖瘡窓脹艙菖蒼債埰寀寨彩採砦綵菜蔡采釵冊柵策"],["f4a1","責凄妻悽處倜刺剔尺慽戚拓擲斥滌瘠脊蹠陟隻仟千喘天川擅泉淺玔穿舛薦賤踐遷釧闡阡韆凸哲喆徹撤澈綴輟轍鐵僉尖沾添甛瞻簽籤詹諂堞妾帖捷牒疊睫諜貼輒廳晴淸聽菁請靑鯖切剃替涕滯締諦逮遞體初剿哨憔抄招梢"],["f5a1","椒楚樵炒焦硝礁礎秒稍肖艸苕草蕉貂超酢醋醮促囑燭矗蜀觸寸忖村邨叢塚寵悤憁摠總聰蔥銃撮催崔最墜抽推椎楸樞湫皺秋芻萩諏趨追鄒酋醜錐錘鎚雛騶鰍丑畜祝竺筑築縮蓄蹙蹴軸逐春椿瑃出朮黜充忠沖蟲衝衷悴膵萃"],["f6a1","贅取吹嘴娶就炊翠聚脆臭趣醉驟鷲側仄厠惻測層侈値嗤峙幟恥梔治淄熾痔痴癡稚穉緇緻置致蚩輜雉馳齒則勅飭親七柒漆侵寢枕沈浸琛砧針鍼蟄秤稱快他咤唾墮妥惰打拖朶楕舵陀馱駝倬卓啄坼度托拓擢晫柝濁濯琢琸託"],["f7a1","鐸呑嘆坦彈憚歎灘炭綻誕奪脫探眈耽貪塔搭榻宕帑湯糖蕩兌台太怠態殆汰泰笞胎苔跆邰颱宅擇澤撑攄兎吐土討慟桶洞痛筒統通堆槌腿褪退頹偸套妬投透鬪慝特闖坡婆巴把播擺杷波派爬琶破罷芭跛頗判坂板版瓣販辦鈑"],["f8a1","阪八叭捌佩唄悖敗沛浿牌狽稗覇貝彭澎烹膨愎便偏扁片篇編翩遍鞭騙貶坪平枰萍評吠嬖幣廢弊斃肺蔽閉陛佈包匍匏咆哺圃布怖抛抱捕暴泡浦疱砲胞脯苞葡蒲袍褒逋鋪飽鮑幅暴曝瀑爆輻俵剽彪慓杓標漂瓢票表豹飇飄驃"],["f9a1","品稟楓諷豊風馮彼披疲皮被避陂匹弼必泌珌畢疋筆苾馝乏逼下何厦夏廈昰河瑕荷蝦賀遐霞鰕壑學虐謔鶴寒恨悍旱汗漢澣瀚罕翰閑閒限韓割轄函含咸啣喊檻涵緘艦銜陷鹹合哈盒蛤閤闔陜亢伉姮嫦巷恒抗杭桁沆港缸肛航"],["faa1","行降項亥偕咳垓奚孩害懈楷海瀣蟹解該諧邂駭骸劾核倖幸杏荇行享向嚮珦鄕響餉饗香噓墟虛許憲櫶獻軒歇險驗奕爀赫革俔峴弦懸晛泫炫玄玹現眩睍絃絢縣舷衒見賢鉉顯孑穴血頁嫌俠協夾峽挾浹狹脅脇莢鋏頰亨兄刑型"],["fba1","形泂滎瀅灐炯熒珩瑩荊螢衡逈邢鎣馨兮彗惠慧暳蕙蹊醯鞋乎互呼壕壺好岵弧戶扈昊晧毫浩淏湖滸澔濠濩灝狐琥瑚瓠皓祜糊縞胡芦葫蒿虎號蝴護豪鎬頀顥惑或酷婚昏混渾琿魂忽惚笏哄弘汞泓洪烘紅虹訌鴻化和嬅樺火畵"],["fca1","禍禾花華話譁貨靴廓擴攫確碻穫丸喚奐宦幻患換歡晥桓渙煥環紈還驩鰥活滑猾豁闊凰幌徨恍惶愰慌晃晄榥況湟滉潢煌璜皇篁簧荒蝗遑隍黃匯回廻徊恢悔懷晦會檜淮澮灰獪繪膾茴蛔誨賄劃獲宖橫鐄哮嚆孝效斅曉梟涍淆"],["fda1","爻肴酵驍侯候厚后吼喉嗅帿後朽煦珝逅勛勳塤壎焄熏燻薰訓暈薨喧暄煊萱卉喙毁彙徽揮暉煇諱輝麾休携烋畦虧恤譎鷸兇凶匈洶胸黑昕欣炘痕吃屹紇訖欠欽歆吸恰洽翕興僖凞喜噫囍姬嬉希憙憘戱晞曦熙熹熺犧禧稀羲詰"]];
/***/ }),
/***/ 932:
/***/ (function(module) {
module.exports = [["0","\u0000",127],["a140"," ,、。.‧;:?!︰…‥﹐﹑﹒·﹔﹕﹖﹗|–︱—︳╴︴﹏()︵︶{}︷︸〔〕︹︺【】︻︼《》︽︾〈〉︿﹀「」﹁﹂『』﹃﹄﹙﹚"],["a1a1","﹛﹜﹝﹞‘’“”〝〞‵′#&*※§〃○●△▲◎☆★◇◆□■▽▼㊣℅¯ ̄_ˍ﹉﹊﹍﹎﹋﹌﹟﹠﹡+-×÷±√<>=≦≧≠∞≒≡﹢",4,"~∩∪⊥∠∟⊿㏒㏑∫∮∵∴♀♂⊕⊙↑↓←→↖↗↙↘∥∣/"],["a240","\∕﹨$¥〒¢£%@℃℉﹩﹪﹫㏕㎜㎝㎞㏎㎡㎎㎏㏄°兙兛兞兝兡兣嗧瓩糎▁",7,"▏▎▍▌▋▊▉┼┴┬┤├▔─│▕┌┐└┘╭"],["a2a1","╮╰╯═╞╪╡◢◣◥◤╱╲╳0",9,"Ⅰ",9,"〡",8,"十卄卅A",25,"a",21],["a340","wxyzΑ",16,"Σ",6,"α",16,"σ",6,"ㄅ",10],["a3a1","ㄐ",25,"˙ˉˊˇˋ"],["a3e1","€"],["a440","一乙丁七乃九了二人儿入八几刀刁力匕十卜又三下丈上丫丸凡久么也乞于亡兀刃勺千叉口土士夕大女子孑孓寸小尢尸山川工己已巳巾干廾弋弓才"],["a4a1","丑丐不中丰丹之尹予云井互五亢仁什仃仆仇仍今介仄元允內六兮公冗凶分切刈勻勾勿化匹午升卅卞厄友及反壬天夫太夭孔少尤尺屯巴幻廿弔引心戈戶手扎支文斗斤方日曰月木欠止歹毋比毛氏水火爪父爻片牙牛犬王丙"],["a540","世丕且丘主乍乏乎以付仔仕他仗代令仙仞充兄冉冊冬凹出凸刊加功包匆北匝仟半卉卡占卯卮去可古右召叮叩叨叼司叵叫另只史叱台句叭叻四囚外"],["a5a1","央失奴奶孕它尼巨巧左市布平幼弁弘弗必戊打扔扒扑斥旦朮本未末札正母民氐永汁汀氾犯玄玉瓜瓦甘生用甩田由甲申疋白皮皿目矛矢石示禾穴立丞丟乒乓乩亙交亦亥仿伉伙伊伕伍伐休伏仲件任仰仳份企伋光兇兆先全"],["a640","共再冰列刑划刎刖劣匈匡匠印危吉吏同吊吐吁吋各向名合吃后吆吒因回囝圳地在圭圬圯圩夙多夷夸妄奸妃好她如妁字存宇守宅安寺尖屹州帆并年"],["a6a1","式弛忙忖戎戌戍成扣扛托收早旨旬旭曲曳有朽朴朱朵次此死氖汝汗汙江池汐汕污汛汍汎灰牟牝百竹米糸缶羊羽老考而耒耳聿肉肋肌臣自至臼舌舛舟艮色艾虫血行衣西阡串亨位住佇佗佞伴佛何估佐佑伽伺伸佃佔似但佣"],["a740","作你伯低伶余佝佈佚兌克免兵冶冷別判利刪刨劫助努劬匣即卵吝吭吞吾否呎吧呆呃吳呈呂君吩告吹吻吸吮吵吶吠吼呀吱含吟听囪困囤囫坊坑址坍"],["a7a1","均坎圾坐坏圻壯夾妝妒妨妞妣妙妖妍妤妓妊妥孝孜孚孛完宋宏尬局屁尿尾岐岑岔岌巫希序庇床廷弄弟彤形彷役忘忌志忍忱快忸忪戒我抄抗抖技扶抉扭把扼找批扳抒扯折扮投抓抑抆改攻攸旱更束李杏材村杜杖杞杉杆杠"],["a840","杓杗步每求汞沙沁沈沉沅沛汪決沐汰沌汨沖沒汽沃汲汾汴沆汶沍沔沘沂灶灼災灸牢牡牠狄狂玖甬甫男甸皂盯矣私秀禿究系罕肖肓肝肘肛肚育良芒"],["a8a1","芋芍見角言谷豆豕貝赤走足身車辛辰迂迆迅迄巡邑邢邪邦那酉釆里防阮阱阪阬並乖乳事些亞享京佯依侍佳使佬供例來侃佰併侈佩佻侖佾侏侑佺兔兒兕兩具其典冽函刻券刷刺到刮制剁劾劻卒協卓卑卦卷卸卹取叔受味呵"],["a940","咖呸咕咀呻呷咄咒咆呼咐呱呶和咚呢周咋命咎固垃坷坪坩坡坦坤坼夜奉奇奈奄奔妾妻委妹妮姑姆姐姍始姓姊妯妳姒姅孟孤季宗定官宜宙宛尚屈居"],["a9a1","屆岷岡岸岩岫岱岳帘帚帖帕帛帑幸庚店府底庖延弦弧弩往征彿彼忝忠忽念忿怏怔怯怵怖怪怕怡性怩怫怛或戕房戾所承拉拌拄抿拂抹拒招披拓拔拋拈抨抽押拐拙拇拍抵拚抱拘拖拗拆抬拎放斧於旺昔易昌昆昂明昀昏昕昊"],["aa40","昇服朋杭枋枕東果杳杷枇枝林杯杰板枉松析杵枚枓杼杪杲欣武歧歿氓氛泣注泳沱泌泥河沽沾沼波沫法泓沸泄油況沮泗泅泱沿治泡泛泊沬泯泜泖泠"],["aaa1","炕炎炒炊炙爬爭爸版牧物狀狎狙狗狐玩玨玟玫玥甽疝疙疚的盂盲直知矽社祀祁秉秈空穹竺糾罔羌羋者肺肥肢肱股肫肩肴肪肯臥臾舍芳芝芙芭芽芟芹花芬芥芯芸芣芰芾芷虎虱初表軋迎返近邵邸邱邶采金長門阜陀阿阻附"],["ab40","陂隹雨青非亟亭亮信侵侯便俠俑俏保促侶俘俟俊俗侮俐俄係俚俎俞侷兗冒冑冠剎剃削前剌剋則勇勉勃勁匍南卻厚叛咬哀咨哎哉咸咦咳哇哂咽咪品"],["aba1","哄哈咯咫咱咻咩咧咿囿垂型垠垣垢城垮垓奕契奏奎奐姜姘姿姣姨娃姥姪姚姦威姻孩宣宦室客宥封屎屏屍屋峙峒巷帝帥帟幽庠度建弈弭彥很待徊律徇後徉怒思怠急怎怨恍恰恨恢恆恃恬恫恪恤扁拜挖按拼拭持拮拽指拱拷"],["ac40","拯括拾拴挑挂政故斫施既春昭映昧是星昨昱昤曷柿染柱柔某柬架枯柵柩柯柄柑枴柚查枸柏柞柳枰柙柢柝柒歪殃殆段毒毗氟泉洋洲洪流津洌洱洞洗"],["aca1","活洽派洶洛泵洹洧洸洩洮洵洎洫炫為炳炬炯炭炸炮炤爰牲牯牴狩狠狡玷珊玻玲珍珀玳甚甭畏界畎畋疫疤疥疢疣癸皆皇皈盈盆盃盅省盹相眉看盾盼眇矜砂研砌砍祆祉祈祇禹禺科秒秋穿突竿竽籽紂紅紀紉紇約紆缸美羿耄"],["ad40","耐耍耑耶胖胥胚胃胄背胡胛胎胞胤胝致舢苧范茅苣苛苦茄若茂茉苒苗英茁苜苔苑苞苓苟苯茆虐虹虻虺衍衫要觔計訂訃貞負赴赳趴軍軌述迦迢迪迥"],["ada1","迭迫迤迨郊郎郁郃酋酊重閂限陋陌降面革韋韭音頁風飛食首香乘亳倌倍倣俯倦倥俸倩倖倆值借倚倒們俺倀倔倨俱倡個候倘俳修倭倪俾倫倉兼冤冥冢凍凌准凋剖剜剔剛剝匪卿原厝叟哨唐唁唷哼哥哲唆哺唔哩哭員唉哮哪"],["ae40","哦唧唇哽唏圃圄埂埔埋埃堉夏套奘奚娑娘娜娟娛娓姬娠娣娩娥娌娉孫屘宰害家宴宮宵容宸射屑展屐峭峽峻峪峨峰島崁峴差席師庫庭座弱徒徑徐恙"],["aea1","恣恥恐恕恭恩息悄悟悚悍悔悌悅悖扇拳挈拿捎挾振捕捂捆捏捉挺捐挽挪挫挨捍捌效敉料旁旅時晉晏晃晒晌晅晁書朔朕朗校核案框桓根桂桔栩梳栗桌桑栽柴桐桀格桃株桅栓栘桁殊殉殷氣氧氨氦氤泰浪涕消涇浦浸海浙涓"],["af40","浬涉浮浚浴浩涌涊浹涅浥涔烊烘烤烙烈烏爹特狼狹狽狸狷玆班琉珮珠珪珞畔畝畜畚留疾病症疲疳疽疼疹痂疸皋皰益盍盎眩真眠眨矩砰砧砸砝破砷"],["afa1","砥砭砠砟砲祕祐祠祟祖神祝祗祚秤秣秧租秦秩秘窄窈站笆笑粉紡紗紋紊素索純紐紕級紜納紙紛缺罟羔翅翁耆耘耕耙耗耽耿胱脂胰脅胭胴脆胸胳脈能脊胼胯臭臬舀舐航舫舨般芻茫荒荔荊茸荐草茵茴荏茲茹茶茗荀茱茨荃"],["b040","虔蚊蚪蚓蚤蚩蚌蚣蚜衰衷袁袂衽衹記訐討訌訕訊託訓訖訏訑豈豺豹財貢起躬軒軔軏辱送逆迷退迺迴逃追逅迸邕郡郝郢酒配酌釘針釗釜釙閃院陣陡"],["b0a1","陛陝除陘陞隻飢馬骨高鬥鬲鬼乾偺偽停假偃偌做偉健偶偎偕偵側偷偏倏偯偭兜冕凰剪副勒務勘動匐匏匙匿區匾參曼商啪啦啄啞啡啃啊唱啖問啕唯啤唸售啜唬啣唳啁啗圈國圉域堅堊堆埠埤基堂堵執培夠奢娶婁婉婦婪婀"],["b140","娼婢婚婆婊孰寇寅寄寂宿密尉專將屠屜屝崇崆崎崛崖崢崑崩崔崙崤崧崗巢常帶帳帷康庸庶庵庾張強彗彬彩彫得徙從徘御徠徜恿患悉悠您惋悴惦悽"],["b1a1","情悻悵惜悼惘惕惆惟悸惚惇戚戛扈掠控捲掖探接捷捧掘措捱掩掉掃掛捫推掄授掙採掬排掏掀捻捩捨捺敝敖救教敗啟敏敘敕敔斜斛斬族旋旌旎晝晚晤晨晦晞曹勗望梁梯梢梓梵桿桶梱梧梗械梃棄梭梆梅梔條梨梟梡梂欲殺"],["b240","毫毬氫涎涼淳淙液淡淌淤添淺清淇淋涯淑涮淞淹涸混淵淅淒渚涵淚淫淘淪深淮淨淆淄涪淬涿淦烹焉焊烽烯爽牽犁猜猛猖猓猙率琅琊球理現琍瓠瓶"],["b2a1","瓷甜產略畦畢異疏痔痕疵痊痍皎盔盒盛眷眾眼眶眸眺硫硃硎祥票祭移窒窕笠笨笛第符笙笞笮粒粗粕絆絃統紮紹紼絀細紳組累終紲紱缽羞羚翌翎習耜聊聆脯脖脣脫脩脰脤舂舵舷舶船莎莞莘荸莢莖莽莫莒莊莓莉莠荷荻荼"],["b340","莆莧處彪蛇蛀蚶蛄蚵蛆蛋蚱蚯蛉術袞袈被袒袖袍袋覓規訪訝訣訥許設訟訛訢豉豚販責貫貨貪貧赧赦趾趺軛軟這逍通逗連速逝逐逕逞造透逢逖逛途"],["b3a1","部郭都酗野釵釦釣釧釭釩閉陪陵陳陸陰陴陶陷陬雀雪雩章竟頂頃魚鳥鹵鹿麥麻傢傍傅備傑傀傖傘傚最凱割剴創剩勞勝勛博厥啻喀喧啼喊喝喘喂喜喪喔喇喋喃喳單喟唾喲喚喻喬喱啾喉喫喙圍堯堪場堤堰報堡堝堠壹壺奠"],["b440","婷媚婿媒媛媧孳孱寒富寓寐尊尋就嵌嵐崴嵇巽幅帽幀幃幾廊廁廂廄弼彭復循徨惑惡悲悶惠愜愣惺愕惰惻惴慨惱愎惶愉愀愒戟扉掣掌描揀揩揉揆揍"],["b4a1","插揣提握揖揭揮捶援揪換摒揚揹敞敦敢散斑斐斯普晰晴晶景暑智晾晷曾替期朝棺棕棠棘棗椅棟棵森棧棹棒棲棣棋棍植椒椎棉棚楮棻款欺欽殘殖殼毯氮氯氬港游湔渡渲湧湊渠渥渣減湛湘渤湖湮渭渦湯渴湍渺測湃渝渾滋"],["b540","溉渙湎湣湄湲湩湟焙焚焦焰無然煮焜牌犄犀猶猥猴猩琺琪琳琢琥琵琶琴琯琛琦琨甥甦畫番痢痛痣痙痘痞痠登發皖皓皴盜睏短硝硬硯稍稈程稅稀窘"],["b5a1","窗窖童竣等策筆筐筒答筍筋筏筑粟粥絞結絨絕紫絮絲絡給絢絰絳善翔翕耋聒肅腕腔腋腑腎脹腆脾腌腓腴舒舜菩萃菸萍菠菅萋菁華菱菴著萊菰萌菌菽菲菊萸萎萄菜萇菔菟虛蛟蛙蛭蛔蛛蛤蛐蛞街裁裂袱覃視註詠評詞証詁"],["b640","詔詛詐詆訴診訶詖象貂貯貼貳貽賁費賀貴買貶貿貸越超趁跎距跋跚跑跌跛跆軻軸軼辜逮逵週逸進逶鄂郵鄉郾酣酥量鈔鈕鈣鈉鈞鈍鈐鈇鈑閔閏開閑"],["b6a1","間閒閎隊階隋陽隅隆隍陲隄雁雅雄集雇雯雲韌項順須飧飪飯飩飲飭馮馭黃黍黑亂傭債傲傳僅傾催傷傻傯僇剿剷剽募勦勤勢勣匯嗟嗨嗓嗦嗎嗜嗇嗑嗣嗤嗯嗚嗡嗅嗆嗥嗉園圓塞塑塘塗塚塔填塌塭塊塢塒塋奧嫁嫉嫌媾媽媼"],["b740","媳嫂媲嵩嵯幌幹廉廈弒彙徬微愚意慈感想愛惹愁愈慎慌慄慍愾愴愧愍愆愷戡戢搓搾搞搪搭搽搬搏搜搔損搶搖搗搆敬斟新暗暉暇暈暖暄暘暍會榔業"],["b7a1","楚楷楠楔極椰概楊楨楫楞楓楹榆楝楣楛歇歲毀殿毓毽溢溯滓溶滂源溝滇滅溥溘溼溺溫滑準溜滄滔溪溧溴煎煙煩煤煉照煜煬煦煌煥煞煆煨煖爺牒猷獅猿猾瑯瑚瑕瑟瑞瑁琿瑙瑛瑜當畸瘀痰瘁痲痱痺痿痴痳盞盟睛睫睦睞督"],["b840","睹睪睬睜睥睨睢矮碎碰碗碘碌碉硼碑碓硿祺祿禁萬禽稜稚稠稔稟稞窟窠筷節筠筮筧粱粳粵經絹綑綁綏絛置罩罪署義羨群聖聘肆肄腱腰腸腥腮腳腫"],["b8a1","腹腺腦舅艇蒂葷落萱葵葦葫葉葬葛萼萵葡董葩葭葆虞虜號蛹蜓蜈蜇蜀蛾蛻蜂蜃蜆蜊衙裟裔裙補裘裝裡裊裕裒覜解詫該詳試詩詰誇詼詣誠話誅詭詢詮詬詹詻訾詨豢貊貉賊資賈賄貲賃賂賅跡跟跨路跳跺跪跤跦躲較載軾輊"],["b940","辟農運遊道遂達逼違遐遇遏過遍遑逾遁鄒鄗酬酪酩釉鈷鉗鈸鈽鉀鈾鉛鉋鉤鉑鈴鉉鉍鉅鈹鈿鉚閘隘隔隕雍雋雉雊雷電雹零靖靴靶預頑頓頊頒頌飼飴"],["b9a1","飽飾馳馱馴髡鳩麂鼎鼓鼠僧僮僥僖僭僚僕像僑僱僎僩兢凳劃劂匱厭嗾嘀嘛嘗嗽嘔嘆嘉嘍嘎嗷嘖嘟嘈嘐嗶團圖塵塾境墓墊塹墅塽壽夥夢夤奪奩嫡嫦嫩嫗嫖嫘嫣孵寞寧寡寥實寨寢寤察對屢嶄嶇幛幣幕幗幔廓廖弊彆彰徹慇"],["ba40","愿態慷慢慣慟慚慘慵截撇摘摔撤摸摟摺摑摧搴摭摻敲斡旗旖暢暨暝榜榨榕槁榮槓構榛榷榻榫榴槐槍榭槌榦槃榣歉歌氳漳演滾漓滴漩漾漠漬漏漂漢"],["baa1","滿滯漆漱漸漲漣漕漫漯澈漪滬漁滲滌滷熔熙煽熊熄熒爾犒犖獄獐瑤瑣瑪瑰瑭甄疑瘧瘍瘋瘉瘓盡監瞄睽睿睡磁碟碧碳碩碣禎福禍種稱窪窩竭端管箕箋筵算箝箔箏箸箇箄粹粽精綻綰綜綽綾綠緊綴網綱綺綢綿綵綸維緒緇綬"],["bb40","罰翠翡翟聞聚肇腐膀膏膈膊腿膂臧臺與舔舞艋蓉蒿蓆蓄蒙蒞蒲蒜蓋蒸蓀蓓蒐蒼蓑蓊蜿蜜蜻蜢蜥蜴蜘蝕蜷蜩裳褂裴裹裸製裨褚裯誦誌語誣認誡誓誤"],["bba1","說誥誨誘誑誚誧豪貍貌賓賑賒赫趙趕跼輔輒輕輓辣遠遘遜遣遙遞遢遝遛鄙鄘鄞酵酸酷酴鉸銀銅銘銖鉻銓銜銨鉼銑閡閨閩閣閥閤隙障際雌雒需靼鞅韶頗領颯颱餃餅餌餉駁骯骰髦魁魂鳴鳶鳳麼鼻齊億儀僻僵價儂儈儉儅凜"],["bc40","劇劈劉劍劊勰厲嘮嘻嘹嘲嘿嘴嘩噓噎噗噴嘶嘯嘰墀墟增墳墜墮墩墦奭嬉嫻嬋嫵嬌嬈寮寬審寫層履嶝嶔幢幟幡廢廚廟廝廣廠彈影德徵慶慧慮慝慕憂"],["bca1","慼慰慫慾憧憐憫憎憬憚憤憔憮戮摩摯摹撞撲撈撐撰撥撓撕撩撒撮播撫撚撬撙撢撳敵敷數暮暫暴暱樣樟槨樁樞標槽模樓樊槳樂樅槭樑歐歎殤毅毆漿潼澄潑潦潔澆潭潛潸潮澎潺潰潤澗潘滕潯潠潟熟熬熱熨牖犛獎獗瑩璋璃"],["bd40","瑾璀畿瘠瘩瘟瘤瘦瘡瘢皚皺盤瞎瞇瞌瞑瞋磋磅確磊碾磕碼磐稿稼穀稽稷稻窯窮箭箱範箴篆篇篁箠篌糊締練緯緻緘緬緝編緣線緞緩綞緙緲緹罵罷羯"],["bda1","翩耦膛膜膝膠膚膘蔗蔽蔚蓮蔬蔭蔓蔑蔣蔡蔔蓬蔥蓿蔆螂蝴蝶蝠蝦蝸蝨蝙蝗蝌蝓衛衝褐複褒褓褕褊誼諒談諄誕請諸課諉諂調誰論諍誶誹諛豌豎豬賠賞賦賤賬賭賢賣賜質賡赭趟趣踫踐踝踢踏踩踟踡踞躺輝輛輟輩輦輪輜輞"],["be40","輥適遮遨遭遷鄰鄭鄧鄱醇醉醋醃鋅銻銷鋪銬鋤鋁銳銼鋒鋇鋰銲閭閱霄霆震霉靠鞍鞋鞏頡頫頜颳養餓餒餘駝駐駟駛駑駕駒駙骷髮髯鬧魅魄魷魯鴆鴉"],["bea1","鴃麩麾黎墨齒儒儘儔儐儕冀冪凝劑劓勳噙噫噹噩噤噸噪器噥噱噯噬噢噶壁墾壇壅奮嬝嬴學寰導彊憲憑憩憊懍憶憾懊懈戰擅擁擋撻撼據擄擇擂操撿擒擔撾整曆曉暹曄曇暸樽樸樺橙橫橘樹橄橢橡橋橇樵機橈歙歷氅濂澱澡"],["bf40","濃澤濁澧澳激澹澶澦澠澴熾燉燐燒燈燕熹燎燙燜燃燄獨璜璣璘璟璞瓢甌甍瘴瘸瘺盧盥瞠瞞瞟瞥磨磚磬磧禦積穎穆穌穋窺篙簑築篤篛篡篩篦糕糖縊"],["bfa1","縑縈縛縣縞縝縉縐罹羲翰翱翮耨膳膩膨臻興艘艙蕊蕙蕈蕨蕩蕃蕉蕭蕪蕞螃螟螞螢融衡褪褲褥褫褡親覦諦諺諫諱謀諜諧諮諾謁謂諷諭諳諶諼豫豭貓賴蹄踱踴蹂踹踵輻輯輸輳辨辦遵遴選遲遼遺鄴醒錠錶鋸錳錯錢鋼錫錄錚"],["c040","錐錦錡錕錮錙閻隧隨險雕霎霑霖霍霓霏靛靜靦鞘頰頸頻頷頭頹頤餐館餞餛餡餚駭駢駱骸骼髻髭鬨鮑鴕鴣鴦鴨鴒鴛默黔龍龜優償儡儲勵嚎嚀嚐嚅嚇"],["c0a1","嚏壕壓壑壎嬰嬪嬤孺尷屨嶼嶺嶽嶸幫彌徽應懂懇懦懋戲戴擎擊擘擠擰擦擬擱擢擭斂斃曙曖檀檔檄檢檜櫛檣橾檗檐檠歜殮毚氈濘濱濟濠濛濤濫濯澀濬濡濩濕濮濰燧營燮燦燥燭燬燴燠爵牆獰獲璩環璦璨癆療癌盪瞳瞪瞰瞬"],["c140","瞧瞭矯磷磺磴磯礁禧禪穗窿簇簍篾篷簌篠糠糜糞糢糟糙糝縮績繆縷縲繃縫總縱繅繁縴縹繈縵縿縯罄翳翼聱聲聰聯聳臆臃膺臂臀膿膽臉膾臨舉艱薪"],["c1a1","薄蕾薜薑薔薯薛薇薨薊虧蟀蟑螳蟒蟆螫螻螺蟈蟋褻褶襄褸褽覬謎謗謙講謊謠謝謄謐豁谿豳賺賽購賸賻趨蹉蹋蹈蹊轄輾轂轅輿避遽還邁邂邀鄹醣醞醜鍍鎂錨鍵鍊鍥鍋錘鍾鍬鍛鍰鍚鍔闊闋闌闈闆隱隸雖霜霞鞠韓顆颶餵騁"],["c240","駿鮮鮫鮪鮭鴻鴿麋黏點黜黝黛鼾齋叢嚕嚮壙壘嬸彝懣戳擴擲擾攆擺擻擷斷曜朦檳檬櫃檻檸櫂檮檯歟歸殯瀉瀋濾瀆濺瀑瀏燻燼燾燸獷獵璧璿甕癖癘"],["c2a1","癒瞽瞿瞻瞼礎禮穡穢穠竄竅簫簧簪簞簣簡糧織繕繞繚繡繒繙罈翹翻職聶臍臏舊藏薩藍藐藉薰薺薹薦蟯蟬蟲蟠覆覲觴謨謹謬謫豐贅蹙蹣蹦蹤蹟蹕軀轉轍邇邃邈醫醬釐鎔鎊鎖鎢鎳鎮鎬鎰鎘鎚鎗闔闖闐闕離雜雙雛雞霤鞣鞦"],["c340","鞭韹額顏題顎顓颺餾餿餽餮馥騎髁鬃鬆魏魎魍鯊鯉鯽鯈鯀鵑鵝鵠黠鼕鼬儳嚥壞壟壢寵龐廬懲懷懶懵攀攏曠曝櫥櫝櫚櫓瀛瀟瀨瀚瀝瀕瀘爆爍牘犢獸"],["c3a1","獺璽瓊瓣疇疆癟癡矇礙禱穫穩簾簿簸簽簷籀繫繭繹繩繪羅繳羶羹羸臘藩藝藪藕藤藥藷蟻蠅蠍蟹蟾襠襟襖襞譁譜識證譚譎譏譆譙贈贊蹼蹲躇蹶蹬蹺蹴轔轎辭邊邋醱醮鏡鏑鏟鏃鏈鏜鏝鏖鏢鏍鏘鏤鏗鏨關隴難霪霧靡韜韻類"],["c440","願顛颼饅饉騖騙鬍鯨鯧鯖鯛鶉鵡鵲鵪鵬麒麗麓麴勸嚨嚷嚶嚴嚼壤孀孃孽寶巉懸懺攘攔攙曦朧櫬瀾瀰瀲爐獻瓏癢癥礦礪礬礫竇競籌籃籍糯糰辮繽繼"],["c4a1","纂罌耀臚艦藻藹蘑藺蘆蘋蘇蘊蠔蠕襤覺觸議譬警譯譟譫贏贍躉躁躅躂醴釋鐘鐃鏽闡霰飄饒饑馨騫騰騷騵鰓鰍鹹麵黨鼯齟齣齡儷儸囁囀囂夔屬巍懼懾攝攜斕曩櫻欄櫺殲灌爛犧瓖瓔癩矓籐纏續羼蘗蘭蘚蠣蠢蠡蠟襪襬覽譴"],["c540","護譽贓躊躍躋轟辯醺鐮鐳鐵鐺鐸鐲鐫闢霸霹露響顧顥饗驅驃驀騾髏魔魑鰭鰥鶯鶴鷂鶸麝黯鼙齜齦齧儼儻囈囊囉孿巔巒彎懿攤權歡灑灘玀瓤疊癮癬"],["c5a1","禳籠籟聾聽臟襲襯觼讀贖贗躑躓轡酈鑄鑑鑒霽霾韃韁顫饕驕驍髒鬚鱉鰱鰾鰻鷓鷗鼴齬齪龔囌巖戀攣攫攪曬欐瓚竊籤籣籥纓纖纔臢蘸蘿蠱變邐邏鑣鑠鑤靨顯饜驚驛驗髓體髑鱔鱗鱖鷥麟黴囑壩攬灞癱癲矗罐羈蠶蠹衢讓讒"],["c640","讖艷贛釀鑪靂靈靄韆顰驟鬢魘鱟鷹鷺鹼鹽鼇齷齲廳欖灣籬籮蠻觀躡釁鑲鑰顱饞髖鬣黌灤矚讚鑷韉驢驥纜讜躪釅鑽鑾鑼鱷鱸黷豔鑿鸚爨驪鬱鸛鸞籲"],["c940","乂乜凵匚厂万丌乇亍囗兀屮彳丏冇与丮亓仂仉仈冘勼卬厹圠夃夬尐巿旡殳毌气爿丱丼仨仜仩仡仝仚刌匜卌圢圣夗夯宁宄尒尻屴屳帄庀庂忉戉扐氕"],["c9a1","氶汃氿氻犮犰玊禸肊阞伎优伬仵伔仱伀价伈伝伂伅伢伓伄仴伒冱刓刉刐劦匢匟卍厊吇囡囟圮圪圴夼妀奼妅奻奾奷奿孖尕尥屼屺屻屾巟幵庄异弚彴忕忔忏扜扞扤扡扦扢扙扠扚扥旯旮朾朹朸朻机朿朼朳氘汆汒汜汏汊汔汋"],["ca40","汌灱牞犴犵玎甪癿穵网艸艼芀艽艿虍襾邙邗邘邛邔阢阤阠阣佖伻佢佉体佤伾佧佒佟佁佘伭伳伿佡冏冹刜刞刡劭劮匉卣卲厎厏吰吷吪呔呅吙吜吥吘"],["caa1","吽呏呁吨吤呇囮囧囥坁坅坌坉坋坒夆奀妦妘妠妗妎妢妐妏妧妡宎宒尨尪岍岏岈岋岉岒岊岆岓岕巠帊帎庋庉庌庈庍弅弝彸彶忒忑忐忭忨忮忳忡忤忣忺忯忷忻怀忴戺抃抌抎抏抔抇扱扻扺扰抁抈扷扽扲扴攷旰旴旳旲旵杅杇"],["cb40","杙杕杌杈杝杍杚杋毐氙氚汸汧汫沄沋沏汱汯汩沚汭沇沕沜汦汳汥汻沎灴灺牣犿犽狃狆狁犺狅玕玗玓玔玒町甹疔疕皁礽耴肕肙肐肒肜芐芏芅芎芑芓"],["cba1","芊芃芄豸迉辿邟邡邥邞邧邠阰阨阯阭丳侘佼侅佽侀侇佶佴侉侄佷佌侗佪侚佹侁佸侐侜侔侞侒侂侕佫佮冞冼冾刵刲刳剆刱劼匊匋匼厒厔咇呿咁咑咂咈呫呺呾呥呬呴呦咍呯呡呠咘呣呧呤囷囹坯坲坭坫坱坰坶垀坵坻坳坴坢"],["cc40","坨坽夌奅妵妺姏姎妲姌姁妶妼姃姖妱妽姀姈妴姇孢孥宓宕屄屇岮岤岠岵岯岨岬岟岣岭岢岪岧岝岥岶岰岦帗帔帙弨弢弣弤彔徂彾彽忞忥怭怦怙怲怋"],["cca1","怴怊怗怳怚怞怬怢怍怐怮怓怑怌怉怜戔戽抭抴拑抾抪抶拊抮抳抯抻抩抰抸攽斨斻昉旼昄昒昈旻昃昋昍昅旽昑昐曶朊枅杬枎枒杶杻枘枆构杴枍枌杺枟枑枙枃杽极杸杹枔欥殀歾毞氝沓泬泫泮泙沶泔沭泧沷泐泂沺泃泆泭泲"],["cd40","泒泝沴沊沝沀泞泀洰泍泇沰泹泏泩泑炔炘炅炓炆炄炑炖炂炚炃牪狖狋狘狉狜狒狔狚狌狑玤玡玭玦玢玠玬玝瓝瓨甿畀甾疌疘皯盳盱盰盵矸矼矹矻矺"],["cda1","矷祂礿秅穸穻竻籵糽耵肏肮肣肸肵肭舠芠苀芫芚芘芛芵芧芮芼芞芺芴芨芡芩苂芤苃芶芢虰虯虭虮豖迒迋迓迍迖迕迗邲邴邯邳邰阹阽阼阺陃俍俅俓侲俉俋俁俔俜俙侻侳俛俇俖侺俀侹俬剄剉勀勂匽卼厗厖厙厘咺咡咭咥哏"],["ce40","哃茍咷咮哖咶哅哆咠呰咼咢咾呲哞咰垵垞垟垤垌垗垝垛垔垘垏垙垥垚垕壴复奓姡姞姮娀姱姝姺姽姼姶姤姲姷姛姩姳姵姠姾姴姭宨屌峐峘峌峗峋峛"],["cea1","峞峚峉峇峊峖峓峔峏峈峆峎峟峸巹帡帢帣帠帤庰庤庢庛庣庥弇弮彖徆怷怹恔恲恞恅恓恇恉恛恌恀恂恟怤恄恘恦恮扂扃拏挍挋拵挎挃拫拹挏挌拸拶挀挓挔拺挕拻拰敁敃斪斿昶昡昲昵昜昦昢昳昫昺昝昴昹昮朏朐柁柲柈枺"],["cf40","柜枻柸柘柀枷柅柫柤柟枵柍枳柷柶柮柣柂枹柎柧柰枲柼柆柭柌枮柦柛柺柉柊柃柪柋欨殂殄殶毖毘毠氠氡洨洴洭洟洼洿洒洊泚洳洄洙洺洚洑洀洝浂"],["cfa1","洁洘洷洃洏浀洇洠洬洈洢洉洐炷炟炾炱炰炡炴炵炩牁牉牊牬牰牳牮狊狤狨狫狟狪狦狣玅珌珂珈珅玹玶玵玴珫玿珇玾珃珆玸珋瓬瓮甮畇畈疧疪癹盄眈眃眄眅眊盷盻盺矧矨砆砑砒砅砐砏砎砉砃砓祊祌祋祅祄秕种秏秖秎窀"],["d040","穾竑笀笁籺籸籹籿粀粁紃紈紁罘羑羍羾耇耎耏耔耷胘胇胠胑胈胂胐胅胣胙胜胊胕胉胏胗胦胍臿舡芔苙苾苹茇苨茀苕茺苫苖苴苬苡苲苵茌苻苶苰苪"],["d0a1","苤苠苺苳苭虷虴虼虳衁衎衧衪衩觓訄訇赲迣迡迮迠郱邽邿郕郅邾郇郋郈釔釓陔陏陑陓陊陎倞倅倇倓倢倰倛俵俴倳倷倬俶俷倗倜倠倧倵倯倱倎党冔冓凊凄凅凈凎剡剚剒剞剟剕剢勍匎厞唦哢唗唒哧哳哤唚哿唄唈哫唑唅哱"],["d140","唊哻哷哸哠唎唃唋圁圂埌堲埕埒垺埆垽垼垸垶垿埇埐垹埁夎奊娙娖娭娮娕娏娗娊娞娳孬宧宭宬尃屖屔峬峿峮峱峷崀峹帩帨庨庮庪庬弳弰彧恝恚恧"],["d1a1","恁悢悈悀悒悁悝悃悕悛悗悇悜悎戙扆拲挐捖挬捄捅挶捃揤挹捋捊挼挩捁挴捘捔捙挭捇挳捚捑挸捗捀捈敊敆旆旃旄旂晊晟晇晑朒朓栟栚桉栲栳栻桋桏栖栱栜栵栫栭栯桎桄栴栝栒栔栦栨栮桍栺栥栠欬欯欭欱欴歭肂殈毦毤"],["d240","毨毣毢毧氥浺浣浤浶洍浡涒浘浢浭浯涑涍淯浿涆浞浧浠涗浰浼浟涂涘洯浨涋浾涀涄洖涃浻浽浵涐烜烓烑烝烋缹烢烗烒烞烠烔烍烅烆烇烚烎烡牂牸"],["d2a1","牷牶猀狺狴狾狶狳狻猁珓珙珥珖玼珧珣珩珜珒珛珔珝珚珗珘珨瓞瓟瓴瓵甡畛畟疰痁疻痄痀疿疶疺皊盉眝眛眐眓眒眣眑眕眙眚眢眧砣砬砢砵砯砨砮砫砡砩砳砪砱祔祛祏祜祓祒祑秫秬秠秮秭秪秜秞秝窆窉窅窋窌窊窇竘笐"],["d340","笄笓笅笏笈笊笎笉笒粄粑粊粌粈粍粅紞紝紑紎紘紖紓紟紒紏紌罜罡罞罠罝罛羖羒翃翂翀耖耾耹胺胲胹胵脁胻脀舁舯舥茳茭荄茙荑茥荖茿荁茦茜茢"],["d3a1","荂荎茛茪茈茼荍茖茤茠茷茯茩荇荅荌荓茞茬荋茧荈虓虒蚢蚨蚖蚍蚑蚞蚇蚗蚆蚋蚚蚅蚥蚙蚡蚧蚕蚘蚎蚝蚐蚔衃衄衭衵衶衲袀衱衿衯袃衾衴衼訒豇豗豻貤貣赶赸趵趷趶軑軓迾迵适迿迻逄迼迶郖郠郙郚郣郟郥郘郛郗郜郤酐"],["d440","酎酏釕釢釚陜陟隼飣髟鬯乿偰偪偡偞偠偓偋偝偲偈偍偁偛偊偢倕偅偟偩偫偣偤偆偀偮偳偗偑凐剫剭剬剮勖勓匭厜啵啶唼啍啐唴唪啑啢唶唵唰啒啅"],["d4a1","唌唲啥啎唹啈唭唻啀啋圊圇埻堔埢埶埜埴堀埭埽堈埸堋埳埏堇埮埣埲埥埬埡堎埼堐埧堁堌埱埩埰堍堄奜婠婘婕婧婞娸娵婭婐婟婥婬婓婤婗婃婝婒婄婛婈媎娾婍娹婌婰婩婇婑婖婂婜孲孮寁寀屙崞崋崝崚崠崌崨崍崦崥崏"],["d540","崰崒崣崟崮帾帴庱庴庹庲庳弶弸徛徖徟悊悐悆悾悰悺惓惔惏惤惙惝惈悱惛悷惊悿惃惍惀挲捥掊掂捽掽掞掭掝掗掫掎捯掇掐据掯捵掜捭掮捼掤挻掟"],["d5a1","捸掅掁掑掍捰敓旍晥晡晛晙晜晢朘桹梇梐梜桭桮梮梫楖桯梣梬梩桵桴梲梏桷梒桼桫桲梪梀桱桾梛梖梋梠梉梤桸桻梑梌梊桽欶欳欷欸殑殏殍殎殌氪淀涫涴涳湴涬淩淢涷淶淔渀淈淠淟淖涾淥淜淝淛淴淊涽淭淰涺淕淂淏淉"],["d640","淐淲淓淽淗淍淣涻烺焍烷焗烴焌烰焄烳焐烼烿焆焓焀烸烶焋焂焎牾牻牼牿猝猗猇猑猘猊猈狿猏猞玈珶珸珵琄琁珽琇琀珺珼珿琌琋珴琈畤畣痎痒痏"],["d6a1","痋痌痑痐皏皉盓眹眯眭眱眲眴眳眽眥眻眵硈硒硉硍硊硌砦硅硐祤祧祩祪祣祫祡离秺秸秶秷窏窔窐笵筇笴笥笰笢笤笳笘笪笝笱笫笭笯笲笸笚笣粔粘粖粣紵紽紸紶紺絅紬紩絁絇紾紿絊紻紨罣羕羜羝羛翊翋翍翐翑翇翏翉耟"],["d740","耞耛聇聃聈脘脥脙脛脭脟脬脞脡脕脧脝脢舑舸舳舺舴舲艴莐莣莨莍荺荳莤荴莏莁莕莙荵莔莩荽莃莌莝莛莪莋荾莥莯莈莗莰荿莦莇莮荶莚虙虖蚿蚷"],["d7a1","蛂蛁蛅蚺蚰蛈蚹蚳蚸蛌蚴蚻蚼蛃蚽蚾衒袉袕袨袢袪袚袑袡袟袘袧袙袛袗袤袬袌袓袎覂觖觙觕訰訧訬訞谹谻豜豝豽貥赽赻赹趼跂趹趿跁軘軞軝軜軗軠軡逤逋逑逜逌逡郯郪郰郴郲郳郔郫郬郩酖酘酚酓酕釬釴釱釳釸釤釹釪"],["d840","釫釷釨釮镺閆閈陼陭陫陱陯隿靪頄飥馗傛傕傔傞傋傣傃傌傎傝偨傜傒傂傇兟凔匒匑厤厧喑喨喥喭啷噅喢喓喈喏喵喁喣喒喤啽喌喦啿喕喡喎圌堩堷"],["d8a1","堙堞堧堣堨埵塈堥堜堛堳堿堶堮堹堸堭堬堻奡媯媔媟婺媢媞婸媦婼媥媬媕媮娷媄媊媗媃媋媩婻婽媌媜媏媓媝寪寍寋寔寑寊寎尌尰崷嵃嵫嵁嵋崿崵嵑嵎嵕崳崺嵒崽崱嵙嵂崹嵉崸崼崲崶嵀嵅幄幁彘徦徥徫惉悹惌惢惎惄愔"],["d940","惲愊愖愅惵愓惸惼惾惁愃愘愝愐惿愄愋扊掔掱掰揎揥揨揯揃撝揳揊揠揶揕揲揵摡揟掾揝揜揄揘揓揂揇揌揋揈揰揗揙攲敧敪敤敜敨敥斌斝斞斮旐旒"],["d9a1","晼晬晻暀晱晹晪晲朁椌棓椄棜椪棬棪棱椏棖棷棫棤棶椓椐棳棡椇棌椈楰梴椑棯棆椔棸棐棽棼棨椋椊椗棎棈棝棞棦棴棑椆棔棩椕椥棇欹欻欿欼殔殗殙殕殽毰毲毳氰淼湆湇渟湉溈渼渽湅湢渫渿湁湝湳渜渳湋湀湑渻渃渮湞"],["da40","湨湜湡渱渨湠湱湫渹渢渰湓湥渧湸湤湷湕湹湒湦渵渶湚焠焞焯烻焮焱焣焥焢焲焟焨焺焛牋牚犈犉犆犅犋猒猋猰猢猱猳猧猲猭猦猣猵猌琮琬琰琫琖"],["daa1","琚琡琭琱琤琣琝琩琠琲瓻甯畯畬痧痚痡痦痝痟痤痗皕皒盚睆睇睄睍睅睊睎睋睌矞矬硠硤硥硜硭硱硪确硰硩硨硞硢祴祳祲祰稂稊稃稌稄窙竦竤筊笻筄筈筌筎筀筘筅粢粞粨粡絘絯絣絓絖絧絪絏絭絜絫絒絔絩絑絟絎缾缿罥"],["db40","罦羢羠羡翗聑聏聐胾胔腃腊腒腏腇脽腍脺臦臮臷臸臹舄舼舽舿艵茻菏菹萣菀菨萒菧菤菼菶萐菆菈菫菣莿萁菝菥菘菿菡菋菎菖菵菉萉萏菞萑萆菂菳"],["dba1","菕菺菇菑菪萓菃菬菮菄菻菗菢萛菛菾蛘蛢蛦蛓蛣蛚蛪蛝蛫蛜蛬蛩蛗蛨蛑衈衖衕袺裗袹袸裀袾袶袼袷袽袲褁裉覕覘覗觝觚觛詎詍訹詙詀詗詘詄詅詒詈詑詊詌詏豟貁貀貺貾貰貹貵趄趀趉跘跓跍跇跖跜跏跕跙跈跗跅軯軷軺"],["dc40","軹軦軮軥軵軧軨軶軫軱軬軴軩逭逴逯鄆鄬鄄郿郼鄈郹郻鄁鄀鄇鄅鄃酡酤酟酢酠鈁鈊鈥鈃鈚鈦鈏鈌鈀鈒釿釽鈆鈄鈧鈂鈜鈤鈙鈗鈅鈖镻閍閌閐隇陾隈"],["dca1","隉隃隀雂雈雃雱雰靬靰靮頇颩飫鳦黹亃亄亶傽傿僆傮僄僊傴僈僂傰僁傺傱僋僉傶傸凗剺剸剻剼嗃嗛嗌嗐嗋嗊嗝嗀嗔嗄嗩喿嗒喍嗏嗕嗢嗖嗈嗲嗍嗙嗂圔塓塨塤塏塍塉塯塕塎塝塙塥塛堽塣塱壼嫇嫄嫋媺媸媱媵媰媿嫈媻嫆"],["dd40","媷嫀嫊媴媶嫍媹媐寖寘寙尟尳嵱嵣嵊嵥嵲嵬嵞嵨嵧嵢巰幏幎幊幍幋廅廌廆廋廇彀徯徭惷慉慊愫慅愶愲愮慆愯慏愩慀戠酨戣戥戤揅揱揫搐搒搉搠搤"],["dda1","搳摃搟搕搘搹搷搢搣搌搦搰搨摁搵搯搊搚摀搥搧搋揧搛搮搡搎敯斒旓暆暌暕暐暋暊暙暔晸朠楦楟椸楎楢楱椿楅楪椹楂楗楙楺楈楉椵楬椳椽楥棰楸椴楩楀楯楄楶楘楁楴楌椻楋椷楜楏楑椲楒椯楻椼歆歅歃歂歈歁殛嗀毻毼"],["de40","毹毷毸溛滖滈溏滀溟溓溔溠溱溹滆滒溽滁溞滉溷溰滍溦滏溲溾滃滜滘溙溒溎溍溤溡溿溳滐滊溗溮溣煇煔煒煣煠煁煝煢煲煸煪煡煂煘煃煋煰煟煐煓"],["dea1","煄煍煚牏犍犌犑犐犎猼獂猻猺獀獊獉瑄瑊瑋瑒瑑瑗瑀瑏瑐瑎瑂瑆瑍瑔瓡瓿瓾瓽甝畹畷榃痯瘏瘃痷痾痼痹痸瘐痻痶痭痵痽皙皵盝睕睟睠睒睖睚睩睧睔睙睭矠碇碚碔碏碄碕碅碆碡碃硹碙碀碖硻祼禂祽祹稑稘稙稒稗稕稢稓"],["df40","稛稐窣窢窞竫筦筤筭筴筩筲筥筳筱筰筡筸筶筣粲粴粯綈綆綀綍絿綅絺綎絻綃絼綌綔綄絽綒罭罫罧罨罬羦羥羧翛翜耡腤腠腷腜腩腛腢腲朡腞腶腧腯"],["dfa1","腄腡舝艉艄艀艂艅蓱萿葖葶葹蒏蒍葥葑葀蒆葧萰葍葽葚葙葴葳葝蔇葞萷萺萴葺葃葸萲葅萩菙葋萯葂萭葟葰萹葎葌葒葯蓅蒎萻葇萶萳葨葾葄萫葠葔葮葐蜋蜄蛷蜌蛺蛖蛵蝍蛸蜎蜉蜁蛶蜍蜅裖裋裍裎裞裛裚裌裐覅覛觟觥觤"],["e040","觡觠觢觜触詶誆詿詡訿詷誂誄詵誃誁詴詺谼豋豊豥豤豦貆貄貅賌赨赩趑趌趎趏趍趓趔趐趒跰跠跬跱跮跐跩跣跢跧跲跫跴輆軿輁輀輅輇輈輂輋遒逿"],["e0a1","遄遉逽鄐鄍鄏鄑鄖鄔鄋鄎酮酯鉈鉒鈰鈺鉦鈳鉥鉞銃鈮鉊鉆鉭鉬鉏鉠鉧鉯鈶鉡鉰鈱鉔鉣鉐鉲鉎鉓鉌鉖鈲閟閜閞閛隒隓隑隗雎雺雽雸雵靳靷靸靲頏頍頎颬飶飹馯馲馰馵骭骫魛鳪鳭鳧麀黽僦僔僗僨僳僛僪僝僤僓僬僰僯僣僠"],["e140","凘劀劁勩勫匰厬嘧嘕嘌嘒嗼嘏嘜嘁嘓嘂嗺嘝嘄嗿嗹墉塼墐墘墆墁塿塴墋塺墇墑墎塶墂墈塻墔墏壾奫嫜嫮嫥嫕嫪嫚嫭嫫嫳嫢嫠嫛嫬嫞嫝嫙嫨嫟孷寠"],["e1a1","寣屣嶂嶀嵽嶆嵺嶁嵷嶊嶉嶈嵾嵼嶍嵹嵿幘幙幓廘廑廗廎廜廕廙廒廔彄彃彯徶愬愨慁慞慱慳慒慓慲慬憀慴慔慺慛慥愻慪慡慖戩戧戫搫摍摛摝摴摶摲摳摽摵摦撦摎撂摞摜摋摓摠摐摿搿摬摫摙摥摷敳斠暡暠暟朅朄朢榱榶槉"],["e240","榠槎榖榰榬榼榑榙榎榧榍榩榾榯榿槄榽榤槔榹槊榚槏榳榓榪榡榞槙榗榐槂榵榥槆歊歍歋殞殟殠毃毄毾滎滵滱漃漥滸漷滻漮漉潎漙漚漧漘漻漒滭漊"],["e2a1","漶潳滹滮漭潀漰漼漵滫漇漎潃漅滽滶漹漜滼漺漟漍漞漈漡熇熐熉熀熅熂熏煻熆熁熗牄牓犗犕犓獃獍獑獌瑢瑳瑱瑵瑲瑧瑮甀甂甃畽疐瘖瘈瘌瘕瘑瘊瘔皸瞁睼瞅瞂睮瞀睯睾瞃碲碪碴碭碨硾碫碞碥碠碬碢碤禘禊禋禖禕禔禓"],["e340","禗禈禒禐稫穊稰稯稨稦窨窫窬竮箈箜箊箑箐箖箍箌箛箎箅箘劄箙箤箂粻粿粼粺綧綷緂綣綪緁緀緅綝緎緄緆緋緌綯綹綖綼綟綦綮綩綡緉罳翢翣翥翞"],["e3a1","耤聝聜膉膆膃膇膍膌膋舕蒗蒤蒡蒟蒺蓎蓂蒬蒮蒫蒹蒴蓁蓍蒪蒚蒱蓐蒝蒧蒻蒢蒔蓇蓌蒛蒩蒯蒨蓖蒘蒶蓏蒠蓗蓔蓒蓛蒰蒑虡蜳蜣蜨蝫蝀蜮蜞蜡蜙蜛蝃蜬蝁蜾蝆蜠蜲蜪蜭蜼蜒蜺蜱蜵蝂蜦蜧蜸蜤蜚蜰蜑裷裧裱裲裺裾裮裼裶裻"],["e440","裰裬裫覝覡覟覞觩觫觨誫誙誋誒誏誖谽豨豩賕賏賗趖踉踂跿踍跽踊踃踇踆踅跾踀踄輐輑輎輍鄣鄜鄠鄢鄟鄝鄚鄤鄡鄛酺酲酹酳銥銤鉶銛鉺銠銔銪銍"],["e4a1","銦銚銫鉹銗鉿銣鋮銎銂銕銢鉽銈銡銊銆銌銙銧鉾銇銩銝銋鈭隞隡雿靘靽靺靾鞃鞀鞂靻鞄鞁靿韎韍頖颭颮餂餀餇馝馜駃馹馻馺駂馽駇骱髣髧鬾鬿魠魡魟鳱鳲鳵麧僿儃儰僸儆儇僶僾儋儌僽儊劋劌勱勯噈噂噌嘵噁噊噉噆噘"],["e540","噚噀嘳嘽嘬嘾嘸嘪嘺圚墫墝墱墠墣墯墬墥墡壿嫿嫴嫽嫷嫶嬃嫸嬂嫹嬁嬇嬅嬏屧嶙嶗嶟嶒嶢嶓嶕嶠嶜嶡嶚嶞幩幝幠幜緳廛廞廡彉徲憋憃慹憱憰憢憉"],["e5a1","憛憓憯憭憟憒憪憡憍慦憳戭摮摰撖撠撅撗撜撏撋撊撌撣撟摨撱撘敶敺敹敻斲斳暵暰暩暲暷暪暯樀樆樗槥槸樕槱槤樠槿槬槢樛樝槾樧槲槮樔槷槧橀樈槦槻樍槼槫樉樄樘樥樏槶樦樇槴樖歑殥殣殢殦氁氀毿氂潁漦潾澇濆澒"],["e640","澍澉澌潢潏澅潚澖潶潬澂潕潲潒潐潗澔澓潝漀潡潫潽潧澐潓澋潩潿澕潣潷潪潻熲熯熛熰熠熚熩熵熝熥熞熤熡熪熜熧熳犘犚獘獒獞獟獠獝獛獡獚獙"],["e6a1","獢璇璉璊璆璁瑽璅璈瑼瑹甈甇畾瘥瘞瘙瘝瘜瘣瘚瘨瘛皜皝皞皛瞍瞏瞉瞈磍碻磏磌磑磎磔磈磃磄磉禚禡禠禜禢禛歶稹窲窴窳箷篋箾箬篎箯箹篊箵糅糈糌糋緷緛緪緧緗緡縃緺緦緶緱緰緮緟罶羬羰羭翭翫翪翬翦翨聤聧膣膟"],["e740","膞膕膢膙膗舖艏艓艒艐艎艑蔤蔻蔏蔀蔩蔎蔉蔍蔟蔊蔧蔜蓻蔫蓺蔈蔌蓴蔪蓲蔕蓷蓫蓳蓼蔒蓪蓩蔖蓾蔨蔝蔮蔂蓽蔞蓶蔱蔦蓧蓨蓰蓯蓹蔘蔠蔰蔋蔙蔯虢"],["e7a1","蝖蝣蝤蝷蟡蝳蝘蝔蝛蝒蝡蝚蝑蝞蝭蝪蝐蝎蝟蝝蝯蝬蝺蝮蝜蝥蝏蝻蝵蝢蝧蝩衚褅褌褔褋褗褘褙褆褖褑褎褉覢覤覣觭觰觬諏諆誸諓諑諔諕誻諗誾諀諅諘諃誺誽諙谾豍貏賥賟賙賨賚賝賧趠趜趡趛踠踣踥踤踮踕踛踖踑踙踦踧"],["e840","踔踒踘踓踜踗踚輬輤輘輚輠輣輖輗遳遰遯遧遫鄯鄫鄩鄪鄲鄦鄮醅醆醊醁醂醄醀鋐鋃鋄鋀鋙銶鋏鋱鋟鋘鋩鋗鋝鋌鋯鋂鋨鋊鋈鋎鋦鋍鋕鋉鋠鋞鋧鋑鋓"],["e8a1","銵鋡鋆銴镼閬閫閮閰隤隢雓霅霈霂靚鞊鞎鞈韐韏頞頝頦頩頨頠頛頧颲餈飺餑餔餖餗餕駜駍駏駓駔駎駉駖駘駋駗駌骳髬髫髳髲髱魆魃魧魴魱魦魶魵魰魨魤魬鳼鳺鳽鳿鳷鴇鴀鳹鳻鴈鴅鴄麃黓鼏鼐儜儓儗儚儑凞匴叡噰噠噮"],["e940","噳噦噣噭噲噞噷圜圛壈墽壉墿墺壂墼壆嬗嬙嬛嬡嬔嬓嬐嬖嬨嬚嬠嬞寯嶬嶱嶩嶧嶵嶰嶮嶪嶨嶲嶭嶯嶴幧幨幦幯廩廧廦廨廥彋徼憝憨憖懅憴懆懁懌憺"],["e9a1","憿憸憌擗擖擐擏擉撽撉擃擛擳擙攳敿敼斢曈暾曀曊曋曏暽暻暺曌朣樴橦橉橧樲橨樾橝橭橶橛橑樨橚樻樿橁橪橤橐橏橔橯橩橠樼橞橖橕橍橎橆歕歔歖殧殪殫毈毇氄氃氆澭濋澣濇澼濎濈潞濄澽澞濊澨瀄澥澮澺澬澪濏澿澸"],["ea40","澢濉澫濍澯澲澰燅燂熿熸燖燀燁燋燔燊燇燏熽燘熼燆燚燛犝犞獩獦獧獬獥獫獪瑿璚璠璔璒璕璡甋疀瘯瘭瘱瘽瘳瘼瘵瘲瘰皻盦瞚瞝瞡瞜瞛瞢瞣瞕瞙"],["eaa1","瞗磝磩磥磪磞磣磛磡磢磭磟磠禤穄穈穇窶窸窵窱窷篞篣篧篝篕篥篚篨篹篔篪篢篜篫篘篟糒糔糗糐糑縒縡縗縌縟縠縓縎縜縕縚縢縋縏縖縍縔縥縤罃罻罼罺羱翯耪耩聬膱膦膮膹膵膫膰膬膴膲膷膧臲艕艖艗蕖蕅蕫蕍蕓蕡蕘"],["eb40","蕀蕆蕤蕁蕢蕄蕑蕇蕣蔾蕛蕱蕎蕮蕵蕕蕧蕠薌蕦蕝蕔蕥蕬虣虥虤螛螏螗螓螒螈螁螖螘蝹螇螣螅螐螑螝螄螔螜螚螉褞褦褰褭褮褧褱褢褩褣褯褬褟觱諠"],["eba1","諢諲諴諵諝謔諤諟諰諈諞諡諨諿諯諻貑貒貐賵賮賱賰賳赬赮趥趧踳踾踸蹀蹅踶踼踽蹁踰踿躽輶輮輵輲輹輷輴遶遹遻邆郺鄳鄵鄶醓醐醑醍醏錧錞錈錟錆錏鍺錸錼錛錣錒錁鍆錭錎錍鋋錝鋺錥錓鋹鋷錴錂錤鋿錩錹錵錪錔錌"],["ec40","錋鋾錉錀鋻錖閼闍閾閹閺閶閿閵閽隩雔霋霒霐鞙鞗鞔韰韸頵頯頲餤餟餧餩馞駮駬駥駤駰駣駪駩駧骹骿骴骻髶髺髹髷鬳鮀鮅鮇魼魾魻鮂鮓鮒鮐魺鮕"],["eca1","魽鮈鴥鴗鴠鴞鴔鴩鴝鴘鴢鴐鴙鴟麈麆麇麮麭黕黖黺鼒鼽儦儥儢儤儠儩勴嚓嚌嚍嚆嚄嚃噾嚂噿嚁壖壔壏壒嬭嬥嬲嬣嬬嬧嬦嬯嬮孻寱寲嶷幬幪徾徻懃憵憼懧懠懥懤懨懞擯擩擣擫擤擨斁斀斶旚曒檍檖檁檥檉檟檛檡檞檇檓檎"],["ed40","檕檃檨檤檑橿檦檚檅檌檒歛殭氉濌澩濴濔濣濜濭濧濦濞濲濝濢濨燡燱燨燲燤燰燢獳獮獯璗璲璫璐璪璭璱璥璯甐甑甒甏疄癃癈癉癇皤盩瞵瞫瞲瞷瞶"],["eda1","瞴瞱瞨矰磳磽礂磻磼磲礅磹磾礄禫禨穜穛穖穘穔穚窾竀竁簅簏篲簀篿篻簎篴簋篳簂簉簃簁篸篽簆篰篱簐簊糨縭縼繂縳顈縸縪繉繀繇縩繌縰縻縶繄縺罅罿罾罽翴翲耬膻臄臌臊臅臇膼臩艛艚艜薃薀薏薧薕薠薋薣蕻薤薚薞"],["ee40","蕷蕼薉薡蕺蕸蕗薎薖薆薍薙薝薁薢薂薈薅蕹蕶薘薐薟虨螾螪螭蟅螰螬螹螵螼螮蟉蟃蟂蟌螷螯蟄蟊螴螶螿螸螽蟞螲褵褳褼褾襁襒褷襂覭覯覮觲觳謞"],["eea1","謘謖謑謅謋謢謏謒謕謇謍謈謆謜謓謚豏豰豲豱豯貕貔賹赯蹎蹍蹓蹐蹌蹇轃轀邅遾鄸醚醢醛醙醟醡醝醠鎡鎃鎯鍤鍖鍇鍼鍘鍜鍶鍉鍐鍑鍠鍭鎏鍌鍪鍹鍗鍕鍒鍏鍱鍷鍻鍡鍞鍣鍧鎀鍎鍙闇闀闉闃闅閷隮隰隬霠霟霘霝霙鞚鞡鞜"],["ef40","鞞鞝韕韔韱顁顄顊顉顅顃餥餫餬餪餳餲餯餭餱餰馘馣馡騂駺駴駷駹駸駶駻駽駾駼騃骾髾髽鬁髼魈鮚鮨鮞鮛鮦鮡鮥鮤鮆鮢鮠鮯鴳鵁鵧鴶鴮鴯鴱鴸鴰"],["efa1","鵅鵂鵃鴾鴷鵀鴽翵鴭麊麉麍麰黈黚黻黿鼤鼣鼢齔龠儱儭儮嚘嚜嚗嚚嚝嚙奰嬼屩屪巀幭幮懘懟懭懮懱懪懰懫懖懩擿攄擽擸攁攃擼斔旛曚曛曘櫅檹檽櫡櫆檺檶檷櫇檴檭歞毉氋瀇瀌瀍瀁瀅瀔瀎濿瀀濻瀦濼濷瀊爁燿燹爃燽獶"],["f040","璸瓀璵瓁璾璶璻瓂甔甓癜癤癙癐癓癗癚皦皽盬矂瞺磿礌礓礔礉礐礒礑禭禬穟簜簩簙簠簟簭簝簦簨簢簥簰繜繐繖繣繘繢繟繑繠繗繓羵羳翷翸聵臑臒"],["f0a1","臐艟艞薴藆藀藃藂薳薵薽藇藄薿藋藎藈藅薱薶藒蘤薸薷薾虩蟧蟦蟢蟛蟫蟪蟥蟟蟳蟤蟔蟜蟓蟭蟘蟣螤蟗蟙蠁蟴蟨蟝襓襋襏襌襆襐襑襉謪謧謣謳謰謵譇謯謼謾謱謥謷謦謶謮謤謻謽謺豂豵貙貘貗賾贄贂贀蹜蹢蹠蹗蹖蹞蹥蹧"],["f140","蹛蹚蹡蹝蹩蹔轆轇轈轋鄨鄺鄻鄾醨醥醧醯醪鎵鎌鎒鎷鎛鎝鎉鎧鎎鎪鎞鎦鎕鎈鎙鎟鎍鎱鎑鎲鎤鎨鎴鎣鎥闒闓闑隳雗雚巂雟雘雝霣霢霥鞬鞮鞨鞫鞤鞪"],["f1a1","鞢鞥韗韙韖韘韺顐顑顒颸饁餼餺騏騋騉騍騄騑騊騅騇騆髀髜鬈鬄鬅鬩鬵魊魌魋鯇鯆鯃鮿鯁鮵鮸鯓鮶鯄鮹鮽鵜鵓鵏鵊鵛鵋鵙鵖鵌鵗鵒鵔鵟鵘鵚麎麌黟鼁鼀鼖鼥鼫鼪鼩鼨齌齕儴儵劖勷厴嚫嚭嚦嚧嚪嚬壚壝壛夒嬽嬾嬿巃幰"],["f240","徿懻攇攐攍攉攌攎斄旞旝曞櫧櫠櫌櫑櫙櫋櫟櫜櫐櫫櫏櫍櫞歠殰氌瀙瀧瀠瀖瀫瀡瀢瀣瀩瀗瀤瀜瀪爌爊爇爂爅犥犦犤犣犡瓋瓅璷瓃甖癠矉矊矄矱礝礛"],["f2a1","礡礜礗礞禰穧穨簳簼簹簬簻糬糪繶繵繸繰繷繯繺繲繴繨罋罊羃羆羷翽翾聸臗臕艤艡艣藫藱藭藙藡藨藚藗藬藲藸藘藟藣藜藑藰藦藯藞藢蠀蟺蠃蟶蟷蠉蠌蠋蠆蟼蠈蟿蠊蠂襢襚襛襗襡襜襘襝襙覈覷覶觶譐譈譊譀譓譖譔譋譕"],["f340","譑譂譒譗豃豷豶貚贆贇贉趬趪趭趫蹭蹸蹳蹪蹯蹻軂轒轑轏轐轓辴酀鄿醰醭鏞鏇鏏鏂鏚鏐鏹鏬鏌鏙鎩鏦鏊鏔鏮鏣鏕鏄鏎鏀鏒鏧镽闚闛雡霩霫霬霨霦"],["f3a1","鞳鞷鞶韝韞韟顜顙顝顗颿颽颻颾饈饇饃馦馧騚騕騥騝騤騛騢騠騧騣騞騜騔髂鬋鬊鬎鬌鬷鯪鯫鯠鯞鯤鯦鯢鯰鯔鯗鯬鯜鯙鯥鯕鯡鯚鵷鶁鶊鶄鶈鵱鶀鵸鶆鶋鶌鵽鵫鵴鵵鵰鵩鶅鵳鵻鶂鵯鵹鵿鶇鵨麔麑黀黼鼭齀齁齍齖齗齘匷嚲"],["f440","嚵嚳壣孅巆巇廮廯忀忁懹攗攖攕攓旟曨曣曤櫳櫰櫪櫨櫹櫱櫮櫯瀼瀵瀯瀷瀴瀱灂瀸瀿瀺瀹灀瀻瀳灁爓爔犨獽獼璺皫皪皾盭矌矎矏矍矲礥礣礧礨礤礩"],["f4a1","禲穮穬穭竷籉籈籊籇籅糮繻繾纁纀羺翿聹臛臙舋艨艩蘢藿蘁藾蘛蘀藶蘄蘉蘅蘌藽蠙蠐蠑蠗蠓蠖襣襦覹觷譠譪譝譨譣譥譧譭趮躆躈躄轙轖轗轕轘轚邍酃酁醷醵醲醳鐋鐓鏻鐠鐏鐔鏾鐕鐐鐨鐙鐍鏵鐀鏷鐇鐎鐖鐒鏺鐉鏸鐊鏿"],["f540","鏼鐌鏶鐑鐆闞闠闟霮霯鞹鞻韽韾顠顢顣顟飁飂饐饎饙饌饋饓騲騴騱騬騪騶騩騮騸騭髇髊髆鬐鬒鬑鰋鰈鯷鰅鰒鯸鱀鰇鰎鰆鰗鰔鰉鶟鶙鶤鶝鶒鶘鶐鶛"],["f5a1","鶠鶔鶜鶪鶗鶡鶚鶢鶨鶞鶣鶿鶩鶖鶦鶧麙麛麚黥黤黧黦鼰鼮齛齠齞齝齙龑儺儹劘劗囃嚽嚾孈孇巋巏廱懽攛欂櫼欃櫸欀灃灄灊灈灉灅灆爝爚爙獾甗癪矐礭礱礯籔籓糲纊纇纈纋纆纍罍羻耰臝蘘蘪蘦蘟蘣蘜蘙蘧蘮蘡蘠蘩蘞蘥"],["f640","蠩蠝蠛蠠蠤蠜蠫衊襭襩襮襫觺譹譸譅譺譻贐贔趯躎躌轞轛轝酆酄酅醹鐿鐻鐶鐩鐽鐼鐰鐹鐪鐷鐬鑀鐱闥闤闣霵霺鞿韡顤飉飆飀饘饖騹騽驆驄驂驁騺"],["f6a1","騿髍鬕鬗鬘鬖鬺魒鰫鰝鰜鰬鰣鰨鰩鰤鰡鶷鶶鶼鷁鷇鷊鷏鶾鷅鷃鶻鶵鷎鶹鶺鶬鷈鶱鶭鷌鶳鷍鶲鹺麜黫黮黭鼛鼘鼚鼱齎齥齤龒亹囆囅囋奱孋孌巕巑廲攡攠攦攢欋欈欉氍灕灖灗灒爞爟犩獿瓘瓕瓙瓗癭皭礵禴穰穱籗籜籙籛籚"],["f740","糴糱纑罏羇臞艫蘴蘵蘳蘬蘲蘶蠬蠨蠦蠪蠥襱覿覾觻譾讄讂讆讅譿贕躕躔躚躒躐躖躗轠轢酇鑌鑐鑊鑋鑏鑇鑅鑈鑉鑆霿韣顪顩飋饔饛驎驓驔驌驏驈驊"],["f7a1","驉驒驐髐鬙鬫鬻魖魕鱆鱈鰿鱄鰹鰳鱁鰼鰷鰴鰲鰽鰶鷛鷒鷞鷚鷋鷐鷜鷑鷟鷩鷙鷘鷖鷵鷕鷝麶黰鼵鼳鼲齂齫龕龢儽劙壨壧奲孍巘蠯彏戁戃戄攩攥斖曫欑欒欏毊灛灚爢玂玁玃癰矔籧籦纕艬蘺虀蘹蘼蘱蘻蘾蠰蠲蠮蠳襶襴襳觾"],["f840","讌讎讋讈豅贙躘轤轣醼鑢鑕鑝鑗鑞韄韅頀驖驙鬞鬟鬠鱒鱘鱐鱊鱍鱋鱕鱙鱌鱎鷻鷷鷯鷣鷫鷸鷤鷶鷡鷮鷦鷲鷰鷢鷬鷴鷳鷨鷭黂黐黲黳鼆鼜鼸鼷鼶齃齏"],["f8a1","齱齰齮齯囓囍孎屭攭曭曮欓灟灡灝灠爣瓛瓥矕礸禷禶籪纗羉艭虃蠸蠷蠵衋讔讕躞躟躠躝醾醽釂鑫鑨鑩雥靆靃靇韇韥驞髕魙鱣鱧鱦鱢鱞鱠鸂鷾鸇鸃鸆鸅鸀鸁鸉鷿鷽鸄麠鼞齆齴齵齶囔攮斸欘欙欗欚灢爦犪矘矙礹籩籫糶纚"],["f940","纘纛纙臠臡虆虇虈襹襺襼襻觿讘讙躥躤躣鑮鑭鑯鑱鑳靉顲饟鱨鱮鱭鸋鸍鸐鸏鸒鸑麡黵鼉齇齸齻齺齹圞灦籯蠼趲躦釃鑴鑸鑶鑵驠鱴鱳鱱鱵鸔鸓黶鼊"],["f9a1","龤灨灥糷虪蠾蠽蠿讞貜躩軉靋顳顴飌饡馫驤驦驧鬤鸕鸗齈戇欞爧虌躨钂钀钁驩驨鬮鸙爩虋讟钃鱹麷癵驫鱺鸝灩灪麤齾齉龘碁銹裏墻恒粧嫺╔╦╗╠╬╣╚╩╝╒╤╕╞╪╡╘╧╛╓╥╖╟╫╢╙╨╜║═╭╮╰╯▓"]];
/***/ }),
/***/ 942:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"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.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.getChangedFiles = void 0;
const child_process_1 = __webpack_require__(129);
const readline_1 = __webpack_require__(58);
const fs_1 = __webpack_require__(747);
const core = __importStar(__webpack_require__(470));
const github = __importStar(__webpack_require__(469));
const picomatch_1 = __importDefault(__webpack_require__(827));
async function getChangedFiles() {
const pattern = core.getInput('files', {
required: false,
});
const globs = pattern.length ? pattern.split(',') : ['**.php'];
const isMatch = picomatch_1.default(globs);
console.log('Filter patterns:', globs, isMatch('src/test.php'));
const payload = github.context
.payload;
/*
getting them from Git
git diff-tree --no-commit-id --name-status --diff-filter=d -r ${{ github.event.pull_request.base.sha }}..${{ github.event.after }}
*/
try {
const git = child_process_1.spawn('git', [
'--no-pager',
'diff-tree',
'--no-commit-id',
'--name-status',
'--diff-filter=d',
'-r',
`${payload.pull_request.base.sha}..`,
], {
windowsHide: true,
timeout: 5000,
});
const readline = readline_1.createInterface({
input: git.stdout,
});
const result = {
added: [],
modified: [],
};
for await (const line of readline) {
const parsed = /^(?<status>[ACMR])[\s\t]+(?<file>\S+)$/.exec(line);
if (parsed === null || parsed === void 0 ? void 0 : parsed.groups) {
const { status, file } = parsed.groups;
// ensure file exists
if (isMatch(file) && fs_1.existsSync(file)) {
switch (status) {
case 'A':
case 'C':
case 'R':
result.added.push(file);
break;
case 'M':
result.modified.push(file);
}
}
}
}
return result;
}
catch (err) {
console.error(err);
return {
added: [],
modified: [],
};
}
}
exports.getChangedFiles = getChangedFiles;
/***/ }),
/***/ 947:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = __webpack_require__(422);
var pascal_case_1 = __webpack_require__(857);
function camelCaseTransform(input, index) {
if (index === 0)
return input.toLowerCase();
return pascal_case_1.pascalCaseTransform(input, index);
}
exports.camelCaseTransform = camelCaseTransform;
function camelCaseTransformMerge(input, index) {
if (index === 0)
return input.toLowerCase();
return pascal_case_1.pascalCaseTransformMerge(input);
}
exports.camelCaseTransformMerge = camelCaseTransformMerge;
function camelCase(input, options) {
if (options === void 0) { options = {}; }
return pascal_case_1.pascalCase(input, tslib_1.__assign({ transform: camelCaseTransform }, options));
}
exports.camelCase = camelCase;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 950:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const url = __webpack_require__(835);
function getProxyUrl(reqUrl) {
let usingSsl = reqUrl.protocol === 'https:';
let proxyUrl;
if (checkBypass(reqUrl)) {
return proxyUrl;
}
let proxyVar;
if (usingSsl) {
proxyVar = process.env['https_proxy'] || process.env['HTTPS_PROXY'];
}
else {
proxyVar = process.env['http_proxy'] || process.env['HTTP_PROXY'];
}
if (proxyVar) {
proxyUrl = url.parse(proxyVar);
}
return proxyUrl;
}
exports.getProxyUrl = getProxyUrl;
function checkBypass(reqUrl) {
if (!reqUrl.hostname) {
return false;
}
let noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || '';
if (!noProxy) {
return false;
}
// Determine the request port
let reqPort;
if (reqUrl.port) {
reqPort = Number(reqUrl.port);
}
else if (reqUrl.protocol === 'http:') {
reqPort = 80;
}
else if (reqUrl.protocol === 'https:') {
reqPort = 443;
}
// Format the request hostname and hostname with port
let upperReqHosts = [reqUrl.hostname.toUpperCase()];
if (typeof reqPort === 'number') {
upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`);
}
// Compare request host against noproxy
for (let upperNoProxyItem of noProxy
.split(',')
.map(x => x.trim().toUpperCase())
.filter(x => x)) {
if (upperReqHosts.some(x => x === upperNoProxyItem)) {
return true;
}
}
return false;
}
exports.checkBypass = checkBypass;
/***/ }),
/***/ 986:
/***/ (function(module, __unusedexports, __webpack_require__) {
"use strict";
var Buffer = __webpack_require__(643).Buffer;
// NOTE: Due to 'stream' module being pretty large (~100Kb, significant in browser environments),
// we opt to dependency-inject it instead of creating a hard dependency.
module.exports = function(stream_module) {
var Transform = stream_module.Transform;
// == Encoder stream =======================================================
function IconvLiteEncoderStream(conv, options) {
this.conv = conv;
options = options || {};
options.decodeStrings = false; // We accept only strings, so we don't need to decode them.
Transform.call(this, options);
}
IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, {
constructor: { value: IconvLiteEncoderStream }
});
IconvLiteEncoderStream.prototype._transform = function(chunk, encoding, done) {
if (typeof chunk != 'string')
return done(new Error("Iconv encoding stream needs strings as its input."));
try {
var res = this.conv.write(chunk);
if (res && res.length) this.push(res);
done();
}
catch (e) {
done(e);
}
}
IconvLiteEncoderStream.prototype._flush = function(done) {
try {
var res = this.conv.end();
if (res && res.length) this.push(res);
done();
}
catch (e) {
done(e);
}
}
IconvLiteEncoderStream.prototype.collect = function(cb) {
var chunks = [];
this.on('error', cb);
this.on('data', function(chunk) { chunks.push(chunk); });
this.on('end', function() {
cb(null, Buffer.concat(chunks));
});
return this;
}
// == Decoder stream =======================================================
function IconvLiteDecoderStream(conv, options) {
this.conv = conv;
options = options || {};
options.encoding = this.encoding = 'utf8'; // We output strings.
Transform.call(this, options);
}
IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, {
constructor: { value: IconvLiteDecoderStream }
});
IconvLiteDecoderStream.prototype._transform = function(chunk, encoding, done) {
if (!Buffer.isBuffer(chunk) && !(chunk instanceof Uint8Array))
return done(new Error("Iconv decoding stream needs buffers as its input."));
try {
var res = this.conv.write(chunk);
if (res && res.length) this.push(res, this.encoding);
done();
}
catch (e) {
done(e);
}
}
IconvLiteDecoderStream.prototype._flush = function(done) {
try {
var res = this.conv.end();
if (res && res.length) this.push(res, this.encoding);
done();
}
catch (e) {
done(e);
}
}
IconvLiteDecoderStream.prototype.collect = function(cb) {
var res = '';
this.on('error', cb);
this.on('data', function(chunk) { res += chunk; });
this.on('end', function() {
cb(null, res);
});
return this;
}
return {
IconvLiteEncoderStream: IconvLiteEncoderStream,
IconvLiteDecoderStream: IconvLiteDecoderStream,
};
};
/***/ })
/******/ });
|
if (!contentType || /^text\/|charset=utf-8$/.test(contentType)) {
|
queue_test.py
|
import cv2
import pickle
import numpy as np
import ptlib as pt
from ptlib.core.metadata import MetadataManager
from ptlib.core.queue import Queue
class VideoIngest(pt.Task):
# variables here are static
NUM_WORKERS = 1
VIDEO_PATH = "C:\\Users\\Owner\\Videos\\Battlefield 2042 Open Beta\\testvid.mp4"
BATCH_SIZE = 30 * 5 # fps * duartion in seconds
def __init__(self):
# maybe no init
super().__init__(num_workers=VideoIngest.NUM_WORKERS)
def create_map(self, worker):
# create capture object
capture = cv2.VideoCapture(self.VIDEO_PATH)
# compute task specific start position, stop position, and batch_id
num_frames = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))
start_pos = worker.id * num_frames // self.num_workers
stop_pos = (worker.id + 1) * num_frames // self.num_workers
worker.batch_id = start_pos // self.BATCH_SIZE
print(
f"ingest: {worker.id} | start: {start_pos} | stop: {stop_pos} | batch_id: {worker.batch_id}")
# get shape and dtype
_, frame = capture.read()
shape, dtype = frame.shape, frame.dtype
# set the capture object to the start position
capture.set(cv2.CAP_PROP_POS_FRAMES, start_pos)
# create range to iterate over
batch_iter = [i for i in range(self.BATCH_SIZE)]
# set the current frame position
worker.current_pos = start_pos
# set zero array and output array
worker.output_arr = np.zeros((self.BATCH_SIZE, *shape), dtype=dtype)
def job_map(input_job):
worker.output_arr.fill(0)
for i in batch_iter:
ret, frame = capture.read()
if not ret or worker.current_pos == stop_pos:
capture.release()
worker.EXIT_FLAG = True
break
worker.output_arr[i] = frame
worker.current_pos += 1
worker.batch_id += 1
# return output_batch
return [worker.output_arr]
return job_map
##### pseudo-controller implementation for testing #####
def run(pipeline, meta_manager, output_q):
# link output queue
|
if __name__ == '__main__':
# create pipeline
pipeline = VideoIngest()
# infer output
output_job, job_specs = pipeline.infer_structure(None)
# create I/O queues
input_q, output_q = Queue(), Queue(job_specs, capacity=5)
# create metadata manager
meta_manager = MetadataManager(pipeline)
# create workers and assign them to task
pipeline.create_workers(input_q, output_q, meta_manager.meta_q)
# start pseudo-controller
run(pipeline, meta_manager, output_q)
# create and run controller
# controller = pt.Controller(pipeline, 5)
# controller.run()
# controller.graph()
|
output_q._link_mem(create_local=True)
# set start time
meta_manager.set_time()
# start all worker processes
for task in pipeline.iter_tasks():
task._start_workers()
task = pipeline
while task is not pt.EmptyTask:
# force pull from output queue
output_q.get()
# update metadata
meta_manager.update()
# if current task finishes, send kill signal to workers
if not task._workers_running():
print(f"Task Finished: {task.name}")
task = task.next
task._kill_workers()
# finish retreiving metadata (in case loop exits before getting all metadata)
meta_manager.update()
# set finish time
meta_manager.set_time()
|
LTAR_Flux_QC.py
|
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 21 15:53:46 2018
@author: Eric S. Russell
Laboratory for Atmospheric Research
Dept. of Civil and Environmental Engineering
Washington State University
[email protected]
Not all of these functions are used in the column rename script; these are potentially to be used with this processing
depending on other's thoughts. This is a trial run of dealing with code across sites.
"""
import numpy as np
import pandas as pd
import datetime
"""
QA/QC processing for flux data:
Inputs:
data: Full input data
grade: Maximum QA/QC grade as assigned by the flux calculation code
LE_B: Two number array with the highest (LE_B[1]) and lowest (LE_B[0]) hard limit LE value
H_B: Same as LE_B but for H
F_B: Same as LE-B but for Fc
cls:
gg:
Outputs:
data: Dataframe with the filtered data; does not track reason for removing data.
Conditional for door_is_open_Hst since not all sites will/do have enclosure door sensors installed
"""
# This function not implemented into the script; still thinking about how I want to format this and integrate so user doesn't have to do a lot to make work
def Grade_cs(df,info, Site, site=False):
|
#Fills in the blanks spaces with NaN's so the time index is continuous
def indx_fill(df, time):
df.index = pd.to_datetime(df.index)
# Sort index in case it came in out of order, a possibility depending on filenames and naming scheme
df = df.sort_index()
# Remove any duplicate times, can occur if files from mixed sources and have overlapping endpoints
df = df[~df.index.duplicated(keep='first')]
for k in range (0,len(df)):
if str(df.index[k])=='NaT':
df = df.drop(df.index[k])
# Fill in missing times due to tower being down and pad dataframe to midnight of the first and last day
idx = pd.date_range(df.index[0].floor('D'),df.index[len(df.index)-1].ceil('D'),freq = time)
df = df.reindex(idx, fill_value=np.NaN)
return df
# Used to format EddyPro data by combining the date and time into a common index and dropping the filename column
def format_ep(df):
df.index = df['date']+' '+df['time']
df = df.drop(['filename'],1)
df.index = pd.to_datetime(df.index)
return df
# This function not used in main script; potential to be used with QC function
def ReadIn_Initial(info):
# Values pulled in from a separate *.csv file because easier and flexible
grade = int(info['Val_L']['grade'])
LE_B = [float(info['Val_L']['LE_B']),float(info['Val_U']['LE_B'])]
H_B = [float(info['Val_L']['H_B']),float(info['Val_U']['H_B'])]
F_B = [float(info['Val_L']['F_B']),float(info['Val_U']['F_B'])]
gg = [(info['Val_L']['gg']),(info['Val_U']['gg']),(info['Val_3']['gg'])]
cls = [(info['Val_L']['cls']),(info['Val_U']['cls']),(info['Val_3']['cls']), (info['Val_4']['cls'])]
return grade, LE_B,H_B,F_B,gg,cls
# Reads in a directory of files based on the format for either EddyPro or EasyFlux
def Fast_Read(filenames, time, form):
if len(filenames) == 0:
print('No Files in directory, check the path name.')
return # 'exit' function and return error
else:
#Initialize dataframe used within function
Final = [];Final = pd.DataFrame(Final)
if form == 'EF':
for k in range (0,len(filenames)):
df = pd.read_csv(filenames[k],index_col = 'TIMESTAMP',header= 1,skiprows=[2,3],low_memory=False)
Final = pd.concat([Final,df], sort = False)
elif form == 'EP':
for k in range (0,len(filenames)):
df = pd.read_csv(filenames[k],header= 1,skiprows=[2],sep=',',low_memory=False)
Final = pd.concat([Final,df])
Final.index = Final['date']+' '+Final['time'] # Eddypro outputs both time and date as separate columns
Final =Final.drop(['filename'],1) # not needed string-based column; gets in the way of converting to floating point
elif form == 'Biomet':
for k in range (0,len(filenames)):
df = pd.read_csv(filenames[k],header= 0,skiprows=[1],sep=',',low_memory=False)
Final = pd.concat([Final,df])
Final.index = Final['date']+' '+Final['time'] # Eddypro outputs both time and date as separate columns
else:
print('Format must be either EF or EP')
return
# Convert time index
Final = Final.sort_index()
Out = indx_fill(Final, time)
return Out # Return dataframe to main function.
def Despike_7(s,ss,x,lab,delta_time, multi):
an,Tim = [],[]
while ss < x.index[-1]:
x_m = np.nanmean(x[ss:s])
x_s = np.nanstd(x[ss:s])
x_d = x[ss:s]
an.append((x_d > (x_m-(multi*x_s))) & (x_d < (x_m+(multi*x_s))))
ss+= datetime.timedelta(days=delta_time)
Tim.append((x_d.index))
s+= datetime.timedelta(days=delta_time)
qq = np.hstack(an)
an = pd.DataFrame(qq, columns = [lab])
an.index = np.hstack(Tim)
an = an[~an.index.duplicated(keep='first')]
# x[an[lab]==False] = np.NaN
return an
def Met_QAQC(**kwargs):
Q = None
if 'Tair' in kwargs.keys():
Tair = pd.DataFrame(kwargs['Tair'])
Q = Tair; Q = pd.DataFrame(Q);
Q['Tair_Hard_Limit'] = (Q[Tair.columns[0]].astype(float) <= 50) & (Q[Tair.columns[0]].astype(float) >= -40)
Q['Tair_Change'] = ~(np.abs(Q[Tair.columns[0]].diff() >= 25)) & (np.abs(Q[Tair.columns[0]].diff() != 0)) # (~np.isnan(Q[Tair.columns[0]].diff())) &
Q['Tair_Day_Change'] = (Tair.resample('D').mean().diff !=0)
Q['Tair_Filtered'] = Q[Tair.columns[0]][Q['Tair_Hard_Limit'] & Q['Tair_Change'] & Q['Tair_Day_Change']]
else:
print('**** Temperature not present ****')
if 'RH' in kwargs.keys():
RH = pd.DataFrame(kwargs['RH'])
if Q is None:
Q = RH; Q = pd.DataFrame(Q)
else: Q= Q.join(RH)
Q['RH_Hard_Limit'] = (Q[RH.columns[0]].astype(float) <= 100) & (Q[RH.columns[0]].astype(float) >= 0)
Q['RH_gt_100'] = (Q[RH.columns[0]].astype(float) >= 100) & (Q[RH.columns[0]].astype(float) <= 110)
Q['RH_Change'] = (np.abs(Q[RH.columns[0]].astype(float).diff() <= 50)) & (np.abs(Q[RH.columns[0]].diff() != 0)) # & (~np.isnan(Q[RH.columns[0]].astype(float).diff()))
Q['RH_Day_Change'] = (RH.resample('D').mean().diff !=0)
Q['RH_Filtered'] = Q[RH.columns[0]][Q['RH_Hard_Limit']&Q['RH_Change']& Q['RH_Day_Change']]
Q['RH_Filtered'] = Q['RH_Filtered'].replace(to_replace=Q['RH_Filtered'][Q['RH_gt_100']], value = 100)
# Q['RH_Filtered'][Q['RH_gt_100']]=100
else:
print('**** RH not present ****')
if 'P' in kwargs.keys():
P = pd.DataFrame(kwargs['P']);
if Q is None:
Q = P; Q = pd.DataFrame(Q)
else: Q= Q.join(P)
Q['P_Hard_Limit'] = (Q[P.columns[0]].astype(float) <= 100) &(Q[P.columns[0]].astype(float) >= 70)
Q['P_Change'] = (np.abs(Q[P.columns[0]].diff() <= 3.1)) & (np.abs(Q[P.columns[0]].diff() != 0)) # & (~np.isnan(Q[P.columns[0]].diff()))
Q['P_Filtered'] = Q[P.columns[0]][Q['P_Hard_Limit'] & Q['P_Change']]
if ('Tair' in kwargs.keys()) & ('z' in kwargs.keys()):
MSLP = [];
H = pd.DataFrame((8.314*(Tair[Tair.columns[0]]+273.15))/(0.029*9.81)/1000) # Scale height
x = pd.DataFrame(-kwargs['z']/H[H.columns[0]]);
MSLP = P[P.columns[0]]/np.exp(x[x.columns[0]]) # Mean Sea Level Pressure
MSLP = pd.DataFrame(MSLP);MSLP = MSLP.rename(columns={MSLP.columns[0]:"MSLP"})
Q= Q.join(MSLP)
Q['MSLP_Hard_Limit'] = (Q[MSLP.columns[0]].astype(float) <= 110) &(Q[MSLP.columns[0]].astype(float) >= 80)
Q['MSLP_Change'] = (np.abs(Q[MSLP.columns[0]].diff() <= 31)) & (np.abs(Q[MSLP.columns[0]].diff() != 0)) #& (~np.isnan(Q[MSLP.columns[0]].diff()))
Q['MSLP_Filtered'] = Q[MSLP.columns[0]][Q['MSLP_Hard_Limit'] & Q['MSLP_Change']]
else:
print('**** Mean sea level pressure not present ****')
else:
print('**** Pressure not present ****')
if 'WS' in kwargs.keys():
WS = pd.DataFrame(kwargs['WS'])
if Q is None:
Q = WS; Q = pd.DataFrame(Q)
else: Q= Q.join(WS)
Q['WS_Hard_Limit'] = (Q[WS.columns[0]].astype(float) < 60) & (Q[WS.columns[0]].astype(float) >= 0)
Q['WS_Change'] = (np.abs(Q[WS.columns[0]].diff() <= 15)) & (np.abs(Q[WS.columns[0]].diff() != 0)) #& (~np.isnan(Q[WS.columns[0]].diff()))
Q['WS_Day_Change'] = (WS.resample('D').mean().diff !=0)
Q['WS_Filtered'] = Q[WS.columns[0]][Q['WS_Hard_Limit']&Q['WS_Change']&Q['WS_Day_Change']]
else:
print('**** Wind Speed not present ****')
if 'WD' in kwargs.keys():
WD = pd.DataFrame(kwargs['WD'])
if Q is None:
Q = WD; Q = pd.DataFrame(Q)
else: Q= Q.join(WD)
Q['WD_Hard_Limit'] = (Q[WD.columns[0]].astype(float) < 360) & (Q[WD.columns[0]].astype(float) >= 0)
Q['WD_Change'] = (np.abs(Q[WD.columns[0]].diff() != 0)) # (~np.isnan(Q[WD.columns[0]].diff())) &
Q['WD_Filtered'] = Q[WD.columns[0]][Q['WD_Hard_Limit']&Q['WD_Change']]
else:
print('**** Wind Direction not present ****')
if 'PAR' in kwargs.keys():
PAR = pd.DataFrame(kwargs['PAR']);
if Q is None:
Q = PAR; Q = pd.DataFrame(Q)
else: Q= Q.join(PAR)
Q['PAR_Hard_Limit'] = (Q[PAR.columns[0]].astype(float) >= 0) & (Q[PAR.columns[0]].astype(float) < 5000)
Q['PAR_Change'] = (np.abs(Q[PAR.columns[0]].diff() <= 1500))# & (~np.isnan(Q[PAR.columns[0]].diff()))
Q['PAR_Day_Change'] = (PAR.resample('D').mean().diff != 0) # Causing problems for some reason
Q['PAR_Filtered'] = Q[PAR.columns[0]][Q['PAR_Hard_Limit']&Q['PAR_Change']&Q['PAR_Day_Change']]
else:
print('**** PAR not present ****')
if 'Rn' in kwargs.keys():
Rn = pd.DataFrame(kwargs['Rn'])
if Q is None:
Q = Rn; Q = pd.DataFrame(Q)
else: Q= Q.join(Rn)
Q['Rn_Hard_Limit'] = (Q[Rn.columns[0]].astype(float) >= -150) & (Q[Rn.columns[0]].astype(float) <= 1500)
Q['Rn_Change'] = (np.abs(Q[Rn.columns[0]].astype(float).diff() <= 500)) & (np.abs(Q[Rn.columns[0]].diff() != 0)) #& (~np.isnan(Q[Rn.columns[0]].astype(float).diff()))
Q['Rn_Day_Change'] = (Rn.resample('D').mean().diff !=0)
Q['Rn_Filtered'] = Q[Rn.columns[0]][Q['Rn_Hard_Limit']&Q['Rn_Change']&Q['Rn_Day_Change']]
else:
print('**** Net Radiations not present ****')
if 'Precip' in kwargs.keys():
Precip = pd.DataFrame(kwargs['Precip'])
if Q is None:
Q = P; Q = pd.DataFrame(Q)
else: Q= Q.join(Precip)
Q['Precip_Hard_Limit'] = (Q[Precip.columns[0]].astype(float) < 100) & (Q[Precip.columns[0]].astype(float) >= 0)
Z_Precip = Q[Precip.columns[0]].astype(float) ==0
# if ('RH' in kwargs.keys()) & ('Tair' in kwargs.keys()):
# Q['Precip_RH_gt_90'] = (Q[Precip.columns[0]].astype(float) > 0) & (Q['RH_Filtered'].astype(float) >= 90)
# Q['Precip_Tair_lt_Zero'] = (Q[Precip.columns[0]].astype(float) > 0) & (Q['Tair_Filtered'] < 0)
# Q['Precip_Filtered'] = Q[Precip.columns[0]][Q['Precip_Hard_Limit']&Q['Precip_RH_gt_90']&~Q['Precip_Tair_lt_Zero']]
# Q['Precip_Filtered'] = Q['Precip_Filtered'].replace(to_replace=Q['Precip_Filtered'][Z_Precip], value = 0)
# elif ('RH' in kwargs.keys()) & ('Tair' not in kwargs.keys()):
# Q['Precip_RH_gt_90'] = (Q[Precip.columns[0]].astype(float) > 0) & (Q['RH_Filtered'].astype(float) >= 90)
# Q['Precip_Filtered'] = Q[Precip.columns[0]][Q['Precip_Hard_Limit']&Q['Precip_RH']]
# Q['Precip_Filtered'] = Q['Precip_Filtered'].replace(to_replace=Q['Precip_Filtered'][Z_Precip], value = 0)
if 'Tair' in kwargs.keys():
Q['Precip_Tair_lt_Zero'] = (Q[Precip.columns[0]].astype(float) > 0) & (Q['Tair_Filtered'] < 0)
Q['Precip_Filtered'] = Q[Precip.columns[0]][Q['Precip_Hard_Limit']& ~Q['Precip_Tair_lt_Zero']]
Q['Precip_Filtered'] = Q['Precip_Filtered'].replace(to_replace=Q['Precip_Filtered'][Z_Precip], value = 0)
else:
Q['Precip_Filtered'] = Q[Precip.columns[0]][Q['Precip_Hard_Limit']]
Q['Precip_Filtered'] = Q['Precip_Filtered'].replace(to_replace=Q['Precip_Filtered'][Z_Precip], value = 0)
else:
print('**** Precipitation not present ****')
if 'VPD' in kwargs.keys():
VPD = pd.DataFrame(kwargs['VPD'])
if Q is None:
Q = VPD; Q = pd.DataFrame(Q)
else: Q= Q.join(VPD)
Q['VPD_Hard_Limit'] = (Q[VPD.columns[0]].astype(float) < 50) & (Q[VPD.columns[0]].astype(float) >= 0)
Q['VPD_Change'] = (np.abs(Q[VPD.columns[0]].astype(float).diff() <= 10)) & (np.abs(Q[VPD.columns[0]].diff() != 0))
Q['VPD_Day_Change'] = (VPD.resample('D').mean().diff !=0)
Q['VPD_Filtered'] = Q[VPD.columns[0]][Q['VPD_Hard_Limit']&Q['VPD_Change']&Q['VPD_Day_Change']]
if 'e' in kwargs.keys():
e = pd.DataFrame(kwargs['e'])
if Q is None:
Q = e; Q = pd.DataFrame(Q)
else: Q= Q.join(e)
Q['e_Hard_Limit'] = (Q[e.columns[0]].astype(float) < 50) & (Q[e.columns[0]].astype(float) >= 0)
Q['e_Change'] = (np.abs(Q[e.columns[0]].astype(float).diff() <= 10)) & (np.abs(Q[e.columns[0]].diff() != 0))
Q['e_Day_Change'] = (e.resample('D').mean().diff !=0)
Q['e_Filtered'] = Q[e.columns[0]][Q['e_Hard_Limit']&Q['e_Change']&Q['e_Day_Change']]
if 'e_s' in kwargs.keys():
e_s = pd.DataFrame(kwargs['e_s'])
if Q is None:
Q = e_s; Q = pd.DataFrame(Q)
else: Q= Q.join(e_s)
Q['e_s_Hard_Limit'] = (Q[e_s.columns[0]].astype(float) < 50) & (Q[e_s.columns[0]].astype(float) >= 0)
Q['e_s_Change'] = (np.abs(Q[e_s.columns[0]].astype(float).diff() <= 10)) & (np.abs(Q[e_s.columns[0]].diff() != 0))
Q['e_s_Day_Change'] = (e_s.resample('D').mean().diff !=0)
Q['e_s_Filtered'] = Q[e_s.columns[0]][Q['e_s_Hard_Limit']&Q['e_s_Change']&Q['e_s_Day_Change']]
return Q
|
if site == True:
grade = int(info['grade'][Site])
LE_B = [float(info['LEL'][Site]),float(info['LEU'][Site])]
H_B = [float(info['HL'][Site]),float(info['HU'][Site])]
F_B = [float(info['FCL'][Site]),float(info['FCU'][Site])]
T_B = [float(info['TL'][Site]),float(info['TU'][Site])]
elif site == False:
grade = int(info['Val_L']['grade'])
LE_B = [float(info['Val_L']['LE_B']),float(info['Val_U']['LE_B'])]
H_B = [float(info['Val_L']['H_B']),float(info['Val_U']['H_B'])]
F_B = [float(info['Val_L']['F_B']),float(info['Val_U']['F_B'])]
T_B = [float(info['Val_L']['T_B']),float(info['Val_U']['T_B'])]
gg = ['H_SSITC_TEST','LE_SSITC_TEST','FC_SSITC_TEST','TAU_SSITC_TEST']
cls =['H','LE','FC', 'TAU']
# var = ['H_Flags','LE_Flags','Fc_Flags'] Needs flagging system for QC
pd.options.mode.chained_assignment = None
if (grade >9) | (grade<1):
print('Grade number must be between 0-9.')
return # 'exit' function and return error
Good = None
data = []; data=pd.DataFrame(data,index=df.index)
if cls[1] in df.columns:
HL = (df[cls[1]].astype(float) < LE_B[0]) | (df[cls[1]].astype(float)>LE_B[1]) | df[cls[1]].astype(float).isnull()
if gg[1] in df.columns:
Grade = (df[gg[1]].astype(float) <= grade) & (~HL)
else: Grade = ~HL
df[cls[1]][~Grade] = np.NaN
data[cls[1]+'_Flag'] = 0
data[cls[1]+'_Flag'][~Grade] = 1
if cls[0] in df.columns:
HL = (df[cls[0]].astype(float) < H_B[0]) | (df[cls[0]].astype(float)> H_B[1]) | df[cls[0]].astype(float).isnull()
if gg[0] in df.columns:
Grade = (df[gg[0]].astype(float) <= grade) & (~HL)
else: Grade = ~HL
df[cls[0]][~Grade] = np.NaN
data[cls[0]+'_Flag'] = 0
data[cls[0]+'_Flag'][~Grade] = 1
if cls[2] in df.columns:
HL = (df[cls[2]].astype(float) < F_B[0])|(df[cls[2]].astype(float) > F_B[1]) | df[cls[2]].astype(float).isnull()
if gg[2] in df.columns:
Grade = (df[gg[2]].astype(float) <= grade) & (~HL)
else: Grade = ~HL
df[cls[2]][~Grade] = np.NaN
data[cls[2]+'_Flag'] = 0
data[cls[2]+'_Flag'][~Grade] = 1
if cls[3] in df.columns:
HL = (df[cls[3]].astype(float) < T_B[0])|(df[cls[3]].astype(float) > T_B[1]) | df[cls[3]].astype(float).isnull()
if gg[3] in df.columns:
Grade = (df[gg[3]].astype(float) <= grade) & (~HL)
else: Grade = ~HL
data[cls[3]+'_Flag'] = 0
data[cls[3]+'_Flag'][~Grade] = 1
# Rain Mask
if 'P' in df.columns:
Precip = (df['P'].astype(float) == 0) | (df['P'].astype(float) == -9999)
precip = True
data['P_Flag'] = 0
data['P_Flag'][~Precip] = 1
else: precip = False
if 'CO2_sig_strgth_Min' in df.columns:
c_sig_strength = df['CO2_sig_strgth_Min'] > 0.7
data['CO2_Signal_Strength'] = 0
data['CO2_Signal_Strength'][~c_sig_strength] = 1
if 'H2O_sig_strgth_Min' in df.columns:
w_sig_strength = df['H2O_sig_strgth_Min'] > 0.7
data['H2O_Signal_Strength'] = 0
data['H2O_Signal_Strength'][~w_sig_strength] = 1
if 'CO2_samples_Tot' in df.columns:
Samp_Good_IRGA = df['CO2_samples_Tot'].astype(float)>14400
data['CO2_Samples_Flag'] = 0
data['CO2_Samples_Flag'][~Samp_Good_IRGA] = 1
irga = True
else: irga=False
if 'sonic_samples_Tot' in df.columns:
Samp_Good_Sonic = df['sonic_samples_Tot'].astype(float) > 14400
data['Sonic_Samples_Flag'] = 0
data['Sonic_Samples_Flag'][~Samp_Good_Sonic] = 1
sonic = True
else: sonic=False
if 'used_records' in df.columns:
Samp_Good_Sonic = df['used_records'].astype(float)>14400
sonic = True
else: sonic=False
if 'door_is_open_Hst' in df.columns:
Door_Closed = df['door_is_open_Hst'].astype(float) == 0
pc = True
else: pc = False
if precip&irga&sonic&pc:
Good = Door_Closed &Samp_Good_Sonic&Samp_Good_IRGA&Precip&w_sig_strength&c_sig_strength
elif precip&irga&sonic&~pc:
Good = Samp_Good_Sonic&Samp_Good_IRGA&Precip&w_sig_strength&c_sig_strength
elif precip&~irga&~sonic&~pc:
Good = Precip&w_sig_strength&c_sig_strength
elif precip&~irga&sonic&~pc:
Good = Samp_Good_Sonic&Precip&w_sig_strength&c_sig_strength
elif ~precip&~irga&sonic&~pc:
Good = Samp_Good_Sonic&w_sig_strength&c_sig_strength
elif ~precip&irga&sonic&pc:
Good = Samp_Good_Sonic&Samp_Good_IRGA&w_sig_strength&c_sig_strength
if Good is not None:
if cls[3] in df.columns:
df[cls[3]][~Good] = np.NaN
if cls[2] in df.columns:
df[cls[2]][~Good] = np.NaN
if cls[1] in df.columns:
df[cls[1]][~Good] = np.NaN
if cls[0] in df.columns:
df[cls[0]][~Good] = np.NaN
return df, data
|
transparentDataEncryption.go
|
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
package v20200202preview
import (
"context"
"reflect"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/sdk/v2/go/pulumi"
)
// A logical database transparent data encryption state.
type TransparentDataEncryption struct {
pulumi.CustomResourceState
// Resource name.
Name pulumi.StringOutput `pulumi:"name"`
// Specifies the state of the transparent data encryption.
State pulumi.StringOutput `pulumi:"state"`
// Resource type.
Type pulumi.StringOutput `pulumi:"type"`
}
// NewTransparentDataEncryption registers a new resource with the given unique name, arguments, and options.
func NewTransparentDataEncryption(ctx *pulumi.Context,
name string, args *TransparentDataEncryptionArgs, opts ...pulumi.ResourceOption) (*TransparentDataEncryption, error) {
if args == nil {
return nil, errors.New("missing one or more required arguments")
}
if args.DatabaseName == nil {
return nil, errors.New("invalid value for required argument 'DatabaseName'")
}
if args.ResourceGroupName == nil {
return nil, errors.New("invalid value for required argument 'ResourceGroupName'")
}
if args.ServerName == nil {
return nil, errors.New("invalid value for required argument 'ServerName'")
}
aliases := pulumi.Aliases([]pulumi.Alias{
{
Type: pulumi.String("azure-nextgen:sql/v20200202preview:TransparentDataEncryption"),
},
{
Type: pulumi.String("azure-native:sql:TransparentDataEncryption"),
},
{
Type: pulumi.String("azure-nextgen:sql:TransparentDataEncryption"),
},
{
Type: pulumi.String("azure-native:sql/latest:TransparentDataEncryption"),
},
{
Type: pulumi.String("azure-nextgen:sql/latest:TransparentDataEncryption"),
},
{
Type: pulumi.String("azure-native:sql/v20140401:TransparentDataEncryption"),
},
{
Type: pulumi.String("azure-nextgen:sql/v20140401:TransparentDataEncryption"),
},
{
Type: pulumi.String("azure-native:sql/v20200801preview:TransparentDataEncryption"),
},
{
Type: pulumi.String("azure-nextgen:sql/v20200801preview:TransparentDataEncryption"),
},
})
opts = append(opts, aliases)
var resource TransparentDataEncryption
err := ctx.RegisterResource("azure-native:sql/v20200202preview:TransparentDataEncryption", name, args, &resource, opts...)
if err != nil {
return nil, err
}
return &resource, nil
}
// GetTransparentDataEncryption gets an existing TransparentDataEncryption resource's state with the given name, ID, and optional
// state properties that are used to uniquely qualify the lookup (nil if not required).
func GetTransparentDataEncryption(ctx *pulumi.Context,
name string, id pulumi.IDInput, state *TransparentDataEncryptionState, opts ...pulumi.ResourceOption) (*TransparentDataEncryption, error) {
var resource TransparentDataEncryption
err := ctx.ReadResource("azure-native:sql/v20200202preview:TransparentDataEncryption", name, id, state, &resource, opts...)
if err != nil {
return nil, err
}
return &resource, nil
}
// Input properties used for looking up and filtering TransparentDataEncryption resources.
type transparentDataEncryptionState struct {
// Resource name.
Name *string `pulumi:"name"`
// Specifies the state of the transparent data encryption.
State *string `pulumi:"state"`
// Resource type.
Type *string `pulumi:"type"`
}
type TransparentDataEncryptionState struct {
// Resource name.
Name pulumi.StringPtrInput
// Specifies the state of the transparent data encryption.
State pulumi.StringPtrInput
// Resource type.
Type pulumi.StringPtrInput
}
func (TransparentDataEncryptionState) ElementType() reflect.Type {
return reflect.TypeOf((*transparentDataEncryptionState)(nil)).Elem()
}
type transparentDataEncryptionArgs struct {
// The name of the logical database for which the security alert policy is defined.
DatabaseName string `pulumi:"databaseName"`
// The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
ResourceGroupName string `pulumi:"resourceGroupName"`
// The name of the server.
ServerName string `pulumi:"serverName"`
// Specifies the state of the transparent data encryption.
State string `pulumi:"state"`
// The name of the transparent data encryption configuration.
TdeName *string `pulumi:"tdeName"`
}
// The set of arguments for constructing a TransparentDataEncryption resource.
type TransparentDataEncryptionArgs struct {
// The name of the logical database for which the security alert policy is defined.
DatabaseName pulumi.StringInput
// The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
ResourceGroupName pulumi.StringInput
// The name of the server.
ServerName pulumi.StringInput
// Specifies the state of the transparent data encryption.
State TransparentDataEncryptionStateEnum
// The name of the transparent data encryption configuration.
TdeName pulumi.StringPtrInput
}
func (TransparentDataEncryptionArgs) ElementType() reflect.Type {
return reflect.TypeOf((*transparentDataEncryptionArgs)(nil)).Elem()
}
type TransparentDataEncryptionInput interface {
pulumi.Input
ToTransparentDataEncryptionOutput() TransparentDataEncryptionOutput
ToTransparentDataEncryptionOutputWithContext(ctx context.Context) TransparentDataEncryptionOutput
}
func (*TransparentDataEncryption) ElementType() reflect.Type {
return reflect.TypeOf((*TransparentDataEncryption)(nil))
}
func (i *TransparentDataEncryption) ToTransparentDataEncryptionOutput() TransparentDataEncryptionOutput {
return i.ToTransparentDataEncryptionOutputWithContext(context.Background())
}
func (i *TransparentDataEncryption) ToTransparentDataEncryptionOutputWithContext(ctx context.Context) TransparentDataEncryptionOutput {
return pulumi.ToOutputWithContext(ctx, i).(TransparentDataEncryptionOutput)
}
type TransparentDataEncryptionOutput struct {
*pulumi.OutputState
}
func (TransparentDataEncryptionOutput) ElementType() reflect.Type {
return reflect.TypeOf((*TransparentDataEncryption)(nil))
}
func (o TransparentDataEncryptionOutput) ToTransparentDataEncryptionOutput() TransparentDataEncryptionOutput {
return o
}
func (o TransparentDataEncryptionOutput) ToTransparentDataEncryptionOutputWithContext(ctx context.Context) TransparentDataEncryptionOutput {
return o
}
func
|
() {
pulumi.RegisterOutputType(TransparentDataEncryptionOutput{})
}
|
init
|
model.py
|
from lib.object_detector import ObjectDetector, gather_res
import torch
import torch.nn as nn
import torch.nn.parallel
from combine_sg2im_neural_motifs.sg2im_model import Sg2ImModel
from combine_sg2im_neural_motifs.discriminators import PatchDiscriminator, AcCropDiscriminator
import os
from collections import defaultdict
from lib.pytorch_misc import optimistic_restore
import torch.nn.functional as F
from config import BOX_SCALE
from sg2im.utils import timeit
def
|
(args):
if args.checkpoint_start_from is not None:
checkpoint = torch.load(args.checkpoint_start_from)
kwargs = checkpoint['model_kwargs']
model = Sg2ImModel(**kwargs)
raw_state_dict = checkpoint['model_state']
state_dict = {}
for k, v in raw_state_dict.items():
if k.startswith('module.'):
k = k[7:]
state_dict[k] = v
model.load_state_dict(state_dict)
else:
kwargs = {
'image_size': args.image_size,
'embedding_dim': args.embedding_dim,
'gconv_dim': args.gconv_dim,
'gconv_hidden_dim': args.gconv_hidden_dim,
'gconv_num_layers': args.gconv_num_layers,
'mlp_normalization': args.mlp_normalization,
'refinement_dims': args.refinement_network_dims,
'normalization': args.normalization,
'activation': args.activation,
'mask_size': args.mask_size,
'layout_noise_dim': args.layout_noise_dim,
}
model = Sg2ImModel(**kwargs)
return model, kwargs
def build_obj_discriminator(args, vocab):
discriminator = None
d_kwargs = {}
d_weight = args.discriminator_loss_weight
d_obj_weight = args.d_obj_weight
if d_weight == 0 or d_obj_weight == 0:
return discriminator, d_kwargs
d_kwargs = {
'vocab': vocab,
'arch': args.d_obj_arch,
'normalization': args.d_normalization,
'activation': args.d_activation,
'padding': args.d_padding,
'object_size': args.crop_size,
}
discriminator = AcCropDiscriminator(**d_kwargs)
return discriminator, d_kwargs
def build_img_discriminator(args):
discriminator = None
d_kwargs = {}
d_weight = args.discriminator_loss_weight
d_img_weight = args.d_img_weight
if d_weight == 0 or d_img_weight == 0:
return discriminator, d_kwargs
d_kwargs = {
'arch': args.d_img_arch,
'normalization': args.d_normalization,
'activation': args.d_activation,
'padding': args.d_padding,
}
discriminator = PatchDiscriminator(**d_kwargs)
return discriminator, d_kwargs
class neural_motifs_sg2im_model(nn.Module):
def __init__(self, args, ind_to_classes):
super(neural_motifs_sg2im_model, self).__init__()
self.args = args
# define and initial detector
self.detector = ObjectDetector(classes=ind_to_classes, num_gpus=args.num_gpus,
mode='refinerels' if not args.use_proposals else 'proposals',
use_resnet=args.use_resnet)
if args.ckpt is not None:
ckpt = torch.load(args.ckpt)
optimistic_restore(self.detector, ckpt['state_dict'])
self.detector.eval()
# define and initial generator, image_discriminator, obj_discriminator,
# and corresponding optimizer
vocab = {
'object_idx_to_name': ind_to_classes,
}
self.model, model_kwargs = build_model(args)
self.optimizer = torch.optim.Adam(self.model.parameters(), lr=args.learning_rate)
self.obj_discriminator, d_obj_kwargs = build_obj_discriminator(args, vocab)
self.img_discriminator, d_img_kwargs = build_img_discriminator(args)
if self.obj_discriminator is not None:
self.obj_discriminator.train()
self.optimizer_d_obj = torch.optim.Adam(self.obj_discriminator.parameters(), lr=args.learning_rate)
if self.img_discriminator is not None:
self.img_discriminator.train()
self.optimizer_d_img = torch.optim.Adam(self.img_discriminator.parameters(), lr=args.learning_rate)
restore_path = None
if args.restore_from_checkpoint:
restore_path = '%s_with_model.pt' % args.checkpoint_name
restore_path = os.path.join(args.output_dir, restore_path)
if restore_path is not None and os.path.isfile(restore_path):
print('Restoring from checkpoint:')
print(restore_path)
checkpoint = torch.load(restore_path)
self.model.load_state_dict(checkpoint['model_state'])
self.optimizer.load_state_dict(checkpoint['optim_state'])
if self.obj_discriminator is not None:
self.obj_discriminator.load_state_dict(checkpoint['d_obj_state'])
self.optimizer_d_obj.load_state_dict(checkpoint['d_obj_optim_state'])
if self.img_discriminator is not None:
self.img_discriminator.load_state_dict(checkpoint['d_img_state'])
self.optimizer_d_img.load_state_dict(checkpoint['d_img_optim_state'])
t = checkpoint['counters']['t']
if 0 <= args.eval_mode_after <= t:
self.model.eval()
else:
self.model.train()
epoch = checkpoint['counters']['epoch']
else:
t, epoch = 0, 0
checkpoint = {
'vocab': vocab,
'model_kwargs': model_kwargs,
'd_obj_kwargs': d_obj_kwargs,
'd_img_kwargs': d_img_kwargs,
'losses_ts': [],
'losses': defaultdict(list),
'd_losses': defaultdict(list),
'checkpoint_ts': [],
'train_batch_data': [],
'train_samples': [],
'train_iou': [],
'val_batch_data': [],
'val_samples': [],
'val_losses': defaultdict(list),
'val_iou': [],
'norm_d': [],
'norm_g': [],
'counters': {
't': None,
'epoch': None,
},
'model_state': None, 'model_best_state': None, 'optim_state': None,
'd_obj_state': None, 'd_obj_best_state': None, 'd_obj_optim_state': None,
'd_img_state': None, 'd_img_best_state': None, 'd_img_optim_state': None,
'best_t': [],
}
self.t, self.epoch, self.checkpoint = t, epoch, checkpoint
def forward(self, x, im_sizes, image_offset,
gt_boxes=None, gt_classes=None, gt_rels=None, proposals=None, train_anchor_inds=None,
return_fmap=False):
# forward detector
with timeit('detector forward', self.args.timing):
result = self.detector(x, im_sizes, image_offset, gt_boxes, gt_classes, gt_rels, proposals,
train_anchor_inds, return_fmap=True)
if result.is_none():
return ValueError("heck")
# forward generator
imgs = F.interpolate(x, size=self.args.image_size)
objs = result.obj_preds
boxes = result.rm_box_priors / BOX_SCALE
obj_to_img = result.im_inds - image_offset
obj_fmap = result.obj_fmap
# check if all image have detection
cnt = torch.zeros(len(imgs)).byte()
cnt[obj_to_img] += 1
if (cnt > 0).sum() != len(imgs):
print("some imgs have no detection")
print(cnt)
imgs = imgs[cnt]
obj_to_img_new = obj_to_img.clone()
for i in range(len(cnt)):
if cnt[i] == 0:
obj_to_img_new -= (obj_to_img > i).long()
obj_to_img = obj_to_img_new
with timeit('generator forward', self.args.timing):
imgs_pred = self.model(obj_to_img, boxes, obj_fmap)
# forward discriminators to train generator
if self.obj_discriminator is not None:
with timeit('d_obj forward for g', self.args.timing):
g_scores_fake_crop, g_obj_scores_fake_crop = self.obj_discriminator(imgs_pred, objs, boxes, obj_to_img)
if self.img_discriminator is not None:
with timeit('d_img forward for g', self.args.timing):
g_scores_fake_img = self.img_discriminator(imgs_pred)
# forward discriminators to train discriminators
if self.obj_discriminator is not None:
imgs_fake = imgs_pred.detach()
with timeit('d_obj forward for d', self.args.timing):
d_scores_fake_crop, d_obj_scores_fake_crop = self.obj_discriminator(imgs_fake, objs, boxes, obj_to_img)
d_scores_real_crop, d_obj_scores_real_crop = self.obj_discriminator(imgs, objs, boxes, obj_to_img)
if self.img_discriminator is not None:
imgs_fake = imgs_pred.detach()
with timeit('d_img forward for d', self.args.timing):
d_scores_fake_img = self.img_discriminator(imgs_fake)
d_scores_real_img = self.img_discriminator(imgs)
return Result(
imgs=imgs,
imgs_pred=imgs_pred,
objs=objs,
g_scores_fake_crop=g_scores_fake_crop,
g_obj_scores_fake_crop=g_obj_scores_fake_crop,
g_scores_fake_img=g_scores_fake_img,
d_scores_fake_crop=d_scores_fake_crop,
d_obj_scores_fake_crop=d_obj_scores_fake_crop,
d_scores_real_crop=d_scores_real_crop,
d_obj_scores_real_crop=d_obj_scores_real_crop,
d_scores_fake_img=d_scores_fake_img,
d_scores_real_img=d_scores_real_img
)
# return imgs, imgs_pred, objs, g_scores_fake_crop, g_obj_scores_fake_crop, g_scores_fake_img, d_scores_fake_crop, \
# d_obj_scores_fake_crop, d_scores_real_crop, d_obj_scores_real_crop, d_scores_fake_img, d_scores_real_img
def __getitem__(self, batch):
""" Hack to do multi-GPU training"""
batch.scatter()
if self.args.num_gpus == 1:
return self(*batch[0])
replicas = nn.parallel.replicate(self, devices=list(range(self.args.num_gpus)))
outputs = nn.parallel.parallel_apply(replicas, [batch[i] for i in range(self.args.num_gpus)])
if self.training:
return gather_res(outputs, 0, dim=0)
return outputs
class Result(object):
def __init__(self, imgs=None,
imgs_pred=None,
objs=None,
g_scores_fake_crop=None,
g_obj_scores_fake_crop=None,
g_scores_fake_img=None,
d_scores_fake_crop=None,
d_obj_scores_fake_crop=None,
d_scores_real_crop=None,
d_obj_scores_real_crop=None,
d_scores_fake_img=None,
d_scores_real_img=None):
self.__dict__.update(locals())
del self.__dict__['self']
def is_none(self):
return all([v is None for k, v in self.__dict__.items() if k != 'self'])
|
build_model
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.