file_name
stringlengths 3
137
| prefix
stringlengths 0
918k
| suffix
stringlengths 0
962k
| middle
stringlengths 0
812k
|
---|---|---|---|
check.rs | use anyhow::Result;
use bartholomew::content::Content;
use colorful::{Color, Colorful};
use std::path::{Path, PathBuf};
use structopt::StructOpt;
/// Check content and identify errors or warnings.
#[derive(StructOpt, Debug)]
pub struct CheckCommand {
/// The path to check.
#[structopt()]
pub paths: Vec<PathBuf>,
}
impl CheckCommand {
pub async fn run(self) -> Result<()> {
if self.paths.is_empty() {
anyhow::bail!("Supply one or more content files to check.")
}
let mut exit_with_err = false;
for file_path in self.paths {
if file_path.is_dir() {
continue;
}
match check_file(&file_path).await {
Ok(()) => println!(
"✅ {}",
&file_path.to_str().unwrap_or("").color(Color::Green)
),
Err(e) => {
println!(
"❌ {}\t{}",
&file_path.to_str().unwrap_or("").color(Color::Red),
e
);
exit_with_err = true;
}
}
}
if exit_with_err {
let msg = "One or more pieces of content are invalid".color(Color::Red);
Err(anyhow::anyhow!("{}", msg))
} else {
Ok(())
}
}
}
async fn chec | &Path) -> Result<()> {
let raw_data = std::fs::read_to_string(p)
.map_err(|e| anyhow::anyhow!("Could not read file {:?} as a string: {}", &p, e))?;
let content: Content = raw_data
.parse()
.map_err(|e| anyhow::anyhow!("Could not parse file {:?}: {}", &p, e))?;
// This will catch (only) panic cases.
let _html = content.render_markdown();
// Things we could do from here:
// - Check whether requested template is known
// - Check that date parses correctly (Actually, is done already)
// - Warn if there is a publish date
if content.head.title.len() == 0 {
anyhow::bail!("Title should not be empty");
} else if content.head.title == "Untitled" {
anyhow::bail!("Document seems to be missing title. Is there TOML metadata?");
}
if let Some(tpl) = content.head.template {
let tpl_path = Path::new("templates").join(format!("{}.hbs", &tpl));
if let Err(e) = std::fs::metadata(&tpl_path) {
return Err(anyhow::anyhow!(
"Failed to open template {:?}: {}",
tpl_path,
e
));
}
}
Ok(())
}
| k_file(p: |
vault.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: vault.proto
package pb
import (
context "context"
fmt "fmt"
proto "github.com/golang/protobuf/proto"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
math "math"
)
// 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 HashRequest struct {
Password string `protobuf:"bytes,1,opt,name=password,proto3" json:"password,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *HashRequest) Reset() { *m = HashRequest{} }
func (m *HashRequest) String() string { return proto.CompactTextString(m) }
func (*HashRequest) ProtoMessage() {}
func (*HashRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_0adf1cc59b0dff3b, []int{0}
}
func (m *HashRequest) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_HashRequest.Unmarshal(m, b)
}
func (m *HashRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_HashRequest.Marshal(b, m, deterministic)
}
func (m *HashRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_HashRequest.Merge(m, src)
}
func (m *HashRequest) XXX_Size() int {
return xxx_messageInfo_HashRequest.Size(m)
}
func (m *HashRequest) XXX_DiscardUnknown() {
xxx_messageInfo_HashRequest.DiscardUnknown(m)
}
var xxx_messageInfo_HashRequest proto.InternalMessageInfo
func (m *HashRequest) GetPassword() string {
if m != nil {
return m.Password
}
return ""
}
type HashResponse struct {
Hash string `protobuf:"bytes,1,opt,name=hash,proto3" json:"hash,omitempty"`
Err string `protobuf:"bytes,2,opt,name=err,proto3" json:"err,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *HashResponse) Reset() { *m = HashResponse{} }
func (m *HashResponse) String() string { return proto.CompactTextString(m) }
func (*HashResponse) ProtoMessage() {}
func (*HashResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_0adf1cc59b0dff3b, []int{1}
}
func (m *HashResponse) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_HashResponse.Unmarshal(m, b)
}
func (m *HashResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_HashResponse.Marshal(b, m, deterministic)
}
func (m *HashResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_HashResponse.Merge(m, src)
}
func (m *HashResponse) XXX_Size() int {
return xxx_messageInfo_HashResponse.Size(m)
}
func (m *HashResponse) XXX_DiscardUnknown() {
xxx_messageInfo_HashResponse.DiscardUnknown(m)
}
var xxx_messageInfo_HashResponse proto.InternalMessageInfo
func (m *HashResponse) GetHash() string {
if m != nil {
return m.Hash
}
return ""
}
func (m *HashResponse) GetErr() string {
if m != nil {
return m.Err
}
return ""
}
type ValidateRequest struct {
Password string `protobuf:"bytes,1,opt,name=password,proto3" json:"password,omitempty"`
Hash string `protobuf:"bytes,2,opt,name=hash,proto3" json:"hash,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *ValidateRequest) Reset() { *m = ValidateRequest{} }
func (m *ValidateRequest) String() string { return proto.CompactTextString(m) }
func (*ValidateRequest) ProtoMessage() {}
func (*ValidateRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_0adf1cc59b0dff3b, []int{2}
}
func (m *ValidateRequest) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_ValidateRequest.Unmarshal(m, b)
}
func (m *ValidateRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_ValidateRequest.Marshal(b, m, deterministic)
}
func (m *ValidateRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_ValidateRequest.Merge(m, src)
}
func (m *ValidateRequest) XXX_Size() int {
return xxx_messageInfo_ValidateRequest.Size(m)
}
func (m *ValidateRequest) XXX_DiscardUnknown() {
xxx_messageInfo_ValidateRequest.DiscardUnknown(m)
}
var xxx_messageInfo_ValidateRequest proto.InternalMessageInfo
func (m *ValidateRequest) GetPassword() string {
if m != nil {
return m.Password
}
return ""
}
func (m *ValidateRequest) GetHash() string {
if m != nil {
return m.Hash
}
return ""
}
type ValidateResponse struct {
Valid bool `protobuf:"varint,1,opt,name=valid,proto3" json:"valid,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *ValidateResponse) Reset() { *m = ValidateResponse{} }
func (m *ValidateResponse) String() string { return proto.CompactTextString(m) }
func (*ValidateResponse) ProtoMessage() {}
func (*ValidateResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_0adf1cc59b0dff3b, []int{3}
}
func (m *ValidateResponse) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_ValidateResponse.Unmarshal(m, b)
}
func (m *ValidateResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_ValidateResponse.Marshal(b, m, deterministic)
}
func (m *ValidateResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_ValidateResponse.Merge(m, src)
}
func (m *ValidateResponse) XXX_Size() int {
return xxx_messageInfo_ValidateResponse.Size(m)
}
func (m *ValidateResponse) XXX_DiscardUnknown() {
xxx_messageInfo_ValidateResponse.DiscardUnknown(m)
}
var xxx_messageInfo_ValidateResponse proto.InternalMessageInfo
func (m *ValidateResponse) GetValid() bool {
if m != nil {
return m.Valid
}
return false
}
func init() {
proto.RegisterType((*HashRequest)(nil), "pb.HashRequest")
proto.RegisterType((*HashResponse)(nil), "pb.HashResponse")
proto.RegisterType((*ValidateRequest)(nil), "pb.ValidateRequest")
proto.RegisterType((*ValidateResponse)(nil), "pb.ValidateResponse")
}
func init() { proto.RegisterFile("vault.proto", fileDescriptor_0adf1cc59b0dff3b) }
var fileDescriptor_0adf1cc59b0dff3b = []byte{
// 207 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x2e, 0x4b, 0x2c, 0xcd,
0x29, 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x2a, 0x48, 0x52, 0xd2, 0xe4, 0xe2, 0xf6,
0x48, 0x2c, 0xce, 0x08, 0x4a, 0x2d, 0x2c, 0x4d, 0x2d, 0x2e, 0x11, 0x92, 0xe2, 0xe2, 0x28, 0x48,
0x2c, 0x2e, 0x2e, 0xcf, 0x2f, 0x4a, 0x91, 0x60, 0x54, 0x60, 0xd4, 0xe0, 0x0c, 0x82, 0xf3, 0x95,
0x4c, 0xb8, 0x78, 0x20, 0x4a, 0x8b, 0x0b, 0xf2, 0xf3, 0x8a, 0x53, 0x85, 0x84, 0xb8, 0x58, 0x32,
0x12, 0x8b, 0x33, 0xa0, 0xea, 0xc0, 0x6c, 0x21, 0x01, 0x2e, 0xe6, 0xd4, 0xa2, 0x22, 0x09, 0x26,
0xb0, 0x10, 0x88, 0xa9, 0xe4, 0xc8, 0xc5, 0x1f, 0x96, 0x98, 0x93, 0x99, 0x92, 0x58, 0x92, 0x4a,
0x84, 0x25, 0x70, 0x43, 0x99, 0x10, 0x86, 0x2a, 0x69, 0x70, 0x09, 0x20, 0x8c, 0x80, 0x5a, 0x2e,
0xc2, 0xc5, 0x5a, 0x06, 0x12, 0x03, 0x1b, 0xc0, 0x11, 0x04, 0xe1, 0x18, 0xe5, 0x72, 0xb1, 0x86,
0x81, 0x3c, 0x28, 0xa4, 0xcd, 0xc5, 0x02, 0x72, 0xab, 0x10, 0xbf, 0x5e, 0x41, 0x92, 0x1e, 0x92,
0x07, 0xa5, 0x04, 0x10, 0x02, 0x10, 0x93, 0x94, 0x18, 0x84, 0xcc, 0xb9, 0x38, 0x60, 0xe6, 0x0b,
0x09, 0x83, 0xe4, 0xd1, 0x1c, 0x2c, 0x25, 0x82, 0x2a, 0x08, 0xd3, 0x98, 0xc4, 0x06, 0x0e, 0x47,
0x63, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0x27, 0x61, 0x09, 0xbd, 0x56, 0x01, 0x00, 0x00,
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion4
// VaultClient is the client API for Vault service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type VaultClient interface {
Hash(ctx context.Context, in *HashRequest, opts ...grpc.CallOption) (*HashResponse, error)
Validate(ctx context.Context, in *ValidateRequest, opts ...grpc.CallOption) (*ValidateResponse, error)
}
type vaultClient struct {
cc *grpc.ClientConn
}
func NewVaultClient(cc *grpc.ClientConn) VaultClient {
return &vaultClient{cc}
}
func (c *vaultClient) Hash(ctx context.Context, in *HashRequest, opts ...grpc.CallOption) (*HashResponse, error) {
out := new(HashResponse)
err := c.cc.Invoke(ctx, "/pb.Vault/Hash", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *vaultClient) Validate(ctx context.Context, in *ValidateRequest, opts ...grpc.CallOption) (*ValidateResponse, error) {
out := new(ValidateResponse)
err := c.cc.Invoke(ctx, "/pb.Vault/Validate", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// VaultServer is the server API for Vault service.
type VaultServer interface {
Hash(context.Context, *HashRequest) (*HashResponse, error)
Validate(context.Context, *ValidateRequest) (*ValidateResponse, error)
}
// UnimplementedVaultServer can be embedded to have forward compatible implementations.
type UnimplementedVaultServer struct {
}
func (*UnimplementedVaultServer) Hash(ctx context.Context, req *HashRequest) (*HashResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method Hash not implemented")
}
func (*UnimplementedVaultServer) Validate(ctx context.Context, req *ValidateRequest) (*ValidateResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method Validate not implemented")
}
func | (s *grpc.Server, srv VaultServer) {
s.RegisterService(&_Vault_serviceDesc, srv)
}
func _Vault_Hash_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(HashRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(VaultServer).Hash(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/pb.Vault/Hash",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(VaultServer).Hash(ctx, req.(*HashRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Vault_Validate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ValidateRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(VaultServer).Validate(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/pb.Vault/Validate",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(VaultServer).Validate(ctx, req.(*ValidateRequest))
}
return interceptor(ctx, in, info, handler)
}
var _Vault_serviceDesc = grpc.ServiceDesc{
ServiceName: "pb.Vault",
HandlerType: (*VaultServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "Hash",
Handler: _Vault_Hash_Handler,
},
{
MethodName: "Validate",
Handler: _Vault_Validate_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "vault.proto",
}
| RegisterVaultServer |
wa.go | package main
import (
"encoding/gob"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"math/rand"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
qrcodeTerminal "github.com/mdp/qrterminal/v3"
whatsapp "github.com/Rhymen/go-whatsapp"
)
// var mainApi = "https://covid19-api.yggdrasil.id%s"
var mainApi = "http://localhost:5001"
var userAgent = "gobot-covid19/3.0"
type waHandler struct {
c *whatsapp.Conn
startTime uint64
}
func (wh *waHandler) HandleTextMessage(message whatsapp.TextMessage) {
if !strings.Contains(strings.ToLower(message.Text), "!covid") || message.Info.Timestamp < wh.startTime {
return
}
reply := "timeout"
waitSec := rand.Intn(4-2)+2
param := "/"
log.Printf("Randomly paused %d for throtling", waitSec)
time.Sleep(time.Duration(waitSec) * time.Second)
command := strings.Fields(message.Text)
if len(command) > 1{
for index := range command[1:] {
param += command[index+1]
}
}
link := fmt.Sprintf(mainApi + "%s", param)
body, err:= reqUrl(link)
if err >= 400 {
log.Printf("Error, %d when access %s ", err, link)
return
}
var result map[string]interface {}
jsonErr := json.Unmarshal(body, &result)
if jsonErr != nil {
log.Fatalf("Break point 4 %s %s", jsonErr, result)
}
messages := result["messages"]
// images := result["images"].([]interface{})
// files := result["files"].([]interface{})
reply = messages.(string)
if reply != "timeout" {
go sendMessage(wh.c, reply, message.Info.RemoteJid)
}
}
func main() {
//create new WhatsApp connection
wac, err := whatsapp.NewConn(5 * time.Second)
wac.SetClientVersion(0, 4, 2080)
if err != nil {
log.Fatalf("error creating connection: %v\n", err)
}
//Add handler
wac.AddHandler(&waHandler{wac, uint64(time.Now().Unix())})
//login or restore
if err := login(wac); err != nil {
log.Fatalf("error logging in: %v\n", err)
}
//verifies phone connectivity
pong, err := wac.AdminTest()
if !pong || err != nil {
log.Fatalf("error pinging in: %v\n", err)
}
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
<-c
//Disconnect safe
fmt.Println("Shutting down now.")
session, err := wac.Disconnect()
if err != nil {
log.Fatalf("error disconnecting: %v\n", err)
}
if err := writeSession(session); err != nil {
log.Fatalf("error saving session: %v", err)
}
}
func sendMessage(wac *whatsapp.Conn, message string, RJID string) {
msg := whatsapp.TextMessage{
Info: whatsapp.MessageInfo{
RemoteJid: RJID,
},
Text: message,
}
msgId, err := wac.Send(msg)
if err != nil {
fmt.Fprintf(os.Stderr, "error sending message: %v", err)
os.Exit(1)
} else {
fmt.Println("Message Sent -> ID : " + msgId)
}
}
func login(wac *whatsapp.Conn) error {
//load saved session
session, err := readSession()
if err == nil {
//restore session
session, err = wac.RestoreWithSession(session)
if err != nil {
return fmt.Errorf("restoring failed: %v\n", err)
}
} else {
//no saved session -> regular login
qr := make(chan string)
go func(){
config := qrcodeTerminal.Config{
Level: qrcodeTerminal.L,
Writer: os.Stdout,
BlackChar: qrcodeTerminal.BLACK,
WhiteChar: qrcodeTerminal.WHITE,
QuietZone: 1,
}
qrcodeTerminal.GenerateWithConfig(<-qr, config)
}()
session, err = wac.Login(qr)
if err != nil {
return fmt.Errorf("error during login: %v\n", err)
}
}
//save session
err = writeSession(session)
if err != nil {
return fmt.Errorf("error saving session: %v\n", err)
}
return nil
}
func readSession() (whatsapp.Session, error) {
session := whatsapp.Session{}
log.Println("Trying to get the session " + getSessionName())
file, err := os.Open(getSessionName())
if err != nil {
return session, err
}
defer file.Close()
decoder := gob.NewDecoder(file)
err = decoder.Decode(&session)
if err != nil {
return session, err
}
return session, nil
}
func writeSession(session whatsapp.Session) error {
file, err := os.Create(getSessionName())
if err != nil {
return err
}
defer file.Close()
encoder := gob.NewEncoder(file)
err = encoder.Encode(session)
if err != nil {
return err
}
return nil
}
func getSessionName() string |
//HandleError needs to be implemented to be a valid WhatsApp handler
func (h *waHandler) HandleError(err error) {
if e, ok := err.(*whatsapp.ErrConnectionFailed); ok {
log.Printf("Connection failed, underlying error: %v", e.Err)
log.Println("Waiting 30sec...")
<-time.After(30 * time.Second)
log.Println("Reconnecting...")
err := h.c.Restore()
if err != nil {
log.Fatalf("Restore failed: %v", err)
}
} else {
log.Printf("error occoured: %v\n", err)
}
}
func reqUrl(url string) ([]byte, int) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Fatalf("Break point 1 %s", err)
}
req.Header.Set("User-Agent", "gobot-covid19/3.0")
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
log.Fatalln(err)
}
if res.StatusCode >= 400 {
return nil, res.StatusCode
}
body, readErr := ioutil.ReadAll(res.Body)
if readErr != nil {
log.Fatalf("Break point 3 %s", readErr)
}
return body, 200
}
| {
mydir, err := os.Getwd()
if err != nil {
fmt.Println(err)
}
if _, err := os.Stat(mydir + "/session"); os.IsNotExist(err) {
os.MkdirAll(mydir+"/session", os.ModePerm)
}
sessionName := ""
if len(os.Args) == 1 {
sessionName = mydir + "/session" + "/whatsappSession.gob"
} else {
sessionName = mydir + "/session/" + os.Args[1] + ".gob"
}
return sessionName
} |
discrete_factor.py | """
The MIT License (MIT)
Copyright (c) 2013-2017 pgmpy
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import copy
import numpy as np
class DiscreteFactor:
def __init__(self, variables, cardinality, values=None, state_names=None):
"""
Args
variables: list,
variables in the scope of the factor
cardinality: list,
cardinalities of each variable, where len(cardinality)=len(variables)
values: list,
row vector of values of variables with ordering such that right-most variables
defined in `variables` cycle through their values the fastest
state_names: dictionary,
mapping variables to their states, of format {label_name: ['state1', 'state2']}
"""
self.variables = list(variables)
self.cardinality = list(cardinality)
if values is None:
self._values = None
else:
self._values = np.array(values).reshape(self.cardinality)
self.state_names = state_names
def __mul__(self, other):
return self.product(other)
def | (self):
"""Return a copy of the factor"""
return self.__class__(self.variables,
self.cardinality,
self._values,
copy.deepcopy(self.state_names))
@property
def values(self):
return self._values
def update_values(self, new_values):
"""We make this available because _values is allowed to be None on init"""
self._values = np.array(new_values).reshape(self.cardinality)
def get_value_for_state_vector(self, dict_of_states):
"""
Return the value for a dictionary of variable states.
Args
dict_of_states: dictionary,
of format {label_name1: 'state1', label_name2: 'True'}
Returns
probability, a float, the factor value for a specific combination of variable states
"""
assert sorted(dict_of_states.keys()) == sorted(self.variables), \
"The keys for the dictionary of states must match the variables in factor scope."
state_coordinates = []
for var in self.variables:
var_state = dict_of_states[var]
idx_in_var_axis = self.state_names[var].index(var_state)
state_coordinates.append(idx_in_var_axis)
return self.values[tuple(state_coordinates)]
def add_new_variables_from_other_factor(self, other):
"""Add new variables from `other` factor to the factor."""
extra_vars = set(other.variables) - set(self.variables)
# if all of these variables already exist there is nothing to do
if len(extra_vars) == 0:
return
# otherwise, extend the values array
slice_ = [slice(None)] * len(self.variables)
slice_.extend([np.newaxis] * len(extra_vars))
self._values = self._values[slice_]
self.variables.extend(extra_vars)
new_card_var = other.get_cardinality(extra_vars)
self.cardinality.extend([new_card_var[var] for var in extra_vars])
def get_cardinality(self, variables):
return {var: self.cardinality[self.variables.index(var)] for var in variables}
def product(self, other):
left = self.copy()
if isinstance(other, (int, float)):
return self.values * other
else:
assert isinstance(other, DiscreteFactor), \
"__mul__ is only defined between subclasses of DiscreteFactor"
right = other.copy()
left.add_new_variables_from_other_factor(right)
right.add_new_variables_from_other_factor(left)
# reorder variables in right factor to match order in left
source_axes = list(range(right.values.ndim))
destination_axes = [right.variables.index(var) for var in left.variables]
right.variables = [right.variables[idx] for idx in destination_axes]
# rearrange values in right factor to correspond to the reordered variables
right._values = np.moveaxis(right.values, source_axes, destination_axes)
left._values = left.values * right.values
return left
def marginalize(self, vars):
"""
Args
vars: list,
variables over which to marginalize the factor
Returns
DiscreteFactor, whose scope is set(self.variables) - set(vars)
"""
phi = copy.deepcopy(self)
var_indexes = []
for var in vars:
if var not in phi.variables:
raise ValueError('{} not in scope'.format(var))
else:
var_indexes.append(self.variables.index(var))
index_to_keep = sorted(set(range(len(self.variables))) - set(var_indexes))
phi.variables = [self.variables[index] for index in index_to_keep]
phi.cardinality = [self.cardinality[index] for index in index_to_keep]
phi._values = np.sum(phi.values, axis=tuple(var_indexes))
return phi
| copy |
hostname.go | package main
import (
// standard
"fmt"
)
func | (target string, section string) {
switch section {
case gen:
handleHostGen(target)
case geo:
handleHostGeo(target)
case passive_dns:
fallthrough
case dns:
handleHostDns(target)
case malware:
handleHostMalware(target)
default:
notImpl("Hostname", section)
}
}
func handleHostGen(target string) {
data, err := client.GetHostnameGeneral(target)
checkError("hostname", geo, err)
printSections(data.Sections)
fmt.Printf("Alexa:\t%s\n", data.Alexa)
printBaseIndicator(data.BaseIndicator)
fmt.Printf("Indicator:\t%s\n", data.Indicator)
printPulseInfo(data.PulseInfo)
printValidation(data.Validation)
fmt.Printf("Whois:\t%s\n", data.Whois)
}
func handleHostGeo(target string) {
data, err := client.GetHostnameGeo(target)
checkError("hostname", geo, err)
printGeoData(data)
}
func handleHostDns(target string) {
data, err := client.GetHostnamePassiveDns(target)
checkError("hostname", dns, err)
printPassiveDns(data)
}
func handleHostMalware(target string) {
data, err := client.GetHostnameMalware(target)
checkError("hostname", malware, err)
printMalwareCSV(data)
}
| process_hostname |
shared-messages.js | // Copyright © 2021 The Things Network Foundation, The Things Industries B.V.
//
// 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 { defineMessages } from 'react-intl'
export default defineMessages({
// Keep these sorted alphabetically.
'16Bit': '16 bit',
'32Bit': '32 bit',
abp: 'Activation by personalization (ABP)',
accuracy: 'Accuracy',
activationMode: 'Activation mode',
add: 'Add',
addApiKey: 'Add API key',
addApplication: 'Add application',
addAttributes: 'Add attributes',
addCollaborator: 'Add collaborator',
addDevice: 'Add end device',
addDeviceBulk: 'End device bulk creation',
addGateway: 'Add gateway',
addOrganization: 'Add organization',
addPubsub: 'Add Pub/Sub',
address: 'Address',
addressPlaceholder: 'host',
addWebhook: 'Add webhook',
admin: 'Admin',
advancedSettings: 'Advanced settings',
all: 'All',
allAdmin: 'All (Admin)',
altitude: 'Altitude',
altitudeDesc: 'The altitude in meters, where 0 means sea level',
antennas: 'Antennas',
apiKey: 'API key',
apiKeyCounted: '{count, plural, one {API key} other {API keys}}',
apiKeyNamePlaceholder: 'My new API key',
apiKeys: 'API keys',
appEUI: 'AppEUI',
appEUIJoinEUI: 'AppEUI/JoinEUI',
appEUIDescription:
'The AppEUI uniquely identifies the owner of the end device. If no AppEUI is provided by the device manufacturer (usually for development), it can be filled with zeros.',
appId: 'Application ID',
appKey: 'AppKey',
application: 'Application',
applications: 'Applications',
applicationServerAddress: 'Application Server address',
approve: 'Approve',
appSKey: 'AppSKey',
asServerID: 'Application Server ID',
asServerIDDescription: 'The AS-ID of the Application Server to use',
asServerKekLabel: 'Application Server KEK label',
asServerKekLabelDescription:
'The KEK label of the Application Server to use for wrapping the application session key',
attributeDescription:
'Attributes can be used to set arbitrary information about the entity, to be used by scripts, or simply for your own organization',
attributeKeyValidateTooShort:
'Attribute keys must have at least 3 characters and contain no special characters',
attributes: 'Attributes',
attributesValidateRequired:
'All attribute entry values are required. Please remove empty entries.',
attributesValidateTooMany: '{field} must be 10 items or fewer',
automaticUpdates: 'Automatic updates',
autoUpdateDescription: 'Gateway can be updated automatically',
backToOverview: 'Back to overview',
brand: 'Brand',
cancel: 'Cancel',
changeLocation: 'Change location settings',
changePassword: 'Change password',
channel: 'Channel',
claimAuthCode: 'Claim authentication code',
claiming: 'Claiming',
clear: 'Clear',
collaborator: 'Collaborator',
collaboratorCounted: '{count, plural, one {Collaborator} other {Collaborators}}',
collaboratorDeleteSuccess: 'Collaborator removed',
collaboratorEdit: 'Edit {collaboratorId}',
collaboratorEditRights: 'Edit rights of {collaboratorId}',
collaboratorId: 'Collaborator ID',
collaboratorIdPlaceholder: 'collaborator-id',
collaboratorWarningSelf: 'Changing your own rights could result in loss of access',
collaboratorModalWarning: 'Are you sure you want to remove {collaboratorId} as a collaborator?',
collaboratorModalWarningSelf:
'Are you sure you want to remove yourself as a collaborator? Access to this entity will be lost until someone else adds you as a collaborator again.',
collaboratorRemove: 'Collaborator remove',
collaborators: 'Collaborators',
collaboratorUpdateSuccess: 'Collaborator rights updated',
componentAs: 'Application Server',
componentEdtc: 'End Device Template Converter',
componentGs: 'Gateway Server',
componentIs: 'Identity Server',
componentJs: 'Join Server',
componentNs: 'Network Server',
componentQrg: 'QR Code Generator',
confirmPassword: 'Confirm password',
connected: 'Connected',
connecting: 'Connecting',
connectionIssues: 'Connection issues',
createApiKey: 'Create API key',
created: 'Created',
createdAt: 'Created at',
currentCollaborators: 'Current collaborators',
currentUserIndicator: '(This is you)',
data: 'Data',
defineRights: 'Define rights',
delayWarning:
'Delay too short. The lower bound ({minimumValue}ms) will be used by the Gateway Server.',
description: 'Description',
devAddr: 'Device address',
devDesc: 'End device description',
devEUI: 'DevEUI',
deviceCounted: '{count, plural, one {End device} other {End devices}}',
deviceDescDescription:
'Optional end device description; can also be used to save notes about the end device', | deviceSimulationDisabledWarning: 'Simulation is disabled for devices that skip payload crypto',
device: 'End device',
devices: 'End devices',
devID: 'End device ID',
devName: 'End device name',
disabled: 'Disabled',
disconnected: 'Disconnected',
documentation: 'Documentation',
downlink: 'Downlink',
downlinkAck: 'Downlink ack',
downlinkFailed: 'Downlink failed',
downlinkFrameCount: 'Downlink frame count',
downlinkNack: 'Downlink nack',
downlinkPush: 'Downlink push',
downlinkQueued: 'Downlink queued',
downlinkQueueInvalidated: 'Downlink queue invalidated',
downlinkReplace: 'Downlink replace',
downlinkSent: 'Downlink sent',
downlinksScheduled: 'Downlinks (re)scheduled',
edit: 'Edit',
email: 'Email',
emailAddress: 'Email address',
empty: 'Empty',
enabled: 'Enabled',
enforceDutyCycleDescription:
'Recommended for all gateways in order to respect spectrum regulations',
enforceDutyCycle: 'Enforce duty cycle',
entityId: 'Entity ID',
eventsCannotShow: 'Cannot show events',
external: 'External',
externalJoinServer: 'External Join Server',
fetching: 'Fetching data…',
firmwareVersion: 'Firmware version',
fNwkSIntKey: 'FNwkSIntKey',
frameCounterWidth: 'Frame counter width',
frequencyPlan: 'Frequency plan',
frequencyPlanWarning:
'Without choosing a frequency plan, packets from the gateway will not be correctly processed',
gateway: 'Gateway',
gatewayDescDescription:
'Optional gateway description; can also be used to save notes about the gateway',
gatewayDescPlaceholder: 'Description for my new gateway',
gatewayDescription: 'Gateway description',
gatewayEUI: 'Gateway EUI',
gatewayID: 'Gateway ID',
gatewayIdPlaceholder: 'my-new-gateway',
gatewayLocation: 'Gateway location',
gatewayName: 'Gateway name',
gatewayNamePlaceholder: 'My new gateway',
gateways: 'Gateways',
gatewayScheduleDownlinkLate: 'Schedule downlink late',
gatewayServerAddress: 'Gateway Server address',
gatewayStatus: 'Gateway status',
gatewayUpdateOptions: 'Gateway updates',
general: 'General',
generalInformation: 'General information',
generalSettings: 'General settings',
getSupport: 'Get Support',
gsServerAddressDescription: 'The address of the Gateway Server to connect to',
hardware: 'Hardware',
hardwareVersion: 'Hardware version',
homeNetID: 'Home NetID',
homeNetIDDescription: 'ID to identify the LoRaWAN network',
hours: 'hours',
id: 'ID',
idAlreadyExists: 'ID already exists',
import: 'Import',
importDevices: 'Import end devices',
integrations: 'Integrations',
joinAccept: 'Join accept',
insufficientAppKeyRights: 'Insufficient rights to set an AppKey',
insufficientNwkKeyRights: 'Insufficient rights to set a NwkKey',
joinEUI: 'JoinEUI',
joinServerAddress: 'Join Server address',
key: 'key',
keyEdit: 'Edit API key',
keyId: 'Key ID',
lastSeen: 'Last seen',
lastSeenUnavailable: 'Last seen info unavailable',
latitude: 'Latitude',
latitudeDesc: 'The north-south position in degrees, where 0 is the equator',
lbsLNSSecret: 'LoRa Basics Station LNS Authentication Key',
lbsLNSSecretDescription:
'The Authentication Key for Lora Basics Station LNS connections. This field is ignored for other gateways.',
link: 'Link',
linked: 'Linked',
liveData: 'Live data',
location: 'Location',
locationSolved: 'Location solved',
login: 'Login',
logout: 'Logout',
longitude: 'Longitude',
longitudeDesc: 'The east-west position in degrees, where 0 is the prime meridian (Greenwich)',
loraCloud: 'LoRa Cloud',
lorawanClassCapabilities: 'LoRaWAN class capabilities',
lorawanInformation: 'LoRaWAN information',
lorawanOptions: 'LoRaWAN options',
lorawanPhyVersionDescription: 'The LoRaWAN PHY version of the end device',
macVersion: 'LoRaWAN version',
messaging: 'Messaging',
messageTypes: 'Message types',
milliseconds: 'milliseconds',
minutes: 'minutes',
model: 'Model',
moreInformation: 'More information',
mqtt: 'MQTT',
multicast: 'Multicast',
name: 'Name',
networkServerAddress: 'Network Server address',
next: 'Next',
noDesc: 'This end device has no description',
noEvents: 'Waiting for events from <pre>{entityId}</pre>…',
noLocation: 'No location information available',
noMatch: 'No items found',
none: 'None',
notAvailable: 'n/a',
notLinked: 'Not linked',
notSet: 'Not set',
nsAddress: 'Network Server address',
nsEmptyDefault: 'Leave empty to link to the Network Server in the same cluster',
nsServerKekLabel: 'Network Server KEK label',
nsServerKekLabelDescription:
'The KEK label of the Network Server to use for wrapping the network session key',
nwkKey: 'NwkKey',
nwkSEncKey: 'NwkSEncKey',
nwkSEncKeyDescription: 'Network session encryption key',
nwkSKey: 'NwkSKey',
offline: 'Offline',
ok: 'Ok',
online: 'Online',
options: 'Options',
organization: 'Organization',
organizationId: 'Organization ID',
organizations: 'Organizations',
otaa: 'Over the air activation (OTAA)',
otherCluster: 'Other cluster',
overview: 'Overview',
password: 'Password',
passwordChanged: 'Password changed',
pause: 'Pause',
payload: 'Payload',
payloadFormatters: 'Payload formatters',
payloadFormattersDownlink: 'Downlink payload formatters',
payloadFormattersUpdateFailure: 'There was an error updating the payload formatter',
payloadFormattersUpdateSuccess: 'Payload formatter updated',
payloadFormattersUplink: 'Uplink payload formatters',
personalApiKeys: 'Personal API keys',
phyVersion: 'Regional Parameters version',
phyVersionDescription:
'The Regional Parameters version (PHY), as provided by the device manufacturer',
port: 'Port',
privacyPolicy: 'Privacy policy',
profileSettings: 'Profile settings',
provider: 'Provider',
provisionedOnExternalJoinServer: 'Provisioned on external Join Server',
public: 'Public',
pubsubBaseTopic: 'Base topic',
pubsubFormat: 'Pub/Sub format',
pubsubId: 'Pub/Sub ID',
pubsubs: 'Pub/Subs',
redirecting: 'Redirecting…',
refresh: 'Refresh',
replaceWebhook: 'Replace webhook',
removeCollaborator: 'Remove collaborator',
removeCollaboratorSelf: 'Remove yourself as collaborator',
requireAuthenticatedConnection: 'Require authenticated connection',
requireAuthenticatedConnectionDescription:
'Controls whether this gateway may only connect if it uses an authenticated Basic Station or MQTT connection',
resetsFCnt: 'Resets frame counters',
resetsJoinNonces: 'Resets join nonces',
resetWarning: 'Reseting is insecure and makes your end device susceptible for replay attacks',
restartStream: 'Restart stream',
resume: 'Resume',
rights: 'Rights',
rootKeys: 'Root keys',
saveChanges: 'Save changes',
scheduleAnyTimeDelay: 'Schedule any time delay',
scheduleAnyTimeDescription:
'Configure gateway delay (minimum: {minimumValue}ms, default: {defaultValue}ms)',
scheduleDownlinkLateDescription: 'Enable server-side buffer of downlink messages',
searchById: 'Search by ID',
seconds: 'seconds',
secure: 'Secure',
serviceData: 'Service data',
settings: 'Settings',
skipCryptoDescription: 'Skip decryption of uplink payloads and encryption of downlink payloads',
skipCryptoPlaceholder: 'Encryption/decryption disabled',
skipCryptoTitle: 'Skip payload encryption and decryption',
sNwkSIKey: 'SNwkSIntKey',
sNwkSIKeyDescription: 'Serving network session integrity key',
source: 'Source',
stable: 'Stable',
state: 'State',
stateApproved: 'Approved',
stateFlagged: 'Flagged',
stateRejected: 'Rejected',
stateRequested: 'Requested',
stateSuspended: 'Suspended',
status: 'Status',
statusDescription: 'The status of this gateway may be publicly displayed',
statusUnknown: 'Status unknown',
success: 'Success',
supportsClassB: 'Supports class B',
supportsClassC: 'Supports class C',
takeMeBack: 'Take me back',
termsAndCondition: 'Terms and conditions',
time: 'Time',
token: 'Token',
tokenDelete: 'Token delete',
tokenDeleted: 'Token deleted',
tokenSet: 'Set token',
tokenUpdated: 'Token updated',
traffic: 'Traffic',
type: 'Type',
unknown: 'Unknown',
updateChannelDescription: 'Channel for gateway automatic updates',
updatedAt: 'Last updated at',
uplink: 'Uplink',
uplinkFrameCount: 'Uplink frame count',
uplinkMessage: 'Uplink message',
uplinksReceived: 'Uplinks received',
unexposed: 'Unexposed',
user: 'User',
userAdd: 'Add user',
userDelete: 'Delete user',
userEdit: 'Edit user',
userId: 'User ID',
userManagement: 'User management',
username: 'Username',
users: 'Users',
validateAddressFormat: '{field} must be in the format "host" or "host:port"',
validateApiKey: 'API keys must follow the format "NNSXS.[…].[…]"',
validateDelayFormat: '{field} must be a positive, whole number',
validateDigit: '{field} must have at least {digit} {digit, plural, one {digit} other {digits}}',
validateEmail: 'An email address must use exactly one "@", one "." and use no special characters',
validateFreqNumberic: 'All frequency values must be positive integers',
validateFreqRequired: 'All frequency values are required. Please remove empty entries.',
validateHexLength: '{field} must be a complete hex value',
validateIdFormat: '{field} must contain only lowercase letters, numbers and dashes (-)',
validateInt32: '{field} must be a whole number, negative or positive',
validateLatitude: 'Latitude must be a whole or decimal number between -90 and 90',
validateLength: '{field} must be exactly {length} characters long',
validateLongitude: 'Longitude must be a whole or decimal number between -180 and 180',
validateMqttPassword: '{field} must be empty or have at least 2 characters',
validateMqttUrl:
'MQTT URLs must have the format "mqtt[s]://[username][:password]@host.domain[:port]"',
validateNoSpaces: '{field} must contain no spaces',
validateNumberGte: '{field} must be at least {min} or higher',
validateNumberLte: '{field} must be {max} or lower',
validatePasswordMatch: 'Passwords must match',
validateRequired: '{field} is required',
validateRights: 'At least one right must be selected',
validateSpecial:
'{field} must have at least {special} special {special, plural, one {character} other {characters}}',
validateTooLong: '{field} must have less than {max} characters',
validateTooShort: '{field} must have at least {min} characters',
validateUppercase:
'{field} must have at least {upper} uppercase {upper, plural, one {character} other {characters}}',
validateUrl: 'Must be a valid URL format, contain no spaces or special characters',
validFrom: 'Valid from',
validTo: 'Valid to',
value: 'value',
webhookAlreadyExistsModalMessage:
'A Webhook with the ID "{id}" already exists. Do you wish to replace this webhook?',
webhookBaseUrl: 'Base URL',
webhookFormat: 'Webhook format',
webhookId: 'Webhook ID',
webhooks: 'Webhooks',
}) | deviceDescPlaceholder: 'Description for my new end device',
deviceIdPlaceholder: 'my-new-device',
deviceNamePlaceholder: 'My new end device', |
driver.py | """Improved Training of Wasserstein GANs.
Papers:
https://arxiv.org/abs/1701.07875
https://arxiv.org/abs/1704.00028
Created on Tue Oct 26 15:17:08 2021
@author: gonzo
"""
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim.lr_scheduler import CosineAnnealingLR
from torch.utils.data import DataLoader, ConcatDataset
from torch.utils.tensorboard import SummaryWriter
from torchvision import transforms, datasets
from torchvision.utils import make_grid
from model import Generator, Critic
device = "cuda:0" if torch.cuda.is_available() else "cpu"
def gradient_penalty(critic, real, fake, device=device):
|
def main():
# Data
train_dataset = datasets.CIFAR10(
root='./data/train',
train=True,
download=True,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean=[-0.0163, -0.0347, -0.1056],
std=[0.4045, 0.3987, 0.4020]),
])
)
test_dataset = datasets.CIFAR10(
root='./data/test/',
train=False,
download=True,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean=[-0.0163, -0.0347, -0.1056],
std=[0.4045, 0.3987, 0.4020]),
])
)
dataset = ConcatDataset([train_dataset, test_dataset])
# Hyperparameters
epochs = 200
critic_iterations = 5
lambda_gp = 10
z_dim = 100
batch_size = 2 ** 9
fixed_noise = torch.randn((batch_size, z_dim, 1, 1), device=device)
generator = Generator().to(device)
critic = Critic().to(device)
total_params = sum(p.numel() for p in generator.parameters())
total_params += sum(p.numel() for p in critic.parameters())
print(f'Number of parameters: {total_params:,}')
lr_G = 5e-4
lr_D = 4e-6
betas = (0.0, 0.9)
optim_G = optim.Adam(generator.parameters(), lr=lr_G, betas=betas)
optim_C = optim.Adam(critic.parameters(), lr=lr_D, betas=betas)
sched_G = CosineAnnealingLR(optim_G, T_max=20, eta_min=0)
sched_C = CosineAnnealingLR(optim_C, T_max=20, eta_min=0)
loader = DataLoader(dataset, batch_size=batch_size, shuffle=True)
writer = SummaryWriter("logs/fake")
step = 0
for epoch in range(epochs):
for batch_idx, (real, label) in enumerate(loader):
# real = real.reshape((-1, 3, 32, 32)).to(device)
real = real.to(device)
for iteration in range(critic_iterations):
noise = torch.randn((real.shape[0], z_dim, 1, 1), device=device)
fake = generator(noise)
critic_real = critic(real).reshape(-1)
critic_fake = critic(fake).reshape(-1)
gp = gradient_penalty(critic, real, fake, device=device)
loss_critic = torch.mean(critic_fake) - torch.mean(critic_real)
loss_critic += lambda_gp * gp
loss_C = torch.mean(critic_fake) - torch.mean(critic_real)
critic.zero_grad(set_to_none=True)
loss_C.backward(retain_graph=True)
optim_C.step()
sched_C.step()
# Minimize Generator
C_fake = critic(fake)
loss_G = -torch.mean(C_fake)
generator.zero_grad(set_to_none=True)
loss_G.backward()
optim_G.step()
sched_G.step()
if batch_idx % 25 == 0:
print(f"{epoch}.{batch_idx} {loss_C: .3e} {loss_G: .3e}")
generator.eval()
with torch.no_grad():
fake = generator(fixed_noise)
img_grid = make_grid(fake, normalize=True)
writer.add_image("Fake Images", img_grid, global_step=step)
step += 1
generator.train()
if __name__ == '__main__':
main()
| BATCH_SIZE, C, H, W = real.shape
alpha = torch.rand((BATCH_SIZE, 1, 1, 1)).repeat(1, C, H, W).to(device)
interpolated_images = real * alpha + fake * (1 - alpha)
# Calculate critic scores
mixed_scores = critic(interpolated_images)
# Take the gradient of the scores with respect to the images
gradient = torch.autograd.grad(
inputs=interpolated_images,
outputs=mixed_scores,
grad_outputs=torch.ones_like(mixed_scores),
create_graph=True,
retain_graph=True,
)[0]
gradient = gradient.view(gradient.shape[0], -1)
gradient_norm = gradient.norm(2, dim=1)
gradient_penalty = torch.mean((gradient_norm - 1) ** 2)
return gradient_penalty |
Point.d.ts | export interface IPoint {
x: number;
y: number;
}
export declare class Point implements IPoint {
x: number;
y: number; | mul(pt: IPoint): Point;
div(pt: IPoint): Point;
abs(): Point;
magnitude(): number;
floor(): Point;
} | constructor(x: number, y: number);
add(pt: IPoint): Point;
sub(pt: IPoint): Point; |
blinky.rs | #![no_std]
#![no_main]
#![feature(type_alias_impl_trait)]
use defmt::*;
use embassy::executor::Spawner;
use embassy::time::{Duration, Timer};
use embassy_stm32::gpio::{Level, Output, Speed};
use embassy_stm32::Peripherals;
use {defmt_rtt as _, panic_probe as _};
#[embassy::main]
async fn main(_spawner: Spawner, p: Peripherals) | {
info!("Hello World!");
let mut led = Output::new(p.PB14, Level::High, Speed::Low);
loop {
info!("high");
led.set_high();
Timer::after(Duration::from_millis(500)).await;
info!("low");
led.set_low();
Timer::after(Duration::from_millis(500)).await;
}
} |
|
receiver_report.rs | use std::fmt;
use std::io::{Read, Write};
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use util::Error;
use super::errors::*;
use super::header::*;
use super::reception_report::*;
use crate::util::get_padding;
#[cfg(test)]
mod receiver_report_test;
// A ReceiverReport (RR) packet provides reception quality feedback for an RTP stream
#[derive(Debug, PartialEq, Default, Clone)]
pub struct ReceiverReport {
// The synchronization source identifier for the originator of this RR packet.
pub ssrc: u32,
// Zero or more reception report blocks depending on the number of other
// sources heard by this sender since the last report. Each reception report
// block conveys statistics on the reception of RTP packets from a
// single synchronization source.
pub reports: Vec<ReceptionReport>,
// Extension contains additional, payload-specific information that needs to
// be reported regularly about the receiver.
pub profile_extensions: Vec<u8>,
}
impl fmt::Display for ReceiverReport {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut out = format!("ReceiverReport from {}\n", self.ssrc);
out += "\tSSRC \tLost\tLastSequence\n";
for rep in &self.reports {
out += format!(
"\t{:x}\t{}/{}\t{}\n",
rep.ssrc, rep.fraction_lost, rep.total_lost, rep.last_sequence_number
)
.as_str();
}
out += format!("\tProfile Extension Data: {:?}\n", self.profile_extensions).as_str();
write!(f, "{}", out)
}
}
impl ReceiverReport {
fn size(&self) -> usize {
let mut reps_length = 0;
for rep in &self.reports {
reps_length += rep.size();
}
HEADER_LENGTH + SSRC_LENGTH + reps_length + self.profile_extensions.len()
}
// Unmarshal decodes the ReceiverReport from binary
pub fn unmarshal<R: Read>(reader: &mut R) -> Result<Self, Error> {
/*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* header |V=2|P| RC | PT=RR=201 | length |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | SSRC of packet sender |
* +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
* report | SSRC_1 (SSRC of first source) |
* block +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* 1 | fraction lost | cumulative number of packets lost |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | extended highest sequence number received |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | interarrival jitter |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | last SR (LSR) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | delay since last SR (DLSR) |
* +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
* report | SSRC_2 (SSRC of second source) |
* block +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* 2 : ... :
* +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
* | profile-specific extensions |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
let header = Header::unmarshal(reader)?;
if header.packet_type != PacketType::ReceiverReport {
return Err(ERR_WRONG_TYPE.clone());
}
let ssrc = reader.read_u32::<BigEndian>()?;
let mut reports = vec![];
for _i in 0..header.count {
reports.push(ReceptionReport::unmarshal(reader)?);
}
let mut profile_extensions: Vec<u8> = vec![];
reader.read_to_end(&mut profile_extensions)?;
Ok(ReceiverReport { | profile_extensions,
})
}
// Header returns the Header associated with this packet.
pub fn header(&self) -> Header {
let l = self.size() + get_padding(self.size());
Header {
padding: false,
count: self.reports.len() as u8,
packet_type: PacketType::ReceiverReport,
length: ((l / 4) - 1) as u16,
}
}
// destination_ssrc returns an array of SSRC values that this packet refers to.
pub fn destination_ssrc(&self) -> Vec<u32> {
self.reports.iter().map(|x| x.ssrc).collect()
}
// Marshal encodes the packet in binary.
pub fn marshal<W: Write>(&self, writer: &mut W) -> Result<(), Error> {
/*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* header |V=2|P| RC | PT=RR=201 | length |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | SSRC of packet sender |
* +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
* report | SSRC_1 (SSRC of first source) |
* block +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* 1 | fraction lost | cumulative number of packets lost |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | extended highest sequence number received |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | interarrival jitter |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | last SR (LSR) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | delay since last SR (DLSR) |
* +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
* report | SSRC_2 (SSRC of second source) |
* block +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* 2 : ... :
* +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
* | profile-specific extensions |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
if self.reports.len() > COUNT_MAX {
return Err(ERR_TOO_MANY_REPORTS.clone());
}
self.header().marshal(writer)?;
writer.write_u32::<BigEndian>(self.ssrc)?;
for rep in &self.reports {
rep.marshal(writer)?;
}
writer.write_all(&self.profile_extensions)?;
Ok(())
}
} | ssrc,
reports, |
flags.go | /*
Copyright 2018 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.
*/
package kubelet
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/golang/glog"
kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm"
kubeadmapiv1beta1 "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/v1beta1"
"k8s.io/kubernetes/cmd/kubeadm/app/constants"
"k8s.io/kubernetes/cmd/kubeadm/app/features"
kubeadmutil "k8s.io/kubernetes/cmd/kubeadm/app/util"
nodeutil "k8s.io/kubernetes/pkg/util/node"
"k8s.io/kubernetes/pkg/util/procfs"
utilsexec "k8s.io/utils/exec"
)
type kubeletFlagsOpts struct {
nodeRegOpts *kubeadmapi.NodeRegistrationOptions
featureGates map[string]bool
registerTaintsUsingFlags bool
execer utilsexec.Interface
pidOfFunc func(string) ([]int, error)
defaultHostname string
}
// WriteKubeletDynamicEnvFile writes an environment file with dynamic flags to the kubelet.
// Used at "kubeadm init" and "kubeadm join" time.
func WriteKubeletDynamicEnvFile(nodeRegOpts *kubeadmapi.NodeRegistrationOptions, featureGates map[string]bool, registerTaintsUsingFlags bool, kubeletDir string) error |
// buildKubeletArgMap takes a InitConfiguration object and builds based on that a string-string map with flags
// that should be given to the local kubelet daemon.
func buildKubeletArgMap(opts kubeletFlagsOpts) map[string]string {
kubeletFlags := map[string]string{}
if opts.nodeRegOpts.CRISocket == kubeadmapiv1beta1.DefaultCRISocket {
// These flags should only be set when running docker
kubeletFlags["network-plugin"] = "cni"
driver, err := kubeadmutil.GetCgroupDriverDocker(opts.execer)
if err != nil {
glog.Warningf("cannot automatically assign a '--cgroup-driver' value when starting the Kubelet: %v\n", err)
} else {
kubeletFlags["cgroup-driver"] = driver
}
} else {
kubeletFlags["container-runtime"] = "remote"
kubeletFlags["container-runtime-endpoint"] = opts.nodeRegOpts.CRISocket
}
if opts.registerTaintsUsingFlags && opts.nodeRegOpts.Taints != nil && len(opts.nodeRegOpts.Taints) > 0 {
taintStrs := []string{}
for _, taint := range opts.nodeRegOpts.Taints {
taintStrs = append(taintStrs, taint.ToString())
}
kubeletFlags["register-with-taints"] = strings.Join(taintStrs, ",")
}
if pids, _ := opts.pidOfFunc("systemd-resolved"); len(pids) > 0 {
// procfs.PidOf only returns an error if the regex is empty or doesn't compile, so we can ignore it
kubeletFlags["resolv-conf"] = "/run/systemd/resolve/resolv.conf"
}
// Make sure the node name we're passed will work with Kubelet
if opts.nodeRegOpts.Name != "" && opts.nodeRegOpts.Name != opts.defaultHostname {
glog.V(1).Infof("setting kubelet hostname-override to %q", opts.nodeRegOpts.Name)
kubeletFlags["hostname-override"] = opts.nodeRegOpts.Name
}
// If the user enabled Dynamic Kubelet Configuration (which is disabled by default), set the directory
// in the CLI flags so that the feature actually gets enabled
if features.Enabled(opts.featureGates, features.DynamicKubeletConfig) {
kubeletFlags["dynamic-config-dir"] = filepath.Join(constants.KubeletRunDirectory, constants.DynamicKubeletConfigurationDirectoryName)
}
// TODO: Conditionally set `--cgroup-driver` to either `systemd` or `cgroupfs` for CRI other than Docker
return kubeletFlags
}
// writeKubeletFlagBytesToDisk writes a byte slice down to disk at the specific location of the kubelet flag overrides file
func writeKubeletFlagBytesToDisk(b []byte, kubeletDir string) error {
kubeletEnvFilePath := filepath.Join(kubeletDir, constants.KubeletEnvFileName)
fmt.Printf("[kubelet-start] Writing kubelet environment file with flags to file %q\n", kubeletEnvFilePath)
// creates target folder if not already exists
if err := os.MkdirAll(kubeletDir, 0700); err != nil {
return fmt.Errorf("failed to create directory %q: %v", kubeletDir, err)
}
if err := ioutil.WriteFile(kubeletEnvFilePath, b, 0644); err != nil {
return fmt.Errorf("failed to write kubelet configuration to the file %q: %v", kubeletEnvFilePath, err)
}
return nil
}
| {
hostName, err := nodeutil.GetHostname("")
if err != nil {
return err
}
flagOpts := kubeletFlagsOpts{
nodeRegOpts: nodeRegOpts,
featureGates: featureGates,
registerTaintsUsingFlags: registerTaintsUsingFlags,
execer: utilsexec.New(),
pidOfFunc: procfs.PidOf,
defaultHostname: hostName,
}
stringMap := buildKubeletArgMap(flagOpts)
argList := kubeadmutil.BuildArgumentListFromMap(stringMap, nodeRegOpts.KubeletExtraArgs)
envFileContent := fmt.Sprintf("%s=%s\n", constants.KubeletEnvFileVariableName, strings.Join(argList, " "))
return writeKubeletFlagBytesToDisk([]byte(envFileContent), kubeletDir)
} |
exercise-errors.go | // conver e to float64(e) first to avide infinite loop
// Why? sprintf e will call e.Error(), in this case, e.Error is Sprintf, so loop.
package main
import (
"fmt"
)
type ErrNegativeSqrt float64
func (e ErrNegativeSqrt) Error() string {
return fmt.Sprintf("Cannot Sqrt negative number: %v", float64(e))
}
func Sqrt(x float64) (float64, error) {
if x < 0 {
return 0, ErrNegativeSqrt(x)
}
z := 1.0
for i := 1; i < 10; i++ {
z -= (z*z - x) / (2 * z)
}
return z, nil
}
func | () {
fmt.Println(Sqrt(2))
fmt.Println(Sqrt(-2))
}
| main |
header.js | /*
* The AnVIL
* https://www.anvilproject.org
*
* The AnVIL header component.
*/
// Core dependencies
import {Link} from "gatsby";
import React from "react";
// App dependencies
import ClickHandler from "../click-handler/click-handler";
import * as HeaderService from "../../utils/header.service";
// Images
import cloudNCPI from "../../../images/cloud-ncpi.svg";
import logoAnvil from "../../../images/logo.png";
// Styles
import compStyles from "./header.module.css";
import globalStyles from "../../styles/global.module.css";
let classNames = require("classnames");
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {showNav: false};
this.toggleMenu = this.toggleMenu.bind(this);
}
toggleMenu = () => {
this.setState({showNav: !this.state.showNav});
this.props.onMenuOpen(this.state.showNav);
};
render() {
const {links, ncpi} = this.props;
const showPartiallyActive = !ncpi;
const logoLink = ncpi ? "/ncpi" : "/";
return (
<div className={compStyles.header}>
<div className={globalStyles.container}>
<Link to={logoLink} className={classNames(compStyles.logo, {[compStyles.ncpi]: ncpi})}>
{ncpi ? <img src={cloudNCPI} alt="ncpi"/> : <img src={logoAnvil} alt="anVIL"/>}
</Link>
<ClickHandler
className={classNames({[compStyles.hidden]: this.state.showNav}, "material-icons-round")}
clickAction={this.toggleMenu}
tag={"i"}
label="Show menu">menu</ClickHandler>
<ClickHandler
className={classNames({[compStyles.hidden]: !this.state.showNav}, "material-icons-round")}
clickAction={this.toggleMenu}
tag={"i"}
label="Hide menu">close</ClickHandler>
<ul className={classNames({[compStyles.nav]: this.state.showNav})}>
{links.map((l, i) => <li key={i}>
<Link activeClassName={compStyles.active} partiallyActive={showPartiallyActive} to={l.path}>{l.name}</Link>
</li>)}
</ul>
</div>
</div>
);
}
} | const links = HeaderService.getHeaderLinks(ncpi);
return (
<Header links={links} {...props}/>
);
} |
export default (props) => {
const {ncpi} = props; |
module2.ts | export function concat(args: any[], sep: { getSeparator: (sep: "dot" | "comma") => string }) {
return args.join(sep.getSeparator("comma") + " ");
}
export function addExclamation(str: string) { | return str + "!";
} |
|
stream.go | package mp4
import (
"github.com/aloim/joy4/av"
"github.com/aloim/joy4/format/mp4/mp4io"
"time"
)
type Stream struct {
av.CodecData
trackAtom *mp4io.Track
idx int
lastpkt *av.Packet
timeScale int64
duration int64
muxer *Muxer
demuxer *Demuxer
sample *mp4io.SampleTable
sampleIndex int
sampleOffsetInChunk int64
syncSampleIndex int
dts int64
sttsEntryIndex int
sampleIndexInSttsEntry int
cttsEntryIndex int
sampleIndexInCttsEntry int
chunkGroupIndex int
chunkIndex int
sampleIndexInChunk int
sttsEntry *mp4io.TimeToSampleEntry
cttsEntry *mp4io.CompositionOffsetEntry
}
func timeToTs(tm time.Duration, timeScale int64) int64 {
return int64(tm * time.Duration(timeScale) / time.Second)
}
func | (ts int64, timeScale int64) time.Duration {
return time.Duration(ts) * time.Second / time.Duration(timeScale)
}
func (self *Stream) timeToTs(tm time.Duration) int64 {
return int64(tm * time.Duration(self.timeScale) / time.Second)
}
func (self *Stream) tsToTime(ts int64) time.Duration {
return time.Duration(ts) * time.Second / time.Duration(self.timeScale)
}
| tsToTime |
bootstrap-sphinx.js | (function ($) {
/**
* Patch TOC list.
*
* Will mutate the underlying span to have a correct ul for nav.
*
* @param $span: Span containing nested UL's to mutate.
* @param minLevel: Starting level for nested lists. (1: global, 2: local).
*/
var patchToc = function ($ul, minLevel) {
var findA,
patchTables,
$localLi;
// Find all a "internal" tags, traversing recursively.
findA = function ($elem, level) {
level = level || 0;
var $items = $elem.find("> li > a.internal, > ul, > li > ul");
// Iterate everything in order.
$items.each(function (index, item) {
var $item = $(item),
tag = item.tagName.toLowerCase(),
$childrenLi = $item.children('li'),
$parentLi = $($item.parent('li'), $item.parent().parent('li'));
// Add dropdowns if more children and above minimum level.
if (tag === 'ul' && level >= minLevel && $childrenLi.length > 0) {
$parentLi
.addClass('dropdown-submenu')
.children('a').first().attr('tabindex', -1);
$item.addClass('dropdown-menu');
}
findA($item, level + 1);
});
};
findA($ul);
};
/**
* Patch all tables to remove ``docutils`` class and add Bootstrap base
* ``table`` class.
*/
patchTables = function () {
$("table.docutils")
.removeClass("docutils")
.addClass("table")
.attr("border", 0);
};
$(window).load(function () {
/*
* Scroll the window to avoid the topnav bar
* https://github.com/twitter/bootstrap/issues/1768
*/
if ($("#navbar.navbar-fixed-top").length > 0) {
var navHeight = $("#navbar").height(),
shiftWindow = function() { scrollBy(0, -navHeight - 10); };
if (location.hash) {
setTimeout(shiftWindow, 1);
}
window.addEventListener("hashchange", shiftWindow);
}
});
$(document).ready(function () {
// Add styling, structure to TOC's.
$(".dropdown-menu").each(function () {
$(this).find("ul").each(function (index, item){
var $item = $(item);
$item.addClass('unstyled');
});
}); | // Global TOC.
if ($("ul.globaltoc li").length) {
patchToc($("ul.globaltoc"), 1);
} else {
// Remove Global TOC.
$(".globaltoc-container").remove();
}
// Local TOC.
$(".bs-sidenav ul").addClass("nav nav-list");
$(".bs-sidenav > ul > li > a").addClass("nav-header");
// back to top
setTimeout(function () {
var $sideBar = $('.bs-sidenav');
$sideBar.affix({
offset: {
top: function () {
var offsetTop = $sideBar.offset().top;
var sideBarMargin = parseInt($sideBar.children(0).css('margin-top'), 10);
var navOuterHeight = $('#navbar').height();
return (this.top = offsetTop - navOuterHeight - sideBarMargin);
}
, bottom: function () {
// add 25 because the footer height doesn't seem to be enough
return (this.bottom = $('.footer').outerHeight(true) + 25);
}
}
});
}, 100);
// Local TOC.
patchToc($("ul.localtoc"), 2);
// Mutate sub-lists (for bs-2.3.0).
$(".dropdown-menu ul").not(".dropdown-menu").each(function () {
var $ul = $(this),
$parent = $ul.parent(),
tag = $parent[0].tagName.toLowerCase(),
$kids = $ul.children().detach();
// Replace list with items if submenu header.
if (tag === "ul") {
$ul.replaceWith($kids);
} else if (tag === "li") {
// Insert into previous list.
$parent.after($kids);
$ul.remove();
}
});
// Add divider in page TOC.
$localLi = $("ul.localtoc li");
if ($localLi.length > 2) {
$localLi.first().after('<li class="divider"></li>');
}
// Manually add dropdown.
// Appears unnecessary as of:
// https://github.com/ryan-roemer/sphinx-bootstrap-theme/pull/90
// Remove next time around...
// a.dropdown-toggle class needed in globaltoc.html
//$('.dropdown-toggle').dropdown();
// Patch tables.
patchTables();
// Add Note, Warning styles. (BS v2,3 compatible).
$('.admonition').addClass('alert alert-info')
.filter('.warning, .caution')
.removeClass('alert-info')
.addClass('alert-warning').end()
.filter('.error, .danger')
.removeClass('alert-info')
.addClass('alert-danger alert-error').end();
// Inline code styles to Bootstrap style.
$('tt.docutils.literal').not(".xref").each(function (i, e) {
// ignore references
if (!$(e).parent().hasClass("reference")) {
$(e).replaceWith(function () {
return $("<code />").html($(this).html());
});
}});
// Update sourcelink to remove outerdiv (fixes appearance in navbar).
var $srcLink = $(".nav #sourcelink");
$srcLink.parent().html($srcLink.html());
});
}(window.$jqTheme || window.jQuery)); | |
controller-test.js | var test = require('tape')
var ctrl = require('../lib/controller')()
test('controller: instantiation', function (t) {
t.ok(ctrl.processFeatureServer, 'has processFeatureServer method')
t.ok(ctrl.errorResponse, 'has errorResponse method')
t.end()
})
// mock res object
function mockRes (cb) {
var res = {}
res.jsonp = function (opt) { cb(opt) }
res.json = res.jsonp
res.send = res.jsonp
res.status = function () { return res }
return res
}
test('controller.errorResponse: default', function (t) {
var res = mockRes(function (response) {
t.ok(response.error, 'error exists')
t.equal(response.error.code, 500, 'code is correct')
t.equal(response.error.message, 'Internal Server Error', 'message is correct')
t.end()
})
ctrl.errorResponse(null, res)
})
test('controller.errorResponse: custom status code', function (t) {
var res = mockRes(function (response) {
t.ok(response.error, 'error exists')
t.equal(response.error.code, 404, 'code is correct')
t.equal(response.error.message, 'Internal Server Error', 'message is correct') | ctrl.errorResponse({ code: 404 }, res)
})
test('controller.errorResponse: custom error message', function (t) {
var res = mockRes(function (response) {
t.ok(response.error, 'error exists')
t.equal(response.error.code, 500, 'code is correct')
t.equal(response.error.message, 'I dunno', 'message is correct')
t.end()
})
ctrl.errorResponse({ message: 'I dunno' }, res)
})
test('controller.errorResponse: extra error content', function (t) {
var res = mockRes(function (response) {
t.ok(response.error, 'error exists')
t.equal(response.error.code, 500, 'code is correct')
t.equal(response.error.message, 'Internal Server Error', 'message is correct')
t.equal(response.error.prop, 'xyz', 'extra property is correct')
t.end()
})
ctrl.errorResponse({ prop: 'xyz' }, res)
})
test('controller.processFeatureServer: no data found', function (t) {
var req = { query: { geometry: null } }
var res = mockRes(function (response) {
t.ok(response.error, 'error exists')
t.equal(response.error.code, 400, 'code is correct')
t.equal(response.error.message, 'No data found', 'message is correct')
t.end()
})
ctrl.processFeatureServer(req, res, null)
}) | t.end()
})
|
integration.rs | use {
assert_matches::assert_matches,
governance_demo::processor::process_instruction,
solana_program::{
instruction::{AccountMeta, Instruction},
pubkey::Pubkey,
},
solana_program_test::{processor, tokio, ProgramTest},
solana_sdk::{signature::Signer, transaction::Transaction},
};
#[tokio::test]
async fn | () {
let program_id = Pubkey::new_unique();
let pt = ProgramTest::new(
"governance-demo",
program_id,
processor!(process_instruction),
);
let (mut banks_client, payer, recent_blockhash) = pt.start().await;
let mut transaction = Transaction::new_with_payer(
&[Instruction {
program_id,
accounts: vec![AccountMeta::new(payer.pubkey(), false)],
data: vec![1, 2, 3],
}],
Some(&payer.pubkey()),
);
transaction.sign(&[&payer], recent_blockhash);
assert_matches!(banks_client.process_transaction(transaction).await, Ok(()));
}
| test_transaction |
MeniscusTest.py | import openpnm as op
import openpnm.models.physics as pm
import scipy as sp
class MeniscusTest:
def setup_class(self):
sp.random.seed(1)
self.net = op.network.Cubic(shape=[5, 1, 5], spacing=5e-5) | self.phase = op.phases.Water(network=self.net)
self.phys = op.physics.Standard(network=self.net,
phase=self.phase,
geometry=self.geo)
def test_toroidal_touch(self):
phys = self.phys
r_tor = 1e-6
self.geo['throat.touch_length'] = 2e-6
phys.add_model(propname='throat.tor_max',
model=pm.meniscus.purcell,
mode='max',
r_toroid=r_tor)
phys.add_model(propname='throat.tor_touch',
model=pm.meniscus.purcell,
mode='touch',
r_toroid=r_tor)
assert sp.any(phys['throat.tor_touch'] < phys['throat.tor_max'])
def test_sinusoidal_touch(self):
phys = self.phys
self.geo['throat.amplitude'] = 5e-6
self.geo['throat.touch_length'] = 1e-6
phys.add_model(propname='throat.sin_pressure_max',
model=pm.meniscus.sinusoidal,
mode='max')
phys.add_model(propname='throat.sin_pressure_touch',
model=pm.meniscus.sinusoidal,
mode='touch')
h = phys.check_data_health()
for check in h.values():
if len(check) > 0:
assert 1 == 2
assert sp.any((phys['throat.sin_pressure_touch'] <
phys['throat.sin_pressure_max']))
def test_sinusoidal(self):
phys = self.phys
self.geo['throat.amplitude'] = 5e-6
phys.add_model(propname='throat.sin_pressure',
model=pm.meniscus.sinusoidal,
mode='max')
phys.add_model(propname='throat.sin_meniscus',
model=pm.meniscus.sinusoidal,
mode='men',
target_Pc=5000)
h = phys.check_data_health()
for check in h.values():
if len(check) > 0:
assert 1 == 2
def test_toroidal(self):
phys = self.phys
r_tor = 1e-6
phys.add_model(propname='throat.purcell_pressure',
model=pm.capillary_pressure.purcell,
r_toroid=r_tor)
phys.add_model(propname='throat.tor_pressure',
model=pm.meniscus.purcell,
mode='max',
r_toroid=r_tor,
num_points=1000)
phys.add_model(propname='throat.tor_meniscus',
model=pm.meniscus.purcell,
mode='men',
r_toroid=r_tor,
target_Pc=5000)
a = sp.around(phys['throat.purcell_pressure'], 10)
b = sp.around(phys['throat.tor_pressure'], 10)
assert sp.allclose(a, b)
h = phys.check_data_health()
for check in h.values():
if len(check) > 0:
assert 1 == 2
def test_general_toroidal(self):
phys = self.phys
r_tor = 1e-6
phys.add_model(propname='throat.purcell_pressure',
model=pm.capillary_pressure.purcell,
r_toroid=r_tor)
phys['throat.scale_a'] = r_tor
phys['throat.scale_b'] = r_tor
phys.add_model(propname='throat.general_pressure',
model=pm.meniscus.general_toroidal,
mode='max',
num_points=1000)
a = sp.around(phys['throat.purcell_pressure'], 10)
b = sp.around(phys['throat.general_pressure'], 10)
assert sp.allclose(a, b)
h = phys.check_data_health()
for check in h.values():
if len(check) > 0:
assert 1 == 2
if __name__ == '__main__':
t = MeniscusTest()
self = t
t.setup_class()
for item in t.__dir__():
if item.startswith('test'):
print('running test: '+item)
t.__getattribute__(item)() | self.geo = op.geometry.StickAndBall(network=self.net,
pores=self.net.pores(),
throats=self.net.throats()) |
tears.py | #
# Copyright 2015 Quantopian, 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.
from __future__ import division
from time import time
import warnings
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np
import scipy.stats
import pandas as pd
from . import timeseries
from . import utils
from . import pos
from . import txn
from . import round_trips
from . import plotting
from . import _seaborn as sns
from .plotting import plotting_context
try:
from . import bayesian
except ImportError:
warnings.warn(
"Could not import bayesian submodule due to missing pymc3 dependency.",
ImportWarning)
def | (msg_body, previous_time):
current_time = time()
run_time = current_time - previous_time
message = "\nFinished " + msg_body + " (required {:.2f} seconds)."
print(message.format(run_time))
return current_time
def create_full_tear_sheet(returns,
positions=None,
transactions=None,
benchmark_rets=None,
gross_lev=None,
slippage=None,
live_start_date=None,
sector_mappings=None,
bayesian=False,
round_trips=False,
hide_positions=False,
cone_std=(1.0, 1.5, 2.0),
bootstrap=False,
set_context=True):
"""
Generate a number of tear sheets that are useful
for analyzing a strategy's performance.
- Fetches benchmarks if needed.
- Creates tear sheets for returns, and significant events.
If possible, also creates tear sheets for position analysis,
transaction analysis, and Bayesian analysis.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- Time series with decimal returns.
- Example:
2015-07-16 -0.012143
2015-07-17 0.045350
2015-07-20 0.030957
2015-07-21 0.004902
positions : pd.DataFrame, optional
Daily net position values.
- Time series of dollar amount invested in each position and cash.
- Days where stocks are not held can be represented by 0 or NaN.
- Non-working capital is labelled 'cash'
- Example:
index 'AAPL' 'MSFT' cash
2004-01-09 13939.3800 -14012.9930 711.5585
2004-01-12 14492.6300 -14624.8700 27.1821
2004-01-13 -13853.2800 13653.6400 -43.6375
transactions : pd.DataFrame, optional
Executed trade volumes and fill prices.
- One row per trade.
- Trades on different names that occur at the
same time will have identical indicies.
- Example:
index amount price symbol
2004-01-09 12:18:01 483 324.12 'AAPL'
2004-01-09 12:18:01 122 83.10 'MSFT'
2004-01-13 14:12:23 -75 340.43 'AAPL'
gross_lev : pd.Series, optional
The leverage of a strategy.
- Time series of the sum of long and short exposure per share
divided by net asset value.
- Example:
2009-12-04 0.999932
2009-12-07 0.999783
2009-12-08 0.999880
2009-12-09 1.000283
slippage : int/float, optional
Basis points of slippage to apply to returns before generating
tearsheet stats and plots.
If a value is provided, slippage parameter sweep
plots will be generated from the unadjusted returns.
Transactions and positions must also be passed.
- See txn.adjust_returns_for_slippage for more details.
live_start_date : datetime, optional
The point in time when the strategy began live trading,
after its backtest period. This datetime should be normalized.
hide_positions : bool, optional
If True, will not output any symbol names.
bayesian: boolean, optional
If True, causes the generation of a Bayesian tear sheet.
round_trips: boolean, optional
If True, causes the generation of a round trip tear sheet.
cone_std : float, or tuple, optional
If float, The standard deviation to use for the cone plots.
If tuple, Tuple of standard deviation values to use for the cone plots
- The cone is a normal distribution with this standard deviation
centered around a linear regression.
bootstrap : boolean (optional)
Whether to perform bootstrap analysis for the performance
metrics. Takes a few minutes longer.
set_context : boolean, optional
If True, set default plotting style context.
- See plotting.context().
"""
if benchmark_rets is None:
benchmark_rets = utils.get_symbol_rets('SPY')
# If the strategy's history is longer than the benchmark's, limit strategy
if returns.index[0] < benchmark_rets.index[0]:
returns = returns[returns.index > benchmark_rets.index[0]]
if slippage is not None and transactions is not None:
turnover = txn.get_turnover(positions, transactions,
period=None, average=False)
unadjusted_returns = returns.copy()
returns = txn.adjust_returns_for_slippage(returns, turnover, slippage)
else:
unadjusted_returns = None
create_returns_tear_sheet(
returns,
live_start_date=live_start_date,
cone_std=cone_std,
benchmark_rets=benchmark_rets,
bootstrap=bootstrap,
set_context=set_context)
create_interesting_times_tear_sheet(returns,
benchmark_rets=benchmark_rets,
set_context=set_context)
if positions is not None:
create_position_tear_sheet(returns, positions,
gross_lev=gross_lev,
hide_positions=hide_positions,
set_context=set_context,
sector_mappings=sector_mappings)
if transactions is not None:
create_txn_tear_sheet(returns, positions, transactions,
unadjusted_returns=unadjusted_returns,
set_context=set_context)
if round_trips:
create_round_trip_tear_sheet(
positions=positions,
transactions=transactions,
sector_mappings=sector_mappings)
if bayesian:
create_bayesian_tear_sheet(returns,
live_start_date=live_start_date,
benchmark_rets=benchmark_rets,
set_context=set_context)
@plotting_context
def create_returns_tear_sheet(returns, live_start_date=None,
cone_std=(1.0, 1.5, 2.0),
benchmark_rets=None,
bootstrap=False,
return_fig=False):
"""
Generate a number of plots for analyzing a strategy's returns.
- Fetches benchmarks, then creates the plots on a single figure.
- Plots: rolling returns (with cone), rolling beta, rolling sharpe,
rolling Fama-French risk factors, drawdowns, underwater plot, monthly
and annual return plots, daily similarity plots,
and return quantile box plot.
- Will also print the start and end dates of the strategy,
performance statistics, drawdown periods, and the return range.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in create_full_tear_sheet.
live_start_date : datetime, optional
The point in time when the strategy began live trading,
after its backtest period.
cone_std : float, or tuple, optional
If float, The standard deviation to use for the cone plots.
If tuple, Tuple of standard deviation values to use for the cone plots
- The cone is a normal distribution with this standard deviation
centered around a linear regression.
benchmark_rets : pd.Series, optional
Daily noncumulative returns of the benchmark.
- This is in the same style as returns.
bootstrap : boolean (optional)
Whether to perform bootstrap analysis for the performance
metrics. Takes a few minutes longer.
return_fig : boolean, optional
If True, returns the figure that was plotted on.
set_context : boolean, optional
If True, set default plotting style context.
"""
if benchmark_rets is None:
benchmark_rets = utils.get_symbol_rets('SPY')
# If the strategy's history is longer than the benchmark's, limit
# strategy
if returns.index[0] < benchmark_rets.index[0]:
returns = returns[returns.index > benchmark_rets.index[0]]
df_cum_rets = timeseries.cum_returns(returns, starting_value=1)
print("Entire data start date: " + str(df_cum_rets
.index[0].strftime('%Y-%m-%d')))
print("Entire data end date: " + str(df_cum_rets
.index[-1].strftime('%Y-%m-%d')))
print('\n')
plotting.show_perf_stats(returns, benchmark_rets,
bootstrap=bootstrap,
live_start_date=live_start_date)
if live_start_date is not None:
vertical_sections = 11
live_start_date = utils.get_utc_timestamp(live_start_date)
else:
vertical_sections = 10
if bootstrap:
vertical_sections += 1
fig = plt.figure(figsize=(14, vertical_sections * 6))
gs = gridspec.GridSpec(vertical_sections, 3, wspace=0.5, hspace=0.5)
ax_rolling_returns = plt.subplot(gs[:2, :])
ax_rolling_returns_vol_match = plt.subplot(gs[2, :],
sharex=ax_rolling_returns)
ax_rolling_beta = plt.subplot(gs[3, :], sharex=ax_rolling_returns)
ax_rolling_sharpe = plt.subplot(gs[4, :], sharex=ax_rolling_returns)
ax_rolling_risk = plt.subplot(gs[5, :], sharex=ax_rolling_returns)
ax_drawdown = plt.subplot(gs[6, :], sharex=ax_rolling_returns)
ax_underwater = plt.subplot(gs[7, :], sharex=ax_rolling_returns)
ax_monthly_heatmap = plt.subplot(gs[8, 0])
ax_annual_returns = plt.subplot(gs[8, 1])
ax_monthly_dist = plt.subplot(gs[8, 2])
ax_return_quantiles = plt.subplot(gs[9, :])
plotting.plot_rolling_returns(
returns,
factor_returns=benchmark_rets,
live_start_date=live_start_date,
cone_std=cone_std,
ax=ax_rolling_returns)
ax_rolling_returns.set_title(
'Cumulative Returns')
plotting.plot_rolling_returns(
returns,
factor_returns=benchmark_rets,
live_start_date=live_start_date,
cone_std=None,
volatility_match=True,
legend_loc=None,
ax=ax_rolling_returns_vol_match)
ax_rolling_returns_vol_match.set_title(
'Cumulative returns volatility matched to benchmark.')
plotting.plot_rolling_beta(
returns, benchmark_rets, ax=ax_rolling_beta)
plotting.plot_rolling_sharpe(
returns, ax=ax_rolling_sharpe)
plotting.plot_rolling_fama_french(
returns, ax=ax_rolling_risk)
# Drawdowns
plotting.plot_drawdown_periods(
returns, top=5, ax=ax_drawdown)
plotting.plot_drawdown_underwater(
returns=returns, ax=ax_underwater)
plotting.show_worst_drawdown_periods(returns)
df_weekly = timeseries.aggregate_returns(returns, 'weekly')
df_monthly = timeseries.aggregate_returns(returns, 'monthly')
print('\n')
plotting.show_return_range(returns, df_weekly)
plotting.plot_monthly_returns_heatmap(returns, ax=ax_monthly_heatmap)
plotting.plot_annual_returns(returns, ax=ax_annual_returns)
plotting.plot_monthly_returns_dist(returns, ax=ax_monthly_dist)
plotting.plot_return_quantiles(
returns,
df_weekly,
df_monthly,
ax=ax_return_quantiles)
if bootstrap:
ax_bootstrap = plt.subplot(gs[10, :])
plotting.plot_perf_stats(returns, benchmark_rets,
ax=ax_bootstrap)
for ax in fig.axes:
plt.setp(ax.get_xticklabels(), visible=True)
plt.show()
if return_fig:
return fig
@plotting_context
def create_position_tear_sheet(returns, positions, gross_lev=None,
show_and_plot_top_pos=2, hide_positions=False,
return_fig=False, sector_mappings=None):
"""
Generate a number of plots for analyzing a
strategy's positions and holdings.
- Plots: gross leverage, exposures, top positions, and holdings.
- Will also print the top positions held.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in create_full_tear_sheet.
positions : pd.DataFrame
Daily net position values.
- See full explanation in create_full_tear_sheet.
gross_lev : pd.Series, optional
The leverage of a strategy.
- See full explanation in create_full_tear_sheet.
show_and_plot_top_pos : int, optional
By default, this is 2, and both prints and plots the
top 10 positions.
If this is 0, it will only plot; if 1, it will only print.
hide_positions : bool, optional
If True, will not output any symbol names.
Overrides show_and_plot_top_pos to 0 to suppress text output.
return_fig : boolean, optional
If True, returns the figure that was plotted on.
set_context : boolean, optional
If True, set default plotting style context.
sector_mappings : dict or pd.Series, optional
Security identifier to sector mapping.
Security ids as keys, sectors as values.
"""
if hide_positions:
show_and_plot_top_pos = 0
vertical_sections = 6 if sector_mappings is not None else 5
fig = plt.figure(figsize=(14, vertical_sections * 6))
gs = gridspec.GridSpec(vertical_sections, 3, wspace=0.5, hspace=0.5)
ax_gross_leverage = plt.subplot(gs[0, :])
ax_exposures = plt.subplot(gs[1, :], sharex=ax_gross_leverage)
ax_top_positions = plt.subplot(gs[2, :], sharex=ax_gross_leverage)
ax_max_median_pos = plt.subplot(gs[3, :], sharex=ax_gross_leverage)
ax_holdings = plt.subplot(gs[4, :], sharex=ax_gross_leverage)
positions_alloc = pos.get_percent_alloc(positions)
if gross_lev is not None:
plotting.plot_gross_leverage(returns, gross_lev, ax=ax_gross_leverage)
plotting.plot_exposures(returns, positions_alloc, ax=ax_exposures)
plotting.show_and_plot_top_positions(
returns,
positions_alloc,
show_and_plot=show_and_plot_top_pos,
hide_positions=hide_positions,
ax=ax_top_positions)
plotting.plot_max_median_position_concentration(positions,
ax=ax_max_median_pos)
plotting.plot_holdings(returns, positions_alloc, ax=ax_holdings)
if sector_mappings is not None:
sector_exposures = pos.get_sector_exposures(positions, sector_mappings)
if len(sector_exposures.columns) > 1:
sector_alloc = pos.get_percent_alloc(sector_exposures)
sector_alloc = sector_alloc.drop('cash', axis='columns')
ax_sector_alloc = plt.subplot(gs[5, :], sharex=ax_gross_leverage)
plotting.plot_sector_allocations(returns, sector_alloc,
ax=ax_sector_alloc)
for ax in fig.axes:
plt.setp(ax.get_xticklabels(), visible=True)
plt.show()
if return_fig:
return fig
@plotting_context
def create_txn_tear_sheet(returns, positions, transactions,
unadjusted_returns=None, return_fig=False):
"""
Generate a number of plots for analyzing a strategy's transactions.
Plots: turnover, daily volume, and a histogram of daily volume.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in create_full_tear_sheet.
positions : pd.DataFrame
Daily net position values.
- See full explanation in create_full_tear_sheet.
transactions : pd.DataFrame
Prices and amounts of executed trades. One row per trade.
- See full explanation in create_full_tear_sheet.
unadjusted_returns : pd.Series, optional
Daily unadjusted returns of the strategy, noncumulative.
Will plot additional swippage sweep analysis.
- See pyfolio.plotting.plot_swippage_sleep and
pyfolio.plotting.plot_slippage_sensitivity
return_fig : boolean, optional
If True, returns the figure that was plotted on.
"""
vertical_sections = 5 if unadjusted_returns is not None else 3
fig = plt.figure(figsize=(14, vertical_sections * 6))
gs = gridspec.GridSpec(vertical_sections, 3, wspace=0.5, hspace=0.5)
ax_turnover = plt.subplot(gs[0, :])
ax_daily_volume = plt.subplot(gs[1, :], sharex=ax_turnover)
ax_turnover_hist = plt.subplot(gs[2, :])
plotting.plot_turnover(
returns,
transactions,
positions,
ax=ax_turnover)
plotting.plot_daily_volume(returns, transactions, ax=ax_daily_volume)
try:
plotting.plot_daily_turnover_hist(transactions, positions,
ax=ax_turnover_hist)
except ValueError:
warnings.warn('Unable to generate turnover plot.', UserWarning)
if unadjusted_returns is not None:
ax_slippage_sweep = plt.subplot(gs[3, :])
plotting.plot_slippage_sweep(unadjusted_returns,
transactions,
positions,
ax=ax_slippage_sweep
)
ax_slippage_sensitivity = plt.subplot(gs[4, :])
plotting.plot_slippage_sensitivity(unadjusted_returns,
transactions,
positions,
ax=ax_slippage_sensitivity
)
for ax in fig.axes:
plt.setp(ax.get_xticklabels(), visible=True)
plt.show()
if return_fig:
return fig
@plotting_context
def create_round_trip_tear_sheet(positions, transactions,
sector_mappings=None,
return_fig=False):
"""
Generate a number of figures and plots describing the duration,
frequency, and profitability of trade "round trips."
A round trip is started when a new long or short position is
opened and is only completed when the number of shares in that
position returns to or crosses zero.
Parameters
----------
positions : pd.DataFrame
Daily net position values.
- See full explanation in create_full_tear_sheet.
transactions : pd.DataFrame
Prices and amounts of executed trades. One row per trade.
- See full explanation in create_full_tear_sheet.
sector_mappings : dict or pd.Series, optional
Security identifier to sector mapping.
Security ids as keys, sectors as values.
return_fig : boolean, optional
If True, returns the figure that was plotted on.
"""
transactions_closed = round_trips.add_closing_transactions(positions,
transactions)
trades = round_trips.extract_round_trips(transactions_closed)
if len(trades) < 5:
warnings.warn(
"""Fewer than 5 round-trip trades made.
Skipping round trip tearsheet.""", UserWarning)
return
ndays = len(positions)
print(trades.drop(['open_dt', 'close_dt', 'symbol'],
axis='columns').describe())
print('Percent of round trips profitable = {:.4}%'.format(
(trades.pnl > 0).mean() * 100))
winning_round_trips = trades[trades.pnl > 0]
losing_round_trips = trades[trades.pnl < 0]
print('Mean return per winning round trip = {:.4}'.format(
winning_round_trips.returns.mean()))
print('Mean return per losing round trip = {:.4}'.format(
losing_round_trips.returns.mean()))
print('A decision is made every {:.4} days.'.format(ndays / len(trades)))
print('{:.4} trading decisions per day.'.format(len(trades) * 1. / ndays))
print('{:.4} trading decisions per month.'.format(
len(trades) * 1. / (ndays / 21)))
plotting.show_profit_attribution(trades)
if sector_mappings is not None:
sector_trades = round_trips.apply_sector_mappings_to_round_trips(
trades, sector_mappings)
plotting.show_profit_attribution(sector_trades)
fig = plt.figure(figsize=(14, 3 * 6))
fig = plt.figure(figsize=(14, 3 * 6))
gs = gridspec.GridSpec(3, 2, wspace=0.5, hspace=0.5)
ax_trade_lifetimes = plt.subplot(gs[0, :])
ax_prob_profit_trade = plt.subplot(gs[1, 0])
ax_holding_time = plt.subplot(gs[1, 1])
ax_pnl_per_round_trip_dollars = plt.subplot(gs[2, 0])
ax_pnl_per_round_trip_pct = plt.subplot(gs[2, 1])
plotting.plot_round_trip_life_times(trades, ax=ax_trade_lifetimes)
plotting.plot_prob_profit_trade(trades, ax=ax_prob_profit_trade)
trade_holding_times = [x.days for x in trades['duration']]
sns.distplot(trade_holding_times, kde=False, ax=ax_holding_time)
ax_holding_time.set(xlabel='holding time in days')
sns.distplot(trades.pnl, kde=False, ax=ax_pnl_per_round_trip_dollars)
ax_pnl_per_round_trip_dollars.set(xlabel='PnL per round-trip trade in $')
sns.distplot(trades.returns * 100, kde=False,
ax=ax_pnl_per_round_trip_pct)
ax_pnl_per_round_trip_pct.set(
xlabel='Round-trip returns in %')
gs.tight_layout(fig)
plt.show()
if return_fig:
return fig
@plotting_context
def create_interesting_times_tear_sheet(
returns, benchmark_rets=None, legend_loc='best', return_fig=False):
"""
Generate a number of returns plots around interesting points in time,
like the flash crash and 9/11.
Plots: returns around the dotcom bubble burst, Lehmann Brothers' failure,
9/11, US downgrade and EU debt crisis, Fukushima meltdown, US housing
bubble burst, EZB IR, Great Recession (August 2007, March and September
of 2008, Q1 & Q2 2009), flash crash, April and October 2014.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in create_full_tear_sheet.
benchmark_rets : pd.Series, optional
Daily noncumulative returns of the benchmark.
- This is in the same style as returns.
legend_loc : plt.legend_loc, optional
The legend's location.
return_fig : boolean, optional
If True, returns the figure that was plotted on.
set_context : boolean, optional
If True, set default plotting style context.
"""
rets_interesting = timeseries.extract_interesting_date_ranges(returns)
if len(rets_interesting) == 0:
warnings.warn('Passed returns do not overlap with any'
'interesting times.', UserWarning)
return
print('\nStress Events')
print(np.round(pd.DataFrame(rets_interesting).describe().transpose().loc[
:, ['mean', 'min', 'max']], 3))
if benchmark_rets is None:
benchmark_rets = utils.get_symbol_rets('SPY')
# If the strategy's history is longer than the benchmark's, limit
# strategy
if returns.index[0] < benchmark_rets.index[0]:
returns = returns[returns.index > benchmark_rets.index[0]]
bmark_interesting = timeseries.extract_interesting_date_ranges(
benchmark_rets)
num_plots = len(rets_interesting)
# 2 plots, 1 row; 3 plots, 2 rows; 4 plots, 2 rows; etc.
num_rows = int((num_plots + 1) / 2.0)
fig = plt.figure(figsize=(14, num_rows * 6.0))
gs = gridspec.GridSpec(num_rows, 2, wspace=0.5, hspace=0.5)
for i, (name, rets_period) in enumerate(rets_interesting.items()):
# i=0 -> 0, i=1 -> 0, i=2 -> 1 ;; i=0 -> 0, i=1 -> 1, i=2 -> 0
ax = plt.subplot(gs[int(i / 2.0), i % 2])
timeseries.cum_returns(rets_period).plot(
ax=ax, color='forestgreen', label='algo', alpha=0.7, lw=2)
timeseries.cum_returns(bmark_interesting[name]).plot(
ax=ax, color='gray', label='SPY', alpha=0.6)
ax.legend(['algo',
'SPY'],
loc=legend_loc)
ax.set_title(name, size=14)
ax.set_ylabel('Returns')
ax.set_xlabel('')
plt.show()
if return_fig:
return fig
@plotting_context
def create_bayesian_tear_sheet(returns, benchmark_rets=None,
live_start_date=None, samples=2000,
return_fig=False, stoch_vol=False):
"""
Generate a number of Bayesian distributions and a Bayesian
cone plot of returns.
Plots: Sharpe distribution, annual volatility distribution,
annual alpha distribution, beta distribution, predicted 1 and 5
day returns distributions, and a cumulative returns cone plot.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in create_full_tear_sheet.
benchmark_rets : pd.Series or pd.DataFrame, optional
Daily noncumulative returns of the benchmark.
- This is in the same style as returns.
live_start_date : datetime, optional
The point in time when the strategy began live
trading, after its backtest period.
samples : int, optional
Number of posterior samples to draw.
return_fig : boolean, optional
If True, returns the figure that was plotted on.
set_context : boolean, optional
If True, set default plotting style context.
stoch_vol : boolean, optional
If True, run and plot the stochastic volatility model
"""
if live_start_date is None:
raise NotImplementedError(
'Bayesian tear sheet requires setting of live_start_date'
)
# start by benchmark is S&P500
fama_french = False
if benchmark_rets is None:
benchmark_rets = pd.DataFrame(
utils.get_symbol_rets('SPY',
start=returns.index[0],
end=returns.index[-1]))
# unless user indicates otherwise
elif isinstance(benchmark_rets, str) and (benchmark_rets ==
'Fama-French'):
fama_french = True
rolling_window = utils.APPROX_BDAYS_PER_MONTH * 6
benchmark_rets = timeseries.rolling_fama_french(
returns, rolling_window=rolling_window)
live_start_date = utils.get_utc_timestamp(live_start_date)
df_train = returns.loc[returns.index < live_start_date]
df_test = returns.loc[returns.index >= live_start_date]
# Run T model with missing data
print("Running T model")
previous_time = time()
# track the total run time of the Bayesian tear sheet
start_time = previous_time
trace_t, ppc_t = bayesian.run_model('t', df_train,
returns_test=df_test,
samples=samples, ppc=True)
previous_time = timer("T model", previous_time)
# Compute BEST model
print("\nRunning BEST model")
trace_best = bayesian.run_model('best', df_train,
returns_test=df_test,
samples=samples)
previous_time = timer("BEST model", previous_time)
# Plot results
fig = plt.figure(figsize=(14, 10 * 2))
gs = gridspec.GridSpec(9, 2, wspace=0.3, hspace=0.3)
axs = []
row = 0
# Plot Bayesian cone
ax_cone = plt.subplot(gs[row, :])
bayesian.plot_bayes_cone(df_train, df_test, ppc_t, ax=ax_cone)
previous_time = timer("plotting Bayesian cone", previous_time)
# Plot BEST results
row += 1
axs.append(plt.subplot(gs[row, 0]))
axs.append(plt.subplot(gs[row, 1]))
row += 1
axs.append(plt.subplot(gs[row, 0]))
axs.append(plt.subplot(gs[row, 1]))
row += 1
axs.append(plt.subplot(gs[row, 0]))
axs.append(plt.subplot(gs[row, 1]))
row += 1
# Effect size across two
axs.append(plt.subplot(gs[row, :]))
bayesian.plot_best(trace=trace_best, axs=axs)
previous_time = timer("plotting BEST results", previous_time)
# Compute Bayesian predictions
row += 1
ax_ret_pred_day = plt.subplot(gs[row, 0])
ax_ret_pred_week = plt.subplot(gs[row, 1])
day_pred = ppc_t[:, 0]
p5 = scipy.stats.scoreatpercentile(day_pred, 5)
sns.distplot(day_pred,
ax=ax_ret_pred_day
)
ax_ret_pred_day.axvline(p5, linestyle='--', linewidth=3.)
ax_ret_pred_day.set_xlabel('Predicted returns 1 day')
ax_ret_pred_day.set_ylabel('Frequency')
ax_ret_pred_day.text(0.4, 0.9, 'Bayesian VaR = %.2f' % p5,
verticalalignment='bottom',
horizontalalignment='right',
transform=ax_ret_pred_day.transAxes)
previous_time = timer("computing Bayesian predictions", previous_time)
# Plot Bayesian VaRs
week_pred = (
np.cumprod(ppc_t[:, :5] + 1, 1) - 1)[:, -1]
p5 = scipy.stats.scoreatpercentile(week_pred, 5)
sns.distplot(week_pred,
ax=ax_ret_pred_week
)
ax_ret_pred_week.axvline(p5, linestyle='--', linewidth=3.)
ax_ret_pred_week.set_xlabel('Predicted cum returns 5 days')
ax_ret_pred_week.set_ylabel('Frequency')
ax_ret_pred_week.text(0.4, 0.9, 'Bayesian VaR = %.2f' % p5,
verticalalignment='bottom',
horizontalalignment='right',
transform=ax_ret_pred_week.transAxes)
previous_time = timer("plotting Bayesian VaRs estimate", previous_time)
# Run alpha beta model
print("\nRunning alpha beta model")
benchmark_rets = benchmark_rets.loc[df_train.index]
trace_alpha_beta = bayesian.run_model('alpha_beta', df_train,
bmark=benchmark_rets,
samples=samples)
previous_time = timer("running alpha beta model", previous_time)
# Plot alpha and beta
row += 1
ax_alpha = plt.subplot(gs[row, 0])
ax_beta = plt.subplot(gs[row, 1])
if fama_french:
sns.distplot((1 + trace_alpha_beta['alpha'][100:])**252 - 1,
ax=ax_alpha)
betas = ['SMB', 'HML', 'UMD']
nbeta = trace_alpha_beta['beta'].shape[1]
for i in range(nbeta):
sns.distplot(trace_alpha_beta['beta'][100:, i], ax=ax_beta,
label=betas[i])
plt.legend()
else:
sns.distplot((1 + trace_alpha_beta['alpha'][100:])**252 - 1,
ax=ax_alpha)
sns.distplot(trace_alpha_beta['beta'][100:], ax=ax_beta)
ax_alpha.set_xlabel('Annual Alpha')
ax_alpha.set_ylabel('Belief')
ax_beta.set_xlabel('Beta')
ax_beta.set_ylabel('Belief')
previous_time = timer("plotting alpha beta model", previous_time)
if stoch_vol:
# run stochastic volatility model
returns_cutoff = 400
print(
"\nRunning stochastic volatility model on "
"most recent {} days of returns.".format(returns_cutoff)
)
if df_train.size > returns_cutoff:
df_train_truncated = df_train[-returns_cutoff:]
_, trace_stoch_vol = bayesian.model_stoch_vol(df_train_truncated)
previous_time = timer(
"running stochastic volatility model", previous_time)
# plot log(sigma) and log(nu)
print("\nPlotting stochastic volatility model")
row += 1
ax_sigma_log = plt.subplot(gs[row, 0])
ax_nu_log = plt.subplot(gs[row, 1])
sigma_log = trace_stoch_vol['sigma_log']
sns.distplot(sigma_log, ax=ax_sigma_log)
ax_sigma_log.set_xlabel('log(Sigma)')
ax_sigma_log.set_ylabel('Belief')
nu_log = trace_stoch_vol['nu_log']
sns.distplot(nu_log, ax=ax_nu_log)
ax_nu_log.set_xlabel('log(nu)')
ax_nu_log.set_ylabel('Belief')
# plot latent volatility
row += 1
ax_volatility = plt.subplot(gs[row, :])
bayesian.plot_stoch_vol(
df_train_truncated, trace=trace_stoch_vol, ax=ax_volatility)
previous_time = timer(
"plotting stochastic volatility model", previous_time)
total_time = time() - start_time
print("\nTotal runtime was {:.2f} seconds.".format(total_time))
gs.tight_layout(fig)
plt.show()
if return_fig:
return fig
| timer |
capi.rs | use rand::prelude::*;
use std::{
cell::RefCell,
ffi::{CStr, CString},
fmt,
os::raw::c_char,
};
enum Error {
Biscuit(crate::error::Token),
InvalidArgument,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::InvalidArgument => write!(f, "invalid argument"),
Error::Biscuit(e) => write!(f, "{}", e),
}
}
}
thread_local! {
static LAST_ERROR: RefCell<Option<Error>> = RefCell::new(None);
}
fn update_last_error(err: Error) {
LAST_ERROR.with(|prev| {
*prev.borrow_mut() = Some(err);
});
}
#[no_mangle]
pub extern "C" fn error_message() -> *const c_char {
thread_local! {
static LAST: RefCell<Option<CString>> = RefCell::new(None);
}
LAST_ERROR.with(|prev| match *prev.borrow() {
Some(ref err) => {
let err = CString::new(err.to_string()).ok();
LAST.with(|ret| {
*ret.borrow_mut() = err;
ret.borrow()
.as_ref()
.map(|x| x.as_ptr())
.unwrap_or(std::ptr::null())
})
}
None => std::ptr::null(),
})
}
#[repr(C)]
pub enum ErrorKind {
None,
InvalidArgument,
InternalError,
FormatSignatureInvalidFormat,
FormatSignatureInvalidSignature,
FormatSealedSignature,
FormatEmptyKeys,
FormatUnknownPublicKey,
FormatDeserializationError,
FormatSerializationError,
FormatBlockDeserializationError,
FormatBlockSerializationError,
FormatVersion,
InvalidAuthorityIndex,
InvalidBlockIndex,
SymbolTableOverlap,
MissingSymbols,
Sealed,
LogicInvalidAuthorityFact,
LogicInvalidAmbientFact,
LogicInvalidBlockFact,
LogicInvalidBlockRule,
LogicFailedChecks,
LogicAuthorizerNotEmpty,
LogicDeny,
LogicNoMatchingPolicy,
ParseError,
TooManyFacts,
TooManyIterations,
Timeout,
ConversionError,
FormatInvalidKeySize,
FormatInvalidSignatureSize,
FormatInvalidKey,
FormatSignatureInvalidSignatureGeneration,
}
#[no_mangle]
pub extern "C" fn error_kind() -> ErrorKind {
LAST_ERROR.with(|prev| match *prev.borrow() {
Some(ref err) => match err {
Error::InvalidArgument => ErrorKind::InvalidArgument,
Error::Biscuit(e) => {
use crate::error::*;
match e {
Token::InternalError => ErrorKind::InternalError,
Token::Format(Format::Signature(Signature::InvalidFormat)) => {
ErrorKind::FormatSignatureInvalidFormat
}
Token::Format(Format::Signature(Signature::InvalidSignature(_))) => {
ErrorKind::FormatSignatureInvalidSignature
}
Token::Format(Format::Signature(Signature::InvalidSignatureGeneration(_))) => {
ErrorKind::FormatSignatureInvalidSignatureGeneration
}
Token::Format(Format::SealedSignature) => ErrorKind::FormatSealedSignature,
Token::Format(Format::EmptyKeys) => ErrorKind::FormatEmptyKeys,
Token::Format(Format::UnknownPublicKey) => ErrorKind::FormatUnknownPublicKey,
Token::Format(Format::DeserializationError(_)) => {
ErrorKind::FormatDeserializationError
}
Token::Format(Format::SerializationError(_)) => {
ErrorKind::FormatSerializationError
}
Token::Format(Format::BlockDeserializationError(_)) => {
ErrorKind::FormatBlockDeserializationError
}
Token::Format(Format::BlockSerializationError(_)) => {
ErrorKind::FormatBlockSerializationError
}
Token::Format(Format::Version { .. }) => ErrorKind::FormatVersion,
Token::Format(Format::InvalidKeySize(_)) => ErrorKind::FormatInvalidKeySize,
Token::Format(Format::InvalidSignatureSize(_)) => {
ErrorKind::FormatInvalidSignatureSize
}
Token::Format(Format::InvalidKey(_)) => ErrorKind::FormatInvalidKey,
Token::InvalidAuthorityIndex(_) => ErrorKind::InvalidAuthorityIndex,
Token::InvalidBlockIndex(_) => ErrorKind::InvalidBlockIndex,
Token::SymbolTableOverlap => ErrorKind::SymbolTableOverlap,
Token::MissingSymbols => ErrorKind::MissingSymbols,
Token::Sealed => ErrorKind::Sealed,
Token::ParseError(_) => ErrorKind::ParseError,
Token::FailedLogic(Logic::InvalidAuthorityFact(_)) => {
ErrorKind::LogicInvalidAuthorityFact
}
Token::FailedLogic(Logic::InvalidAmbientFact(_)) => {
ErrorKind::LogicInvalidAmbientFact
}
Token::FailedLogic(Logic::InvalidBlockFact(_, _)) => {
ErrorKind::LogicInvalidBlockFact
}
Token::FailedLogic(Logic::InvalidBlockRule(_, _)) => {
ErrorKind::LogicInvalidBlockRule
}
Token::FailedLogic(Logic::FailedChecks(_)) => ErrorKind::LogicFailedChecks,
Token::FailedLogic(Logic::AuthorizerNotEmpty) => {
ErrorKind::LogicAuthorizerNotEmpty
}
Token::FailedLogic(Logic::Deny(_)) => ErrorKind::LogicDeny,
Token::FailedLogic(Logic::NoMatchingPolicy) => ErrorKind::LogicNoMatchingPolicy,
Token::RunLimit(RunLimit::TooManyFacts) => ErrorKind::TooManyFacts,
Token::RunLimit(RunLimit::TooManyIterations) => ErrorKind::TooManyIterations,
Token::RunLimit(RunLimit::Timeout) => ErrorKind::Timeout,
Token::ConversionError(_) => ErrorKind::ConversionError,
Token::Base64(_) => ErrorKind::FormatDeserializationError,
}
}
},
None => ErrorKind::None,
})
}
#[no_mangle]
pub extern "C" fn error_check_count() -> u64 {
use crate::error::*;
LAST_ERROR.with(|prev| match *prev.borrow() {
Some(Error::Biscuit(Token::FailedLogic(Logic::FailedChecks(ref v)))) => v.len() as u64,
_ => 0,
})
}
#[no_mangle]
pub extern "C" fn error_check_id(check_index: u64) -> u64 {
use crate::error::*;
LAST_ERROR.with(|prev| match *prev.borrow() {
Some(Error::Biscuit(Token::FailedLogic(Logic::FailedChecks(ref v)))) => {
if check_index >= v.len() as u64 {
u64::MAX
} else {
match v[check_index as usize] {
FailedCheck::Block(FailedBlockCheck { check_id, .. }) => check_id as u64,
FailedCheck::Authorizer(FailedAuthorizerCheck { check_id, .. }) => {
check_id as u64
}
}
}
}
_ => u64::MAX,
})
}
#[no_mangle]
pub extern "C" fn error_check_block_id(check_index: u64) -> u64 {
use crate::error::*;
LAST_ERROR.with(|prev| match *prev.borrow() {
Some(Error::Biscuit(Token::FailedLogic(Logic::FailedChecks(ref v)))) => {
if check_index >= v.len() as u64 {
u64::MAX
} else {
match v[check_index as usize] {
FailedCheck::Block(FailedBlockCheck { block_id, .. }) => block_id as u64,
_ => u64::MAX,
}
}
}
_ => u64::MAX,
})
}
/// deallocation is handled by Biscuit
/// the string is overwritten on each call
#[no_mangle]
pub extern "C" fn error_check_rule(check_index: u64) -> *const c_char {
use crate::error::*;
thread_local! {
static CAVEAT_RULE: RefCell<Option<CString>> = RefCell::new(None);
}
LAST_ERROR.with(|prev| match *prev.borrow() {
Some(Error::Biscuit(Token::FailedLogic(Logic::FailedChecks(ref v)))) => {
if check_index >= v.len() as u64 {
std::ptr::null()
} else {
let rule = match &v[check_index as usize] {
FailedCheck::Block(FailedBlockCheck { rule, .. }) => rule,
FailedCheck::Authorizer(FailedAuthorizerCheck { rule, .. }) => rule,
};
let err = CString::new(rule.clone()).ok();
CAVEAT_RULE.with(|ret| {
*ret.borrow_mut() = err;
ret.borrow()
.as_ref()
.map(|x| x.as_ptr())
.unwrap_or(std::ptr::null())
})
}
}
_ => std::ptr::null(),
})
}
#[no_mangle]
pub extern "C" fn error_check_is_authorizer(check_index: u64) -> bool {
use crate::error::*;
LAST_ERROR.with(|prev| match *prev.borrow() {
Some(Error::Biscuit(Token::FailedLogic(Logic::FailedChecks(ref v)))) => {
if check_index >= v.len() as u64 {
false
} else {
match v[check_index as usize] {
FailedCheck::Block(FailedBlockCheck { .. }) => false,
FailedCheck::Authorizer(FailedAuthorizerCheck { .. }) => true,
}
}
}
_ => false,
})
}
pub struct Biscuit(crate::token::Biscuit);
pub struct KeyPair(crate::crypto::KeyPair);
pub struct PublicKey(crate::crypto::PublicKey);
pub struct BiscuitBuilder<'a>(crate::token::builder::BiscuitBuilder<'a>);
pub struct BlockBuilder(crate::token::builder::BlockBuilder);
pub struct Authorizer<'t>(crate::token::authorizer::Authorizer<'t>);
#[no_mangle]
pub unsafe extern "C" fn | <'a>(
seed_ptr: *const u8,
seed_len: usize,
) -> Option<Box<KeyPair>> {
let slice = std::slice::from_raw_parts(seed_ptr, seed_len);
if slice.len() != 32 {
update_last_error(Error::InvalidArgument);
return None;
}
let mut seed = [0u8; 32];
seed.copy_from_slice(slice);
let mut rng: StdRng = SeedableRng::from_seed(seed);
Some(Box::new(KeyPair(crate::crypto::KeyPair::new_with_rng(
&mut rng,
))))
}
#[no_mangle]
pub unsafe extern "C" fn key_pair_public(kp: Option<&KeyPair>) -> Option<Box<PublicKey>> {
if kp.is_none() {
update_last_error(Error::InvalidArgument);
}
let kp = kp?;
Some(Box::new(PublicKey((*kp).0.public())))
}
/// expects a 32 byte buffer
#[no_mangle]
pub unsafe extern "C" fn key_pair_serialize(kp: Option<&KeyPair>, buffer_ptr: *mut u8) -> usize {
if kp.is_none() {
update_last_error(Error::InvalidArgument);
return 0;
}
let kp = kp.unwrap();
let output_slice = std::slice::from_raw_parts_mut(buffer_ptr, 32);
output_slice.copy_from_slice(&kp.0.private().to_bytes()[..]);
32
}
/// expects a 32 byte buffer
#[no_mangle]
pub unsafe extern "C" fn key_pair_deserialize(buffer_ptr: *mut u8) -> Option<Box<KeyPair>> {
let input_slice = std::slice::from_raw_parts_mut(buffer_ptr, 32);
match crate::crypto::PrivateKey::from_bytes(input_slice).ok() {
None => {
update_last_error(Error::InvalidArgument);
None
}
Some(privkey) => Some(Box::new(KeyPair(crate::crypto::KeyPair::from(privkey)))),
}
}
#[no_mangle]
pub unsafe extern "C" fn key_pair_free(_kp: Option<Box<KeyPair>>) {}
/// expects a 32 byte buffer
#[no_mangle]
pub unsafe extern "C" fn public_key_serialize(
kp: Option<&PublicKey>,
buffer_ptr: *mut u8,
) -> usize {
if kp.is_none() {
update_last_error(Error::InvalidArgument);
return 0;
}
let kp = kp.unwrap();
let output_slice = std::slice::from_raw_parts_mut(buffer_ptr, 32);
output_slice.copy_from_slice(&kp.0.to_bytes()[..]);
32
}
/// expects a 32 byte buffer
#[no_mangle]
pub unsafe extern "C" fn public_key_deserialize(buffer_ptr: *mut u8) -> Option<Box<PublicKey>> {
let input_slice = std::slice::from_raw_parts_mut(buffer_ptr, 32);
match crate::crypto::PublicKey::from_bytes(input_slice).ok() {
None => {
update_last_error(Error::InvalidArgument);
None
}
Some(pubkey) => Some(Box::new(PublicKey(pubkey))),
}
}
#[no_mangle]
pub unsafe extern "C" fn public_key_free(_kp: Option<Box<PublicKey>>) {}
#[no_mangle]
pub unsafe extern "C" fn biscuit_builder<'a>(
key_pair: Option<&'a KeyPair>,
) -> Option<Box<BiscuitBuilder<'a>>> {
if key_pair.is_none() {
update_last_error(Error::InvalidArgument);
}
let key_pair = key_pair?;
Some(Box::new(BiscuitBuilder(crate::token::Biscuit::builder(
&key_pair.0,
))))
}
#[no_mangle]
pub unsafe extern "C" fn biscuit_builder_set_authority_context<'a>(
builder: Option<&mut BiscuitBuilder<'a>>,
context: *const c_char,
) -> bool {
if builder.is_none() {
update_last_error(Error::InvalidArgument);
return false;
}
let builder = builder.unwrap();
let context = CStr::from_ptr(context);
let s = context.to_str();
match s {
Err(_) => {
update_last_error(Error::InvalidArgument);
false
}
Ok(context) => {
builder.0.set_context(context.to_string());
true
}
}
}
#[no_mangle]
pub unsafe extern "C" fn biscuit_builder_add_authority_fact<'a>(
builder: Option<&mut BiscuitBuilder<'a>>,
fact: *const c_char,
) -> bool {
if builder.is_none() {
update_last_error(Error::InvalidArgument);
return false;
}
let builder = builder.unwrap();
let fact = CStr::from_ptr(fact);
let s = fact.to_str();
if s.is_err() {
update_last_error(Error::InvalidArgument);
return false;
}
builder
.0
.add_authority_fact(s.unwrap())
.map_err(|e| {
update_last_error(Error::Biscuit(e));
})
.is_ok()
}
#[no_mangle]
pub unsafe extern "C" fn biscuit_builder_add_authority_rule<'a>(
builder: Option<&mut BiscuitBuilder<'a>>,
rule: *const c_char,
) -> bool {
if builder.is_none() {
update_last_error(Error::InvalidArgument);
return false;
}
let builder = builder.unwrap();
let rule = CStr::from_ptr(rule);
let s = rule.to_str();
if s.is_err() {
update_last_error(Error::InvalidArgument);
return false;
}
builder
.0
.add_authority_rule(s.unwrap())
.map_err(|e| {
update_last_error(Error::Biscuit(e));
})
.is_ok()
}
#[no_mangle]
pub unsafe extern "C" fn biscuit_builder_add_authority_check<'a>(
builder: Option<&mut BiscuitBuilder<'a>>,
check: *const c_char,
) -> bool {
if builder.is_none() {
update_last_error(Error::InvalidArgument);
return false;
}
let builder = builder.unwrap();
let check = CStr::from_ptr(check);
let s = check.to_str();
if s.is_err() {
update_last_error(Error::InvalidArgument);
return false;
}
builder
.0
.add_authority_check(s.unwrap())
.map_err(|e| {
update_last_error(Error::Biscuit(e));
})
.is_ok()
}
#[no_mangle]
pub unsafe extern "C" fn biscuit_builder_build<'a>(
builder: Option<&BiscuitBuilder<'a>>,
seed_ptr: *const u8,
seed_len: usize,
) -> Option<Box<Biscuit>> {
if builder.is_none() {
update_last_error(Error::InvalidArgument);
}
let builder = builder?;
let slice = std::slice::from_raw_parts(seed_ptr, seed_len);
if slice.len() != 32 {
return None;
}
let mut seed = [0u8; 32];
seed.copy_from_slice(slice);
let mut rng: StdRng = SeedableRng::from_seed(seed);
(*builder)
.0
.clone()
.build_with_rng(&mut rng)
.map(Biscuit)
.map(Box::new)
.ok()
}
#[no_mangle]
pub unsafe extern "C" fn biscuit_builder_free<'a>(_builder: Option<Box<BiscuitBuilder<'a>>>) {}
#[no_mangle]
pub unsafe extern "C" fn biscuit_from<'a>(
biscuit_ptr: *const u8,
biscuit_len: usize,
root: Option<&'a PublicKey>,
) -> Option<Box<Biscuit>> {
let biscuit = std::slice::from_raw_parts(biscuit_ptr, biscuit_len);
if root.is_none() {
update_last_error(Error::InvalidArgument);
}
let root = root?;
crate::token::Biscuit::from(biscuit, |_| root.0)
.map(Biscuit)
.map(Box::new)
.ok()
}
#[no_mangle]
pub unsafe extern "C" fn biscuit_serialized_size(biscuit: Option<&Biscuit>) -> usize {
if biscuit.is_none() {
update_last_error(Error::InvalidArgument);
return 0;
}
let biscuit = biscuit.unwrap();
match biscuit.0.serialized_size() {
Ok(sz) => sz,
Err(e) => {
update_last_error(Error::Biscuit(e));
return 0;
}
}
}
#[no_mangle]
pub unsafe extern "C" fn biscuit_sealed_size(biscuit: Option<&Biscuit>) -> usize {
if biscuit.is_none() {
update_last_error(Error::InvalidArgument);
return 0;
}
let biscuit = biscuit.unwrap();
match biscuit.0.serialized_size() {
Ok(sz) => sz,
Err(e) => {
update_last_error(Error::Biscuit(e));
return 0;
}
}
}
#[no_mangle]
pub unsafe extern "C" fn biscuit_serialize(
biscuit: Option<&Biscuit>,
buffer_ptr: *mut u8,
) -> usize {
if biscuit.is_none() {
update_last_error(Error::InvalidArgument);
return 0;
}
let biscuit = biscuit.unwrap();
match (*biscuit).0.to_vec() {
Ok(v) => {
let size = match biscuit.0.serialized_size() {
Ok(sz) => sz,
Err(e) => {
update_last_error(Error::Biscuit(e));
return 0;
}
};
let output_slice = std::slice::from_raw_parts_mut(buffer_ptr, size);
output_slice.copy_from_slice(&v[..]);
v.len()
}
Err(e) => {
update_last_error(Error::Biscuit(e));
0
}
}
}
#[no_mangle]
pub unsafe extern "C" fn biscuit_serialize_sealed(
biscuit: Option<&Biscuit>,
buffer_ptr: *mut u8,
) -> usize {
if biscuit.is_none() {
update_last_error(Error::InvalidArgument);
return 0;
}
let biscuit = biscuit.unwrap();
match (*biscuit).0.seal() {
Ok(b) => match b.to_vec() {
Ok(v) => {
let size = match biscuit.0.serialized_size() {
Ok(sz) => sz,
Err(e) => {
update_last_error(Error::Biscuit(e));
return 0;
}
};
let output_slice = std::slice::from_raw_parts_mut(buffer_ptr, size);
output_slice.copy_from_slice(&v[..]);
v.len()
}
Err(e) => {
update_last_error(Error::Biscuit(e));
0
}
},
Err(e) => {
update_last_error(Error::Biscuit(e));
0
}
}
}
#[no_mangle]
pub unsafe extern "C" fn biscuit_block_count(biscuit: Option<&Biscuit>) -> usize {
if biscuit.is_none() {
update_last_error(Error::InvalidArgument);
return 0;
}
let biscuit = biscuit.unwrap();
biscuit.0.blocks.len() + 1
}
#[no_mangle]
pub unsafe extern "C" fn biscuit_block_fact_count(
biscuit: Option<&Biscuit>,
block_index: u32,
) -> usize {
if biscuit.is_none() {
update_last_error(Error::InvalidArgument);
return 0;
}
let biscuit = biscuit.unwrap();
if block_index == 0 {
biscuit.0.authority.facts.len()
} else {
match biscuit.0.blocks.get(block_index as usize - 1) {
Some(b) => b.facts.len(),
None => {
update_last_error(Error::InvalidArgument);
return 0;
}
}
}
}
#[no_mangle]
pub unsafe extern "C" fn biscuit_block_rule_count(
biscuit: Option<&Biscuit>,
block_index: u32,
) -> usize {
if biscuit.is_none() {
update_last_error(Error::InvalidArgument);
return 0;
}
let biscuit = biscuit.unwrap();
if block_index == 0 {
biscuit.0.authority.rules.len()
} else {
match biscuit.0.blocks.get(block_index as usize - 1) {
Some(b) => b.rules.len(),
None => {
update_last_error(Error::InvalidArgument);
return 0;
}
}
}
}
#[no_mangle]
pub unsafe extern "C" fn biscuit_block_check_count(
biscuit: Option<&Biscuit>,
block_index: u32,
) -> usize {
if biscuit.is_none() {
update_last_error(Error::InvalidArgument);
return 0;
}
let biscuit = biscuit.unwrap();
if block_index == 0 {
biscuit.0.authority.checks.len()
} else {
match biscuit.0.blocks.get(block_index as usize - 1) {
Some(b) => b.checks.len(),
None => {
update_last_error(Error::InvalidArgument);
return 0;
}
}
}
}
#[no_mangle]
pub unsafe extern "C" fn biscuit_block_fact(
biscuit: Option<&Biscuit>,
block_index: u32,
fact_index: u32,
) -> *mut c_char {
if biscuit.is_none() {
update_last_error(Error::InvalidArgument);
return std::ptr::null_mut();
}
let biscuit = biscuit.unwrap();
let block = if block_index == 0 {
&biscuit.0.authority
} else {
match biscuit.0.blocks.get(block_index as usize - 1) {
Some(b) => b,
None => {
update_last_error(Error::InvalidArgument);
return std::ptr::null_mut();
}
}
};
match block.facts.get(fact_index as usize) {
None => {
update_last_error(Error::InvalidArgument);
return std::ptr::null_mut();
}
Some(fact) => match CString::new(biscuit.0.symbols.print_fact(fact)) {
Ok(s) => s.into_raw(),
Err(_) => {
update_last_error(Error::InvalidArgument);
return std::ptr::null_mut();
}
},
}
}
#[no_mangle]
pub unsafe extern "C" fn biscuit_block_rule(
biscuit: Option<&Biscuit>,
block_index: u32,
rule_index: u32,
) -> *mut c_char {
if biscuit.is_none() {
update_last_error(Error::InvalidArgument);
return std::ptr::null_mut();
}
let biscuit = biscuit.unwrap();
let block = if block_index == 0 {
&biscuit.0.authority
} else {
match biscuit.0.blocks.get(block_index as usize - 1) {
Some(b) => b,
None => {
update_last_error(Error::InvalidArgument);
return std::ptr::null_mut();
}
}
};
match block.rules.get(rule_index as usize) {
None => {
update_last_error(Error::InvalidArgument);
return std::ptr::null_mut();
}
Some(rule) => match CString::new(biscuit.0.symbols.print_rule(rule)) {
Ok(s) => s.into_raw(),
Err(_) => {
update_last_error(Error::InvalidArgument);
return std::ptr::null_mut();
}
},
}
}
#[no_mangle]
pub unsafe extern "C" fn biscuit_block_check(
biscuit: Option<&Biscuit>,
block_index: u32,
check_index: u32,
) -> *mut c_char {
if biscuit.is_none() {
update_last_error(Error::InvalidArgument);
return std::ptr::null_mut();
}
let biscuit = biscuit.unwrap();
let block = if block_index == 0 {
&biscuit.0.authority
} else {
match biscuit.0.blocks.get(block_index as usize - 1) {
Some(b) => b,
None => {
update_last_error(Error::InvalidArgument);
return std::ptr::null_mut();
}
}
};
match block.checks.get(check_index as usize) {
None => {
update_last_error(Error::InvalidArgument);
return std::ptr::null_mut();
}
Some(check) => match CString::new(biscuit.0.symbols.print_check(check)) {
Ok(s) => s.into_raw(),
Err(_) => {
update_last_error(Error::InvalidArgument);
return std::ptr::null_mut();
}
},
}
}
#[no_mangle]
pub unsafe extern "C" fn biscuit_block_context(
biscuit: Option<&Biscuit>,
block_index: u32,
) -> *mut c_char {
if biscuit.is_none() {
update_last_error(Error::InvalidArgument);
return std::ptr::null_mut();
}
let biscuit = biscuit.unwrap();
let block = if block_index == 0 {
&biscuit.0.authority
} else {
match biscuit.0.blocks.get(block_index as usize - 1) {
Some(b) => b,
None => {
update_last_error(Error::InvalidArgument);
return std::ptr::null_mut();
}
}
};
match &block.context {
None => {
return std::ptr::null_mut();
}
Some(context) => match CString::new(context.clone()) {
Ok(s) => s.into_raw(),
Err(_) => {
update_last_error(Error::InvalidArgument);
return std::ptr::null_mut();
}
},
}
}
#[no_mangle]
pub unsafe extern "C" fn biscuit_create_block(
biscuit: Option<&Biscuit>,
) -> Option<Box<BlockBuilder>> {
if biscuit.is_none() {
update_last_error(Error::InvalidArgument);
}
let biscuit = biscuit?;
Some(Box::new(BlockBuilder(biscuit.0.create_block())))
}
#[no_mangle]
pub unsafe extern "C" fn biscuit_append_block(
biscuit: Option<&Biscuit>,
block_builder: Option<&BlockBuilder>,
key_pair: Option<&KeyPair>,
) -> Option<Box<Biscuit>> {
if biscuit.is_none() {
update_last_error(Error::InvalidArgument);
}
let biscuit = biscuit?;
if block_builder.is_none() {
update_last_error(Error::InvalidArgument);
}
let builder = block_builder?;
if key_pair.is_none() {
update_last_error(Error::InvalidArgument);
}
let key_pair = key_pair?;
match biscuit
.0
.append_with_keypair(&key_pair.0, builder.0.clone())
{
Ok(token) => Some(Box::new(Biscuit(token))),
Err(e) => {
update_last_error(Error::Biscuit(e));
None
}
}
}
#[no_mangle]
pub unsafe extern "C" fn biscuit_authorizer<'a, 'b>(
biscuit: Option<&'a Biscuit>,
) -> Option<Box<Authorizer<'a>>> {
if biscuit.is_none() {
update_last_error(Error::InvalidArgument);
}
let biscuit = biscuit?;
(*biscuit).0.authorizer().map(Authorizer).map(Box::new).ok()
}
#[no_mangle]
pub unsafe extern "C" fn biscuit_free(_biscuit: Option<Box<Biscuit>>) {}
#[no_mangle]
pub unsafe extern "C" fn block_builder_set_context(
builder: Option<&mut BlockBuilder>,
context: *const c_char,
) -> bool {
if builder.is_none() {
update_last_error(Error::InvalidArgument);
return false;
}
let builder = builder.unwrap();
let context = CStr::from_ptr(context);
let s = context.to_str();
match s {
Err(_) => {
update_last_error(Error::InvalidArgument);
false
}
Ok(context) => {
builder.0.set_context(context.to_string());
true
}
}
}
#[no_mangle]
pub unsafe extern "C" fn block_builder_add_fact(
builder: Option<&mut BlockBuilder>,
fact: *const c_char,
) -> bool {
if builder.is_none() {
update_last_error(Error::InvalidArgument);
return false;
}
let builder = builder.unwrap();
let fact = CStr::from_ptr(fact);
let s = fact.to_str();
if s.is_err() {
update_last_error(Error::InvalidArgument);
return false;
}
builder
.0
.add_fact(s.unwrap())
.map_err(|e| {
update_last_error(Error::Biscuit(e));
})
.is_ok()
}
#[no_mangle]
pub unsafe extern "C" fn block_builder_add_rule(
builder: Option<&mut BlockBuilder>,
rule: *const c_char,
) -> bool {
if builder.is_none() {
update_last_error(Error::InvalidArgument);
return false;
}
let builder = builder.unwrap();
let rule = CStr::from_ptr(rule);
let s = rule.to_str();
if s.is_err() {
update_last_error(Error::InvalidArgument);
return false;
}
builder
.0
.add_rule(s.unwrap())
.map_err(|e| {
update_last_error(Error::Biscuit(e));
})
.is_ok()
}
#[no_mangle]
pub unsafe extern "C" fn block_builder_add_check(
builder: Option<&mut BlockBuilder>,
check: *const c_char,
) -> bool {
if builder.is_none() {
update_last_error(Error::InvalidArgument);
return false;
}
let builder = builder.unwrap();
let check = CStr::from_ptr(check);
let s = check.to_str();
if s.is_err() {
update_last_error(Error::InvalidArgument);
return false;
}
builder
.0
.add_check(s.unwrap())
.map_err(|e| {
update_last_error(Error::Biscuit(e));
})
.is_ok()
}
#[no_mangle]
pub unsafe extern "C" fn block_builder_free(_builder: Option<Box<BlockBuilder>>) {}
#[no_mangle]
pub unsafe extern "C" fn authorizer_add_fact(
authorizer: Option<&mut Authorizer>,
fact: *const c_char,
) -> bool {
if authorizer.is_none() {
update_last_error(Error::InvalidArgument);
return false;
}
let authorizer = authorizer.unwrap();
let fact = CStr::from_ptr(fact);
let s = fact.to_str();
if s.is_err() {
update_last_error(Error::InvalidArgument);
return false;
}
authorizer
.0
.add_fact(s.unwrap())
.map_err(|e| {
update_last_error(Error::Biscuit(e));
})
.is_ok()
}
#[no_mangle]
pub unsafe extern "C" fn authorizer_add_rule(
authorizer: Option<&mut Authorizer>,
rule: *const c_char,
) -> bool {
if authorizer.is_none() {
update_last_error(Error::InvalidArgument);
return false;
}
let authorizer = authorizer.unwrap();
let rule = CStr::from_ptr(rule);
let s = rule.to_str();
if s.is_err() {
update_last_error(Error::InvalidArgument);
return false;
}
authorizer
.0
.add_rule(s.unwrap())
.map_err(|e| {
update_last_error(Error::Biscuit(e));
})
.is_ok()
}
#[no_mangle]
pub unsafe extern "C" fn authorizer_add_check(
authorizer: Option<&mut Authorizer>,
check: *const c_char,
) -> bool {
if authorizer.is_none() {
update_last_error(Error::InvalidArgument);
return false;
}
let authorizer = authorizer.unwrap();
let check = CStr::from_ptr(check);
let s = check.to_str();
if s.is_err() {
update_last_error(Error::InvalidArgument);
return false;
}
authorizer
.0
.add_check(s.unwrap())
.map_err(|e| {
update_last_error(Error::Biscuit(e));
})
.is_ok()
}
#[no_mangle]
pub unsafe extern "C" fn authorizer_authorize(authorizer: Option<&mut Authorizer>) -> bool {
if authorizer.is_none() {
update_last_error(Error::InvalidArgument);
return false;
}
let authorizer = authorizer.unwrap();
match authorizer.0.authorize() {
Ok(_index) => true,
Err(e) => {
update_last_error(Error::Biscuit(e));
false
}
}
}
#[no_mangle]
pub unsafe extern "C" fn authorizer_print(authorizer: Option<&mut Authorizer>) -> *mut c_char {
if authorizer.is_none() {
update_last_error(Error::InvalidArgument);
return std::ptr::null_mut();
}
let authorizer = authorizer.unwrap();
match CString::new(authorizer.0.print_world()) {
Ok(s) => s.into_raw(),
Err(_) => {
update_last_error(Error::InvalidArgument);
return std::ptr::null_mut();
}
}
}
#[no_mangle]
pub unsafe extern "C" fn authorizer_free(_authorizer: Option<Box<Authorizer>>) {}
#[no_mangle]
pub unsafe extern "C" fn string_free(ptr: *mut c_char) {
if ptr != std::ptr::null_mut() {
CString::from_raw(ptr);
}
}
#[no_mangle]
pub unsafe extern "C" fn biscuit_print(biscuit: Option<&Biscuit>) -> *const c_char {
if biscuit.is_none() {
update_last_error(Error::InvalidArgument);
return std::ptr::null();
}
let biscuit = biscuit.unwrap();
match CString::new(biscuit.0.print()) {
Ok(s) => s.into_raw(),
Err(_) => {
update_last_error(Error::InvalidArgument);
return std::ptr::null();
}
}
}
| key_pair_new |
mod.rs | //!
//! A multi-key style of `MapxRaw`.
//!
//! NOTE:
//! - Both keys and values will **NOT** be encoded in this structure
//!
#[cfg(test)]
mod test;
use crate::{
basic::mapx_raw::MapxRaw,
common::{ende::ValueEnDe, RawValue},
};
use ruc::*;
use serde::{Deserialize, Serialize};
use std::ops::{Deref, DerefMut};
#[derive(Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Debug)]
#[serde(bound = "")]
pub struct MapxRawMk {
// Will never be changed once created
key_size: usize,
// A nested map-structure, looks like:
// map { key => map { key => map { key => value } } }
inner: MapxRaw,
}
impl MapxRawMk {
/// # Panic
/// Will panic if `0 == key_size`.
#[inline(always)]
pub fn new(key_size: usize) -> Self {
assert!(0 < key_size);
Self {
key_size,
inner: MapxRaw::new(),
}
}
#[inline(always)]
pub fn get(&self, key: &[&[u8]]) -> Option<RawValue> {
if key.len() != self.key_size {
return None;
}
let mut hdr = self.inner;
for (idx, k) in key.iter().enumerate() {
if let Some(v) = hdr.get(k) {
if 1 + idx == self.key_size {
return Some(v);
} else {
hdr = pnk!(ValueEnDe::decode(&v));
}
} else {
return None;
}
}
None // empty key
}
#[inline(always)]
pub fn get_mut<'a>(&'a self, key: &'a [&'a [u8]]) -> Option<ValueMut<'a>> {
self.get(key).map(move |v| ValueMut::new(self, key, v))
}
#[inline(always)]
pub fn contains_key(&self, key: &[&[u8]]) -> bool {
self.get(key).is_some()
}
#[inline(always)]
pub fn is_empty(&self) -> bool {
self.inner.is_empty()
}
#[inline(always)]
pub fn entry_ref<'a>(&'a self, key: &'a [&'a [u8]]) -> Entry<'a> {
Entry { key, hdr: self }
}
#[inline(always)]
pub fn insert(&self, key: &[&[u8]], value: &[u8]) -> Result<Option<RawValue>> {
if key.len() != self.key_size {
return Err(eg!("Incorrect key size"));
}
let mut ret = None;
let mut hdr = self.inner;
for (idx, k) in key.iter().enumerate() {
if 1 + idx == self.key_size {
ret = hdr.insert(k, value);
break;
} else {
let mut new_hdr = None;
let f = || {
new_hdr.replace(MapxRaw::new());
new_hdr.as_ref().unwrap().encode()
};
let mutv = hdr.entry_ref(k).or_insert_ref_with(f);
let h = if let Some(h) = new_hdr {
h
} else {
pnk!(ValueEnDe::decode(mutv.as_ref()))
};
drop(mutv);
hdr = h;
}
}
Ok(ret)
}
/// Support batch removal.
#[inline(always)]
pub fn remove(&self, key: &[&[u8]]) -> Result<Option<RawValue>> {
// Support batch removal from key path.
if key.len() > self.key_size {
return Err(eg!("Incorrect key size"));
}
let mut hdr = self.inner;
for (idx, k) in key.iter().enumerate() {
if let Some(v) = hdr.get(k) {
// NOTE: use `key.len()` instead of `self.key_size`
if 1 + idx == key.len() {
let ret = hdr.remove(k);
// NOTE: use `self.key_size` instead of `key.len()`
if 1 + idx == self.key_size {
return Ok(ret);
} else {
return Ok(None);
}
} else {
hdr = pnk!(ValueEnDe::decode(&v));
}
} else {
return Ok(None);
}
}
Ok(None) // empty key
}
#[inline(always)]
pub fn clear(&self) {
self.inner.clear();
}
#[inline(always)]
pub fn iter_op<F>(&self, op: &mut F) -> Result<()>
where
F: FnMut(&[&[u8]], &[u8]) -> Result<()>,
{
self.iter_op_with_key_prefix(op, &[]).c(d!())
}
#[inline(always)]
pub fn iter_op_with_key_prefix<F>(
&self,
op: &mut F,
key_prefix: &[&[u8]],
) -> Result<()>
where
F: FnMut(&[&[u8]], &[u8]) -> Result<()>,
{
let mut key_buf = vec![Default::default(); self.key_size()];
let mut hdr = self.inner;
let mut depth = self.key_size();
if self.key_size() < key_prefix.len() {
return Err(eg!("Invalid key size"));
} else {
for (idx, k) in key_prefix.iter().enumerate() {
if let Some(v) = hdr.get(k) {
key_buf[idx] = k.to_vec().into_boxed_slice();
if 1 + idx == self.key_size {
let key = key_buf
.iter()
.map(|sub_k| sub_k.as_ref())
.collect::<Vec<_>>();
return op(key.as_slice(), &v).c(d!());
} else {
hdr = pnk!(ValueEnDe::decode(&v));
depth -= 1;
}
} else {
// key-prefix does not exist
return Ok(());
}
}
};
self.recursive_walk(hdr, &mut key_buf, depth, op).c(d!())
}
fn recursive_walk<F>(
&self,
hdr: MapxRaw,
key_buf: &mut [RawValue],
depth: usize,
op: &mut F,
) -> Result<()>
where
F: FnMut(&[&[u8]], &[u8]) -> Result<()>,
{
let idx = self.key_size() - depth;
if 1 == depth {
for (k, v) in hdr.iter() {
key_buf[idx] = k;
let key = key_buf
.iter()
.map(|sub_k| sub_k.as_ref())
.collect::<Vec<_>>();
op(key.as_slice(), &v[..]).c(d!())?;
}
} else {
for (k, v) in hdr.iter() {
key_buf[idx] = k;
let hdr = pnk!(ValueEnDe::decode(&v));
self.recursive_walk(hdr, key_buf, depth - 1, op).c(d!())?;
}
}
Ok(())
}
#[inline(always)]
pub(super) fn iter_op_typed_value<V, F>(&self, op: &mut F) -> Result<()>
where
F: FnMut(&[&[u8]], &V) -> Result<()>,
V: ValueEnDe,
{
self.iter_op_typed_value_with_key_prefix(op, &[]).c(d!())
}
#[inline(always)]
pub fn iter_op_typed_value_with_key_prefix<V, F>(
&self,
op: &mut F,
key_prefix: &[&[u8]],
) -> Result<()>
where
F: FnMut(&[&[u8]], &V) -> Result<()>,
V: ValueEnDe,
{
let mut key_buf = vec![Default::default(); self.key_size()];
let mut hdr = self.inner;
let mut depth = self.key_size();
if self.key_size() < key_prefix.len() {
return Err(eg!("Invalid key size"));
} else {
for (idx, k) in key_prefix.iter().enumerate() {
if let Some(v) = hdr.get(k) {
key_buf[idx] = k.to_vec().into_boxed_slice();
if 1 + idx == self.key_size {
let key = key_buf
.iter()
.map(|sub_k| sub_k.as_ref())
.collect::<Vec<_>>();
return op(key.as_slice(), &pnk!(ValueEnDe::decode(&v))).c(d!());
} else {
hdr = pnk!(ValueEnDe::decode(&v));
depth -= 1;
}
} else {
// key-prefix does not exist
return Ok(());
}
}
};
| .c(d!())
}
fn recursive_walk_typed_value<V, F>(
&self,
hdr: MapxRaw,
key_buf: &mut [RawValue],
depth: usize,
op: &mut F,
) -> Result<()>
where
F: FnMut(&[&[u8]], &V) -> Result<()>,
V: ValueEnDe,
{
let idx = self.key_size() - depth;
if 1 == depth {
for (k, v) in hdr.iter() {
key_buf[idx] = k;
let key = key_buf
.iter()
.map(|sub_k| sub_k.as_ref())
.collect::<Vec<_>>();
op(key.as_slice(), &pnk!(ValueEnDe::decode(&v))).c(d!())?;
}
} else {
for (k, v) in hdr.iter() {
key_buf[idx] = k;
let hdr = pnk!(ValueEnDe::decode(&v));
self.recursive_walk_typed_value(hdr, key_buf, depth - 1, op)
.c(d!())?;
}
}
Ok(())
}
#[inline(always)]
pub fn key_size(&self) -> usize {
self.key_size
}
}
#[derive(PartialEq, Eq, Debug)]
pub struct ValueMut<'a> {
hdr: &'a MapxRawMk,
key: &'a [&'a [u8]],
value: RawValue,
}
impl<'a> ValueMut<'a> {
fn new(hdr: &'a MapxRawMk, key: &'a [&'a [u8]], value: RawValue) -> Self {
ValueMut { hdr, key, value }
}
}
impl<'a> Drop for ValueMut<'a> {
fn drop(&mut self) {
pnk!(self.hdr.insert(self.key, &self.value));
}
}
impl<'a> Deref for ValueMut<'a> {
type Target = RawValue;
fn deref(&self) -> &Self::Target {
&self.value
}
}
impl<'a> DerefMut for ValueMut<'a> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.value
}
}
pub struct Entry<'a> {
key: &'a [&'a [u8]],
hdr: &'a MapxRawMk,
}
impl<'a> Entry<'a> {
pub fn or_insert_ref(self, default: &'a [u8]) -> Result<ValueMut<'a>> {
if !self.hdr.contains_key(self.key) {
self.hdr.insert(self.key, default).c(d!())?;
}
self.hdr.get_mut(self.key).c(d!())
}
} | self.recursive_walk_typed_value(hdr, &mut key_buf, depth, op) |
dbw_node.py | #!/usr/bin/env python
import rospy
from std_msgs.msg import Bool
from dbw_mkz_msgs.msg import ThrottleCmd, SteeringCmd, BrakeCmd, SteeringReport
from geometry_msgs.msg import TwistStamped
import math
from twist_controller import Controller
'''
You can build this node only after you have built (or partially built) the `waypoint_updater` node.
You will subscribe to `/twist_cmd` message which provides the proposed linear and angular velocities.
You can subscribe to any other message that you find important or refer to the document for list
of messages subscribed to by the reference implementation of this node.
One thing to keep in mind while building this node and the `twist_controller` class is the status
of `dbw_enabled`. While in the simulator, its enabled all the time, in the real car, that will
not be the case. This may cause your PID controller to accumulate error because the car could
temporarily be driven by a human instead of your controller.
We have provided two launch files with this node. Vehicle specific values (like vehicle_mass,
wheel_base) etc should not be altered in these files.
We have also provided some reference implementations for PID controller and other utility classes.
You are free to use them or build your own.
Once you have the proposed throttle, brake, and steer values, publish it on the various publishers
that we have created in the `__init__` function.
'''
class | (object):
def __init__(self):
rospy.init_node('dbw_node')
vehicle_mass = rospy.get_param('~vehicle_mass', 1736.35)
fuel_capacity = rospy.get_param('~fuel_capacity', 13.5)
brake_deadband = rospy.get_param('~brake_deadband', .1)
decel_limit = rospy.get_param('~decel_limit', -5)
accel_limit = rospy.get_param('~accel_limit', 1.)
wheel_radius = rospy.get_param('~wheel_radius', 0.2413)
wheel_base = rospy.get_param('~wheel_base', 2.8498)
steer_ratio = rospy.get_param('~steer_ratio', 14.8)
max_lat_accel = rospy.get_param('~max_lat_accel', 3.)
max_steer_angle = rospy.get_param('~max_steer_angle', 8.)
self.steer_pub = rospy.Publisher('/vehicle/steering_cmd',
SteeringCmd, queue_size=1)
self.throttle_pub = rospy.Publisher('/vehicle/throttle_cmd',
ThrottleCmd, queue_size=1)
self.brake_pub = rospy.Publisher('/vehicle/brake_cmd',
BrakeCmd, queue_size=1)
# TODO: Create `Controller` object
self.controller = Controller(vehicle_mass=vehicle_mass,
fuel_capacity=fuel_capacity,
brake_deadband=brake_deadband,
decel_limit=decel_limit,
accel_limit=accel_limit,
wheel_radius=wheel_radius,
wheel_base=wheel_base,
steer_ratio=steer_ratio,
max_lat_accel=max_lat_accel,
max_steer_angle=max_steer_angle)
# TODO: Subscribe to all the topics you need to
rospy.Subscriber('/vehicle/dbw_enabled', Bool, self.dbw_enabled_cb)
rospy.Subscriber('/twist_cmd', TwistStamped, self.twist_cb)
rospy.Subscriber('/current_velocity', TwistStamped, self.velocity_cb)
self.current_vel = None
self.curr_ang_vel = None
self.dbw_enabled = None
self.linear_vel = None
self.angular_vel = None
self.throttle = self.steering = self.brake = 0
self.loop()
def loop(self):
rate = rospy.Rate(50) # 50Hz
while not rospy.is_shutdown():
# TODO: Get predicted throttle, brake, and steering using `twist_controller`
# You should only publish the control commands if dbw is enabled
if not None in (self.current_vel, self.linear_vel, self.angular_vel):
self.throttle, self.brake, self.steering = self.controller.control(self.current_vel,
self.dbw_enabled,
self.linear_vel,
self.angular_vel)
if self.dbw_enabled:
self.publish(self.throttle, self.brake, self.steering)
rate.sleep()
def dbw_enabled_cb(self, msg):
self.dbw_enabled = msg
def twist_cb(self, msg):
self.linear_vel = msg.twist.linear.x
self.angular_vel = msg.twist.angular.z
def velocity_cb(self, msg):
self.current_vel = msg.twist.linear.x
def publish(self, throttle, brake, steer):
tcmd = ThrottleCmd()
tcmd.enable = True
tcmd.pedal_cmd_type = ThrottleCmd.CMD_PERCENT
tcmd.pedal_cmd = throttle
self.throttle_pub.publish(tcmd)
scmd = SteeringCmd()
scmd.enable = True
scmd.steering_wheel_angle_cmd = steer
self.steer_pub.publish(scmd)
bcmd = BrakeCmd()
bcmd.enable = True
bcmd.pedal_cmd_type = BrakeCmd.CMD_TORQUE
bcmd.pedal_cmd = brake
self.brake_pub.publish(bcmd)
if __name__ == '__main__':
DBWNode()
| DBWNode |
get-subdomain.js | import isEmpty from "lodash.isempty"
import isNil from "lodash.isnil"
export const isAllowedSubdomain = (subdomain = "www", subdomains = {}) => {
return Object.values(subdomains).includes(subdomain) |
export const getSubdomain = (
url = "",
subdomains = {},
defaultSub = "rentspree"
) => {
if (isNil(url) || isEmpty(url)) return "rentspree"
const fullPath = url.replace(/http[s]?:\/\//, "")
let subdomain = fullPath.slice(0, fullPath.indexOf("."))
subdomain = isNil(subdomain) || isEmpty(subdomain) ? defaultSub : subdomain
if (!isEmpty(subdomains)) {
return isAllowedSubdomain(subdomain, subdomains) ? subdomain : defaultSub
}
return subdomain
} | } |
logging.py | """
Created on 20 Jan 2021
@author: Bruno Beloff ([email protected])
https://realpython.com/python-logging/
"""
import logging
import sys
# --------------------------------------------------------------------------------------------------------------------
# noinspection PyPep8Naming
class Logging(object):
"""
classdocs
"""
__NAME = None
__MULTI_FORMAT = '%(name)s: %(message)s'
# ----------------------------------------------------------------------------------------------------------------
@classmethod
def config(cls, name, verbose=False, level=logging.ERROR, stream=sys.stderr):
cls.__NAME = name
level = logging.INFO if verbose else level
logging.basicConfig(format=cls.__MULTI_FORMAT, level=level, stream=stream)
@classmethod
def | (cls, name=None):
logger_name = cls.__NAME if cls.__NAME else name
return logging.getLogger(logger_name)
| getLogger |
TreeElementVisitor.d.ts | import Object = require('nashorn/java/lang/Object');
import LeafElement = require('nashorn/com/intellij/psi/impl/source/tree/LeafElement');
import CompositeElement = require('nashorn/com/intellij/psi/impl/source/tree/CompositeElement');
declare class | extends Object {
constructor();
visitLeaf(arg1 : LeafElement) : void;
visitComposite(arg1 : CompositeElement) : void;
}
export = TreeElementVisitor
| TreeElementVisitor |
connection.rs | use crate::discord::{
commands::{help::*, *},
handler,
shard::{PostgresPool, ShardManagerContainer},
};
use bb8_postgres::PostgresConnectionManager;
use postgres::NoTls;
use serenity::{client::Client, framework::standard::StandardFramework, model::id::UserId};
use std::{collections::HashSet, env, sync::Arc};
pub async fn setup(pool: &bb8::Pool<PostgresConnectionManager<NoTls>>) | {
let token: String = env::var("DISCORD_TOKEN").expect("Missing token env");
let mut owners = HashSet::new();
owners.insert(UserId(83281345949728768));
let framework = StandardFramework::new()
.configure(|c| {
c.owners(owners)
.prefix("!")
.ignore_bots(true)
.ignore_webhooks(true)
.allow_dm(false)
})
.help(&HELP)
.group(&ADMIN_GROUP);
let mut client: Client = Client::builder(&token)
.event_handler(handler::Handler)
.framework(framework)
.await
.expect("Error creating client");
{
let mut data = client.data.write().await;
data.insert::<ShardManagerContainer>(Arc::clone(&client.shard_manager));
data.insert::<PostgresPool>(pool.clone());
}
client
.start_autosharded()
.await
.expect("Failed to start autosharding.");
} |
|
private.rs | use super::Account;
use super::{Address, Metadata, Source};
use tcx_constants::CoinInfo;
use tcx_crypto::{Crypto, Pbkdf2Params};
use super::Error;
use super::Result;
use crate::keystore::Store;
use tcx_crypto::hash::dsha256;
use tcx_primitive::TypedPrivateKey;
use uuid::Uuid;
pub fn key_hash_from_private_key(data: &[u8]) -> String {
hex::encode(dsha256(data)[..20].to_vec())
}
pub struct PrivateKeystore {
store: Store,
private_key: Option<Vec<u8>>,
}
impl PrivateKeystore {
pub const VERSION: i64 = 11001i64;
pub(crate) fn store(&self) -> &Store {
&self.store
}
pub(crate) fn store_mut(&mut self) -> &mut Store {
&mut self.store
}
pub(crate) fn from_store(store: Store) -> Self {
PrivateKeystore {
store,
private_key: None,
}
}
pub(crate) fn unlock_by_password(&mut self, password: &str) -> Result<()> {
self.private_key = Some(self.decrypt_private_key(password)?);
Ok(())
}
pub(crate) fn | (&mut self) {
self.private_key = None;
}
pub(crate) fn is_locked(&self) -> bool {
self.private_key.is_none()
}
pub(crate) fn find_private_key(&self, address: &str) -> Result<TypedPrivateKey> {
tcx_ensure!(self.private_key.is_some(), Error::KeystoreLocked);
let account = self
.store
.active_accounts
.iter()
.find(|acc| acc.address == address)
.ok_or(Error::AccountNotFound)?;
let private_key = self.private_key.as_ref().unwrap().as_slice();
TypedPrivateKey::from_slice(account.curve, private_key)
}
pub(crate) fn derive_coin<A: Address>(&mut self, coin_info: &CoinInfo) -> Result<Account> {
tcx_ensure!(self.private_key.is_some(), Error::KeystoreLocked);
let sk = self.private_key.as_ref().unwrap();
let account = Self::private_key_to_account::<A>(coin_info, sk)?;
if let Some(_) = self
.store
.active_accounts
.iter()
.find(|x| x.address == account.address && x.coin == account.coin)
{
return Ok(account);
} else {
self.store.active_accounts.push(account.clone());
Ok(account)
}
}
/// Find an account by coin symbol
pub(crate) fn account(&self, symbol: &str, address: &str) -> Option<&Account> {
self.store
.active_accounts
.iter()
.find(|acc| acc.coin == symbol && acc.address == address)
}
pub(crate) fn verify_password(&self, password: &str) -> bool {
self.store.crypto.verify_password(password)
}
pub fn from_private_key(private_key: &str, password: &str, source: Source) -> PrivateKeystore {
let key_data: Vec<u8> = hex::decode(private_key).expect("hex can't decode");
let key_hash = key_hash_from_private_key(&key_data);
// let pk_bytes = hex::decode(private_key).expect("valid private_key");
let crypto: Crypto<Pbkdf2Params> = Crypto::new(password, &key_data);
let meta = Metadata {
source,
..Metadata::default()
};
let store = Store {
key_hash,
crypto,
meta,
id: Uuid::new_v4().to_hyphenated().to_string(),
version: PrivateKeystore::VERSION,
active_accounts: vec![],
};
PrivateKeystore {
store,
private_key: None,
}
}
pub(crate) fn private_key_to_account<A: Address>(
coin: &CoinInfo,
private_key: &[u8],
) -> Result<Account> {
let tsk = TypedPrivateKey::from_slice(coin.curve, private_key)?;
let addr = A::from_public_key(&tsk.public_key(), coin)?;
let acc = Account {
address: addr,
derivation_path: "".to_string(),
curve: coin.curve,
coin: coin.coin.to_owned(),
network: coin.network.to_string(),
seg_wit: coin.seg_wit.to_string(),
ext_pub_key: "".to_string(),
};
Ok(acc)
}
pub(crate) fn private_key(&self) -> Result<String> {
tcx_ensure!(self.private_key.is_some(), Error::KeystoreLocked);
let vec = self.private_key.as_ref().unwrap().to_vec();
Ok(hex::encode(&vec))
}
fn decrypt_private_key(&self, password: &str) -> Result<Vec<u8>> {
self.store.crypto.decrypt(password)
}
}
#[cfg(test)]
mod tests {
use crate::{PrivateKeystore, Source};
use tcx_constants::TEST_PASSWORD;
#[test]
pub fn from_private_key_test() {
let keystore = PrivateKeystore::from_private_key(
"a392604efc2fad9c0b3da43b5f698a2e3f270f170d859912be0d54742275c5f6",
TEST_PASSWORD,
Source::Private,
);
assert_eq!(keystore.store.version, 11001);
assert_ne!(keystore.store.id, "");
assert_eq!(keystore.store.active_accounts.len(), 0);
}
}
| lock |
test_nbconvertapp.py | # -*- coding: utf-8 -*-
"""Test NbConvertApp"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
import os
import io
import nbformat
from .base import TestsBase
from ..postprocessors import PostProcessorBase
from ..tests.utils import onlyif_cmds_exist
from nbconvert import nbconvertapp
from nbconvert.exporters import Exporter
from traitlets.tests.utils import check_help_all_output
from testpath import tempdir
import pytest
#-----------------------------------------------------------------------------
# Classes and functions
#-----------------------------------------------------------------------------
class DummyPost(PostProcessorBase):
def postprocess(self, filename):
print("Dummy:%s" % filename)
class TestNbConvertApp(TestsBase):
"""Collection of NbConvertApp tests"""
def test_notebook_help(self):
"""Will help show if no notebooks are specified?"""
with self.create_temp_cwd():
out, err = self.nbconvert('--log-level 0', ignore_return_code=True)
self.assertIn("--help-all", out)
def test_help_output(self):
"""ipython nbconvert --help-all works"""
check_help_all_output('nbconvert')
def test_glob(self):
"""
Do search patterns work for notebook names?
"""
with self.create_temp_cwd(['notebook*.ipynb']):
self.nbconvert('--to python *.ipynb --log-level 0')
assert os.path.isfile('notebook1.py')
assert os.path.isfile('notebook2.py')
def test_glob_subdir(self):
"""
Do search patterns work for subdirectory notebook names?
"""
with self.create_temp_cwd():
self.copy_files_to(['notebook*.ipynb'], 'subdir/')
self.nbconvert('--to python --log-level 0 ' +
os.path.join('subdir', '*.ipynb'))
assert os.path.isfile(os.path.join('subdir', 'notebook1.py'))
assert os.path.isfile(os.path.join('subdir', 'notebook2.py'))
def test_build_dir(self):
"""build_directory affects export location"""
with self.create_temp_cwd():
self.copy_files_to(['notebook*.ipynb'], 'subdir/')
self.nbconvert('--to python --log-level 0 --output-dir . ' +
os.path.join('subdir', '*.ipynb'))
assert os.path.isfile('notebook1.py')
assert os.path.isfile('notebook2.py')
def test_convert_full_qualified_name(self):
"""
Test that nbconvert can convert file using a full qualified name for a
package, import and use it.
"""
with self.create_temp_cwd():
self.copy_files_to(['notebook*.ipynb'], 'subdir')
self.nbconvert('--to nbconvert.tests.fake_exporters.MyExporter --log-level 0 ' +
os.path.join('subdir', '*.ipynb'))
assert os.path.isfile(os.path.join('subdir', 'notebook1.test_ext'))
assert os.path.isfile(os.path.join('subdir', 'notebook2.test_ext'))
def test_explicit(self):
"""
Do explicit notebook names work?
"""
with self.create_temp_cwd(['notebook*.ipynb']):
self.nbconvert('--log-level 0 --to python notebook2')
assert not os.path.isfile('notebook1.py')
assert os.path.isfile('notebook2.py')
def test_clear_output(self):
"""
Can we clear outputs?
"""
with self.create_temp_cwd(['notebook*.ipynb']) as td:
self.nbconvert('--clear-output notebook1')
assert os.path.isfile('notebook1.ipynb')
with open('notebook1.ipynb', encoding='utf8') as f:
nb = nbformat.read(f, 4)
for cell in nb.cells:
# Skip markdown cells
if 'outputs' in cell:
assert cell.outputs == []
def test_absolute_template_file(self):
"""--template-file '/path/to/template.tpl'"""
with self.create_temp_cwd(['notebook*.ipynb']), tempdir.TemporaryDirectory() as td:
template = os.path.join(td, 'mytemplate.tpl')
test_output = 'success!'
with open(template, 'w') as f:
f.write(test_output)
self.nbconvert('--log-level 0 notebook2 --to html --template-file %s' % template)
assert os.path.isfile('notebook2.html')
with open('notebook2.html') as f:
text = f.read()
assert text == test_output
def test_relative_template_file(self):
"""Test --template-file 'relative/path.tpl'"""
with self.create_temp_cwd(['notebook*.ipynb']):
os.mkdir('relative')
template = os.path.join('relative', 'path.tpl')
test_output = 'success!'
with open(template, 'w') as f:
f.write(test_output)
self.nbconvert('--log-level 0 notebook2 --to html --template-file %s' % template)
assert os.path.isfile('notebook2.html')
with open('notebook2.html') as f:
text = f.read()
assert text == test_output
@onlyif_cmds_exist('pandoc', 'xelatex')
def test_filename_spaces(self):
"""
Generate PDFs with graphics if notebooks have spaces in the name?
"""
with self.create_temp_cwd(['notebook2.ipynb']):
os.rename('notebook2.ipynb', 'notebook with spaces.ipynb')
self.nbconvert('--log-level 0 --to pdf'
' "notebook with spaces"'
' --PDFExporter.latex_count=1'
' --PDFExporter.verbose=True'
)
assert os.path.isfile('notebook with spaces.pdf')
@pytest.mark.network
def test_webpdf_with_chromium(self):
"""
Generate PDFs if chromium allowed to be downloaded?
"""
with self.create_temp_cwd(['notebook2.ipynb']):
self.nbconvert('--to webpdf '
'--allow-chromium-download '
'"notebook2"'
)
assert os.path.isfile('notebook2.pdf')
@onlyif_cmds_exist('pandoc', 'xelatex')
def test_pdf(self):
"""
Check to see if pdfs compile, even if strikethroughs are included.
"""
with self.create_temp_cwd(['notebook2.ipynb']):
self.nbconvert('--log-level 0 --to pdf'
' "notebook2"'
' --PDFExporter.latex_count=1'
' --PDFExporter.verbose=True'
)
assert os.path.isfile('notebook2.pdf')
def test_post_processor(self):
"""Do post processors work?"""
with self.create_temp_cwd(['notebook1.ipynb']):
out, err = self.nbconvert('--log-level 0 --to python notebook1 '
'--post nbconvert.tests.test_nbconvertapp.DummyPost')
self.assertIn('Dummy:notebook1.py', out)
@onlyif_cmds_exist('pandoc')
def test_spurious_cr(self):
"""Check for extra CR characters"""
with self.create_temp_cwd(['notebook2.ipynb']):
self.nbconvert('--log-level 0 --to latex notebook2')
assert os.path.isfile('notebook2.tex')
with open('notebook2.tex') as f:
tex = f.read()
self.nbconvert('--log-level 0 --to html notebook2')
assert os.path.isfile('notebook2.html')
with open('notebook2.html') as f:
html = f.read()
self.assertEqual(tex.count('\r'), tex.count('\r\n'))
self.assertEqual(html.count('\r'), html.count('\r\n'))
@onlyif_cmds_exist('pandoc')
def test_png_base64_html_ok(self):
"""Is embedded png data well formed in HTML?"""
with self.create_temp_cwd(['notebook2.ipynb']):
self.nbconvert('--log-level 0 --to HTML '
'notebook2.ipynb --template lab')
assert os.path.isfile('notebook2.html')
with open('notebook2.html') as f:
assert "data:image/png;base64,b'" not in f.read()
@onlyif_cmds_exist('pandoc')
def test_template(self):
"""
Do export templates work?
"""
with self.create_temp_cwd(['notebook2.ipynb']):
self.nbconvert('--log-level 0 --to slides '
'notebook2.ipynb')
assert os.path.isfile('notebook2.slides.html')
with open('notebook2.slides.html') as f:
assert '/reveal.css' in f.read()
def test_output_ext(self):
"""test --output=outputfile[.ext]"""
with self.create_temp_cwd(['notebook1.ipynb']):
self.nbconvert('--log-level 0 --to python '
'notebook1.ipynb --output nb.py')
assert os.path.exists('nb.py')
self.nbconvert('--log-level 0 --to python '
'notebook1.ipynb --output nb2')
assert os.path.exists('nb2.py')
def test_glob_explicit(self):
"""
Can a search pattern be used along with matching explicit notebook names?
"""
with self.create_temp_cwd(['notebook*.ipynb']):
self.nbconvert('--log-level 0 --to python '
'*.ipynb notebook1.ipynb notebook2.ipynb')
assert os.path.isfile('notebook1.py')
assert os.path.isfile('notebook2.py')
def test_explicit_glob(self):
"""
Can explicit notebook names be used and then a matching search pattern?
"""
with self.create_temp_cwd(['notebook*.ipynb']):
self.nbconvert('--log-level 0 --to=python '
'notebook1.ipynb notebook2.ipynb *.ipynb')
assert os.path.isfile('notebook1.py')
assert os.path.isfile('notebook2.py')
def test_default_config(self):
"""
Does the default config work?
"""
with self.create_temp_cwd(['notebook*.ipynb', 'jupyter_nbconvert_config.py']):
self.nbconvert('--log-level 0')
assert os.path.isfile('notebook1.py')
assert not os.path.isfile('notebook2.py')
def test_override_config(self):
"""
Can the default config be overridden?
"""
with self.create_temp_cwd(['notebook*.ipynb',
'jupyter_nbconvert_config.py',
'override.py']):
self.nbconvert('--log-level 0 --config="override.py"')
assert not os.path.isfile('notebook1.py')
assert os.path.isfile('notebook2.py')
def test_accents_in_filename(self):
"""
Can notebook names include accents?
"""
with self.create_temp_cwd():
self.create_empty_notebook(u'nb1_análisis.ipynb')
self.nbconvert('--log-level 0 --to Python nb1_*')
assert os.path.isfile(u'nb1_análisis.py')
@onlyif_cmds_exist('xelatex', 'pandoc')
def test_filename_accent_pdf(self):
"""
Generate PDFs if notebooks have an accent in their name?
"""
with self.create_temp_cwd():
self.create_empty_notebook(u'nb1_análisis.ipynb')
self.nbconvert('--log-level 0 --to pdf "nb1_*"'
' --PDFExporter.latex_count=1'
' --PDFExporter.verbose=True')
assert os.path.isfile(u'nb1_análisis.pdf')
def test_cwd_plugin(self):
"""
Verify that an extension in the cwd can be imported.
"""
with self.create_temp_cwd(['hello.py']):
self.create_empty_notebook(u'empty.ipynb')
self.nbconvert('empty --to html --NbConvertApp.writer_class=\'hello.HelloWriter\'')
assert os.path.isfile(u'hello.txt')
def test_output_suffix(self):
"""
Verify that the output suffix is applied
"""
with self.create_temp_cwd():
self.create_empty_notebook('empty.ipynb')
self.nbconvert('empty.ipynb --to notebook')
assert os.path.isfile('empty.nbconvert.ipynb')
def test_different_build_dir(self):
"""
Verify that the output suffix is not applied
"""
with self.create_temp_cwd():
self.create_empty_notebook('empty.ipynb')
os.mkdir('output')
self.nbconvert(
'empty.ipynb --to notebook '
'--FilesWriter.build_directory=output')
assert os.path.isfile('output/empty.ipynb')
def test_inplace(self):
"""
Verify that the notebook is converted in place
"""
with self.create_temp_cwd():
self.create_empty_notebook('empty.ipynb')
self.nbconvert('empty.ipynb --inplace')
assert os.path.isfile('empty.ipynb')
assert not os.path.isfile('empty.nbconvert.ipynb')
assert not os.path.isfile('empty.html')
def test_no_prompt(self):
"""
Verify that the html has no prompts when given --no-prompt.
"""
with self.create_temp_cwd(["notebook1.ipynb"]):
self.nbconvert('notebook1.ipynb --log-level 0 --no-prompt --to html')
assert os.path.isfile('notebook1.html')
with open("notebook1.html",'r') as f:
text = f.read()
assert "In [" not in text
assert "Out[6]" not in text
self.nbconvert('notebook1.ipynb --log-level 0 --to html')
assert os.path.isfile('notebook1.html')
with open("notebook1.html",'r') as f:
text2 = f.read()
assert "In [" in text2
assert "Out[6]" in text2
def test_cell_tag_output(self):
"""
| def test_no_input(self):
"""
Verify that the html has no input when given --no-input.
"""
with self.create_temp_cwd(["notebook1.ipynb"]):
self.nbconvert('notebook1.ipynb --log-level 0 --no-input --to html')
assert os.path.isfile('notebook1.html')
with open("notebook1.html",'r') as f:
text = f.read()
assert "In [" not in text
assert "Out[6]" not in text
assert ('<span class="n">x</span>'
'<span class="p">,</span>'
'<span class="n">y</span>'
'<span class="p">,</span>'
'<span class="n">z</span> '
'<span class="o">=</span> '
'<span class="n">symbols</span>'
'<span class="p">(</span>'
'<span class="s1">'x y z'</span>'
'<span class="p">)</span>') not in text
self.nbconvert('notebook1.ipynb --log-level 0 --to html')
assert os.path.isfile('notebook1.html')
with open("notebook1.html",'r') as f:
text2 = f.read()
assert "In [" in text2
assert "Out[6]" in text2
assert ('<span class="n">x</span>'
'<span class="p">,</span>'
'<span class="n">y</span>'
'<span class="p">,</span>'
'<span class="n">z</span> '
'<span class="o">=</span> '
'<span class="n">symbols</span>'
'<span class="p">(</span>'
'<span class="s1">'x y z'</span>'
'<span class="p">)</span>') in text2
def test_allow_errors(self):
"""
Verify that conversion is aborted with '--execute' if an error is
encountered, but that conversion continues if '--allow-errors' is
used in addition.
"""
with self.create_temp_cwd(['notebook3*.ipynb']):
# Convert notebook containing a cell that raises an error,
# both without and with cell execution enabled.
output1, _ = self.nbconvert('--to markdown --stdout notebook3*.ipynb') # no cell execution
output2, _ = self.nbconvert('--to markdown --allow-errors --stdout notebook3*.ipynb') # no cell execution; --allow-errors should have no effect
output3, _ = self.nbconvert('--execute --allow-errors --to markdown --stdout notebook3*.ipynb') # with cell execution; errors are allowed
# Un-executed outputs should not contain either
# of the two numbers computed in the notebook.
assert '23' not in output1
assert '42' not in output1
assert '23' not in output2
assert '42' not in output2
# Executed output should contain both numbers.
assert '23' in output3
assert '42' in output3
# Executing the notebook should raise an exception if --allow-errors is not specified
with pytest.raises(OSError):
self.nbconvert('--execute --to markdown --stdout notebook3*.ipynb')
def test_errors_print_traceback(self):
"""
Verify that the stderr output contains the traceback of the cell execution exception.
"""
with self.create_temp_cwd(['notebook3_with_errors.ipynb']):
_, error_output = self.nbconvert('--execute --to markdown --stdout notebook3_with_errors.ipynb',
ignore_return_code=True)
assert 'print("Some text before the error")' in error_output
assert 'raise RuntimeError("This is a deliberate exception")' in error_output
assert 'RuntimeError: This is a deliberate exception' in error_output
def test_fenced_code_blocks_markdown(self):
"""
Verify that input cells use fenced code blocks with the language
name in nb.metadata.kernelspec.language, if that exists
"""
with self.create_temp_cwd(["notebook1*.ipynb"]):
# this notebook doesn't have nb.metadata.kernelspec, so it should
# just do a fenced code block, with no language
output1, _ = self.nbconvert('--to markdown --stdout notebook1.ipynb')
assert '```python' not in output1 # shouldn't have language
assert "```" in output1 # but should have fenced blocks
with self.create_temp_cwd(["notebook_jl*.ipynb"]):
output2, _ = self.nbconvert('--to markdown --stdout notebook_jl.ipynb')
assert '```julia' in output2 # shouldn't have language
assert "```" in output2 # but should also plain ``` to close cell
def test_convert_from_stdin_to_stdout(self):
"""
Verify that conversion can be done via stdin to stdout
"""
with self.create_temp_cwd(["notebook1.ipynb"]):
with io.open('notebook1.ipynb') as f:
notebook = f.read().encode()
output1, _ = self.nbconvert('--to markdown --stdin --stdout', stdin=notebook)
assert '```python' not in output1 # shouldn't have language
assert "```" in output1 # but should have fenced blocks
def test_convert_from_stdin(self):
"""
Verify that conversion can be done via stdin.
"""
with self.create_temp_cwd(["notebook1.ipynb"]):
with io.open('notebook1.ipynb') as f:
notebook = f.read().encode()
self.nbconvert('--to markdown --stdin', stdin=notebook)
assert os.path.isfile("notebook.md") # default name for stdin input
with io.open('notebook.md') as f:
output1 = f.read()
assert '```python' not in output1 # shouldn't have language
assert "```" in output1 # but should have fenced blocks
@onlyif_cmds_exist('pandoc', 'xelatex')
def test_linked_images(self):
"""
Generate PDFs with an image linked in a markdown cell
"""
with self.create_temp_cwd(['latex-linked-image.ipynb', 'testimage.png']):
self.nbconvert('--to pdf latex-linked-image.ipynb')
assert os.path.isfile('latex-linked-image.pdf')
@onlyif_cmds_exist('pandoc')
def test_embedded_jpeg(self):
"""
Verify that latex conversion succeeds
with a notebook with an embedded .jpeg
"""
with self.create_temp_cwd(['notebook4_jpeg.ipynb',
'containerized_deployments.jpeg']):
self.nbconvert('--to latex notebook4_jpeg.ipynb')
assert os.path.isfile('notebook4_jpeg.tex')
@onlyif_cmds_exist('pandoc')
def test_markdown_display_priority(self):
"""
Check to see if markdown conversion embeds PNGs,
even if an (unsupported) PDF is present.
"""
with self.create_temp_cwd(['markdown_display_priority.ipynb']):
self.nbconvert('--log-level 0 --to markdown '
'"markdown_display_priority.ipynb"')
assert os.path.isfile('markdown_display_priority.md')
with io.open('markdown_display_priority.md') as f:
markdown_output = f.read()
assert ("markdown_display_priority_files/"
"markdown_display_priority_0_1.png") in markdown_output
@onlyif_cmds_exist('pandoc')
def test_write_figures_to_custom_path(self):
"""
Check if figure files are copied to configured path.
"""
def fig_exists(path):
return (len(os.listdir(path)) > 0)
# check absolute path
with self.create_temp_cwd(['notebook4_jpeg.ipynb',
'containerized_deployments.jpeg']):
output_dir = tempdir.TemporaryDirectory()
path = os.path.join(output_dir.name, 'files')
self.nbconvert(
'--log-level 0 notebook4_jpeg.ipynb --to rst '
'--NbConvertApp.output_files_dir={}'
.format(path))
assert fig_exists(path)
output_dir.cleanup()
# check relative path
with self.create_temp_cwd(['notebook4_jpeg.ipynb',
'containerized_deployments.jpeg']):
self.nbconvert(
'--log-level 0 notebook4_jpeg.ipynb --to rst '
'--NbConvertApp.output_files_dir=output')
assert fig_exists('output')
# check default path with notebook name
with self.create_temp_cwd(['notebook4_jpeg.ipynb',
'containerized_deployments.jpeg']):
self.nbconvert(
'--log-level 0 notebook4_jpeg.ipynb --to rst')
assert fig_exists('notebook4_jpeg_files')
| Verify that the html has tags in cell attributes if they exist.
"""
with self.create_temp_cwd(["notebook_tags.ipynb"]):
self.nbconvert('notebook_tags.ipynb --log-level 0 --to html')
assert os.path.isfile('notebook_tags.html')
with open("notebook_tags.html",'r') as f:
text = f.read()
assert 'celltag_mycelltag celltag_mysecondcelltag' in text
assert 'celltag_mymarkdowncelltag' in text
|
_menu.py | from PyInquirer import prompt, Separator
# The menus displays a list of checkboxes, which allows the user to select the separators and modules he wants to use
def | (self):
# Get a list of all existing separators
separators = self.config["separators"]
separators_menu = [
{
'type': 'checkbox',
'qmark': '⚙️ ',
'message': 'Select separators',
'name': 'separators',
'choices': []
}
]
for separator, value in separators.items():
# Separator title
separators_menu[0]["choices"].append(Separator("{} - Exemple : john{}doe".format(separator, value)))
# Separator
separators_menu[0]["choices"].append({"name": value})
self.separators = prompt(separators_menu)["separators"]
def services_menu(self):
# Get a list of all enabled modules
modules_list = sorted([module for module in self.config["plateform"] if self.config["plateform"][module]["enabled"] == "yes"])
# Create a list of all existing categories
categories = sorted(list(set([content["type"] for module, content in self.config["plateform"].items() if module in modules_list])))
services_menu = [
{
'type': 'checkbox',
'qmark': '⚙️ ',
'message': 'Select services',
'name': 'modules',
'choices': [
],
'validate': lambda answer: 'You must choose at least one service !' \
if len(answer) == 0 else True
}
]
for category in categories:
# Category title
services_menu[0]["choices"].append(Separator(category.upper()))
# Append category items
for module in modules_list:
if self.config["plateform"][module]["type"] == category:
services_menu[0]["choices"].append(
{
'name': module,
# Checked by default
'checked': module in self.config["report_elements"]
})
modules = prompt(services_menu)["modules"]
self.modules_update(modules) | separators_menu |
App.test.js | import React from 'react';
import {
createShallowRenderer,
id,
type,
childrenOf
} from './shallowHelpers';
import { App } from '../src/App';
import { MenuButtons } from '../src/MenuButtons';
import { StatementHistory } from '../src/StatementHistory';
import { ScriptName } from '../src/ScriptName';
import { Drawing } from '../src/Drawing';
import { Prompt } from '../src/Prompt';
import { PromptError } from '../src/PromptError';
describe('App', () => {
let render, elementMatching;
let output;
beforeEach(() => {
({ render, elementMatching } = createShallowRenderer());
render(<App />);
});
const table = () => elementMatching(type('table'));
it('renders a ScriptName component as the first item in the menu', () => {
expect(
childrenOf(elementMatching(id('menu')))[0].type
).toEqual(ScriptName);
});
| ).toEqual(MenuButtons);
});
it('renders a Display component in div#drawing', () => {
expect(
childrenOf(elementMatching(id('drawing'))).map(c => c.type)
).toContain(Drawing);
});
it('renders a table in div#commands', () => {
expect(
childrenOf(elementMatching(id('commands'))).map(c => c.type)
).toContain('table');
});
it('renders a StatementHistory component as the first item in the table', () => {
expect(childrenOf(table())[0].type).toEqual(StatementHistory);
});
it('renders a Prompt component as the second item in the table', () => {
expect(childrenOf(table())[1].type).toEqual(Prompt);
});
it('renders a PromptError component as the third item in the table', () => {
expect(childrenOf(table())[2].type).toEqual(PromptError);
});
}); | it('renders a MenuButtons component as the second items in the menu', () => {
expect(
childrenOf(elementMatching(id('menu')))[1].type |
ut_metadata.rs | use crate::ControlMessage;
use bip_handshake::InfoHash;
use bip_metainfo::Info;
use bip_metainfo::Metainfo;
use bip_peer::PeerInfo;
use bip_peer::messages::{ExtendedMessage, ExtendedType};
use bip_peer::messages::UtMetadataDataMessage;
use bip_peer::messages::UtMetadataMessage;
use bip_peer::messages::UtMetadataRejectMessage;
use bip_peer::messages::UtMetadataRequestMessage;
use bip_peer::messages::builders::ExtendedMessageBuilder;
use bytes::BytesMut;
use crate::discovery::IDiscoveryMessage;
use crate::discovery::ODiscoveryMessage;
use crate::discovery::error::{DiscoveryError, DiscoveryErrorKind};
use crate::extended::ExtendedListener;
use crate::extended::ExtendedPeerInfo;
use futures::Async;
use futures::AsyncSink;
use futures::Poll;
use futures::Sink;
use futures::StartSend;
use futures::Stream;
use futures::task;
use futures::task::Task;
use rand::{self, Rng};
use std::collections::HashMap;
use std::collections::HashSet;
use std::collections::VecDeque;
use std::collections::hash_map::Entry;
use std::io::Write;
use std::time::Duration;
const REQUEST_TIMEOUT_MILLIS: u64 = 2000;
const MAX_REQUEST_SIZE: usize = 16 * 1024;
const MAX_ACTIVE_REQUESTS: usize = 100;
const MAX_PEER_REQUESTS: usize = 100;
struct PendingInfo {
messages: Vec<UtMetadataRequestMessage>,
left: usize,
bytes: Vec<u8>,
}
struct ActiveRequest {
left: Duration,
message: UtMetadataRequestMessage,
sent_to: PeerInfo,
}
struct PeerRequest {
send_to: PeerInfo,
request: UtMetadataRequestMessage,
}
struct ActivePeers {
peers: HashSet<PeerInfo>,
metadata_size: i64,
}
/// Module for sending/receiving metadata from other peers.
///
/// If you are using this module, you should make sure to handshake
/// peers with `Extension::ExtensionProtocol` active. Failure to do
/// this will result in this module not sending any messages.
///
/// Metadata will be retrieved when `IDiscoveryMessage::DownloadMetadata`
/// is received, and will be served when
/// `IDiscoveryMessage::Control(ControlMessage::AddTorrent)` is received.
pub struct UtMetadataModule {
completed_map: HashMap<InfoHash, Vec<u8>>,
pending_map: HashMap<InfoHash, Option<PendingInfo>>,
active_peers: HashMap<InfoHash, ActivePeers>,
active_requests: Vec<ActiveRequest>,
peer_requests: VecDeque<PeerRequest>,
opt_sink: Option<Task>,
opt_stream: Option<Task>,
}
impl UtMetadataModule {
/// Create a new `UtMetadataModule`.
pub fn new() -> UtMetadataModule {
UtMetadataModule {
completed_map: HashMap::new(),
pending_map: HashMap::new(),
active_peers: HashMap::new(),
active_requests: Vec::new(),
peer_requests: VecDeque::new(),
opt_sink: None,
opt_stream: None,
}
}
fn add_torrent(&mut self, metainfo: Metainfo) -> StartSend<IDiscoveryMessage, DiscoveryError> {
let info_hash = metainfo.info().info_hash();
match self.completed_map.entry(info_hash) {
Entry::Occupied(_) => {
Err(DiscoveryError::from_kind(DiscoveryErrorKind::InvalidMetainfoExists { hash: info_hash }))
},
Entry::Vacant(vac) => {
let info_bytes = metainfo.info().to_bytes();
vac.insert(info_bytes);
Ok(AsyncSink::Ready)
},
}
}
fn remove_torrent(&mut self, metainfo: Metainfo) -> StartSend<IDiscoveryMessage, DiscoveryError> {
if self.completed_map
.remove(&metainfo.info().info_hash())
.is_none()
{
Err(DiscoveryError::from_kind(DiscoveryErrorKind::InvalidMetainfoNotExists {
hash: metainfo.info().info_hash(),
}))
} else {
Ok(AsyncSink::Ready)
}
}
fn add_peer(&mut self, info: PeerInfo, ext_info: &ExtendedPeerInfo) -> StartSend<IDiscoveryMessage, DiscoveryError> {
let our_support = ext_info
.our_message()
.and_then(|msg| msg.query_id(&ExtendedType::UtMetadata))
.is_some();
let they_support = ext_info
.their_message()
.and_then(|msg| msg.query_id(&ExtendedType::UtMetadata))
.is_some();
let opt_metadata_size = ext_info
.their_message()
.and_then(ExtendedMessage::metadata_size);
info!(
"Our Support For UtMetadata Is {:?} And {:?} Support For UtMetadata Is {:?} With Metdata Size {:?}",
our_support,
info.addr(),
they_support,
opt_metadata_size
);
// If peer supports it, but they dont have the metadata size, then they probably dont have the file yet...
match (our_support, they_support, opt_metadata_size) {
(true, true, Some(metadata_size)) => {
self.active_peers
.entry(*info.hash())
.or_insert_with(|| {
ActivePeers {
peers: HashSet::new(),
metadata_size,
}
})
.peers
.insert(info);
},
_ => {
},
}
Ok(AsyncSink::Ready)
}
fn remove_peer(&mut self, info: PeerInfo) -> StartSend<IDiscoveryMessage, DiscoveryError> {
let empty_peers = if let Some(active_peers) = self.active_peers.get_mut(info.hash()) {
active_peers.peers.remove(&info);
active_peers.peers.is_empty()
} else {
false
};
if empty_peers { |
Ok(AsyncSink::Ready)
}
fn apply_tick(&mut self, duration: Duration) -> StartSend<IDiscoveryMessage, DiscoveryError> {
let active_requests = &mut self.active_requests;
let active_peers = &mut self.active_peers;
let pending_map = &mut self.pending_map;
// Retain only the requests that arent expired
active_requests.retain(|request| {
let is_expired = request.left.checked_sub(duration).is_none();
if is_expired {
// Peer didnt respond to our request, remove from active peers
if let Some(active) = active_peers.get_mut(&request.sent_to.hash()) {
active.peers.remove(&request.sent_to);
}
// Push request back to pending
pending_map
.get_mut(&request.sent_to.hash())
.map(|opt_pending| {
opt_pending.as_mut().map(|pending| {
pending.messages.push(request.message);
})
});
}
!is_expired
});
// Go back through and subtract from the left over requests, they wont underflow
for active_request in active_requests.iter_mut() {
active_request.left -= duration;
}
Ok(AsyncSink::Ready)
}
fn download_metainfo(&mut self, hash: InfoHash) -> StartSend<IDiscoveryMessage, DiscoveryError> {
self.pending_map.entry(hash).or_insert(None);
Ok(AsyncSink::Ready)
}
fn recv_request(&mut self, info: PeerInfo, request: UtMetadataRequestMessage) -> StartSend<IDiscoveryMessage, DiscoveryError> {
if self.peer_requests.len() == MAX_PEER_REQUESTS {
Ok(AsyncSink::NotReady(
IDiscoveryMessage::ReceivedUtMetadataMessage(info, UtMetadataMessage::Request(request)),
))
} else {
self.peer_requests.push_back(PeerRequest {
send_to: info,
request,
});
Ok(AsyncSink::Ready)
}
}
fn recv_data(&mut self, info: PeerInfo, data: UtMetadataDataMessage) -> StartSend<IDiscoveryMessage, DiscoveryError> {
// See if we can find the request that we made to the peer for that piece
let opt_index = self.active_requests
.iter()
.position(|request| request.sent_to == info && request.message.piece() == data.piece());
// If so, go ahead and process it, if not, ignore it (could ban peer...)
if let Some(index) = opt_index {
self.active_requests.swap_remove(index);
if let Some(&mut Some(ref mut pending)) = self.pending_map.get_mut(&info.hash()) {
let data_offset = (data.piece() as usize) * MAX_REQUEST_SIZE;
pending.left -= 1;
(&mut pending.bytes.as_mut_slice()[data_offset..])
.write(data.data().as_ref())
.unwrap();
}
}
Ok(AsyncSink::Ready)
}
fn recv_reject(&mut self, _info: PeerInfo, _reject: UtMetadataRejectMessage) -> StartSend<IDiscoveryMessage, DiscoveryError> {
// TODO: Remove any requests after receiving a reject, for now, we will just timeout
Ok(AsyncSink::Ready)
}
//-------------------------------------------------------------------------------//
fn retrieve_completed_download(&mut self) -> Option<Result<ODiscoveryMessage, DiscoveryError>> {
let opt_completed_hash = self.pending_map
.iter()
.find(|&(_, ref opt_pending)| {
opt_pending
.as_ref()
.map(|pending| pending.left == 0)
.unwrap_or(false)
})
.map(|(hash, _)| *hash);
opt_completed_hash.and_then(|completed_hash| {
let completed = self.pending_map.remove(&completed_hash).unwrap().unwrap();
// Clean up other structures since the download is complete
self.active_peers.remove(&completed_hash);
match Info::from_bytes(&completed.bytes[..]) {
Ok(info) => {
Some(Ok(ODiscoveryMessage::DownloadedMetainfo(info.into())))
},
Err(_) => {
self.retrieve_completed_download()
},
}
})
}
fn retrieve_piece_request(&mut self) -> Option<Result<ODiscoveryMessage, DiscoveryError>> {
for (hash, opt_pending) in self.pending_map.iter_mut() {
let has_ready_requests = opt_pending
.as_ref()
.map(|pending| !pending.messages.is_empty())
.unwrap_or(false);
let has_active_peers = self.active_peers
.get(hash)
.map(|peers| !peers.peers.is_empty())
.unwrap_or(false);
if has_ready_requests && has_active_peers {
let pending = opt_pending.as_mut().unwrap();
let mut active_peers = self.active_peers.get(hash).unwrap().peers.iter();
let num_active_peers = active_peers.len();
let selected_peer_num = rand::thread_rng().next_u32() as usize % num_active_peers;
let selected_peer = active_peers.nth(selected_peer_num).unwrap();
let selected_message = pending.messages.pop().unwrap();
self.active_requests
.push(generate_active_request(selected_message, *selected_peer));
info!("Requesting Piece {:?} For Hash {:?}", selected_message.piece(), selected_peer.hash());
return Some(Ok(ODiscoveryMessage::SendUtMetadataMessage(
*selected_peer,
UtMetadataMessage::Request(selected_message),
)));
}
}
None
}
fn retrieve_piece_response(&mut self) -> Option<Result<ODiscoveryMessage, DiscoveryError>> {
while let Some(request) = self.peer_requests.pop_front() {
let hash = request.send_to.hash();
let piece = request.request.piece();
let start = piece as usize * MAX_REQUEST_SIZE;
let end = start + MAX_REQUEST_SIZE;
if let Some(data) = self.completed_map.get(hash) {
if start <= data.len() && end <= data.len() {
let info_slice = &data[start..end];
let mut info_payload = BytesMut::with_capacity(info_slice.len());
info_payload.extend_from_slice(info_slice);
let message = UtMetadataDataMessage::new(piece, info_slice.len() as i64, info_payload.freeze());
return Some(Ok(ODiscoveryMessage::SendUtMetadataMessage(request.send_to, UtMetadataMessage::Data(message))));
} else {
// Peer asked for a piece outside of the range...dont respond to that
}
}
}
None
}
//-------------------------------------------------------------------------------//
fn initialize_pending(&mut self) -> bool {
let mut pending_tasks_available = false;
// Initialize PeningInfo once we get peers that have told us the metadata size
for (hash, opt_pending) in self.pending_map.iter_mut() {
if opt_pending.is_none() {
let opt_pending_info = self.active_peers
.get(hash)
.map(|active_peers| pending_info_from_metadata_size(active_peers.metadata_size));
*opt_pending = opt_pending_info;
}
// If pending is there, and the messages array is not empty
pending_tasks_available |= opt_pending
.as_ref()
.map(|pending| !pending.messages.is_empty())
.unwrap_or(false);
}
pending_tasks_available
}
fn validate_downloaded(&mut self) -> bool {
let mut completed_downloads_available = false;
// Sweep over all "pending" requests, and check if completed downloads pass hash validation
// If not, set them back to None so they get re-initialized
// If yes, mark down that we have completed downloads
for (&expected_hash, opt_pending) in self.pending_map.iter_mut() {
let should_reset = opt_pending
.as_mut()
.map(|pending| {
if pending.left == 0 {
let real_hash = InfoHash::from_bytes(&pending.bytes[..]);
let needs_reset = real_hash != expected_hash;
// If we dont need a reset, we finished and validation passed!
completed_downloads_available |= !needs_reset;
// If we need a reset, we finished and validation failed!
needs_reset
} else {
false
}
})
.unwrap_or(false);
if should_reset {
*opt_pending = None;
}
}
completed_downloads_available
}
//-------------------------------------------------------------------------------//
fn check_stream_unblock(&mut self) {
// Will invalidate downloads that dont pass hash check
let downloads_available = self.validate_downloaded();
// Will potentially re-initialize downloads that failed hash check
let tasks_available = self.initialize_pending();
let free_task_queue_space = self.active_requests.len() != MAX_ACTIVE_REQUESTS;
let peer_requests_available = !self.peer_requests.is_empty();
// Check if stream is currently blocked AND either we can queue more requests OR we can service some requests OR we have complete downloads
let should_unblock =
self.opt_stream.is_some() && ((free_task_queue_space && tasks_available) || peer_requests_available || downloads_available);
if should_unblock {
self.opt_stream.take().unwrap().notify();
}
}
fn check_sink_unblock(&mut self) {
// Check if sink is currently blocked AND max peer requests has not been reached
let should_unblock = self.opt_sink.is_some() && self.peer_requests.len() != MAX_PEER_REQUESTS;
if should_unblock {
self.opt_sink.take().unwrap().notify();
}
}
}
fn generate_active_request(message: UtMetadataRequestMessage, peer: PeerInfo) -> ActiveRequest {
ActiveRequest {
left: Duration::from_millis(REQUEST_TIMEOUT_MILLIS),
message,
sent_to: peer,
}
}
fn pending_info_from_metadata_size(metadata_size: i64) -> PendingInfo {
let cast_metadata_size = metadata_size as usize;
let bytes = vec![0u8; cast_metadata_size];
let mut messages = Vec::new();
let num_pieces = if cast_metadata_size % MAX_REQUEST_SIZE != 0 {
cast_metadata_size / MAX_REQUEST_SIZE + 1
} else {
cast_metadata_size / MAX_REQUEST_SIZE
};
for index in 0..num_pieces {
messages.push(UtMetadataRequestMessage::new((index) as i64));
}
PendingInfo {
messages,
left: num_pieces,
bytes,
}
}
//-------------------------------------------------------------------------------//
impl ExtendedListener for UtMetadataModule {
fn extend(&self, _info: &PeerInfo, builder: ExtendedMessageBuilder) -> ExtendedMessageBuilder {
builder.with_extended_type(ExtendedType::UtMetadata, Some(5))
}
fn on_update(&mut self, info: &PeerInfo, extended: &ExtendedPeerInfo) {
self.add_peer(*info, extended)
.expect("bip_select: UtMetadataModule::on_update Failed To Add Peer...");
// Check if we need to unblock the stream after performing our work
self.check_stream_unblock();
}
}
//-------------------------------------------------------------------------------//
impl Sink for UtMetadataModule {
type SinkItem = IDiscoveryMessage;
type SinkError = DiscoveryError;
fn start_send(&mut self, item: Self::SinkItem) -> StartSend<Self::SinkItem, Self::SinkError> {
let start_send = match item {
IDiscoveryMessage::Control(ControlMessage::AddTorrent(metainfo)) => {
self.add_torrent(metainfo)
},
IDiscoveryMessage::Control(ControlMessage::RemoveTorrent(metainfo)) => {
self.remove_torrent(metainfo)
},
// Dont add the peer yet, use listener to get notified when they send extension messages
IDiscoveryMessage::Control(ControlMessage::PeerConnected(_)) => {
Ok(AsyncSink::Ready)
},
IDiscoveryMessage::Control(ControlMessage::PeerDisconnected(info)) => {
self.remove_peer(info)
},
IDiscoveryMessage::Control(ControlMessage::Tick(duration)) => {
self.apply_tick(duration)
},
IDiscoveryMessage::DownloadMetainfo(hash) => {
self.download_metainfo(hash)
},
IDiscoveryMessage::ReceivedUtMetadataMessage(info, UtMetadataMessage::Request(msg)) => {
self.recv_request(info, msg)
},
IDiscoveryMessage::ReceivedUtMetadataMessage(info, UtMetadataMessage::Data(msg)) => {
self.recv_data(info, msg)
},
IDiscoveryMessage::ReceivedUtMetadataMessage(info, UtMetadataMessage::Reject(msg)) => {
self.recv_reject(info, msg)
},
};
// Check if we need to unblock the stream after performing our work
self.check_stream_unblock();
// Check if we need to block the sink, if so, set the task
if start_send
.as_ref()
.map(|result| result.is_not_ready())
.unwrap_or(false)
{
self.opt_sink = Some(task::current());
}
start_send
}
fn poll_complete(&mut self) -> Poll<(), Self::SinkError> {
Ok(Async::Ready(()))
}
}
impl Stream for UtMetadataModule {
type Item = ODiscoveryMessage;
type Error = DiscoveryError;
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
// Check if we completed any downloads
// Or if we can send any requests
// Or if we can send any responses
let opt_result = self.retrieve_completed_download()
.or_else(|| self.retrieve_piece_request())
.or_else(|| self.retrieve_piece_response());
// Check if we can unblock the sink after performing our work
self.check_sink_unblock();
// Check if we need to block the stream, if so, set the task
match opt_result {
Some(result) => {
result.map(|value| Async::Ready(Some(value)))
},
None => {
self.opt_stream = Some(task::current());
Ok(Async::NotReady)
},
}
}
} | self.active_peers.remove(&info.hash());
} |
xml.go | // Beego (http://beego.me/)
// @description beego is an open-source, high-performance web framework for the Go programming language.
// @link http://github.com/astaxie/beego for the canonical source repository
// @license http://github.com/astaxie/beego/blob/master/LICENSE
// @authors astaxie
package config
import ( | "os"
"strconv"
"strings"
"sync"
"github.com/astaxie/beego/config"
"github.com/beego/x2j"
)
// XmlConfig is a xml config parser and implements Config interface.
// xml configurations should be included in <config></config> tag.
// only support key/value pair as <key>value</key> as each item.
type XMLConfig struct {
}
// Parse returns a ConfigContainer with parsed xml config map.
func (xmls *XMLConfig) Parse(filename string) (config.ConfigContainer, error) {
file, err := os.Open(filename)
if err != nil {
return nil, err
}
defer file.Close()
x := &XMLConfigContainer{
data: make(map[string]interface{}),
}
content, err := ioutil.ReadAll(file)
if err != nil {
return nil, err
}
d, err := x2j.DocToMap(string(content))
if err != nil {
return nil, err
}
x.data = d["config"].(map[string]interface{})
return x, nil
}
// A Config represents the xml configuration.
type XMLConfigContainer struct {
data map[string]interface{}
sync.Mutex
}
// Bool returns the boolean value for a given key.
func (c *XMLConfigContainer) Bool(key string) (bool, error) {
return strconv.ParseBool(c.data[key].(string))
}
// Int returns the integer value for a given key.
func (c *XMLConfigContainer) Int(key string) (int, error) {
return strconv.Atoi(c.data[key].(string))
}
// Int64 returns the int64 value for a given key.
func (c *XMLConfigContainer) Int64(key string) (int64, error) {
return strconv.ParseInt(c.data[key].(string), 10, 64)
}
// Float returns the float value for a given key.
func (c *XMLConfigContainer) Float(key string) (float64, error) {
return strconv.ParseFloat(c.data[key].(string), 64)
}
// String returns the string value for a given key.
func (c *XMLConfigContainer) String(key string) string {
if v, ok := c.data[key].(string); ok {
return v
}
return ""
}
// Strings returns the []string value for a given key.
func (c *XMLConfigContainer) Strings(key string) []string {
return strings.Split(c.String(key), ";")
}
// WriteValue writes a new value for key.
func (c *XMLConfigContainer) Set(key, val string) error {
c.Lock()
defer c.Unlock()
c.data[key] = val
return nil
}
// DIY returns the raw value by a given key.
func (c *XMLConfigContainer) DIY(key string) (v interface{}, err error) {
if v, ok := c.data[key]; ok {
return v, nil
}
return nil, errors.New("not exist key")
}
func init() {
config.Register("xml", &XMLConfig{})
} | "errors"
"io/ioutil" |
convert.go | /*
Copyright 2020 The Jetstack cert-manager contributors.
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 convert
import (
"fmt"
logf "github.com/jetstack/cert-manager/pkg/logs"
"github.com/spf13/cobra"
metainternalversion "k8s.io/apimachinery/pkg/apis/meta/internalversion"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/runtime/serializer"
apijson "k8s.io/apimachinery/pkg/runtime/serializer/json"
"k8s.io/cli-runtime/pkg/genericclioptions"
"k8s.io/cli-runtime/pkg/printers"
"k8s.io/cli-runtime/pkg/resource"
cmdutil "k8s.io/kubectl/pkg/cmd/util"
"k8s.io/kubectl/pkg/util/i18n"
"k8s.io/kubectl/pkg/util/templates"
cmapiv1alpha2 "github.com/jetstack/cert-manager/pkg/apis/certmanager/v1alpha2"
"github.com/jetstack/cert-manager/pkg/ctl"
)
var (
example = templates.Examples(i18n.T(`
# Convert 'cert.yaml' to latest version and print to stdout.
kubectl cert-manager convert -f cert.yaml
# Convert kustomize overlay under current directory to 'cert-manager.io/v1alpha3'
kubectl cert-manager convert -k . --output-version cert-manager.io/v1alpha3`))
longDesc = templates.LongDesc(i18n.T(`
Convert cert-manager config files between different API versions. Both YAML
and JSON formats are accepted.
The command takes filename, directory, or URL as input, and converts into the
format of the version specified by --output-version flag. If target version is
not specified or not supported, it will convert to the latest version
The default output will be printed to stdout in YAML format. One can use -o option
to change to output destination.`))
)
var (
// Use this scheme as it has the internal cert-manager types
// and their conversion functions registered.
scheme = ctl.Scheme
)
// Options is a struct to support convert command
type Options struct {
PrintFlags *genericclioptions.PrintFlags
Printer printers.ResourcePrinter
OutputVersion string
resource.FilenameOptions
genericclioptions.IOStreams
}
// NewOptions returns initialized Options
func NewOptions(ioStreams genericclioptions.IOStreams) *Options {
return &Options{
IOStreams: ioStreams,
PrintFlags: genericclioptions.NewPrintFlags("converted").WithDefaultOutput("yaml"),
}
}
// NewCmdConvert returns a cobra command for converting cert-manager resources
func NewCmdConvert(ioStreams genericclioptions.IOStreams) *cobra.Command {
o := NewOptions(ioStreams)
cmd := &cobra.Command{
Use: "convert",
Short: "Convert cert-manager config files between different API versions",
Long: longDesc,
Example: example,
DisableFlagsInUseLine: true,
Run: func(cmd *cobra.Command, args []string) {
cmdutil.CheckErr(o.Complete())
cmdutil.CheckErr(o.Run())
},
}
cmd.Flags().StringVar(&o.OutputVersion, "output-version", o.OutputVersion, "Output the formatted object with the given group version (for ex: 'cert-manager.io/v1alpha3').")
cmdutil.AddFilenameOptionFlags(cmd, &o.FilenameOptions, "Path to a file containing cert-manager resources to be converted.")
o.PrintFlags.AddFlags(cmd)
return cmd
}
// Complete collects information required to run Convert command from command line.
func (o *Options) Complete() error {
err := o.FilenameOptions.RequireFilenameOrKustomize()
if err != nil {
return err
}
// build the printer
o.Printer, err = o.PrintFlags.ToPrinter()
if err != nil {
return err
}
return nil
}
// Run executes convert command
func (o *Options) Run() error {
builder := new(resource.Builder)
r := builder.
WithScheme(scheme, schema.GroupVersion{Group: cmapiv1alpha2.SchemeGroupVersion.Group, Version: runtime.APIVersionInternal}).
LocalParam(true).FilenameParam(false, &o.FilenameOptions).Flatten().Do()
if err := r.Err(); err != nil {
return fmt.Errorf("error here: %s", err)
}
singleItemImplied := false
infos, err := r.IntoSingleItemImplied(&singleItemImplied).Infos()
if err != nil {
return fmt.Errorf("error here instead: %s", err)
}
if len(infos) == 0 {
return fmt.Errorf("no objects passed to convert")
}
var specifiedOutputVersion schema.GroupVersion
if len(o.OutputVersion) > 0 {
specifiedOutputVersion, err = schema.ParseGroupVersion(o.OutputVersion)
if err != nil {
return err
}
}
factory := serializer.NewCodecFactory(scheme)
serializer := apijson.NewSerializerWithOptions(apijson.DefaultMetaFactory, scheme, scheme, apijson.SerializerOptions{})
encoder := factory.WithoutConversion().EncoderForVersion(serializer, nil)
objects, err := asVersionedObject(infos, !singleItemImplied, specifiedOutputVersion, encoder)
if err != nil {
return err
}
return o.Printer.PrintObj(objects, o.Out)
}
// asVersionedObject converts a list of infos into a single object - either a List containing
// the objects as children, or if only a single Object is present, as that object. The provided
// version will be preferred as the conversion target, but the Object's mapping version will be
// used if that version is not present.
func asVersionedObject(infos []*resource.Info, forceList bool, specifiedOutputVersion schema.GroupVersion, encoder runtime.Encoder) (runtime.Object, error) {
objects, err := asVersionedObjects(infos, specifiedOutputVersion, encoder)
if err != nil {
return nil, err
}
var object runtime.Object
if len(objects) == 1 && !forceList {
object = objects[0]
} else {
object = &metainternalversion.List{Items: objects}
targetVersions := []schema.GroupVersion{}
if !specifiedOutputVersion.Empty() {
targetVersions = append(targetVersions, specifiedOutputVersion)
}
// This is needed so we are able to handle the List object when converting
// multiple resources
targetVersions = append(targetVersions, schema.GroupVersion{Group: "", Version: "v1"})
converted, err := tryConvert(object, targetVersions...)
if err != nil {
return nil, err
}
object = converted
}
actualVersion := object.GetObjectKind().GroupVersionKind()
if actualVersion.Version != specifiedOutputVersion.Version {
defaultVersionInfo := ""
if len(actualVersion.Version) > 0 {
defaultVersionInfo = fmt.Sprintf("Defaulting to %q", actualVersion.Version)
}
logf.V(logf.WarnLevel).Infof("info: the output version specified is invalid. %s\n", defaultVersionInfo)
}
return object, nil
}
// asVersionedObjects converts a list of infos into versioned objects. The provided
// version will be preferred as the conversion target, but the Object's mapping version will be
// used if that version is not present.
func asVersionedObjects(infos []*resource.Info, specifiedOutputVersion schema.GroupVersion, encoder runtime.Encoder) ([]runtime.Object, error) {
objects := []runtime.Object{}
for _, info := range infos {
if info.Object == nil {
continue
}
targetVersions := []schema.GroupVersion{}
// objects that are not part of api.Scheme must be converted to JSON
if !specifiedOutputVersion.Empty() {
_, _, err := scheme.ObjectKinds(info.Object)
if err != nil {
if runtime.IsNotRegisteredError(err) {
data, err := runtime.Encode(encoder, info.Object)
if err != nil {
return nil, err
}
objects = append(objects, &runtime.Unknown{Raw: data})
continue
}
return nil, err
}
targetVersions = append(targetVersions, specifiedOutputVersion)
} else {
gvks, _, err := scheme.ObjectKinds(info.Object)
if err == nil {
for _, gvk := range gvks {
targetVersions = append(targetVersions, scheme.PrioritizedVersionsForGroup(gvk.Group)...)
}
}
}
converted, err := tryConvert(info.Object, targetVersions...)
if err != nil {
return nil, err
}
objects = append(objects, converted)
}
return objects, nil
}
// tryConvert attempts to convert the given object to the provided versions in order. This function assumes
// the object is in internal version.
func tryConvert(object runtime.Object, versions ...schema.GroupVersion) (runtime.Object, error) | {
var last error
for _, version := range versions {
if version.Empty() {
return object, nil
}
obj, err := scheme.ConvertToVersion(object, version)
if err != nil {
last = err
continue
}
return obj, nil
}
return nil, last
} |
|
css_lexer.go | package css_lexer
import (
"strings"
"unicode/utf8"
"github.com/evanw/esbuild/internal/logger"
)
// The lexer converts a source file to a stream of tokens. Unlike esbuild's
// JavaScript lexer, this CSS lexer runs to completion before the CSS parser
// begins, resulting in a single array of all tokens in the file.
type T uint8
const eof = -1
const replacementCharacter = 0xFFFD
const (
TEndOfFile T = iota
TAtKeyword
TBadString
TBadURL
TCDC // "-->"
TCDO // "<!--"
TCloseBrace
TCloseBracket
TCloseParen
TColon
TComma
TDelim
TDelimAmpersand
TDelimAsterisk
TDelimBar
TDelimCaret
TDelimDollar
TDelimDot
TDelimEquals
TDelimExclamation
TDelimGreaterThan
TDelimPlus
TDelimSlash
TDelimTilde
TDimension
TFunction
THash
TIdent
TNumber
TOpenBrace
TOpenBracket
TOpenParen
TPercentage
TSemicolon
TString
TURL
TWhitespace
)
var tokenToString = []string{
"end of file",
"@-keyword",
"bad string token",
"bad URL token",
"\"-->\"",
"\"<!--\"",
"\"}\"",
"\"]\"",
"\")\"",
"\":\"",
"\",\"",
"delimiter",
"\"&\"",
"\"*\"",
"\"|\"",
"\"^\"",
"\"$\"",
"\".\"",
"\"=\"",
"\"!\"",
"\">\"",
"\"+\"",
"\"/\"",
"\"~\"",
"dimension",
"function token",
"hash token",
"identifier",
"number",
"\"{\"",
"\"[\"",
"\"(\"",
"percentage",
"\";\"",
"string token",
"URL token",
"whitespace",
}
func (t T) String() string {
return tokenToString[t]
}
// This token struct is designed to be memory-efficient. It just references a
// range in the input file instead of directly containing the substring of text
// since a range takes up less memory than a string.
type Token struct {
Range logger.Range // 8 bytes
UnitOffset uint16 // 2 bytes
Kind T // 1 byte
IsID bool // 1 byte
}
func (token Token) DecodedText(contents string) string {
raw := contents[token.Range.Loc.Start:token.Range.End()]
switch token.Kind {
case TIdent, TDimension:
return decodeEscapesInToken(raw)
case TAtKeyword, THash:
return decodeEscapesInToken(raw[1:])
case TFunction:
return decodeEscapesInToken(raw[:len(raw)-1])
case TString:
return decodeEscapesInToken(raw[1 : len(raw)-1])
case TURL:
start := 4
end := len(raw) - 1
// Trim leading and trailing whitespace
for start < end && isWhitespace(rune(raw[start])) {
start++
}
for start < end && isWhitespace(rune(raw[end-1])) {
end--
}
return decodeEscapesInToken(raw[start:end])
}
return raw
}
type lexer struct {
log logger.Log
source logger.Source
current int
codePoint rune
Token Token
}
func Tokenize(log logger.Log, source logger.Source) (tokens []Token) {
lexer := lexer{
log: log,
source: source,
}
lexer.step()
lexer.next()
for lexer.Token.Kind != TEndOfFile {
tokens = append(tokens, lexer.Token)
lexer.next()
}
return
}
func (lexer *lexer) step() {
codePoint, width := utf8.DecodeRuneInString(lexer.source.Contents[lexer.current:])
// Use -1 to indicate the end of the file
if width == 0 {
codePoint = eof
}
lexer.codePoint = codePoint
lexer.Token.Range.Len = int32(lexer.current) - lexer.Token.Range.Loc.Start
lexer.current += width
}
func (lexer *lexer) next() {
// Reference: https://www.w3.org/TR/css-syntax-3/
for {
lexer.Token = Token{Range: logger.Range{Loc: logger.Loc{Start: lexer.Token.Range.End()}}}
switch lexer.codePoint {
case eof:
lexer.Token.Kind = TEndOfFile
case '/':
lexer.step()
switch lexer.codePoint {
case '*':
lexer.step()
lexer.consumeToEndOfMultiLineComment(lexer.Token.Range)
continue
case '/':
lexer.step()
lexer.consumeToEndOfSingleLineComment()
continue
}
lexer.Token.Kind = TDelimSlash
case ' ', '\t', '\n', '\r', '\f':
lexer.step()
for {
if isWhitespace(lexer.codePoint) {
lexer.step()
} else if lexer.codePoint == '/' && lexer.current < len(lexer.source.Contents) && lexer.source.Contents[lexer.current] == '*' {
startRange := logger.Range{Loc: logger.Loc{Start: lexer.Token.Range.End()}, Len: 2}
lexer.step()
lexer.step()
lexer.consumeToEndOfMultiLineComment(startRange)
} else {
break
}
}
lexer.Token.Kind = TWhitespace
case '"', '\'':
lexer.Token.Kind = lexer.consumeString()
case '#':
lexer.step()
if IsNameContinue(lexer.codePoint) || lexer.isValidEscape() {
lexer.Token.Kind = THash
if lexer.wouldStartIdentifier() {
lexer.Token.IsID = true
}
lexer.consumeName()
} else {
lexer.Token.Kind = TDelim
}
case '(':
lexer.step()
lexer.Token.Kind = TOpenParen
case ')':
lexer.step()
lexer.Token.Kind = TCloseParen
case '[':
lexer.step()
lexer.Token.Kind = TOpenBracket
case ']':
lexer.step()
lexer.Token.Kind = TCloseBracket
case '{':
lexer.step()
lexer.Token.Kind = TOpenBrace
case '}':
lexer.step()
lexer.Token.Kind = TCloseBrace
case ',':
lexer.step()
lexer.Token.Kind = TComma
case ':':
lexer.step()
lexer.Token.Kind = TColon
case ';':
lexer.step()
lexer.Token.Kind = TSemicolon
case '+':
if lexer.wouldStartNumber() {
lexer.Token.Kind = lexer.consumeNumeric()
} else {
lexer.step()
lexer.Token.Kind = TDelimPlus
}
case '.':
if lexer.wouldStartNumber() {
lexer.Token.Kind = lexer.consumeNumeric()
} else {
lexer.step()
lexer.Token.Kind = TDelimDot
}
case '-':
if lexer.wouldStartNumber() {
lexer.Token.Kind = lexer.consumeNumeric()
} else if lexer.current+2 <= len(lexer.source.Contents) && lexer.source.Contents[lexer.current:lexer.current+2] == "->" {
lexer.step()
lexer.step()
lexer.step()
lexer.Token.Kind = TCDC
} else if lexer.wouldStartIdentifier() {
lexer.consumeName()
lexer.Token.Kind = TIdent
} else {
lexer.step()
lexer.Token.Kind = TDelim
}
case '<':
if lexer.current+3 <= len(lexer.source.Contents) && lexer.source.Contents[lexer.current:lexer.current+3] == "!--" {
lexer.step()
lexer.step()
lexer.step()
lexer.step()
lexer.Token.Kind = TCDO
} else {
lexer.step()
lexer.Token.Kind = TDelim
}
case '@':
lexer.step()
if lexer.wouldStartIdentifier() {
lexer.consumeName()
lexer.Token.Kind = TAtKeyword
} else {
lexer.Token.Kind = TDelim
}
case '\\':
if lexer.isValidEscape() {
lexer.Token.Kind = lexer.consumeIdentLike()
} else {
lexer.step()
lexer.log.AddRangeError(&lexer.source, lexer.Token.Range, "Invalid escape")
lexer.Token.Kind = TDelim
}
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
lexer.Token.Kind = lexer.consumeNumeric()
case '>':
lexer.step()
lexer.Token.Kind = TDelimGreaterThan
case '~':
lexer.step()
lexer.Token.Kind = TDelimTilde
case '&':
lexer.step()
lexer.Token.Kind = TDelimAmpersand
case '*':
lexer.step()
lexer.Token.Kind = TDelimAsterisk
case '|':
lexer.step()
lexer.Token.Kind = TDelimBar
case '!':
lexer.step()
lexer.Token.Kind = TDelimExclamation
case '=':
lexer.step()
lexer.Token.Kind = TDelimEquals
case '^':
lexer.step()
lexer.Token.Kind = TDelimCaret
case '$':
lexer.step()
lexer.Token.Kind = TDelimDollar
default:
if IsNameStart(lexer.codePoint) {
lexer.Token.Kind = lexer.consumeIdentLike()
} else {
lexer.step()
lexer.Token.Kind = TDelim
}
}
return
}
}
func (lexer *lexer) consumeToEndOfMultiLineComment(startRange logger.Range) {
for {
switch lexer.codePoint {
case '*':
lexer.step()
if lexer.codePoint == '/' {
lexer.step()
return
}
case eof: // This indicates the end of the file
lexer.log.AddErrorWithNotes(&lexer.source, logger.Loc{Start: lexer.Token.Range.End()}, "Expected \"*/\" to terminate multi-line comment",
[]logger.MsgData{logger.RangeData(&lexer.source, startRange, "The multi-line comment starts here")})
return
default:
lexer.step()
}
}
}
func (lexer *lexer) consumeToEndOfSingleLineComment() {
for !isNewline(lexer.codePoint) && lexer.codePoint != eof {
lexer.step()
}
lexer.log.AddRangeWarning(&lexer.source, lexer.Token.Range, "Comments in CSS use \"/* ... */\" instead of \"//\"")
}
func (lexer *lexer) isValidEscape() bool {
if lexer.codePoint != '\\' {
return false
}
c, _ := utf8.DecodeRuneInString(lexer.source.Contents[lexer.current:])
return !isNewline(c)
}
func (lexer *lexer) wouldStartIdentifier() bool {
if IsNameStart(lexer.codePoint) {
return true
}
if lexer.codePoint == '-' {
c, w := utf8.DecodeRuneInString(lexer.source.Contents[lexer.current:])
if IsNameStart(c) || c == '-' {
return true
}
if c == '\\' {
c, _ = utf8.DecodeRuneInString(lexer.source.Contents[lexer.current+w:])
return !isNewline(c)
}
return false
}
return lexer.isValidEscape()
}
func WouldStartIdentifierWithoutEscapes(text string) bool {
if len(text) > 0 {
c, width := utf8.DecodeRuneInString(text)
if IsNameStart(c) {
return true
} else if c == '-' {
if c, _ := utf8.DecodeRuneInString(text[width:]); IsNameStart(c) || c == '-' {
return true
}
}
}
return false
}
func (lexer *lexer) wouldStartNumber() bool {
if lexer.codePoint >= '0' && lexer.codePoint <= '9' {
return true
} else if lexer.codePoint == '.' {
contents := lexer.source.Contents
if lexer.current < len(contents) {
c := contents[lexer.current]
return c >= '0' && c <= '9'
}
} else if lexer.codePoint == '+' || lexer.codePoint == '-' {
contents := lexer.source.Contents
n := len(contents)
if lexer.current < n {
c := contents[lexer.current]
if c >= '0' && c <= '9' {
return true
}
if c == '.' && lexer.current+1 < n {
c = contents[lexer.current+1]
return c >= '0' && c <= '9'
}
}
}
return false
}
func (lexer *lexer) consumeName() string {
// Common case: no escapes, identifier is a substring of the input
for IsNameContinue(lexer.codePoint) {
lexer.step()
}
raw := lexer.source.Contents[lexer.Token.Range.Loc.Start:lexer.Token.Range.End()]
if !lexer.isValidEscape() {
return raw
}
// Uncommon case: escapes, identifier is allocated
sb := strings.Builder{}
sb.WriteString(raw)
sb.WriteRune(lexer.consumeEscape())
for {
if IsNameContinue(lexer.codePoint) {
sb.WriteRune(lexer.codePoint)
lexer.step()
} else if lexer.isValidEscape() {
sb.WriteRune(lexer.consumeEscape())
} else {
break
}
}
return sb.String()
}
func (lexer *lexer) consumeEscape() rune {
lexer.step() // Skip the backslash
c := lexer.codePoint
if hex, ok := isHex(c); ok {
lexer.step()
for i := 0; i < 5; i++ {
if next, ok := isHex(lexer.codePoint); ok {
lexer.step()
hex = hex*16 + next
} else {
break
}
}
if isWhitespace(lexer.codePoint) {
lexer.step()
}
if hex == 0 || (hex >= 0xD800 && hex <= 0xDFFF) || hex > 0x10FFFF {
return replacementCharacter
}
return rune(hex)
}
if c == eof {
return replacementCharacter
}
lexer.step()
return c
}
func (lexer *lexer) consumeIdentLike() T {
name := lexer.consumeName()
if lexer.codePoint == '(' {
lexer.step()
if len(name) == 3 {
u, r, l := name[0], name[1], name[2]
if (u == 'u' || u == 'U') && (r == 'r' || r == 'R') && (l == 'l' || l == 'L') {
for isWhitespace(lexer.codePoint) {
lexer.step()
}
if lexer.codePoint != '"' && lexer.codePoint != '\'' {
return lexer.consumeURL()
}
}
}
return TFunction
}
return TIdent
}
func (lexer *lexer) consumeURL() T {
validURL:
for {
switch lexer.codePoint {
case ')':
lexer.step()
return TURL
case eof:
loc := logger.Loc{Start: lexer.Token.Range.End()}
lexer.log.AddError(&lexer.source, loc, "Expected \")\" to end URL token")
return TBadURL
case ' ', '\t', '\n', '\r', '\f':
lexer.step()
for isWhitespace(lexer.codePoint) {
lexer.step()
}
if lexer.codePoint != ')' {
loc := logger.Loc{Start: lexer.Token.Range.End()}
lexer.log.AddError(&lexer.source, loc, "Expected \")\" to end URL token")
break validURL
}
lexer.step()
return TURL
case '"', '\'', '(':
r := logger.Range{Loc: logger.Loc{Start: lexer.Token.Range.End()}, Len: 1}
lexer.log.AddRangeError(&lexer.source, r, "Expected \")\" to end URL token")
break validURL
case '\\':
if !lexer.isValidEscape() {
r := logger.Range{Loc: logger.Loc{Start: lexer.Token.Range.End()}, Len: 1}
lexer.log.AddRangeError(&lexer.source, r, "Invalid escape")
break validURL
}
lexer.consumeEscape()
default:
if isNonPrintable(lexer.codePoint) {
r := logger.Range{Loc: logger.Loc{Start: lexer.Token.Range.End()}, Len: 1}
lexer.log.AddRangeError(&lexer.source, r, "Unexpected non-printable character in URL token")
}
lexer.step()
}
}
// Consume the remnants of a bad url
for {
switch lexer.codePoint {
case ')', eof:
lexer.step()
return TBadURL
case '\\':
if lexer.isValidEscape() {
lexer.consumeEscape()
}
}
lexer.step()
}
}
func (lexer *lexer) consumeString() T {
quote := lexer.codePoint
lexer.step()
for {
switch lexer.codePoint {
case '\\':
lexer.step()
// Handle Windows CRLF
if lexer.codePoint == '\r' {
lexer.step()
if lexer.codePoint == '\n' {
lexer.step()
}
continue
}
// Otherwise, fall through to ignore the character after the backslash
case eof:
lexer.log.AddError(&lexer.source, logger.Loc{Start: lexer.Token.Range.End()}, "Unterminated string token")
return TBadString
case '\n', '\r', '\f':
lexer.log.AddError(&lexer.source, logger.Loc{Start: lexer.Token.Range.End()}, "Unterminated string token")
return TBadString
case quote:
lexer.step()
return TString
}
lexer.step()
}
}
func (lexer *lexer) consumeNumeric() T {
// Skip over leading sign
if lexer.codePoint == '+' || lexer.codePoint == '-' {
lexer.step()
}
// Skip over leading digits
for lexer.codePoint >= '0' && lexer.codePoint <= '9' {
lexer.step()
}
// Skip over digits after dot
if lexer.codePoint == '.' {
lexer.step()
for lexer.codePoint >= '0' && lexer.codePoint <= '9' {
lexer.step()
}
}
// Skip over exponent
if lexer.codePoint == 'e' || lexer.codePoint == 'E' {
contents := lexer.source.Contents
// Look ahead before advancing to make sure this is an exponent, not a unit
if lexer.current < len(contents) {
c := contents[lexer.current]
if (c == '+' || c == '-') && lexer.current+1 < len(contents) {
c = contents[lexer.current+1]
}
// Only consume this if it's an exponent
if c >= '0' && c <= '9' {
lexer.step()
if lexer.codePoint == '+' || lexer.codePoint == '-' {
lexer.step()
}
for lexer.codePoint >= '0' && lexer.codePoint <= '9' {
lexer.step()
}
}
}
}
// Determine the numeric type
if lexer.wouldStartIdentifier() {
lexer.Token.UnitOffset = uint16(lexer.Token.Range.Len)
lexer.consumeName()
return TDimension
}
if lexer.codePoint == '%' {
lexer.step()
return TPercentage
}
return TNumber
}
func IsNameStart(c rune) bool {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || c >= 0x80
}
func IsNameContinue(c rune) bool {
return IsNameStart(c) || (c >= '0' && c <= '9') || c == '-'
}
func isNewline(c rune) bool {
switch c {
case '\n', '\r', '\f':
return true
}
return false
}
func isWhitespace(c rune) bool |
func isHex(c rune) (int, bool) {
if c >= '0' && c <= '9' {
return int(c - '0'), true
}
if c >= 'a' && c <= 'f' {
return int(c + (10 - 'a')), true
}
if c >= 'A' && c <= 'F' {
return int(c + (10 - 'A')), true
}
return 0, false
}
func isNonPrintable(c rune) bool {
return c <= 0x08 || c == 0x0B || (c >= 0x0E && c <= 0x1F) || c == 0x7F
}
func decodeEscapesInToken(inner string) string {
i := 0
for i < len(inner) {
if inner[i] == '\\' {
break
}
i++
}
if i == len(inner) {
return inner
}
sb := strings.Builder{}
sb.WriteString(inner[:i])
inner = inner[i:]
for len(inner) > 0 {
c, width := utf8.DecodeRuneInString(inner)
inner = inner[width:]
if c != '\\' {
sb.WriteRune(c)
continue
}
if len(inner) == 0 {
sb.WriteRune(replacementCharacter)
continue
}
c, width = utf8.DecodeRuneInString(inner)
inner = inner[width:]
hex, ok := isHex(c)
if !ok {
if c == '\n' || c == '\f' {
continue
}
// Handle Windows CRLF
if c == '\r' {
c, width = utf8.DecodeRuneInString(inner)
if c == '\n' {
inner = inner[width:]
}
continue
}
// If we get here, this is not a valid escape. However, this is still
// allowed. In this case the backslash is just ignored.
sb.WriteRune(c)
continue
}
// Parse up to five additional hex characters (so six in total)
for i := 0; i < 5 && len(inner) > 0; i++ {
c, width = utf8.DecodeRuneInString(inner)
if next, ok := isHex(c); ok {
inner = inner[width:]
hex = hex*16 + next
} else {
break
}
}
if len(inner) > 0 {
c, width = utf8.DecodeRuneInString(inner)
if isWhitespace(c) {
inner = inner[width:]
}
}
if hex == 0 || (hex >= 0xD800 && hex <= 0xDFFF) || hex > 0x10FFFF {
sb.WriteRune(replacementCharacter)
continue
}
sb.WriteRune(rune(hex))
}
return sb.String()
}
| {
switch c {
case ' ', '\t', '\n', '\r', '\f':
return true
}
return false
} |
run.go | package command
import (
// Std lib
"errors"
"fmt"
"io"
"strings"
// External
"github.com/sirupsen/logrus"
// Internal
"github.com/VEuPathDB/util-exporter-server/internal/config"
"github.com/VEuPathDB/util-exporter-server/internal/job"
"github.com/VEuPathDB/util-exporter-server/internal/service/cache"
"github.com/VEuPathDB/util-exporter-server/internal/service/workspace"
)
type RunResult struct {
Error error
Stream io.ReadCloser
Name string
} | options config.FileOptions,
wkspc workspace.Workspace,
log *logrus.Entry,
) Runner {
return &runner{
log: log,
token: token,
options: options,
wkspc: wkspc,
}
}
type Runner interface {
Run() RunResult
}
type runner struct {
log *logrus.Entry
token string
options config.FileOptions
details job.Details
meta job.Metadata
wkspc workspace.Workspace
}
func (r *runner) Run() RunResult {
r.log.Trace("command.runner.Run")
var err error
r.getDetails()
r.getMeta()
r.updateStatus(job.StatusUnpacking)
if err = r.unpack(&r.details); err != nil {
return r.fail(err)
}
r.updateStatus(job.StatusProcessing)
if err = r.handleCommand(r.options.Commands()); err != nil {
return r.fail(err)
}
fileName, err := r.findTar()
if err != nil {
return r.fail(err)
}
file, err := r.wkspc.Open(fileName)
if err != nil {
return r.fail(
errors.New("Failed to open packaged tar for reading: " + err.Error()))
}
r.updateStatus(job.StatusCompleted)
return RunResult{
Stream: file,
Name: fileName,
}
}
func (r *runner) getDetails() {
r.log.Trace("command.runner.getDetails")
r.details, _ = cache.GetDetails(r.token)
}
func (r *runner) storeDetails() {
r.log.Trace("command.runner.storeDetails")
cache.PutDetails(r.token, r.details)
}
func (r *runner) getMeta() {
r.log.Trace("command.runner.getMeta")
r.meta, _ = cache.GetMetadata(r.token)
}
func (r *runner) updateStatus(status job.Status) {
r.log.Trace("command.runner.updateStatus")
r.details.Status = status
r.storeDetails()
}
func (r *runner) findTar() (string, error) {
r.log.Trace("command.runner.findTar")
prefix := fmt.Sprintf("dataset_u%d", r.meta.Owner)
matches, err := r.wkspc.Files(func(f string) bool {
return strings.HasPrefix(f, prefix)
})
if err != nil {
return "", err
}
switch len(matches) {
case 0:
return "", errors.New("no dataset archive found")
case 1:
return matches[0], nil
default:
return "", errors.New("invalid state, more than one dataset archive present in workspace")
}
} |
func NewCommandRunner(
token string, |
data_test.go | package packets
import (
"testing"
"time"
"github.com/paulbellamy/go-ndn/name"
"github.com/stretchr/testify/assert"
)
func Test_Data_Name(t *testing.T) {
subject := &Data{}
// when unspecified
assert.Equal(t, subject.GetName().Size(), 0)
n := name.New(name.Component{"a"}, name.Component{"b"})
subject.SetName(n)
assert.Equal(t, subject.GetName(), n)
// check it is copied
n.Clear()
assert.Equal(t, subject.GetName(), name.New(name.Component{"a"}, name.Component{"b"}))
}
func Test_Data_FreshnessPeriod(t *testing.T) {
subject := &Data{}
// when unspecified
assert.Equal(t, subject.GetFreshnessPeriod(), -1)
subject.SetFreshnessPeriod(2 * time.Minute)
assert.Equal(t, subject.GetFreshnessPeriod(), 2*time.Minute)
}
func | (t *testing.T) {
subject := &Data{}
// when unspecified
assert.Equal(t, subject.GetContent(), []byte{})
content := []byte("hello world")
subject.SetContent(content)
assert.Equal(t, subject.GetContent(), content)
}
func Test_Data_Signature(t *testing.T) {
subject := &Data{}
assert.Nil(t, subject.GetSignature())
signature := Sha256WithRSASignature{}
subject.SetSignature(signature)
assert.Equal(t, subject.GetSignature(), signature)
}
| Test_Data_Content |
context.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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.
//! Distributed execution context.
use parking_lot::Mutex;
use sqlparser::ast::Statement;
use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;
use std::sync::Arc;
use ballista_core::config::BallistaConfig;
use ballista_core::serde::protobuf::LogicalPlanNode;
use ballista_core::utils::create_df_ctx_with_ballista_query_planner;
use datafusion::catalog::TableReference;
use datafusion::dataframe::DataFrame;
use datafusion::datasource::TableProvider;
use datafusion::error::{DataFusionError, Result};
use datafusion::execution::dataframe_impl::DataFrameImpl;
use datafusion::logical_plan::{CreateExternalTable, LogicalPlan, TableScan};
use datafusion::prelude::{
AvroReadOptions, CsvReadOptions, ExecutionConfig, ExecutionContext,
};
use datafusion::sql::parser::{DFParser, FileType, Statement as DFStatement};
struct BallistaContextState {
/// Ballista configuration
config: BallistaConfig,
/// Scheduler host
scheduler_host: String,
/// Scheduler port
scheduler_port: u16,
/// Tables that have been registered with this context
tables: HashMap<String, Arc<dyn TableProvider>>,
}
impl BallistaContextState {
pub fn new(
scheduler_host: String,
scheduler_port: u16,
config: &BallistaConfig,
) -> Self {
Self {
config: config.clone(),
scheduler_host,
scheduler_port,
tables: HashMap::new(),
}
}
#[cfg(feature = "standalone")]
pub async fn new_standalone(
config: &BallistaConfig,
concurrent_tasks: usize,
) -> ballista_core::error::Result<Self> {
use ballista_core::serde::protobuf::scheduler_grpc_client::SchedulerGrpcClient;
use ballista_core::serde::protobuf::PhysicalPlanNode;
use ballista_core::serde::BallistaCodec;
log::info!("Running in local mode. Scheduler will be run in-proc");
let addr = ballista_scheduler::standalone::new_standalone_scheduler().await?;
let scheduler = loop {
match SchedulerGrpcClient::connect(format!(
"http://localhost:{}",
addr.port()
))
.await
{
Err(_) => {
tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
log::info!("Attempting to connect to in-proc scheduler...");
}
Ok(scheduler) => break scheduler,
}
};
let default_codec: BallistaCodec<LogicalPlanNode, PhysicalPlanNode> =
BallistaCodec::default();
ballista_executor::new_standalone_executor(
scheduler,
concurrent_tasks, | .await?;
Ok(Self {
config: config.clone(),
scheduler_host: "localhost".to_string(),
scheduler_port: addr.port(),
tables: HashMap::new(),
})
}
pub fn config(&self) -> &BallistaConfig {
&self.config
}
}
pub struct BallistaContext {
state: Arc<Mutex<BallistaContextState>>,
}
impl BallistaContext {
/// Create a context for executing queries against a remote Ballista scheduler instance
pub fn remote(host: &str, port: u16, config: &BallistaConfig) -> Self {
let state = BallistaContextState::new(host.to_owned(), port, config);
Self {
state: Arc::new(Mutex::new(state)),
}
}
#[cfg(feature = "standalone")]
pub async fn standalone(
config: &BallistaConfig,
concurrent_tasks: usize,
) -> ballista_core::error::Result<Self> {
let state =
BallistaContextState::new_standalone(config, concurrent_tasks).await?;
Ok(Self {
state: Arc::new(Mutex::new(state)),
})
}
/// Create a DataFrame representing an Avro table scan
/// TODO fetch schema from scheduler instead of resolving locally
pub async fn read_avro(
&self,
path: &str,
options: AvroReadOptions<'_>,
) -> Result<Arc<dyn DataFrame>> {
// convert to absolute path because the executor likely has a different working directory
let path = PathBuf::from(path);
let path = fs::canonicalize(&path)?;
// use local DataFusion context for now but later this might call the scheduler
let mut ctx = {
let guard = self.state.lock();
create_df_ctx_with_ballista_query_planner::<LogicalPlanNode>(
&guard.scheduler_host,
guard.scheduler_port,
guard.config(),
)
};
let df = ctx.read_avro(path.to_str().unwrap(), options).await?;
Ok(df)
}
/// Create a DataFrame representing a Parquet table scan
/// TODO fetch schema from scheduler instead of resolving locally
pub async fn read_parquet(&self, path: &str) -> Result<Arc<dyn DataFrame>> {
// convert to absolute path because the executor likely has a different working directory
let path = PathBuf::from(path);
let path = fs::canonicalize(&path)?;
// use local DataFusion context for now but later this might call the scheduler
let mut ctx = {
let guard = self.state.lock();
create_df_ctx_with_ballista_query_planner::<LogicalPlanNode>(
&guard.scheduler_host,
guard.scheduler_port,
guard.config(),
)
};
let df = ctx.read_parquet(path.to_str().unwrap()).await?;
Ok(df)
}
/// Create a DataFrame representing a CSV table scan
/// TODO fetch schema from scheduler instead of resolving locally
pub async fn read_csv(
&self,
path: &str,
options: CsvReadOptions<'_>,
) -> Result<Arc<dyn DataFrame>> {
// convert to absolute path because the executor likely has a different working directory
let path = PathBuf::from(path);
let path = fs::canonicalize(&path)?;
// use local DataFusion context for now but later this might call the scheduler
let mut ctx = {
let guard = self.state.lock();
create_df_ctx_with_ballista_query_planner::<LogicalPlanNode>(
&guard.scheduler_host,
guard.scheduler_port,
guard.config(),
)
};
let df = ctx.read_csv(path.to_str().unwrap(), options).await?;
Ok(df)
}
/// Register a DataFrame as a table that can be referenced from a SQL query
pub fn register_table(
&self,
name: &str,
table: Arc<dyn TableProvider>,
) -> Result<()> {
let mut state = self.state.lock();
state.tables.insert(name.to_owned(), table);
Ok(())
}
pub async fn register_csv(
&self,
name: &str,
path: &str,
options: CsvReadOptions<'_>,
) -> Result<()> {
match self.read_csv(path, options).await?.to_logical_plan() {
LogicalPlan::TableScan(TableScan { source, .. }) => {
self.register_table(name, source)
}
_ => Err(DataFusionError::Internal("Expected tables scan".to_owned())),
}
}
pub async fn register_parquet(&self, name: &str, path: &str) -> Result<()> {
match self.read_parquet(path).await?.to_logical_plan() {
LogicalPlan::TableScan(TableScan { source, .. }) => {
self.register_table(name, source)
}
_ => Err(DataFusionError::Internal("Expected tables scan".to_owned())),
}
}
pub async fn register_avro(
&self,
name: &str,
path: &str,
options: AvroReadOptions<'_>,
) -> Result<()> {
match self.read_avro(path, options).await?.to_logical_plan() {
LogicalPlan::TableScan(TableScan { source, .. }) => {
self.register_table(name, source)
}
_ => Err(DataFusionError::Internal("Expected tables scan".to_owned())),
}
}
/// is a 'show *' sql
pub async fn is_show_statement(&self, sql: &str) -> Result<bool> {
let mut is_show_variable: bool = false;
let statements = DFParser::parse_sql(sql)?;
if statements.len() != 1 {
return Err(DataFusionError::NotImplemented(
"The context currently only supports a single SQL statement".to_string(),
));
}
if let DFStatement::Statement(s) = &statements[0] {
let st: &Statement = s;
match st {
Statement::ShowVariable { .. } => {
is_show_variable = true;
}
Statement::ShowColumns { .. } => {
is_show_variable = true;
}
_ => {
is_show_variable = false;
}
}
};
Ok(is_show_variable)
}
/// Create a DataFrame from a SQL statement.
///
/// This method is `async` because queries of type `CREATE EXTERNAL TABLE`
/// might require the schema to be inferred.
pub async fn sql(&self, sql: &str) -> Result<Arc<dyn DataFrame>> {
let mut ctx = {
let state = self.state.lock();
create_df_ctx_with_ballista_query_planner::<LogicalPlanNode>(
&state.scheduler_host,
state.scheduler_port,
state.config(),
)
};
let is_show = self.is_show_statement(sql).await?;
// the show tables、 show columns sql can not run at scheduler because the tables is store at client
if is_show {
let state = self.state.lock();
ctx = ExecutionContext::with_config(
ExecutionConfig::new().with_information_schema(
state.config.default_with_information_schema(),
),
);
}
// register tables with DataFusion context
{
let state = self.state.lock();
for (name, prov) in &state.tables {
ctx.register_table(
TableReference::Bare { table: name },
Arc::clone(prov),
)?;
}
}
let plan = ctx.create_logical_plan(sql)?;
match plan {
LogicalPlan::CreateExternalTable(CreateExternalTable {
ref schema,
ref name,
ref location,
ref file_type,
ref has_header,
}) => match file_type {
FileType::CSV => {
self.register_csv(
name,
location,
CsvReadOptions::new()
.schema(&schema.as_ref().to_owned().into())
.has_header(*has_header),
)
.await?;
Ok(Arc::new(DataFrameImpl::new(ctx.state, &plan)))
}
FileType::Parquet => {
self.register_parquet(name, location).await?;
Ok(Arc::new(DataFrameImpl::new(ctx.state, &plan)))
}
FileType::Avro => {
self.register_avro(name, location, AvroReadOptions::default())
.await?;
Ok(Arc::new(DataFrameImpl::new(ctx.state, &plan)))
}
_ => Err(DataFusionError::NotImplemented(format!(
"Unsupported file type {:?}.",
file_type
))),
},
_ => ctx.sql(sql).await,
}
}
}
#[cfg(test)]
mod tests {
#[tokio::test]
#[cfg(feature = "standalone")]
async fn test_standalone_mode() {
use super::*;
let context = BallistaContext::standalone(&BallistaConfig::new().unwrap(), 1)
.await
.unwrap();
let df = context.sql("SELECT 1;").await.unwrap();
df.collect().await.unwrap();
}
#[tokio::test]
#[cfg(feature = "standalone")]
async fn test_ballista_show_tables() {
use super::*;
use std::fs::File;
use std::io::Write;
use tempfile::TempDir;
let context = BallistaContext::standalone(&BallistaConfig::new().unwrap(), 1)
.await
.unwrap();
let data = "Jorge,2018-12-13T12:12:10.011Z\n\
Andrew,2018-11-13T17:11:10.011Z";
let tmp_dir = TempDir::new().unwrap();
let file_path = tmp_dir.path().join("timestamps.csv");
// scope to ensure the file is closed and written
{
File::create(&file_path)
.expect("creating temp file")
.write_all(data.as_bytes())
.expect("writing data");
}
let sql = format!(
"CREATE EXTERNAL TABLE csv_with_timestamps (
name VARCHAR,
ts TIMESTAMP
)
STORED AS CSV
LOCATION '{}'
",
file_path.to_str().expect("path is utf8")
);
context.sql(sql.as_str()).await.unwrap();
let df = context.sql("show columns from csv_with_timestamps;").await;
assert!(df.is_err());
}
#[tokio::test]
#[cfg(feature = "standalone")]
async fn test_show_tables_not_with_information_schema() {
use super::*;
use ballista_core::config::{
BallistaConfigBuilder, BALLISTA_WITH_INFORMATION_SCHEMA,
};
use std::fs::File;
use std::io::Write;
use tempfile::TempDir;
let config = BallistaConfigBuilder::default()
.set(BALLISTA_WITH_INFORMATION_SCHEMA, "true")
.build()
.unwrap();
let context = BallistaContext::standalone(&config, 1).await.unwrap();
let data = "Jorge,2018-12-13T12:12:10.011Z\n\
Andrew,2018-11-13T17:11:10.011Z";
let tmp_dir = TempDir::new().unwrap();
let file_path = tmp_dir.path().join("timestamps.csv");
// scope to ensure the file is closed and written
{
File::create(&file_path)
.expect("creating temp file")
.write_all(data.as_bytes())
.expect("writing data");
}
let sql = format!(
"CREATE EXTERNAL TABLE csv_with_timestamps (
name VARCHAR,
ts TIMESTAMP
)
STORED AS CSV
LOCATION '{}'
",
file_path.to_str().expect("path is utf8")
);
context.sql(sql.as_str()).await.unwrap();
let df = context.sql("show tables;").await;
assert!(df.is_ok());
}
#[tokio::test]
#[cfg(feature = "standalone")]
#[ignore]
// Tracking: https://github.com/apache/arrow-datafusion/issues/1840
async fn test_task_stuck_when_referenced_task_failed() {
use super::*;
use datafusion::arrow::datatypes::Schema;
use datafusion::arrow::util::pretty;
use datafusion::datasource::file_format::csv::CsvFormat;
use datafusion::datasource::file_format::parquet::ParquetFormat;
use datafusion::datasource::listing::{
ListingOptions, ListingTable, ListingTableConfig,
};
use ballista_core::config::{
BallistaConfigBuilder, BALLISTA_WITH_INFORMATION_SCHEMA,
};
use std::fs::File;
use std::io::Write;
use tempfile::TempDir;
let config = BallistaConfigBuilder::default()
.set(BALLISTA_WITH_INFORMATION_SCHEMA, "true")
.build()
.unwrap();
let context = BallistaContext::standalone(&config, 1).await.unwrap();
let testdata = datafusion::test_util::parquet_test_data();
context
.register_parquet("single_nan", &format!("{}/single_nan.parquet", testdata))
.await
.unwrap();
{
let mut guard = context.state.lock();
let csv_table = guard.tables.get("single_nan");
if let Some(table_provide) = csv_table {
if let Some(listing_table) = table_provide
.clone()
.as_any()
.downcast_ref::<ListingTable>()
{
let x = listing_table.options();
let error_options = ListingOptions {
file_extension: x.file_extension.clone(),
format: Arc::new(CsvFormat::default()),
table_partition_cols: x.table_partition_cols.clone(),
collect_stat: x.collect_stat,
target_partitions: x.target_partitions,
};
let config = ListingTableConfig::new(
listing_table.object_store().clone(),
listing_table.table_path().to_string(),
)
.with_schema(Arc::new(Schema::new(vec![])))
.with_listing_options(error_options);
let error_table = ListingTable::try_new(config).unwrap();
// change the table to an error table
guard
.tables
.insert("single_nan".to_string(), Arc::new(error_table));
}
}
}
let df = context
.sql("select count(1) from single_nan;")
.await
.unwrap();
let results = df.collect().await.unwrap();
pretty::print_batches(&results);
}
#[tokio::test]
#[cfg(feature = "standalone")]
async fn test_empty_exec_with_one_row() {
use crate::context::BallistaContext;
use ballista_core::config::{
BallistaConfigBuilder, BALLISTA_WITH_INFORMATION_SCHEMA,
};
let config = BallistaConfigBuilder::default()
.set(BALLISTA_WITH_INFORMATION_SCHEMA, "true")
.build()
.unwrap();
let context = BallistaContext::standalone(&config, 1).await.unwrap();
let sql = "select EXTRACT(year FROM to_timestamp('2020-09-08T12:13:14+00:00'));";
let df = context.sql(sql).await.unwrap();
assert!(!df.collect().await.unwrap().is_empty());
}
} | default_codec,
) |
__init__.py | import os
import enum
def __init__():
global __all__
global arch
import sys
import importlib
__all__ = []
arch = dict()
CurModule = sys.modules[__name__]
for entry in os.listdir(os.path.dirname(__file__)):
if os.path.isdir(os.path.dirname(__file__) + "/" + entry):
__all__.append(entry)
arch[entry] = importlib.import_module("architectures." + entry)
arch[entry].architectures = CurModule
def | (Arch, Config, Filename):
#see if the input file is different than the output file, if so then recompile it via make
Recompile = False
CurPath = os.path.dirname(os.path.abspath(__file__))
if os.path.isfile("%s/%s/patches/patch_%s.bin" % (CurPath, Arch, Filename)) == False:
Recompile = True
elif not os.path.isfile("%s/%s/patches/patch_%s.S" % (CurPath, Arch, Filename)):
print "Error finding %s/patches/patch_%s.S" % (Arch, Filename)
return -1
else:
InStat = os.stat("%s/%s/patches/patch_%s.S" % (CurPath, Arch, Filename))
OutStat = os.stat("%s/%s/patches/patch_%s.bin" % (CurPath, Arch, Filename))
#if our time is newer then recompile
if InStat.st_mtime > OutStat.st_mtime:
Recompile = True
os.unlink("%s/%s/patches/patch_%s.bin" % (CurPath, Arch, Filename))
#if we need to recompile then do so
if Recompile:
import subprocess
s = subprocess.Popen(["make", "-C", "%s/%s/patches" % (CurPath, Arch), "INCLUDE=" + Config, "NAME=" + Filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
ret = s.wait()
if (ret != 0) or (not os.path.isfile("%s/%s/patches/patch_%s.bin" % (CurPath, Arch, Filename))):
print "Error compiling %s/patches/patch_%s.bin" % (Arch, Filename)
stdoutdata, stderrdata = s.communicate()
print("STDOUT:\n{}\n\nSTDERR:{}\n".format(stdoutdata, stderrdata))
return -1
return 0
__init__()
| RecompileIfChanged |
utils.rs | use process_control::{ChildExt, Control};
use std::ffi::OsStr;
use std::fmt::Debug;
use std::fs::read_to_string;
use std::io::{Error, ErrorKind, Result};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
use crate::context::Shell;
/// Return the string contents of a file
pub fn read_file<P: AsRef<Path> + Debug>(file_name: P) -> Result<String> {
log::trace!("Trying to read from {:?}", file_name);
let result = read_to_string(file_name);
if result.is_err() {
log::debug!("Error reading file: {:?}", result);
} else {
log::trace!("File read successfully");
};
result
}
/// Reads command output from stderr or stdout depending on to which stream program streamed it's output
pub fn get_command_string_output(command: CommandOutput) -> String {
if command.stdout.is_empty() {
command.stderr
} else {
command.stdout
}
}
/// Attempt to resolve `binary_name` from and creates a new `Command` pointing at it
/// This allows executing cmd files on Windows and prevents running executable from cwd on Windows
/// This function also initialises std{err,out,in} to protect against processes changing the console mode
pub fn create_command<T: AsRef<OsStr>>(binary_name: T) -> Result<Command> {
let binary_name = binary_name.as_ref();
log::trace!("Creating Command for binary {:?}", binary_name);
let full_path = match which::which(binary_name) {
Ok(full_path) => {
log::trace!("Using {:?} as {:?}", full_path, binary_name);
full_path
}
Err(error) => {
log::trace!("Unable to find {:?} in PATH, {:?}", binary_name, error);
return Err(Error::new(ErrorKind::NotFound, error));
}
};
#[allow(clippy::disallowed_method)]
let mut cmd = Command::new(full_path);
cmd.stderr(Stdio::piped())
.stdout(Stdio::piped())
.stdin(Stdio::null());
Ok(cmd)
}
#[derive(Debug, Clone)]
pub struct CommandOutput {
pub stdout: String,
pub stderr: String,
}
impl PartialEq for CommandOutput {
fn eq(&self, other: &Self) -> bool {
self.stdout == other.stdout && self.stderr == other.stderr
}
}
#[cfg(test)]
pub fn display_command<T: AsRef<OsStr> + Debug, U: AsRef<OsStr> + Debug>(
cmd: T,
args: &[U],
) -> String {
std::iter::once(cmd.as_ref())
.chain(args.iter().map(|i| i.as_ref()))
.map(|i| i.to_string_lossy().into_owned())
.collect::<Vec<String>>()
.join(" ")
}
/// Execute a command and return the output on stdout and stderr if successful
pub fn exec_cmd<T: AsRef<OsStr> + Debug, U: AsRef<OsStr> + Debug>(
cmd: T,
args: &[U],
time_limit: Duration,
) -> Option<CommandOutput> {
log::trace!("Executing command {:?} with args {:?}", cmd, args);
#[cfg(test)]
if let Some(o) = mock_cmd(&cmd, args) {
return o;
}
internal_exec_cmd(cmd, args, time_limit)
}
#[cfg(test)]
pub fn mock_cmd<T: AsRef<OsStr> + Debug, U: AsRef<OsStr> + Debug>(
cmd: T,
args: &[U],
) -> Option<Option<CommandOutput>> {
let command = display_command(&cmd, args);
let out = match command.as_str() {
"cobc -version" => Some(CommandOutput {
stdout: String::from("\
cobc (GnuCOBOL) 3.1.2.0
Copyright (C) 2020 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Written by Keisuke Nishida, Roger While, Ron Norman, Simon Sobisch, Edward Hart
Built Dec 24 2020 19:08:58
Packaged Dec 23 2020 12:04:58 UTC
C version \"10.2.0\""),
stderr: String::default(),
}),
"crystal --version" => Some(CommandOutput {
stdout: String::from(
"\
Crystal 0.35.1 (2020-06-19)
LLVM: 10.0.0
Default target: x86_64-apple-macosx\n",
),
stderr: String::default(),
}),
"dart --version" => Some(CommandOutput {
stdout: String::default(),
stderr: String::from(
"Dart VM version: 2.8.4 (stable) (Wed Jun 3 12:26:04 2020 +0200) on \"macos_x64\"",
),
}),
"deno -V" => Some(CommandOutput {
stdout: String::from("deno 1.8.3\n"),
stderr: String::default()
}),
"dummy_command" => Some(CommandOutput {
stdout: String::from("stdout ok!\n"),
stderr: String::from("stderr ok!\n"),
}),
"elixir --version" => Some(CommandOutput {
stdout: String::from(
"\
Erlang/OTP 22 [erts-10.6.4] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [hipe]
Elixir 1.10 (compiled with Erlang/OTP 22)\n",
),
stderr: String::default(),
}),
"elm --version" => Some(CommandOutput {
stdout: String::from("0.19.1\n"),
stderr: String::default(),
}),
"go version" => Some(CommandOutput {
stdout: String::from("go version go1.12.1 linux/amd64\n"),
stderr: String::default(),
}),
"helm version --short --client" => Some(CommandOutput {
stdout: String::from("v3.1.1+gafe7058\n"),
stderr: String::default(),
}),
s if s.ends_with("java -Xinternalversion") => Some(CommandOutput {
stdout: String::from("OpenJDK 64-Bit Server VM (13.0.2+8) for bsd-amd64 JRE (13.0.2+8), built on Feb 6 2020 02:07:52 by \"brew\" with clang 4.2.1 Compatible Apple LLVM 11.0.0 (clang-1100.0.33.17)"),
stderr: String::default(),
}),
"scalac -version" => Some(CommandOutput {
stdout: String::from("Scala compiler version 2.13.5 -- Copyright 2002-2020, LAMP/EPFL and Lightbend, Inc."),
stderr: String::default(),
}),
"julia --version" => Some(CommandOutput {
stdout: String::from("julia version 1.4.0\n"),
stderr: String::default(),
}),
"kotlin -version" => Some(CommandOutput {
stdout: String::from("Kotlin version 1.4.21-release-411 (JRE 14.0.1+7)\n"),
stderr: String::default(),
}),
"kotlinc -version" => Some(CommandOutput {
stdout: String::from("info: kotlinc-jvm 1.4.21 (JRE 14.0.1+7)\n"),
stderr: String::default(),
}),
"lua -v" => Some(CommandOutput{
stdout: String::from("Lua 5.4.0 Copyright (C) 1994-2020 Lua.org, PUC-Rio\n"),
stderr: String::default(),
}),
"luajit -v" => Some(CommandOutput{
stdout: String::from("LuaJIT 2.0.5 -- Copyright (C) 2005-2017 Mike Pall. http://luajit.org/\n"),
stderr: String::default(),
}),
"nim --version" => Some(CommandOutput {
stdout: String::from(
"\
Nim Compiler Version 1.2.0 [Linux: amd64]
Compiled at 2020-04-03
Copyright (c) 2006-2020 by Andreas Rumpf
git hash: 7e83adff84be5d0c401a213eccb61e321a3fb1ff
active boot switches: -d:release\n",
),
stderr: String::default(),
}),
"node --version" => Some(CommandOutput {
stdout: String::from("v12.0.0\n"),
stderr: String::default(),
}),
"ocaml -vnum" => Some(CommandOutput {
stdout: String::from("4.10.0\n"),
stderr: String::default(),
}),
"opam switch show --safe" => Some(CommandOutput {
stdout: String::from("default\n"),
stderr: String::default(),
}),
"esy ocaml -vnum" => Some(CommandOutput {
stdout: String::from("4.08.1\n"),
stderr: String::default(),
}),
"perl -e printf q#%vd#,$^V;" => Some(CommandOutput {
stdout: String::from("5.26.1"),
stderr: String::default(),
}),
"php -nr echo PHP_MAJOR_VERSION.\".\".PHP_MINOR_VERSION.\".\".PHP_RELEASE_VERSION;" => {
Some(CommandOutput {
stdout: String::from("7.3.8"),
stderr: String::default(),
})
},
"pulumi version" => Some(CommandOutput{
stdout: String::from("1.2.3-ver.1631311768+e696fb6c"),
stderr: String::default(),
}),
"purs --version" => Some(CommandOutput {
stdout: String::from("0.13.5\n"),
stderr: String::default(),
}),
"pyenv version-name" => Some(CommandOutput {
stdout: String::from("system\n"),
stderr: String::default(),
}),
"python --version" => None,
"python2 --version" => Some(CommandOutput {
stdout: String::default(),
stderr: String::from("Python 2.7.17\n"),
}),
"python3 --version" => Some(CommandOutput {
stdout: String::from("Python 3.8.0\n"),
stderr: String::default(),
}),
"R --version" => Some(CommandOutput {
stdout: String::default(),
stderr: String::from(
r#"R version 4.1.0 (2021-05-18) -- "Camp Pontanezen"
Copyright (C) 2021 The R Foundation for Statistical Computing
Platform: x86_64-w64-mingw32/x64 (64-bit)\n
R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under the terms of the
GNU General Public License versions 2 or 3.
For more information about these matters see
https://www.gnu.org/licenses/."#
),
}),
"red --version" => Some(CommandOutput {
stdout: String::from("0.6.4\n"),
stderr: String::default()
}),
"ruby -v" => Some(CommandOutput {
stdout: String::from("ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-linux-gnu]\n"),
stderr: String::default(),
}),
"swift --version" => Some(CommandOutput {
stdout: String::from(
"\
Apple Swift version 5.2.2 (swiftlang-1103.0.32.6 clang-1103.0.32.51)
Target: x86_64-apple-darwin19.4.0\n",
),
stderr: String::default(),
}),
"vagrant --version" => Some(CommandOutput {
stdout: String::from("Vagrant 2.2.10\n"),
stderr: String::default(),
}),
"v version" => Some(CommandOutput {
stdout: String::from("V 0.2 30c0659"),
stderr: String::default()
}),
"zig version" => Some(CommandOutput {
stdout: String::from("0.6.0\n"),
stderr: String::default(),
}),
"cmake --version" => Some(CommandOutput {
stdout: String::from(
"\
cmake version 3.17.3
CMake suite maintained and supported by Kitware (kitware.com/cmake).\n",
),
stderr: String::default(),
}),
"dotnet --version" => Some(CommandOutput {
stdout: String::from("3.1.103"),
stderr: String::default(),
}),
"dotnet --list-sdks" => Some(CommandOutput {
stdout: String::from("3.1.103 [/usr/share/dotnet/sdk]"),
stderr: String::default(),
}),
"terraform version" => Some(CommandOutput {
stdout: String::from("Terraform v0.12.14\n"),
stderr: String::default(),
}),
s if s.starts_with("erl -noshell -eval") => Some(CommandOutput {
stdout: String::from("22.1.3\n"),
stderr: String::default(),
}),
_ => return None,
};
Some(out)
}
/// Wraps ANSI color escape sequences in the shell-appropriate wrappers.
pub fn wrap_colorseq_for_shell(ansi: String, shell: Shell) -> String {
const ESCAPE_BEGIN: char = '\u{1b}';
const ESCAPE_END: char = 'm';
wrap_seq_for_shell(ansi, shell, ESCAPE_BEGIN, ESCAPE_END)
}
/// Many shells cannot deal with raw unprintable characters and miscompute the cursor position,
/// leading to strange visual bugs like duplicated/missing chars. This function wraps a specified
/// sequence in shell-specific escapes to avoid these problems.
pub fn | (
ansi: String,
shell: Shell,
escape_begin: char,
escape_end: char,
) -> String {
const BASH_BEG: &str = "\u{5c}\u{5b}"; // \[
const BASH_END: &str = "\u{5c}\u{5d}"; // \]
const ZSH_BEG: &str = "\u{25}\u{7b}"; // %{
const ZSH_END: &str = "\u{25}\u{7d}"; // %}
const TCSH_BEG: &str = "\u{25}\u{7b}"; // %{
const TCSH_END: &str = "\u{25}\u{7d}"; // %}
// ANSI escape codes cannot be nested, so we can keep track of whether we're
// in an escape or not with a single boolean variable
let mut escaped = false;
let final_string: String = ansi
.chars()
.map(|x| {
if x == escape_begin && !escaped {
escaped = true;
match shell {
Shell::Bash => format!("{}{}", BASH_BEG, escape_begin),
Shell::Zsh => format!("{}{}", ZSH_BEG, escape_begin),
Shell::Tcsh => format!("{}{}", TCSH_BEG, escape_begin),
_ => x.to_string(),
}
} else if x == escape_end && escaped {
escaped = false;
match shell {
Shell::Bash => format!("{}{}", escape_end, BASH_END),
Shell::Zsh => format!("{}{}", escape_end, ZSH_END),
Shell::Tcsh => format!("{}{}", escape_end, TCSH_END),
_ => x.to_string(),
}
} else {
x.to_string()
}
})
.collect();
final_string
}
fn internal_exec_cmd<T: AsRef<OsStr> + Debug, U: AsRef<OsStr> + Debug>(
cmd: T,
args: &[U],
time_limit: Duration,
) -> Option<CommandOutput> {
let mut cmd = create_command(cmd).ok()?;
cmd.args(args);
exec_timeout(&mut cmd, time_limit)
}
pub fn exec_timeout(cmd: &mut Command, time_limit: Duration) -> Option<CommandOutput> {
let start = Instant::now();
let process = match cmd.spawn() {
Ok(process) => process,
Err(error) => {
log::info!("Unable to run {:?}, {:?}", cmd.get_program(), error);
return None;
}
};
match process
.controlled_with_output()
.time_limit(time_limit)
.terminate_for_timeout()
.wait()
{
Ok(Some(output)) => {
let stdout_string = match String::from_utf8(output.stdout) {
Ok(stdout) => stdout,
Err(error) => {
log::warn!("Unable to decode stdout: {:?}", error);
return None;
}
};
let stderr_string = match String::from_utf8(output.stderr) {
Ok(stderr) => stderr,
Err(error) => {
log::warn!("Unable to decode stderr: {:?}", error);
return None;
}
};
log::trace!(
"stdout: {:?}, stderr: {:?}, exit code: \"{:?}\", took {:?}",
stdout_string,
stderr_string,
output.status.code(),
start.elapsed()
);
if !output.status.success() {
return None;
}
Some(CommandOutput {
stdout: stdout_string,
stderr: stderr_string,
})
}
Ok(None) => {
log::warn!("Executing command {:?} timed out.", cmd.get_program());
log::warn!("You can set command_timeout in your config to a higher value to allow longer-running commands to keep executing.");
None
}
Err(error) => {
log::info!(
"Executing command {:?} failed by: {:?}",
cmd.get_program(),
error
);
None
}
}
}
// Render the time into a nice human-readable string
pub fn render_time(raw_millis: u128, show_millis: bool) -> String {
// Make sure it renders something if the time equals zero instead of an empty string
if raw_millis == 0 {
return "0ms".into();
}
// Calculate a simple breakdown into days/hours/minutes/seconds/milliseconds
let (millis, raw_seconds) = (raw_millis % 1000, raw_millis / 1000);
let (seconds, raw_minutes) = (raw_seconds % 60, raw_seconds / 60);
let (minutes, raw_hours) = (raw_minutes % 60, raw_minutes / 60);
let (hours, days) = (raw_hours % 24, raw_hours / 24);
let components = [days, hours, minutes, seconds];
let suffixes = ["d", "h", "m", "s"];
let mut rendered_components: Vec<String> = components
.iter()
.zip(&suffixes)
.map(render_time_component)
.collect();
if show_millis || raw_millis < 1000 {
rendered_components.push(render_time_component((&millis, &"ms")));
}
rendered_components.join("")
}
/// Render a single component of the time string, giving an empty string if component is zero
fn render_time_component((component, suffix): (&u128, &&str)) -> String {
match component {
0 => String::new(),
n => format!("{}{}", n, suffix),
}
}
pub fn home_dir() -> Option<PathBuf> {
directories_next::BaseDirs::new().map(|base_dirs| base_dirs.home_dir().to_owned())
}
const HEXTABLE: &[char] = &[
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
];
/// Encode a u8 slice into a hexadecimal string.
pub fn encode_to_hex(slice: &[u8]) -> String {
// let mut j = 0;
let mut dst = Vec::with_capacity(slice.len() * 2);
for &v in slice {
dst.push(HEXTABLE[(v >> 4) as usize] as u8);
dst.push(HEXTABLE[(v & 0x0f) as usize] as u8);
}
String::from_utf8(dst).unwrap()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_0ms() {
assert_eq!(render_time(0_u128, true), "0ms")
}
#[test]
fn test_500ms() {
assert_eq!(render_time(500_u128, true), "500ms")
}
#[test]
fn test_10s() {
assert_eq!(render_time(10_000_u128, true), "10s")
}
#[test]
fn test_90s() {
assert_eq!(render_time(90_000_u128, true), "1m30s")
}
#[test]
fn test_10110s() {
assert_eq!(render_time(10_110_000_u128, true), "2h48m30s")
}
#[test]
fn test_1d() {
assert_eq!(render_time(86_400_000_u128, true), "1d")
}
#[test]
fn exec_mocked_command() {
let result = exec_cmd(
"dummy_command",
&[] as &[&OsStr],
Duration::from_millis(500),
);
let expected = Some(CommandOutput {
stdout: String::from("stdout ok!\n"),
stderr: String::from("stderr ok!\n"),
});
assert_eq!(result, expected)
}
// While the exec_cmd should work on Windows some of these tests assume a Unix-like
// environment.
#[test]
#[cfg(not(windows))]
fn exec_no_output() {
let result = internal_exec_cmd("true", &[] as &[&OsStr], Duration::from_millis(500));
let expected = Some(CommandOutput {
stdout: String::from(""),
stderr: String::from(""),
});
assert_eq!(result, expected)
}
#[test]
#[cfg(not(windows))]
fn exec_with_output_stdout() {
let result =
internal_exec_cmd("/bin/sh", &["-c", "echo hello"], Duration::from_millis(500));
let expected = Some(CommandOutput {
stdout: String::from("hello\n"),
stderr: String::from(""),
});
assert_eq!(result, expected)
}
#[test]
#[cfg(not(windows))]
fn exec_with_output_stderr() {
let result = internal_exec_cmd(
"/bin/sh",
&["-c", "echo hello >&2"],
Duration::from_millis(500),
);
let expected = Some(CommandOutput {
stdout: String::from(""),
stderr: String::from("hello\n"),
});
assert_eq!(result, expected)
}
#[test]
#[cfg(not(windows))]
fn exec_with_output_both() {
let result = internal_exec_cmd(
"/bin/sh",
&["-c", "echo hello; echo world >&2"],
Duration::from_millis(500),
);
let expected = Some(CommandOutput {
stdout: String::from("hello\n"),
stderr: String::from("world\n"),
});
assert_eq!(result, expected)
}
#[test]
#[cfg(not(windows))]
fn exec_with_non_zero_exit_code() {
let result = internal_exec_cmd("false", &[] as &[&OsStr], Duration::from_millis(500));
let expected = None;
assert_eq!(result, expected)
}
#[test]
#[cfg(not(windows))]
fn exec_slow_command() {
let result = internal_exec_cmd("sleep", &["500"], Duration::from_millis(500));
let expected = None;
assert_eq!(result, expected)
}
#[test]
fn test_color_sequence_wrappers() {
let test0 = "\x1b2mhellomynamekeyes\x1b2m"; // BEGIN: \x1b END: m
let test1 = "\x1b]330;mlol\x1b]0m"; // BEGIN: \x1b END: m
let test2 = "\u{1b}J"; // BEGIN: \x1b END: J
let test3 = "OH NO"; // BEGIN: O END: O
let test4 = "herpaderp";
let test5 = "";
let zresult0 = wrap_seq_for_shell(test0.to_string(), Shell::Zsh, '\x1b', 'm');
let zresult1 = wrap_seq_for_shell(test1.to_string(), Shell::Zsh, '\x1b', 'm');
let zresult2 = wrap_seq_for_shell(test2.to_string(), Shell::Zsh, '\x1b', 'J');
let zresult3 = wrap_seq_for_shell(test3.to_string(), Shell::Zsh, 'O', 'O');
let zresult4 = wrap_seq_for_shell(test4.to_string(), Shell::Zsh, '\x1b', 'm');
let zresult5 = wrap_seq_for_shell(test5.to_string(), Shell::Zsh, '\x1b', 'm');
assert_eq!(&zresult0, "%{\x1b2m%}hellomynamekeyes%{\x1b2m%}");
assert_eq!(&zresult1, "%{\x1b]330;m%}lol%{\x1b]0m%}");
assert_eq!(&zresult2, "%{\x1bJ%}");
assert_eq!(&zresult3, "%{OH NO%}");
assert_eq!(&zresult4, "herpaderp");
assert_eq!(&zresult5, "");
let bresult0 = wrap_seq_for_shell(test0.to_string(), Shell::Bash, '\x1b', 'm');
let bresult1 = wrap_seq_for_shell(test1.to_string(), Shell::Bash, '\x1b', 'm');
let bresult2 = wrap_seq_for_shell(test2.to_string(), Shell::Bash, '\x1b', 'J');
let bresult3 = wrap_seq_for_shell(test3.to_string(), Shell::Bash, 'O', 'O');
let bresult4 = wrap_seq_for_shell(test4.to_string(), Shell::Bash, '\x1b', 'm');
let bresult5 = wrap_seq_for_shell(test5.to_string(), Shell::Bash, '\x1b', 'm');
assert_eq!(&bresult0, "\\[\x1b2m\\]hellomynamekeyes\\[\x1b2m\\]");
assert_eq!(&bresult1, "\\[\x1b]330;m\\]lol\\[\x1b]0m\\]");
assert_eq!(&bresult2, "\\[\x1bJ\\]");
assert_eq!(&bresult3, "\\[OH NO\\]");
assert_eq!(&bresult4, "herpaderp");
assert_eq!(&bresult5, "");
}
#[test]
fn test_get_command_string_output() {
let case1 = CommandOutput {
stdout: String::from("stdout"),
stderr: String::from("stderr"),
};
assert_eq!(get_command_string_output(case1), "stdout");
let case2 = CommandOutput {
stdout: String::from(""),
stderr: String::from("stderr"),
};
assert_eq!(get_command_string_output(case2), "stderr");
}
#[test]
fn sha1_hex() {
assert_eq!(
encode_to_hex(&[8, 13, 9, 189, 129, 94]),
"080d09bd815e".to_string()
);
}
}
| wrap_seq_for_shell |
launcher.py | import pickle
import plaidrl.torch.pytorch_util as ptu
from plaidrl.core import logger
from plaidrl.core.meta_rl_algorithm import MetaRLAlgorithm
from plaidrl.core.simple_offline_rl_algorithm import OfflineMetaRLAlgorithm
from plaidrl.data_management.env_replay_buffer import EnvReplayBuffer
from plaidrl.demos.source.mdp_path_loader import MDPPathLoader
from plaidrl.envs.pearl_envs import ENVS, register_pearl_envs
from plaidrl.envs.wrappers import NormalizedBoxEnv
from plaidrl.torch.networks import ConcatMlp
from plaidrl.torch.smac.agent import SmacAgent
from plaidrl.torch.smac.diagnostics import get_env_info_sizes
from plaidrl.torch.smac.launcher_util import (
EvalPearl,
load_buffer_onto_algo,
load_macaw_buffer_onto_algo,
policy_class_from_str,
relabel_offline_data,
)
from plaidrl.torch.smac.networks import DummyMlpEncoder, MlpDecoder, MlpEncoder
from plaidrl.torch.smac.smac import SmacTrainer
from plaidrl.util.io import load_local_or_remote_file
def smac_experiment(
trainer_kwargs=None,
algo_kwargs=None,
qf_kwargs=None,
policy_kwargs=None,
context_encoder_kwargs=None,
context_decoder_kwargs=None,
env_name=None,
env_params=None,
path_loader_kwargs=None,
latent_dim=None,
policy_class="TanhGaussianPolicy",
# video/debug
debug=False,
use_dummy_encoder=False,
networks_ignore_context=False,
use_ground_truth_context=False,
save_video=False,
save_video_period=False,
# Pre-train params
pretrain_rl=False,
pretrain_offline_algo_kwargs=None,
pretrain_buffer_kwargs=None,
load_buffer_kwargs=None,
saved_tasks_path=None,
macaw_format_base_path=None, # overrides saved_tasks_path and load_buffer_kwargs
load_macaw_buffer_kwargs=None,
train_task_idxs=None,
eval_task_idxs=None,
relabel_offline_dataset=False,
skip_initial_data_collection_if_pretrained=False,
relabel_kwargs=None,
# PEARL
n_train_tasks=0,
n_eval_tasks=0,
use_next_obs_in_context=False,
tags=None,
online_trainer_kwargs=None,
):
| if not skip_initial_data_collection_if_pretrained:
raise NotImplementedError("deprecated! make sure to skip it!")
if relabel_kwargs is None:
relabel_kwargs = {}
del tags
pretrain_buffer_kwargs = pretrain_buffer_kwargs or {}
context_decoder_kwargs = context_decoder_kwargs or {}
pretrain_offline_algo_kwargs = pretrain_offline_algo_kwargs or {}
online_trainer_kwargs = online_trainer_kwargs or {}
register_pearl_envs()
env_params = env_params or {}
context_encoder_kwargs = context_encoder_kwargs or {}
trainer_kwargs = trainer_kwargs or {}
path_loader_kwargs = path_loader_kwargs or {}
load_macaw_buffer_kwargs = load_macaw_buffer_kwargs or {}
base_env = ENVS[env_name](**env_params)
if saved_tasks_path:
task_data = load_local_or_remote_file(saved_tasks_path, file_type="joblib")
tasks = task_data["tasks"]
train_task_idxs = task_data["train_task_indices"]
eval_task_idxs = task_data["eval_task_indices"]
base_env.tasks = tasks
elif macaw_format_base_path is not None:
tasks = pickle.load(open("{}/tasks.pkl".format(macaw_format_base_path), "rb"))
base_env.tasks = tasks
else:
tasks = base_env.tasks
task_indices = base_env.get_all_task_idx()
train_task_idxs = list(task_indices[:n_train_tasks])
eval_task_idxs = list(task_indices[-n_eval_tasks:])
if hasattr(base_env, "task_to_vec"):
train_tasks = [base_env.task_to_vec(tasks[i]) for i in train_task_idxs]
eval_tasks = [base_env.task_to_vec(tasks[i]) for i in eval_task_idxs]
else:
train_tasks = [tasks[i] for i in train_task_idxs]
eval_tasks = [tasks[i] for i in eval_task_idxs]
if use_ground_truth_context:
latent_dim = len(train_tasks[0])
expl_env = NormalizedBoxEnv(base_env)
reward_dim = 1
if debug:
algo_kwargs["max_path_length"] = 50
algo_kwargs["batch_size"] = 5
algo_kwargs["num_epochs"] = 5
algo_kwargs["num_eval_steps_per_epoch"] = 100
algo_kwargs["num_expl_steps_per_train_loop"] = 100
algo_kwargs["num_trains_per_train_loop"] = 10
algo_kwargs["min_num_steps_before_training"] = 100
obs_dim = expl_env.observation_space.low.size
action_dim = expl_env.action_space.low.size
if use_next_obs_in_context:
context_encoder_input_dim = 2 * obs_dim + action_dim + reward_dim
else:
context_encoder_input_dim = obs_dim + action_dim + reward_dim
context_encoder_output_dim = latent_dim * 2
def create_qf():
return ConcatMlp(
input_size=obs_dim + action_dim + latent_dim, output_size=1, **qf_kwargs
)
qf1 = create_qf()
qf2 = create_qf()
target_qf1 = create_qf()
target_qf2 = create_qf()
if isinstance(policy_class, str):
policy_class = policy_class_from_str(policy_class)
policy = policy_class(
obs_dim=obs_dim + latent_dim,
action_dim=action_dim,
**policy_kwargs,
)
encoder_class = DummyMlpEncoder if use_dummy_encoder else MlpEncoder
context_encoder = encoder_class(
input_size=context_encoder_input_dim,
output_size=context_encoder_output_dim,
hidden_sizes=[200, 200, 200],
use_ground_truth_context=use_ground_truth_context,
**context_encoder_kwargs,
)
context_decoder = MlpDecoder(
input_size=obs_dim + action_dim + latent_dim,
output_size=1,
**context_decoder_kwargs,
)
reward_predictor = context_decoder
agent = SmacAgent(
latent_dim,
context_encoder,
policy,
reward_predictor,
use_next_obs_in_context=use_next_obs_in_context,
_debug_ignore_context=networks_ignore_context,
_debug_use_ground_truth_context=use_ground_truth_context,
)
trainer = SmacTrainer(
agent=agent,
env=expl_env,
latent_dim=latent_dim,
qf1=qf1,
qf2=qf2,
target_qf1=target_qf1,
target_qf2=target_qf2,
reward_predictor=reward_predictor,
context_encoder=context_encoder,
context_decoder=context_decoder,
_debug_ignore_context=networks_ignore_context,
_debug_use_ground_truth_context=use_ground_truth_context,
**trainer_kwargs,
)
algorithm = MetaRLAlgorithm(
agent=agent,
env=expl_env,
trainer=trainer,
train_task_indices=train_task_idxs,
eval_task_indices=eval_task_idxs,
train_tasks=train_tasks,
eval_tasks=eval_tasks,
use_next_obs_in_context=use_next_obs_in_context,
use_ground_truth_context=use_ground_truth_context,
env_info_sizes=get_env_info_sizes(expl_env),
**algo_kwargs,
)
if macaw_format_base_path:
load_macaw_buffer_onto_algo(
algo=algorithm,
base_directory=macaw_format_base_path,
train_task_idxs=train_task_idxs,
**load_macaw_buffer_kwargs,
)
elif load_buffer_kwargs:
load_buffer_onto_algo(algorithm, **load_buffer_kwargs)
if relabel_offline_dataset:
relabel_offline_data(
algorithm, tasks=tasks, env=expl_env.wrapped_env, **relabel_kwargs
)
if path_loader_kwargs:
replay_buffer = algorithm.replay_buffer.task_buffers[0]
enc_replay_buffer = algorithm.enc_replay_buffer.task_buffers[0]
demo_test_buffer = EnvReplayBuffer(env=expl_env, **pretrain_buffer_kwargs)
path_loader = MDPPathLoader(
trainer,
replay_buffer=replay_buffer,
demo_train_buffer=enc_replay_buffer,
demo_test_buffer=demo_test_buffer,
**path_loader_kwargs,
)
path_loader.load_demos()
if pretrain_rl:
eval_pearl_fn = EvalPearl(algorithm, train_task_idxs, eval_task_idxs)
pretrain_algo = OfflineMetaRLAlgorithm(
meta_replay_buffer=algorithm.meta_replay_buffer,
replay_buffer=algorithm.replay_buffer,
task_embedding_replay_buffer=algorithm.enc_replay_buffer,
trainer=trainer,
train_tasks=train_task_idxs,
extra_eval_fns=[eval_pearl_fn],
use_meta_learning_buffer=algorithm.use_meta_learning_buffer,
**pretrain_offline_algo_kwargs,
)
pretrain_algo.to(ptu.device)
logger.remove_tabular_output("progress.csv", relative_to_snapshot_dir=True)
logger.add_tabular_output("pretrain.csv", relative_to_snapshot_dir=True)
pretrain_algo.train()
logger.remove_tabular_output("pretrain.csv", relative_to_snapshot_dir=True)
logger.add_tabular_output(
"progress.csv",
relative_to_snapshot_dir=True,
)
if skip_initial_data_collection_if_pretrained:
algorithm.num_initial_steps = 0
algorithm.trainer.configure(**online_trainer_kwargs)
algorithm.to(ptu.device)
algorithm.train() |
|
day07.rs | fn solution<F: Fn(i64) -> i64>(input: &str, calc_fuel: F) -> i64 {
let positions = input
.trim()
.split(',')
.map(|x| x.parse::<i64>().unwrap())
.collect::<Vec<_>>();
let min = *positions.iter().min().unwrap();
let max = *positions.iter().max().unwrap();
(min..max)
.map(|x| positions.iter().map(|i| calc_fuel((i - x).abs())).sum())
.min()
.unwrap()
}
pub fn | (input: &str) -> i64 {
solution(input, |x| x)
}
pub fn part2(input: &str) -> i64 {
solution(input, |x| x * (x + 1) / 2)
}
| part1 |
fake_ciliumclusterwideenvoyconfig.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of Cilium
// Code generated by client-gen. DO NOT EDIT.
package fake
import (
"context"
v2 "github.com/cilium/cilium/pkg/k8s/apis/cilium.io/v2"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
labels "k8s.io/apimachinery/pkg/labels"
schema "k8s.io/apimachinery/pkg/runtime/schema"
types "k8s.io/apimachinery/pkg/types"
watch "k8s.io/apimachinery/pkg/watch"
testing "k8s.io/client-go/testing"
)
// FakeCiliumClusterwideEnvoyConfigs implements CiliumClusterwideEnvoyConfigInterface
type FakeCiliumClusterwideEnvoyConfigs struct {
Fake *FakeCiliumV2
}
var ciliumclusterwideenvoyconfigsResource = schema.GroupVersionResource{Group: "cilium.io", Version: "v2", Resource: "ciliumclusterwideenvoyconfigs"}
var ciliumclusterwideenvoyconfigsKind = schema.GroupVersionKind{Group: "cilium.io", Version: "v2", Kind: "CiliumClusterwideEnvoyConfig"}
// Get takes name of the ciliumClusterwideEnvoyConfig, and returns the corresponding ciliumClusterwideEnvoyConfig object, and an error if there is any.
func (c *FakeCiliumClusterwideEnvoyConfigs) Get(ctx context.Context, name string, options v1.GetOptions) (result *v2.CiliumClusterwideEnvoyConfig, err error) {
obj, err := c.Fake.
Invokes(testing.NewRootGetAction(ciliumclusterwideenvoyconfigsResource, name), &v2.CiliumClusterwideEnvoyConfig{})
if obj == nil {
return nil, err
}
return obj.(*v2.CiliumClusterwideEnvoyConfig), err
}
// List takes label and field selectors, and returns the list of CiliumClusterwideEnvoyConfigs that match those selectors.
func (c *FakeCiliumClusterwideEnvoyConfigs) List(ctx context.Context, opts v1.ListOptions) (result *v2.CiliumClusterwideEnvoyConfigList, err error) {
obj, err := c.Fake.
Invokes(testing.NewRootListAction(ciliumclusterwideenvoyconfigsResource, ciliumclusterwideenvoyconfigsKind, opts), &v2.CiliumClusterwideEnvoyConfigList{})
if obj == nil {
return nil, err
}
label, _, _ := testing.ExtractFromListOptions(opts)
if label == nil {
label = labels.Everything()
}
list := &v2.CiliumClusterwideEnvoyConfigList{ListMeta: obj.(*v2.CiliumClusterwideEnvoyConfigList).ListMeta}
for _, item := range obj.(*v2.CiliumClusterwideEnvoyConfigList).Items {
if label.Matches(labels.Set(item.Labels)) |
}
return list, err
}
// Watch returns a watch.Interface that watches the requested ciliumClusterwideEnvoyConfigs.
func (c *FakeCiliumClusterwideEnvoyConfigs) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {
return c.Fake.
InvokesWatch(testing.NewRootWatchAction(ciliumclusterwideenvoyconfigsResource, opts))
}
// Create takes the representation of a ciliumClusterwideEnvoyConfig and creates it. Returns the server's representation of the ciliumClusterwideEnvoyConfig, and an error, if there is any.
func (c *FakeCiliumClusterwideEnvoyConfigs) Create(ctx context.Context, ciliumClusterwideEnvoyConfig *v2.CiliumClusterwideEnvoyConfig, opts v1.CreateOptions) (result *v2.CiliumClusterwideEnvoyConfig, err error) {
obj, err := c.Fake.
Invokes(testing.NewRootCreateAction(ciliumclusterwideenvoyconfigsResource, ciliumClusterwideEnvoyConfig), &v2.CiliumClusterwideEnvoyConfig{})
if obj == nil {
return nil, err
}
return obj.(*v2.CiliumClusterwideEnvoyConfig), err
}
// Update takes the representation of a ciliumClusterwideEnvoyConfig and updates it. Returns the server's representation of the ciliumClusterwideEnvoyConfig, and an error, if there is any.
func (c *FakeCiliumClusterwideEnvoyConfigs) Update(ctx context.Context, ciliumClusterwideEnvoyConfig *v2.CiliumClusterwideEnvoyConfig, opts v1.UpdateOptions) (result *v2.CiliumClusterwideEnvoyConfig, err error) {
obj, err := c.Fake.
Invokes(testing.NewRootUpdateAction(ciliumclusterwideenvoyconfigsResource, ciliumClusterwideEnvoyConfig), &v2.CiliumClusterwideEnvoyConfig{})
if obj == nil {
return nil, err
}
return obj.(*v2.CiliumClusterwideEnvoyConfig), err
}
// Delete takes name of the ciliumClusterwideEnvoyConfig and deletes it. Returns an error if one occurs.
func (c *FakeCiliumClusterwideEnvoyConfigs) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {
_, err := c.Fake.
Invokes(testing.NewRootDeleteActionWithOptions(ciliumclusterwideenvoyconfigsResource, name, opts), &v2.CiliumClusterwideEnvoyConfig{})
return err
}
// DeleteCollection deletes a collection of objects.
func (c *FakeCiliumClusterwideEnvoyConfigs) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {
action := testing.NewRootDeleteCollectionAction(ciliumclusterwideenvoyconfigsResource, listOpts)
_, err := c.Fake.Invokes(action, &v2.CiliumClusterwideEnvoyConfigList{})
return err
}
// Patch applies the patch and returns the patched ciliumClusterwideEnvoyConfig.
func (c *FakeCiliumClusterwideEnvoyConfigs) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v2.CiliumClusterwideEnvoyConfig, err error) {
obj, err := c.Fake.
Invokes(testing.NewRootPatchSubresourceAction(ciliumclusterwideenvoyconfigsResource, name, pt, data, subresources...), &v2.CiliumClusterwideEnvoyConfig{})
if obj == nil {
return nil, err
}
return obj.(*v2.CiliumClusterwideEnvoyConfig), err
}
| {
list.Items = append(list.Items, item)
} |
dcim_device_types_list_parameters.go | // Code generated by go-swagger; DO NOT EDIT.
// Copyright 2020 The go-netbox 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 dcim
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"time"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
cr "github.com/go-openapi/runtime/client"
"github.com/go-openapi/swag"
strfmt "github.com/go-openapi/strfmt"
)
// NewDcimDeviceTypesListParams creates a new DcimDeviceTypesListParams object
// with the default values initialized.
func NewDcimDeviceTypesListParams() *DcimDeviceTypesListParams {
var ()
return &DcimDeviceTypesListParams{
timeout: cr.DefaultTimeout,
}
}
// NewDcimDeviceTypesListParamsWithTimeout creates a new DcimDeviceTypesListParams object
// with the default values initialized, and the ability to set a timeout on a request
func NewDcimDeviceTypesListParamsWithTimeout(timeout time.Duration) *DcimDeviceTypesListParams {
var ()
return &DcimDeviceTypesListParams{
timeout: timeout,
}
}
// NewDcimDeviceTypesListParamsWithContext creates a new DcimDeviceTypesListParams object
// with the default values initialized, and the ability to set a context for a request
func NewDcimDeviceTypesListParamsWithContext(ctx context.Context) *DcimDeviceTypesListParams {
var ()
return &DcimDeviceTypesListParams{
Context: ctx,
}
}
// NewDcimDeviceTypesListParamsWithHTTPClient creates a new DcimDeviceTypesListParams object
// with the default values initialized, and the ability to set a custom HTTPClient for a request
func NewDcimDeviceTypesListParamsWithHTTPClient(client *http.Client) *DcimDeviceTypesListParams {
var ()
return &DcimDeviceTypesListParams{
HTTPClient: client,
}
}
/*DcimDeviceTypesListParams contains all the parameters to send to the API endpoint
for the dcim device types list operation typically these are written to a http.Request
*/
type DcimDeviceTypesListParams struct {
/*ConsolePorts*/
ConsolePorts *string
/*ConsoleServerPorts*/
ConsoleServerPorts *string
/*Created*/
Created *string
/*CreatedGte*/
CreatedGte *string
/*CreatedLte*/
CreatedLte *string
/*DeviceBays*/
DeviceBays *string
/*ID*/
ID *string
/*IDGt*/
IDGt *string
/*IDGte*/
IDGte *string
/*IDLt*/
IDLt *string
/*IDLte*/
IDLte *string
/*IDN*/
IDN *string
/*Interfaces*/
Interfaces *string
/*IsFullDepth*/
IsFullDepth *string
/*LastUpdated*/
LastUpdated *string
/*LastUpdatedGte*/
LastUpdatedGte *string
/*LastUpdatedLte*/
LastUpdatedLte *string
/*Limit
Number of results to return per page.
*/
Limit *int64
/*Manufacturer*/
Manufacturer *string
/*ManufacturerN*/
ManufacturerN *string
/*ManufacturerID*/
ManufacturerID *string
/*ManufacturerIDN*/
ManufacturerIDN *string
/*Model*/
Model *string
/*ModelIc*/
ModelIc *string
/*ModelIe*/
ModelIe *string
/*ModelIew*/
ModelIew *string
/*ModelIsw*/
ModelIsw *string
/*ModelN*/
ModelN *string
/*ModelNic*/
ModelNic *string
/*ModelNie*/
ModelNie *string
/*ModelNiew*/
ModelNiew *string
/*ModelNisw*/
ModelNisw *string
/*Offset
The initial index from which to return the results.
*/
Offset *int64
/*PartNumber*/
PartNumber *string
/*PartNumberIc*/
PartNumberIc *string
/*PartNumberIe*/
PartNumberIe *string
/*PartNumberIew*/
PartNumberIew *string
/*PartNumberIsw*/
PartNumberIsw *string
/*PartNumberN*/
PartNumberN *string
/*PartNumberNic*/
PartNumberNic *string
/*PartNumberNie*/
PartNumberNie *string
/*PartNumberNiew*/
PartNumberNiew *string
/*PartNumberNisw*/
PartNumberNisw *string
/*PassThroughPorts*/
PassThroughPorts *string
/*PowerOutlets*/
PowerOutlets *string
/*PowerPorts*/
PowerPorts *string
/*Q*/
Q *string
/*Slug*/
Slug *string
/*SlugIc*/
SlugIc *string
/*SlugIe*/
SlugIe *string
/*SlugIew*/
SlugIew *string
/*SlugIsw*/
SlugIsw *string
/*SlugN*/
SlugN *string
/*SlugNic*/
SlugNic *string
/*SlugNie*/
SlugNie *string
/*SlugNiew*/
SlugNiew *string
/*SlugNisw*/
SlugNisw *string
/*SubdeviceRole*/
SubdeviceRole *string
/*SubdeviceRoleN*/
SubdeviceRoleN *string
/*Tag*/
Tag *string
/*TagN*/
TagN *string
/*UHeight*/
UHeight *string
/*UHeightGt*/
UHeightGt *string
/*UHeightGte*/
UHeightGte *string
/*UHeightLt*/
UHeightLt *string
/*UHeightLte*/
UHeightLte *string
/*UHeightN*/
UHeightN *string
timeout time.Duration
Context context.Context
HTTPClient *http.Client
}
// WithTimeout adds the timeout to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithTimeout(timeout time.Duration) *DcimDeviceTypesListParams {
o.SetTimeout(timeout)
return o
}
// SetTimeout adds the timeout to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetTimeout(timeout time.Duration) {
o.timeout = timeout
}
// WithContext adds the context to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithContext(ctx context.Context) *DcimDeviceTypesListParams {
o.SetContext(ctx)
return o
}
// SetContext adds the context to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetContext(ctx context.Context) {
o.Context = ctx
}
// WithHTTPClient adds the HTTPClient to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithHTTPClient(client *http.Client) *DcimDeviceTypesListParams {
o.SetHTTPClient(client)
return o
}
// SetHTTPClient adds the HTTPClient to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithConsolePorts adds the consolePorts to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithConsolePorts(consolePorts *string) *DcimDeviceTypesListParams {
o.SetConsolePorts(consolePorts)
return o
}
// SetConsolePorts adds the consolePorts to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetConsolePorts(consolePorts *string) {
o.ConsolePorts = consolePorts
}
// WithConsoleServerPorts adds the consoleServerPorts to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithConsoleServerPorts(consoleServerPorts *string) *DcimDeviceTypesListParams {
o.SetConsoleServerPorts(consoleServerPorts)
return o
}
// SetConsoleServerPorts adds the consoleServerPorts to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetConsoleServerPorts(consoleServerPorts *string) {
o.ConsoleServerPorts = consoleServerPorts
}
// WithCreated adds the created to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithCreated(created *string) *DcimDeviceTypesListParams {
o.SetCreated(created)
return o
}
// SetCreated adds the created to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetCreated(created *string) {
o.Created = created
}
// WithCreatedGte adds the createdGte to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithCreatedGte(createdGte *string) *DcimDeviceTypesListParams {
o.SetCreatedGte(createdGte)
return o
}
// SetCreatedGte adds the createdGte to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetCreatedGte(createdGte *string) {
o.CreatedGte = createdGte
}
// WithCreatedLte adds the createdLte to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithCreatedLte(createdLte *string) *DcimDeviceTypesListParams {
o.SetCreatedLte(createdLte)
return o
}
// SetCreatedLte adds the createdLte to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetCreatedLte(createdLte *string) {
o.CreatedLte = createdLte
}
// WithDeviceBays adds the deviceBays to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithDeviceBays(deviceBays *string) *DcimDeviceTypesListParams {
o.SetDeviceBays(deviceBays)
return o
}
// SetDeviceBays adds the deviceBays to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetDeviceBays(deviceBays *string) {
o.DeviceBays = deviceBays
}
// WithID adds the id to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithID(id *string) *DcimDeviceTypesListParams {
o.SetID(id)
return o
}
// SetID adds the id to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetID(id *string) {
o.ID = id
}
// WithIDGt adds the iDGt to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithIDGt(iDGt *string) *DcimDeviceTypesListParams {
o.SetIDGt(iDGt)
return o
}
// SetIDGt adds the idGt to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetIDGt(iDGt *string) {
o.IDGt = iDGt
}
// WithIDGte adds the iDGte to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithIDGte(iDGte *string) *DcimDeviceTypesListParams {
o.SetIDGte(iDGte)
return o
}
// SetIDGte adds the idGte to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetIDGte(iDGte *string) {
o.IDGte = iDGte
}
// WithIDLt adds the iDLt to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithIDLt(iDLt *string) *DcimDeviceTypesListParams {
o.SetIDLt(iDLt)
return o
}
// SetIDLt adds the idLt to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetIDLt(iDLt *string) {
o.IDLt = iDLt
}
// WithIDLte adds the iDLte to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithIDLte(iDLte *string) *DcimDeviceTypesListParams {
o.SetIDLte(iDLte)
return o
}
// SetIDLte adds the idLte to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetIDLte(iDLte *string) {
o.IDLte = iDLte
}
// WithIDN adds the iDN to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithIDN(iDN *string) *DcimDeviceTypesListParams {
o.SetIDN(iDN)
return o
}
// SetIDN adds the idN to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetIDN(iDN *string) {
o.IDN = iDN
}
// WithInterfaces adds the interfaces to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithInterfaces(interfaces *string) *DcimDeviceTypesListParams {
o.SetInterfaces(interfaces)
return o
}
// SetInterfaces adds the interfaces to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetInterfaces(interfaces *string) {
o.Interfaces = interfaces
}
// WithIsFullDepth adds the isFullDepth to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithIsFullDepth(isFullDepth *string) *DcimDeviceTypesListParams {
o.SetIsFullDepth(isFullDepth)
return o
}
// SetIsFullDepth adds the isFullDepth to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetIsFullDepth(isFullDepth *string) {
o.IsFullDepth = isFullDepth
}
// WithLastUpdated adds the lastUpdated to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithLastUpdated(lastUpdated *string) *DcimDeviceTypesListParams {
o.SetLastUpdated(lastUpdated)
return o
}
// SetLastUpdated adds the lastUpdated to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetLastUpdated(lastUpdated *string) {
o.LastUpdated = lastUpdated
}
// WithLastUpdatedGte adds the lastUpdatedGte to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithLastUpdatedGte(lastUpdatedGte *string) *DcimDeviceTypesListParams {
o.SetLastUpdatedGte(lastUpdatedGte)
return o
}
// SetLastUpdatedGte adds the lastUpdatedGte to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetLastUpdatedGte(lastUpdatedGte *string) {
o.LastUpdatedGte = lastUpdatedGte
}
// WithLastUpdatedLte adds the lastUpdatedLte to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithLastUpdatedLte(lastUpdatedLte *string) *DcimDeviceTypesListParams {
o.SetLastUpdatedLte(lastUpdatedLte)
return o
}
// SetLastUpdatedLte adds the lastUpdatedLte to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetLastUpdatedLte(lastUpdatedLte *string) {
o.LastUpdatedLte = lastUpdatedLte
}
// WithLimit adds the limit to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithLimit(limit *int64) *DcimDeviceTypesListParams {
o.SetLimit(limit)
return o
}
// SetLimit adds the limit to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetLimit(limit *int64) {
o.Limit = limit
}
// WithManufacturer adds the manufacturer to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithManufacturer(manufacturer *string) *DcimDeviceTypesListParams {
o.SetManufacturer(manufacturer)
return o
}
// SetManufacturer adds the manufacturer to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetManufacturer(manufacturer *string) {
o.Manufacturer = manufacturer
}
// WithManufacturerN adds the manufacturerN to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithManufacturerN(manufacturerN *string) *DcimDeviceTypesListParams {
o.SetManufacturerN(manufacturerN)
return o
}
// SetManufacturerN adds the manufacturerN to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetManufacturerN(manufacturerN *string) {
o.ManufacturerN = manufacturerN
}
// WithManufacturerID adds the manufacturerID to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithManufacturerID(manufacturerID *string) *DcimDeviceTypesListParams {
o.SetManufacturerID(manufacturerID)
return o
}
// SetManufacturerID adds the manufacturerId to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetManufacturerID(manufacturerID *string) {
o.ManufacturerID = manufacturerID
}
// WithManufacturerIDN adds the manufacturerIDN to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithManufacturerIDN(manufacturerIDN *string) *DcimDeviceTypesListParams {
o.SetManufacturerIDN(manufacturerIDN)
return o
}
// SetManufacturerIDN adds the manufacturerIdN to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetManufacturerIDN(manufacturerIDN *string) {
o.ManufacturerIDN = manufacturerIDN
}
// WithModel adds the model to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithModel(model *string) *DcimDeviceTypesListParams {
o.SetModel(model)
return o
}
// SetModel adds the model to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetModel(model *string) {
o.Model = model
}
// WithModelIc adds the modelIc to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithModelIc(modelIc *string) *DcimDeviceTypesListParams {
o.SetModelIc(modelIc)
return o
}
// SetModelIc adds the modelIc to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetModelIc(modelIc *string) {
o.ModelIc = modelIc
}
// WithModelIe adds the modelIe to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithModelIe(modelIe *string) *DcimDeviceTypesListParams {
o.SetModelIe(modelIe)
return o
}
// SetModelIe adds the modelIe to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetModelIe(modelIe *string) {
o.ModelIe = modelIe
}
// WithModelIew adds the modelIew to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithModelIew(modelIew *string) *DcimDeviceTypesListParams {
o.SetModelIew(modelIew)
return o
}
// SetModelIew adds the modelIew to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetModelIew(modelIew *string) {
o.ModelIew = modelIew
}
// WithModelIsw adds the modelIsw to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithModelIsw(modelIsw *string) *DcimDeviceTypesListParams {
o.SetModelIsw(modelIsw)
return o
}
// SetModelIsw adds the modelIsw to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetModelIsw(modelIsw *string) {
o.ModelIsw = modelIsw
}
// WithModelN adds the modelN to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithModelN(modelN *string) *DcimDeviceTypesListParams {
o.SetModelN(modelN)
return o
}
// SetModelN adds the modelN to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetModelN(modelN *string) {
o.ModelN = modelN
}
// WithModelNic adds the modelNic to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithModelNic(modelNic *string) *DcimDeviceTypesListParams {
o.SetModelNic(modelNic)
return o
}
// SetModelNic adds the modelNic to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetModelNic(modelNic *string) {
o.ModelNic = modelNic
}
// WithModelNie adds the modelNie to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithModelNie(modelNie *string) *DcimDeviceTypesListParams {
o.SetModelNie(modelNie)
return o
}
// SetModelNie adds the modelNie to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetModelNie(modelNie *string) {
o.ModelNie = modelNie
}
// WithModelNiew adds the modelNiew to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithModelNiew(modelNiew *string) *DcimDeviceTypesListParams {
o.SetModelNiew(modelNiew)
return o
}
// SetModelNiew adds the modelNiew to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetModelNiew(modelNiew *string) {
o.ModelNiew = modelNiew
}
// WithModelNisw adds the modelNisw to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithModelNisw(modelNisw *string) *DcimDeviceTypesListParams {
o.SetModelNisw(modelNisw)
return o
}
// SetModelNisw adds the modelNisw to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetModelNisw(modelNisw *string) {
o.ModelNisw = modelNisw
}
// WithOffset adds the offset to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithOffset(offset *int64) *DcimDeviceTypesListParams {
o.SetOffset(offset)
return o
}
// SetOffset adds the offset to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetOffset(offset *int64) {
o.Offset = offset
}
// WithPartNumber adds the partNumber to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithPartNumber(partNumber *string) *DcimDeviceTypesListParams {
o.SetPartNumber(partNumber)
return o
}
// SetPartNumber adds the partNumber to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetPartNumber(partNumber *string) {
o.PartNumber = partNumber
}
// WithPartNumberIc adds the partNumberIc to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithPartNumberIc(partNumberIc *string) *DcimDeviceTypesListParams {
o.SetPartNumberIc(partNumberIc)
return o
}
// SetPartNumberIc adds the partNumberIc to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetPartNumberIc(partNumberIc *string) {
o.PartNumberIc = partNumberIc
}
// WithPartNumberIe adds the partNumberIe to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithPartNumberIe(partNumberIe *string) *DcimDeviceTypesListParams {
o.SetPartNumberIe(partNumberIe)
return o
}
// SetPartNumberIe adds the partNumberIe to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetPartNumberIe(partNumberIe *string) {
o.PartNumberIe = partNumberIe
}
// WithPartNumberIew adds the partNumberIew to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithPartNumberIew(partNumberIew *string) *DcimDeviceTypesListParams {
o.SetPartNumberIew(partNumberIew)
return o
}
// SetPartNumberIew adds the partNumberIew to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetPartNumberIew(partNumberIew *string) {
o.PartNumberIew = partNumberIew
}
// WithPartNumberIsw adds the partNumberIsw to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithPartNumberIsw(partNumberIsw *string) *DcimDeviceTypesListParams {
o.SetPartNumberIsw(partNumberIsw)
return o
}
// SetPartNumberIsw adds the partNumberIsw to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetPartNumberIsw(partNumberIsw *string) {
o.PartNumberIsw = partNumberIsw
}
// WithPartNumberN adds the partNumberN to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithPartNumberN(partNumberN *string) *DcimDeviceTypesListParams {
o.SetPartNumberN(partNumberN)
return o
}
// SetPartNumberN adds the partNumberN to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetPartNumberN(partNumberN *string) {
o.PartNumberN = partNumberN
}
// WithPartNumberNic adds the partNumberNic to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithPartNumberNic(partNumberNic *string) *DcimDeviceTypesListParams {
o.SetPartNumberNic(partNumberNic)
return o
}
// SetPartNumberNic adds the partNumberNic to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetPartNumberNic(partNumberNic *string) {
o.PartNumberNic = partNumberNic
}
// WithPartNumberNie adds the partNumberNie to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithPartNumberNie(partNumberNie *string) *DcimDeviceTypesListParams {
o.SetPartNumberNie(partNumberNie)
return o
}
// SetPartNumberNie adds the partNumberNie to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetPartNumberNie(partNumberNie *string) {
o.PartNumberNie = partNumberNie
}
// WithPartNumberNiew adds the partNumberNiew to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithPartNumberNiew(partNumberNiew *string) *DcimDeviceTypesListParams {
o.SetPartNumberNiew(partNumberNiew)
return o
}
// SetPartNumberNiew adds the partNumberNiew to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetPartNumberNiew(partNumberNiew *string) {
o.PartNumberNiew = partNumberNiew
}
// WithPartNumberNisw adds the partNumberNisw to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithPartNumberNisw(partNumberNisw *string) *DcimDeviceTypesListParams {
o.SetPartNumberNisw(partNumberNisw)
return o
}
// SetPartNumberNisw adds the partNumberNisw to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetPartNumberNisw(partNumberNisw *string) {
o.PartNumberNisw = partNumberNisw
}
// WithPassThroughPorts adds the passThroughPorts to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithPassThroughPorts(passThroughPorts *string) *DcimDeviceTypesListParams {
o.SetPassThroughPorts(passThroughPorts)
return o
}
// SetPassThroughPorts adds the passThroughPorts to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetPassThroughPorts(passThroughPorts *string) {
o.PassThroughPorts = passThroughPorts
}
// WithPowerOutlets adds the powerOutlets to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithPowerOutlets(powerOutlets *string) *DcimDeviceTypesListParams {
o.SetPowerOutlets(powerOutlets)
return o
}
// SetPowerOutlets adds the powerOutlets to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetPowerOutlets(powerOutlets *string) {
o.PowerOutlets = powerOutlets
}
// WithPowerPorts adds the powerPorts to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithPowerPorts(powerPorts *string) *DcimDeviceTypesListParams {
o.SetPowerPorts(powerPorts)
return o
}
// SetPowerPorts adds the powerPorts to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetPowerPorts(powerPorts *string) {
o.PowerPorts = powerPorts
}
// WithQ adds the q to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithQ(q *string) *DcimDeviceTypesListParams {
o.SetQ(q)
return o
}
// SetQ adds the q to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetQ(q *string) {
o.Q = q
}
// WithSlug adds the slug to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithSlug(slug *string) *DcimDeviceTypesListParams {
o.SetSlug(slug)
return o
}
// SetSlug adds the slug to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetSlug(slug *string) {
o.Slug = slug
}
// WithSlugIc adds the slugIc to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithSlugIc(slugIc *string) *DcimDeviceTypesListParams {
o.SetSlugIc(slugIc)
return o
}
// SetSlugIc adds the slugIc to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetSlugIc(slugIc *string) {
o.SlugIc = slugIc
}
// WithSlugIe adds the slugIe to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithSlugIe(slugIe *string) *DcimDeviceTypesListParams {
o.SetSlugIe(slugIe)
return o
}
// SetSlugIe adds the slugIe to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetSlugIe(slugIe *string) {
o.SlugIe = slugIe
}
// WithSlugIew adds the slugIew to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithSlugIew(slugIew *string) *DcimDeviceTypesListParams {
o.SetSlugIew(slugIew)
return o
}
// SetSlugIew adds the slugIew to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetSlugIew(slugIew *string) {
o.SlugIew = slugIew
}
// WithSlugIsw adds the slugIsw to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithSlugIsw(slugIsw *string) *DcimDeviceTypesListParams {
o.SetSlugIsw(slugIsw)
return o
}
// SetSlugIsw adds the slugIsw to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetSlugIsw(slugIsw *string) {
o.SlugIsw = slugIsw
}
// WithSlugN adds the slugN to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithSlugN(slugN *string) *DcimDeviceTypesListParams {
o.SetSlugN(slugN)
return o
}
// SetSlugN adds the slugN to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetSlugN(slugN *string) {
o.SlugN = slugN
}
// WithSlugNic adds the slugNic to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithSlugNic(slugNic *string) *DcimDeviceTypesListParams {
o.SetSlugNic(slugNic)
return o
}
// SetSlugNic adds the slugNic to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetSlugNic(slugNic *string) {
o.SlugNic = slugNic
}
// WithSlugNie adds the slugNie to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithSlugNie(slugNie *string) *DcimDeviceTypesListParams {
o.SetSlugNie(slugNie)
return o
}
// SetSlugNie adds the slugNie to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetSlugNie(slugNie *string) {
o.SlugNie = slugNie
}
// WithSlugNiew adds the slugNiew to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithSlugNiew(slugNiew *string) *DcimDeviceTypesListParams {
o.SetSlugNiew(slugNiew)
return o
}
// SetSlugNiew adds the slugNiew to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetSlugNiew(slugNiew *string) {
o.SlugNiew = slugNiew
}
// WithSlugNisw adds the slugNisw to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithSlugNisw(slugNisw *string) *DcimDeviceTypesListParams {
o.SetSlugNisw(slugNisw)
return o
}
// SetSlugNisw adds the slugNisw to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetSlugNisw(slugNisw *string) {
o.SlugNisw = slugNisw
}
// WithSubdeviceRole adds the subdeviceRole to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithSubdeviceRole(subdeviceRole *string) *DcimDeviceTypesListParams {
o.SetSubdeviceRole(subdeviceRole)
return o
}
// SetSubdeviceRole adds the subdeviceRole to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetSubdeviceRole(subdeviceRole *string) {
o.SubdeviceRole = subdeviceRole
}
// WithSubdeviceRoleN adds the subdeviceRoleN to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithSubdeviceRoleN(subdeviceRoleN *string) *DcimDeviceTypesListParams {
o.SetSubdeviceRoleN(subdeviceRoleN)
return o
}
// SetSubdeviceRoleN adds the subdeviceRoleN to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetSubdeviceRoleN(subdeviceRoleN *string) {
o.SubdeviceRoleN = subdeviceRoleN
}
// WithTag adds the tag to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithTag(tag *string) *DcimDeviceTypesListParams {
o.SetTag(tag)
return o
}
// SetTag adds the tag to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetTag(tag *string) {
o.Tag = tag
}
// WithTagN adds the tagN to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithTagN(tagN *string) *DcimDeviceTypesListParams {
o.SetTagN(tagN)
return o
}
// SetTagN adds the tagN to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetTagN(tagN *string) {
o.TagN = tagN
}
// WithUHeight adds the uHeight to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithUHeight(uHeight *string) *DcimDeviceTypesListParams {
o.SetUHeight(uHeight)
return o
}
// SetUHeight adds the uHeight to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetUHeight(uHeight *string) {
o.UHeight = uHeight
}
// WithUHeightGt adds the uHeightGt to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithUHeightGt(uHeightGt *string) *DcimDeviceTypesListParams {
o.SetUHeightGt(uHeightGt)
return o
}
// SetUHeightGt adds the uHeightGt to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetUHeightGt(uHeightGt *string) {
o.UHeightGt = uHeightGt
}
// WithUHeightGte adds the uHeightGte to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithUHeightGte(uHeightGte *string) *DcimDeviceTypesListParams {
o.SetUHeightGte(uHeightGte)
return o
}
// SetUHeightGte adds the uHeightGte to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetUHeightGte(uHeightGte *string) {
o.UHeightGte = uHeightGte
}
// WithUHeightLt adds the uHeightLt to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithUHeightLt(uHeightLt *string) *DcimDeviceTypesListParams {
o.SetUHeightLt(uHeightLt)
return o
}
// SetUHeightLt adds the uHeightLt to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetUHeightLt(uHeightLt *string) {
o.UHeightLt = uHeightLt
}
// WithUHeightLte adds the uHeightLte to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithUHeightLte(uHeightLte *string) *DcimDeviceTypesListParams {
o.SetUHeightLte(uHeightLte)
return o
}
// SetUHeightLte adds the uHeightLte to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetUHeightLte(uHeightLte *string) {
o.UHeightLte = uHeightLte
}
// WithUHeightN adds the uHeightN to the dcim device types list params
func (o *DcimDeviceTypesListParams) WithUHeightN(uHeightN *string) *DcimDeviceTypesListParams {
o.SetUHeightN(uHeightN)
return o
}
// SetUHeightN adds the uHeightN to the dcim device types list params
func (o *DcimDeviceTypesListParams) SetUHeightN(uHeightN *string) {
o.UHeightN = uHeightN
}
// WriteToRequest writes these params to a swagger request
func (o *DcimDeviceTypesListParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {
if err := r.SetTimeout(o.timeout); err != nil {
return err
}
var res []error
if o.ConsolePorts != nil {
// query param console_ports
var qrConsolePorts string
if o.ConsolePorts != nil {
qrConsolePorts = *o.ConsolePorts
}
qConsolePorts := qrConsolePorts
if qConsolePorts != "" {
if err := r.SetQueryParam("console_ports", qConsolePorts); err != nil {
return err
}
}
}
if o.ConsoleServerPorts != nil {
// query param console_server_ports
var qrConsoleServerPorts string
if o.ConsoleServerPorts != nil {
qrConsoleServerPorts = *o.ConsoleServerPorts
}
qConsoleServerPorts := qrConsoleServerPorts
if qConsoleServerPorts != "" {
if err := r.SetQueryParam("console_server_ports", qConsoleServerPorts); err != nil {
return err
}
}
}
if o.Created != nil {
// query param created
var qrCreated string
if o.Created != nil {
qrCreated = *o.Created
}
qCreated := qrCreated
if qCreated != "" {
if err := r.SetQueryParam("created", qCreated); err != nil {
return err
}
}
}
if o.CreatedGte != nil {
// query param created__gte
var qrCreatedGte string
if o.CreatedGte != nil {
qrCreatedGte = *o.CreatedGte
}
qCreatedGte := qrCreatedGte
if qCreatedGte != "" {
if err := r.SetQueryParam("created__gte", qCreatedGte); err != nil {
return err
}
}
}
if o.CreatedLte != nil {
// query param created__lte
var qrCreatedLte string
if o.CreatedLte != nil {
qrCreatedLte = *o.CreatedLte
}
qCreatedLte := qrCreatedLte
if qCreatedLte != "" {
if err := r.SetQueryParam("created__lte", qCreatedLte); err != nil {
return err
}
}
}
if o.DeviceBays != nil {
// query param device_bays
var qrDeviceBays string
if o.DeviceBays != nil {
qrDeviceBays = *o.DeviceBays
}
qDeviceBays := qrDeviceBays
if qDeviceBays != "" {
if err := r.SetQueryParam("device_bays", qDeviceBays); err != nil {
return err
}
}
}
if o.ID != nil {
// query param id
var qrID string
if o.ID != nil {
qrID = *o.ID
}
qID := qrID
if qID != "" {
if err := r.SetQueryParam("id", qID); err != nil {
return err
}
}
}
if o.IDGt != nil {
// query param id__gt
var qrIDGt string
if o.IDGt != nil {
qrIDGt = *o.IDGt
}
qIDGt := qrIDGt
if qIDGt != "" {
if err := r.SetQueryParam("id__gt", qIDGt); err != nil {
return err
}
}
}
if o.IDGte != nil {
// query param id__gte
var qrIDGte string
if o.IDGte != nil {
qrIDGte = *o.IDGte
}
qIDGte := qrIDGte
if qIDGte != "" {
if err := r.SetQueryParam("id__gte", qIDGte); err != nil {
return err
}
}
}
if o.IDLt != nil {
// query param id__lt
var qrIDLt string
if o.IDLt != nil {
qrIDLt = *o.IDLt
}
qIDLt := qrIDLt
if qIDLt != "" {
if err := r.SetQueryParam("id__lt", qIDLt); err != nil {
return err
}
}
}
if o.IDLte != nil {
// query param id__lte
var qrIDLte string
if o.IDLte != nil {
qrIDLte = *o.IDLte
}
qIDLte := qrIDLte
if qIDLte != "" {
if err := r.SetQueryParam("id__lte", qIDLte); err != nil {
return err
}
}
}
if o.IDN != nil {
// query param id__n
var qrIDN string
if o.IDN != nil {
qrIDN = *o.IDN
}
qIDN := qrIDN
if qIDN != "" {
if err := r.SetQueryParam("id__n", qIDN); err != nil {
return err
}
}
}
if o.Interfaces != nil {
// query param interfaces
var qrInterfaces string
if o.Interfaces != nil {
qrInterfaces = *o.Interfaces
}
qInterfaces := qrInterfaces
if qInterfaces != "" {
if err := r.SetQueryParam("interfaces", qInterfaces); err != nil {
return err
}
}
}
if o.IsFullDepth != nil {
// query param is_full_depth
var qrIsFullDepth string
if o.IsFullDepth != nil {
qrIsFullDepth = *o.IsFullDepth
}
qIsFullDepth := qrIsFullDepth
if qIsFullDepth != "" {
if err := r.SetQueryParam("is_full_depth", qIsFullDepth); err != nil {
return err
}
}
}
if o.LastUpdated != nil {
// query param last_updated
var qrLastUpdated string
if o.LastUpdated != nil {
qrLastUpdated = *o.LastUpdated
}
qLastUpdated := qrLastUpdated
if qLastUpdated != "" {
if err := r.SetQueryParam("last_updated", qLastUpdated); err != nil {
return err
}
}
}
if o.LastUpdatedGte != nil {
// query param last_updated__gte
var qrLastUpdatedGte string
if o.LastUpdatedGte != nil {
qrLastUpdatedGte = *o.LastUpdatedGte
}
qLastUpdatedGte := qrLastUpdatedGte
if qLastUpdatedGte != "" {
if err := r.SetQueryParam("last_updated__gte", qLastUpdatedGte); err != nil {
return err
}
}
}
if o.LastUpdatedLte != nil {
// query param last_updated__lte
var qrLastUpdatedLte string
if o.LastUpdatedLte != nil {
qrLastUpdatedLte = *o.LastUpdatedLte
}
qLastUpdatedLte := qrLastUpdatedLte
if qLastUpdatedLte != "" {
if err := r.SetQueryParam("last_updated__lte", qLastUpdatedLte); err != nil {
return err
}
}
}
if o.Limit != nil {
// query param limit
var qrLimit int64
if o.Limit != nil {
qrLimit = *o.Limit
}
qLimit := swag.FormatInt64(qrLimit)
if qLimit != "" {
if err := r.SetQueryParam("limit", qLimit); err != nil {
return err
}
}
}
if o.Manufacturer != nil {
// query param manufacturer
var qrManufacturer string
if o.Manufacturer != nil {
qrManufacturer = *o.Manufacturer
}
qManufacturer := qrManufacturer
if qManufacturer != "" {
if err := r.SetQueryParam("manufacturer", qManufacturer); err != nil {
return err
}
}
}
if o.ManufacturerN != nil {
// query param manufacturer__n
var qrManufacturerN string
if o.ManufacturerN != nil {
qrManufacturerN = *o.ManufacturerN
}
qManufacturerN := qrManufacturerN
if qManufacturerN != "" {
if err := r.SetQueryParam("manufacturer__n", qManufacturerN); err != nil {
return err
}
}
}
if o.ManufacturerID != nil {
// query param manufacturer_id
var qrManufacturerID string
if o.ManufacturerID != nil {
qrManufacturerID = *o.ManufacturerID
}
qManufacturerID := qrManufacturerID
if qManufacturerID != "" {
if err := r.SetQueryParam("manufacturer_id", qManufacturerID); err != nil {
return err
}
}
}
if o.ManufacturerIDN != nil {
// query param manufacturer_id__n
var qrManufacturerIDN string
if o.ManufacturerIDN != nil {
qrManufacturerIDN = *o.ManufacturerIDN
}
qManufacturerIDN := qrManufacturerIDN
if qManufacturerIDN != "" {
if err := r.SetQueryParam("manufacturer_id__n", qManufacturerIDN); err != nil {
return err
}
}
}
if o.Model != nil {
// query param model
var qrModel string
if o.Model != nil {
qrModel = *o.Model
}
qModel := qrModel
if qModel != "" {
if err := r.SetQueryParam("model", qModel); err != nil {
return err
}
}
}
if o.ModelIc != nil {
// query param model__ic
var qrModelIc string
if o.ModelIc != nil {
qrModelIc = *o.ModelIc
}
qModelIc := qrModelIc
if qModelIc != "" {
if err := r.SetQueryParam("model__ic", qModelIc); err != nil {
return err
}
}
}
if o.ModelIe != nil {
// query param model__ie
var qrModelIe string
if o.ModelIe != nil {
qrModelIe = *o.ModelIe
}
qModelIe := qrModelIe
if qModelIe != "" {
if err := r.SetQueryParam("model__ie", qModelIe); err != nil {
return err
}
}
}
if o.ModelIew != nil {
// query param model__iew
var qrModelIew string
if o.ModelIew != nil {
qrModelIew = *o.ModelIew
} | qModelIew := qrModelIew
if qModelIew != "" {
if err := r.SetQueryParam("model__iew", qModelIew); err != nil {
return err
}
}
}
if o.ModelIsw != nil {
// query param model__isw
var qrModelIsw string
if o.ModelIsw != nil {
qrModelIsw = *o.ModelIsw
}
qModelIsw := qrModelIsw
if qModelIsw != "" {
if err := r.SetQueryParam("model__isw", qModelIsw); err != nil {
return err
}
}
}
if o.ModelN != nil {
// query param model__n
var qrModelN string
if o.ModelN != nil {
qrModelN = *o.ModelN
}
qModelN := qrModelN
if qModelN != "" {
if err := r.SetQueryParam("model__n", qModelN); err != nil {
return err
}
}
}
if o.ModelNic != nil {
// query param model__nic
var qrModelNic string
if o.ModelNic != nil {
qrModelNic = *o.ModelNic
}
qModelNic := qrModelNic
if qModelNic != "" {
if err := r.SetQueryParam("model__nic", qModelNic); err != nil {
return err
}
}
}
if o.ModelNie != nil {
// query param model__nie
var qrModelNie string
if o.ModelNie != nil {
qrModelNie = *o.ModelNie
}
qModelNie := qrModelNie
if qModelNie != "" {
if err := r.SetQueryParam("model__nie", qModelNie); err != nil {
return err
}
}
}
if o.ModelNiew != nil {
// query param model__niew
var qrModelNiew string
if o.ModelNiew != nil {
qrModelNiew = *o.ModelNiew
}
qModelNiew := qrModelNiew
if qModelNiew != "" {
if err := r.SetQueryParam("model__niew", qModelNiew); err != nil {
return err
}
}
}
if o.ModelNisw != nil {
// query param model__nisw
var qrModelNisw string
if o.ModelNisw != nil {
qrModelNisw = *o.ModelNisw
}
qModelNisw := qrModelNisw
if qModelNisw != "" {
if err := r.SetQueryParam("model__nisw", qModelNisw); err != nil {
return err
}
}
}
if o.Offset != nil {
// query param offset
var qrOffset int64
if o.Offset != nil {
qrOffset = *o.Offset
}
qOffset := swag.FormatInt64(qrOffset)
if qOffset != "" {
if err := r.SetQueryParam("offset", qOffset); err != nil {
return err
}
}
}
if o.PartNumber != nil {
// query param part_number
var qrPartNumber string
if o.PartNumber != nil {
qrPartNumber = *o.PartNumber
}
qPartNumber := qrPartNumber
if qPartNumber != "" {
if err := r.SetQueryParam("part_number", qPartNumber); err != nil {
return err
}
}
}
if o.PartNumberIc != nil {
// query param part_number__ic
var qrPartNumberIc string
if o.PartNumberIc != nil {
qrPartNumberIc = *o.PartNumberIc
}
qPartNumberIc := qrPartNumberIc
if qPartNumberIc != "" {
if err := r.SetQueryParam("part_number__ic", qPartNumberIc); err != nil {
return err
}
}
}
if o.PartNumberIe != nil {
// query param part_number__ie
var qrPartNumberIe string
if o.PartNumberIe != nil {
qrPartNumberIe = *o.PartNumberIe
}
qPartNumberIe := qrPartNumberIe
if qPartNumberIe != "" {
if err := r.SetQueryParam("part_number__ie", qPartNumberIe); err != nil {
return err
}
}
}
if o.PartNumberIew != nil {
// query param part_number__iew
var qrPartNumberIew string
if o.PartNumberIew != nil {
qrPartNumberIew = *o.PartNumberIew
}
qPartNumberIew := qrPartNumberIew
if qPartNumberIew != "" {
if err := r.SetQueryParam("part_number__iew", qPartNumberIew); err != nil {
return err
}
}
}
if o.PartNumberIsw != nil {
// query param part_number__isw
var qrPartNumberIsw string
if o.PartNumberIsw != nil {
qrPartNumberIsw = *o.PartNumberIsw
}
qPartNumberIsw := qrPartNumberIsw
if qPartNumberIsw != "" {
if err := r.SetQueryParam("part_number__isw", qPartNumberIsw); err != nil {
return err
}
}
}
if o.PartNumberN != nil {
// query param part_number__n
var qrPartNumberN string
if o.PartNumberN != nil {
qrPartNumberN = *o.PartNumberN
}
qPartNumberN := qrPartNumberN
if qPartNumberN != "" {
if err := r.SetQueryParam("part_number__n", qPartNumberN); err != nil {
return err
}
}
}
if o.PartNumberNic != nil {
// query param part_number__nic
var qrPartNumberNic string
if o.PartNumberNic != nil {
qrPartNumberNic = *o.PartNumberNic
}
qPartNumberNic := qrPartNumberNic
if qPartNumberNic != "" {
if err := r.SetQueryParam("part_number__nic", qPartNumberNic); err != nil {
return err
}
}
}
if o.PartNumberNie != nil {
// query param part_number__nie
var qrPartNumberNie string
if o.PartNumberNie != nil {
qrPartNumberNie = *o.PartNumberNie
}
qPartNumberNie := qrPartNumberNie
if qPartNumberNie != "" {
if err := r.SetQueryParam("part_number__nie", qPartNumberNie); err != nil {
return err
}
}
}
if o.PartNumberNiew != nil {
// query param part_number__niew
var qrPartNumberNiew string
if o.PartNumberNiew != nil {
qrPartNumberNiew = *o.PartNumberNiew
}
qPartNumberNiew := qrPartNumberNiew
if qPartNumberNiew != "" {
if err := r.SetQueryParam("part_number__niew", qPartNumberNiew); err != nil {
return err
}
}
}
if o.PartNumberNisw != nil {
// query param part_number__nisw
var qrPartNumberNisw string
if o.PartNumberNisw != nil {
qrPartNumberNisw = *o.PartNumberNisw
}
qPartNumberNisw := qrPartNumberNisw
if qPartNumberNisw != "" {
if err := r.SetQueryParam("part_number__nisw", qPartNumberNisw); err != nil {
return err
}
}
}
if o.PassThroughPorts != nil {
// query param pass_through_ports
var qrPassThroughPorts string
if o.PassThroughPorts != nil {
qrPassThroughPorts = *o.PassThroughPorts
}
qPassThroughPorts := qrPassThroughPorts
if qPassThroughPorts != "" {
if err := r.SetQueryParam("pass_through_ports", qPassThroughPorts); err != nil {
return err
}
}
}
if o.PowerOutlets != nil {
// query param power_outlets
var qrPowerOutlets string
if o.PowerOutlets != nil {
qrPowerOutlets = *o.PowerOutlets
}
qPowerOutlets := qrPowerOutlets
if qPowerOutlets != "" {
if err := r.SetQueryParam("power_outlets", qPowerOutlets); err != nil {
return err
}
}
}
if o.PowerPorts != nil {
// query param power_ports
var qrPowerPorts string
if o.PowerPorts != nil {
qrPowerPorts = *o.PowerPorts
}
qPowerPorts := qrPowerPorts
if qPowerPorts != "" {
if err := r.SetQueryParam("power_ports", qPowerPorts); err != nil {
return err
}
}
}
if o.Q != nil {
// query param q
var qrQ string
if o.Q != nil {
qrQ = *o.Q
}
qQ := qrQ
if qQ != "" {
if err := r.SetQueryParam("q", qQ); err != nil {
return err
}
}
}
if o.Slug != nil {
// query param slug
var qrSlug string
if o.Slug != nil {
qrSlug = *o.Slug
}
qSlug := qrSlug
if qSlug != "" {
if err := r.SetQueryParam("slug", qSlug); err != nil {
return err
}
}
}
if o.SlugIc != nil {
// query param slug__ic
var qrSlugIc string
if o.SlugIc != nil {
qrSlugIc = *o.SlugIc
}
qSlugIc := qrSlugIc
if qSlugIc != "" {
if err := r.SetQueryParam("slug__ic", qSlugIc); err != nil {
return err
}
}
}
if o.SlugIe != nil {
// query param slug__ie
var qrSlugIe string
if o.SlugIe != nil {
qrSlugIe = *o.SlugIe
}
qSlugIe := qrSlugIe
if qSlugIe != "" {
if err := r.SetQueryParam("slug__ie", qSlugIe); err != nil {
return err
}
}
}
if o.SlugIew != nil {
// query param slug__iew
var qrSlugIew string
if o.SlugIew != nil {
qrSlugIew = *o.SlugIew
}
qSlugIew := qrSlugIew
if qSlugIew != "" {
if err := r.SetQueryParam("slug__iew", qSlugIew); err != nil {
return err
}
}
}
if o.SlugIsw != nil {
// query param slug__isw
var qrSlugIsw string
if o.SlugIsw != nil {
qrSlugIsw = *o.SlugIsw
}
qSlugIsw := qrSlugIsw
if qSlugIsw != "" {
if err := r.SetQueryParam("slug__isw", qSlugIsw); err != nil {
return err
}
}
}
if o.SlugN != nil {
// query param slug__n
var qrSlugN string
if o.SlugN != nil {
qrSlugN = *o.SlugN
}
qSlugN := qrSlugN
if qSlugN != "" {
if err := r.SetQueryParam("slug__n", qSlugN); err != nil {
return err
}
}
}
if o.SlugNic != nil {
// query param slug__nic
var qrSlugNic string
if o.SlugNic != nil {
qrSlugNic = *o.SlugNic
}
qSlugNic := qrSlugNic
if qSlugNic != "" {
if err := r.SetQueryParam("slug__nic", qSlugNic); err != nil {
return err
}
}
}
if o.SlugNie != nil {
// query param slug__nie
var qrSlugNie string
if o.SlugNie != nil {
qrSlugNie = *o.SlugNie
}
qSlugNie := qrSlugNie
if qSlugNie != "" {
if err := r.SetQueryParam("slug__nie", qSlugNie); err != nil {
return err
}
}
}
if o.SlugNiew != nil {
// query param slug__niew
var qrSlugNiew string
if o.SlugNiew != nil {
qrSlugNiew = *o.SlugNiew
}
qSlugNiew := qrSlugNiew
if qSlugNiew != "" {
if err := r.SetQueryParam("slug__niew", qSlugNiew); err != nil {
return err
}
}
}
if o.SlugNisw != nil {
// query param slug__nisw
var qrSlugNisw string
if o.SlugNisw != nil {
qrSlugNisw = *o.SlugNisw
}
qSlugNisw := qrSlugNisw
if qSlugNisw != "" {
if err := r.SetQueryParam("slug__nisw", qSlugNisw); err != nil {
return err
}
}
}
if o.SubdeviceRole != nil {
// query param subdevice_role
var qrSubdeviceRole string
if o.SubdeviceRole != nil {
qrSubdeviceRole = *o.SubdeviceRole
}
qSubdeviceRole := qrSubdeviceRole
if qSubdeviceRole != "" {
if err := r.SetQueryParam("subdevice_role", qSubdeviceRole); err != nil {
return err
}
}
}
if o.SubdeviceRoleN != nil {
// query param subdevice_role__n
var qrSubdeviceRoleN string
if o.SubdeviceRoleN != nil {
qrSubdeviceRoleN = *o.SubdeviceRoleN
}
qSubdeviceRoleN := qrSubdeviceRoleN
if qSubdeviceRoleN != "" {
if err := r.SetQueryParam("subdevice_role__n", qSubdeviceRoleN); err != nil {
return err
}
}
}
if o.Tag != nil {
// query param tag
var qrTag string
if o.Tag != nil {
qrTag = *o.Tag
}
qTag := qrTag
if qTag != "" {
if err := r.SetQueryParam("tag", qTag); err != nil {
return err
}
}
}
if o.TagN != nil {
// query param tag__n
var qrTagN string
if o.TagN != nil {
qrTagN = *o.TagN
}
qTagN := qrTagN
if qTagN != "" {
if err := r.SetQueryParam("tag__n", qTagN); err != nil {
return err
}
}
}
if o.UHeight != nil {
// query param u_height
var qrUHeight string
if o.UHeight != nil {
qrUHeight = *o.UHeight
}
qUHeight := qrUHeight
if qUHeight != "" {
if err := r.SetQueryParam("u_height", qUHeight); err != nil {
return err
}
}
}
if o.UHeightGt != nil {
// query param u_height__gt
var qrUHeightGt string
if o.UHeightGt != nil {
qrUHeightGt = *o.UHeightGt
}
qUHeightGt := qrUHeightGt
if qUHeightGt != "" {
if err := r.SetQueryParam("u_height__gt", qUHeightGt); err != nil {
return err
}
}
}
if o.UHeightGte != nil {
// query param u_height__gte
var qrUHeightGte string
if o.UHeightGte != nil {
qrUHeightGte = *o.UHeightGte
}
qUHeightGte := qrUHeightGte
if qUHeightGte != "" {
if err := r.SetQueryParam("u_height__gte", qUHeightGte); err != nil {
return err
}
}
}
if o.UHeightLt != nil {
// query param u_height__lt
var qrUHeightLt string
if o.UHeightLt != nil {
qrUHeightLt = *o.UHeightLt
}
qUHeightLt := qrUHeightLt
if qUHeightLt != "" {
if err := r.SetQueryParam("u_height__lt", qUHeightLt); err != nil {
return err
}
}
}
if o.UHeightLte != nil {
// query param u_height__lte
var qrUHeightLte string
if o.UHeightLte != nil {
qrUHeightLte = *o.UHeightLte
}
qUHeightLte := qrUHeightLte
if qUHeightLte != "" {
if err := r.SetQueryParam("u_height__lte", qUHeightLte); err != nil {
return err
}
}
}
if o.UHeightN != nil {
// query param u_height__n
var qrUHeightN string
if o.UHeightN != nil {
qrUHeightN = *o.UHeightN
}
qUHeightN := qrUHeightN
if qUHeightN != "" {
if err := r.SetQueryParam("u_height__n", qUHeightN); err != nil {
return err
}
}
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
} | |
reconciler.go | package ups
import (
"context"
"fmt"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
corev1 "k8s.io/api/core/v1"
"github.com/integr8ly/integreatly-operator/pkg/resources/backup"
"github.com/integr8ly/integreatly-operator/pkg/resources/events"
"github.com/integr8ly/integreatly-operator/pkg/resources/owner"
"github.com/integr8ly/cloud-resource-operator/pkg/apis/integreatly/v1alpha1/types"
"github.com/sirupsen/logrus"
"github.com/integr8ly/integreatly-operator/pkg/products/monitoring"
upsv1alpha1 "github.com/aerogear/unifiedpush-operator/pkg/apis/push/v1alpha1"
monitoringv1alpha1 "github.com/integr8ly/application-monitoring-operator/pkg/apis/applicationmonitoring/v1alpha1"
croUtil "github.com/integr8ly/cloud-resource-operator/pkg/client"
integreatlyv1alpha1 "github.com/integr8ly/integreatly-operator/pkg/apis/integreatly/v1alpha1"
"github.com/integr8ly/integreatly-operator/pkg/config"
"github.com/integr8ly/integreatly-operator/pkg/resources"
"github.com/integr8ly/integreatly-operator/pkg/resources/marketplace"
routev1 "github.com/openshift/api/route/v1"
"github.com/integr8ly/integreatly-operator/pkg/resources/constants"
appsv1 "k8s.io/api/apps/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/tools/record"
k8sclient "sigs.k8s.io/controller-runtime/pkg/client"
)
const (
defaultInstallationNamespace = "ups"
defaultUpsName = "ups"
defaultRoutename = defaultUpsName + "-unifiedpush-proxy"
manifestPackage = "integreatly-unifiedpush"
tier = "production"
)
type Reconciler struct {
Config *config.Ups
ConfigManager config.ConfigReadWriter
mpm marketplace.MarketplaceInterface
logger *logrus.Entry
*resources.Reconciler
recorder record.EventRecorder
}
func NewReconciler(configManager config.ConfigReadWriter, installation *integreatlyv1alpha1.RHMI, mpm marketplace.MarketplaceInterface, recorder record.EventRecorder) (*Reconciler, error) {
config, err := configManager.ReadUps()
if err != nil {
return nil, fmt.Errorf("could not retrieve ups config: %w", err)
}
if config.GetNamespace() == "" {
config.SetNamespace(installation.Spec.NamespacePrefix + defaultInstallationNamespace)
configManager.WriteConfig(config)
}
if config.GetOperatorNamespace() == "" {
if installation.Spec.OperatorsInProductNamespace {
config.SetOperatorNamespace(config.GetNamespace())
} else {
config.SetOperatorNamespace(config.GetNamespace() + "-operator")
}
configManager.WriteConfig(config)
}
config.SetBlackboxTargetPath("/rest/auth/config/")
logger := logrus.NewEntry(logrus.StandardLogger())
return &Reconciler{
ConfigManager: configManager,
Config: config,
mpm: mpm,
logger: logger,
Reconciler: resources.NewReconciler(mpm),
recorder: recorder,
}, nil
}
func (r *Reconciler) GetPreflightObject(ns string) runtime.Object {
return &appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Name: "unifiedpush-operator",
Namespace: ns,
},
}
}
func (r *Reconciler) Reconcile(ctx context.Context, installation *integreatlyv1alpha1.RHMI, product *integreatlyv1alpha1.RHMIProductStatus, serverClient k8sclient.Client) (integreatlyv1alpha1.StatusPhase, error) {
logrus.Infof("Reconciling %s", defaultUpsName)
phase, err := r.ReconcileFinalizer(ctx, serverClient, installation, string(r.Config.GetProductName()), func() (integreatlyv1alpha1.StatusPhase, error) {
phase, err := resources.RemoveNamespace(ctx, installation, serverClient, r.Config.GetNamespace())
if err != nil || phase != integreatlyv1alpha1.PhaseCompleted {
return phase, err
}
phase, err = resources.RemoveNamespace(ctx, installation, serverClient, r.Config.GetOperatorNamespace())
if err != nil || phase != integreatlyv1alpha1.PhaseCompleted {
return phase, err
}
return integreatlyv1alpha1.PhaseCompleted, nil
})
if err != nil || phase != integreatlyv1alpha1.PhaseCompleted {
events.HandleError(r.recorder, installation, phase, "Failed to reconcile finalizer", err)
return phase, err
}
phase, err = r.ReconcileNamespace(ctx, r.Config.GetOperatorNamespace(), installation, serverClient)
if err != nil || phase != integreatlyv1alpha1.PhaseCompleted {
events.HandleError(r.recorder, installation, phase, fmt.Sprintf("Failed to reconcile %s namespace", r.Config.GetOperatorNamespace()), err)
return phase, err
}
ns := r.Config.GetNamespace()
phase, err = r.ReconcileNamespace(ctx, ns, installation, serverClient)
if err != nil || phase != integreatlyv1alpha1.PhaseCompleted {
events.HandleError(r.recorder, installation, phase, fmt.Sprintf("Failed to reconcile %s namespace", ns), err)
return phase, err
}
namespace, err := resources.GetNS(ctx, ns, serverClient)
if err != nil {
events.HandleError(r.recorder, installation, integreatlyv1alpha1.PhaseFailed, fmt.Sprintf("Failed to retrieve %s namespace", ns), err)
return integreatlyv1alpha1.PhaseFailed, err
}
preUpgradeBackups := preUpgradeBackupExecutor(installation)
phase, err = r.ReconcileSubscription(ctx, namespace, marketplace.Target{Pkg: constants.UPSSubscriptionName, Namespace: r.Config.GetOperatorNamespace(), Channel: marketplace.IntegreatlyChannel, ManifestPackage: manifestPackage}, []string{ns}, preUpgradeBackups, serverClient)
if err != nil || phase != integreatlyv1alpha1.PhaseCompleted {
events.HandleError(r.recorder, installation, phase, fmt.Sprintf("Failed to reconcile %s subscription", constants.UPSSubscriptionName), err)
return phase, err
}
phase, err = r.reconcileComponents(ctx, installation, serverClient)
if err != nil || phase != integreatlyv1alpha1.PhaseCompleted {
events.HandleError(r.recorder, installation, phase, "Failed to reconcile components", err)
return phase, err
}
phase, err = r.reconcileHost(ctx, serverClient)
if err != nil || phase != integreatlyv1alpha1.PhaseCompleted {
events.HandleError(r.recorder, installation, phase, "Failed to reconcile host", err)
return phase, err
}
phase, err = r.reconcileBlackboxTargets(ctx, installation, serverClient)
if err != nil || phase != integreatlyv1alpha1.PhaseCompleted {
events.HandleError(r.recorder, installation, phase, "Failed to reconcile blackbox targets", err)
return phase, err
}
product.Host = r.Config.GetHost()
product.Version = r.Config.GetProductVersion()
product.OperatorVersion = r.Config.GetOperatorVersion()
events.HandleProductComplete(r.recorder, installation, integreatlyv1alpha1.ProductsStage, r.Config.GetProductName())
logrus.Infof("%s is successfully reconciled", defaultUpsName)
return integreatlyv1alpha1.PhaseCompleted, nil
}
func (r *Reconciler) reconcileComponents(ctx context.Context, installation *integreatlyv1alpha1.RHMI, client k8sclient.Client) (integreatlyv1alpha1.StatusPhase, error) {
logrus.Info("Reconciling external postgres")
ns := installation.Namespace
// setup postgres custom resource
// this will be used by the cloud resources operator to provision a postgres instance
postgresName := fmt.Sprintf("%s%s", constants.UPSPostgresPrefix, installation.Name)
postgres, err := croUtil.ReconcilePostgres(ctx, client, defaultInstallationNamespace, installation.Spec.Type, tier, postgresName, ns, postgresName, ns, func(cr metav1.Object) error {
owner.AddIntegreatlyOwnerAnnotations(cr, installation)
return nil
})
if err != nil {
return integreatlyv1alpha1.PhaseFailed, fmt.Errorf("failed to reconcile postgres request: %w", err)
}
// cr returning a failed state
_, err = resources.CreatePostgresResourceStatusPhaseFailedAlert(ctx, client, installation, postgres)
if err != nil {
return integreatlyv1alpha1.PhaseFailed, fmt.Errorf("Failed to create postgres resource on provider: %w", err)
}
// cr stuck in a pending state for greater that 5 min
_, err = resources.CreatePostgresResourceStatusPhasePendingAlert(ctx, client, installation, postgres)
if err != nil {
return integreatlyv1alpha1.PhaseFailed, fmt.Errorf("Failed to create postgres resource on provider stuck in a pending state: %w", err)
}
// wait for the postgres instance to reconcile
if postgres.Status.Phase != types.PhaseComplete {
return integreatlyv1alpha1.PhaseAwaitingComponents, nil
}
// create the prometheus availability rule
if _, err = resources.CreatePostgresAvailabilityAlert(ctx, client, installation, postgres); err != nil {
return integreatlyv1alpha1.PhaseFailed, fmt.Errorf("failed to create postgres prometheus alert for ups: %w", err)
}
// create the prometheus connectivity rule
if _, err = resources.CreatePostgresConnectivityAlert(ctx, client, installation, postgres); err != nil {
return integreatlyv1alpha1.PhaseFailed, fmt.Errorf("failed to create postgres connectivity prometheus rule: %s", err)
}
// get the secret created by the cloud resources operator
// containing postgres connection details
connSec := &corev1.Secret{}
err = client.Get(ctx, k8sclient.ObjectKey{Name: postgres.Status.SecretRef.Name, Namespace: postgres.Status.SecretRef.Namespace}, connSec)
if err != nil {
return integreatlyv1alpha1.PhaseFailed, fmt.Errorf("failed to get postgres credential secret: %w", err)
}
postgresSecret := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: postgres.Status.SecretRef.Name,
Namespace: r.Config.GetNamespace(),
},
}
controllerutil.CreateOrUpdate(ctx, client, postgresSecret, func() error {
postgresSecret.StringData = map[string]string{
"POSTGRES_DATABASE": string(connSec.Data["database"]),
"POSTGRES_HOST": string(connSec.Data["host"]),
"POSTGRES_PORT": string(connSec.Data["port"]),
"POSTGRES_USERNAME": string(connSec.Data["username"]),
"POSTGRES_PASSWORD": string(connSec.Data["password"]),
"POSTGRES_SUPERUSER": "false",
"POSTGRES_VERSION": "10",
}
return nil
})
// Reconcile ups custom resource
logrus.Info("Reconciling unified push server cr")
cr := &upsv1alpha1.UnifiedPushServer{
ObjectMeta: metav1.ObjectMeta{
Name: defaultUpsName,
Namespace: r.Config.GetNamespace(),
},
Spec: upsv1alpha1.UnifiedPushServerSpec{
ExternalDB: true,
DatabaseSecret: postgres.Status.SecretRef.Name,
},
}
_, err = controllerutil.CreateOrUpdate(ctx, client, cr, func() error {
cr.ObjectMeta.Name = defaultUpsName
cr.ObjectMeta.Namespace = r.Config.GetNamespace()
cr.Spec.ExternalDB = true
cr.Spec.DatabaseSecret = postgres.Status.SecretRef.Name
owner.AddIntegreatlyOwnerAnnotations(cr, installation)
return nil
})
if err != nil {
return integreatlyv1alpha1.PhaseFailed, fmt.Errorf("failed to create/maintain unifiedpush server custom resource during reconcile: %w", err)
}
// Wait till the ups cr status is complete
if cr.Status.Phase != upsv1alpha1.PhaseReconciling {
logrus.Info("Waiting for unified push server cr phase to complete")
return integreatlyv1alpha1.PhaseInProgress, nil
}
logrus.Info("Successfully reconciled unified push server custom resource")
return integreatlyv1alpha1.PhaseCompleted, nil
}
func (r *Reconciler) reconcileHost(ctx context.Context, serverClient k8sclient.Client) (integreatlyv1alpha1.StatusPhase, error) {
// Setting host on config to exposed route
logrus.Info("Setting unified push server config host")
upsRoute := &routev1.Route{}
err := serverClient.Get(ctx, k8sclient.ObjectKey{Name: defaultRoutename, Namespace: r.Config.GetNamespace()}, upsRoute)
if err != nil {
return integreatlyv1alpha1.PhaseFailed, fmt.Errorf("failed to get route for unified push server: %w", err)
}
r.Config.SetHost("https://" + upsRoute.Spec.Host)
err = r.ConfigManager.WriteConfig(r.Config)
if err != nil {
return integreatlyv1alpha1.PhaseFailed, fmt.Errorf("could not update unified push server config: %w", err)
}
logrus.Info("Successfully set unified push server host")
return integreatlyv1alpha1.PhaseCompleted, nil
}
func (r *Reconciler) reconcileBlackboxTargets(ctx context.Context, installation *integreatlyv1alpha1.RHMI, client k8sclient.Client) (integreatlyv1alpha1.StatusPhase, error) {
cfg, err := r.ConfigManager.ReadMonitoring()
if err != nil {
return integreatlyv1alpha1.PhaseFailed, fmt.Errorf("error reading monitoring config: %w", err)
}
err = monitoring.CreateBlackboxTarget(ctx, "integreatly-ups", monitoringv1alpha1.BlackboxtargetData{
Url: r.Config.GetHost() + "/" + r.Config.GetBlackboxTargetPath(),
Service: "ups-ui",
}, cfg, installation, client)
if err != nil {
return integreatlyv1alpha1.PhaseFailed, fmt.Errorf("error creating ups blackbox target: %w", err)
}
return integreatlyv1alpha1.PhaseCompleted, nil
}
func | (installation *integreatlyv1alpha1.RHMI) backup.BackupExecutor {
if installation.Spec.UseClusterStorage != "false" {
return backup.NewNoopBackupExecutor()
}
return backup.NewAWSBackupExecutor(
installation.Namespace,
"ups-postgres-rhmi",
backup.PostgresSnapshotType,
)
}
| preUpgradeBackupExecutor |
startTraining.py | """
Copyright (c) 2016, Jose Dolz .All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met: | this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
Jose Dolz. Dec, 2016.
email: [email protected]
LIVIA Department, ETS, Montreal.
"""
import os
import numpy as np
from Modules.IO.sampling import getSamplesSubepoch
from Modules.General.Utils import dump_model_to_gzip_file
from Modules.General.Utils import getImagesSet
from Modules.General.Utils import load_model_from_gzip_file
from Modules.Parsers.parsersUtils import parserConfigIni
from startTesting import segmentVolume
def startTraining(networkModelName,configIniName):
print (" ************************************************ STARTING TRAINING **************************************************")
print (" ********************** Starting training model (Reading parameters) **********************")
myParserConfigIni = parserConfigIni()
myParserConfigIni.readConfigIniFile(configIniName,1)
# Image type (0: Nifti, 1: Matlab)
imageType = myParserConfigIni.imageTypesTrain
print (" --- Do training in {} epochs with {} subEpochs each...".format(myParserConfigIni.numberOfEpochs, myParserConfigIni.numberOfSubEpochs))
print ("-------- Reading Images names used in training/validation -------------")
##-----##
# from sklearn.model_selection import KFold
# import numpy as np
# y1 = myParserConfigIni.indexesForTraining
# #x1 = myParserConfigIni.indexesForValidation
# kf = KFold(n_splits= 5)
#
# for train_index, test_index in kf.split(y1):
# print("TRAIN:", train_index, "TEST:", test_index)
# y, x = np.array(y1)[train_index], np.array(y1)[test_index]
##-----##
# from sklearn.model_selection import LeavePOut
# lpo = LeavePOut(p=5)
# y1 = myParserConfigIni.indexesForTraining
# for train, test in lpo.split(y1):
# y, x = np.array(y1)[train], np.array(y1)[test]
##-----train##
from sklearn.cross_validation import LeaveOneOut
loo = LeaveOneOut(4)
y1 = myParserConfigIni.indexesForTraining
x1 = myParserConfigIni.indexesForValidation
for train_index, test_index in loo:
print("TRAIN:", train_index, "TEST:", test_index)
y, x = np.array(y1)[train_index], np.array(y1)[test_index]
##------he
# from sklearn.model_selection import train_test_split
# X_train, X_test, Y_train, Y_test = train_test_split(DataX, DataY, test_size=0.2)
# -- Get list of images used for training -- #
(imageNames_Train, names_Train) = getImagesSet(myParserConfigIni.imagesFolder,y) # Images
(groundTruthNames_Train, gt_names_Train) = getImagesSet(myParserConfigIni.GroundTruthFolder,y) # Ground truth
(roiNames_Train, roi_names_Train) = getImagesSet(myParserConfigIni.ROIFolder,y) # ROI
# -- Get list of images used for validation -- #
(imageNames_Val, names_Val) = getImagesSet(myParserConfigIni.imagesFolder,x) # Images
(groundTruthNames_Val, gt_names_Val) = getImagesSet(myParserConfigIni.GroundTruthFolder,x) # Ground truth
(roiNames_Val, roi_names_Val) = getImagesSet(myParserConfigIni.ROIFolder,x) # ROI
# Print names
print (" ================== Images for training ================")
for i in range(0,len(names_Train)):
if len(roi_names_Train) > 0:
print(" Image({}): {} | GT: {} | ROI {} ".format(i,names_Train[i], gt_names_Train[i], roi_names_Train[i] ))
else:
print(" Image({}): {} | GT: {} ".format(i,names_Train[i], gt_names_Train[i] ))
print (" ================== Images for validation ================")
for i in range(0,len(names_Val)):
if len(roi_names_Train) > 0:
print(" Image({}): {} | GT: {} | ROI {} ".format(i,names_Val[i], gt_names_Val[i], roi_names_Val[i] ))
else:
print(" Image({}): {} | GT: {} ".format(i,names_Val[i], gt_names_Val[i]))
print (" ===============================================================")
# --------------- Load my LiviaNet3D object ---------------
print (" ... Loading model from {}".format(networkModelName))
myLiviaNet3D = load_model_from_gzip_file(networkModelName)
print (" ... Network architecture successfully loaded....")
# Asign parameters to loaded Net
myLiviaNet3D.numberOfEpochs = myParserConfigIni.numberOfEpochs
myLiviaNet3D.numberOfSubEpochs = myParserConfigIni.numberOfSubEpochs
myLiviaNet3D.numberOfSamplesSupEpoch = myParserConfigIni.numberOfSamplesSupEpoch
myLiviaNet3D.firstEpochChangeLR = myParserConfigIni.firstEpochChangeLR
myLiviaNet3D.frequencyChangeLR = myParserConfigIni.frequencyChangeLR
numberOfEpochs = myLiviaNet3D.numberOfEpochs
numberOfSubEpochs = myLiviaNet3D.numberOfSubEpochs
numberOfSamplesSupEpoch = myLiviaNet3D.numberOfSamplesSupEpoch
# --------------- -------------- ---------------
# --------------- Start TRAINING ---------------
# --------------- -------------- ---------------
# Get sample dimension values
receptiveField = myLiviaNet3D.receptiveField
sampleSize_Train = myLiviaNet3D.sampleSize_Train
trainingCost = []
if myParserConfigIni.applyPadding == 1:
applyPadding = True
else:
applyPadding = False
learningRateModifiedEpoch = 0
# Run over all the (remaining) epochs and subepochs
for e_i in xrange(numberOfEpochs):
# Recover last trained epoch
numberOfEpochsTrained = myLiviaNet3D.numberOfEpochsTrained
print(" ============== EPOCH: {}/{} =================".format(numberOfEpochsTrained+1,numberOfEpochs))
costsOfEpoch = []
for subE_i in xrange(numberOfSubEpochs):
epoch_nr = subE_i+1
print (" --- SubEPOCH: {}/{}".format(epoch_nr,myLiviaNet3D.numberOfSubEpochs))
# Get all the samples that will be used in this sub-epoch
[imagesSamplesAll,
gt_samplesAll] = getSamplesSubepoch(numberOfSamplesSupEpoch,
imageNames_Train,
groundTruthNames_Train,
roiNames_Train,
imageType,
sampleSize_Train,
receptiveField,
applyPadding
)
# Variable that will contain weights for the cost function
# --- In its current implementation, all the classes have the same weight
weightsCostFunction = np.ones(myLiviaNet3D.n_classes, dtype='float32')
numberBatches = len(imagesSamplesAll) / myLiviaNet3D.batch_Size
myLiviaNet3D.trainingData_x.set_value(imagesSamplesAll, borrow=True)
myLiviaNet3D.trainingData_y.set_value(gt_samplesAll, borrow=True)
costsOfBatches = []
evalResultsSubepoch = np.zeros([ myLiviaNet3D.n_classes, 4 ], dtype="int32")
for b_i in xrange(numberBatches):
# TODO: Make a line that adds a point at each trained batch (Or percentage being updated)
costErrors = myLiviaNet3D.networkModel_Train(b_i, weightsCostFunction)
meanBatchCostError = costErrors[0]
costsOfBatches.append(meanBatchCostError)
myLiviaNet3D.updateLayersMatricesBatchNorm()
#======== Calculate and Report accuracy over subepoch
meanCostOfSubepoch = sum(costsOfBatches) / float(numberBatches)
print(" ---------- Cost of this subEpoch: {}".format(meanCostOfSubepoch))
# Release data
myLiviaNet3D.trainingData_x.set_value(np.zeros([1,1,1,1,1], dtype="float32"))
myLiviaNet3D.trainingData_y.set_value(np.zeros([1,1,1,1], dtype="float32"))
# Get mean cost epoch
costsOfEpoch.append(meanCostOfSubepoch)
meanCostOfEpoch = sum(costsOfEpoch) / float(numberOfSubEpochs)
# Include the epoch cost to the main training cost and update current mean
trainingCost.append(meanCostOfEpoch)
currentMeanCost = sum(trainingCost) / float(str( e_i + 1))
print(" ---------- Training on Epoch #" + str(e_i) + " finished ----------" )
print(" ---------- Cost of Epoch: {} / Mean training error {}".format(meanCostOfEpoch,currentMeanCost))
print(" -------------------------------------------------------- " )
# ------------- Update Learning Rate if required ----------------#
if e_i >= myLiviaNet3D.firstEpochChangeLR :
if learningRateModifiedEpoch == 0:
currentLR = myLiviaNet3D.learning_rate.get_value()
newLR = currentLR / 2.0
myLiviaNet3D.learning_rate.set_value(newLR)
print(" ... Learning rate has been changed from {} to {}".format(currentLR, newLR))
learningRateModifiedEpoch = e_i
else:
if (e_i) == (learningRateModifiedEpoch + myLiviaNet3D.frequencyChangeLR):
currentLR = myLiviaNet3D.learning_rate.get_value()
newLR = currentLR / 2.0
myLiviaNet3D.learning_rate.set_value(newLR)
print(" ... Learning rate has been changed from {} to {}".format(currentLR, newLR))
learningRateModifiedEpoch = e_i
# ---------------------- Start validation ---------------------- #
numberImagesToSegment = len(imageNames_Val)
print(" ********************** Starting validation **********************")
# Run over the images to segment
for i_d in xrange(numberImagesToSegment) :
print("------------- Segmenting subject: {} ....total: {}/{}... -------------".format(names_Val[i_d],str(i_d+1),str(numberImagesToSegment)))
strideValues = myLiviaNet3D.lastLayer.outputShapeTest[2:]
segmentVolume(myLiviaNet3D,
i_d,
imageNames_Val, # Full path
names_Val, # Only image name
groundTruthNames_Val,
roiNames_Val,
imageType,
applyPadding,
receptiveField,
sampleSize_Train,
strideValues,
myLiviaNet3D.batch_Size,
0 # Validation (0) or testing (1)
)
print(" ********************** Validation DONE ********************** ")
# ------ In this point the training is done at Epoch n ---------#
# Increase number of epochs trained
myLiviaNet3D.numberOfEpochsTrained += 1
# --------------- Save the model ---------------
BASE_DIR = os.getcwd()
path_Temp = os.path.join(BASE_DIR,'outputFiles')
netFolderName = os.path.join(path_Temp,myLiviaNet3D.folderName)
netFolderName = os.path.join(netFolderName,'Networks')
modelFileName = netFolderName + "/" + myLiviaNet3D.networkName + "_Epoch" + str (myLiviaNet3D.numberOfEpochsTrained)
dump_model_to_gzip_file(myLiviaNet3D, modelFileName)
strFinal = " Network model saved in " + netFolderName + " as " + myLiviaNet3D.networkName + "_Epoch" + str (myLiviaNet3D.numberOfEpochsTrained)
print (strFinal)
print("................ The whole Training is done.....")
print(" ************************************************************************************ ") |
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, |
injected.rs | use proc_macro2::TokenStream as TokenStream2;
use quote::{quote, ToTokens};
use syn::Ident;
impl<'a> ToTokens for InjectedBody<'a> {
fn to_tokens(&self, stream: &mut TokenStream2) {
let Self {
graph_ident,
imported_graph_ident,
fields,
} = self;
for field in fields {
let ident = &field.ident;
let ty = &field.ty;
let out = quote! {
#ident: #graph_ident
.get_node::<#ty>()
.or_else(|| contraband::graph::Graph::search_all(#imported_graph_ident))
.unwrap()
.to_owned(),
};
stream.extend(out);
}
}
}
pub(crate) struct InjectedBody<'a> {
graph_ident: &'a Ident,
imported_graph_ident: &'a Ident,
fields: Vec<syn::Field>,
}
impl<'a> InjectedBody<'a> {
pub(crate) fn | (
graph_ident: &'a Ident,
imported_graph_ident: &'a Ident,
data: &syn::DataStruct,
) -> syn::Result<Self> {
let mut fields = Vec::new();
match &data.fields {
syn::Fields::Named(fl) => {
for field in fl.named.iter() {
fields.push(field.to_owned());
}
}
syn::Fields::Unit => {}
fields => {
return Err(syn::Error::new_spanned(
fields,
"Unnamed structs are not allowed.",
));
}
}
Ok(Self {
graph_ident,
imported_graph_ident,
fields,
})
}
}
| new |
postal.js | /*
postal
Author: Jim Cowart (http://freshbrewedcode.com/jimcowart)
License: Dual licensed MIT (http://www.opensource.org/licenses/mit-license) & GPL (http://www.opensource.org/licenses/gpl-license)
Version 0.7.3
*/
(function ( root, factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define( ["underscore"], function ( _ ) {
return factory( _, root );
} );
} else {
// Browser globals
factory( root._, root );
}
}( this, function ( _, global, undefined ) {
var DEFAULT_CHANNEL = "/",
DEFAULT_PRIORITY = 50,
DEFAULT_DISPOSEAFTER = 0,
SYSTEM_CHANNEL = "postal",
NO_OP = function () {
};
var ConsecutiveDistinctPredicate = function () {
var previous;
return function ( data ) {
var eq = false;
if ( _.isString( data ) ) {
eq = data === previous;
previous = data;
}
else {
eq = _.isEqual( data, previous );
previous = _.clone( data );
}
return !eq;
};
};
var DistinctPredicate = function () {
var previous = [];
return function (data) {
var isDistinct = !_.any(previous, function (p) {
if (_.isObject(data) || _.isArray(data)) {
return _.isEqual(data, p);
}
return data === p;
});
if (isDistinct) {
previous.push(data);
}
return isDistinct;
};
};
var ChannelDefinition = function ( channelName, defaultTopic ) {
this.channel = channelName || DEFAULT_CHANNEL;
this._topic = defaultTopic || "";
};
ChannelDefinition.prototype = {
subscribe : function () {
var len = arguments.length;
if ( len === 1 ) {
return new SubscriptionDefinition( this.channel, this._topic, arguments[0] );
}
else if ( len === 2 ) {
return new SubscriptionDefinition( this.channel, arguments[0], arguments[1] );
}
},
publish : function ( obj ) {
var _obj = obj || {};
var envelope = {
channel : this.channel,
topic : this._topic,
data : _obj
};
// If this is an envelope....
if ( _obj.topic && _obj.data ) {
envelope = _obj;
envelope.channel = envelope.channel || this.channel;
}
envelope.timeStamp = new Date();
postal.configuration.bus.publish( envelope );
return envelope;
},
topic : function ( topic ) {
if ( topic === this._topic ) {
return this;
}
return new ChannelDefinition( this.channel, topic );
}
};
var SubscriptionDefinition = function ( channel, topic, callback ) {
this.channel = channel;
this.topic = topic;
this.callback = callback;
this.priority = DEFAULT_PRIORITY;
this.constraints = new Array( 0 ); | channel : SYSTEM_CHANNEL,
topic : "subscription.created",
timeStamp : new Date(),
data : {
event : "subscription.created",
channel : channel,
topic : topic
}
} );
postal.configuration.bus.subscribe( this );
};
SubscriptionDefinition.prototype = {
unsubscribe : function () {
postal.configuration.bus.unsubscribe( this );
postal.configuration.bus.publish( {
channel : SYSTEM_CHANNEL,
topic : "subscription.removed",
timeStamp : new Date(),
data : {
event : "subscription.removed",
channel : this.channel,
topic : this.topic
}
} );
},
defer : function () {
var fn = this.callback;
this.callback = function ( data ) {
setTimeout( fn, 0, data );
};
return this;
},
disposeAfter : function ( maxCalls ) {
if ( _.isNaN( maxCalls ) || maxCalls <= 0 ) {
throw "The value provided to disposeAfter (maxCalls) must be a number greater than zero.";
}
var fn = this.onHandled;
var dispose = _.after( maxCalls, _.bind( function () {
this.unsubscribe( this );
}, this ) );
this.onHandled = function () {
fn.apply( this.context, arguments );
dispose();
};
return this;
},
distinctUntilChanged : function () {
this.withConstraint( new ConsecutiveDistinctPredicate() );
return this;
},
distinct : function () {
this.withConstraint( new DistinctPredicate() );
return this;
},
once: function() {
this.disposeAfter(1);
},
withConstraint : function ( predicate ) {
if ( !_.isFunction( predicate ) ) {
throw "Predicate constraint must be a function";
}
this.constraints.push( predicate );
return this;
},
withConstraints : function ( predicates ) {
var self = this;
if ( _.isArray( predicates ) ) {
_.each( predicates, function ( predicate ) {
self.withConstraint( predicate );
} );
}
return self;
},
withContext : function ( context ) {
this.context = context;
return this;
},
withDebounce : function ( milliseconds ) {
if ( _.isNaN( milliseconds ) ) {
throw "Milliseconds must be a number";
}
var fn = this.callback;
this.callback = _.debounce( fn, milliseconds );
return this;
},
withDelay : function ( milliseconds ) {
if ( _.isNaN( milliseconds ) ) {
throw "Milliseconds must be a number";
}
var fn = this.callback;
this.callback = function ( data ) {
setTimeout( function () {
fn( data );
}, milliseconds );
};
return this;
},
withPriority : function ( priority ) {
if ( _.isNaN( priority ) ) {
throw "Priority must be a number";
}
this.priority = priority;
postal.configuration.bus.changePriority( this );
return this;
},
withThrottle : function ( milliseconds ) {
if ( _.isNaN( milliseconds ) ) {
throw "Milliseconds must be a number";
}
var fn = this.callback;
this.callback = _.throttle( fn, milliseconds );
return this;
},
subscribe : function ( callback ) {
this.callback = callback;
return this;
}
};
var bindingsResolver = {
cache : { },
compare : function ( binding, topic ) {
if ( this.cache[topic] && this.cache[topic][binding] ) {
return true;
}
var pattern = ("^" + binding.replace( /\./g, "\\." ) // escape actual periods
.replace( /\*/g, "[A-Z,a-z,0-9]*" ) // asterisks match any alpha-numeric 'word'
.replace( /#/g, ".*" ) + "$") // hash matches 'n' # of words (+ optional on start/end of topic)
.replace( "\\..*$", "(\\..*)*$" ) // fix end of topic matching on hash wildcards
.replace( "^.*\\.", "^(.*\\.)*" ); // fix beginning of topic matching on hash wildcards
var rgx = new RegExp( pattern );
var result = rgx.test( topic );
if ( result ) {
if ( !this.cache[topic] ) {
this.cache[topic] = {};
}
this.cache[topic][binding] = true;
}
return result;
},
reset : function () {
this.cache = {};
}
};
var localBus = {
addWireTap : function ( callback ) {
var self = this;
self.wireTaps.push( callback );
return function () {
var idx = self.wireTaps.indexOf( callback );
if ( idx !== -1 ) {
self.wireTaps.splice( idx, 1 );
}
};
},
changePriority : function ( subDef ) {
var idx, found;
if ( this.subscriptions[subDef.channel] && this.subscriptions[subDef.channel][subDef.topic] ) {
this.subscriptions[subDef.channel][subDef.topic] = _.without( this.subscriptions[subDef.channel][subDef.topic], subDef );
idx = this.subscriptions[subDef.channel][subDef.topic].length - 1;
for ( ; idx >= 0; idx-- ) {
if ( this.subscriptions[subDef.channel][subDef.topic][idx].priority <= subDef.priority ) {
this.subscriptions[subDef.channel][subDef.topic].splice( idx + 1, 0, subDef );
found = true;
break;
}
}
if ( !found ) {
this.subscriptions[subDef.channel][subDef.topic].unshift( subDef );
}
}
},
publish : function ( envelope ) {
_.each( this.wireTaps, function ( tap ) {
tap( envelope.data, envelope );
} );
if ( this.subscriptions[envelope.channel] ) {
_.each( this.subscriptions[envelope.channel], function ( topic ) {
// TODO: research faster ways to handle this than _.clone
_.each( _.clone( topic ), function ( subDef ) {
if ( postal.configuration.resolver.compare( subDef.topic, envelope.topic ) ) {
if ( _.all( subDef.constraints, function ( constraint ) {
return constraint( envelope.data, envelope );
} ) ) {
if ( typeof subDef.callback === 'function' ) {
subDef.callback.apply( subDef.context, [envelope.data, envelope] );
subDef.onHandled();
}
}
}
} );
} );
}
},
reset : function () {
if ( this.subscriptions ) {
_.each( this.subscriptions, function ( channel ) {
_.each( channel, function ( topic ) {
while ( topic.length ) {
topic.pop().unsubscribe();
}
} );
} );
this.subscriptions = {};
}
},
subscribe : function ( subDef ) {
var idx, found, fn, channel = this.subscriptions[subDef.channel], subs;
if ( !channel ) {
channel = this.subscriptions[subDef.channel] = {};
}
subs = this.subscriptions[subDef.channel][subDef.topic];
if ( !subs ) {
subs = this.subscriptions[subDef.channel][subDef.topic] = new Array( 0 );
}
subs.push( subDef );
return subDef;
},
subscriptions : {},
wireTaps : new Array( 0 ),
unsubscribe : function ( config ) {
if ( this.subscriptions[config.channel][config.topic] ) {
var len = this.subscriptions[config.channel][config.topic].length,
idx = 0;
for ( ; idx < len; idx++ ) {
if ( this.subscriptions[config.channel][config.topic][idx] === config ) {
this.subscriptions[config.channel][config.topic].splice( idx, 1 );
break;
}
}
}
}
};
var publishPicker = {
"1" : function ( envelope ) {
if ( !envelope ) {
throw new Error( "publishing from the 'global' postal.publish call requires a valid envelope." );
}
envelope.channel = envelope.channel || DEFAULT_CHANNEL;
envelope.timeStamp = new Date();
postal.configuration.bus.publish( envelope );
return envelope;
},
"2" : function ( topic, data ) {
var envelope = { channel : DEFAULT_CHANNEL, topic : topic, timeStamp : new Date(), data : data };
postal.configuration.bus.publish( envelope );
return envelope;
},
"3" : function ( channel, topic, data ) {
var envelope = { channel : channel, topic : topic, timeStamp : new Date(), data : data };
postal.configuration.bus.publish( envelope );
return envelope;
}
},
channelPicker = {
"1" : function ( chn ) {
var channel = chn, topic, options = {};
if ( Object.prototype.toString.call( channel ) === "[object String]" ) {
channel = DEFAULT_CHANNEL;
topic = chn;
}
else {
channel = chn.channel || DEFAULT_CHANNEL;
topic = chn.topic;
options = chn.options || options;
}
return new postal.channelTypes[ options.type || "local" ]( channel, topic );
},
"2" : function ( chn, tpc ) {
var channel = chn, topic = tpc, options = {};
if ( Object.prototype.toString.call( tpc ) === "[object Object]" ) {
channel = DEFAULT_CHANNEL;
topic = chn;
options = tpc;
}
return new postal.channelTypes[ options.type || "local" ]( channel, topic );
},
"3" : function ( channel, topic, options ) {
return new postal.channelTypes[ options.type || "local" ]( channel, topic );
}
},
sessionInfo = {};
// save some setup time, albeit tiny
localBus.subscriptions[SYSTEM_CHANNEL] = {};
var postal = {
configuration : {
bus : localBus,
resolver : bindingsResolver,
DEFAULT_CHANNEL : DEFAULT_CHANNEL,
DEFAULT_PRIORITY : DEFAULT_PRIORITY,
DEFAULT_DISPOSEAFTER : DEFAULT_DISPOSEAFTER,
SYSTEM_CHANNEL : SYSTEM_CHANNEL
},
channelTypes : {
local : ChannelDefinition
},
channel : function () {
var len = arguments.length;
if ( channelPicker[len] ) {
return channelPicker[len].apply( this, arguments );
}
},
subscribe : function ( options ) {
var callback = options.callback,
topic = options.topic,
channel = options.channel || DEFAULT_CHANNEL;
return new SubscriptionDefinition( channel, topic, callback );
},
publish : function () {
var len = arguments.length;
if ( publishPicker[len] ) {
return publishPicker[len].apply( this, arguments );
}
},
addWireTap : function ( callback ) {
return this.configuration.bus.addWireTap( callback );
},
linkChannels : function ( sources, destinations ) {
var result = [];
if ( !_.isArray( sources ) ) {
sources = [sources];
}
if ( !_.isArray( destinations ) ) {
destinations = [destinations];
}
_.each( sources, function ( source ) {
var sourceTopic = source.topic || "#";
_.each( destinations, function ( destination ) {
var destChannel = destination.channel || DEFAULT_CHANNEL;
result.push(
postal.subscribe( {
channel : source.channel || DEFAULT_CHANNEL,
topic : source.topic || "#",
callback : function ( data, env ) {
var newEnv = _.clone( env );
newEnv.topic = _.isFunction( destination.topic ) ? destination.topic( env.topic ) : destination.topic || env.topic;
newEnv.channel = destChannel;
newEnv.data = data;
postal.publish( newEnv );
}
} )
);
} );
} );
return result;
},
utils : {
getSubscribersFor : function () {
var channel = arguments[ 0 ],
tpc = arguments[ 1 ],
result = [];
if ( arguments.length === 1 ) {
if ( Object.prototype.toString.call( channel ) === "[object String]" ) {
channel = postal.configuration.DEFAULT_CHANNEL;
tpc = arguments[ 0 ];
}
else {
channel = arguments[ 0 ].channel || postal.configuration.DEFAULT_CHANNEL;
tpc = arguments[ 0 ].topic;
}
}
if ( postal.configuration.bus.subscriptions[ channel ] &&
postal.configuration.bus.subscriptions[ channel ].hasOwnProperty( tpc ) ) {
result = postal.configuration.bus.subscriptions[ channel ][ tpc ];
}
return result;
},
reset : function () {
postal.configuration.bus.reset();
postal.configuration.resolver.reset();
}
}
};
global.postal = postal;
return postal;
} )); | this.maxCalls = DEFAULT_DISPOSEAFTER;
this.onHandled = NO_OP;
this.context = null;
postal.configuration.bus.publish( { |
server.py | import logging
import os
import random
import click
import flask
from OpenSSL import crypto
from pegaflow.service import cache
from pegaflow.service._encoder import PegasusJsonEncoder
from pegaflow.service.base import BooleanConverter
from pegaflow.service.filters import register_jinja2_filters
from pegaflow.service.lifecycle import register_lifecycle_handlers
log = logging.getLogger(__name__)
# Services
services = ["dashboard", "monitoring"]
def generate_self_signed_certificate(certfile, pkeyfile):
"""
SSL.
:param certfile:
:param pkeyfile:
:return:
If certfile and pkeyfile don't exist, create a self-signed certificate
"""
if os.path.isfile(certfile) and os.path.isfile(pkeyfile):
return
logging.info("Generating self-signed certificate")
pkey = crypto.PKey()
pkey.generate_key(crypto.TYPE_RSA, 2048)
cert = crypto.X509()
sub = cert.get_subject()
sub.C = "US"
sub.ST = "California"
sub.L = "Marina Del Rey"
sub.O = "University of Southern California"
sub.OU = "Information Sciences Institute"
sub.CN = "Pegasus Service"
cert.set_version(1)
cert.set_serial_number(random.randint(0, 2 ** 32))
cert.gmtime_adj_notBefore(0)
cert.gmtime_adj_notAfter(10 * 365 * 24 * 60 * 60) # 10 years
cert.set_issuer(sub)
cert.set_pubkey(pkey)
cert.sign(pkey, "sha1")
open(certfile, "wb").write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
open(pkeyfile, "wb").write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))
def run(host="localhost", port=5000, debug=True, verbose=logging.INFO, **kwargs):
app = create_app(env=os.getenv("FLASK_ENV", "development"))
if debug:
app.config.update(DEBUG=True)
logging.getLogger().setLevel(logging.DEBUG)
pegasusdir = os.path.expanduser("~/.pegasus")
if not os.path.isdir(pegasusdir):
os.makedirs(pegasusdir, mode=0o744)
cert = app.config.get("CERTIFICATE", None)
pkey = app.config.get("PRIVATE_KEY", None)
if cert is None or pkey is None:
log.warning("SSL is not configured: Using self-signed certificate")
cert = os.path.expanduser("~/.pegasus/selfcert.pem")
pkey = os.path.expanduser("~/.pegasus/selfkey.pem")
generate_self_signed_certificate(cert, pkey)
ssl_context = (cert, pkey)
if os.getuid() != 0:
log.warning("Service not running as root: Will not be able to switch users")
app.run(
host=host, port=port, threaded=True, ssl_context=ssl_context,
)
log.info("Exiting")
def _load_user_config(app):
# Load user configuration
|
def create_app(config=None, env="development"):
"""Configure app."""
# Environment
os.environ["FLASK_ENV"] = env
app = flask.Flask(__name__)
# Flask Configuration
app.config.from_object("Pegasus.service.defaults")
# app.config.from_object("Pegasus.service.config.%sConfig" % env.capitalize())
_load_user_config(app)
app.config.update(config or {})
if "PEGASUS_ENV" in os.environ:
app.config.from_envvar("PEGASUS_ENV")
# Initialize Extensions
cache.init_app(app)
# db.init_app(app)
# socketio.init_app(app, json=flask.json)
configure_app(app)
# Service Configuration
for service in services:
config_method = "configure_%s" % service
if config_method in globals():
globals()["configure_%s" % service](app)
return app
def configure_app(app):
#
# Flask URL variables support int, float, and path converters.
# Adding support for a boolean converter.
#
app.url_map.converters["boolean"] = BooleanConverter
#
# Relax trailing slash requirement
#
app.url_map.strict_slashes = False
# Attach global JSONEncoder
app.json_encoder = PegasusJsonEncoder
# Register lifecycle methods
register_lifecycle_handlers(app)
# Register Jinja2 Filters
register_jinja2_filters(app)
# Error handlers
## register_error_handlers(app)
...
def configure_dashboard(app):
from pegaflow.service.dashboard import blueprint
app.register_blueprint(blueprint)
def configure_monitoring(app):
from pegaflow.service.monitoring import monitoring
app.register_blueprint(monitoring, url_prefix="/api/v1/user/<string:username>")
@click.command(name="pegasus-service")
@click.option(
"--host",
default="localhost",
metavar="<hostname>",
show_default=True,
help="Hostname",
)
@click.option(
"-p",
"--port",
type=int,
default=5000,
metavar="<port-number>",
show_default=True,
help="Port no. on which to listen for requests",
)
@click.option(
"-d/-nd",
"--debug/--no-debug",
default=True,
metavar="<debug-mode>",
help="Start server in development mode",
)
@click.option(
"-v",
"--verbose",
default=logging.DEBUG,
count=True,
metavar="<verbosity>",
help="Logging verbosity",
)
def main(host: str, port: int, debug: bool, verbose: int):
"""Run the Pegasus Service server."""
run(host=host, port=port, debug=debug, verbose=verbose)
if __name__ == "__main__":
main()
| conf = os.path.expanduser("~/.pegasus/service.py")
if os.path.isfile(conf):
app.config.from_pyfile(conf) |
apps.py | from django.apps import AppConfig
class InvoicebookConfig(AppConfig): | name = 'InvoiceBook' | |
decorators.py |
from functools import wraps
from django.http import HttpResponse
from rest_framework.response import Response
from rest_framework import status
from website.constants import WIDGET_NAMES
def | (function):
@wraps(function)
def decorator(request, *a, **k):
if request.user.userprofile.can_use_widget(WIDGET_NAMES.memetext):
return function(request, *a, **k)
else:
return HttpResponse(
"<h1>ERROR 401: No access to this widget.</h1>", # should be 403
status=status.HTTP_401_UNAUTHORIZED,
)
return decorator
def user_can_use_api_widget(function):
@wraps(function)
def decorator(request, *a, **k):
if request.user.userprofile.can_use_widget(WIDGET_NAMES.memetext):
return function(request, *a, **k)
else:
return Response(
"no access to this widget",
status.HTTP_401_UNAUTHORIZED, # should be 403
)
return decorator
| user_can_use_web_widget |
asset_set_asset_status.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.25.0
// protoc v3.18.1
// source: google/ads/googleads/v10/enums/asset_set_asset_status.proto
package enums
import (
proto "github.com/golang/protobuf/proto"
_ "google.golang.org/genproto/googleapis/api/annotations"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
// This is a compile-time assertion that a sufficiently up-to-date version
// of the legacy proto package is being used.
const _ = proto.ProtoPackageIsVersion4
type AssetSetAssetStatusEnum_AssetSetAssetStatus int32
const (
AssetSetAssetStatusEnum_UNSPECIFIED AssetSetAssetStatusEnum_AssetSetAssetStatus = 0
AssetSetAssetStatusEnum_UNKNOWN AssetSetAssetStatusEnum_AssetSetAssetStatus = 1
AssetSetAssetStatusEnum_ENABLED AssetSetAssetStatusEnum_AssetSetAssetStatus = 2
AssetSetAssetStatusEnum_REMOVED AssetSetAssetStatusEnum_AssetSetAssetStatus = 3
)
// Enum value maps for AssetSetAssetStatusEnum_AssetSetAssetStatus.
var (
AssetSetAssetStatusEnum_AssetSetAssetStatus_name = map[int32]string{
0: "UNSPECIFIED",
1: "UNKNOWN",
2: "ENABLED",
3: "REMOVED",
}
AssetSetAssetStatusEnum_AssetSetAssetStatus_value = map[string]int32{
"UNSPECIFIED": 0,
"UNKNOWN": 1,
"ENABLED": 2,
"REMOVED": 3,
}
)
func (x AssetSetAssetStatusEnum_AssetSetAssetStatus) Enum() *AssetSetAssetStatusEnum_AssetSetAssetStatus {
p := new(AssetSetAssetStatusEnum_AssetSetAssetStatus)
*p = x
return p
}
func (x AssetSetAssetStatusEnum_AssetSetAssetStatus) String() string {
return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
}
func (AssetSetAssetStatusEnum_AssetSetAssetStatus) Descriptor() protoreflect.EnumDescriptor {
return file_google_ads_googleads_v10_enums_asset_set_asset_status_proto_enumTypes[0].Descriptor()
}
func (AssetSetAssetStatusEnum_AssetSetAssetStatus) Type() protoreflect.EnumType {
return &file_google_ads_googleads_v10_enums_asset_set_asset_status_proto_enumTypes[0]
}
func (x AssetSetAssetStatusEnum_AssetSetAssetStatus) Number() protoreflect.EnumNumber {
return protoreflect.EnumNumber(x)
}
// Deprecated: Use AssetSetAssetStatusEnum_AssetSetAssetStatus.Descriptor instead.
func (AssetSetAssetStatusEnum_AssetSetAssetStatus) EnumDescriptor() ([]byte, []int) {
return file_google_ads_googleads_v10_enums_asset_set_asset_status_proto_rawDescGZIP(), []int{0, 0}
}
type AssetSetAssetStatusEnum struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
}
func (x *AssetSetAssetStatusEnum) Reset() {
*x = AssetSetAssetStatusEnum{}
if protoimpl.UnsafeEnabled {
mi := &file_google_ads_googleads_v10_enums_asset_set_asset_status_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *AssetSetAssetStatusEnum) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AssetSetAssetStatusEnum) ProtoMessage() {}
func (x *AssetSetAssetStatusEnum) ProtoReflect() protoreflect.Message {
mi := &file_google_ads_googleads_v10_enums_asset_set_asset_status_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AssetSetAssetStatusEnum.ProtoReflect.Descriptor instead.
func (*AssetSetAssetStatusEnum) Descriptor() ([]byte, []int) {
return file_google_ads_googleads_v10_enums_asset_set_asset_status_proto_rawDescGZIP(), []int{0}
}
var File_google_ads_googleads_v10_enums_asset_set_asset_status_proto protoreflect.FileDescriptor
var file_google_ads_googleads_v10_enums_asset_set_asset_status_proto_rawDesc = []byte{
0x0a, 0x3b, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, 0x64, 0x73, 0x2f, 0x67, 0x6f, 0x6f,
0x67, 0x6c, 0x65, 0x61, 0x64, 0x73, 0x2f, 0x76, 0x31, 0x30, 0x2f, 0x65, 0x6e, 0x75, 0x6d, 0x73,
0x2f, 0x61, 0x73, 0x73, 0x65, 0x74, 0x5f, 0x73, 0x65, 0x74, 0x5f, 0x61, 0x73, 0x73, 0x65, 0x74,
0x5f, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x1e, 0x67,
0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x64, 0x73, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65,
0x61, 0x64, 0x73, 0x2e, 0x76, 0x31, 0x30, 0x2e, 0x65, 0x6e, 0x75, 0x6d, 0x73, 0x1a, 0x1c, 0x67,
0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61,
0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x68, 0x0a, 0x17, 0x41,
0x73, 0x73, 0x65, 0x74, 0x53, 0x65, 0x74, 0x41, 0x73, 0x73, 0x65, 0x74, 0x53, 0x74, 0x61, 0x74,
0x75, 0x73, 0x45, 0x6e, 0x75, 0x6d, 0x22, 0x4d, 0x0a, 0x13, 0x41, 0x73, 0x73, 0x65, 0x74, 0x53,
0x65, 0x74, 0x41, 0x73, 0x73, 0x65, 0x74, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x0f, 0x0a,
0x0b, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x0b,
0x0a, 0x07, 0x55, 0x4e, 0x4b, 0x4e, 0x4f, 0x57, 0x4e, 0x10, 0x01, 0x12, 0x0b, 0x0a, 0x07, 0x45,
0x4e, 0x41, 0x42, 0x4c, 0x45, 0x44, 0x10, 0x02, 0x12, 0x0b, 0x0a, 0x07, 0x52, 0x45, 0x4d, 0x4f,
0x56, 0x45, 0x44, 0x10, 0x03, 0x42, 0xf2, 0x01, 0x0a, 0x22, 0x63, 0x6f, 0x6d, 0x2e, 0x67, 0x6f,
0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x64, 0x73, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61,
0x64, 0x73, 0x2e, 0x76, 0x31, 0x30, 0x2e, 0x65, 0x6e, 0x75, 0x6d, 0x73, 0x42, 0x18, 0x41, 0x73,
0x73, 0x65, 0x74, 0x53, 0x65, 0x74, 0x41, 0x73, 0x73, 0x65, 0x74, 0x53, 0x74, 0x61, 0x74, 0x75,
0x73, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x43, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65,
0x2e, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x67, 0x65, 0x6e, 0x70,
0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2f,
0x61, 0x64, 0x73, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x64, 0x73, 0x2f, 0x76, 0x31,
0x30, 0x2f, 0x65, 0x6e, 0x75, 0x6d, 0x73, 0x3b, 0x65, 0x6e, 0x75, 0x6d, 0x73, 0xa2, 0x02, 0x03,
0x47, 0x41, 0x41, 0xaa, 0x02, 0x1e, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x41, 0x64, 0x73,
0x2e, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x41, 0x64, 0x73, 0x2e, 0x56, 0x31, 0x30, 0x2e, 0x45,
0x6e, 0x75, 0x6d, 0x73, 0xca, 0x02, 0x1e, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x5c, 0x41, 0x64,
0x73, 0x5c, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x41, 0x64, 0x73, 0x5c, 0x56, 0x31, 0x30, 0x5c,
0x45, 0x6e, 0x75, 0x6d, 0x73, 0xea, 0x02, 0x22, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x3a, 0x3a,
0x41, 0x64, 0x73, 0x3a, 0x3a, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x41, 0x64, 0x73, 0x3a, 0x3a,
0x56, 0x31, 0x30, 0x3a, 0x3a, 0x45, 0x6e, 0x75, 0x6d, 0x73, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74,
0x6f, 0x33,
}
var (
file_google_ads_googleads_v10_enums_asset_set_asset_status_proto_rawDescOnce sync.Once
file_google_ads_googleads_v10_enums_asset_set_asset_status_proto_rawDescData = file_google_ads_googleads_v10_enums_asset_set_asset_status_proto_rawDesc
)
func file_google_ads_googleads_v10_enums_asset_set_asset_status_proto_rawDescGZIP() []byte {
file_google_ads_googleads_v10_enums_asset_set_asset_status_proto_rawDescOnce.Do(func() {
file_google_ads_googleads_v10_enums_asset_set_asset_status_proto_rawDescData = protoimpl.X.CompressGZIP(file_google_ads_googleads_v10_enums_asset_set_asset_status_proto_rawDescData)
})
return file_google_ads_googleads_v10_enums_asset_set_asset_status_proto_rawDescData
}
var file_google_ads_googleads_v10_enums_asset_set_asset_status_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
var file_google_ads_googleads_v10_enums_asset_set_asset_status_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_google_ads_googleads_v10_enums_asset_set_asset_status_proto_goTypes = []interface{}{
(AssetSetAssetStatusEnum_AssetSetAssetStatus)(0), // 0: google.ads.googleads.v10.enums.AssetSetAssetStatusEnum.AssetSetAssetStatus
(*AssetSetAssetStatusEnum)(nil), // 1: google.ads.googleads.v10.enums.AssetSetAssetStatusEnum
}
var file_google_ads_googleads_v10_enums_asset_set_asset_status_proto_depIdxs = []int32{
0, // [0:0] is the sub-list for method output_type
0, // [0:0] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() |
func file_google_ads_googleads_v10_enums_asset_set_asset_status_proto_init() {
if File_google_ads_googleads_v10_enums_asset_set_asset_status_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_google_ads_googleads_v10_enums_asset_set_asset_status_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*AssetSetAssetStatusEnum); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_google_ads_googleads_v10_enums_asset_set_asset_status_proto_rawDesc,
NumEnums: 1,
NumMessages: 1,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_google_ads_googleads_v10_enums_asset_set_asset_status_proto_goTypes,
DependencyIndexes: file_google_ads_googleads_v10_enums_asset_set_asset_status_proto_depIdxs,
EnumInfos: file_google_ads_googleads_v10_enums_asset_set_asset_status_proto_enumTypes,
MessageInfos: file_google_ads_googleads_v10_enums_asset_set_asset_status_proto_msgTypes,
}.Build()
File_google_ads_googleads_v10_enums_asset_set_asset_status_proto = out.File
file_google_ads_googleads_v10_enums_asset_set_asset_status_proto_rawDesc = nil
file_google_ads_googleads_v10_enums_asset_set_asset_status_proto_goTypes = nil
file_google_ads_googleads_v10_enums_asset_set_asset_status_proto_depIdxs = nil
}
| { file_google_ads_googleads_v10_enums_asset_set_asset_status_proto_init() } |
analytical.py | """
Analytical template tags and filters.
"""
from __future__ import absolute_import
import logging
from django import template
from django.template import Node, TemplateSyntaxError
from importlib import import_module
from analytical.utils import AnalyticalException
TAG_LOCATIONS = ['head_top', 'head_bottom', 'body_top', 'body_bottom']
TAG_POSITIONS = ['first', None, 'last']
TAG_MODULES = [
'analytical.chartbeat',
'analytical.clickmap',
'analytical.clicky',
'analytical.crazy_egg',
'analytical.facebook_pixel',
'analytical.gauges',
'analytical.google_analytics',
'analytical.google_analytics_js',
'analytical.gosquared',
'analytical.hotjar',
'analytical.hubspot',
'analytical.intercom',
'analytical.kiss_insights',
'analytical.kiss_metrics',
'analytical.matomo',
'analytical.mixpanel',
'analytical.olark',
'analytical.optimizely',
'analytical.performable',
'analytical.piwik', | 'analytical.snapengage',
'analytical.spring_metrics',
'analytical.uservoice',
'analytical.woopra',
'analytical.yandex_metrica',
]
logger = logging.getLogger(__name__)
register = template.Library()
def _location_tag(location):
def analytical_tag(parser, token):
bits = token.split_contents()
if len(bits) > 1:
raise TemplateSyntaxError("'%s' tag takes no arguments" % bits[0])
return AnalyticalNode(location)
return analytical_tag
for loc in TAG_LOCATIONS:
register.tag('analytical_%s' % loc, _location_tag(loc))
class AnalyticalNode(Node):
def __init__(self, location):
self.nodes = [node_cls() for node_cls in template_nodes[location]]
def render(self, context):
return "".join([node.render(context) for node in self.nodes])
def _load_template_nodes():
template_nodes = dict((l, dict((p, []) for p in TAG_POSITIONS))
for l in TAG_LOCATIONS)
def add_node_cls(location, node, position=None):
template_nodes[location][position].append(node)
for path in TAG_MODULES:
module = _import_tag_module(path)
try:
module.contribute_to_analytical(add_node_cls)
except AnalyticalException as e:
logger.debug("not loading tags from '%s': %s", path, e)
for location in TAG_LOCATIONS:
template_nodes[location] = sum((template_nodes[location][p]
for p in TAG_POSITIONS), [])
return template_nodes
def _import_tag_module(path):
app_name, lib_name = path.rsplit('.', 1)
return import_module("%s.templatetags.%s" % (app_name, lib_name))
template_nodes = _load_template_nodes() | 'analytical.rating_mailru', |
repeated_computed_layer.py | #!/usr/bin/env python
import torch
import torch.nn as nn
from colossalai.nn import CheckpointModule
from .utils.dummy_data_generator import DummyDataGenerator
from .registry import non_distributed_component_funcs
class NetWithRepeatedlyComputedLayers(CheckpointModule):
"""
This model is to test with layers which go through forward pass multiple times.
In this model, the fc1 and fc2 call forward twice
"""
def __init__(self, checkpoint=False) -> None:
super().__init__(checkpoint=checkpoint)
self.fc1 = nn.Linear(5, 5)
self.fc2 = nn.Linear(5, 5)
self.fc3 = nn.Linear(5, 2)
self.layers = [self.fc1, self.fc2, self.fc1, self.fc2, self.fc3]
def forward(self, x):
for layer in self.layers:
x = layer(x)
return x
class DummyDataLoader(DummyDataGenerator):
def generate(self):
data = torch.rand(16, 5)
label = torch.randint(low=0, high=2, size=(16,))
return data, label
@non_distributed_component_funcs.register(name='repeated_computed_layers')
def get_training_components():
def model_builder(checkpoint=True):
return NetWithRepeatedlyComputedLayers(checkpoint)
trainloader = DummyDataLoader()
testloader = DummyDataLoader() | criterion = torch.nn.CrossEntropyLoss()
return model_builder, trainloader, testloader, torch.optim.Adam, criterion | |
min_height_overrides_height_on_root.rs | pub fn compute() | {
let mut stretch = stretch::Stretch::new();
let node = stretch
.new_node(
stretch::style::Style {
size: stretch::geometry::Size {
height: stretch::style::Dimension::Points(50f32),
..Default::default()
},
min_size: stretch::geometry::Size {
height: stretch::style::Dimension::Points(100f32),
..Default::default()
},
..Default::default()
},
vec![],
)
.unwrap();
stretch.compute_layout(node, stretch::geometry::Size::undefined()).unwrap();
} |
|
tests.rs | use crate::{
canister_manager::tests::InstallCodeContextBuilder,
canister_manager::{CanisterManager, CanisterMgrConfig},
canister_settings::CanisterSettings,
hypervisor::Hypervisor,
IngressHistoryWriterImpl, InternalHttpQueryHandler,
};
use ic_base_types::NumSeconds;
use ic_config::{execution_environment::Config, flag_status::FlagStatus};
use ic_error_types::ErrorCode;
use ic_interfaces::execution_environment::{
AvailableMemory, ExecutionMode, ExecutionParameters, QueryHandler,
};
use ic_metrics::MetricsRegistry;
use ic_registry_routing_table::{CanisterIdRange, RoutingTable};
use ic_registry_subnet_type::SubnetType;
use ic_replicated_state::ReplicatedState;
use ic_test_utilities::{
cycles_account_manager::CyclesAccountManagerBuilder,
types::ids::{canister_test_id, subnet_test_id, user_test_id},
universal_canister::{call_args, wasm, UNIVERSAL_CANISTER_WASM},
with_test_replica_logger,
};
use ic_types::{ingress::WasmResult, messages::UserQuery, ComputeAllocation};
use ic_types::{CanisterId, Cycles, NumBytes, NumInstructions, SubnetId};
use maplit::btreemap;
use std::{convert::TryFrom, path::Path, sync::Arc};
const CYCLE_BALANCE: Cycles = Cycles::new(100_000_000_000_000);
const INSTRUCTION_LIMIT: NumInstructions = NumInstructions::new(1_000_000_000);
const MEMORY_CAPACITY: NumBytes = NumBytes::new(1_000_000_000);
const MAX_NUMBER_OF_CANISTERS: u64 = 0;
fn with_setup<F>(subnet_type: SubnetType, f: F)
where
F: FnOnce(InternalHttpQueryHandler, CanisterManager, ReplicatedState),
{
fn canister_manager_config(subnet_id: SubnetId, subnet_type: SubnetType) -> CanisterMgrConfig {
CanisterMgrConfig::new(
MEMORY_CAPACITY,
CYCLE_BALANCE,
NumSeconds::from(100_000),
subnet_id,
subnet_type,
1000,
1,
FlagStatus::Enabled,
)
}
fn initial_state(path: &Path, subnet_id: SubnetId, subnet_type: SubnetType) -> ReplicatedState {
let routing_table = Arc::new(RoutingTable::try_from(btreemap! {
CanisterIdRange{ start: CanisterId::from(0), end: CanisterId::from(0xff) } => subnet_id,
}).unwrap());
let mut state = ReplicatedState::new_rooted_at(subnet_id, subnet_type, path.to_path_buf());
state.metadata.network_topology.routing_table = routing_table;
state.metadata.network_topology.nns_subnet_id = subnet_id;
state
}
with_test_replica_logger(|log| {
let subnet_id = subnet_test_id(1);
let metrics_registry = MetricsRegistry::new();
let cycles_account_manager = Arc::new(CyclesAccountManagerBuilder::new().build());
let hypervisor = Hypervisor::new(
Config::default(),
&metrics_registry,
subnet_id,
subnet_type,
log.clone(),
Arc::clone(&cycles_account_manager),
);
let hypervisor = Arc::new(hypervisor);
let ingress_history_writer = Arc::new(IngressHistoryWriterImpl::new(
Config::default(),
log.clone(),
&metrics_registry,
));
let canister_manager = CanisterManager::new(
Arc::clone(&hypervisor) as Arc<_>,
log.clone(),
canister_manager_config(subnet_id, subnet_type),
cycles_account_manager,
ingress_history_writer,
);
let tmpdir = tempfile::Builder::new().prefix("test").tempdir().unwrap();
let state = initial_state(tmpdir.path(), subnet_id, subnet_type);
let query_handler = InternalHttpQueryHandler::new(
log,
hypervisor,
subnet_type,
Config::default(),
&metrics_registry,
INSTRUCTION_LIMIT,
);
f(query_handler, canister_manager, state);
});
}
fn universal_canister(
canister_manager: &CanisterManager,
state: &mut ReplicatedState,
) -> CanisterId {
let sender = canister_test_id(1).get();
let sender_subnet_id = subnet_test_id(1);
let canister_id = canister_manager
.create_canister(
sender,
sender_subnet_id,
CYCLE_BALANCE,
CanisterSettings::default(),
MAX_NUMBER_OF_CANISTERS,
state,
)
.0
.unwrap();
canister_manager
.install_code(
InstallCodeContextBuilder::default()
.sender(sender)
.canister_id(canister_id)
.wasm_module(UNIVERSAL_CANISTER_WASM.to_vec())
.build(),
state,
ExecutionParameters {
total_instruction_limit: INSTRUCTION_LIMIT,
slice_instruction_limit: INSTRUCTION_LIMIT,
canister_memory_limit: MEMORY_CAPACITY,
subnet_available_memory: AvailableMemory::new(
MEMORY_CAPACITY.get() as i64,
MEMORY_CAPACITY.get() as i64,
)
.into(),
compute_allocation: ComputeAllocation::default(),
subnet_type: SubnetType::Application,
execution_mode: ExecutionMode::Replicated,
},
)
.1
.unwrap();
canister_id
}
#[test]
fn query_metrics_are_reported() {
with_setup(
SubnetType::VerifiedApplication,
|query_handler, canister_manager, mut state| {
// In this test we have two canisters A and B.
// Canister A handles the user query by calling canister B.
let canister_a = universal_canister(&canister_manager, &mut state);
let canister_b = universal_canister(&canister_manager, &mut state);
let output = query_handler.query(
UserQuery {
source: user_test_id(2),
receiver: canister_a,
method_name: "query".to_string(),
method_payload: wasm()
.inter_query(
canister_b,
call_args().other_side(wasm().reply_data(b"pong".as_ref())),
)
.build(),
ingress_expiry: 0,
nonce: None,
},
Arc::new(state),
vec![],
);
assert_eq!(output, Ok(WasmResult::Reply(b"pong".to_vec())));
assert_eq!(1, query_handler.metrics.query.duration.get_sample_count());
assert_eq!(
1,
query_handler.metrics.query.instructions.get_sample_count()
);
assert!(0 < query_handler.metrics.query.instructions.get_sample_sum() as u64);
assert_eq!(1, query_handler.metrics.query.messages.get_sample_count());
// We expect four messages:
// - canister_a.query() as pure
// - canister_a.query() as stateful
// - canister_b.query() as stateful
// - canister_a.on_reply()
assert_eq!(
4,
query_handler.metrics.query.messages.get_sample_sum() as u64
);
assert_eq!(
1,
query_handler
.metrics
.query_initial_call
.duration
.get_sample_count()
);
assert!(
0 < query_handler
.metrics
.query_initial_call
.instructions
.get_sample_sum() as u64
);
assert_eq!(
1,
query_handler
.metrics
.query_initial_call
.instructions
.get_sample_count()
);
assert_eq!(
1,
query_handler
.metrics
.query_initial_call
.messages
.get_sample_count()
);
assert_eq!(
1,
query_handler
.metrics
.query_initial_call
.messages
.get_sample_sum() as u64
);
assert_eq!(
1,
query_handler
.metrics
.query_retry_call
.duration
.get_sample_count()
);
assert_eq!(
1,
query_handler
.metrics
.query_spawned_calls
.duration
.get_sample_count()
);
assert_eq!(
1,
query_handler
.metrics
.query_spawned_calls
.instructions
.get_sample_count()
);
assert!(
0 < query_handler
.metrics
.query_spawned_calls
.instructions
.get_sample_sum() as u64
);
assert_eq!(
1,
query_handler
.metrics
.query_spawned_calls
.messages
.get_sample_count()
);
assert_eq!(
2,
query_handler
.metrics
.query_spawned_calls
.messages
.get_sample_sum() as u64
);
assert_eq!(
query_handler.metrics.query.instructions.get_sample_sum() as u64,
query_handler
.metrics
.query_initial_call
.instructions
.get_sample_sum() as u64
+ query_handler
.metrics
.query_retry_call
.instructions
.get_sample_sum() as u64
+ query_handler
.metrics
.query_spawned_calls
.instructions
.get_sample_sum() as u64
)
},
);
}
#[test]
fn query_call_with_side_effects() {
with_setup(
SubnetType::System,
|query_handler, canister_manager, mut state| {
// In this test we have two canisters A and B.
// Canister A does a side-effectful operation (stable_grow) and then
// calls canister B. The side effect must happen once and only once.
let canister_a = universal_canister(&canister_manager, &mut state);
let canister_b = universal_canister(&canister_manager, &mut state);
let output = query_handler.query(
UserQuery {
source: user_test_id(2),
receiver: canister_a,
method_name: "query".to_string(),
method_payload: wasm()
.stable_grow(10)
.inter_query(
canister_b,
call_args()
.other_side(wasm().reply_data(b"ignore".as_ref()))
.on_reply(wasm().stable_size().reply_int()),
)
.build(),
ingress_expiry: 0,
nonce: None,
},
Arc::new(state),
vec![],
);
assert_eq!(output, Ok(WasmResult::Reply(10_i32.to_le_bytes().to_vec())));
},
);
}
#[test]
fn query_calls_disabled_for_application_subnet() |
#[test]
fn query_compilied_once() {
with_setup(
SubnetType::Application,
|query_handler, canister_manager, mut state| {
let canister_id = universal_canister(&canister_manager, &mut state);
let canister = state.canister_state_mut(&canister_id).unwrap();
// The canister was compiled during installation.
assert_eq!(1, query_handler.hypervisor.compile_count());
// Drop the embedder cache to force compilation during query handling.
canister
.execution_state
.as_mut()
.unwrap()
.wasm_binary
.clear_compilation_cache();
let result = query_handler.query(
UserQuery {
source: user_test_id(2),
receiver: canister_id,
method_name: "query".to_string(),
method_payload: wasm().reply().build(),
ingress_expiry: 0,
nonce: None,
},
Arc::new(state.clone()),
vec![],
);
assert!(result.is_ok());
// Now we expect the compilation counter to increase because the query
// had to compile.
assert_eq!(2, query_handler.hypervisor.compile_count());
let result = query_handler.query(
UserQuery {
source: user_test_id(2),
receiver: canister_id,
method_name: "query".to_string(),
method_payload: wasm().reply().build(),
ingress_expiry: 0,
nonce: None,
},
Arc::new(state),
vec![],
);
assert!(result.is_ok());
// The last query should have reused the compiled code.
assert_eq!(2, query_handler.hypervisor.compile_count());
},
);
}
| {
with_setup(
SubnetType::Application,
|query_handler, canister_manager, mut state| {
// In this test we have two canisters A and B.
// Canister A does a side-effectful operation (stable_grow) and then
// calls canister B. The side effect must happen once and only once.
let canister_a = universal_canister(&canister_manager, &mut state);
let canister_b = universal_canister(&canister_manager, &mut state);
let output = query_handler.query(
UserQuery {
source: user_test_id(2),
receiver: canister_a,
method_name: "query".to_string(),
method_payload: wasm()
.stable_grow(10)
.inter_query(
canister_b,
call_args()
.other_side(wasm().reply_data(b"ignore".as_ref()))
.on_reply(wasm().stable_size().reply_int()),
)
.build(),
ingress_expiry: 0,
nonce: None,
},
Arc::new(state),
vec![],
);
match output {
Ok(_) => unreachable!("The query was expected to fail, but it succeeded."),
Err(err) => assert_eq!(err.code(), ErrorCode::CanisterContractViolation),
}
},
);
} |
algebraic.py | """ Functions for algebraic fitting """
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
import numpy as np
MODE_DICT_ELLIPSE = {'circle': 'xy', 'ellipse_aligned': '0', 'ellipse': ''}
MODE_DICT_ELLIPSOID = {'sphere': 'xyz', 'prolate': 'xy', 'oblate': 'xy',
'ellipsoid': '', 'ellipsoid_aligned': '0',
'prolate_aligned': '0xy', 'oblate_aligned': '0xy'}
def fit_ellipse(coords, mode=''):
""" Fits an ellipse to datapoints using an algebraic method.
This method is different from least squares minimization of the distnace
between each datapoint and the fitted ellipse (so-called geometrical
approach). For circles, this makes no difference. The higher the aspect
ratio of the ellipse, the worse the approximation gets.
Parameters
----------
coords : numpy array of floats
array of shape (N, 2) containing datapoints
mode : {'circle', 'ellipse', 'ellipse_aligned'}
'ellipse' or None fits an arbitrary ellipse (default)
'circle' fits a circle
'ellipse_aligned' fits an ellipse with its axes aligned along [x y] axes
Returns
-------
center, radii, angle
References
----------
.. [1] Bertoni B (2010) Multi-dimensional ellipsoidal fitting.
"""
if coords.shape[0] != 2:
raise ValueError('Input data must have two columns!')
if mode in MODE_DICT_ELLIPSE:
mode = MODE_DICT_ELLIPSE[mode]
x = coords[0, :, np.newaxis]
y = coords[1, :, np.newaxis]
if mode == '':
D = np.hstack((x**2 - y**2, 2*x*y, 2*x, 2*y, np.ones_like(x)))
elif mode == '0':
D = np.hstack((x**2 - y**2, 2*x, 2*y, np.ones_like(x)))
elif mode == 'xy':
D = np.hstack((2*x, 2*y, np.ones_like(x)))
d2 = x**2 + y**2 # the RHS of the llsq problem (y's)
u = np.linalg.solve(np.dot(D.T, D), (np.dot(D.T, d2)))[:, 0]
v = np.empty((6), dtype=u.dtype)
if mode == '':
v[0] = u[0] - 1
v[1] = -u[0] - 1
v[2:] = u[1:]
elif mode == '0':
v[0] = u[0] - 1
v[1] = -u[0] - 1
v[2] = 0
v[3:] = u[1:]
elif mode == 'xy':
v[:2] = -1
v[2] = 0
v[3:] = u
A = np.array([[v[0], v[2], v[3]],
[v[2], v[1], v[4]],
[v[3], v[4], v[5]]])
# find the center of the ellipse
center = -np.linalg.solve(A[:2, :2], v[3:5])
# translate to the center
T = np.identity(3, dtype=A.dtype)
T[2, :2] = center
R = np.dot(np.dot(T, A), T.T)
# solve the eigenproblem
evals, evecs = np.linalg.eig(R[:2, :2] / -R[2, 2])
radius = (np.sqrt(1 / np.abs(evals)) * np.sign(evals))
if mode == '':
new_order = np.argmax(np.abs(evecs), 1)
radius = radius[new_order]
evecs = evecs[:, new_order]
r11, r12, r21, r22 = evecs.T.flat
angle = np.arctan(-r12/r11)
else:
angle = 0
return radius, center, angle
def fit_ellipsoid(coords, mode='', return_mode=''):
"""
Fit an ellipsoid/sphere/paraboloid/hyperboloid to a set of xyz data points:
Parameters
----------
coords : ndarray
Cartesian coordinates, 3 x n array
mode : {'', 'xy', 'xz', 'xyz', '0', '0xy', '0xz'} t
'' or None fits an arbitrary ellipsoid (default)
'xy' fits a spheroid with x- and y- radii equal
'xz' fits a spheroid with x- and z- radii equal
'xyz' fits a sphere
'0' fits an ellipsoid with its axes aligned along [x y z] axes
'0xy' the same with x- and y- radii equal
'0xz' the same with x- and z- radii equal
return_mode : {'', 'euler', 'skew'}
'' returns the directions of the radii as 3x3 array
'euler' returns euler angles
'skew' returns skew in xy
Returns
-------
radius : ndarray
ellipsoid radii [zr, yr, xr]
center : ndarray
ellipsoid center coordinates [zc, yc, xc]
value :
return_mode == '': the radii directions as columns of the 3x3 matrix
return_mode == 'euler':
euler angles, applied in x, y, z order [z, y, x]
the y value is the angle with the z axis (tilt)
the z value is the angle around the z axis (rotation)
the x value is the 3rd rotation, should be around 0
return_mode == 'skew':
skew in y, x order
Notes
-----
Author: Yury Petrov, Oculus VR Date: September, 2015
ported to python by Casper van der Wel, December 2015
added euler angles and skew by Casper van der Wel
"""
if coords.shape[0] != 3:
raise ValueError('Input data must have three columns!')
if mode in MODE_DICT_ELLIPSOID:
mode = MODE_DICT_ELLIPSOID[mode]
if return_mode == 'skew' and 'xy' not in mode:
raise ValueError('Cannot return skew when x, y radii are not equal')
if return_mode == 'euler':
raise ValueError('Euler mode is not implemented fully')
z = coords[0, :, np.newaxis]
y = coords[1, :, np.newaxis]
x = coords[2, :, np.newaxis]
# fit ellipsoid in the form Ax^2 + By^2 + Cz^2 + 2Dxy + 2Exz + 2Fyz + 2Gx +
# 2Hy + 2Iz + J = 0 and A + B + C = 3 constraint removing one extra param
if mode == '':
D = np.hstack((x**2 + y**2 - 2 * z**2, x**2 + z**2 - 2 * y**2,
2 * x * y, 2 * x * z, 2 * y * z, 2 * x, 2 * y, 2 * z,
np.ones_like(x)))
elif mode == 'xy':
D = np.hstack((x**2 + y**2 - 2 * z**2, 2 * x * y, 2 * x * z, 2 * y * z,
2 * x, 2 * y, 2 * z, np.ones_like(x)))
elif mode == 'xz':
D = np.hstack((x**2 + z**2 - 2 * y**2, 2 * x * y, 2 * x * z, 2 * y * z,
2 * x, 2 * y, 2 * z, np.ones_like(x)))
# fit ellipsoid in the form Ax^2 + By^2 + Cz^2 + 2Gx + 2Hy + 2Iz = 1
elif mode == '0':
D = np.hstack((x**2 + y**2 - 2 * z**2, x**2 + z**2 - 2 * y**2,
2 * x, 2 * y, 2 * z, np.ones_like(x)))
# fit ellipsoid in the form Ax^2 + By^2 + Cz^2 + 2Gx + 2Hy + 2Iz = 1,
# where A = B or B = C or A = C
elif mode == '0xy':
D = np.hstack((x**2 + y**2 - 2 * z**2, 2 * x, 2 * y, 2 * z,
np.ones_like(x)))
elif mode == '0xz':
D = np.hstack((x**2 + z**2 - 2 * y**2, 2 * x, 2 * y, 2 * z,
np.ones_like(x)))
# fit sphere in the form A(x^2 + y^2 + z^2) + 2Gx + 2Hy + 2Iz = 1
elif mode == 'xyz':
D = np.hstack((2 * x, 2 * y, 2 * z, np.ones_like(x)))
else:
raise ValueError('Unknown mode "{}"'.format(mode))
if D.shape[0] < D.shape[1]:
raise ValueError('Not enough datapoints')
# solve the normal system of equations
d2 = x**2 + y**2 + z**2 # the RHS of the llsq problem (y's)
u = np.linalg.solve(np.dot(D.T, D), (np.dot(D.T, d2)))[:, 0]
# find the ellipsoid parameters
# convert back to the conventional algebraic form
v = np.empty((10), dtype=u.dtype)
if mode == '':
v[0] = u[0] + u[1] - 1
v[1] = u[0] - 2 * u[1] - 1
v[2] = u[1] - 2 * u[0] - 1
v[3:10] = u[2:9]
elif mode == 'xy':
v[0] = u[0] - 1
v[1] = u[0] - 1
v[2] = -2 * u[0] - 1
v[3:10] = u[1:8]
elif mode == 'xz':
v[0] = u[0] - 1
v[1] = -2 * u[0] - 1
v[2] = u[0] - 1
v[3:10] = u[1:8]
elif mode == '0':
v[0] = u[0] + u[1] - 1
v[1] = u[0] - 2 * u[1] - 1
v[2] = u[1] - 2 * u[0] - 1
v[3:6] = 0
v[6:10] = u[2:6]
elif mode == '0xy':
v[0] = u[0] - 1
v[1] = u[0] - 1
v[2] = -2 * u[0] - 1
v[3:6] = 0
v[6:10] = u[2:6]
elif mode == '0xz':
v[0] = u[0] - 1
v[1] = -2 * u[0] - 1
v[2] = u[0] - 1
v[3:6] = 0
v[6:10] = u[2:6]
elif mode == 'xyz':
v[:3] = -1
v[3:6] = 0
v[6:10] = u[:4]
# form the algebraic form of the ellipsoid
A = np.array([[v[0], v[3], v[4], v[6]],
[v[3], v[1], v[5], v[7]],
[v[4], v[5], v[2], v[8]],
[v[6], v[7], v[8], v[9]]])
# find the center of the ellipsoid
center = -np.linalg.solve(A[:3, :3], v[6:9])
# form the corresponding translation matrix
T = np.identity(4, dtype=A.dtype)
T[3, :3] = center
# translate to the center
R = np.dot(np.dot(T, A), T.T)
if return_mode == 'skew':
# extract the xy skew (ignoring a parameter here!)
skew_xy = -R[2, :2] / np.diag(R[:2, :2])
radius = np.diag(R[:3, :3]) / R[3, 3]
# do some trick to make radius_z be the unskewed radius
radius[2] -= np.sum(radius[:2] * skew_xy**2)
radius = np.sqrt(1 / np.abs(radius))
return radius[::-1], center[::-1], skew_xy[::-1]
# solve the eigenproblem
evals, evecs = np.linalg.eig(R[:3, :3] / -R[3, 3])
radii = (np.sqrt(1 / np.abs(evals)) * np.sign(evals))
if return_mode == 'euler':
# sort the vectors so that -> z, y, x
new_order = np.argmax(np.abs(evecs), 1)
radii = radii[new_order]
evecs = evecs[:, new_order]
# Discover Euler angle vector from 3x3 matrix
cy_thresh = np.finfo(evecs.dtype).eps * 4
r11, r12, r13, r21, r22, r23, r31, r32, r33 = evecs.T.flat
# cy: sqrt((cos(y)*cos(z))**2 + (cos(x)*cos(y))**2)
cy = np.sqrt(r33*r33 + r23*r23)
if cy > cy_thresh: # cos(y) not close to zero, standard form
# z: atan2(cos(y)*sin(z), cos(y)*cos(z)),
# y: atan2(sin(y), cy), atan2(cos(y)*sin(x),
# x: cos(x)*cos(y))
angles = np.array([np.arctan(r12/r11), np.arctan(-r13/cy),
np.arctan(r23/r33)])
else: # cos(y) (close to) zero, so x -> 0.0 (see above)
# so r21 -> sin(z), r22 -> cos(z) and
# y: atan2(sin(y), cy)
angles = np.array([np.arctan(-r21/r22), np.arctan(-r13/cy), 0.0])
return radii[::-1], center[::-1], angles
return radii[::-1], center[::-1], evecs[::-1]
def ellipse_grid(radius, center, rotation=0, skew=0, n=None, spacing=1):
|
def ellipsoid_grid(radius, center, spacing=1):
""" Returns points and normal (unit) vectors on an ellipse on only
integer values of z.
Parameters
----------
radius : tuple
(zr, yr, xr) the three principle radii of the ellipsoid
center : tuple
(zc, yc, xc) the center coordinate of the ellipsoid
spacing : float, optional
Distance between points
Returns
-------
two arrays of shape (3, N), being the coordinates and unit normals
"""
zc, yc, xc = center
zr, yr, xr = radius
pos = np.empty((3, 0))
for z in range(int(zc - zr + 1), int(zc + zr) + 1):
n = int(2*np.pi*np.sqrt((yr**2 + xr**2) / 2) / spacing)
if n == 0:
continue
phi = np.linspace(-np.pi, np.pi, n, endpoint=False)
factor = np.sqrt(1 - ((zc - z) / zr)**2) # = sin(arccos((zc/z)/zr))
pos = np.append(pos,
np.array([[float(z)] * n,
yr * factor * np.sin(phi) + yc,
xr * factor * np.cos(phi) + xc]),
axis=1)
normal = (pos - np.array(center)[:, np.newaxis]) / np.array(radius)[:, np.newaxis]
normal /= np.sqrt((normal**2).sum(0))
mask = np.isfinite(pos).all(0) & np.isfinite(normal).all(0)
return pos[:, mask], normal[:, mask]
def max_linregress(arr, maxfit_size=2, threshold=0.1, axis=1):
""" Locates maxima by fitting parabolas to values around the maximum.
This function is optimized for two-dimensional numpy arrays. For each row
in the array, the index of the maximum value is located. Then some values
around it (given by ``maxfit_size``) are taken, the first (discrete)
derivative is taken, and linear regression is done. This gives the location
of the maximum with sub-pixel precision. Effectively, a parabola is fitted.
Parameters
----------
arr : ndarray
maxfit_size : integer, optional
Defines the fit region around the maximum value. By default, this value
is 2, that is, two pixels before and two pixels after the maximum are
used for the fit (a total of 5).
threshold :
Discard points when the average value of the fit region is lower than
``threshold`` times the maximum in the whole fit array. This helps
discarding low-intensity peaks. Default 0.1: if the average intensity
in the fitregion is below 10% of the global maximum, the point is
discarded.
axis : {0, 1}
axis along which the maxima are fitted. Default 1.
Returns
-------
ndarray with the locations of the maxima.
Elements are NaN in all of the following cases:
- any pixel in the fitregion is 0
- the mean of the fitregion < threshold * global max
- regression returned infinity
- maximum is outside of the fit region.
"""
if axis == 0:
arr = arr.T
# identify the regions around the max value
maxes = np.argmax(arr[:, maxfit_size:-maxfit_size],
axis=1) + maxfit_size
ind = maxes[:, np.newaxis] + range(-maxfit_size, maxfit_size+1)
# must cast dtype from unsigned to signed integer
dtype = np.dtype(arr.dtype)
if dtype.kind == 'u':
if dtype.itemsize == 1:
dtype = np.int16
elif dtype.itemsize == 2:
dtype = np.int32
else:
dtype = np.int64
else:
dtype = arr.dtype
fitregion = np.array([_int.take(_ind) for _int, _ind in zip(arr, ind)],
dtype=dtype)
# fit max using linear regression
intdiff = np.diff(fitregion, 1)
x_norm = np.arange(-maxfit_size + 0.5, maxfit_size + 0.5)
y_mean = np.mean(intdiff, axis=1, keepdims=True)
y_norm = intdiff - y_mean
slope = np.sum(x_norm[np.newaxis, :] * y_norm, 1) / np.sum(x_norm * x_norm)
slope[slope == 0] = np.nan # protect against division by zero
r_dev = - y_mean[:, 0] / slope
# mask invalid fits
threshold = threshold * fitregion.max() # relative to global maximum
with np.errstate(invalid='ignore'): # ignore comparison with np.nan
valid = (np.isfinite(r_dev) & # finite result
(fitregion > 0).all(1) & # all pixels in fitregion > 0
(fitregion.mean(1) > threshold) & # fitregion mean > threshold
(r_dev > -maxfit_size + 0.5) & # maximum inside fit region
(r_dev < maxfit_size - 0.5))
r_dev[~valid] = np.nan
return r_dev + maxes
def max_edge(arr, threshold=0.5, axis=1):
""" Find strongest decreasing edge on each row """
if axis == 0:
arr = arr.T
if np.issubdtype(arr.dtype, np.unsignedinteger):
arr = arr.astype(np.int)
derivative = -np.diff(arr)
index = np.argmax(derivative, axis=1)
values = np.max(derivative, axis=1)
r_dev = index + 0.5
r_dev[values < threshold * values.max()] = np.nan
return r_dev
| """ Returns points and normal (unit) vectors on an ellipse.
Parameters
----------
radius : tuple
(yr, xr) the two principle radii of the ellipse
center : tuple
(yc, xc) the center coordinate of the ellipse
rotation : float, optional
angle of xr with the x-axis, in radians. Rotates clockwise in image.
skew : float, optional
skew: y -> y + skew * x
n : int, optional
number of points
spacing : float, optional
When `n` is not given then the spacing is determined by `spacing`.
Returns
-------
two arrays of shape (2, N), being the coordinates and unit normals
"""
yr, xr = radius
yc, xc = center
if n is None:
n = int(2*np.pi*np.sqrt((yr**2 + xr**2) / 2) / spacing)
phi = np.linspace(-np.pi, np.pi, n, endpoint=False)
pos = np.array([yr * np.sin(phi), xr * np.cos(phi)])
normal = np.array([np.sin(phi) / yr, np.cos(phi) / xr])
normal /= np.sqrt((normal**2).sum(0))
mask = np.isfinite(pos).all(0) & np.isfinite(normal).all(0)
pos = pos[:, mask]
normal = normal[:, mask]
if rotation != 0:
R = np.array([[ np.cos(rotation), np.sin(rotation)],
[-np.sin(rotation), np.cos(rotation)]])
pos = np.dot(pos.T, R).T
elif skew != 0:
pos[0] += pos[1] * skew
# translate
pos[0] += yc
pos[1] += xc
return pos, normal # both in y_list, x_list format |
model_kubernetes_cluster_certificate_configuration_all_of.go | /*
Cisco Intersight
Cisco Intersight is a management platform delivered as a service with embedded analytics for your Cisco and 3rd party IT infrastructure. This platform offers an intelligent level of management that enables IT organizations to analyze, simplify, and automate their environments in more advanced ways than the prior generations of tools. Cisco Intersight provides an integrated and intuitive management experience for resources in the traditional data center as well as at the edge. With flexible deployment options to address complex security needs, getting started with Intersight is quick and easy. Cisco Intersight has deep integration with Cisco UCS and HyperFlex systems allowing for remote deployment, configuration, and ongoing maintenance. The model-based deployment works for a single system in a remote location or hundreds of systems in a data center and enables rapid, standardized configuration and deployment. It also streamlines maintaining those systems whether you are working with small or very large configurations. The Intersight OpenAPI document defines the complete set of properties that are returned in the HTTP response. From that perspective, a client can expect that no additional properties are returned, unless these properties are explicitly defined in the OpenAPI document. However, when a client uses an older version of the Intersight OpenAPI document, the server may send additional properties because the software is more recent than the client. In that case, the client may receive properties that it does not know about. Some generated SDKs perform a strict validation of the HTTP response body against the OpenAPI document.
API version: 1.0.9-5517
Contact: [email protected]
*/
// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT.
package intersight
import (
"encoding/json"
)
// KubernetesClusterCertificateConfigurationAllOf Definition of the list of properties defined in 'kubernetes.ClusterCertificateConfiguration', excluding properties defined in parent classes.
type KubernetesClusterCertificateConfigurationAllOf struct {
// The fully-qualified name of the instantiated, concrete type. This property is used as a discriminator to identify the type of the payload when marshaling and unmarshaling data.
ClassId string `json:"ClassId"`
// The fully-qualified name of the instantiated, concrete type. The value should be the same as the 'ClassId' property.
ObjectType string `json:"ObjectType"`
// Certificate for the Kubernetes API server.
CaCert *string `json:"CaCert,omitempty"`
// Private Key for the Kubernetes API server.
CaKey *string `json:"CaKey,omitempty"`
// Certificate for the etcd cluster.
EtcdCert *string `json:"EtcdCert,omitempty"`
EtcdEncryptionKey []string `json:"EtcdEncryptionKey,omitempty"`
// Private key for the etcd cluster.
EtcdKey *string `json:"EtcdKey,omitempty"`
// Certificate for the front proxy to support Kubernetes API aggregators.
FrontProxyCert *string `json:"FrontProxyCert,omitempty"`
// Private key for the front proxy to support Kubernetes API aggregators.
FrontProxyKey *string `json:"FrontProxyKey,omitempty"`
// Service account private key used by Kubernetes Token Controller to sign generated service account tokens.
SaPrivateKey *string `json:"SaPrivateKey,omitempty"`
// Service account public key used by Kubernetes API Server to validate service account tokens generated by the Token Controller.
SaPublicKey *string `json:"SaPublicKey,omitempty"`
AdditionalProperties map[string]interface{}
}
type _KubernetesClusterCertificateConfigurationAllOf KubernetesClusterCertificateConfigurationAllOf
// NewKubernetesClusterCertificateConfigurationAllOf instantiates a new KubernetesClusterCertificateConfigurationAllOf object
// This constructor will assign default values to properties that have it defined,
// and makes sure properties required by API are set, but the set of arguments
// will change when the set of required properties is changed
func NewKubernetesClusterCertificateConfigurationAllOf(classId string, objectType string) *KubernetesClusterCertificateConfigurationAllOf |
// NewKubernetesClusterCertificateConfigurationAllOfWithDefaults instantiates a new KubernetesClusterCertificateConfigurationAllOf object
// This constructor will only assign default values to properties that have it defined,
// but it doesn't guarantee that properties required by API are set
func NewKubernetesClusterCertificateConfigurationAllOfWithDefaults() *KubernetesClusterCertificateConfigurationAllOf {
this := KubernetesClusterCertificateConfigurationAllOf{}
var classId string = "kubernetes.ClusterCertificateConfiguration"
this.ClassId = classId
var objectType string = "kubernetes.ClusterCertificateConfiguration"
this.ObjectType = objectType
return &this
}
// GetClassId returns the ClassId field value
func (o *KubernetesClusterCertificateConfigurationAllOf) GetClassId() string {
if o == nil {
var ret string
return ret
}
return o.ClassId
}
// GetClassIdOk returns a tuple with the ClassId field value
// and a boolean to check if the value has been set.
func (o *KubernetesClusterCertificateConfigurationAllOf) GetClassIdOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.ClassId, true
}
// SetClassId sets field value
func (o *KubernetesClusterCertificateConfigurationAllOf) SetClassId(v string) {
o.ClassId = v
}
// GetObjectType returns the ObjectType field value
func (o *KubernetesClusterCertificateConfigurationAllOf) GetObjectType() string {
if o == nil {
var ret string
return ret
}
return o.ObjectType
}
// GetObjectTypeOk returns a tuple with the ObjectType field value
// and a boolean to check if the value has been set.
func (o *KubernetesClusterCertificateConfigurationAllOf) GetObjectTypeOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.ObjectType, true
}
// SetObjectType sets field value
func (o *KubernetesClusterCertificateConfigurationAllOf) SetObjectType(v string) {
o.ObjectType = v
}
// GetCaCert returns the CaCert field value if set, zero value otherwise.
func (o *KubernetesClusterCertificateConfigurationAllOf) GetCaCert() string {
if o == nil || o.CaCert == nil {
var ret string
return ret
}
return *o.CaCert
}
// GetCaCertOk returns a tuple with the CaCert field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *KubernetesClusterCertificateConfigurationAllOf) GetCaCertOk() (*string, bool) {
if o == nil || o.CaCert == nil {
return nil, false
}
return o.CaCert, true
}
// HasCaCert returns a boolean if a field has been set.
func (o *KubernetesClusterCertificateConfigurationAllOf) HasCaCert() bool {
if o != nil && o.CaCert != nil {
return true
}
return false
}
// SetCaCert gets a reference to the given string and assigns it to the CaCert field.
func (o *KubernetesClusterCertificateConfigurationAllOf) SetCaCert(v string) {
o.CaCert = &v
}
// GetCaKey returns the CaKey field value if set, zero value otherwise.
func (o *KubernetesClusterCertificateConfigurationAllOf) GetCaKey() string {
if o == nil || o.CaKey == nil {
var ret string
return ret
}
return *o.CaKey
}
// GetCaKeyOk returns a tuple with the CaKey field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *KubernetesClusterCertificateConfigurationAllOf) GetCaKeyOk() (*string, bool) {
if o == nil || o.CaKey == nil {
return nil, false
}
return o.CaKey, true
}
// HasCaKey returns a boolean if a field has been set.
func (o *KubernetesClusterCertificateConfigurationAllOf) HasCaKey() bool {
if o != nil && o.CaKey != nil {
return true
}
return false
}
// SetCaKey gets a reference to the given string and assigns it to the CaKey field.
func (o *KubernetesClusterCertificateConfigurationAllOf) SetCaKey(v string) {
o.CaKey = &v
}
// GetEtcdCert returns the EtcdCert field value if set, zero value otherwise.
func (o *KubernetesClusterCertificateConfigurationAllOf) GetEtcdCert() string {
if o == nil || o.EtcdCert == nil {
var ret string
return ret
}
return *o.EtcdCert
}
// GetEtcdCertOk returns a tuple with the EtcdCert field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *KubernetesClusterCertificateConfigurationAllOf) GetEtcdCertOk() (*string, bool) {
if o == nil || o.EtcdCert == nil {
return nil, false
}
return o.EtcdCert, true
}
// HasEtcdCert returns a boolean if a field has been set.
func (o *KubernetesClusterCertificateConfigurationAllOf) HasEtcdCert() bool {
if o != nil && o.EtcdCert != nil {
return true
}
return false
}
// SetEtcdCert gets a reference to the given string and assigns it to the EtcdCert field.
func (o *KubernetesClusterCertificateConfigurationAllOf) SetEtcdCert(v string) {
o.EtcdCert = &v
}
// GetEtcdEncryptionKey returns the EtcdEncryptionKey field value if set, zero value otherwise (both if not set or set to explicit null).
func (o *KubernetesClusterCertificateConfigurationAllOf) GetEtcdEncryptionKey() []string {
if o == nil {
var ret []string
return ret
}
return o.EtcdEncryptionKey
}
// GetEtcdEncryptionKeyOk returns a tuple with the EtcdEncryptionKey field value if set, nil otherwise
// and a boolean to check if the value has been set.
// NOTE: If the value is an explicit nil, `nil, true` will be returned
func (o *KubernetesClusterCertificateConfigurationAllOf) GetEtcdEncryptionKeyOk() (*[]string, bool) {
if o == nil || o.EtcdEncryptionKey == nil {
return nil, false
}
return &o.EtcdEncryptionKey, true
}
// HasEtcdEncryptionKey returns a boolean if a field has been set.
func (o *KubernetesClusterCertificateConfigurationAllOf) HasEtcdEncryptionKey() bool {
if o != nil && o.EtcdEncryptionKey != nil {
return true
}
return false
}
// SetEtcdEncryptionKey gets a reference to the given []string and assigns it to the EtcdEncryptionKey field.
func (o *KubernetesClusterCertificateConfigurationAllOf) SetEtcdEncryptionKey(v []string) {
o.EtcdEncryptionKey = v
}
// GetEtcdKey returns the EtcdKey field value if set, zero value otherwise.
func (o *KubernetesClusterCertificateConfigurationAllOf) GetEtcdKey() string {
if o == nil || o.EtcdKey == nil {
var ret string
return ret
}
return *o.EtcdKey
}
// GetEtcdKeyOk returns a tuple with the EtcdKey field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *KubernetesClusterCertificateConfigurationAllOf) GetEtcdKeyOk() (*string, bool) {
if o == nil || o.EtcdKey == nil {
return nil, false
}
return o.EtcdKey, true
}
// HasEtcdKey returns a boolean if a field has been set.
func (o *KubernetesClusterCertificateConfigurationAllOf) HasEtcdKey() bool {
if o != nil && o.EtcdKey != nil {
return true
}
return false
}
// SetEtcdKey gets a reference to the given string and assigns it to the EtcdKey field.
func (o *KubernetesClusterCertificateConfigurationAllOf) SetEtcdKey(v string) {
o.EtcdKey = &v
}
// GetFrontProxyCert returns the FrontProxyCert field value if set, zero value otherwise.
func (o *KubernetesClusterCertificateConfigurationAllOf) GetFrontProxyCert() string {
if o == nil || o.FrontProxyCert == nil {
var ret string
return ret
}
return *o.FrontProxyCert
}
// GetFrontProxyCertOk returns a tuple with the FrontProxyCert field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *KubernetesClusterCertificateConfigurationAllOf) GetFrontProxyCertOk() (*string, bool) {
if o == nil || o.FrontProxyCert == nil {
return nil, false
}
return o.FrontProxyCert, true
}
// HasFrontProxyCert returns a boolean if a field has been set.
func (o *KubernetesClusterCertificateConfigurationAllOf) HasFrontProxyCert() bool {
if o != nil && o.FrontProxyCert != nil {
return true
}
return false
}
// SetFrontProxyCert gets a reference to the given string and assigns it to the FrontProxyCert field.
func (o *KubernetesClusterCertificateConfigurationAllOf) SetFrontProxyCert(v string) {
o.FrontProxyCert = &v
}
// GetFrontProxyKey returns the FrontProxyKey field value if set, zero value otherwise.
func (o *KubernetesClusterCertificateConfigurationAllOf) GetFrontProxyKey() string {
if o == nil || o.FrontProxyKey == nil {
var ret string
return ret
}
return *o.FrontProxyKey
}
// GetFrontProxyKeyOk returns a tuple with the FrontProxyKey field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *KubernetesClusterCertificateConfigurationAllOf) GetFrontProxyKeyOk() (*string, bool) {
if o == nil || o.FrontProxyKey == nil {
return nil, false
}
return o.FrontProxyKey, true
}
// HasFrontProxyKey returns a boolean if a field has been set.
func (o *KubernetesClusterCertificateConfigurationAllOf) HasFrontProxyKey() bool {
if o != nil && o.FrontProxyKey != nil {
return true
}
return false
}
// SetFrontProxyKey gets a reference to the given string and assigns it to the FrontProxyKey field.
func (o *KubernetesClusterCertificateConfigurationAllOf) SetFrontProxyKey(v string) {
o.FrontProxyKey = &v
}
// GetSaPrivateKey returns the SaPrivateKey field value if set, zero value otherwise.
func (o *KubernetesClusterCertificateConfigurationAllOf) GetSaPrivateKey() string {
if o == nil || o.SaPrivateKey == nil {
var ret string
return ret
}
return *o.SaPrivateKey
}
// GetSaPrivateKeyOk returns a tuple with the SaPrivateKey field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *KubernetesClusterCertificateConfigurationAllOf) GetSaPrivateKeyOk() (*string, bool) {
if o == nil || o.SaPrivateKey == nil {
return nil, false
}
return o.SaPrivateKey, true
}
// HasSaPrivateKey returns a boolean if a field has been set.
func (o *KubernetesClusterCertificateConfigurationAllOf) HasSaPrivateKey() bool {
if o != nil && o.SaPrivateKey != nil {
return true
}
return false
}
// SetSaPrivateKey gets a reference to the given string and assigns it to the SaPrivateKey field.
func (o *KubernetesClusterCertificateConfigurationAllOf) SetSaPrivateKey(v string) {
o.SaPrivateKey = &v
}
// GetSaPublicKey returns the SaPublicKey field value if set, zero value otherwise.
func (o *KubernetesClusterCertificateConfigurationAllOf) GetSaPublicKey() string {
if o == nil || o.SaPublicKey == nil {
var ret string
return ret
}
return *o.SaPublicKey
}
// GetSaPublicKeyOk returns a tuple with the SaPublicKey field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *KubernetesClusterCertificateConfigurationAllOf) GetSaPublicKeyOk() (*string, bool) {
if o == nil || o.SaPublicKey == nil {
return nil, false
}
return o.SaPublicKey, true
}
// HasSaPublicKey returns a boolean if a field has been set.
func (o *KubernetesClusterCertificateConfigurationAllOf) HasSaPublicKey() bool {
if o != nil && o.SaPublicKey != nil {
return true
}
return false
}
// SetSaPublicKey gets a reference to the given string and assigns it to the SaPublicKey field.
func (o *KubernetesClusterCertificateConfigurationAllOf) SetSaPublicKey(v string) {
o.SaPublicKey = &v
}
func (o KubernetesClusterCertificateConfigurationAllOf) MarshalJSON() ([]byte, error) {
toSerialize := map[string]interface{}{}
if true {
toSerialize["ClassId"] = o.ClassId
}
if true {
toSerialize["ObjectType"] = o.ObjectType
}
if o.CaCert != nil {
toSerialize["CaCert"] = o.CaCert
}
if o.CaKey != nil {
toSerialize["CaKey"] = o.CaKey
}
if o.EtcdCert != nil {
toSerialize["EtcdCert"] = o.EtcdCert
}
if o.EtcdEncryptionKey != nil {
toSerialize["EtcdEncryptionKey"] = o.EtcdEncryptionKey
}
if o.EtcdKey != nil {
toSerialize["EtcdKey"] = o.EtcdKey
}
if o.FrontProxyCert != nil {
toSerialize["FrontProxyCert"] = o.FrontProxyCert
}
if o.FrontProxyKey != nil {
toSerialize["FrontProxyKey"] = o.FrontProxyKey
}
if o.SaPrivateKey != nil {
toSerialize["SaPrivateKey"] = o.SaPrivateKey
}
if o.SaPublicKey != nil {
toSerialize["SaPublicKey"] = o.SaPublicKey
}
for key, value := range o.AdditionalProperties {
toSerialize[key] = value
}
return json.Marshal(toSerialize)
}
func (o *KubernetesClusterCertificateConfigurationAllOf) UnmarshalJSON(bytes []byte) (err error) {
varKubernetesClusterCertificateConfigurationAllOf := _KubernetesClusterCertificateConfigurationAllOf{}
if err = json.Unmarshal(bytes, &varKubernetesClusterCertificateConfigurationAllOf); err == nil {
*o = KubernetesClusterCertificateConfigurationAllOf(varKubernetesClusterCertificateConfigurationAllOf)
}
additionalProperties := make(map[string]interface{})
if err = json.Unmarshal(bytes, &additionalProperties); err == nil {
delete(additionalProperties, "ClassId")
delete(additionalProperties, "ObjectType")
delete(additionalProperties, "CaCert")
delete(additionalProperties, "CaKey")
delete(additionalProperties, "EtcdCert")
delete(additionalProperties, "EtcdEncryptionKey")
delete(additionalProperties, "EtcdKey")
delete(additionalProperties, "FrontProxyCert")
delete(additionalProperties, "FrontProxyKey")
delete(additionalProperties, "SaPrivateKey")
delete(additionalProperties, "SaPublicKey")
o.AdditionalProperties = additionalProperties
}
return err
}
type NullableKubernetesClusterCertificateConfigurationAllOf struct {
value *KubernetesClusterCertificateConfigurationAllOf
isSet bool
}
func (v NullableKubernetesClusterCertificateConfigurationAllOf) Get() *KubernetesClusterCertificateConfigurationAllOf {
return v.value
}
func (v *NullableKubernetesClusterCertificateConfigurationAllOf) Set(val *KubernetesClusterCertificateConfigurationAllOf) {
v.value = val
v.isSet = true
}
func (v NullableKubernetesClusterCertificateConfigurationAllOf) IsSet() bool {
return v.isSet
}
func (v *NullableKubernetesClusterCertificateConfigurationAllOf) Unset() {
v.value = nil
v.isSet = false
}
func NewNullableKubernetesClusterCertificateConfigurationAllOf(val *KubernetesClusterCertificateConfigurationAllOf) *NullableKubernetesClusterCertificateConfigurationAllOf {
return &NullableKubernetesClusterCertificateConfigurationAllOf{value: val, isSet: true}
}
func (v NullableKubernetesClusterCertificateConfigurationAllOf) MarshalJSON() ([]byte, error) {
return json.Marshal(v.value)
}
func (v *NullableKubernetesClusterCertificateConfigurationAllOf) UnmarshalJSON(src []byte) error {
v.isSet = true
return json.Unmarshal(src, &v.value)
}
| {
this := KubernetesClusterCertificateConfigurationAllOf{}
this.ClassId = classId
this.ObjectType = objectType
return &this
} |
new 2.py | def maximum_consecutive(lst, n):
count = 0
result = 0
for i in range(0, n):
if (lst[i] == 0):
count = 0
| else:
count+= 1
result = max(result, count)
return result
lst=[0,0,0,1,1,1,0,0,0,1,1,0,1,1,1,1,0,0,1,1]
n=len(lst)
print(maximum_consecutive(lst, n)) | |
vis.py | import numpy as np
from ai.domain_adaptation.datasets import image_index
from ai.domain_adaptation.utils import np_utils
from IPython.display import display, Image
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
def load_data_for_vis(prob_path, target_domain_file, dataset_dir):
domain_info = image_index.parse_domain_file(target_domain_file, dataset_dir)
yhat_info = np_utils.parse_predictions_from_pickle(prob_path)
return domain_info, yhat_info
def visulize_confidence(prob_path, target_domain_file, dataset_dir, cls_id):
domain_info, yhat_info = load_data_for_vis(prob_path, target_domain_file, dataset_dir)
vis_confident_predictions(cls_id, None, domain_info, yhat_info)
def vis_confident_predictions(cls_id, top_k=20, domain_info=None, yhat_info=None):
|
def plot_confusion_matrix(y_true, y_pred, classes,
normalize=False,
title=None,
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
if not title:
if normalize:
title = 'Normalized confusion matrix'
else:
title = 'Confusion matrix, without normalization'
# Compute confusion matrix
cm = confusion_matrix(y_true, y_pred)
# Only use the labels that appear in the data
# classes = classes[unique_labels(y_true, y_pred)]
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
# np.set_printoptions(precision=3)
fig, ax = plt.subplots(figsize=(20, 20))
im = ax.imshow(cm, interpolation='nearest', cmap=cmap)
# ax.figure.colorbar(im, ax=ax)
# We want to show all ticks...
ax.set(xticks=np.arange(cm.shape[1]),
yticks=np.arange(cm.shape[0]),
# ... and label them with the respective list entries
xticklabels=classes, yticklabels=classes,
title=title,
ylabel='True label',
xlabel='Predicted label')
# Rotate the tick labels and set their alignment.
plt.setp(ax.get_xticklabels(), rotation=45, ha="right",
rotation_mode="anchor")
# Loop over data dimensions and create text annotations.
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.
for i in range(cm.shape[0]):
for j in range(cm.shape[1]):
ax.text(j, i, format(cm[i, j], fmt),
ha="center", va="center",
color="white" if cm[i, j] > thresh else "black")
fig.tight_layout()
fig.savefig(f'./plots/confusion_matrix{title}.pdf')
return ax
| sorted_id_indices = np_utils.retrieve_sorted_indices_for_one_cls(cls_id, yhat_info)
for ith, example_id in enumerate(sorted_id_indices):
filename, label = domain_info.image_path_label_tuples[example_id]
print(f'{domain_info.label_description_dict[label]}, P {yhat_info.prob[example_id, cls_id]:.3}')
img = Image(filename=filename, width=150, height=150)
display(img)
if top_k is not None and ith > top_k:
break |
__init__.py | import logging
import azure.functions as func
import json
import os
from azure.cosmosdb.table.tableservice import TableService
from azure.cosmosdb.table.models import Entity
def | (req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
# Connect to Azure Table Storage
table_service = TableService(connection_string= os.environ['AzureWebJobsStorage'])
table_service.create_table('intents') if not table_service.exists('intents') else None
req_body = req.get_json()
if req_body:
# Create row to be saved on Azure Table Storage
print(req_body.get('ConversationId'))
data = req_body
data["PartitionKey"] = req_body.get('ConversationId')
data["RowKey"] = req_body.get('MessageId')
# Save row on Azure Table Storage
table_service.insert_or_replace_entity('intents', data)
return func.HttpResponse(f"Row {req_body.get('MessageId')} for {req_body.get('ConversationId')} added")
else:
return func.HttpResponse(
"Please pass valid request body",
status_code=400
) | main |
main.go | // Copyright 2018 The Kubeflow 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 main
import (
"github.com/kubeflow/kfctl/v3/cmd/kfctl/cmd"
"github.com/onrik/logrus/filename"
log "github.com/sirupsen/logrus"
"os"
)
var (
// VERSION is set during build
VERSION = "0.0.1"
)
func | () {
// Add filename as one of the fields of the structured log message.
filenameHook := filename.NewHook()
filenameHook.Field = "filename"
log.AddHook(filenameHook)
// Log as JSON instead of the default ASCII formatter.
log.SetFormatter(&log.JSONFormatter{})
// Output to stdout instead of the default stderr
// Can be any io.Writer, see below for File example
log.SetOutput(os.Stdout)
// Only log the warning severity or above.
log.SetLevel(log.DebugLevel)
}
func main() {
cmd.Execute(VERSION)
}
| init |
Astropedia_gdal2ISIS3.py | #!/usr/bin/env python
#/******************************************************************************
# * $Id$
# *
# * Project: GDAL Utilities
# * Purpose: Create a ISIS3 compatible (raw w/ ISIS3 label) from a GDAL supported image.
# * Author: Trent Hare, <[email protected]>
# * Date: June 05, 2013
# * version: 0.1
# *
# * Port from gdalinfo.py whose author is Even Rouault
# ******************************************************************************
# * Copyright (c) 2010, Even Rouault
# * Copyright (c) 1998, Frank Warmerdam
# *
# * Permission is hereby granted, free of charge, to any person obtaining a
# * copy of this software and associated documentation files (the "Software"),
# * to deal in the Software without restriction, including without limitation
# * the rights to use, copy, modify, merge, publish, distribute, sublicense,
# * and/or sell copies of the Software, and to permit persons to whom the
# * Software is furnished to do so, subject to the following conditions:
# *
# * The above copyright notice and this permission notice shall be included
# * in all copies or substantial portions of the Software.
# *
# * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# * DEALINGS IN THE SOFTWARE.
# ****************************************************************************/
import sys
import math
import datetime
import time
import os
import subprocess
try:
from osgeo import gdal
from osgeo import osr
except:
import gdal
import osr
#/************************************************************************/
#/* Usage() */
#/************************************************************************/
def Usage(theApp):
print( '\nUsage: Astropedia_gdal2ISIS3.py in.tif output.cub') # % theApp)
print( ' optional: to print out image information also send -debug')
print( ' optional: to just get a label *.lbl, send -noimage')
print( ' optional: to attach the *.lbl to the ISIS image -attach - requires ISIS3')
print( ' optional: to get lonsys=360, send -force360')
print( ' optional: to override the center Longitude, send -centerLon 180')
print( ' optional: to set scaler and offset send -base 17374000 and/or -multiplier 0.5')
print( 'Usage: Astropedia_gdal2ISIS3.py -debug in.cub output.cub\n') # % theApp)
print( 'Note: Currently this routine will only work for a limited set of images\n')
sys.exit(1)
def EQUAL(a, b):
return a.lower() == b.lower()
#/************************************************************************/
#/* main() */
#/************************************************************************/
def main( argv = None ):
bComputeMinMax = False
bSample = False
bShowGCPs = True
bShowMetadata = False
bShowRAT=False
debug = False
attach = False
bStats = False
bApproxStats = True
bShowColorTable = True
bComputeChecksum = False
bReportHistograms = False
pszFilename = None
papszExtraMDDomains = [ ]
pszProjection = None
hTransform = None
bShowFileList = True
dst_cub = None
dst_lbl = None
dst_hst = None
bands = 1
centLat = 0
centLon = 0
centerLon = False
TMscale = 1.0
UpperLeftCornerX = 0
UpperLeftCornerY = 0
falseEast = 0
falseNorth = 0
bMakeImage = True
force360 = False
base = None
multiplier = None
#/* Must process GDAL_SKIP before GDALAllRegister(), but we can't call */
#/* GDALGeneralCmdLineProcessor before it needs the drivers to be registered */
#/* for the --format or --formats options */
#for( i = 1; i < argc; i++ )
#{
# if EQUAL(argv[i],"--config") and i + 2 < argc and EQUAL(argv[i + 1], "GDAL_SKIP"):
# {
# CPLSetConfigOption( argv[i+1], argv[i+2] );
#
# i += 2;
# }
#}
#
#GDALAllRegister();
if argv is None:
argv = sys.argv
argv = gdal.GeneralCmdLineProcessor( argv )
if argv is None:
return 1
nArgc = len(argv)
#/* -------------------------------------------------------------------- */
#/* Parse arguments. */
#/* -------------------------------------------------------------------- */
i = 1
while i < nArgc:
if EQUAL(argv[i], "--utility_version"):
print("%s is running against GDAL %s" %
(argv[0], gdal.VersionInfo("RELEASE_NAME")))
return 0
elif EQUAL(argv[i], "-debug"):
debug = True
elif EQUAL(argv[i], "-attach"):
attach = True
elif EQUAL(argv[i], "-force360"):
force360 = True
elif EQUAL(argv[i], "-centerLon"):
i = i + 1
centerLon = float(argv[i])
elif EQUAL(argv[i], "-mm"):
bComputeMinMax = True
elif EQUAL(argv[i], "-hist"):
bReportHistograms = True
elif EQUAL(argv[i], "-stats"):
bStats = True
bApproxStats = False
elif EQUAL(argv[i], "-approx_stats"):
bStats = True
bApproxStats = True
elif EQUAL(argv[i], "-sample"):
bSample = True
elif EQUAL(argv[i], "-checksum"):
bComputeChecksum = True
elif EQUAL(argv[i], "-nogcp"):
bShowGCPs = False
elif EQUAL(argv[i], "-nomd"):
bShowMetadata = False
elif EQUAL(argv[i], "-norat"):
bShowRAT = False
elif EQUAL(argv[i], "-noct"):
bShowColorTable = False
elif EQUAL(argv[i], "-mdd") and i < nArgc-1:
i = i + 1
papszExtraMDDomains.append( argv[i] )
elif EQUAL(argv[i], "-nofl"):
bShowFileList = False
elif EQUAL(argv[i], "-noimage"):
bMakeImage = False
elif EQUAL(argv[i], "-base"):
i = i + 1
base = float(argv[i])
elif EQUAL(argv[i], "-multiplier"):
i = i + 1
multiplier = float(argv[i])
elif argv[i][0] == '-':
return Usage(argv[0])
elif pszFilename is None:
pszFilename = argv[i]
elif dst_cub is None:
dst_cub = argv[i]
else:
return Usage(argv[0])
i = i + 1
if pszFilename is None:
return Usage(argv[0])
if dst_cub is None:
return Usage(argv[0])
#/* -------------------------------------------------------------------- */
#/* Open dataset. */
#/* -------------------------------------------------------------------- */
hDataset = gdal.Open( pszFilename, gdal.GA_ReadOnly )
if hDataset is None:
print("gdalinfo failed - unable to open '%s'." % pszFilename )
sys.exit(1)
# Open the output file.
if dst_cub is not None:
dst_lbl = dst_cub.replace("CUB","LBL")
dst_lbl = dst_lbl.replace("cub","lbl")
dst_hst = dst_cub.replace("CUB","History.IsisCube")
dst_hst = dst_hst.replace("cub","History.IsisCube")
dst_hdr = dst_cub.replace("CUB","hdr")
dst_hdr = dst_hdr.replace("cub","hdr")
dst_aux = dst_cub.replace("CUB","cub.aux.xml")
dst_aux = dst_aux.replace("cub","cub.aux.xml")
if attach:
attach_cub = dst_cub
dst_cub = "XXX"+dst_cub
dst_lbl = "XXX"+dst_lbl
dst_hst = "XXX"+dst_hst
dst_hdr = "XXX"+dst_hdr
dst_aux = "XXX"+dst_aux
if (EQUAL(dst_lbl,dst_cub)):
print('Extension must be .CUB or .cub - unable to run using filename: %s' % pszFilename )
sys.exit(1)
else:
f = open(dst_lbl,'wt')
f_hst = open(dst_hst,'wt')
# else:
# f = sys.stdout
# dst_cub = "out.cub"
#/* -------------------------------------------------------------------- */
#/* Report general info. */
#/* -------------------------------------------------------------------- */
hDriver = hDataset.GetDriver();
if debug:
print( "Driver: %s/%s" % ( \
hDriver.ShortName, \
hDriver.LongName ))
papszFileList = hDataset.GetFileList();
if papszFileList is None or len(papszFileList) == 0:
print( "Files: none associated" )
else:
if debug:
print( "Files: %s" % papszFileList[0] )
if bShowFileList:
for i in range(1, len(papszFileList)):
print( " %s" % papszFileList[i] )
if debug:
print( "Size is %d, %d" % (hDataset.RasterXSize, hDataset.RasterYSize))
#/* -------------------------------------------------------------------- */
#/* Report projection. */
#/* -------------------------------------------------------------------- */
pszProjection = hDataset.GetProjectionRef()
if pszProjection is not None:
hSRS = osr.SpatialReference()
if hSRS.ImportFromWkt(pszProjection ) == gdal.CE_None:
pszPrettyWkt = hSRS.ExportToPrettyWkt(False)
if debug:
print( "Coordinate System is:\n%s" % pszPrettyWkt )
else:
if debug:
print( "Coordinate System is `%s'" % pszProjection )
hSRS = osr.SpatialReference()
if hSRS.ImportFromWkt(pszProjection) == gdal.CE_None:
pszPrettyWkt = hSRS.ExportToPrettyWkt(False)
#print( "Coordinate System is:\n%s" % pszPrettyWkt )
mapProjection = "None"
#Extract projection information
target = hSRS.GetAttrValue("DATUM",0)
target = target.replace("D_","").replace("_2000","").replace("GCS_","")
semiMajor = hSRS.GetSemiMajor()
semiMinor = hSRS.GetSemiMinor()
if (pszProjection[0:6] == "GEOGCS"):
mapProjection = "SimpleCylindrical"
centLon = hSRS.GetProjParm('central_meridian')
if (pszProjection[0:6] == "PROJCS"):
mapProjection = hSRS.GetAttrValue("PROJECTION",0)
if EQUAL(mapProjection,"Sinusoidal"):
centLon = hSRS.GetProjParm('central_meridian')
if EQUAL(mapProjection,"Equirectangular"):
centLat = hSRS.GetProjParm('standard_parallel_1')
centLon = hSRS.GetProjParm('central_meridian')
if EQUAL(mapProjection,"Transverse_Mercator"):
mapProjection = "TransverseMercator"
centLat = hSRS.GetProjParm('standard_parallel_1')
centLon = hSRS.GetProjParm('central_meridian')
TMscale = hSRS.GetProjParm('scale_factor')
#Need to research when TM actually applies false values
falseEast = hSRS.GetProjParm('false_easting')
falseNorth = hSRS.GetProjParm('false_northing')
if EQUAL(mapProjection,"Orthographic"):
centLat = hSRS.GetProjParm('standard_parallel_1')
centLon = hSRS.GetProjParm('central_meridian')
if EQUAL(mapProjection,"Mercator_1SP"):
mapProjection = "Mercator"
centLat = hSRS.GetProjParm('standard_parallel_1')
centLon = hSRS.GetProjParm('central_meridian')
if EQUAL(mapProjection,"Mercator"):
centLat = hSRS.GetProjParm('standard_parallel_1')
centLon = hSRS.GetProjParm('central_meridian')
if EQUAL(mapProjection,"Polar_Stereographic"):
mapProjection = "PolarStereographic"
centLat = hSRS.GetProjParm('latitude_of_origin')
centLon = hSRS.GetProjParm('central_meridian')
if EQUAL(mapProjection,"Stereographic_South_Pole"):
mapProjection = "PolarStereographic"
centLat = hSRS.GetProjParm('latitude_of_origin')
centLon = hSRS.GetProjParm('central_meridian')
if EQUAL(mapProjection,"Stereographic_North_Pole"):
mapProjection = "PolarStereographic"
centLat = hSRS.GetProjParm('latitude_of_origin')
centLon = hSRS.GetProjParm('central_meridian')
if debug:
print( "Coordinate System is:\n%s" % pszPrettyWkt )
else:
print( "Warning - Currently we can't parse this type of projection" )
print( "Coordinate System is `%s'" % pszProjection )
target = "n/a"
#sys.exit(1)
else:
print( "Warning - No Coordinate System defined:\n" )
target = "n/a"
#sys.exit(1)
#/* -------------------------------------------------------------------- */
#/* Report Geotransform. */
#/* -------------------------------------------------------------------- */
adfGeoTransform = hDataset.GetGeoTransform(can_return_null = True)
if adfGeoTransform is not None:
UpperLeftCornerX = adfGeoTransform[0] - falseEast
UpperLeftCornerY = adfGeoTransform[3] - falseNorth
if adfGeoTransform[2] == 0.0 and adfGeoTransform[4] == 0.0:
if debug:
print( "Origin = (%.15f,%.15f)" % ( \
adfGeoTransform[0], adfGeoTransform[3] ))
print( "Pixel Size = (%.15f,%.15f)" % ( \
adfGeoTransform[1], adfGeoTransform[5] ))
else:
if debug:
print( "GeoTransform =\n" \
" %.16g, %.16g, %.16g\n" \
" %.16g, %.16g, %.16g" % ( \
adfGeoTransform[0], \
adfGeoTransform[1], \
adfGeoTransform[2], \
adfGeoTransform[3], \
adfGeoTransform[4], \
adfGeoTransform[5] ))
#Using a very simple method to calculate cellsize.
#Warning: might not always be good.
if (pszProjection[0:6] == "GEOGCS"):
#convert degrees/pixel to m/pixel
mapres = 1 / adfGeoTransform[1]
mres = adfGeoTransform[1] * (semiMajor * math.pi / 180.0)
else:
#convert m/pixel to pixel/degree
mapres = 1 / (adfGeoTransform[1] / (semiMajor * math.pi / 180.0))
mres = adfGeoTransform[1]
#/* -------------------------------------------------------------------- */
#/* Report GCPs. */
#/* -------------------------------------------------------------------- */
if bShowGCPs and hDataset.GetGCPCount() > 0:
pszProjection = hDataset.GetGCPProjection()
if pszProjection is not None:
hSRS = osr.SpatialReference()
if hSRS.ImportFromWkt(pszProjection ) == gdal.CE_None:
pszPrettyWkt = hSRS.ExportToPrettyWkt(False)
if debug:
print( "GCP Projection = \n%s" % pszPrettyWkt )
else:
if debug:
print( "GCP Projection = %s" % \
pszProjection )
gcps = hDataset.GetGCPs()
i = 0
for gcp in gcps:
if debug:
print( "GCP[%3d]: Id=%s, Info=%s\n" \
" (%.15g,%.15g) -> (%.15g,%.15g,%.15g)" % ( \
i, gcp.Id, gcp.Info, \
gcp.GCPPixel, gcp.GCPLine, \
gcp.GCPX, gcp.GCPY, gcp.GCPZ ))
i = i + 1
#/* -------------------------------------------------------------------- */
#/* Report metadata. */
#/* -------------------------------------------------------------------- */
if debug:
if bShowMetadata:
papszMetadata = hDataset.GetMetadata_List()
else:
papszMetadata = None
if bShowMetadata and papszMetadata is not None and len(papszMetadata) > 0 :
print( "Metadata:" )
for metadata in papszMetadata:
print( " %s" % metadata )
if bShowMetadata:
for extra_domain in papszExtraMDDomains:
papszMetadata = hDataset.GetMetadata_List(extra_domain)
if papszMetadata is not None and len(papszMetadata) > 0 :
print( "Metadata (%s):" % extra_domain)
for metadata in papszMetadata:
print( " %s" % metadata )
#/* -------------------------------------------------------------------- */
#/* Report "IMAGE_STRUCTURE" metadata. */
#/* -------------------------------------------------------------------- */
if bShowMetadata:
papszMetadata = hDataset.GetMetadata_List("IMAGE_STRUCTURE")
else:
papszMetadata = None
if bShowMetadata and papszMetadata is not None and len(papszMetadata) > 0 :
print( "Image Structure Metadata:" )
for metadata in papszMetadata:
print( " %s" % metadata )
#/* -------------------------------------------------------------------- */
#/* Report subdatasets. */
#/* -------------------------------------------------------------------- */
papszMetadata = hDataset.GetMetadata_List("SUBDATASETS")
if papszMetadata is not None and len(papszMetadata) > 0 :
print( "Subdatasets:" )
for metadata in papszMetadata:
print( " %s" % metadata )
#/* -------------------------------------------------------------------- */
#/* Report geolocation. */
#/* -------------------------------------------------------------------- */
if bShowMetadata:
papszMetadata = hDataset.GetMetadata_List("GEOLOCATION")
else:
papszMetadata = None
if bShowMetadata and papszMetadata is not None and len(papszMetadata) > 0 :
print( "Geolocation:" )
for metadata in papszMetadata:
print( " %s" % metadata )
#/* -------------------------------------------------------------------- */
#/* Report RPCs */
#/* -------------------------------------------------------------------- */
if bShowMetadata:
papszMetadata = hDataset.GetMetadata_List("RPC")
else:
papszMetadata = None
if bShowMetadata and papszMetadata is not None and len(papszMetadata) > 0 :
print( "RPC Metadata:" )
for metadata in papszMetadata:
print( " %s" % metadata )
#/* -------------------------------------------------------------------- */
#/* Setup projected to lat/long transform if appropriate. */
#/* -------------------------------------------------------------------- */
if pszProjection is not None and len(pszProjection) > 0:
hProj = osr.SpatialReference( pszProjection )
if hProj is not None:
hLatLong = hProj.CloneGeogCS()
if hLatLong is not None:
gdal.PushErrorHandler( 'CPLQuietErrorHandler' )
hTransform = osr.CoordinateTransformation( hProj, hLatLong )
gdal.PopErrorHandler()
if gdal.GetLastErrorMsg().find( 'Unable to load PROJ.4 library' ) != -1:
hTransform = None
#/* -------------------------------------------------------------------- */
#/* Report corners. */
#/* -------------------------------------------------------------------- */
if debug:
print( "Corner Coordinates:" )
GDALInfoReportCorner( hDataset, hTransform, "Upper Left", \
0.0, 0.0 );
GDALInfoReportCorner( hDataset, hTransform, "Lower Left", \
0.0, hDataset.RasterYSize);
GDALInfoReportCorner( hDataset, hTransform, "Upper Right", \
hDataset.RasterXSize, 0.0 );
GDALInfoReportCorner( hDataset, hTransform, "Lower Right", \
hDataset.RasterXSize, \
hDataset.RasterYSize );
GDALInfoReportCorner( hDataset, hTransform, "Center", \
hDataset.RasterXSize/2.0, \
hDataset.RasterYSize/2.0 );
#Get bounds
ulx = GDALGetLon( hDataset, hTransform, 0.0, 0.0 );
uly = GDALGetLat( hDataset, hTransform, 0.0, 0.0 );
lrx = GDALGetLon( hDataset, hTransform, hDataset.RasterXSize, \
hDataset.RasterYSize );
lry = GDALGetLat( hDataset, hTransform, hDataset.RasterXSize, \
hDataset.RasterYSize );
if (centerLon):
centLon = centerLon
#Calculate Simple Cylindrical X,Y in meters from bounds if not projected.
#Needs testing.
if (pszProjection[0:6] == "GEOGCS"):
#note that: mres = adfGeoTransform[1] * (semiMajor * math.pi / 180.0)
UpperLeftCornerX = semiMajor * (ulx - centLon) * math.pi / 180.0
UpperLeftCornerY = semiMajor * uly * math.pi / 180.0
#/* ==================================================================== */
#/* Loop over bands. */
#/* ==================================================================== */
if debug:
bands = hDataset.RasterCount
for iBand in range(hDataset.RasterCount):
hBand = hDataset.GetRasterBand(iBand+1 )
#if( bSample )
#{
# float afSample[10000];
# int nCount;
#
# nCount = GDALGetRandomRasterSample( hBand, 10000, afSample );
# print( "Got %d samples.\n", nCount );
#}
(nBlockXSize, nBlockYSize) = hBand.GetBlockSize()
print( "Band %d Block=%dx%d Type=%s, ColorInterp=%s" % ( iBand+1, \
nBlockXSize, nBlockYSize, \
gdal.GetDataTypeName(hBand.DataType), \
gdal.GetColorInterpretationName( \
hBand.GetRasterColorInterpretation()) ))
if hBand.GetDescription() is not None \
and len(hBand.GetDescription()) > 0 :
print( " Description = %s" % hBand.GetDescription() )
dfMin = hBand.GetMinimum()
dfMax = hBand.GetMaximum()
if dfMin is not None or dfMax is not None or bComputeMinMax:
line = " "
if dfMin is not None:
line = line + ("Min=%.3f " % dfMin)
if dfMax is not None:
line = line + ("Max=%.3f " % dfMax)
if bComputeMinMax:
gdal.ErrorReset()
adfCMinMax = hBand.ComputeRasterMinMax(False)
if gdal.GetLastErrorType() == gdal.CE_None:
line = line + ( " Computed Min/Max=%.3f,%.3f" % ( \
adfCMinMax[0], adfCMinMax[1] ))
print( line )
stats = hBand.GetStatistics( bApproxStats, bStats)
# Dirty hack to recognize if stats are valid. If invalid, the returned
# stddev is negative
if stats[3] >= 0.0:
print( " Minimum=%.3f, Maximum=%.3f, Mean=%.3f, StdDev=%.3f" % ( \
stats[0], stats[1], stats[2], stats[3] ))
if bReportHistograms:
hist = hBand.GetDefaultHistogram(force = True, callback = gdal.TermProgress)
if hist is not None:
dfMin = hist[0]
dfMax = hist[1]
nBucketCount = hist[2]
panHistogram = hist[3]
print( " %d buckets from %g to %g:" % ( \
nBucketCount, dfMin, dfMax ))
line = ' '
for bucket in panHistogram:
line = line + ("%d " % bucket)
print(line)
if bComputeChecksum:
print( " Checksum=%d" % hBand.Checksum())
dfNoData = hBand.GetNoDataValue()
if dfNoData is not None:
if dfNoData != dfNoData:
print( " NoData Value=nan" )
else:
print( " NoData Value=%.18g" % dfNoData )
if hBand.GetOverviewCount() > 0:
line = " Overviews: "
for iOverview in range(hBand.GetOverviewCount()):
if iOverview != 0 :
line = line + ", "
hOverview = hBand.GetOverview( iOverview );
if hOverview is not None:
line = line + ( "%dx%d" % (hOverview.XSize, hOverview.YSize))
pszResampling = \
hOverview.GetMetadataItem( "RESAMPLING", "" )
if pszResampling is not None \
and len(pszResampling) >= 12 \
and EQUAL(pszResampling[0:12],"AVERAGE_BIT2"):
line = line + "*"
else:
line = line + "(null)"
print(line)
if bComputeChecksum:
line = " Overviews checksum: "
for iOverview in range(hBand.GetOverviewCount()):
if iOverview != 0:
line = line + ", "
hOverview = hBand.GetOverview( iOverview );
if hOverview is not None:
line = line + ( "%d" % hOverview.Checksum())
else:
line = line + "(null)"
print(line)
if hBand.HasArbitraryOverviews():
print( " Overviews: arbitrary" )
nMaskFlags = hBand.GetMaskFlags()
if (nMaskFlags & (gdal.GMF_NODATA|gdal.GMF_ALL_VALID)) == 0:
hMaskBand = hBand.GetMaskBand()
line = " Mask Flags: "
if (nMaskFlags & gdal.GMF_PER_DATASET) != 0:
line = line + "PER_DATASET "
if (nMaskFlags & gdal.GMF_ALPHA) != 0:
line = line + "ALPHA "
if (nMaskFlags & gdal.GMF_NODATA) != 0:
line = line + "NODATA "
if (nMaskFlags & gdal.GMF_ALL_VALID) != 0:
line = line + "ALL_VALID "
print(line)
if hMaskBand is not None and \
hMaskBand.GetOverviewCount() > 0:
line = " Overviews of mask band: "
for iOverview in range(hMaskBand.GetOverviewCount()):
if iOverview != 0:
line = line + ", "
hOverview = hMaskBand.GetOverview( iOverview );
if hOverview is not None:
line = line + ( "%d" % hOverview.Checksum())
else:
line = line + "(null)"
if len(hBand.GetUnitType()) > 0:
print( " Unit Type: %s" % hBand.GetUnitType())
papszCategories = hBand.GetRasterCategoryNames()
if papszCategories is not None:
print( " Categories:" );
i = 0
for category in papszCategories:
print( " %3d: %s" % (i, category) )
i = i + 1
if hBand.GetScale() != 1.0 or hBand.GetOffset() != 0.0:
print( " Offset: %.15g, Scale:%.15g" % \
( hBand.GetOffset(), hBand.GetScale()))
if bShowMetadata:
papszMetadata = hBand.GetMetadata_List()
else:
papszMetadata = None
if bShowMetadata and papszMetadata is not None and len(papszMetadata) > 0 :
print( " Metadata:" )
for metadata in papszMetadata:
print( " %s" % metadata )
if bShowMetadata:
papszMetadata = hBand.GetMetadata_List("IMAGE_STRUCTURE")
else:
papszMetadata = None
if bShowMetadata and papszMetadata is not None and len(papszMetadata) > 0 :
print( " Image Structure Metadata:" )
for metadata in papszMetadata:
print( " %s" % metadata )
hTable = hBand.GetRasterColorTable()
if hBand.GetRasterColorInterpretation() == gdal.GCI_PaletteIndex \
and hTable is not None:
print( " Color Table (%s with %d entries)" % (\
gdal.GetPaletteInterpretationName( \
hTable.GetPaletteInterpretation( )), \
hTable.GetCount() ))
if bShowColorTable:
for i in range(hTable.GetCount()):
sEntry = hTable.GetColorEntry(i)
print( " %3d: %d,%d,%d,%d" % ( \
i, \
sEntry[0],\
sEntry[1],\
sEntry[2],\
sEntry[3] ))
if bShowRAT:
hRAT = hBand.GetDefaultRAT()
#GDALRATDumpReadable( hRAT, None );
#/***************************************************************************/
#/* WriteISISlabel() */
#/***************************************************************************/
#def WriteISISLabel(outFile, DataSetID, pszFilename, sampleBits, lines, samples):
#Currently just procedural programming. Gets the job done...
#
instrList = pszFilename.split("_")
hBand = hDataset.GetRasterBand( 1 )
#get the datatype
print gdal.GetDataTypeName(hBand.DataType)
if EQUAL(gdal.GetDataTypeName(hBand.DataType), "Float32"):
sample_bits = 32
sample_type = "Real"
sample_mask = "2#11111111111111111111111111111111#"
elif EQUAL(gdal.GetDataTypeName(hBand.DataType), "Float64"):
sample_bits = 32
sample_type = "Real"
sample_mask = "2#11111111111111111111111111111111#"
elif EQUAL(gdal.GetDataTypeName(hBand.DataType), "INT16"):
sample_bits = 16
sample_type = "SignedWord"
sample_mask = "2#1111111111111111#"
elif EQUAL(gdal.GetDataTypeName(hBand.DataType), "UINT16"):
sample_bits = 16
sample_type = "UsignedWord"
sample_mask = "2#1111111111111111#"
elif EQUAL(gdal.GetDataTypeName(hBand.DataType), "Byte"):
sample_bits = 8
sample_type = "UnsignedByte"
sample_mask = "2#11111111#"
else:
print( " %s: Not supported pixel type. Please convert to 8, 16 Int, or 32 Float" % gdal.GetDataTypeName(hBand.DataType))
sys.exit(1)
f.write('Object = IsisCube\n')
f.write(' Object = Core\n')
f.write(' StartByte = 1\n')
#f.write('/* The source image data definition. */\n')
f.write(' ^Core = %s\n' % (dst_cub))
f.write(' Format = BandSequential\n')
f.write('\n')
f.write(' Group = Dimensions\n')
f.write(' Samples = %d\n' % (hDataset.RasterXSize))
f.write(' Lines = %d\n' % hDataset.RasterYSize)
f.write(' Bands = %d\n' % hDataset.RasterCount)
f.write(' End_Group\n')
f.write('\n')
f.write(' Group = Pixels\n')
f.write(' Type = %s\n' % (sample_type))
f.write(' ByteOrder = Lsb\n')
if base is None:
f.write(' Base = %.10g\n' % ( hBand.GetOffset() ))
if EQUAL(sample_type, "REAL"):
if (hBand.GetOffset() <> 0):
print("Warning: a none 0 'base' was set but input is 32bit Float. ISIS will not use this value when type is REAL. Please use 'fx' to apply this base value: %.10g" % ( hBand.GetOffset() ))
else:
f.write(' Base = %.10g\n' % base )
if EQUAL(sample_type, "REAL"):
print("Warning: '-base' was set but input is 32bit Float. ISIS will not use this value when type is REAL. Please use 'fx' to apply this base value.")
if multiplier is None:
f.write(' Multiplier = %.10g\n' % ( hBand.GetScale() ))
if EQUAL(sample_type, "REAL"):
if (hBand.GetScale() <> 1):
print("Warning: a none 1 'multiplier' was set but input is 32bit Float. ISIS will not use this value when type is REAL. Please use 'fx' to apply this multiplier value: %.10g" % ( hBand.GetScale() ))
else:
f.write(' Multiplier = %.10g\n' % multiplier )
if EQUAL(sample_type, "REAL"):
print("Warning: '-multiplier' was set but input is 32bit Float. ISIS will not use this value when type is REAL. Please use 'fx' to apply this multiplier value.")
f.write(' End_Group\n')
f.write(' End_Object\n')
f.write('\n')
f.write(' Group = Archive\n')
f.write(' DataSetId = %s\n' % pszFilename.split(".")[0])
f.write(' ProducerInstitutionName = \"Astrogeology Science Center\"\n')
f.write(' ProducerId = Astrogeology\n')
f.write(' ProducerFullName = USGS\n')
if "_v" in pszFilename:
f.write(' ProductId = %s\n' % instrList[-1].split(".")[0].upper())
else:
f.write(' ProductId = n/a\n')
f.write(' ProductVersionId = n/a\n')
f.write(' InstrumentHostName = n/a\n')
f.write(' InstrumentName = n/a\n')
f.write(' InstrumentId = n/a\n')
f.write(' TargetName = %s\n' % target)
f.write(' MissionPhaseName = n/a\n')
f.write(' End_Group\n')
f.write('\n')
if target <> "n/a":
f.write(' Group = Mapping\n')
f.write(' ProjectionName = %s\n' % mapProjection)
if ((centLon < 0) and force360):
centLon = centLon + 360
f.write(' CenterLongitude = %.5f\n' % centLon)
f.write(' CenterLatitude = %.5f\n' % centLat)
if EQUAL(mapProjection,"TransverseMercator"):
f.write(' ScaleFactor = %6.5f\n' % TMscale)
f.write(' TargetName = %s\n' % target)
f.write(' EquatorialRadius = %.1f <meters>\n' % semiMajor)
f.write(' PolarRadius = %.1f <meters>\n' % semiMinor)
if EQUAL(mapProjection,"TransverseMercator"):
f.write(' LatitudeType = Planetographic\n')
else:
f.write(' LatitudeType = Planetocentric\n')
f.write(' LongitudeDirection = PositiveEast\n')
if (force360 or (lrx > 180)):
f.write(' LongitudeDomain = 360\n')
else:
f.write(' LongitudeDomain = 180\n')
f.write(' PixelResolution = %.8f <meters/pixel>\n' % mres )
f.write(' Scale = %.4f <pixel/degree>\n' % mapres )
if lry < uly:
f.write(' MinimumLatitude = %.8f\n' % lry)
f.write(' MaximumLatitude = %.8f\n' % uly)
else:
f.write(' MinimumLatitude = %.8f\n' % uly)
f.write(' MaximumLatitude = %.8f\n' % lry)
#push into 360 domain (for Astropedia)
if (force360):
if (ulx < 0):
ulx = ulx + 360
if (lrx < 0):
lrx = lrx + 360
if lrx < ulx:
f.write(' MinimumLongitude = %.8f\n' % lrx)
f.write(' MaximumLongitude = %.8f\n' % ulx)
else:
f.write(' MinimumLongitude = %.8f\n' % ulx)
f.write(' MaximumLongitude = %.8f\n' % lrx)
f.write(' UpperLeftCornerX = %.6f <meters>\n' % ( UpperLeftCornerX ))
f.write(' UpperLeftCornerY = %.6f <meters>\n' % ( UpperLeftCornerY ))
f.write(' End_Group\n')
f.write('End_Object\n')
f.write('\n')
f.write('Object = Label\n')
#NOT correct
f.write(' Bytes = 256\n')
f.write('End_Object\n')
f.write('\n')
f.write('Object = History\n')
f.write(' Name = IsisCube\n')
f.write(' StartByte = 1\n')
#NOT correct
f.write(' Bytes = 0\n')
f.write(' ^History = %s\n' % dst_hst)
f.write('End_Object\n')
f.write('End\n')
f.close()
#remove history until we fix the size. This is causing issues with cathist
#f_hst.write('Object = Astropedia_gdal2isis.py\n')
#f_hst.write(' Version = 0.1\n')
#f_hst.write(' ProgramVersion = 2013-06-05\n')
#f_hst.write(' ExecutionDateTime = %s\n' % str(datetime.datetime.now().isoformat()))
#f_hst.write(' Description = \"Convert GDAL supported image to an ISIS detached label and raw image\"\n')
#f_hst.write('End_Object\n')
f_hst.close()
#########################
#Export out raw image
#########################
#Setup the output dataset
print (' - ISIS3 label created: %s' % dst_lbl)
print (' - ISIS3 history created: %s' % dst_hst)
if bMakeImage:
print ('Please wait, writing out raw image: %s' % dst_cub)
driver = gdal.GetDriverByName('ENVI')
output = driver.CreateCopy(dst_cub, hDataset, 1)
if attach:
#print 'sleeping 5 seconds'
#time.sleep(5)
cmd = "/usgs/cdev/contrib/bin/run_cubeatt.sh %s %s" % (dst_lbl, attach_cub)
#cmd = "cubeatt from=%s to=%s\n" % (dst_lbl, attach_cub)
print cmd
#subprocess.call(cmd, shell=True)
os.system(cmd)
os.remove(dst_cub)
os.remove(dst_lbl)
os.remove(dst_hst)
os.remove(dst_hdr)
os.remove(dst_aux)
print ('Complete')
return 0
#/************************************************************************/
#/* GDALInfoReportCorner() */
#/************************************************************************/
def GDALInfoReportCorner( hDataset, hTransform, corner_name, x, y ):
line = "%-11s " % corner_name
#/* -------------------------------------------------------------------- */
#/* Transform the point into georeferenced coordinates. */
#/* -------------------------------------------------------------------- */
adfGeoTransform = hDataset.GetGeoTransform(can_return_null = True)
if adfGeoTransform is not None:
dfGeoX = adfGeoTransform[0] + adfGeoTransform[1] * x \
+ adfGeoTransform[2] * y
dfGeoY = adfGeoTransform[3] + adfGeoTransform[4] * x \
+ adfGeoTransform[5] * y
else:
line = line + ("(%7.1f,%7.1f)" % (x, y ))
print(line)
return False
#/* -------------------------------------------------------------------- */
#/* Report the georeferenced coordinates. */
#/* -------------------------------------------------------------------- */
if abs(dfGeoX) < 181 and abs(dfGeoY) < 91:
line = line + ( "(%12.7f,%12.7f) " % (dfGeoX, dfGeoY ))
else:
line = line + ( "(%12.3f,%12.3f) " % (dfGeoX, dfGeoY ))
#/* -------------------------------------------------------------------- */
#/* Transform to latlong and report. */
#/* -------------------------------------------------------------------- */
if hTransform is not None:
pnt = hTransform.TransformPoint(dfGeoX, dfGeoY, 0)
if pnt is not None:
line = line + ( "(%s," % gdal.DecToDMS( pnt[0], "Long", 2 ) )
line = line + ( "%s)" % gdal.DecToDMS( pnt[1], "Lat", 2 ) )
print(line)
return True
#/************************************************************************/
#/* GDALGetLon() */
#/************************************************************************/
def GDALGetLon( hDataset, hTransform, x, y ):
#/* -------------------------------------------------------------------- */
#/* Transform the point into georeferenced coordinates. */
#/* -------------------------------------------------------------------- */
adfGeoTransform = hDataset.GetGeoTransform(can_return_null = True)
if adfGeoTransform is not None:
dfGeoX = adfGeoTransform[0] + adfGeoTransform[1] * x \
+ adfGeoTransform[2] * y
dfGeoY = adfGeoTransform[3] + adfGeoTransform[4] * x \
+ adfGeoTransform[5] * y
else:
return 0.0
#/* -------------------------------------------------------------------- */
#/* Transform to latlong and report. */
#/* -------------------------------------------------------------------- */
if hTransform is not None:
pnt = hTransform.TransformPoint(dfGeoX, dfGeoY, 0)
if pnt is not None:
return pnt[0]
return dfGeoX
#/************************************************************************/
#/* GDALGetLat() */
#/************************************************************************/
def GDALGetLat( hDataset, hTransform, x, y ):
#/* -------------------------------------------------------------------- */
#/* Transform the point into georeferenced coordinates. */
#/* -------------------------------------------------------------------- */
|
if __name__ == '__main__':
version_num = int(gdal.VersionInfo('VERSION_NUM'))
if version_num < 1800: # because of GetGeoTransform(can_return_null)
print('ERROR: Python bindings of GDAL 1.8.0 or later required')
sys.exit(1)
sys.exit(main(sys.argv))
| adfGeoTransform = hDataset.GetGeoTransform(can_return_null = True)
if adfGeoTransform is not None:
dfGeoX = adfGeoTransform[0] + adfGeoTransform[1] * x \
+ adfGeoTransform[2] * y
dfGeoY = adfGeoTransform[3] + adfGeoTransform[4] * x \
+ adfGeoTransform[5] * y
else:
return 0.0
#/* -------------------------------------------------------------------- */
#/* Transform to latlong and report. */
#/* -------------------------------------------------------------------- */
if hTransform is not None:
pnt = hTransform.TransformPoint(dfGeoX, dfGeoY, 0)
if pnt is not None:
return pnt[1]
return dfGeoY |
coinbase-form.js | const Component = require('react').Component
const h = require('react-hyperscript')
const inherits = require('util').inherits
const connect = require('react-redux').connect
const actions = require('../actions')
module.exports = connect(mapStateToProps)(CoinbaseForm)
function | (state) {
return {
warning: state.appState.warning,
}
}
inherits(CoinbaseForm, Component)
function CoinbaseForm () {
Component.call(this)
}
CoinbaseForm.prototype.render = function () {
var props = this.props
return h('.flex-column', {
style: {
marginTop: '35px',
padding: '25px',
width: '100%',
},
}, [
h('.flex-row', {
style: {
justifyContent: 'space-around',
margin: '33px',
marginTop: '0px',
},
}, [
h('button.btn-green', {
onClick: this.toCoinbase.bind(this),
}, 'Continue to Coinbase'),
h('button.btn-red', {
onClick: () => props.dispatch(actions.goHome()),
}, 'Cancel'),
]),
])
}
CoinbaseForm.prototype.toCoinbase = function () {
const props = this.props
const address = props.buyView.buyAddress
props.dispatch(actions.buyEth({ network: '1', address, amount: 0 }))
}
CoinbaseForm.prototype.renderLoading = function () {
return h('img', {
style: {
width: '27px',
marginRight: '-27px',
},
src: 'images/loading.svg',
})
}
| mapStateToProps |
bar-chart.js | import React from 'react'
import {View} from 'react-native'
import {Svg, Rect, G} from 'react-native-svg'
import AbstractChart from './abstract-chart'
const barWidth = 32
class BarChart extends AbstractChart {
renderBars = config => {
const {data, width, height, paddingTop, paddingRight} = config
return data.map((x, i) => {
const barHeight =
(height / 4) * 3 * ((x - Math.min(...data)) / this.calcScaler(data))
const barWidth = 32
return (
<Rect
key={Math.random()}
x={
paddingRight +
(i * (width - paddingRight)) / data.length +
barWidth / 2
}
y={(height / 4) * 3 - barHeight + paddingTop}
width={barWidth}
height={barHeight}
fill="url(#fillShadowGradient)"
/>
)
})
}
renderBarTops = config => {
const {data, width, height, paddingTop, paddingRight} = config
return data.map((x, i) => { | (height / 4) * 3 * ((x - Math.min(...data)) / this.calcScaler(data))
return (
<Rect
key={Math.random()}
x={
paddingRight +
(i * (width - paddingRight)) / data.length +
barWidth / 2
}
y={(height / 4) * 3 - barHeight + paddingTop}
width={barWidth}
height={2}
fill={this.props.chartConfig.color(0.6)}
/>
)
})
}
render() {
const paddingTop = 16
const paddingRight = 64
const {width, height, data, style = {}} = this.props
const {borderRadius = 0} = style
const config = {
width,
height
}
return (
<View style={style}>
<Svg height={height} width={width}>
{this.renderDefs({
...config,
...this.props.chartConfig
})}
<Rect
width="100%"
height={height}
rx={borderRadius}
ry={borderRadius}
fill="url(#backgroundGradient)"
/>
<G>
{this.renderHorizontalLines({
...config,
count: 4,
paddingTop
})}
</G>
<G>
{this.renderHorizontalLabels({
...config,
count: 4,
data: data.datasets[0].data,
paddingTop,
paddingRight
})}
</G>
<G>
{this.renderVerticalLabels({
...config,
labels: data.labels,
paddingRight,
paddingTop,
horizontalOffset: barWidth
})}
</G>
<G>
{this.renderBars({
...config,
data: data.datasets[0].data,
paddingTop,
paddingRight
})}
</G>
<G>
{this.renderBarTops({
...config,
data: data.datasets[0].data,
paddingTop,
paddingRight
})}
</G>
</Svg>
</View>
)
}
}
export default BarChart | const barHeight = |
anko_test.go | package fix
import (
"io/ioutil"
"strings"
"testing"
"github.com/gobuffalo/packr/v2" | r := require.New(t)
box := packr.New("./fixtures", "./fixtures")
err := box.Walk(func(path string, info packr.File) error {
if strings.HasPrefix(path, "pass") {
t.Run(path, testPass(path, info))
return nil
}
t.Run(path, testFail(path, info))
return nil
})
r.NoError(err)
}
func testPass(path string, info packr.File) func(*testing.T) {
return func(t *testing.T) {
r := require.New(t)
b, err := ioutil.ReadAll(info)
r.NoError(err)
body := string(b)
fixed, err := Anko(body)
r.NoError(err)
if strings.Contains(path, "anko") {
r.NotEqual(body, fixed)
} else {
r.Equal(body, fixed)
}
}
}
func testFail(path string, info packr.File) func(*testing.T) {
return func(t *testing.T) {
r := require.New(t)
b, err := ioutil.ReadAll(info)
r.NoError(err)
body := string(b)
_, err = Anko(body)
r.Error(err)
}
} | "github.com/stretchr/testify/require"
)
func Test_Anko(t *testing.T) { |
main.rs | use actix_web::{error, get, web, App, HttpRequest, HttpResponse, HttpServer};
use anyhow::{Context, Result};
use http::StatusCode;
use log::info;
use serde::de;
use serde::Deserialize;
use serde::Deserializer;
use std::net::IpAddr;
use std::net::TcpStream;
use std::net::ToSocketAddrs;
use std::net::{Shutdown, SocketAddr};
use std::time::Duration;
use structopt::clap::crate_version;
use structopt::StructOpt;
use crate::args::ProbyConfig;
mod args;
#[derive(Debug, Clone)]
struct SocketInfo {
original_str: String,
socket_addr: SocketAddr,
}
impl<'de> Deserialize<'de> for SocketInfo {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let param = String::deserialize(deserializer)?;
let mut socket_addrs = param
.as_str()
.to_socket_addrs()
.map_err(|_| de::Error::custom("Error while parsing host or port"))?;
Ok(Self {
socket_addr: socket_addrs
.next()
.ok_or_else(|| de::Error::custom("Weird bug happened"))?,
original_str: param,
})
}
}
#[derive(Clone)]
struct FormattedSockets {
data: Vec<String>,
}
#[get("/")]
async fn usage(sockets: web::Data<FormattedSockets>) -> String {
let examples: String = sockets
.data
.iter()
.map(|x| format!(" curl http://{}/example.com:1337\n", x))
.collect();
format!(
"proby {version}
Try something like this:
{examples}",
version = crate_version!(),
examples = examples,
)
}
#[derive(Debug, Deserialize)]
struct HttpCode(#[serde(with = "serde_with::rust::display_fromstr")] StatusCode);
#[derive(Debug, Deserialize)]
struct CheckHostPortOptions {
good: Option<HttpCode>,
bad: Option<HttpCode>,
timeout: Option<u64>,
}
#[get("/{socket_info}")]
async fn check_host_port(
args: web::Data<ProbyConfig>,
req: HttpRequest,
socket_info: web::Path<SocketInfo>,
params: web::Query<CheckHostPortOptions>,
) -> HttpResponse {
let good_status = params.good.as_ref().unwrap_or(&HttpCode(StatusCode::OK));
let bad_status = params
.bad
.as_ref()
.unwrap_or(&HttpCode(StatusCode::SERVICE_UNAVAILABLE));
let timeout = Duration::new(params.timeout.unwrap_or(1), 0);
if args.verbose {
let params_text = format!(
"(good: {}, bad: {}, timeout: {})",
good_status.0.as_u16(),
bad_status.0.as_u16(),
timeout.as_secs()
);
info!(
"{} requesting check of {} {}",
req.peer_addr().unwrap(),
socket_info.original_str,
params_text,
);
}
let socket_addr = socket_info.socket_addr;
if let Ok(stream) = web::block(move || TcpStream::connect_timeout(&socket_addr, timeout)).await
{
stream
.shutdown(Shutdown::Both)
.expect("Couldn't tear down TCP connection");
let good_body = format!("{} is connectable", socket_info.original_str);
HttpResponse::with_body(good_status.0, good_body.into())
} else {
let bad_body = format!("{} is NOT connectable", socket_info.original_str);
HttpResponse::with_body(bad_status.0, bad_body.into())
}
}
/// Convert a `Vec` of interfaces and a port to a `Vec` of `SocketAddr`.
fn interfaces_to_sockets(interfaces: &[IpAddr], port: u16) -> Result<Vec<SocketAddr>> {
interfaces
.iter()
.map(|&interface| {
if interface.is_ipv6() | else {
format!("{}", interface)
}
})
.map(|interface| {
format!("{interface}:{port}", interface = &interface, port = port,)
.parse::<SocketAddr>()
})
.collect::<Result<Vec<SocketAddr>, std::net::AddrParseError>>()
.context("Error during creation of sockets from interfaces and port")
}
#[actix_web::main]
async fn main() -> Result<()> {
let args = ProbyConfig::from_args();
let socket_addresses = interfaces_to_sockets(&args.interfaces, args.port)?;
let formatted_sockets = FormattedSockets {
data: socket_addresses.iter().map(|x| x.to_string()).collect(),
};
let log_level = if args.quiet {
simplelog::LevelFilter::Error
} else {
simplelog::LevelFilter::Info
};
if simplelog::TermLogger::init(
log_level,
simplelog::Config::default(),
simplelog::TerminalMode::Mixed,
simplelog::ColorChoice::Auto,
)
.is_err()
{
simplelog::SimpleLogger::init(log_level, simplelog::Config::default())
.expect("Couldn't initialize logger")
}
info!("proby {version}", version = crate_version!(),);
HttpServer::new(move || {
App::new()
.data(args.clone())
.data(formatted_sockets.clone())
.service(usage)
.service(check_host_port)
.app_data(web::PathConfig::default().error_handler(|err, _req| {
let err_text = err.to_string();
error::InternalError::from_response(err, HttpResponse::BadRequest().body(err_text))
.into()
}))
})
.bind(socket_addresses.as_slice())?
.run()
.await
.context("Error while running web server!")
}
| {
// If the interface is IPv6 then we'll print it with brackets so that it is
// clickable and also because for some reason, actix-web won't it otherwise.
format!("[{}]", interface)
} |
fil_PH.go | package fil_PH
import (
"math"
"strconv"
"time"
"github.com/DeineAgenturUG/locales"
"github.com/DeineAgenturUG/locales/currency"
)
type fil_PH struct {
locale string
pluralsCardinal []locales.PluralRule
pluralsOrdinal []locales.PluralRule
pluralsRange []locales.PluralRule
decimal string
group string
minus string
percent string
perMille string
timeSeparator string
inifinity string
currencies []string // idx = enum of currency code
currencyNegativePrefix string
currencyNegativeSuffix string
monthsAbbreviated []string
monthsNarrow []string
monthsWide []string
daysAbbreviated []string
daysNarrow []string
daysShort []string
daysWide []string
periodsAbbreviated []string
periodsNarrow []string
periodsShort []string
periodsWide []string
erasAbbreviated []string
erasNarrow []string
erasWide []string
timezones map[string]string
}
// New returns a new instance of translator for the 'fil_PH' locale
func New() locales.Translator | e returns the current translators string locale
func (fil *fil_PH) Locale() string {
return fil.locale
}
// PluralsCardinal returns the list of cardinal plural rules associated with 'fil_PH'
func (fil *fil_PH) PluralsCardinal() []locales.PluralRule {
return fil.pluralsCardinal
}
// PluralsOrdinal returns the list of ordinal plural rules associated with 'fil_PH'
func (fil *fil_PH) PluralsOrdinal() []locales.PluralRule {
return fil.pluralsOrdinal
}
// PluralsRange returns the list of range plural rules associated with 'fil_PH'
func (fil *fil_PH) PluralsRange() []locales.PluralRule {
return fil.pluralsRange
}
// CardinalPluralRule returns the cardinal PluralRule given 'num' and digits/precision of 'v' for 'fil_PH'
func (fil *fil_PH) CardinalPluralRule(num float64, v uint64) locales.PluralRule {
n := math.Abs(num)
i := int64(n)
f := locales.F(n, v)
iMod10 := i % 10
fMod10 := f % 10
if (v == 0 && (i == 1 || i == 2 || i == 3)) || (v == 0 && (iMod10 != 4 && iMod10 != 6 && iMod10 != 9)) || (v != 0 && (fMod10 != 4 && fMod10 != 6 && fMod10 != 9)) {
return locales.PluralRuleOne
}
return locales.PluralRuleOther
}
// OrdinalPluralRule returns the ordinal PluralRule given 'num' and digits/precision of 'v' for 'fil_PH'
func (fil *fil_PH) OrdinalPluralRule(num float64, v uint64) locales.PluralRule {
n := math.Abs(num)
if n == 1 {
return locales.PluralRuleOne
}
return locales.PluralRuleOther
}
// RangePluralRule returns the ordinal PluralRule given 'num1', 'num2' and digits/precision of 'v1' and 'v2' for 'fil_PH'
func (fil *fil_PH) RangePluralRule(num1 float64, v1 uint64, num2 float64, v2 uint64) locales.PluralRule {
start := fil.CardinalPluralRule(num1, v1)
end := fil.CardinalPluralRule(num2, v2)
if start == locales.PluralRuleOne && end == locales.PluralRuleOne {
return locales.PluralRuleOne
} else if start == locales.PluralRuleOne && end == locales.PluralRuleOther {
return locales.PluralRuleOther
} else if start == locales.PluralRuleOther && end == locales.PluralRuleOne {
return locales.PluralRuleOne
}
return locales.PluralRuleOther
}
// MonthAbbreviated returns the locales abbreviated month given the 'month' provided
func (fil *fil_PH) MonthAbbreviated(month time.Month) string {
return fil.monthsAbbreviated[month]
}
// MonthsAbbreviated returns the locales abbreviated months
func (fil *fil_PH) MonthsAbbreviated() []string {
return fil.monthsAbbreviated[1:]
}
// MonthNarrow returns the locales narrow month given the 'month' provided
func (fil *fil_PH) MonthNarrow(month time.Month) string {
return fil.monthsNarrow[month]
}
// MonthsNarrow returns the locales narrow months
func (fil *fil_PH) MonthsNarrow() []string {
return fil.monthsNarrow[1:]
}
// MonthWide returns the locales wide month given the 'month' provided
func (fil *fil_PH) MonthWide(month time.Month) string {
return fil.monthsWide[month]
}
// MonthsWide returns the locales wide months
func (fil *fil_PH) MonthsWide() []string {
return fil.monthsWide[1:]
}
// WeekdayAbbreviated returns the locales abbreviated weekday given the 'weekday' provided
func (fil *fil_PH) WeekdayAbbreviated(weekday time.Weekday) string {
return fil.daysAbbreviated[weekday]
}
// WeekdaysAbbreviated returns the locales abbreviated weekdays
func (fil *fil_PH) WeekdaysAbbreviated() []string {
return fil.daysAbbreviated
}
// WeekdayNarrow returns the locales narrow weekday given the 'weekday' provided
func (fil *fil_PH) WeekdayNarrow(weekday time.Weekday) string {
return fil.daysNarrow[weekday]
}
// WeekdaysNarrow returns the locales narrow weekdays
func (fil *fil_PH) WeekdaysNarrow() []string {
return fil.daysNarrow
}
// WeekdayShort returns the locales short weekday given the 'weekday' provided
func (fil *fil_PH) WeekdayShort(weekday time.Weekday) string {
return fil.daysShort[weekday]
}
// WeekdaysShort returns the locales short weekdays
func (fil *fil_PH) WeekdaysShort() []string {
return fil.daysShort
}
// WeekdayWide returns the locales wide weekday given the 'weekday' provided
func (fil *fil_PH) WeekdayWide(weekday time.Weekday) string {
return fil.daysWide[weekday]
}
// WeekdaysWide returns the locales wide weekdays
func (fil *fil_PH) WeekdaysWide() []string {
return fil.daysWide
}
// Decimal returns the decimal point of number
func (fil *fil_PH) Decimal() string {
return fil.decimal
}
// Group returns the group of number
func (fil *fil_PH) Group() string {
return fil.group
}
// Group returns the minus sign of number
func (fil *fil_PH) Minus() string {
return fil.minus
}
// FmtNumber returns 'num' with digits/precision of 'v' for 'fil_PH' and handles both Whole and Real numbers based on 'v'
func (fil *fil_PH) FmtNumber(num float64, v uint64) string {
s := strconv.FormatFloat(math.Abs(num), 'f', int(v), 64)
l := len(s) + 2 + 1*len(s[:len(s)-int(v)-1])/3
count := 0
inWhole := v == 0
b := make([]byte, 0, l)
for i := len(s) - 1; i >= 0; i-- {
if s[i] == '.' {
b = append(b, fil.decimal[0])
inWhole = true
continue
}
if inWhole {
if count == 3 {
b = append(b, fil.group[0])
count = 1
} else {
count++
}
}
b = append(b, s[i])
}
if num < 0 {
b = append(b, fil.minus[0])
}
// reverse
for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
b[i], b[j] = b[j], b[i]
}
return string(b)
}
// FmtPercent returns 'num' with digits/precision of 'v' for 'fil_PH' and handles both Whole and Real numbers based on 'v'
// NOTE: 'num' passed into FmtPercent is assumed to be in percent already
func (fil *fil_PH) FmtPercent(num float64, v uint64) string {
s := strconv.FormatFloat(math.Abs(num), 'f', int(v), 64)
l := len(s) + 3
b := make([]byte, 0, l)
for i := len(s) - 1; i >= 0; i-- {
if s[i] == '.' {
b = append(b, fil.decimal[0])
continue
}
b = append(b, s[i])
}
if num < 0 {
b = append(b, fil.minus[0])
}
// reverse
for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
b[i], b[j] = b[j], b[i]
}
b = append(b, fil.percent...)
return string(b)
}
// FmtCurrency returns the currency representation of 'num' with digits/precision of 'v' for 'fil_PH'
func (fil *fil_PH) FmtCurrency(num float64, v uint64, currency currency.Type) string {
s := strconv.FormatFloat(math.Abs(num), 'f', int(v), 64)
symbol := fil.currencies[currency]
l := len(s) + len(symbol) + 2 + 1*len(s[:len(s)-int(v)-1])/3
count := 0
inWhole := v == 0
b := make([]byte, 0, l)
for i := len(s) - 1; i >= 0; i-- {
if s[i] == '.' {
b = append(b, fil.decimal[0])
inWhole = true
continue
}
if inWhole {
if count == 3 {
b = append(b, fil.group[0])
count = 1
} else {
count++
}
}
b = append(b, s[i])
}
for j := len(symbol) - 1; j >= 0; j-- {
b = append(b, symbol[j])
}
if num < 0 {
b = append(b, fil.minus[0])
}
// reverse
for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
b[i], b[j] = b[j], b[i]
}
if int(v) < 2 {
if v == 0 {
b = append(b, fil.decimal...)
}
for i := 0; i < 2-int(v); i++ {
b = append(b, '0')
}
}
return string(b)
}
// FmtAccounting returns the currency representation of 'num' with digits/precision of 'v' for 'fil_PH'
// in accounting notation.
func (fil *fil_PH) FmtAccounting(num float64, v uint64, currency currency.Type) string {
s := strconv.FormatFloat(math.Abs(num), 'f', int(v), 64)
symbol := fil.currencies[currency]
l := len(s) + len(symbol) + 4 + 1*len(s[:len(s)-int(v)-1])/3
count := 0
inWhole := v == 0
b := make([]byte, 0, l)
for i := len(s) - 1; i >= 0; i-- {
if s[i] == '.' {
b = append(b, fil.decimal[0])
inWhole = true
continue
}
if inWhole {
if count == 3 {
b = append(b, fil.group[0])
count = 1
} else {
count++
}
}
b = append(b, s[i])
}
if num < 0 {
for j := len(symbol) - 1; j >= 0; j-- {
b = append(b, symbol[j])
}
b = append(b, fil.currencyNegativePrefix[0])
} else {
for j := len(symbol) - 1; j >= 0; j-- {
b = append(b, symbol[j])
}
}
// reverse
for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
b[i], b[j] = b[j], b[i]
}
if int(v) < 2 {
if v == 0 {
b = append(b, fil.decimal...)
}
for i := 0; i < 2-int(v); i++ {
b = append(b, '0')
}
}
if num < 0 {
b = append(b, fil.currencyNegativeSuffix...)
}
return string(b)
}
// FmtDateShort returns the short date representation of 't' for 'fil_PH'
func (fil *fil_PH) FmtDateShort(t time.Time) string {
b := make([]byte, 0, 32)
b = strconv.AppendInt(b, int64(t.Month()), 10)
b = append(b, []byte{0x2f}...)
b = strconv.AppendInt(b, int64(t.Day()), 10)
b = append(b, []byte{0x2f}...)
if t.Year() > 9 {
b = append(b, strconv.Itoa(t.Year())[2:]...)
} else {
b = append(b, strconv.Itoa(t.Year())[1:]...)
}
return string(b)
}
// FmtDateMedium returns the medium date representation of 't' for 'fil_PH'
func (fil *fil_PH) FmtDateMedium(t time.Time) string {
b := make([]byte, 0, 32)
b = append(b, fil.monthsAbbreviated[t.Month()]...)
b = append(b, []byte{0x20}...)
b = strconv.AppendInt(b, int64(t.Day()), 10)
b = append(b, []byte{0x2c, 0x20}...)
if t.Year() > 0 {
b = strconv.AppendInt(b, int64(t.Year()), 10)
} else {
b = strconv.AppendInt(b, int64(-t.Year()), 10)
}
return string(b)
}
// FmtDateLong returns the long date representation of 't' for 'fil_PH'
func (fil *fil_PH) FmtDateLong(t time.Time) string {
b := make([]byte, 0, 32)
b = append(b, fil.monthsWide[t.Month()]...)
b = append(b, []byte{0x20}...)
b = strconv.AppendInt(b, int64(t.Day()), 10)
b = append(b, []byte{0x2c, 0x20}...)
if t.Year() > 0 {
b = strconv.AppendInt(b, int64(t.Year()), 10)
} else {
b = strconv.AppendInt(b, int64(-t.Year()), 10)
}
return string(b)
}
// FmtDateFull returns the full date representation of 't' for 'fil_PH'
func (fil *fil_PH) FmtDateFull(t time.Time) string {
b := make([]byte, 0, 32)
b = append(b, fil.daysWide[t.Weekday()]...)
b = append(b, []byte{0x2c, 0x20}...)
b = append(b, fil.monthsWide[t.Month()]...)
b = append(b, []byte{0x20}...)
b = strconv.AppendInt(b, int64(t.Day()), 10)
b = append(b, []byte{0x2c, 0x20}...)
if t.Year() > 0 {
b = strconv.AppendInt(b, int64(t.Year()), 10)
} else {
b = strconv.AppendInt(b, int64(-t.Year()), 10)
}
return string(b)
}
// FmtTimeShort returns the short time representation of 't' for 'fil_PH'
func (fil *fil_PH) FmtTimeShort(t time.Time) string {
b := make([]byte, 0, 32)
h := t.Hour()
if h > 12 {
h -= 12
}
b = strconv.AppendInt(b, int64(h), 10)
b = append(b, fil.timeSeparator...)
if t.Minute() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Minute()), 10)
b = append(b, []byte{0x20}...)
if t.Hour() < 12 {
b = append(b, fil.periodsAbbreviated[0]...)
} else {
b = append(b, fil.periodsAbbreviated[1]...)
}
return string(b)
}
// FmtTimeMedium returns the medium time representation of 't' for 'fil_PH'
func (fil *fil_PH) FmtTimeMedium(t time.Time) string {
b := make([]byte, 0, 32)
h := t.Hour()
if h > 12 {
h -= 12
}
b = strconv.AppendInt(b, int64(h), 10)
b = append(b, fil.timeSeparator...)
if t.Minute() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Minute()), 10)
b = append(b, fil.timeSeparator...)
if t.Second() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Second()), 10)
b = append(b, []byte{0x20}...)
if t.Hour() < 12 {
b = append(b, fil.periodsAbbreviated[0]...)
} else {
b = append(b, fil.periodsAbbreviated[1]...)
}
return string(b)
}
// FmtTimeLong returns the long time representation of 't' for 'fil_PH'
func (fil *fil_PH) FmtTimeLong(t time.Time) string {
b := make([]byte, 0, 32)
h := t.Hour()
if h > 12 {
h -= 12
}
b = strconv.AppendInt(b, int64(h), 10)
b = append(b, fil.timeSeparator...)
if t.Minute() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Minute()), 10)
b = append(b, fil.timeSeparator...)
if t.Second() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Second()), 10)
b = append(b, []byte{0x20}...)
if t.Hour() < 12 {
b = append(b, fil.periodsAbbreviated[0]...)
} else {
b = append(b, fil.periodsAbbreviated[1]...)
}
b = append(b, []byte{0x20}...)
tz, _ := t.Zone()
b = append(b, tz...)
return string(b)
}
// FmtTimeFull returns the full time representation of 't' for 'fil_PH'
func (fil *fil_PH) FmtTimeFull(t time.Time) string {
b := make([]byte, 0, 32)
h := t.Hour()
if h > 12 {
h -= 12
}
b = strconv.AppendInt(b, int64(h), 10)
b = append(b, fil.timeSeparator...)
if t.Minute() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Minute()), 10)
b = append(b, fil.timeSeparator...)
if t.Second() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Second()), 10)
b = append(b, []byte{0x20}...)
if t.Hour() < 12 {
b = append(b, fil.periodsAbbreviated[0]...)
} else {
b = append(b, fil.periodsAbbreviated[1]...)
}
b = append(b, []byte{0x20}...)
tz, _ := t.Zone()
if btz, ok := fil.timezones[tz]; ok {
b = append(b, btz...)
} else {
b = append(b, tz...)
}
return string(b)
}
| {
return &fil_PH{
locale: "fil_PH",
pluralsCardinal: []locales.PluralRule{2, 6},
pluralsOrdinal: []locales.PluralRule{2, 6},
pluralsRange: []locales.PluralRule{2, 6},
decimal: ".",
group: ",",
minus: "-",
percent: "%",
perMille: "‰",
timeSeparator: ":",
inifinity: "∞",
currencies: []string{"ADP", "AED", "AFA", "AFN", "ALK", "ALL", "AMD", "ANG", "AOA", "AOK", "AON", "AOR", "ARA", "ARL", "ARM", "ARP", "ARS", "ATS", "AUD", "AWG", "AZM", "AZN", "BAD", "BAM", "BAN", "BBD", "BDT", "BEC", "BEF", "BEL", "BGL", "BGM", "BGN", "BGO", "BHD", "BIF", "BMD", "BND", "BOB", "BOL", "BOP", "BOV", "BRB", "BRC", "BRE", "BRL", "BRN", "BRR", "BRZ", "BSD", "BTN", "BUK", "BWP", "BYB", "BYN", "BYR", "BZD", "CAD", "CDF", "CHE", "CHF", "CHW", "CLE", "CLF", "CLP", "CNH", "CNX", "CNY", "COP", "COU", "CRC", "CSD", "CSK", "CUC", "CUP", "CVE", "CYP", "CZK", "DDM", "DEM", "DJF", "DKK", "DOP", "DZD", "ECS", "ECV", "EEK", "EGP", "ERN", "ESA", "ESB", "ESP", "ETB", "EUR", "FIM", "FJD", "FKP", "FRF", "GBP", "GEK", "GEL", "GHC", "GHS", "GIP", "GMD", "GNF", "GNS", "GQE", "GRD", "GTQ", "GWE", "GWP", "GYD", "HKD", "HNL", "HRD", "HRK", "HTG", "HUF", "IDR", "IEP", "ILP", "ILR", "ILS", "INR", "IQD", "IRR", "ISJ", "ISK", "ITL", "JMD", "JOD", "JPY", "KES", "KGS", "KHR", "KMF", "KPW", "KRH", "KRO", "KRW", "KWD", "KYD", "KZT", "LAK", "LBP", "LKR", "LRD", "LSL", "LTL", "LTT", "LUC", "LUF", "LUL", "LVL", "LVR", "LYD", "MAD", "MAF", "MCF", "MDC", "MDL", "MGA", "MGF", "MKD", "MKN", "MLF", "MMK", "MNT", "MOP", "MRO", "MRU", "MTL", "MTP", "MUR", "MVP", "MVR", "MWK", "MXN", "MXP", "MXV", "MYR", "MZE", "MZM", "MZN", "NAD", "NGN", "NIC", "NIO", "NLG", "NOK", "NPR", "NZD", "OMR", "PAB", "PEI", "PEN", "PES", "PGK", "PHP", "PKR", "PLN", "PLZ", "PTE", "PYG", "QAR", "RHD", "ROL", "RON", "RSD", "RUB", "RUR", "RWF", "SAR", "SBD", "SCR", "SDD", "SDG", "SDP", "SEK", "SGD", "SHP", "SIT", "SKK", "SLL", "SOS", "SRD", "SRG", "SSP", "STD", "STN", "SUR", "SVC", "SYP", "SZL", "THB", "TJR", "TJS", "TMM", "TMT", "TND", "TOP", "TPE", "TRL", "TRY", "TTD", "TWD", "TZS", "UAH", "UAK", "UGS", "UGX", "USD", "USN", "USS", "UYI", "UYP", "UYU", "UYW", "UZS", "VEB", "VEF", "VES", "VND", "VNN", "VUV", "WST", "XAF", "XAG", "XAU", "XBA", "XBB", "XBC", "XBD", "XCD", "XDR", "XEU", "XFO", "XFU", "XOF", "XPD", "XPF", "XPT", "XRE", "XSU", "XTS", "XUA", "XXX", "YDD", "YER", "YUD", "YUM", "YUN", "YUR", "ZAL", "ZAR", "ZMK", "ZMW", "ZRN", "ZRZ", "ZWD", "ZWL", "ZWR"},
currencyNegativePrefix: "(",
currencyNegativeSuffix: ")",
monthsAbbreviated: []string{"", "Ene", "Peb", "Mar", "Abr", "May", "Hun", "Hul", "Ago", "Set", "Okt", "Nob", "Dis"},
monthsNarrow: []string{"", "Ene", "Peb", "Mar", "Abr", "May", "Hun", "Hul", "Ago", "Set", "Okt", "Nob", "Dis"},
monthsWide: []string{"", "Enero", "Pebrero", "Marso", "Abril", "Mayo", "Hunyo", "Hulyo", "Agosto", "Setyembre", "Oktubre", "Nobyembre", "Disyembre"},
daysAbbreviated: []string{"Lin", "Lun", "Mar", "Miy", "Huw", "Biy", "Sab"},
daysNarrow: []string{"Lin", "Lun", "Mar", "Miy", "Huw", "Biy", "Sab"},
daysShort: []string{"Li", "Lu", "Ma", "Mi", "Hu", "Bi", "Sa"},
daysWide: []string{"Linggo", "Lunes", "Martes", "Miyerkules", "Huwebes", "Biyernes", "Sabado"},
periodsAbbreviated: []string{"AM", "PM"},
periodsNarrow: []string{"am", "pm"},
periodsWide: []string{"AM", "PM"},
erasAbbreviated: []string{"BC", "AD"},
erasNarrow: []string{"", ""},
erasWide: []string{"Before Christ", "Anno Domini"},
timezones: map[string]string{"CAT": "Oras sa Gitnang Africa", "COST": "Oras sa Tag-init ng Colombia", "HEEG": "Oras sa Tag-init ng Silangang Greenland", "MEZ": "Standard na Oras sa Gitnang Europe", "HAT": "Daylight Time sa Newfoundland", "HNPM": "Standard na Oras sa Saint Pierre & Miquelon", "HEPM": "Daylight Time sa Saint Pierre & Miquelon", "ACST": "Standard na Oras sa Gitnang Australya", "WEZ": "Standard na Oras sa Kanlurang Europe", "JDT": "Daylight Time sa Japan", "WARST": "Oras sa Tag-init ng Kanlurang Argentina", "HNEG": "Standard na Oras sa Silangang Greenland", "NZDT": "Daylight Time sa New Zealand", "HNCU": "Standard na Oras sa Cuba", "HNT": "Standard na Oras sa Newfoundland", "ART": "Standard na Oras sa Argentina", "LHST": "Standard na Oras sa Lord Howe", "UYST": "Oras sa Tag-init ng Uruguay", "∅∅∅": "Oras sa Tag-init ng Amazon", "HENOMX": "Daylight Time sa Hilagang-kanlurang Mexico", "HNOG": "Standard na Oras sa Kanlurang Greenland", "AEST": "Standard na Oras sa Silangang Australya", "HEOG": "Oras sa Tag-init ng Kanlurang Greenland", "NZST": "Standard na Oras sa New Zealand", "IST": "Standard na Oras sa Bhutan", "GYT": "Oras sa Guyana", "AST": "Standard na Oras sa Atlantiko", "AEDT": "Daylight Time sa Silangang Australya", "WIB": "Oras sa Kanlurang Indonesia", "HAST": "Standard na Oras sa Hawaii-Aleutian", "HEPMX": "Daylight Time sa Pasipiko ng Mexico", "ChST": "Standard na Oras sa Chamorro", "HNPMX": "Standard na Oras sa Pasipiko ng Mexico", "GFT": "Oras sa French Guiana", "ACWDT": "Daylight Time sa Gitnang Kanlurang Australya", "ADT": "Daylight Time sa Atlantiko", "HKT": "Standard na Oras sa Hong Kong", "TMT": "Standard na Oras sa Turkmenistan", "OEZ": "Standard na Oras sa Silangang Europe", "PST": "Standard na Oras sa Pasipiko", "CHAST": "Standard na Oras sa Chatham", "MYT": "Oras sa Malaysia", "ACDT": "Daylight Time sa Gitnang Australya", "CST": "Sentral na Karaniwang Oras", "MST": "MST", "AWDT": "Daylight Time sa Kanlurang Australya", "EDT": "Eastern Daylight Time", "WAT": "Standard na Oras sa Kanlurang Africa", "ARST": "Oras sa Tag-init ng Argentina", "CDT": "Sentral na Daylight Time", "LHDT": "Daylight Time sa Lorde Howe", "WAST": "Oras sa Tag-init ng Kanlurang Africa", "COT": "Standard na Oras sa Colombia", "TMST": "Oras sa Tag-init ng Turkmenistan", "HNNOMX": "Standard na Oras sa Hilagang-kanlurang Mexico", "BOT": "Oras sa Bolivia", "HADT": "Oras sa Tag-init ng Hawaii-Aleutian", "GMT": "Greenwich Mean Time", "HKST": "Oras sa Tag-init ng Hong Kong", "WIT": "Oras sa Silangang Indonesia", "VET": "Oras sa Venezuela", "WESZ": "Oras sa Tag-init ng Kanlurang Europe", "AKST": "Standard na Oras sa Alaska", "AKDT": "Daylight Time sa Alaska", "CLT": "Standard na Oras sa Chile", "CLST": "Oras sa Tag-init ng Chile", "SGT": "Standard na Oras sa Singapore", "OESZ": "Oras sa Tag-init ng Silangang Europe", "HECU": "Daylight Time sa Cuba", "SAST": "Oras sa Timog Africa", "WITA": "Oras sa Gitnang Indonesia", "CHADT": "Daylight Time sa Chatham", "EST": "Eastern na Standard na Oras", "UYT": "Standard na Oras sa Uruguay", "MDT": "MDT", "ECT": "Oras sa Ecuador", "JST": "Standard na Oras sa Japan", "PDT": "Daylight Time sa Pasipiko", "MESZ": "Oras sa Tag-init ng Gitnang Europe", "BT": "Oras sa Bhutan", "AWST": "Standard na Oras sa Kanlurang Australya", "SRT": "Oras sa Suriname", "EAT": "Oras sa Silangang Africa", "WART": "Standard na Oras sa Kanlurang Argentina", "ACWST": "Standard Time ng Gitnang Kanluran ng Australya"},
}
}
// Local |
auth.go | package auth
import (
"fmt"
"strings"
jwt "github.com/dgrijalva/jwt-go"
"github.com/jinzhu/gorm"
"github.com/qorpress/qorpress/core/auth/auth_identity"
"github.com/qorpress/qorpress/core/auth/claims"
"github.com/qorpress/qorpress/core/mailer"
"github.com/qorpress/qorpress/core/mailer/logger"
"github.com/qorpress/qorpress/core/redirect_back"
"github.com/qorpress/qorpress/core/render"
"github.com/qorpress/qorpress/core/session/manager"
)
// Auth auth struct
type Auth struct {
*Config
// Embed SessionStorer to match Authority's AuthInterface
SessionStorerInterface
providers []Provider
}
// Config auth config
type Config struct {
// Default Database, which will be used in Auth when do CRUD, you can change a request's DB isntance by setting request Context's value, refer https://github.com/qorpress/qorpress/core/auth/blob/master/utils.go#L32
DB *gorm.DB
// AuthIdentityModel a model used to save auth info, like email/password, OAuth token, linked user's ID, https://github.com/qorpress/qorpress/core/auth/blob/master/auth_identity/auth_identity.go is the default implemention
AuthIdentityModel interface{}
// UserModel should be point of user struct's instance, it could be nil, then Auth will assume there is no user linked to auth info, and will return current auth info when get current user
UserModel interface{}
// Mount Auth into router with URLPrefix's value as prefix, default value is `/auth`.
URLPrefix string
// ViewPaths prepend views paths for auth
ViewPaths []string
// Auth is using [Render](https://github.com/qorpress/qorpress/core/render) to render pages, you could configure it with your project's Render if you have advanced usage like [BindataFS](https://github.com/qorpress/bindatafs)
Render *render.Render
// Auth is using [Mailer](https://github.com/qorpress/qorpress/core/mailer) to send email, by default, it will print email into console, you need to configure it to send real one
Mailer *mailer.Mailer
// UserStorer is an interface that defined how to get/save user, Auth provides a default one based on AuthIdentityModel, UserModel's definition
UserStorer UserStorerInterface
// SessionStorer is an interface that defined how to encode/validate/save/destroy session data and flash messages between requests, Auth provides a default method do the job, to use the default value, don't forgot to mount SessionManager's middleware into your router to save session data correctly. refer [session](https://github.com/qorpress/qorpress/core/session) for more details
SessionStorer SessionStorerInterface
// Redirector redirect user to a new page after registered, logged, confirmed...
Redirector RedirectorInterface
// LoginHandler defined behaviour when request `{Auth Prefix}/login`, default behaviour defined in http://godoc.org/github.com/qorpress/qorpress/core/auth#pkg-variables
LoginHandler func(*Context, func(*Context) (*claims.Claims, error))
// RegisterHandler defined behaviour when request `{Auth Prefix}/register`, default behaviour defined in http://godoc.org/github.com/qorpress/qorpress/core/auth#pkg-variables
RegisterHandler func(*Context, func(*Context) (*claims.Claims, error))
// LogoutHandler defined behaviour when request `{Auth Prefix}/logout`, default behaviour defined in http://godoc.org/github.com/qorpress/qorpress/core/auth#pkg-variables
LogoutHandler func(*Context)
}
// New initialize Auth
func New(config *Config) *Auth {
if config == nil {
config = &Config{}
}
if config.URLPrefix == "" {
config.URLPrefix = "/auth/"
} else {
config.URLPrefix = fmt.Sprintf("/%v/", strings.Trim(config.URLPrefix, "/"))
}
if config.AuthIdentityModel == nil {
config.AuthIdentityModel = &auth_identity.AuthIdentity{}
}
if config.Render == nil {
config.Render = render.New(nil)
}
if config.Mailer == nil {
config.Mailer = mailer.New(&mailer.Config{
Sender: logger.New(&logger.Config{}),
})
}
if config.UserStorer == nil {
config.UserStorer = &UserStorer{}
}
if config.SessionStorer == nil {
config.SessionStorer = &SessionStorer{
SessionName: "_auth_session",
SessionManager: manager.SessionManager,
SigningMethod: jwt.SigningMethodHS256,
}
}
if config.Redirector == nil |
if config.LoginHandler == nil {
config.LoginHandler = DefaultLoginHandler
}
if config.RegisterHandler == nil {
config.RegisterHandler = DefaultRegisterHandler
}
if config.LogoutHandler == nil {
config.LogoutHandler = DefaultLogoutHandler
}
for _, viewPath := range config.ViewPaths {
config.Render.RegisterViewPath(viewPath)
}
config.Render.RegisterViewPath("github.com/qorpress/qorpress/core/auth/views")
auth := &Auth{Config: config}
auth.SessionStorerInterface = config.SessionStorer
return auth
}
| {
config.Redirector = &Redirector{redirect_back.New(&redirect_back.Config{
SessionManager: manager.SessionManager,
IgnoredPrefixes: []string{config.URLPrefix},
})}
} |
material-list.umd.js | * Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('@angular/material/core'), require('@angular/cdk/a11y'), require('@angular/cdk/coercion'), require('@angular/cdk/collections'), require('@angular/cdk/keycodes'), require('@angular/forms'), require('rxjs'), require('@angular/common'), require('@angular/material/divider')) :
typeof define === 'function' && define.amd ? define('@angular/material/list', ['exports', '@angular/core', '@angular/material/core', '@angular/cdk/a11y', '@angular/cdk/coercion', '@angular/cdk/collections', '@angular/cdk/keycodes', '@angular/forms', 'rxjs', '@angular/common', '@angular/material/divider'], factory) :
(factory((global.ng = global.ng || {}, global.ng.material = global.ng.material || {}, global.ng.material.list = {}),global.ng.core,global.ng.material.core,global.ng.cdk.a11y,global.ng.cdk.coercion,global.ng.cdk.collections,global.ng.cdk.keycodes,global.ng.forms,global.rxjs,global.ng.common,global.ng.material.divider));
}(this, (function (exports,core,core$1,a11y,coercion,collections,keycodes,forms,rxjs,common,divider) { 'use strict';
/*! *****************************************************************************
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 Reflect, Promise */
var extendStatics = function(d, b) {
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]; };
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* \@docs-private
*/
var /**
* \@docs-private
*/
MatListBase = /** @class */ (function () {
function MatListBase() {
}
return MatListBase;
}());
var /** @type {?} */ _MatListMixinBase = core$1.mixinDisableRipple(MatListBase);
/**
* \@docs-private
*/
var /**
* \@docs-private
*/
MatListItemBase = /** @class */ (function () {
function MatListItemBase() {
}
return MatListItemBase;
}());
var /** @type {?} */ _MatListItemMixinBase = core$1.mixinDisableRipple(MatListItemBase);
var MatNavList = /** @class */ (function (_super) {
__extends(MatNavList, _super);
function MatNavList() {
return _super !== null && _super.apply(this, arguments) || this;
}
MatNavList.decorators = [
{ type: core.Component, args: [{selector: 'mat-nav-list',
exportAs: 'matNavList',
host: {
'role': 'navigation',
'class': 'mat-nav-list'
},
template: "<ng-content></ng-content>",
styles: [".mat-divider{display:block;margin:0;border-top-width:1px;border-top-style:solid}.mat-divider.mat-divider-vertical{border-top:0;border-right-width:1px;border-right-style:solid}.mat-divider.mat-divider-inset{margin-left:80px}[dir=rtl] .mat-divider.mat-divider-inset{margin-left:auto;margin-right:80px}.mat-subheader{display:flex;box-sizing:border-box;padding:16px;align-items:center}.mat-list .mat-subheader,.mat-nav-list .mat-subheader,.mat-selection-list .mat-subheader{margin:0}.mat-list,.mat-nav-list,.mat-selection-list{padding-top:8px;display:block;-webkit-tap-highlight-color:transparent}.mat-list .mat-subheader,.mat-nav-list .mat-subheader,.mat-selection-list .mat-subheader{height:48px;line-height:16px}.mat-list .mat-subheader:first-child,.mat-nav-list .mat-subheader:first-child,.mat-selection-list .mat-subheader:first-child{margin-top:-8px}.mat-list .mat-list-item,.mat-list .mat-list-option,.mat-nav-list .mat-list-item,.mat-nav-list .mat-list-option,.mat-selection-list .mat-list-item,.mat-selection-list .mat-list-option{display:block;height:48px;-webkit-tap-highlight-color:transparent}.mat-list .mat-list-item .mat-list-item-content,.mat-list .mat-list-option .mat-list-item-content,.mat-nav-list .mat-list-item .mat-list-item-content,.mat-nav-list .mat-list-option .mat-list-item-content,.mat-selection-list .mat-list-item .mat-list-item-content,.mat-selection-list .mat-list-option .mat-list-item-content{display:flex;flex-direction:row;align-items:center;box-sizing:border-box;padding:0 16px;position:relative;height:inherit}.mat-list .mat-list-item .mat-list-item-content-reverse,.mat-list .mat-list-option .mat-list-item-content-reverse,.mat-nav-list .mat-list-item .mat-list-item-content-reverse,.mat-nav-list .mat-list-option .mat-list-item-content-reverse,.mat-selection-list .mat-list-item .mat-list-item-content-reverse,.mat-selection-list .mat-list-option .mat-list-item-content-reverse{display:flex;align-items:center;padding:0 16px;flex-direction:row-reverse;justify-content:space-around}.mat-list .mat-list-item .mat-list-item-ripple,.mat-list .mat-list-option .mat-list-item-ripple,.mat-nav-list .mat-list-item .mat-list-item-ripple,.mat-nav-list .mat-list-option .mat-list-item-ripple,.mat-selection-list .mat-list-item .mat-list-item-ripple,.mat-selection-list .mat-list-option .mat-list-item-ripple{top:0;left:0;right:0;bottom:0;position:absolute;pointer-events:none}.mat-list .mat-list-item.mat-list-item-with-avatar,.mat-list .mat-list-option.mat-list-item-with-avatar,.mat-nav-list .mat-list-item.mat-list-item-with-avatar,.mat-nav-list .mat-list-option.mat-list-item-with-avatar,.mat-selection-list .mat-list-item.mat-list-item-with-avatar,.mat-selection-list .mat-list-option.mat-list-item-with-avatar{height:56px}.mat-list .mat-list-item.mat-2-line,.mat-list .mat-list-option.mat-2-line,.mat-nav-list .mat-list-item.mat-2-line,.mat-nav-list .mat-list-option.mat-2-line,.mat-selection-list .mat-list-item.mat-2-line,.mat-selection-list .mat-list-option.mat-2-line{height:72px}.mat-list .mat-list-item.mat-3-line,.mat-list .mat-list-option.mat-3-line,.mat-nav-list .mat-list-item.mat-3-line,.mat-nav-list .mat-list-option.mat-3-line,.mat-selection-list .mat-list-item.mat-3-line,.mat-selection-list .mat-list-option.mat-3-line{height:88px}.mat-list .mat-list-item.mat-multi-line,.mat-list .mat-list-option.mat-multi-line,.mat-nav-list .mat-list-item.mat-multi-line,.mat-nav-list .mat-list-option.mat-multi-line,.mat-selection-list .mat-list-item.mat-multi-line,.mat-selection-list .mat-list-option.mat-multi-line{height:auto}.mat-list .mat-list-item.mat-multi-line .mat-list-item-content,.mat-list .mat-list-option.mat-multi-line .mat-list-item-content,.mat-nav-list .mat-list-item.mat-multi-line .mat-list-item-content,.mat-nav-list .mat-list-option.mat-multi-line .mat-list-item-content,.mat-selection-list .mat-list-item.mat-multi-line .mat-list-item-content,.mat-selection-list .mat-list-option.mat-multi-line .mat-list-item-content{padding-top:16px;padding-bottom:16px}.mat-list .mat-list-item .mat-list-text,.mat-list .mat-list-option .mat-list-text,.mat-nav-list .mat-list-item .mat-list-text,.mat-nav-list .mat-list-option .mat-list-text,.mat-selection-list .mat-list-item .mat-list-text,.mat-selection-list .mat-list-option .mat-list-text{display:flex;flex-direction:column;width:100%;box-sizing:border-box;overflow:hidden;padding:0}.mat-list .mat-list-item .mat-list-text>*,.mat-list .mat-list-option .mat-list-text>*,.mat-nav-list .mat-list-item .mat-list-text>*,.mat-nav-list .mat-list-option .mat-list-text>*,.mat-selection-list .mat-list-item .mat-list-text>*,.mat-selection-list .mat-list-option .mat-list-text>*{margin:0;padding:0;font-weight:400;font-size:inherit}.mat-list .mat-list-item .mat-list-text:empty,.mat-list .mat-list-option .mat-list-text:empty,.mat-nav-list .mat-list-item .mat-list-text:empty,.mat-nav-list .mat-list-option .mat-list-text:empty,.mat-selection-list .mat-list-item .mat-list-text:empty,.mat-selection-list .mat-list-option .mat-list-text:empty{display:none}.mat-list .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-list .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,.mat-list .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-list .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text,.mat-nav-list .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-nav-list .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,.mat-nav-list .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-nav-list .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text,.mat-selection-list .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-selection-list .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,.mat-selection-list .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-selection-list .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text{padding-right:0;padding-left:16px}[dir=rtl] .mat-list .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-nav-list .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-nav-list .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-nav-list .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-nav-list .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-selection-list .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-selection-list .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-selection-list .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-selection-list .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text{padding-right:16px;padding-left:0}.mat-list .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-list .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-list .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-nav-list .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-nav-list .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-nav-list .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-nav-list .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-selection-list .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-selection-list .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-selection-list .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-selection-list .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-left:0;padding-right:16px}[dir=rtl] .mat-list .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-nav-list .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-nav-list .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-nav-list .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-nav-list .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-selection-list .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-selection-list .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-selection-list .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-selection-list .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-right:0;padding-left:16px}.mat-list .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-list .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-list .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-nav-list .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-nav-list .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-nav-list .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-nav-list .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-selection-list .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-selection-list .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-selection-list .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-selection-list .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-right:16px;padding-left:16px}.mat-list .mat-list-item .mat-list-avatar,.mat-list .mat-list-option .mat-list-avatar,.mat-nav-list .mat-list-item .mat-list-avatar,.mat-nav-list .mat-list-option .mat-list-avatar,.mat-selection-list .mat-list-item .mat-list-avatar,.mat-selection-list .mat-list-option .mat-list-avatar{flex-shrink:0;width:40px;height:40px;border-radius:50%}.mat-list .mat-list-item .mat-list-avatar~.mat-divider-inset,.mat-list .mat-list-option .mat-list-avatar~.mat-divider-inset,.mat-nav-list .mat-list-item .mat-list-avatar~.mat-divider-inset,.mat-nav-list .mat-list-option .mat-list-avatar~.mat-divider-inset,.mat-selection-list .mat-list-item .mat-list-avatar~.mat-divider-inset,.mat-selection-list .mat-list-option .mat-list-avatar~.mat-divider-inset{margin-left:72px;width:calc(100% - 72px)}[dir=rtl] .mat-list .mat-list-item .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-list .mat-list-option .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-nav-list .mat-list-item .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-nav-list .mat-list-option .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-selection-list .mat-list-item .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-selection-list .mat-list-option .mat-list-avatar~.mat-divider-inset{margin-left:auto;margin-right:72px}.mat-list .mat-list-item .mat-list-icon,.mat-list .mat-list-option .mat-list-icon,.mat-nav-list .mat-list-item .mat-list-icon,.mat-nav-list .mat-list-option .mat-list-icon,.mat-selection-list .mat-list-item .mat-list-icon,.mat-selection-list .mat-list-option .mat-list-icon{flex-shrink:0;width:24px;height:24px;font-size:24px;box-sizing:content-box;border-radius:50%;padding:4px}.mat-list .mat-list-item .mat-list-icon~.mat-divider-inset,.mat-list .mat-list-option .mat-list-icon~.mat-divider-inset,.mat-nav-list .mat-list-item .mat-list-icon~.mat-divider-inset,.mat-nav-list .mat-list-option .mat-list-icon~.mat-divider-inset,.mat-selection-list .mat-list-item .mat-list-icon~.mat-divider-inset,.mat-selection-list .mat-list-option .mat-list-icon~.mat-divider-inset{margin-left:64px;width:calc(100% - 64px)}[dir=rtl] .mat-list .mat-list-item .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-list .mat-list-option .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-nav-list .mat-list-item .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-nav-list .mat-list-option .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-selection-list .mat-list-item .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-selection-list .mat-list-option .mat-list-icon~.mat-divider-inset{margin-left:auto;margin-right:64px}.mat-list .mat-list-item .mat-divider,.mat-list .mat-list-option .mat-divider,.mat-nav-list .mat-list-item .mat-divider,.mat-nav-list .mat-list-option .mat-divider,.mat-selection-list .mat-list-item .mat-divider,.mat-selection-list .mat-list-option .mat-divider{position:absolute;bottom:0;left:0;width:100%;margin:0}[dir=rtl] .mat-list .mat-list-item .mat-divider,[dir=rtl] .mat-list .mat-list-option .mat-divider,[dir=rtl] .mat-nav-list .mat-list-item .mat-divider,[dir=rtl] .mat-nav-list .mat-list-option .mat-divider,[dir=rtl] .mat-selection-list .mat-list-item .mat-divider,[dir=rtl] .mat-selection-list .mat-list-option .mat-divider{margin-left:auto;margin-right:0}.mat-list .mat-list-item .mat-divider.mat-divider-inset,.mat-list .mat-list-option .mat-divider.mat-divider-inset,.mat-nav-list .mat-list-item .mat-divider.mat-divider-inset,.mat-nav-list .mat-list-option .mat-divider.mat-divider-inset,.mat-selection-list .mat-list-item .mat-divider.mat-divider-inset,.mat-selection-list .mat-list-option .mat-divider.mat-divider-inset{position:absolute}.mat-list[dense],.mat-nav-list[dense],.mat-selection-list[dense]{padding-top:4px;display:block}.mat-list[dense] .mat-subheader,.mat-nav-list[dense] .mat-subheader,.mat-selection-list[dense] .mat-subheader{height:40px;line-height:8px}.mat-list[dense] .mat-subheader:first-child,.mat-nav-list[dense] .mat-subheader:first-child,.mat-selection-list[dense] .mat-subheader:first-child{margin-top:-4px}.mat-list[dense] .mat-list-item,.mat-list[dense] .mat-list-option,.mat-nav-list[dense] .mat-list-item,.mat-nav-list[dense] .mat-list-option,.mat-selection-list[dense] .mat-list-item,.mat-selection-list[dense] .mat-list-option{display:block;height:40px;-webkit-tap-highlight-color:transparent}.mat-list[dense] .mat-list-item .mat-list-item-content,.mat-list[dense] .mat-list-option .mat-list-item-content,.mat-nav-list[dense] .mat-list-item .mat-list-item-content,.mat-nav-list[dense] .mat-list-option .mat-list-item-content,.mat-selection-list[dense] .mat-list-item .mat-list-item-content,.mat-selection-list[dense] .mat-list-option .mat-list-item-content{display:flex;flex-direction:row;align-items:center;box-sizing:border-box;padding:0 16px;position:relative;height:inherit}.mat-list[dense] .mat-list-item .mat-list-item-content-reverse,.mat-list[dense] .mat-list-option .mat-list-item-content-reverse,.mat-nav-list[dense] .mat-list-item .mat-list-item-content-reverse,.mat-nav-list[dense] .mat-list-option .mat-list-item-content-reverse,.mat-selection-list[dense] .mat-list-item .mat-list-item-content-reverse,.mat-selection-list[dense] .mat-list-option .mat-list-item-content-reverse{display:flex;align-items:center;padding:0 16px;flex-direction:row-reverse;justify-content:space-around}.mat-list[dense] .mat-list-item .mat-list-item-ripple,.mat-list[dense] .mat-list-option .mat-list-item-ripple,.mat-nav-list[dense] .mat-list-item .mat-list-item-ripple,.mat-nav-list[dense] .mat-list-option .mat-list-item-ripple,.mat-selection-list[dense] .mat-list-item .mat-list-item-ripple,.mat-selection-list[dense] .mat-list-option .mat-list-item-ripple{top:0;left:0;right:0;bottom:0;position:absolute;pointer-events:none}.mat-list[dense] .mat-list-item.mat-list-item-with-avatar,.mat-list[dense] .mat-list-option.mat-list-item-with-avatar,.mat-nav-list[dense] .mat-list-item.mat-list-item-with-avatar,.mat-nav-list[dense] .mat-list-option.mat-list-item-with-avatar,.mat-selection-list[dense] .mat-list-item.mat-list-item-with-avatar,.mat-selection-list[dense] .mat-list-option.mat-list-item-with-avatar{height:48px}.mat-list[dense] .mat-list-item.mat-2-line,.mat-list[dense] .mat-list-option.mat-2-line,.mat-nav-list[dense] .mat-list-item.mat-2-line,.mat-nav-list[dense] .mat-list-option.mat-2-line,.mat-selection-list[dense] .mat-list-item.mat-2-line,.mat-selection-list[dense] .mat-list-option.mat-2-line{height:60px}.mat-list[dense] .mat-list-item.mat-3-line,.mat-list[dense] .mat-list-option.mat-3-line,.mat-nav-list[dense] .mat-list-item.mat-3-line,.mat-nav-list[dense] .mat-list-option.mat-3-line,.mat-selection-list[dense] .mat-list-item.mat-3-line,.mat-selection-list[dense] .mat-list-option.mat-3-line{height:76px}.mat-list[dense] .mat-list-item.mat-multi-line,.mat-list[dense] .mat-list-option.mat-multi-line,.mat-nav-list[dense] .mat-list-item.mat-multi-line,.mat-nav-list[dense] .mat-list-option.mat-multi-line,.mat-selection-list[dense] .mat-list-item.mat-multi-line,.mat-selection-list[dense] .mat-list-option.mat-multi-line{height:auto}.mat-list[dense] .mat-list-item.mat-multi-line .mat-list-item-content,.mat-list[dense] .mat-list-option.mat-multi-line .mat-list-item-content,.mat-nav-list[dense] .mat-list-item.mat-multi-line .mat-list-item-content,.mat-nav-list[dense] .mat-list-option.mat-multi-line .mat-list-item-content,.mat-selection-list[dense] .mat-list-item.mat-multi-line .mat-list-item-content,.mat-selection-list[dense] .mat-list-option.mat-multi-line .mat-list-item-content{padding-top:16px;padding-bottom:16px}.mat-list[dense] .mat-list-item .mat-list-text,.mat-list[dense] .mat-list-option .mat-list-text,.mat-nav-list[dense] .mat-list-item .mat-list-text,.mat-nav-list[dense] .mat-list-option .mat-list-text,.mat-selection-list[dense] .mat-list-item .mat-list-text,.mat-selection-list[dense] .mat-list-option .mat-list-text{display:flex;flex-direction:column;width:100%;box-sizing:border-box;overflow:hidden;padding:0}.mat-list[dense] .mat-list-item .mat-list-text>*,.mat-list[dense] .mat-list-option .mat-list-text>*,.mat-nav-list[dense] .mat-list-item .mat-list-text>*,.mat-nav-list[dense] .mat-list-option .mat-list-text>*,.mat-selection-list[dense] .mat-list-item .mat-list-text>*,.mat-selection-list[dense] .mat-list-option .mat-list-text>*{margin:0;padding:0;font-weight:400;font-size:inherit}.mat-list[dense] .mat-list-item .mat-list-text:empty,.mat-list[dense] .mat-list-option .mat-list-text:empty,.mat-nav-list[dense] .mat-list-item .mat-list-text:empty,.mat-nav-list[dense] .mat-list-option .mat-list-text:empty,.mat-selection-list[dense] .mat-list-item .mat-list-text:empty,.mat-selection-list[dense] .mat-list-option .mat-list-text:empty{display:none}.mat-list[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-list[dense] .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,.mat-list[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-list[dense] .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text,.mat-nav-list[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-nav-list[dense] .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,.mat-nav-list[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-nav-list[dense] .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text,.mat-selection-list[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-selection-list[dense] .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,.mat-selection-list[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-selection-list[dense] .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text{padding-right:0;padding-left:16px}[dir=rtl] .mat-list[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list[dense] .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list[dense] .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-nav-list[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-nav-list[dense] .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-nav-list[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-nav-list[dense] .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-selection-list[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-selection-list[dense] .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-selection-list[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-selection-list[dense] .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text{padding-right:16px;padding-left:0}.mat-list[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-list[dense] .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-list[dense] .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-nav-list[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-nav-list[dense] .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-nav-list[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-nav-list[dense] .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-selection-list[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-selection-list[dense] .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-selection-list[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-selection-list[dense] .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-left:0;padding-right:16px}[dir=rtl] .mat-list[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list[dense] .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list[dense] .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-nav-list[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-nav-list[dense] .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-nav-list[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-nav-list[dense] .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-selection-list[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-selection-list[dense] .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-selection-list[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-selection-list[dense] .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-right:0;padding-left:16px}.mat-list[dense] .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-list[dense] .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list[dense] .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-list[dense] .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-nav-list[dense] .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-nav-list[dense] .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-nav-list[dense] .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-nav-list[dense] .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-selection-list[dense] .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-selection-list[dense] .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-selection-list[dense] .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-selection-list[dense] .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-right:16px;padding-left:16px}.mat-list[dense] .mat-list-item .mat-list-avatar,.mat-list[dense] .mat-list-option .mat-list-avatar,.mat-nav-list[dense] .mat-list-item .mat-list-avatar,.mat-nav-list[dense] .mat-list-option .mat-list-avatar,.mat-selection-list[dense] .mat-list-item .mat-list-avatar,.mat-selection-list[dense] .mat-list-option .mat-list-avatar{flex-shrink:0;width:36px;height:36px;border-radius:50%}.mat-list[dense] .mat-list-item .mat-list-avatar~.mat-divider-inset,.mat-list[dense] .mat-list-option .mat-list-avatar~.mat-divider-inset,.mat-nav-list[dense] .mat-list-item .mat-list-avatar~.mat-divider-inset,.mat-nav-list[dense] .mat-list-option .mat-list-avatar~.mat-divider-inset,.mat-selection-list[dense] .mat-list-item .mat-list-avatar~.mat-divider-inset,.mat-selection-list[dense] .mat-list-option .mat-list-avatar~.mat-divider-inset{margin-left:68px;width:calc(100% - 68px)}[dir=rtl] .mat-list[dense] .mat-list-item .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-list[dense] .mat-list-option .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-nav-list[dense] .mat-list-item .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-nav-list[dense] .mat-list-option .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-selection-list[dense] .mat-list-item .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-selection-list[dense] .mat-list-option .mat-list-avatar~.mat-divider-inset{margin-left:auto;margin-right:68px}.mat-list[dense] .mat-list-item .mat-list-icon,.mat-list[dense] .mat-list-option .mat-list-icon,.mat-nav-list[dense] .mat-list-item .mat-list-icon,.mat-nav-list[dense] .mat-list-option .mat-list-icon,.mat-selection-list[dense] .mat-list-item .mat-list-icon,.mat-selection-list[dense] .mat-list-option .mat-list-icon{flex-shrink:0;width:20px;height:20px;font-size:20px;box-sizing:content-box;border-radius:50%;padding:4px}.mat-list[dense] .mat-list-item .mat-list-icon~.mat-divider-inset,.mat-list[dense] .mat-list-option .mat-list-icon~.mat-divider-inset,.mat-nav-list[dense] .mat-list-item .mat-list-icon~.mat-divider-inset,.mat-nav-list[dense] .mat-list-option .mat-list-icon~.mat-divider-inset,.mat-selection-list[dense] .mat-list-item .mat-list-icon~.mat-divider-inset,.mat-selection-list[dense] .mat-list-option .mat-list-icon~.mat-divider-inset{margin-left:60px;width:calc(100% - 60px)}[dir=rtl] .mat-list[dense] .mat-list-item .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-list[dense] .mat-list-option .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-nav-list[dense] .mat-list-item .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-nav-list[dense] .mat-list-option .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-selection-list[dense] .mat-list-item .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-selection-list[dense] .mat-list-option .mat-list-icon~.mat-divider-inset{margin-left:auto;margin-right:60px}.mat-list[dense] .mat-list-item .mat-divider,.mat-list[dense] .mat-list-option .mat-divider,.mat-nav-list[dense] .mat-list-item .mat-divider,.mat-nav-list[dense] .mat-list-option .mat-divider,.mat-selection-list[dense] .mat-list-item .mat-divider,.mat-selection-list[dense] .mat-list-option .mat-divider{position:absolute;bottom:0;left:0;width:100%;margin:0}[dir=rtl] .mat-list[dense] .mat-list-item .mat-divider,[dir=rtl] .mat-list[dense] .mat-list-option .mat-divider,[dir=rtl] .mat-nav-list[dense] .mat-list-item .mat-divider,[dir=rtl] .mat-nav-list[dense] .mat-list-option .mat-divider,[dir=rtl] .mat-selection-list[dense] .mat-list-item .mat-divider,[dir=rtl] .mat-selection-list[dense] .mat-list-option .mat-divider{margin-left:auto;margin-right:0}.mat-list[dense] .mat-list-item .mat-divider.mat-divider-inset,.mat-list[dense] .mat-list-option .mat-divider.mat-divider-inset,.mat-nav-list[dense] .mat-list-item .mat-divider.mat-divider-inset,.mat-nav-list[dense] .mat-list-option .mat-divider.mat-divider-inset,.mat-selection-list[dense] .mat-list-item .mat-divider.mat-divider-inset,.mat-selection-list[dense] .mat-list-option .mat-divider.mat-divider-inset{position:absolute}.mat-nav-list a{text-decoration:none;color:inherit}.mat-nav-list .mat-list-item{cursor:pointer;outline:0}.mat-list-option:not(.mat-list-item-disabled){cursor:pointer;outline:0}@media (hover:none){.mat-list-option:hover,.mat-nav-list .mat-list-item:hover{background:0 0}}"],
inputs: ['disableRipple'],
encapsulation: core.ViewEncapsulation.None,
changeDetection: core.ChangeDetectionStrategy.OnPush,
},] },
];
return MatNavList;
}(_MatListMixinBase));
var MatList = /** @class */ (function (_super) {
__extends(MatList, _super);
function MatList() {
return _super !== null && _super.apply(this, arguments) || this;
}
MatList.decorators = [
{ type: core.Component, args: [{selector: 'mat-list',
exportAs: 'matList',
template: "<ng-content></ng-content>",
host: { 'class': 'mat-list' },
styles: [".mat-divider{display:block;margin:0;border-top-width:1px;border-top-style:solid}.mat-divider.mat-divider-vertical{border-top:0;border-right-width:1px;border-right-style:solid}.mat-divider.mat-divider-inset{margin-left:80px}[dir=rtl] .mat-divider.mat-divider-inset{margin-left:auto;margin-right:80px}.mat-subheader{display:flex;box-sizing:border-box;padding:16px;align-items:center}.mat-list .mat-subheader,.mat-nav-list .mat-subheader,.mat-selection-list .mat-subheader{margin:0}.mat-list,.mat-nav-list,.mat-selection-list{padding-top:8px;display:block;-webkit-tap-highlight-color:transparent}.mat-list .mat-subheader,.mat-nav-list .mat-subheader,.mat-selection-list .mat-subheader{height:48px;line-height:16px}.mat-list .mat-subheader:first-child,.mat-nav-list .mat-subheader:first-child,.mat-selection-list .mat-subheader:first-child{margin-top:-8px}.mat-list .mat-list-item,.mat-list .mat-list-option,.mat-nav-list .mat-list-item,.mat-nav-list .mat-list-option,.mat-selection-list .mat-list-item,.mat-selection-list .mat-list-option{display:block;height:48px;-webkit-tap-highlight-color:transparent}.mat-list .mat-list-item .mat-list-item-content,.mat-list .mat-list-option .mat-list-item-content,.mat-nav-list .mat-list-item .mat-list-item-content,.mat-nav-list .mat-list-option .mat-list-item-content,.mat-selection-list .mat-list-item .mat-list-item-content,.mat-selection-list .mat-list-option .mat-list-item-content{display:flex;flex-direction:row;align-items:center;box-sizing:border-box;padding:0 16px;position:relative;height:inherit}.mat-list .mat-list-item .mat-list-item-content-reverse,.mat-list .mat-list-option .mat-list-item-content-reverse,.mat-nav-list .mat-list-item .mat-list-item-content-reverse,.mat-nav-list .mat-list-option .mat-list-item-content-reverse,.mat-selection-list .mat-list-item .mat-list-item-content-reverse,.mat-selection-list .mat-list-option .mat-list-item-content-reverse{display:flex;align-items:center;padding:0 16px;flex-direction:row-reverse;justify-content:space-around}.mat-list .mat-list-item .mat-list-item-ripple,.mat-list .mat-list-option .mat-list-item-ripple,.mat-nav-list .mat-list-item .mat-list-item-ripple,.mat-nav-list .mat-list-option .mat-list-item-ripple,.mat-selection-list .mat-list-item .mat-list-item-ripple,.mat-selection-list .mat-list-option .mat-list-item-ripple{top:0;left:0;right:0;bottom:0;position:absolute;pointer-events:none}.mat-list .mat-list-item.mat-list-item-with-avatar,.mat-list .mat-list-option.mat-list-item-with-avatar,.mat-nav-list .mat-list-item.mat-list-item-with-avatar,.mat-nav-list .mat-list-option.mat-list-item-with-avatar,.mat-selection-list .mat-list-item.mat-list-item-with-avatar,.mat-selection-list .mat-list-option.mat-list-item-with-avatar{height:56px}.mat-list .mat-list-item.mat-2-line,.mat-list .mat-list-option.mat-2-line,.mat-nav-list .mat-list-item.mat-2-line,.mat-nav-list .mat-list-option.mat-2-line,.mat-selection-list .mat-list-item.mat-2-line,.mat-selection-list .mat-list-option.mat-2-line{height:72px}.mat-list .mat-list-item.mat-3-line,.mat-list .mat-list-option.mat-3-line,.mat-nav-list .mat-list-item.mat-3-line,.mat-nav-list .mat-list-option.mat-3-line,.mat-selection-list .mat-list-item.mat-3-line,.mat-selection-list .mat-list-option.mat-3-line{height:88px}.mat-list .mat-list-item.mat-multi-line,.mat-list .mat-list-option.mat-multi-line,.mat-nav-list .mat-list-item.mat-multi-line,.mat-nav-list .mat-list-option.mat-multi-line,.mat-selection-list .mat-list-item.mat-multi-line,.mat-selection-list .mat-list-option.mat-multi-line{height:auto}.mat-list .mat-list-item.mat-multi-line .mat-list-item-content,.mat-list .mat-list-option.mat-multi-line .mat-list-item-content,.mat-nav-list .mat-list-item.mat-multi-line .mat-list-item-content,.mat-nav-list .mat-list-option.mat-multi-line .mat-list-item-content,.mat-selection-list .mat-list-item.mat-multi-line .mat-list-item-content,.mat-selection-list .mat-list-option.mat-multi-line .mat-list-item-content{padding-top:16px;padding-bottom:16px}.mat-list .mat-list-item .mat-list-text,.mat-list .mat-list-option .mat-list-text,.mat-nav-list .mat-list-item .mat-list-text,.mat-nav-list .mat-list-option .mat-list-text,.mat-selection-list .mat-list-item .mat-list-text,.mat-selection-list .mat-list-option .mat-list-text{display:flex;flex-direction:column;width:100%;box-sizing:border-box;overflow:hidden;padding:0}.mat-list .mat-list-item .mat-list-text>*,.mat-list .mat-list-option .mat-list-text>*,.mat-nav-list .mat-list-item .mat-list-text>*,.mat-nav-list .mat-list-option .mat-list-text>*,.mat-selection-list .mat-list-item .mat-list-text>*,.mat-selection-list .mat-list-option .mat-list-text>*{margin:0;padding:0;font-weight:400;font-size:inherit}.mat-list .mat-list-item .mat-list-text:empty,.mat-list .mat-list-option .mat-list-text:empty,.mat-nav-list .mat-list-item .mat-list-text:empty,.mat-nav-list .mat-list-option .mat-list-text:empty,.mat-selection-list .mat-list-item .mat-list-text:empty,.mat-selection-list .mat-list-option .mat-list-text:empty{display:none}.mat-list .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-list .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,.mat-list .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-list .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text,.mat-nav-list .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-nav-list .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,.mat-nav-list .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-nav-list .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text,.mat-selection-list .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-selection-list .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,.mat-selection-list .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-selection-list .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text{padding-right:0;padding-left:16px}[dir=rtl] .mat-list .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-nav-list .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-nav-list .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-nav-list .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-nav-list .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-selection-list .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-selection-list .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-selection-list .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-selection-list .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text{padding-right:16px;padding-left:0}.mat-list .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-list .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-list .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-nav-list .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-nav-list .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-nav-list .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-nav-list .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-selection-list .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-selection-list .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-selection-list .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-selection-list .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-left:0;padding-right:16px}[dir=rtl] .mat-list .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-nav-list .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-nav-list .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-nav-list .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-nav-list .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-selection-list .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-selection-list .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-selection-list .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-selection-list .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-right:0;padding-left:16px}.mat-list .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-list .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-list .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-nav-list .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-nav-list .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-nav-list .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-nav-list .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-selection-list .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-selection-list .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-selection-list .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-selection-list .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-right:16px;padding-left:16px}.mat-list .mat-list-item .mat-list-avatar,.mat-list .mat-list-option .mat-list-avatar,.mat-nav-list .mat-list-item .mat-list-avatar,.mat-nav-list .mat-list-option .mat-list-avatar,.mat-selection-list .mat-list-item .mat-list-avatar,.mat-selection-list .mat-list-option .mat-list-avatar{flex-shrink:0;width:40px;height:40px;border-radius:50%}.mat-list .mat-list-item .mat-list-avatar~.mat-divider-inset,.mat-list .mat-list-option .mat-list-avatar~.mat-divider-inset,.mat-nav-list .mat-list-item .mat-list-avatar~.mat-divider-inset,.mat-nav-list .mat-list-option .mat-list-avatar~.mat-divider-inset,.mat-selection-list .mat-list-item .mat-list-avatar~.mat-divider-inset,.mat-selection-list .mat-list-option .mat-list-avatar~.mat-divider-inset{margin-left:72px;width:calc(100% - 72px)}[dir=rtl] .mat-list .mat-list-item .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-list .mat-list-option .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-nav-list .mat-list-item .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-nav-list .mat-list-option .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-selection-list .mat-list-item .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-selection-list .mat-list-option .mat-list-avatar~.mat-divider-inset{margin-left:auto;margin-right:72px}.mat-list .mat-list-item .mat-list-icon,.mat-list .mat-list-option .mat-list-icon,.mat-nav-list .mat-list-item .mat-list-icon,.mat-nav-list .mat-list-option .mat-list-icon,.mat-selection-list .mat-list-item .mat-list-icon,.mat-selection-list .mat-list-option .mat-list-icon{flex-shrink:0;width:24px;height:24px;font-size:24px;box-sizing:content-box;border-radius:50%;padding:4px}.mat-list .mat-list-item .mat-list-icon~.mat-divider-inset,.mat-list .mat-list-option .mat-list-icon~.mat-divider-inset,.mat-nav-list .mat-list-item .mat-list-icon~.mat-divider-inset,.mat-nav-list .mat-list-option .mat-list-icon~.mat-divider-inset,.mat-selection-list .mat-list-item .mat-list-icon~.mat-divider-inset,.mat-selection-list .mat-list-option .mat-list-icon~.mat-divider-inset{margin-left:64px;width:calc(100% - 64px)}[dir=rtl] .mat-list .mat-list-item .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-list .mat-list-option .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-nav-list .mat-list-item .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-nav-list .mat-list-option .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-selection-list .mat-list-item .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-selection-list .mat-list-option .mat-list-icon~.mat-divider-inset{margin-left:auto;margin-right:64px}.mat-list .mat-list-item .mat-divider,.mat-list .mat-list-option .mat-divider,.mat-nav-list .mat-list-item .mat-divider,.mat-nav-list .mat-list-option .mat-divider,.mat-selection-list .mat-list-item .mat-divider,.mat-selection-list .mat-list-option .mat-divider{position:absolute;bottom:0;left:0;width:100%;margin:0}[dir=rtl] .mat-list .mat-list-item .mat-divider,[dir=rtl] .mat-list .mat-list-option .mat-divider,[dir=rtl] .mat-nav-list .mat-list-item .mat-divider,[dir=rtl] .mat-nav-list .mat-list-option .mat-divider,[dir=rtl] .mat-selection-list .mat-list-item .mat-divider,[dir=rtl] .mat-selection-list .mat-list-option .mat-divider{margin-left:auto;margin-right:0}.mat-list .mat-list-item .mat-divider.mat-divider-inset,.mat-list .mat-list-option .mat-divider.mat-divider-inset,.mat-nav-list .mat-list-item .mat-divider.mat-divider-inset,.mat-nav-list .mat-list-option .mat-divider.mat-divider-inset,.mat-selection-list .mat-list-item .mat-divider.mat-divider-inset,.mat-selection-list .mat-list-option .mat-divider.mat-divider-inset{position:absolute}.mat-list[dense],.mat-nav-list[dense],.mat-selection-list[dense]{padding-top:4px;display:block}.mat-list[dense] .mat-subheader,.mat-nav-list[dense] .mat-subheader,.mat-selection-list[dense] .mat-subheader{height:40px;line-height:8px}.mat-list[dense] .mat-subheader:first-child,.mat-nav-list[dense] .mat-subheader:first-child,.mat-selection-list[dense] .mat-subheader:first-child{margin-top:-4px}.mat-list[dense] .mat-list-item,.mat-list[dense] .mat-list-option,.mat-nav-list[dense] .mat-list-item,.mat-nav-list[dense] .mat-list-option,.mat-selection-list[dense] .mat-list-item,.mat-selection-list[dense] .mat-list-option{display:block;height:40px;-webkit-tap-highlight-color:transparent}.mat-list[dense] .mat-list-item .mat-list-item-content,.mat-list[dense] .mat-list-option .mat-list-item-content,.mat-nav-list[dense] .mat-list-item .mat-list-item-content,.mat-nav-list[dense] .mat-list-option .mat-list-item-content,.mat-selection-list[dense] .mat-list-item .mat-list-item-content,.mat-selection-list[dense] .mat-list-option .mat-list-item-content{display:flex;flex-direction:row;align-items:center;box-sizing:border-box;padding:0 16px;position:relative;height:inherit}.mat-list[dense] .mat-list-item .mat-list-item-content-reverse,.mat-list[dense] .mat-list-option .mat-list-item-content-reverse,.mat-nav-list[dense] .mat-list-item .mat-list-item-content-reverse,.mat-nav-list[dense] .mat-list-option .mat-list-item-content-reverse,.mat-selection-list[dense] .mat-list-item .mat-list-item-content-reverse,.mat-selection-list[dense] .mat-list-option .mat-list-item-content-reverse{display:flex;align-items:center;padding:0 16px;flex-direction:row-reverse;justify-content:space-around}.mat-list[dense] .mat-list-item .mat-list-item-ripple,.mat-list[dense] .mat-list-option .mat-list-item-ripple,.mat-nav-list[dense] .mat-list-item .mat-list-item-ripple,.mat-nav-list[dense] .mat-list-option .mat-list-item-ripple,.mat-selection-list[dense] .mat-list-item .mat-list-item-ripple,.mat-selection-list[dense] .mat-list-option .mat-list-item-ripple{top:0;left:0;right:0;bottom:0;position:absolute;pointer-events:none}.mat-list[dense] .mat-list-item.mat-list-item-with-avatar,.mat-list[dense] .mat-list-option.mat-list-item-with-avatar,.mat-nav-list[dense] .mat-list-item.mat-list-item-with-avatar,.mat-nav-list[dense] .mat-list-option.mat-list-item-with-avatar,.mat-selection-list[dense] .mat-list-item.mat-list-item-with-avatar,.mat-selection-list[dense] .mat-list-option.mat-list-item-with-avatar{height:48px}.mat-list[dense] .mat-list-item.mat-2-line,.mat-list[dense] .mat-list-option.mat-2-line,.mat-nav-list[dense] .mat-list-item.mat-2-line,.mat-nav-list[dense] .mat-list-option.mat-2-line,.mat-selection-list[dense] .mat-list-item.mat-2-line,.mat-selection-list[dense] .mat-list-option.mat-2-line{height:60px}.mat-list[dense] .mat-list-item.mat-3-line,.mat-list[dense] .mat-list-option.mat-3-line,.mat-nav-list[dense] .mat-list-item.mat-3-line,.mat-nav-list[dense] .mat-list-option.mat-3-line,.mat-selection-list[dense] .mat-list-item.mat-3-line,.mat-selection-list[dense] .mat-list-option.mat-3-line{height:76px}.mat-list[dense] .mat-list-item.mat-multi-line,.mat-list[dense] .mat-list-option.mat-multi-line,.mat-nav-list[dense] .mat-list-item.mat-multi-line,.mat-nav-list[dense] .mat-list-option.mat-multi-line,.mat-selection-list[dense] .mat-list-item.mat-multi-line,.mat-selection-list[dense] .mat-list-option.mat-multi-line{height:auto}.mat-list[dense] .mat-list-item.mat-multi-line .mat-list-item-content,.mat-list[dense] .mat-list-option.mat-multi-line .mat-list-item-content,.mat-nav-list[dense] .mat-list-item.mat-multi-line .mat-list-item-content,.mat-nav-list[dense] .mat-list-option.mat-multi-line .mat-list-item-content,.mat-selection-list[dense] .mat-list-item.mat-multi-line .mat-list-item-content,.mat-selection-list[dense] .mat-list-option.mat-multi-line .mat-list-item-content{padding-top:16px;padding-bottom:16px}.mat-list[dense] .mat-list-item .mat-list-text,.mat-list[dense] .mat-list-option .mat-list-text,.mat-nav-list[dense] .mat-list-item .mat-list-text,.mat-nav-list[dense] .mat-list-option .mat-list-text,.mat-selection-list[dense] .mat-list-item .mat-list-text,.mat-selection-list[dense] .mat-list-option .mat-list-text{display:flex;flex-direction:column;width:100%;box-sizing:border-box;overflow:hidden;padding:0}.mat-list[dense] .mat-list-item .mat-list-text>*,.mat-list[dense] .mat-list-option .mat-list-text>*,.mat-nav-list[dense] .mat-list-item .mat-list-text>*,.mat-nav-list[dense] .mat-list-option .mat-list-text>*,.mat-selection-list[dense] .mat-list-item .mat-list-text>*,.mat-selection-list[dense] .mat-list-option .mat-list-text>*{margin:0;padding:0;font-weight:400;font-size:inherit}.mat-list[dense] .mat-list-item .mat-list-text:empty,.mat-list[dense] .mat-list-option .mat-list-text:empty,.mat-nav-list[dense] .mat-list-item .mat-list-text:empty,.mat-nav-list[dense] .mat-list-option .mat-list-text:empty,.mat-selection-list[dense] .mat-list-item .mat-list-text:empty,.mat-selection-list[dense] .mat-list-option .mat-list-text:empty{display:none}.mat-list[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-list[dense] .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,.mat-list[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-list[dense] .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text,.mat-nav-list[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-nav-list[dense] .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,.mat-nav-list[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-nav-list[dense] .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text,.mat-selection-list[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-selection-list[dense] .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,.mat-selection-list[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-selection-list[dense] .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text{padding-right:0;padding-left:16px}[dir=rtl] .mat-list[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list[dense] .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list[dense] .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-nav-list[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-nav-list[dense] .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-nav-list[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-nav-list[dense] .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-selection-list[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-selection-list[dense] .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-selection-list[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-selection-list[dense] .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text{padding-right:16px;padding-left:0}.mat-list[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-list[dense] .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-list[dense] .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-nav-list[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-nav-list[dense] .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-nav-list[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-nav-list[dense] .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-selection-list[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-selection-list[dense] .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-selection-list[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-selection-list[dense] .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-left:0;padding-right:16px}[dir=rtl] .mat-list[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list[dense] .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list[dense] .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-nav-list[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-nav-list[dense] .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-nav-list[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-nav-list[dense] .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-selection-list[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-selection-list[dense] .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-selection-list[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-selection-list[dense] .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-right:0;padding-left:16px}.mat-list[dense] .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-list[dense] .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list[dense] .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-list[dense] .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-nav-list[dense] .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-nav-list[dense] .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-nav-list[dense] .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-nav-list[dense] .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-selection-list[dense] .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-selection-list[dense] .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-selection-list[dense] .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-selection-list[dense] .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-right:16px;padding-left:16px}.mat-list[dense] .mat-list-item .mat-list-avatar,.mat-list[dense] .mat-list-option .mat-list-avatar,.mat-nav-list[dense] .mat-list-item .mat-list-avatar,.mat-nav-list[dense] .mat-list-option .mat-list-avatar,.mat-selection-list[dense] .mat-list-item .mat-list-avatar,.mat-selection-list[dense] .mat-list-option .mat-list-avatar{flex-shrink:0;width:36px;height:36px;border-radius:50%}.mat-list[dense] .mat-list-item .mat-list-avatar~.mat-divider-inset,.mat-list[dense] .mat-list-option .mat-list-avatar~.mat-divider-inset,.mat-nav-list[dense] .mat-list-item .mat-list-avatar~.mat-divider-inset,.mat-nav-list[dense] .mat-list-option .mat-list-avatar~.mat-divider-inset,.mat-selection-list[dense] .mat-list-item .mat-list-avatar~.mat-divider-inset,.mat-selection-list[dense] .mat-list-option .mat-list-avatar~.mat-divider-inset{margin-left:68px;width:calc(100% - 68px)}[dir=rtl] .mat-list[dense] .mat-list-item .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-list[dense] .mat-list-option .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-nav-list[dense] .mat-list-item .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-nav-list[dense] .mat-list-option .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-selection-list[dense] .mat-list-item .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-selection-list[dense] .mat-list-option .mat-list-avatar~.mat-divider-inset{margin-left:auto;margin-right:68px}.mat-list[dense] .mat-list-item .mat-list-icon,.mat-list[dense] .mat-list-option .mat-list-icon,.mat-nav-list[dense] .mat-list-item .mat-list-icon,.mat-nav-list[dense] .mat-list-option .mat-list-icon,.mat-selection-list[dense] .mat-list-item .mat-list-icon,.mat-selection-list[dense] .mat-list-option .mat-list-icon{flex-shrink:0;width:20px;height:20px;font-size:20px;box-sizing:content-box;border-radius:50%;padding:4px}.mat-list[dense] .mat-list-item .mat-list-icon~.mat-divider-inset,.mat-list[dense] .mat-list-option .mat-list-icon~.mat-divider-inset,.mat-nav-list[dense] .mat-list-item .mat-list-icon~.mat-divider-inset,.mat-nav-list[dense] .mat-list-option .mat-list-icon~.mat-divider-inset,.mat-selection-list[dense] .mat-list-item .mat-list-icon~.mat-divider-inset,.mat-selection-list[dense] .mat-list-option .mat-list-icon~.mat-divider-inset{margin-left:60px;width:calc(100% - 60px)}[dir=rtl] .mat-list[dense] .mat-list-item .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-list[dense] .mat-list-option .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-nav-list[dense] .mat-list-item .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-nav-list[dense] .mat-list-option .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-selection-list[dense] .mat-list-item .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-selection-list[dense] .mat-list-option .mat-list-icon~.mat-divider-inset{margin-left:auto;margin-right:60px}.mat-list[dense] .mat-list-item .mat-divider,.mat-list[dense] .mat-list-option .mat-divider,.mat-nav-list[dense] .mat-list-item .mat-divider,.mat-nav-list[dense] .mat-list-option .mat-divider,.mat-selection-list[dense] .mat-list-item .mat-divider,.mat-selection-list[dense] .mat-list-option .mat-divider{position:absolute;bottom:0;left:0;width:100%;margin:0}[dir=rtl] .mat-list[dense] .mat-list-item .mat-divider,[dir=rtl] .mat-list[dense] .mat-list-option .mat-divider,[dir=rtl] .mat-nav-list[dense] .mat-list-item .mat-divider,[dir=rtl] .mat-nav-list[dense] .mat-list-option .mat-divider,[dir=rtl] .mat-selection-list[dense] .mat-list-item .mat-divider,[dir=rtl] .mat-selection-list[dense] .mat-list-option .mat-divider{margin-left:auto;margin-right:0}.mat-list[dense] .mat-list-item .mat-divider.mat-divider-inset,.mat-list[dense] .mat-list-option .mat-divider.mat-divider-inset,.mat-nav-list[dense] .mat-list-item .mat-divider.mat-divider-inset,.mat-nav-list[dense] .mat-list-option .mat-divider.mat-divider-inset,.mat-selection-list[dense] .mat-list-item .mat-divider.mat-divider-inset,.mat-selection-list[dense] .mat-list-option .mat-divider.mat-divider-inset{position:absolute}.mat-nav-list a{text-decoration:none;color:inherit}.mat-nav-list .mat-list-item{cursor:pointer;outline:0}.mat-list-option:not(.mat-list-item-disabled){cursor:pointer;outline:0}@media (hover:none){.mat-list-option:hover,.mat-nav-list .mat-list-item:hover{background:0 0}}"],
inputs: ['disableRipple'],
encapsulation: core.ViewEncapsulation.None,
changeDetection: core.ChangeDetectionStrategy.OnPush,
},] },
];
return MatList;
}(_MatListMixinBase));
/**
* Directive whose purpose is to add the mat- CSS styling to this selector.
* \@docs-private
*/
var MatListAvatarCssMatStyler = /** @class */ (function () {
function MatListAvatarCssMatStyler() {
}
MatListAvatarCssMatStyler.decorators = [
{ type: core.Directive, args: [{
selector: '[mat-list-avatar], [matListAvatar]',
host: { 'class': 'mat-list-avatar' }
},] },
];
return MatListAvatarCssMatStyler;
}());
/**
* Directive whose purpose is to add the mat- CSS styling to this selector.
* \@docs-private
*/
var MatListIconCssMatStyler = /** @class */ (function () {
function MatListIconCssMatStyler() {
}
MatListIconCssMatStyler.decorators = [
{ type: core.Directive, args: [{
selector: '[mat-list-icon], [matListIcon]',
host: { 'class': 'mat-list-icon' }
},] },
];
return MatListIconCssMatStyler;
}());
/**
* Directive whose purpose is to add the mat- CSS styling to this selector.
* \@docs-private
*/
var MatListSubheaderCssMatStyler = /** @class */ (function () {
function MatListSubheaderCssMatStyler() {
}
MatListSubheaderCssMatStyler.decorators = [
{ type: core.Directive, args: [{
selector: '[mat-subheader], [matSubheader]',
host: { 'class': 'mat-subheader' }
},] },
];
return MatListSubheaderCssMatStyler;
}());
/**
* An item within a Material Design list.
*/
var MatListItem = /** @class */ (function (_super) {
__extends(MatListItem, _super);
function MatListItem(_element, _navList) {
var _this = _super.call(this) || this;
_this._element = _element;
_this._navList = _navList;
_this._isNavList = false;
_this._isNavList = !!_navList;
return _this;
}
/**
* @return {?}
*/
MatListItem.prototype.ngAfterContentInit = /**
* @return {?}
*/
function () {
// TODO: consider turning the setter into a function, it doesn't do anything as a class.
// tslint:disable-next-line:no-unused-expression
new core$1.MatLineSetter(this._lines, this._element);
};
/** Whether this list item should show a ripple effect when clicked. */
/**
* Whether this list item should show a ripple effect when clicked.
* @return {?}
*/
MatListItem.prototype._isRippleDisabled = /**
* Whether this list item should show a ripple effect when clicked.
* @return {?}
*/
function () {
return !this._isNavList || this.disableRipple || this._navList.disableRipple;
};
/**
* @return {?}
*/
MatListItem.prototype._handleFocus = /**
* @return {?}
*/
function () {
this._element.nativeElement.classList.add('mat-list-item-focus');
};
/**
* @return {?}
*/
MatListItem.prototype._handleBlur = /**
* @return {?}
*/
function () {
this._element.nativeElement.classList.remove('mat-list-item-focus');
};
/** Retrieves the DOM element of the component host. */
/**
* Retrieves the DOM element of the component host.
* @return {?}
*/
MatListItem.prototype._getHostElement = /**
* Retrieves the DOM element of the component host.
* @return {?}
*/
function () {
return this._element.nativeElement;
};
MatListItem.decorators = [
{ type: core.Component, args: [{selector: 'mat-list-item, a[mat-list-item]',
exportAs: 'matListItem',
host: {
'class': 'mat-list-item',
// @breaking-change 7.0.0 Remove `mat-list-item-avatar` in favor of `mat-list-item-with-avatar`.
'[class.mat-list-item-avatar]': '_avatar || _icon',
'[class.mat-list-item-with-avatar]': '_avatar || _icon',
'(focus)': '_handleFocus()',
'(blur)': '_handleBlur()',
},
inputs: ['disableRipple'],
template: "<div class=\"mat-list-item-content\"><div class=\"mat-list-item-ripple\" mat-ripple [matRippleTrigger]=\"_getHostElement()\" [matRippleDisabled]=\"_isRippleDisabled()\"></div><ng-content select=\"[mat-list-avatar], [mat-list-icon], [matListAvatar], [matListIcon]\"></ng-content><div class=\"mat-list-text\"><ng-content select=\"[mat-line], [matLine]\"></ng-content></div><ng-content></ng-content></div>",
encapsulation: core.ViewEncapsulation.None,
changeDetection: core.ChangeDetectionStrategy.OnPush,
},] },
];
/** @nocollapse */
MatListItem.ctorParameters = function () { return [
{ type: core.ElementRef, },
{ type: MatNavList, decorators: [{ type: core.Optional },] },
]; };
MatListItem.propDecorators = {
"_lines": [{ type: core.ContentChildren, args: [core$1.MatLine,] },],
"_avatar": [{ type: core.ContentChild, args: [MatListAvatarCssMatStyler,] },],
"_icon": [{ type: core.ContentChild, args: [MatListIconCssMatStyler,] },],
};
return MatListItem;
}(_MatListItemMixinBase));
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* \@docs-private
*/
var /**
* \@docs-private
*/
MatSelectionListBase = /** @class */ (function () {
function MatSelectionListBase() {
}
return MatSelectionListBase;
}());
var /** @type {?} */ _MatSelectionListMixinBase = core$1.mixinDisableRipple(MatSelectionListBase);
/**
* \@docs-private
*/
var /**
* \@docs-private
*/
MatListOptionBase = /** @class */ (function () {
function MatListOptionBase() {
}
return MatListOptionBase;
}());
var /** @type {?} */ _MatListOptionMixinBase = core$1.mixinDisableRipple(MatListOptionBase);
/**
* \@docs-private
*/
var /** @type {?} */ MAT_SELECTION_LIST_VALUE_ACCESSOR = {
provide: forms.NG_VALUE_ACCESSOR,
useExisting: core.forwardRef(function () { return MatSelectionList; }),
multi: true
};
/**
* Change event that is being fired whenever the selected state of an option changes.
*/
var /**
* Change event that is being fired whenever the selected state of an option changes.
*/
MatSelectionListChange = /** @class */ (function () {
function MatSelectionListChange(source, option) {
this.source = source;
this.option = option;
}
return MatSelectionListChange;
}());
/**
* Component for list-options of selection-list. Each list-option can automatically
* generate a checkbox and can put current item into the selectionModel of selection-list
* if the current item is selected.
*/
var MatListOption = /** @class */ (function (_super) {
__extends(MatListOption, _super);
function MatListOption(_element, _changeDetector, /** @docs-private */
selectionList) {
var _this = _super.call(this) || this;
_this._element = _element;
_this._changeDetector = _changeDetector;
_this.selectionList = selectionList;
_this._selected = false;
_this._disabled = false;
/**
* Whether the option has focus.
*/
_this._hasFocus = false;
/**
* Whether the label should appear before or after the checkbox. Defaults to 'after'
*/
_this.checkboxPosition = 'after';
return _this;
}
Object.defineProperty(MatListOption.prototype, "disabled", {
get: /**
* Whether the option is disabled.
* @return {?}
*/
function () { return this._disabled || (this.selectionList && this.selectionList.disabled); },
set: /**
* @param {?} value
* @return {?}
*/
function (value) {
var /** @type {?} */ newValue = coercion.coerceBooleanProperty(value);
if (newValue !== this._disabled) {
this._disabled = newValue;
this._changeDetector.markForCheck();
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(MatListOption.prototype, "selected", {
get: /**
* Whether the option is selected.
* @return {?}
*/
function () { return this.selectionList.selectedOptions.isSelected(this); },
set: /**
* @param {?} value
* @return {?}
*/
function (value) {
var /** @type {?} */ isSelected = coercion.coerceBooleanProperty(value);
if (isSelected !== this._selected) {
this._setSelected(isSelected);
this.selectionList._reportValueChange();
}
},
enumerable: true,
configurable: true
});
/**
* @return {?}
*/
MatListOption.prototype.ngOnInit = /**
* @return {?}
*/
function () {
var _this = this;
// List options that are selected at initialization can't be reported properly to the form
// control. This is because it takes some time until the selection-list knows about all
// available options. Also it can happen that the ControlValueAccessor has an initial value
// that should be used instead. Deferring the value change report to the next tick ensures
// that the form control value is not being overwritten.
var /** @type {?} */ wasSelected = this._selected;
Promise.resolve().then(function () {
if (_this._selected || wasSelected) {
_this.selected = true;
_this._changeDetector.markForCheck();
}
});
};
/**
* @return {?}
*/
MatListOption.prototype.ngAfterContentInit = /**
* @return {?}
*/
function () {
// TODO: consider turning the setter into a function, it doesn't do anything as a class.
// tslint:disable-next-line:no-unused-expression
new core$1.MatLineSetter(this._lines, this._element);
};
/**
* @return {?}
*/
MatListOption.prototype.ngOnDestroy = /**
* @return {?}
*/
function () {
var _this = this;
if (this.selected) {
// We have to delay this until the next tick in order
// to avoid changed after checked errors.
Promise.resolve().then(function () { return _this.selected = false; });
}
this.selectionList._removeOptionFromList(this);
};
/** Toggles the selection state of the option. */
/**
* Toggles the selection state of the option.
* @return {?}
*/
MatListOption.prototype.toggle = /**
* Toggles the selection state of the option.
* @return {?}
*/
function () {
this.selected = !this.selected;
};
/** Allows for programmatic focusing of the option. */
/**
* Allows for programmatic focusing of the option.
* @return {?}
*/
MatListOption.prototype.focus = /**
* Allows for programmatic focusing of the option.
* @return {?}
*/
function () {
this._element.nativeElement.focus();
};
/**
* Returns the list item's text label. Implemented as a part of the FocusKeyManager.
* @docs-private
*/
/**
* Returns the list item's text label. Implemented as a part of the FocusKeyManager.
* \@docs-private
* @return {?}
*/
MatListOption.prototype.getLabel = /**
* Returns the list item's text label. Implemented as a part of the FocusKeyManager.
* \@docs-private
* @return {?}
*/
function () {
return this._text ? this._text.nativeElement.textContent : '';
};
/** Whether this list item should show a ripple effect when clicked. */
/**
* Whether this list item should show a ripple effect when clicked.
* @return {?}
*/
MatListOption.prototype._isRippleDisabled = /**
* Whether this list item should show a ripple effect when clicked.
* @return {?}
*/
function () {
return this.disabled || this.disableRipple || this.selectionList.disableRipple;
};
/**
* @return {?}
*/
MatListOption.prototype._handleClick = /**
* @return {?}
*/
function () {
if (!this.disabled) {
this.toggle();
// Emit a change event if the selected state of the option changed through user interaction.
this.selectionList._emitChangeEvent(this);
}
};
/**
* @return {?}
*/
MatListOption.prototype._handleFocus = /**
* @return {?}
*/
function () {
this._hasFocus = true;
this.selectionList._setFocusedOption(this);
};
/**
* @return {?}
*/
MatListOption.prototype._handleBlur = /**
* @return {?}
*/
function () {
this._hasFocus = false;
this.selectionList._onTouched();
};
/** Retrieves the DOM element of the component host. */
/**
* Retrieves the DOM element of the component host.
* @return {?}
*/
MatListOption.prototype._getHostElement = /**
* Retrieves the DOM element of the component host.
* @return {?}
*/
function () {
return this._element.nativeElement;
};
/** Sets the selected state of the option. Returns whether the value has changed. */
/**
* Sets the selected state of the option. Returns whether the value has changed.
* @param {?} selected
* @return {?}
*/
MatListOption.prototype._setSelected = /**
* Sets the selected state of the option. Returns whether the value has changed.
* @param {?} selected
* @return {?}
*/
function (selected) {
if (selected === this._selected) {
return false;
}
this._selected = selected;
if (selected) {
this.selectionList.selectedOptions.select(this);
}
else {
this.selectionList.selectedOptions.deselect(this);
}
this._changeDetector.markForCheck();
return true;
};
/**
* Notifies Angular that the option needs to be checked in the next change detection run. Mainly
* used to trigger an update of the list option if the disabled state of the selection list
* changed.
*/
/**
* Notifies Angular that the option needs to be checked in the next change detection run. Mainly
* used to trigger an update of the list option if the disabled state of the selection list
* changed.
* @return {?}
*/
MatListOption.prototype._markForCheck = /**
* Notifies Angular that the option needs to be checked in the next change detection run. Mainly
* used to trigger an update of the list option if the disabled state of the selection list
* changed.
* @return {?}
*/
function () {
this._changeDetector.markForCheck();
};
MatListOption.decorators = [
{ type: core.Component, args: [{selector: 'mat-list-option',
exportAs: 'matListOption',
inputs: ['disableRipple'],
host: {
'role': 'option',
'class': 'mat-list-item mat-list-option',
'(focus)': '_handleFocus()',
'(blur)': '_handleBlur()',
'(click)': '_handleClick()',
'tabindex': '-1',
'[class.mat-list-item-disabled]': 'disabled',
'[class.mat-list-item-focus]': '_hasFocus',
'[class.mat-list-item-with-avatar]': '_avatar',
'[attr.aria-selected]': 'selected.toString()',
'[attr.aria-disabled]': 'disabled.toString()',
},
template: "<div class=\"mat-list-item-content\" [class.mat-list-item-content-reverse]=\"checkboxPosition == 'after'\"><div mat-ripple class=\"mat-list-item-ripple\" [matRippleTrigger]=\"_getHostElement()\" [matRippleDisabled]=\"_isRippleDisabled()\"></div><mat-pseudo-checkbox [state]=\"selected ? 'checked' : 'unchecked'\" [disabled]=\"disabled\"></mat-pseudo-checkbox><div class=\"mat-list-text\" #text><ng-content></ng-content></div><ng-content select=\"[mat-list-avatar], [mat-list-icon], [matListAvatar], [matListIcon]\"></ng-content></div>",
encapsulation: core.ViewEncapsulation.None,
changeDetection: core.ChangeDetectionStrategy.OnPush,
},] },
];
/** @nocollapse */
MatListOption.ctorParameters = function () { return [
{ type: core.ElementRef, },
{ type: core.ChangeDetectorRef, },
{ type: MatSelectionList, decorators: [{ type: core.Inject, args: [core.forwardRef(function () { return MatSelectionList; }),] },] },
]; };
MatListOption.propDecorators = {
"_avatar": [{ type: core.ContentChild, args: [MatListAvatarCssMatStyler,] },],
"_lines": [{ type: core.ContentChildren, args: [core$1.MatLine,] },],
"_text": [{ type: core.ViewChild, args: ['text',] },],
"checkboxPosition": [{ type: core.Input },],
"value": [{ type: core.Input },],
"disabled": [{ type: core.Input },],
"selected": [{ type: core.Input },],
};
return MatListOption;
}(_MatListOptionMixinBase));
/**
* Material Design list component where each item is a selectable option. Behaves as a listbox.
*/
var MatSelectionList = /** @class */ (function (_super) {
__extends(MatSelectionList, _super);
function MatSelectionList(_element, tabIndex) {
var _this = _super.call(this) || this;
_this._element = _element;
/**
* Emits a change event whenever the selected state of an option changes.
*/
_this.selectionChange = new core.EventEmitter();
/**
* Tabindex of the selection list.
*/
_this.tabIndex = 0;
_this._disabled = false;
/**
* The currently selected options.
*/
_this.selectedOptions = new collections.SelectionModel(true);
/**
* View to model callback that should be called whenever the selected options change.
*/
_this._onChange = function (_) { };
/**
* Subscription to sync value changes in the SelectionModel back to the SelectionList.
*/
_this._modelChanges = rxjs.Subscription.EMPTY;
/**
* View to model callback that should be called if the list or its options lost focus.
*/
_this._onTouched = function () { };
_this.tabIndex = parseInt(tabIndex) || 0;
return _this;
}
Object.defineProperty(MatSelectionList.prototype, "disabled", {
get: /**
* Whether the selection list is disabled.
* @return {?}
*/
function () { return this._disabled; },
set: /**
* @param {?} value
* @return {?}
*/
function (value) {
this._disabled = coercion.coerceBooleanProperty(value);
// The `MatSelectionList` and `MatListOption` are using the `OnPush` change detection
// strategy. Therefore the options will not check for any changes if the `MatSelectionList`
// changed its state. Since we know that a change to `disabled` property of the list affects
// the state of the options, we manually mark each option for check.
if (this.options) {
this.options.forEach(function (option) { return option._markForCheck(); });
}
},
enumerable: true,
configurable: true
});
/**
* @return {?}
*/
MatSelectionList.prototype.ngAfterContentInit = /**
* @return {?}
*/
function () {
this._keyManager = new a11y.FocusKeyManager(this.options)
.withWrap()
.withTypeAhead()
.skipPredicate(function () { return false; });
if (this._tempValues) {
this._setOptionsFromValues(this._tempValues);
this._tempValues = null;
}
// Sync external changes to the model back to the options.
this._modelChanges = /** @type {?} */ ((this.selectedOptions.onChange)).subscribe(function (event) {
if (event.added) {
for (var _i = 0, _a = event.added; _i < _a.length; _i++) {
var item = _a[_i];
item.selected = true;
}
}
if (event.removed) {
for (var _b = 0, _c = event.removed; _b < _c.length; _b++) {
var item = _c[_b];
item.selected = false;
}
}
});
};
/**
* @return {?}
*/
MatSelectionList.prototype.ngOnDestroy = /**
* @return {?}
*/
function () {
this._modelChanges.unsubscribe();
};
/** Focuses the last active list option. */
/**
* Focuses the last active list option.
* @return {?}
*/
MatSelectionList.prototype.focus = /**
* Focuses the last active list option.
* @return {?}
*/
function () {
this._element.nativeElement.focus();
};
/** Selects all of the options. */
/**
* Selects all of the options.
* @return {?}
*/
MatSelectionList.prototype.selectAll = /**
* Selects all of the options.
* @return {?}
*/
function () {
this._setAllOptionsSelected(true);
};
/** Deselects all of the options. */
/**
* Deselects all of the options.
* @return {?}
*/
MatSelectionList.prototype.deselectAll = /**
* Deselects all of the options.
* @return {?}
*/
function () {
this._setAllOptionsSelected(false);
};
/** Sets the focused option of the selection-list. */
/**
* Sets the focused option of the selection-list.
* @param {?} option
* @return {?}
*/
MatSelectionList.prototype._setFocusedOption = /**
* Sets the focused option of the selection-list.
* @param {?} option
* @return {?}
*/
function (option) {
this._keyManager.updateActiveItemIndex(this._getOptionIndex(option));
};
/** Removes an option from the selection list and updates the active item. */
/**
* Removes an option from the selection list and updates the active item.
* @param {?} option
* @return {?}
*/
MatSelectionList.prototype._removeOptionFromList = /**
* Removes an option from the selection list and updates the active item.
* @param {?} option
* @return {?}
*/
function (option) {
if (option._hasFocus) {
var /** @type {?} */ optionIndex = this._getOptionIndex(option);
// Check whether the option is the last item
if (optionIndex > 0) {
this._keyManager.setPreviousItemActive();
}
else if (optionIndex === 0 && this.options.length > 1) {
this._keyManager.setNextItemActive();
}
}
};
/** Passes relevant key presses to our key manager. */
/**
* Passes relevant key presses to our key manager.
* @param {?} event
* @return {?}
*/
MatSelectionList.prototype._keydown = /**
* Passes relevant key presses to our key manager.
* @param {?} event
* @return {?}
*/
function (event) {
var /** @type {?} */ keyCode = event.keyCode;
var /** @type {?} */ manager = this._keyManager;
var /** @type {?} */ previousFocusIndex = manager.activeItemIndex;
switch (keyCode) {
case keycodes.SPACE:
case keycodes.ENTER:
if (!this.disabled) {
this._toggleSelectOnFocusedOption();
// Always prevent space from scrolling the page since the list has focus
event.preventDefault();
}
break;
case keycodes.HOME:
case keycodes.END:
keyCode === keycodes.HOME ? manager.setFirstItemActive() : manager.setLastItemActive();
event.preventDefault();
break;
case keycodes.A:
if (event.ctrlKey) {
this.options.find(function (option) { return !option.selected; }) ? this.selectAll() : this.deselectAll();
event.preventDefault();
}
break;
default:
manager.onKeydown(event);
}
if ((keyCode === keycodes.UP_ARROW || keyCode === keycodes.DOWN_ARROW) && event.shiftKey &&
manager.activeItemIndex !== previousFocusIndex) {
this._toggleSelectOnFocusedOption();
}
};
/** Reports a value change to the ControlValueAccessor */
/**
* Reports a value change to the ControlValueAccessor
* @return {?}
*/
MatSelectionList.prototype._reportValueChange = /**
* Reports a value change to the ControlValueAccessor
* @return {?}
*/
function () {
if (this.options) {
this._onChange(this._getSelectedOptionValues());
}
};
/** Emits a change event if the selected state of an option changed. */
/**
* Emits a change event if the selected state of an option changed.
* @param {?} option
* @return {?}
*/
MatSelectionList.prototype._emitChangeEvent = /**
* Emits a change event if the selected state of an option changed.
* @param {?} option
* @return {?}
*/
function (option) {
this.selectionChange.emit(new MatSelectionListChange(this, option));
};
/** Implemented as part of ControlValueAccessor. */
/**
* Implemented as part of ControlValueAccessor.
* @param {?} values
* @return {?}
*/
MatSelectionList.prototype.writeValue = /**
* Implemented as part of ControlValueAccessor.
* @param {?} values
* @return {?}
*/
function (values) {
if (this.options) {
this._setOptionsFromValues(values || []);
}
else {
this._tempValues = values;
}
};
/** Implemented as a part of ControlValueAccessor. */
/**
* Implemented as a part of ControlValueAccessor.
* @param {?} isDisabled
* @return {?}
*/
MatSelectionList.prototype.setDisabledState = /**
* Implemented as a part of ControlValueAccessor.
* @param {?} isDisabled
* @return {?}
*/
function (isDisabled) {
this.disabled = isDisabled;
};
/** Implemented as part of ControlValueAccessor. */
/**
* Implemented as part of ControlValueAccessor.
* @param {?} fn
* @return {?}
*/
MatSelectionList.prototype.registerOnChange = /**
* Implemented as part of ControlValueAccessor.
* @param {?} fn
* @return {?}
*/
function (fn) {
this._onChange = fn;
};
/** Implemented as part of ControlValueAccessor. */
/**
* Implemented as part of ControlValueAccessor.
* @param {?} fn
* @return {?}
*/
MatSelectionList.prototype.registerOnTouched = /**
* Implemented as part of ControlValueAccessor.
* @param {?} fn
* @return {?}
*/
function (fn) {
this._onTouched = fn;
};
/**
* Sets the selected options based on the specified values.
* @param {?} values
* @return {?}
*/
MatSelectionList.prototype._setOptionsFromValues = /**
* Sets the selected options based on the specified values.
* @param {?} values
* @return {?}
*/
function (values) {
var _this = this;
this.options.forEach(function (option) { return option._setSelected(false); });
values
.map(function (value) {
return _this.options.find(function (option) {
return _this.compareWith ? _this.compareWith(option.value, value) : option.value === value;
});
})
.filter(Boolean)
.forEach(function (option) { return ((option))._setSelected(true); });
};
/**
* Returns the values of the selected options.
* @return {?}
*/
MatSelectionList.prototype._getSelectedOptionValues = /**
* Returns the values of the selected options.
* @return {?}
*/
function () {
return this.options.filter(function (option) { return option.selected; }).map(function (option) { return option.value; });
};
/**
* Toggles the selected state of the currently focused option.
* @return {?}
*/
MatSelectionList.prototype._toggleSelectOnFocusedOption = /**
* Toggles the selected state of the currently focused option.
* @return {?}
*/
function () {
var /** @type {?} */ focusedIndex = this._keyManager.activeItemIndex;
if (focusedIndex != null && this._isValidIndex(focusedIndex)) {
var /** @type {?} */ focusedOption = this.options.toArray()[focusedIndex];
if (focusedOption) {
focusedOption.toggle();
// Emit a change event because the focused option changed its state through user
// interaction.
this._emitChangeEvent(focusedOption);
}
}
};
/**
* Sets the selected state on all of the options
* and emits an event if anything changed.
* @param {?} isSelected
* @return {?}
*/
MatSelectionList.prototype._setAllOptionsSelected = /**
* Sets the selected state on all of the options
* and emits an event if anything changed.
* @param {?} isSelected
* @return {?}
*/
function (isSelected) {
// Keep track of whether anything changed, because we only want to
// emit the changed event when something actually changed.
var /** @type {?} */ hasChanged = false;
this.options.forEach(function (option) {
if (option._setSelected(isSelected)) {
hasChanged = true;
}
});
if (hasChanged) {
this._reportValueChange();
}
};
/**
* Utility to ensure all indexes are valid.
* @param {?} index The index to be checked.
* @return {?} True if the index is valid for our list of options.
*/
MatSelectionList.prototype._isValidIndex = /**
* Utility to ensure all indexes are valid.
* @param {?} index The index to be checked.
* @return {?} True if the index is valid for our list of options.
*/
function (index) {
return index >= 0 && index < this.options.length;
};
/**
* Returns the index of the specified list option.
* @param {?} option
* @return {?}
*/
MatSelectionList.prototype._getOptionIndex = /**
* Returns the index of the specified list option.
* @param {?} option
* @return {?}
*/
function (option) {
return this.options.toArray().indexOf(option);
};
MatSelectionList.decorators = [
{ type: core.Component, args: [{selector: 'mat-selection-list',
exportAs: 'matSelectionList',
inputs: ['disabled', 'disableRipple', 'tabIndex'],
host: {
'role': 'listbox',
'[tabIndex]': 'tabIndex',
'class': 'mat-selection-list',
'(focus)': 'focus()',
'(blur)': '_onTouched()',
'(keydown)': '_keydown($event)',
'[attr.aria-disabled]': 'disabled.toString()',
},
template: '<ng-content></ng-content>',
styles: [".mat-divider{display:block;margin:0;border-top-width:1px;border-top-style:solid}.mat-divider.mat-divider-vertical{border-top:0;border-right-width:1px;border-right-style:solid}.mat-divider.mat-divider-inset{margin-left:80px}[dir=rtl] .mat-divider.mat-divider-inset{margin-left:auto;margin-right:80px}.mat-subheader{display:flex;box-sizing:border-box;padding:16px;align-items:center}.mat-list .mat-subheader,.mat-nav-list .mat-subheader,.mat-selection-list .mat-subheader{margin:0}.mat-list,.mat-nav-list,.mat-selection-list{padding-top:8px;display:block;-webkit-tap-highlight-color:transparent}.mat-list .mat-subheader,.mat-nav-list .mat-subheader,.mat-selection-list .mat-subheader{height:48px;line-height:16px}.mat-list .mat-subheader:first-child,.mat-nav-list .mat-subheader:first-child,.mat-selection-list .mat-subheader:first-child{margin-top:-8px}.mat-list .mat-list-item,.mat-list .mat-list-option,.mat-nav-list .mat-list-item,.mat-nav-list .mat-list-option,.mat-selection-list .mat-list-item,.mat-selection-list .mat-list-option{display:block;height:48px;-webkit-tap-highlight-color:transparent}.mat-list .mat-list-item .mat-list-item-content,.mat-list .mat-list-option .mat-list-item-content,.mat-nav-list .mat-list-item .mat-list-item-content,.mat-nav-list .mat-list-option .mat-list-item-content,.mat-selection-list .mat-list-item .mat-list-item-content,.mat-selection-list .mat-list-option .mat-list-item-content{display:flex;flex-direction:row;align-items:center;box-sizing:border-box;padding:0 16px;position:relative;height:inherit}.mat-list .mat-list-item .mat-list-item-content-reverse,.mat-list .mat-list-option .mat-list-item-content-reverse,.mat-nav-list .mat-list-item .mat-list-item-content-reverse,.mat-nav-list .mat-list-option .mat-list-item-content-reverse,.mat-selection-list .mat-list-item .mat-list-item-content-reverse,.mat-selection-list .mat-list-option .mat-list-item-content-reverse{display:flex;align-items:center;padding:0 16px;flex-direction:row-reverse;justify-content:space-around}.mat-list .mat-list-item .mat-list-item-ripple,.mat-list .mat-list-option .mat-list-item-ripple,.mat-nav-list .mat-list-item .mat-list-item-ripple,.mat-nav-list .mat-list-option .mat-list-item-ripple,.mat-selection-list .mat-list-item .mat-list-item-ripple,.mat-selection-list .mat-list-option .mat-list-item-ripple{top:0;left:0;right:0;bottom:0;position:absolute;pointer-events:none}.mat-list .mat-list-item.mat-list-item-with-avatar,.mat-list .mat-list-option.mat-list-item-with-avatar,.mat-nav-list .mat-list-item.mat-list-item-with-avatar,.mat-nav-list .mat-list-option.mat-list-item-with-avatar,.mat-selection-list .mat-list-item.mat-list-item-with-avatar,.mat-selection-list .mat-list-option.mat-list-item-with-avatar{height:56px}.mat-list .mat-list-item.mat-2-line,.mat-list .mat-list-option.mat-2-line,.mat-nav-list .mat-list-item.mat-2-line,.mat-nav-list .mat-list-option.mat-2-line,.mat-selection-list .mat-list-item.mat-2-line,.mat-selection-list .mat-list-option.mat-2-line{height:72px}.mat-list .mat-list-item.mat-3-line,.mat-list .mat-list-option.mat-3-line,.mat-nav-list .mat-list-item.mat-3-line,.mat-nav-list .mat-list-option.mat-3-line,.mat-selection-list .mat-list-item.mat-3-line,.mat-selection-list .mat-list-option.mat-3-line{height:88px}.mat-list .mat-list-item.mat-multi-line,.mat-list .mat-list-option.mat-multi-line,.mat-nav-list .mat-list-item.mat-multi-line,.mat-nav-list .mat-list-option.mat-multi-line,.mat-selection-list .mat-list-item.mat-multi-line,.mat-selection-list .mat-list-option.mat-multi-line{height:auto}.mat-list .mat-list-item.mat-multi-line .mat-list-item-content,.mat-list .mat-list-option.mat-multi-line .mat-list-item-content,.mat-nav-list .mat-list-item.mat-multi-line .mat-list-item-content,.mat-nav-list .mat-list-option.mat-multi-line .mat-list-item-content,.mat-selection-list .mat-list-item.mat-multi-line .mat-list-item-content,.mat-selection-list .mat-list-option.mat-multi-line .mat-list-item-content{padding-top:16px;padding-bottom:16px}.mat-list .mat-list-item .mat-list-text,.mat-list .mat-list-option .mat-list-text,.mat-nav-list .mat-list-item .mat-list-text,.mat-nav-list .mat-list-option .mat-list-text,.mat-selection-list .mat-list-item .mat-list-text,.mat-selection-list .mat-list-option .mat-list-text{display:flex;flex-direction:column;width:100%;box-sizing:border-box;overflow:hidden;padding:0}.mat-list .mat-list-item .mat-list-text>*,.mat-list .mat-list-option .mat-list-text>*,.mat-nav-list .mat-list-item .mat-list-text>*,.mat-nav-list .mat-list-option .mat-list-text>*,.mat-selection-list .mat-list-item .mat-list-text>*,.mat-selection-list .mat-list-option .mat-list-text>*{margin:0;padding:0;font-weight:400;font-size:inherit}.mat-list .mat-list-item .mat-list-text:empty,.mat-list .mat-list-option .mat-list-text:empty,.mat-nav-list .mat-list-item .mat-list-text:empty,.mat-nav-list .mat-list-option .mat-list-text:empty,.mat-selection-list .mat-list-item .mat-list-text:empty,.mat-selection-list .mat-list-option .mat-list-text:empty{display:none}.mat-list .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-list .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,.mat-list .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-list .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text,.mat-nav-list .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-nav-list .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,.mat-nav-list .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-nav-list .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text,.mat-selection-list .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-selection-list .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,.mat-selection-list .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-selection-list .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text{padding-right:0;padding-left:16px}[dir=rtl] .mat-list .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-nav-list .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-nav-list .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-nav-list .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-nav-list .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-selection-list .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-selection-list .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-selection-list .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-selection-list .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text{padding-right:16px;padding-left:0}.mat-list .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-list .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-list .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-nav-list .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-nav-list .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-nav-list .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-nav-list .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-selection-list .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-selection-list .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-selection-list .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-selection-list .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-left:0;padding-right:16px}[dir=rtl] .mat-list .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-nav-list .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-nav-list .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-nav-list .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-nav-list .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-selection-list .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-selection-list .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-selection-list .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-selection-list .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-right:0;padding-left:16px}.mat-list .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-list .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-list .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-nav-list .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-nav-list .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-nav-list .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-nav-list .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-selection-list .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-selection-list .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-selection-list .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-selection-list .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-right:16px;padding-left:16px}.mat-list .mat-list-item .mat-list-avatar,.mat-list .mat-list-option .mat-list-avatar,.mat-nav-list .mat-list-item .mat-list-avatar,.mat-nav-list .mat-list-option .mat-list-avatar,.mat-selection-list .mat-list-item .mat-list-avatar,.mat-selection-list .mat-list-option .mat-list-avatar{flex-shrink:0;width:40px;height:40px;border-radius:50%}.mat-list .mat-list-item .mat-list-avatar~.mat-divider-inset,.mat-list .mat-list-option .mat-list-avatar~.mat-divider-inset,.mat-nav-list .mat-list-item .mat-list-avatar~.mat-divider-inset,.mat-nav-list .mat-list-option .mat-list-avatar~.mat-divider-inset,.mat-selection-list .mat-list-item .mat-list-avatar~.mat-divider-inset,.mat-selection-list .mat-list-option .mat-list-avatar~.mat-divider-inset{margin-left:72px;width:calc(100% - 72px)}[dir=rtl] .mat-list .mat-list-item .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-list .mat-list-option .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-nav-list .mat-list-item .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-nav-list .mat-list-option .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-selection-list .mat-list-item .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-selection-list .mat-list-option .mat-list-avatar~.mat-divider-inset{margin-left:auto;margin-right:72px}.mat-list .mat-list-item .mat-list-icon,.mat-list .mat-list-option .mat-list-icon,.mat-nav-list .mat-list-item .mat-list-icon,.mat-nav-list .mat-list-option .mat-list-icon,.mat-selection-list .mat-list-item .mat-list-icon,.mat-selection-list .mat-list-option .mat-list-icon{flex-shrink:0;width:24px;height:24px;font-size:24px;box-sizing:content-box;border-radius:50%;padding:4px}.mat-list .mat-list-item .mat-list-icon~.mat-divider-inset,.mat-list .mat-list-option .mat-list-icon~.mat-divider-inset,.mat-nav-list .mat-list-item .mat-list-icon~.mat-divider-inset,.mat-nav-list .mat-list-option .mat-list-icon~.mat-divider-inset,.mat-selection-list .mat-list-item .mat-list-icon~.mat-divider-inset,.mat-selection-list .mat-list-option .mat-list-icon~.mat-divider-inset{margin-left:64px;width:calc(100% - 64px)}[dir=rtl] .mat-list .mat-list-item .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-list .mat-list-option .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-nav-list .mat-list-item .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-nav-list .mat-list-option .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-selection-list .mat-list-item .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-selection-list .mat-list-option .mat-list-icon~.mat-divider-inset{margin-left:auto;margin-right:64px}.mat-list .mat-list-item .mat-divider,.mat-list .mat-list-option .mat-divider,.mat-nav-list .mat-list-item .mat-divider,.mat-nav-list .mat-list-option .mat-divider,.mat-selection-list .mat-list-item .mat-divider,.mat-selection-list .mat-list-option .mat-divider{position:absolute;bottom:0;left:0;width:100%;margin:0}[dir=rtl] .mat-list .mat-list-item .mat-divider,[dir=rtl] .mat-list .mat-list-option .mat-divider,[dir=rtl] .mat-nav-list .mat-list-item .mat-divider,[dir=rtl] .mat-nav-list .mat-list-option .mat-divider,[dir=rtl] .mat-selection-list .mat-list-item .mat-divider,[dir=rtl] .mat-selection-list .mat-list-option .mat-divider{margin-left:auto;margin-right:0}.mat-list .mat-list-item .mat-divider.mat-divider-inset,.mat-list .mat-list-option .mat-divider.mat-divider-inset,.mat-nav-list .mat-list-item .mat-divider.mat-divider-inset,.mat-nav-list .mat-list-option .mat-divider.mat-divider-inset,.mat-selection-list .mat-list-item .mat-divider.mat-divider-inset,.mat-selection-list .mat-list-option .mat-divider.mat-divider-inset{position:absolute}.mat-list[dense],.mat-nav-list[dense],.mat-selection-list[dense]{padding-top:4px;display:block}.mat-list[dense] .mat-subheader,.mat-nav-list[dense] .mat-subheader,.mat-selection-list[dense] .mat-subheader{height:40px;line-height:8px}.mat-list[dense] .mat-subheader:first-child,.mat-nav-list[dense] .mat-subheader:first-child,.mat-selection-list[dense] .mat-subheader:first-child{margin-top:-4px}.mat-list[dense] .mat-list-item,.mat-list[dense] .mat-list-option,.mat-nav-list[dense] .mat-list-item,.mat-nav-list[dense] .mat-list-option,.mat-selection-list[dense] .mat-list-item,.mat-selection-list[dense] .mat-list-option{display:block;height:40px;-webkit-tap-highlight-color:transparent}.mat-list[dense] .mat-list-item .mat-list-item-content,.mat-list[dense] .mat-list-option .mat-list-item-content,.mat-nav-list[dense] .mat-list-item .mat-list-item-content,.mat-nav-list[dense] .mat-list-option .mat-list-item-content,.mat-selection-list[dense] .mat-list-item .mat-list-item-content,.mat-selection-list[dense] .mat-list-option .mat-list-item-content{display:flex;flex-direction:row;align-items:center;box-sizing:border-box;padding:0 16px;position:relative;height:inherit}.mat-list[dense] .mat-list-item .mat-list-item-content-reverse,.mat-list[dense] .mat-list-option .mat-list-item-content-reverse,.mat-nav-list[dense] .mat-list-item .mat-list-item-content-reverse,.mat-nav-list[dense] .mat-list-option .mat-list-item-content-reverse,.mat-selection-list[dense] .mat-list-item .mat-list-item-content-reverse,.mat-selection-list[dense] .mat-list-option .mat-list-item-content-reverse{display:flex;align-items:center;padding:0 16px;flex-direction:row-reverse;justify-content:space-around}.mat-list[dense] .mat-list-item .mat-list-item-ripple,.mat-list[dense] .mat-list-option .mat-list-item-ripple,.mat-nav-list[dense] .mat-list-item .mat-list-item-ripple,.mat-nav-list[dense] .mat-list-option .mat-list-item-ripple,.mat-selection-list[dense] .mat-list-item .mat-list-item-ripple,.mat-selection-list[dense] .mat-list-option .mat-list-item-ripple{top:0;left:0;right:0;bottom:0;position:absolute;pointer-events:none}.mat-list[dense] .mat-list-item.mat-list-item-with-avatar,.mat-list[dense] .mat-list-option.mat-list-item-with-avatar,.mat-nav-list[dense] .mat-list-item.mat-list-item-with-avatar,.mat-nav-list[dense] .mat-list-option.mat-list-item-with-avatar,.mat-selection-list[dense] .mat-list-item.mat-list-item-with-avatar,.mat-selection-list[dense] .mat-list-option.mat-list-item-with-avatar{height:48px}.mat-list[dense] .mat-list-item.mat-2-line,.mat-list[dense] .mat-list-option.mat-2-line,.mat-nav-list[dense] .mat-list-item.mat-2-line,.mat-nav-list[dense] .mat-list-option.mat-2-line,.mat-selection-list[dense] .mat-list-item.mat-2-line,.mat-selection-list[dense] .mat-list-option.mat-2-line{height:60px}.mat-list[dense] .mat-list-item.mat-3-line,.mat-list[dense] .mat-list-option.mat-3-line,.mat-nav-list[dense] .mat-list-item.mat-3-line,.mat-nav-list[dense] .mat-list-option.mat-3-line,.mat-selection-list[dense] .mat-list-item.mat-3-line,.mat-selection-list[dense] .mat-list-option.mat-3-line{height:76px}.mat-list[dense] .mat-list-item.mat-multi-line,.mat-list[dense] .mat-list-option.mat-multi-line,.mat-nav-list[dense] .mat-list-item.mat-multi-line,.mat-nav-list[dense] .mat-list-option.mat-multi-line,.mat-selection-list[dense] .mat-list-item.mat-multi-line,.mat-selection-list[dense] .mat-list-option.mat-multi-line{height:auto}.mat-list[dense] .mat-list-item.mat-multi-line .mat-list-item-content,.mat-list[dense] .mat-list-option.mat-multi-line .mat-list-item-content,.mat-nav-list[dense] .mat-list-item.mat-multi-line .mat-list-item-content,.mat-nav-list[dense] .mat-list-option.mat-multi-line .mat-list-item-content,.mat-selection-list[dense] .mat-list-item.mat-multi-line .mat-list-item-content,.mat-selection-list[dense] .mat-list-option.mat-multi-line .mat-list-item-content{padding-top:16px;padding-bottom:16px}.mat-list[dense] .mat-list-item .mat-list-text,.mat-list[dense] .mat-list-option .mat-list-text,.mat-nav-list[dense] .mat-list-item .mat-list-text,.mat-nav-list[dense] .mat-list-option .mat-list-text,.mat-selection-list[dense] .mat-list-item .mat-list-text,.mat-selection-list[dense] .mat-list-option .mat-list-text{display:flex;flex-direction:column;width:100%;box-sizing:border-box;overflow:hidden;padding:0}.mat-list[dense] .mat-list-item .mat-list-text>*,.mat-list[dense] .mat-list-option .mat-list-text>*,.mat-nav-list[dense] .mat-list-item .mat-list-text>*,.mat-nav-list[dense] .mat-list-option .mat-list-text>*,.mat-selection-list[dense] .mat-list-item .mat-list-text>*,.mat-selection-list[dense] .mat-list-option .mat-list-text>*{margin:0;padding:0;font-weight:400;font-size:inherit}.mat-list[dense] .mat-list-item .mat-list-text:empty,.mat-list[dense] .mat-list-option .mat-list-text:empty,.mat-nav-list[dense] .mat-list-item .mat-list-text:empty,.mat-nav-list[dense] .mat-list-option .mat-list-text:empty,.mat-selection-list[dense] .mat-list-item .mat-list-text:empty,.mat-selection-list[dense] .mat-list-option .mat-list-text:empty{display:none}.mat-list[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-list[dense] .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,.mat-list[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-list[dense] .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text,.mat-nav-list[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-nav-list[dense] .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,.mat-nav-list[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-nav-list[dense] .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text,.mat-selection-list[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-selection-list[dense] .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,.mat-selection-list[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-selection-list[dense] .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text{padding-right:0;padding-left:16px}[dir=rtl] .mat-list[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list[dense] .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list[dense] .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-nav-list[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-nav-list[dense] .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-nav-list[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-nav-list[dense] .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-selection-list[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-selection-list[dense] .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-selection-list[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-selection-list[dense] .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text{padding-right:16px;padding-left:0}.mat-list[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-list[dense] .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-list[dense] .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-nav-list[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-nav-list[dense] .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-nav-list[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-nav-list[dense] .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-selection-list[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-selection-list[dense] .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-selection-list[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-selection-list[dense] .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-left:0;padding-right:16px}[dir=rtl] .mat-list[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list[dense] .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list[dense] .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-nav-list[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-nav-list[dense] .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-nav-list[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-nav-list[dense] .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-selection-list[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-selection-list[dense] .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-selection-list[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-selection-list[dense] .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-right:0;padding-left:16px}.mat-list[dense] .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-list[dense] .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list[dense] .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-list[dense] .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-nav-list[dense] .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-nav-list[dense] .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-nav-list[dense] .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-nav-list[dense] .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-selection-list[dense] .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-selection-list[dense] .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-selection-list[dense] .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-selection-list[dense] .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-right:16px;padding-left:16px}.mat-list[dense] .mat-list-item .mat-list-avatar,.mat-list[dense] .mat-list-option .mat-list-avatar,.mat-nav-list[dense] .mat-list-item .mat-list-avatar,.mat-nav-list[dense] .mat-list-option .mat-list-avatar,.mat-selection-list[dense] .mat-list-item .mat-list-avatar,.mat-selection-list[dense] .mat-list-option .mat-list-avatar{flex-shrink:0;width:36px;height:36px;border-radius:50%}.mat-list[dense] .mat-list-item .mat-list-avatar~.mat-divider-inset,.mat-list[dense] .mat-list-option .mat-list-avatar~.mat-divider-inset,.mat-nav-list[dense] .mat-list-item .mat-list-avatar~.mat-divider-inset,.mat-nav-list[dense] .mat-list-option .mat-list-avatar~.mat-divider-inset,.mat-selection-list[dense] .mat-list-item .mat-list-avatar~.mat-divider-inset,.mat-selection-list[dense] .mat-list-option .mat-list-avatar~.mat-divider-inset{margin-left:68px;width:calc(100% - 68px)}[dir=rtl] .mat-list[dense] .mat-list-item .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-list[dense] .mat-list-option .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-nav-list[dense] .mat-list-item .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-nav-list[dense] .mat-list-option .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-selection-list[dense] .mat-list-item .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-selection-list[dense] .mat-list-option .mat-list-avatar~.mat-divider-inset{margin-left:auto;margin-right:68px}.mat-list[dense] .mat-list-item .mat-list-icon,.mat-list[dense] .mat-list-option .mat-list-icon,.mat-nav-list[dense] .mat-list-item .mat-list-icon,.mat-nav-list[dense] .mat-list-option .mat-list-icon,.mat-selection-list[dense] .mat-list-item .mat-list-icon,.mat-selection-list[dense] .mat-list-option .mat-list-icon{flex-shrink:0;width:20px;height:20px;font-size:20px;box-sizing:content-box;border-radius:50%;padding:4px}.mat-list[dense] .mat-list-item .mat-list-icon~.mat-divider-inset,.mat-list[dense] .mat-list-option .mat-list-icon~.mat-divider-inset,.mat-nav-list[dense] .mat-list-item .mat-list-icon~.mat-divider-inset,.mat-nav-list[dense] .mat-list-option .mat-list-icon~.mat-divider-inset,.mat-selection-list[dense] .mat-list-item .mat-list-icon~.mat-divider-inset,.mat-selection-list[dense] .mat-list-option .mat-list-icon~.mat-divider-inset{margin-left:60px;width:calc(100% - 60px)}[dir=rtl] .mat-list[dense] .mat-list-item .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-list[dense] .mat-list-option .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-nav-list[dense] .mat-list-item .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-nav-list[dense] .mat-list-option .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-selection-list[dense] .mat-list-item .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-selection-list[dense] .mat-list-option .mat-list-icon~.mat-divider-inset{margin-left:auto;margin-right:60px}.mat-list[dense] .mat-list-item .mat-divider,.mat-list[dense] .mat-list-option .mat-divider,.mat-nav-list[dense] .mat-list-item .mat-divider,.mat-nav-list[dense] .mat-list-option .mat-divider,.mat-selection-list[dense] .mat-list-item .mat-divider,.mat-selection-list[dense] .mat-list-option .mat-divider{position:absolute;bottom:0;left:0;width:100%;margin:0}[dir=rtl] .mat-list[dense] .mat-list-item .mat-divider,[dir=rtl] .mat-list[dense] .mat-list-option .mat-divider,[dir=rtl] .mat-nav-list[dense] .mat-list-item .mat-divider,[dir=rtl] .mat-nav-list[dense] .mat-list-option .mat-divider,[dir=rtl] .mat-selection-list[dense] .mat-list-item .mat-divider,[dir=rtl] .mat-selection-list[dense] .mat-list-option .mat-divider{margin-left:auto;margin-right:0}.mat-list[dense] .mat-list-item .mat-divider.mat-divider-inset,.mat-list[dense] .mat-list-option .mat-divider.mat-divider-inset,.mat-nav-list[dense] .mat-list-item .mat-divider.mat-divider-inset,.mat-nav-list[dense] .mat-list-option .mat-divider.mat-divider-inset,.mat-selection-list[dense] .mat-list-item .mat-divider.mat-divider-inset,.mat-selection-list[dense] .mat-list-option .mat-divider.mat-divider-inset{position:absolute}.mat-nav-list a{text-decoration:none;color:inherit}.mat-nav-list .mat-list-item{cursor:pointer;outline:0}.mat-list-option:not(.mat-list-item-disabled){cursor:pointer;outline:0}@media (hover:none){.mat-list-option:hover,.mat-nav-list .mat-list-item:hover{background:0 0}}"],
encapsulation: core.ViewEncapsulation.None,
providers: [MAT_SELECTION_LIST_VALUE_ACCESSOR],
changeDetection: core.ChangeDetectionStrategy.OnPush
},] },
];
/** @nocollapse */
MatSelectionList.ctorParameters = function () { return [
{ type: core.ElementRef, },
{ type: undefined, decorators: [{ type: core.Attribute, args: ['tabindex',] },] },
]; };
MatSelectionList.propDecorators = {
"options": [{ type: core.ContentChildren, args: [MatListOption,] },],
"selectionChange": [{ type: core.Output },],
"tabIndex": [{ type: core.Input },],
"compareWith": [{ type: core.Input },],
"disabled": [{ type: core.Input },],
};
return MatSelectionList;
}(_MatSelectionListMixinBase));
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
var MatListModule = /** @class */ (function () {
function MatListModule() {
}
MatListModule.decorators = [
{ type: core.NgModule, args: [{
imports: [core$1.MatLineModule, core$1.MatRippleModule, core$1.MatCommonModule, core$1.MatPseudoCheckboxModule, common.CommonModule],
exports: [
MatList,
MatNavList,
MatListItem,
MatListAvatarCssMatStyler,
core$1.MatLineModule,
core$1.MatCommonModule,
MatListIconCssMatStyler,
MatListSubheaderCssMatStyler,
core$1.MatPseudoCheckboxModule,
MatSelectionList,
MatListOption,
divider.MatDividerModule
],
declarations: [
MatList,
MatNavList,
MatListItem,
MatListAvatarCssMatStyler,
MatListIconCssMatStyler,
MatListSubheaderCssMatStyler,
MatSelectionList,
MatListOption
],
},] },
];
return MatListModule;
}());
exports.MatListModule = MatListModule;
exports.MatListBase = MatListBase;
exports._MatListMixinBase = _MatListMixinBase;
exports.MatListItemBase = MatListItemBase;
exports._MatListItemMixinBase = _MatListItemMixinBase;
exports.MatNavList = MatNavList;
exports.MatList = MatList;
exports.MatListAvatarCssMatStyler = MatListAvatarCssMatStyler;
exports.MatListIconCssMatStyler = MatListIconCssMatStyler;
exports.MatListSubheaderCssMatStyler = MatListSubheaderCssMatStyler;
exports.MatListItem = MatListItem;
exports.MatSelectionListBase = MatSelectionListBase;
exports._MatSelectionListMixinBase = _MatSelectionListMixinBase;
exports.MatListOptionBase = MatListOptionBase;
exports._MatListOptionMixinBase = _MatListOptionMixinBase;
exports.MAT_SELECTION_LIST_VALUE_ACCESSOR = MAT_SELECTION_LIST_VALUE_ACCESSOR;
exports.MatSelectionListChange = MatSelectionListChange;
exports.MatListOption = MatListOption;
exports.MatSelectionList = MatSelectionList;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=material-list.umd.js.map | /**
* @license |
|
index.tsx | import React from 'react';
import { AppLoading } from 'expo';
import { useAuth } from '../hooks/auth';
import AppRouter from './app.routes';
import AuthRouter from './auth.routes';
const Routes: React.FC = () => {
const { loading, user } = useAuth();
if (loading) {
return <AppLoading />
}
return user ? <AppRouter /> : <AuthRouter /> | };
export default Routes; |
|
10265687.py | import sys
n, r = map(int, sys.stdin.readline().split())
def main():
|
if __name__ == '__main__':
ans = main()
print(ans)
| res = r + 100 * max(10 - n, 0)
return res |
email-mixin.js | /**
* @author aakimov
*/
/*jshint browser:true jquery:true*/
/*global alert*/
define([
'jquery',
'mage/utils/wrapper',
'Magento_Checkout/js/model/quote'
], function ($, wrapper, quote) {
'use strict';
return function (targetModule) {
var masterpassData = window.checkoutConfig.masterpassData;
var isCustomerLoggedIn = targetModule.isCustomerLoggedIn;
var isCustomerLoggedInWrapper = wrapper.wrap(isCustomerLoggedIn, function (originalAction) {
var result = originalAction();
if (Object.keys(masterpassData).length) {
//hide login form if this is masterpass payment
result = true;
}
return result;
});
targetModule.isCustomerLoggedIn = isCustomerLoggedInWrapper;
var defaults = targetModule.defaults;
var defaultsWrapper = wrapper.wrap(defaults, function (originalAction) {
var result = originalAction();
if (Object.keys(masterpassData).length) {
result.template = 'Svea_MaksuturvaMasterpass/checkout/form/element/email';
}
return result;
});
targetModule.defaults = defaultsWrapper;
var getQuoteEmail = function(){
var email = "";
if (Object.keys(masterpassData).length) {
$.each(masterpassData.addresses, function (key, item) {
email = item.email;
quote.guestEmail = email;
return false;
});
} | }
targetModule.getQuoteEmail = getQuoteEmail;
return targetModule;
};
}
); | return email; |
maps.go | // Copyright (c) 2015, Emir Pasic. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package maps provides an abstract Map interface.
//
// In computer science, an associative array, map, symbol table, or dictionary is an abstract data type composed of a collection of (key, value) pairs, such that each possible key appears just once in the collection.
//
// Operations associated with this data type allow:
// - the addition of a pair to the collection
// - the removal of a pair from the collection
// - the modification of an existing pair
// - the lookup of a value associated with a particular key
//
// Reference: https://en.wikipedia.org/wiki/Associative_array
package maps
import "github.com/douguohai/gods/containers"
// Map interface that all maps implement
type Map interface {
Put(key interface{}, value interface{})
Get(key interface{}) (value interface{}, found bool)
Remove(key interface{})
Keys() []interface{}
containers.Container
// Empty() bool
// Size() int
// Clear()
// Values() []interface{}
} | type BidiMap interface {
GetKey(value interface{}) (key interface{}, found bool)
Map
} |
// BidiMap interface that all bidirectional maps implement (extends the Map interface) |
modal-blog.component.ts | import { Component, OnInit, ViewChild } from '@angular/core';
import { NgbModalRef, NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { faCalendar, faEnvelope } from '@fortawesome/free-solid-svg-icons';
import {
faFacebook,
faTwitter,
faGooglePlus,
faLinkedin
} from '@fortawesome/free-brands-svg-icons';
@Component({
selector: 'app-modal-blog',
templateUrl: './modal-blog.component.html',
styleUrls: ['./modal-blog.component.scss']
})
export class | implements OnInit {
public dataPost: any;
// fontawesome icons
faCalendar = faCalendar;
faEnvelope = faEnvelope;
faFacebook = faFacebook;
faTwitter = faTwitter;
faGooglePlus = faGooglePlus;
faLinkedin = faLinkedin;
private modalRef: NgbModalRef;
@ViewChild('childmodal', { static: false })
child: any;
constructor(private modalService: NgbModal) {}
ngOnInit() {}
open(post: any) {
this.dataPost = post;
this.modalRef = this.modalService.open(this.child, {
size: 'lg',
backdrop: 'static'
});
}
}
| ModalBlogComponent |
__init__.py | from .buyback_auth import CashBuybackAuthorizations, ShareBuybackAuthorizations
from .earnings import EarningsCalendar
from .equity_pricing import USEquityPricing
from .dataset import DataSet, Column, BoundColumn
__all__ = [
'BoundColumn',
'CashBuybackAuthorizations',
'Column',
'DataSet',
'EarningsCalendar',
'ShareBuybackAuthorizations',
'USEquityPricing', | ] |
|
day24_more_linked_lists.py | class Node:
def __init__(self, data):
self.data = data
self.next = None
class Solution:
def insert(self, head, data):
p = Node(data)
if head is None:
head = p
elif head.next is None:
head.next = p
else:
start = head
while(start.next is not None):
start = start.next
start.next = p
return head
def display(self, head):
current = head
while current:
print(current.data, end=' ')
current = current.next
def removeDuplicates(self, head):
# Write your code here
if head is None:
return head
current = head
while current.next:
if current.data == current.next.data:
current.next = current.next.next
else:
current = current.next
return head
mylist = Solution()
T = int(input())
head = None
for i in range(T):
data = int(input())
head = mylist.insert(head, data)
head = mylist.removeDuplicates(head) | mylist.display(head) |
|
deployInitializer.controller.js | 'use strict';
let angular = require('angular');
module.exports = angular.module('spinnaker.azure.serverGroup.configure.deployInitialization.controller', [
require('../../../../core/serverGroup/serverGroup.read.service.js'),
require('../../../../core/utils/lodash.js'),
require('../serverGroupCommandBuilder.service.js'),
])
.controller('azureDeployInitializerCtrl', function($scope, azureServerGroupCommandBuilder, serverGroupReader, _) {
$scope.templates = [];
if (!$scope.command.viewState.disableNoTemplateSelection) {
var noTemplate = { label: 'None', serverGroup: null, cluster: null };
$scope.command.viewState.template = noTemplate;
$scope.templates = [ noTemplate ];
}
var allClusters = _.groupBy(_.filter($scope.application.serverGroups.data, { type: 'azure' }), function(serverGroup) {
return [serverGroup.cluster, serverGroup.account, serverGroup.region].join(':');
}); | $scope.templates.push({
cluster: latest.cluster,
account: latest.account,
region: latest.region,
serverGroupName: latest.name,
serverGroup: latest
});
});
function applyCommandToScope(command) {
command.viewState.disableImageSelection = true;
command.viewState.disableStrategySelection = $scope.command.viewState.disableStrategySelection || false;
command.viewState.imageId = null;
command.viewState.readOnlyFields = $scope.command.viewState.readOnlyFields || {};
command.viewState.submitButtonLabel = 'Add';
command.viewState.hideClusterNamePreview = $scope.command.viewState.hideClusterNamePreview || false;
command.viewState.templatingEnabled = true;
if ($scope.command.viewState.overrides) {
_.forOwn($scope.command.viewState.overrides, function(val, key) {
command[key] = val;
});
}
angular.copy(command, $scope.command);
}
function buildEmptyCommand() {
return azureServerGroupCommandBuilder.buildNewServerGroupCommand($scope.application, {mode: 'createPipeline'}).then(function(command) {
applyCommandToScope(command);
});
}
function buildCommandFromTemplate(serverGroup) {
return serverGroupReader.getServerGroup($scope.application.name, serverGroup.account, serverGroup.region, serverGroup.name).then(function (details) {
angular.extend(details, serverGroup);
return azureServerGroupCommandBuilder.buildServerGroupCommandFromExisting($scope.application, details, 'editPipeline').then(function (command) {
applyCommandToScope(command);
$scope.command.strategy = 'redblack';
});
});
}
this.selectTemplate = function () {
var selection = $scope.command.viewState.template;
if (selection && selection.cluster && selection.serverGroup) {
return buildCommandFromTemplate(selection.serverGroup);
} else {
return buildEmptyCommand();
}
};
this.useTemplate = function() {
$scope.state.loaded = false;
this.selectTemplate().then(function() {
$scope.$emit('template-selected');
});
};
}); |
_.forEach(allClusters, function(cluster) {
var latest = _.sortBy(cluster, 'name').pop(); |
core_util.go | // Copyright 2014 The goyy Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package main
import (
"github.com/axgle/mahonia"
"gopkg.in/goyy/goyy.v0/util/errors"
"gopkg.in/goyy/goyy.v0/util/strings"
)
func tagItemValue(tag, name string) string {
return strings.Between(tag, name+`:"`, `"`)
}
func tagAttrValue(tag, name string) (string, error) {
attributes := strings.Split(tag, "&")
for _, attr := range attributes {
pair := strings.Split(attr, "=")
if len(pair) != 2 |
switch strings.ToLower(pair[0]) {
case name:
return pair[1], nil
}
}
return "", errors.Newf("%s was not found in tag", name)
}
func convertUTF8(in string) string {
enc := mahonia.NewEncoder("gbk")
return enc.ConvertString(in)
}
| {
return "", errors.Newf("Malformed tag: '%s'", attr)
} |
public-interfaces.ts | export interface Response {
error?: any;
}
export interface StoreResponse extends Response {
key: string,
value: any;
}
export interface Entity extends Response {
id: string;
code?: string;
type: EntityType;
link: string;
description: string;
}
export enum EntityType {
BIB_MMS = 'BIB_MMS',
LICENSE = 'LICENSE',
USER = 'USER',
ITEM = 'ITEM',
COURSE = 'COURSE',
READING_LIST = 'READING_LIST',
REQUEST = 'REQUEST',
CITATION = 'CITATION',
AUTHORITY = 'AUTHORITY',
HOLDING = 'HOLDING',
/** Electronic collections */
IEPA = 'IEPA',
/** Library collections */
IEC = 'IEC',
PO_LINE = 'PO_LINE',
PORTFOLIO = 'PORTFOLIO',
INVOICE = 'INVOICE',
ELECTRONIC_SERVICE = 'ELECTRONIC_SERVICE',
INVOICE_LINE = 'INVOICE_LINE',
LOAN = 'LOAN',
REPRESENTATION = 'REPRESENTATION',
REPRESENTATION_FILE = 'REPRESENTATION_FILE',
VENDOR = 'VENDOR',
FUND = 'FUND',
REMINDER = 'REMINDER',
BORROWING_REQUEST = 'BORROWING_REQUEST',
LENDING_REQUEST = 'LENDING_REQUEST',
SET = 'SET'
}
export interface PageInfo extends Response {
entities: Entity[];
}
export enum UrlTypes {
ALMA = 'alma'
}
export interface InitData extends Response {
user: {
firstName: string,
lastName: string,
primaryId: string,
currentlyAtLibCode: string,
isAdmin: boolean
},
| color: string
}
export interface BasicResponse extends Response {
success: boolean;
}
export interface RestResponse extends Response {
body: any
}
export interface RestErrorResponse extends Response {
ok: boolean,
status: any,
statusText: string,
message: string,
error: any
}
export interface RefreshPageResponse extends BasicResponse { }
export interface WriteSettingsResponse extends BasicResponse { }
export interface ReadSettingsResponse extends BasicResponse { }
export interface WriteConfigResponse extends BasicResponse { }
export interface ReadConfigResponse extends BasicResponse { } | lang: string,
instCode: string,
urls: { [key in UrlTypes]: string },
|
test_web_cli.py | import pytest
from aiohttp import web
def test_entry_func_empty(mocker) -> None:
|
def test_entry_func_only_module(mocker) -> None:
argv = ["test"]
error = mocker.patch("aiohttp.web.ArgumentParser.error", side_effect=SystemExit)
with pytest.raises(SystemExit):
web.main(argv)
error.assert_called_with("'entry-func' not in 'module:function' syntax")
def test_entry_func_only_function(mocker) -> None:
argv = [":test"]
error = mocker.patch("aiohttp.web.ArgumentParser.error", side_effect=SystemExit)
with pytest.raises(SystemExit):
web.main(argv)
error.assert_called_with("'entry-func' not in 'module:function' syntax")
def test_entry_func_only_separator(mocker) -> None:
argv = [":"]
error = mocker.patch("aiohttp.web.ArgumentParser.error", side_effect=SystemExit)
with pytest.raises(SystemExit):
web.main(argv)
error.assert_called_with("'entry-func' not in 'module:function' syntax")
def test_entry_func_relative_module(mocker) -> None:
argv = [".a.b:c"]
error = mocker.patch("aiohttp.web.ArgumentParser.error", side_effect=SystemExit)
with pytest.raises(SystemExit):
web.main(argv)
error.assert_called_with("relative module names not supported")
def test_entry_func_non_existent_module(mocker) -> None:
argv = ["alpha.beta:func"]
mocker.patch("aiohttp.web.import_module", side_effect=ImportError("Test Error"))
error = mocker.patch("aiohttp.web.ArgumentParser.error", side_effect=SystemExit)
with pytest.raises(SystemExit):
web.main(argv)
error.assert_called_with("unable to import alpha.beta: Test Error")
def test_entry_func_non_existent_attribute(mocker) -> None:
argv = ["alpha.beta:func"]
import_module = mocker.patch("aiohttp.web.import_module")
error = mocker.patch("aiohttp.web.ArgumentParser.error", side_effect=SystemExit)
module = import_module("alpha.beta")
del module.func
with pytest.raises(SystemExit):
web.main(argv)
error.assert_called_with(
"module alpha.beta has no attribute func"
)
def test_path_when_unsupported(mocker, monkeypatch) -> None:
argv = "--path=test_path.sock alpha.beta:func".split()
mocker.patch("aiohttp.web.import_module")
monkeypatch.delattr("socket.AF_UNIX", raising=False)
error = mocker.patch("aiohttp.web.ArgumentParser.error", side_effect=SystemExit)
with pytest.raises(SystemExit):
web.main(argv)
error.assert_called_with(
"file system paths not supported by your" " operating environment"
)
def test_entry_func_call(mocker) -> None:
mocker.patch("aiohttp.web.run_app")
import_module = mocker.patch("aiohttp.web.import_module")
argv = (
"-H testhost -P 6666 --extra-optional-eins alpha.beta:func "
"--extra-optional-zwei extra positional args"
).split()
module = import_module("alpha.beta")
with pytest.raises(SystemExit):
web.main(argv)
module.func.assert_called_with(
("--extra-optional-eins --extra-optional-zwei extra positional " "args").split()
)
def test_running_application(mocker) -> None:
run_app = mocker.patch("aiohttp.web.run_app")
import_module = mocker.patch("aiohttp.web.import_module")
exit = mocker.patch("aiohttp.web.ArgumentParser.exit", side_effect=SystemExit)
argv = (
"-H testhost -P 6666 --extra-optional-eins alpha.beta:func "
"--extra-optional-zwei extra positional args"
).split()
module = import_module("alpha.beta")
app = module.func()
with pytest.raises(SystemExit):
web.main(argv)
run_app.assert_called_with(app, host="testhost", port=6666, path=None)
exit.assert_called_with(message="Stopped\n")
| error = mocker.patch("aiohttp.web.ArgumentParser.error", side_effect=SystemExit)
argv = [""]
with pytest.raises(SystemExit):
web.main(argv)
error.assert_called_with("'entry-func' not in 'module:function' syntax") |
gocloak_adapter_service_account_test.go | package adapter
import (
"testing"
"github.com/Nerzal/gocloak/v8"
)
func TestGoCloakAdapter_SetServiceAccountAttributes(t *testing.T) {
mockClient := new(MockGoCloakClient)
adapter := GoCloakAdapter{
client: mockClient,
basePath: "",
token: &gocloak.JWT{AccessToken: "token"},
}
usr1 := gocloak.User{
Username: gocloak.StringP("user1"),
Attributes: &map[string][]string{
"foo1": []string{"bar1"},
},
}
usr2 := gocloak.User{
Username: gocloak.StringP("user1"),
Attributes: &map[string][]string{
"foo": {"bar"},
},
}
mockClient.On("GetClientServiceAccount", "realm1", "clientID1").Return(&usr1, nil)
mockClient.On("UpdateUser", "realm1", usr2).Return(nil)
if err := adapter.SetServiceAccountAttributes("realm1", "clientID1",
map[string]string{"foo": "bar"}); err != nil |
}
| {
t.Fatal(err)
} |
main.go | package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/url"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"
appsv1 "k8s.io/api/apps/v1"
kyaml "k8s.io/apimachinery/pkg/util/yaml"
"github.com/cloudevents/sdk-go/pkg/cloudevents/types"
"github.com/google/uuid"
"gopkg.in/yaml.v2"
"github.com/cloudevents/sdk-go/pkg/cloudevents"
"github.com/cloudevents/sdk-go/pkg/cloudevents/client"
cloudeventshttp "github.com/cloudevents/sdk-go/pkg/cloudevents/transport/http"
"github.com/kelseyhightower/envconfig"
keptnevents "github.com/keptn/go-utils/pkg/events"
keptnmodels "github.com/keptn/go-utils/pkg/models"
keptnutils "github.com/keptn/go-utils/pkg/utils"
"k8s.io/client-go/kubernetes"
_ "k8s.io/client-go/plugin/pkg/client/auth"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/helm/pkg/helm"
helm_env "k8s.io/helm/pkg/helm/environment"
"k8s.io/helm/pkg/helm/portforwarder"
"k8s.io/helm/pkg/kube"
)
const tillernamespace = "kube-system"
const remediationfilename = "remediation.yaml"
const configurationserviceconnection = "CONFIGURATION_SERVICE" //"localhost:6060" // "configuration-service:8080"
const eventbroker = "EVENTBROKER"
type envConfig struct {
Port int `envconfig:"RCV_PORT" default:"8080"`
Path string `envconfig:"RCV_PATH" default:"/"`
}
func main() {
var env envConfig
if err := envconfig.Process("", &env); err != nil {
log.Fatalf("failed to process env var: %s", err)
}
os.Exit(_main(os.Args[1:], env))
}
func _main(args []string, env envConfig) int {
ctx := context.Background()
t, err := cloudeventshttp.New(
cloudeventshttp.WithPort(env.Port),
cloudeventshttp.WithPath(env.Path),
)
if err != nil {
log.Fatalf("failed to create transport: %v", err)
}
c, err := client.New(t)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
log.Fatalf("failed to start receiver: %s", c.StartReceiver(ctx, gotEvent))
return 0
}
func gotEvent(ctx context.Context, event cloudevents.Event) error {
var shkeptncontext string
event.Context.ExtensionAs("shkeptncontext", &shkeptncontext)
logger := keptnutils.NewLogger(shkeptncontext, event.Context.GetID(), "remediation-service")
logger.Debug("Received event for shkeptncontext:" + shkeptncontext)
var eventData *keptnevents.ProblemEventData
if event.Type() == keptnevents.ProblemOpenEventType {
logger.Debug("Received problem notification")
eventData = &keptnevents.ProblemEventData{}
if err := event.DataAs(eventData); err != nil {
return err
}
}
releasename, err := getReleasename(eventData)
if err != nil {
logger.Error("could not get release name")
return err
}
projectname, stagename, servicename := splitReleaseName(*releasename)
if eventData.State != "OPEN" {
logger.Debug("Received closed problem")
sendTestsFinishedEvent(shkeptncontext, projectname, stagename, servicename)
return nil
}
logger.Debug("Received open problem")
resourceURI := remediationfilename
// valide if remediation should be performed
resourceHandler := keptnutils.NewResourceHandler(os.Getenv(configurationserviceconnection))
autoremediate := isRemediationEnabled(resourceHandler, projectname, stagename)
logger.Debug(fmt.Sprintf("remediation enabled for project and stage: %t", autoremediate))
if !autoremediate {
return errors.New("remediation not enabled for project and stage")
}
// get remediation.yaml
resource, err := resourceHandler.GetServiceResource(projectname, stagename, servicename, resourceURI)
if err != nil {
logger.Error("could not get remediation.yaml file")
return err
}
logger.Debug("remediation.yaml for service found")
// get remediation action from remediation.yaml
var remediationData keptnmodels.Remediations
yaml.Unmarshal([]byte(resource.ResourceContent), &remediationData)
for _, remediation := range remediationData.Remediations {
if remediation.Name == eventData.ProblemTitle {
logger.Debug("Remediation for problem found in remediation.yaml")
// currently only one remediation action is supported
if remediation.Actions[0].Action == "scaling" {
currentReplicaCount, err := getReplicaCount(logger, projectname, stagename, servicename, os.Getenv(configurationserviceconnection))
if err != nil {
logger.Error("could not get replica count")
return err
}
adjustment, err := strconv.Atoi(remediation.Actions[0].Value)
if err != nil {
logger.Error("could not get value for scaling remediation action")
}
propertyPath := "spec.replicas"
propertyValue := currentReplicaCount + adjustment
err = createAndSendEvent(shkeptncontext, projectname, servicename, stagename, propertyPath, propertyValue)
if err != nil {
logger.Error(err.Error())
}
}
}
}
logger.Debug("remediation service finished")
return nil
}
// initialize helm
func init() {
_, err := keptnutils.ExecuteCommand("helm", []string{"init", "--client-only"})
if err != nil {
log.Fatal(err)
}
fmt.Println("initialization of Helm done")
}
// get helm release name by impacted entity
func getReleasename(eventData *keptnevents.ProblemEventData) (*string, error) {
switch impact := eventData.ProblemDetails; {
case strings.HasPrefix(impact, "Pod"):
return getReleaseByPodName(eventData.ImpactedEntity)
case strings.HasPrefix(impact, "Service"):
return nil, errors.New("Service remediation not yet supported")
case strings.HasPrefix(impact, "Node"):
return nil, errors.New("Node remediation not yet supported")
default:
return nil, errors.New("could not interpret problem details")
}
}
// getKubeClient creates a Kubernetes config and client for a given kubeconfig context.
func getKubeClient(context string, kubeconfig string) (*rest.Config, kubernetes.Interface, error) {
var config *rest.Config
var err error
config, err = getK8sConfig()
if err != nil {
return nil, nil, fmt.Errorf("could not get config for Kubernetes client: %s", err)
}
client, err := kubernetes.NewForConfig(config)
if err != nil {
return nil, nil, fmt.Errorf("could not get Kubernetes client: %s", err)
}
return config, client, nil
}
// UserHomeDir retries home directory of user
func UserHomeDir() string {
if runtime.GOOS == "windows" {
home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
if home == "" {
home = os.Getenv("USERPROFILE")
}
return home
}
return os.Getenv("HOME")
}
func getK8sConfig() (*rest.Config, error) {
var useInClusterConfig bool
if os.Getenv("ENVIRONMENT") == "production" {
useInClusterConfig = true
} else {
useInClusterConfig = false
}
var config *rest.Config
var err error
if useInClusterConfig {
config, err = rest.InClusterConfig()
} else {
kubeconfig := filepath.Join(
UserHomeDir(), ".kube", "config",
)
config, err = clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil {
return nil, err
}
}
return config, nil
}
func getHelmClient() (*helm.Client, error) {
var settings helm_env.EnvSettings
var tillerTunnel *kube.Tunnel
if settings.TillerHost == "" {
config, client, err := getKubeClient(settings.KubeContext, settings.KubeConfig)
if err != nil {
return nil, err
}
settings.TillerNamespace = tillernamespace
tillerTunnel, err = portforwarder.New(settings.TillerNamespace, client, config)
if err != nil {
return nil, err
}
settings.TillerHost = fmt.Sprintf("127.0.0.1:%d", tillerTunnel.Local)
}
options := []helm.Option{helm.Host(settings.TillerHost), helm.ConnectTimeout(5)}
client := helm.NewClient(options...)
return client, nil
}
func isRemediationEnabled(rh *keptnutils.ResourceHandler, project string, stage string) bool {
keptnHandler := keptnutils.NewKeptnHandler(rh)
fmt.Println("get shipyard for ", project)
shipyard, err := keptnHandler.GetShipyard(project)
if err != nil {
return false
}
fmt.Println("shipyard: ", shipyard)
for _, s := range shipyard.Stages {
if s.Name == stage && s.RemediationStrategy == "automated" {
return true
}
}
return false
}
// gets Helm release name by pod name
func getReleaseByPodName(podname string) (*string, error) {
client, err := getHelmClient()
if err != nil {
fmt.Println("could not get Helm client")
return nil, err
}
releaseList, err := client.ListReleases()
if err != nil {
fmt.Println("could not fetch list of releases")
return nil, err
}
for _, r := range releaseList.GetReleases() {
rs, err := client.ReleaseStatus(r.Name, helm.StatusReleaseVersion(0))
if err != nil {
fmt.Println("release status error: ", err)
return nil, err
}
if strings.Contains(rs.Info.Status.Resources, podname) {
return &r.Name, nil
}
}
return nil, errors.New("could not find release for pod")
}
// splits helm release name into project, stage and service
func splitReleaseName(releasename string) (project string, stage string, service string) {
// currently no "-" in project and stage name are allowed, thus "-" is used to split
s := strings.SplitN(releasename, "-", 3)
project = s[0]
stage = s[1]
// remove the "-generated" suffix
service = strings.Replace(s[2], "-generated", "", 1)
return project, stage, service
}
// gets replica count from helm chart
func getReplicaCount(logger *keptnutils.Logger, project, stage, service, configServiceURL string) (int, error) {
helmChartName := service + "-generated"
// Read chart
chart, err := keptnutils.GetChart(project, service, stage, helmChartName, configServiceURL)
if err != nil {
return -1, err
}
logger.Debug("chart found for affected service")
for _, template := range chart.Templates {
dec := kyaml.NewYAMLToJSONDecoder(bytes.NewReader(template.Data))
for {
var document interface{}
err := dec.Decode(&document)
if err == io.EOF {
break
}
if err != nil { | }
doc, err := json.Marshal(document)
if err != nil {
return -1, err
}
var depl appsv1.Deployment
if err := json.Unmarshal(doc, &depl); err == nil && keptnutils.IsDeployment(&depl) {
// It is a deployment
fmt.Println(depl.Spec.Replicas)
return int(*depl.Spec.Replicas), nil
}
}
}
return -1, errors.New("could not find replica count")
}
// creates and sends cloud event
func createAndSendEvent(shkeptncontext string, project string,
service string, stage string, propertyPath string, propertyValue interface{}) error {
source, _ := url.Parse("https://github.com/keptn/keptn/remediation-service")
contentType := "application/json"
pc := keptnevents.PropertyChange{
PropertyPath: propertyPath,
Value: propertyValue,
}
configChangedEvent := keptnevents.ConfigurationChangeEventData{
Project: project,
Service: service,
Stage: stage,
DeploymentChanges: []keptnevents.PropertyChange{pc},
}
event := cloudevents.Event{
Context: cloudevents.EventContextV02{
ID: uuid.New().String(),
Time: &types.Timestamp{Time: time.Now()},
Type: keptnevents.ConfigurationChangeEventType,
Source: types.URLRef{URL: *source},
ContentType: &contentType,
Extensions: map[string]interface{}{"shkeptncontext": shkeptncontext},
}.AsV02(),
Data: configChangedEvent,
}
return sendEvent(event)
}
func sendEvent(event cloudevents.Event) error {
endPoint, err := getServiceEndpoint(eventbroker)
if err != nil {
return errors.New("Failed to retrieve endpoint of eventbroker. %s" + err.Error())
}
if endPoint.Host == "" {
return errors.New("Host of eventbroker not set")
}
transport, err := cloudeventshttp.New(
cloudeventshttp.WithTarget(endPoint.String()),
cloudeventshttp.WithEncoding(cloudeventshttp.StructuredV02),
)
if err != nil {
return errors.New("Failed to create transport:" + err.Error())
}
c, err := client.New(transport)
if err != nil {
return errors.New("Failed to create HTTP client:" + err.Error())
}
if _, err := c.Send(context.Background(), event); err != nil {
return errors.New("Failed to send cloudevent:, " + err.Error())
}
return nil
}
// sendTestsFinishedEvent sends a Cloud Event of type sh.keptn.events.tests-finished to the event broker
func sendTestsFinishedEvent(shkeptncontext string, project string, stage string, service string) error {
source, _ := url.Parse("remediation-service")
contentType := "application/json"
testFinishedData := keptnevents.TestsFinishedEventData{}
testFinishedData.Project = project
testFinishedData.Stage = stage
testFinishedData.Service = service
testFinishedData.TestStrategy = "real-user"
event := cloudevents.Event{
Context: cloudevents.EventContextV02{
ID: uuid.New().String(),
Time: &types.Timestamp{Time: time.Now()},
Type: "sh.keptn.events.tests-finished",
Source: types.URLRef{URL: *source},
ContentType: &contentType,
Extensions: map[string]interface{}{"shkeptncontext": shkeptncontext},
}.AsV02(),
Data: testFinishedData,
}
return sendEvent(event)
}
// getServiceEndpoint gets an endpoint stored in an environment variable and sets http as default scheme
func getServiceEndpoint(service string) (url.URL, error) {
url, err := url.Parse(os.Getenv(service))
if err != nil {
return *url, fmt.Errorf("Failed to retrieve value from ENVIRONMENT_VARIABLE: %s", service)
}
if url.Scheme == "" {
url.Scheme = "http"
}
return *url, nil
} | return -1, err |
ueditor.all.min.js | /*!
* UEditor
* version: ueditor
* build: Wed Aug 10 2016 11:06:03 GMT+0800 (CST)
*/
!function(){function getListener(a,b,c){var d;return b=b.toLowerCase(),(d=a.__allListeners||c&&(a.__allListeners={}))&&(d[b]||c&&(d[b]=[]))}function getDomNode(a,b,c,d,e,f){var g,h=d&&a[b];for(!h&&(h=a[c]);!h&&(g=(g||a).parentNode);){if("BODY"==g.tagName||f&&!f(g))return null;h=g[c]}return h&&e&&!e(h)?getDomNode(h,b,c,!1,e):h}UEDITOR_CONFIG=window.UEDITOR_CONFIG||{};var baidu=window.baidu||{};window.baidu=baidu,window.UE=baidu.editor=window.UE||{},UE.plugins={},UE.commands={},UE.instants={},UE.I18N={},UE._customizeUI={},UE.version="1.4.3";var dom=UE.dom={},browser=UE.browser=function(){var a=navigator.userAgent.toLowerCase(),b=window.opera,c={ie:/(msie\s|trident.*rv:)([\w.]+)/.test(a),opera:!!b&&b.version,webkit:a.indexOf(" applewebkit/")>-1,mac:a.indexOf("macintosh")>-1,quirks:"BackCompat"==document.compatMode};c.gecko="Gecko"==navigator.product&&!c.webkit&&!c.opera&&!c.ie;var d=0;if(c.ie){var e=a.match(/(?:msie\s([\w.]+))/),f=a.match(/(?:trident.*rv:([\w.]+))/);d=e&&f&&e[1]&&f[1]?Math.max(1*e[1],1*f[1]):e&&e[1]?1*e[1]:f&&f[1]?1*f[1]:0,c.ie11Compat=11==document.documentMode,c.ie9Compat=9==document.documentMode,c.ie8=!!document.documentMode,c.ie8Compat=8==document.documentMode,c.ie7Compat=7==d&&!document.documentMode||7==document.documentMode,c.ie6Compat=d<7||c.quirks,c.ie9above=d>8,c.ie9below=d<9,c.ie11above=d>10,c.ie11below=d<11}if(c.gecko){var g=a.match(/rv:([\d\.]+)/);g&&(g=g[1].split("."),d=1e4*g[0]+100*(g[1]||0)+1*(g[2]||0))}return/chrome\/(\d+\.\d)/i.test(a)&&(c.chrome=+RegExp.$1),/(\d+\.\d)?(?:\.\d)?\s+safari\/?(\d+\.\d+)?/i.test(a)&&!/chrome/i.test(a)&&(c.safari=+(RegExp.$1||RegExp.$2)),c.opera&&(d=parseFloat(b.version())),c.webkit&&(d=parseFloat(a.match(/ applewebkit\/(\d+)/)[1])),c.version=d,c.isCompatible=!c.mobile&&(c.ie&&d>=6||c.gecko&&d>=10801||c.opera&&d>=9.5||c.air&&d>=1||c.webkit&&d>=522||!1),c}(),ie=browser.ie,webkit=browser.webkit,gecko=browser.gecko,opera=browser.opera,utils=UE.utils={each:function(a,b,c){if(null!=a)if(a.length===+a.length){for(var d=0,e=a.length;d<e;d++)if(b.call(c,a[d],d,a)===!1)return!1}else for(var f in a)if(a.hasOwnProperty(f)&&b.call(c,a[f],f,a)===!1)return!1},makeInstance:function(a){var b=new Function;return b.prototype=a,a=new b,b.prototype=null,a},extend:function(a,b,c){if(b)for(var d in b)c&&a.hasOwnProperty(d)||(a[d]=b[d]);return a},extend2:function(a){for(var b=arguments,c=1;c<b.length;c++){var d=b[c];for(var e in d)a.hasOwnProperty(e)||(a[e]=d[e])}return a},inherits:function(a,b){var c=a.prototype,d=utils.makeInstance(b.prototype);return utils.extend(d,c,!0),a.prototype=d,d.constructor=a},bind:function(a,b){return function(){return a.apply(b,arguments)}},defer:function(a,b,c){var d;return function(){c&&clearTimeout(d),d=setTimeout(a,b)}},indexOf:function(a,b,c){var d=-1;return c=this.isNumber(c)?c:0,this.each(a,function(a,e){if(e>=c&&a===b)return d=e,!1}),d},removeItem:function(a,b){for(var c=0,d=a.length;c<d;c++)a[c]===b&&(a.splice(c,1),c--)},trim:function(a){return a.replace(/(^[ \t\n\r]+)|([ \t\n\r]+$)/g,"")},listToMap:function(a){if(!a)return{};a=utils.isArray(a)?a:a.split(",");for(var b,c=0,d={};b=a[c++];)d[b.toUpperCase()]=d[b]=1;return d},unhtml:function(a,b){return a?a.replace(b||/[&<">'](?:(amp|lt|quot|gt|#39|nbsp|#\d+);)?/g,function(a,b){return b?a:{"<":"<","&":"&",'"':""",">":">","'":"'"}[a]}):""},unhtmlForUrl:function(a,b){return a?a.replace(b||/[<">']/g,function(a){return{"<":"<","&":"&",'"':""",">":">","'":"'"}[a]}):""},html:function(a){return a?a.replace(/&((g|l|quo)t|amp|#39|nbsp);/g,function(a){return{"<":"<","&":"&",""":'"',">":">","'":"'"," ":" "}[a]}):""},cssStyleToDomStyle:function(){var a=document.createElement("div").style,b={"float":void 0!=a.cssFloat?"cssFloat":void 0!=a.styleFloat?"styleFloat":"float"};return function(a){return b[a]||(b[a]=a.toLowerCase().replace(/-./g,function(a){return a.charAt(1).toUpperCase()}))}}(),loadFile:function(){function a(a,c){try{for(var d,e=0;d=b[e++];)if(d.doc===a&&d.url==(c.src||c.href))return d}catch(f){return null}}var b=[];return function(c,d,e){var f=a(c,d);if(f)return void(f.ready?e&&e():f.funs.push(e));if(b.push({doc:c,url:d.src||d.href,funs:[e]}),!c.body){var g=[];for(var h in d)"tag"!=h&&g.push(h+'="'+d[h]+'"');return void c.write("<"+d.tag+" "+g.join(" ")+" ></"+d.tag+">")}if(!d.id||!c.getElementById(d.id)){var i=c.createElement(d.tag);delete d.tag;for(var h in d)i.setAttribute(h,d[h]);i.onload=i.onreadystatechange=function(){if(!this.readyState||/loaded|complete/.test(this.readyState)){if(f=a(c,d),f.funs.length>0){f.ready=1;for(var b;b=f.funs.pop();)b()}i.onload=i.onreadystatechange=null}},i.onerror=function(){throw Error("The load "+(d.href||d.src)+" fails,check the url settings of file ueditor.config.js ")},c.getElementsByTagName("head")[0].appendChild(i)}}}(),isEmptyObject:function(a){if(null==a)return!0;if(this.isArray(a)||this.isString(a))return 0===a.length;for(var b in a)if(a.hasOwnProperty(b))return!1;return!0},fixColor:function(a,b){if(/color/i.test(a)&&/rgba?/.test(b)){var c=b.split(",");if(c.length>3)return"";b="#";for(var d,e=0;d=c[e++];)d=parseInt(d.replace(/[^\d]/gi,""),10).toString(16),b+=1==d.length?"0"+d:d;b=b.toUpperCase()}return b},optCss:function(a){function b(a,b){if(!a)return"";var c=a.top,d=a.bottom,e=a.left,f=a.right,g="";if(c&&e&&d&&f)g+=";"+b+":"+(c==d&&d==e&&e==f?c:c==d&&e==f?c+" "+e:e==f?c+" "+e+" "+d:c+" "+f+" "+d+" "+e)+";";else for(var h in a)g+=";"+b+"-"+h+":"+a[h]+";";return g}var c,d;return a=a.replace(/(padding|margin|border)\-([^:]+):([^;]+);?/gi,function(a,b,e,f){if(1==f.split(" ").length)switch(b){case"padding":return!c&&(c={}),c[e]=f,"";case"margin":return!d&&(d={}),d[e]=f,"";case"border":return"initial"==f?"":a}return a}),a+=b(c,"padding")+b(d,"margin"),a.replace(/^[ \n\r\t;]*|[ \n\r\t]*$/,"").replace(/;([ \n\r\t]+)|\1;/g,";").replace(/(&((l|g)t|quot|#39))?;{2,}/g,function(a,b){return b?b+";;":";"})},clone:function(a,b){var c;b=b||{};for(var d in a)a.hasOwnProperty(d)&&(c=a[d],"object"==typeof c?(b[d]=utils.isArray(c)?[]:{},utils.clone(a[d],b[d])):b[d]=c);return b},transUnitToPx:function(a){if(!/(pt|cm)/.test(a))return a;var b;switch(a.replace(/([\d.]+)(\w+)/,function(c,d,e){a=d,b=e}),b){case"cm":a=25*parseFloat(a);break;case"pt":a=Math.round(96*parseFloat(a)/72)}return a+(a?"px":"")},domReady:function(){function a(a){a.isReady=!0;for(var c;c=b.pop();c());}var b=[];return function(c,d){d=d||window;var e=d.document;c&&b.push(c),"complete"===e.readyState?a(e):(e.isReady&&a(e),browser.ie&&11!=browser.version?(!function(){if(!e.isReady){try{e.documentElement.doScroll("left")}catch(b){return void setTimeout(arguments.callee,0)}a(e)}}(),d.attachEvent("onload",function(){a(e)})):(e.addEventListener("DOMContentLoaded",function(){e.removeEventListener("DOMContentLoaded",arguments.callee,!1),a(e)},!1),d.addEventListener("load",function(){a(e)},!1)))}}(),cssRule:browser.ie&&11!=browser.version?function(a,b,c){var d,e;if(void 0===b||b&&b.nodeType&&9==b.nodeType){if(c=b&&b.nodeType&&9==b.nodeType?b:c||document,d=c.indexList||(c.indexList={}),e=d[a],void 0!==e)return c.styleSheets[e].cssText}else{if(c=c||document,d=c.indexList||(c.indexList={}),e=d[a],""===b)return void 0!==e&&(c.styleSheets[e].cssText="",delete d[a],!0);void 0!==e?sheetStyle=c.styleSheets[e]:(sheetStyle=c.createStyleSheet("",e=c.styleSheets.length),d[a]=e),sheetStyle.cssText=b}}:function(a,b,c){var d;return void 0===b||b&&b.nodeType&&9==b.nodeType?(c=b&&b.nodeType&&9==b.nodeType?b:c||document,d=c.getElementById(a),d?d.innerHTML:void 0):(c=c||document,d=c.getElementById(a),""===b?!!d&&(d.parentNode.removeChild(d),!0):void(d?d.innerHTML=b:(d=c.createElement("style"),d.id=a,d.innerHTML=b,c.getElementsByTagName("head")[0].appendChild(d))))},sort:function(a,b){b=b||function(a,b){return a.localeCompare(b)};for(var c=0,d=a.length;c<d;c++)for(var e=c,f=a.length;e<f;e++)if(b(a[c],a[e])>0){var g=a[c];a[c]=a[e],a[e]=g}return a},serializeParam:function(a){var b=[];for(var c in a)if("method"!=c&&"timeout"!=c&&"async"!=c)if("function"!=(typeof a[c]).toLowerCase()&&"object"!=(typeof a[c]).toLowerCase())b.push(encodeURIComponent(c)+"="+encodeURIComponent(a[c]));else if(utils.isArray(a[c]))for(var d=0;d<a[c].length;d++)b.push(encodeURIComponent(c)+"[]="+encodeURIComponent(a[c][d]));return b.join("&")},formatUrl:function(a){var b=a.replace(/&&/g,"&");return b=b.replace(/\?&/g,"?"),b=b.replace(/&$/g,""),b=b.replace(/&#/g,"#"),b=b.replace(/&+/g,"&")},isCrossDomainUrl:function(a){var b=document.createElement("a");return b.href=a,browser.ie&&(b.href=b.href),!(b.protocol==location.protocol&&b.hostname==location.hostname&&(b.port==location.port||"80"==b.port&&""==location.port||""==b.port&&"80"==location.port))},clearEmptyAttrs:function(a){for(var b in a)""===a[b]&&delete a[b];return a},str2json:function(a){return utils.isString(a)?window.JSON?JSON.parse(a):new Function("return "+utils.trim(a||""))():null},json2str:function(){function a(a){return/["\\\x00-\x1f]/.test(a)&&(a=a.replace(/["\\\x00-\x1f]/g,function(a){var b=e[a];return b?b:(b=a.charCodeAt(),"\\u00"+Math.floor(b/16).toString(16)+(b%16).toString(16))})),'"'+a+'"'}function b(a){var b,c,d,e=["["],f=a.length;for(c=0;c<f;c++)switch(d=a[c],typeof d){case"undefined":case"function":case"unknown":break;default:b&&e.push(","),e.push(utils.json2str(d)),b=1}return e.push("]"),e.join("")}function c(a){return a<10?"0"+a:a}function d(a){return'"'+a.getFullYear()+"-"+c(a.getMonth()+1)+"-"+c(a.getDate())+"T"+c(a.getHours())+":"+c(a.getMinutes())+":"+c(a.getSeconds())+'"'}if(window.JSON)return JSON.stringify;var e={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};return function(c){switch(typeof c){case"undefined":return"undefined";case"number":return isFinite(c)?String(c):"null";case"string":return a(c);case"boolean":return String(c);default:if(null===c)return"null";if(utils.isArray(c))return b(c);if(utils.isDate(c))return d(c);var e,f,g=["{"],h=utils.json2str;for(var i in c)if(Object.prototype.hasOwnProperty.call(c,i))switch(f=c[i],typeof f){case"undefined":case"unknown":case"function":break;default:e&&g.push(","),e=1,g.push(h(i)+":"+h(f))}return g.push("}"),g.join("")}}}()};utils.each(["String","Function","Array","Number","RegExp","Object","Date"],function(a){UE.utils["is"+a]=function(b){return Object.prototype.toString.apply(b)=="[object "+a+"]"}});var EventBase=UE.EventBase=function(){};EventBase.prototype={addListener:function(a,b){a=utils.trim(a).split(/\s+/);for(var c,d=0;c=a[d++];)getListener(this,c,!0).push(b)},on:function(a,b){return this.addListener(a,b)},off:function(a,b){return this.removeListener(a,b)},trigger:function(){return this.fireEvent.apply(this,arguments)},removeListener:function(a,b){a=utils.trim(a).split(/\s+/);for(var c,d=0;c=a[d++];)utils.removeItem(getListener(this,c)||[],b)},fireEvent:function(){var a=arguments[0];a=utils.trim(a).split(" ");for(var b,c=0;b=a[c++];){var d,e,f,g=getListener(this,b);if(g)for(f=g.length;f--;)if(g[f]){if(e=g[f].apply(this,arguments),e===!0)return e;void 0!==e&&(d=e)}(e=this["on"+b.toLowerCase()])&&(d=e.apply(this,arguments))}return d}};var dtd=dom.dtd=function(){function a(a){for(var b in a)a[b.toUpperCase()]=a[b];return a}var b=utils.extend2,c=a({isindex:1,fieldset:1}),d=a({input:1,button:1,select:1,textarea:1,label:1}),e=b(a({a:1}),d),f=b({iframe:1},e),g=a({hr:1,ul:1,menu:1,div:1,blockquote:1,noscript:1,table:1,center:1,address:1,dir:1,pre:1,h5:1,dl:1,h4:1,noframes:1,h6:1,ol:1,h1:1,h3:1,h2:1}),h=a({ins:1,del:1,script:1,style:1}),i=b(a({b:1,acronym:1,bdo:1,"var":1,"#":1,abbr:1,code:1,br:1,i:1,cite:1,kbd:1,u:1,strike:1,s:1,tt:1,strong:1,q:1,samp:1,em:1,dfn:1,span:1}),h),j=b(a({sub:1,img:1,embed:1,object:1,sup:1,basefont:1,map:1,applet:1,font:1,big:1,small:1}),i),k=b(a({p:1}),j),l=b(a({iframe:1}),j,d),m=a({img:1,embed:1,noscript:1,br:1,kbd:1,center:1,button:1,basefont:1,h5:1,h4:1,samp:1,h6:1,ol:1,h1:1,h3:1,h2:1,form:1,font:1,"#":1,select:1,menu:1,ins:1,abbr:1,label:1,code:1,table:1,script:1,cite:1,input:1,iframe:1,strong:1,textarea:1,noframes:1,big:1,small:1,span:1,hr:1,sub:1,bdo:1,"var":1,div:1,object:1,sup:1,strike:1,dir:1,map:1,dl:1,applet:1,del:1,isindex:1,fieldset:1,ul:1,b:1,acronym:1,a:1,blockquote:1,i:1,u:1,s:1,tt:1,address:1,q:1,pre:1,p:1,em:1,dfn:1}),n=b(a({a:0}),l),o=a({tr:1}),p=a({"#":1}),q=b(a({param:1}),m),r=b(a({form:1}),c,f,g,k),s=a({li:1,ol:1,ul:1}),t=a({style:1,script:1}),u=a({base:1,link:1,meta:1,title:1}),v=b(u,t),w=a({head:1,body:1}),x=a({html:1}),y=a({address:1,blockquote:1,center:1,dir:1,div:1,dl:1,fieldset:1,form:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,hr:1,isindex:1,menu:1,noframes:1,ol:1,p:1,pre:1,table:1,ul:1}),z=a({area:1,base:1,basefont:1,br:1,col:1,command:1,dialog:1,embed:1,hr:1,img:1,input:1,isindex:1,keygen:1,link:1,meta:1,param:1,source:1,track:1,wbr:1});return a({$nonBodyContent:b(x,w,u),$block:y,$inline:n,$inlineWithA:b(a({a:1}),n),$body:b(a({script:1,style:1}),y),$cdata:a({script:1,style:1}),$empty:z,$nonChild:a({iframe:1,textarea:1}),$listItem:a({dd:1,dt:1,li:1}),$list:a({ul:1,ol:1,dl:1}),$isNotEmpty:a({table:1,ul:1,ol:1,dl:1,iframe:1,area:1,base:1,col:1,hr:1,img:1,embed:1,input:1,link:1,meta:1,param:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1}),$removeEmpty:a({a:1,abbr:1,acronym:1,address:1,b:1,bdo:1,big:1,cite:1,code:1,del:1,dfn:1,em:1,font:1,i:1,ins:1,label:1,kbd:1,q:1,s:1,samp:1,small:1,span:1,strike:1,strong:1,sub:1,sup:1,tt:1,u:1,"var":1}),$removeEmptyBlock:a({p:1,div:1}),$tableContent:a({caption:1,col:1,colgroup:1,tbody:1,td:1,tfoot:1,th:1,thead:1,tr:1,table:1}),$notTransContent:a({pre:1,script:1,style:1,textarea:1}),html:w,head:v,style:p,script:p,body:r,base:{},link:{},meta:{},title:p,col:{},tr:a({td:1,th:1}),img:{},embed:{},colgroup:a({thead:1,col:1,tbody:1,tr:1,tfoot:1}),noscript:r,td:r,br:{},th:r,center:r,kbd:n,button:b(k,g),basefont:{},h5:n,h4:n,samp:n,h6:n,ol:s,h1:n,h3:n,option:p,h2:n,form:b(c,f,g,k),select:a({optgroup:1,option:1}),font:n,ins:n,menu:s,abbr:n,label:n,table:a({thead:1,col:1,tbody:1,tr:1,colgroup:1,caption:1,tfoot:1}),code:n,tfoot:o,cite:n,li:r,input:{},iframe:r,strong:n,textarea:p,noframes:r,big:n,small:n,span:a({"#":1,br:1,b:1,strong:1,u:1,i:1,em:1,sub:1,sup:1,strike:1,span:1}),hr:n,dt:n,sub:n,optgroup:a({option:1}),param:{},bdo:n,"var":n,div:r,object:q,sup:n,dd:r,strike:n,area:{},dir:s,map:b(a({area:1,form:1,p:1}),c,h,g),applet:q,dl:a({dt:1,dd:1}),del:n,isindex:{},fieldset:b(a({legend:1}),m),thead:o,ul:s,acronym:n,b:n,a:b(a({a:1}),l),blockquote:b(a({td:1,tr:1,tbody:1,li:1}),r),caption:n,i:n,u:n,tbody:o,s:n,address:b(f,k),tt:n,legend:n,q:n,pre:b(i,e),p:b(a({a:1}),n),em:n,dfn:n})}(),attrFix=ie&&browser.version<9?{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder"}:{tabindex:"tabIndex",readonly:"readOnly"},styleBlock=utils.listToMap(["-webkit-box","-moz-box","block","list-item","table","table-row-group","table-header-group","table-footer-group","table-row","table-column-group","table-column","table-cell","table-caption"]),domUtils=dom.domUtils={NODE_ELEMENT:1,NODE_DOCUMENT:9,NODE_TEXT:3,NODE_COMMENT:8,NODE_DOCUMENT_FRAGMENT:11,POSITION_IDENTICAL:0,POSITION_DISCONNECTED:1,POSITION_FOLLOWING:2,POSITION_PRECEDING:4,POSITION_IS_CONTAINED:8,POSITION_CONTAINS:16,fillChar:ie&&"6"==browser.version?"\ufeff":"",keys:{8:1,46:1,16:1,17:1,18:1,37:1,38:1,39:1,40:1,13:1},getPosition:function(a,b){if(a===b)return 0;var c,d=[a],e=[b];for(c=a;c=c.parentNode;){if(c===b)return 10;d.push(c)}for(c=b;c=c.parentNode;){if(c===a)return 20;e.push(c)}if(d.reverse(),e.reverse(),d[0]!==e[0])return 1;for(var f=-1;f++,d[f]===e[f];);for(a=d[f],b=e[f];a=a.nextSibling;)if(a===b)return 4;return 2},getNodeIndex:function(a,b){for(var c=a,d=0;c=c.previousSibling;)b&&3==c.nodeType?c.nodeType!=c.nextSibling.nodeType&&d++:d++;return d},inDoc:function(a,b){return 10==domUtils.getPosition(a,b)},findParent:function(a,b,c){if(a&&!domUtils.isBody(a))for(a=c?a:a.parentNode;a;){if(!b||b(a)||domUtils.isBody(a))return b&&!b(a)&&domUtils.isBody(a)?null:a;a=a.parentNode}return null},findParentByTagName:function(a,b,c,d){return b=utils.listToMap(utils.isArray(b)?b:[b]),domUtils.findParent(a,function(a){return b[a.tagName]&&!(d&&d(a))},c)},findParents:function(a,b,c,d){for(var e=b&&(c&&c(a)||!c)?[a]:[];a=domUtils.findParent(a,c);)e.push(a);return d?e:e.reverse()},insertAfter:function(a,b){return a.nextSibling?a.parentNode.insertBefore(b,a.nextSibling):a.parentNode.appendChild(b)},remove:function(a,b){var c,d=a.parentNode;if(d){if(b&&a.hasChildNodes())for(;c=a.firstChild;)d.insertBefore(c,a);d.removeChild(a)}return a},getNextDomNode:function(a,b,c,d){return getDomNode(a,"firstChild","nextSibling",b,c,d)},getPreDomNode:function(a,b,c,d){return getDomNode(a,"lastChild","previousSibling",b,c,d)},isBookmarkNode:function(a){return 1==a.nodeType&&a.id&&/^_baidu_bookmark_/i.test(a.id)},getWindow:function(a){var b=a.ownerDocument||a;return b.defaultView||b.parentWindow},getCommonAncestor:function(a,b){if(a===b)return a;for(var c=[a],d=[b],e=a,f=-1;e=e.parentNode;){if(e===b)return e;c.push(e)}for(e=b;e=e.parentNode;){if(e===a)return e;d.push(e)}for(c.reverse(),d.reverse();f++,c[f]===d[f];);return 0==f?null:c[f-1]},clearEmptySibling:function(a,b,c){function d(a,b){for(var c;a&&!domUtils.isBookmarkNode(a)&&(domUtils.isEmptyInlineElement(a)||!new RegExp("[^\t\n\r"+domUtils.fillChar+"]").test(a.nodeValue));)c=a[b],domUtils.remove(a),a=c}!b&&d(a.nextSibling,"nextSibling"),!c&&d(a.previousSibling,"previousSibling")},split:function(a,b){var c=a.ownerDocument;if(browser.ie&&b==a.nodeValue.length){var d=c.createTextNode("");return domUtils.insertAfter(a,d)}var e=a.splitText(b);if(browser.ie8){var f=c.createTextNode("");domUtils.insertAfter(e,f),domUtils.remove(f)}return e},isWhitespace:function(a){return!new RegExp("[^ \t\n\r"+domUtils.fillChar+"]").test(a.nodeValue)},getXY:function(a){for(var b=0,c=0;a.offsetParent;)c+=a.offsetTop,b+=a.offsetLeft,a=a.offsetParent;return{x:b,y:c}},on:function(a,b,c){var d=utils.isArray(b)?b:utils.trim(b).split(/\s+/),e=d.length;if(e)for(;e--;)if(b=d[e],a.addEventListener)a.addEventListener(b,c,!1);else{c._d||(c._d={els:[]});var f=b+c.toString(),g=utils.indexOf(c._d.els,a);c._d[f]&&g!=-1||(g==-1&&c._d.els.push(a),c._d[f]||(c._d[f]=function(a){return c.call(a.srcElement,a||window.event)}),a.attachEvent("on"+b,c._d[f]))}a=null},un:function(a,b,c){var d=utils.isArray(b)?b:utils.trim(b).split(/\s+/),e=d.length;if(e)for(;e--;)if(b=d[e],a.removeEventListener)a.removeEventListener(b,c,!1);else{var f=b+c.toString();try{a.detachEvent("on"+b,c._d?c._d[f]:c)}catch(g){}if(c._d&&c._d[f]){var h=utils.indexOf(c._d.els,a);h!=-1&&c._d.els.splice(h,1),0==c._d.els.length&&delete c._d[f]}}},isSameElement:function(a,b){if(a.tagName!=b.tagName)return!1;var c=a.attributes,d=b.attributes;if(!ie&&c.length!=d.length)return!1;for(var e,f,g=0,h=0,i=0;e=c[i++];){if("style"==e.nodeName){if(e.specified&&g++,domUtils.isSameStyle(a,b))continue;return!1}if(ie){if(!e.specified)continue;g++,f=d.getNamedItem(e.nodeName)}else f=b.attributes[e.nodeName];if(!f.specified||e.nodeValue!=f.nodeValue)return!1}if(ie){for(i=0;f=d[i++];)f.specified&&h++;if(g!=h)return!1}return!0},isSameStyle:function(a,b){var c=a.style.cssText.replace(/( ?; ?)/g,";").replace(/( ?: ?)/g,":"),d=b.style.cssText.replace(/( ?; ?)/g,";").replace(/( ?: ?)/g,":");if(browser.opera){if(c=a.style,d=b.style,c.length!=d.length)return!1;for(var e in c)if(!/^(\d+|csstext)$/i.test(e)&&c[e]!=d[e])return!1;return!0}if(!c||!d)return c==d;if(c=c.split(";"),d=d.split(";"),c.length!=d.length)return!1;for(var f,g=0;f=c[g++];)if(utils.indexOf(d,f)==-1)return!1;return!0},isBlockElm:function(a){return 1==a.nodeType&&(dtd.$block[a.tagName]||styleBlock[domUtils.getComputedStyle(a,"display")])&&!dtd.$nonChild[a.tagName]},isBody:function(a){return a&&1==a.nodeType&&"body"==a.tagName.toLowerCase()},breakParent:function(a,b){var c,d,e,f=a,g=a;do{for(f=f.parentNode,d?(c=f.cloneNode(!1),c.appendChild(d),d=c,c=f.cloneNode(!1),c.appendChild(e),e=c):(d=f.cloneNode(!1),e=d.cloneNode(!1));c=g.previousSibling;)d.insertBefore(c,d.firstChild);for(;c=g.nextSibling;)e.appendChild(c);g=f}while(b!==f);return c=b.parentNode,c.insertBefore(d,b),c.insertBefore(e,b),c.insertBefore(a,e),domUtils.remove(b),a},isEmptyInlineElement:function(a){if(1!=a.nodeType||!dtd.$removeEmpty[a.tagName])return 0;for(a=a.firstChild;a;){if(domUtils.isBookmarkNode(a))return 0;if(1==a.nodeType&&!domUtils.isEmptyInlineElement(a)||3==a.nodeType&&!domUtils.isWhitespace(a))return 0;a=a.nextSibling}return 1},trimWhiteTextNode:function(a){function b(b){for(var c;(c=a[b])&&3==c.nodeType&&domUtils.isWhitespace(c);)a.removeChild(c)}b("firstChild"),b("lastChild")},mergeChild:function(a,b,c){for(var d,e=domUtils.getElementsByTagName(a,a.tagName.toLowerCase()),f=0;d=e[f++];)if(d.parentNode&&!domUtils.isBookmarkNode(d))if("span"!=d.tagName.toLowerCase())domUtils.isSameElement(a,d)&&domUtils.remove(d,!0);else{if(a===d.parentNode&&(domUtils.trimWhiteTextNode(a),1==a.childNodes.length)){a.style.cssText=d.style.cssText+";"+a.style.cssText,domUtils.remove(d,!0);continue}if(d.style.cssText=a.style.cssText+";"+d.style.cssText,c){var g=c.style;if(g){g=g.split(";");for(var h,i=0;h=g[i++];)d.style[utils.cssStyleToDomStyle(h.split(":")[0])]=h.split(":")[1]}}domUtils.isSameStyle(d,a)&&domUtils.remove(d,!0)}},getElementsByTagName:function(a,b,c){if(c&&utils.isString(c)){var d=c;c=function(a){return domUtils.hasClass(a,d)}}b=utils.trim(b).replace(/[ ]{2,}/g," ").split(" ");for(var e,f=[],g=0;e=b[g++];)for(var h,i=a.getElementsByTagName(e),j=0;h=i[j++];)c&&!c(h)||f.push(h);return f},mergeToParent:function(a){for(var b=a.parentNode;b&&dtd.$removeEmpty[b.tagName];){if(b.tagName==a.tagName||"A"==b.tagName){if(domUtils.trimWhiteTextNode(b),"SPAN"==b.tagName&&!domUtils.isSameStyle(b,a)||"A"==b.tagName&&"SPAN"==a.tagName){if(b.childNodes.length>1||b!==a.parentNode){a.style.cssText=b.style.cssText+";"+a.style.cssText,b=b.parentNode;continue}b.style.cssText+=";"+a.style.cssText,"A"==b.tagName&&(b.style.textDecoration="underline")}if("A"!=b.tagName){b===a.parentNode&&domUtils.remove(a,!0);break}}b=b.parentNode}},mergeSibling:function(a,b,c){function d(a,b,c){var d;if((d=c[a])&&!domUtils.isBookmarkNode(d)&&1==d.nodeType&&domUtils.isSameElement(c,d)){for(;d.firstChild;)"firstChild"==b?c.insertBefore(d.lastChild,c.firstChild):c.appendChild(d.firstChild);domUtils.remove(d)}}!b&&d("previousSibling","firstChild",a),!c&&d("nextSibling","lastChild",a)},unSelectable:ie&&browser.ie9below||browser.opera?function(a){a.onselectstart=function(){return!1},a.onclick=a.onkeyup=a.onkeydown=function(){return!1},a.unselectable="on",a.setAttribute("unselectable","on");for(var b,c=0;b=a.all[c++];)switch(b.tagName.toLowerCase()){case"iframe":case"textarea":case"input":case"select":break;default:b.unselectable="on",a.setAttribute("unselectable","on")}}:function(a){a.style.MozUserSelect=a.style.webkitUserSelect=a.style.msUserSelect=a.style.KhtmlUserSelect="none"},removeAttributes:function(a,b){b=utils.isArray(b)?b:utils.trim(b).replace(/[ ]{2,}/g," ").split(" ");for(var c,d=0;c=b[d++];){switch(c=attrFix[c]||c){case"className":a[c]="";break;case"style":a.style.cssText="";var e=a.getAttributeNode("style");!browser.ie&&e&&a.removeAttributeNode(e)}a.removeAttribute(c)}},createElement:function(a,b,c){return domUtils.setAttributes(a.createElement(b),c)},setAttributes:function(a,b){for(var c in b)if(b.hasOwnProperty(c)){var d=b[c];switch(c){case"class":a.className=d;break;case"style":a.style.cssText=a.style.cssText+";"+d;break;case"innerHTML":a[c]=d;break;case"value":a.value=d;break;default:a.setAttribute(attrFix[c]||c,d)}}return a},getComputedStyle:function(a,b){var c="width height top left";if(c.indexOf(b)>-1)return a["offset"+b.replace(/^\w/,function(a){return a.toUpperCase()})]+"px";if(3==a.nodeType&&(a=a.parentNode),browser.ie&&browser.version<9&&"font-size"==b&&!a.style.fontSize&&!dtd.$empty[a.tagName]&&!dtd.$nonChild[a.tagName]){var d=a.ownerDocument.createElement("span");d.style.cssText="padding:0;border:0;font-family:simsun;",d.innerHTML=".",a.appendChild(d);var e=d.offsetHeight;return a.removeChild(d),d=null,e+"px"}try{var f=domUtils.getStyle(a,b)||(window.getComputedStyle?domUtils.getWindow(a).getComputedStyle(a,"").getPropertyValue(b):(a.currentStyle||a.style)[utils.cssStyleToDomStyle(b)])}catch(g){return""}return utils.transUnitToPx(utils.fixColor(b,f))},removeClasses:function(a,b){b=utils.isArray(b)?b:utils.trim(b).replace(/[ ]{2,}/g," ").split(" ");for(var c,d=0,e=a.className;c=b[d++];)e=e.replace(new RegExp("\\b"+c+"\\b"),"");e=utils.trim(e).replace(/[ ]{2,}/g," "),e?a.className=e:domUtils.removeAttributes(a,["class"])},addClass:function(a,b){if(a){b=utils.trim(b).replace(/[ ]{2,}/g," ").split(" ");for(var c,d=0,e=a.className;c=b[d++];)new RegExp("\\b"+c+"\\b").test(e)||(e+=" "+c);a.className=utils.trim(e)}},hasClass:function(a,b){if(utils.isRegExp(b))return b.test(a.className);b=utils.trim(b).replace(/[ ]{2,}/g," ").split(" ");for(var c,d=0,e=a.className;c=b[d++];)if(!new RegExp("\\b"+c+"\\b","i").test(e))return!1;return d-1==b.length},preventDefault:function(a){a.preventDefault?a.preventDefault():a.returnValue=!1},removeStyle:function(a,b){browser.ie?("color"==b&&(b="(^|;)"+b),a.style.cssText=a.style.cssText.replace(new RegExp(b+"[^:]*:[^;]+;?","ig"),"")):a.style.removeProperty?a.style.removeProperty(b):a.style.removeAttribute(utils.cssStyleToDomStyle(b)),a.style.cssText||domUtils.removeAttributes(a,["style"])},getStyle:function(a,b){var c=a.style[utils.cssStyleToDomStyle(b)];return utils.fixColor(b,c)},setStyle:function(a,b,c){a.style[utils.cssStyleToDomStyle(b)]=c,utils.trim(a.style.cssText)||this.removeAttributes(a,"style")},setStyles:function(a,b){for(var c in b)b.hasOwnProperty(c)&&domUtils.setStyle(a,c,b[c])},removeDirtyAttr:function(a){for(var b,c=0,d=a.getElementsByTagName("*");b=d[c++];)b.removeAttribute("_moz_dirty");a.removeAttribute("_moz_dirty")},getChildCount:function(a,b){var c=0,d=a.firstChild;for(b=b||function(){return 1};d;)b(d)&&c++,d=d.nextSibling;return c},isEmptyNode:function(a){return!a.firstChild||0==domUtils.getChildCount(a,function(a){return!domUtils.isBr(a)&&!domUtils.isBookmarkNode(a)&&!domUtils.isWhitespace(a)})},clearSelectedArr:function(a){for(var b;b=a.pop();)domUtils.removeAttributes(b,["class"])},scrollToView:function(a,b,c){var d=function(){var a=b.document,c="CSS1Compat"==a.compatMode;return{width:(c?a.documentElement.clientWidth:a.body.clientWidth)||0,height:(c?a.documentElement.clientHeight:a.body.clientHeight)||0}},e=function(a){if("pageXOffset"in a)return{x:a.pageXOffset||0,y:a.pageYOffset||0};var b=a.document;return{x:b.documentElement.scrollLeft||b.body.scrollLeft||0,y:b.documentElement.scrollTop||b.body.scrollTop||0}},f=d().height,g=f*-1+c;g+=a.offsetHeight||0;var h=domUtils.getXY(a);g+=h.y;var i=e(b).y;(g>i||g<i-f)&&b.scrollTo(0,g+(g<0?-20:20))},isBr:function(a){return 1==a.nodeType&&"BR"==a.tagName},isFillChar:function(a,b){if(3!=a.nodeType)return!1;var c=a.nodeValue;return b?new RegExp("^"+domUtils.fillChar).test(c):!c.replace(new RegExp(domUtils.fillChar,"g"),"").length},isStartInblock:function(a){var b,c=a.cloneRange(),d=0,e=c.startContainer;if(1==e.nodeType&&e.childNodes[c.startOffset]){e=e.childNodes[c.startOffset];for(var f=e.previousSibling;f&&domUtils.isFillChar(f);)e=f,f=f.previousSibling}for(this.isFillChar(e,!0)&&1==c.startOffset&&(c.setStartBefore(e),e=c.startContainer);e&&domUtils.isFillChar(e);)b=e,e=e.previousSibling;for(b&&(c.setStartBefore(b),e=c.startContainer),1==e.nodeType&&domUtils.isEmptyNode(e)&&1==c.startOffset&&c.setStart(e,0).collapse(!0);!c.startOffset;){if(e=c.startContainer,domUtils.isBlockElm(e)||domUtils.isBody(e)){d=1;break}var g,f=c.startContainer.previousSibling;if(f){for(;f&&domUtils.isFillChar(f);)g=f,f=f.previousSibling;g?c.setStartBefore(g):c.setStartBefore(c.startContainer)}else c.setStartBefore(c.startContainer)}return d&&!domUtils.isBody(c.startContainer)?1:0},isEmptyBlock:function(a,b){if(1!=a.nodeType)return 0;if(b=b||new RegExp("[ \t\r\n"+domUtils.fillChar+"]","g"),a[browser.ie?"innerText":"textContent"].replace(b,"").length>0)return 0;for(var c in dtd.$isNotEmpty)if(a.getElementsByTagName(c).length)return 0;return 1},setViewportOffset:function(a,b){var c=0|parseInt(a.style.left),d=0|parseInt(a.style.top),e=a.getBoundingClientRect(),f=b.left-e.left,g=b.top-e.top;f&&(a.style.left=c+f+"px"),g&&(a.style.top=d+g+"px")},fillNode:function(a,b){var c=browser.ie?a.createTextNode(domUtils.fillChar):a.createElement("br");b.innerHTML="",b.appendChild(c)},moveChild:function(a,b,c){for(;a.firstChild;)c&&b.firstChild?b.insertBefore(a.lastChild,b.firstChild):b.appendChild(a.firstChild)},hasNoAttributes:function(a){return browser.ie?/^<\w+\s*?>/.test(a.outerHTML):0==a.attributes.length},isCustomeNode:function(a){return 1==a.nodeType&&a.getAttribute("_ue_custom_node_")},isTagNode:function(a,b){return 1==a.nodeType&&new RegExp("\\b"+a.tagName+"\\b","i").test(b)},filterNodeList:function(a,b,c){var d=[];if(!utils.isFunction(b)){var e=b;b=function(a){return utils.indexOf(utils.isArray(e)?e:e.split(" "),a.tagName.toLowerCase())!=-1}}return utils.each(a,function(a){b(a)&&d.push(a)}),0==d.length?null:1!=d.length&&c?d:d[0]},isInNodeEndBoundary:function(a,b){var c=a.startContainer;if(3==c.nodeType&&a.startOffset!=c.nodeValue.length)return 0;if(1==c.nodeType&&a.startOffset!=c.childNodes.length)return 0;for(;c!==b;){if(c.nextSibling)return 0;c=c.parentNode}return 1},isBoundaryNode:function(a,b){for(var c;!domUtils.isBody(a);)if(c=a,a=a.parentNode,c!==a[b])return!1;return!0},fillHtml:browser.ie11below?" ":"<br/>"},fillCharReg=new RegExp(domUtils.fillChar,"g");!function(){function a(a){a.collapsed=a.startContainer&&a.endContainer&&a.startContainer===a.endContainer&&a.startOffset==a.endOffset}function b(a){return!a.collapsed&&1==a.startContainer.nodeType&&a.startContainer===a.endContainer&&a.endOffset-a.startOffset==1}function c(b,c,d,e){return 1==c.nodeType&&(dtd.$empty[c.tagName]||dtd.$nonChild[c.tagName])&&(d=domUtils.getNodeIndex(c)+(b?0:1),c=c.parentNode),b?(e.startContainer=c,e.startOffset=d,e.endContainer||e.collapse(!0)):(e.endContainer=c,e.endOffset=d,e.startContainer||e.collapse(!1)),a(e),e}function d(a,b){var c,d,e=a.startContainer,f=a.endContainer,g=a.startOffset,h=a.endOffset,i=a.document,j=i.createDocumentFragment();if(1==e.nodeType&&(e=e.childNodes[g]||(c=e.appendChild(i.createTextNode("")))),1==f.nodeType&&(f=f.childNodes[h]||(d=f.appendChild(i.createTextNode("")))),e===f&&3==e.nodeType)return j.appendChild(i.createTextNode(e.substringData(g,h-g))),b&&(e.deleteData(g,h-g),a.collapse(!0)),j;for(var k,l,m=j,n=domUtils.findParents(e,!0),o=domUtils.findParents(f,!0),p=0;n[p]==o[p];)p++;for(var q,r=p;q=n[r];r++){for(k=q.nextSibling,q==e?c||(3==a.startContainer.nodeType?(m.appendChild(i.createTextNode(e.nodeValue.slice(g))),b&&e.deleteData(g,e.nodeValue.length-g)):m.appendChild(b?e:e.cloneNode(!0))):(l=q.cloneNode(!1),m.appendChild(l));k&&k!==f&&k!==o[r];)q=k.nextSibling,m.appendChild(b?k:k.cloneNode(!0)),k=q;m=l}m=j,n[p]||(m.appendChild(n[p-1].cloneNode(!1)),m=m.firstChild);for(var s,r=p;s=o[r];r++){if(k=s.previousSibling,s==f?d||3!=a.endContainer.nodeType||(m.appendChild(i.createTextNode(f.substringData(0,h))),b&&f.deleteData(0,h)):(l=s.cloneNode(!1),m.appendChild(l)),r!=p||!n[p])for(;k&&k!==e;)s=k.previousSibling,m.insertBefore(b?k:k.cloneNode(!0),m.firstChild),k=s;m=l}return b&&a.setStartBefore(o[p]?n[p]?o[p]:n[p-1]:o[p-1]).collapse(!0),c&&domUtils.remove(c),d&&domUtils.remove(d),j}function e(a,b){try{if(g&&domUtils.inDoc(g,a))if(g.nodeValue.replace(fillCharReg,"").length)g.nodeValue=g.nodeValue.replace(fillCharReg,"");else{var c=g.parentNode;for(domUtils.remove(g);c&&domUtils.isEmptyInlineElement(c)&&(browser.safari?!(domUtils.getPosition(c,b)&domUtils.POSITION_CONTAINS):!c.contains(b));)g=c.parentNode,domUtils.remove(c),c=g}}catch(d){}
}function f(a,b){var c;for(a=a[b];a&&domUtils.isFillChar(a);)c=a[b],domUtils.remove(a),a=c}var g,h=0,i=domUtils.fillChar,j=dom.Range=function(a){var b=this;b.startContainer=b.startOffset=b.endContainer=b.endOffset=null,b.document=a,b.collapsed=!0};j.prototype={cloneContents:function(){return this.collapsed?null:d(this,0)},deleteContents:function(){var a;return this.collapsed||d(this,1),browser.webkit&&(a=this.startContainer,3!=a.nodeType||a.nodeValue.length||(this.setStartBefore(a).collapse(!0),domUtils.remove(a))),this},extractContents:function(){return this.collapsed?null:d(this,2)},setStart:function(a,b){return c(!0,a,b,this)},setEnd:function(a,b){return c(!1,a,b,this)},setStartAfter:function(a){return this.setStart(a.parentNode,domUtils.getNodeIndex(a)+1)},setStartBefore:function(a){return this.setStart(a.parentNode,domUtils.getNodeIndex(a))},setEndAfter:function(a){return this.setEnd(a.parentNode,domUtils.getNodeIndex(a)+1)},setEndBefore:function(a){return this.setEnd(a.parentNode,domUtils.getNodeIndex(a))},setStartAtFirst:function(a){return this.setStart(a,0)},setStartAtLast:function(a){return this.setStart(a,3==a.nodeType?a.nodeValue.length:a.childNodes.length)},setEndAtFirst:function(a){return this.setEnd(a,0)},setEndAtLast:function(a){return this.setEnd(a,3==a.nodeType?a.nodeValue.length:a.childNodes.length)},selectNode:function(a){return this.setStartBefore(a).setEndAfter(a)},selectNodeContents:function(a){return this.setStart(a,0).setEndAtLast(a)},cloneRange:function(){var a=this;return new j(a.document).setStart(a.startContainer,a.startOffset).setEnd(a.endContainer,a.endOffset)},collapse:function(a){var b=this;return a?(b.endContainer=b.startContainer,b.endOffset=b.startOffset):(b.startContainer=b.endContainer,b.startOffset=b.endOffset),b.collapsed=!0,b},shrinkBoundary:function(a){function b(a){return 1==a.nodeType&&!domUtils.isBookmarkNode(a)&&!dtd.$empty[a.tagName]&&!dtd.$nonChild[a.tagName]}for(var c,d=this,e=d.collapsed;1==d.startContainer.nodeType&&(c=d.startContainer.childNodes[d.startOffset])&&b(c);)d.setStart(c,0);if(e)return d.collapse(!0);if(!a)for(;1==d.endContainer.nodeType&&d.endOffset>0&&(c=d.endContainer.childNodes[d.endOffset-1])&&b(c);)d.setEnd(c,c.childNodes.length);return d},getCommonAncestor:function(a,c){var d=this,e=d.startContainer,f=d.endContainer;return e===f?a&&b(this)&&(e=e.childNodes[d.startOffset],1==e.nodeType)?e:c&&3==e.nodeType?e.parentNode:e:domUtils.getCommonAncestor(e,f)},trimBoundary:function(a){this.txtToElmBoundary();var b=this.startContainer,c=this.startOffset,d=this.collapsed,e=this.endContainer;if(3==b.nodeType){if(0==c)this.setStartBefore(b);else if(c>=b.nodeValue.length)this.setStartAfter(b);else{var f=domUtils.split(b,c);b===e?this.setEnd(f,this.endOffset-c):b.parentNode===e&&(this.endOffset+=1),this.setStartBefore(f)}if(d)return this.collapse(!0)}return a||(c=this.endOffset,e=this.endContainer,3==e.nodeType&&(0==c?this.setEndBefore(e):(c<e.nodeValue.length&&domUtils.split(e,c),this.setEndAfter(e)))),this},txtToElmBoundary:function(a){function b(a,b){var c=a[b+"Container"],d=a[b+"Offset"];3==c.nodeType&&(d?d>=c.nodeValue.length&&a["set"+b.replace(/(\w)/,function(a){return a.toUpperCase()})+"After"](c):a["set"+b.replace(/(\w)/,function(a){return a.toUpperCase()})+"Before"](c))}return!a&&this.collapsed||(b(this,"start"),b(this,"end")),this},insertNode:function(a){var b=a,c=1;11==a.nodeType&&(b=a.firstChild,c=a.childNodes.length),this.trimBoundary(!0);var d=this.startContainer,e=this.startOffset,f=d.childNodes[e];return f?d.insertBefore(a,f):d.appendChild(a),b.parentNode===this.endContainer&&(this.endOffset=this.endOffset+c),this.setStartBefore(b)},setCursor:function(a,b){return this.collapse(!a).select(b)},createBookmark:function(a,b){var c,d=this.document.createElement("span");return d.style.cssText="display:none;line-height:0px;",d.appendChild(this.document.createTextNode("")),d.id="_baidu_bookmark_start_"+(b?"":h++),this.collapsed||(c=d.cloneNode(!0),c.id="_baidu_bookmark_end_"+(b?"":h++)),this.insertNode(d),c&&this.collapse().insertNode(c).setEndBefore(c),this.setStartAfter(d),{start:a?d.id:d,end:c?a?c.id:c:null,id:a}},moveToBookmark:function(a){var b=a.id?this.document.getElementById(a.start):a.start,c=a.end&&a.id?this.document.getElementById(a.end):a.end;return this.setStartBefore(b),domUtils.remove(b),c?(this.setEndBefore(c),domUtils.remove(c)):this.collapse(!0),this},enlarge:function(a,b){var c,d,e=domUtils.isBody,f=this.document.createTextNode("");if(a){for(d=this.startContainer,1==d.nodeType?d.childNodes[this.startOffset]?c=d=d.childNodes[this.startOffset]:(d.appendChild(f),c=d=f):c=d;;){if(domUtils.isBlockElm(d)){for(d=c;(c=d.previousSibling)&&!domUtils.isBlockElm(c);)d=c;this.setStartBefore(d);break}c=d,d=d.parentNode}for(d=this.endContainer,1==d.nodeType?((c=d.childNodes[this.endOffset])?d.insertBefore(f,c):d.appendChild(f),c=d=f):c=d;;){if(domUtils.isBlockElm(d)){for(d=c;(c=d.nextSibling)&&!domUtils.isBlockElm(c);)d=c;this.setEndAfter(d);break}c=d,d=d.parentNode}f.parentNode===this.endContainer&&this.endOffset--,domUtils.remove(f)}if(!this.collapsed){for(;!(0!=this.startOffset||b&&b(this.startContainer)||e(this.startContainer));)this.setStartBefore(this.startContainer);for(;!(this.endOffset!=(1==this.endContainer.nodeType?this.endContainer.childNodes.length:this.endContainer.nodeValue.length)||b&&b(this.endContainer)||e(this.endContainer));)this.setEndAfter(this.endContainer)}return this},enlargeToBlockElm:function(a){for(;!domUtils.isBlockElm(this.startContainer);)this.setStartBefore(this.startContainer);if(!a)for(;!domUtils.isBlockElm(this.endContainer);)this.setEndAfter(this.endContainer);return this},adjustmentBoundary:function(){if(!this.collapsed){for(;!domUtils.isBody(this.startContainer)&&this.startOffset==this.startContainer[3==this.startContainer.nodeType?"nodeValue":"childNodes"].length&&this.startContainer[3==this.startContainer.nodeType?"nodeValue":"childNodes"].length;)this.setStartAfter(this.startContainer);for(;!domUtils.isBody(this.endContainer)&&!this.endOffset&&this.endContainer[3==this.endContainer.nodeType?"nodeValue":"childNodes"].length;)this.setEndBefore(this.endContainer)}return this},applyInlineStyle:function(a,b,c){if(this.collapsed)return this;this.trimBoundary().enlarge(!1,function(a){return 1==a.nodeType&&domUtils.isBlockElm(a)}).adjustmentBoundary();for(var d,e,f=this.createBookmark(),g=f.end,h=function(a){return 1==a.nodeType?"br"!=a.tagName.toLowerCase():!domUtils.isWhitespace(a)},i=domUtils.getNextDomNode(f.start,!1,h),j=this.cloneRange();i&&domUtils.getPosition(i,g)&domUtils.POSITION_PRECEDING;)if(3==i.nodeType||dtd[a][i.tagName]){for(j.setStartBefore(i),d=i;d&&(3==d.nodeType||dtd[a][d.tagName])&&d!==g;)e=d,d=domUtils.getNextDomNode(d,1==d.nodeType,null,function(b){return dtd[a][b.tagName]});var k,l=j.setEndAfter(e).extractContents();if(c&&c.length>0){var m,n;n=m=c[0].cloneNode(!1);for(var o,p=1;o=c[p++];)m.appendChild(o.cloneNode(!1)),m=m.firstChild;k=m}else k=j.document.createElement(a);b&&domUtils.setAttributes(k,b),k.appendChild(l),j.insertNode(c?n:k);var q;if("span"==a&&b.style&&/text\-decoration/.test(b.style)&&(q=domUtils.findParentByTagName(k,"a",!0))?(domUtils.setAttributes(q,b),domUtils.remove(k,!0),k=q):(domUtils.mergeSibling(k),domUtils.clearEmptySibling(k)),domUtils.mergeChild(k,b),i=domUtils.getNextDomNode(k,!1,h),domUtils.mergeToParent(k),d===g)break}else i=domUtils.getNextDomNode(i,!0,h);return this.moveToBookmark(f)},removeInlineStyle:function(a){if(this.collapsed)return this;a=utils.isArray(a)?a:[a],this.shrinkBoundary().adjustmentBoundary();for(var b=this.startContainer,c=this.endContainer;;){if(1==b.nodeType){if(utils.indexOf(a,b.tagName.toLowerCase())>-1)break;if("body"==b.tagName.toLowerCase()){b=null;break}}b=b.parentNode}for(;;){if(1==c.nodeType){if(utils.indexOf(a,c.tagName.toLowerCase())>-1)break;if("body"==c.tagName.toLowerCase()){c=null;break}}c=c.parentNode}var d,e,f=this.createBookmark();b&&(e=this.cloneRange().setEndBefore(f.start).setStartBefore(b),d=e.extractContents(),e.insertNode(d),domUtils.clearEmptySibling(b,!0),b.parentNode.insertBefore(f.start,b)),c&&(e=this.cloneRange().setStartAfter(f.end).setEndAfter(c),d=e.extractContents(),e.insertNode(d),domUtils.clearEmptySibling(c,!1,!0),c.parentNode.insertBefore(f.end,c.nextSibling));for(var g,h=domUtils.getNextDomNode(f.start,!1,function(a){return 1==a.nodeType});h&&h!==f.end;)g=domUtils.getNextDomNode(h,!0,function(a){return 1==a.nodeType}),utils.indexOf(a,h.tagName.toLowerCase())>-1&&domUtils.remove(h,!0),h=g;return this.moveToBookmark(f)},getClosedNode:function(){var a;if(!this.collapsed){var c=this.cloneRange().adjustmentBoundary().shrinkBoundary();if(b(c)){var d=c.startContainer.childNodes[c.startOffset];d&&1==d.nodeType&&(dtd.$empty[d.tagName]||dtd.$nonChild[d.tagName])&&(a=d)}}return a},select:browser.ie?function(a,b){var c;this.collapsed||this.shrinkBoundary();var d=this.getClosedNode();if(d&&!b){try{c=this.document.body.createControlRange(),c.addElement(d),c.select()}catch(h){}return this}var j,k=this.createBookmark(),l=k.start;if(c=this.document.body.createTextRange(),c.moveToElementText(l),c.moveStart("character",1),this.collapsed){if(!a&&3!=this.startContainer.nodeType){var m=this.document.createTextNode(i),n=this.document.createElement("span");n.appendChild(this.document.createTextNode(i)),l.parentNode.insertBefore(n,l),l.parentNode.insertBefore(m,l),e(this.document,m),g=m,f(n,"previousSibling"),f(l,"nextSibling"),c.moveStart("character",-1),c.collapse(!0)}}else{var o=this.document.body.createTextRange();j=k.end,o.moveToElementText(j),c.setEndPoint("EndToEnd",o)}this.moveToBookmark(k),n&&domUtils.remove(n);try{c.select()}catch(h){}return this}:function(a){function b(a){function b(b,c,d){3==b.nodeType&&b.nodeValue.length<c&&(a[d+"Offset"]=b.nodeValue.length)}b(a.startContainer,a.startOffset,"start"),b(a.endContainer,a.endOffset,"end")}var c,d=domUtils.getWindow(this.document),h=d.getSelection();if(browser.gecko?this.document.body.focus():d.focus(),h){if(h.removeAllRanges(),this.collapsed&&!a){var j=this.startContainer,k=j;1==j.nodeType&&(k=j.childNodes[this.startOffset]),3==j.nodeType&&this.startOffset||(k?k.previousSibling&&3==k.previousSibling.nodeType:j.lastChild&&3==j.lastChild.nodeType)||(c=this.document.createTextNode(i),this.insertNode(c),e(this.document,c),f(c,"previousSibling"),f(c,"nextSibling"),g=c,this.setStart(c,browser.webkit?1:0).collapse(!0))}var l=this.document.createRange();if(this.collapsed&&browser.opera&&1==this.startContainer.nodeType){var k=this.startContainer.childNodes[this.startOffset];if(k){for(;k&&domUtils.isBlockElm(k)&&1==k.nodeType&&k.childNodes[0];)k=k.childNodes[0];k&&this.setStartBefore(k).collapse(!0)}else k=this.startContainer.lastChild,k&&domUtils.isBr(k)&&this.setStartBefore(k).collapse(!0)}b(this),l.setStart(this.startContainer,this.startOffset),l.setEnd(this.endContainer,this.endOffset),h.addRange(l)}return this},scrollToView:function(a,b){a=a?window:domUtils.getWindow(this.document);var c=this,d=c.document.createElement("span");return d.innerHTML=" ",c.cloneRange().insertNode(d),domUtils.scrollToView(d,a,b),domUtils.remove(d),c},inFillChar:function(){var a=this.startContainer;return!(!this.collapsed||3!=a.nodeType||a.nodeValue.replace(new RegExp("^"+domUtils.fillChar),"").length+1!=a.nodeValue.length)},createAddress:function(a,b){function c(a){for(var c,d=a?e.startContainer:e.endContainer,f=domUtils.findParents(d,!0,function(a){return!domUtils.isBody(a)}),g=[],h=0;c=f[h++];)g.push(domUtils.getNodeIndex(c,b));var i=0;if(b)if(3==d.nodeType){for(var j=d.previousSibling;j&&3==j.nodeType;)i+=j.nodeValue.replace(fillCharReg,"").length,j=j.previousSibling;i+=a?e.startOffset:e.endOffset}else if(d=d.childNodes[a?e.startOffset:e.endOffset])i=domUtils.getNodeIndex(d,b);else{d=a?e.startContainer:e.endContainer;for(var k=d.firstChild;k;)if(domUtils.isFillChar(k))k=k.nextSibling;else if(i++,3==k.nodeType)for(;k&&3==k.nodeType;)k=k.nextSibling;else k=k.nextSibling}else i=a?domUtils.isFillChar(d)?0:e.startOffset:e.endOffset;return i<0&&(i=0),g.push(i),g}var d={},e=this;return d.startAddress=c(!0),a||(d.endAddress=e.collapsed?[].concat(d.startAddress):c()),d},moveToAddress:function(a,b){function c(a,b){for(var c,e,f,g=d.document.body,h=0,i=a.length;h<i;h++)if(f=a[h],c=g,g=g.childNodes[f],!g){e=f;break}b?g?d.setStartBefore(g):d.setStart(c,e):g?d.setEndBefore(g):d.setEnd(c,e)}var d=this;return c(a.startAddress,!0),!b&&a.endAddress&&c(a.endAddress),d},equals:function(a){for(var b in this)if(this.hasOwnProperty(b)&&this[b]!==a[b])return!1;return!0},traversal:function(a,b){if(this.collapsed)return this;for(var c=this.createBookmark(),d=c.end,e=domUtils.getNextDomNode(c.start,!1,b);e&&e!==d&&domUtils.getPosition(e,d)&domUtils.POSITION_PRECEDING;){var f=domUtils.getNextDomNode(e,!1,b);a(e),e=f}return this.moveToBookmark(c)}}}(),function(){function a(a,b){var c=domUtils.getNodeIndex;a=a.duplicate(),a.collapse(b);var d=a.parentElement();if(!d.hasChildNodes())return{container:d,offset:0};for(var e,f,g=d.children,h=a.duplicate(),i=0,j=g.length-1,k=-1;i<=j;){k=Math.floor((i+j)/2),e=g[k],h.moveToElementText(e);var l=h.compareEndPoints("StartToStart",a);if(l>0)j=k-1;else{if(!(l<0))return{container:d,offset:c(e)};i=k+1}}if(k==-1){if(h.moveToElementText(d),h.setEndPoint("StartToStart",a),f=h.text.replace(/(\r\n|\r)/g,"\n").length,g=d.childNodes,!f)return e=g[g.length-1],{container:e,offset:e.nodeValue.length};for(var m=g.length;f>0;)f-=g[--m].nodeValue.length;return{container:g[m],offset:-f}}if(h.collapse(l>0),h.setEndPoint(l>0?"StartToStart":"EndToStart",a),f=h.text.replace(/(\r\n|\r)/g,"\n").length,!f)return dtd.$empty[e.tagName]||dtd.$nonChild[e.tagName]?{container:d,offset:c(e)+(l>0?0:1)}:{container:e,offset:l>0?0:e.childNodes.length};for(;f>0;)try{var n=e;e=e[l>0?"previousSibling":"nextSibling"],f-=e.nodeValue.length}catch(o){return{container:d,offset:c(n)}}return{container:e,offset:l>0?-f:e.nodeValue.length+f}}function b(b,c){if(b.item)c.selectNode(b.item(0));else{var d=a(b,!0);c.setStart(d.container,d.offset),0!=b.compareEndPoints("StartToEnd",b)&&(d=a(b,!1),c.setEnd(d.container,d.offset))}return c}function c(a){var b;try{b=a.getNative().createRange()}catch(c){return null}var d=b.item?b.item(0):b.parentElement();return(d.ownerDocument||d)===a.document?b:null}var d=dom.Selection=function(a){var b,d=this;d.document=a,browser.ie9below&&(b=domUtils.getWindow(a).frameElement,domUtils.on(b,"beforedeactivate",function(){d._bakIERange=d.getIERange()}),domUtils.on(b,"activate",function(){try{!c(d)&&d._bakIERange&&d._bakIERange.select()}catch(a){}d._bakIERange=null})),b=a=null};d.prototype={rangeInBody:function(a,b){var c=browser.ie9below||b?a.item?a.item():a.parentElement():a.startContainer;return c===this.document.body||domUtils.inDoc(c,this.document)},getNative:function(){var a=this.document;try{return a?browser.ie9below?a.selection:domUtils.getWindow(a).getSelection():null}catch(b){return null}},getIERange:function(){var a=c(this);return!a&&this._bakIERange?this._bakIERange:a},cache:function(){this.clear(),this._cachedRange=this.getRange(),this._cachedStartElement=this.getStart(),this._cachedStartElementPath=this.getStartElementPath()},getStartElementPath:function(){if(this._cachedStartElementPath)return this._cachedStartElementPath;var a=this.getStart();return a?domUtils.findParents(a,!0,null,!0):[]},clear:function(){this._cachedStartElementPath=this._cachedRange=this._cachedStartElement=null},isFocus:function(){try{if(browser.ie9below){var a=c(this);return!(!a||!this.rangeInBody(a))}return!!this.getNative().rangeCount}catch(b){return!1}},getRange:function(){function a(a){for(var b=c.document.body.firstChild,d=a.collapsed;b&&b.firstChild;)a.setStart(b,0),b=b.firstChild;a.startContainer||a.setStart(c.document.body,0),d&&a.collapse(!0)}var c=this;if(null!=c._cachedRange)return this._cachedRange;var d=new baidu.editor.dom.Range(c.document);if(browser.ie9below){var e=c.getIERange();if(e)try{b(e,d)}catch(f){a(d)}else a(d)}else{var g=c.getNative();if(g&&g.rangeCount){var h=g.getRangeAt(0),i=g.getRangeAt(g.rangeCount-1);d.setStart(h.startContainer,h.startOffset).setEnd(i.endContainer,i.endOffset),d.collapsed&&domUtils.isBody(d.startContainer)&&!d.startOffset&&a(d)}else{if(this._bakRange&&domUtils.inDoc(this._bakRange.startContainer,this.document))return this._bakRange;a(d)}}return this._bakRange=d},getStart:function(){if(this._cachedStartElement)return this._cachedStartElement;var a,b,c,d,e=browser.ie9below?this.getIERange():this.getRange();if(browser.ie9below){if(!e)return this.document.body.firstChild;if(e.item)return e.item(0);for(a=e.duplicate(),a.text.length>0&&a.moveStart("character",1),a.collapse(1),b=a.parentElement(),d=c=e.parentElement();c=c.parentNode;)if(c==b){b=d;break}}else if(e.shrinkBoundary(),b=e.startContainer,1==b.nodeType&&b.hasChildNodes()&&(b=b.childNodes[Math.min(b.childNodes.length-1,e.startOffset)]),3==b.nodeType)return b.parentNode;return b},getText:function(){var a,b;return this.isFocus()&&(a=this.getNative())?(b=browser.ie9below?a.createRange():a.getRangeAt(0),browser.ie9below?b.text:b.toString()):""},clearRange:function(){this.getNative()[browser.ie9below?"empty":"removeAllRanges"]()}}}(),function(){function a(a,b){var c;if(b.textarea)if(utils.isString(b.textarea)){for(var d,e=0,f=domUtils.getElementsByTagName(a,"textarea");d=f[e++];)if(d.id=="ueditor_textarea_"+b.options.textarea){c=d;break}}else c=b.textarea;c||(a.appendChild(c=domUtils.createElement(document,"textarea",{name:b.options.textarea,id:"ueditor_textarea_"+b.options.textarea,style:"display:none"})),b.textarea=c),!c.getAttribute("name")&&c.setAttribute("name",b.options.textarea),c.value=b.hasContents()?b.options.allHtmlEnabled?b.getAllHtml():b.getContent(null,null,!0):""}function b(a){for(var b in a)return b}function c(a){a.langIsReady=!0,a.fireEvent("langReady")}var d,e=0,f=UE.Editor=function(a){var d=this;d.uid=e++,EventBase.call(d),d.commands={},d.options=utils.extend(utils.clone(a||{}),UEDITOR_CONFIG,!0),d.shortcutkeys={},d.inputRules=[],d.outputRules=[],d.setOpt(f.defaultOptions(d)),d.loadServerConfig(),utils.isEmptyObject(UE.I18N)?utils.loadFile(document,{src:d.options.langPath+d.options.lang+"/"+d.options.lang+".js",tag:"script",type:"text/javascript",defer:"defer"},function(){UE.plugin.load(d),c(d)}):(d.options.lang=b(UE.I18N),UE.plugin.load(d),c(d)),UE.instants["ueditorInstant"+d.uid]=d};f.prototype={registerCommand:function(a,b){this.commands[a]=b},ready:function(a){var b=this;a&&(b.isReady?a.apply(b):b.addListener("ready",a))},setOpt:function(a,b){var c={};utils.isString(a)?c[a]=b:c=a,utils.extend(this.options,c,!0)},getOpt:function(a){return this.options[a]},destroy:function(){var a=this;a.fireEvent("destroy");var b=a.container.parentNode,c=a.textarea;c?c.style.display="":(c=document.createElement("textarea"),b.parentNode.insertBefore(c,b)),c.style.width=a.iframe.offsetWidth+"px",c.style.height=a.iframe.offsetHeight+"px",c.value=a.getContent(),c.id=a.key,b.innerHTML="",domUtils.remove(b);var d=a.key;for(var e in a)a.hasOwnProperty(e)&&delete this[e];UE.delEditor(d)},render:function(a){var b=this,c=b.options,d=function(b){return parseInt(domUtils.getComputedStyle(a,b))};if(utils.isString(a)&&(a=document.getElementById(a)),a){c.initialFrameWidth?c.minFrameWidth=c.initialFrameWidth:c.minFrameWidth=c.initialFrameWidth=a.offsetWidth,c.initialFrameHeight?c.minFrameHeight=c.initialFrameHeight:c.initialFrameHeight=c.minFrameHeight=a.offsetHeight,a.style.width=/%$/.test(c.initialFrameWidth)?"100%":c.initialFrameWidth-d("padding-left")-d("padding-right")+"px",a.style.height=/%$/.test(c.initialFrameHeight)?"100%":c.initialFrameHeight-d("padding-top")-d("padding-bottom")+"px",a.style.zIndex=c.zIndex;var e=(ie&&browser.version<9?"":"<!DOCTYPE html>")+"<html xmlns='http://www.w3.org/1999/xhtml' class='view' ><head><style type='text/css'>.view{padding:0;word-wrap:break-word;cursor:text;height:90%;}\nbody{margin:8px;font-family:sans-serif;font-size:16px;}p{margin:5px 0;}</style>"+(c.iframeCssUrl?"<link rel='stylesheet' type='text/css' href='"+utils.unhtml(c.iframeCssUrl)+"'/>":"")+(c.initialStyle?"<style>"+c.initialStyle+"</style>":"")+"</head><body class='view' ></body><script type='text/javascript' "+(ie?"defer='defer'":"")+" id='_initialScript'>setTimeout(function(){editor = window.parent.UE.instants['ueditorInstant"+b.uid+"'];editor._setup(document);},0);var _tmpScript = document.getElementById('_initialScript');_tmpScript.parentNode.removeChild(_tmpScript);</script></html>";a.appendChild(domUtils.createElement(document,"iframe",{id:"ueditor_"+b.uid,width:"100%",height:"100%",frameborder:"0",src:"javascript:void(function(){document.open();"+(c.customDomain&&document.domain!=location.hostname?'document.domain="'+document.domain+'";':"")+'document.write("'+e+'");document.close();}())'})),a.style.overflow="hidden",setTimeout(function(){/%$/.test(c.initialFrameWidth)&&(c.minFrameWidth=c.initialFrameWidth=a.offsetWidth),/%$/.test(c.initialFrameHeight)&&(c.minFrameHeight=c.initialFrameHeight=a.offsetHeight,a.style.height=c.initialFrameHeight+"px")})}},_setup:function(b){var c=this,d=c.options;ie?(b.body.disabled=!0,b.body.contentEditable=!0,b.body.disabled=!1):b.body.contentEditable=!0,b.body.spellcheck=!1,c.document=b,c.window=b.defaultView||b.parentWindow,c.iframe=c.window.frameElement,c.body=b.body,c.selection=new dom.Selection(b);var e;browser.gecko&&(e=this.selection.getNative())&&e.removeAllRanges(),this._initEvents();for(var f=this.iframe.parentNode;!domUtils.isBody(f);f=f.parentNode)if("FORM"==f.tagName){c.form=f,c.options.autoSyncData?domUtils.on(c.window,"blur",function(){a(f,c)}):domUtils.on(f,"submit",function(){a(this,c)});break}if(d.initialContent)if(d.autoClearinitialContent){var g=c.execCommand;c.execCommand=function(){return c.fireEvent("firstBeforeExecCommand"),g.apply(c,arguments)},this._setDefaultContent(d.initialContent)}else this.setContent(d.initialContent,!1,!0);domUtils.isEmptyNode(c.body)&&(c.body.innerHTML="<p>"+(browser.ie?"":"<br/>")+"</p>"),d.focus&&setTimeout(function(){c.focus(c.options.focusInEnd),!c.options.autoClearinitialContent&&c._selectionChange()},0),c.container||(c.container=this.iframe.parentNode),d.fullscreen&&c.ui&&c.ui.setFullScreen(!0);try{c.document.execCommand("2D-position",!1,!1)}catch(h){}try{c.document.execCommand("enableInlineTableEditing",!1,!1)}catch(h){}try{c.document.execCommand("enableObjectResizing",!1,!1)}catch(h){}c._bindshortcutKeys(),c.isReady=1,c.fireEvent("ready"),d.onready&&d.onready.call(c),browser.ie9below||domUtils.on(c.window,["blur","focus"],function(a){if("blur"==a.type){c._bakRange=c.selection.getRange();try{c._bakNativeRange=c.selection.getNative().getRangeAt(0),c.selection.getNative().removeAllRanges()}catch(a){c._bakNativeRange=null}}else try{c._bakRange&&c._bakRange.select()}catch(a){}}),browser.gecko&&browser.version<=10902&&(c.body.contentEditable=!1,setTimeout(function(){c.body.contentEditable=!0},100),setInterval(function(){c.body.style.height=c.iframe.offsetHeight-20+"px"},100)),!d.isShow&&c.setHide(),d.readonly&&c.setDisabled()},sync:function(b){var c=this,d=b?document.getElementById(b):domUtils.findParent(c.iframe.parentNode,function(a){return"FORM"==a.tagName},!0);d&&a(d,c)},setHeight:function(a,b){a!==parseInt(this.iframe.parentNode.style.height)&&(this.iframe.parentNode.style.height=a+"px"),!b&&(this.options.minFrameHeight=this.options.initialFrameHeight=a),this.body.style.height=a+"px",!b&&this.trigger("setHeight")},addshortcutkey:function(a,b){var c={};b?c[a]=b:c=a,utils.extend(this.shortcutkeys,c)},_bindshortcutKeys:function(){var a=this,b=this.shortcutkeys;a.addListener("keydown",function(c,d){var e=d.keyCode||d.which;for(var f in b)for(var g,h=b[f].split(","),i=0;g=h[i++];){g=g.split(":");var j=g[0],k=g[1];(/^(ctrl)(\+shift)?\+(\d+)$/.test(j.toLowerCase())||/^(\d+)$/.test(j))&&(("ctrl"==RegExp.$1?d.ctrlKey||d.metaKey:0)&&(""!=RegExp.$2?d[RegExp.$2.slice(1)+"Key"]:1)&&e==RegExp.$3||e==RegExp.$1)&&(a.queryCommandState(f,k)!=-1&&a.execCommand(f,k),domUtils.preventDefault(d))}})},getContent:function(a,b,c,d,e){var f=this;if(a&&utils.isFunction(a)&&(b=a,a=""),b?!b():!this.hasContents())return"";f.fireEvent("beforegetcontent");var g=UE.htmlparser(f.body.innerHTML,d);return f.filterOutputRule(g),f.fireEvent("aftergetcontent",a,g),g.toHtml(e)},getAllHtml:function(){var a=this,b=[];if(a.fireEvent("getAllHtml",b),browser.ie&&browser.version>8){var c="";utils.each(a.document.styleSheets,function(a){c+=a.href?'<link rel="stylesheet" type="text/css" href="'+a.href+'" />':"<style>"+a.cssText+"</style>"}),utils.each(a.document.getElementsByTagName("script"),function(a){c+=a.outerHTML})}return"<html><head>"+(a.options.charset?'<meta http-equiv="Content-Type" content="text/html; charset='+a.options.charset+'"/>':"")+(c||a.document.getElementsByTagName("head")[0].innerHTML)+b.join("\n")+"</head><body "+(ie&&browser.version<9?'class="view"':"")+">"+a.getContent(null,null,!0)+"</body></html>"},getPlainTxt:function(){var a=new RegExp(domUtils.fillChar,"g"),b=this.body.innerHTML.replace(/[\n\r]/g,"");return b=b.replace(/<(p|div)[^>]*>(<br\/?>| )<\/\1>/gi,"\n").replace(/<br\/?>/gi,"\n").replace(/<[^>\/]+>/g,"").replace(/(\n)?<\/([^>]+)>/g,function(a,b,c){return dtd.$block[c]?"\n":b?b:""}),b.replace(a,"").replace(/\u00a0/g," ").replace(/ /g," ")},getContentTxt:function(){var a=new RegExp(domUtils.fillChar,"g");return this.body[browser.ie?"innerText":"textContent"].replace(a,"").replace(/\u00a0/g," ")},setContent:function(b,c,d){function e(a){return"DIV"==a.tagName&&a.getAttribute("cdata_tag")}var f=this;f.fireEvent("beforesetcontent",b);var g=UE.htmlparser(b);if(f.filterInputRule(g),b=g.toHtml(),f.body.innerHTML=(c?f.body.innerHTML:"")+b,"p"==f.options.enterTag){var h,i=this.body.firstChild;if(!i||1==i.nodeType&&(dtd.$cdata[i.tagName]||e(i)||domUtils.isCustomeNode(i))&&i===this.body.lastChild)this.body.innerHTML="<p>"+(browser.ie?" ":"<br/>")+"</p>"+this.body.innerHTML;else for(var j=f.document.createElement("p");i;){for(;i&&(3==i.nodeType||1==i.nodeType&&dtd.p[i.tagName]&&!dtd.$cdata[i.tagName]);)h=i.nextSibling,j.appendChild(i),i=h;if(j.firstChild){if(!i){f.body.appendChild(j);break}i.parentNode.insertBefore(j,i),j=f.document.createElement("p")}i=i.nextSibling}}f.fireEvent("aftersetcontent"),f.fireEvent("contentchange"),!d&&f._selectionChange(),f._bakRange=f._bakIERange=f._bakNativeRange=null;var k;browser.gecko&&(k=this.selection.getNative())&&k.removeAllRanges(),f.options.autoSyncData&&f.form&&a(f.form,f)},focus:function(a){try{var b=this,c=b.selection.getRange();if(a){var d=b.body.lastChild;d&&1==d.nodeType&&!dtd.$empty[d.tagName]&&(domUtils.isEmptyBlock(d)?c.setStartAtFirst(d):c.setStartAtLast(d),c.collapse(!0)),c.setCursor(!0)}else{if(!c.collapsed&&domUtils.isBody(c.startContainer)&&0==c.startOffset){var d=b.body.firstChild;d&&1==d.nodeType&&!dtd.$empty[d.tagName]&&c.setStartAtFirst(d).collapse(!0)}c.select(!0)}this.fireEvent("focus selectionchange")}catch(e){}},isFocus:function(){return this.selection.isFocus()},blur:function(){var a=this.selection.getNative();if(a.empty&&browser.ie){var b=document.body.createTextRange();b.moveToElementText(document.body),b.collapse(!0),b.select(),a.empty()}else a.removeAllRanges()},_initEvents:function(){var a=this,b=a.document,c=a.window;a._proxyDomEvent=utils.bind(a._proxyDomEvent,a),domUtils.on(b,["click","contextmenu","mousedown","keydown","keyup","keypress","mouseup","mouseover","mouseout","selectstart"],a._proxyDomEvent),domUtils.on(c,["focus","blur"],a._proxyDomEvent),domUtils.on(a.body,"drop",function(b){browser.gecko&&b.stopPropagation&&b.stopPropagation(),a.fireEvent("contentchange")}),domUtils.on(b,["mouseup","keydown"],function(b){"keydown"==b.type&&(b.ctrlKey||b.metaKey||b.shiftKey||b.altKey)||2!=b.button&&a._selectionChange(250,b)})},_proxyDomEvent:function(a){return this.fireEvent("before"+a.type.replace(/^on/,"").toLowerCase())!==!1&&(this.fireEvent(a.type.replace(/^on/,""),a)!==!1&&this.fireEvent("after"+a.type.replace(/^on/,"").toLowerCase()))},_selectionChange:function(a,b){var c,e,f=this,g=!1;if(browser.ie&&browser.version<9&&b&&"mouseup"==b.type){var h=this.selection.getRange();h.collapsed||(g=!0,c=b.clientX,e=b.clientY)}clearTimeout(d),d=setTimeout(function(){if(f.selection&&f.selection.getNative()){var a;if(g&&"None"==f.selection.getNative().type){a=f.document.body.createTextRange();try{a.moveToPoint(c,e)}catch(d){a=null}}var h;a&&(h=f.selection.getIERange,f.selection.getIERange=function(){return a}),f.selection.cache(),h&&(f.selection.getIERange=h),f.selection._cachedRange&&f.selection._cachedStartElement&&(f.fireEvent("beforeselectionchange"),f.fireEvent("selectionchange",!!b),f.fireEvent("afterselectionchange"),f.selection.clear())}},a||50)},_callCmdFn:function(a,b){var c,d,e=b[0].toLowerCase();return c=this.commands[e]||UE.commands[e],d=c&&c[a],c&&d||"queryCommandState"!=a?d?d.apply(this,b):void 0:0},execCommand:function(a){a=a.toLowerCase();var b,c=this,d=c.commands[a]||UE.commands[a];return d&&d.execCommand?(d.notNeedUndo||c.__hasEnterExecCommand?(b=this._callCmdFn("execCommand",arguments),!c.__hasEnterExecCommand&&!d.ignoreContentChange&&!c._ignoreContentChange&&c.fireEvent("contentchange")):(c.__hasEnterExecCommand=!0,c.queryCommandState.apply(c,arguments)!=-1&&(c.fireEvent("saveScene"),c.fireEvent.apply(c,["beforeexeccommand",a].concat(arguments)),b=this._callCmdFn("execCommand",arguments),c.fireEvent.apply(c,["afterexeccommand",a].concat(arguments)),c.fireEvent("saveScene")),c.__hasEnterExecCommand=!1),!c.__hasEnterExecCommand&&!d.ignoreContentChange&&!c._ignoreContentChange&&c._selectionChange(),b):null},queryCommandState:function(a){return this._callCmdFn("queryCommandState",arguments)},queryCommandValue:function(a){return this._callCmdFn("queryCommandValue",arguments)},hasContents:function(a){if(a)for(var b,c=0;b=a[c++];)if(this.document.getElementsByTagName(b).length>0)return!0;if(!domUtils.isEmptyBlock(this.body))return!0;for(a=["div"],c=0;b=a[c++];)for(var d,e=domUtils.getElementsByTagName(this.document,b),f=0;d=e[f++];)if(domUtils.isCustomeNode(d))return!0;return!1},reset:function(){this.fireEvent("reset")},setEnabled:function(){var a,b=this;if("false"==b.body.contentEditable){b.body.contentEditable=!0,a=b.selection.getRange();try{a.moveToBookmark(b.lastBk),delete b.lastBk}catch(c){a.setStartAtFirst(b.body).collapse(!0)}a.select(!0),b.bkqueryCommandState&&(b.queryCommandState=b.bkqueryCommandState,delete b.bkqueryCommandState),b.bkqueryCommandValue&&(b.queryCommandValue=b.bkqueryCommandValue,delete b.bkqueryCommandValue),b.fireEvent("selectionchange")}},enable:function(){return this.setEnabled()},setDisabled:function(a){var b=this;a=a?utils.isArray(a)?a:[a]:[],"true"==b.body.contentEditable&&(b.lastBk||(b.lastBk=b.selection.getRange().createBookmark(!0)),b.body.contentEditable=!1,b.bkqueryCommandState=b.queryCommandState,b.bkqueryCommandValue=b.queryCommandValue,b.queryCommandState=function(c){return utils.indexOf(a,c)!=-1?b.bkqueryCommandState.apply(b,arguments):-1},b.queryCommandValue=function(c){return utils.indexOf(a,c)!=-1?b.bkqueryCommandValue.apply(b,arguments):null},b.fireEvent("selectionchange"))},disable:function(a){return this.setDisabled(a)},_setDefaultContent:function(){function a(){var b=this;b.document.getElementById("initContent")&&(b.body.innerHTML="<p>"+(ie?"":"<br/>")+"</p>",b.removeListener("firstBeforeExecCommand focus",a),setTimeout(function(){b.focus(),b._selectionChange()},0))}return function(b){var c=this;c.body.innerHTML='<p id="initContent">'+b+"</p>",c.addListener("firstBeforeExecCommand focus",a)}}(),setShow:function(){var a=this,b=a.selection.getRange();if("none"==a.container.style.display){try{b.moveToBookmark(a.lastBk),delete a.lastBk}catch(c){b.setStartAtFirst(a.body).collapse(!0)}setTimeout(function(){b.select(!0)},100),a.container.style.display=""}},show:function(){return this.setShow()},setHide:function(){
var a=this;a.lastBk||(a.lastBk=a.selection.getRange().createBookmark(!0)),a.container.style.display="none"},hide:function(){return this.setHide()},getLang:function(a){var b=UE.I18N[this.options.lang];if(!b)throw Error("not import language file");a=(a||"").split(".");for(var c,d=0;(c=a[d++])&&(b=b[c],b););return b},getContentLength:function(a,b){var c=this.getContent(!1,!1,!0).length;if(a){b=(b||[]).concat(["hr","img","iframe"]),c=this.getContentTxt().replace(/[\t\r\n]+/g,"").length;for(var d,e=0;d=b[e++];)c+=this.document.getElementsByTagName(d).length}return c},addInputRule:function(a){this.inputRules.push(a)},filterInputRule:function(a){for(var b,c=0;b=this.inputRules[c++];)b.call(this,a)},addOutputRule:function(a){this.outputRules.push(a)},filterOutputRule:function(a){for(var b,c=0;b=this.outputRules[c++];)b.call(this,a)},getActionUrl:function(a){var b=this.getOpt(a)||a,c=this.getOpt("imageUrl"),d=this.getOpt("serverUrl");return!d&&c&&(d=c.replace(/^(.*[\/]).+([\.].+)$/,"$1controller$2")),d?(d=d+(d.indexOf("?")==-1?"?":"&")+"action="+(b||""),utils.formatUrl(d)):""}},utils.inherits(f,EventBase)}(),UE.Editor.defaultOptions=function(a){var b=a.options.UEDITOR_HOME_URL;return{isShow:!0,initialContent:"",initialStyle:"",autoClearinitialContent:!1,iframeCssUrl:b+"themes/iframe.css",textarea:"editorValue",focus:!1,focusInEnd:!0,autoClearEmptyNode:!0,fullscreen:!1,readonly:!1,zIndex:999,imagePopup:!0,enterTag:"p",customDomain:!1,lang:"zh-cn",langPath:b+"lang/",theme:"default",themePath:b+"themes/",allHtmlEnabled:!1,scaleEnabled:!1,tableNativeEditInFF:!1,autoSyncData:!0,fileNameFormat:"{time}{rand:6}"}},function(){UE.Editor.prototype.loadServerConfig=function(){function showErrorMsg(a){console&&console.error(a)}var me=this;setTimeout(function(){try{me.options.imageUrl&&me.setOpt("serverUrl",me.options.imageUrl.replace(/^(.*[\/]).+([\.].+)$/,"$1controller$2"));var configUrl=me.getActionUrl("config"),isJsonp=utils.isCrossDomainUrl(configUrl);me._serverConfigLoaded=!1,configUrl&&UE.ajax.request(configUrl,{method:"GET",dataType:isJsonp?"jsonp":"",onsuccess:function(r){try{var config=isJsonp?r:eval("("+r.responseText+")");utils.extend(me.options,config),me.fireEvent("serverConfigLoaded"),me._serverConfigLoaded=!0}catch(e){showErrorMsg(me.getLang("loadconfigFormatError"))}},onerror:function(){showErrorMsg(me.getLang("loadconfigHttpError"))}})}catch(e){showErrorMsg(me.getLang("loadconfigError"))}})},UE.Editor.prototype.isServerConfigLoaded=function(){var a=this;return a._serverConfigLoaded||!1},UE.Editor.prototype.afterConfigReady=function(a){if(a&&utils.isFunction(a)){var b=this,c=function(){a.apply(b,arguments),b.removeListener("serverConfigLoaded",c)};b.isServerConfigLoaded()?a.call(b,"serverConfigLoaded"):b.addListener("serverConfigLoaded",c)}}}(),UE.ajax=function(){function a(a){var b=[];for(var c in a)if("method"!=c&&"timeout"!=c&&"async"!=c&&"dataType"!=c&&"callback"!=c&&void 0!=a[c]&&null!=a[c])if("function"!=(typeof a[c]).toLowerCase()&&"object"!=(typeof a[c]).toLowerCase())b.push(encodeURIComponent(c)+"="+encodeURIComponent(a[c]));else if(utils.isArray(a[c]))for(var d=0;d<a[c].length;d++)b.push(encodeURIComponent(c)+"[]="+encodeURIComponent(a[c][d]));return b.join("&")}function b(b,c){var d=f(),e=!1,g={method:"POST",timeout:5e3,async:!0,data:{},onsuccess:function(){},onerror:function(){}};if("object"==typeof b&&(c=b,b=c.url),d&&b){var h=c?utils.extend(g,c):g,i=a(h);utils.isEmptyObject(h.data)||(i+=(i?"&":"")+a(h.data));var j=setTimeout(function(){4!=d.readyState&&(e=!0,d.abort(),clearTimeout(j))},h.timeout),k=h.method.toUpperCase(),l=b+(b.indexOf("?")==-1?"?":"&")+("POST"==k?"":i+"&noCache="+ +new Date);d.open(k,l,h.async),d.onreadystatechange=function(){4==d.readyState&&(e||200!=d.status?h.onerror(d):h.onsuccess(d))},"POST"==k?(d.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),d.send(i)):d.send(null)}}function c(b,c){function d(a,b,c){a.setAttribute("type","text/javascript"),a.setAttribute("defer","defer"),c&&a.setAttribute("charset",c),a.setAttribute("src",b),document.getElementsByTagName("head")[0].appendChild(a)}function e(a){return function(){try{if(a)k.onerror&&k.onerror();else try{clearTimeout(g),i.apply(window,arguments)}catch(b){}}catch(c){k.onerror&&k.onerror.call(window,c)}finally{k.oncomplete&&k.oncomplete.apply(window,arguments),j.parentNode&&j.parentNode.removeChild(j),window[f]=null;try{delete window[f]}catch(b){}}}}var f,g,h,i=c.onsuccess||function(){},j=document.createElement("SCRIPT"),k=c||{},l=k.charset,m=k.jsonp||"callback",n=k.timeOut||0,o=new RegExp("(\\?|&)"+m+"=([^&]*)");utils.isFunction(i)?(f="bd__editor__"+Math.floor(2147483648*Math.random()).toString(36),window[f]=e(0)):utils.isString(i)?f=i:(h=o.exec(b))&&(f=h[2]),b=b.replace(o,"$1"+m+"="+f),b.search(o)<0&&(b+=(b.indexOf("?")<0?"?":"&")+m+"="+f);var p=a(c);utils.isEmptyObject(c.data)||(p+=(p?"&":"")+a(c.data)),p&&(b=b.replace(/\?/,"?"+p+"&")),j.onerror=e(1),n&&(g=setTimeout(e(1),n)),d(j,b,l)}var d="XMLHttpRequest()";try{new ActiveXObject("Msxml2.XMLHTTP"),d="ActiveXObject('Msxml2.XMLHTTP')"}catch(e){try{new ActiveXObject("Microsoft.XMLHTTP"),d="ActiveXObject('Microsoft.XMLHTTP')"}catch(e){}}var f=new Function("return new "+d);return{request:function(a,d){d&&"jsonp"==d.dataType?c(a,d):b(a,d)},getJSONP:function(a,b,d){var e={data:b,oncomplete:d};c(a,e)}}}();var filterWord=UE.filterWord=function(){function a(a){return/(class="?Mso|style="[^"]*\bmso\-|w:WordDocument|<(v|o):|lang=)/gi.test(a)}function b(a){return a=a.replace(/[\d.]+\w+/g,function(a){return utils.transUnitToPx(a)})}function c(a){return a.replace(/[\t\r\n]+/g," ").replace(/<!--[\s\S]*?-->/gi,"").replace(/<v:shape [^>]*>[\s\S]*?.<\/v:shape>/gi,function(a){if(browser.opera)return"";try{if(/Bitmap/i.test(a))return"";var c=a.match(/width:([ \d.]*p[tx])/i)[1],d=a.match(/height:([ \d.]*p[tx])/i)[1],e=a.match(/src=\s*"([^"]*)"/i)[1];return'<img width="'+b(c)+'" height="'+b(d)+'" src="'+e+'" />'}catch(f){return""}}).replace(/<\/?div[^>]*>/g,"").replace(/v:\w+=(["']?)[^'"]+\1/g,"").replace(/<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|xml|meta|link|style|\w+:\w+)(?=[\s\/>]))[^>]*>/gi,"").replace(/<p [^>]*class="?MsoHeading"?[^>]*>(.*?)<\/p>/gi,"<p><strong>$1</strong></p>").replace(/\s+(class|lang|align)\s*=\s*(['"]?)([\w-]+)\2/gi,function(a,b,c,d){return"class"==b&&"MsoListParagraph"==d?a:""}).replace(/<(font|span)[^>]*>(\s*)<\/\1>/gi,function(a,b,c){return c.replace(/[\t\r\n ]+/g," ")}).replace(/(<[a-z][^>]*)\sstyle=(["'])([^\2]*?)\2/gi,function(a,c,d,e){for(var f,g=[],h=e.replace(/^\s+|\s+$/,"").replace(/'/g,"'").replace(/"/gi,"'").replace(/[\d.]+(cm|pt)/g,function(a){return utils.transUnitToPx(a)}).split(/;\s*/g),i=0;f=h[i];i++){var j,k,l=f.split(":");if(2==l.length){if(j=l[0].toLowerCase(),k=l[1].toLowerCase(),/^(background)\w*/.test(j)&&0==k.replace(/(initial|\s)/g,"").length||/^(margin)\w*/.test(j)&&/^0\w+$/.test(k))continue;switch(j){case"mso-padding-alt":case"mso-padding-top-alt":case"mso-padding-right-alt":case"mso-padding-bottom-alt":case"mso-padding-left-alt":case"mso-margin-alt":case"mso-margin-top-alt":case"mso-margin-right-alt":case"mso-margin-bottom-alt":case"mso-margin-left-alt":case"mso-height":case"mso-width":case"mso-vertical-align-alt":/<table/.test(c)||(g[i]=j.replace(/^mso-|-alt$/g,"")+":"+b(k));continue;case"horiz-align":g[i]="text-align:"+k;continue;case"vert-align":g[i]="vertical-align:"+k;continue;case"font-color":case"mso-foreground":g[i]="color:"+k;continue;case"mso-background":case"mso-highlight":g[i]="background:"+k;continue;case"mso-default-height":g[i]="min-height:"+b(k);continue;case"mso-default-width":g[i]="min-width:"+b(k);continue;case"mso-padding-between-alt":g[i]="border-collapse:separate;border-spacing:"+b(k);continue;case"text-line-through":"single"!=k&&"double"!=k||(g[i]="text-decoration:line-through");continue;case"mso-zero-height":"yes"==k&&(g[i]="display:none");continue;case"margin":if(!/[1-9]/.test(k))continue}if(/^(mso|column|font-emph|lang|layout|line-break|list-image|nav|panose|punct|row|ruby|sep|size|src|tab-|table-border|text-(?:decor|trans)|top-bar|version|vnd|word-break)/.test(j)||/text\-indent|padding|margin/.test(j)&&/\-[\d.]+/.test(k))continue;g[i]=j+":"+l[1]}}return c+(g.length?' style="'+g.join(";").replace(/;{2,}/g,";")+'"':"")})}return function(b){return a(b)?c(b):b}}();!function(){function a(a,b,c){return a.push(n),b+(c?1:-1)}function b(a,b){for(var c=0;c<b;c++)a.push(m)}function c(g,h,i,j){switch(g.type){case"root":for(var k,l=0;k=g.children[l++];)i&&"element"==k.type&&!dtd.$inlineWithA[k.tagName]&&l>1&&(a(h,j,!0),b(h,j)),c(k,h,i,j);break;case"text":d(g,h);break;case"element":e(g,h,i,j);break;case"comment":f(g,h,i)}return h}function d(a,b){"pre"==a.parentNode.tagName?b.push(a.data):b.push(l[a.parentNode.tagName]?utils.html(a.data):a.data.replace(/[ ]{2}/g," "))}function e(d,e,f,g){var h="";if(d.attrs){h=[];var i=d.attrs;for(var j in i)h.push(j+(void 0!==i[j]?'="'+(k[j]?utils.html(i[j]).replace(/["]/g,function(a){return"""}):utils.unhtml(i[j]))+'"':""));h=h.join(" ")}if(e.push("<"+d.tagName+(h?" "+h:"")+(dtd.$empty[d.tagName]?"/":"")+">"),f&&!dtd.$inlineWithA[d.tagName]&&"pre"!=d.tagName&&d.children&&d.children.length&&(g=a(e,g,!0),b(e,g)),d.children&&d.children.length)for(var l,m=0;l=d.children[m++];)f&&"element"==l.type&&!dtd.$inlineWithA[l.tagName]&&m>1&&(a(e,g),b(e,g)),c(l,e,f,g);dtd.$empty[d.tagName]||(f&&!dtd.$inlineWithA[d.tagName]&&"pre"!=d.tagName&&d.children&&d.children.length&&(g=a(e,g),b(e,g)),e.push("</"+d.tagName+">"))}function f(a,b){b.push("<!--"+a.data+"-->")}function g(a,b){var c;if("element"==a.type&&a.getAttr("id")==b)return a;if(a.children&&a.children.length)for(var d,e=0;d=a.children[e++];)if(c=g(d,b))return c}function h(a,b,c){if("element"==a.type&&a.tagName==b&&c.push(a),a.children&&a.children.length)for(var d,e=0;d=a.children[e++];)h(d,b,c)}function i(a,b){if(a.children&&a.children.length)for(var c,d=0;c=a.children[d];)i(c,b),c.parentNode&&(c.children&&c.children.length&&b(c),c.parentNode&&d++);else b(a)}var j=UE.uNode=function(a){this.type=a.type,this.data=a.data,this.tagName=a.tagName,this.parentNode=a.parentNode,this.attrs=a.attrs||{},this.children=a.children},k={href:1,src:1,_src:1,_href:1,cdata_data:1},l={style:1,script:1},m=" ",n="\n";j.createElement=function(a){return/[<>]/.test(a)?UE.htmlparser(a).children[0]:new j({type:"element",children:[],tagName:a})},j.createText=function(a,b){return new UE.uNode({type:"text",data:b?a:utils.unhtml(a||"")})},j.prototype={toHtml:function(a){var b=[];return c(this,b,a,0),b.join("")},innerHTML:function(a){if("element"!=this.type||dtd.$empty[this.tagName])return this;if(utils.isString(a)){if(this.children)for(var b,c=0;b=this.children[c++];)b.parentNode=null;this.children=[];for(var b,d=UE.htmlparser(a),c=0;b=d.children[c++];)this.children.push(b),b.parentNode=this;return this}var d=new UE.uNode({type:"root",children:this.children});return d.toHtml()},innerText:function(a,b){if("element"!=this.type||dtd.$empty[this.tagName])return this;if(a){if(this.children)for(var c,d=0;c=this.children[d++];)c.parentNode=null;return this.children=[],this.appendChild(j.createText(a,b)),this}return this.toHtml().replace(/<[^>]+>/g,"")},getData:function(){return"element"==this.type?"":this.data},firstChild:function(){return this.children?this.children[0]:null},lastChild:function(){return this.children?this.children[this.children.length-1]:null},previousSibling:function(){for(var a,b=this.parentNode,c=0;a=b.children[c];c++)if(a===this)return 0==c?null:b.children[c-1]},nextSibling:function(){for(var a,b=this.parentNode,c=0;a=b.children[c++];)if(a===this)return b.children[c]},replaceChild:function(a,b){if(this.children){a.parentNode&&a.parentNode.removeChild(a);for(var c,d=0;c=this.children[d];d++)if(c===b)return this.children.splice(d,1,a),b.parentNode=null,a.parentNode=this,a}},appendChild:function(a){if("root"==this.type||"element"==this.type&&!dtd.$empty[this.tagName]){this.children||(this.children=[]),a.parentNode&&a.parentNode.removeChild(a);for(var b,c=0;b=this.children[c];c++)if(b===a){this.children.splice(c,1);break}return this.children.push(a),a.parentNode=this,a}},insertBefore:function(a,b){if(this.children){a.parentNode&&a.parentNode.removeChild(a);for(var c,d=0;c=this.children[d];d++)if(c===b)return this.children.splice(d,0,a),a.parentNode=this,a}},insertAfter:function(a,b){if(this.children){a.parentNode&&a.parentNode.removeChild(a);for(var c,d=0;c=this.children[d];d++)if(c===b)return this.children.splice(d+1,0,a),a.parentNode=this,a}},removeChild:function(a,b){if(this.children)for(var c,d=0;c=this.children[d];d++)if(c===a){if(this.children.splice(d,1),c.parentNode=null,b&&c.children&&c.children.length)for(var e,f=0;e=c.children[f];f++)this.children.splice(d+f,0,e),e.parentNode=this;return c}},getAttr:function(a){return this.attrs&&this.attrs[a.toLowerCase()]},setAttr:function(a,b){if(!a)return void delete this.attrs;if(this.attrs||(this.attrs={}),utils.isObject(a))for(var c in a)a[c]?this.attrs[c.toLowerCase()]=a[c]:delete this.attrs[c];else b?this.attrs[a.toLowerCase()]=b:delete this.attrs[a]},getIndex:function(){for(var a,b=this.parentNode,c=0;a=b.children[c];c++)if(a===this)return c;return-1},getNodeById:function(a){var b;if(this.children&&this.children.length)for(var c,d=0;c=this.children[d++];)if(b=g(c,a))return b},getNodesByTagName:function(a){a=utils.trim(a).replace(/[ ]{2,}/g," ").split(" ");var b=[],c=this;return utils.each(a,function(a){if(c.children&&c.children.length)for(var d,e=0;d=c.children[e++];)h(d,a,b)}),b},getStyle:function(a){var b=this.getAttr("style");if(!b)return"";var c=new RegExp("(^|;)\\s*"+a+":([^;]+)","i"),d=b.match(c);return d&&d[0]?d[2]:""},setStyle:function(a,b){function c(a,b){var c=new RegExp("(^|;)\\s*"+a+":([^;]+;?)","gi");d=d.replace(c,"$1"),b&&(d=a+":"+utils.unhtml(b)+";"+d)}var d=this.getAttr("style");if(d||(d=""),utils.isObject(a))for(var e in a)c(e,a[e]);else c(a,b);this.setAttr("style",utils.trim(d))},traversal:function(a){return this.children&&this.children.length&&i(this,a),this}}}();var htmlparser=UE.htmlparser=function(a,b){function c(a,b){if(m[a.tagName]){var c=k.createElement(m[a.tagName]);a.appendChild(c),c.appendChild(k.createText(b)),a=c}else a.appendChild(k.createText(b))}function d(a,b,c){var e;if(e=l[b]){for(var f,h=a;"root"!=h.type;){if(utils.isArray(e)?utils.indexOf(e,h.tagName)!=-1:e==h.tagName){a=h,f=!0;break}h=h.parentNode}f||(a=d(a,utils.isArray(e)?e[0]:e))}var i=new k({parentNode:a,type:"element",tagName:b.toLowerCase(),children:dtd.$empty[b]?null:[]});if(c){for(var m,n={};m=g.exec(c);)n[m[1].toLowerCase()]=j[m[1].toLowerCase()]?m[2]||m[3]||m[4]:utils.unhtml(m[2]||m[3]||m[4]);i.attrs=n}return a.children.push(i),dtd.$empty[b]?a:i}function e(a,b){a.children.push(new k({type:"comment",data:b,parentNode:a}))}var f=/<(?:(?:\/([^>]+)>)|(?:!--([\S|\s]*?)-->)|(?:([^\s\/<>]+)\s*((?:(?:"[^"]*")|(?:'[^']*')|[^"'<>])*)\/?>))/g,g=/([\w\-:.]+)(?:(?:\s*=\s*(?:(?:"([^"]*)")|(?:'([^']*)')|([^\s>]+)))|(?=\s|$))/g,h={b:1,code:1,i:1,u:1,strike:1,s:1,tt:1,strong:1,q:1,samp:1,em:1,span:1,sub:1,img:1,sup:1,font:1,big:1,small:1,iframe:1,a:1,br:1,pre:1};a=a.replace(new RegExp(domUtils.fillChar,"g"),""),b||(a=a.replace(new RegExp("[\\r\\t\\n"+(b?"":" ")+"]*</?(\\w+)\\s*(?:[^>]*)>[\\r\\t\\n"+(b?"":" ")+"]*","g"),function(a,c){return c&&h[c.toLowerCase()]?a.replace(/(^[\n\r]+)|([\n\r]+$)/g,""):a.replace(new RegExp("^[\\r\\n"+(b?"":" ")+"]+"),"").replace(new RegExp("[\\r\\n"+(b?"":" ")+"]+$"),"")}));for(var i,j={href:1,src:1},k=UE.uNode,l={td:"tr",tr:["tbody","thead","tfoot"],tbody:"table",th:"tr",thead:"table",tfoot:"table",caption:"table",li:["ul","ol"],dt:"dl",dd:"dl",option:"select"},m={ol:"li",ul:"li"},n=0,o=0,p=new k({type:"root",children:[]}),q=p;i=f.exec(a);){n=i.index;try{if(n>o&&c(q,a.slice(o,n)),i[3])dtd.$cdata[q.tagName]?c(q,i[0]):q=d(q,i[3].toLowerCase(),i[4]);else if(i[1]){if("root"!=q.type)if(dtd.$cdata[q.tagName]&&!dtd.$cdata[i[1]])c(q,i[0]);else{for(var r=q;"element"==q.type&&q.tagName!=i[1].toLowerCase();)if(q=q.parentNode,"root"==q.type)throw q=r,"break";q=q.parentNode}}else i[2]&&e(q,i[2])}catch(s){}o=f.lastIndex}return o<a.length&&c(q,a.slice(o)),p},filterNode=UE.filterNode=function(){function a(b,c){switch(b.type){case"text":break;case"element":var d;if(d=c[b.tagName])if("-"===d)b.parentNode.removeChild(b);else if(utils.isFunction(d)){var e=b.parentNode,f=b.getIndex();if(d(b),b.parentNode){if(b.children)for(var g,h=0;g=b.children[h];)a(g,c),g.parentNode&&h++}else for(var g,h=f;g=e.children[h];)a(g,c),g.parentNode&&h++}else{var i=d.$;if(i&&b.attrs){var j,k={};for(var l in i){if(j=b.getAttr(l),"style"==l&&utils.isArray(i[l])){var m=[];utils.each(i[l],function(a){var c;(c=b.getStyle(a))&&m.push(a+":"+c)}),j=m.join(";")}j&&(k[l]=j)}b.attrs=k}if(b.children)for(var g,h=0;g=b.children[h];)a(g,c),g.parentNode&&h++}else if(dtd.$cdata[b.tagName])b.parentNode.removeChild(b);else{var e=b.parentNode,f=b.getIndex();b.parentNode.removeChild(b,!0);for(var g,h=f;g=e.children[h];)a(g,c),g.parentNode&&h++}break;case"comment":b.parentNode.removeChild(b)}}return function(b,c){if(utils.isEmptyObject(c))return b;var d;(d=c["-"])&&utils.each(d.split(" "),function(a){c[a]="-"});for(var e,f=0;e=b.children[f];)a(e,c),e.parentNode&&f++;return b}}();UE.plugin=function(){var a={};return{register:function(b,c,d,e){d&&utils.isFunction(d)&&(e=d,d=null),a[b]={optionName:d||b,execFn:c,afterDisabled:e}},load:function(b){utils.each(a,function(a){var c=a.execFn.call(b);b.options[a.optionName]!==!1?c&&utils.each(c,function(a,c){switch(c.toLowerCase()){case"shortcutkey":b.addshortcutkey(a);break;case"bindevents":utils.each(a,function(a,c){b.addListener(c,a)});break;case"bindmultievents":utils.each(utils.isArray(a)?a:[a],function(a){var c=utils.trim(a.type).split(/\s+/);utils.each(c,function(c){b.addListener(c,a.handler)})});break;case"commands":utils.each(a,function(a,c){b.commands[c]=a});break;case"outputrule":b.addOutputRule(a);break;case"inputrule":b.addInputRule(a);break;case"defaultoptions":b.setOpt(a)}}):a.afterDisabled&&a.afterDisabled.call(b)}),utils.each(UE.plugins,function(a){a.call(b)})},run:function(b,c){var d=a[b];d&&d.exeFn.call(c)}}}();var keymap=UE.keymap={Backspace:8,Tab:9,Enter:13,Shift:16,Control:17,Alt:18,CapsLock:20,Esc:27,Spacebar:32,PageUp:33,PageDown:34,End:35,Home:36,Left:37,Up:38,Right:39,Down:40,Insert:45,Del:46,NumLock:144,Cmd:91,"=":187,"-":189,b:66,i:73,z:90,y:89,v:86,x:88,s:83,n:78},LocalStorage=UE.LocalStorage=function(){function a(){var a=document.createElement("div");return a.style.display="none",a.addBehavior?(a.addBehavior("#default#userdata"),{getItem:function(b){var d=null;try{document.body.appendChild(a),a.load(c),d=a.getAttribute(b),document.body.removeChild(a)}catch(e){}return d},setItem:function(b,d){document.body.appendChild(a),a.setAttribute(b,d),a.save(c),document.body.removeChild(a)},removeItem:function(b){document.body.appendChild(a),a.removeAttribute(b),a.save(c),document.body.removeChild(a)}}):null}var b=window.localStorage||a()||null,c="localStorage";return{saveLocalData:function(a,c){return!(!b||!c)&&(b.setItem(a,c),!0)},getLocalData:function(a){return b?b.getItem(a):null},removeItem:function(a){b&&b.removeItem(a)}}}();!function(){var a="ueditor_preference";UE.Editor.prototype.setPreferences=function(b,c){var d={};utils.isString(b)?d[b]=c:d=b;var e=LocalStorage.getLocalData(a);e&&(e=utils.str2json(e))?utils.extend(e,d):e=d,e&&LocalStorage.saveLocalData(a,utils.json2str(e))},UE.Editor.prototype.getPreferences=function(b){var c=LocalStorage.getLocalData(a);return c&&(c=utils.str2json(c))?b?c[b]:c:null},UE.Editor.prototype.removePreferences=function(b){var c=LocalStorage.getLocalData(a);c&&(c=utils.str2json(c))&&(c[b]=void 0,delete c[b]),c&&LocalStorage.saveLocalData(a,utils.json2str(c))}}(),UE.plugins.defaultfilter=function(){var a=this;a.setOpt({allowDivTransToP:!0,disabledTableInTable:!0}),a.addInputRule(function(b){function c(a){for(;a&&"element"==a.type;){if("td"==a.tagName)return!0;a=a.parentNode}return!1}var d,e=this.options.allowDivTransToP;b.traversal(function(b){if("element"==b.type){if(!dtd.$cdata[b.tagName]&&a.options.autoClearEmptyNode&&dtd.$inline[b.tagName]&&!dtd.$empty[b.tagName]&&(!b.attrs||utils.isEmptyObject(b.attrs)))return void(b.firstChild()?"span"!=b.tagName||b.attrs&&!utils.isEmptyObject(b.attrs)||b.parentNode.removeChild(b,!0):b.parentNode.removeChild(b));switch(b.tagName){case"style":case"script":b.setAttr({cdata_tag:b.tagName,cdata_data:b.innerHTML()||"",_ue_custom_node_:"true"}),b.tagName="div",b.innerHTML("");break;case"a":(d=b.getAttr("href"))&&b.setAttr("_href",d);break;case"img":if((d=b.getAttr("src"))&&/^data:/.test(d)){b.parentNode.removeChild(b);break}b.setAttr("_src",b.getAttr("src"));break;case"span":browser.webkit&&(d=b.getStyle("white-space"))&&/nowrap|normal/.test(d)&&(b.setStyle("white-space",""),a.options.autoClearEmptyNode&&utils.isEmptyObject(b.attrs)&&b.parentNode.removeChild(b,!0)),d=b.getAttr("id"),d&&/^_baidu_bookmark_/i.test(d)&&b.parentNode.removeChild(b);break;case"p":(d=b.getAttr("align"))&&(b.setAttr("align"),b.setStyle("text-align",d)),utils.each(b.children,function(a){if("element"==a.type&&"p"==a.tagName){var c=a.nextSibling();b.parentNode.insertAfter(a,b);for(var d=a;c;){var e=c.nextSibling();b.parentNode.insertAfter(c,d),d=c,c=e}return!1}}),b.firstChild()||b.innerHTML(browser.ie?" ":"<br/>");break;case"div":if(b.getAttr("cdata_tag"))break;if(d=b.getAttr("class"),d&&/^line number\d+/.test(d))break;if(!e)break;for(var f,g=UE.uNode.createElement("p");f=b.firstChild();)"text"!=f.type&&UE.dom.dtd.$block[f.tagName]?g.firstChild()?(b.parentNode.insertBefore(g,b),g=UE.uNode.createElement("p")):b.parentNode.insertBefore(f,b):g.appendChild(f);g.firstChild()&&b.parentNode.insertBefore(g,b),b.parentNode.removeChild(b);break;case"dl":b.tagName="ul";break;case"dt":case"dd":b.tagName="li";break;case"li":var h=b.getAttr("class");h&&/list\-/.test(h)||b.setAttr();var i=b.getNodesByTagName("ol ul");UE.utils.each(i,function(a){b.parentNode.insertAfter(a,b)});break;case"td":case"th":case"caption":b.children&&b.children.length||b.appendChild(browser.ie11below?UE.uNode.createText(" "):UE.uNode.createElement("br"));break;case"table":a.options.disabledTableInTable&&c(b)&&(b.parentNode.insertBefore(UE.uNode.createText(b.innerText()),b),b.parentNode.removeChild(b))}}})}),a.addOutputRule(function(b){var c;b.traversal(function(b){if("element"==b.type){if(a.options.autoClearEmptyNode&&dtd.$inline[b.tagName]&&!dtd.$empty[b.tagName]&&(!b.attrs||utils.isEmptyObject(b.attrs)))return void(b.firstChild()?"span"!=b.tagName||b.attrs&&!utils.isEmptyObject(b.attrs)||b.parentNode.removeChild(b,!0):b.parentNode.removeChild(b));switch(b.tagName){case"div":(c=b.getAttr("cdata_tag"))&&(b.tagName=c,b.appendChild(UE.uNode.createText(b.getAttr("cdata_data"))),b.setAttr({cdata_tag:"",cdata_data:"",_ue_custom_node_:""}));break;case"a":(c=b.getAttr("_href"))&&b.setAttr({href:utils.html(c),_href:""});break;case"span":c=b.getAttr("id"),c&&/^_baidu_bookmark_/i.test(c)&&b.parentNode.removeChild(b);break;case"img":(c=b.getAttr("_src"))&&b.setAttr({src:b.getAttr("_src"),_src:""})}}})})},UE.commands.inserthtml={execCommand:function(a,b,c){var d,e,f=this;if(b&&f.fireEvent("beforeinserthtml",b)!==!0){if(d=f.selection.getRange(),e=d.document.createElement("div"),e.style.display="inline",!c){var g=UE.htmlparser(b);f.options.filterRules&&UE.filterNode(g,f.options.filterRules),f.filterInputRule(g),b=g.toHtml()}if(e.innerHTML=utils.trim(b),!d.collapsed){var h=d.startContainer;if(domUtils.isFillChar(h)&&d.setStartBefore(h),h=d.endContainer,domUtils.isFillChar(h)&&d.setEndAfter(h),d.txtToElmBoundary(),d.endContainer&&1==d.endContainer.nodeType&&(h=d.endContainer.childNodes[d.endOffset],h&&domUtils.isBr(h)&&d.setEndAfter(h)),0==d.startOffset&&(h=d.startContainer,domUtils.isBoundaryNode(h,"firstChild")&&(h=d.endContainer,d.endOffset==(3==h.nodeType?h.nodeValue.length:h.childNodes.length)&&domUtils.isBoundaryNode(h,"lastChild")&&(f.body.innerHTML="<p>"+(browser.ie?"":"<br/>")+"</p>",d.setStart(f.body.firstChild,0).collapse(!0)))),!d.collapsed&&d.deleteContents(),1==d.startContainer.nodeType){var i,j=d.startContainer.childNodes[d.startOffset];if(j&&domUtils.isBlockElm(j)&&(i=j.previousSibling)&&domUtils.isBlockElm(i)){for(d.setEnd(i,i.childNodes.length).collapse();j.firstChild;)i.appendChild(j.firstChild);domUtils.remove(j)}}}var j,k,i,l,m,n=0;d.inFillChar()&&(j=d.startContainer,domUtils.isFillChar(j)?(d.setStartBefore(j).collapse(!0),domUtils.remove(j)):domUtils.isFillChar(j,!0)&&(j.nodeValue=j.nodeValue.replace(fillCharReg,""),d.startOffset--,d.collapsed&&d.collapse(!0)));var o=domUtils.findParentByTagName(d.startContainer,"li",!0);if(o){for(var p,q;j=e.firstChild;){for(;j&&(3==j.nodeType||!domUtils.isBlockElm(j)||"HR"==j.tagName);)p=j.nextSibling,d.insertNode(j).collapse(),q=j,j=p;if(j)if(/^(ol|ul)$/i.test(j.tagName)){for(;j.firstChild;)q=j.firstChild,domUtils.insertAfter(o,j.firstChild),o=o.nextSibling;domUtils.remove(j)}else{var r;p=j.nextSibling,r=f.document.createElement("li"),domUtils.insertAfter(o,r),r.appendChild(j),q=j,j=p,o=r}}o=domUtils.findParentByTagName(d.startContainer,"li",!0),domUtils.isEmptyBlock(o)&&domUtils.remove(o),q&&d.setStartAfter(q).collapse(!0).select(!0)}else{for(;j=e.firstChild;){if(n){for(var s=f.document.createElement("p");j&&(3==j.nodeType||!dtd.$block[j.tagName]);)m=j.nextSibling,s.appendChild(j),j=m;s.firstChild&&(j=s)}if(d.insertNode(j),m=j.nextSibling,!n&&j.nodeType==domUtils.NODE_ELEMENT&&domUtils.isBlockElm(j)&&(k=domUtils.findParent(j,function(a){return domUtils.isBlockElm(a)}),k&&"body"!=k.tagName.toLowerCase()&&(!dtd[k.tagName][j.nodeName]||j.parentNode!==k))){if(dtd[k.tagName][j.nodeName])for(l=j.parentNode;l!==k;)i=l,l=l.parentNode;else i=k;domUtils.breakParent(j,i||l);var i=j.previousSibling;domUtils.trimWhiteTextNode(i),i.childNodes.length||domUtils.remove(i),!browser.ie&&(p=j.nextSibling)&&domUtils.isBlockElm(p)&&p.lastChild&&!domUtils.isBr(p.lastChild)&&p.appendChild(f.document.createElement("br")),n=1}var p=j.nextSibling;if(!e.firstChild&&p&&domUtils.isBlockElm(p)){d.setStart(p,0).collapse(!0);break}d.setEndAfter(j).collapse()}if(j=d.startContainer,m&&domUtils.isBr(m)&&domUtils.remove(m),domUtils.isBlockElm(j)&&domUtils.isEmptyNode(j))if(m=j.nextSibling)domUtils.remove(j),1==m.nodeType&&dtd.$block[m.tagName]&&d.setStart(m,0).collapse(!0).shrinkBoundary();else try{j.innerHTML=browser.ie?domUtils.fillChar:"<br/>"}catch(t){d.setStartBefore(j),domUtils.remove(j)}try{d.select(!0)}catch(t){}}setTimeout(function(){d=f.selection.getRange(),d.scrollToView(f.autoHeightEnabled,f.autoHeightEnabled?domUtils.getXY(f.iframe).y:0),f.fireEvent("afterinserthtml",b)},200)}}},UE.plugins.autotypeset=function(){function a(a,b){return a&&3!=a.nodeType?domUtils.isBr(a)?1:a&&a.parentNode&&l[a.tagName.toLowerCase()]?g&&g.contains(a)||a.getAttribute("pagebreak")?0:b?!domUtils.isEmptyBlock(a):domUtils.isEmptyBlock(a,new RegExp("[\\s"+domUtils.fillChar+"]","g")):void 0:0}function b(a){a.style.cssText||(domUtils.removeAttributes(a,["style"]),"span"==a.tagName.toLowerCase()&&domUtils.hasNoAttributes(a)&&domUtils.remove(a,!0))}function c(c,f){var h,l=this;if(f){if(!i.pasteFilter)return;h=l.document.createElement("div"),h.innerHTML=f.html}else h=l.document.body;for(var m,n=domUtils.getElementsByTagName(h,"*"),o=0;m=n[o++];)if(l.fireEvent("excludeNodeinautotype",m)!==!0){if(i.clearFontSize&&m.style.fontSize&&(domUtils.removeStyle(m,"font-size"),b(m)),i.clearFontFamily&&m.style.fontFamily&&(domUtils.removeStyle(m,"font-family"),b(m)),a(m)){if(i.mergeEmptyline)for(var p,q=m.nextSibling,r=domUtils.isBr(m);a(q)&&(p=q,q=p.nextSibling,!r||q&&(!q||domUtils.isBr(q)));)domUtils.remove(p);if(i.removeEmptyline&&domUtils.inDoc(m,h)&&!k[m.parentNode.tagName.toLowerCase()]){if(domUtils.isBr(m)&&(q=m.nextSibling,q&&!domUtils.isBr(q)))continue;domUtils.remove(m);continue}}if(a(m,!0)&&"SPAN"!=m.tagName&&(i.indent&&(m.style.textIndent=i.indentValue),i.textAlign&&(m.style.textAlign=i.textAlign)),i.removeClass&&m.className&&!j[m.className.toLowerCase()]){if(g&&g.contains(m))continue;domUtils.removeAttributes(m,["class"])}if(i.imageBlockLine&&"img"==m.tagName.toLowerCase()&&!m.getAttribute("emotion"))if(f){var s=m;switch(i.imageBlockLine){case"left":case"right":case"none":for(var p,t,q,u=s.parentNode;dtd.$inline[u.tagName]||"A"==u.tagName;)u=u.parentNode;if(p=u,"P"==p.tagName&&"center"==domUtils.getStyle(p,"text-align")&&!domUtils.isBody(p)&&1==domUtils.getChildCount(p,function(a){return!domUtils.isBr(a)&&!domUtils.isWhitespace(a)}))if(t=p.previousSibling,q=p.nextSibling,t&&q&&1==t.nodeType&&1==q.nodeType&&t.tagName==q.tagName&&domUtils.isBlockElm(t)){for(t.appendChild(p.firstChild);q.firstChild;)t.appendChild(q.firstChild);domUtils.remove(p),domUtils.remove(q)}else domUtils.setStyle(p,"text-align","");domUtils.setStyle(s,"float",i.imageBlockLine);break;case"center":if("center"!=l.queryCommandValue("imagefloat")){for(u=s.parentNode,domUtils.setStyle(s,"float","none"),p=s;u&&1==domUtils.getChildCount(u,function(a){return!domUtils.isBr(a)&&!domUtils.isWhitespace(a)})&&(dtd.$inline[u.tagName]||"A"==u.tagName);)p=u,u=u.parentNode;var v=l.document.createElement("p");domUtils.setAttributes(v,{style:"text-align:center"}),p.parentNode.insertBefore(v,p),v.appendChild(p),domUtils.setStyle(p,"float","")}}}else{var w=l.selection.getRange();w.selectNode(m).select(),l.execCommand("imagefloat",i.imageBlockLine)}i.removeEmptyNode&&i.removeTagNames[m.tagName.toLowerCase()]&&domUtils.hasNoAttributes(m)&&domUtils.isEmptyBlock(m)&&domUtils.remove(m)}if(i.tobdc){var x=UE.htmlparser(h.innerHTML);x.traversal(function(a){"text"==a.type&&(a.data=e(a.data))}),h.innerHTML=x.toHtml()}if(i.bdc2sb){var x=UE.htmlparser(h.innerHTML);x.traversal(function(a){"text"==a.type&&(a.data=d(a.data))}),h.innerHTML=x.toHtml()}f&&(f.html=h.innerHTML)}function d(a){for(var b="",c=0;c<a.length;c++){var d=a.charCodeAt(c);b+=d>=65281&&d<=65373?String.fromCharCode(a.charCodeAt(c)-65248):12288==d?String.fromCharCode(a.charCodeAt(c)-12288+32):a.charAt(c)}return b}function e(a){a=utils.html(a);for(var b="",c=0;c<a.length;c++)b+=32==a.charCodeAt(c)?String.fromCharCode(12288):a.charCodeAt(c)<127?String.fromCharCode(a.charCodeAt(c)+65248):a.charAt(c);return b}function f(){var a=h.getPreferences("autotypeset");utils.extend(h.options.autotypeset,a)}this.setOpt({autotypeset:{mergeEmptyline:!0,removeClass:!0,removeEmptyline:!1,textAlign:"left",imageBlockLine:"center",pasteFilter:!1,clearFontSize:!1,clearFontFamily:!1,removeEmptyNode:!1,removeTagNames:utils.extend({div:1},dtd.$removeEmpty),indent:!1,indentValue:"2em",bdc2sb:!1,tobdc:!1}});var g,h=this,i=h.options.autotypeset,j={selectTdClass:1,pagebreak:1,anchorclass:1},k={li:1},l={div:1,p:1,blockquote:1,center:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,span:1};i&&(f(),i.pasteFilter&&h.addListener("beforepaste",c),h.commands.autotypeset={execCommand:function(){h.removeListener("beforepaste",c),i.pasteFilter&&h.addListener("beforepaste",c),c.call(h)}})},UE.plugin.register("autosubmit",function(){return{shortcutkey:{autosubmit:"ctrl+13"},commands:{autosubmit:{execCommand:function(){var a=this,b=domUtils.findParentByTagName(a.iframe,"form",!1);if(b){if(a.fireEvent("beforesubmit")===!1)return;a.sync(),b.submit()}}}}}}),UE.plugin.register("background",function(){function a(a){var b={},c=a.split(";");return utils.each(c,function(a){var c=a.indexOf(":"),d=utils.trim(a.substr(0,c)).toLowerCase();d&&(b[d]=utils.trim(a.substr(c+1)||""))}),b}function b(a){if(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(c+":"+a[c]+"; ");utils.cssRule(e,b.length?"body{"+b.join("")+"}":"",d.document)}else utils.cssRule(e,"",d.document)}var c,d=this,e="editor_background",f=new RegExp("body[\\s]*\\{(.+)\\}","i"),g=d.hasContents;return d.hasContents=function(){return!!d.queryCommandValue("background")||g.apply(d,arguments)},{bindEvents:{getAllHtml:function(a,b){var c=this.body,e=domUtils.getComputedStyle(c,"background-image"),f="";
f=e.indexOf(d.options.imagePath)>0?e.substring(e.indexOf(d.options.imagePath),e.length-1).replace(/"|\(|\)/gi,""):"none"!=e?e.replace(/url\("?|"?\)/gi,""):"";var g='<style type="text/css">body{',h={"background-color":domUtils.getComputedStyle(c,"background-color")||"#ffffff","background-image":f?"url("+f+")":"","background-repeat":domUtils.getComputedStyle(c,"background-repeat")||"","background-position":browser.ie?domUtils.getComputedStyle(c,"background-position-x")+" "+domUtils.getComputedStyle(c,"background-position-y"):domUtils.getComputedStyle(c,"background-position"),height:domUtils.getComputedStyle(c,"height")};for(var i in h)h.hasOwnProperty(i)&&(g+=i+":"+h[i]+"; ");g+="}</style> ",b.push(g)},aftersetcontent:function(){0==c&&b()}},inputRule:function(d){c=!1,utils.each(d.getNodesByTagName("p"),function(d){var e=d.getAttr("data-background");e&&(c=!0,b(a(e)),d.parentNode.removeChild(d))})},outputRule:function(a){var b=this,c=(utils.cssRule(e,b.document)||"").replace(/[\n\r]+/g,"").match(f);c&&a.appendChild(UE.uNode.createElement('<p style="display:none;" data-background="'+utils.trim(c[1].replace(/"/g,"").replace(/[\s]+/g," "))+'"><br/></p>'))},commands:{background:{execCommand:function(a,c){b(c)},queryCommandValue:function(){var b=this,c=(utils.cssRule(e,b.document)||"").replace(/[\n\r]+/g,"").match(f);return c?a(c[1]):null},notNeedUndo:!0}}}}),UE.commands.imagefloat={execCommand:function(a,b){var c=this,d=c.selection.getRange();if(!d.collapsed){var e=d.getClosedNode();if(e&&"IMG"==e.tagName)switch(b){case"left":case"right":case"none":for(var f,g,h,i=e.parentNode;dtd.$inline[i.tagName]||"A"==i.tagName;)i=i.parentNode;if(f=i,"P"==f.tagName&&"center"==domUtils.getStyle(f,"text-align")){if(!domUtils.isBody(f)&&1==domUtils.getChildCount(f,function(a){return!domUtils.isBr(a)&&!domUtils.isWhitespace(a)}))if(g=f.previousSibling,h=f.nextSibling,g&&h&&1==g.nodeType&&1==h.nodeType&&g.tagName==h.tagName&&domUtils.isBlockElm(g)){for(g.appendChild(f.firstChild);h.firstChild;)g.appendChild(h.firstChild);domUtils.remove(f),domUtils.remove(h)}else domUtils.setStyle(f,"text-align","");d.selectNode(e).select()}domUtils.setStyle(e,"float","none"==b?"":b),"none"==b&&domUtils.removeAttributes(e,"align");break;case"center":if("center"!=c.queryCommandValue("imagefloat")){for(i=e.parentNode,domUtils.setStyle(e,"float",""),domUtils.removeAttributes(e,"align"),f=e;i&&1==domUtils.getChildCount(i,function(a){return!domUtils.isBr(a)&&!domUtils.isWhitespace(a)})&&(dtd.$inline[i.tagName]||"A"==i.tagName);)f=i,i=i.parentNode;d.setStartBefore(f).setCursor(!1),i=c.document.createElement("div"),i.appendChild(f),domUtils.setStyle(f,"float",""),c.execCommand("insertHtml",'<p id="_img_parent_tmp" style="text-align:center">'+i.innerHTML+"</p>"),f=c.document.getElementById("_img_parent_tmp"),f.removeAttribute("id"),f=f.firstChild,d.selectNode(f).select(),h=f.parentNode.nextSibling,h&&domUtils.isEmptyNode(h)&&domUtils.remove(h)}}}},queryCommandValue:function(){var a,b,c=this.selection.getRange();return c.collapsed?"none":(a=c.getClosedNode(),a&&1==a.nodeType&&"IMG"==a.tagName?(b=domUtils.getComputedStyle(a,"float")||a.getAttribute("align"),"none"==b&&(b="center"==domUtils.getComputedStyle(a.parentNode,"text-align")?"center":b),{left:1,right:1,center:1}[b]?b:"none"):"none")},queryCommandState:function(){var a,b=this.selection.getRange();return b.collapsed?-1:(a=b.getClosedNode(),a&&1==a.nodeType&&"IMG"==a.tagName?0:-1)}},UE.commands.insertimage={execCommand:function(a,b){function c(a){utils.each("width,height,border,hspace,vspace".split(","),function(b){a[b]&&(a[b]=parseInt(a[b],10)||0)}),utils.each("src,_src".split(","),function(b){a[b]&&(a[b]=utils.unhtmlForUrl(a[b]))}),utils.each("title,alt".split(","),function(b){a[b]&&(a[b]=utils.unhtml(a[b]))})}if(b=utils.isArray(b)?b:[b],b.length){var d=this,e=d.selection.getRange(),f=e.getClosedNode();if(d.fireEvent("beforeinsertimage",b)!==!0){if(!f||!/img/i.test(f.tagName)||"edui-faked-video"==f.className&&f.className.indexOf("edui-upload-video")==-1||f.getAttribute("word_img")){var g,h=[],i="";if(g=b[0],1==b.length)c(g),i='<img src="'+g.src+'" '+(g._src?' _src="'+g._src+'" ':"")+(g.width?'width="'+g.width+'" ':"")+(g.height?' height="'+g.height+'" ':"")+("left"==g.floatStyle||"right"==g.floatStyle?' style="float:'+g.floatStyle+';"':"")+(g.title&&""!=g.title?' title="'+g.title+'"':"")+(g.border&&"0"!=g.border?' border="'+g.border+'"':"")+(g.alt&&""!=g.alt?' alt="'+g.alt+'"':"")+(g.hspace&&"0"!=g.hspace?' hspace = "'+g.hspace+'"':"")+(g.vspace&&"0"!=g.vspace?' vspace = "'+g.vspace+'"':"")+"/>","center"==g.floatStyle&&(i='<p style="text-align: center">'+i+"</p>"),h.push(i);else for(var j=0;g=b[j++];)c(g),i="<p "+("center"==g.floatStyle?'style="text-align: center" ':"")+'><img src="'+g.src+'" '+(g.width?'width="'+g.width+'" ':"")+(g._src?' _src="'+g._src+'" ':"")+(g.height?' height="'+g.height+'" ':"")+' style="'+(g.floatStyle&&"center"!=g.floatStyle?"float:"+g.floatStyle+";":"")+(g.border||"")+'" '+(g.title?' title="'+g.title+'"':"")+" /></p>",h.push(i);d.execCommand("insertHtml",h.join(""))}else{var k=b.shift(),l=k.floatStyle;delete k.floatStyle,domUtils.setAttributes(f,k),d.execCommand("imagefloat",l),b.length>0&&(e.setStartAfter(f).setCursor(!1,!0),d.execCommand("insertimage",b))}d.fireEvent("afterinsertimage",b)}}}},UE.plugins.justify=function(){var a=domUtils.isBlockElm,b={left:1,right:1,center:1,justify:1},c=function(b,c){var d=b.createBookmark(),e=function(a){return 1==a.nodeType?"br"!=a.tagName.toLowerCase()&&!domUtils.isBookmarkNode(a):!domUtils.isWhitespace(a)};b.enlarge(!0);for(var f,g=b.createBookmark(),h=domUtils.getNextDomNode(g.start,!1,e),i=b.cloneRange();h&&!(domUtils.getPosition(h,g.end)&domUtils.POSITION_FOLLOWING);)if(3!=h.nodeType&&a(h))h=domUtils.getNextDomNode(h,!0,e);else{for(i.setStartBefore(h);h&&h!==g.end&&!a(h);)f=h,h=domUtils.getNextDomNode(h,!1,null,function(b){return!a(b)});i.setEndAfter(f);var j=i.getCommonAncestor();if(!domUtils.isBody(j)&&a(j))domUtils.setStyles(j,utils.isString(c)?{"text-align":c}:c),h=j;else{var k=b.document.createElement("p");domUtils.setStyles(k,utils.isString(c)?{"text-align":c}:c);var l=i.extractContents();k.appendChild(l),i.insertNode(k),h=k}h=domUtils.getNextDomNode(h,!1,e)}return b.moveToBookmark(g).moveToBookmark(d)};UE.commands.justify={execCommand:function(a,b){var d,e=this.selection.getRange();return e.collapsed&&(d=this.document.createTextNode("p"),e.insertNode(d)),c(e,b),d&&(e.setStartBefore(d).collapse(!0),domUtils.remove(d)),e.select(),!0},queryCommandValue:function(){var a=this.selection.getStart(),c=domUtils.getComputedStyle(a,"text-align");return b[c]?c:"left"},queryCommandState:function(){var a=this.selection.getStart(),b=a&&domUtils.findParentByTagName(a,["td","th","caption"],!0);return b?-1:0}}},UE.plugins.font=function(){function a(a){for(var b;(b=a.parentNode)&&"SPAN"==b.tagName&&1==domUtils.getChildCount(b,function(a){return!domUtils.isBookmarkNode(a)&&!domUtils.isBr(a)});)b.style.cssText+=a.style.cssText,domUtils.remove(a,!0),a=b}function b(a,b,c){if(g[b]&&(a.adjustmentBoundary(),!a.collapsed&&1==a.startContainer.nodeType)){var d=a.startContainer.childNodes[a.startOffset];if(d&&domUtils.isTagNode(d,"span")){var e=a.createBookmark();utils.each(domUtils.getElementsByTagName(d,"span"),function(a){a.parentNode&&!domUtils.isBookmarkNode(a)&&("backcolor"==b&&domUtils.getComputedStyle(a,"background-color").toLowerCase()===c||(domUtils.removeStyle(a,g[b]),0==a.style.cssText.replace(/^\s+$/,"").length&&domUtils.remove(a,!0)))}),a.moveToBookmark(e)}}}function c(c,d,e){var f,g=c.collapsed,h=c.createBookmark();if(g)for(f=h.start.parentNode;dtd.$inline[f.tagName];)f=f.parentNode;else f=domUtils.getCommonAncestor(h.start,h.end);utils.each(domUtils.getElementsByTagName(f,"span"),function(b){if(b.parentNode&&!domUtils.isBookmarkNode(b)){if(/\s*border\s*:\s*none;?\s*/i.test(b.style.cssText))return void(/^\s*border\s*:\s*none;?\s*$/.test(b.style.cssText)?domUtils.remove(b,!0):domUtils.removeStyle(b,"border"));if(/border/i.test(b.style.cssText)&&"SPAN"==b.parentNode.tagName&&/border/i.test(b.parentNode.style.cssText)&&(b.style.cssText=b.style.cssText.replace(/border[^:]*:[^;]+;?/gi,"")),"fontborder"!=d||"none"!=e)for(var c=b.nextSibling;c&&1==c.nodeType&&"SPAN"==c.tagName;)if(domUtils.isBookmarkNode(c)&&"fontborder"==d)b.appendChild(c),c=b.nextSibling;else{if(c.style.cssText==b.style.cssText&&(domUtils.moveChild(c,b),domUtils.remove(c)),b.nextSibling===c)break;c=b.nextSibling}if(a(b),browser.ie&&browser.version>8){var f=domUtils.findParent(b,function(a){return"SPAN"==a.tagName&&/background-color/.test(a.style.cssText)});f&&!/background-color/.test(b.style.cssText)&&(b.style.backgroundColor=f.style.backgroundColor)}}}),c.moveToBookmark(h),b(c,d,e)}var d=this,e={forecolor:"color",backcolor:"background-color",fontsize:"font-size",fontfamily:"font-family",underline:"text-decoration",strikethrough:"text-decoration",fontborder:"border"},f={underline:1,strikethrough:1,fontborder:1},g={forecolor:"color",backcolor:"background-color",fontsize:"font-size",fontfamily:"font-family"};d.setOpt({fontfamily:[{name:"songti",val:"宋体,SimSun"},{name:"yahei",val:"微软雅黑,Microsoft YaHei"},{name:"kaiti",val:"楷体,楷体_GB2312, SimKai"},{name:"heiti",val:"黑体, SimHei"},{name:"lishu",val:"隶书, SimLi"},{name:"andaleMono",val:"andale mono"},{name:"arial",val:"arial, helvetica,sans-serif"},{name:"arialBlack",val:"arial black,avant garde"},{name:"comicSansMs",val:"comic sans ms"},{name:"impact",val:"impact,chicago"},{name:"timesNewRoman",val:"times new roman"}],fontsize:[10,11,12,14,16,18,20,24,36]}),d.addInputRule(function(a){utils.each(a.getNodesByTagName("u s del font strike"),function(a){if("font"==a.tagName){var b=[];for(var c in a.attrs)switch(c){case"size":b.push("font-size:"+({1:"10",2:"12",3:"16",4:"18",5:"24",6:"32",7:"48"}[a.attrs[c]]||a.attrs[c])+"px");break;case"color":b.push("color:"+a.attrs[c]);break;case"face":b.push("font-family:"+a.attrs[c]);break;case"style":b.push(a.attrs[c])}a.attrs={style:b.join(";")}}else{var d="u"==a.tagName?"underline":"line-through";a.attrs={style:(a.getAttr("style")||"")+"text-decoration:"+d+";"}}a.tagName="span"})});for(var h in e)!function(a,b){UE.commands[a]={execCommand:function(d,e){e=e||(this.queryCommandState(d)?"none":"underline"==d?"underline":"fontborder"==d?"1px solid #000":"line-through");var g,h=this,i=this.selection.getRange();if("default"==e)i.collapsed&&(g=h.document.createTextNode("font"),i.insertNode(g).select()),h.execCommand("removeFormat","span,a",b),g&&(i.setStartBefore(g).collapse(!0),domUtils.remove(g)),c(i,d,e),i.select();else if(i.collapsed){var j=domUtils.findParentByTagName(i.startContainer,"span",!0);if(g=h.document.createTextNode("font"),!j||j.children.length||j[browser.ie?"innerText":"textContent"].replace(fillCharReg,"").length){if(i.insertNode(g),i.selectNode(g).select(),j=i.document.createElement("span"),f[a]){if(domUtils.findParentByTagName(g,"a",!0))return i.setStartBefore(g).setCursor(),void domUtils.remove(g);h.execCommand("removeFormat","span,a",b)}if(j.style.cssText=b+":"+e,g.parentNode.insertBefore(j,g),!browser.ie||browser.ie&&9==browser.version)for(var k=j.parentNode;!domUtils.isBlockElm(k);)"SPAN"==k.tagName&&(j.style.cssText=k.style.cssText+";"+j.style.cssText),k=k.parentNode;opera?setTimeout(function(){i.setStart(j,0).collapse(!0),c(i,d,e),i.select()}):(i.setStart(j,0).collapse(!0),c(i,d,e),i.select())}else i.insertNode(g),f[a]&&(i.selectNode(g).select(),h.execCommand("removeFormat","span,a",b,null),j=domUtils.findParentByTagName(g,"span",!0),i.setStartBefore(g)),j&&(j.style.cssText+=";"+b+":"+e),i.collapse(!0).select();domUtils.remove(g)}else f[a]&&h.queryCommandValue(a)&&h.execCommand("removeFormat","span,a",b),i=h.selection.getRange(),i.applyInlineStyle("span",{style:b+":"+e}),c(i,d,e),i.select();return!0},queryCommandValue:function(a){var c=this.selection.getStart();if("underline"==a||"strikethrough"==a){for(var d,e=c;e&&!domUtils.isBlockElm(e)&&!domUtils.isBody(e);){if(1==e.nodeType&&(d=domUtils.getComputedStyle(e,b),"none"!=d))return d;e=e.parentNode}return"none"}if("fontborder"==a){for(var f,g=c;g&&dtd.$inline[g.tagName];){if((f=domUtils.getComputedStyle(g,"border"))&&/1px/.test(f)&&/solid/.test(f))return f;g=g.parentNode}return""}if("FontSize"==a){var h=domUtils.getComputedStyle(c,b),g=/^([\d\.]+)(\w+)$/.exec(h);return g?Math.floor(g[1])+g[2]:h}return domUtils.getComputedStyle(c,b)},queryCommandState:function(a){if(!f[a])return 0;var b=this.queryCommandValue(a);return"fontborder"==a?/1px/.test(b)&&/solid/.test(b):"underline"==a?/underline/.test(b):/line\-through/.test(b)}}}(h,e[h])},UE.plugins.link=function(){function a(a){var b=a.startContainer,c=a.endContainer;(b=domUtils.findParentByTagName(b,"a",!0))&&a.setStartBefore(b),(c=domUtils.findParentByTagName(c,"a",!0))&&a.setEndAfter(c)}function b(b,c,d){var e=b.cloneRange(),f=d.queryCommandValue("link");a(b=b.adjustmentBoundary());var g=b.startContainer;if(1==g.nodeType&&f&&(g=g.childNodes[b.startOffset],g&&1==g.nodeType&&"A"==g.tagName&&/^(?:https?|ftp|file)\s*:\s*\/\//.test(g[browser.ie?"innerText":"textContent"])&&(g[browser.ie?"innerText":"textContent"]=utils.html(c.textValue||c.href))),e.collapsed&&!f||(b.removeInlineStyle("a"),e=b.cloneRange()),e.collapsed){var h=b.document.createElement("a"),i="";c.textValue?(i=utils.html(c.textValue),delete c.textValue):i=utils.html(c.href),domUtils.setAttributes(h,c),g=domUtils.findParentByTagName(e.startContainer,"a",!0),g&&domUtils.isInNodeEndBoundary(e,g)&&b.setStartAfter(g).collapse(!0),h[browser.ie?"innerText":"textContent"]=i,b.insertNode(h).selectNode(h)}else b.applyInlineStyle("a",c)}UE.commands.unlink={execCommand:function(){var b,c=this.selection.getRange();c.collapsed&&!domUtils.findParentByTagName(c.startContainer,"a",!0)||(b=c.createBookmark(),a(c),c.removeInlineStyle("a").moveToBookmark(b).select())},queryCommandState:function(){return!this.highlight&&this.queryCommandValue("link")?0:-1}},UE.commands.link={execCommand:function(a,c){var d;c._href&&(c._href=utils.unhtml(c._href,/[<">]/g)),c.href&&(c.href=utils.unhtml(c.href,/[<">]/g)),c.textValue&&(c.textValue=utils.unhtml(c.textValue,/[<">]/g)),b(d=this.selection.getRange(),c,this),d.collapse().select(!0)},queryCommandValue:function(){var a,b=this.selection.getRange();if(!b.collapsed){b.shrinkBoundary();var c=3!=b.startContainer.nodeType&&b.startContainer.childNodes[b.startOffset]?b.startContainer.childNodes[b.startOffset]:b.startContainer,d=3==b.endContainer.nodeType||0==b.endOffset?b.endContainer:b.endContainer.childNodes[b.endOffset-1],e=b.getCommonAncestor();if(a=domUtils.findParentByTagName(e,"a",!0),!a&&1==e.nodeType)for(var f,g,h,i=e.getElementsByTagName("a"),j=0;h=i[j++];)if(f=domUtils.getPosition(h,c),g=domUtils.getPosition(h,d),(f&domUtils.POSITION_FOLLOWING||f&domUtils.POSITION_CONTAINS)&&(g&domUtils.POSITION_PRECEDING||g&domUtils.POSITION_CONTAINS)){a=h;break}return a}if(a=b.startContainer,a=1==a.nodeType?a:a.parentNode,a&&(a=domUtils.findParentByTagName(a,"a",!0))&&!domUtils.isInNodeEndBoundary(b,a))return a},queryCommandState:function(){var a=this.selection.getRange().getClosedNode(),b=a&&("edui-faked-video"==a.className||a.className.indexOf("edui-upload-video")!=-1);return b?-1:0}}},UE.plugins.insertframe=function(){function a(){b._iframe&&delete b._iframe}var b=this;b.addListener("selectionchange",function(){a()})},UE.commands.scrawl={queryCommandState:function(){return browser.ie&&browser.version<=8?-1:0}},UE.plugins.removeformat=function(){var a=this;a.setOpt({removeFormatTags:"b,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var",removeFormatAttributes:"class,style,lang,width,height,align,hspace,valign"}),a.commands.removeformat={execCommand:function(a,b,c,d,e){function f(a){if(3==a.nodeType||"span"!=a.tagName.toLowerCase())return 0;if(browser.ie){var b=a.attributes;if(b.length){for(var c=0,d=b.length;c<d;c++)if(b[c].specified)return 0;return 1}}return!a.attributes.length}function g(a){var b=a.createBookmark();if(a.collapsed&&a.enlarge(!0),!e){var d=domUtils.findParentByTagName(a.startContainer,"a",!0);d&&a.setStartBefore(d),d=domUtils.findParentByTagName(a.endContainer,"a",!0),d&&a.setEndAfter(d)}for(h=a.createBookmark(),p=h.start;(i=p.parentNode)&&!domUtils.isBlockElm(i);)domUtils.breakParent(p,i),domUtils.clearEmptySibling(p);if(h.end){for(p=h.end;(i=p.parentNode)&&!domUtils.isBlockElm(i);)domUtils.breakParent(p,i),domUtils.clearEmptySibling(p);for(var g,l=domUtils.getNextDomNode(h.start,!1,m);l&&l!=h.end;)g=domUtils.getNextDomNode(l,!0,m),dtd.$empty[l.tagName.toLowerCase()]||domUtils.isBookmarkNode(l)||(j.test(l.tagName)?c?(domUtils.removeStyle(l,c),f(l)&&"text-decoration"!=c&&domUtils.remove(l,!0)):domUtils.remove(l,!0):dtd.$tableContent[l.tagName]||dtd.$list[l.tagName]||(domUtils.removeAttributes(l,k),f(l)&&domUtils.remove(l,!0))),l=g}var n=h.start.parentNode;!domUtils.isBlockElm(n)||dtd.$tableContent[n.tagName]||dtd.$list[n.tagName]||domUtils.removeAttributes(n,k),n=h.end.parentNode,h.end&&domUtils.isBlockElm(n)&&!dtd.$tableContent[n.tagName]&&!dtd.$list[n.tagName]&&domUtils.removeAttributes(n,k),a.moveToBookmark(h).moveToBookmark(b);for(var o,p=a.startContainer,q=a.collapsed;1==p.nodeType&&domUtils.isEmptyNode(p)&&dtd.$removeEmpty[p.tagName];)o=p.parentNode,a.setStartBefore(p),a.startContainer===a.endContainer&&a.endOffset--,domUtils.remove(p),p=o;if(!q)for(p=a.endContainer;1==p.nodeType&&domUtils.isEmptyNode(p)&&dtd.$removeEmpty[p.tagName];)o=p.parentNode,a.setEndBefore(p),domUtils.remove(p),p=o}var h,i,j=new RegExp("^(?:"+(b||this.options.removeFormatTags).replace(/,/g,"|")+")$","i"),k=c?[]:(d||this.options.removeFormatAttributes).split(","),l=new dom.Range(this.document),m=function(a){return 1==a.nodeType};l=this.selection.getRange(),g(l),l.select()}}},UE.plugins.blockquote=function(){function a(a){return domUtils.filterNodeList(a.selection.getStartElementPath(),"blockquote")}var b=this;b.commands.blockquote={execCommand:function(b,c){var d=this.selection.getRange(),e=a(this),f=dtd.blockquote,g=d.createBookmark();if(e){var h=d.startContainer,i=domUtils.isBlockElm(h)?h:domUtils.findParent(h,function(a){return domUtils.isBlockElm(a)}),j=d.endContainer,k=domUtils.isBlockElm(j)?j:domUtils.findParent(j,function(a){return domUtils.isBlockElm(a)});i=domUtils.findParentByTagName(i,"li",!0)||i,k=domUtils.findParentByTagName(k,"li",!0)||k,"LI"==i.tagName||"TD"==i.tagName||i===e||domUtils.isBody(i)?domUtils.remove(e,!0):domUtils.breakParent(i,e),i!==k&&(e=domUtils.findParentByTagName(k,"blockquote"),e&&("LI"==k.tagName||"TD"==k.tagName||domUtils.isBody(k)?e.parentNode&&domUtils.remove(e,!0):domUtils.breakParent(k,e)));for(var l,m=domUtils.getElementsByTagName(this.document,"blockquote"),n=0;l=m[n++];)l.childNodes.length?domUtils.getPosition(l,i)&domUtils.POSITION_FOLLOWING&&domUtils.getPosition(l,k)&domUtils.POSITION_PRECEDING&&domUtils.remove(l,!0):domUtils.remove(l)}else{for(var o=d.cloneRange(),p=1==o.startContainer.nodeType?o.startContainer:o.startContainer.parentNode,q=p,r=1;;){if(domUtils.isBody(p)){q!==p?d.collapsed?(o.selectNode(q),r=0):o.setStartBefore(q):o.setStart(p,0);break}if(!f[p.tagName]){d.collapsed?o.selectNode(q):o.setStartBefore(q);break}q=p,p=p.parentNode}if(r)for(q=p=p=1==o.endContainer.nodeType?o.endContainer:o.endContainer.parentNode;;){if(domUtils.isBody(p)){q!==p?o.setEndAfter(q):o.setEnd(p,p.childNodes.length);break}if(!f[p.tagName]){o.setEndAfter(q);break}q=p,p=p.parentNode}p=d.document.createElement("blockquote"),domUtils.setAttributes(p,c),p.appendChild(o.extractContents()),o.insertNode(p);for(var s,t=domUtils.getElementsByTagName(p,"blockquote"),n=0;s=t[n++];)s.parentNode&&domUtils.remove(s,!0)}d.moveToBookmark(g).select()},queryCommandState:function(){return a(this)?1:0}}},UE.commands.touppercase=UE.commands.tolowercase={execCommand:function(a){var b=this,c=b.selection.getRange();if(c.collapsed)return c;for(var d=c.createBookmark(),e=d.end,f=function(a){return!domUtils.isBr(a)&&!domUtils.isWhitespace(a)},g=domUtils.getNextDomNode(d.start,!1,f);g&&domUtils.getPosition(g,e)&domUtils.POSITION_PRECEDING&&(3==g.nodeType&&(g.nodeValue=g.nodeValue["touppercase"==a?"toUpperCase":"toLowerCase"]()),g=domUtils.getNextDomNode(g,!0,f),g!==e););c.moveToBookmark(d).select()}},UE.commands.indent={execCommand:function(){var a=this,b=a.queryCommandState("indent")?"0em":a.options.indentValue||"2em";a.execCommand("Paragraph","p",{style:"text-indent:"+b})},queryCommandState:function(){var a=domUtils.filterNodeList(this.selection.getStartElementPath(),"p h1 h2 h3 h4 h5 h6");return a&&a.style.textIndent&&parseInt(a.style.textIndent)?1:0}},UE.commands.print={execCommand:function(){this.window.print()},notNeedUndo:1},UE.commands.preview={execCommand:function(){var a=window.open("","_blank",""),b=a.document;b.open(),b.write('<!DOCTYPE html><html><head><meta charset="utf-8"/><script src="'+this.options.UEDITOR_HOME_URL+"ueditor.parse.js\"></script><script>setTimeout(function(){uParse('div',{rootPath: '"+this.options.UEDITOR_HOME_URL+"'})},300)</script></head><body><div>"+this.getContent(null,null,!0)+"</div></body></html>"),b.close()},notNeedUndo:1},UE.plugins.selectall=function(){var a=this;a.commands.selectall={execCommand:function(){var a=this,b=a.body,c=a.selection.getRange();c.selectNodeContents(b),domUtils.isEmptyBlock(b)&&(browser.opera&&b.firstChild&&1==b.firstChild.nodeType&&c.setStartAtFirst(b.firstChild),c.collapse(!0)),c.select(!0)},notNeedUndo:1},a.addshortcutkey({selectAll:"ctrl+65"})},UE.plugins.paragraph=function(){var a=this,b=domUtils.isBlockElm,c=["TD","LI","PRE"],d=function(a,d,e,f){var g,h=a.createBookmark(),i=function(a){return 1==a.nodeType?"br"!=a.tagName.toLowerCase()&&!domUtils.isBookmarkNode(a):!domUtils.isWhitespace(a)};a.enlarge(!0);for(var j,k=a.createBookmark(),l=domUtils.getNextDomNode(k.start,!1,i),m=a.cloneRange();l&&!(domUtils.getPosition(l,k.end)&domUtils.POSITION_FOLLOWING);)if(3!=l.nodeType&&b(l))l=domUtils.getNextDomNode(l,!0,i);else{for(m.setStartBefore(l);l&&l!==k.end&&!b(l);)j=l,l=domUtils.getNextDomNode(l,!1,null,function(a){return!b(a)});m.setEndAfter(j),g=a.document.createElement(d),e&&(domUtils.setAttributes(g,e),f&&"customstyle"==f&&e.style&&(g.style.cssText=e.style)),g.appendChild(m.extractContents()),domUtils.isEmptyNode(g)&&domUtils.fillChar(a.document,g),m.insertNode(g);var n=g.parentNode;b(n)&&!domUtils.isBody(g.parentNode)&&utils.indexOf(c,n.tagName)==-1&&(f&&"customstyle"==f||(n.getAttribute("dir")&&g.setAttribute("dir",n.getAttribute("dir")),n.style.cssText&&(g.style.cssText=n.style.cssText+";"+g.style.cssText),n.style.textAlign&&!g.style.textAlign&&(g.style.textAlign=n.style.textAlign),n.style.textIndent&&!g.style.textIndent&&(g.style.textIndent=n.style.textIndent),n.style.padding&&!g.style.padding&&(g.style.padding=n.style.padding)),e&&/h\d/i.test(n.tagName)&&!/h\d/i.test(g.tagName)?(domUtils.setAttributes(n,e),f&&"customstyle"==f&&e.style&&(n.style.cssText=e.style),domUtils.remove(g,!0),g=n):domUtils.remove(g.parentNode,!0)),l=utils.indexOf(c,n.tagName)!=-1?n:g,l=domUtils.getNextDomNode(l,!1,i)}return a.moveToBookmark(k).moveToBookmark(h)};a.setOpt("paragraph",{p:"",h1:"",h2:"",h3:"",h4:"",h5:"",h6:""}),a.commands.paragraph={execCommand:function(a,b,c,e){var f=this.selection.getRange();if(f.collapsed){var g=this.document.createTextNode("p");if(f.insertNode(g),browser.ie){var h=g.previousSibling;h&&domUtils.isWhitespace(h)&&domUtils.remove(h),h=g.nextSibling,h&&domUtils.isWhitespace(h)&&domUtils.remove(h)}}if(f=d(f,b,c,e),g&&(f.setStartBefore(g).collapse(!0),pN=g.parentNode,domUtils.remove(g),domUtils.isBlockElm(pN)&&domUtils.isEmptyNode(pN)&&domUtils.fillNode(this.document,pN)),browser.gecko&&f.collapsed&&1==f.startContainer.nodeType){var i=f.startContainer.childNodes[f.startOffset];i&&1==i.nodeType&&i.tagName.toLowerCase()==b&&f.setStart(i,0).collapse(!0)}return f.select(),!0},queryCommandValue:function(){var a=domUtils.filterNodeList(this.selection.getStartElementPath(),"p h1 h2 h3 h4 h5 h6");return a?a.tagName.toLowerCase():""}}},function(){var a=domUtils.isBlockElm,b=function(a){return domUtils.filterNodeList(a.selection.getStartElementPath(),function(a){return a&&1==a.nodeType&&a.getAttribute("dir")})},c=function(c,d,e){var f,g=function(a){return 1==a.nodeType?!domUtils.isBookmarkNode(a):!domUtils.isWhitespace(a)},h=b(d);if(h&&c.collapsed)return h.setAttribute("dir",e),c;f=c.createBookmark(),c.enlarge(!0);for(var i,j=c.createBookmark(),k=domUtils.getNextDomNode(j.start,!1,g),l=c.cloneRange();k&&!(domUtils.getPosition(k,j.end)&domUtils.POSITION_FOLLOWING);)if(3!=k.nodeType&&a(k))k=domUtils.getNextDomNode(k,!0,g);else{for(l.setStartBefore(k);k&&k!==j.end&&!a(k);)i=k,k=domUtils.getNextDomNode(k,!1,null,function(b){return!a(b)});l.setEndAfter(i);var m=l.getCommonAncestor();if(!domUtils.isBody(m)&&a(m))m.setAttribute("dir",e),k=m;else{var n=c.document.createElement("p");n.setAttribute("dir",e);var o=l.extractContents();n.appendChild(o),l.insertNode(n),k=n}k=domUtils.getNextDomNode(k,!1,g)}return c.moveToBookmark(j).moveToBookmark(f)};UE.commands.directionality={execCommand:function(a,b){var d=this.selection.getRange();if(d.collapsed){var e=this.document.createTextNode("d");d.insertNode(e)}return c(d,this,b),e&&(d.setStartBefore(e).collapse(!0),domUtils.remove(e)),d.select(),!0},queryCommandValue:function(){var a=b(this);return a?a.getAttribute("dir"):"ltr"}}}(),UE.plugins.horizontal=function(){var a=this;a.commands.horizontal={execCommand:function(a){var b=this;if(b.queryCommandState(a)!==-1){b.execCommand("insertHtml","<hr>");var c=b.selection.getRange(),d=c.startContainer;if(1==d.nodeType&&!d.childNodes[c.startOffset]){var e;(e=d.childNodes[c.startOffset-1])&&1==e.nodeType&&"HR"==e.tagName&&("p"==b.options.enterTag?(e=b.document.createElement("p"),c.insertNode(e),c.setStart(e,0).setCursor()):(e=b.document.createElement("br"),c.insertNode(e),c.setStartBefore(e).setCursor()))}return!0}},queryCommandState:function(){return domUtils.filterNodeList(this.selection.getStartElementPath(),"table")?-1:0}},a.addListener("delkeydown",function(a,b){var c=this.selection.getRange();if(c.txtToElmBoundary(!0),domUtils.isStartInblock(c)){var d=c.startContainer,e=d.previousSibling;if(e&&domUtils.isTagNode(e,"hr"))return domUtils.remove(e),c.select(),domUtils.preventDefault(b),!0}})},UE.commands.time=UE.commands.date={execCommand:function(a,b){function c(a,b){var c=("0"+a.getHours()).slice(-2),d=("0"+a.getMinutes()).slice(-2),e=("0"+a.getSeconds()).slice(-2);return b=b||"hh:ii:ss",b.replace(/hh/gi,c).replace(/ii/gi,d).replace(/ss/gi,e)}function d(a,b){var c=("000"+a.getFullYear()).slice(-4),d=c.slice(-2),e=("0"+(a.getMonth()+1)).slice(-2),f=("0"+a.getDate()).slice(-2);return b=b||"yyyy-mm-dd",b.replace(/yyyy/gi,c).replace(/yy/gi,d).replace(/mm/gi,e).replace(/dd/gi,f)}var e=new Date;this.execCommand("insertHtml","time"==a?c(e,b):d(e,b))}},UE.plugins.rowspacing=function(){var a=this;a.setOpt({rowspacingtop:["5","10","15","20","25"],rowspacingbottom:["5","10","15","20","25"]}),a.commands.rowspacing={execCommand:function(a,b,c){return this.execCommand("paragraph","p",{style:"margin-"+c+":"+b+"px"}),!0},queryCommandValue:function(a,b){var c,d=domUtils.filterNodeList(this.selection.getStartElementPath(),function(a){return domUtils.isBlockElm(a)});return d?(c=domUtils.getComputedStyle(d,"margin-"+b).replace(/[^\d]/g,""),c?c:0):0}}},UE.plugins.lineheight=function(){var a=this;a.setOpt({lineheight:["1","1.5","1.75","2","3","4","5"]}),a.commands.lineheight={execCommand:function(a,b){return this.execCommand("paragraph","p",{style:"line-height:"+("1"==b?"normal":b+"em")}),!0},queryCommandValue:function(){var a=domUtils.filterNodeList(this.selection.getStartElementPath(),function(a){return domUtils.isBlockElm(a)});if(a){var b=domUtils.getComputedStyle(a,"line-height");return"normal"==b?1:b.replace(/[^\d.]*/gi,"")}}}},UE.plugins.insertcode=function(){var a=this;a.ready(function(){utils.cssRule("pre","pre{margin:.5em 0;padding:.4em .6em;border-radius:8px;background:#f8f8f8;}",a.document)}),a.setOpt("insertcode",{as3:"ActionScript3",bash:"Bash/Shell",cpp:"C/C++",css:"Css",cf:"CodeFunction","c#":"C#",delphi:"Delphi",diff:"Diff",erlang:"Erlang",groovy:"Groovy",html:"Html",java:"Java",jfx:"JavaFx",js:"Javascript",pl:"Perl",php:"Php",plain:"Plain Text",ps:"PowerShell",python:"Python",ruby:"Ruby",scala:"Scala",sql:"Sql",vb:"Vb",xml:"Xml"}),a.commands.insertcode={execCommand:function(a,b){var c=this,d=c.selection.getRange(),e=domUtils.findParentByTagName(d.startContainer,"pre",!0);if(e)e.className="brush:"+b+";toolbar:false;";else{var f="";if(d.collapsed)f=browser.ie&&browser.ie11below?browser.version<=8?" ":"":"<br/>";else{var g=d.extractContents(),h=c.document.createElement("div");h.appendChild(g),utils.each(UE.filterNode(UE.htmlparser(h.innerHTML.replace(/[\r\t]/g,"")),c.options.filterTxtRules).children,function(a){if(browser.ie&&browser.ie11below&&browser.version>8)"element"==a.type?"br"==a.tagName?f+="\n":dtd.$empty[a.tagName]||(utils.each(a.children,function(b){"element"==b.type?"br"==b.tagName?f+="\n":dtd.$empty[a.tagName]||(f+=b.innerText()):f+=b.data}),/\n$/.test(f)||(f+="\n")):f+=a.data+"\n",!a.nextSibling()&&/\n$/.test(f)&&(f=f.replace(/\n$/,""));else if(browser.ie&&browser.ie11below)"element"==a.type?"br"==a.tagName?f+="<br>":dtd.$empty[a.tagName]||(utils.each(a.children,function(b){"element"==b.type?"br"==b.tagName?f+="<br>":dtd.$empty[a.tagName]||(f+=b.innerText()):f+=b.data}),/br>$/.test(f)||(f+="<br>")):f+=a.data+"<br>",!a.nextSibling()&&/<br>$/.test(f)&&(f=f.replace(/<br>$/,""));else if(f+="element"==a.type?dtd.$empty[a.tagName]?"":a.innerText():a.data,!/br\/?\s*>$/.test(f)){if(!a.nextSibling())return;f+="<br>"}})}c.execCommand("inserthtml",'<pre id="coder"class="brush:'+b+';toolbar:false">'+f+"</pre>",!0),e=c.document.getElementById("coder"),domUtils.removeAttributes(e,"id");var i=e.previousSibling;i&&(3==i.nodeType&&1==i.nodeValue.length&&browser.ie&&6==browser.version||domUtils.isEmptyBlock(i))&&domUtils.remove(i);var d=c.selection.getRange();domUtils.isEmptyBlock(e)?d.setStart(e,0).setCursor(!1,!0):d.selectNodeContents(e).select()}},queryCommandValue:function(){var a=this.selection.getStartElementPath(),b="";return utils.each(a,function(a){if("PRE"==a.nodeName){var c=a.className.match(/brush:([^;]+)/);return b=c&&c[1]?c[1]:"",!1}}),b}},a.addInputRule(function(a){utils.each(a.getNodesByTagName("pre"),function(a){var b=a.getNodesByTagName("br");if(b.length)return void(browser.ie&&browser.ie11below&&browser.version>8&&utils.each(b,function(a){var b=UE.uNode.createText("\n");a.parentNode.insertBefore(b,a),a.parentNode.removeChild(a)}));if(!(browser.ie&&browser.ie11below&&browser.version>8)){var c=a.innerText().split(/\n/);a.innerHTML(""),utils.each(c,function(b){b.length&&a.appendChild(UE.uNode.createText(b)),a.appendChild(UE.uNode.createElement("br"))})}})}),a.addOutputRule(function(a){utils.each(a.getNodesByTagName("pre"),function(a){var b="";utils.each(a.children,function(a){b+="text"==a.type?a.data.replace(/[ ]/g," ").replace(/\n$/,""):"br"==a.tagName?"\n":dtd.$empty[a.tagName]?a.innerText():""}),a.innerText(b.replace(/( |\n)+$/,""))})}),a.notNeedCodeQuery={help:1,undo:1,redo:1,source:1,print:1,searchreplace:1,fullscreen:1,preview:1,insertparagraph:1,elementpath:1,insertcode:1,inserthtml:1,selectall:1};a.queryCommandState;a.queryCommandState=function(a){var b=this;return!b.notNeedCodeQuery[a.toLowerCase()]&&b.selection&&b.queryCommandValue("insertcode")?-1:UE.Editor.prototype.queryCommandState.apply(this,arguments)},a.addListener("beforeenterkeydown",function(){var b=a.selection.getRange(),c=domUtils.findParentByTagName(b.startContainer,"pre",!0);if(c){if(a.fireEvent("saveScene"),b.collapsed||b.deleteContents(),!browser.ie||browser.ie9above){var c,d=a.document.createElement("br");b.insertNode(d).setStartAfter(d).collapse(!0);var e=d.nextSibling;e||browser.ie&&!(browser.version>10)?b.setStartAfter(d):b.insertNode(d.cloneNode(!1)),
c=d.previousSibling;for(var f;c;)if(f=c,c=c.previousSibling,!c||"BR"==c.nodeName){c=f;break}if(c){for(var g="";c&&"BR"!=c.nodeName&&new RegExp("^[\\s"+domUtils.fillChar+"]*$").test(c.nodeValue);)g+=c.nodeValue,c=c.nextSibling;if("BR"!=c.nodeName){var h=c.nodeValue.match(new RegExp("^([\\s"+domUtils.fillChar+"]+)"));h&&h[1]&&(g+=h[1])}g&&(g=a.document.createTextNode(g),b.insertNode(g).setStartAfter(g))}b.collapse(!0).select(!0)}else if(browser.version>8){var i=a.document.createTextNode("\n"),j=b.startContainer;if(0==b.startOffset){var k=j.previousSibling;if(k){b.insertNode(i);var l=a.document.createTextNode(" ");b.setStartAfter(i).insertNode(l).setStart(l,0).collapse(!0).select(!0)}}else{b.insertNode(i).setStartAfter(i);var l=a.document.createTextNode(" ");j=b.startContainer.childNodes[b.startOffset],j&&!/^\n/.test(j.nodeValue)&&b.setStartBefore(i),b.insertNode(l).setStart(l,0).collapse(!0).select(!0)}}else{var d=a.document.createElement("br");b.insertNode(d),b.insertNode(a.document.createTextNode(domUtils.fillChar)),b.setStartAfter(d),c=d.previousSibling;for(var f;c;)if(f=c,c=c.previousSibling,!c||"BR"==c.nodeName){c=f;break}if(c){for(var g="";c&&"BR"!=c.nodeName&&new RegExp("^[ "+domUtils.fillChar+"]*$").test(c.nodeValue);)g+=c.nodeValue,c=c.nextSibling;if("BR"!=c.nodeName){var h=c.nodeValue.match(new RegExp("^([ "+domUtils.fillChar+"]+)"));h&&h[1]&&(g+=h[1])}g=a.document.createTextNode(g),b.insertNode(g).setStartAfter(g)}b.collapse(!0).select()}return a.fireEvent("saveScene"),!0}}),a.addListener("tabkeydown",function(b,c){var d=a.selection.getRange(),e=domUtils.findParentByTagName(d.startContainer,"pre",!0);if(e){if(a.fireEvent("saveScene"),c.shiftKey);else if(d.collapsed){var f=a.document.createTextNode(" ");d.insertNode(f).setStartAfter(f).collapse(!0).select(!0)}else{for(var g=d.createBookmark(),h=g.start.previousSibling;h;){if(e.firstChild===h&&!domUtils.isBr(h)){e.insertBefore(a.document.createTextNode(" "),h);break}if(domUtils.isBr(h)){e.insertBefore(a.document.createTextNode(" "),h.nextSibling);break}h=h.previousSibling}var i=g.end;for(h=g.start.nextSibling,e.firstChild===g.start&&e.insertBefore(a.document.createTextNode(" "),h.nextSibling);h&&h!==i;){if(domUtils.isBr(h)&&h.nextSibling){if(h.nextSibling===i)break;e.insertBefore(a.document.createTextNode(" "),h.nextSibling)}h=h.nextSibling}d.moveToBookmark(g).select()}return a.fireEvent("saveScene"),!0}}),a.addListener("beforeinserthtml",function(a,b){var c=this,d=c.selection.getRange(),e=domUtils.findParentByTagName(d.startContainer,"pre",!0);if(e){d.collapsed||d.deleteContents();var f="";if(browser.ie&&browser.version>8){utils.each(UE.filterNode(UE.htmlparser(b),c.options.filterTxtRules).children,function(a){"element"==a.type?"br"==a.tagName?f+="\n":dtd.$empty[a.tagName]||(utils.each(a.children,function(b){"element"==b.type?"br"==b.tagName?f+="\n":dtd.$empty[a.tagName]||(f+=b.innerText()):f+=b.data}),/\n$/.test(f)||(f+="\n")):f+=a.data+"\n",!a.nextSibling()&&/\n$/.test(f)&&(f=f.replace(/\n$/,""))});var g=c.document.createTextNode(utils.html(f.replace(/ /g," ")));d.insertNode(g).selectNode(g).select()}else{var h=c.document.createDocumentFragment();utils.each(UE.filterNode(UE.htmlparser(b),c.options.filterTxtRules).children,function(a){"element"==a.type?"br"==a.tagName?h.appendChild(c.document.createElement("br")):dtd.$empty[a.tagName]||(utils.each(a.children,function(b){"element"==b.type?"br"==b.tagName?h.appendChild(c.document.createElement("br")):dtd.$empty[a.tagName]||h.appendChild(c.document.createTextNode(utils.html(b.innerText().replace(/ /g," ")))):h.appendChild(c.document.createTextNode(utils.html(b.data.replace(/ /g," "))))}),"BR"!=h.lastChild.nodeName&&h.appendChild(c.document.createElement("br"))):h.appendChild(c.document.createTextNode(utils.html(a.data.replace(/ /g," ")))),a.nextSibling()||"BR"!=h.lastChild.nodeName||h.removeChild(h.lastChild)}),d.insertNode(h).select()}return!0}}),a.addListener("keydown",function(a,b){var c=this,d=b.keyCode||b.which;if(40==d){var e,f=c.selection.getRange(),g=f.startContainer;if(f.collapsed&&(e=domUtils.findParentByTagName(f.startContainer,"pre",!0))&&!e.nextSibling){for(var h=e.lastChild;h&&"BR"==h.nodeName;)h=h.previousSibling;(h===g||f.startContainer===e&&f.startOffset==e.childNodes.length)&&(c.execCommand("insertparagraph"),domUtils.preventDefault(b))}}}),a.addListener("delkeydown",function(b,c){var d=this.selection.getRange();d.txtToElmBoundary(!0);var e=d.startContainer;if(domUtils.isTagNode(e,"pre")&&d.collapsed&&domUtils.isStartInblock(d)){var f=a.document.createElement("p");return domUtils.fillNode(a.document,f),e.parentNode.insertBefore(f,e),domUtils.remove(e),d.setStart(f,0).setCursor(!1,!0),domUtils.preventDefault(c),!0}})},UE.commands.cleardoc={execCommand:function(a){var b=this,c=b.options.enterTag,d=b.selection.getRange();"br"==c?(b.body.innerHTML="<br/>",d.setStart(b.body,0).setCursor()):(b.body.innerHTML="<p>"+(ie?"":"<br/>")+"</p>",d.setStart(b.body.firstChild,0).setCursor(!1,!0)),setTimeout(function(){b.fireEvent("clearDoc")},0)}},UE.plugin.register("anchor",function(){return{bindEvents:{ready:function(){utils.cssRule("anchor",".anchorclass{background: url('"+this.options.themePath+this.options.theme+"/img/anchor.gif') no-repeat scroll left center transparent;cursor: auto;display: inline-block;height: 16px;width: 15px;}",this.document)}},outputRule:function(a){utils.each(a.getNodesByTagName("img"),function(a){var b;(b=a.getAttr("anchorname"))&&(a.tagName="a",a.setAttr({anchorname:"",name:b,"class":""}))})},inputRule:function(a){utils.each(a.getNodesByTagName("a"),function(a){var b;(b=a.getAttr("name"))&&!a.getAttr("href")&&(a.tagName="img",a.setAttr({anchorname:a.getAttr("name"),"class":"anchorclass"}),a.setAttr("name"))})},commands:{anchor:{execCommand:function(a,b){var c=this.selection.getRange(),d=c.getClosedNode();if(d&&d.getAttribute("anchorname"))b?d.setAttribute("anchorname",b):(c.setStartBefore(d).setCursor(),domUtils.remove(d));else if(b){var e=this.document.createElement("img");c.collapse(!0),domUtils.setAttributes(e,{anchorname:b,"class":"anchorclass"}),c.insertNode(e).setStartAfter(e).setCursor(!1,!0)}}}}}}),UE.plugins.wordcount=function(){var a=this;a.setOpt("wordCount",!0),a.addListener("contentchange",function(){a.fireEvent("wordcount")});var b;a.addListener("ready",function(){var a=this;domUtils.on(a.body,"keyup",function(c){var d=c.keyCode||c.which,e={16:1,18:1,20:1,37:1,38:1,39:1,40:1};d in e||(clearTimeout(b),b=setTimeout(function(){a.fireEvent("wordcount")},200))})})},UE.plugins.pagebreak=function(){function a(a){if(domUtils.isEmptyBlock(a)){for(var b,d=a.firstChild;d&&1==d.nodeType&&domUtils.isEmptyBlock(d);)b=d,d=d.firstChild;!b&&(b=a),domUtils.fillNode(c.document,b)}}function b(a){return a&&1==a.nodeType&&"HR"==a.tagName&&"pagebreak"==a.className}var c=this,d=["td"];c.setOpt("pageBreakTag","_ueditor_page_break_tag_"),c.ready(function(){utils.cssRule("pagebreak",".pagebreak{display:block;clear:both !important;cursor:default !important;width: 100% !important;margin:0;}",c.document)}),c.addInputRule(function(a){a.traversal(function(a){if("text"==a.type&&a.data==c.options.pageBreakTag){var b=UE.uNode.createElement('<hr class="pagebreak" noshade="noshade" size="5" style="-webkit-user-select: none;">');a.parentNode.insertBefore(b,a),a.parentNode.removeChild(a)}})}),c.addOutputRule(function(a){utils.each(a.getNodesByTagName("hr"),function(a){if("pagebreak"==a.getAttr("class")){var b=UE.uNode.createText(c.options.pageBreakTag);a.parentNode.insertBefore(b,a),a.parentNode.removeChild(a)}})}),c.commands.pagebreak={execCommand:function(){var e=c.selection.getRange(),f=c.document.createElement("hr");domUtils.setAttributes(f,{"class":"pagebreak",noshade:"noshade",size:"5"}),domUtils.unSelectable(f);var g,h=domUtils.findParentByTagName(e.startContainer,d,!0),i=[];if(h)switch(h.tagName){case"TD":if(g=h.parentNode,g.previousSibling)g.parentNode.insertBefore(f,g),i=domUtils.findParents(f);else{var j=domUtils.findParentByTagName(g,"table");j.parentNode.insertBefore(f,j),i=domUtils.findParents(f,!0)}g=i[1],f!==g&&domUtils.breakParent(f,g),c.fireEvent("afteradjusttable",c.document)}else{if(!e.collapsed){e.deleteContents();for(var k=e.startContainer;!domUtils.isBody(k)&&domUtils.isBlockElm(k)&&domUtils.isEmptyNode(k);)e.setStartBefore(k).collapse(!0),domUtils.remove(k),k=e.startContainer}e.insertNode(f);for(var l,g=f.parentNode;!domUtils.isBody(g);)domUtils.breakParent(f,g),l=f.nextSibling,l&&domUtils.isEmptyBlock(l)&&domUtils.remove(l),g=f.parentNode;l=f.nextSibling;var m=f.previousSibling;if(b(m)?domUtils.remove(m):m&&a(m),l)b(l)?domUtils.remove(l):a(l),e.setEndAfter(f).collapse(!1);else{var n=c.document.createElement("p");f.parentNode.appendChild(n),domUtils.fillNode(c.document,n),e.setStart(n,0).collapse(!0)}e.select(!0)}}}},UE.plugin.register("wordimage",function(){var a=this,b=[];return{commands:{wordimage:{execCommand:function(){for(var b,c=domUtils.getElementsByTagName(a.body,"img"),d=[],e=0;b=c[e++];){var f=b.getAttribute("word_img");f&&d.push(f)}return d},queryCommandState:function(){b=domUtils.getElementsByTagName(a.body,"img");for(var c,d=0;c=b[d++];)if(c.getAttribute("word_img"))return 1;return-1},notNeedUndo:!0}},inputRule:function(b){utils.each(b.getNodesByTagName("img"),function(b){var c=b.attrs,d=parseInt(c.width)<128||parseInt(c.height)<43,e=a.options,f=e.UEDITOR_HOME_URL+"themes/default/img/spacer.gif";c.src&&/^(?:(file:\/+))/.test(c.src)&&b.setAttr({width:c.width,height:c.height,alt:c.alt,word_img:c.src,src:f,style:"background:url("+(d?e.themePath+e.theme+"/img/word.gif":e.langPath+e.lang+"/img/localimage.png")+") no-repeat center center;border:1px solid #ddd"})})}}}),UE.plugins.dragdrop=function(){var a=this;a.ready(function(){domUtils.on(this.body,"dragend",function(){var b=a.selection.getRange(),c=b.getClosedNode()||a.selection.getStart();if(c&&"IMG"==c.tagName){for(var d,e=c.previousSibling;(d=c.nextSibling)&&1==d.nodeType&&"SPAN"==d.tagName&&!d.firstChild;)domUtils.remove(d);(!e||1!=e.nodeType||domUtils.isEmptyBlock(e))&&e||d&&(!d||domUtils.isEmptyBlock(d))||(e&&"P"==e.tagName&&!domUtils.isEmptyBlock(e)?(e.appendChild(c),domUtils.moveChild(d,e),domUtils.remove(d)):d&&"P"==d.tagName&&!domUtils.isEmptyBlock(d)&&d.insertBefore(c,d.firstChild),e&&"P"==e.tagName&&domUtils.isEmptyBlock(e)&&domUtils.remove(e),d&&"P"==d.tagName&&domUtils.isEmptyBlock(d)&&domUtils.remove(d),b.selectNode(c).select(),a.fireEvent("saveScene"))}})}),a.addListener("keyup",function(b,c){var d=c.keyCode||c.which;if(13==d){var e,f=a.selection.getRange();(e=domUtils.findParentByTagName(f.startContainer,"p",!0))&&"center"==domUtils.getComputedStyle(e,"text-align")&&domUtils.removeStyle(e,"text-align")}})},UE.plugins.undo=function(){function a(a,b){if(a.length!=b.length)return 0;for(var c=0,d=a.length;c<d;c++)if(a[c]!=b[c])return 0;return 1}function b(b,c){return b.collapsed!=c.collapsed?0:a(b.startAddress,c.startAddress)&&a(b.endAddress,c.endAddress)?1:0}function c(){this.list=[],this.index=0,this.hasUndo=!1,this.hasRedo=!1,this.undo=function(){if(this.hasUndo){if(!this.list[this.index-1]&&1==this.list.length)return void this.reset();for(;this.list[this.index].content==this.list[this.index-1].content;)if(this.index--,0==this.index)return this.restore(0);this.restore(--this.index)}},this.redo=function(){if(this.hasRedo){for(;this.list[this.index].content==this.list[this.index+1].content;)if(this.index++,this.index==this.list.length-1)return this.restore(this.index);this.restore(++this.index)}},this.restore=function(){var a=this.editor,b=this.list[this.index],c=UE.htmlparser(b.content.replace(h,""));a.options.autoClearEmptyNode=!1,a.filterInputRule(c),a.options.autoClearEmptyNode=j,a.document.body.innerHTML=c.toHtml(),a.fireEvent("afterscencerestore"),browser.ie&&utils.each(domUtils.getElementsByTagName(a.document,"td th caption p"),function(b){domUtils.isEmptyNode(b)&&domUtils.fillNode(a.document,b)});try{var d=new dom.Range(a.document).moveToAddress(b.address);d.select(i[d.startContainer.nodeName.toLowerCase()])}catch(e){}this.update(),this.clearKey(),a.fireEvent("reset",!0)},this.getScene=function(){var a=this.editor,b=a.selection.getRange(),c=b.createAddress(!1,!0);a.fireEvent("beforegetscene");var d=UE.htmlparser(a.body.innerHTML);a.options.autoClearEmptyNode=!1,a.filterOutputRule(d),a.options.autoClearEmptyNode=j;var e=d.toHtml();return a.fireEvent("aftergetscene"),{address:c,content:e}},this.save=function(a,c){clearTimeout(d);var g=this.getScene(c),h=this.list[this.index];h&&h.content!=g.content&&e.trigger("contentchange"),h&&h.content==g.content&&(a?1:b(h.address,g.address))||(this.list=this.list.slice(0,this.index+1),this.list.push(g),this.list.length>f&&this.list.shift(),this.index=this.list.length-1,this.clearKey(),this.update())},this.update=function(){this.hasRedo=!!this.list[this.index+1],this.hasUndo=!!this.list[this.index-1]},this.reset=function(){this.list=[],this.index=0,this.hasUndo=!1,this.hasRedo=!1,this.clearKey()},this.clearKey=function(){m=0,k=null}}var d,e=this,f=e.options.maxUndoCount||20,g=e.options.maxInputCount||20,h=new RegExp(domUtils.fillChar+"|</hr>","gi"),i={ol:1,ul:1,table:1,tbody:1,tr:1,body:1},j=e.options.autoClearEmptyNode;e.undoManger=new c,e.undoManger.editor=e,e.addListener("saveScene",function(){var a=Array.prototype.splice.call(arguments,1);this.undoManger.save.apply(this.undoManger,a)}),e.addListener("reset",function(a,b){b||this.undoManger.reset()}),e.commands.redo=e.commands.undo={execCommand:function(a){this.undoManger[a]()},queryCommandState:function(a){return this.undoManger["has"+("undo"==a.toLowerCase()?"Undo":"Redo")]?0:-1},notNeedUndo:1};var k,l={16:1,17:1,18:1,37:1,38:1,39:1,40:1},m=0,n=!1;e.addListener("ready",function(){domUtils.on(this.body,"compositionstart",function(){n=!0}),domUtils.on(this.body,"compositionend",function(){n=!1})}),e.addshortcutkey({Undo:"ctrl+90",Redo:"ctrl+89"});var o=!0;e.addListener("keydown",function(a,b){function c(a){a.undoManger.save(!1,!0),a.fireEvent("selectionchange")}var e=this,f=b.keyCode||b.which;if(!(l[f]||b.ctrlKey||b.metaKey||b.shiftKey||b.altKey)){if(n)return;if(!e.selection.getRange().collapsed)return e.undoManger.save(!1,!0),void(o=!1);0==e.undoManger.list.length&&e.undoManger.save(!0),clearTimeout(d),d=setTimeout(function(){if(n)var a=setInterval(function(){n||(c(e),clearInterval(a))},300);else c(e)},200),k=f,m++,m>=g&&c(e)}}),e.addListener("keyup",function(a,b){var c=b.keyCode||b.which;if(!(l[c]||b.ctrlKey||b.metaKey||b.shiftKey||b.altKey)){if(n)return;o||(this.undoManger.save(!1,!0),o=!0)}}),e.stopCmdUndo=function(){e.__hasEnterExecCommand=!0},e.startCmdUndo=function(){e.__hasEnterExecCommand=!1}},UE.plugin.register("copy",function(){function a(){ZeroClipboard.config({debug:!1,swfPath:b.options.UEDITOR_HOME_URL+"third-party/zeroclipboard/ZeroClipboard.swf"});var a=b.zeroclipboard=new ZeroClipboard;a.on("copy",function(a){var c=a.client,d=b.selection.getRange(),e=document.createElement("div");e.appendChild(d.cloneContents()),c.setText(e.innerText||e.textContent),c.setHtml(e.innerHTML),d.select()}),a.on("mouseover mouseout",function(a){var b=a.target;"mouseover"==a.type?domUtils.addClass(b,"edui-state-hover"):"mouseout"==a.type&&domUtils.removeClasses(b,"edui-state-hover")}),a.on("wrongflash noflash",function(){ZeroClipboard.destroy()})}var b=this;return{bindEvents:{ready:function(){browser.ie||(window.ZeroClipboard?a():utils.loadFile(document,{src:b.options.UEDITOR_HOME_URL+"third-party/zeroclipboard/ZeroClipboard.js",tag:"script",type:"text/javascript",defer:"defer"},function(){a()}))}},commands:{copy:{execCommand:function(a){b.document.execCommand("copy")||alert(b.getLang("copymsg"))}}}}}),UE.plugins.paste=function(){function a(a){var b=this.document;if(!b.getElementById("baidu_pastebin")){var c=this.selection.getRange(),d=c.createBookmark(),e=b.createElement("div");e.id="baidu_pastebin",browser.webkit&&e.appendChild(b.createTextNode(domUtils.fillChar+domUtils.fillChar)),b.body.appendChild(e),d.start.style.display="",e.style.cssText="position:absolute;width:1px;height:1px;overflow:hidden;left:-1000px;white-space:nowrap;top:"+domUtils.getXY(d.start).y+"px",c.selectNodeContents(e).select(!0),setTimeout(function(){if(browser.webkit)for(var f,g=0,h=b.querySelectorAll("#baidu_pastebin");f=h[g++];){if(!domUtils.isEmptyNode(f)){e=f;break}domUtils.remove(f)}try{e.parentNode.removeChild(e)}catch(i){}c.moveToBookmark(d).select(!0),a(e)},0)}}function b(a){return a.replace(/<(\/?)([\w\-]+)([^>]*)>/gi,function(a,b,c,d){return c=c.toLowerCase(),{img:1}[c]?a:(d=d.replace(/([\w\-]*?)\s*=\s*(("([^"]*)")|('([^']*)')|([^\s>]+))/gi,function(a,b,c){return{src:1,href:1,name:1}[b.toLowerCase()]?b+"="+c+" ":""}),{span:1,div:1}[c]?"":"<"+b+c+" "+utils.trim(d)+">")})}function c(a){var c;if(a.firstChild){for(var h,i=domUtils.getElementsByTagName(a,"span"),j=0;h=i[j++];)"_baidu_cut_start"!=h.id&&"_baidu_cut_end"!=h.id||domUtils.remove(h);if(browser.webkit){for(var k,l=a.querySelectorAll("div br"),j=0;k=l[j++];){var m=k.parentNode;"DIV"==m.tagName&&1==m.childNodes.length&&(m.innerHTML="<p><br/></p>",domUtils.remove(m))}for(var n,o=a.querySelectorAll("#baidu_pastebin"),j=0;n=o[j++];){var p=d.document.createElement("p");for(n.parentNode.insertBefore(p,n);n.firstChild;)p.appendChild(n.firstChild);domUtils.remove(n)}for(var q,r=a.querySelectorAll("meta"),j=0;q=r[j++];)domUtils.remove(q);var l=a.querySelectorAll("br");for(j=0;q=l[j++];)/^apple-/i.test(q.className)&&domUtils.remove(q)}if(browser.gecko){var s=a.querySelectorAll("[_moz_dirty]");for(j=0;q=s[j++];)q.removeAttribute("_moz_dirty")}if(!browser.ie)for(var q,t=a.querySelectorAll("span.Apple-style-span"),j=0;q=t[j++];)domUtils.remove(q,!0);c=a.innerHTML,c=UE.filterWord(c);var u=UE.htmlparser(c);if(d.options.filterRules&&UE.filterNode(u,d.options.filterRules),d.filterInputRule(u),browser.webkit){var v=u.lastChild();v&&"element"==v.type&&"br"==v.tagName&&u.removeChild(v),utils.each(d.body.querySelectorAll("div"),function(a){domUtils.isEmptyBlock(a)&&domUtils.remove(a,!0)})}if(c={html:u.toHtml()},d.fireEvent("beforepaste",c,u),!c.html)return;u=UE.htmlparser(c.html,!0),1===d.queryCommandState("pasteplain")?d.execCommand("insertHtml",UE.filterNode(u,d.options.filterTxtRules).toHtml(),!0):(UE.filterNode(u,d.options.filterTxtRules),e=u.toHtml(),f=c.html,g=d.selection.getRange().createAddress(!0),d.execCommand("insertHtml",d.getOpt("retainOnlyLabelPasted")===!0?b(f):f,!0)),d.fireEvent("afterpaste",c)}}var d=this;d.setOpt({retainOnlyLabelPasted:!1});var e,f,g;d.addListener("pasteTransfer",function(a,c){if(g&&e&&f&&e!=f){var h=d.selection.getRange();if(h.moveToAddress(g,!0),!h.collapsed){for(;!domUtils.isBody(h.startContainer);){var i=h.startContainer;if(1==i.nodeType){if(i=i.childNodes[h.startOffset],!i){h.setStartBefore(h.startContainer);continue}var j=i.previousSibling;j&&3==j.nodeType&&new RegExp("^[\n\r\t "+domUtils.fillChar+"]*$").test(j.nodeValue)&&h.setStartBefore(j)}if(0!=h.startOffset)break;h.setStartBefore(h.startContainer)}for(;!domUtils.isBody(h.endContainer);){var k=h.endContainer;if(1==k.nodeType){if(k=k.childNodes[h.endOffset],!k){h.setEndAfter(h.endContainer);continue}var l=k.nextSibling;l&&3==l.nodeType&&new RegExp("^[\n\r\t"+domUtils.fillChar+"]*$").test(l.nodeValue)&&h.setEndAfter(l)}if(h.endOffset!=h.endContainer[3==h.endContainer.nodeType?"nodeValue":"childNodes"].length)break;h.setEndAfter(h.endContainer)}}h.deleteContents(),h.select(!0),d.__hasEnterExecCommand=!0;var m=f;2===c?m=b(m):c&&(m=e),d.execCommand("inserthtml",m,!0),d.__hasEnterExecCommand=!1;for(var n=d.selection.getRange();!domUtils.isBody(n.startContainer)&&!n.startOffset&&n.startContainer[3==n.startContainer.nodeType?"nodeValue":"childNodes"].length;)n.setStartBefore(n.startContainer);var o=n.createAddress(!0);g.endAddress=o.startAddress}}),d.addListener("ready",function(){domUtils.on(d.body,"cut",function(){var a=d.selection.getRange();!a.collapsed&&d.undoManger&&d.undoManger.save()}),domUtils.on(d.body,browser.ie||browser.opera?"keydown":"paste",function(b){(!browser.ie&&!browser.opera||(b.ctrlKey||b.metaKey)&&"86"==b.keyCode)&&a.call(d,function(a){c(a)})})}),d.commands.paste={execCommand:function(b){browser.ie?(a.call(d,function(a){c(a)}),d.document.execCommand("paste")):alert(d.getLang("pastemsg"))}}},UE.plugins.pasteplain=function(){var a=this;a.setOpt({pasteplain:!1,filterTxtRules:function(){function a(a){a.tagName="p",a.setStyle()}function b(a){a.parentNode.removeChild(a,!0)}return{"-":"script style object iframe embed input select",p:{$:{}},br:{$:{}},div:function(a){for(var b,c=UE.uNode.createElement("p");b=a.firstChild();)"text"!=b.type&&UE.dom.dtd.$block[b.tagName]?c.firstChild()?(a.parentNode.insertBefore(c,a),c=UE.uNode.createElement("p")):a.parentNode.insertBefore(b,a):c.appendChild(b);c.firstChild()&&a.parentNode.insertBefore(c,a),a.parentNode.removeChild(a)},ol:b,ul:b,dl:b,dt:b,dd:b,li:b,caption:a,th:a,tr:a,h1:a,h2:a,h3:a,h4:a,h5:a,h6:a,td:function(a){var b=!!a.innerText();b&&a.parentNode.insertAfter(UE.uNode.createText(" "),a),a.parentNode.removeChild(a,a.innerText())}}}()});var b=a.options.pasteplain;a.commands.pasteplain={queryCommandState:function(){return b?1:0},execCommand:function(){b=0|!b},notNeedUndo:1}},UE.plugins.list=function(){function a(a){var b=[];for(var c in a)b.push(c);return b}function b(a){var b=a.className;return domUtils.hasClass(a,/custom_/)?b.match(/custom_(\w+)/)[1]:domUtils.getStyle(a,"list-style-type")}function c(a,c){utils.each(domUtils.getElementsByTagName(a,"ol ul"),function(f){if(domUtils.inDoc(f,a)){var g=f.parentNode;if(g.tagName==f.tagName){var h=b(f)||("OL"==f.tagName?"decimal":"disc"),i=b(g)||("OL"==g.tagName?"decimal":"disc");if(h==i){var l=utils.indexOf(k[f.tagName],h);l=l+1==k[f.tagName].length?0:l+1,e(f,k[f.tagName][l])}}var m=0,n=2;domUtils.hasClass(f,/custom_/)?/[ou]l/i.test(g.tagName)&&domUtils.hasClass(g,/custom_/)||(n=1):/[ou]l/i.test(g.tagName)&&domUtils.hasClass(g,/custom_/)&&(n=3);var o=domUtils.getStyle(f,"list-style-type");o&&(f.style.cssText="list-style-type:"+o),f.className=utils.trim(f.className.replace(/list-paddingleft-\w+/,""))+" list-paddingleft-"+n,utils.each(domUtils.getElementsByTagName(f,"li"),function(a){if(a.style.cssText&&(a.style.cssText=""),!a.firstChild)return void domUtils.remove(a);if(a.parentNode===f){if(m++,domUtils.hasClass(f,/custom_/)){var c=1,d=b(f);if("OL"==f.tagName){if(d)switch(d){case"cn":case"cn1":case"cn2":m>10&&(m%10==0||m>10&&m<20)?c=2:m>20&&(c=3);break;case"num2":m>9&&(c=2)}a.className="list-"+j[d]+m+" list-"+d+"-paddingleft-"+c}else a.className="list-"+j[d]+" list-"+d+"-paddingleft"}else a.className=a.className.replace(/list-[\w\-]+/gi,"");var e=a.getAttribute("class");null===e||e.replace(/\s/g,"")||domUtils.removeAttributes(a,"class")}}),!c&&d(f,f.tagName.toLowerCase(),b(f)||domUtils.getStyle(f,"list-style-type"),!0)}})}function d(a,d,e,f){var g=a.nextSibling;g&&1==g.nodeType&&g.tagName.toLowerCase()==d&&(b(g)||domUtils.getStyle(g,"list-style-type")||("ol"==d?"decimal":"disc"))==e&&(domUtils.moveChild(g,a),0==g.childNodes.length&&domUtils.remove(g)),g&&domUtils.isFillChar(g)&&domUtils.remove(g);var h=a.previousSibling;h&&1==h.nodeType&&h.tagName.toLowerCase()==d&&(b(h)||domUtils.getStyle(h,"list-style-type")||("ol"==d?"decimal":"disc"))==e&&domUtils.moveChild(a,h),h&&domUtils.isFillChar(h)&&domUtils.remove(h),!f&&domUtils.isEmptyBlock(a)&&domUtils.remove(a),b(a)&&c(a.ownerDocument,!0)}function e(a,b){j[b]&&(a.className="custom_"+b);try{domUtils.setStyle(a,"list-style-type",b)}catch(c){}}function f(a){var b=a.previousSibling;b&&domUtils.isEmptyBlock(b)&&domUtils.remove(b),b=a.nextSibling,b&&domUtils.isEmptyBlock(b)&&domUtils.remove(b)}function g(a){for(;a&&!domUtils.isBody(a);){if("TABLE"==a.nodeName)return null;if("LI"==a.nodeName)return a;a=a.parentNode}}var h=this,i={TD:1,PRE:1,BLOCKQUOTE:1},j={cn:"cn-1-",cn1:"cn-2-",cn2:"cn-3-",num:"num-1-",num1:"num-2-",num2:"num-3-",dash:"dash",dot:"dot"};h.setOpt({autoTransWordToList:!1,insertorderedlist:{num:"",num1:"",num2:"",cn:"",cn1:"",cn2:"",decimal:"","lower-alpha":"","lower-roman":"","upper-alpha":"","upper-roman":""},insertunorderedlist:{circle:"",disc:"",square:"",dash:"",dot:""},listDefaultPaddingLeft:"30",listiconpath:"http://bs.baidu.com/listicon/",maxListLevel:-1,disablePInList:!1});var k={OL:a(h.options.insertorderedlist),UL:a(h.options.insertunorderedlist)},l=h.options.listiconpath;for(var m in j)h.options.insertorderedlist.hasOwnProperty(m)||h.options.insertunorderedlist.hasOwnProperty(m)||delete j[m];h.ready(function(){var a=[];for(var b in j){if("dash"==b||"dot"==b)a.push("li.list-"+j[b]+"{background-image:url("+l+j[b]+".gif)}"),a.push("ul.custom_"+b+"{list-style:none;}ul.custom_"+b+" li{background-position:0 3px;background-repeat:no-repeat}");else{for(var c=0;c<99;c++)a.push("li.list-"+j[b]+c+"{background-image:url("+l+"list-"+j[b]+c+".gif)}");a.push("ol.custom_"+b+"{list-style:none;}ol.custom_"+b+" li{background-position:0 3px;background-repeat:no-repeat}")}switch(b){case"cn":a.push("li.list-"+b+"-paddingleft-1{padding-left:25px}"),a.push("li.list-"+b+"-paddingleft-2{padding-left:40px}"),a.push("li.list-"+b+"-paddingleft-3{padding-left:55px}");break;case"cn1":a.push("li.list-"+b+"-paddingleft-1{padding-left:30px}"),a.push("li.list-"+b+"-paddingleft-2{padding-left:40px}"),a.push("li.list-"+b+"-paddingleft-3{padding-left:55px}");break;case"cn2":a.push("li.list-"+b+"-paddingleft-1{padding-left:40px}"),a.push("li.list-"+b+"-paddingleft-2{padding-left:55px}"),a.push("li.list-"+b+"-paddingleft-3{padding-left:68px}");break;case"num":case"num1":a.push("li.list-"+b+"-paddingleft-1{padding-left:25px}");break;case"num2":a.push("li.list-"+b+"-paddingleft-1{padding-left:35px}"),a.push("li.list-"+b+"-paddingleft-2{padding-left:40px}");break;case"dash":a.push("li.list-"+b+"-paddingleft{padding-left:35px}");break;case"dot":a.push("li.list-"+b+"-paddingleft{padding-left:20px}")}}a.push(".list-paddingleft-1{padding-left:0}"),a.push(".list-paddingleft-2{padding-left:"+h.options.listDefaultPaddingLeft+"px}"),a.push(".list-paddingleft-3{padding-left:"+2*h.options.listDefaultPaddingLeft+"px}"),utils.cssRule("list","ol,ul{margin:0;pading:0;"+(browser.ie?"":"width:95%")+"}li{clear:both;}"+a.join("\n"),h.document)}),h.ready(function(){domUtils.on(h.body,"cut",function(){setTimeout(function(){var a,b=h.selection.getRange();if(!b.collapsed&&(a=domUtils.findParentByTagName(b.startContainer,"li",!0))&&!a.nextSibling&&domUtils.isEmptyBlock(a)){var c,d=a.parentNode;if(c=d.previousSibling)domUtils.remove(d),b.setStartAtLast(c).collapse(!0),b.select(!0);else if(c=d.nextSibling)domUtils.remove(d),b.setStartAtFirst(c).collapse(!0),b.select(!0);else{var e=h.document.createElement("p");domUtils.fillNode(h.document,e),d.parentNode.insertBefore(e,d),domUtils.remove(d),b.setStart(e,0).collapse(!0),b.select(!0)}}})})}),h.addListener("beforepaste",function(a,c){var d,e=this,f=e.selection.getRange(),g=UE.htmlparser(c.html,!0);if(d=domUtils.findParentByTagName(f.startContainer,"li",!0)){var h=d.parentNode,i="OL"==h.tagName?"ul":"ol";utils.each(g.getNodesByTagName(i),function(c){if(c.tagName=h.tagName,c.setAttr(),c.parentNode===g)a=b(h)||("OL"==h.tagName?"decimal":"disc");else{var d=c.parentNode.getAttr("class");a=d&&/custom_/.test(d)?d.match(/custom_(\w+)/)[1]:c.parentNode.getStyle("list-style-type"),a||(a="OL"==h.tagName?"decimal":"disc")}var e=utils.indexOf(k[h.tagName],a);c.parentNode!==g&&(e=e+1==k[h.tagName].length?0:e+1);var f=k[h.tagName][e];j[f]?c.setAttr("class","custom_"+f):c.setStyle("list-style-type",f)})}c.html=g.toHtml()}),h.getOpt("disablePInList")===!0&&h.addOutputRule(function(a){utils.each(a.getNodesByTagName("li"),function(a){var b=[],c=0;utils.each(a.children,function(d){if("p"==d.tagName){for(var e;e=d.children.pop();)b.splice(c,0,e),e.parentNode=a,lastNode=e;if(e=b[b.length-1],!e||"element"!=e.type||"br"!=e.tagName){var f=UE.uNode.createElement("br");f.parentNode=a,b.push(f)}c=b.length}}),b.length&&(a.children=b)})}),h.addInputRule(function(a){function b(a,b){var e=b.firstChild();if(e&&"element"==e.type&&"span"==e.tagName&&/Wingdings|Symbol/.test(e.getStyle("font-family"))){for(var f in d)if(d[f]==e.data)return f;return"disc"}for(var f in c)if(c[f].test(a))return f}if(utils.each(a.getNodesByTagName("li"),function(a){for(var b,c=UE.uNode.createElement("p"),d=0;b=a.children[d];)"text"==b.type||dtd.p[b.tagName]?c.appendChild(b):c.firstChild()?(a.insertBefore(c,b),c=UE.uNode.createElement("p"),d+=2):d++;(c.firstChild()&&!c.parentNode||!a.firstChild())&&a.appendChild(c),c.firstChild()||c.innerHTML(browser.ie?" ":"<br/>");var e=a.firstChild(),f=e.lastChild();f&&"text"==f.type&&/^\s*$/.test(f.data)&&e.removeChild(f)}),h.options.autoTransWordToList){var c={num1:/^\d+\)/,decimal:/^\d+\./,"lower-alpha":/^[a-z]+\)/,"upper-alpha":/^[A-Z]+\./,cn:/^[\u4E00\u4E8C\u4E09\u56DB\u516d\u4e94\u4e03\u516b\u4e5d]+[\u3001]/,cn2:/^\([\u4E00\u4E8C\u4E09\u56DB\u516d\u4e94\u4e03\u516b\u4e5d]+\)/},d={square:"n"};utils.each(a.getNodesByTagName("p"),function(a){function d(a,b,d){if("ol"==a.tagName)if(browser.ie){var e=b.firstChild();"element"==e.type&&"span"==e.tagName&&c[d].test(e.innerText())&&b.removeChild(e)}else b.innerHTML(b.innerHTML().replace(c[d],""));else b.removeChild(b.firstChild());var f=UE.uNode.createElement("li");f.appendChild(b),a.appendChild(f)}if("MsoListParagraph"==a.getAttr("class")){a.setStyle("margin",""),a.setStyle("margin-left",""),a.setAttr("class","");var e,f=a,g=a;if("li"!=a.parentNode.tagName&&(e=b(a.innerText(),a))){var i=UE.uNode.createElement(h.options.insertorderedlist.hasOwnProperty(e)?"ol":"ul");for(j[e]?i.setAttr("class","custom_"+e):i.setStyle("list-style-type",e);a&&"li"!=a.parentNode.tagName&&b(a.innerText(),a);)f=a.nextSibling(),f||a.parentNode.insertBefore(i,a),d(i,a,e),a=f;!i.parentNode&&a&&a.parentNode&&a.parentNode.insertBefore(i,a)}var k=g.firstChild();k&&"element"==k.type&&"span"==k.tagName&&/^\s*( )+\s*$/.test(k.innerText())&&k.parentNode.removeChild(k)}})}}),h.addListener("contentchange",function(){c(h.document)}),h.addListener("keydown",function(a,b){function c(){b.preventDefault?b.preventDefault():b.returnValue=!1,h.fireEvent("contentchange"),h.undoManger&&h.undoManger.save()}function d(a,b){for(;a&&!domUtils.isBody(a);){if(b(a))return null;if(1==a.nodeType&&/[ou]l/i.test(a.tagName))return a;a=a.parentNode}return null}var e=b.keyCode||b.which;if(13==e&&!b.shiftKey){var g=h.selection.getRange(),i=domUtils.findParent(g.startContainer,function(a){return domUtils.isBlockElm(a)},!0),j=domUtils.findParentByTagName(g.startContainer,"li",!0);if(i&&"PRE"!=i.tagName&&!j){var k=i.innerHTML.replace(new RegExp(domUtils.fillChar,"g"),"");/^\s*1\s*\.[^\d]/.test(k)&&(i.innerHTML=k.replace(/^\s*1\s*\./,""),g.setStartAtLast(i).collapse(!0).select(),h.__hasEnterExecCommand=!0,h.execCommand("insertorderedlist"),h.__hasEnterExecCommand=!1)}var l=h.selection.getRange(),m=d(l.startContainer,function(a){return"TABLE"==a.tagName}),n=l.collapsed?m:d(l.endContainer,function(a){return"TABLE"==a.tagName});if(m&&n&&m===n){if(!l.collapsed){if(m=domUtils.findParentByTagName(l.startContainer,"li",!0),n=domUtils.findParentByTagName(l.endContainer,"li",!0),!m||!n||m!==n){var o=l.cloneRange(),p=o.collapse(!1).createBookmark();l.deleteContents(),o.moveToBookmark(p);var j=domUtils.findParentByTagName(o.startContainer,"li",!0);return f(j),o.select(),void c()}if(l.deleteContents(),j=domUtils.findParentByTagName(l.startContainer,"li",!0),j&&domUtils.isEmptyBlock(j))return v=j.previousSibling,next=j.nextSibling,s=h.document.createElement("p"),domUtils.fillNode(h.document,s),q=j.parentNode,v&&next?(l.setStart(next,0).collapse(!0).select(!0),domUtils.remove(j)):((v||next)&&v?j.parentNode.parentNode.insertBefore(s,q.nextSibling):q.parentNode.insertBefore(s,q),domUtils.remove(j),q.firstChild||domUtils.remove(q),l.setStart(s,0).setCursor()),void c()}if(j=domUtils.findParentByTagName(l.startContainer,"li",!0)){
if(domUtils.isEmptyBlock(j)){p=l.createBookmark();var q=j.parentNode;if(j!==q.lastChild?(domUtils.breakParent(j,q),f(j)):(q.parentNode.insertBefore(j,q.nextSibling),domUtils.isEmptyNode(q)&&domUtils.remove(q)),!dtd.$list[j.parentNode.tagName])if(domUtils.isBlockElm(j.firstChild))domUtils.remove(j,!0);else{for(s=h.document.createElement("p"),j.parentNode.insertBefore(s,j);j.firstChild;)s.appendChild(j.firstChild);domUtils.remove(j)}l.moveToBookmark(p).select()}else{var r=j.firstChild;if(!r||!domUtils.isBlockElm(r)){var s=h.document.createElement("p");for(!j.firstChild&&domUtils.fillNode(h.document,s);j.firstChild;)s.appendChild(j.firstChild);j.appendChild(s),r=s}var t=h.document.createElement("span");l.insertNode(t),domUtils.breakParent(t,j);var u=t.nextSibling;r=u.firstChild,r||(s=h.document.createElement("p"),domUtils.fillNode(h.document,s),u.appendChild(s),r=s),domUtils.isEmptyNode(r)&&(r.innerHTML="",domUtils.fillNode(h.document,r)),l.setStart(r,0).collapse(!0).shrinkBoundary().select(),domUtils.remove(t);var v=u.previousSibling;v&&domUtils.isEmptyBlock(v)&&(v.innerHTML="<p></p>",domUtils.fillNode(h.document,v.firstChild))}c()}}}if(8==e&&(l=h.selection.getRange(),l.collapsed&&domUtils.isStartInblock(l)&&(o=l.cloneRange().trimBoundary(),j=domUtils.findParentByTagName(l.startContainer,"li",!0),j&&domUtils.isStartInblock(o)))){if(m=domUtils.findParentByTagName(l.startContainer,"p",!0),m&&m!==j.firstChild){var q=domUtils.findParentByTagName(m,["ol","ul"]);return domUtils.breakParent(m,q),f(m),h.fireEvent("contentchange"),l.setStart(m,0).setCursor(!1,!0),h.fireEvent("saveScene"),void domUtils.preventDefault(b)}if(j&&(v=j.previousSibling)){if(46==e&&j.childNodes.length)return;if(dtd.$list[v.tagName]&&(v=v.lastChild),h.undoManger&&h.undoManger.save(),r=j.firstChild,domUtils.isBlockElm(r))if(domUtils.isEmptyNode(r))for(v.appendChild(r),l.setStart(r,0).setCursor(!1,!0);j.firstChild;)v.appendChild(j.firstChild);else t=h.document.createElement("span"),l.insertNode(t),domUtils.isEmptyBlock(v)&&(v.innerHTML=""),domUtils.moveChild(j,v),l.setStartBefore(t).collapse(!0).select(!0),domUtils.remove(t);else if(domUtils.isEmptyNode(j)){var s=h.document.createElement("p");v.appendChild(s),l.setStart(s,0).setCursor()}else for(l.setEnd(v,v.childNodes.length).collapse().select(!0);j.firstChild;)v.appendChild(j.firstChild);return domUtils.remove(j),h.fireEvent("contentchange"),h.fireEvent("saveScene"),void domUtils.preventDefault(b)}if(j&&!j.previousSibling){var q=j.parentNode,p=l.createBookmark();if(domUtils.isTagNode(q.parentNode,"ol ul"))q.parentNode.insertBefore(j,q),domUtils.isEmptyNode(q)&&domUtils.remove(q);else{for(;j.firstChild;)q.parentNode.insertBefore(j.firstChild,q);domUtils.remove(j),domUtils.isEmptyNode(q)&&domUtils.remove(q)}return l.moveToBookmark(p).setCursor(!1,!0),h.fireEvent("contentchange"),h.fireEvent("saveScene"),void domUtils.preventDefault(b)}}}),h.addListener("keyup",function(a,c){var e=c.keyCode||c.which;if(8==e){var f,g=h.selection.getRange();(f=domUtils.findParentByTagName(g.startContainer,["ol","ul"],!0))&&d(f,f.tagName.toLowerCase(),b(f)||domUtils.getComputedStyle(f,"list-style-type"),!0)}}),h.addListener("tabkeydown",function(){function a(a){if(h.options.maxListLevel!=-1){for(var b=a.parentNode,c=0;/[ou]l/i.test(b.tagName);)c++,b=b.parentNode;if(c>=h.options.maxListLevel)return!0}}var c=h.selection.getRange(),f=domUtils.findParentByTagName(c.startContainer,"li",!0);if(f){var g;if(!c.collapsed){h.fireEvent("saveScene"),g=c.createBookmark();for(var i,j,l=0,m=domUtils.findParents(f);j=m[l++];)if(domUtils.isTagNode(j,"ol ul")){i=j;break}var n=f;if(g.end)for(;n&&!(domUtils.getPosition(n,g.end)&domUtils.POSITION_FOLLOWING);)if(a(n))n=domUtils.getNextDomNode(n,!1,null,function(a){return a!==i});else{var o=n.parentNode,p=h.document.createElement(o.tagName),q=utils.indexOf(k[p.tagName],b(o)||domUtils.getComputedStyle(o,"list-style-type")),r=q+1==k[p.tagName].length?0:q+1,s=k[p.tagName][r];for(e(p,s),o.insertBefore(p,n);n&&!(domUtils.getPosition(n,g.end)&domUtils.POSITION_FOLLOWING);){if(f=n.nextSibling,p.appendChild(n),!f||domUtils.isTagNode(f,"ol ul")){if(f)for(;(f=f.firstChild)&&"LI"!=f.tagName;);else f=domUtils.getNextDomNode(n,!1,null,function(a){return a!==i});break}n=f}d(p,p.tagName.toLowerCase(),s),n=f}return h.fireEvent("contentchange"),c.moveToBookmark(g).select(),!0}if(a(f))return!0;var o=f.parentNode,p=h.document.createElement(o.tagName),q=utils.indexOf(k[p.tagName],b(o)||domUtils.getComputedStyle(o,"list-style-type"));q=q+1==k[p.tagName].length?0:q+1;var s=k[p.tagName][q];if(e(p,s),domUtils.isStartInblock(c))return h.fireEvent("saveScene"),g=c.createBookmark(),o.insertBefore(p,f),p.appendChild(f),d(p,p.tagName.toLowerCase(),s),h.fireEvent("contentchange"),c.moveToBookmark(g).select(!0),!0}}),h.commands.insertorderedlist=h.commands.insertunorderedlist={execCommand:function(a,c){c||(c="insertorderedlist"==a.toLowerCase()?"decimal":"disc");var f=this,h=this.selection.getRange(),j=function(a){return 1==a.nodeType?"br"!=a.tagName.toLowerCase():!domUtils.isWhitespace(a)},k="insertorderedlist"==a.toLowerCase()?"ol":"ul",l=f.document.createDocumentFragment();h.adjustmentBoundary().shrinkBoundary();var m,n,o,p,q=h.createBookmark(!0),r=g(f.document.getElementById(q.start)),s=0,t=g(f.document.getElementById(q.end)),u=0;if(r||t){if(r&&(m=r.parentNode),q.end||(t=r),t&&(n=t.parentNode),m===n){for(;r!==t;){if(p=r,r=r.nextSibling,!domUtils.isBlockElm(p.firstChild)){for(var v=f.document.createElement("p");p.firstChild;)v.appendChild(p.firstChild);p.appendChild(v)}l.appendChild(p)}if(p=f.document.createElement("span"),m.insertBefore(p,t),!domUtils.isBlockElm(t.firstChild)){for(v=f.document.createElement("p");t.firstChild;)v.appendChild(t.firstChild);t.appendChild(v)}l.appendChild(t),domUtils.breakParent(p,m),domUtils.isEmptyNode(p.previousSibling)&&domUtils.remove(p.previousSibling),domUtils.isEmptyNode(p.nextSibling)&&domUtils.remove(p.nextSibling);var w=b(m)||domUtils.getComputedStyle(m,"list-style-type")||("insertorderedlist"==a.toLowerCase()?"decimal":"disc");if(m.tagName.toLowerCase()==k&&w==c){for(var x,y=0,z=f.document.createDocumentFragment();x=l.firstChild;)if(domUtils.isTagNode(x,"ol ul"))z.appendChild(x);else for(;x.firstChild;)z.appendChild(x.firstChild),domUtils.remove(x);p.parentNode.insertBefore(z,p)}else o=f.document.createElement(k),e(o,c),o.appendChild(l),p.parentNode.insertBefore(o,p);return domUtils.remove(p),o&&d(o,k,c),void h.moveToBookmark(q).select()}if(r){for(;r;){if(p=r.nextSibling,domUtils.isTagNode(r,"ol ul"))l.appendChild(r);else{for(var A=f.document.createDocumentFragment(),B=0;r.firstChild;)domUtils.isBlockElm(r.firstChild)&&(B=1),A.appendChild(r.firstChild);if(B)l.appendChild(A);else{var C=f.document.createElement("p");C.appendChild(A),l.appendChild(C)}domUtils.remove(r)}r=p}m.parentNode.insertBefore(l,m.nextSibling),domUtils.isEmptyNode(m)?(h.setStartBefore(m),domUtils.remove(m)):h.setStartAfter(m),s=1}if(t&&domUtils.inDoc(n,f.document)){for(r=n.firstChild;r&&r!==t;){if(p=r.nextSibling,domUtils.isTagNode(r,"ol ul"))l.appendChild(r);else{for(A=f.document.createDocumentFragment(),B=0;r.firstChild;)domUtils.isBlockElm(r.firstChild)&&(B=1),A.appendChild(r.firstChild);B?l.appendChild(A):(C=f.document.createElement("p"),C.appendChild(A),l.appendChild(C)),domUtils.remove(r)}r=p}var D=domUtils.createElement(f.document,"div",{tmpDiv:1});domUtils.moveChild(t,D),l.appendChild(D),domUtils.remove(t),n.parentNode.insertBefore(l,n),h.setEndBefore(n),domUtils.isEmptyNode(n)&&domUtils.remove(n),u=1}}s||h.setStartBefore(f.document.getElementById(q.start)),q.end&&!u&&h.setEndAfter(f.document.getElementById(q.end)),h.enlarge(!0,function(a){return i[a.tagName]}),l=f.document.createDocumentFragment();for(var E,F=h.createBookmark(),G=domUtils.getNextDomNode(F.start,!1,j),H=h.cloneRange(),I=domUtils.isBlockElm;G&&G!==F.end&&domUtils.getPosition(G,F.end)&domUtils.POSITION_PRECEDING;)if(3==G.nodeType||dtd.li[G.tagName]){if(1==G.nodeType&&dtd.$list[G.tagName]){for(;G.firstChild;)l.appendChild(G.firstChild);E=domUtils.getNextDomNode(G,!1,j),domUtils.remove(G),G=E;continue}for(E=G,H.setStartBefore(G);G&&G!==F.end&&(!I(G)||domUtils.isBookmarkNode(G));)E=G,G=domUtils.getNextDomNode(G,!1,null,function(a){return!i[a.tagName]});G&&I(G)&&(p=domUtils.getNextDomNode(E,!1,j),p&&domUtils.isBookmarkNode(p)&&(G=domUtils.getNextDomNode(p,!1,j),E=p)),H.setEndAfter(E),G=domUtils.getNextDomNode(E,!1,j);var J=h.document.createElement("li");if(J.appendChild(H.extractContents()),domUtils.isEmptyNode(J)){for(var E=h.document.createElement("p");J.firstChild;)E.appendChild(J.firstChild);J.appendChild(E)}l.appendChild(J)}else G=domUtils.getNextDomNode(G,!0,j);h.moveToBookmark(F).collapse(!0),o=f.document.createElement(k),e(o,c),o.appendChild(l),h.insertNode(o),d(o,k,c);for(var x,y=0,K=domUtils.getElementsByTagName(o,"div");x=K[y++];)x.getAttribute("tmpDiv")&&domUtils.remove(x,!0);h.moveToBookmark(q).select()},queryCommandState:function(a){for(var b,c="insertorderedlist"==a.toLowerCase()?"ol":"ul",d=this.selection.getStartElementPath(),e=0;b=d[e++];){if("TABLE"==b.nodeName)return 0;if(c==b.nodeName.toLowerCase())return 1}return 0},queryCommandValue:function(a){for(var c,d,e="insertorderedlist"==a.toLowerCase()?"ol":"ul",f=this.selection.getStartElementPath(),g=0;d=f[g++];){if("TABLE"==d.nodeName){c=null;break}if(e==d.nodeName.toLowerCase()){c=d;break}}return c?b(c)||domUtils.getComputedStyle(c,"list-style-type"):null}}},function(){var a={textarea:function(a,b){var c=b.ownerDocument.createElement("textarea");return c.style.cssText="position:absolute;resize:none;width:100%;height:100%;border:0;padding:0;margin:0;overflow-y:auto;",browser.ie&&browser.version<8&&(c.style.width=b.offsetWidth+"px",c.style.height=b.offsetHeight+"px",b.onresize=function(){c.style.width=b.offsetWidth+"px",c.style.height=b.offsetHeight+"px"}),b.appendChild(c),{setContent:function(a){c.value=a},getContent:function(){return c.value},select:function(){var a;browser.ie?(a=c.createTextRange(),a.collapse(!0),a.select()):(c.setSelectionRange(0,0),c.focus())},dispose:function(){b.removeChild(c),b.onresize=null,c=null,b=null}}},codemirror:function(a,b){var c=window.CodeMirror(b,{mode:"text/html",tabMode:"indent",lineNumbers:!0,lineWrapping:!0}),d=c.getWrapperElement();return d.style.cssText='position:absolute;left:0;top:0;width:100%;height:100%;font-family:consolas,"Courier new",monospace;font-size:13px;',c.getScrollerElement().style.cssText="position:absolute;left:0;top:0;width:100%;height:100%;",c.refresh(),{getCodeMirror:function(){return c},setContent:function(a){c.setValue(a)},getContent:function(){return c.getValue()},select:function(){c.focus()},dispose:function(){b.removeChild(d),d=null,c=null}}}};UE.plugins.source=function(){function b(b){return a["codemirror"==f.sourceEditor&&window.CodeMirror?"codemirror":"textarea"](e,b)}var c,d,e=this,f=this.options,g=!1;f.sourceEditor=browser.ie?"textarea":f.sourceEditor||"codemirror",e.setOpt({sourceEditorFirst:!1});var h,i,j;e.commands.source={execCommand:function(){if(g=!g){j=e.selection.getRange().createAddress(!1,!0),e.undoManger&&e.undoManger.save(!0),browser.gecko&&(e.body.contentEditable=!1),h=e.iframe.style.cssText,e.iframe.style.cssText+="position:absolute;left:-32768px;top:-32768px;",e.fireEvent("beforegetcontent");var a=UE.htmlparser(e.body.innerHTML);e.filterOutputRule(a),a.traversal(function(a){if("element"==a.type)switch(a.tagName){case"td":case"th":case"caption":a.children&&1==a.children.length&&"br"==a.firstChild().tagName&&a.removeChild(a.firstChild());break;case"pre":a.innerText(a.innerText().replace(/ /g," "))}}),e.fireEvent("aftergetcontent");var f=a.toHtml(!0);c=b(e.iframe.parentNode),c.setContent(f),d=e.setContent,e.setContent=function(a){var b=UE.htmlparser(a);e.filterInputRule(b),a=b.toHtml(),c.setContent(a)},setTimeout(function(){c.select(),e.addListener("fullscreenchanged",function(){try{c.getCodeMirror().refresh()}catch(a){}})}),i=e.getContent,e.getContent=function(){return c.getContent()||"<p>"+(browser.ie?"":"<br/>")+"</p>"}}else{e.iframe.style.cssText=h;var k=c.getContent()||"<p>"+(browser.ie?"":"<br/>")+"</p>";k=k.replace(new RegExp("[\\r\\t\\n ]*</?(\\w+)\\s*(?:[^>]*)>","g"),function(a,b){return b&&!dtd.$inlineWithA[b.toLowerCase()]?a.replace(/(^[\n\r\t ]*)|([\n\r\t ]*$)/g,""):a.replace(/(^[\n\r\t]*)|([\n\r\t]*$)/g,"")}),e.setContent=d,e.setContent(k),c.dispose(),c=null,e.getContent=i;var l=e.body.firstChild;if(l||(e.body.innerHTML="<p>"+(browser.ie?"":"<br/>")+"</p>",l=e.body.firstChild),e.undoManger&&e.undoManger.save(!0),browser.gecko){var m=document.createElement("input");m.style.cssText="position:absolute;left:0;top:-32768px",document.body.appendChild(m),e.body.contentEditable=!1,setTimeout(function(){domUtils.setViewportOffset(m,{left:-32768,top:0}),m.focus(),setTimeout(function(){e.body.contentEditable=!0,e.selection.getRange().moveToAddress(j).select(!0),domUtils.remove(m)})})}else try{e.selection.getRange().moveToAddress(j).select(!0)}catch(n){}}this.fireEvent("sourcemodechanged",g)},queryCommandState:function(){return 0|g},notNeedUndo:1};var k=e.queryCommandState;e.queryCommandState=function(a){return a=a.toLowerCase(),g?a in{source:1,fullscreen:1}?1:-1:k.apply(this,arguments)},"codemirror"==f.sourceEditor&&e.addListener("ready",function(){utils.loadFile(document,{src:f.codeMirrorJsUrl||f.UEDITOR_HOME_URL+"third-party/codemirror/codemirror.js",tag:"script",type:"text/javascript",defer:"defer"},function(){f.sourceEditorFirst&&setTimeout(function(){e.execCommand("source")},0)}),utils.loadFile(document,{tag:"link",rel:"stylesheet",type:"text/css",href:f.codeMirrorCssUrl||f.UEDITOR_HOME_URL+"third-party/codemirror/codemirror.css"})})}}(),UE.plugins.enterkey=function(){var a,b=this,c=b.options.enterTag;b.addListener("keyup",function(c,d){var e=d.keyCode||d.which;if(13==e){var f,g=b.selection.getRange(),h=g.startContainer;if(browser.ie)b.fireEvent("saveScene",!0,!0);else{if(/h\d/i.test(a)){if(browser.gecko){var i=domUtils.findParentByTagName(h,["h1","h2","h3","h4","h5","h6","blockquote","caption","table"],!0);i||(b.document.execCommand("formatBlock",!1,"<p>"),f=1)}else if(1==h.nodeType){var j,k=b.document.createTextNode("");if(g.insertNode(k),j=domUtils.findParentByTagName(k,"div",!0)){for(var l=b.document.createElement("p");j.firstChild;)l.appendChild(j.firstChild);j.parentNode.insertBefore(l,j),domUtils.remove(j),g.setStartBefore(k).setCursor(),f=1}domUtils.remove(k)}b.undoManger&&f&&b.undoManger.save()}browser.opera&&g.select()}}}),b.addListener("keydown",function(d,e){var f=e.keyCode||e.which;if(13==f){if(b.fireEvent("beforeenterkeydown"))return void domUtils.preventDefault(e);b.fireEvent("saveScene",!0,!0),a="";var g=b.selection.getRange();if(!g.collapsed){var h=g.startContainer,i=g.endContainer,j=domUtils.findParentByTagName(h,"td",!0),k=domUtils.findParentByTagName(i,"td",!0);if(j&&k&&j!==k||!j&&k||j&&!k)return void(e.preventDefault?e.preventDefault():e.returnValue=!1)}if("p"==c)browser.ie||(h=domUtils.findParentByTagName(g.startContainer,["ol","ul","p","h1","h2","h3","h4","h5","h6","blockquote","caption"],!0),h||browser.opera?(a=h.tagName,"p"==h.tagName.toLowerCase()&&browser.gecko&&domUtils.removeDirtyAttr(h)):(b.document.execCommand("formatBlock",!1,"<p>"),browser.gecko&&(g=b.selection.getRange(),h=domUtils.findParentByTagName(g.startContainer,"p",!0),h&&domUtils.removeDirtyAttr(h))));else if(e.preventDefault?e.preventDefault():e.returnValue=!1,g.collapsed){m=g.document.createElement("br"),g.insertNode(m);var l=m.parentNode;l.lastChild===m?(m.parentNode.insertBefore(m.cloneNode(!0),m),g.setStartBefore(m)):g.setStartAfter(m),g.setCursor()}else if(g.deleteContents(),h=g.startContainer,1==h.nodeType&&(h=h.childNodes[g.startOffset])){for(;1==h.nodeType;){if(dtd.$empty[h.tagName])return g.setStartBefore(h).setCursor(),b.undoManger&&b.undoManger.save(),!1;if(!h.firstChild){var m=g.document.createElement("br");return h.appendChild(m),g.setStart(h,0).setCursor(),b.undoManger&&b.undoManger.save(),!1}h=h.firstChild}h===g.startContainer.childNodes[g.startOffset]?(m=g.document.createElement("br"),g.insertNode(m).setCursor()):g.setStart(h,0).setCursor()}else m=g.document.createElement("br"),g.insertNode(m).setStartAfter(m).setCursor()}})},UE.plugins.keystrokes=function(){var a=this,b=!0;a.addListener("keydown",function(c,d){var e=d.keyCode||d.which,f=a.selection.getRange();if(!f.collapsed&&!(d.ctrlKey||d.shiftKey||d.altKey||d.metaKey)&&(e>=65&&e<=90||e>=48&&e<=57||e>=96&&e<=111||{13:1,8:1,46:1}[e])){var g=f.startContainer;if(domUtils.isFillChar(g)&&f.setStartBefore(g),g=f.endContainer,domUtils.isFillChar(g)&&f.setEndAfter(g),f.txtToElmBoundary(),f.endContainer&&1==f.endContainer.nodeType&&(g=f.endContainer.childNodes[f.endOffset],g&&domUtils.isBr(g)&&f.setEndAfter(g)),0==f.startOffset&&(g=f.startContainer,domUtils.isBoundaryNode(g,"firstChild")&&(g=f.endContainer,f.endOffset==(3==g.nodeType?g.nodeValue.length:g.childNodes.length)&&domUtils.isBoundaryNode(g,"lastChild"))))return a.fireEvent("saveScene"),a.body.innerHTML="<p>"+(browser.ie?"":"<br/>")+"</p>",f.setStart(a.body.firstChild,0).setCursor(!1,!0),void a._selectionChange()}if(e==keymap.Backspace){if(f=a.selection.getRange(),b=f.collapsed,a.fireEvent("delkeydown",d))return;var h,i;if(f.collapsed&&f.inFillChar()&&(h=f.startContainer,domUtils.isFillChar(h)?(f.setStartBefore(h).shrinkBoundary(!0).collapse(!0),domUtils.remove(h)):(h.nodeValue=h.nodeValue.replace(new RegExp("^"+domUtils.fillChar),""),f.startOffset--,f.collapse(!0).select(!0))),h=f.getClosedNode())return a.fireEvent("saveScene"),f.setStartBefore(h),domUtils.remove(h),f.setCursor(),a.fireEvent("saveScene"),void domUtils.preventDefault(d);if(!browser.ie&&(h=domUtils.findParentByTagName(f.startContainer,"table",!0),i=domUtils.findParentByTagName(f.endContainer,"table",!0),h&&!i||!h&&i||h!==i))return void d.preventDefault()}if(e==keymap.Tab){var j={ol:1,ul:1,table:1};if(a.fireEvent("tabkeydown",d))return void domUtils.preventDefault(d);var k=a.selection.getRange();a.fireEvent("saveScene");for(var l=0,m="",n=a.options.tabSize||4,o=a.options.tabNode||" ";l<n;l++)m+=o;var p=a.document.createElement("span");if(p.innerHTML=m+domUtils.fillChar,k.collapsed)k.insertNode(p.cloneNode(!0).firstChild).setCursor(!0);else{var q=function(a){return domUtils.isBlockElm(a)&&!j[a.tagName.toLowerCase()]};if(h=domUtils.findParent(k.startContainer,q,!0),i=domUtils.findParent(k.endContainer,q,!0),h&&i&&h===i)k.deleteContents(),k.insertNode(p.cloneNode(!0).firstChild).setCursor(!0);else{var r=k.createBookmark();k.enlarge(!0);for(var s=k.createBookmark(),t=domUtils.getNextDomNode(s.start,!1,q);t&&!(domUtils.getPosition(t,s.end)&domUtils.POSITION_FOLLOWING);)t.insertBefore(p.cloneNode(!0).firstChild,t.firstChild),t=domUtils.getNextDomNode(t,!1,q);k.moveToBookmark(s).moveToBookmark(r).select()}}domUtils.preventDefault(d)}if(browser.gecko&&46==e&&(k=a.selection.getRange(),k.collapsed&&(h=k.startContainer,domUtils.isEmptyBlock(h)))){for(var u=h.parentNode;1==domUtils.getChildCount(u)&&!domUtils.isBody(u);)h=u,u=u.parentNode;return void(h===u.lastChild&&d.preventDefault())}}),a.addListener("keyup",function(a,c){var d,e=c.keyCode||c.which,f=this;if(e==keymap.Backspace){if(f.fireEvent("delkeyup"))return;if(d=f.selection.getRange(),d.collapsed){var g,h=["h1","h2","h3","h4","h5","h6"];if((g=domUtils.findParentByTagName(d.startContainer,h,!0))&&domUtils.isEmptyBlock(g)){var i=g.previousSibling;if(i&&"TABLE"!=i.nodeName)return domUtils.remove(g),void d.setStartAtLast(i).setCursor(!1,!0);var j=g.nextSibling;if(j&&"TABLE"!=j.nodeName)return domUtils.remove(g),void d.setStartAtFirst(j).setCursor(!1,!0)}if(domUtils.isBody(d.startContainer)){var g=domUtils.createElement(f.document,"p",{innerHTML:browser.ie?domUtils.fillChar:"<br/>"});d.insertNode(g).setStart(g,0).setCursor(!1,!0)}}if(!b&&(3==d.startContainer.nodeType||1==d.startContainer.nodeType&&domUtils.isEmptyBlock(d.startContainer)))if(browser.ie){var k=d.document.createElement("span");d.insertNode(k).setStartBefore(k).collapse(!0),d.select(),domUtils.remove(k)}else d.select()}})},UE.plugins.fiximgclick=function(){function a(){this.editor=null,this.resizer=null,this.cover=null,this.doc=document,this.prePos={x:0,y:0},this.startPos={x:0,y:0}}var b=!1;return function(){var c=[[0,0,-1,-1],[0,0,0,-1],[0,0,1,-1],[0,0,-1,0],[0,0,1,0],[0,0,-1,1],[0,0,0,1],[0,0,1,1]];a.prototype={init:function(a){var b=this;b.editor=a,b.startPos=this.prePos={x:0,y:0},b.dragId=-1;var c=[],d=b.cover=document.createElement("div"),e=b.resizer=document.createElement("div");for(d.id=b.editor.ui.id+"_imagescale_cover",d.style.cssText="position:absolute;display:none;z-index:"+b.editor.options.zIndex+";filter:alpha(opacity=0); opacity:0;background:#CCC;",domUtils.on(d,"mousedown click",function(){b.hide()}),i=0;i<8;i++)c.push('<span class="edui-editor-imagescale-hand'+i+'"></span>');e.id=b.editor.ui.id+"_imagescale",e.className="edui-editor-imagescale",e.innerHTML=c.join(""),e.style.cssText+=";display:none;border:1px solid #3b77ff;z-index:"+b.editor.options.zIndex+";",b.editor.ui.getDom().appendChild(d),b.editor.ui.getDom().appendChild(e),b.initStyle(),b.initEvents()},initStyle:function(){utils.cssRule("imagescale",".edui-editor-imagescale{display:none;position:absolute;border:1px solid #38B2CE;cursor:hand;-webkit-box-sizing: content-box;-moz-box-sizing: content-box;box-sizing: content-box;}.edui-editor-imagescale span{position:absolute;width:6px;height:6px;overflow:hidden;font-size:0px;display:block;background-color:#3C9DD0;}.edui-editor-imagescale .edui-editor-imagescale-hand0{cursor:nw-resize;top:0;margin-top:-4px;left:0;margin-left:-4px;}.edui-editor-imagescale .edui-editor-imagescale-hand1{cursor:n-resize;top:0;margin-top:-4px;left:50%;margin-left:-4px;}.edui-editor-imagescale .edui-editor-imagescale-hand2{cursor:ne-resize;top:0;margin-top:-4px;left:100%;margin-left:-3px;}.edui-editor-imagescale .edui-editor-imagescale-hand3{cursor:w-resize;top:50%;margin-top:-4px;left:0;margin-left:-4px;}.edui-editor-imagescale .edui-editor-imagescale-hand4{cursor:e-resize;top:50%;margin-top:-4px;left:100%;margin-left:-3px;}.edui-editor-imagescale .edui-editor-imagescale-hand5{cursor:sw-resize;top:100%;margin-top:-3px;left:0;margin-left:-4px;}.edui-editor-imagescale .edui-editor-imagescale-hand6{cursor:s-resize;top:100%;margin-top:-3px;left:50%;margin-left:-4px;}.edui-editor-imagescale .edui-editor-imagescale-hand7{cursor:se-resize;top:100%;margin-top:-3px;left:100%;margin-left:-3px;}")},initEvents:function(){var a=this;a.startPos.x=a.startPos.y=0,a.isDraging=!1},_eventHandler:function(a){var c=this;switch(a.type){case"mousedown":var d,d=a.target||a.srcElement;d.className.indexOf("edui-editor-imagescale-hand")!=-1&&c.dragId==-1&&(c.dragId=d.className.slice(-1),c.startPos.x=c.prePos.x=a.clientX,c.startPos.y=c.prePos.y=a.clientY,domUtils.on(c.doc,"mousemove",c.proxy(c._eventHandler,c)));break;case"mousemove":c.dragId!=-1&&(c.updateContainerStyle(c.dragId,{x:a.clientX-c.prePos.x,y:a.clientY-c.prePos.y}),c.prePos.x=a.clientX,c.prePos.y=a.clientY,b=!0,c.updateTargetElement());break;case"mouseup":c.dragId!=-1&&(c.updateContainerStyle(c.dragId,{x:a.clientX-c.prePos.x,y:a.clientY-c.prePos.y}),c.updateTargetElement(),c.target.parentNode&&c.attachTo(c.target),c.dragId=-1),domUtils.un(c.doc,"mousemove",c.proxy(c._eventHandler,c)),b&&(b=!1,c.editor.fireEvent("contentchange"))}},updateTargetElement:function(){var a=this;domUtils.setStyles(a.target,{width:a.resizer.style.width,height:a.resizer.style.height}),a.target.width=parseInt(a.resizer.style.width),a.target.height=parseInt(a.resizer.style.height),a.attachTo(a.target)},updateContainerStyle:function(a,b){var d,e=this,f=e.resizer;0!=c[a][0]&&(d=parseInt(f.style.left)+b.x,f.style.left=e._validScaledProp("left",d)+"px"),0!=c[a][1]&&(d=parseInt(f.style.top)+b.y,f.style.top=e._validScaledProp("top",d)+"px"),0!=c[a][2]&&(d=f.clientWidth+c[a][2]*b.x,f.style.width=e._validScaledProp("width",d)+"px"),0!=c[a][3]&&(d=f.clientHeight+c[a][3]*b.y,f.style.height=e._validScaledProp("height",d)+"px")},_validScaledProp:function(a,b){var c=this.resizer,d=document;switch(b=isNaN(b)?0:b,a){case"left":return b<0?0:b+c.clientWidth>d.clientWidth?d.clientWidth-c.clientWidth:b;case"top":return b<0?0:b+c.clientHeight>d.clientHeight?d.clientHeight-c.clientHeight:b;case"width":return b<=0?1:b+c.offsetLeft>d.clientWidth?d.clientWidth-c.offsetLeft:b;case"height":return b<=0?1:b+c.offsetTop>d.clientHeight?d.clientHeight-c.offsetTop:b}},hideCover:function(){this.cover.style.display="none"},showCover:function(){var a=this,b=domUtils.getXY(a.editor.ui.getDom()),c=domUtils.getXY(a.editor.iframe);domUtils.setStyles(a.cover,{width:a.editor.iframe.offsetWidth+"px",height:a.editor.iframe.offsetHeight+"px",top:c.y-b.y+"px",left:c.x-b.x+"px",position:"absolute",display:""})},show:function(a){var b=this;b.resizer.style.display="block",a&&b.attachTo(a),domUtils.on(this.resizer,"mousedown",b.proxy(b._eventHandler,b)),domUtils.on(b.doc,"mouseup",b.proxy(b._eventHandler,b)),b.showCover(),b.editor.fireEvent("afterscaleshow",b),b.editor.fireEvent("saveScene")},hide:function(){var a=this;a.hideCover(),a.resizer.style.display="none",domUtils.un(a.resizer,"mousedown",a.proxy(a._eventHandler,a)),domUtils.un(a.doc,"mouseup",a.proxy(a._eventHandler,a)),a.editor.fireEvent("afterscalehide",a)},proxy:function(a,b){return function(c){return a.apply(b||this,arguments)}},attachTo:function(a){var b=this,c=b.target=a,d=this.resizer,e=domUtils.getXY(c),f=domUtils.getXY(b.editor.iframe),g=domUtils.getXY(d.parentNode);domUtils.setStyles(d,{width:c.width+"px",height:c.height+"px",left:f.x+e.x-b.editor.document.body.scrollLeft-g.x-parseInt(d.style.borderLeftWidth)+"px",top:f.y+e.y-b.editor.document.body.scrollTop-g.y-parseInt(d.style.borderTopWidth)+"px"})}}}(),function(){var b,c=this;c.setOpt("imageScaleEnabled",!0),!browser.ie&&c.options.imageScaleEnabled&&c.addListener("click",function(d,e){var f=c.selection.getRange(),g=f.getClosedNode();if(g&&"IMG"==g.tagName&&"false"!=c.body.contentEditable){if(g.className.indexOf("edui-faked-music")!=-1||g.getAttribute("anchorname")||domUtils.hasClass(g,"loadingclass")||domUtils.hasClass(g,"loaderrorclass"))return;if(!b){b=new a,b.init(c),c.ui.getDom().appendChild(b.resizer);var h,i=function(a){b.hide(),b.target&&c.selection.getRange().selectNode(b.target).select()},j=function(a){var b=a.target||a.srcElement;!b||void 0!==b.className&&b.className.indexOf("edui-editor-imagescale")!=-1||i(a)};c.addListener("afterscaleshow",function(a){c.addListener("beforekeydown",i),c.addListener("beforemousedown",j),domUtils.on(document,"keydown",i),domUtils.on(document,"mousedown",j),c.selection.getNative().removeAllRanges()}),c.addListener("afterscalehide",function(a){c.removeListener("beforekeydown",i),c.removeListener("beforemousedown",j),domUtils.un(document,"keydown",i),domUtils.un(document,"mousedown",j);var d=b.target;d.parentNode&&c.selection.getRange().selectNode(d).select()}),domUtils.on(b.resizer,"mousedown",function(a){c.selection.getNative().removeAllRanges();var d=a.target||a.srcElement;d&&d.className.indexOf("edui-editor-imagescale-hand")==-1&&(h=setTimeout(function(){b.hide(),b.target&&c.selection.getRange().selectNode(d).select()},200))}),domUtils.on(b.resizer,"mouseup",function(a){var b=a.target||a.srcElement;b&&b.className.indexOf("edui-editor-imagescale-hand")==-1&&clearTimeout(h)})}b.show(g)}else b&&"none"!=b.resizer.style.display&&b.hide()}),browser.webkit&&c.addListener("click",function(a,b){if("IMG"==b.target.tagName&&"false"!=c.body.contentEditable){var d=new dom.Range(c.document);d.selectNode(b.target).select()}})}}(),UE.plugin.register("autolink",function(){var a=0;return browser.ie?{}:{bindEvents:{reset:function(){a=0},keydown:function(a,b){var c=this,d=b.keyCode||b.which;if(32==d||13==d){for(var e,f,g=c.selection.getNative(),h=g.getRangeAt(0).cloneRange(),i=h.startContainer;1==i.nodeType&&h.startOffset>0&&(i=h.startContainer.childNodes[h.startOffset-1]);)h.setStart(i,1==i.nodeType?i.childNodes.length:i.nodeValue.length),h.collapse(!0),i=h.startContainer;do{if(0==h.startOffset){for(i=h.startContainer.previousSibling;i&&1==i.nodeType;)i=i.lastChild;if(!i||domUtils.isFillChar(i))break;e=i.nodeValue.length}else i=h.startContainer,e=h.startOffset;h.setStart(i,e-1),f=h.toString().charCodeAt(0)}while(160!=f&&32!=f);if(h.toString().replace(new RegExp(domUtils.fillChar,"g"),"").match(/(?:https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.)/i)){for(;h.toString().length&&!/^(?:https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.)/i.test(h.toString());)try{h.setStart(h.startContainer,h.startOffset+1)}catch(j){for(var i=h.startContainer;!(next=i.nextSibling);){if(domUtils.isBody(i))return;i=i.parentNode}h.setStart(next,0)}if(domUtils.findParentByTagName(h.startContainer,"a",!0))return;var k,l=c.document.createElement("a"),m=c.document.createTextNode(" ");c.undoManger&&c.undoManger.save(),l.appendChild(h.extractContents()),l.href=l.innerHTML=l.innerHTML.replace(/<[^>]+>/g,""),k=l.getAttribute("href").replace(new RegExp(domUtils.fillChar,"g"),""),k=/^(?:https?:\/\/)/gi.test(k)?k:"http://"+k,l.setAttribute("_src",utils.html(k)),l.href=utils.html(k),h.insertNode(l),l.parentNode.insertBefore(m,l.nextSibling),h.setStart(m,0),h.collapse(!0),g.removeAllRanges(),g.addRange(h),c.undoManger&&c.undoManger.save()}}}}}},function(){function a(a){if(3==a.nodeType)return null;if("A"==a.nodeName)return a;for(var b=a.lastChild;b;){if("A"==b.nodeName)return b;if(3==b.nodeType){if(domUtils.isWhitespace(b)){b=b.previousSibling;continue}return null}b=b.lastChild}}var b={37:1,38:1,39:1,40:1,13:1,32:1};browser.ie&&this.addListener("keyup",function(c,d){var e=this,f=d.keyCode;if(b[f]){var g=e.selection.getRange(),h=g.startContainer;if(13==f){for(;h&&!domUtils.isBody(h)&&!domUtils.isBlockElm(h);)h=h.parentNode;if(h&&!domUtils.isBody(h)&&"P"==h.nodeName){var i=h.previousSibling;if(i&&1==i.nodeType){var i=a(i);i&&!i.getAttribute("_href")&&domUtils.remove(i,!0)}}}else if(32==f)3==h.nodeType&&/^\s$/.test(h.nodeValue)&&(h=h.previousSibling,h&&"A"==h.nodeName&&!h.getAttribute("_href")&&domUtils.remove(h,!0));else if(h=domUtils.findParentByTagName(h,"a",!0),h&&!h.getAttribute("_href")){var j=g.createBookmark();domUtils.remove(h,!0),g.moveToBookmark(j).select(!0)}}})}),UE.plugins.autoheight=function(){function a(){var a=this;clearTimeout(e),f||(!a.queryCommandState||a.queryCommandState&&1!=a.queryCommandState("source"))&&(e=setTimeout(function(){for(var b=a.body.lastChild;b&&1!=b.nodeType;)b=b.previousSibling;b&&1==b.nodeType&&(b.style.clear="both",d=Math.max(domUtils.getXY(b).y+b.offsetHeight+25,Math.max(h.minFrameHeight,h.initialFrameHeight)),d!=g&&(d!==parseInt(a.iframe.parentNode.style.height)&&(a.iframe.parentNode.style.height=d+"px"),a.body.style.height=d+"px",g=d),domUtils.removeStyle(b,"clear"))},50))}var b=this;if(b.autoHeightEnabled=b.options.autoHeightEnabled!==!1,b.autoHeightEnabled){var c,d,e,f,g=0,h=b.options;b.addListener("fullscreenchanged",function(a,b){f=b}),b.addListener("destroy",function(){b.removeListener("contentchange afterinserthtml keyup mouseup",a)}),b.enableAutoHeight=function(){var b=this;if(b.autoHeightEnabled){var d=b.document;b.autoHeightEnabled=!0,c=d.body.style.overflowY,d.body.style.overflowY="hidden",b.addListener("contentchange afterinserthtml keyup mouseup",a),setTimeout(function(){a.call(b)},browser.gecko?100:0),b.fireEvent("autoheightchanged",b.autoHeightEnabled)}},b.disableAutoHeight=function(){b.body.style.overflowY=c||"",b.removeListener("contentchange",a),b.removeListener("keyup",a),b.removeListener("mouseup",a),b.autoHeightEnabled=!1,b.fireEvent("autoheightchanged",b.autoHeightEnabled)},b.on("setHeight",function(){b.disableAutoHeight()}),b.addListener("ready",function(){b.enableAutoHeight();var c;domUtils.on(browser.ie?b.body:b.document,browser.webkit?"dragover":"drop",function(){clearTimeout(c),c=setTimeout(function(){a.call(b)},100)});var d;window.onscroll=function(){
null===d?d=this.scrollY:0==this.scrollY&&0!=d&&(b.window.scrollTo(0,0),d=null)}})}},UE.plugins.autofloat=function(){function a(){return UE.ui?1:(alert(g.autofloatMsg),0)}function b(){var a=document.body.style;a.backgroundImage='url("about:blank")',a.backgroundAttachment="fixed"}function c(){var a=domUtils.getXY(k),b=domUtils.getComputedStyle(k,"position"),c=domUtils.getComputedStyle(k,"left");k.style.width=k.offsetWidth+"px",k.style.zIndex=1*f.options.zIndex+1,k.parentNode.insertBefore(q,k),o||p&&browser.ie?("absolute"!=k.style.position&&(k.style.position="absolute"),k.style.top=(document.body.scrollTop||document.documentElement.scrollTop)-l+i+"px"):(browser.ie7Compat&&r&&(r=!1,k.style.left=domUtils.getXY(k).x-document.documentElement.getBoundingClientRect().left+2+"px"),"fixed"!=k.style.position&&(k.style.position="fixed",k.style.top=i+"px",("absolute"==b||"relative"==b)&&parseFloat(c)&&(k.style.left=a.x+"px")))}function d(){r=!0,q.parentNode&&q.parentNode.removeChild(q),k.style.cssText=j}function e(){var a=m(f.container),b=f.options.toolbarTopOffset||0;a.top<0&&a.bottom-k.offsetHeight>b?c():d()}var f=this,g=f.getLang();f.setOpt({topOffset:0});var h=f.options.autoFloatEnabled!==!1,i=f.options.topOffset;if(h){var j,k,l,m,n=UE.ui.uiUtils,o=browser.ie&&browser.version<=6,p=browser.quirks,q=document.createElement("div"),r=!0,s=utils.defer(function(){e()},browser.ie?200:100,!0);f.addListener("destroy",function(){domUtils.un(window,["scroll","resize"],e),f.removeListener("keydown",s)}),f.addListener("ready",function(){if(a(f)){if(!f.ui)return;m=n.getClientRect,k=f.ui.getDom("toolbarbox"),l=m(k).top,j=k.style.cssText,q.style.height=k.offsetHeight+"px",o&&b(),domUtils.on(window,["scroll","resize"],e),f.addListener("keydown",s),f.addListener("beforefullscreenchange",function(a,b){b&&d()}),f.addListener("fullscreenchanged",function(a,b){b||e()}),f.addListener("sourcemodechanged",function(a,b){setTimeout(function(){e()},0)}),f.addListener("clearDoc",function(){setTimeout(function(){e()},0)})}})}},UE.plugins.video=function(){function a(a,b,d,e,f,g,h){a=utils.unhtmlForUrl(a),f=utils.unhtml(f),g=utils.unhtml(g),b=parseInt(b,10)||0,d=parseInt(d,10)||0;var i;switch(h){case"image":i="<img "+(e?'id="'+e+'"':"")+' width="'+b+'" height="'+d+'" _url="'+a+'" class="'+g.replace(/\bvideo-js\b/,"")+'" src="'+c.options.UEDITOR_HOME_URL+'themes/default/img/spacer.gif" style="background:url('+c.options.UEDITOR_HOME_URL+"themes/default/img/videologo.gif) no-repeat center center; border:1px solid gray;"+(f?"float:"+f+";":"")+'" />';break;case"embed":i='<embed type="application/x-shockwave-flash" class="'+g+'" pluginspage="http://www.macromedia.com/go/getflashplayer" src="'+utils.html(a)+'" width="'+b+'" height="'+d+'"'+(f?' style="float:'+f+'"':"")+' wmode="transparent" play="true" loop="false" menu="false" allowscriptaccess="never" allowfullscreen="true" >';break;case"video":var j=a.substr(a.lastIndexOf(".")+1);"ogv"==j&&(j="ogg"),i="<video"+(e?' id="'+e+'"':"")+' class="'+g+' video-js" '+(f?' style="float:'+f+'"':"")+' controls preload="none" width="'+b+'" height="'+d+'" src="'+a+'" data-setup="{}"><source src="'+a+'" type="video/'+j+'" /></video>'}return i}function b(b,c){utils.each(b.getNodesByTagName(c?"img":"embed video"),function(b){var d=b.getAttr("class");if(d&&d.indexOf("edui-faked-video")!=-1){var e=a(c?b.getAttr("_url"):b.getAttr("src"),b.getAttr("width"),b.getAttr("height"),null,b.getStyle("float")||"",d,c?"embed":"image");b.parentNode.replaceChild(UE.uNode.createElement(e),b)}if(d&&d.indexOf("edui-upload-video")!=-1){var e=a(c?b.getAttr("_url"):b.getAttr("src"),b.getAttr("width"),b.getAttr("height"),null,b.getStyle("float")||"",d,c?"video":"image");b.parentNode.replaceChild(UE.uNode.createElement(e),b)}})}var c=this;c.addOutputRule(function(a){b(a,!0)}),c.addInputRule(function(a){b(a)}),c.commands.insertvideo={execCommand:function(b,d,e){d=utils.isArray(d)?d:[d];for(var f,g,h=[],i="tmpVedio",j=0,k=d.length;j<k;j++)g=d[j],f="upload"==e?"edui-upload-video video-js vjs-default-skin":"edui-faked-video",h.push(a(g.url,g.width||420,g.height||280,i+j,null,f,"image"));c.execCommand("inserthtml",h.join(""),!0);for(var l=this.selection.getRange(),j=0,k=d.length;j<k;j++){var m=this.document.getElementById("tmpVedio"+j);domUtils.removeAttributes(m,"id"),l.selectNode(m).select(),c.execCommand("imagefloat",d[j].align)}},queryCommandState:function(){var a=c.selection.getRange().getClosedNode(),b=a&&("edui-faked-video"==a.className||a.className.indexOf("edui-upload-video")!=-1);return b?1:0}}},function(){function a(a){}var b=UE.UETable=function(a){this.table=a,this.indexTable=[],this.selectedTds=[],this.cellsRange={},this.update(a)};b.removeSelectedClass=function(a){utils.each(a,function(a){domUtils.removeClasses(a,"selectTdClass")})},b.addSelectedClass=function(a){utils.each(a,function(a){domUtils.addClass(a,"selectTdClass")})},b.isEmptyBlock=function(a){var b=new RegExp(domUtils.fillChar,"g");if(a[browser.ie?"innerText":"textContent"].replace(/^\s*$/,"").replace(b,"").length>0)return 0;for(var c in dtd.$isNotEmpty)if(dtd.$isNotEmpty.hasOwnProperty(c)&&a.getElementsByTagName(c).length)return 0;return 1},b.getWidth=function(a){return a?parseInt(domUtils.getComputedStyle(a,"width"),10):0},b.getTableCellAlignState=function(a){!utils.isArray(a)&&(a=[a]);var b={},c=["align","valign"],d=null,e=!0;return utils.each(a,function(a){return utils.each(c,function(c){if(d=a.getAttribute(c),!b[c]&&d)b[c]=d;else if(!b[c]||d!==b[c])return e=!1,!1}),e}),e?b:null},b.getTableItemsByRange=function(a){var b=a.selection.getStart();b&&b.id&&0===b.id.indexOf("_baidu_bookmark_start_")&&b.nextSibling&&(b=b.nextSibling);var c=b&&domUtils.findParentByTagName(b,["td","th"],!0),d=c&&c.parentNode,e=b&&domUtils.findParentByTagName(b,"caption",!0),f=e?e.parentNode:d&&d.parentNode.parentNode;return{cell:c,tr:d,table:f,caption:e}},b.getUETableBySelected=function(a){var c=b.getTableItemsByRange(a).table;return c&&c.ueTable&&c.ueTable.selectedTds.length?c.ueTable:null},b.getDefaultValue=function(a,b){var c,d,e,f,g={thin:"0px",medium:"1px",thick:"2px"};if(b)return h=b.getElementsByTagName("td")[0],f=domUtils.getComputedStyle(b,"border-left-width"),c=parseInt(g[f]||f,10),f=domUtils.getComputedStyle(h,"padding-left"),d=parseInt(g[f]||f,10),f=domUtils.getComputedStyle(h,"border-left-width"),e=parseInt(g[f]||f,10),{tableBorder:c,tdPadding:d,tdBorder:e};b=a.document.createElement("table"),b.insertRow(0).insertCell(0).innerHTML="xxx",a.body.appendChild(b);var h=b.getElementsByTagName("td")[0];return f=domUtils.getComputedStyle(b,"border-left-width"),c=parseInt(g[f]||f,10),f=domUtils.getComputedStyle(h,"padding-left"),d=parseInt(g[f]||f,10),f=domUtils.getComputedStyle(h,"border-left-width"),e=parseInt(g[f]||f,10),domUtils.remove(b),{tableBorder:c,tdPadding:d,tdBorder:e}},b.getUETable=function(a){var c=a.tagName.toLowerCase();return a="td"==c||"th"==c||"caption"==c?domUtils.findParentByTagName(a,"table",!0):a,a.ueTable||(a.ueTable=new b(a)),a.ueTable},b.cloneCell=function(a,b,c){if(!a||utils.isString(a))return this.table.ownerDocument.createElement(a||"td");var d=domUtils.hasClass(a,"selectTdClass");d&&domUtils.removeClasses(a,"selectTdClass");var e=a.cloneNode(!0);return b&&(e.rowSpan=e.colSpan=1),!c&&domUtils.removeAttributes(e,"width height"),!c&&domUtils.removeAttributes(e,"style"),e.style.borderLeftStyle="",e.style.borderTopStyle="",e.style.borderLeftColor=a.style.borderRightColor,e.style.borderLeftWidth=a.style.borderRightWidth,e.style.borderTopColor=a.style.borderBottomColor,e.style.borderTopWidth=a.style.borderBottomWidth,d&&domUtils.addClass(a,"selectTdClass"),e},b.prototype={getMaxRows:function(){for(var a,b=this.table.rows,c=1,d=0;a=b[d];d++){for(var e,f=1,g=0;e=a.cells[g++];)f=Math.max(e.rowSpan||1,f);c=Math.max(f+d,c)}return c},getMaxCols:function(){for(var a,b=this.table.rows,c=0,d={},e=0;a=b[e];e++){for(var f,g=0,h=0;f=a.cells[h++];)if(g+=f.colSpan||1,f.rowSpan&&f.rowSpan>1)for(var i=1;i<f.rowSpan;i++)d["row_"+(e+i)]?d["row_"+(e+i)]++:d["row_"+(e+i)]=f.colSpan||1;g+=d["row_"+e]||0,c=Math.max(g,c)}return c},getCellColIndex:function(a){},getHSideCell:function(b,c){try{var d,e,f=this.getCellInfo(b),g=this.selectedTds.length,h=this.cellsRange;return!c&&(g?!h.beginColIndex:!f.colIndex)||c&&(g?h.endColIndex==this.colsNum-1:f.colIndex==this.colsNum-1)?null:(d=g?h.beginRowIndex:f.rowIndex,e=c?g?h.endColIndex+1:f.colIndex+1:g?h.beginColIndex-1:f.colIndex<1?0:f.colIndex-1,this.getCell(this.indexTable[d][e].rowIndex,this.indexTable[d][e].cellIndex))}catch(i){a(i)}},getTabNextCell:function(a,b){var c,d=this.getCellInfo(a),e=b||d.rowIndex,f=d.colIndex+1+(d.colSpan-1);try{c=this.getCell(this.indexTable[e][f].rowIndex,this.indexTable[e][f].cellIndex)}catch(g){try{e=1*e+1,f=0,c=this.getCell(this.indexTable[e][f].rowIndex,this.indexTable[e][f].cellIndex)}catch(g){}}return c},getVSideCell:function(b,c,d){try{var e,f,g=this.getCellInfo(b),h=this.selectedTds.length&&!d,i=this.cellsRange;return!c&&0==g.rowIndex||c&&(h?i.endRowIndex==this.rowsNum-1:g.rowIndex+g.rowSpan>this.rowsNum-1)?null:(e=c?h?i.endRowIndex+1:g.rowIndex+g.rowSpan:h?i.beginRowIndex-1:g.rowIndex-1,f=h?i.beginColIndex:g.colIndex,this.getCell(this.indexTable[e][f].rowIndex,this.indexTable[e][f].cellIndex))}catch(j){a(j)}},getSameEndPosCells:function(b,c){try{for(var d="x"===c.toLowerCase(),e=domUtils.getXY(b)[d?"x":"y"]+b["offset"+(d?"Width":"Height")],f=this.table.rows,g=null,h=[],i=0;i<this.rowsNum;i++){g=f[i].cells;for(var j,k=0;j=g[k++];){var l=domUtils.getXY(j)[d?"x":"y"]+j["offset"+(d?"Width":"Height")];if(l>e&&d)break;if((b==j||e==l)&&(1==j[d?"colSpan":"rowSpan"]&&h.push(j),d))break}}return h}catch(m){a(m)}},setCellContent:function(a,b){a.innerHTML=b||(browser.ie?domUtils.fillChar:"<br />")},cloneCell:b.cloneCell,getSameStartPosXCells:function(b){try{for(var c,d=domUtils.getXY(b).x+b.offsetWidth,e=this.table.rows,f=[],g=0;g<this.rowsNum;g++){c=e[g].cells;for(var h,i=0;h=c[i++];){var j=domUtils.getXY(h).x;if(j>d)break;if(j==d&&1==h.colSpan){f.push(h);break}}}return f}catch(k){a(k)}},update:function(a){this.table=a||this.table,this.selectedTds=[],this.cellsRange={},this.indexTable=[];for(var b=this.table.rows,c=this.getMaxRows(),d=c-b.length,e=this.getMaxCols();d--;)this.table.insertRow(b.length);this.rowsNum=c,this.colsNum=e;for(var f=0,g=b.length;f<g;f++)this.indexTable[f]=new Array(e);for(var h,i=0;h=b[i];i++)for(var j,k=0,l=h.cells;j=l[k];k++){j.rowSpan>c&&(j.rowSpan=c);for(var m=k,n=j.rowSpan||1,o=j.colSpan||1;this.indexTable[i][m];)m++;for(var p=0;p<n;p++)for(var q=0;q<o;q++)this.indexTable[i+p][m+q]={rowIndex:i,cellIndex:k,colIndex:m,rowSpan:n,colSpan:o}}for(p=0;p<c;p++)for(q=0;q<e;q++)void 0===this.indexTable[p][q]&&(h=b[p],j=h.cells[h.cells.length-1],j=j?j.cloneNode(!0):this.table.ownerDocument.createElement("td"),this.setCellContent(j),1!==j.colSpan&&(j.colSpan=1),1!==j.rowSpan&&(j.rowSpan=1),h.appendChild(j),this.indexTable[p][q]={rowIndex:p,cellIndex:j.cellIndex,colIndex:q,rowSpan:1,colSpan:1});var r=domUtils.getElementsByTagName(this.table,"td"),s=[];if(utils.each(r,function(a){domUtils.hasClass(a,"selectTdClass")&&s.push(a)}),s.length){var t=s[0],u=s[s.length-1],v=this.getCellInfo(t),w=this.getCellInfo(u);this.selectedTds=s,this.cellsRange={beginRowIndex:v.rowIndex,beginColIndex:v.colIndex,endRowIndex:w.rowIndex+w.rowSpan-1,endColIndex:w.colIndex+w.colSpan-1}}if(!domUtils.hasClass(this.table.rows[0],"firstRow")){domUtils.addClass(this.table.rows[0],"firstRow");for(var f=1;f<this.table.rows.length;f++)domUtils.removeClasses(this.table.rows[f],"firstRow")}},getCellInfo:function(a){if(a)for(var b=a.cellIndex,c=a.parentNode.rowIndex,d=this.indexTable[c],e=this.colsNum,f=b;f<e;f++){var g=d[f];if(g.rowIndex===c&&g.cellIndex===b)return g}},getCell:function(a,b){return a<this.rowsNum&&this.table.rows[a].cells[b]||null},deleteCell:function(a,b){b="number"==typeof b?b:a.parentNode.rowIndex;var c=this.table.rows[b];c.deleteCell(a.cellIndex)},getCellsRange:function(a,b){function c(a,b,e,f){var g,h,i,j=a,k=b,l=e,m=f;if(a>0)for(h=b;h<f;h++)g=d.indexTable[a][h],i=g.rowIndex,i<a&&(j=Math.min(i,j));if(f<d.colsNum)for(i=a;i<e;i++)g=d.indexTable[i][f],h=g.colIndex+g.colSpan-1,h>f&&(m=Math.max(h,m));if(e<d.rowsNum)for(h=b;h<f;h++)g=d.indexTable[e][h],i=g.rowIndex+g.rowSpan-1,i>e&&(l=Math.max(i,l));if(b>0)for(i=a;i<e;i++)g=d.indexTable[i][b],h=g.colIndex,h<b&&(k=Math.min(g.colIndex,k));return j!=a||k!=b||l!=e||m!=f?c(j,k,l,m):{beginRowIndex:a,beginColIndex:b,endRowIndex:e,endColIndex:f}}try{var d=this,e=d.getCellInfo(a);if(a===b)return{beginRowIndex:e.rowIndex,beginColIndex:e.colIndex,endRowIndex:e.rowIndex+e.rowSpan-1,endColIndex:e.colIndex+e.colSpan-1};var f=d.getCellInfo(b),g=Math.min(e.rowIndex,f.rowIndex),h=Math.min(e.colIndex,f.colIndex),i=Math.max(e.rowIndex+e.rowSpan-1,f.rowIndex+f.rowSpan-1),j=Math.max(e.colIndex+e.colSpan-1,f.colIndex+f.colSpan-1);return c(g,h,i,j)}catch(k){}},getCells:function(a){this.clearSelected();for(var b,c,d,e=a.beginRowIndex,f=a.beginColIndex,g=a.endRowIndex,h=a.endColIndex,i={},j=[],k=e;k<=g;k++)for(var l=f;l<=h;l++){b=this.indexTable[k][l],c=b.rowIndex,d=b.colIndex;var m=c+"|"+d;if(!i[m]){if(i[m]=1,c<k||d<l||c+b.rowSpan-1>g||d+b.colSpan-1>h)return null;j.push(this.getCell(c,b.cellIndex))}}return j},clearSelected:function(){b.removeSelectedClass(this.selectedTds),this.selectedTds=[],this.cellsRange={}},setSelected:function(a){var c=this.getCells(a);b.addSelectedClass(c),this.selectedTds=c,this.cellsRange=a},isFullRow:function(){var a=this.cellsRange;return a.endColIndex-a.beginColIndex+1==this.colsNum},isFullCol:function(){var a=this.cellsRange,b=this.table,c=b.getElementsByTagName("th"),d=a.endRowIndex-a.beginRowIndex+1;return c.length?d==this.rowsNum||d==this.rowsNum-1:d==this.rowsNum},getNextCell:function(b,c,d){try{var e,f,g=this.getCellInfo(b),h=this.selectedTds.length&&!d,i=this.cellsRange;return!c&&0==g.rowIndex||c&&(h?i.endRowIndex==this.rowsNum-1:g.rowIndex+g.rowSpan>this.rowsNum-1)?null:(e=c?h?i.endRowIndex+1:g.rowIndex+g.rowSpan:h?i.beginRowIndex-1:g.rowIndex-1,f=h?i.beginColIndex:g.colIndex,this.getCell(this.indexTable[e][f].rowIndex,this.indexTable[e][f].cellIndex))}catch(j){a(j)}},getPreviewCell:function(b,c){try{var d,e,f=this.getCellInfo(b),g=this.selectedTds.length,h=this.cellsRange;return!c&&(g?!h.beginColIndex:!f.colIndex)||c&&(g?h.endColIndex==this.colsNum-1:f.rowIndex>this.colsNum-1)?null:(d=c?g?h.beginRowIndex:f.rowIndex<1?0:f.rowIndex-1:g?h.beginRowIndex:f.rowIndex,e=c?g?h.endColIndex+1:f.colIndex:g?h.beginColIndex-1:f.colIndex<1?0:f.colIndex-1,this.getCell(this.indexTable[d][e].rowIndex,this.indexTable[d][e].cellIndex))}catch(i){a(i)}},moveContent:function(a,c){if(!b.isEmptyBlock(c)){if(b.isEmptyBlock(a))return void(a.innerHTML=c.innerHTML);var d=a.lastChild;for(3!=d.nodeType&&dtd.$block[d.tagName]||a.appendChild(a.ownerDocument.createElement("br"));d=c.firstChild;)a.appendChild(d)}},mergeRight:function(a){var b=this.getCellInfo(a),c=b.colIndex+b.colSpan,d=this.indexTable[b.rowIndex][c],e=this.getCell(d.rowIndex,d.cellIndex);a.colSpan=b.colSpan+d.colSpan,a.removeAttribute("width"),this.moveContent(a,e),this.deleteCell(e,d.rowIndex),this.update()},mergeDown:function(a){var b=this.getCellInfo(a),c=b.rowIndex+b.rowSpan,d=this.indexTable[c][b.colIndex],e=this.getCell(d.rowIndex,d.cellIndex);a.rowSpan=b.rowSpan+d.rowSpan,a.removeAttribute("height"),this.moveContent(a,e),this.deleteCell(e,d.rowIndex),this.update()},mergeRange:function(){var a=this.cellsRange,b=this.getCell(a.beginRowIndex,this.indexTable[a.beginRowIndex][a.beginColIndex].cellIndex);if("TH"==b.tagName&&a.endRowIndex!==a.beginRowIndex){var c=this.indexTable,d=this.getCellInfo(b);b=this.getCell(1,c[1][d.colIndex].cellIndex),a=this.getCellsRange(b,this.getCell(c[this.rowsNum-1][d.colIndex].rowIndex,c[this.rowsNum-1][d.colIndex].cellIndex))}for(var e,f=this.getCells(a),g=0;e=f[g++];)e!==b&&(this.moveContent(b,e),this.deleteCell(e));if(b.rowSpan=a.endRowIndex-a.beginRowIndex+1,b.rowSpan>1&&b.removeAttribute("height"),b.colSpan=a.endColIndex-a.beginColIndex+1,b.colSpan>1&&b.removeAttribute("width"),b.rowSpan==this.rowsNum&&1!=b.colSpan&&(b.colSpan=1),b.colSpan==this.colsNum&&1!=b.rowSpan){var h=b.parentNode.rowIndex;if(this.table.deleteRow)for(var g=h+1,i=h+1,j=b.rowSpan;g<j;g++)this.table.deleteRow(i);else for(var g=0,j=b.rowSpan-1;g<j;g++){var k=this.table.rows[h+1];k.parentNode.removeChild(k)}b.rowSpan=1}this.update()},insertRow:function(a,b){function c(a,b,c){if(0==a){var d=c.nextSibling||c.previousSibling,e=d.cells[a];"TH"==e.tagName&&(e=b.ownerDocument.createElement("th"),e.appendChild(b.firstChild),c.insertBefore(e,b),domUtils.remove(b))}else if("TH"==b.tagName){var f=b.ownerDocument.createElement("td");f.appendChild(b.firstChild),c.insertBefore(f,b),domUtils.remove(b)}}var d,e=this.colsNum,f=this.table,g=f.insertRow(a),h="string"==typeof b&&"TH"==b.toUpperCase();if(0==a||a==this.rowsNum)for(var i=0;i<e;i++)d=this.cloneCell(b,!0),this.setCellContent(d),d.getAttribute("vAlign")&&d.setAttribute("vAlign",d.getAttribute("vAlign")),g.appendChild(d),h||c(i,d,g);else{var j=this.indexTable[a];for(i=0;i<e;i++){var k=j[i];k.rowIndex<a?(d=this.getCell(k.rowIndex,k.cellIndex),d.rowSpan=k.rowSpan+1):(d=this.cloneCell(b,!0),this.setCellContent(d),g.appendChild(d)),h||c(i,d,g)}}return this.update(),g},deleteRow:function(a){for(var b=this.table.rows[a],c=this.indexTable[a],d=this.colsNum,e=0,f=0;f<d;){var g=c[f],h=this.getCell(g.rowIndex,g.cellIndex);if(h.rowSpan>1&&g.rowIndex==a){var i=h.cloneNode(!0);i.rowSpan=h.rowSpan-1,i.innerHTML="",h.rowSpan=1;var j,k=a+1,l=this.table.rows[k],m=this.getPreviewMergedCellsNum(k,f)-e;m<f?(j=f-m-1,domUtils.insertAfter(l.cells[j],i)):l.cells.length&&l.insertBefore(i,l.cells[0]),e+=1}f+=h.colSpan||1}var n=[],o={};for(f=0;f<d;f++){var p=c[f].rowIndex,q=c[f].cellIndex,r=p+"_"+q;o[r]||(o[r]=1,h=this.getCell(p,q),n.push(h))}var s=[];utils.each(n,function(a){1==a.rowSpan?a.parentNode.removeChild(a):s.push(a)}),utils.each(s,function(a){a.rowSpan--}),b.parentNode.removeChild(b),this.update()},insertCol:function(a,b,c){function d(a,b,c){if(0==a){var d=b.nextSibling||b.previousSibling;"TH"==d.tagName&&(d=b.ownerDocument.createElement("th"),d.appendChild(b.firstChild),c.insertBefore(d,b),domUtils.remove(b))}else if("TH"==b.tagName){var e=b.ownerDocument.createElement("td");e.appendChild(b.firstChild),c.insertBefore(e,b),domUtils.remove(b)}}var e,f,g,h=this.rowsNum,i=0,j=parseInt((this.table.offsetWidth-20*(this.colsNum+1)-(this.colsNum+1))/(this.colsNum+1),10),k="string"==typeof b&&"TH"==b.toUpperCase();if(0==a||a==this.colsNum)for(;i<h;i++)e=this.table.rows[i],g=e.cells[0==a?a:e.cells.length],f=this.cloneCell(b,!0),this.setCellContent(f),f.setAttribute("vAlign",f.getAttribute("vAlign")),g&&f.setAttribute("width",g.getAttribute("width")),a?domUtils.insertAfter(e.cells[e.cells.length-1],f):e.insertBefore(f,e.cells[0]),k||d(i,f,e);else for(;i<h;i++){var l=this.indexTable[i][a];l.colIndex<a?(f=this.getCell(l.rowIndex,l.cellIndex),f.colSpan=l.colSpan+1):(e=this.table.rows[i],g=e.cells[l.cellIndex],f=this.cloneCell(b,!0),this.setCellContent(f),f.setAttribute("vAlign",f.getAttribute("vAlign")),g&&f.setAttribute("width",g.getAttribute("width")),g?e.insertBefore(f,g):e.appendChild(f)),k||d(i,f,e)}this.update(),this.updateWidth(j,c||{tdPadding:10,tdBorder:1})},updateWidth:function(a,c){var d=this.table,e=b.getWidth(d)-2*c.tdPadding-c.tdBorder+a;if(e<d.ownerDocument.body.offsetWidth)return void d.setAttribute("width",e);var f=domUtils.getElementsByTagName(this.table,"td th");utils.each(f,function(b){b.setAttribute("width",a)})},deleteCol:function(a){for(var b=this.indexTable,c=this.table.rows,d=this.table.getAttribute("width"),e=0,f=this.rowsNum,g={},h=0;h<f;){var i=b[h],j=i[a],k=j.rowIndex+"_"+j.colIndex;if(!g[k]){g[k]=1;var l=this.getCell(j.rowIndex,j.cellIndex);e||(e=l&&parseInt(l.offsetWidth/l.colSpan,10).toFixed(0)),l.colSpan>1?l.colSpan--:c[h].deleteCell(j.cellIndex),h+=j.rowSpan||1}}this.table.setAttribute("width",d-e),this.update()},splitToCells:function(a){var b=this,c=this.splitToRows(a);utils.each(c,function(a){b.splitToCols(a)})},splitToRows:function(a){var b=this.getCellInfo(a),c=b.rowIndex,d=b.colIndex,e=[];a.rowSpan=1,e.push(a);for(var f=c,g=c+b.rowSpan;f<g;f++)if(f!=c){var h=this.table.rows[f],i=h.insertCell(d-this.getPreviewMergedCellsNum(f,d));i.colSpan=b.colSpan,this.setCellContent(i),i.setAttribute("vAlign",a.getAttribute("vAlign")),i.setAttribute("align",a.getAttribute("align")),a.style.cssText&&(i.style.cssText=a.style.cssText),e.push(i)}return this.update(),e},getPreviewMergedCellsNum:function(a,b){for(var c=this.indexTable[a],d=0,e=0;e<b;){var f=c[e].colSpan,g=c[e].rowIndex;d+=f-(g==a?1:0),e+=f}return d},splitToCols:function(a){var b=(a.offsetWidth/a.colSpan-22).toFixed(0),c=this.getCellInfo(a),d=c.rowIndex,e=c.colIndex,f=[];a.colSpan=1,a.setAttribute("width",b),f.push(a);for(var g=e,h=e+c.colSpan;g<h;g++)if(g!=e){var i=this.table.rows[d],j=i.insertCell(this.indexTable[d][g].cellIndex+1);if(j.rowSpan=c.rowSpan,this.setCellContent(j),j.setAttribute("vAlign",a.getAttribute("vAlign")),j.setAttribute("align",a.getAttribute("align")),j.setAttribute("width",b),a.style.cssText&&(j.style.cssText=a.style.cssText),"TH"==a.tagName){var k=a.ownerDocument.createElement("th");k.appendChild(j.firstChild),k.setAttribute("vAlign",a.getAttribute("vAlign")),k.rowSpan=j.rowSpan,i.insertBefore(k,j),domUtils.remove(j)}f.push(j)}return this.update(),f},isLastCell:function(a,b,c){b=b||this.rowsNum,c=c||this.colsNum;var d=this.getCellInfo(a);return d.rowIndex+d.rowSpan==b&&d.colIndex+d.colSpan==c},getLastCell:function(a){a=a||this.table.getElementsByTagName("td");var b,c=(this.getCellInfo(a[0]),this),d=a[0],e=d.parentNode,f=0,g=0;return utils.each(a,function(a){a.parentNode==e&&(g+=a.colSpan||1),f+=a.rowSpan*a.colSpan||1}),b=f/g,utils.each(a,function(a){if(c.isLastCell(a,b,g))return d=a,!1}),d},selectRow:function(a){var b=this.indexTable[a],c=this.getCell(b[0].rowIndex,b[0].cellIndex),d=this.getCell(b[this.colsNum-1].rowIndex,b[this.colsNum-1].cellIndex),e=this.getCellsRange(c,d);this.setSelected(e)},selectTable:function(){var a=this.table.getElementsByTagName("td"),b=this.getCellsRange(a[0],a[a.length-1]);this.setSelected(b)},setBackground:function(a,b){if("string"==typeof b)utils.each(a,function(a){a.style.backgroundColor=b});else if("object"==typeof b){b=utils.extend({repeat:!0,colorList:["#ddd","#fff"]},b);for(var c,d=this.getCellInfo(a[0]).rowIndex,e=0,f=b.colorList,g=function(a,b,c){return a[b]?a[b]:c?a[b%a.length]:""},h=0;c=a[h++];){var i=this.getCellInfo(c);c.style.backgroundColor=g(f,d+e==i.rowIndex?e:++e,b.repeat)}}},removeBackground:function(a){utils.each(a,function(a){a.style.backgroundColor=""})}}}(),function(){function a(a,c){var d=domUtils.getElementsByTagName(a,"td th");utils.each(d,function(a){a.removeAttribute("width")}),a.setAttribute("width",b(c,!0,g(c,a)));var e=[];setTimeout(function(){utils.each(d,function(a){1==a.colSpan&&e.push(a.offsetWidth)}),utils.each(d,function(a,b){1==a.colSpan&&a.setAttribute("width",e[b]+"")})},0)}function b(a,b,c){var d=a.body;return d.offsetWidth-(b?2*parseInt(domUtils.getComputedStyle(d,"margin-left"),10):0)-2*c.tableBorder-(a.options.offsetWidth||0)}function c(a){var b=e(a).cell;if(b){var c=h(b);return c.selectedTds.length?c.selectedTds:[b]}return[]}var d=UE.UETable,e=function(a){return d.getTableItemsByRange(a)},f=function(a){return d.getUETableBySelected(a)},g=function(a,b){return d.getDefaultValue(a,b)},h=function(a){return d.getUETable(a)};UE.commands.inserttable={queryCommandState:function(){return e(this).table?-1:0},execCommand:function(a,b){function c(a,b){for(var c=[],d=a.numRows,e=a.numCols,f=0;f<d;f++){c.push("<tr"+(0==f?' class="firstRow"':"")+">");for(var g=0;g<e;g++)c.push('<td width="'+b+'" vAlign="'+a.tdvalign+'" >'+(browser.ie&&browser.version<11?domUtils.fillChar:"<br/>")+"</td>");c.push("</tr>")}return"<table><tbody>"+c.join("")+"</tbody></table>"}b||(b=utils.extend({},{numCols:this.options.defaultCols,numRows:this.options.defaultRows,tdvalign:this.options.tdvalign}));var d=this,e=this.selection.getRange(),f=e.startContainer,h=domUtils.findParent(f,function(a){return domUtils.isBlockElm(a)},!0)||d.body,i=g(d),j=h.offsetWidth,k=Math.floor(j/b.numCols-2*i.tdPadding-i.tdBorder);!b.tdvalign&&(b.tdvalign=d.options.tdvalign),d.execCommand("inserthtml",c(b,k))}},UE.commands.insertparagraphbeforetable={queryCommandState:function(){return e(this).cell?0:-1},execCommand:function(){var a=e(this).table;if(a){var b=this.document.createElement("p");b.innerHTML=browser.ie?" ":"<br />",a.parentNode.insertBefore(b,a),this.selection.getRange().setStart(b,0).setCursor()}}},UE.commands.deletetable={queryCommandState:function(){var a=this.selection.getRange();return domUtils.findParentByTagName(a.startContainer,"table",!0)?0:-1},execCommand:function(a,b){var c=this.selection.getRange();if(b=b||domUtils.findParentByTagName(c.startContainer,"table",!0)){var d=b.nextSibling;d||(d=domUtils.createElement(this.document,"p",{innerHTML:browser.ie?domUtils.fillChar:"<br/>"}),b.parentNode.insertBefore(d,b)),domUtils.remove(b),c=this.selection.getRange(),3==d.nodeType?c.setStartBefore(d):c.setStart(d,0),c.setCursor(!1,!0),this.fireEvent("tablehasdeleted")}}},UE.commands.cellalign={queryCommandState:function(){return c(this).length?0:-1},execCommand:function(a,b){var d=c(this);if(d.length)for(var e,f=0;e=d[f++];)e.setAttribute("align",b)}},UE.commands.cellvalign={queryCommandState:function(){return c(this).length?0:-1},execCommand:function(a,b){var d=c(this);if(d.length)for(var e,f=0;e=d[f++];)e.setAttribute("vAlign",b)}},UE.commands.insertcaption={queryCommandState:function(){var a=e(this).table;return a&&0==a.getElementsByTagName("caption").length?1:-1},execCommand:function(){var a=e(this).table;if(a){var b=this.document.createElement("caption");b.innerHTML=browser.ie?domUtils.fillChar:"<br/>",a.insertBefore(b,a.firstChild);var c=this.selection.getRange();c.setStart(b,0).setCursor()}}},UE.commands.deletecaption={queryCommandState:function(){var a=this.selection.getRange(),b=domUtils.findParentByTagName(a.startContainer,"table");return b?0==b.getElementsByTagName("caption").length?-1:1:-1},execCommand:function(){var a=this.selection.getRange(),b=domUtils.findParentByTagName(a.startContainer,"table");if(b){domUtils.remove(b.getElementsByTagName("caption")[0]);var c=this.selection.getRange();c.setStart(b.rows[0].cells[0],0).setCursor()}}},UE.commands.inserttitle={queryCommandState:function(){var a=e(this).table;if(a){var b=a.rows[0];return"th"!=b.cells[b.cells.length-1].tagName.toLowerCase()?0:-1}return-1},execCommand:function(){var a=e(this).table;a&&h(a).insertRow(0,"th");var b=a.getElementsByTagName("th")[0];this.selection.getRange().setStart(b,0).setCursor(!1,!0)}},UE.commands.deletetitle={queryCommandState:function(){var a=e(this).table;if(a){var b=a.rows[0];return"th"==b.cells[b.cells.length-1].tagName.toLowerCase()?0:-1}return-1},execCommand:function(){var a=e(this).table;a&&domUtils.remove(a.rows[0]);var b=a.getElementsByTagName("td")[0];this.selection.getRange().setStart(b,0).setCursor(!1,!0)}},UE.commands.inserttitlecol={queryCommandState:function(){var a=e(this).table;if(a){var b=a.rows[a.rows.length-1];return b.getElementsByTagName("th").length?-1:0}return-1},execCommand:function(b){var c=e(this).table;c&&h(c).insertCol(0,"th"),a(c,this);var d=c.getElementsByTagName("th")[0];this.selection.getRange().setStart(d,0).setCursor(!1,!0)}},UE.commands.deletetitlecol={queryCommandState:function(){var a=e(this).table;if(a){var b=a.rows[a.rows.length-1];return b.getElementsByTagName("th").length?0:-1}return-1},execCommand:function(){var b=e(this).table;if(b)for(var c=0;c<b.rows.length;c++)domUtils.remove(b.rows[c].children[0]);a(b,this);var d=b.getElementsByTagName("td")[0];this.selection.getRange().setStart(d,0).setCursor(!1,!0)}},UE.commands.mergeright={queryCommandState:function(a){var b=e(this),c=b.table,d=b.cell;if(!c||!d)return-1;var f=h(c);if(f.selectedTds.length)return-1;var g=f.getCellInfo(d),i=g.colIndex+g.colSpan;if(i>=f.colsNum)return-1;var j=f.indexTable[g.rowIndex][i],k=c.rows[j.rowIndex].cells[j.cellIndex];return k&&d.tagName==k.tagName&&j.rowIndex==g.rowIndex&&j.rowSpan==g.rowSpan?0:-1},execCommand:function(a){var b=this.selection.getRange(),c=b.createBookmark(!0),d=e(this).cell,f=h(d);f.mergeRight(d),b.moveToBookmark(c).select()}},UE.commands.mergedown={queryCommandState:function(a){var b=e(this),c=b.table,d=b.cell;if(!c||!d)return-1;var f=h(c);if(f.selectedTds.length)return-1;var g=f.getCellInfo(d),i=g.rowIndex+g.rowSpan;if(i>=f.rowsNum)return-1;var j=f.indexTable[i][g.colIndex],k=c.rows[j.rowIndex].cells[j.cellIndex];return k&&d.tagName==k.tagName&&j.colIndex==g.colIndex&&j.colSpan==g.colSpan?0:-1},execCommand:function(){var a=this.selection.getRange(),b=a.createBookmark(!0),c=e(this).cell,d=h(c);d.mergeDown(c),a.moveToBookmark(b).select()}},UE.commands.mergecells={queryCommandState:function(){return f(this)?0:-1},execCommand:function(){var a=f(this);if(a&&a.selectedTds.length){var b=a.selectedTds[0];a.mergeRange();var c=this.selection.getRange();domUtils.isEmptyBlock(b)?c.setStart(b,0).collapse(!0):c.selectNodeContents(b),c.select()}}},UE.commands.insertrow={queryCommandState:function(){var a=e(this),b=a.cell;return b&&("TD"==b.tagName||"TH"==b.tagName&&a.tr!==a.table.rows[0])&&h(a.table).rowsNum<this.options.maxRowNum?0:-1},execCommand:function(){var a=this.selection.getRange(),b=a.createBookmark(!0),c=e(this),d=c.cell,f=c.table,g=h(f),i=g.getCellInfo(d);if(g.selectedTds.length)for(var j=g.cellsRange,k=0,l=j.endRowIndex-j.beginRowIndex+1;k<l;k++)g.insertRow(j.beginRowIndex,d);else g.insertRow(i.rowIndex,d);a.moveToBookmark(b).select(),"enabled"===f.getAttribute("interlaced")&&this.fireEvent("interlacetable",f)}},UE.commands.insertrownext={queryCommandState:function(){var a=e(this),b=a.cell;return b&&"TD"==b.tagName&&h(a.table).rowsNum<this.options.maxRowNum?0:-1},execCommand:function(){var a=this.selection.getRange(),b=a.createBookmark(!0),c=e(this),d=c.cell,f=c.table,g=h(f),i=g.getCellInfo(d);if(g.selectedTds.length)for(var j=g.cellsRange,k=0,l=j.endRowIndex-j.beginRowIndex+1;k<l;k++)g.insertRow(j.endRowIndex+1,d);else g.insertRow(i.rowIndex+i.rowSpan,d);a.moveToBookmark(b).select(),"enabled"===f.getAttribute("interlaced")&&this.fireEvent("interlacetable",f)}},UE.commands.deleterow={queryCommandState:function(){var a=e(this);return a.cell?0:-1},execCommand:function(){var a=e(this).cell,b=h(a),c=b.cellsRange,d=b.getCellInfo(a),f=b.getVSideCell(a),g=b.getVSideCell(a,!0),i=this.selection.getRange();if(utils.isEmptyObject(c))b.deleteRow(d.rowIndex);else for(var j=c.beginRowIndex;j<c.endRowIndex+1;j++)b.deleteRow(c.beginRowIndex);var k=b.table;if(k.getElementsByTagName("td").length)if(1==d.rowSpan||d.rowSpan==c.endRowIndex-c.beginRowIndex+1)(g||f)&&i.selectNodeContents(g||f).setCursor(!1,!0);else{var l=b.getCell(d.rowIndex,b.indexTable[d.rowIndex][d.colIndex].cellIndex);l&&i.selectNodeContents(l).setCursor(!1,!0)}else{var m=k.nextSibling;domUtils.remove(k),m&&i.setStart(m,0).setCursor(!1,!0)}"enabled"===k.getAttribute("interlaced")&&this.fireEvent("interlacetable",k)}},UE.commands.insertcol={queryCommandState:function(a){var b=e(this),c=b.cell;return c&&("TD"==c.tagName||"TH"==c.tagName&&c!==b.tr.cells[0])&&h(b.table).colsNum<this.options.maxColNum?0:-1},execCommand:function(a){var b=this.selection.getRange(),c=b.createBookmark(!0);if(this.queryCommandState(a)!=-1){var d=e(this).cell,f=h(d),g=f.getCellInfo(d);if(f.selectedTds.length)for(var i=f.cellsRange,j=0,k=i.endColIndex-i.beginColIndex+1;j<k;j++)f.insertCol(i.beginColIndex,d);else f.insertCol(g.colIndex,d);b.moveToBookmark(c).select(!0)}}},UE.commands.insertcolnext={queryCommandState:function(){var a=e(this),b=a.cell;return b&&h(a.table).colsNum<this.options.maxColNum?0:-1},execCommand:function(){var a=this.selection.getRange(),b=a.createBookmark(!0),c=e(this).cell,d=h(c),f=d.getCellInfo(c);
if(d.selectedTds.length)for(var g=d.cellsRange,i=0,j=g.endColIndex-g.beginColIndex+1;i<j;i++)d.insertCol(g.endColIndex+1,c);else d.insertCol(f.colIndex+f.colSpan,c);a.moveToBookmark(b).select()}},UE.commands.deletecol={queryCommandState:function(){var a=e(this);return a.cell?0:-1},execCommand:function(){var a=e(this).cell,b=h(a),c=b.cellsRange,d=b.getCellInfo(a),f=b.getHSideCell(a),g=b.getHSideCell(a,!0);if(utils.isEmptyObject(c))b.deleteCol(d.colIndex);else for(var i=c.beginColIndex;i<c.endColIndex+1;i++)b.deleteCol(c.beginColIndex);var j=b.table,k=this.selection.getRange();if(j.getElementsByTagName("td").length)domUtils.inDoc(a,this.document)?k.setStart(a,0).setCursor(!1,!0):g&&domUtils.inDoc(g,this.document)?k.selectNodeContents(g).setCursor(!1,!0):f&&domUtils.inDoc(f,this.document)&&k.selectNodeContents(f).setCursor(!0,!0);else{var l=j.nextSibling;domUtils.remove(j),l&&k.setStart(l,0).setCursor(!1,!0)}}},UE.commands.splittocells={queryCommandState:function(){var a=e(this),b=a.cell;if(!b)return-1;var c=h(a.table);return c.selectedTds.length>0?-1:b&&(b.colSpan>1||b.rowSpan>1)?0:-1},execCommand:function(){var a=this.selection.getRange(),b=a.createBookmark(!0),c=e(this).cell,d=h(c);d.splitToCells(c),a.moveToBookmark(b).select()}},UE.commands.splittorows={queryCommandState:function(){var a=e(this),b=a.cell;if(!b)return-1;var c=h(a.table);return c.selectedTds.length>0?-1:b&&b.rowSpan>1?0:-1},execCommand:function(){var a=this.selection.getRange(),b=a.createBookmark(!0),c=e(this).cell,d=h(c);d.splitToRows(c),a.moveToBookmark(b).select()}},UE.commands.splittocols={queryCommandState:function(){var a=e(this),b=a.cell;if(!b)return-1;var c=h(a.table);return c.selectedTds.length>0?-1:b&&b.colSpan>1?0:-1},execCommand:function(){var a=this.selection.getRange(),b=a.createBookmark(!0),c=e(this).cell,d=h(c);d.splitToCols(c),a.moveToBookmark(b).select()}},UE.commands.adaptbytext=UE.commands.adaptbywindow={queryCommandState:function(){return e(this).table?0:-1},execCommand:function(b){var c=e(this),d=c.table;if(d)if("adaptbywindow"==b)a(d,this);else{var f=domUtils.getElementsByTagName(d,"td th");utils.each(f,function(a){a.removeAttribute("width")}),d.removeAttribute("width")}}},UE.commands.averagedistributecol={queryCommandState:function(){var a=f(this);return a&&(a.isFullRow()||a.isFullCol())?0:-1},execCommand:function(a){function b(){var a,b=e.table,c=0,f=0,h=g(d,b);if(e.isFullRow())c=b.offsetWidth,f=e.colsNum;else for(var i,j=e.cellsRange.beginColIndex,k=e.cellsRange.endColIndex,l=j;l<=k;)i=e.selectedTds[l],c+=i.offsetWidth,l+=i.colSpan,f+=1;return a=Math.ceil(c/f)-2*h.tdBorder-2*h.tdPadding}function c(a){utils.each(domUtils.getElementsByTagName(e.table,"th"),function(a){a.setAttribute("width","")});var b=e.isFullRow()?domUtils.getElementsByTagName(e.table,"td"):e.selectedTds;utils.each(b,function(b){1==b.colSpan&&b.setAttribute("width",a)})}var d=this,e=f(d);e&&e.selectedTds.length&&c(b())}},UE.commands.averagedistributerow={queryCommandState:function(){var a=f(this);return a?a.selectedTds&&/th/gi.test(a.selectedTds[0].tagName)?-1:a.isFullRow()||a.isFullCol()?0:-1:-1},execCommand:function(a){function b(){var a,b,c=0,f=e.table,h=g(d,f),i=parseInt(domUtils.getComputedStyle(f.getElementsByTagName("td")[0],"padding-top"));if(e.isFullCol()){var j,k,l=domUtils.getElementsByTagName(f,"caption"),m=domUtils.getElementsByTagName(f,"th");l.length>0&&(j=l[0].offsetHeight),m.length>0&&(k=m[0].offsetHeight),c=f.offsetHeight-(j||0)-(k||0),b=0==m.length?e.rowsNum:e.rowsNum-1}else{for(var n=e.cellsRange.beginRowIndex,o=e.cellsRange.endRowIndex,p=0,q=domUtils.getElementsByTagName(f,"tr"),r=n;r<=o;r++)c+=q[r].offsetHeight,p+=1;b=p}return a=browser.ie&&browser.version<9?Math.ceil(c/b):Math.ceil(c/b)-2*h.tdBorder-2*i}function c(a){var b=e.isFullCol()?domUtils.getElementsByTagName(e.table,"td"):e.selectedTds;utils.each(b,function(b){1==b.rowSpan&&b.setAttribute("height",a)})}var d=this,e=f(d);e&&e.selectedTds.length&&c(b())}},UE.commands.cellalignment={queryCommandState:function(){return e(this).table?0:-1},execCommand:function(a,b){var c=this,d=f(c);if(d)utils.each(d.selectedTds,function(a){domUtils.setAttributes(a,b)});else{var e=c.selection.getStart(),g=e&&domUtils.findParentByTagName(e,["td","th","caption"],!0);/caption/gi.test(g.tagName)?(g.style.textAlign=b.align,g.style.verticalAlign=b.vAlign):domUtils.setAttributes(g,b),c.selection.getRange().setCursor(!0)}},queryCommandValue:function(a){var b=e(this).cell;if(b||(b=c(this)[0]),b){var d=UE.UETable.getUETable(b).selectedTds;return!d.length&&(d=b),UE.UETable.getTableCellAlignState(d)}return null}},UE.commands.tablealignment={queryCommandState:function(){return browser.ie&&browser.version<8?-1:e(this).table?0:-1},execCommand:function(a,b){var c=this,d=c.selection.getStart(),e=d&&domUtils.findParentByTagName(d,["table"],!0);e&&e.setAttribute("align",b)}},UE.commands.edittable={queryCommandState:function(){return e(this).table?0:-1},execCommand:function(a,b){var c=this.selection.getRange(),d=domUtils.findParentByTagName(c.startContainer,"table");if(d){var e=domUtils.getElementsByTagName(d,"td").concat(domUtils.getElementsByTagName(d,"th"),domUtils.getElementsByTagName(d,"caption"));utils.each(e,function(a){a.style.borderColor=b})}}},UE.commands.edittd={queryCommandState:function(){return e(this).table?0:-1},execCommand:function(a,b){var c=this,d=f(c);if(d)utils.each(d.selectedTds,function(a){a.style.backgroundColor=b});else{var e=c.selection.getStart(),g=e&&domUtils.findParentByTagName(e,["td","th","caption"],!0);g&&(g.style.backgroundColor=b)}}},UE.commands.settablebackground={queryCommandState:function(){return c(this).length>1?0:-1},execCommand:function(a,b){var d,e;d=c(this),e=h(d[0]),e.setBackground(d,b)}},UE.commands.cleartablebackground={queryCommandState:function(){var a=c(this);if(!a.length)return-1;for(var b,d=0;b=a[d++];)if(""!==b.style.backgroundColor)return 0;return-1},execCommand:function(){var a=c(this),b=h(a[0]);b.removeBackground(a)}},UE.commands.interlacetable=UE.commands.uninterlacetable={queryCommandState:function(a){var b=e(this).table;if(!b)return-1;var c=b.getAttribute("interlaced");return"interlacetable"==a?"enabled"===c?-1:0:c&&"disabled"!==c?0:-1},execCommand:function(a,b){var c=e(this).table;"interlacetable"==a?(c.setAttribute("interlaced","enabled"),this.fireEvent("interlacetable",c,b)):(c.setAttribute("interlaced","disabled"),this.fireEvent("uninterlacetable",c))}},UE.commands.setbordervisible={queryCommandState:function(a){var b=e(this).table;return b?0:-1},execCommand:function(){var a=e(this).table;utils.each(domUtils.getElementsByTagName(a,"td"),function(a){a.style.borderWidth="1px",a.style.borderStyle="solid"})}}}(),UE.plugins.table=function(){function a(a){}function b(a,b){c(a,"width",!0),c(a,"height",!0)}function c(a,b,c){a.style[b]&&(c&&a.setAttribute(b,parseInt(a.style[b],10)),a.style[b]="")}function d(a){if("TD"==a.tagName||"TH"==a.tagName)return a;var b;return(b=domUtils.findParentByTagName(a,"td",!0)||domUtils.findParentByTagName(a,"th",!0))?b:null}function e(a){var b=new RegExp(domUtils.fillChar,"g");if(a[browser.ie?"innerText":"textContent"].replace(/^\s*$/,"").replace(b,"").length>0)return 0;for(var c in dtd.$isNotEmpty)if(a.getElementsByTagName(c).length)return 0;return 1}function f(a){return a.pageX||a.pageY?{x:a.pageX,y:a.pageY}:{x:a.clientX+N.document.body.scrollLeft-N.document.body.clientLeft,y:a.clientY+N.document.body.scrollTop-N.document.body.clientTop}}function g(b){if(!A())try{var c,e=d(b.target||b.srcElement);if(R&&(N.body.style.webkitUserSelect="none",(Math.abs(V.x-b.clientX)>T||Math.abs(V.y-b.clientY)>T)&&(t(),R=!1,U=0,v(b))),ca&&ha)return U=0,N.body.style.webkitUserSelect="none",N.selection.getNative()[browser.ie9below?"empty":"removeAllRanges"](),c=f(b),m(N,!0,ca,c,e),void("h"==ca?ga.style.left=k(ha,b)+"px":"v"==ca&&(ga.style.top=l(ha,b)+"px"));if(e){if(N.fireEvent("excludetable",e)===!0)return;c=f(b);var g=n(e,c),i=domUtils.findParentByTagName(e,"table",!0);if(j(i,e,b,!0)){if(N.fireEvent("excludetable",i)===!0)return;N.body.style.cursor="url("+N.options.cursorpath+"h.png),pointer"}else if(j(i,e,b)){if(N.fireEvent("excludetable",i)===!0)return;N.body.style.cursor="url("+N.options.cursorpath+"v.png),pointer"}else{N.body.style.cursor="text";/\d/.test(g)&&(g=g.replace(/\d/,""),e=Y(e).getPreviewCell(e,"v"==g)),m(N,!!e&&!!g,e?g:"",c,e)}}else h(!1,i,N)}catch(o){a(o)}}function h(a,b,c){if(a)i(b,c);else{if(fa)return;la=setTimeout(function(){!fa&&ea&&ea.parentNode&&ea.parentNode.removeChild(ea)},2e3)}}function i(a,b){function c(c,d){clearTimeout(g),g=setTimeout(function(){b.fireEvent("tableClicked",a,d)},300)}function d(c){clearTimeout(g);var d=Y(a),e=a.rows[0].cells[0],f=d.getLastCell(),h=d.getCellsRange(e,f);b.selection.getRange().setStart(e,0).setCursor(!1,!0),d.setSelected(h)}var e=domUtils.getXY(a),f=a.ownerDocument;if(ea&&ea.parentNode)return ea;ea=f.createElement("div"),ea.contentEditable=!1,ea.innerHTML="",ea.style.cssText="width:15px;height:15px;background-image:url("+b.options.UEDITOR_HOME_URL+"dialogs/table/dragicon.png);position: absolute;cursor:move;top:"+(e.y-15)+"px;left:"+e.x+"px;",domUtils.unSelectable(ea),ea.onmouseover=function(a){fa=!0},ea.onmouseout=function(a){fa=!1},domUtils.on(ea,"click",function(a,b){c(b,this)}),domUtils.on(ea,"dblclick",function(a,b){d(b)}),domUtils.on(ea,"dragstart",function(a,b){domUtils.preventDefault(b)});var g;f.body.appendChild(ea)}function j(a,b,c,d){var e=f(c),g=n(b,e);if(d){var h=a.getElementsByTagName("caption")[0],i=h?h.offsetHeight:0;return"v1"==g&&e.y-domUtils.getXY(a).y-i<8}return"h1"==g&&e.x-domUtils.getXY(a).x<8}function k(a,b){var c=Y(a);if(c){var d=c.getSameEndPosCells(a,"x")[0],e=c.getSameStartPosXCells(a)[0],g=f(b).x,h=(d?domUtils.getXY(d).x:domUtils.getXY(c.table).x)+20,i=e?domUtils.getXY(e).x+e.offsetWidth-20:N.body.offsetWidth+5||parseInt(domUtils.getComputedStyle(N.body,"width"),10);return h+=Q,i-=Q,g<h?h:g>i?i:g}}function l(b,c){try{var d=domUtils.getXY(b).y,e=f(c).y;return e<d?d:e}catch(g){a(g)}}function m(b,c,d,e,f){try{b.body.style.cursor="h"==d?"col-resize":"v"==d?"row-resize":"text",browser.ie&&(!d||ia||Z(b)?I(b):(H(b,b.document),J(d,f))),da=c}catch(g){a(g)}}function n(a,b){var c=domUtils.getXY(a);return c?c.x+a.offsetWidth-b.x<S?"h":b.x-c.x<S?"h1":c.y+a.offsetHeight-b.y<S?"v":b.y-c.y<S?"v1":"":""}function o(a,b){if(!A())if(V={x:b.clientX,y:b.clientY},2==b.button){var c=Z(N),d=!1;if(c){var e=M(N,b);utils.each(c.selectedTds,function(a){a===e&&(d=!0)}),d?(e=c.selectedTds[0],setTimeout(function(){N.selection.getRange().setStart(e,0).setCursor(!1,!0)},0)):(_(domUtils.getElementsByTagName(N.body,"th td")),c.clearSelected())}}else q(b)}function p(a){U=0,a=a||N.window.event;var b=d(a.target||a.srcElement);if(b){var c;if(c=n(b,f(a))){if(I(N),"h1"==c)if(c="h",j(domUtils.findParentByTagName(b,"table"),b,a))N.execCommand("adaptbywindow");else if(b=Y(b).getPreviewCell(b)){var e=N.selection.getRange();e.selectNodeContents(b).setCursor(!0,!0)}if("h"==c){var g=Y(b),h=g.table,i=C(b,h,!0);i=s(i,"left"),g.width=g.offsetWidth;var k=[],l=[];utils.each(i,function(a){k.push(a.offsetWidth)}),utils.each(i,function(a){a.removeAttribute("width")}),window.setTimeout(function(){var a=!0;utils.each(i,function(b,c){var d=b.offsetWidth;return d>k[c]?(a=!1,!1):void l.push(d)});var b=a?l:k;utils.each(i,function(a,c){a.width=b[c]-G()})},0)}}}}function q(a){if(_(domUtils.getElementsByTagName(N.body,"td th")),utils.each(N.document.getElementsByTagName("table"),function(a){a.ueTable=null}),aa=M(N,a)){var b=domUtils.findParentByTagName(aa,"table",!0);ut=Y(b),ut&&ut.clearSelected(),da?r(a):(N.document.body.style.webkitUserSelect="",ia=!0,N.addListener("mouseover",x))}}function r(a){browser.ie&&(a=u(a)),t(),R=!0,O=setTimeout(function(){v(a)},W)}function s(a,b){for(var c=[],d=null,e=0,f=a.length;e<f;e++)d=a[e][b],d&&c.push(d);return c}function t(){O&&clearTimeout(O),O=null}function u(a){var b=["pageX","pageY","clientX","clientY","srcElement","target"],c={};if(a)for(var d,e,f=0;d=b[f];f++)e=a[d],e&&(c[d]=e);return c}function v(a){if(R=!1,aa=a.target||a.srcElement){var b=n(aa,f(a));/\d/.test(b)&&(b=b.replace(/\d/,""),aa=Y(aa).getPreviewCell(aa,"v"==b)),I(N),H(N,N.document),N.fireEvent("saveScene"),J(b,aa),ia=!0,ca=b,ha=aa}}function w(a,b){if(!A()){if(t(),R=!1,da&&(U=++U%3,V={x:b.clientX,y:b.clientY},P=setTimeout(function(){U>0&&U--},W),2===U))return U=0,void p(b);if(2!=b.button){var c=this,d=c.selection.getRange(),e=domUtils.findParentByTagName(d.startContainer,"table",!0),f=domUtils.findParentByTagName(d.endContainer,"table",!0);if((e||f)&&(e===f?(e=domUtils.findParentByTagName(d.startContainer,["td","th","caption"],!0),f=domUtils.findParentByTagName(d.endContainer,["td","th","caption"],!0),e!==f&&c.selection.clearRange()):c.selection.clearRange()),ia=!1,c.document.body.style.webkitUserSelect="",ca&&ha&&(c.selection.getNative()[browser.ie9below?"empty":"removeAllRanges"](),U=0,ga=c.document.getElementById("ue_tableDragLine"))){var g=domUtils.getXY(ha),h=domUtils.getXY(ga);switch(ca){case"h":z(ha,h.x-g.x);break;case"v":B(ha,h.y-g.y-ha.offsetHeight)}return ca="",ha=null,I(c),void c.fireEvent("saveScene")}if(aa){var i=Y(aa),j=i?i.selectedTds[0]:null;if(j)d=new dom.Range(c.document),domUtils.isEmptyBlock(j)?d.setStart(j,0).setCursor(!1,!0):d.selectNodeContents(j).shrinkBoundary().setCursor(!1,!0);else if(d=c.selection.getRange().shrinkBoundary(),!d.collapsed){var e=domUtils.findParentByTagName(d.startContainer,["td","th"],!0),f=domUtils.findParentByTagName(d.endContainer,["td","th"],!0);(e&&!f||!e&&f||e&&f&&e!==f)&&d.setCursor(!1,!0)}aa=null,c.removeListener("mouseover",x)}else{var k=domUtils.findParentByTagName(b.target||b.srcElement,"td",!0);if(k||(k=domUtils.findParentByTagName(b.target||b.srcElement,"th",!0)),k&&("TD"==k.tagName||"TH"==k.tagName)){if(c.fireEvent("excludetable",k)===!0)return;d=new dom.Range(c.document),d.setStart(k,0).setCursor(!1,!0)}}c._selectionChange(250,b)}}}function x(a,b){if(!A()){var c=this,d=b.target||b.srcElement;if(ba=domUtils.findParentByTagName(d,"td",!0)||domUtils.findParentByTagName(d,"th",!0),aa&&ba&&("TD"==aa.tagName&&"TD"==ba.tagName||"TH"==aa.tagName&&"TH"==ba.tagName)&&domUtils.findParentByTagName(aa,"table")==domUtils.findParentByTagName(ba,"table")){var e=Y(ba);if(aa!=ba){c.document.body.style.webkitUserSelect="none",c.selection.getNative()[browser.ie9below?"empty":"removeAllRanges"]();var f=e.getCellsRange(aa,ba);e.setSelected(f)}else c.document.body.style.webkitUserSelect="",e.clearSelected()}b.preventDefault?b.preventDefault():b.returnValue=!1}}function y(a,b,c){var d=parseInt(domUtils.getComputedStyle(a,"line-height"),10),e=c+b;b=e<d?d:e,a.style.height&&(a.style.height=""),1==a.rowSpan?a.setAttribute("height",b):a.removeAttribute&&a.removeAttribute("height")}function z(a,b){var c=Y(a);if(c){var d=c.table,e=C(a,d);if(d.style.width="",d.removeAttribute("width"),b=D(b,a,e),a.nextSibling){utils.each(e,function(a){a.left.width=+a.left.width+b,a.right&&(a.right.width=+a.right.width-b)})}else utils.each(e,function(a){a.left.width-=-b})}}function A(){return"false"===N.body.contentEditable}function B(a,b){if(!(Math.abs(b)<10)){var c=Y(a);if(c)for(var d,e=c.getSameEndPosCells(a,"y"),f=e[0]?e[0].offsetHeight:0,g=0;d=e[g++];)y(d,b,f)}}function C(a,b,c){if(b||(b=domUtils.findParentByTagName(a,"table")),!b)return null;for(var d=(domUtils.getNodeIndex(a),a),e=b.rows,f=0;d;)1===d.nodeType&&(f+=d.colSpan||1),d=d.previousSibling;d=null;var g=[];return utils.each(e,function(a){var b=a.cells,d=0;utils.each(b,function(a){return d+=a.colSpan||1,d===f?(g.push({left:a,right:a.nextSibling||null}),!1):d>f?(c&&g.push({left:a}),!1):void 0})}),g}function D(a,b,c){if(a-=G(),a<0)return 0;a-=E(b);var d=a<0?"left":"right";return a=Math.abs(a),utils.each(c,function(b){var c=b[d];c&&(a=Math.min(a,E(c)-Q))}),a=a<0?0:a,"left"===d?-a:a}function E(a){var b=0,b=a.offsetWidth-G();a.nextSibling||(b-=F(a)),b=b<0?0:b;try{a.width=b}catch(c){}return b}function F(a){if(tab=domUtils.findParentByTagName(a,"table",!1),void 0===tab.offsetVal){var b=a.previousSibling;b?tab.offsetVal=a.offsetWidth-b.offsetWidth===X.borderWidth?X.borderWidth:0:tab.offsetVal=0}return tab.offsetVal}function G(){if(void 0===X.tabcellSpace){var a=N.document.createElement("table"),b=N.document.createElement("tbody"),c=N.document.createElement("tr"),d=N.document.createElement("td"),e=null;d.style.cssText="border: 0;",d.width=1,c.appendChild(d),c.appendChild(e=d.cloneNode(!1)),b.appendChild(c),a.appendChild(b),a.style.cssText="visibility: hidden;",N.body.appendChild(a),X.paddingSpace=d.offsetWidth-1;var f=a.offsetWidth;d.style.cssText="",e.style.cssText="",X.borderWidth=(a.offsetWidth-f)/3,X.tabcellSpace=X.paddingSpace+X.borderWidth,N.body.removeChild(a)}return G=function(){return X.tabcellSpace},X.tabcellSpace}function H(a,b){ia||(ga=a.document.createElement("div"),domUtils.setAttributes(ga,{id:"ue_tableDragLine",unselectable:"on",contenteditable:!1,onresizestart:"return false",ondragstart:"return false",onselectstart:"return false",style:"background-color:blue;position:absolute;padding:0;margin:0;background-image:none;border:0px none;opacity:0;filter:alpha(opacity=0)"}),a.body.appendChild(ga))}function I(a){if(!ia)for(var b;b=a.document.getElementById("ue_tableDragLine");)domUtils.remove(b)}function J(a,b){if(b){var c,d=domUtils.findParentByTagName(b,"table"),e=d.getElementsByTagName("caption"),f=d.offsetWidth,g=d.offsetHeight-(e.length>0?e[0].offsetHeight:0),h=domUtils.getXY(d),i=domUtils.getXY(b);switch(a){case"h":c="height:"+g+"px;top:"+(h.y+(e.length>0?e[0].offsetHeight:0))+"px;left:"+(i.x+b.offsetWidth),ga.style.cssText=c+"px;position: absolute;display:block;background-color:blue;width:1px;border:0; color:blue;opacity:.3;filter:alpha(opacity=30)";break;case"v":c="width:"+f+"px;left:"+h.x+"px;top:"+(i.y+b.offsetHeight),ga.style.cssText=c+"px;overflow:hidden;position: absolute;display:block;background-color:blue;height:1px;border:0;color:blue;opacity:.2;filter:alpha(opacity=20)"}}}function K(a,b){for(var c,d,e=domUtils.getElementsByTagName(a.body,"table"),f=0;d=e[f++];){var g=domUtils.getElementsByTagName(d,"td");g[0]&&(b?(c=g[0].style.borderColor.replace(/\s/g,""),/(#ffffff)|(rgb\(255,255,255\))/gi.test(c)&&domUtils.addClass(d,"noBorderTable")):domUtils.removeClasses(d,"noBorderTable"))}}function L(a,b,c){var d=a.body;return d.offsetWidth-(b?2*parseInt(domUtils.getComputedStyle(d,"margin-left"),10):0)-2*c.tableBorder-(a.options.offsetWidth||0)}function M(a,b){var c=domUtils.findParentByTagName(b.target||b.srcElement,["td","th"],!0),d=null;if(!c)return null;if(d=n(c,f(b)),!c)return null;if("h1"===d&&c.previousSibling){var e=domUtils.getXY(c),g=c.offsetWidth;Math.abs(e.x+g-b.clientX)>g/3&&(c=c.previousSibling)}else if("v1"===d&&c.parentNode.previousSibling){var e=domUtils.getXY(c),h=c.offsetHeight;Math.abs(e.y+h-b.clientY)>h/3&&(c=c.parentNode.previousSibling.firstChild)}return c&&a.fireEvent("excludetable",c)!==!0?c:null}var N=this,O=null,P=null,Q=5,R=!1,S=5,T=10,U=0,V=null,W=360,X=UE.UETable,Y=function(a){return X.getUETable(a)},Z=function(a){return X.getUETableBySelected(a)},$=function(a,b){return X.getDefaultValue(a,b)},_=function(a){return X.removeSelectedClass(a)};N.ready(function(){var a=this,b=a.selection.getText;a.selection.getText=function(){var c=Z(a);if(c){var d="";return utils.each(c.selectedTds,function(a){d+=a[browser.ie?"innerText":"textContent"]}),d}return b.call(a.selection)}});var aa=null,ba=null,ca="",da=!1,ea=null,fa=!1,ga=null,ha=null,ia=!1,ja=!0;N.setOpt({maxColNum:20,maxRowNum:100,defaultCols:5,defaultRows:5,tdvalign:"top",cursorpath:N.options.UEDITOR_HOME_URL+"themes/default/img/cursor_",tableDragable:!1,classList:["ue-table-interlace-color-single","ue-table-interlace-color-double"]}),N.getUETable=Y;var ka={deletetable:1,inserttable:1,cellvalign:1,insertcaption:1,deletecaption:1,inserttitle:1,deletetitle:1,mergeright:1,mergedown:1,mergecells:1,insertrow:1,insertrownext:1,deleterow:1,insertcol:1,insertcolnext:1,deletecol:1,splittocells:1,splittorows:1,splittocols:1,adaptbytext:1,adaptbywindow:1,adaptbycustomer:1,insertparagraph:1,insertparagraphbeforetable:1,averagedistributecol:1,averagedistributerow:1};N.ready(function(){utils.cssRule("table",".selectTdClass{background-color:#edf5fa !important}table.noBorderTable td,table.noBorderTable th,table.noBorderTable caption{border:1px dashed #ddd !important}table{margin-bottom:10px;border-collapse:collapse;display:table;}td,th{padding: 5px 10px;border: 1px solid #DDD;}caption{border:1px dashed #DDD;border-bottom:0;padding:3px;text-align:center;}th{border-top:1px solid #BBB;background-color:#F7F7F7;}table tr.firstRow th{border-top-width:2px;}.ue-table-interlace-color-single{ background-color: #fcfcfc; } .ue-table-interlace-color-double{ background-color: #f7faff; }td p{margin:0;padding:0;}",N.document);var a,c,f;N.addListener("keydown",function(b,d){var g=this,h=d.keyCode||d.which;if(8==h){var i=Z(g);i&&i.selectedTds.length&&(i.isFullCol()?g.execCommand("deletecol"):i.isFullRow()?g.execCommand("deleterow"):g.fireEvent("delcells"),domUtils.preventDefault(d));var j=domUtils.findParentByTagName(g.selection.getStart(),"caption",!0),k=g.selection.getRange();if(k.collapsed&&j&&e(j)){g.fireEvent("saveScene");var l=j.parentNode;domUtils.remove(j),l&&k.setStart(l.rows[0].cells[0],0).setCursor(!1,!0),g.fireEvent("saveScene")}}if(46==h&&(i=Z(g))){g.fireEvent("saveScene");for(var m,n=0;m=i.selectedTds[n++];)domUtils.fillNode(g.document,m);g.fireEvent("saveScene"),domUtils.preventDefault(d)}if(13==h){var o=g.selection.getRange(),j=domUtils.findParentByTagName(o.startContainer,"caption",!0);if(j){var l=domUtils.findParentByTagName(j,"table");return o.collapsed?j&&o.setStart(l.rows[0].cells[0],0).setCursor(!1,!0):(o.deleteContents(),g.fireEvent("saveScene")),void domUtils.preventDefault(d)}if(o.collapsed){var l=domUtils.findParentByTagName(o.startContainer,"table");if(l){var p=l.rows[0].cells[0],q=domUtils.findParentByTagName(g.selection.getStart(),["td","th"],!0),r=l.previousSibling;if(p===q&&(!r||1==r.nodeType&&"TABLE"==r.tagName)&&domUtils.isStartInblock(o)){var s=domUtils.findParent(g.selection.getStart(),function(a){return domUtils.isBlockElm(a)},!0);s&&(/t(h|d)/i.test(s.tagName)||s===q.firstChild)&&(g.execCommand("insertparagraphbeforetable"),domUtils.preventDefault(d))}}}}if((d.ctrlKey||d.metaKey)&&"67"==d.keyCode){a=null;var i=Z(g);if(i){var t=i.selectedTds;c=i.isFullCol(),f=i.isFullRow(),a=[[i.cloneCell(t[0],null,!0)]];for(var m,n=1;m=t[n];n++)m.parentNode!==t[n-1].parentNode?a.push([i.cloneCell(m,null,!0)]):a[a.length-1].push(i.cloneCell(m,null,!0))}}}),N.addListener("tablehasdeleted",function(){m(this,!1,"",null),ea&&domUtils.remove(ea)}),N.addListener("beforepaste",function(d,g){var h=this,i=h.selection.getRange();if(domUtils.findParentByTagName(i.startContainer,"caption",!0)){var j=h.document.createElement("div");return j.innerHTML=g.html,void(g.html=j[browser.ie9below?"innerText":"textContent"])}var k=Z(h);if(a){h.fireEvent("saveScene");var l,m,i=h.selection.getRange(),n=domUtils.findParentByTagName(i.startContainer,["td","th"],!0);if(n){var o=Y(n);if(f){var p=o.getCellInfo(n).rowIndex;"TH"==n.tagName&&p++;for(var q,r=0;q=a[r++];){for(var s,t=o.insertRow(p++,"td"),u=0;s=q[u];u++){var v=t.cells[u];v||(v=t.insertCell(u)),v.innerHTML=s.innerHTML,s.getAttribute("width")&&v.setAttribute("width",s.getAttribute("width")),s.getAttribute("vAlign")&&v.setAttribute("vAlign",s.getAttribute("vAlign")),s.getAttribute("align")&&v.setAttribute("align",s.getAttribute("align")),s.style.cssText&&(v.style.cssText=s.style.cssText)}for(var s,u=0;(s=t.cells[u])&&q[u];u++)s.innerHTML=q[u].innerHTML,q[u].getAttribute("width")&&s.setAttribute("width",q[u].getAttribute("width")),q[u].getAttribute("vAlign")&&s.setAttribute("vAlign",q[u].getAttribute("vAlign")),q[u].getAttribute("align")&&s.setAttribute("align",q[u].getAttribute("align")),q[u].style.cssText&&(s.style.cssText=q[u].style.cssText)}}else{if(c){y=o.getCellInfo(n);for(var s,w=0,u=0,q=a[0];s=q[u++];)w+=s.colSpan||1;for(h.__hasEnterExecCommand=!0,r=0;r<w;r++)h.execCommand("insertcol");h.__hasEnterExecCommand=!1,n=o.table.rows[0].cells[y.cellIndex],"TH"==n.tagName&&(n=o.table.rows[1].cells[y.cellIndex])}for(var q,r=0;q=a[r++];){l=n;for(var s,u=0;s=q[u++];)if(n)n.innerHTML=s.innerHTML,s.getAttribute("width")&&n.setAttribute("width",s.getAttribute("width")),s.getAttribute("vAlign")&&n.setAttribute("vAlign",s.getAttribute("vAlign")),s.getAttribute("align")&&n.setAttribute("align",s.getAttribute("align")),s.style.cssText&&(n.style.cssText=s.style.cssText),m=n,n=n.nextSibling;else{var x=s.cloneNode(!0);domUtils.removeAttributes(x,["class","rowSpan","colSpan"]),m.parentNode.appendChild(x)}if(n=o.getNextCell(l,!0,!0),!a[r])break;if(!n){var y=o.getCellInfo(l);o.table.insertRow(o.table.rows.length),o.update(),n=o.getVSideCell(l,!0)}}}o.update()}else{k=h.document.createElement("table");for(var q,r=0;q=a[r++];){for(var s,t=k.insertRow(k.rows.length),u=0;s=q[u++];)x=X.cloneCell(s,null,!0),domUtils.removeAttributes(x,["class"]),t.appendChild(x);2==u&&x.rowSpan>1&&(x.rowSpan=1)}var z=$(h),A=h.body.offsetWidth-(ja?2*parseInt(domUtils.getComputedStyle(h.body,"margin-left"),10):0)-2*z.tableBorder-(h.options.offsetWidth||0);h.execCommand("insertHTML","<table "+(c&&f?'width="'+A+'"':"")+">"+k.innerHTML.replace(/>\s*</g,"><").replace(/\bth\b/gi,"td")+"</table>")}return h.fireEvent("contentchange"),h.fireEvent("saveScene"),g.html="",!0}var B,j=h.document.createElement("div");j.innerHTML=g.html,B=j.getElementsByTagName("table"),domUtils.findParentByTagName(h.selection.getStart(),"table")?(utils.each(B,function(a){domUtils.remove(a)}),domUtils.findParentByTagName(h.selection.getStart(),"caption",!0)&&(j.innerHTML=j[browser.ie?"innerText":"textContent"])):utils.each(B,function(a){b(a,!0),domUtils.removeAttributes(a,["style","border"]),utils.each(domUtils.getElementsByTagName(a,"td"),function(a){e(a)&&domUtils.fillNode(h.document,a),b(a,!0)})}),g.html=j.innerHTML}),N.addListener("afterpaste",function(){utils.each(domUtils.getElementsByTagName(N.body,"table"),function(a){if(a.offsetWidth>N.body.offsetWidth){var b=$(N,a);a.style.width=N.body.offsetWidth-(ja?2*parseInt(domUtils.getComputedStyle(N.body,"margin-left"),10):0)-2*b.tableBorder-(N.options.offsetWidth||0)+"px"}})}),N.addListener("blur",function(){a=null});var i;N.addListener("keydown",function(){clearTimeout(i),i=setTimeout(function(){var a=N.selection.getRange(),b=domUtils.findParentByTagName(a.startContainer,["th","td"],!0);if(b){var c=b.parentNode.parentNode.parentNode;c.offsetWidth>c.getAttribute("width")&&(b.style.wordBreak="break-all")}},100)}),N.addListener("selectionchange",function(){m(N,!1,"",null)}),N.addListener("contentchange",function(){var a=this;if(I(a),!Z(a)){var b=a.selection.getRange(),c=b.startContainer;c=domUtils.findParentByTagName(c,["td","th"],!0),utils.each(domUtils.getElementsByTagName(a.document,"table"),function(b){a.fireEvent("excludetable",b)!==!0&&(b.ueTable=new X(b),b.onmouseover=function(){a.fireEvent("tablemouseover",b)},b.onmousemove=function(){a.fireEvent("tablemousemove",b),a.options.tableDragable&&h(!0,this,a),utils.defer(function(){a.fireEvent("contentchange",50)},!0)},b.onmouseout=function(){a.fireEvent("tablemouseout",b),m(a,!1,"",null),I(a)},b.onclick=function(b){b=a.window.event||b;var c=d(b.target||b.srcElement);if(c){var e,f=Y(c),g=f.table,h=f.getCellInfo(c),i=a.selection.getRange();if(j(g,c,b,!0)){var k=f.getCell(f.indexTable[f.rowsNum-1][h.colIndex].rowIndex,f.indexTable[f.rowsNum-1][h.colIndex].cellIndex);return void(b.shiftKey&&f.selectedTds.length?f.selectedTds[0]!==k?(e=f.getCellsRange(f.selectedTds[0],k),f.setSelected(e)):i&&i.selectNodeContents(k).select():c!==k?(e=f.getCellsRange(c,k),f.setSelected(e)):i&&i.selectNodeContents(k).select())}if(j(g,c,b)){var l=f.getCell(f.indexTable[h.rowIndex][f.colsNum-1].rowIndex,f.indexTable[h.rowIndex][f.colsNum-1].cellIndex);b.shiftKey&&f.selectedTds.length?f.selectedTds[0]!==l?(e=f.getCellsRange(f.selectedTds[0],l),f.setSelected(e)):i&&i.selectNodeContents(l).select():c!==l?(e=f.getCellsRange(c,l),f.setSelected(e)):i&&i.selectNodeContents(l).select()}}})}),K(a,!0)}}),domUtils.on(N.document,"mousemove",g),domUtils.on(N.document,"mouseout",function(a){var b=a.target||a.srcElement;"TABLE"==b.tagName&&m(N,!1,"",null)}),N.addListener("interlacetable",function(a,b,c){if(b)for(var d=this,e=b.rows,f=e.length,g=function(a,b,c){return a[b]?a[b]:c?a[b%a.length]:""},h=0;h<f;h++)e[h].className=g(c||d.options.classList,h,!0)}),N.addListener("uninterlacetable",function(a,b){if(b)for(var c=this,d=b.rows,e=c.options.classList,f=d.length,g=0;g<f;g++)domUtils.removeClasses(d[g],e)}),N.addListener("mousedown",o),N.addListener("mouseup",w),domUtils.on(N.body,"dragstart",function(a){w.call(N,"dragstart",a)}),N.addOutputRule(function(a){utils.each(a.getNodesByTagName("div"),function(a){"ue_tableDragLine"==a.getAttr("id")&&a.parentNode.removeChild(a)})});var k=0;N.addListener("mousedown",function(){k=0}),N.addListener("tabkeydown",function(){var a=this.selection.getRange(),b=a.getCommonAncestor(!0,!0),c=domUtils.findParentByTagName(b,"table");if(c){if(domUtils.findParentByTagName(b,"caption",!0)){var d=domUtils.getElementsByTagName(c,"th td");d&&d.length&&a.setStart(d[0],0).setCursor(!1,!0)}else{var d=domUtils.findParentByTagName(b,["td","th"],!0),f=Y(d);k=d.rowSpan>1?k:f.getCellInfo(d).rowIndex;var g=f.getTabNextCell(d,k);g?e(g)?a.setStart(g,0).setCursor(!1,!0):a.selectNodeContents(g).select():(N.fireEvent("saveScene"),N.__hasEnterExecCommand=!0,this.execCommand("insertrownext"),N.__hasEnterExecCommand=!1,a=this.selection.getRange(),a.setStart(c.rows[c.rows.length-1].cells[0],0).setCursor(),N.fireEvent("saveScene"))}return!0}}),browser.ie&&N.addListener("selectionchange",function(){m(this,!1,"",null)}),N.addListener("keydown",function(a,b){var c=this,d=b.keyCode||b.which;if(8!=d&&46!=d){var e=!(b.ctrlKey||b.metaKey||b.shiftKey||b.altKey);e&&_(domUtils.getElementsByTagName(c.body,"td"));var f=Z(c);f&&e&&f.clearSelected()}}),N.addListener("beforegetcontent",function(){K(this,!1),browser.ie&&utils.each(this.document.getElementsByTagName("caption"),function(a){domUtils.isEmptyNode(a)&&(a.innerHTML=" ")})}),N.addListener("aftergetcontent",function(){K(this,!0)}),N.addListener("getAllHtml",function(){_(N.document.getElementsByTagName("td"))}),N.addListener("fullscreenchanged",function(a,b){if(!b){var c=this.body.offsetWidth/document.body.offsetWidth,d=domUtils.getElementsByTagName(this.body,"table");utils.each(d,function(a){if(a.offsetWidth<N.body.offsetWidth)return!1;var b=domUtils.getElementsByTagName(a,"td"),d=[];utils.each(b,function(a){d.push(a.offsetWidth)});for(var e,f=0;e=b[f];f++)e.setAttribute("width",Math.floor(d[f]*c));a.setAttribute("width",Math.floor(L(N,ja,$(N))))})}});var l=N.execCommand;N.execCommand=function(a,b){var c=this;a=a.toLowerCase();var d,f,g=Z(c),h=new dom.Range(c.document),i=c.commands[a]||UE.commands[a];if(i){if(!g||ka[a]||i.notNeedUndo||c.__hasEnterExecCommand)f=l.apply(c,arguments);else{c.__hasEnterExecCommand=!0,c.fireEvent("beforeexeccommand",a),d=g.selectedTds;for(var j,k,m,n=-2,o=-2,p=0;m=d[p];p++)e(m)?h.setStart(m,0).setCursor(!1,!0):h.selectNode(m).select(!0),k=c.queryCommandState(a),j=c.queryCommandValue(a),k!=-1&&(n===k&&o===j||(c._ignoreContentChange=!0,f=l.apply(c,arguments),c._ignoreContentChange=!1),n=c.queryCommandState(a),o=c.queryCommandValue(a),domUtils.isEmptyBlock(m)&&domUtils.fillNode(c.document,m));h.setStart(d[0],0).shrinkBoundary(!0).setCursor(!1,!0),c.fireEvent("contentchange"),c.fireEvent("afterexeccommand",a),c.__hasEnterExecCommand=!1,c._selectionChange()}return f}}});var la},UE.UETable.prototype.sortTable=function(a,b){var c=this.table,d=c.rows,e=[],f="TH"===d[0].cells[0].tagName,g=0;if(this.selectedTds.length){for(var h=this.cellsRange,i=h.endRowIndex+1,j=h.beginRowIndex;j<i;j++)e[j]=d[j];e.splice(0,h.beginRowIndex),g=h.endRowIndex+1===this.rowsNum?0:h.endRowIndex+1;
}else for(var j=0,i=d.length;j<i;j++)e[j]=d[j];var k={reversecurrent:function(a,b){return 1},orderbyasc:function(a,b){var c=a.innerText||a.textContent,d=b.innerText||b.textContent;return c.localeCompare(d)},reversebyasc:function(a,b){var c=a.innerHTML,d=b.innerHTML;return d.localeCompare(c)},orderbynum:function(a,b){var c=a[browser.ie?"innerText":"textContent"].match(/\d+/),d=b[browser.ie?"innerText":"textContent"].match(/\d+/);return c&&(c=+c[0]),d&&(d=+d[0]),(c||0)-(d||0)},reversebynum:function(a,b){var c=a[browser.ie?"innerText":"textContent"].match(/\d+/),d=b[browser.ie?"innerText":"textContent"].match(/\d+/);return c&&(c=+c[0]),d&&(d=+d[0]),(d||0)-(c||0)}};c.setAttribute("data-sort-type",b&&"string"==typeof b&&k[b]?b:""),f&&e.splice(0,1),e=utils.sort(e,function(c,d){var e;return e=b&&"function"==typeof b?b.call(this,c.cells[a],d.cells[a]):b&&"number"==typeof b?1:b&&"string"==typeof b&&k[b]?k[b].call(this,c.cells[a],d.cells[a]):k.orderbyasc.call(this,c.cells[a],d.cells[a])});for(var l=c.ownerDocument.createDocumentFragment(),m=0,i=e.length;m<i;m++)l.appendChild(e[m]);var n=c.getElementsByTagName("tbody")[0];g?n.insertBefore(l,d[g-h.endRowIndex+h.beginRowIndex-1]):n.appendChild(l)},UE.plugins.tablesort=function(){var a=this,b=UE.UETable,c=function(a){return b.getUETable(a)},d=function(a){return b.getTableItemsByRange(a)};a.ready(function(){utils.cssRule("tablesort","table.sortEnabled tr.firstRow th,table.sortEnabled tr.firstRow td{padding-right:20px;background-repeat: no-repeat;background-position: center right; background-image:url("+a.options.themePath+a.options.theme+"/img/sortable.png);}",a.document),a.addListener("afterexeccommand",function(a,b){"mergeright"!=b&&"mergedown"!=b&&"mergecells"!=b||this.execCommand("disablesort")})}),UE.commands.sorttable={queryCommandState:function(){var a=this,b=d(a);if(!b.cell)return-1;for(var c,e=b.table,f=e.getElementsByTagName("td"),g=0;c=f[g++];)if(1!=c.rowSpan||1!=c.colSpan)return-1;return 0},execCommand:function(a,b){var e=this,f=e.selection.getRange(),g=f.createBookmark(!0),h=d(e),i=h.cell,j=c(h.table),k=j.getCellInfo(i);j.sortTable(k.cellIndex,b),f.moveToBookmark(g);try{f.select()}catch(l){}}},UE.commands.enablesort=UE.commands.disablesort={queryCommandState:function(a){var b=d(this).table;if(b&&"enablesort"==a)for(var c=domUtils.getElementsByTagName(b,"th td"),e=0;e<c.length;e++)if(c[e].getAttribute("colspan")>1||c[e].getAttribute("rowspan")>1)return-1;return b?"enablesort"==a^"sortEnabled"!=b.getAttribute("data-sort")?-1:0:-1},execCommand:function(a){var b=d(this).table;b.setAttribute("data-sort","enablesort"==a?"sortEnabled":"sortDisabled"),"enablesort"==a?domUtils.addClass(b,"sortEnabled"):domUtils.removeClasses(b,"sortEnabled")}}},UE.plugins.contextmenu=function(){var a=this;if(a.setOpt("enableContextMenu",!0),a.getOpt("enableContextMenu")!==!1){var b,c=a.getLang("contextMenu"),d=a.options.contextMenu||[{label:c.selectall,cmdName:"selectall"},{label:c.cleardoc,cmdName:"cleardoc",exec:function(){confirm(c.confirmclear)&&this.execCommand("cleardoc")}},"-",{label:c.unlink,cmdName:"unlink"},"-",{group:c.paragraph,icon:"justifyjustify",subMenu:[{label:c.justifyleft,cmdName:"justify",value:"left"},{label:c.justifyright,cmdName:"justify",value:"right"},{label:c.justifycenter,cmdName:"justify",value:"center"},{label:c.justifyjustify,cmdName:"justify",value:"justify"}]},"-",{group:c.table,icon:"table",subMenu:[{label:c.inserttable,cmdName:"inserttable"},{label:c.deletetable,cmdName:"deletetable"},"-",{label:c.deleterow,cmdName:"deleterow"},{label:c.deletecol,cmdName:"deletecol"},{label:c.insertcol,cmdName:"insertcol"},{label:c.insertcolnext,cmdName:"insertcolnext"},{label:c.insertrow,cmdName:"insertrow"},{label:c.insertrownext,cmdName:"insertrownext"},"-",{label:c.insertcaption,cmdName:"insertcaption"},{label:c.deletecaption,cmdName:"deletecaption"},{label:c.inserttitle,cmdName:"inserttitle"},{label:c.deletetitle,cmdName:"deletetitle"},{label:c.inserttitlecol,cmdName:"inserttitlecol"},{label:c.deletetitlecol,cmdName:"deletetitlecol"},"-",{label:c.mergecells,cmdName:"mergecells"},{label:c.mergeright,cmdName:"mergeright"},{label:c.mergedown,cmdName:"mergedown"},"-",{label:c.splittorows,cmdName:"splittorows"},{label:c.splittocols,cmdName:"splittocols"},{label:c.splittocells,cmdName:"splittocells"},"-",{label:c.averageDiseRow,cmdName:"averagedistributerow"},{label:c.averageDisCol,cmdName:"averagedistributecol"},"-",{label:c.edittd,cmdName:"edittd",exec:function(){UE.ui.edittd&&new UE.ui.edittd(this),this.getDialog("edittd").open()}},{label:c.edittable,cmdName:"edittable",exec:function(){UE.ui.edittable&&new UE.ui.edittable(this),this.getDialog("edittable").open()}},{label:c.setbordervisible,cmdName:"setbordervisible"}]},{group:c.tablesort,icon:"tablesort",subMenu:[{label:c.enablesort,cmdName:"enablesort"},{label:c.disablesort,cmdName:"disablesort"},"-",{label:c.reversecurrent,cmdName:"sorttable",value:"reversecurrent"},{label:c.orderbyasc,cmdName:"sorttable",value:"orderbyasc"},{label:c.reversebyasc,cmdName:"sorttable",value:"reversebyasc"},{label:c.orderbynum,cmdName:"sorttable",value:"orderbynum"},{label:c.reversebynum,cmdName:"sorttable",value:"reversebynum"}]},{group:c.borderbk,icon:"borderBack",subMenu:[{label:c.setcolor,cmdName:"interlacetable",exec:function(){this.execCommand("interlacetable")}},{label:c.unsetcolor,cmdName:"uninterlacetable",exec:function(){this.execCommand("uninterlacetable")}},{label:c.setbackground,cmdName:"settablebackground",exec:function(){this.execCommand("settablebackground",{repeat:!0,colorList:["#bbb","#ccc"]})}},{label:c.unsetbackground,cmdName:"cleartablebackground",exec:function(){this.execCommand("cleartablebackground")}},{label:c.redandblue,cmdName:"settablebackground",exec:function(){this.execCommand("settablebackground",{repeat:!0,colorList:["red","blue"]})}},{label:c.threecolorgradient,cmdName:"settablebackground",exec:function(){this.execCommand("settablebackground",{repeat:!0,colorList:["#aaa","#bbb","#ccc"]})}}]},{group:c.aligntd,icon:"aligntd",subMenu:[{cmdName:"cellalignment",value:{align:"left",vAlign:"top"}},{cmdName:"cellalignment",value:{align:"center",vAlign:"top"}},{cmdName:"cellalignment",value:{align:"right",vAlign:"top"}},{cmdName:"cellalignment",value:{align:"left",vAlign:"middle"}},{cmdName:"cellalignment",value:{align:"center",vAlign:"middle"}},{cmdName:"cellalignment",value:{align:"right",vAlign:"middle"}},{cmdName:"cellalignment",value:{align:"left",vAlign:"bottom"}},{cmdName:"cellalignment",value:{align:"center",vAlign:"bottom"}},{cmdName:"cellalignment",value:{align:"right",vAlign:"bottom"}}]},{group:c.aligntable,icon:"aligntable",subMenu:[{cmdName:"tablealignment",className:"left",label:c.tableleft,value:"left"},{cmdName:"tablealignment",className:"center",label:c.tablecenter,value:"center"},{cmdName:"tablealignment",className:"right",label:c.tableright,value:"right"}]},"-",{label:c.insertparagraphbefore,cmdName:"insertparagraph",value:!0},{label:c.insertparagraphafter,cmdName:"insertparagraph"},{label:c.copy,cmdName:"copy"},{label:c.paste,cmdName:"paste"}];if(d.length){var e=UE.ui.uiUtils;a.addListener("contextmenu",function(f,g){var h=e.getViewportOffsetByEvent(g);a.fireEvent("beforeselectionchange"),b&&b.destroy();for(var i,j=0,k=[];i=d[j];j++){var l;!function(b){function d(){switch(b.icon){case"table":return a.getLang("contextMenu.table");case"justifyjustify":return a.getLang("contextMenu.paragraph");case"aligntd":return a.getLang("contextMenu.aligntd");case"aligntable":return a.getLang("contextMenu.aligntable");case"tablesort":return c.tablesort;case"borderBack":return c.borderbk;default:return""}}if("-"==b)(l=k[k.length-1])&&"-"!==l&&k.push("-");else if(b.hasOwnProperty("group")){for(var e,f=0,g=[];e=b.subMenu[f];f++)!function(b){"-"==b?(l=g[g.length-1])&&"-"!==l?g.push("-"):g.splice(g.length-1):(a.commands[b.cmdName]||UE.commands[b.cmdName]||b.query)&&(b.query?b.query():a.queryCommandState(b.cmdName))>-1&&g.push({label:b.label||a.getLang("contextMenu."+b.cmdName+(b.value||""))||"",className:"edui-for-"+b.cmdName+(b.className?" edui-for-"+b.cmdName+"-"+b.className:""),onclick:b.exec?function(){b.exec.call(a)}:function(){a.execCommand(b.cmdName,b.value)}})}(e);g.length&&k.push({label:d(),className:"edui-for-"+b.icon,subMenu:{items:g,editor:a}})}else(a.commands[b.cmdName]||UE.commands[b.cmdName]||b.query)&&(b.query?b.query.call(a):a.queryCommandState(b.cmdName))>-1&&k.push({label:b.label||a.getLang("contextMenu."+b.cmdName),className:"edui-for-"+(b.icon?b.icon:b.cmdName+(b.value||"")),onclick:b.exec?function(){b.exec.call(a)}:function(){a.execCommand(b.cmdName,b.value)}})}(i)}if("-"==k[k.length-1]&&k.pop(),b=new UE.ui.Menu({items:k,className:"edui-contextmenu",editor:a}),b.render(),b.showAt(h),a.fireEvent("aftershowcontextmenu",b),domUtils.preventDefault(g),browser.ie){var m;try{m=a.selection.getNative().createRange()}catch(n){return}if(m.item){var o=new dom.Range(a.document);o.selectNode(m.item(0)).select(!0,!0)}}}),a.addListener("aftershowcontextmenu",function(b,c){if(a.zeroclipboard){var d=c.items;for(var e in d)"edui-for-copy"==d[e].className&&a.zeroclipboard.clip(d[e].getDom())}})}}},UE.plugins.shortcutmenu=function(){var a,b=this,c=b.options.shortcutMenu||[];c.length&&(b.addListener("contextmenu mouseup",function(b,d){var e=this,f={type:b,target:d.target||d.srcElement,screenX:d.screenX,screenY:d.screenY,clientX:d.clientX,clientY:d.clientY};if(setTimeout(function(){var d=e.selection.getRange();d.collapsed!==!1&&"contextmenu"!=b||(a||(a=new baidu.editor.ui.ShortCutMenu({editor:e,items:c,theme:e.options.theme,className:"edui-shortcutmenu"}),a.render(),e.fireEvent("afterrendershortcutmenu",a)),a.show(f,!!UE.plugins.contextmenu))}),"contextmenu"==b&&(domUtils.preventDefault(d),browser.ie9below)){var g;try{g=e.selection.getNative().createRange()}catch(d){return}if(g.item){var h=new dom.Range(e.document);h.selectNode(g.item(0)).select(!0,!0)}}}),b.addListener("keydown",function(b){"keydown"==b&&a&&!a.isHidden&&a.hide()}))},UE.plugins.basestyle=function(){var a={bold:["strong","b"],italic:["em","i"],subscript:["sub"],superscript:["sup"]},b=function(a,b){return domUtils.filterNodeList(a.selection.getStartElementPath(),b)},c=this;c.addshortcutkey({Bold:"ctrl+66",Italic:"ctrl+73",Underline:"ctrl+85"}),c.addInputRule(function(a){utils.each(a.getNodesByTagName("b i"),function(a){switch(a.tagName){case"b":a.tagName="strong";break;case"i":a.tagName="em"}})});for(var d in a)!function(a,d){c.commands[a]={execCommand:function(a){var e=c.selection.getRange(),f=b(this,d);if(e.collapsed){if(f){var g=c.document.createTextNode("");e.insertNode(g).removeInlineStyle(d),e.setStartBefore(g),domUtils.remove(g)}else{var h=e.document.createElement(d[0]);"superscript"!=a&&"subscript"!=a||(g=c.document.createTextNode(""),e.insertNode(g).removeInlineStyle(["sub","sup"]).setStartBefore(g).collapse(!0)),e.insertNode(h).setStart(h,0)}e.collapse(!0)}else"superscript"!=a&&"subscript"!=a||f&&f.tagName.toLowerCase()==a||e.removeInlineStyle(["sub","sup"]),f?e.removeInlineStyle(d):e.applyInlineStyle(d[0]);e.select()},queryCommandState:function(){return b(this,d)?1:0}}}(d,a[d])},UE.plugins.elementpath=function(){var a,b,c=this;c.setOpt("elementPathEnabled",!0),c.options.elementPathEnabled&&(c.commands.elementpath={execCommand:function(d,e){var f=b[e],g=c.selection.getRange();a=1*e,g.selectNode(f).select()},queryCommandValue:function(){var c=[].concat(this.selection.getStartElementPath()).reverse(),d=[];b=c;for(var e,f=0;e=c[f];f++)if(3!=e.nodeType){var g=e.tagName.toLowerCase();if("img"==g&&e.getAttribute("anchorname")&&(g="anchor"),d[f]=g,a==f){a=-1;break}}return d}})},UE.plugins.formatmatch=function(){function a(f,g){function h(a){return m&&a.selectNode(m),a.applyInlineStyle(d[d.length-1].tagName,null,d)}if(browser.webkit)var i="IMG"==g.target.tagName?g.target:null;c.undoManger&&c.undoManger.save();var j=c.selection.getRange(),k=i||j.getClosedNode();if(b&&k&&"IMG"==k.tagName)k.style.cssText+=";float:"+(b.style.cssFloat||b.style.styleFloat||"none")+";display:"+(b.style.display||"inline"),b=null;else if(!b){var l=j.collapsed;if(l){var m=c.document.createTextNode("match");j.insertNode(m).select()}c.__hasEnterExecCommand=!0;var n=c.options.removeFormatAttributes;c.options.removeFormatAttributes="",c.execCommand("removeformat"),c.options.removeFormatAttributes=n,c.__hasEnterExecCommand=!1,j=c.selection.getRange(),d.length&&h(j),m&&j.setStartBefore(m).collapse(!0),j.select(),m&&domUtils.remove(m)}c.undoManger&&c.undoManger.save(),c.removeListener("mouseup",a),e=0}var b,c=this,d=[],e=0;c.addListener("reset",function(){d=[],e=0}),c.commands.formatmatch={execCommand:function(f){if(e)return e=0,d=[],void c.removeListener("mouseup",a);var g=c.selection.getRange();if(b=g.getClosedNode(),!b||"IMG"!=b.tagName){g.collapse(!0).shrinkBoundary();var h=g.startContainer;d=domUtils.findParents(h,!0,function(a){return!domUtils.isBlockElm(a)&&1==a.nodeType});for(var i,j=0;i=d[j];j++)if("A"==i.tagName){d.splice(j,1);break}}c.addListener("mouseup",a),e=1},queryCommandState:function(){return e},notNeedUndo:1}},UE.plugin.register("searchreplace",function(){function a(a,b,c){var d=b.searchStr;b.dir==-1&&(a=a.split("").reverse().join(""),d=d.split("").reverse().join(""),c=a.length-c);for(var e,f=new RegExp(d,"g"+(b.casesensitive?"":"i"));e=f.exec(a);)if(e.index>=c)return b.dir==-1?a.length-e.index-b.searchStr.length:e.index;return-1}function b(b,c,d){var e,f,h=d.all||1==d.dir?"getNextDomNode":"getPreDomNode";domUtils.isBody(b)&&(b=b.firstChild);for(var i=1;b;){if(e=3==b.nodeType?b.nodeValue:b[browser.ie?"innerText":"textContent"],f=a(e,d,c),i=0,f!=-1)return{node:b,index:f};for(b=domUtils[h](b);b&&g[b.nodeName.toLowerCase()];)b=domUtils[h](b,!0);b&&(c=d.dir==-1?(3==b.nodeType?b.nodeValue:b[browser.ie?"innerText":"textContent"]).length:0)}}function c(a,b,d){for(var e,f=0,g=a.firstChild,h=0;g;){if(3==g.nodeType){if(h=g.nodeValue.replace(/(^[\t\r\n]+)|([\t\r\n]+$)/,"").length,f+=h,f>=b)return{node:g,index:h-(f-b)}}else if(!dtd.$empty[g.tagName]&&(h=g[browser.ie?"innerText":"textContent"].replace(/(^[\t\r\n]+)|([\t\r\n]+$)/,"").length,f+=h,f>=b&&(e=c(g,h-(f-b),d))))return e;g=domUtils.getNextDomNode(g)}}function d(a,d){var f,g=a.selection.getRange(),h=d.searchStr,i=a.document.createElement("span");if(i.innerHTML="$$ueditor_searchreplace_key$$",g.shrinkBoundary(!0),!g.collapsed){g.select();var j=a.selection.getText();if(new RegExp("^"+d.searchStr+"$",d.casesensitive?"":"i").test(j)){if(void 0!=d.replaceStr)return e(g,d.replaceStr),g.select(),!0;g.collapse(d.dir==-1)}}g.insertNode(i),g.enlargeToBlockElm(!0),f=g.startContainer;var k=f[browser.ie?"innerText":"textContent"].indexOf("$$ueditor_searchreplace_key$$");g.setStartBefore(i),domUtils.remove(i);var l=b(f,k,d);if(l){var m=c(l.node,l.index,h),n=c(l.node,l.index+h.length,h);return g.setStart(m.node,m.index).setEnd(n.node,n.index),void 0!==d.replaceStr&&e(g,d.replaceStr),g.select(),!0}g.setCursor()}function e(a,b){b=f.document.createTextNode(b),a.deleteContents().insertNode(b)}var f=this,g={table:1,tbody:1,tr:1,ol:1,ul:1};return{commands:{searchreplace:{execCommand:function(a,b){utils.extend(b,{all:!1,casesensitive:!1,dir:1},!0);var c=0;if(b.all){var e=f.selection.getRange(),g=f.body.firstChild;for(g&&1==g.nodeType?(e.setStart(g,0),e.shrinkBoundary(!0)):3==g.nodeType&&e.setStartBefore(g),e.collapse(!0).select(!0),void 0!==b.replaceStr&&f.fireEvent("saveScene");d(this,b);)c++;c&&f.fireEvent("saveScene")}else void 0!==b.replaceStr&&f.fireEvent("saveScene"),d(this,b)&&c++,c&&f.fireEvent("saveScene");return c},notNeedUndo:1}}}}),UE.plugins.customstyle=function(){var a=this;a.setOpt({customstyle:[{tag:"h1",name:"tc",style:"font-size:32px;font-weight:bold;border-bottom:#ccc 2px solid;padding:0 4px 0 0;text-align:center;margin:0 0 20px 0;"},{tag:"h1",name:"tl",style:"font-size:32px;font-weight:bold;border-bottom:#ccc 2px solid;padding:0 4px 0 0;text-align:left;margin:0 0 10px 0;"},{tag:"span",name:"im",style:"font-size:16px;font-style:italic;font-weight:bold;line-height:18px;"},{tag:"span",name:"hi",style:"font-size:16px;font-style:italic;font-weight:bold;color:rgb(51, 153, 204);line-height:18px;"}]}),a.commands.customstyle={execCommand:function(a,b){var c,d,e=this,f=b.tag,g=domUtils.findParent(e.selection.getStart(),function(a){return a.getAttribute("label")},!0),h={};for(var i in b)void 0!==b[i]&&(h[i]=b[i]);if(delete h.tag,g&&g.getAttribute("label")==b.label){if(c=this.selection.getRange(),d=c.createBookmark(),c.collapsed)if(dtd.$block[g.tagName]){var j=e.document.createElement("p");domUtils.moveChild(g,j),g.parentNode.insertBefore(j,g),domUtils.remove(g)}else domUtils.remove(g,!0);else{var k=domUtils.getCommonAncestor(d.start,d.end),l=domUtils.getElementsByTagName(k,f);new RegExp(f,"i").test(k.tagName)&&l.push(k);for(var m,n=0;m=l[n++];)if(m.getAttribute("label")==b.label){var o=domUtils.getPosition(m,d.start),p=domUtils.getPosition(m,d.end);if((o&domUtils.POSITION_FOLLOWING||o&domUtils.POSITION_CONTAINS)&&(p&domUtils.POSITION_PRECEDING||p&domUtils.POSITION_CONTAINS)&&dtd.$block[f]){var j=e.document.createElement("p");domUtils.moveChild(m,j),m.parentNode.insertBefore(j,m)}domUtils.remove(m,!0)}g=domUtils.findParent(k,function(a){return a.getAttribute("label")==b.label},!0),g&&domUtils.remove(g,!0)}c.moveToBookmark(d).select()}else if(dtd.$block[f]){if(this.execCommand("paragraph",f,h,"customstyle"),c=e.selection.getRange(),!c.collapsed){c.collapse(),g=domUtils.findParent(e.selection.getStart(),function(a){return a.getAttribute("label")==b.label},!0);var q=e.document.createElement("p");domUtils.insertAfter(g,q),domUtils.fillNode(e.document,q),c.setStart(q,0).setCursor()}}else{if(c=e.selection.getRange(),c.collapsed)return g=e.document.createElement(f),domUtils.setAttributes(g,h),void c.insertNode(g).setStart(g,0).setCursor();d=c.createBookmark(),c.applyInlineStyle(f,h).moveToBookmark(d).select()}},queryCommandValue:function(){var a=domUtils.filterNodeList(this.selection.getStartElementPath(),function(a){return a.getAttribute("label")});return a?a.getAttribute("label"):""}},a.addListener("keyup",function(b,c){var d=c.keyCode||c.which;if(32==d||13==d){var e=a.selection.getRange();if(e.collapsed){var f=domUtils.findParent(a.selection.getStart(),function(a){return a.getAttribute("label")},!0);if(f&&dtd.$block[f.tagName]&&domUtils.isEmptyNode(f)){var g=a.document.createElement("p");domUtils.insertAfter(f,g),domUtils.fillNode(a.document,g),domUtils.remove(f),e.setStart(g,0).setCursor()}}}})},UE.plugins.catchremoteimage=function(){var me=this,ajax=UE.ajax;me.options.catchRemoteImageEnable!==!1&&(me.setOpt({catchRemoteImageEnable:!1}),me.addListener("afterpaste",function(){me.fireEvent("catchRemoteImage")}),me.addListener("catchRemoteImage",function(){function catchremoteimage(a,b){var c=utils.serializeParam(me.queryCommandValue("serverparam"))||"",d=utils.formatUrl(catcherActionUrl+(catcherActionUrl.indexOf("?")==-1?"?":"&")+c),e=utils.isCrossDomainUrl(d),f={method:"POST",dataType:e?"jsonp":"",timeout:6e4,onsuccess:b.success,onerror:b.error};f[catcherFieldName]=a,ajax.request(d,f)}for(var catcherLocalDomain=me.getOpt("catcherLocalDomain"),catcherActionUrl=me.getActionUrl(me.getOpt("catcherActionName")),catcherUrlPrefix=me.getOpt("catcherUrlPrefix"),catcherFieldName=me.getOpt("catcherFieldName"),remoteImages=[],imgs=domUtils.getElementsByTagName(me.document,"img"),test=function(a,b){if(a.indexOf(location.host)!=-1||/(^\.)|(^\/)/.test(a))return!0;if(b)for(var c,d=0;c=b[d++];)if(a.indexOf(c)!==-1)return!0;return!1},i=0,ci;ci=imgs[i++];)if(!ci.getAttribute("word_img")){var src=ci.getAttribute("_src")||ci.src||"";/^(https?|ftp):/i.test(src)&&!test(src,catcherLocalDomain)&&remoteImages.push(src)}remoteImages.length&&catchremoteimage(remoteImages,{success:function(r){try{var info=void 0!==r.state?r:eval("("+r.responseText+")")}catch(e){return}var i,j,ci,cj,oldSrc,newSrc,list=info.list;for(i=0;ci=imgs[i++];)for(oldSrc=ci.getAttribute("_src")||ci.src||"",j=0;cj=list[j++];)if(oldSrc==cj.source&&"SUCCESS"==cj.state){newSrc=catcherUrlPrefix+cj.url,domUtils.setAttributes(ci,{src:newSrc,_src:newSrc});break}me.fireEvent("catchremotesuccess")},error:function(){me.fireEvent("catchremoteerror")}})}))},UE.plugin.register("snapscreen",function(){function getLocation(a){var b,c=document.createElement("a"),d=utils.serializeParam(me.queryCommandValue("serverparam"))||"";return c.href=a,browser.ie&&(c.href=c.href),b=c.search,d&&(b=b+(b.indexOf("?")==-1?"?":"&")+d,b=b.replace(/[&]+/gi,"&")),{port:c.port,hostname:c.hostname,path:c.pathname+b||+c.hash}}var me=this,snapplugin;return{commands:{snapscreen:{execCommand:function(cmd){function onSuccess(rs){try{if(rs=eval("("+rs+")"),"SUCCESS"==rs.state){var opt=me.options;me.execCommand("insertimage",{src:opt.snapscreenUrlPrefix+rs.url,_src:opt.snapscreenUrlPrefix+rs.url,alt:rs.title||"",floatStyle:opt.snapscreenImgAlign})}else alert(rs.state)}catch(e){alert(lang.callBackErrorMsg)}}var url,local,res,lang=me.getLang("snapScreen_plugin");if(!snapplugin){var container=me.container,doc=me.container.ownerDocument||me.container.document;snapplugin=doc.createElement("object");try{snapplugin.type="application/x-pluginbaidusnap"}catch(e){return}snapplugin.style.cssText="position:absolute;left:-9999px;width:0;height:0;",snapplugin.setAttribute("width","0"),snapplugin.setAttribute("height","0"),container.appendChild(snapplugin)}url=me.getActionUrl(me.getOpt("snapscreenActionName")),local=getLocation(url),setTimeout(function(){try{res=snapplugin.saveSnapshot(local.hostname,local.path,local.port)}catch(a){return void me.ui._dialogs.snapscreenDialog.open()}onSuccess(res)},50)},queryCommandState:function(){return navigator.userAgent.indexOf("Windows",0)!=-1?0:-1}}}}}),UE.commands.insertparagraph={execCommand:function(a,b){for(var c,d=this,e=d.selection.getRange(),f=e.startContainer;f&&!domUtils.isBody(f);)c=f,f=f.parentNode;if(c){var g=d.document.createElement("p");b?c.parentNode.insertBefore(g,c):c.parentNode.insertBefore(g,c.nextSibling),domUtils.fillNode(d.document,g),e.setStart(g,0).setCursor(!1,!0)}}},UE.plugin.register("webapp",function(){function a(a,c){return c?'<iframe class="edui-faked-webapp" title="'+a.title+'" '+(a.align&&!a.cssfloat?'align="'+a.align+'"':"")+(a.cssfloat?'style="float:'+a.cssfloat+'"':"")+'width="'+a.width+'" height="'+a.height+'" scrolling="no" frameborder="0" src="'+a.url+'" logo_url = "'+a.logo+'"></iframe>':'<img title="'+a.title+'" width="'+a.width+'" height="'+a.height+'" src="'+b.options.UEDITOR_HOME_URL+'themes/default/img/spacer.gif" _logo_url="'+a.logo+'" style="background:url('+a.logo+') no-repeat center center; border:1px solid gray;" class="edui-faked-webapp" _url="'+a.url+'" '+(a.align&&!a.cssfloat?'align="'+a.align+'"':"")+(a.cssfloat?'style="float:'+a.cssfloat+'"':"")+"/>"}var b=this;return{outputRule:function(b){utils.each(b.getNodesByTagName("img"),function(b){var c;if("edui-faked-webapp"==b.getAttr("class")){c=a({title:b.getAttr("title"),width:b.getAttr("width"),height:b.getAttr("height"),align:b.getAttr("align"),cssfloat:b.getStyle("float"),url:b.getAttr("_url"),logo:b.getAttr("_logo_url")},!0);var d=UE.uNode.createElement(c);b.parentNode.replaceChild(d,b)}})},inputRule:function(b){utils.each(b.getNodesByTagName("iframe"),function(b){if("edui-faked-webapp"==b.getAttr("class")){var c=UE.uNode.createElement(a({title:b.getAttr("title"),width:b.getAttr("width"),height:b.getAttr("height"),align:b.getAttr("align"),cssfloat:b.getStyle("float"),url:b.getAttr("src"),logo:b.getAttr("logo_url")}));b.parentNode.replaceChild(c,b)}})},commands:{webapp:{execCommand:function(b,c){var d=this,e=a(utils.extend(c,{align:"none"}),!1);d.execCommand("inserthtml",e)},queryCommandState:function(){var a=this,b=a.selection.getRange().getClosedNode(),c=b&&"edui-faked-webapp"==b.className;return c?1:0}}}}}),UE.plugins.template=function(){UE.commands.template={execCommand:function(a,b){b.html&&this.execCommand("inserthtml",b.html)}},this.addListener("click",function(a,b){var c=b.target||b.srcElement,d=this.selection.getRange(),e=domUtils.findParent(c,function(a){if(a.className&&domUtils.hasClass(a,"ue_t"))return a},!0);e&&d.selectNode(e).shrinkBoundary().select()}),this.addListener("keydown",function(a,b){var c=this.selection.getRange();if(!c.collapsed&&!(b.ctrlKey||b.metaKey||b.shiftKey||b.altKey)){var d=domUtils.findParent(c.startContainer,function(a){if(a.className&&domUtils.hasClass(a,"ue_t"))return a},!0);d&&domUtils.removeClasses(d,["ue_t"])}})},UE.plugin.register("music",function(){function a(a,c,d,e,f,g){return g?'<embed type="application/x-shockwave-flash" class="edui-faked-music" pluginspage="http://www.macromedia.com/go/getflashplayer" src="'+a+'" width="'+c+'" height="'+d+'" '+(e&&!f?'align="'+e+'"':"")+(f?'style="float:'+f+'"':"")+' wmode="transparent" play="true" loop="false" menu="false" allowscriptaccess="never" allowfullscreen="true" >':"<img "+(e&&!f?'align="'+e+'"':"")+(f?'style="float:'+f+'"':"")+' width="'+c+'" height="'+d+'" _url="'+a+'" class="edui-faked-music" src="'+b.options.langPath+b.options.lang+'/img/music.png" />'}var b=this;return{outputRule:function(b){utils.each(b.getNodesByTagName("img"),function(b){var c;if("edui-faked-music"==b.getAttr("class")){var d=b.getStyle("float"),e=b.getAttr("align");c=a(b.getAttr("_url"),b.getAttr("width"),b.getAttr("height"),e,d,!0);var f=UE.uNode.createElement(c);b.parentNode.replaceChild(f,b)}})},inputRule:function(b){utils.each(b.getNodesByTagName("embed"),function(b){if("edui-faked-music"==b.getAttr("class")){var c=b.getStyle("float"),d=b.getAttr("align");html=a(b.getAttr("src"),b.getAttr("width"),b.getAttr("height"),d,c,!1);var e=UE.uNode.createElement(html);b.parentNode.replaceChild(e,b)}})},commands:{music:{execCommand:function(b,c){var d=this,e=a(c.url,c.width||400,c.height||95,"none",!1);d.execCommand("inserthtml",e)},queryCommandState:function(){var a=this,b=a.selection.getRange().getClosedNode(),c=b&&"edui-faked-music"==b.className;return c?1:0}}}}}),UE.plugin.register("autoupload",function(){function a(a,b){var c,d,e,f,g,h,i,j,k=b,l=/image\/\w+/i.test(a.type)?"image":"file",m="loading_"+(+new Date).toString(36);if(c=k.getOpt(l+"FieldName"),d=k.getOpt(l+"UrlPrefix"),e=k.getOpt(l+"MaxSize"),f=k.getOpt(l+"AllowFiles"),g=k.getActionUrl(k.getOpt(l+"ActionName")),i=function(a){var b=k.document.getElementById(m);b&&domUtils.remove(b),k.fireEvent("showmessage",{id:m,content:a,type:"error",timeout:4e3})},"image"==l?(h='<img class="loadingclass" id="'+m+'" src="'+k.options.themePath+k.options.theme+'/img/spacer.gif" title="'+(k.getLang("autoupload.loading")||"")+'" >',j=function(a){var b=d+a.url,c=k.document.getElementById(m);c&&(c.setAttribute("src",b),c.setAttribute("_src",b),c.setAttribute("title",a.title||""),c.setAttribute("alt",a.original||""),c.removeAttribute("id"),domUtils.removeClasses(c,"loadingclass"))}):(h='<p><img class="loadingclass" id="'+m+'" src="'+k.options.themePath+k.options.theme+'/img/spacer.gif" title="'+(k.getLang("autoupload.loading")||"")+'" ></p>',j=function(a){var b=d+a.url,c=k.document.getElementById(m),e=k.selection.getRange(),f=e.createBookmark();e.selectNode(c).select(),k.execCommand("insertfile",{url:b}),e.moveToBookmark(f).select()}),k.execCommand("inserthtml",h),!k.getOpt(l+"ActionName"))return void i(k.getLang("autoupload.errorLoadConfig"));if(a.size>e)return void i(k.getLang("autoupload.exceedSizeError"));var n=a.name?a.name.substr(a.name.lastIndexOf(".")):"";if(n&&"image"!=l||f&&(f.join("")+".").indexOf(n.toLowerCase()+".")==-1)return void i(k.getLang("autoupload.exceedTypeError"));var o=new XMLHttpRequest,p=new FormData,q=utils.serializeParam(k.queryCommandValue("serverparam"))||"",r=utils.formatUrl(g+(g.indexOf("?")==-1?"?":"&")+q);p.append(c,a,a.name||"blob."+a.type.substr("image/".length)),p.append("type","ajax"),o.open("post",r,!0),o.setRequestHeader("X-Requested-With","XMLHttpRequest"),o.addEventListener("load",function(a){try{var b=new Function("return "+utils.trim(a.target.response))();"SUCCESS"==b.state&&b.url?j(b):i(b.state)}catch(c){i(k.getLang("autoupload.loadError"))}}),o.send(p)}function b(a){return a.clipboardData&&a.clipboardData.items&&1==a.clipboardData.items.length&&/^image\//.test(a.clipboardData.items[0].type)?a.clipboardData.items:null}function c(a){return a.dataTransfer&&a.dataTransfer.files?a.dataTransfer.files:null}return{outputRule:function(a){utils.each(a.getNodesByTagName("img"),function(a){/\b(loaderrorclass)|(bloaderrorclass)\b/.test(a.getAttr("class"))&&a.parentNode.removeChild(a)}),utils.each(a.getNodesByTagName("p"),function(a){/\bloadpara\b/.test(a.getAttr("class"))&&a.parentNode.removeChild(a)})},bindEvents:{ready:function(d){var e=this;window.FormData&&window.FileReader&&(domUtils.on(e.body,"paste drop",function(d){var f,g=!1;if(f="paste"==d.type?b(d):c(d)){for(var h,i=f.length;i--;)h=f[i],h.getAsFile&&(h=h.getAsFile()),h&&h.size>0&&(a(h,e),g=!0);g&&d.preventDefault()}}),domUtils.on(e.body,"dragover",function(a){"Files"==a.dataTransfer.types[0]&&a.preventDefault()}),utils.cssRule("loading",".loadingclass{display:inline-block;cursor:default;background: url('"+this.options.themePath+this.options.theme+"/img/loading.gif') no-repeat center center transparent;border:1px solid #cccccc;margin-left:1px;height: 22px;width: 22px;}\n.loaderrorclass{display:inline-block;cursor:default;background: url('"+this.options.themePath+this.options.theme+"/img/loaderror.png') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;}",this.document))}}}}),UE.plugin.register("autosave",function(){function a(a){var f;if(!(new Date-c<d)){if(!a.hasContents())return void(e&&b.removePreferences(e));c=new Date,a._saveFlag=null,f=b.body.innerHTML,a.fireEvent("beforeautosave",{content:f})!==!1&&(b.setPreferences(e,f),a.fireEvent("afterautosave",{content:f}))}}var b=this,c=new Date,d=20,e=null;return{defaultOptions:{saveInterval:500},bindEvents:{ready:function(){var a="-drafts-data",c=null;c=b.key?b.key+a:(b.container.parentNode.id||"ue-common")+a,e=(location.protocol+location.host+location.pathname).replace(/[.:\/]/g,"_")+c},contentchange:function(){e&&(b._saveFlag&&window.clearTimeout(b._saveFlag),b.options.saveInterval>0?b._saveFlag=window.setTimeout(function(){a(b)},b.options.saveInterval):a(b))}},commands:{clearlocaldata:{execCommand:function(a,c){e&&b.getPreferences(e)&&b.removePreferences(e)},notNeedUndo:!0,ignoreContentChange:!0},getlocaldata:{execCommand:function(a,c){return e?b.getPreferences(e)||"":""},notNeedUndo:!0,ignoreContentChange:!0},drafts:{execCommand:function(a,c){e&&(b.body.innerHTML=b.getPreferences(e)||"<p>"+domUtils.fillHtml+"</p>",b.focus(!0))},queryCommandState:function(){return e?null===b.getPreferences(e)?-1:0:-1},notNeedUndo:!0,ignoreContentChange:!0}}}}),UE.plugin.register("charts",function(){function a(a){var b=null,c=0;if(a.rows.length<2)return!1;if(a.rows[0].cells.length<2)return!1;b=a.rows[0].cells,c=b.length;for(var d,e=0;d=b[e];e++)if("th"!==d.tagName.toLowerCase())return!1;for(var f,e=1;f=a.rows[e];e++){if(f.cells.length!=c)return!1;if("th"!==f.cells[0].tagName.toLowerCase())return!1;for(var d,g=1;d=f.cells[g];g++){var h=utils.trim(d.innerText||d.textContent||"");if(h=h.replace(new RegExp(UE.dom.domUtils.fillChar,"g"),"").replace(/^\s+|\s+$/g,""),!/^\d*\.?\d+$/.test(h))return!1}}return!0}var b=this;return{bindEvents:{chartserror:function(){}},commands:{charts:{execCommand:function(c,d){var e=domUtils.findParentByTagName(this.selection.getRange().startContainer,"table",!0),f=[],g={};if(!e)return!1;if(!a(e))return b.fireEvent("chartserror"),!1;g.title=d.title||"",g.subTitle=d.subTitle||"",g.xTitle=d.xTitle||"",g.yTitle=d.yTitle||"",g.suffix=d.suffix||"",g.tip=d.tip||"",g.dataFormat=d.tableDataFormat||"",g.chartType=d.chartType||0;for(var h in g)g.hasOwnProperty(h)&&f.push(h+":"+g[h]);e.setAttribute("data-chart",f.join(";")),domUtils.addClass(e,"edui-charts-table")},queryCommandState:function(b,c){
var d=domUtils.findParentByTagName(this.selection.getRange().startContainer,"table",!0);return d&&a(d)?0:-1}}},inputRule:function(a){utils.each(a.getNodesByTagName("table"),function(a){void 0!==a.getAttr("data-chart")&&a.setAttr("style")})},outputRule:function(a){utils.each(a.getNodesByTagName("table"),function(a){void 0!==a.getAttr("data-chart")&&a.setAttr("style","display: none;")})}}}),UE.plugin.register("section",function(){function a(a){this.tag="",this.level=-1,this.dom=null,this.nextSection=null,this.previousSection=null,this.parentSection=null,this.startAddress=[],this.endAddress=[],this.children=[]}function b(b){var c=new a;return utils.extend(c,b)}function c(a,b){for(var c=b,d=0;d<a.length;d++){if(!c.childNodes)return null;c=c.childNodes[a[d]]}return c}var d=this;return{bindMultiEvents:{type:"aftersetcontent afterscencerestore",handler:function(){d.fireEvent("updateSections")}},bindEvents:{ready:function(){d.fireEvent("updateSections"),domUtils.on(d.body,"drop paste",function(){d.fireEvent("updateSections")})},afterexeccommand:function(a,b){"paragraph"==b&&d.fireEvent("updateSections")},keyup:function(a,b){var c=this,d=c.selection.getRange();if(1!=d.collapsed)c.fireEvent("updateSections");else{var e=b.keyCode||b.which;13!=e&&8!=e&&46!=e||c.fireEvent("updateSections")}}},commands:{getsections:{execCommand:function(a,c){function d(a){for(var b=0;b<f.length;b++)if(f[b](a))return b;return-1}function e(a,c){for(var f,g,i,k=null,l=a.childNodes,m=0,n=l.length;m<n;m++)if(i=l[m],f=d(i),f>=0){var o=h.selection.getRange().selectNode(i).createAddress(!0).startAddress,p=b({tag:i.tagName,title:i.innerText||i.textContent||"",level:f,dom:i,startAddress:utils.clone(o,[]),endAddress:utils.clone(o,[]),children:[]});for(j.nextSection=p,p.previousSection=j,g=j;f<=g.level;)g=g.parentSection;p.parentSection=g,g.children.push(p),k=j=p}else 1===i.nodeType&&e(i,c),k&&k.endAddress[k.endAddress.length-1]++}for(var f=c||["h1","h2","h3","h4","h5","h6"],g=0;g<f.length;g++)"string"==typeof f[g]?f[g]=function(a){return function(b){return b.tagName==a.toUpperCase()}}(f[g]):"function"!=typeof f[g]&&(f[g]=function(a){return null});var h=this,i=b({level:-1,title:"root"}),j=i;return e(h.body,i),i},notNeedUndo:!0},movesection:{execCommand:function(a,b,d,e){function f(a,b,c){for(var d=!1,e=!1,f=0;f<a.length&&!(f>=c.length);f++){if(c[f]>a[f]){d=!0;break}if(c[f]<a[f])break}for(var f=0;f<b.length&&!(f>=c.length);f++){if(c[f]<a[f]){e=!0;break}if(c[f]>a[f])break}return d&&e}var g,h,i=this;if(b&&d&&d.level!=-1&&(g=e?d.endAddress:d.startAddress,h=c(g,i.body),g&&h&&!f(b.startAddress,b.endAddress,g))){var j,k,l=c(b.startAddress,i.body),m=c(b.endAddress,i.body);if(e)for(j=m;j&&!(domUtils.getPosition(l,j)&domUtils.POSITION_FOLLOWING)&&(k=j.previousSibling,domUtils.insertAfter(h,j),j!=l);)j=k;else for(j=l;j&&!(domUtils.getPosition(j,m)&domUtils.POSITION_FOLLOWING)&&(k=j.nextSibling,h.parentNode.insertBefore(j,h),j!=m);)j=k;i.fireEvent("updateSections")}}},deletesection:{execCommand:function(a,b,c){function d(a){for(var b=e.body,c=0;c<a.length;c++){if(!b.childNodes)return null;b=b.childNodes[a[c]]}return b}var e=this;if(b){var f,g=d(b.startAddress),h=d(b.endAddress),i=g;if(c)domUtils.remove(i);else for(;i&&domUtils.inDoc(h,e.document)&&!(domUtils.getPosition(i,h)&domUtils.POSITION_FOLLOWING);)f=i.nextSibling,domUtils.remove(i),i=f;e.fireEvent("updateSections")}}},selectsection:{execCommand:function(a,b){if(!b&&!b.dom)return!1;var c=this,d=c.selection.getRange(),e={startAddress:utils.clone(b.startAddress,[]),endAddress:utils.clone(b.endAddress,[])};return e.endAddress[e.endAddress.length-1]++,d.moveToAddress(e).select().scrollToView(),!0},notNeedUndo:!0},scrolltosection:{execCommand:function(a,b){if(!b&&!b.dom)return!1;var c=this,d=c.selection.getRange(),e={startAddress:b.startAddress,endAddress:b.endAddress};return e.endAddress[e.endAddress.length-1]++,d.moveToAddress(e).scrollToView(),!0},notNeedUndo:!0}}}}),UE.plugin.register("simpleupload",function(){function a(){var a=b.offsetWidth||20,e=b.offsetHeight||20,f=document.createElement("iframe"),g="display:block;width:"+a+"px;height:"+e+"px;overflow:hidden;border:0;margin:0;padding:0;position:absolute;top:0;left:0;filter:alpha(opacity=0);-moz-opacity:0;-khtml-opacity: 0;opacity: 0;cursor:pointer;";domUtils.on(f,"load",function(){var b,h,i,j=(+new Date).toString(36);h=f.contentDocument||f.contentWindow.document,i=h.body,b=h.createElement("div"),b.innerHTML='<form id="edui_form_'+j+'" target="edui_iframe_'+j+'" method="POST" enctype="multipart/form-data" action="'+c.getOpt("serverUrl")+'" style="'+g+'"><input id="edui_input_'+j+'" type="file" accept="image/*" name="'+c.options.imageFieldName+'" style="'+g+'"></form><iframe id="edui_iframe_'+j+'" name="edui_iframe_'+j+'" style="display:none;width:0;height:0;border:0;margin:0;padding:0;position:absolute;"></iframe>',b.className="edui-"+c.options.theme,b.id=c.ui.id+"_iframeupload",i.style.cssText=g,i.style.width=a+"px",i.style.height=e+"px",i.appendChild(b),i.parentNode&&(i.parentNode.style.width=a+"px",i.parentNode.style.height=a+"px");var k=h.getElementById("edui_form_"+j),l=h.getElementById("edui_input_"+j),m=h.getElementById("edui_iframe_"+j);domUtils.on(l,"change",function(){function a(){try{var e,f,g,h=(m.contentDocument||m.contentWindow.document).body,i=h.innerText||h.textContent||"";f=new Function("return "+i)(),e=c.options.imageUrlPrefix+f.url,"SUCCESS"==f.state&&f.url?(g=c.document.getElementById(d),g.setAttribute("src",e),g.setAttribute("_src",e),g.setAttribute("title",f.title||""),g.setAttribute("alt",f.original||""),g.removeAttribute("id"),domUtils.removeClasses(g,"loadingclass")):b&&b(f.state)}catch(j){b&&b(c.getLang("simpleupload.loadError"))}k.reset(),domUtils.un(m,"load",a)}function b(a){if(d){var b=c.document.getElementById(d);b&&domUtils.remove(b),c.fireEvent("showmessage",{id:d,content:a,type:"error",timeout:4e3})}}if(l.value){var d="loading_"+(+new Date).toString(36),e=utils.serializeParam(c.queryCommandValue("serverparam"))||"",f=c.getActionUrl(c.getOpt("imageActionName")),g=c.getOpt("imageAllowFiles");if(c.focus(),c.execCommand("inserthtml",'<img class="loadingclass" id="'+d+'" src="'+c.options.themePath+c.options.theme+'/img/spacer.gif" title="'+(c.getLang("simpleupload.loading")||"")+'" >'),!c.getOpt("imageActionName"))return void errorHandler(c.getLang("autoupload.errorLoadConfig"));var h=l.value,i=h?h.substr(h.lastIndexOf(".")):"";if(!i||g&&(g.join("")+".").indexOf(i.toLowerCase()+".")==-1)return void b(c.getLang("simpleupload.exceedTypeError"));domUtils.on(m,"load",a),k.action=utils.formatUrl(f+(f.indexOf("?")==-1?"?":"&")+e),k.submit()}});var n;c.addListener("selectionchange",function(){clearTimeout(n),n=setTimeout(function(){var a=c.queryCommandState("simpleupload");a==-1?l.disabled="disabled":l.disabled=!1},400)}),d=!0}),f.style.cssText=g,b.appendChild(f)}var b,c=this,d=!1;return{bindEvents:{ready:function(){utils.cssRule("loading",".loadingclass{display:inline-block;cursor:default;background: url('"+this.options.themePath+this.options.theme+"/img/loading.gif') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;}\n.loaderrorclass{display:inline-block;cursor:default;background: url('"+this.options.themePath+this.options.theme+"/img/loaderror.png') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;}",this.document)},simpleuploadbtnready:function(d,e){b=e,c.afterConfigReady(a)}},outputRule:function(a){utils.each(a.getNodesByTagName("img"),function(a){/\b(loaderrorclass)|(bloaderrorclass)\b/.test(a.getAttr("class"))&&a.parentNode.removeChild(a)})},commands:{simpleupload:{queryCommandState:function(){return d?0:-1}}}}}),UE.plugin.register("serverparam",function(){var a={};return{commands:{serverparam:{execCommand:function(b,c,d){void 0===c||null===c?a={}:utils.isString(c)?void 0===d||null===d?delete a[c]:a[c]=d:utils.isObject(c)?utils.extend(a,c,!0):utils.isFunction(c)&&utils.extend(a,c(),!0)},queryCommandValue:function(){return a||{}}}}}}),UE.plugin.register("insertfile",function(){function a(a){var b=a.substr(a.lastIndexOf(".")+1).toLowerCase(),c={rar:"icon_rar.gif",zip:"icon_rar.gif",tar:"icon_rar.gif",gz:"icon_rar.gif",bz2:"icon_rar.gif",doc:"icon_doc.gif",docx:"icon_doc.gif",pdf:"icon_pdf.gif",mp3:"icon_mp3.gif",xls:"icon_xls.gif",chm:"icon_chm.gif",ppt:"icon_ppt.gif",pptx:"icon_ppt.gif",avi:"icon_mv.gif",rmvb:"icon_mv.gif",wmv:"icon_mv.gif",flv:"icon_mv.gif",swf:"icon_mv.gif",rm:"icon_mv.gif",exe:"icon_exe.gif",psd:"icon_psd.gif",txt:"icon_txt.gif",jpg:"icon_jpg.gif",png:"icon_jpg.gif",jpeg:"icon_jpg.gif",gif:"icon_jpg.gif",ico:"icon_jpg.gif",bmp:"icon_jpg.gif"};return c[b]?c[b]:c.txt}var b=this;return{commands:{insertfile:{execCommand:function(c,d){d=utils.isArray(d)?d:[d];var e,f,g,h,i="",j=b.getOpt("UEDITOR_HOME_URL"),k=j+("/"==j.substr(j.length-1)?"":"/")+"dialogs/attachment/fileTypeImages/";for(e=0;e<d.length;e++)f=d[e],g=k+a(f.url),h=f.title||f.url.substr(f.url.lastIndexOf("/")+1),i+='<p style="line-height: 16px;"><img style="vertical-align: middle; margin-right: 2px;" src="'+g+'" _src="'+g+'" /><a style="font-size:12px; color:#0066cc;" href="'+f.url+'" title="'+h+'">'+h+"</a></p>";b.execCommand("insertHtml",i)}}}}}),UE.plugins.xssFilter=function(){function a(a){var b=a.tagName,d=a.attrs;return c.hasOwnProperty(b)?void UE.utils.each(d,function(d,e){c[b].indexOf(e)===-1&&a.setAttr(e)}):(a.parentNode.removeChild(a),!1)}var b=UEDITOR_CONFIG,c=b.whitList;c&&b.xssFilterRules&&(this.options.filterRules=function(){var b={};return UE.utils.each(c,function(c,d){b[d]=function(b){return a(b)}}),b}());var d=[];UE.utils.each(c,function(a,b){d.push(b)}),c&&b.inputXssFilter&&this.addInputRule(function(b){b.traversal(function(b){return"element"===b.type&&void a(b)})}),c&&b.outputXssFilter&&this.addOutputRule(function(b){b.traversal(function(b){return"element"===b.type&&void a(b)})})};var baidu=baidu||{};baidu.editor=baidu.editor||{},UE.ui=baidu.editor.ui={},function(){function a(){var a=document.getElementById("edui_fixedlayer");i.setViewportOffset(a,{left:0,top:0})}function b(b){d.on(window,"scroll",a),d.on(window,"resize",baidu.editor.utils.defer(a,0,!0))}var c=baidu.editor.browser,d=baidu.editor.dom.domUtils,e="$EDITORUI",f=window[e]={},g="ID"+e,h=0,i=baidu.editor.ui.uiUtils={uid:function(a){return a?a[g]||(a[g]=++h):++h},hook:function(a,b){var c;return a&&a._callbacks?c=a:(c=function(){var b;a&&(b=a.apply(this,arguments));for(var d=c._callbacks,e=d.length;e--;){var f=d[e].apply(this,arguments);void 0===b&&(b=f)}return b},c._callbacks=[]),c._callbacks.push(b),c},createElementByHtml:function(a){var b=document.createElement("div");return b.innerHTML=a,b=b.firstChild,b.parentNode.removeChild(b),b},getViewportElement:function(){return c.ie&&c.quirks?document.body:document.documentElement},getClientRect:function(a){var b;try{b=a.getBoundingClientRect()}catch(c){b={left:0,top:0,height:0,width:0}}for(var e,f={left:Math.round(b.left),top:Math.round(b.top),height:Math.round(b.bottom-b.top),width:Math.round(b.right-b.left)};(e=a.ownerDocument)!==document&&(a=d.getWindow(e).frameElement);)b=a.getBoundingClientRect(),f.left+=b.left,f.top+=b.top;return f.bottom=f.top+f.height,f.right=f.left+f.width,f},getViewportRect:function(){var a=i.getViewportElement(),b=0|(window.innerWidth||a.clientWidth),c=0|(window.innerHeight||a.clientHeight);return{left:0,top:0,height:c,width:b,bottom:c,right:b}},setViewportOffset:function(a,b){var c=i.getFixedLayer();a.parentNode===c?(a.style.left=b.left+"px",a.style.top=b.top+"px"):d.setViewportOffset(a,b)},getEventOffset:function(a){var b=a.target||a.srcElement,c=i.getClientRect(b),d=i.getViewportOffsetByEvent(a);return{left:d.left-c.left,top:d.top-c.top}},getViewportOffsetByEvent:function(a){var b=a.target||a.srcElement,c=d.getWindow(b).frameElement,e={left:a.clientX,top:a.clientY};if(c&&b.ownerDocument!==document){var f=i.getClientRect(c);e.left+=f.left,e.top+=f.top}return e},setGlobal:function(a,b){return f[a]=b,e+'["'+a+'"]'},unsetGlobal:function(a){delete f[a]},copyAttributes:function(a,b){for(var e=b.attributes,f=e.length;f--;){var g=e[f];"style"==g.nodeName||"class"==g.nodeName||c.ie&&!g.specified||a.setAttribute(g.nodeName,g.nodeValue)}b.className&&d.addClass(a,b.className),b.style.cssText&&(a.style.cssText+=";"+b.style.cssText)},removeStyle:function(a,b){if(a.style.removeProperty)a.style.removeProperty(b);else{if(!a.style.removeAttribute)throw"";a.style.removeAttribute(b)}},contains:function(a,b){return a&&b&&a!==b&&(a.contains?a.contains(b):16&a.compareDocumentPosition(b))},startDrag:function(a,b,c){function d(a){var c=a.clientX-g,d=a.clientY-h;b.ondragmove(c,d,a),a.stopPropagation?a.stopPropagation():a.cancelBubble=!0}function e(a){c.removeEventListener("mousemove",d,!0),c.removeEventListener("mouseup",e,!0),window.removeEventListener("mouseup",e,!0),b.ondragstop()}function f(){i.releaseCapture(),i.detachEvent("onmousemove",d),i.detachEvent("onmouseup",f),i.detachEvent("onlosecaptrue",f),b.ondragstop()}var c=c||document,g=a.clientX,h=a.clientY;if(c.addEventListener)c.addEventListener("mousemove",d,!0),c.addEventListener("mouseup",e,!0),window.addEventListener("mouseup",e,!0),a.preventDefault();else{var i=a.srcElement;i.setCapture(),i.attachEvent("onmousemove",d),i.attachEvent("onmouseup",f),i.attachEvent("onlosecaptrue",f),a.returnValue=!1}b.ondragstart()},getFixedLayer:function(){var d=document.getElementById("edui_fixedlayer");return null==d&&(d=document.createElement("div"),d.id="edui_fixedlayer",document.body.appendChild(d),c.ie&&c.version<=8?(d.style.position="absolute",b(),setTimeout(a)):d.style.position="fixed",d.style.left="0",d.style.top="0",d.style.width="0",d.style.height="0"),d},makeUnselectable:function(a){if(c.opera||c.ie&&c.version<9){if(a.unselectable="on",a.hasChildNodes())for(var b=0;b<a.childNodes.length;b++)1==a.childNodes[b].nodeType&&i.makeUnselectable(a.childNodes[b])}else void 0!==a.style.MozUserSelect?a.style.MozUserSelect="none":void 0!==a.style.WebkitUserSelect?a.style.WebkitUserSelect="none":void 0!==a.style.KhtmlUserSelect&&(a.style.KhtmlUserSelect="none")}}}(),function(){var a=baidu.editor.utils,b=baidu.editor.ui.uiUtils,c=baidu.editor.EventBase,d=baidu.editor.ui.UIBase=function(){};d.prototype={className:"",uiName:"",initOptions:function(a){var c=this;for(var d in a)c[d]=a[d];this.id=this.id||"edui"+b.uid()},initUIBase:function(){this._globalKey=a.unhtml(b.setGlobal(this.id,this))},render:function(a){for(var c,d=this.renderHtml(),e=b.createElementByHtml(d),f=domUtils.getElementsByTagName(e,"*"),g="edui-"+(this.theme||this.editor.options.theme),h=document.getElementById("edui_fixedlayer"),i=0;c=f[i++];)domUtils.addClass(c,g);domUtils.addClass(e,g),h&&(h.className="",domUtils.addClass(h,g));var j=this.getDom();null!=j?(j.parentNode.replaceChild(e,j),b.copyAttributes(e,j)):("string"==typeof a&&(a=document.getElementById(a)),a=a||b.getFixedLayer(),domUtils.addClass(a,g),a.appendChild(e)),this.postRender()},getDom:function(a){return a?document.getElementById(this.id+"_"+a):document.getElementById(this.id)},postRender:function(){this.fireEvent("postrender")},getHtmlTpl:function(){return""},formatHtml:function(a){var b="edui-"+this.uiName;return a.replace(/##/g,this.id).replace(/%%-/g,this.uiName?b+"-":"").replace(/%%/g,(this.uiName?b:"")+" "+this.className).replace(/\$\$/g,this._globalKey)},renderHtml:function(){return this.formatHtml(this.getHtmlTpl())},dispose:function(){var a=this.getDom();a&&baidu.editor.dom.domUtils.remove(a),b.unsetGlobal(this.id)}},a.inherits(d,c)}(),function(){var a=baidu.editor.utils,b=baidu.editor.ui.UIBase,c=baidu.editor.ui.Separator=function(a){this.initOptions(a),this.initSeparator()};c.prototype={uiName:"separator",initSeparator:function(){this.initUIBase()},getHtmlTpl:function(){return'<div id="##" class="edui-box %%"></div>'}},a.inherits(c,b)}(),function(){var a=baidu.editor.utils,b=baidu.editor.dom.domUtils,c=baidu.editor.ui.UIBase,d=baidu.editor.ui.uiUtils,e=baidu.editor.ui.Mask=function(a){this.initOptions(a),this.initUIBase()};e.prototype={getHtmlTpl:function(){return'<div id="##" class="edui-mask %%" onclick="return $$._onClick(event, this);" onmousedown="return $$._onMouseDown(event, this);"></div>'},postRender:function(){var a=this;b.on(window,"resize",function(){setTimeout(function(){a.isHidden()||a._fill()})})},show:function(a){this._fill(),this.getDom().style.display="",this.getDom().style.zIndex=a},hide:function(){this.getDom().style.display="none",this.getDom().style.zIndex=""},isHidden:function(){return"none"==this.getDom().style.display},_onMouseDown:function(){return!1},_onClick:function(a,b){this.fireEvent("click",a,b)},_fill:function(){var a=this.getDom(),b=d.getViewportRect();a.style.width=b.width+"px",a.style.height=b.height+"px"}},a.inherits(e,c)}(),function(){function a(a,b){for(var c=0;c<g.length;c++){var d=g[c];if(!d.isHidden()&&d.queryAutoHide(b)!==!1){if(a&&/scroll/gi.test(a.type)&&"edui-wordpastepop"==d.className)return;d.hide()}}g.length&&d.editor.fireEvent("afterhidepop")}var b=baidu.editor.utils,c=baidu.editor.ui.uiUtils,d=baidu.editor.dom.domUtils,e=baidu.editor.ui.UIBase,f=baidu.editor.ui.Popup=function(a){this.initOptions(a),this.initPopup()},g=[];f.postHide=a;var h=["edui-anchor-topleft","edui-anchor-topright","edui-anchor-bottomleft","edui-anchor-bottomright"];f.prototype={SHADOW_RADIUS:5,content:null,_hidden:!1,autoRender:!0,canSideLeft:!0,canSideUp:!0,initPopup:function(){this.initUIBase(),g.push(this)},getHtmlTpl:function(){return'<div id="##" class="edui-popup %%" onmousedown="return false;"> <div id="##_body" class="edui-popup-body"> <iframe style="position:absolute;z-index:-1;left:0;top:0;background-color: transparent;" frameborder="0" width="100%" height="100%" src="about:blank"></iframe> <div class="edui-shadow"></div> <div id="##_content" class="edui-popup-content">'+this.getContentHtmlTpl()+" </div> </div></div>"},getContentHtmlTpl:function(){return this.content?"string"==typeof this.content?this.content:this.content.renderHtml():""},_UIBase_postRender:e.prototype.postRender,postRender:function(){if(this.content instanceof e&&this.content.postRender(),this.captureWheel&&!this.captured){this.captured=!0;var a=(document.documentElement.clientHeight||document.body.clientHeight)-80,b=this.getDom().offsetHeight,f=c.getClientRect(this.combox.getDom()).top,g=this.getDom("content"),h=this.getDom("body").getElementsByTagName("iframe"),i=this;for(h.length&&(h=h[0]);f+b>a;)b-=30;g.style.height=b+"px",h&&(h.style.height=b+"px"),window.XMLHttpRequest?d.on(g,"onmousewheel"in document.body?"mousewheel":"DOMMouseScroll",function(a){a.preventDefault?a.preventDefault():a.returnValue=!1,a.wheelDelta?g.scrollTop-=a.wheelDelta/120*60:g.scrollTop-=a.detail/-3*60}):d.on(this.getDom(),"mousewheel",function(a){a.returnValue=!1,i.getDom("content").scrollTop-=a.wheelDelta/120*60})}this.fireEvent("postRenderAfter"),this.hide(!0),this._UIBase_postRender()},_doAutoRender:function(){!this.getDom()&&this.autoRender&&this.render()},mesureSize:function(){var a=this.getDom("content");return c.getClientRect(a)},fitSize:function(){if(this.captureWheel&&this.sized)return this.__size;this.sized=!0;var a=this.getDom("body");a.style.width="",a.style.height="";var b=this.mesureSize();if(this.captureWheel){a.style.width=-(-20-b.width)+"px";var c=parseInt(this.getDom("content").style.height,10);!window.isNaN(c)&&(b.height=c)}else a.style.width=b.width+"px";return a.style.height=b.height+"px",this.__size=b,this.captureWheel&&(this.getDom("content").style.overflow="auto"),b},showAnchor:function(a,b){this.showAnchorRect(c.getClientRect(a),b)},showAnchorRect:function(a,b,e){this._doAutoRender();var f=c.getViewportRect();this.getDom().style.visibility="hidden",this._show();var g,i,j,k,l=this.fitSize();b?(g=this.canSideLeft&&a.right+l.width>f.right&&a.left>l.width,i=this.canSideUp&&a.top+l.height>f.bottom&&a.bottom>l.height,j=g?a.left-l.width:a.right,k=i?a.bottom-l.height:a.top):(g=this.canSideLeft&&a.right+l.width>f.right&&a.left>l.width,i=this.canSideUp&&a.top+l.height>f.bottom&&a.bottom>l.height,j=g?a.right-l.width:a.left,k=i?a.top-l.height:a.bottom);var m=this.getDom();c.setViewportOffset(m,{left:j,top:k}),d.removeClasses(m,h),m.className+=" "+h[2*(i?1:0)+(g?1:0)],this.editor&&(m.style.zIndex=1*this.editor.container.style.zIndex+10,baidu.editor.ui.uiUtils.getFixedLayer().style.zIndex=m.style.zIndex-1),this.getDom().style.visibility="visible"},showAt:function(a){var b=a.left,c=a.top,d={left:b,top:c,right:b,bottom:c,height:0,width:0};this.showAnchorRect(d,!1,!0)},_show:function(){if(this._hidden){var a=this.getDom();a.style.display="",this._hidden=!1,this.fireEvent("show")}},isHidden:function(){return this._hidden},show:function(){this._doAutoRender(),this._show()},hide:function(a){!this._hidden&&this.getDom()&&(this.getDom().style.display="none",this._hidden=!0,a||this.fireEvent("hide"))},queryAutoHide:function(a){return!a||!c.contains(this.getDom(),a)}},b.inherits(f,e),d.on(document,"mousedown",function(b){var c=b.target||b.srcElement;a(b,c)}),d.on(window,"scroll",function(b,c){a(b,c)})}(),function(){function a(a,b){for(var c='<div id="##" class="edui-colorpicker %%"><div class="edui-colorpicker-topbar edui-clearfix"><div unselectable="on" id="##_preview" class="edui-colorpicker-preview"></div><div unselectable="on" class="edui-colorpicker-nocolor" onclick="$$._onPickNoColor(event, this);">'+a+'</div></div><table class="edui-box" style="border-collapse: collapse;" onmouseover="$$._onTableOver(event, this);" onmouseout="$$._onTableOut(event, this);" onclick="return $$._onTableClick(event, this);" cellspacing="0" cellpadding="0"><tr style="border-bottom: 1px solid #ddd;font-size: 13px;line-height: 25px;color:#39C;padding-top: 2px"><td colspan="10">'+b.getLang("themeColor")+'</td> </tr><tr class="edui-colorpicker-tablefirstrow" >',d=0;d<e.length;d++)d&&d%10===0&&(c+="</tr>"+(60==d?'<tr style="border-bottom: 1px solid #ddd;font-size: 13px;line-height: 25px;color:#39C;"><td colspan="10">'+b.getLang("standardColor")+"</td></tr>":"")+"<tr"+(60==d?' class="edui-colorpicker-tablefirstrow"':"")+">"),c+=d<70?'<td style="padding: 0 2px;"><a hidefocus title="'+e[d]+'" onclick="return false;" href="javascript:" unselectable="on" class="edui-box edui-colorpicker-colorcell" data-color="#'+e[d]+'" style="background-color:#'+e[d]+";border:solid #ccc;"+(d<10||d>=60?"border-width:1px;":d>=10&&d<20?"border-width:1px 1px 0 1px;":"border-width:0 1px 0 1px;")+'"></a></td>':"";return c+="</tr></table></div>"}var b=baidu.editor.utils,c=baidu.editor.ui.UIBase,d=baidu.editor.ui.ColorPicker=function(a){this.initOptions(a),this.noColorText=this.noColorText||this.editor.getLang("clearColor"),this.initUIBase()};d.prototype={getHtmlTpl:function(){return a(this.noColorText,this.editor)},_onTableClick:function(a){var b=a.target||a.srcElement,c=b.getAttribute("data-color");c&&this.fireEvent("pickcolor",c)},_onTableOver:function(a){var b=a.target||a.srcElement,c=b.getAttribute("data-color");c&&(this.getDom("preview").style.backgroundColor=c)},_onTableOut:function(){this.getDom("preview").style.backgroundColor=""},_onPickNoColor:function(){this.fireEvent("picknocolor")}},b.inherits(d,c);var e="ffffff,000000,eeece1,1f497d,4f81bd,c0504d,9bbb59,8064a2,4bacc6,f79646,f2f2f2,7f7f7f,ddd9c3,c6d9f0,dbe5f1,f2dcdb,ebf1dd,e5e0ec,dbeef3,fdeada,d8d8d8,595959,c4bd97,8db3e2,b8cce4,e5b9b7,d7e3bc,ccc1d9,b7dde8,fbd5b5,bfbfbf,3f3f3f,938953,548dd4,95b3d7,d99694,c3d69b,b2a2c7,92cddc,fac08f,a5a5a5,262626,494429,17365d,366092,953734,76923c,5f497a,31859b,e36c09,7f7f7f,0c0c0c,1d1b10,0f243e,244061,632423,4f6128,3f3151,205867,974806,c00000,ff0000,ffc000,ffff00,92d050,00b050,00b0f0,0070c0,002060,7030a0,".split(",")}(),function(){var a=baidu.editor.utils,b=baidu.editor.ui.uiUtils,c=baidu.editor.ui.UIBase,d=baidu.editor.ui.TablePicker=function(a){this.initOptions(a),this.initTablePicker()};d.prototype={defaultNumRows:10,defaultNumCols:10,maxNumRows:20,maxNumCols:20,numRows:10,numCols:10,lengthOfCellSide:22,initTablePicker:function(){this.initUIBase()},getHtmlTpl:function(){return'<div id="##" class="edui-tablepicker %%"><div class="edui-tablepicker-body"><div class="edui-infoarea"><span id="##_label" class="edui-label"></span></div><div class="edui-pickarea" onmousemove="$$._onMouseMove(event, this);" onmouseover="$$._onMouseOver(event, this);" onmouseout="$$._onMouseOut(event, this);" onclick="$$._onClick(event, this);"><div id="##_overlay" class="edui-overlay"></div></div></div></div>'},_UIBase_render:c.prototype.render,render:function(a){this._UIBase_render(a),this.getDom("label").innerHTML="0"+this.editor.getLang("t_row")+" x 0"+this.editor.getLang("t_col")},_track:function(a,b){var c=this.getDom("overlay").style,d=this.lengthOfCellSide;c.width=a*d+"px",c.height=b*d+"px";var e=this.getDom("label");e.innerHTML=a+this.editor.getLang("t_col")+" x "+b+this.editor.getLang("t_row"),this.numCols=a,this.numRows=b},_onMouseOver:function(a,c){var d=a.relatedTarget||a.fromElement;b.contains(c,d)||c===d||(this.getDom("label").innerHTML="0"+this.editor.getLang("t_col")+" x 0"+this.editor.getLang("t_row"),this.getDom("overlay").style.visibility="")},_onMouseOut:function(a,c){var d=a.relatedTarget||a.toElement;b.contains(c,d)||c===d||(this.getDom("label").innerHTML="0"+this.editor.getLang("t_col")+" x 0"+this.editor.getLang("t_row"),this.getDom("overlay").style.visibility="hidden")},_onMouseMove:function(a,c){var d=(this.getDom("overlay").style,b.getEventOffset(a)),e=this.lengthOfCellSide,f=Math.ceil(d.left/e),g=Math.ceil(d.top/e);this._track(f,g)},_onClick:function(){this.fireEvent("picktable",this.numCols,this.numRows)}},a.inherits(d,c)}(),function(){var a=baidu.editor.browser,b=baidu.editor.dom.domUtils,c=baidu.editor.ui.uiUtils,d='onmousedown="$$.Stateful_onMouseDown(event, this);" onmouseup="$$.Stateful_onMouseUp(event, this);"'+(a.ie?' onmouseenter="$$.Stateful_onMouseEnter(event, this);" onmouseleave="$$.Stateful_onMouseLeave(event, this);"':' onmouseover="$$.Stateful_onMouseOver(event, this);" onmouseout="$$.Stateful_onMouseOut(event, this);"');baidu.editor.ui.Stateful={alwalysHoverable:!1,target:null,Stateful_init:function(){this._Stateful_dGetHtmlTpl=this.getHtmlTpl,this.getHtmlTpl=this.Stateful_getHtmlTpl},Stateful_getHtmlTpl:function(){var a=this._Stateful_dGetHtmlTpl();return a.replace(/stateful/g,function(){return d})},Stateful_onMouseEnter:function(a,b){this.target=b,this.isDisabled()&&!this.alwalysHoverable||(this.addState("hover"),this.fireEvent("over"))},Stateful_onMouseLeave:function(a,b){this.isDisabled()&&!this.alwalysHoverable||(this.removeState("hover"),this.removeState("active"),this.fireEvent("out"))},Stateful_onMouseOver:function(a,b){var d=a.relatedTarget;c.contains(b,d)||b===d||this.Stateful_onMouseEnter(a,b)},Stateful_onMouseOut:function(a,b){var d=a.relatedTarget;c.contains(b,d)||b===d||this.Stateful_onMouseLeave(a,b)},Stateful_onMouseDown:function(a,b){this.isDisabled()||this.addState("active")},Stateful_onMouseUp:function(a,b){this.isDisabled()||this.removeState("active")},Stateful_postRender:function(){this.disabled&&!this.hasState("disabled")&&this.addState("disabled")},hasState:function(a){return b.hasClass(this.getStateDom(),"edui-state-"+a)},addState:function(a){this.hasState(a)||(this.getStateDom().className+=" edui-state-"+a)},removeState:function(a){this.hasState(a)&&b.removeClasses(this.getStateDom(),["edui-state-"+a])},getStateDom:function(){return this.getDom("state")},isChecked:function(){return this.hasState("checked")},setChecked:function(a){!this.isDisabled()&&a?this.addState("checked"):this.removeState("checked")},isDisabled:function(){return this.hasState("disabled")},setDisabled:function(a){a?(this.removeState("hover"),this.removeState("checked"),this.removeState("active"),this.addState("disabled")):this.removeState("disabled")}}}(),function(){var a=baidu.editor.utils,b=baidu.editor.ui.UIBase,c=baidu.editor.ui.Stateful,d=baidu.editor.ui.Button=function(a){if(a.name){var b=a.name,c=a.cssRules;a.className||(a.className="edui-for-"+b),a.cssRules=".edui-default .edui-for-"+b+" .edui-icon {"+c+"}"}this.initOptions(a),this.initButton()};d.prototype={uiName:"button",label:"",title:"",showIcon:!0,showText:!0,cssRules:"",initButton:function(){this.initUIBase(),this.Stateful_init(),this.cssRules&&a.cssRule("edui-customize-"+this.name+"-style",this.cssRules)},getHtmlTpl:function(){return'<div id="##" class="edui-box %%"><div id="##_state" stateful><div class="%%-wrap"><div id="##_body" unselectable="on" '+(this.title?'title="'+this.title+'"':"")+' class="%%-body" onmousedown="return $$._onMouseDown(event, this);" onclick="return $$._onClick(event, this);">'+(this.showIcon?'<div class="edui-box edui-icon"></div>':"")+(this.showText?'<div class="edui-box edui-label">'+this.label+"</div>":"")+"</div></div></div></div>"},postRender:function(){this.Stateful_postRender(),this.setDisabled(this.disabled)},_onMouseDown:function(a){var b=a.target||a.srcElement,c=b&&b.tagName&&b.tagName.toLowerCase();if("input"==c||"object"==c||"object"==c)return!1},_onClick:function(){this.isDisabled()||this.fireEvent("click")},setTitle:function(a){var b=this.getDom("label");b.innerHTML=a}},a.inherits(d,b),a.extend(d.prototype,c)}(),function(){var a=baidu.editor.utils,b=baidu.editor.ui.uiUtils,c=(baidu.editor.dom.domUtils,baidu.editor.ui.UIBase),d=baidu.editor.ui.Stateful,e=baidu.editor.ui.SplitButton=function(a){this.initOptions(a),this.initSplitButton()};e.prototype={popup:null,uiName:"splitbutton",title:"",initSplitButton:function(){this.initUIBase(),this.Stateful_init();if(null!=this.popup){var a=this.popup;this.popup=null,this.setPopup(a)}},_UIBase_postRender:c.prototype.postRender,postRender:function(){this.Stateful_postRender(),this._UIBase_postRender()},setPopup:function(c){this.popup!==c&&(null!=this.popup&&this.popup.dispose(),c.addListener("show",a.bind(this._onPopupShow,this)),c.addListener("hide",a.bind(this._onPopupHide,this)),c.addListener("postrender",a.bind(function(){c.getDom("body").appendChild(b.createElementByHtml('<div id="'+this.popup.id+'_bordereraser" class="edui-bordereraser edui-background" style="width:'+(b.getClientRect(this.getDom()).width+20)+'px"></div>')),c.getDom().className+=" "+this.className},this)),this.popup=c)},_onPopupShow:function(){this.addState("opened")},_onPopupHide:function(){this.removeState("opened")},getHtmlTpl:function(){return'<div id="##" class="edui-box %%"><div '+(this.title?'title="'+this.title+'"':"")+' id="##_state" stateful><div class="%%-body"><div id="##_button_body" class="edui-box edui-button-body" onclick="$$._onButtonClick(event, this);"><div class="edui-box edui-icon"></div></div><div class="edui-box edui-splitborder"></div><div class="edui-box edui-arrow" onclick="$$._onArrowClick();"></div></div></div></div>'},showPopup:function(){var a=b.getClientRect(this.getDom());a.top-=this.popup.SHADOW_RADIUS,a.height+=this.popup.SHADOW_RADIUS,this.popup.showAnchorRect(a)},_onArrowClick:function(a,b){this.isDisabled()||this.showPopup()},_onButtonClick:function(){this.isDisabled()||this.fireEvent("buttonclick")}},a.inherits(e,c),a.extend(e.prototype,d,!0)}(),function(){var a=baidu.editor.utils,b=baidu.editor.ui.uiUtils,c=baidu.editor.ui.ColorPicker,d=baidu.editor.ui.Popup,e=baidu.editor.ui.SplitButton,f=baidu.editor.ui.ColorButton=function(a){this.initOptions(a),this.initColorButton()};f.prototype={initColorButton:function(){var a=this;this.popup=new d({content:new c({noColorText:a.editor.getLang("clearColor"),editor:a.editor,onpickcolor:function(b,c){a._onPickColor(c)},onpicknocolor:function(b,c){a._onPickNoColor(c)}}),editor:a.editor}),this.initSplitButton()},_SplitButton_postRender:e.prototype.postRender,postRender:function(){this._SplitButton_postRender(),this.getDom("button_body").appendChild(b.createElementByHtml('<div id="'+this.id+'_colorlump" class="edui-colorlump"></div>')),this.getDom().className+=" edui-colorbutton";
},setColor:function(a){this.getDom("colorlump").style.backgroundColor=a,this.color=a},_onPickColor:function(a){this.fireEvent("pickcolor",a)!==!1&&(this.setColor(a),this.popup.hide())},_onPickNoColor:function(a){this.fireEvent("picknocolor")!==!1&&this.popup.hide()}},a.inherits(f,e)}(),function(){var a=baidu.editor.utils,b=baidu.editor.ui.Popup,c=baidu.editor.ui.TablePicker,d=baidu.editor.ui.SplitButton,e=baidu.editor.ui.TableButton=function(a){this.initOptions(a),this.initTableButton()};e.prototype={initTableButton:function(){var a=this;this.popup=new b({content:new c({editor:a.editor,onpicktable:function(b,c,d){a._onPickTable(c,d)}}),editor:a.editor}),this.initSplitButton()},_onPickTable:function(a,b){this.fireEvent("picktable",a,b)!==!1&&this.popup.hide()}},a.inherits(e,d)}(),function(){var a=baidu.editor.utils,b=baidu.editor.ui.UIBase,c=baidu.editor.ui.AutoTypeSetPicker=function(a){this.initOptions(a),this.initAutoTypeSetPicker()};c.prototype={initAutoTypeSetPicker:function(){this.initUIBase()},getHtmlTpl:function(){var a=this.editor,b=a.options.autotypeset,c=a.getLang("autoTypeSet"),d="textAlignValue"+a.uid,e="imageBlockLineValue"+a.uid,f="symbolConverValue"+a.uid;return'<div id="##" class="edui-autotypesetpicker %%"><div class="edui-autotypesetpicker-body"><table ><tr><td nowrap><input type="checkbox" name="mergeEmptyline" '+(b.mergeEmptyline?"checked":"")+">"+c.mergeLine+'</td><td colspan="2"><input type="checkbox" name="removeEmptyline" '+(b.removeEmptyline?"checked":"")+">"+c.delLine+'</td></tr><tr><td nowrap><input type="checkbox" name="removeClass" '+(b.removeClass?"checked":"")+">"+c.removeFormat+'</td><td colspan="2"><input type="checkbox" name="indent" '+(b.indent?"checked":"")+">"+c.indent+'</td></tr><tr><td nowrap><input type="checkbox" name="textAlign" '+(b.textAlign?"checked":"")+">"+c.alignment+'</td><td colspan="2" id="'+d+'"><input type="radio" name="'+d+'" value="left" '+(b.textAlign&&"left"==b.textAlign?"checked":"")+">"+a.getLang("justifyleft")+'<input type="radio" name="'+d+'" value="center" '+(b.textAlign&&"center"==b.textAlign?"checked":"")+">"+a.getLang("justifycenter")+'<input type="radio" name="'+d+'" value="right" '+(b.textAlign&&"right"==b.textAlign?"checked":"")+">"+a.getLang("justifyright")+'</td></tr><tr><td nowrap><input type="checkbox" name="imageBlockLine" '+(b.imageBlockLine?"checked":"")+">"+c.imageFloat+'</td><td nowrap id="'+e+'"><input type="radio" name="'+e+'" value="none" '+(b.imageBlockLine&&"none"==b.imageBlockLine?"checked":"")+">"+a.getLang("default")+'<input type="radio" name="'+e+'" value="left" '+(b.imageBlockLine&&"left"==b.imageBlockLine?"checked":"")+">"+a.getLang("justifyleft")+'<input type="radio" name="'+e+'" value="center" '+(b.imageBlockLine&&"center"==b.imageBlockLine?"checked":"")+">"+a.getLang("justifycenter")+'<input type="radio" name="'+e+'" value="right" '+(b.imageBlockLine&&"right"==b.imageBlockLine?"checked":"")+">"+a.getLang("justifyright")+'</td></tr><tr><td nowrap><input type="checkbox" name="clearFontSize" '+(b.clearFontSize?"checked":"")+">"+c.removeFontsize+'</td><td colspan="2"><input type="checkbox" name="clearFontFamily" '+(b.clearFontFamily?"checked":"")+">"+c.removeFontFamily+'</td></tr><tr><td nowrap colspan="3"><input type="checkbox" name="removeEmptyNode" '+(b.removeEmptyNode?"checked":"")+">"+c.removeHtml+'</td></tr><tr><td nowrap colspan="3"><input type="checkbox" name="pasteFilter" '+(b.pasteFilter?"checked":"")+">"+c.pasteFilter+'</td></tr><tr><td nowrap><input type="checkbox" name="symbolConver" '+(b.bdc2sb||b.tobdc?"checked":"")+">"+c.symbol+'</td><td id="'+f+'"><input type="radio" name="bdc" value="bdc2sb" '+(b.bdc2sb?"checked":"")+">"+c.bdc2sb+'<input type="radio" name="bdc" value="tobdc" '+(b.tobdc?"checked":"")+">"+c.tobdc+'</td><td nowrap align="right"><button >'+c.run+"</button></td></tr></table></div></div>"},_UIBase_render:b.prototype.render},a.inherits(c,b)}(),function(){function a(a){for(var c,d={},e=a.getDom(),f=a.editor.uid,g=null,h=null,i=domUtils.getElementsByTagName(e,"input"),j=i.length-1;c=i[j--];)if(g=c.getAttribute("type"),"checkbox"==g)if(h=c.getAttribute("name"),d[h]&&delete d[h],c.checked){var k=document.getElementById(h+"Value"+f);if(k){if(/input/gi.test(k.tagName))d[h]=k.value;else for(var l,m=k.getElementsByTagName("input"),n=m.length-1;l=m[n--];)if(l.checked){d[h]=l.value;break}}else d[h]=!0}else d[h]=!1;else d[c.getAttribute("value")]=c.checked;for(var o,p=domUtils.getElementsByTagName(e,"select"),j=0;o=p[j++];){var q=o.getAttribute("name");d[q]=d[q]?o.value:""}b.extend(a.editor.options.autotypeset,d),a.editor.setPreferences("autotypeset",d)}var b=baidu.editor.utils,c=baidu.editor.ui.Popup,d=baidu.editor.ui.AutoTypeSetPicker,e=baidu.editor.ui.SplitButton,f=baidu.editor.ui.AutoTypeSetButton=function(a){this.initOptions(a),this.initAutoTypeSetButton()};f.prototype={initAutoTypeSetButton:function(){var b=this;this.popup=new c({content:new d({editor:b.editor}),editor:b.editor,hide:function(){!this._hidden&&this.getDom()&&(a(this),this.getDom().style.display="none",this._hidden=!0,this.fireEvent("hide"))}});var e=0;this.popup.addListener("postRenderAfter",function(){var c=this;if(!e){var d=this.getDom(),f=d.getElementsByTagName("button")[0];f.onclick=function(){a(c),b.editor.execCommand("autotypeset"),c.hide()},domUtils.on(d,"click",function(d){var e=d.target||d.srcElement,f=b.editor.uid;if(e&&"INPUT"==e.tagName){if("imageBlockLine"==e.name||"textAlign"==e.name||"symbolConver"==e.name)for(var g=e.checked,h=document.getElementById(e.name+"Value"+f),i=h.getElementsByTagName("input"),j={imageBlockLine:"none",textAlign:"left",symbolConver:"tobdc"},k=0;k<i.length;k++)g?i[k].value==j[e.name]&&(i[k].checked="checked"):i[k].checked=!1;if(e.name=="imageBlockLineValue"+f||e.name=="textAlignValue"+f||"bdc"==e.name){var l=e.parentNode.previousSibling.getElementsByTagName("input");l&&(l[0].checked=!0)}a(c)}}),e=1}}),this.initSplitButton()}},b.inherits(f,e)}(),function(){var a=baidu.editor.utils,b=baidu.editor.ui.Popup,c=baidu.editor.ui.Stateful,d=baidu.editor.ui.UIBase,e=baidu.editor.ui.CellAlignPicker=function(a){this.initOptions(a),this.initSelected(),this.initCellAlignPicker()};e.prototype={initSelected:function(){var a={valign:{top:0,middle:1,bottom:2},align:{left:0,center:1,right:2},count:3};this.selected&&(this.selectedIndex=a.valign[this.selected.valign]*a.count+a.align[this.selected.align])},initCellAlignPicker:function(){this.initUIBase(),this.Stateful_init()},getHtmlTpl:function(){for(var a=["left","center","right"],b=9,c=null,d=-1,e=[],f=0;f<b;f++)c=this.selectedIndex===f?' class="edui-cellalign-selected" ':"",d=f%3,0===d&&e.push("<tr>"),e.push('<td index="'+f+'" '+c+' stateful><div class="edui-icon edui-'+a[d]+'"></div></td>'),2===d&&e.push("</tr>");return'<div id="##" class="edui-cellalignpicker %%"><div class="edui-cellalignpicker-body"><table onclick="$$._onClick(event);">'+e.join("")+"</table></div></div>"},getStateDom:function(){return this.target},_onClick:function(a){var c=a.target||a.srcElement;/icon/.test(c.className)&&(this.items[c.parentNode.getAttribute("index")].onclick(),b.postHide(a))},_UIBase_render:d.prototype.render},a.inherits(e,d),a.extend(e.prototype,c,!0)}(),function(){var a=baidu.editor.utils,b=baidu.editor.ui.Stateful,c=baidu.editor.ui.uiUtils,d=baidu.editor.ui.UIBase,e=baidu.editor.ui.PastePicker=function(a){this.initOptions(a),this.initPastePicker()};e.prototype={initPastePicker:function(){this.initUIBase(),this.Stateful_init()},getHtmlTpl:function(){return'<div class="edui-pasteicon" onclick="$$._onClick(this)"></div><div class="edui-pastecontainer"><div class="edui-title">'+this.editor.getLang("pasteOpt")+'</div><div class="edui-button"><div title="'+this.editor.getLang("pasteSourceFormat")+'" onclick="$$.format(false)" stateful><div class="edui-richtxticon"></div></div><div title="'+this.editor.getLang("tagFormat")+'" onclick="$$.format(2)" stateful><div class="edui-tagicon"></div></div><div title="'+this.editor.getLang("pasteTextFormat")+'" onclick="$$.format(true)" stateful><div class="edui-plaintxticon"></div></div></div></div></div>'},getStateDom:function(){return this.target},format:function(a){this.editor.ui._isTransfer=!0,this.editor.fireEvent("pasteTransfer",a)},_onClick:function(a){var b=domUtils.getNextDomNode(a),d=c.getViewportRect().height,e=c.getClientRect(b);e.top+e.height>d?b.style.top=-e.height-a.offsetHeight+"px":b.style.top="",/hidden/gi.test(domUtils.getComputedStyle(b,"visibility"))?(b.style.visibility="visible",domUtils.addClass(a,"edui-state-opened")):(b.style.visibility="hidden",domUtils.removeClasses(a,"edui-state-opened"))},_UIBase_render:d.prototype.render},a.inherits(e,d),a.extend(e.prototype,b,!0)}(),function(){var a=baidu.editor.utils,b=baidu.editor.ui.uiUtils,c=baidu.editor.ui.UIBase,d=baidu.editor.ui.Toolbar=function(a){this.initOptions(a),this.initToolbar()};d.prototype={items:null,initToolbar:function(){this.items=this.items||[],this.initUIBase()},add:function(a,b){void 0===b?this.items.push(a):this.items.splice(b,0,a)},getHtmlTpl:function(){for(var a=[],b=0;b<this.items.length;b++)a[b]=this.items[b].renderHtml();return'<div id="##" class="edui-toolbar %%" onselectstart="return false;" onmousedown="return $$._onMouseDown(event, this);">'+a.join("")+"</div>"},postRender:function(){for(var a=this.getDom(),c=0;c<this.items.length;c++)this.items[c].postRender();b.makeUnselectable(a)},_onMouseDown:function(a){var b=a.target||a.srcElement,c=b&&b.tagName&&b.tagName.toLowerCase();if("input"==c||"object"==c||"object"==c)return!1}},a.inherits(d,c)}(),function(){var a=baidu.editor.utils,b=baidu.editor.dom.domUtils,c=baidu.editor.ui.uiUtils,d=baidu.editor.ui.UIBase,e=baidu.editor.ui.Popup,f=baidu.editor.ui.Stateful,g=baidu.editor.ui.CellAlignPicker,h=baidu.editor.ui.Menu=function(a){this.initOptions(a),this.initMenu()},i={renderHtml:function(){return'<div class="edui-menuitem edui-menuseparator"><div class="edui-menuseparator-inner"></div></div>'},postRender:function(){},queryAutoHide:function(){return!0}};h.prototype={items:null,uiName:"menu",initMenu:function(){this.items=this.items||[],this.initPopup(),this.initItems()},initItems:function(){for(var a=0;a<this.items.length;a++){var b=this.items[a];"-"==b?this.items[a]=this.getSeparator():b instanceof j||(b.editor=this.editor,b.theme=this.editor.options.theme,this.items[a]=this.createItem(b))}},getSeparator:function(){return i},createItem:function(a){return a.menu=this,new j(a)},_Popup_getContentHtmlTpl:e.prototype.getContentHtmlTpl,getContentHtmlTpl:function(){if(0==this.items.length)return this._Popup_getContentHtmlTpl();for(var a=[],b=0;b<this.items.length;b++){var c=this.items[b];a[b]=c.renderHtml()}return'<div class="%%-body">'+a.join("")+"</div>"},_Popup_postRender:e.prototype.postRender,postRender:function(){for(var a=this,d=0;d<this.items.length;d++){var e=this.items[d];e.ownerMenu=this,e.postRender()}b.on(this.getDom(),"mouseover",function(b){b=b||event;var d=b.relatedTarget||b.fromElement,e=a.getDom();c.contains(e,d)||e===d||a.fireEvent("over")}),this._Popup_postRender()},queryAutoHide:function(a){if(a){if(c.contains(this.getDom(),a))return!1;for(var b=0;b<this.items.length;b++){var d=this.items[b];if(d.queryAutoHide(a)===!1)return!1}}},clearItems:function(){for(var a=0;a<this.items.length;a++){var b=this.items[a];clearTimeout(b._showingTimer),clearTimeout(b._closingTimer),b.subMenu&&b.subMenu.destroy()}this.items=[]},destroy:function(){this.getDom()&&b.remove(this.getDom()),this.clearItems()},dispose:function(){this.destroy()}},a.inherits(h,e);var j=baidu.editor.ui.MenuItem=function(a){if(this.initOptions(a),this.initUIBase(),this.Stateful_init(),this.subMenu&&!(this.subMenu instanceof h))if(a.className&&a.className.indexOf("aligntd")!=-1){var c=this;this.subMenu.selected=this.editor.queryCommandValue("cellalignment"),this.subMenu=new e({content:new g(this.subMenu),parentMenu:c,editor:c.editor,destroy:function(){this.getDom()&&b.remove(this.getDom())}}),this.subMenu.addListener("postRenderAfter",function(){b.on(this.getDom(),"mouseover",function(){c.addState("opened")})})}else this.subMenu=new h(this.subMenu)};j.prototype={label:"",subMenu:null,ownerMenu:null,uiName:"menuitem",alwalysHoverable:!0,getHtmlTpl:function(){return'<div id="##" class="%%" stateful onclick="$$._onClick(event, this);"><div class="%%-body">'+this.renderLabelHtml()+"</div></div>"},postRender:function(){var a=this;this.addListener("over",function(){a.ownerMenu.fireEvent("submenuover",a),a.subMenu&&a.delayShowSubMenu()}),this.subMenu&&(this.getDom().className+=" edui-hassubmenu",this.subMenu.render(),this.addListener("out",function(){a.delayHideSubMenu()}),this.subMenu.addListener("over",function(){clearTimeout(a._closingTimer),a._closingTimer=null,a.addState("opened")}),this.ownerMenu.addListener("hide",function(){a.hideSubMenu()}),this.ownerMenu.addListener("submenuover",function(b,c){c!==a&&a.delayHideSubMenu()}),this.subMenu._bakQueryAutoHide=this.subMenu.queryAutoHide,this.subMenu.queryAutoHide=function(b){return(!b||!c.contains(a.getDom(),b))&&this._bakQueryAutoHide(b)}),this.getDom().style.tabIndex="-1",c.makeUnselectable(this.getDom()),this.Stateful_postRender()},delayShowSubMenu:function(){var a=this;a.isDisabled()||(a.addState("opened"),clearTimeout(a._showingTimer),clearTimeout(a._closingTimer),a._closingTimer=null,a._showingTimer=setTimeout(function(){a.showSubMenu()},250))},delayHideSubMenu:function(){var a=this;a.isDisabled()||(a.removeState("opened"),clearTimeout(a._showingTimer),a._closingTimer||(a._closingTimer=setTimeout(function(){a.hasState("opened")||a.hideSubMenu(),a._closingTimer=null},400)))},renderLabelHtml:function(){return'<div class="edui-arrow"></div><div class="edui-box edui-icon"></div><div class="edui-box edui-label %%-label">'+(this.label||"")+"</div>"},getStateDom:function(){return this.getDom()},queryAutoHide:function(a){if(this.subMenu&&this.hasState("opened"))return this.subMenu.queryAutoHide(a)},_onClick:function(a,b){this.hasState("disabled")||this.fireEvent("click",a,b)!==!1&&(this.subMenu?this.showSubMenu():e.postHide(a))},showSubMenu:function(){var a=c.getClientRect(this.getDom());a.right-=5,a.left+=2,a.width-=7,a.top-=4,a.bottom+=4,a.height+=8,this.subMenu.showAnchorRect(a,!0,!0)},hideSubMenu:function(){this.subMenu.hide()}},a.inherits(j,d),a.extend(j.prototype,f,!0)}(),function(){var a=baidu.editor.utils,b=baidu.editor.ui.uiUtils,c=baidu.editor.ui.Menu,d=baidu.editor.ui.SplitButton,e=baidu.editor.ui.Combox=function(a){this.initOptions(a),this.initCombox()};e.prototype={uiName:"combox",onbuttonclick:function(){this.showPopup()},initCombox:function(){var a=this;this.items=this.items||[];for(var b=0;b<this.items.length;b++){var d=this.items[b];d.uiName="listitem",d.index=b,d.onclick=function(){a.selectByIndex(this.index)}}this.popup=new c({items:this.items,uiName:"list",editor:this.editor,captureWheel:!0,combox:this}),this.initSplitButton()},_SplitButton_postRender:d.prototype.postRender,postRender:function(){this._SplitButton_postRender(),this.setLabel(this.label||""),this.setValue(this.initValue||"")},showPopup:function(){var a=b.getClientRect(this.getDom());a.top+=1,a.bottom-=1,a.height-=2,this.popup.showAnchorRect(a)},getValue:function(){return this.value},setValue:function(a){var b=this.indexByValue(a);b!=-1?(this.selectedIndex=b,this.setLabel(this.items[b].label),this.value=this.items[b].value):(this.selectedIndex=-1,this.setLabel(this.getLabelForUnknowValue(a)),this.value=a)},setLabel:function(a){this.getDom("button_body").innerHTML=a,this.label=a},getLabelForUnknowValue:function(a){return a},indexByValue:function(a){for(var b=0;b<this.items.length;b++)if(a==this.items[b].value)return b;return-1},getItem:function(a){return this.items[a]},selectByIndex:function(a){a<this.items.length&&this.fireEvent("select",a)!==!1&&(this.selectedIndex=a,this.value=this.items[a].value,this.setLabel(this.items[a].label))}},a.inherits(e,d)}(),function(){var a,b,c,d=baidu.editor.utils,e=baidu.editor.dom.domUtils,f=baidu.editor.ui.uiUtils,g=baidu.editor.ui.Mask,h=baidu.editor.ui.UIBase,i=baidu.editor.ui.Button,j=baidu.editor.ui.Dialog=function(a){if(a.name){var b=a.name,c=a.cssRules;a.className||(a.className="edui-for-"+b),c&&(a.cssRules=".edui-default .edui-for-"+b+" .edui-dialog-content {"+c+"}")}this.initOptions(d.extend({autoReset:!0,draggable:!0,onok:function(){},oncancel:function(){},onclose:function(a,b){return b?this.onok():this.oncancel()},holdScroll:!1},a)),this.initDialog()};j.prototype={draggable:!1,uiName:"dialog",initDialog:function(){var e=this,f=this.editor.options.theme;if(this.cssRules&&d.cssRule("edui-customize-"+this.name+"-style",this.cssRules),this.initUIBase(),this.modalMask=a||(a=new g({className:"edui-dialog-modalmask",theme:f,onclick:function(){c&&c.close(!1)}})),this.dragMask=b||(b=new g({className:"edui-dialog-dragmask",theme:f})),this.closeButton=new i({className:"edui-dialog-closebutton",title:e.closeDialog,theme:f,onclick:function(){e.close(!1)}}),this.fullscreen&&this.initResizeEvent(),this.buttons)for(var h=0;h<this.buttons.length;h++)this.buttons[h]instanceof i||(this.buttons[h]=new i(d.extend(this.buttons[h],{editor:this.editor},!0)))},initResizeEvent:function(){var a=this;e.on(window,"resize",function(){a._hidden||void 0===a._hidden||(a.__resizeTimer&&window.clearTimeout(a.__resizeTimer),a.__resizeTimer=window.setTimeout(function(){a.__resizeTimer=null;var b=a.getDom(),c=a.getDom("content"),d=UE.ui.uiUtils.getClientRect(b),e=UE.ui.uiUtils.getClientRect(c),g=f.getViewportRect();c.style.width=g.width-d.width+e.width+"px",c.style.height=g.height-d.height+e.height+"px",b.style.width=g.width+"px",b.style.height=g.height+"px",a.fireEvent("resize")},100))})},fitSize:function(){var a=this.getDom("body"),b=this.mesureSize();return a.style.width=b.width+"px",a.style.height=b.height+"px",b},safeSetOffset:function(a){var b=this,c=b.getDom(),d=f.getViewportRect(),e=f.getClientRect(c),g=a.left;g+e.width>d.right&&(g=d.right-e.width);var h=a.top;h+e.height>d.bottom&&(h=d.bottom-e.height),c.style.left=Math.max(g,0)+"px",c.style.top=Math.max(h,0)+"px"},showAtCenter:function(){var a=f.getViewportRect();if(this.fullscreen){var b=this.getDom(),c=this.getDom("content");b.style.display="block";var d=UE.ui.uiUtils.getClientRect(b),g=UE.ui.uiUtils.getClientRect(c);b.style.left="-100000px",c.style.width=a.width-d.width+g.width+"px",c.style.height=a.height-d.height+g.height+"px",b.style.width=a.width+"px",b.style.height=a.height+"px",b.style.left=0,this._originalContext={html:{overflowX:document.documentElement.style.overflowX,overflowY:document.documentElement.style.overflowY},body:{overflowX:document.body.style.overflowX,overflowY:document.body.style.overflowY}},document.documentElement.style.overflowX="hidden",document.documentElement.style.overflowY="hidden",document.body.style.overflowX="hidden",document.body.style.overflowY="hidden"}else{this.getDom().style.display="";var h=this.fitSize(),i=0|this.getDom("titlebar").offsetHeight,j=a.width/2-h.width/2,k=a.height/2-(h.height-i)/2-i,l=this.getDom();this.safeSetOffset({left:Math.max(0|j,0),top:Math.max(0|k,0)}),e.hasClass(l,"edui-state-centered")||(l.className+=" edui-state-centered")}this._show()},getContentHtml:function(){var a="";return"string"==typeof this.content?a=this.content:this.iframeUrl&&(a='<span id="'+this.id+'_contmask" class="dialogcontmask"></span><iframe id="'+this.id+'_iframe" class="%%-iframe" height="100%" width="100%" frameborder="0" src="'+this.iframeUrl+'"></iframe>'),a},getHtmlTpl:function(){var a="";if(this.buttons){for(var b=[],c=0;c<this.buttons.length;c++)b[c]=this.buttons[c].renderHtml();a='<div class="%%-foot"><div id="##_buttons" class="%%-buttons">'+b.join("")+"</div></div>"}return'<div id="##" class="%%"><div '+(this.fullscreen?'class="%%-wrap edui-dialog-fullscreen-flag"':'class="%%"')+'><div id="##_body" class="%%-body"><div class="%%-shadow"></div><div id="##_titlebar" class="%%-titlebar"><div class="%%-draghandle" onmousedown="$$._onTitlebarMouseDown(event, this);"><span class="%%-caption">'+(this.title||"")+"</span></div>"+this.closeButton.renderHtml()+'</div><div id="##_content" class="%%-content">'+(this.autoReset?"":this.getContentHtml())+"</div>"+a+"</div></div></div>"},postRender:function(){this.modalMask.getDom()||(this.modalMask.render(),this.modalMask.hide()),this.dragMask.getDom()||(this.dragMask.render(),this.dragMask.hide());var a=this;if(this.addListener("show",function(){a.modalMask.show(this.getDom().style.zIndex-2)}),this.addListener("hide",function(){a.modalMask.hide()}),this.buttons)for(var b=0;b<this.buttons.length;b++)this.buttons[b].postRender();e.on(window,"resize",function(){setTimeout(function(){a.isHidden()||a.safeSetOffset(f.getClientRect(a.getDom()))})}),this._hide()},mesureSize:function(){var a=this.getDom("body"),b=f.getClientRect(this.getDom("content")).width,c=a.style;return c.width=b,f.getClientRect(a)},_onTitlebarMouseDown:function(a,b){if(this.draggable){var c,d=(f.getViewportRect(),this);f.startDrag(a,{ondragstart:function(){c=f.getClientRect(d.getDom()),d.getDom("contmask").style.visibility="visible",d.dragMask.show(d.getDom().style.zIndex-1)},ondragmove:function(a,b){var e=c.left+a,f=c.top+b;d.safeSetOffset({left:e,top:f})},ondragstop:function(){d.getDom("contmask").style.visibility="hidden",e.removeClasses(d.getDom(),["edui-state-centered"]),d.dragMask.hide()}})}},reset:function(){this.getDom("content").innerHTML=this.getContentHtml(),this.fireEvent("dialogafterreset")},_show:function(){this._hidden&&(this.getDom().style.display="",this.editor.container.style.zIndex&&(this.getDom().style.zIndex=1*this.editor.container.style.zIndex+10),this._hidden=!1,this.fireEvent("show"),baidu.editor.ui.uiUtils.getFixedLayer().style.zIndex=this.getDom().style.zIndex-4)},isHidden:function(){return this._hidden},_hide:function(){if(!this._hidden){var a=this.getDom();a.style.display="none",a.style.zIndex="",a.style.width="",a.style.height="",this._hidden=!0,this.fireEvent("hide")}},open:function(){if(this.autoReset)try{this.reset()}catch(a){this.render(),this.open()}if(this.showAtCenter(),this.iframeUrl)try{this.getDom("iframe").focus()}catch(b){}c=this},_onCloseButtonClick:function(a,b){this.close(!1)},close:function(a){if(this.fireEvent("close",a)!==!1){this.fullscreen&&(document.documentElement.style.overflowX=this._originalContext.html.overflowX,document.documentElement.style.overflowY=this._originalContext.html.overflowY,document.body.style.overflowX=this._originalContext.body.overflowX,document.body.style.overflowY=this._originalContext.body.overflowY,delete this._originalContext),this._hide();var b=this.getDom("content"),c=this.getDom("iframe");if(b&&c){var d=c.contentDocument||c.contentWindow.document;d&&(d.body.innerHTML=""),e.remove(b)}}}},d.inherits(j,h)}(),function(){var a=baidu.editor.utils,b=baidu.editor.ui.Menu,c=baidu.editor.ui.SplitButton,d=baidu.editor.ui.MenuButton=function(a){this.initOptions(a),this.initMenuButton()};d.prototype={initMenuButton:function(){var a=this;this.uiName="menubutton",this.popup=new b({items:a.items,className:a.className,editor:a.editor}),this.popup.addListener("show",function(){for(var b=this,c=0;c<b.items.length;c++)b.items[c].removeState("checked"),b.items[c].value==a._value&&(b.items[c].addState("checked"),this.value=a._value)}),this.initSplitButton()},setValue:function(a){this._value=a}},a.inherits(d,c)}(),function(){var a=baidu.editor.utils,b=baidu.editor.ui.Popup,c=baidu.editor.ui.SplitButton,d=baidu.editor.ui.MultiMenuPop=function(a){this.initOptions(a),this.initMultiMenu()};d.prototype={initMultiMenu:function(){var a=this;this.popup=new b({content:"",editor:a.editor,iframe_rendered:!1,onshow:function(){this.iframe_rendered||(this.iframe_rendered=!0,this.getDom("content").innerHTML='<iframe id="'+a.id+'_iframe" src="'+a.iframeUrl+'" frameborder="0"></iframe>',a.editor.container.style.zIndex&&(this.getDom().style.zIndex=1*a.editor.container.style.zIndex+1))}}),this.onbuttonclick=function(){this.showPopup()},this.initSplitButton()}},a.inherits(d,c)}(),function(){function a(a){var b=a.target||a.srcElement,c=g.findParent(b,function(a){return g.hasClass(a,"edui-shortcutmenu")||g.hasClass(a,"edui-popup")},!0);if(!c)for(var d,e=0;d=h[e++];)d.hide()}var b,c=baidu.editor.ui,d=c.UIBase,e=c.uiUtils,f=baidu.editor.utils,g=baidu.editor.dom.domUtils,h=[],i=!1,j=c.ShortCutMenu=function(a){this.initOptions(a),this.initShortCutMenu()};j.postHide=a,j.prototype={isHidden:!0,SPACE:5,initShortCutMenu:function(){this.items=this.items||[],this.initUIBase(),this.initItems(),this.initEvent(),h.push(this)},initEvent:function(){var a=this,c=a.editor.document;g.on(c,"mousemove",function(c){if(a.isHidden===!1){if(a.getSubMenuMark()||"contextmenu"==a.eventType)return;var d=!0,e=a.getDom(),f=e.offsetWidth,g=e.offsetHeight,h=f/2+a.SPACE,i=g/2,j=Math.abs(c.screenX-a.left),k=Math.abs(c.screenY-a.top);clearTimeout(b),b=setTimeout(function(){k>0&&k<i?a.setOpacity(e,"1"):k>i&&k<i+70?(a.setOpacity(e,"0.5"),d=!1):k>i+70&&k<i+140&&a.hide(),d&&j>0&&j<h?a.setOpacity(e,"1"):j>h&&j<h+70?a.setOpacity(e,"0.5"):j>h+70&&j<h+140&&a.hide()})}}),browser.chrome&&g.on(c,"mouseout",function(b){var c=b.relatedTarget||b.toElement;null!=c&&"HTML"!=c.tagName||a.hide()}),a.editor.addListener("afterhidepop",function(){a.isHidden||(i=!0)})},initItems:function(){if(f.isArray(this.items))for(var a=0,b=this.items.length;a<b;a++){var d=this.items[a].toLowerCase();c[d]&&(this.items[a]=new c[d](this.editor),this.items[a].className+=" edui-shortcutsubmenu ")}},setOpacity:function(a,b){browser.ie&&browser.version<9?a.style.filter="alpha(opacity = "+100*parseFloat(b)+");":a.style.opacity=b},getSubMenuMark:function(){i=!1;for(var a,b=e.getFixedLayer(),c=g.getElementsByTagName(b,"div",function(a){return g.hasClass(a,"edui-shortcutsubmenu edui-popup")}),d=0;a=c[d++];)"none"!=a.style.display&&(i=!0);return i},show:function(a,b){function c(a){a.left<0&&(a.left=0),a.top<0&&(a.top=0),i.style.cssText="position:absolute;left:"+a.left+"px;top:"+a.top+"px;"}function d(a){a.tagName||(a=a.getDom()),h.left=parseInt(a.style.left),h.top=parseInt(a.style.top),h.top-=i.offsetHeight+15,c(h)}var f=this,h={},i=this.getDom(),j=e.getFixedLayer();if(f.eventType=a.type,i.style.cssText="display:block;left:-9999px","contextmenu"==a.type&&b){var k=g.getElementsByTagName(j,"div","edui-contextmenu")[0];k?d(k):f.editor.addListener("aftershowcontextmenu",function(a,b){d(b)})}else h=e.getViewportOffsetByEvent(a),h.top-=i.offsetHeight+f.SPACE,h.left+=f.SPACE+20,c(h),f.setOpacity(i,.2);f.isHidden=!1,f.left=a.screenX+i.offsetWidth/2-f.SPACE,f.top=a.screenY-i.offsetHeight/2-f.SPACE,f.editor&&(i.style.zIndex=1*f.editor.container.style.zIndex+10,j.style.zIndex=i.style.zIndex-1)},hide:function(){this.getDom()&&(this.getDom().style.display="none"),this.isHidden=!0},postRender:function(){if(f.isArray(this.items))for(var a,b=0;a=this.items[b++];)a.postRender()},getHtmlTpl:function(){var a;if(f.isArray(this.items)){a=[];for(var b=0;b<this.items.length;b++)a[b]=this.items[b].renderHtml();a=a.join("")}else a=this.items;return'<div id="##" class="%% edui-toolbar" data-src="shortcutmenu" onmousedown="return false;" onselectstart="return false;" >'+a+"</div>"}},f.inherits(j,d),g.on(document,"mousedown",function(b){a(b)}),g.on(window,"scroll",function(b){a(b)})}(),function(){var a=baidu.editor.utils,b=baidu.editor.ui.UIBase,c=baidu.editor.ui.Breakline=function(a){this.initOptions(a),this.initSeparator()};c.prototype={uiName:"Breakline",initSeparator:function(){this.initUIBase()},getHtmlTpl:function(){return"<br/>"}},a.inherits(c,b)}(),function(){var a=baidu.editor.utils,b=baidu.editor.dom.domUtils,c=baidu.editor.ui.UIBase,d=baidu.editor.ui.Message=function(a){this.initOptions(a),this.initMessage()};d.prototype={initMessage:function(){this.initUIBase()},getHtmlTpl:function(){return'<div id="##" class="edui-message %%"> <div id="##_closer" class="edui-message-closer">×</div> <div id="##_body" class="edui-message-body edui-message-type-info"> <iframe style="position:absolute;z-index:-1;left:0;top:0;background-color: transparent;" frameborder="0" width="100%" height="100%" src="about:blank"></iframe> <div class="edui-shadow"></div> <div id="##_content" class="edui-message-content"> </div> </div></div>'},reset:function(a){var b=this;a.keepshow||(clearTimeout(this.timer),b.timer=setTimeout(function(){b.hide()},a.timeout||4e3)),void 0!==a.content&&b.setContent(a.content),void 0!==a.type&&b.setType(a.type),b.show()},postRender:function(){var a=this,c=this.getDom("closer");c&&b.on(c,"click",function(){a.hide()})},setContent:function(a){this.getDom("content").innerHTML=a},setType:function(a){a=a||"info";var b=this.getDom("body");b.className=b.className.replace(/edui-message-type-[\w-]+/,"edui-message-type-"+a)},getContent:function(){return this.getDom("content").innerHTML},getType:function(){var a=this.getDom("body").match(/edui-message-type-([\w-]+)/);return a?a[1]:""},show:function(){this.getDom().style.display="block"},hide:function(){var a=this.getDom();a&&(a.style.display="none",a.parentNode&&a.parentNode.removeChild(a))}},a.inherits(d,c)}(),function(){var a=baidu.editor.utils,b=baidu.editor.ui,c=b.Dialog;b.buttons={},b.Dialog=function(a){var b=new c(a);return b.addListener("hide",function(){if(b.editor){var a=b.editor;try{if(browser.gecko){var c=a.window.scrollY,d=a.window.scrollX;a.body.focus(),a.window.scrollTo(d,c)}else a.focus()}catch(e){}}}),b};for(var d,e={anchor:"~/dialogs/anchor/anchor.html",insertimage:"~/dialogs/image/image.html",link:"~/dialogs/link/link.html",spechars:"~/dialogs/spechars/spechars.html",searchreplace:"~/dialogs/searchreplace/searchreplace.html",map:"~/dialogs/map/map.html",gmap:"~/dialogs/gmap/gmap.html",insertvideo:"~/dialogs/video/video.html",help:"~/dialogs/help/help.html",preview:"~/dialogs/preview/preview.html",emotion:"~/dialogs/emotion/emotion.html",wordimage:"~/dialogs/wordimage/wordimage.html",attachment:"~/dialogs/attachment/attachment.html",insertframe:"~/dialogs/insertframe/insertframe.html",edittip:"~/dialogs/table/edittip.html",edittable:"~/dialogs/table/edittable.html",edittd:"~/dialogs/table/edittd.html",webapp:"~/dialogs/webapp/webapp.html",snapscreen:"~/dialogs/snapscreen/snapscreen.html",scrawl:"~/dialogs/scrawl/scrawl.html",music:"~/dialogs/music/music.html",template:"~/dialogs/template/template.html",background:"~/dialogs/background/background.html",charts:"~/dialogs/charts/charts.html"},f=["undo","redo","formatmatch","bold","italic","underline","fontborder","touppercase","tolowercase","strikethrough","subscript","superscript","source","indent","outdent","blockquote","pasteplain","pagebreak","selectall","print","horizontal","removeformat","time","date","unlink","insertparagraphbeforetable","insertrow","insertcol","mergeright","mergedown","deleterow","deletecol","splittorows","splittocols","splittocells","mergecells","deletetable","drafts"],g=0;d=f[g++];)d=d.toLowerCase(),b[d]=function(a){return function(c){var d=new b.Button({className:"edui-for-"+a,title:c.options.labelMap[a]||c.getLang("labelMap."+a)||"",onclick:function(){c.execCommand(a)},theme:c.options.theme,showText:!1});return b.buttons[a]=d,c.addListener("selectionchange",function(b,e,f){var g=c.queryCommandState(a);g==-1?(d.setDisabled(!0),d.setChecked(!1)):f||(d.setDisabled(!1),d.setChecked(g))}),d}}(d);b.cleardoc=function(a){var c=new b.Button({className:"edui-for-cleardoc",title:a.options.labelMap.cleardoc||a.getLang("labelMap.cleardoc")||"",theme:a.options.theme,onclick:function(){confirm(a.getLang("confirmClear"))&&a.execCommand("cleardoc")}});return b.buttons.cleardoc=c,a.addListener("selectionchange",function(){c.setDisabled(a.queryCommandState("cleardoc")==-1)}),c};var h={justify:["left","right","center","justify"],imagefloat:["none","left","center","right"],directionality:["ltr","rtl"]};for(var i in h)!function(a,c){for(var d,e=0;d=c[e++];)!function(c){b[a.replace("float","")+c]=function(d){var e=new b.Button({
className:"edui-for-"+a.replace("float","")+c,title:d.options.labelMap[a.replace("float","")+c]||d.getLang("labelMap."+a.replace("float","")+c)||"",theme:d.options.theme,onclick:function(){d.execCommand(a,c)}});return b.buttons[a]=e,d.addListener("selectionchange",function(b,f,g){e.setDisabled(d.queryCommandState(a)==-1),e.setChecked(d.queryCommandValue(a)==c&&!g)}),e}}(d)}(i,h[i]);for(var d,g=0;d=["backcolor","forecolor"][g++];)b[d]=function(a){return function(c){var d=new b.ColorButton({className:"edui-for-"+a,color:"default",title:c.options.labelMap[a]||c.getLang("labelMap."+a)||"",editor:c,onpickcolor:function(b,d){c.execCommand(a,d)},onpicknocolor:function(){c.execCommand(a,"default"),this.setColor("transparent"),this.color="default"},onbuttonclick:function(){c.execCommand(a,this.color)}});return b.buttons[a]=d,c.addListener("selectionchange",function(){d.setDisabled(c.queryCommandState(a)==-1)}),d}}(d);var j={noOk:["searchreplace","help","spechars","webapp","preview"],ok:["attachment","anchor","link","insertimage","map","gmap","insertframe","wordimage","insertvideo","insertframe","edittip","edittable","edittd","scrawl","template","music","background","charts"]};for(var i in j)!function(c,d){for(var f,g=0;f=d[g++];)browser.opera&&"searchreplace"===f||!function(d){b[d]=function(f,g,h){g=g||(f.options.iframeUrlMap||{})[d]||e[d],h=f.options.labelMap[d]||f.getLang("labelMap."+d)||"";var i;g&&(i=new b.Dialog(a.extend({iframeUrl:f.ui.mapUrl(g),editor:f,className:"edui-for-"+d,title:h,holdScroll:"insertimage"===d,fullscreen:/charts|preview/.test(d),closeDialog:f.getLang("closeDialog")},"ok"==c?{buttons:[{className:"edui-okbutton",label:f.getLang("ok"),editor:f,onclick:function(){i.close(!0)}},{className:"edui-cancelbutton",label:f.getLang("cancel"),editor:f,onclick:function(){i.close(!1)}}]}:{})),f.ui._dialogs[d+"Dialog"]=i);var j=new b.Button({className:"edui-for-"+d,title:h,onclick:function(){if(i)switch(d){case"wordimage":var a=f.execCommand("wordimage");a&&a.length&&(i.render(),i.open());break;case"scrawl":f.queryCommandState("scrawl")!=-1&&(i.render(),i.open());break;default:i.render(),i.open()}},theme:f.options.theme,disabled:"scrawl"==d&&f.queryCommandState("scrawl")==-1||"charts"==d});return b.buttons[d]=j,f.addListener("selectionchange",function(){var a={edittable:1};if(!(d in a)){var b=f.queryCommandState(d);j.getDom()&&(j.setDisabled(b==-1),j.setChecked(b))}}),j}}(f.toLowerCase())}(i,j[i]);b.snapscreen=function(a,c,d){d=a.options.labelMap.snapscreen||a.getLang("labelMap.snapscreen")||"";var f=new b.Button({className:"edui-for-snapscreen",title:d,onclick:function(){a.execCommand("snapscreen")},theme:a.options.theme});if(b.buttons.snapscreen=f,c=c||(a.options.iframeUrlMap||{}).snapscreen||e.snapscreen){var g=new b.Dialog({iframeUrl:a.ui.mapUrl(c),editor:a,className:"edui-for-snapscreen",title:d,buttons:[{className:"edui-okbutton",label:a.getLang("ok"),editor:a,onclick:function(){g.close(!0)}},{className:"edui-cancelbutton",label:a.getLang("cancel"),editor:a,onclick:function(){g.close(!1)}}]});g.render(),a.ui._dialogs.snapscreenDialog=g}return a.addListener("selectionchange",function(){f.setDisabled(a.queryCommandState("snapscreen")==-1)}),f},b.insertcode=function(c,d,e){d=c.options.insertcode||[],e=c.options.labelMap.insertcode||c.getLang("labelMap.insertcode")||"";var f=[];a.each(d,function(a,b){f.push({label:a,value:b,theme:c.options.theme,renderLabelHtml:function(){return'<div class="edui-label %%-label" >'+(this.label||"")+"</div>"}})});var g=new b.Combox({editor:c,items:f,onselect:function(a,b){c.execCommand("insertcode",this.items[b].value)},onbuttonclick:function(){this.showPopup()},title:e,initValue:e,className:"edui-for-insertcode",indexByValue:function(a){if(a)for(var b,c=0;b=this.items[c];c++)if(b.value.indexOf(a)!=-1)return c;return-1}});return b.buttons.insertcode=g,c.addListener("selectionchange",function(a,b,d){if(!d){var f=c.queryCommandState("insertcode");if(f==-1)g.setDisabled(!0);else{g.setDisabled(!1);var h=c.queryCommandValue("insertcode");if(!h)return void g.setValue(e);h&&(h=h.replace(/['"]/g,"").split(",")[0]),g.setValue(h)}}}),g},b.fontfamily=function(c,d,e){if(d=c.options.fontfamily||[],e=c.options.labelMap.fontfamily||c.getLang("labelMap.fontfamily")||"",d.length){for(var f,g=0,h=[];f=d[g];g++){var i=c.getLang("fontfamily")[f.name]||"";!function(b,d){h.push({label:b,value:d,theme:c.options.theme,renderLabelHtml:function(){return'<div class="edui-label %%-label" style="font-family:'+a.unhtml(this.value)+'">'+(this.label||"")+"</div>"}})}(f.label||i,f.val)}var j=new b.Combox({editor:c,items:h,onselect:function(a,b){c.execCommand("FontFamily",this.items[b].value)},onbuttonclick:function(){this.showPopup()},title:e,initValue:e,className:"edui-for-fontfamily",indexByValue:function(a){if(a)for(var b,c=0;b=this.items[c];c++)if(b.value.indexOf(a)!=-1)return c;return-1}});return b.buttons.fontfamily=j,c.addListener("selectionchange",function(a,b,d){if(!d){var e=c.queryCommandState("FontFamily");if(e==-1)j.setDisabled(!0);else{j.setDisabled(!1);var f=c.queryCommandValue("FontFamily");f&&(f=f.replace(/['"]/g,"").split(",")[0]),j.setValue(f)}}}),j}},b.fontsize=function(a,c,d){if(d=a.options.labelMap.fontsize||a.getLang("labelMap.fontsize")||"",c=c||a.options.fontsize||[],c.length){for(var e=[],f=0;f<c.length;f++){var g=c[f]+"px";e.push({label:g,value:g,theme:a.options.theme,renderLabelHtml:function(){return'<div class="edui-label %%-label" style="line-height:1;font-size:'+this.value+'">'+(this.label||"")+"</div>"}})}var h=new b.Combox({editor:a,items:e,title:d,initValue:d,onselect:function(b,c){a.execCommand("FontSize",this.items[c].value)},onbuttonclick:function(){this.showPopup()},className:"edui-for-fontsize"});return b.buttons.fontsize=h,a.addListener("selectionchange",function(b,c,d){if(!d){var e=a.queryCommandState("FontSize");e==-1?h.setDisabled(!0):(h.setDisabled(!1),h.setValue(a.queryCommandValue("FontSize")))}}),h}},b.paragraph=function(c,d,e){if(e=c.options.labelMap.paragraph||c.getLang("labelMap.paragraph")||"",d=c.options.paragraph||[],!a.isEmptyObject(d)){var f=[];for(var g in d)f.push({value:g,label:d[g]||c.getLang("paragraph")[g],theme:c.options.theme,renderLabelHtml:function(){return'<div class="edui-label %%-label"><span class="edui-for-'+this.value+'">'+(this.label||"")+"</span></div>"}});var h=new b.Combox({editor:c,items:f,title:e,initValue:e,className:"edui-for-paragraph",onselect:function(a,b){c.execCommand("Paragraph",this.items[b].value)},onbuttonclick:function(){this.showPopup()}});return b.buttons.paragraph=h,c.addListener("selectionchange",function(a,b,d){if(!d){var e=c.queryCommandState("Paragraph");if(e==-1)h.setDisabled(!0);else{h.setDisabled(!1);var f=c.queryCommandValue("Paragraph"),g=h.indexByValue(f);g!=-1?h.setValue(f):h.setValue(h.initValue)}}}),h}},b.customstyle=function(a){var c=a.options.customstyle||[],d=a.options.labelMap.customstyle||a.getLang("labelMap.customstyle")||"";if(c.length){for(var e,f=a.getLang("customstyle"),g=0,h=[];e=c[g++];)!function(b){var c={};c.label=b.label?b.label:f[b.name],c.style=b.style,c.className=b.className,c.tag=b.tag,h.push({label:c.label,value:c,theme:a.options.theme,renderLabelHtml:function(){return'<div class="edui-label %%-label"><'+c.tag+" "+(c.className?' class="'+c.className+'"':"")+(c.style?' style="'+c.style+'"':"")+">"+c.label+"</"+c.tag+"></div>"}})}(e);var i=new b.Combox({editor:a,items:h,title:d,initValue:d,className:"edui-for-customstyle",onselect:function(b,c){a.execCommand("customstyle",this.items[c].value)},onbuttonclick:function(){this.showPopup()},indexByValue:function(a){for(var b,c=0;b=this.items[c++];)if(b.label==a)return c-1;return-1}});return b.buttons.customstyle=i,a.addListener("selectionchange",function(b,c,d){if(!d){var e=a.queryCommandState("customstyle");if(e==-1)i.setDisabled(!0);else{i.setDisabled(!1);var f=a.queryCommandValue("customstyle"),g=i.indexByValue(f);g!=-1?i.setValue(f):i.setValue(i.initValue)}}}),i}},b.inserttable=function(a,c,d){d=a.options.labelMap.inserttable||a.getLang("labelMap.inserttable")||"";var e=new b.TableButton({editor:a,title:d,className:"edui-for-inserttable",onpicktable:function(b,c,d){a.execCommand("InsertTable",{numRows:d,numCols:c,border:1})},onbuttonclick:function(){this.showPopup()}});return b.buttons.inserttable=e,a.addListener("selectionchange",function(){e.setDisabled(a.queryCommandState("inserttable")==-1)}),e},b.lineheight=function(a){var c=a.options.lineheight||[];if(c.length){for(var d,e=0,f=[];d=c[e++];)f.push({label:d,value:d,theme:a.options.theme,onclick:function(){a.execCommand("lineheight",this.value)}});var g=new b.MenuButton({editor:a,className:"edui-for-lineheight",title:a.options.labelMap.lineheight||a.getLang("labelMap.lineheight")||"",items:f,onbuttonclick:function(){var b=a.queryCommandValue("LineHeight")||this.value;a.execCommand("LineHeight",b)}});return b.buttons.lineheight=g,a.addListener("selectionchange",function(){var b=a.queryCommandState("LineHeight");if(b==-1)g.setDisabled(!0);else{g.setDisabled(!1);var c=a.queryCommandValue("LineHeight");c&&g.setValue((c+"").replace(/cm/,"")),g.setChecked(b)}}),g}};for(var k,l=["top","bottom"],m=0;k=l[m++];)!function(a){b["rowspacing"+a]=function(c){var d=c.options["rowspacing"+a]||[];if(!d.length)return null;for(var e,f=0,g=[];e=d[f++];)g.push({label:e,value:e,theme:c.options.theme,onclick:function(){c.execCommand("rowspacing",this.value,a)}});var h=new b.MenuButton({editor:c,className:"edui-for-rowspacing"+a,title:c.options.labelMap["rowspacing"+a]||c.getLang("labelMap.rowspacing"+a)||"",items:g,onbuttonclick:function(){var b=c.queryCommandValue("rowspacing",a)||this.value;c.execCommand("rowspacing",b,a)}});return b.buttons[a]=h,c.addListener("selectionchange",function(){var b=c.queryCommandState("rowspacing",a);if(b==-1)h.setDisabled(!0);else{h.setDisabled(!1);var d=c.queryCommandValue("rowspacing",a);d&&h.setValue((d+"").replace(/%/,"")),h.setChecked(b)}}),h}}(k);for(var n,o=["insertorderedlist","insertunorderedlist"],p=0;n=o[p++];)!function(a){b[a]=function(c){var d=c.options[a],e=function(){c.execCommand(a,this.value)},f=[];for(var g in d)f.push({label:d[g]||c.getLang()[a][g]||"",value:g,theme:c.options.theme,onclick:e});var h=new b.MenuButton({editor:c,className:"edui-for-"+a,title:c.getLang("labelMap."+a)||"",items:f,onbuttonclick:function(){var b=c.queryCommandValue(a)||this.value;c.execCommand(a,b)}});return b.buttons[a]=h,c.addListener("selectionchange",function(){var b=c.queryCommandState(a);if(b==-1)h.setDisabled(!0);else{h.setDisabled(!1);var d=c.queryCommandValue(a);h.setValue(d),h.setChecked(b)}}),h}}(n);b.fullscreen=function(a,c){c=a.options.labelMap.fullscreen||a.getLang("labelMap.fullscreen")||"";var d=new b.Button({className:"edui-for-fullscreen",title:c,theme:a.options.theme,onclick:function(){a.ui&&a.ui.setFullScreen(!a.ui.isFullScreen()),this.setChecked(a.ui.isFullScreen())}});return b.buttons.fullscreen=d,a.addListener("selectionchange",function(){var b=a.queryCommandState("fullscreen");d.setDisabled(b==-1),d.setChecked(a.ui.isFullScreen())}),d},b.emotion=function(a,c){var d="emotion",f=new b.MultiMenuPop({title:a.options.labelMap[d]||a.getLang("labelMap."+d)||"",editor:a,className:"edui-for-"+d,iframeUrl:a.ui.mapUrl(c||(a.options.iframeUrlMap||{})[d]||e[d])});return b.buttons[d]=f,a.addListener("selectionchange",function(){f.setDisabled(a.queryCommandState(d)==-1)}),f},b.autotypeset=function(a){var c=new b.AutoTypeSetButton({editor:a,title:a.options.labelMap.autotypeset||a.getLang("labelMap.autotypeset")||"",className:"edui-for-autotypeset",onbuttonclick:function(){a.execCommand("autotypeset")}});return b.buttons.autotypeset=c,a.addListener("selectionchange",function(){c.setDisabled(a.queryCommandState("autotypeset")==-1)}),c},b.simpleupload=function(a){var c="simpleupload",d=new b.Button({className:"edui-for-"+c,title:a.options.labelMap[c]||a.getLang("labelMap."+c)||"",onclick:function(){},theme:a.options.theme,showText:!1});return b.buttons[c]=d,a.addListener("ready",function(){var b=d.getDom("body"),c=b.children[0];a.fireEvent("simpleuploadbtnready",c)}),a.addListener("selectionchange",function(b,e,f){var g=a.queryCommandState(c);g==-1?(d.setDisabled(!0),d.setChecked(!1)):f||(d.setDisabled(!1),d.setChecked(g))}),d}}(),function(){function a(a){this.initOptions(a),this.initEditorUI()}var b=baidu.editor.utils,c=baidu.editor.ui.uiUtils,d=baidu.editor.ui.UIBase,e=baidu.editor.dom.domUtils,f=[];a.prototype={uiName:"editor",initEditorUI:function(){function a(a,b){a.setOpt({wordCount:!0,maximumWords:1e4,wordCountMsg:a.options.wordCountMsg||a.getLang("wordCountMsg"),wordOverFlowMsg:a.options.wordOverFlowMsg||a.getLang("wordOverFlowMsg")});var c=a.options,d=c.maximumWords,e=c.wordCountMsg,f=c.wordOverFlowMsg,g=b.getDom("wordcount");if(c.wordCount){var h=a.getContentLength(!0);h>d?(g.innerHTML=f,a.fireEvent("wordcountoverflow")):g.innerHTML=e.replace("{#leave}",d-h).replace("{#count}",h)}}this.editor.ui=this,this._dialogs={},this.initUIBase(),this._initToolbars();var b=this.editor,c=this;b.addListener("ready",function(){function d(){a(b,c),e.un(b.document,"click",arguments.callee)}b.getDialog=function(a){return b.ui._dialogs[a+"Dialog"]},e.on(b.window,"scroll",function(a){baidu.editor.ui.Popup.postHide(a)}),b.ui._actualFrameWidth=b.options.initialFrameWidth,UE.browser.ie&&6===UE.browser.version&&b.container.ownerDocument.execCommand("BackgroundImageCache",!1,!0),b.options.elementPathEnabled&&(b.ui.getDom("elementpath").innerHTML='<div class="edui-editor-breadcrumb">'+b.getLang("elementPathTip")+":</div>"),b.options.wordCount&&(e.on(b.document,"click",d),b.ui.getDom("wordcount").innerHTML=b.getLang("wordCountTip")),b.ui._scale(),b.options.scaleEnabled?(b.autoHeightEnabled&&b.disableAutoHeight(),c.enableScale()):c.disableScale(),b.options.elementPathEnabled||b.options.wordCount||b.options.scaleEnabled||(b.ui.getDom("elementpath").style.display="none",b.ui.getDom("wordcount").style.display="none",b.ui.getDom("scale").style.display="none"),b.selection.isFocus()&&b.fireEvent("selectionchange",!1,!0)}),b.addListener("mousedown",function(a,b){var c=b.target||b.srcElement;baidu.editor.ui.Popup.postHide(b,c),baidu.editor.ui.ShortCutMenu.postHide(b)}),b.addListener("delcells",function(){UE.ui.edittip&&new UE.ui.edittip(b),b.getDialog("edittip").open()});var d,f,g=!1;b.addListener("afterpaste",function(){b.queryCommandState("pasteplain")||(baidu.editor.ui.PastePicker&&(d=new baidu.editor.ui.Popup({content:new baidu.editor.ui.PastePicker({editor:b}),editor:b,className:"edui-wordpastepop"}),d.render()),g=!0)}),b.addListener("afterinserthtml",function(){clearTimeout(f),f=setTimeout(function(){if(d&&(g||b.ui._isTransfer)){if(d.isHidden()){var a=e.createElement(b.document,"span",{style:"line-height:0px;",innerHTML:"\ufeff"}),c=b.selection.getRange();c.insertNode(a);var f=getDomNode(a,"firstChild","previousSibling");f&&d.showAnchor(3==f.nodeType?f.parentNode:f),e.remove(a)}else d.show();delete b.ui._isTransfer,g=!1}},200)}),b.addListener("contextmenu",function(a,b){baidu.editor.ui.Popup.postHide(b)}),b.addListener("keydown",function(a,b){d&&d.dispose(b);var c=b.keyCode||b.which;b.altKey&&90==c&&UE.ui.buttons.fullscreen.onclick()}),b.addListener("wordcount",function(b){a(this,c)}),b.addListener("selectionchange",function(){b.options.elementPathEnabled&&c[(b.queryCommandState("elementpath")==-1?"dis":"en")+"ableElementPath"](),b.options.scaleEnabled&&c[(b.queryCommandState("scale")==-1?"dis":"en")+"ableScale"]()});var h=new baidu.editor.ui.Popup({editor:b,content:"",className:"edui-bubble",_onEditButtonClick:function(){this.hide(),b.ui._dialogs.linkDialog.open()},_onImgEditButtonClick:function(a){this.hide(),b.ui._dialogs[a]&&b.ui._dialogs[a].open()},_onImgSetFloat:function(a){this.hide(),b.execCommand("imagefloat",a)},_setIframeAlign:function(a){var b=h.anchorEl,c=b.cloneNode(!0);switch(a){case-2:c.setAttribute("align","");break;case-1:c.setAttribute("align","left");break;case 1:c.setAttribute("align","right")}b.parentNode.insertBefore(c,b),e.remove(b),h.anchorEl=c,h.showAnchor(h.anchorEl)},_updateIframe:function(){var a=b._iframe=h.anchorEl;e.hasClass(a,"ueditor_baidumap")?(b.selection.getRange().selectNode(a).select(),b.ui._dialogs.mapDialog.open(),h.hide()):(b.ui._dialogs.insertframeDialog.open(),h.hide())},_onRemoveButtonClick:function(a){b.execCommand(a),this.hide()},queryAutoHide:function(a){return a&&a.ownerDocument==b.document&&("img"==a.tagName.toLowerCase()||e.findParentByTagName(a,"a",!0))?a!==h.anchorEl:baidu.editor.ui.Popup.prototype.queryAutoHide.call(this,a)}});h.render(),b.options.imagePopup&&(b.addListener("mouseover",function(a,c){c=c||window.event;var d=c.target||c.srcElement;if(b.ui._dialogs.insertframeDialog&&/iframe/gi.test(d.tagName)){var e=h.formatHtml("<nobr>"+b.getLang("property")+': <span onclick=$$._setIframeAlign(-2) class="edui-clickable">'+b.getLang("default")+'</span> <span onclick=$$._setIframeAlign(-1) class="edui-clickable">'+b.getLang("justifyleft")+'</span> <span onclick=$$._setIframeAlign(1) class="edui-clickable">'+b.getLang("justifyright")+'</span> <span onclick="$$._updateIframe( this);" class="edui-clickable">'+b.getLang("modify")+"</span></nobr>");e?(h.getDom("content").innerHTML=e,h.anchorEl=d,h.showAnchor(h.anchorEl)):h.hide()}}),b.addListener("selectionchange",function(a,c){if(c){var d="",f="",g=b.selection.getRange().getClosedNode(),i=b.ui._dialogs;if(g&&"IMG"==g.tagName){var j="insertimageDialog";if(g.className.indexOf("edui-faked-video")==-1&&g.className.indexOf("edui-upload-video")==-1||(j="insertvideoDialog"),g.className.indexOf("edui-faked-webapp")!=-1&&(j="webappDialog"),g.src.indexOf("http://api.map.baidu.com")!=-1&&(j="mapDialog"),g.className.indexOf("edui-faked-music")!=-1&&(j="musicDialog"),g.src.indexOf("http://maps.google.com/maps/api/staticmap")!=-1&&(j="gmapDialog"),g.getAttribute("anchorname")&&(j="anchorDialog",d=h.formatHtml("<nobr>"+b.getLang("property")+': <span onclick=$$._onImgEditButtonClick("anchorDialog") class="edui-clickable">'+b.getLang("modify")+"</span> <span onclick=$$._onRemoveButtonClick('anchor') class=\"edui-clickable\">"+b.getLang("delete")+"</span></nobr>")),g.getAttribute("word_img")&&(b.word_img=[g.getAttribute("word_img")],j="wordimageDialog"),(e.hasClass(g,"loadingclass")||e.hasClass(g,"loaderrorclass"))&&(j=""),!i[j])return;f="<nobr>"+b.getLang("property")+': <span onclick=$$._onImgSetFloat("none") class="edui-clickable">'+b.getLang("default")+'</span> <span onclick=$$._onImgSetFloat("left") class="edui-clickable">'+b.getLang("justifyleft")+'</span> <span onclick=$$._onImgSetFloat("right") class="edui-clickable">'+b.getLang("justifyright")+'</span> <span onclick=$$._onImgSetFloat("center") class="edui-clickable">'+b.getLang("justifycenter")+"</span> <span onclick=\"$$._onImgEditButtonClick('"+j+'\');" class="edui-clickable">'+b.getLang("modify")+"</span></nobr>",!d&&(d=h.formatHtml(f))}if(b.ui._dialogs.linkDialog){var k,l=b.queryCommandValue("link");if(l&&(k=l.getAttribute("_href")||l.getAttribute("href",2))){var m=k;k.length>30&&(m=k.substring(0,20)+"..."),d&&(d+='<div style="height:5px;"></div>'),d+=h.formatHtml("<nobr>"+b.getLang("anthorMsg")+': <a target="_blank" href="'+k+'" title="'+k+'" >'+m+'</a> <span class="edui-clickable" onclick="$$._onEditButtonClick();">'+b.getLang("modify")+'</span> <span class="edui-clickable" onclick="$$._onRemoveButtonClick(\'unlink\');"> '+b.getLang("clear")+"</span></nobr>"),h.showAnchor(l)}}d?(h.getDom("content").innerHTML=d,h.anchorEl=g||l,h.showAnchor(h.anchorEl)):h.hide()}}))},_initToolbars:function(){for(var a=this.editor,c=this.toolbars||[],d=[],e=0;e<c.length;e++){for(var f=c[e],g=new baidu.editor.ui.Toolbar({theme:a.options.theme}),h=0;h<f.length;h++){var i=f[h],j=null;if("string"==typeof i){if(i=i.toLowerCase(),"|"==i&&(i="Separator"),"||"==i&&(i="Breakline"),baidu.editor.ui[i]&&(j=new baidu.editor.ui[i](a)),"fullscreen"==i){d&&d[0]?d[0].items.splice(0,0,j):j&&g.items.splice(0,0,j);continue}}else j=i;j&&j.id&&g.add(j)}d[e]=g}b.each(UE._customizeUI,function(b,c){var d,e;return(!b.id||b.id==a.key)&&(d=b.execFn.call(a,a,c),void(d&&(e=b.index,void 0===e&&(e=g.items.length),g.add(d,e))))}),this.toolbars=d},getHtmlTpl:function(){return'<div id="##" class="%%"><div id="##_toolbarbox" class="%%-toolbarbox">'+(this.toolbars.length?'<div id="##_toolbarboxouter" class="%%-toolbarboxouter"><div class="%%-toolbarboxinner">'+this.renderToolbarBoxHtml()+"</div></div>":"")+'<div id="##_toolbarmsg" class="%%-toolbarmsg" style="display:none;"><div id = "##_upload_dialog" class="%%-toolbarmsg-upload" onclick="$$.showWordImageDialog();">'+this.editor.getLang("clickToUpload")+'</div><div class="%%-toolbarmsg-close" onclick="$$.hideToolbarMsg();">x</div><div id="##_toolbarmsg_label" class="%%-toolbarmsg-label"></div><div style="height:0;overflow:hidden;clear:both;"></div></div><div id="##_message_holder" class="%%-messageholder"></div></div><div id="##_iframeholder" class="%%-iframeholder"></div><div id="##_bottombar" class="%%-bottomContainer"><table><tr><td id="##_elementpath" class="%%-bottombar"></td><td id="##_wordcount" class="%%-wordcount"></td><td id="##_scale" class="%%-scale"><div class="%%-icon"></div></td></tr></table></div><div id="##_scalelayer"></div></div>'},showWordImageDialog:function(){this._dialogs.wordimageDialog.open()},renderToolbarBoxHtml:function(){for(var a=[],b=0;b<this.toolbars.length;b++)a.push(this.toolbars[b].renderHtml());return a.join("")},setFullScreen:function(a){var b=this.editor,c=b.container.parentNode.parentNode;if(this._fullscreen!=a){if(this._fullscreen=a,this.editor.fireEvent("beforefullscreenchange",a),baidu.editor.browser.gecko)var d=b.selection.getRange().createBookmark();if(a){for(;"BODY"!=c.tagName;){var e=baidu.editor.dom.domUtils.getComputedStyle(c,"position");f.push(e),c.style.position="static",c=c.parentNode}this._bakHtmlOverflow=document.documentElement.style.overflow,this._bakBodyOverflow=document.body.style.overflow,this._bakAutoHeight=this.editor.autoHeightEnabled,this._bakScrollTop=Math.max(document.documentElement.scrollTop,document.body.scrollTop),this._bakEditorContaninerWidth=b.iframe.parentNode.offsetWidth,this._bakAutoHeight&&(b.autoHeightEnabled=!1,this.editor.disableAutoHeight()),document.documentElement.style.overflow="hidden",window.scrollTo(0,window.scrollY),this._bakCssText=this.getDom().style.cssText,this._bakCssText1=this.getDom("iframeholder").style.cssText,b.iframe.parentNode.style.width="",this._updateFullScreen()}else{for(;"BODY"!=c.tagName;)c.style.position=f.shift(),c=c.parentNode;this.getDom().style.cssText=this._bakCssText,this.getDom("iframeholder").style.cssText=this._bakCssText1,this._bakAutoHeight&&(b.autoHeightEnabled=!0,this.editor.enableAutoHeight()),document.documentElement.style.overflow=this._bakHtmlOverflow,document.body.style.overflow=this._bakBodyOverflow,b.iframe.parentNode.style.width=this._bakEditorContaninerWidth+"px",window.scrollTo(0,this._bakScrollTop)}if(browser.gecko&&"true"===b.body.contentEditable){var g=document.createElement("input");document.body.appendChild(g),b.body.contentEditable=!1,setTimeout(function(){g.focus(),setTimeout(function(){b.body.contentEditable=!0,b.fireEvent("fullscreenchanged",a),b.selection.getRange().moveToBookmark(d).select(!0),baidu.editor.dom.domUtils.remove(g),a&&window.scroll(0,0)},0)},0)}"true"===b.body.contentEditable&&(this.editor.fireEvent("fullscreenchanged",a),this.triggerLayout())}},_updateFullScreen:function(){if(this._fullscreen){var a=c.getViewportRect();if(this.getDom().style.cssText="border:0;position:absolute;left:0;top:"+(this.editor.options.topOffset||0)+"px;width:"+a.width+"px;height:"+a.height+"px;z-index:"+(1*this.getDom().style.zIndex+100),c.setViewportOffset(this.getDom(),{left:0,top:this.editor.options.topOffset||0}),this.editor.setHeight(a.height-this.getDom("toolbarbox").offsetHeight-this.getDom("bottombar").offsetHeight-(this.editor.options.topOffset||0),!0),browser.gecko)try{window.onresize()}catch(b){}}},_updateElementPath:function(){var a,b=this.getDom("elementpath");if(this.elementPathEnabled&&(a=this.editor.queryCommandValue("elementpath"))){for(var c,d=[],e=0;c=a[e];e++)d[e]=this.formatHtml('<span unselectable="on" onclick="$$.editor.execCommand("elementpath", "'+e+'");">'+c+"</span>");b.innerHTML='<div class="edui-editor-breadcrumb" onmousedown="return false;">'+this.editor.getLang("elementPathTip")+": "+d.join(" > ")+"</div>"}else b.style.display="none"},disableElementPath:function(){var a=this.getDom("elementpath");a.innerHTML="",a.style.display="none",this.elementPathEnabled=!1},enableElementPath:function(){var a=this.getDom("elementpath");a.style.display="",this.elementPathEnabled=!0,this._updateElementPath()},_scale:function(){function a(){o=e.getXY(h),p||(p=g.options.minFrameHeight+j.offsetHeight+k.offsetHeight),m.style.cssText="position:absolute;left:0;display:;top:0;background-color:#41ABFF;opacity:0.4;filter: Alpha(opacity=40);width:"+h.offsetWidth+"px;height:"+h.offsetHeight+"px;z-index:"+(g.options.zIndex+1),e.on(f,"mousemove",b),e.on(i,"mouseup",c),e.on(f,"mouseup",c)}function b(a){d();var b=a||window.event;r=b.pageX||f.documentElement.scrollLeft+b.clientX,s=b.pageY||f.documentElement.scrollTop+b.clientY,t=r-o.x,u=s-o.y,t>=q&&(n=!0,m.style.width=t+"px"),u>=p&&(n=!0,m.style.height=u+"px")}function c(){n&&(n=!1,g.ui._actualFrameWidth=m.offsetWidth-2,h.style.width=g.ui._actualFrameWidth+"px",g.setHeight(m.offsetHeight-k.offsetHeight-j.offsetHeight-2,!0)),m&&(m.style.display="none"),d(),e.un(f,"mousemove",b),e.un(i,"mouseup",c),e.un(f,"mouseup",c)}function d(){browser.ie?f.selection.clear():window.getSelection().removeAllRanges()}var f=document,g=this.editor,h=g.container,i=g.document,j=this.getDom("toolbarbox"),k=this.getDom("bottombar"),l=this.getDom("scale"),m=this.getDom("scalelayer"),n=!1,o=null,p=0,q=g.options.minFrameWidth,r=0,s=0,t=0,u=0,v=this;this.editor.addListener("fullscreenchanged",function(a,b){if(b)v.disableScale();else if(v.editor.options.scaleEnabled){v.enableScale();var c=v.editor.document.createElement("span");v.editor.body.appendChild(c),v.editor.body.style.height=Math.max(e.getXY(c).y,v.editor.iframe.offsetHeight-20)+"px",e.remove(c)}}),this.enableScale=function(){1!=g.queryCommandState("source")&&(l.style.display="",this.scaleEnabled=!0,e.on(l,"mousedown",a))},this.disableScale=function(){l.style.display="none",this.scaleEnabled=!1,e.un(l,"mousedown",a)}},isFullScreen:function(){return this._fullscreen},postRender:function(){d.prototype.postRender.call(this);for(var a=0;a<this.toolbars.length;a++)this.toolbars[a].postRender();var b,c=this,e=baidu.editor.dom.domUtils,f=function(){clearTimeout(b),b=setTimeout(function(){c._updateFullScreen()})};e.on(window,"resize",f),c.addListener("destroy",function(){e.un(window,"resize",f),clearTimeout(b)})},showToolbarMsg:function(a,b){if(this.getDom("toolbarmsg_label").innerHTML=a,this.getDom("toolbarmsg").style.display="",!b){var c=this.getDom("upload_dialog");c.style.display="none"}},hideToolbarMsg:function(){this.getDom("toolbarmsg").style.display="none"},mapUrl:function(a){return a?a.replace("~/",this.editor.options.UEDITOR_HOME_URL||""):""},triggerLayout:function(){var a=this.getDom();"1"==a.style.zoom?a.style.zoom="100%":a.style.zoom="1"}},b.inherits(a,baidu.editor.ui.UIBase);var g={};UE.ui.Editor=function(c){var d=new UE.Editor(c);d.options.editor=d,b.loadFile(document,{href:d.options.themePath+d.options.theme+"/css/ueditor.css",tag:"link",type:"text/css",rel:"stylesheet"});var f=d.render;return d.render=function(c){c.constructor===String&&(d.key=c,g[c]=d),b.domReady(function(){function b(){if(d.setOpt({labelMap:d.options.labelMap||d.getLang("labelMap")}),new a(d.options),c&&(c.constructor===String&&(c=document.getElementById(c)),c&&c.getAttribute("name")&&(d.options.textarea=c.getAttribute("name")),c&&/script|textarea/gi.test(c.tagName))){var b=document.createElement("div");c.parentNode.insertBefore(b,c);var g=c.value||c.innerHTML;d.options.initialContent=/^[\t\r\n ]*$/.test(g)?d.options.initialContent:g.replace(/>[\n\r\t]+([ ]{4})+/g,">").replace(/[\n\r\t]+([ ]{4})+</g,"<").replace(/>[\n\r\t]+</g,"><"),c.className&&(b.className=c.className),c.style.cssText&&(b.style.cssText=c.style.cssText),/textarea/i.test(c.tagName)?(d.textarea=c,d.textarea.style.display="none"):c.parentNode.removeChild(c),c.id&&(b.id=c.id,e.removeAttributes(c,"id")),c=b,c.innerHTML=""}e.addClass(c,"edui-"+d.options.theme),d.ui.render(c);var h=d.options;d.container=d.ui.getDom();for(var i,j=e.findParents(c,!0),k=[],l=0;i=j[l];l++)k[l]=i.style.display,i.style.display="block";if(h.initialFrameWidth)h.minFrameWidth=h.initialFrameWidth;else{h.minFrameWidth=h.initialFrameWidth=c.offsetWidth;var m=c.style.width;/%$/.test(m)&&(h.initialFrameWidth=m)}h.initialFrameHeight?h.minFrameHeight=h.initialFrameHeight:h.initialFrameHeight=h.minFrameHeight=c.offsetHeight;for(var i,l=0;i=j[l];l++)i.style.display=k[l];c.style.height&&(c.style.height=""),d.container.style.width=h.initialFrameWidth+(/%$/.test(h.initialFrameWidth)?"":"px"),d.container.style.zIndex=h.zIndex,f.call(d,d.ui.getDom("iframeholder")),d.fireEvent("afteruiready")}d.langIsReady?b():d.addListener("langReady",b)})},d},UE.getEditor=function(a,b){var c=g[a];return c||(c=g[a]=new UE.ui.Editor(b),c.render(a)),c},UE.delEditor=function(a){var b;(b=g[a])&&(b.key&&b.destroy(),delete g[a])},UE.registerUI=function(a,c,d,e){b.each(a.split(/\s+/),function(a){UE._customizeUI[a]={id:e,execFn:c,index:d}})}}(),UE.registerUI("message",function(a){function b(){var a=g.ui.getDom("toolbarbox");a&&(c.style.top=a.offsetHeight+3+"px"),c.style.zIndex=Math.max(g.options.zIndex,g.iframe.style.zIndex)+1}var c,d=baidu.editor.ui,e=d.Message,f=[],g=a;g.addListener("ready",function(){c=document.getElementById(g.ui.id+"_message_holder"),b(),setTimeout(function(){b()},500)}),g.addListener("showmessage",function(a,d){d=utils.isString(d)?{content:d}:d;var h=new e({timeout:d.timeout,type:d.type,content:d.content,keepshow:d.keepshow,editor:g}),i=d.id||"msg_"+(+new Date).toString(36);return h.render(c),f[i]=h,h.reset(d),b(),i}),g.addListener("updatemessage",function(a,b,d){d=utils.isString(d)?{content:d}:d;var e=f[b];e.render(c),e&&e.reset(d)}),g.addListener("hidemessage",function(a,b){var c=f[b];c&&c.hide()})}),UE.registerUI("autosave",function(a){var b=null,c=null;a.on("afterautosave",function(){clearTimeout(b),b=setTimeout(function(){c&&a.trigger("hidemessage",c),c=a.trigger("showmessage",{content:a.getLang("autosave.success"),timeout:2e3})},2e3)})})}(); | ||
log.rs | //! Utility function to setup logging for a Plugin instance.
use crate::{
common::{
error::Result,
log::{init, proxy::LogProxy, tee_file::TeeFile, Log, LogRecord},
},
host::configuration::PluginLogConfiguration,
}; | ///
/// Given a [`PluginConfiguration`], start the configured loggers. Consumes
/// the given log channel sender.
///
/// Starts a thread-local ['LogProxy`], given a [`LoglevelFilter`] bigger
/// than [`Off`] which forwards log records to the simulator [`LogThread`].
/// Starts [`TeeFile`] loggers, given a non-empty vector of [`TeeFile`], to
/// forward log records to output files.
pub fn setup_logging(
configuration: &PluginLogConfiguration,
log_channel: IpcSender<LogRecord>,
) -> Result<()> {
let mut loggers = Vec::with_capacity(1 + configuration.tee_files.len());
loggers.push(LogProxy::boxed(
configuration.name.as_str(),
configuration.verbosity,
log_channel,
) as Box<dyn Log>);
let tee_files: Result<Vec<_>> = configuration
.tee_files
.clone()
.into_iter()
.map(TeeFile::new)
.collect();
loggers.extend(tee_files?.into_iter().map(|l| Box::new(l) as Box<dyn Log>));
init(loggers)?;
Ok(())
} | use ipc_channel::ipc::IpcSender;
/// Setup logging for a Plugin instance. |
StaticAndLocalVariables.py | # Static variables are class level variables |
class Student:
school = 'PQR' #Static variable
def __init__(self,name,roll,section):
super().__init__()
self.name = name #Instance variable
self.roll = roll
self.section = section
def display(self):
school = 'Local School'
print('Name of student: ',self.name)
print('Roll No of student: ',self.roll)
print('Section of Student: ',self.section)
print('School of Student: ', Student.school) #Static variable
print('Local school value: ', school)
#Student.school = 'ABC School' #Another way to declare static variables
s1 = Student('Student A',101,'A')
s2 = Student('Student B',102,'B')
s1.display()
s2.display() | # Static variables are always referenced by class name
# Local variables are local to methods |
di.export.ts | import {exporters} from "../globalization";
export function | (){
return function (type: {new (...args): any}) {
exporters.push(type);
}
} | DIExport |
day02.go | /*
--- Day 2: Password Philosophy ---
Your flight departs in a few days from the coastal airport; the easiest way down to the coast from here is via toboggan.
The shopkeeper at the North Pole Toboggan Rental Shop is having a bad day. "Something's wrong with our computers; we can't log in!" You ask if you can take a look.
Their password database seems to be a little corrupted: some of the passwords wouldn't have been allowed by the Official Toboggan Corporate Policy that was in effect when they were chosen.
To try to debug the problem, they have created a list (your puzzle input) of passwords (according to the corrupted database) and the corporate policy when that password was set.
For example, suppose you have the following list:
1-3 a: abcde
1-3 b: cdefg
2-9 c: ccccccccc
Each line gives the password policy and then the password. The password policy indicates the lowest and highest number of times a given letter must appear for the password to be valid. For example, 1-3 a means that the password must contain a at least 1 time and at most 3 times.
In the above example, 2 passwords are valid. The middle password, cdefg, is not; it contains no instances of b, but needs at least 1. The first and third passwords are valid: they contain one a or nine c, both within the limits of their respective policies.
How many passwords are valid according to their policies?
--- Part Two ---
While it appears you validated the passwords correctly, they don't seem to be what the Official Toboggan Corporate Authentication System is expecting.
The shopkeeper suddenly realizes that he just accidentally explained the password policy rules from his old job at the sled rental place down the street! The Official Toboggan Corporate Policy actually works a little differently.
Each policy actually describes two positions in the password, where 1 means the first character, 2 means the second character, and so on. (Be careful; Toboggan Corporate Policies have no concept of "index zero"!) Exactly one of these positions must contain the given letter. Other occurrences of the letter are irrelevant for the purposes of policy enforcement.
Given the same example list from above:
1-3 a: abcde is valid: position 1 contains a and position 3 does not.
1-3 b: cdefg is invalid: neither position 1 nor position 3 contains b.
2-9 c: ccccccccc is invalid: both position 2 and position 9 contain c.
How many passwords are valid according to the new interpretation of the policies?
*/
package main
import (
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/FollowTheProcess/advent_of_code_2020/utils"
)
type Password struct {
Text string
Letter string
Min int
Max int
}
// Parse takes the raw line e.g. '1-3 a: abcde' and returns a Password
func | (raw string) (*Password, error) {
parts := strings.Split(raw, " ") // []string{"1-3", "a:", "abcde"}
// Should always be 3 parts
if len(parts) != 3 {
return nil, fmt.Errorf("malformed password string: %s", raw)
}
minMax := strings.Split(parts[0], "-")
if len(minMax) != 2 {
return nil, fmt.Errorf("expected 2 parts in constraint: %s", parts[0])
}
min, err := strconv.Atoi(minMax[0])
if err != nil {
return nil, fmt.Errorf("min part of constraint not a valid integer: %v", minMax[0])
}
max, err := strconv.Atoi(minMax[1])
if err != nil {
return nil, fmt.Errorf("max part of constraint not a valid integer: %v", minMax[1])
}
letter := strings.Replace(parts[1], ":", "", 1)
p := &Password{
Text: parts[2],
Letter: letter,
Min: min,
Max: max,
}
return p, nil
}
// IsValid checks whether the password is valid according to it's policy
func (p *Password) IsValid() bool {
count := strings.Count(p.Text, p.Letter)
if count >= p.Min && count <= p.Max {
return true
}
return false
}
// IsValidPart2 checks whether the password meets the part 2 policy
func (p *Password) IsValidPart2() bool {
// Compensate for no zero index, 1 actually means 0 etc
minIndex, maxIndex := p.Min-1, p.Max-1
// Only 1 of these positions can contain letter
// If both, then false
if string(p.Text[minIndex]) == p.Letter && string(p.Text[maxIndex]) == p.Letter {
return false
}
// If neither then false
if string(p.Text[minIndex]) != p.Letter && string(p.Text[maxIndex]) != p.Letter {
return false
}
// Anything else is true
return true
}
func main() {
if err := run(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func run() error {
inputFile := filepath.Join(utils.Root(), "day01", "day01.txt")
raw, err := os.ReadFile(inputFile)
if err != nil {
return err
}
lines := strings.FieldsFunc(string(raw), func(r rune) bool { return r == '\n' })
var passwords []*Password
for _, line := range lines {
p, err := Parse(line)
if err != nil {
return err
}
passwords = append(passwords, p)
}
// Count the valid ones
valid := 0
for _, password := range passwords {
if password.IsValid() {
valid++
}
}
validPart2 := 0
for _, password := range passwords {
if password.IsValidPart2() {
validPart2++
}
}
fmt.Printf("Part 1: %d\n\n", valid)
fmt.Printf("Part 2: %d\n", validPart2)
return nil
}
| Parse |
truffle-config.js | /**
* Use this file to configure your truffle project. It's seeded with some
* common settings for different networks and features like migrations,
* compilation and testing. Uncomment the ones you need or modify
* them to suit your project as necessary.
*
* More information about configuration can be found at:
*
* truffleframework.com/docs/advanced/configuration
*
* To deploy via Infura you'll need a wallet provider (like @truffle/hdwallet-provider)
* to sign your transactions before they're sent to a remote public node. Infura accounts
* are available for free at: infura.io/register.
*
* You'll also need a mnemonic - the twelve word phrase the wallet uses to generate
* public/private key pairs. If you're publishing your code to GitHub make sure you load this
* phrase from a file you've .gitignored so it doesn't accidentally become public.
*
*/
// const HDWalletProvider = require('@truffle/hdwallet-provider');
// const infuraKey = "fj4jll3k.....";
//
// const fs = require('fs');
// const mnemonic = fs.readFileSync(".secret").toString().trim();
module.exports = {
/**
* Networks define how you connect to your ethereum client and let you set the
* defaults web3 uses to send transactions. If you don't specify one truffle
* will spin up a development blockchain for you on port 9545 when you
* run `develop` or `test`. You can ask a truffle command to use a specific
* network from the command line, e.g
*
* $ truffle test --network <network-name>
*/
| // Useful for testing. The `development` name is special - truffle uses it by default
// if it's defined here and no other network is specified at the command line.
// You should run a client (like ganache-cli, geth or parity) in a separate terminal
// tab if you use this network and you must also set the `host`, `port` and `network_id`
// options below to some value.
//
development: {
host: "127.0.0.1", // Localhost (default: none)
port: 8545, // Standard Ethereum port (default: none)
network_id: "5474343", // Any network (default: none)
},
// Another network with more advanced options...
// advanced: {
// port: 8777, // Custom port
// network_id: 1342, // Custom network
// gas: 8500000, // Gas sent with each transaction (default: ~6700000)
// gasPrice: 20000000000, // 20 gwei (in wei) (default: 100 gwei)
// from: <address>, // Account to send txs from (default: accounts[0])
// websockets: true // Enable EventEmitter interface for web3 (default: false)
// },
// Useful for deploying to a public network.
// NB: It's important to wrap the provider as a function.
// ropsten: {
// provider: () => new HDWalletProvider(mnemonic, `https://ropsten.infura.io/v3/YOUR-PROJECT-ID`),
// network_id: 3, // Ropsten's id
// gas: 5500000, // Ropsten has a lower block limit than mainnet
// confirmations: 2, // # of confs to wait between deployments. (default: 0)
// timeoutBlocks: 200, // # of blocks before a deployment times out (minimum/default: 50)
// skipDryRun: true // Skip dry run before migrations? (default: false for public nets )
// },
// Useful for private networks
// private: {
// provider: () => new HDWalletProvider(mnemonic, `https://network.io`),
// network_id: 2111, // This network is yours, in the cloud.
// production: true // Treats this network as if it was a public net. (default: false)
// }
},
// Set default mocha options here, use special reporters etc.
mocha: {
// timeout: 100000
},
// Configure your compilers
compilers: {
solc: {
// version: "0.5.1", // Fetch exact version from solc-bin (default: truffle's version)
// docker: true, // Use "0.5.1" you've installed locally with docker (default: false)
settings: { // See the solidity docs for advice about optimization and evmVersion
optimizer: {
enabled: true,
runs: 200
},
// evmVersion: "byzantium"
}
}
}
} | networks: { |
main.py | # -*- coding: utf-8 -*-
import base64
import datetime
import json
import sys
import time
import random
import traceback
from datetime import date
from calendar import monthrange
import hashlib
import re
import execjs
from dateutil.relativedelta import relativedelta
from requests.utils import add_dict_to_cookiejar
reload(sys)
sys.setdefaultencoding('utf8')
if __name__ == '__main__':
sys.path.append('../..')
sys.path.append('../../..')
sys.path.append('../../../..')
from crawler.base_crawler import BaseCrawler
from tool import parse_call_record, parse_call_record_short
else:
from worker.crawler.base_crawler import BaseCrawler
from worker.crawler.china_mobile.jiangsu.tool import parse_call_record, parse_call_record_short
class Crawler(BaseCrawler):
def __init__(self, **kwargs):
super(Crawler, self).__init__(**kwargs)
# to keep time > 30 seconds between sending two sms veirfication
self.sms_send_time = None
self.start_url = ""
def need_parameters(self, **kwargs):
return ['pin_pwd']
def get_login_verify_type(self, **kwargs):
return 'SMS'
def enPwd(self, pwd):
js_source = """
var CryptoJS=CryptoJS||function(u,l){var d={},n=d.lib={},p=function(){},s=n.Base={extend:function(a){p.prototype=this;var c=new p;a&&c.mixIn(a);c.hasOwnProperty("init")||(c.init=function(){c.$super.init.apply(this,arguments)});c.init.prototype=c;c.$super=this;return c},create:function(){var a=this.extend();a.init.apply(a,arguments);return a},init:function(){},mixIn:function(a){for(var c in a)a.hasOwnProperty(c)&&(this[c]=a[c]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}},
q=n.WordArray=s.extend({init:function(a,c){a=this.words=a||[];this.sigBytes=c!=l?c:4*a.length},toString:function(a){return(a||v).stringify(this)},concat:function(a){var c=this.words,m=a.words,f=this.sigBytes;a=a.sigBytes;this.clamp();if(f%4)for(var t=0;t<a;t++)c[f+t>>>2]|=(m[t>>>2]>>>24-8*(t%4)&255)<<24-8*((f+t)%4);else if(65535<m.length)for(t=0;t<a;t+=4)c[f+t>>>2]=m[t>>>2];else c.push.apply(c,m);this.sigBytes+=a;return this},clamp:function(){var a=this.words,c=this.sigBytes;a[c>>>2]&=4294967295<<
32-8*(c%4);a.length=u.ceil(c/4)},clone:function(){var a=s.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var c=[],m=0;m<a;m+=4)c.push(4294967296*u.random()|0);return new q.init(c,a)}}),w=d.enc={},v=w.Hex={stringify:function(a){var c=a.words;a=a.sigBytes;for(var m=[],f=0;f<a;f++){var t=c[f>>>2]>>>24-8*(f%4)&255;m.push((t>>>4).toString(16));m.push((t&15).toString(16))}return m.join("")},parse:function(a){for(var c=a.length,m=[],f=0;f<c;f+=2)m[f>>>3]|=parseInt(a.substr(f,
2),16)<<24-4*(f%8);return new q.init(m,c/2)}},b=w.Latin1={stringify:function(a){var c=a.words;a=a.sigBytes;for(var m=[],f=0;f<a;f++)m.push(String.fromCharCode(c[f>>>2]>>>24-8*(f%4)&255));return m.join("")},parse:function(a){for(var c=a.length,m=[],f=0;f<c;f++)m[f>>>2]|=(a.charCodeAt(f)&255)<<24-8*(f%4);return new q.init(m,c)}},x=w.Utf8={stringify:function(a){try{return decodeURIComponent(escape(b.stringify(a)))}catch(c){throw Error("Malformed UTF-8 data");}},parse:function(a){return b.parse(unescape(encodeURIComponent(a)))}},
r=n.BufferedBlockAlgorithm=s.extend({reset:function(){this._data=new q.init;this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=x.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var c=this._data,m=c.words,f=c.sigBytes,t=this.blockSize,b=f/(4*t),b=a?u.ceil(b):u.max((b|0)-this._minBufferSize,0);a=b*t;f=u.min(4*a,f);if(a){for(var e=0;e<a;e+=t)this._doProcessBlock(m,e);e=m.splice(0,a);c.sigBytes-=f}return new q.init(e,f)},clone:function(){var a=s.clone.call(this);
a._data=this._data.clone();return a},_minBufferSize:0});n.Hasher=r.extend({cfg:s.extend(),init:function(a){this.cfg=this.cfg.extend(a);this.reset()},reset:function(){r.reset.call(this);this._doReset()},update:function(a){this._append(a);this._process();return this},finalize:function(a){a&&this._append(a);return this._doFinalize()},blockSize:16,_createHelper:function(a){return function(c,m){return(new a.init(m)).finalize(c)}},_createHmacHelper:function(a){return function(c,m){return(new e.HMAC.init(a,
m)).finalize(c)}}});var e=d.algo={};return d}(Math);
(function(){var u=CryptoJS,l=u.lib.WordArray;u.enc.Base64={stringify:function(d){var n=d.words,l=d.sigBytes,s=this._map;d.clamp();d=[];for(var q=0;q<l;q+=3)for(var w=(n[q>>>2]>>>24-8*(q%4)&255)<<16|(n[q+1>>>2]>>>24-8*((q+1)%4)&255)<<8|n[q+2>>>2]>>>24-8*((q+2)%4)&255,v=0;4>v&&q+0.75*v<l;v++)d.push(s.charAt(w>>>6*(3-v)&63));if(n=s.charAt(64))for(;d.length%4;)d.push(n);return d.join("")},parse:function(d){var n=d.length,p=this._map,s=p.charAt(64);s&&(s=d.indexOf(s),-1!=s&&(n=s));for(var s=[],q=0,w=0;w<
n;w++)if(w%4){var v=p.indexOf(d.charAt(w-1))<<2*(w%4),b=p.indexOf(d.charAt(w))>>>6-2*(w%4);s[q>>>2]|=(v|b)<<24-8*(q%4);q++}return l.create(s,q)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}})();
(function(u){function l(b,e,a,c,m,f,t){b=b+(e&a|~e&c)+m+t;return(b<<f|b>>>32-f)+e}function d(b,e,a,c,m,f,t){b=b+(e&c|a&~c)+m+t;return(b<<f|b>>>32-f)+e}function n(b,e,a,c,m,f,t){b=b+(e^a^c)+m+t;return(b<<f|b>>>32-f)+e}function p(b,e,a,c,m,f,t){b=b+(a^(e|~c))+m+t;return(b<<f|b>>>32-f)+e}for(var s=CryptoJS,q=s.lib,w=q.WordArray,v=q.Hasher,q=s.algo,b=[],x=0;64>x;x++)b[x]=4294967296*u.abs(u.sin(x+1))|0;q=q.MD5=v.extend({_doReset:function(){this._hash=new w.init([1732584193,4023233417,2562383102,271733878])},
_doProcessBlock:function(r,e){for(var a=0;16>a;a++){var c=e+a,m=r[c];r[c]=(m<<8|m>>>24)&16711935|(m<<24|m>>>8)&4278255360}var a=this._hash.words,c=r[e+0],m=r[e+1],f=r[e+2],t=r[e+3],y=r[e+4],q=r[e+5],s=r[e+6],w=r[e+7],v=r[e+8],u=r[e+9],x=r[e+10],z=r[e+11],A=r[e+12],B=r[e+13],C=r[e+14],D=r[e+15],g=a[0],h=a[1],j=a[2],k=a[3],g=l(g,h,j,k,c,7,b[0]),k=l(k,g,h,j,m,12,b[1]),j=l(j,k,g,h,f,17,b[2]),h=l(h,j,k,g,t,22,b[3]),g=l(g,h,j,k,y,7,b[4]),k=l(k,g,h,j,q,12,b[5]),j=l(j,k,g,h,s,17,b[6]),h=l(h,j,k,g,w,22,b[7]),
g=l(g,h,j,k,v,7,b[8]),k=l(k,g,h,j,u,12,b[9]),j=l(j,k,g,h,x,17,b[10]),h=l(h,j,k,g,z,22,b[11]),g=l(g,h,j,k,A,7,b[12]),k=l(k,g,h,j,B,12,b[13]),j=l(j,k,g,h,C,17,b[14]),h=l(h,j,k,g,D,22,b[15]),g=d(g,h,j,k,m,5,b[16]),k=d(k,g,h,j,s,9,b[17]),j=d(j,k,g,h,z,14,b[18]),h=d(h,j,k,g,c,20,b[19]),g=d(g,h,j,k,q,5,b[20]),k=d(k,g,h,j,x,9,b[21]),j=d(j,k,g,h,D,14,b[22]),h=d(h,j,k,g,y,20,b[23]),g=d(g,h,j,k,u,5,b[24]),k=d(k,g,h,j,C,9,b[25]),j=d(j,k,g,h,t,14,b[26]),h=d(h,j,k,g,v,20,b[27]),g=d(g,h,j,k,B,5,b[28]),k=d(k,g,
h,j,f,9,b[29]),j=d(j,k,g,h,w,14,b[30]),h=d(h,j,k,g,A,20,b[31]),g=n(g,h,j,k,q,4,b[32]),k=n(k,g,h,j,v,11,b[33]),j=n(j,k,g,h,z,16,b[34]),h=n(h,j,k,g,C,23,b[35]),g=n(g,h,j,k,m,4,b[36]),k=n(k,g,h,j,y,11,b[37]),j=n(j,k,g,h,w,16,b[38]),h=n(h,j,k,g,x,23,b[39]),g=n(g,h,j,k,B,4,b[40]),k=n(k,g,h,j,c,11,b[41]),j=n(j,k,g,h,t,16,b[42]),h=n(h,j,k,g,s,23,b[43]),g=n(g,h,j,k,u,4,b[44]),k=n(k,g,h,j,A,11,b[45]),j=n(j,k,g,h,D,16,b[46]),h=n(h,j,k,g,f,23,b[47]),g=p(g,h,j,k,c,6,b[48]),k=p(k,g,h,j,w,10,b[49]),j=p(j,k,g,h,
C,15,b[50]),h=p(h,j,k,g,q,21,b[51]),g=p(g,h,j,k,A,6,b[52]),k=p(k,g,h,j,t,10,b[53]),j=p(j,k,g,h,x,15,b[54]),h=p(h,j,k,g,m,21,b[55]),g=p(g,h,j,k,v,6,b[56]),k=p(k,g,h,j,D,10,b[57]),j=p(j,k,g,h,s,15,b[58]),h=p(h,j,k,g,B,21,b[59]),g=p(g,h,j,k,y,6,b[60]),k=p(k,g,h,j,z,10,b[61]),j=p(j,k,g,h,f,15,b[62]),h=p(h,j,k,g,u,21,b[63]);a[0]=a[0]+g|0;a[1]=a[1]+h|0;a[2]=a[2]+j|0;a[3]=a[3]+k|0},_doFinalize:function(){var b=this._data,e=b.words,a=8*this._nDataBytes,c=8*b.sigBytes;e[c>>>5]|=128<<24-c%32;var m=u.floor(a/
4294967296);e[(c+64>>>9<<4)+15]=(m<<8|m>>>24)&16711935|(m<<24|m>>>8)&4278255360;e[(c+64>>>9<<4)+14]=(a<<8|a>>>24)&16711935|(a<<24|a>>>8)&4278255360;b.sigBytes=4*(e.length+1);this._process();b=this._hash;e=b.words;for(a=0;4>a;a++)c=e[a],e[a]=(c<<8|c>>>24)&16711935|(c<<24|c>>>8)&4278255360;return b},clone:function(){var b=v.clone.call(this);b._hash=this._hash.clone();return b}});s.MD5=v._createHelper(q);s.HmacMD5=v._createHmacHelper(q)})(Math);
(function(){var u=CryptoJS,l=u.lib,d=l.Base,n=l.WordArray,l=u.algo,p=l.EvpKDF=d.extend({cfg:d.extend({keySize:4,hasher:l.MD5,iterations:1}),init:function(d){this.cfg=this.cfg.extend(d)},compute:function(d,l){for(var p=this.cfg,v=p.hasher.create(),b=n.create(),u=b.words,r=p.keySize,p=p.iterations;u.length<r;){e&&v.update(e);var e=v.update(d).finalize(l);v.reset();for(var a=1;a<p;a++)e=v.finalize(e),v.reset();b.concat(e)}b.sigBytes=4*r;return b}});u.EvpKDF=function(d,l,n){return p.create(n).compute(d,
l)}})();
CryptoJS.lib.Cipher||function(u){var l=CryptoJS,d=l.lib,n=d.Base,p=d.WordArray,s=d.BufferedBlockAlgorithm,q=l.enc.Base64,w=l.algo.EvpKDF,v=d.Cipher=s.extend({cfg:n.extend(),createEncryptor:function(m,a){return this.create(this._ENC_XFORM_MODE,m,a)},createDecryptor:function(m,a){return this.create(this._DEC_XFORM_MODE,m,a)},init:function(m,a,b){this.cfg=this.cfg.extend(b);this._xformMode=m;this._key=a;this.reset()},reset:function(){s.reset.call(this);this._doReset()},process:function(a){this._append(a);return this._process()},
finalize:function(a){a&&this._append(a);return this._doFinalize()},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(m){return{encrypt:function(f,b,e){return("string"==typeof b?c:a).encrypt(m,f,b,e)},decrypt:function(f,b,e){return("string"==typeof b?c:a).decrypt(m,f,b,e)}}}});d.StreamCipher=v.extend({_doFinalize:function(){return this._process(!0)},blockSize:1});var b=l.mode={},x=function(a,f,b){var c=this._iv;c?this._iv=u:c=this._prevBlock;for(var e=0;e<b;e++)a[f+e]^=
c[e]},r=(d.BlockCipherMode=n.extend({createEncryptor:function(a,f){return this.Encryptor.create(a,f)},createDecryptor:function(a,f){return this.Decryptor.create(a,f)},init:function(a,f){this._cipher=a;this._iv=f}})).extend();r.Encryptor=r.extend({processBlock:function(a,f){var b=this._cipher,c=b.blockSize;x.call(this,a,f,c);b.encryptBlock(a,f);this._prevBlock=a.slice(f,f+c)}});r.Decryptor=r.extend({processBlock:function(a,b){var c=this._cipher,e=c.blockSize,d=a.slice(b,b+e);c.decryptBlock(a,b);x.call(this,
a,b,e);this._prevBlock=d}});b=b.CBC=r;r=(l.pad={}).Pkcs7={pad:function(a,b){for(var c=4*b,c=c-a.sigBytes%c,e=c<<24|c<<16|c<<8|c,d=[],l=0;l<c;l+=4)d.push(e);c=p.create(d,c);a.concat(c)},unpad:function(a){a.sigBytes-=a.words[a.sigBytes-1>>>2]&255}};d.BlockCipher=v.extend({cfg:v.cfg.extend({mode:b,padding:r}),reset:function(){v.reset.call(this);var a=this.cfg,c=a.iv,a=a.mode;if(this._xformMode==this._ENC_XFORM_MODE)var b=a.createEncryptor;else b=a.createDecryptor,this._minBufferSize=1;this._mode=b.call(a,
this,c&&c.words)},_doProcessBlock:function(a,c){this._mode.processBlock(a,c)},_doFinalize:function(){var a=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){a.pad(this._data,this.blockSize);var c=this._process(!0)}else c=this._process(!0),a.unpad(c);return c},blockSize:4});var e=d.CipherParams=n.extend({init:function(a){this.mixIn(a)},toString:function(a){return(a||this.formatter).stringify(this)}}),b=(l.format={}).OpenSSL={stringify:function(a){var c=a.ciphertext;a=a.salt;return(a?p.create([1398893684,
1701076831]).concat(a).concat(c):c).toString(q)},parse:function(a){a=q.parse(a);var c=a.words;if(1398893684==c[0]&&1701076831==c[1]){var b=p.create(c.slice(2,4));c.splice(0,4);a.sigBytes-=16}return e.create({ciphertext:a,salt:b})}},a=d.SerializableCipher=n.extend({cfg:n.extend({format:b}),encrypt:function(a,c,b,d){d=this.cfg.extend(d);var l=a.createEncryptor(b,d);c=l.finalize(c);l=l.cfg;return e.create({ciphertext:c,key:b,iv:l.iv,algorithm:a,mode:l.mode,padding:l.padding,blockSize:a.blockSize,formatter:d.format})},
decrypt:function(a,c,b,e){e=this.cfg.extend(e);c=this._parse(c,e.format);return a.createDecryptor(b,e).finalize(c.ciphertext)},_parse:function(a,c){return"string"==typeof a?c.parse(a,this):a}}),l=(l.kdf={}).OpenSSL={execute:function(a,c,b,d){d||(d=p.random(8));a=w.create({keySize:c+b}).compute(a,d);b=p.create(a.words.slice(c),4*b);a.sigBytes=4*c;return e.create({key:a,iv:b,salt:d})}},c=d.PasswordBasedCipher=a.extend({cfg:a.cfg.extend({kdf:l}),encrypt:function(c,b,e,d){d=this.cfg.extend(d);e=d.kdf.execute(e,
c.keySize,c.ivSize);d.iv=e.iv;c=a.encrypt.call(this,c,b,e.key,d);c.mixIn(e);return c},decrypt:function(c,b,e,d){d=this.cfg.extend(d);b=this._parse(b,d.format);e=d.kdf.execute(e,c.keySize,c.ivSize,b.salt);d.iv=e.iv;return a.decrypt.call(this,c,b,e.key,d)}})}();
(function(){function u(b,a){var c=(this._lBlock>>>b^this._rBlock)&a;this._rBlock^=c;this._lBlock^=c<<b}function l(b,a){var c=(this._rBlock>>>b^this._lBlock)&a;this._lBlock^=c;this._rBlock^=c<<b}var d=CryptoJS,n=d.lib,p=n.WordArray,n=n.BlockCipher,s=d.algo,q=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4],w=[14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2,41,52,31,37,47,
55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32],v=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],b=[{"0":8421888,268435456:32768,536870912:8421378,805306368:2,1073741824:512,1342177280:8421890,1610612736:8389122,1879048192:8388608,2147483648:514,2415919104:8389120,2684354560:33280,2952790016:8421376,3221225472:32770,3489660928:8388610,3758096384:0,4026531840:33282,134217728:0,402653184:8421890,671088640:33282,939524096:32768,1207959552:8421888,1476395008:512,1744830464:8421378,2013265920:2,
2281701376:8389120,2550136832:33280,2818572288:8421376,3087007744:8389122,3355443200:8388610,3623878656:32770,3892314112:514,4160749568:8388608,1:32768,268435457:2,536870913:8421888,805306369:8388608,1073741825:8421378,1342177281:33280,1610612737:512,1879048193:8389122,2147483649:8421890,2415919105:8421376,2684354561:8388610,2952790017:33282,3221225473:514,3489660929:8389120,3758096385:32770,4026531841:0,134217729:8421890,402653185:8421376,671088641:8388608,939524097:512,1207959553:32768,1476395009:8388610,
1744830465:2,2013265921:33282,2281701377:32770,2550136833:8389122,2818572289:514,3087007745:8421888,3355443201:8389120,3623878657:0,3892314113:33280,4160749569:8421378},{"0":1074282512,16777216:16384,33554432:524288,50331648:1074266128,67108864:1073741840,83886080:1074282496,100663296:1073758208,117440512:16,134217728:540672,150994944:1073758224,167772160:1073741824,184549376:540688,201326592:524304,218103808:0,234881024:16400,251658240:1074266112,8388608:1073758208,25165824:540688,41943040:16,58720256:1073758224,
75497472:1074282512,92274688:1073741824,109051904:524288,125829120:1074266128,142606336:524304,159383552:0,176160768:16384,192937984:1074266112,209715200:1073741840,226492416:540672,243269632:1074282496,260046848:16400,268435456:0,285212672:1074266128,301989888:1073758224,318767104:1074282496,335544320:1074266112,352321536:16,369098752:540688,385875968:16384,402653184:16400,419430400:524288,436207616:524304,452984832:1073741840,469762048:540672,486539264:1073758208,503316480:1073741824,520093696:1074282512,
276824064:540688,293601280:524288,310378496:1074266112,327155712:16384,343932928:1073758208,360710144:1074282512,377487360:16,394264576:1073741824,411041792:1074282496,427819008:1073741840,444596224:1073758224,461373440:524304,478150656:0,494927872:16400,511705088:1074266128,528482304:540672},{"0":260,1048576:0,2097152:67109120,3145728:65796,4194304:65540,5242880:67108868,6291456:67174660,7340032:67174400,8388608:67108864,9437184:67174656,10485760:65792,11534336:67174404,12582912:67109124,13631488:65536,
14680064:4,15728640:256,524288:67174656,1572864:67174404,2621440:0,3670016:67109120,4718592:67108868,5767168:65536,6815744:65540,7864320:260,8912896:4,9961472:256,11010048:67174400,12058624:65796,13107200:65792,14155776:67109124,15204352:67174660,16252928:67108864,16777216:67174656,17825792:65540,18874368:65536,19922944:67109120,20971520:256,22020096:67174660,23068672:67108868,24117248:0,25165824:67109124,26214400:67108864,27262976:4,28311552:65792,29360128:67174400,30408704:260,31457280:65796,32505856:67174404,
17301504:67108864,18350080:260,19398656:67174656,20447232:0,21495808:65540,22544384:67109120,23592960:256,24641536:67174404,25690112:65536,26738688:67174660,27787264:65796,28835840:67108868,29884416:67109124,30932992:67174400,31981568:4,33030144:65792},{"0":2151682048,65536:2147487808,131072:4198464,196608:2151677952,262144:0,327680:4198400,393216:2147483712,458752:4194368,524288:2147483648,589824:4194304,655360:64,720896:2147487744,786432:2151678016,851968:4160,917504:4096,983040:2151682112,32768:2147487808,
98304:64,163840:2151678016,229376:2147487744,294912:4198400,360448:2151682112,425984:0,491520:2151677952,557056:4096,622592:2151682048,688128:4194304,753664:4160,819200:2147483648,884736:4194368,950272:4198464,1015808:2147483712,1048576:4194368,1114112:4198400,1179648:2147483712,1245184:0,1310720:4160,1376256:2151678016,1441792:2151682048,1507328:2147487808,1572864:2151682112,1638400:2147483648,1703936:2151677952,1769472:4198464,1835008:2147487744,1900544:4194304,1966080:64,2031616:4096,1081344:2151677952,
1146880:2151682112,1212416:0,1277952:4198400,1343488:4194368,1409024:2147483648,1474560:2147487808,1540096:64,1605632:2147483712,1671168:4096,1736704:2147487744,1802240:2151678016,1867776:4160,1933312:2151682048,1998848:4194304,2064384:4198464},{"0":128,4096:17039360,8192:262144,12288:536870912,16384:537133184,20480:16777344,24576:553648256,28672:262272,32768:16777216,36864:537133056,40960:536871040,45056:553910400,49152:553910272,53248:0,57344:17039488,61440:553648128,2048:17039488,6144:553648256,
10240:128,14336:17039360,18432:262144,22528:537133184,26624:553910272,30720:536870912,34816:537133056,38912:0,43008:553910400,47104:16777344,51200:536871040,55296:553648128,59392:16777216,63488:262272,65536:262144,69632:128,73728:536870912,77824:553648256,81920:16777344,86016:553910272,90112:537133184,94208:16777216,98304:553910400,102400:553648128,106496:17039360,110592:537133056,114688:262272,118784:536871040,122880:0,126976:17039488,67584:553648256,71680:16777216,75776:17039360,79872:537133184,
83968:536870912,88064:17039488,92160:128,96256:553910272,100352:262272,104448:553910400,108544:0,112640:553648128,116736:16777344,120832:262144,124928:537133056,129024:536871040},{"0":268435464,256:8192,512:270532608,768:270540808,1024:268443648,1280:2097152,1536:2097160,1792:268435456,2048:0,2304:268443656,2560:2105344,2816:8,3072:270532616,3328:2105352,3584:8200,3840:270540800,128:270532608,384:270540808,640:8,896:2097152,1152:2105352,1408:268435464,1664:268443648,1920:8200,2176:2097160,2432:8192,
2688:268443656,2944:270532616,3200:0,3456:270540800,3712:2105344,3968:268435456,4096:268443648,4352:270532616,4608:270540808,4864:8200,5120:2097152,5376:268435456,5632:268435464,5888:2105344,6144:2105352,6400:0,6656:8,6912:270532608,7168:8192,7424:268443656,7680:270540800,7936:2097160,4224:8,4480:2105344,4736:2097152,4992:268435464,5248:268443648,5504:8200,5760:270540808,6016:270532608,6272:270540800,6528:270532616,6784:8192,7040:2105352,7296:2097160,7552:0,7808:268435456,8064:268443656},{"0":1048576,
16:33555457,32:1024,48:1049601,64:34604033,80:0,96:1,112:34603009,128:33555456,144:1048577,160:33554433,176:34604032,192:34603008,208:1025,224:1049600,240:33554432,8:34603009,24:0,40:33555457,56:34604032,72:1048576,88:33554433,104:33554432,120:1025,136:1049601,152:33555456,168:34603008,184:1048577,200:1024,216:34604033,232:1,248:1049600,256:33554432,272:1048576,288:33555457,304:34603009,320:1048577,336:33555456,352:34604032,368:1049601,384:1025,400:34604033,416:1049600,432:1,448:0,464:34603008,480:33554433,
496:1024,264:1049600,280:33555457,296:34603009,312:1,328:33554432,344:1048576,360:1025,376:34604032,392:33554433,408:34603008,424:0,440:34604033,456:1049601,472:1024,488:33555456,504:1048577},{"0":134219808,1:131072,2:134217728,3:32,4:131104,5:134350880,6:134350848,7:2048,8:134348800,9:134219776,10:133120,11:134348832,12:2080,13:0,14:134217760,15:133152,2147483648:2048,2147483649:134350880,2147483650:134219808,2147483651:134217728,2147483652:134348800,2147483653:133120,2147483654:133152,2147483655:32,
2147483656:134217760,2147483657:2080,2147483658:131104,2147483659:134350848,2147483660:0,2147483661:134348832,2147483662:134219776,2147483663:131072,16:133152,17:134350848,18:32,19:2048,20:134219776,21:134217760,22:134348832,23:131072,24:0,25:131104,26:134348800,27:134219808,28:134350880,29:133120,30:2080,31:134217728,2147483664:131072,2147483665:2048,2147483666:134348832,2147483667:133152,2147483668:32,2147483669:134348800,2147483670:134217728,2147483671:134219808,2147483672:134350880,2147483673:134217760,
2147483674:134219776,2147483675:0,2147483676:133120,2147483677:2080,2147483678:131104,2147483679:134350848}],x=[4160749569,528482304,33030144,2064384,129024,8064,504,2147483679],r=s.DES=n.extend({_doReset:function(){for(var b=this._key.words,a=[],c=0;56>c;c++){var d=q[c]-1;a[c]=b[d>>>5]>>>31-d%32&1}b=this._subKeys=[];for(d=0;16>d;d++){for(var f=b[d]=[],l=v[d],c=0;24>c;c++)f[c/6|0]|=a[(w[c]-1+l)%28]<<31-c%6,f[4+(c/6|0)]|=a[28+(w[c+24]-1+l)%28]<<31-c%6;f[0]=f[0]<<1|f[0]>>>31;for(c=1;7>c;c++)f[c]>>>=
4*(c-1)+3;f[7]=f[7]<<5|f[7]>>>27}a=this._invSubKeys=[];for(c=0;16>c;c++)a[c]=b[15-c]},encryptBlock:function(b,a){this._doCryptBlock(b,a,this._subKeys)},decryptBlock:function(b,a){this._doCryptBlock(b,a,this._invSubKeys)},_doCryptBlock:function(e,a,c){this._lBlock=e[a];this._rBlock=e[a+1];u.call(this,4,252645135);u.call(this,16,65535);l.call(this,2,858993459);l.call(this,8,16711935);u.call(this,1,1431655765);for(var d=0;16>d;d++){for(var f=c[d],n=this._lBlock,p=this._rBlock,q=0,r=0;8>r;r++)q|=b[r][((p^
f[r])&x[r])>>>0];this._lBlock=p;this._rBlock=n^q}c=this._lBlock;this._lBlock=this._rBlock;this._rBlock=c;u.call(this,1,1431655765);l.call(this,8,16711935);l.call(this,2,858993459);u.call(this,16,65535);u.call(this,4,252645135);e[a]=this._lBlock;e[a+1]=this._rBlock},keySize:2,ivSize:2,blockSize:2});d.DES=n._createHelper(r);s=s.TripleDES=n.extend({_doReset:function(){var b=this._key.words;this._des1=r.createEncryptor(p.create(b.slice(0,2)));this._des2=r.createEncryptor(p.create(b.slice(2,4)));this._des3=
r.createEncryptor(p.create(b.slice(4,6)))},encryptBlock:function(b,a){this._des1.encryptBlock(b,a);this._des2.decryptBlock(b,a);this._des3.encryptBlock(b,a)},decryptBlock:function(b,a){this._des3.decryptBlock(b,a);this._des2.encryptBlock(b,a);this._des1.decryptBlock(b,a)},keySize:6,ivSize:2,blockSize:2});d.TripleDES=n._createHelper(s)})();
CryptoJS.mode.ECB = (function () {
var ECB = CryptoJS.lib.BlockCipherMode.extend();
ECB.Encryptor = ECB.extend({
processBlock: function (words, offset) {
this._cipher.encryptBlock(words, offset);
}
});
ECB.Decryptor = ECB.extend({
processBlock: function (words, offset) {
this._cipher.decryptBlock(words, offset);
}
});
return ECB;
}());
function encryptByDES(message, key) {
var keyHex = CryptoJS.enc.Utf8.parse(key);
var encrypted = CryptoJS.DES.encrypt(message, keyHex, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
return encrypted.toString();
}
"""
return execjs.compile(js_source).call("encryptByDES", pwd, "1234567890")
def | (self, **kwargs):
#初始请求
start_time = str(int(time.time() * 1000))
start_url = 'http://service.js.10086.cn/my/MY_QDCX.html?t={}'.format(start_time)
self.start_url = 'my/MY_QDCX.html?t={}'.format(start_time)
code, key, resp = self.get(start_url)
if code != 0:
return code, key, ""
#登录首次请求
login_url = "https://service.js.10086.cn/actionDispatcher.do"
headers = {
'Referer': 'http://service.js.10086.cn/login.html?url=my/MY_QDCX.html',
}
try:
data = {
'userLoginTransferProtocol': 'https',
'redirectUrl': self.start_url + "#home",
'reqUrl': 'login',
'busiNum': 'LOGIN',
'operType': '0',
'passwordType': '1',
'isSavePasswordVal': '0',
'isSavePasswordVal_N': '1',
'currentD': '1',
'loginFormTab': '#home',
'loginType': '1',
'smsFlag': '1',
'smsCode3': '',
'mobile': kwargs['tel'],
'city': 'NJDQ', #
'password': self.enPwd(kwargs['pin_pwd']),
'password3': '',
'verifyCode': '请输入验证码',
}
except:
error = traceback.format_exc()
self.log("crawler", "param_error pin_pwd:{} error:{}".format(kwargs['pin_pwd'], error), "")
return 9, "param_error"
code, key, resp = self.post(login_url, data=data, headers=headers)
if code != 0:
return code, key
if "resultCode=-BSP10001" not in resp.text:
self.log("crawler", "unknown_error", resp)
return 9, "unknown_error", ""
# 发短信
send_sms_url = "http://service.js.10086.cn/actionDispatcher.do"
data = {
'reqUrl': 'login',
'busiNum': 'LOGIN',
'fucName': 'sendLoginMsg',
'flag': '1',
}
code, key, resp = self.post(send_sms_url, data=data)
if code != 0:
return code, key
if '"resultCode":"0"' in resp.text and '"success":true' in resp.text:
return 0, "success", ""
else:
self.log("crawler", "登录短信发送未知错误", resp)
return 9, "send_sms_error", ""
# code, key, resp = self.get("http://service.js.10086.cn/login.html?url=my/MY_QDCX.html")
# if code != 0:
# if isinstance(resp, str):
# pass
# elif resp.status_code == 404:
# return 9, 'website_busy_error', ""
# return code, key, ""
# code, key, resp = self.get("http://service.js.10086.cn/imageVerifyCode?t=new&r=0.611200696976353")
# if code != 0:
# return code, key, ""
# code, key, resp = self.get("http://service.js.10086.cn/imageVerifyCode?t=new&r=0.2331200696976353")
# if code != 0:
# if isinstance(resp, str):
# pass
# elif resp.status_code == 404:
# return 9, 'website_busy_error', ""
# return code, key, ""
# return 0, 'success', ""
# return 0, 'success', resp
def get_call_log_by_month(self, year, month):
data = {}
data['reqUrl'] = 'MY_QDCXQueryNew'
data['busiNum'] = 'QDCX'
data['queryMonth'] = "%d%02d" % (year, month)
data['queryItem'] = 1
data['qryPages'] = ''
data['qryNo'] = '1'
data['operType'] = '3'
data['queryBeginTime'] = "%s-%02d-01" % (year, month)
data['queryEndTime'] = "%s-%02d-31" % (year, month)
headers = {
"X-Requested-With": "XMLHttpRequest",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"Referer": "http://service.js.10086.cn/my/MY_QDCX.html"
}
bill_detail_url = "http://service.js.10086.cn/my/actionDispatcher.do"
code, key, resp = self.post(bill_detail_url, data=data, headers=headers)
if code != 0:
return code, key, "", resp
return 0, "success", "", resp
def login(self, **kwargs):
# get cookies
# login_url = "http://service.js.10086.cn/login.html"
# headers = {
# "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
# "Accept-Encoding": "gzip, deflate",
# "Accept-Language": "zh-CN,zh;q=0.9"
# }
# def rand_browser_finger():
# return hashlib.md5(str(random.randint(1000000000, 9999999999))).hexdigest()
# add_dict_to_cookiejar(self.session.cookies,
# {
# "CmProvid": "js",
# "mywaytoopen": rand_browser_finger(),
# "login_error_number_https": "15094393043",
# "login_error_loginType_https": "1"
# }
# )
# headers = {
# "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
# "Referer": "http://service.js.10086.cn/login.html",
# "Accept-Encoding": "gzip, deflate",
# "Accept-Language": "zh-CN,zh;q=0.9"
# }
# url = "http://service.js.10086.cn/actionDispatcher.do"
# headers = {
# "X-Requested-With": "XMLHttpRequest",
# "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
# "Referer": "http://service.js.10086.cn/login.html",
# "Accept-Encoding": "gzip, deflate",
# "Accept-Language": "zh-CN,zh;q=0.9"
# }
# data = {
# "reqUrl": "MY_WDXX",
# "methodNew": "getMsgCount"
# }
# code, key, resp = self.post(url, headers=headers, data=data)
# if code != 0:
# return code, key
# temp_time = int(time.time() * 1000)
# try:
# pwd = self.enPwd(kwargs['pin_pwd'])
# except:
# error = traceback.format_exc()
# self.log("crawler", "记录错误{} {}".format(kwargs['pin_pwd'], error), "")
# return 9, "website_busy_error"
# LOGIN_URL = 'https://service.js.10086.cn/actionDispatcher.do'
# data = {
# "userLoginTransferProtocol": "https",
# "redirectUrl": "index.html",
# "reqUrl": "login",
# "busiNum": "LOGIN",
# "operType": "0",
# "passwordType": "1",
# "isSavePasswordVal": "0",
# "isSavePasswordVal_N": "1",
# "currentD": "1",
# "loginFormTab": "http",
# "loginType": "1",
# "smsFlag": "1",
# "smsCode3": "",
# "mobile": kwargs['tel'],
# "city": "NJDQ",
# "password": pwd,
# "password3": "",
# "verifyCode": "%E8%AF%B7%E8%BE%93%E5%85%A5%E9%AA%8C%E8%AF%81%E7%A0%81",
# }
#
# headers = {
# "Referer": "http://service.js.10086.cn/login.html",
# "Content-Type": "application/x-www-form-urlencoded",
# "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
# "Accept-Encoding": "gzip, deflate, br",
# "Accept-Language": "zh-CN,zh;q=0.9"
# }
# code, key, resp = self.post(LOGIN_URL, headers=headers, data=data)
# if code != 0:
# return code, key
# if u'login' in resp.url:
# self.log("user", "login_param_error", resp)
# return 1, 'login_param_error'
# elif u'resultCode=-300' in resp.text:
# self.log("user", "pin_pwd_error", resp)
# return 1, 'pin_pwd_error'
# elif u'resultCode=-400' in resp.text or u'resultCode=-9000' in resp.text:
# self.log("user", "verify_error", resp)
# return 9, "website_busy_error"
# elif u'system maintenance' in resp.text:
# self.log("website", "系统升级", resp)
# return 9, "website_maintaining_error"
# for i in range(self.max_retry):
# code, key, resp = self.send_login_verify_request()
# if code != 0:
# continue
# # 云打码
# codetype = 3004
# key, result, cid = self._dama(resp.content, codetype)
#
# if key == "success" and result != "":
# captcha_code = str(result)
# else:
# self.log("website", "website_busy_error: 云打码失败{}".format(result), '')
# code, key = 9, "auto_captcha_code_error"
# continue
# LOGIN_URL = 'http://service.js.10086.cn/actionDispatcher.do'
# data = {}
# data['userLoginTransferProtocol'] = 'https'
# data['redirectUrl'] = 'my/MY_QDCX.html#home'
# data['reqUrl'] = 'login'
# data['busiNum'] = 'LOGIN'
# data['operType'] = '0'
# data['passwordType'] = '1'
# data['isSavePasswordVal'] = '0'
# data['isSavePasswordVal_N'] = '1'
# data['currentD'] = '1'
# data['loginFormTab'] = '#home'
# data['loginType'] = '1'
# data['smsFlag'] = '1'
# data['phone-login'] = 'on'
# data['mobile'] = kwargs['tel']
# data['city'] = 'NJDQ'
# data['password'] = kwargs['pin_pwd']
# data['verifyCode'] = ""
# headers = {"Upgrade-Insecure-Requests": "1", "Referer": "http://service.js.10086.cn/login.html?url=my/MY_QDCX.html?t=1481789973300"}
# code, key, resp = self.post(LOGIN_URL, headers=headers, data=data)
# if code != 0:
# return code, key
# if u'login' in resp.url:
# self.log("user", "login_param_error", resp)
# return 1, 'login_param_error'
# elif u'resultCode=-300' in resp.text:
# self.log("user", "pin_pwd_error", resp)
# return 1, 'pin_pwd_error'
# elif u'resultCode=-400' in resp.text or u'resultCode=-9000' in resp.text:
# self.log("user", "verify_error", resp)
# code, key = 9, "auto_captcha_code_error"
# self._dama_report(cid)
# continue
# else:
# return code, key
# go to bill page and next will need to do sms verification
# 验证短信
verify_login_sms_url = 'http://service.js.10086.cn/actionDispatcher.do'
data = {
'reqUrl': 'login',
'busiNum': 'LOGIN',
'smsLoginCode': kwargs['sms_code'],
'fucName': 'verySmsCode',
'flag': '1',
}
code, key, resp = self.post(verify_login_sms_url, data=data)
if code != 0:
return code, key,
if '"resultCode":"1"' in resp.text and '"success":false' in resp.text:
self.log("user", "短信验证码错误", resp)
return 9, "verify_error"
if '密码错误' in resp.text and 'logicCode":"-3002' in resp.text:
self.log("user", "pin_pwd_error", resp)
return 1, "pin_pwd_error"
if 'resultCode":"0"' not in resp.text and 'success":true' not in resp.text:
self.log("crawler", "unknown_error", resp)
return 9, "unknown_error", ""
query_date = date.today()
level, key, message, r = self.get_call_log_by_month(query_date.year, query_date.month)
if level != 0:
return level, key
bill_panel_url = 'http://service.js.10086.cn/my/MY_QDCX.html'
code, key, resp = self.get(bill_panel_url)
if code != 0:
return code, key
return 0, 'success'
def get_verify_type(self, **kwargs):
return 'SMS'
# return ""
def verify(self, **kwargs):
today = date.today()
data = {}
data['reqUrl'] = 'MY_QDCXQueryNew'
data['busiNum'] = 'QDCX'
data['queryMonth'] = "%d%02d" % (today.year, today.month)
data['queryItem'] = 1
data['qryPages'] = ''
# 1:1002:-1 example for pagination
data['qryNo'] = '1'
data['operType'] = '3'
data['queryBeginTime'] = "%s-%02d-01" % (today.year, today.month)
data['queryEndTime'] = "%s-%02d-31" % (today.year, today.month)
data['confirmFlg'] = '1'
data['smsNum'] = kwargs['sms_code']
url = "http://service.js.10086.cn/my/actionDispatcher.do"
headers = {
"X-Requested-With": "XMLHttpRequest",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"Referer": "http://service.js.10086.cn/my/MY_QDCX.html"
}
code, key, resp = self.post(url, data=data, headers=headers)
if code != 0:
return code, key
try:
if "<title> system maintenance" in resp.text:
self.log("crawler", u"系统维护", resp)
return 9, "website_maintaining_error"
obj = json.loads(resp.text)
if obj['resultCode'] == "0":
status_key, level, message = 'success', 0, ''
else:
self.log("crawler", "验证短信失败", resp)
if obj['systemCode'] == "-200009":
return 2, 'verify_error'
elif obj['systemCode'] == "-200002":
return 9, "website_busy_error"
status_key, level, message = 'verify_error', 2, obj['resultMsg']
self.log("user", "verify_error", resp)
return level, status_key
except:
error = traceback.format_exc()
self.log("crawler", 'unknown_error: ' + error, resp)
return 9, "unknown_error"
def send_verify_request(self, **kwargs):
# see if we need to sleep for a while to send sms verification successfully
if self.sms_send_time != None:
sleep_time = 30 - int(time.time() - self.sms_send_time)
if sleep_time > 0:
time.sleep(sleep_time)
sms_post_url = "http://service.js.10086.cn/my/sms.do"
sms_req_payload = {'busiNum': 'QDCX'}
headers = {"Origin": "http://service.js.10086.cn", 'X-Requested-With': 'XMLHttpRequest',
"Referer": 'http://service.js.10086.cn/'+self.start_url}
# "Referer": "http://service.js.10086.cn/my/MY_QDCX.html?t=1481789973300"
code, key, resp = self.post(sms_post_url, headers=headers, data=sms_req_payload)
# code, key, resp = self.post(sms_post_url, data=sms_req_payload)
if code != 0:
return code, key, ""
if resp.text.strip() == "":
self.log("website", u"官网返回数据为空", resp)
return 9, "website_busy_error", ""
if "<html><head><title> system" in resp.text:
self.log("website", u"系统繁忙或者是升级", resp)
return 9, "website_busy_error", ""
try:
ret = resp.json()
error_code = ret['resultCode']
except:
error = traceback.format_exc()
self.log("crawler", "request_error: " + error, resp)
return 9, 'request_error', ""
if error_code != '0':
self.log("crawler", u"发送短信失败", resp)
return 9, 'send_sms_error', ''
# keep the latest sms sending timestamp
self.sms_send_time = time.time()
return 0, 'success', ''
def crawl_call_log_short_num(self, **kwargs):
miss_list = []
pos_miss_list = []
records = []
message_list = []
today = date.today()
delta_months = [i for i in range(0, -6, -1)]
for delta_month in delta_months:
query_date = today + relativedelta(months=delta_month)
end_date = monthrange(query_date.year, query_date.month)[1]
query_month = "%s%02d" % (query_date.year, query_date.month)
st = "%s-%02d-01" % (query_date.year, query_date.month)
et = "%s-%02d-%d" % (query_date.year, query_date.month, end_date)
data = {
"reqUrl": "MY_QDCXQueryNew",
"busiNum": "QDCX",
"queryMonth": "201709",
"queryItem": "8",
"qryPages": "8:1005:-1",
"qryNo": "1",
"operType": "3",
"queryBeginTime": st,
"queryEndTime": et
}
headers = {
"X-Requested-With": "XMLHttpRequest",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"Referer": "http://service.js.10086.cn/my/MY_QDCX.html"
}
url = "http://service.js.10086.cn/my/actionDispatcher.do"
message = ""
for i in range(self.max_retry):
code, key, resp = self.post(url, data=data, headers=headers)
if code != 0:
message = "network_request_error"
continue
level, key, message, ret = parse_call_record_short(resp.text, query_month, self_obj=self)
if level != 0:
continue
records.extend(ret)
break
else:
if key == 'no_data':
self.log("crawler", "短号码{}{}".format(key, message), resp)
pos_miss_list.append(query_month)
else:
if message != "network_request_error":
self.log("crawler", "短号码{}{}".format(key, message), resp)
miss_list.append(query_month)
message_list.append(key)
return 0, "success", records, miss_list, pos_miss_list
def crawl_call_log(self, **kwargs):
miss_list = []
pos_miss_list = []
today = date.today()
records = []
message_list = []
delta_months = [i for i in range(0, -6, -1)]
page_and_retry = []
bill_detail_url = "http://service.js.10086.cn/my/actionDispatcher.do"
headers = {
"X-Requested-With": "XMLHttpRequest",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"Referer": "http://service.js.10086.cn/my/MY_QDCX.html"
}
for delta_month in delta_months:
query_date = today + relativedelta(months=delta_month)
data = {}
query_month = "%d%02d" % (query_date.year, query_date.month)
data['reqUrl'] = 'MY_QDCXQueryNew'
data['busiNum'] = 'QDCX'
data['queryMonth'] = query_month
data['queryItem'] = 1
data['qryPages'] = ''
# 1:1002:-1 example for pagination
data['qryNo'] = '1'
data['operType'] = '3'
data['queryBeginTime'] = "%s-%02d-01" % (query_date.year, query_date.month)
data['queryEndTime'] = "%s-%02d-31" % (query_date.year, query_date.month)
data['confirmFlg'] = '1'
data['smsNum'] = kwargs['sms_code']
page_and_retry.append((data, query_month, self.max_retry))
log_for_retry_request = []
st_time = time.time()
et_time = st_time + 15
while page_and_retry:
# for i in range(self.max_retry):
data, m_query_month, m_retry_times = page_and_retry.pop(0)
log_for_retry_request.append((m_query_month, m_retry_times))
m_retry_times -= 1
code, key, resp = self.post(bill_detail_url, data=data, headers=headers)
if code == 0:
level, key, message, ret = parse_call_record(resp.text, m_query_month, self_obj=self)
if level != 0:
continue
records.extend(ret)
# break
else:
new_time = time.time()
if m_retry_times > 0:
page_and_retry.append((data, m_query_month, m_retry_times))
elif new_time < et_time:
page_and_retry.append((data, m_query_month, m_retry_times))
time.sleep(random.randint(3, 5))
else:
message = "network_request_error"
continue
if key == 'no_data':
self.log("crawler", "{}{}".format(key, message), resp)
pos_miss_list.append(m_query_month)
elif key == "success":
pass
else:
if message != "network_request_error":
self.log("crawler", "{}{}".format(key, message), resp)
miss_list.append(m_query_month)
message_list.append(key)
short_code, short_key, short_result, short_miss_list, short_pos_miss_list = self.crawl_call_log_short_num(
**kwargs)
records.extend(short_result)
self.log("crawler", "重试记录:{}".format(log_for_retry_request), "")
# print len(records),miss_list,pos_miss_list
if len(miss_list + pos_miss_list) == 6:
temp_list = map(
lambda x: x.count('request_error') or x.count('website_busy_error') or x.count('success') or 0,
message_list)
if temp_list.count(0) == 0:
return 9, 'website_busy_error', [], miss_list, pos_miss_list
else:
return 9, 'crawl_error', [], miss_list, pos_miss_list
return 0, 'success', records, miss_list, pos_miss_list
def time_transform(self, time_str, bm='utf-8', str_format="%Y%m%d%H%M%S"):
try:
time_type = time.strptime(time_str.encode(bm), str_format)
except:
error = traceback.format_exc()
return 9, 'unknown_error', u"time_transform failed: %s %s" % (error, time_str)
return 0, 'success', str(int(time.mktime(time_type)))
def crawl_info(self, **kwargs):
result = {}
url = "http://service.js.10086.cn/my/MY_GRZLGL.html#home"
code, key, resp = self.get(url)
if code != 0:
return code, key, {}
obj_str = ''
sections = resp.text.split('window.top.BmonPage.commonBusiCallBack(')
if len(sections) > 1:
obj_str = sections[1].split(", 'MY_GRZLGL')")[0]
if obj_str == '':
self.log("crawler", 'expected_key_error', resp)
return 9, "expected_key_error", {}
try:
obj = json.loads(obj_str)
result['is_realname_register'] = True
result['full_name'] = obj['resultObj']['kehuName']
result['id_card'] = kwargs['id_card']
result['open_date'] = obj['resultObj']['ruwangAt']
except:
error = traceback.format_exc()
self.log("crawler", 'unknown_error: ' + error, resp)
return 9, "unknown_error", {}
level, key, open_date = self.time_transform(obj['resultObj']['ruwangAt'])
if level != 0:
self.log("crawler", '转换时间失败{}{}'.format(key, open_date), resp)
return level, key, {}
result['open_date'] = open_date
result['address'] = ''
return 0, 'success', result
def crawl_phone_bill(self, **kwargs):
miss_list = []
phone_bill = list()
params = {'tel': kwargs['tel']}
message_list = []
for month in self.__monthly_period(6, '%Y%m'):
params['month'] = month
level, key, message, result, miss = self.crawl_month_bill(**params)
if level != 0:
message_list.append(key)
miss_list.append(miss)
if result.get('bill_amount', '') == '':
continue
if result:
phone_bill.append(result)
now_month = datetime.datetime.now().strftime("%Y%m")
now_month in miss_list and miss_list.remove(now_month)
if len(miss_list) == 5:
temp_list = map(lambda x: x.count('request_error') or x.count('website_busy_error') or 0, message_list)
if temp_list.count(0) == 0:
return 9, 'website_busy_error', [], miss_list
return 9, "crawl_error", [], miss_list
return 0, 'success', phone_bill, miss_list
def crawl_month_bill(self, **kwargs):
month_bill_url = 'http://service.js.10086.cn/my/actionDispatcher.do'
data = {
'reqUrl': 'MY_GRZDQuery',
'busiNum': 'ZDCX',
'methodName': 'getMobileHistoryBill',
'beginDate': kwargs['month']
}
headers = {
"X-Requested-With": "XMLHttpRequest",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"Referer": "http://service.js.10086.cn/my/MY_ZDCX.html"
}
error = ""
for i in range(self.max_retry):
code, key, resp = self.post(month_bill_url, data=data, headers=headers)
if code != 0:
error = "network_request_error"
continue
resp.encoding = 'utf=8'
month_bill = {
'bill_month': kwargs['month'],
'bill_amount': '',
'bill_package': '',
'bill_ext_calls': '',
'bill_ext_data': '',
'bill_ext_sms': '',
'bill_zengzhifei': '',
'bill_daishoufei': '',
'bill_qita': ''
}
try:
result = json.loads(resp.text)
if 'billBean' in result['resultObj']:
bill = result['resultObj']['billBean']['billRet']
# 出账期
if u'移动话费出账期' in result['resultMsg']:
return 9, 'success', '', month_bill, kwargs['month']
if bill == None:
# u'账单查询出错 %d,%s' % (resp.status_code, resp.text)
# return 'json_error', 9, "", [], True
error = "账单查询出错"
continue
month_bill['bill_amount'] = '%.2f' % (float(bill['totalFee']) / 100)
for x in bill['feeDetailList']:
if 1 == x['level']:
if u'套餐及固定费' == x['feeName']:
month_bill['bill_package'] = '%.2f' % (float(x['fee']) / 100)
elif u'套餐外语音通信费' == x['feeName']:
month_bill['bill_ext_calls'] = '%.2f' % (float(x['fee']) / 100)
elif u'套餐外短信、彩信费' == x['feeName']:
month_bill['bill_ext_sms'] = '%.2f' % (float(x['fee']) / 100)
break
except:
error = traceback.format_exc()
# return "json_error", 9, error, resp, True
continue
else:
if error != "network_request_error":
self.log("crawler", error, resp)
return 9, "html_error", error, {}, kwargs['month']
return 0, 'success', '', month_bill, ""
def __monthly_period(self, length=6, strf='%Y%m'):
current_time = datetime.datetime.now()
for month_offset in range(0, length):
yield (current_time - relativedelta(months=month_offset)).strftime(strf)
if __name__ == '__main__':
c = Crawler()
mock = {}
# mock['username'] = u"毛羽建"
# mock['identification'] = '330225198112260052'
# mock['verify_code'] = ''
# mock['website_pwd'] = ''
mock['pin_pwd'] = '340393'
mock['tel'] = '15094393043'
c.self_test(**mock)
# print(c.enPwd('340393'))
# c.send_login_verify_request() | send_login_verify_request |
ping.go | package handler
import (
"github.com/lsds/KungFu/srcs/go/rchannel/connection"
)
type PingHandler struct {
}
func (h *PingHandler) Handle(conn connection.Connection) (int, error) {
name, msg, err := connection.Accept(conn)
if err != nil |
if err := conn.Send(name, *msg, connection.NoFlag); err != nil {
return 1, err
}
return 1, nil
}
| {
return 0, err
} |
byteslike.rs | use crate::builtins::memory::PyBufferRef;
use crate::builtins::PyStrRef;
use crate::common::borrow::{BorrowedValue, BorrowedValueMut};
use crate::vm::VirtualMachine;
use crate::{PyObjectRef, PyResult, TryFromObject};
#[derive(Debug)]
pub struct PyBytesLike(PyBufferRef);
#[derive(Debug)]
pub struct PyRwBytesLike(PyBufferRef);
impl PyBytesLike {
pub fn with_ref<F, R>(&self, f: F) -> R
where
F: FnOnce(&[u8]) -> R,
{
f(&*self.borrow_buf())
}
pub fn len(&self) -> usize {
self.borrow_buf().len()
}
pub fn is_empty(&self) -> bool {
self.borrow_buf().is_empty()
}
pub fn to_cow(&self) -> std::borrow::Cow<[u8]> {
self.borrow_buf().to_vec().into()
}
}
impl PyRwBytesLike {
pub fn with_ref<F, R>(&self, f: F) -> R
where
F: FnOnce(&mut [u8]) -> R,
{
f(&mut *self.borrow_buf_mut())
}
pub fn len(&self) -> usize {
self.borrow_buf_mut().len()
}
pub fn is_empty(&self) -> bool {
self.borrow_buf_mut().is_empty()
}
}
impl PyBytesLike {
pub fn new(vm: &VirtualMachine, obj: &PyObjectRef) -> PyResult<Self> {
let buffer = PyBufferRef::try_from_object(vm, obj.clone())?;
if buffer.get_options().contiguous {
Ok(Self(buffer)) | }
pub fn into_buffer(self) -> PyBufferRef {
self.0
}
pub fn borrow_buf(&self) -> BorrowedValue<'_, [u8]> {
self.0.as_contiguous().unwrap()
}
}
impl TryFromObject for PyBytesLike {
fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
Self::new(vm, &obj)
}
}
pub fn try_bytes_like<R>(
vm: &VirtualMachine,
obj: &PyObjectRef,
f: impl FnOnce(&[u8]) -> R,
) -> PyResult<R> {
let buffer = PyBufferRef::try_from_object(vm, obj.clone())?;
buffer.as_contiguous().map(|x| f(&*x)).ok_or_else(|| {
vm.new_type_error("non-contiguous buffer is not a bytes-like object".to_owned())
})
}
pub fn try_rw_bytes_like<R>(
vm: &VirtualMachine,
obj: &PyObjectRef,
f: impl FnOnce(&mut [u8]) -> R,
) -> PyResult<R> {
let buffer = PyBufferRef::try_from_object(vm, obj.clone())?;
buffer
.as_contiguous_mut()
.map(|mut x| f(&mut *x))
.ok_or_else(|| vm.new_type_error("buffer is not a read-write bytes-like object".to_owned()))
}
impl PyRwBytesLike {
pub fn new(vm: &VirtualMachine, obj: &PyObjectRef) -> PyResult<Self> {
let buffer = PyBufferRef::try_from_object(vm, obj.clone())?;
let options = buffer.get_options();
if !options.contiguous {
Err(vm.new_type_error("non-contiguous buffer is not a bytes-like object".to_owned()))
} else if options.readonly {
Err(vm.new_type_error("buffer is not a read-write bytes-like object".to_owned()))
} else {
Ok(Self(buffer))
}
}
pub fn into_buffer(self) -> PyBufferRef {
self.0
}
pub fn borrow_buf_mut(&self) -> BorrowedValueMut<'_, [u8]> {
self.0.as_contiguous_mut().unwrap()
}
}
impl TryFromObject for PyRwBytesLike {
fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
Self::new(vm, &obj)
}
}
/// A buffer or utf8 string. Like the `s*` format code for `PyArg_Parse` in CPython.
pub enum BufOrStr {
Buf(PyBytesLike),
Str(PyStrRef),
}
impl TryFromObject for BufOrStr {
fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
obj.downcast()
.map(Self::Str)
.or_else(|obj| PyBytesLike::try_from_object(vm, obj).map(Self::Buf))
}
}
impl BufOrStr {
pub fn borrow_bytes(&self) -> BorrowedValue<'_, [u8]> {
match self {
Self::Buf(b) => b.borrow_buf(),
Self::Str(s) => s.as_str().as_bytes().into(),
}
}
} | } else {
Err(vm.new_type_error("non-contiguous buffer is not a bytes-like object".to_owned()))
} |
types.js | export const STYLE_BREAKPOINT_UPDATE = 'STYLE_BREAKPOINT_UPDATE';
export const SVC_ADD_POINT = 'SVC_ADD_POINT';
export const SVC_LABEL_CHANGED = 'SVC_LABEL_CHANGED';
export const SVC_CLEAR_POINTS = 'SVC_CLEAR_POINTS';
export const SVC_UNDO_POINT = 'SVC_UNDO_POINT';
export const SVC_REDO_POINT = 'SVC_REDO_POINT';
export const SVR_ADD_POINT = 'SVR_ADD_POINT';
export const SVR_CLEAR_POINTS = 'SVR_CLEAR_POINTS';
export const SVR_UNDO_POINT = 'SVR_UNDO_POINT'; | export const SVR_REDO_POINT = 'SVR_REDO_POINT'; |
|
hiddenCoins.js | export default [
'BTC',
'BTC (SMS-Protected)', | 'ETH',
'SWAP',
'HDP',
'USDT',
'MSK',
'RURCASH',
'USDSWIFT',
] | 'BTC (Multisig)', |
map-api-loader.service.ts | import { Inject, Injectable, InjectionToken } from '@angular/core';
import { DocumentRef, WindowRef } from '../../utils/browser-globals';
import { LoggerService } from '../logger/logger.service';
export interface IMapAPILoaderConfig {
apiKey?: string;
apiVersion?: string;
urlPath?: string;
debug?: boolean;
}
export const MAP_API_CONFIG = new InjectionToken<IMapAPILoaderConfig>('ngx-amap MAP_API_CONFIG');
@Injectable()
export class MapAPILoaderService {
TAG = 'map-api-loader';
private _defaultUrl = 'https://webapi.amap.com/maps';
private _defaultVersion = '1.4.11';
private _config: IMapAPILoaderConfig;
private _documentRef: DocumentRef;
private _windowRef: WindowRef;
private _mapLoaded: Promise<void>;
constructor(@Inject(MAP_API_CONFIG) config: any,
d: DocumentRef,
w: WindowRef,
private logger: LoggerService) {
this._config = config || {};
this._windowRef = w;
this._documentRef = d;
}
load() {
if (this._mapLoaded) {
return this._mapLoaded;
}
this.logger.d(this.TAG, 'loading AMap api...');
const callbackName = `ngxAMapAPILoader`;
const script = this._documentRef.getNativeDocument().createElement('script');
script.type = 'text/javascript';
script.async = true;
script.defer = true;
script.src = this.getSrcFromConfig(callbackName);
this._mapLoaded = new Promise<void>((resolve: Function, reject: Function) => {
(<any>this._windowRef.getNativeWindow())[callbackName] = () => {
this.logger.d(this.TAG, 'loading AMap api COMPLETE');
resolve();
};
script.onerror = (error: Event) => { reject(error); };
});
this._documentRef.getNativeDocument().body.appendChild(script);
return this._mapLoaded;
}
private getSrcFromConfig(callbackName: string) {
const urlBase = this._config.urlPath || this._defaultUrl; | callback: callbackName,
key: this._config.apiKey
};
const params = Object.keys(queryParams)
.filter((k: string) => queryParams[k] != null)
.filter((k: string) => {
// remove empty arrays
return !Array.isArray(queryParams[k]) ||
(Array.isArray(queryParams[k]) && queryParams[k].length > 0);
})
.map((k: string) => {
// join arrays as comma seperated strings
const i = queryParams[k];
if (Array.isArray(i)) {
return {key: k, value: i.join(',')};
}
return {key: k, value: queryParams[k]};
})
.map((entry: {key: string, value: string}) => `${entry.key}=${entry.value}`)
.join('&');
return `${urlBase}?${params}`;
}
} | const queryParams: {[key: string]: string | Array<string>} = {
v: this._config.apiVersion || this._defaultVersion, |
status.go | // Copyright Istio 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 pilot
import (
"encoding/json"
"fmt"
"io"
"sort"
"strings"
"text/tabwriter"
"istio.io/istio/pilot/pkg/xds"
)
// StatusWriter enables printing of sync status using multiple []byte Pilot responses
type StatusWriter struct {
Writer io.Writer
}
type writerStatus struct {
pilot string
xds.SyncStatus
}
// PrintAll takes a slice of Pilot syncz responses and outputs them using a tabwriter
func (s *StatusWriter) PrintAll(statuses map[string][]byte) error {
w, fullStatus, err := s.setupStatusPrint(statuses)
if err != nil {
return err
}
for _, status := range fullStatus {
if err := statusPrintln(w, status); err != nil {
return err
}
}
return w.Flush()
}
// PrintSingle takes a slice of Pilot syncz responses and outputs them using a tabwriter filtering for a specific pod
func (s *StatusWriter) PrintSingle(statuses map[string][]byte, proxyName string) error {
w, fullStatus, err := s.setupStatusPrint(statuses)
if err != nil {
return err
}
for _, status := range fullStatus {
if strings.Contains(status.ProxyID, proxyName) {
if err := statusPrintln(w, status); err != nil { | return err
}
}
}
return w.Flush()
}
func (s *StatusWriter) setupStatusPrint(statuses map[string][]byte) (*tabwriter.Writer, []*writerStatus, error) {
w := new(tabwriter.Writer).Init(s.Writer, 0, 8, 5, ' ', 0)
_, _ = fmt.Fprintln(w, "NAME\tCDS\tLDS\tEDS\tRDS\tISTIOD\tVERSION")
var fullStatus []*writerStatus
for pilot, status := range statuses {
var ss []*writerStatus
err := json.Unmarshal(status, &ss)
if err != nil {
return nil, nil, err
}
for _, s := range ss {
s.pilot = pilot
}
fullStatus = append(fullStatus, ss...)
}
sort.Slice(fullStatus, func(i, j int) bool {
return fullStatus[i].ProxyID < fullStatus[j].ProxyID
})
return w, fullStatus, nil
}
func statusPrintln(w io.Writer, status *writerStatus) error {
clusterSynced := xdsStatus(status.ClusterSent, status.ClusterAcked)
listenerSynced := xdsStatus(status.ListenerSent, status.ListenerAcked)
routeSynced := xdsStatus(status.RouteSent, status.RouteAcked)
endpointSynced := xdsStatus(status.EndpointSent, status.EndpointAcked)
version := status.IstioVersion
if version == "" {
// If we can't find an Istio version (talking to a 1.1 pilot), fallback to the proxy version
// This is misleading, as the proxy version isn't always the same as the Istio version,
// but it is better than not providing any information.
version = status.ProxyVersion + "*"
}
_, _ = fmt.Fprintf(w, "%v\t%v\t%v\t%v\t%v\t%v\t%v\n",
status.ProxyID, clusterSynced, listenerSynced, endpointSynced, routeSynced, status.pilot, version)
return nil
}
func xdsStatus(sent, acked string) string {
if sent == "" {
return "NOT SENT"
}
if sent == acked {
return "SYNCED"
}
// acked will be empty string when there is never Acknowledged
if acked == "" {
return "STALE (Never Acknowledged)"
}
// Since the Nonce changes to uuid, so there is no more any time diff info
return "STALE"
} | |
mod.rs | pub mod flat_binary;
pub mod functions; | pub mod stack; |
|
test_case_statement.py | from sqlalchemy.testing import assert_raises, eq_
from sqlalchemy.testing import fixtures, AssertsCompiledSQL
from sqlalchemy import (
testing, exc, case, select, literal_column, text, and_, Integer, cast,
String, Column, Table, MetaData)
from sqlalchemy.sql import table, column
info_table = None
class CaseTest(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = 'default'
@classmethod
def setup_class(cls):
metadata = MetaData(testing.db)
global info_table
info_table = Table(
'infos', metadata,
Column('pk', Integer, primary_key=True),
Column('info', String(30)))
info_table.create()
info_table.insert().execute(
{'pk': 1, 'info': 'pk_1_data'},
{'pk': 2, 'info': 'pk_2_data'},
{'pk': 3, 'info': 'pk_3_data'},
{'pk': 4, 'info': 'pk_4_data'},
{'pk': 5, 'info': 'pk_5_data'},
{'pk': 6, 'info': 'pk_6_data'})
@classmethod
def teardown_class(cls):
info_table.drop()
@testing.fails_on('firebird', 'FIXME: unknown')
@testing.requires.subqueries
def test_case(self):
inner = select(
[
case(
[
[info_table.c.pk < 3, 'lessthan3'],
[
and_(info_table.c.pk >= 3, info_table.c.pk < 7),
'gt3']]).label('x'),
info_table.c.pk, info_table.c.info], from_obj=[info_table])
inner_result = inner.execute().fetchall()
# Outputs:
# lessthan3 1 pk_1_data
# lessthan3 2 pk_2_data
# gt3 3 pk_3_data
# gt3 4 pk_4_data
# gt3 5 pk_5_data
# gt3 6 pk_6_data
assert inner_result == [
('lessthan3', 1, 'pk_1_data'),
('lessthan3', 2, 'pk_2_data'),
('gt3', 3, 'pk_3_data'),
('gt3', 4, 'pk_4_data'),
('gt3', 5, 'pk_5_data'),
('gt3', 6, 'pk_6_data')
]
outer = select([inner.alias('q_inner')])
outer_result = outer.execute().fetchall()
assert outer_result == [
('lessthan3', 1, 'pk_1_data'),
('lessthan3', 2, 'pk_2_data'),
('gt3', 3, 'pk_3_data'),
('gt3', 4, 'pk_4_data'),
('gt3', 5, 'pk_5_data'),
('gt3', 6, 'pk_6_data')
]
w_else = select(
[
case(
[
[info_table.c.pk < 3, cast(3, Integer)],
[
and_(
info_table.c.pk >= 3, info_table.c.pk < 6),
6]],
else_=0).label('x'),
info_table.c.pk, info_table.c.info],
from_obj=[info_table])
else_result = w_else.execute().fetchall()
assert else_result == [
(3, 1, 'pk_1_data'),
(3, 2, 'pk_2_data'),
(6, 3, 'pk_3_data'),
(6, 4, 'pk_4_data'),
(6, 5, 'pk_5_data'),
(0, 6, 'pk_6_data')
]
def test_literal_interpretation(self):
|
def test_text_doesnt_explode(self):
for s in [
select(
[
case(
[
(
info_table.c.info == 'pk_4_data',
text("'yes'"))],
else_=text("'no'"))
]).order_by(info_table.c.info),
select(
[
case(
[
(
info_table.c.info == 'pk_4_data',
literal_column("'yes'"))],
else_=literal_column("'no'")
)]
).order_by(info_table.c.info),
]:
if testing.against("firebird"):
eq_(s.execute().fetchall(), [
('no ', ), ('no ', ), ('no ', ), ('yes', ),
('no ', ), ('no ', ),
])
else:
eq_(s.execute().fetchall(), [
('no', ), ('no', ), ('no', ), ('yes', ),
('no', ), ('no', ),
])
@testing.fails_on('firebird', 'FIXME: unknown')
def testcase_with_dict(self):
query = select(
[
case(
{
info_table.c.pk < 3: 'lessthan3',
info_table.c.pk >= 3: 'gt3',
}, else_='other'),
info_table.c.pk, info_table.c.info
],
from_obj=[info_table])
assert query.execute().fetchall() == [
('lessthan3', 1, 'pk_1_data'),
('lessthan3', 2, 'pk_2_data'),
('gt3', 3, 'pk_3_data'),
('gt3', 4, 'pk_4_data'),
('gt3', 5, 'pk_5_data'),
('gt3', 6, 'pk_6_data')
]
simple_query = select(
[
case(
{1: 'one', 2: 'two', },
value=info_table.c.pk, else_='other'),
info_table.c.pk
],
whereclause=info_table.c.pk < 4,
from_obj=[info_table])
assert simple_query.execute().fetchall() == [
('one', 1),
('two', 2),
('other', 3),
]
| t = table('test', column('col1'))
assert_raises(exc.ArgumentError, case, [("x", "y")])
self.assert_compile(
case([("x", "y")], value=t.c.col1),
"CASE test.col1 WHEN :param_1 THEN :param_2 END")
self.assert_compile(
case([(t.c.col1 == 7, "y")], else_="z"),
"CASE WHEN (test.col1 = :col1_1) THEN :param_1 ELSE :param_2 END") |
menubar.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
from PyQt5 import QtGui
from PyQt5 import QtCore
from PyQt5 import QtWidgets
from .guiconfig import collectView
class MenuBar(QtWidgets.QMenuBar):
viewID = "MenuBar"
@collectView
def __init__(self, parent):
super(MenuBar, self).__init__()
self.parent = parent
self.actionlists = {}
self.menusettings = {
'visual': False,
'menus': [
{
'name': self.tr('File'),
'trigger': 'File',
'actions': [
{
'name': self.tr('Settings'),
'icon': u'',
'shortcut': u'',
'trigger': 'Settings',
},
{
'name': self.tr('Language'),
'trigger': 'Language',
'type': 'submenu',
'actions': [
{
'name': 'English',
'icon': u'',
'shortcut': u'',
'trigger': 'English',
"checkable": True
},
{
'name': 'Chinese',
'icon': u'',
'shortcut': u'',
'trigger': 'Chinese',
"checkable": True
},
]
},
{
'name': self.tr('Exit'),
'icon': u'',
'shortcut': u'',
'trigger': 'Exit',
},
]
},
{
'name': self.tr('Screen'),
'trigger': 'Screen',
'actions': [
{
'name': self.tr('MFD3'),
'icon': u'',
'shortcut': u'',
'trigger': 'MFD3',
"checkable": True
},
{
'name': self.tr('MFD4'),
'icon': u'',
'shortcut': u'',
'trigger': 'MFD4',
"checkable": True
},
]
},
{
'name': self.tr('Device'),
'trigger': 'Device',
'actions': [
# {
# 'name': self.tr('Enable Bluetooth'),
# 'icon': u'',
# 'shortcut': u'',
# 'trigger': 'EnableBluetooth',
# },
{
'name': self.tr('Search Devices'),
'icon': u'',
'shortcut': u'',
'trigger': 'SearchDevices',
},
]
},
{
'name': self.tr('View'),
'trigger': 'View',
'actions': [
]
},
{
'name': self.tr('Report'),
'trigger': 'Test Rig',
'actions': [
{
'name': self.tr('Report'),
'icon': u'',
'shortcut': u'',
'trigger': 'TestRigAll',
},
{
'name': self.tr('Start'),
'icon': u'',
'shortcut': u'',
'trigger': 'TestRig',
}
]
},
{
'name': self.tr(' Help '),
'trigger': 'Help',
'actions': [
{
'name': self.tr('About ALE'),
'icon': u'',
'shortcut': u'',
'trigger': 'About',
},
{
'name': self.tr('Feedback to us'),
'icon': u'',
'shortcut': u'',
'trigger': 'Feedbackus',
},
]
}
]
}
self.creatMenus(self.menusettings)
def creatMenus(self, menusettings):
self.setVisible(menusettings['visual'])
for menu in menusettings['menus']:
setattr(
self,
'%smenu' % menu['trigger'],
self.addMenu(u'%s' % menu['name'])
)
submenu = getattr(self, '%smenu' % menu['trigger'])
for menuaction in menu['actions']:
if 'type' in menuaction and menuaction['type'] == "submenu":
self.createSubAction(menu['trigger'], menuaction)
else:
self.creatAction(submenu, menuaction)
def createSubAction(self, pmenu_name, menu):
childmenu = getattr(self, '%smenu' % pmenu_name)
submenu = childmenu.addMenu(u'%s' % menu['name'])
setattr(
self,
'%smenu' % menu['trigger'],
submenu)
for menuaction in menu['actions']:
self.creatAction(submenu, menuaction)
def creatAction(self, submenu, menuaction):
| if 'checkable' in menuaction:
setattr(
self,
'%sAction' % menuaction['trigger'],
QtWidgets.QAction(
QtGui.QIcon(QtGui.QPixmap(menuaction['icon'])),
u'%s' % menuaction['name'],
self,
checkable=menuaction['checkable']
)
)
else:
setattr(
self,
'%sAction' % menuaction['trigger'],
QtWidgets.QAction(
QtGui.QIcon(QtGui.QPixmap(menuaction['icon'])),
u'%s' % menuaction['name'],
self,
)
)
action = getattr(self, '%sAction' % menuaction['trigger'])
action.setShortcut(QtGui.QKeySequence(menuaction['shortcut']))
submenu.addAction(action)
self.actionlists.update({menuaction['trigger']: action})
if hasattr(self.parent, 'action%s' % menuaction['trigger']):
action.triggered.connect(
getattr(self.parent, 'action%s' % menuaction['trigger'])
) |
|
logger.py | import logging
import time
import os
import sys
def create_logger(final_output_path, description=None):
if description is None:
log_file = '{}.log'.format(time.strftime('%Y-%m-%d-%H-%M'))
else:
log_file = '{}_{}.log'.format(time.strftime('%Y-%m-%d-%H-%M'), description) | clogger.setLevel(logging.INFO)
# add handler
# print to stdout and log file
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
clogger.addHandler(ch)
return clogger | head = '%(asctime)-15s %(message)s'
logging.basicConfig(filename=os.path.join(final_output_path, log_file),
format=head)
clogger = logging.getLogger() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.