text
stringlengths 3
1.05M
|
|---|
"""
Human-readable names for operators.
"""
import ast
OPERATION_DESCRIPTION = {
ast.Pow: "an exponent",
ast.Add: "an addition",
ast.Mult: "a multiplication",
ast.Sub: "a subtraction",
ast.Div: "a division",
ast.FloorDiv: "a division",
ast.Mod: "a modulo",
ast.LShift: "a left shift",
ast.RShift: "a right shift",
ast.BitOr: "a bit or",
ast.BitAnd: "a bit and",
ast.BitXor: "a bit xor",
ast.And: "an and",
ast.Or: "an or",
ast.Eq: "an ==",
ast.NotEq: "a !=",
ast.Lt: "a <",
ast.LtE: "a <=",
ast.Gt: "a >",
ast.GtE: "a >=",
ast.Is: "an is",
ast.IsNot: "an is not",
ast.In: "an in",
ast.NotIn: "an not in",
}
COMPARE_OP_NAMES = {
"==": "Eq",
"<": "Lt",
"<=": "Lte",
">=": "Gte",
">": "Gt",
"!=": "NotEq",
"is": "Is",
"is not": "IsNot",
"in": "In",
"not in": "NotIn",
}
BOOL_OP_NAMES = {"and": "And", "or": "Or"}
BIN_OP_NAMES = {
"+": "Add",
"-": "Sub",
"*": "Mult",
"/": "Div",
"//": "FloorDiv",
"%": "Mod",
"**": "Pow",
">>": "LShift",
"<<": "RShift",
"|": "BitOr",
"^": "BitXor",
"&": "BitAnd",
"@": "MatMult",
}
UNARY_OP_NAMES = {
# "+": "UAdd",
# "-": "USub",
"not": "Not",
"~": "Invert",
}
|
# 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.
# pylint: disable=import-self, invalid-name, unused-argument
"""
Tensorflow testcases
====================
This article is a test script to test tensorflow operator with Relay.
"""
from __future__ import print_function
import numpy as np
import pytest
try:
import tensorflow.compat.v1 as tf
except ImportError:
import tensorflow as tf
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import graph_util
from tensorflow.python.ops import nn_ops
from tensorflow.python.ops import nn
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import variables
from tensorflow.python.ops import init_ops
from distutils.version import LooseVersion
import tvm
from tvm import te
from tvm import relay
import tvm.relay.testing.tf as tf_testing
from packaging import version as package_version
#######################################################################
# Generic run functions for TVM & tensorflow
# ------------------------------------------
def convert_to_list(x):
if not isinstance(x, list):
x = [x]
return x
tf_dtypes = {
'float32': tf.float32,
'float16': tf.float16,
'float64': tf.float64,
'int32': tf.int32,
'uint8' : tf.uint8,
'int8': tf.int8,
'int16': tf.int16,
'uint16': tf.uint16,
'int64': tf.int64,
}
def vmobj_to_list(o):
if isinstance(o, tvm.nd.NDArray):
return [o.asnumpy().tolist()]
elif isinstance(o, tvm.runtime.container.ADT):
result = []
for f in o:
result.extend(vmobj_to_list(f))
return result
elif isinstance(o, tvm.relay.backend.interpreter.ConstructorValue):
if o.constructor.name_hint == 'Cons':
tl = vmobj_to_list(o.fields[1])
hd = vmobj_to_list(o.fields[0])
hd.extend(tl)
return hd
elif o.constructor.name_hint == 'Nil':
return []
elif 'tensor_nil' in o.constructor.name_hint:
return [0]
elif 'tensor' in o.constructor.name_hint:
return [o.fields[0].asnumpy()]
else:
raise RuntimeError("Unknown object type: %s" %
o.constructor.name_hint)
else:
raise RuntimeError("Unknown object type: %s" % type(o))
def run_tvm_graph(graph_def, input_data, input_node, num_output=1,
target='llvm', out_names=None, opt_level=3, mode='graph_runtime',
cuda_layout="NCHW"):
""" Generic function to compile on relay and execute on tvm """
input_data = convert_to_list(input_data)
input_node = convert_to_list(input_node)
layout = None
if target == "cuda":
layout = cuda_layout
target_host = None
shape_dict = {e: i.shape for e, i in zip(input_node, input_data)}
mod, params = relay.frontend.from_tensorflow(graph_def,
layout=layout,
shape=shape_dict,
outputs=out_names)
if mode in ['debug', 'vm']:
ex = relay.create_executor(mode, mod=mod, ctx=tvm.cpu(), target="llvm")
inputs = []
for param in mod['main'].params:
found = False
for i, n in enumerate(input_node):
if n == param.name_hint:
found = True
inputs.append(tvm.nd.array(input_data[i]))
break
# Interpreter doesn't bind constants, so still need to find in params
if not found:
inputs.append(tvm.nd.array(params[param.name_hint]))
result = ex.evaluate()(*inputs)
return vmobj_to_list(result)
else:
with relay.build_config(opt_level=opt_level):
graph, lib, params = relay.build(mod, target, target_host, params)
ctx = tvm.context(target, 0)
from tvm.contrib import graph_runtime
m = graph_runtime.create(graph, lib, ctx)
# set inputs
for e, i in zip(input_node, input_data):
m.set_input(e, tvm.nd.array(i))
m.set_input(**params)
# execute
m.run()
# get outputs
assert out_names is None or num_output == len(out_names), (
"out_names: {} num_output: {}".format(out_names, num_output))
tvm_output_list = [m.get_output(i).asnumpy()
for i in range(num_output)]
return tvm_output_list
def run_tf_graph(sess, input_data, input_node, output_node):
""" Generic function to execute tensorflow """
input_data = convert_to_list(input_data)
input_node = convert_to_list(input_node)
output_node = convert_to_list(output_node)
tensor = [sess.graph.get_tensor_by_name(
output_name) for output_name in output_node]
input_dict = {e: input_data[i] for i, e in enumerate(input_node)}
output_data = sess.run(tensor, input_dict)
return output_data
def compare_tf_with_tvm(in_data, in_name, out_name, init_global_variables=False,
no_gpu=False, opt_level=3, mode='graph_runtime',
cuda_layout="NCHW"):
"""Generic function to generate and compare tensorflow and TVM output"""
def name_without_num(name):
return name.split(':')[0] if ":" in name else name
out_name = convert_to_list(out_name)
out_node = [name_without_num(name) for name in out_name]
in_data = convert_to_list(in_data)
in_name = convert_to_list(in_name)
in_node = [name_without_num(name) for name in in_name]
with tf.Session() as sess:
if init_global_variables:
sess.run(variables.global_variables_initializer())
final_graph_def = tf_testing.AddShapesToGraphDef(sess, out_node)
tf_output = run_tf_graph(sess, in_data, in_name, out_name)
for device in ["llvm", "cuda"]:
ctx = tvm.context(device, 0)
if not ctx.exist:
print("Skip because %s is not enabled" % device)
continue
if no_gpu and device == 'cuda':
continue
tvm_output = run_tvm_graph(final_graph_def, in_data, in_node,
target=device, out_names=out_name,
num_output=len(out_name), opt_level=opt_level, mode=mode,
cuda_layout=cuda_layout)
# since the names from tensorflow and relay runs are not exactly same,
# first len(tf_output) will be compared
for i in range(len(tf_output)):
tvm.testing.assert_allclose(
tf_output[i], tvm_output[i], atol=1e-5, rtol=1e-5)
sess.close()
def is_gpu_available():
from tensorflow.python.client import device_lib
local_device_protos = device_lib.list_local_devices()
gpu_list = [x.name for x in local_device_protos if x.device_type == 'GPU']
if len(gpu_list) > 0:
print("Tensorflow GPU:", gpu_list)
return True
else:
return False
#######################################################################
# Pooling
# -------
def _test_pooling_iteration(input_shape, **kwargs):
""" One iteration of pool operation with given shapes and attributes """
x = -np.arange(
np.prod(input_shape), dtype=np.float32).reshape(input_shape) - 1
with tf.Graph().as_default():
in_data = array_ops.placeholder(shape=input_shape, dtype='float32')
nn_ops.pool(in_data, **kwargs)
if kwargs['pooling_type'] == 'MAX':
out_name = 'max_pool:0'
else:
out_name = 'avg_pool:0'
compare_tf_with_tvm(x, 'Placeholder:0', out_name)
def _test_pooling(input_shape, **kwargs):
_test_pooling_iteration(input_shape, **kwargs)
if is_gpu_available():
if len(input_shape) == 4:
input_shape = [input_shape[ii] for ii in (0, 3, 1, 2)]
kwargs['data_format'] = 'NCHW'
_test_pooling_iteration(input_shape, **kwargs)
def test_forward_pooling():
""" Pooling """
# TensorFlow only supports NDHWC for max_pool3d on CPU
for pool_type in ['AVG', 'MAX']:
# NDHWC is the default layout for max_pool3d and avg_pool3d in TensorFlow
_test_pooling(input_shape=[1, 3, 32, 32, 32],
window_shape=[2, 2, 2],
padding='VALID',
pooling_type=pool_type,
dilation_rate=[1, 1, 1],
strides=[2, 2, 2])
_test_pooling(input_shape=[1, 3, 32, 32, 32],
window_shape=[1, 1, 1],
padding='SAME',
pooling_type=pool_type,
dilation_rate=[1, 1, 1],
strides=[1, 1, 1])
_test_pooling(input_shape=[1, 3, 32, 32, 32],
window_shape=[2, 2, 2],
padding='SAME',
pooling_type=pool_type,
dilation_rate=[1, 1, 1],
strides=[2, 2, 2])
# test cases for max_pool3d & avg_pool3d with layout NCDHW
# TensorFlow pool3d doesn't support NCDHW on cpu
if is_gpu_available():
_test_pooling(input_shape=[1, 3, 32, 32, 32],
window_shape=[1, 1, 1],
padding='SAME',
pooling_type=pool_type,
dilation_rate=[1, 1, 1],
strides=[1, 1, 1],
data_format='NCDHW')
_test_pooling(input_shape=[1, 3, 32, 32, 32],
window_shape=[2, 2, 2],
padding='VALID',
pooling_type=pool_type,
dilation_rate=[1, 1, 1],
strides=[2, 2, 2],
data_format='NCDHW')
_test_pooling(input_shape=[2, 9, 10, 2],
window_shape=[1, 1],
padding='SAME',
pooling_type=pool_type,
dilation_rate=[1, 1],
strides=[1, 1])
_test_pooling(input_shape=[2, 10, 9, 2],
window_shape=[1, 1],
padding='SAME',
pooling_type=pool_type,
dilation_rate=[1, 1],
strides=[1, 1])
_test_pooling(input_shape=[2, 9, 10, 2],
window_shape=[2, 1],
padding='SAME',
pooling_type=pool_type,
dilation_rate=[1, 1],
strides=[1, 1])
_test_pooling(input_shape=[2, 10, 9, 2],
window_shape=[2, 3],
padding='SAME',
pooling_type=pool_type,
dilation_rate=[1, 1],
strides=[2, 1])
# Tests involving SpaceToBatchND
_test_pooling(input_shape=[1, 1, 2, 1],
window_shape=[1, 1],
padding='VALID',
pooling_type=pool_type,
dilation_rate=[1, 2])
_test_pooling(input_shape=[1, 2, 1],
window_shape=[1],
padding='VALID',
pooling_type=pool_type,
dilation_rate=[2])
#######################################################################
# Convolution
# -----------
def _test_convolution(opname, tensor_in_sizes, filter_in_sizes,
dilations, strides, padding, data_format,
deconv_output_shape=[]):
""" One iteration of convolution with given shapes and attributes """
total_size_1 = np.prod(tensor_in_sizes)
total_size_2 = np.prod(filter_in_sizes)
# Initializes the input tensor with array containing incrementing
# numbers from 1.
data_array = [f * 1.0 for f in range(1, total_size_1 + 1)]
filter_array = [f * 1.0 for f in range(1, total_size_2 + 1)]
with tf.Graph().as_default():
in_data = array_ops.placeholder(shape=tensor_in_sizes, dtype='float32')
in_filter = constant_op.constant(
filter_array, shape=filter_in_sizes, dtype='float32')
if data_format == 'NHWC':
strides = [1] + strides + [1]
dilations = [1] + dilations + [1]
else:
strides = [1, 1] + strides
dilations = [1, 1] + dilations
if opname == 'conv':
nn_ops.conv2d(in_data,
in_filter,
strides=strides,
dilations=dilations,
padding=padding,
data_format=data_format)
compare_tf_with_tvm(np.reshape(data_array, tensor_in_sizes).astype('float32'),
'Placeholder:0', 'Conv2D:0')
elif opname == 'conv_transpose':
nn_ops.conv2d_transpose(in_data,
in_filter,
output_shape=deconv_output_shape,
strides=strides,
padding=padding,
data_format=data_format)
compare_tf_with_tvm(np.reshape(data_array, tensor_in_sizes).astype('float32'),
'Placeholder:0', 'conv2d_transpose:0')
else:
nn_ops.depthwise_conv2d_native(in_data,
in_filter,
strides=strides,
dilations=dilations,
padding=padding,
data_format=data_format)
compare_tf_with_tvm(np.reshape(data_array, tensor_in_sizes).astype('float32'),
'Placeholder:0', 'DepthwiseConv2dNative:0')
def test_forward_convolution():
if is_gpu_available():
_test_convolution('conv', [4, 176, 8, 8], [1, 1, 176, 32], [1, 1], [1, 1], 'SAME', 'NCHW')
_test_convolution('conv', [4, 19, 17, 17], [3, 3, 19, 19], [1, 1], [2, 2], 'VALID', 'NCHW')
_test_convolution('conv', [4, 124, 17, 17], [1, 1, 124, 19], [1, 1], [1, 1], 'SAME', 'NCHW')
_test_convolution('conv', [4, 12, 17, 17], [3, 3, 12, 32], [1, 1], [2, 2], 'VALID', 'NCHW')
_test_convolution('depthwise', [4, 176, 8, 8], [1, 1, 176, 1], [1, 1], [1, 1], 'SAME', 'NCHW')
_test_convolution('depthwise', [4, 19, 17, 17], [3, 3, 19, 1], [1, 1], [2, 2], 'VALID', 'NCHW')
_test_convolution('depthwise', [4, 124, 17, 17], [1, 1, 124, 1], [1, 1], [1, 1], 'SAME', 'NCHW')
_test_convolution('depthwise', [4, 12, 17, 17], [3, 3, 12, 1], [1, 1], [2, 2], 'VALID', 'NCHW')
_test_convolution('depthwise', [4, 12, 17, 17], [3, 3, 12, 2], [1, 1], [2, 2], 'VALID', 'NCHW')
_test_convolution('conv_transpose', [4, 32, 8, 8], [1, 1, 176, 32], [1, 1], [1, 1], 'SAME',
'NCHW', [4, 176, 8, 8])
_test_convolution('conv_transpose', [4, 32, 8, 8], [2, 2, 176, 32], [1, 1], [1, 1], 'SAME',
'NCHW', [4, 176, 8, 8])
_test_convolution('conv_transpose', [4, 32, 8, 8], [2, 2, 176, 32], [1, 1], [2, 2], 'SAME',
'NCHW', [4, 176, 15, 15])
_test_convolution('conv_transpose', [4, 32, 8, 8], [3, 3, 176, 32], [1, 1], [1, 1], 'SAME',
'NCHW', [4, 176, 8, 8])
_test_convolution('conv_transpose', [4, 32, 8, 8], [3, 3, 176, 32], [1, 1], [2, 2], 'SAME',
'NCHW', [4, 176, 15, 15])
_test_convolution('conv_transpose', [4, 32, 8, 8], [3, 3, 176, 32], [1, 1], [2, 2], 'SAME',
'NCHW', [4, 176, 16, 16])
_test_convolution('conv_transpose', [4, 19, 8, 8], [3, 3, 19, 19], [1, 1], [2, 2], 'VALID',
'NCHW', [4, 19, 17, 17])
_test_convolution('conv_transpose', [4, 19, 17, 17], [1, 1, 124, 19], [1, 1], [1, 1], 'SAME',
'NCHW', [4, 124, 17, 17])
_test_convolution('conv_transpose', [4, 19, 17, 17], [3, 3, 124, 19], [1, 1], [1, 1], 'SAME',
'NCHW', [4, 124, 17, 17])
_test_convolution('conv_transpose', [4, 32, 8, 8], [3, 3, 12, 32], [1, 1], [2, 2], 'VALID',
'NCHW', [4, 12, 17, 17])
# kernel 2x2, strides (2,2)
_test_convolution('conv_transpose', [4, 19, 8, 8], [2, 2, 19, 19], [1, 1], [2, 2], 'VALID',
'NCHW', [4, 19, 16, 16])
_test_convolution('conv_transpose', [4, 32, 8, 8], [2, 2, 12, 32], [1, 1], [2, 2], 'VALID',
'NCHW', [4, 12, 16, 16])
# output channel is 1
_test_convolution('conv_transpose', [1, 19, 8, 8], [1, 1, 1, 19], [1, 1], [1, 1], 'VALID',
'NCHW', [1, 1, 8, 8])
_test_convolution('conv', [4, 8, 8, 176], [1, 1, 176, 32], [1, 1], [1, 1], 'SAME', 'NHWC')
_test_convolution('conv', [4, 17, 17, 19], [3, 3, 19, 19], [1, 1], [2, 2], 'VALID', 'NHWC')
_test_convolution('conv', [4, 17, 17, 124], [1, 1, 124, 19], [1, 1], [1, 1], 'SAME', 'NHWC')
_test_convolution('conv', [4, 17, 17, 12], [3, 3, 12, 32], [1, 1], [2, 2], 'VALID', 'NHWC')
_test_convolution('depthwise', [4, 8, 8, 176], [1, 1, 176, 1], [1, 1], [1, 1], 'SAME', 'NHWC')
_test_convolution('depthwise', [4, 17, 17, 19], [3, 3, 19, 1], [1, 1], [2, 2], 'VALID', 'NHWC')
_test_convolution('depthwise', [4, 17, 17, 124], [1, 1, 124, 1], [1, 1], [1, 1], 'SAME', 'NHWC')
_test_convolution('depthwise', [4, 17, 17, 12], [3, 3, 12, 1], [1, 1], [2, 2], 'VALID', 'NHWC')
_test_convolution('depthwise', [4, 17, 17, 12], [3, 3, 12, 2], [1, 1], [2, 2], 'VALID', 'NHWC')
_test_convolution('conv_transpose', [4, 8, 8, 32], [1, 1, 176, 32], [1, 1], [1, 1], 'SAME',
'NHWC', [4, 8, 8, 176])
_test_convolution('conv_transpose', [4, 8, 8, 32], [2, 2, 176, 32], [1, 1], [1, 1], 'SAME',
'NHWC', [4, 8, 8, 176])
_test_convolution('conv_transpose', [4, 8, 8, 32], [2, 2, 176, 32], [1, 1], [2, 2], 'SAME',
'NHWC', [4, 15, 15, 176])
_test_convolution('conv_transpose', [4, 8, 8, 32], [3, 3, 176, 32], [1, 1], [1, 1], 'SAME',
'NHWC', [4, 8, 8, 176])
_test_convolution('conv_transpose', [4, 8, 8, 32], [3, 3, 176, 32], [1, 1], [2, 2], 'SAME',
'NHWC', [4, 15, 15, 176])
_test_convolution('conv_transpose', [4, 8, 8, 32], [3, 3, 176, 32], [1, 1], [2, 2], 'SAME',
'NHWC', [4, 16, 16, 176])
_test_convolution('conv_transpose', [4, 8, 8, 19], [3, 3, 19, 19], [1, 1], [2, 2], 'VALID',
'NHWC', [4, 17, 17, 19])
_test_convolution('conv_transpose', [4, 17, 17, 19], [1, 1, 124, 19], [1, 1], [1, 1], 'SAME',
'NHWC', [4, 17, 17, 124])
_test_convolution('conv_transpose', [4, 17, 17, 19], [3, 3, 124, 19], [1, 1], [1, 1], 'SAME',
'NHWC', [4, 17, 17, 124])
_test_convolution('conv_transpose', [4, 8, 8, 32], [3, 3, 12, 32], [1, 1], [2, 2], 'VALID',
'NHWC', [4, 17, 17, 12])
# kernel 2x2, strides (2,2)
_test_convolution('conv_transpose', [4, 8, 8, 19], [2, 2, 19, 19], [1, 1], [2, 2], 'VALID',
'NHWC', [4, 16, 16, 19])
_test_convolution('conv_transpose', [4, 8, 8, 32], [2, 2, 12, 32], [1, 1], [2, 2], 'VALID',
'NHWC', [4, 16, 16, 12])
# output channel is 1
_test_convolution('conv_transpose', [1, 8, 8, 19], [1, 1, 1, 19], [1, 1], [1, 1], 'VALID',
'NHWC', [1, 8, 8, 1])
#######################################################################
# Convolution3D
# -----------
def _test_convolution3d(opname, tensor_in_sizes, filter_in_sizes,
dilations, strides, padding, data_format,
deconv_output_shape=[]):
""" One iteration of 3D convolution with given shapes and attributes """
total_size_1 = np.prod(tensor_in_sizes)
total_size_2 = np.prod(filter_in_sizes)
# Initializes the input tensor with array containing incrementing
# numbers from 1.
data_array = [f * 1.0 for f in range(1, total_size_1 + 1)]
filter_array = [f * 1.0 for f in range(1, total_size_2 + 1)]
with tf.Graph().as_default():
in_data = array_ops.placeholder(shape=tensor_in_sizes, dtype='float32')
in_filter = constant_op.constant(
filter_array, shape=filter_in_sizes, dtype='float32')
if data_format == 'NDHWC':
strides = [1] + strides + [1]
dilations = [1] + dilations + [1]
else:
strides = [1, 1] + strides
dilations = [1, 1] + dilations
if opname == 'conv':
nn_ops.conv3d(in_data,
in_filter,
strides=strides,
dilations=dilations,
padding=padding,
data_format=data_format)
compare_tf_with_tvm(np.reshape(data_array, tensor_in_sizes).astype('float32'),
'Placeholder:0', 'Conv3D:0', cuda_layout="NCDHW")
def test_forward_convolution3d():
if is_gpu_available():
_test_convolution3d('conv', [4, 176, 8, 8, 8], [1, 1, 1, 176, 32], [1, 1, 1], [1, 1, 1], 'SAME', 'NCDHW')
_test_convolution3d('conv', [4, 19, 17, 17, 17], [3, 3, 3, 19, 19], [1, 1, 1], [2, 2, 2], 'VALID', 'NCDHW')
_test_convolution3d('conv', [4, 124, 17, 17, 17], [1, 1, 1, 124, 19], [1, 1, 1], [1, 1, 1], 'SAME', 'NCDHW')
_test_convolution3d('conv', [4, 12, 17, 17, 17], [3, 3, 3, 12, 32], [1, 1, 1], [2, 2, 2], 'VALID', 'NCDHW')
_test_convolution3d('conv', [4, 8, 8, 8, 176], [1, 1, 1, 176, 32], [1, 1, 1], [1, 1, 1], 'SAME', 'NDHWC')
_test_convolution3d('conv', [4, 17, 17, 17, 19], [3, 3, 3, 19, 19], [1, 1, 1], [2, 2, 2], 'VALID', 'NDHWC')
_test_convolution3d('conv', [4, 17, 17, 17, 124], [1, 1, 1, 124, 19], [1, 1, 1], [1, 1, 1], 'SAME', 'NDHWC')
_test_convolution3d('conv', [4, 17, 17, 17, 12], [3, 3, 3, 12, 32], [1, 1, 1], [2, 2, 2], 'VALID', 'NDHWC')
#######################################################################
# BiasAdd
# -----------
def _test_biasadd(tensor_in_sizes, data_format):
""" One iteration of biasadd with given shapes and attributes """
total_size_1 = 1
for s in tensor_in_sizes:
total_size_1 *= s
tensor_bias_sizes = [tensor_in_sizes[1]
] if data_format == 'NCHW' else [tensor_in_sizes[3]]
total_size_2 = tensor_bias_sizes[0]
# Initializes the input tensor with array containing incrementing
# numbers from 1.
data_array = [f * 1.0 for f in range(1, total_size_1 + 1)]
bias_array = [f * 1.0 for f in range(1, total_size_2 + 1)]
with tf.Graph().as_default():
in_data = array_ops.placeholder(shape=tensor_in_sizes, dtype='float32')
in_bias = constant_op.constant(
bias_array, shape=tensor_bias_sizes, dtype='float32')
nn_ops.bias_add(in_data,
in_bias,
data_format=data_format)
compare_tf_with_tvm(np.reshape(data_array, tensor_in_sizes).astype('float32'),
'Placeholder:0', 'BiasAdd:0')
def test_forward_biasadd():
if is_gpu_available():
_test_biasadd([4, 176, 8, 8], 'NCHW')
_test_biasadd([1, 100, 1, 1], 'NCHW')
_test_biasadd([4, 19, 17, 17], 'NCHW')
_test_biasadd([4, 124, 3, 3], 'NCHW')
_test_biasadd([4, 8, 8, 176], 'NHWC')
_test_biasadd([1, 1, 1, 100], 'NHWC')
_test_biasadd([4, 17, 17, 19], 'NHWC')
_test_biasadd([4, 3, 3, 124], 'NHWC')
def _test_forward_where(input_shape):
with tf.Graph().as_default():
dtype = tf.float32
t = tf.constant(np.random.choice([0, 1, -2, 3, -1, 0.1, -0.2],
size=input_shape).astype(dtype.name))
out = tf.where(t)
compare_tf_with_tvm([], [], out.name, mode='debug')
compare_tf_with_tvm([], [], out.name, mode='vm')
def test_forward_argwhere():
_test_forward_where((5,))
_test_forward_where((5, 5))
_test_forward_where((5, 5, 5))
_test_forward_where((5, 5, 5, 5))
_test_forward_where((5, 5, 5, 5, 5))
#######################################################################
# SpaceToBatchND
# --------------
def _test_space_to_batch_nd(input_shape, block_shape, paddings, dtype='int32'):
data = np.random.uniform(0, 5, size=input_shape).astype(dtype)
with tf.Graph().as_default():
in_data = tf.placeholder(shape=input_shape, dtype=dtype)
out = tf.space_to_batch_nd(in_data, block_shape, paddings)
compare_tf_with_tvm(data, in_data.name, out.name)
def _test_space_to_batch_nd_infer_paddings(input_shape, block_shape, dtype='int32'):
data = np.random.uniform(0, 5, size=input_shape).astype(dtype)
padding_np = np.array([0, 1]).astype(np.int32).reshape((1, 2))
with tf.Graph().as_default():
in_data = tf.placeholder(shape=input_shape, dtype=dtype)
const1 = tf.constant(padding_np, dtype=tf.int32)
# make paddings an input to tf.transpose, but not an input to the graph,
# so it can be extracted with infer_value_simulated
paddings = tf.reverse(const1, axis=[-1])
out = tf.space_to_batch_nd(in_data, block_shape, paddings)
compare_tf_with_tvm(data, in_data.name, out.name)
def test_forward_space_to_batch_nd():
# test cases: https://www.tensorflow.org/api_docs/cc/class/tensorflow/ops/space-to-batch-n-d
_test_space_to_batch_nd(
input_shape=[1, 2, 2, 1],
block_shape=[2, 2],
paddings=[[0, 0], [0, 0]]
)
_test_space_to_batch_nd(
input_shape=[1, 2, 2, 3],
block_shape=[2, 2],
paddings=[[0, 0], [0, 0]]
)
_test_space_to_batch_nd(
input_shape=[1, 4, 4, 1],
block_shape=[2, 2],
paddings=[[0, 0], [0, 0]]
)
_test_space_to_batch_nd(
input_shape=[2, 2, 4, 1],
block_shape=[2, 2],
paddings=[[0, 0], [2, 0]],
dtype='int64'
)
# pylint: disable=line-too-long
# https://github.com/tensorflow/tensorflow/blob/24f578/tensorflow/python/kernel_tests/spacetobatch_op_test.py
_test_space_to_batch_nd(
input_shape=[2, 3],
block_shape=[2],
paddings=[[1, 0]],
dtype='float32'
)
_test_space_to_batch_nd(
input_shape=[2, 3, 2],
block_shape=[2],
paddings=[[1, 0]],
dtype='float64'
)
_test_space_to_batch_nd_infer_paddings(
input_shape=[2, 3, 2],
block_shape=[2]
)
#######################################################################
# BatchToSpaceND
# --------------
def _test_batch_to_space_nd(input_shape, block_shape, crops, dtype='int32'):
data = np.random.uniform(0, 5, size=input_shape).astype(dtype)
with tf.Graph().as_default():
in_data = tf.placeholder(shape=input_shape, dtype=dtype)
out = tf.batch_to_space_nd(in_data, block_shape, crops)
compare_tf_with_tvm(data, in_data.name, out.name)
def test_forward_batch_to_space_nd():
# test cases: https://www.tensorflow.org/api_docs/cc/class/tensorflow/ops/batch-to-space-n-d
_test_batch_to_space_nd(
input_shape=[4, 1, 1, 1],
block_shape=[2, 2],
crops=[[0, 0], [0, 0]]
)
_test_batch_to_space_nd(
input_shape=[4, 1, 1, 3],
block_shape=[2, 2],
crops=[[0, 0], [0, 0]]
)
_test_batch_to_space_nd(
input_shape=[4, 2, 2, 1],
block_shape=[2, 2],
crops=[[0, 0], [0, 0]]
)
_test_batch_to_space_nd(
input_shape=[8, 1, 3, 1],
block_shape=[2, 2],
crops=[[0, 0], [2, 0]],
dtype='int64'
)
# pylint: disable=line-too-long
# https://github.com/tensorflow/tensorflow/blob/24f578/tensorflow/python/kernel_tests/batchtospace_op_test.py
_test_batch_to_space_nd(
input_shape=[18, 2, 1, 2],
block_shape=[2, 3],
crops=[[1, 1], [0, 0]],
dtype='float32'
)
_test_batch_to_space_nd(
input_shape=[20, 5, 8, 7],
block_shape=[2, 2],
crops=[[1, 1], [1, 1]],
dtype='float64'
)
#######################################################################
# Reshape
# -------
def _test_reshape(data, out_shape):
""" One iteration of reshape operation with given data and out shape """
with tf.Graph().as_default():
in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)
array_ops.reshape(in_data, out_shape)
compare_tf_with_tvm(data, 'Placeholder:0', 'Reshape:0')
def _test_reshape_with_call():
""" relay.expr.Call as shape """
data = np.zeros((6, 4, 2))
with tf.Graph().as_default():
in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)
out_shape = tf.constant([1, 2, 3], dtype="int32")
out_shape = tf.multiply(out_shape, 2)
array_ops.reshape(in_data, out_shape)
compare_tf_with_tvm(data, 'Placeholder:0', 'Reshape:0')
def _test_reshape_like(data, shape_like):
""" A special case for reshape. """
with tf.Graph().as_default():
in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)
in_shape_like = array_ops.placeholder(shape=shape_like.shape, dtype=data.dtype)
out_shape = array_ops.shape(in_shape_like)
array_ops.reshape(in_data, out_shape)
compare_tf_with_tvm(data, 'Placeholder:0', 'Reshape:0')
def test_forward_reshape():
_test_reshape(np.arange(6.0), [2, 3])
_test_reshape(np.arange(6), [-1, 2])
_test_reshape(np.arange(6), [3, -1])
_test_reshape(np.arange(6), [-1])
_test_reshape_with_call()
_test_reshape_like(np.zeros((3, 6)), np.zeros((9, 2)))
#######################################################################
# DepthToSpace
# ------------
def _test_depthtospace(data, block_size):
""" One iteration of depth_to_space operation with given data and block size """
with tf.Graph().as_default():
in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)
array_ops.depth_to_space(in_data, block_size)
compare_tf_with_tvm(data, 'Placeholder:0', 'DepthToSpace:0')
def test_forward_depthtospace():
_test_depthtospace(np.random.normal(size=[1, 32, 32, 4]), 2)
_test_depthtospace(np.random.normal(size=[1, 16, 8, 32]), 4)
#######################################################################
# SpaceToDepth
# ------------
def _test_spacetodepth(data, block_size):
""" One iteration of space_to_depth operation with given data and block size """
with tf.Graph().as_default():
in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)
array_ops.space_to_depth(in_data, block_size)
compare_tf_with_tvm(data, 'Placeholder:0', 'SpaceToDepth:0')
def test_forward_spacetodepth():
_test_spacetodepth(np.random.normal(size=[1, 32, 32, 4]), 2)
_test_spacetodepth(np.random.normal(size=[1, 16, 8, 32]), 4)
#######################################################################
# Squeeze
# -------
def _test_squeeze(data, squeeze_dims=None):
""" One iteration of squeeze """
if squeeze_dims is None:
squeeze_dims = []
with tf.Graph().as_default():
in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)
if squeeze_dims:
array_ops.squeeze(in_data, squeeze_dims)
else:
array_ops.squeeze(in_data)
compare_tf_with_tvm(data, 'Placeholder:0', 'Squeeze:0')
def test_forward_squeeze():
""" Squeeze """
# Nothing to squeeze.
_test_squeeze(np.arange(2).reshape((2)))
_test_squeeze(np.arange(6).reshape((2, 3)))
# Squeeze the middle element away.
_test_squeeze(np.arange(4).reshape((2, 1, 2)))
# Squeeze on both ends.
_test_squeeze(np.arange(6).reshape((1, 2, 1, 3, 1)))
# Positive squeeze dim index.
_test_squeeze(np.arange(6).reshape((1, 2, 1, 3, 1)), [0])
_test_squeeze(np.arange(6).reshape((1, 2, 1, 3, 1)), [2, 4])
_test_squeeze(np.arange(6).reshape((1, 2, 1, 3, 1)), [0, 4, 2])
# Negative squeeze dim index.
_test_squeeze(np.arange(6).reshape((1, 2, 1, 3, 1)), [-1])
_test_squeeze(np.arange(6).reshape((1, 2, 1, 3, 1)), [-3, -5])
_test_squeeze(np.arange(6).reshape((1, 2, 1, 3, 1)), [-3, -5, -1])
def test_tensor_array_constructor():
def run(dtype_str):
with tf.Graph().as_default():
dtype = tf_dtypes[dtype_str]
t = tf.constant(np.array([[1.0, 2.0], [3.0, 4.0]]).astype(dtype_str), dtype=dtype)
t2 = tf.constant(np.array([[1.0, 2.0], [3.0, 4.0]]).astype(dtype_str), dtype=dtype)
ta1 = tf.TensorArray(dtype=dtype, size=2, infer_shape=False, dynamic_size=False)
ta2 = ta1.write(0, t)
ta3 = ta2.write(1, t2)
out = ta3.read(0)
g = tf.get_default_graph()
compare_tf_with_tvm([], [], 'TensorArrayReadV3:0', mode='debug')
for dtype in tf_dtypes.keys():
run(dtype)
def test_tensor_array_scatter():
def run(dtype_str):
with tf.Graph().as_default():
dtype = tf_dtypes[dtype_str]
t = tf.constant(np.array([[1.0], [2.0], [3.0]]).astype(dtype_str), dtype=dtype)
indices = tf.constant([2, 1, 0])
ta1 = tf.TensorArray(dtype=dtype, size=3,
infer_shape=False, dynamic_size=False)
ta2 = ta1.scatter(indices, t)
out0 = ta2.read(0)
out1 = ta2.read(1)
out2 = ta2.read(2)
g = tf.get_default_graph()
compare_tf_with_tvm([], [], ['TensorArrayReadV3:0'], mode='debug')
compare_tf_with_tvm([], [], ['TensorArrayReadV3_1:0'], mode='debug')
compare_tf_with_tvm([], [], ['TensorArrayReadV3_2:0'], mode='debug')
for dtype in tf_dtypes.keys():
run(dtype)
# TODO(wweic): Fix gather issue with PartialEvaluate
# def test_tensor_array_gather():
# with tf.Graph().as_default():
# dtype = 'float32'
# t = tf.constant([[1.0], [2.0], [3.0]])
# scatter_indices = tf.constant([2, 1, 0])
# gather_indices = tf.constant([1, 2])
# ta1 = tf.TensorArray(dtype=tf.float32, size=3, infer_shape=False, dynamic_size=False)
# ta2 = ta1.scatter(scatter_indices, t)
# t1 = ta2.gather(gather_indices)
# g = tf.get_default_graph()
# compare_tf_with_tvm([], [], ['TensorArrayGatherV3:0'], mode='debug')
def test_tensor_array_split():
def run(dtype_str):
with tf.Graph().as_default():
dtype = tf_dtypes[dtype_str]
t = tf.constant(np.array([[1.0], [2.0], [3.0], [4.0], [5.0], [6.0], [7.0], [8.0]]).astype(dtype_str), dtype=dtype)
split_length = tf.constant([2, 2, 2, 2], dtype=tf.int32)
ta1 = tf.TensorArray(dtype=dtype, size=4,
infer_shape=False, dynamic_size=False)
ta2 = ta1.split(t, split_length)
out0 = ta2.read(0)
out1 = ta2.read(1)
out2 = ta2.read(2)
out3 = ta2.read(3)
g = tf.get_default_graph()
compare_tf_with_tvm([], [], ['TensorArrayReadV3:0'], mode='debug')
compare_tf_with_tvm([], [], ['TensorArrayReadV3_1:0'], mode='debug')
compare_tf_with_tvm([], [], ['TensorArrayReadV3_2:0'], mode='debug')
compare_tf_with_tvm([], [], ['TensorArrayReadV3_3:0'], mode='debug')
for dtype in tf_dtypes.keys():
run(dtype)
def test_tensor_array_concat():
def run(dtype_str):
with tf.Graph().as_default():
dtype = tf_dtypes[dtype_str]
t = tf.constant(np.array([[1.0], [2.0], [3.0], [4.0], [5.0], [6.0], [7.0], [8.0]]).astype(dtype_str), dtype=dtype)
split_length = tf.constant([2, 2, 2, 2], dtype=tf.int32)
ta1 = tf.TensorArray(dtype=dtype, size=4,
infer_shape=False, dynamic_size=False)
ta2 = ta1.split(t, split_length)
t = ta2.concat()
out = tf.identity(t)
compare_tf_with_tvm([], [], ['Identity:0'], mode='debug')
for dtype in tf_dtypes.keys():
run(dtype)
def test_tensor_array_size():
def run(dtype_str):
with tf.Graph().as_default():
dtype = tf_dtypes[dtype_str]
ta1 = tf.TensorArray(dtype=dtype, size=2, infer_shape=False, dynamic_size=False)
out = ta1.size()
g = tf.get_default_graph()
compare_tf_with_tvm([], [], 'TensorArraySizeV3:0', mode='debug')
for dtype in tf_dtypes.keys():
run(dtype)
def test_tensor_array_unstack():
def run(dtype_str, input_shape):
with tf.Graph().as_default():
dtype = tf_dtypes[dtype_str]
t = tf.constant(np.random.choice([0, 1, 2, 3],
size=input_shape).astype(dtype.name))
ta1 = tf.TensorArray(dtype=dtype, infer_shape=False, size=input_shape[0])
ta2 = ta1.unstack(t)
out0 = ta2.size()
out1 = ta2.read(0)
compare_tf_with_tvm([], [], 'TensorArraySizeV3:0', mode='debug')
compare_tf_with_tvm([], [], 'TensorArrayReadV3:0', mode='debug')
for dtype in tf_dtypes.keys():
run(dtype, (5,))
run(dtype, (5, 5))
run(dtype, (5, 5, 5))
run(dtype, (5, 5, 5, 5))
run(dtype, (5, 5, 5, 5, 5))
run(dtype, (5, 5, 5, 5, 5, 5))
#######################################################################
# ConcatV2
# --------
def _test_concat_v2(shape1, shape2, dim):
""" One iteration of ConcatV2 """
with tf.Graph().as_default():
dtype = 'float32'
in1 = tf.placeholder(shape=shape1, dtype=dtype, name='in1')
in2 = tf.placeholder(shape=shape2, dtype=dtype, name='in2')
array_ops.concat_v2([in1, in2], dim)
np_data1 = np.random.uniform(size=shape1).astype(dtype)
np_data2 = np.random.uniform(size=shape2).astype(dtype)
compare_tf_with_tvm([np_data1, np_data2], [
'in1:0', 'in2:0'], 'ConcatV2:0')
def test_forward_concat_v2():
if tf.__version__ < LooseVersion('1.4.1'):
return
_test_concat_v2([2, 3], [2, 3], 0)
_test_concat_v2([10, 3, 5], [2, 3, 5], 0)
_test_concat_v2([2, 3], [2, 3], 1)
_test_concat_v2([5, 8], [5, 4], 1)
_test_concat_v2([2, 8, 5], [2, 8, 6], -1)
#######################################################################
# Sigmoid
# -------
def _test_sigmoid(data):
""" One iteration of sigmoid """
with tf.Graph().as_default():
in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)
sigmoid_out = math_ops.sigmoid(in_data)
compare_tf_with_tvm(data, 'Placeholder:0', 'Sigmoid:0')
def test_forward_sigmoid():
""" Sigmoid """
_test_sigmoid(np.random.uniform(size=(3, 4, 4, 3)).astype('float32'))
#######################################################################
# Argmin/Argmax
# -------------
def _test_argx(func, data, **kwargs):
with tf.Graph().as_default():
inp = array_ops.placeholder(
shape=data.shape, dtype=data.dtype, name="c0")
func(inp, name="argx0", output_type=tf.int32, **kwargs)
compare_tf_with_tvm(data, 'c0:0', 'argx0:0')
def test_forward_argminmax():
for axis in [None, 0, 1, 2]:
data = np.random.uniform(size=(8, 4, 9)).astype('float32')
_test_argx(tf.argmax, data=data, axis=axis)
_test_argx(tf.argmin, data=data, axis=axis)
#######################################################################
# Variable
# --------
def _test_variable(data):
""" One iteration of a variable """
tf.reset_default_graph()
with tf.Graph().as_default():
input_op = array_ops.placeholder(shape=data.shape, dtype=data.dtype)
input_tensor = array_ops.reshape(input_op, data.shape)
size = input_tensor.shape.dims[1]
with variable_scope.variable_scope("linear", reuse=None):
w = variable_scope.get_variable(
"w", shape=[size, size], dtype=input_tensor.dtype)
math_ops.matmul(input_tensor, w)
compare_tf_with_tvm(data, 'Placeholder:0', 'MatMul:0',
init_global_variables=True)
def test_forward_variable():
"""Variable type op test"""
_test_variable(np.random.uniform(size=(32, 100)).astype('float32'))
def test_read_variable_op():
""" Read Variable op test """
tf.reset_default_graph()
data = np.random.uniform(size=(32, 100)).astype('float32')
input_tensor = array_ops.placeholder(shape=data.shape, dtype=data.dtype)
size = input_tensor.shape.dims[1]
var_data = np.random.uniform(-5, 5, size=[size, size]).astype(np.float32)
input_var = tf.Variable(var_data, name='var1', use_resource=True)
math_ops.matmul(input_tensor, input_var)
out_name = ['MatMul:0']
out_node = ['MatMul']
in_name = ['Placeholder:0']
in_node = ['Placeholder']
in_data = [data]
with tf.Session() as sess:
sess.run(variables.global_variables_initializer())
final_graph_def = sess.graph.as_graph_def(add_shapes=True)
tf_output = run_tf_graph(sess, in_data, in_name, out_name)
shape_dict = {e: i.shape for e, i in zip(in_name, in_data)}
with pytest.raises(Exception) as exexcinfo:
mod, params = relay.frontend.from_tensorflow(final_graph_def,
layout=None,
shape=shape_dict,
outputs=None)
assert exexcinfo.value.args[0].startswith("Graph is not frozen. Provide a frozen graph.")
# Now convert the variables to constant and run inference on the converted graph
final_graph_def = tf.graph_util.convert_variables_to_constants(
sess,
sess.graph.as_graph_def(add_shapes=True),
out_node,
)
for device in ["llvm", "cuda"]:
ctx = tvm.context(device, 0)
if not ctx.exist:
print("Skip because %s is not enabled" % device)
continue
tvm_output = run_tvm_graph(final_graph_def, in_data, in_node,
target=device, out_names=out_name,
num_output=len(out_name))
for i in range(len(tf_output)):
tvm.testing.assert_allclose(
tf_output[i], tvm_output[i], atol=1e-4, rtol=1e-5)
sess.close()
#######################################################################
# MatMul, BatchMatMul, BatchMatMulV2
# ----------------------------------
def _test_matmul(i, j, k, dtype, outer=None):
""" One iteration of matmul """
A_shape_init = [i, j]
B_shape_init = [j, k]
for transpose_a in [False, True]:
for transpose_b in [False, True]:
outer = outer or []
A_shape = outer + \
(A_shape_init[::-1] if transpose_a else A_shape_init)
B_shape = outer + \
(B_shape_init[::-1] if transpose_b else B_shape_init)
with tf.Graph().as_default():
A = tf.placeholder(shape=A_shape, dtype=dtype, name='A')
B = tf.placeholder(shape=B_shape, dtype=dtype, name='B')
result = tf.matmul(
A, B, transpose_a=transpose_a, transpose_b=transpose_b)
A_np = np.random.uniform(high=5.0, size=A_shape).astype(dtype)
B_np = np.random.uniform(high=5.0, size=B_shape).astype(dtype)
compare_tf_with_tvm(
[A_np, B_np], [A.name, B.name], result.name)
def test_forward_matmul():
""" MatMul op test"""
_test_matmul(1, 3, 6, 'int32')
_test_matmul(5, 3, 1, 'float64')
def _test_batch_matmul(A_shape, B_shape, dtype, adjoint_a=False, adjoint_b=False):
with tf.Graph().as_default():
A = tf.placeholder(shape=A_shape, dtype=dtype, name='A')
B = tf.placeholder(shape=B_shape, dtype=dtype, name='B')
result = tf.matmul(A, B, adjoint_a=adjoint_a,
adjoint_b=adjoint_b, name='batchmatmul')
A_np = np.random.uniform(high=5.0, size=A_shape).astype(dtype)
B_np = np.random.uniform(high=5.0, size=B_shape).astype(dtype)
compare_tf_with_tvm([A_np, B_np], [A.name, B.name], result.name)
def test_forward_batch_matmul():
""" TF op BatchMatMul, BatchMatMulV2 test"""
_test_batch_matmul((3, 5, 4), (3, 4, 5), 'int32')
_test_batch_matmul((3, 5, 4), (3, 4, 5), 'float32', True, True)
_test_batch_matmul((3, 5, 4), (3, 5, 4), 'int32', True, False)
_test_batch_matmul((3, 5, 4), (3, 5, 4), 'float32', False, True)
_test_batch_matmul((2, 3, 4, 5, 6), (2, 3, 4, 6, 5), 'int32')
_test_batch_matmul((1, 2, 3, 4, 5, 6),
(1, 2, 3, 4, 6, 5), 'float32', True, True)
_test_batch_matmul((3, 4, 5, 6), (3, 4, 5, 6), 'int32', True, False)
_test_batch_matmul((2, 3, 4, 2, 3, 4, 5, 6),
(2, 3, 4, 2, 3, 4, 5, 6), 'float32', False, True)
#######################################################################
# StridedSlice
# ------------
def _test_stridedslice(ip_shape, begin, end, stride, dtype,
begin_mask=0, end_mask=0, new_axis_mask=0,
shrink_axis_mask=0, ellipsis_mask=0):
""" One iteration of a Stridedslice """
tf.reset_default_graph()
with tf.Graph().as_default():
in_data = tf.placeholder(dtype, ip_shape, name="in_data")
tf.strided_slice(in_data, begin, end, stride, begin_mask=begin_mask,
end_mask=end_mask, new_axis_mask=new_axis_mask,
shrink_axis_mask=shrink_axis_mask,
ellipsis_mask=ellipsis_mask, name="strided_slice")
np_data = np.random.uniform(size=ip_shape).astype(dtype)
compare_tf_with_tvm(np_data, 'in_data:0', 'strided_slice:0')
def test_forward_stridedslice():
'''test StridedSlice'''
_test_stridedslice((2), [1], [1], [1], 'float32', shrink_axis_mask=1)
_test_stridedslice((2, 1), [0], [1], [1], 'float32', shrink_axis_mask=1)
_test_stridedslice((2, 3, 4), [0], [1], [1], 'float32', shrink_axis_mask=8)
_test_stridedslice((3, 4, 3), [1, -1, 0],
[4, -5, 3], [2, -1, 1], 'float32')
_test_stridedslice((3, 4, 3), [1, 0], [4, 3], [
2, 1], 'float32', ellipsis_mask=8)
_test_stridedslice((3, 4, 3), [1, 0], [4, 2], [
2, 1], 'float32', ellipsis_mask=2)
_test_stridedslice((3, 4, 5, 3), [1, 0], [4, 2], [
2, 1], 'float32', ellipsis_mask=2)
_test_stridedslice((3, 4, 5, 3), [1, 0, 1], [4, 2, 2], [
2, 1, 1], 'float32', ellipsis_mask=2)
_test_stridedslice((3, 4, 3), [1, 1, 0], [4, 4, 2], [
2, 1, 1], 'float32', new_axis_mask=5)
_test_stridedslice((3, 4, 3), [1, 1, 1], [4, 4, 1], [2, 1, 1], 'float32', ellipsis_mask=2,
new_axis_mask=4)
_test_stridedslice((6, 4, 5), [1, 1, 1], [6, 3, 4], [2, 1, 1], 'float32', ellipsis_mask=2,
new_axis_mask=5)
_test_stridedslice((3, 4, 3), [1, 1, 2], [4, 4, 3], [2, 1, 1], 'float32', ellipsis_mask=4,
new_axis_mask=2)
_test_stridedslice((3, 4, 3), [1, 1, 2], [4, 4, 3], [2, 1, 1], 'float32', ellipsis_mask=2,
new_axis_mask=3)
_test_stridedslice((3, 4, 3), [1, 1, 0], [4, 4, 1], [2, 1, 1], 'float32', ellipsis_mask=2,
new_axis_mask=3)
_test_stridedslice((3, 4, 3), [1, 1, 2], [4, 4, 3], [2, 1, 1], 'float32', ellipsis_mask=2,
new_axis_mask=2)
_test_stridedslice((3, 4), [1, 0], [4, 4], [
1, 1], 'float32', shrink_axis_mask=2)
_test_stridedslice((3, 4, 3), [1, 1, 0], [4, 4, 3], [2, 1, 1], 'float32', shrink_axis_mask=2,
new_axis_mask=2)
_test_stridedslice((3, 4, 3), [1, 1, 0], [4, 4, 3], [2, 1, 1], 'float32', shrink_axis_mask=1,
new_axis_mask=2)
_test_stridedslice((3, 4, 3), [1, 1, 0], [4, 4, 3], [2, 1, 1], 'float32', shrink_axis_mask=2,
new_axis_mask=1)
_test_stridedslice((3, 4, 5, 4, 5, 6), [0, 0], [2, 3], [1, 1], 'float32', shrink_axis_mask=5,
new_axis_mask=1)
_test_stridedslice((3, 4, 5, 4, 5, 6), [0, 0, 1, 2, 1], [2, 3, 4, 5, 3], [1, 1, 2, 2, 1],
'float32', shrink_axis_mask=5, new_axis_mask=1, ellipsis_mask=2,
begin_mask=8, end_mask=8)
_test_stridedslice((3, 4, 5, 4, 5, 6), [0, 0, 1, 2, 1], [2, 3, 4, 5, 3], [1, 1, 2, 2, 1],
'float32', shrink_axis_mask=8, new_axis_mask=1, ellipsis_mask=2,
begin_mask=5, end_mask=5)
_test_stridedslice((3, 4, 5, 4, 5, 6), [0, 0, 1, 2, 1], [2, 3, 4, 5, 3], [1, 1, 2, 2, 1],
'float32', shrink_axis_mask=16, new_axis_mask=1, ellipsis_mask=2,
begin_mask=5, end_mask=5)
_test_stridedslice((3, 4, 5, 4, 5, 6), [1, 2, 0, -3], [4, 5, 3, 3], [2, 2, 1, 1],
'float32', shrink_axis_mask=8, new_axis_mask=1, ellipsis_mask=2,
begin_mask=5, end_mask=8)
#######################################################################
# FloorDiv, RealDiv
# -----------------
def _test_forward_divide(ip_shape, dtype):
np_numer = np.random.uniform(-100, 100, size=ip_shape).astype(dtype)
np_denomin = np.random.uniform(1, 100, size=ip_shape).astype(dtype)
tf.reset_default_graph()
with tf.Graph().as_default():
numerator = tf.placeholder(dtype, ip_shape, name="numer")
denominator = tf.placeholder(dtype, ip_shape, name="denomin")
tf.math.divide(numerator, denominator, name='RealDiv')
compare_tf_with_tvm([np_numer, np_denomin], [
'numer:0', 'denomin:0'], 'RealDiv:0')
def _test_forward_floordiv(ip_shape, dtype):
np_numer = np.random.uniform(1, 100, size=ip_shape).astype(dtype)
tf.reset_default_graph()
with tf.Graph().as_default():
numerator = tf.placeholder(dtype, ip_shape, name="numer")
tf.math.floordiv(numerator, tf.constant(5, dtype=dtype), name='FloorDiv')
compare_tf_with_tvm([np_numer], ['numer:0'], 'FloorDiv:0')
def test_forward_divide():
'''test FloorDiv, RealDiv'''
_test_forward_divide((4,), 'int32')
_test_forward_divide((4, 3, 7), 'float32')
_test_forward_floordiv((4, 3, 7), 'float32')
_test_forward_floordiv((4, 3, 7), 'int32')
#######################################################################
# FloorMod
# --------
def _test_forward_floormod(in_shape, if_shape, dtype):
np_numer = np.random.uniform(1, 100, size=in_shape).astype(dtype)
np_factor = np.random.uniform(1, 100, size=if_shape).astype(dtype)
tf.reset_default_graph()
with tf.Graph().as_default():
numerator = tf.placeholder(dtype, in_shape, name="numer")
factor = tf.placeholder(dtype, if_shape, name="factor")
tf.floormod(numerator, factor, name='FloorMod')
compare_tf_with_tvm([np_numer, np_factor], ['numer:0', 'factor:0'], 'FloorMod:0')
def test_forward_floormod():
'''test FloorMod'''
_test_forward_floormod((10,), (10,), 'float32')
_test_forward_floormod((8, 2), (1,), 'float32')
_test_forward_floormod((4, 3, 7), (4, 3, 7), 'float32')
_test_forward_floormod((4, 3, 7), (4, 3, 7), 'int32')
#######################################################################
# TruncateMod
# -----------
def _test_forward_truncatemod(ip_shape, dtype):
np_data_1 = np.random.uniform(-100, 100, size=ip_shape).astype(dtype)
np_data_2 = np.random.uniform(1, 10, size=ip_shape).astype(dtype)
tf.reset_default_graph()
with tf.Graph().as_default():
in_data_1 = tf.placeholder(dtype, ip_shape, name="in_data_1")
in_data_2 = tf.placeholder(dtype, ip_shape, name="in_data_2")
tf.truncatemod(in_data_1, in_data_2, name='truncatemod')
compare_tf_with_tvm([np_data_1, np_data_2], [
'in_data_1:0', 'in_data_2:0'], 'truncatemod:0')
def test_forward_truncatemod():
'''test TruncateMod'''
_test_forward_truncatemod((4, 3, 7), 'int32')
#######################################################################
# Cumsum
# --------------------------
def _cumsum(in_shape, axis=0, exclusive=False, reverse=False):
"""test operator GatherNd"""
tf.reset_default_graph()
with tf.Graph().as_default():
np_data = np.random.uniform(size=in_shape).astype("float32")
in_data = tf.placeholder(tf.float32, in_shape, name="in_data")
tf.cumsum(in_data, axis=axis, exclusive=False, reverse=False, name="cumsum")
compare_tf_with_tvm([np_data], ['in_data:0'], 'cumsum:0')
def test_forward_cumsum():
for exclusive in [False, True]:
for reverse in [False, True]:
_cumsum((4, ), 0, exclusive, reverse)
_cumsum((4, ), -1, exclusive, reverse)
_cumsum((4, 2), 0, exclusive, reverse)
_cumsum((4, 2), 1, exclusive, reverse)
_cumsum((4, 2), -1, exclusive, reverse)
_cumsum((4, 2, 3), 1, exclusive, reverse)
_cumsum((4, 2, 3), 2, exclusive, reverse)
_cumsum((4, 2, 3), 0, exclusive, reverse)
_cumsum((4, 2, 3), -1, exclusive, reverse)
_cumsum((4, 2, 3), -2, exclusive, reverse)
#######################################################################
# Gather, GatherV2, GatherNd
# --------------------------
def _test_gather(ip_shape, indice_shape, indice_value, axis, dtype):
""" One iteration of a GatherV2 """
tf.reset_default_graph()
with tf.Graph().as_default():
in_data = tf.placeholder(dtype, ip_shape, name="in_data")
indices = tf.placeholder("int32", indice_shape, name="indices")
out = tf.gather(in_data, indices, axis=axis)
np_data = np.random.uniform(1, 10, size=ip_shape).astype(dtype)
def _fill_indices(indice_value):
indices = np.array(ip_shape, dtype=dtype)
if isinstance(indice_value, int):
indices = np.array([indice_value], dtype='int32')
else:
indices = np.asarray(indice_value, dtype='int32')
return indices
np_indices = _fill_indices(indice_value)
compare_tf_with_tvm([np_data, np_indices], [
'in_data:0', 'indices:0'], out.name)
def test_forward_gather():
'''test Gather/GatherV2 layer'''
_test_gather((4,), (1,), 1, 0, 'int32')
_test_gather((4,), (1,), 1, 0, 'float32')
_test_gather((1, 4), (1,), [0], 0, 'int32')
_test_gather((4,), (1, 2, 2), [[[1, 0], [0, 1]]], 0, 'float32')
_test_gather((2, 2), (1, 2, 2), [[[1, 0], [0, 1]]], 0, 'int32')
_test_gather((2, 2), (1, 2, 2), [[[1, 0], [0, 1]]], 1, 'int32')
_test_gather((2, 2), (1, 2, 2), [[[1, 0], [0, 1]]], 0, 'float32')
_test_gather((3, 3, 3), (1, 1, 2), [[[1, 0]]], 0, 'int32')
_test_gather((3, 3, 3), (1, 1, 2), [[[1, 0]]], 2, 'int32')
_test_gather((4, 3, 5, 6), (1, 4), [[2, 1, 0, 0]], 0, 'float32')
def test_forward_gather_nd():
"""test operator GatherNd"""
np_data = np.random.uniform(1, 100, size=(2, 2)).astype(np.float32)
tf.reset_default_graph()
with tf.Graph().as_default():
in_data = tf.placeholder(tf.float32, (2, 2), name="in_data")
tf.gather_nd(in_data, indices=[[1, 0], [0, 1]], name="gather_nd")
compare_tf_with_tvm([np_data], ['in_data:0'], 'gather_nd:0')
#######################################################################
# BiasAdd
# -------
def test_forward_bias_add():
"""test Op BiasAdd"""
def check_bias_add(lh_shpae, rh_shape, dtype):
tf.reset_default_graph()
lh_data = np.random.uniform(size=lh_shpae).astype(dtype)
rh_data = np.random.uniform(size=rh_shape).astype(dtype)
with tf.Graph().as_default():
lft_data = tf.placeholder(dtype, name="lft_data")
rgt_data = tf.placeholder(dtype, name="rgt_data")
tf.nn.bias_add(lft_data, rgt_data, name="BiasAdd")
compare_tf_with_tvm([lh_data, rh_data], [
'lft_data:0', 'rgt_data:0'], 'BiasAdd:0')
check_bias_add((10, 8, 16, 32), (32,), dtype="int32")
check_bias_add((10, 20), (20,), dtype="float32")
#######################################################################
# Split
# -----
def _test_split(in_shape, axis, num_or_size_splits, dtype):
np_data = np.random.uniform(-5, 5, size=in_shape).astype(dtype)
""" One iteration of a Split """
tf.reset_default_graph()
with tf.Graph().as_default():
in_data = tf.placeholder(dtype, in_shape, name="in_data")
num_split = len(num_or_size_splits) if isinstance(num_or_size_splits, list)\
else num_or_size_splits
split = tf.split(in_data, num_or_size_splits, axis=axis)
relu = [tf.nn.relu(i) for i in split]
compare_tf_with_tvm([np_data], ['in_data:0'], [n.name for n in relu])
# and now test together with concat
tf.reset_default_graph()
with tf.Graph().as_default():
in_data = tf.placeholder(dtype, in_shape, name="in_data")
splitted = tf.split(in_data, num_or_size_splits, axis=axis)
concat = tf.concat(splitted, axis)
compare_tf_with_tvm([np_data], 'in_data:0', concat.name)
def test_forward_split():
'''test split layer'''
# rank 1
_test_split((3,), 0, 1, 'float32')
_test_split((3,), 0, 3, 'float32')
_test_split((6,), 0, 3, 'float32')
# rank 2
_test_split((6, 2), 0, 3, 'float32')
_test_split((2, 6), 1, 6, 'float32')
# rank 3
_test_split((6, 2, 4), 0, 2, 'int32')
_test_split((2, 6, 4), 1, 3, 'float32')
_test_split((2, 4, 6), 2, 1, 'float32')
# rank 4
_test_split((6, 1, 3, 5), 0, 3, 'float32')
_test_split((1, 6, 3, 5), 1, 3, 'float32')
_test_split((1, 3, 6, 5), 2, 3, 'float32')
_test_split((1, 3, 5, 6), 3, 3, 'float32')
# split along negative axis
_test_split((6, 1, 3, 5), -4, 3, 'float32')
_test_split((1, 6, 3, 5), -3, 3, 'float32')
_test_split((1, 3, 6, 5), -2, 3, 'float32')
_test_split((1, 3, 5, 6), -1, 3, 'float32')
# size_splits list
_test_split((6,), 0, [1, 2, 3], 'int32')
_test_split((3, 6, 4), -2, [1, 4, 1], 'float32')
######################################################################
# TopKV2
# ------
def _test_forward_top_k_v2(in_shape, k):
np_data = np.random.uniform(-100, 100, size=in_shape).astype("float32")
tf.reset_default_graph()
with tf.Graph().as_default():
in_data = tf.placeholder("float32", in_shape, name="in_data")
tf.math.top_k(in_data, k, name='TopK')
compare_tf_with_tvm([np_data], ['in_data:0'], 'TopK:0')
def test_forward_top_k_v2():
_test_forward_top_k_v2((3,), 1)
_test_forward_top_k_v2((3,), 3)
_test_forward_top_k_v2((3, 5, 7), 3)
_test_forward_top_k_v2((3, 5, 7), 3)
#######################################################################
# Unstack
# -------
def _test_unstack(ip_shape, axis, dtype):
np_data = np.random.uniform(-5, 5, size=ip_shape).astype(dtype)
tf.reset_default_graph()
with tf.Graph().as_default():
in_data = tf.placeholder(dtype, ip_shape, name="in_data")
unstack = tf.unstack(in_data, axis=axis)
compare_tf_with_tvm([np_data], ['in_data:0'], [n.name for n in unstack])
tf.reset_default_graph()
with tf.Graph().as_default():
in_data = tf.placeholder(dtype, ip_shape, name="in_data")
tf.stack(tf.unstack(in_data, axis=axis), axis=axis)
compare_tf_with_tvm([np_data], ['in_data:0'], 'stack:0')
def test_forward_unstack():
'''test unstack layer'''
_test_unstack((6,), 0, 'int32')
_test_unstack((2, 6), 1, 'float64')
# negative axis
_test_unstack((1, 4), -1, 'int32')
_test_unstack((3, 6, 4), -2, 'float32')
#######################################################################
# Tile
# ----
def _test_tile(in_shape, multiples, dtype):
np_data = np.random.uniform(-5, 5, size=in_shape).astype(dtype)
tf.reset_default_graph()
with tf.Graph().as_default():
in_data = tf.placeholder(dtype, in_shape, name="in_data")
tf.tile(in_data, multiples=multiples, name="tile")
compare_tf_with_tvm([np_data], ['in_data:0'], 'tile:0')
def test_forward_tile():
'''test Tile'''
_test_tile((2, ), (3, ), "int32")
_test_tile((2, 2), (2, 3), "float32")
_test_tile((2, 4, 6), (6, 7, 8), "float64")
#######################################################################
# ClipByValue
# -----------
def _test_forward_clip_by_value(ip_shape, clip_value_min, clip_value_max, dtype):
tf.reset_default_graph()
with tf.Graph().as_default():
in_data = tf.placeholder(dtype, ip_shape, name="in_data")
tf.clip_by_value(in_data, clip_value_min,
clip_value_max, name="ClipByValue")
np_data = np.random.uniform(-100, 100, size=ip_shape).astype(dtype)
compare_tf_with_tvm([np_data], ['in_data:0'], 'ClipByValue:0')
def test_forward_clip_by_value():
'''test ClipByValue op'''
if tf.__version__ < LooseVersion('1.9'):
_test_forward_clip_by_value((4,), .1, 5., 'float32')
_test_forward_clip_by_value((4, 4), 1, 5, 'int32')
#######################################################################
# Multi Input to graph
# --------------------
def test_forward_multi_input():
with tf.Graph().as_default():
in1 = tf.placeholder(tf.int32, shape=[3, 3], name='in1')
in2 = tf.placeholder(tf.int32, shape=[3, 3], name='in2')
in3 = tf.placeholder(tf.int32, shape=[3, 3], name='in3')
in4 = tf.placeholder(tf.int32, shape=[3, 3], name='in4')
out1 = tf.add(in1, in2, name='out1')
out2 = tf.subtract(in3, in4, name='out2')
out = tf.multiply(out1, out2, name='out')
in_data = np.arange(9, dtype='int32').reshape([3, 3])
compare_tf_with_tvm([in_data, in_data, in_data, in_data],
['in1:0', 'in2:0', 'in3:0', 'in4:0'], 'out:0')
#######################################################################
# Multi Output to Graph
# ---------------------
def test_forward_multi_output():
with tf.Graph().as_default():
in1 = tf.placeholder(tf.int32, shape=[3, 3], name='in1')
in2 = tf.placeholder(tf.int32, shape=[3, 3], name='in2')
in3 = tf.placeholder(tf.int32, shape=[3, 3], name='in3')
in4 = tf.placeholder(tf.int32, shape=[3, 3], name='in4')
out1 = tf.add(in1, in2, name='out1')
out2 = tf.subtract(in3, in4, name='out2')
in_data = np.arange(9, dtype='int32').reshape([3, 3])
in_data = [in_data] * 4
in_name = ['in1:0', 'in2:0', 'in3:0', 'in4:0']
out_name = ['out1:0', 'out2:0']
out_node = [out.strip(':0') for out in out_name]
in_node = [inp.strip(':0') for inp in in_name]
with tf.Session() as sess:
final_graph_def = tf.graph_util.convert_variables_to_constants(
sess, sess.graph.as_graph_def(add_shapes=True), out_node,)
tf_output = run_tf_graph(sess, in_data, in_name, out_name)
tvm_output = run_tvm_graph(final_graph_def, in_data, in_node, target='llvm',
out_names=out_node, num_output=2)
for i in range(len(tf_output)):
tvm.testing.assert_allclose(
tf_output[i], tvm_output[i], atol=1e-5, rtol=1e-5)
#######################################################################
# Resize Bilinear, Nearest_Neighbor
# ---------------------------------
def _test_resize_bilinear(in_shape, to_shape, align_corners):
""" One iteration of resize bilinear """
data = np.random.uniform(size=in_shape).astype('float32')
shape_data = np.array(to_shape).astype('int32')
with tf.Graph().as_default():
in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)
shape_data = constant_op.constant(
shape_data, shape=shape_data.shape, dtype=shape_data.dtype)
tf.image.resize_bilinear(
in_data, shape_data, align_corners=align_corners)
compare_tf_with_tvm(data, 'Placeholder:0', 'ResizeBilinear:0')
def _test_resize_bilinear_from_tensor(in_shape, align_corners):
""" One iteration of resize bilinear with non-constant output shape, requires
value inference to get proper output shape."""
data = np.random.uniform(size=in_shape).astype('float32')
with tf.Graph().as_default():
in_data = array_ops.placeholder(
shape=[in_shape[0], None, None, in_shape[3]], dtype=data.dtype)
to_shape = tf.shape(in_data)[1:3]
tf.image.resize_bilinear(
in_data, to_shape, align_corners=align_corners)
compare_tf_with_tvm(data, 'Placeholder:0', 'ResizeBilinear:0')
def _test_resize_nearest_neighbor(in_shape, to_shape):
""" One iteration of resize nearest neighbor """
data = np.random.uniform(size=in_shape).astype('float32')
shape_data = np.array(to_shape).astype('int32')
with tf.Graph().as_default():
in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)
shape_data = constant_op.constant(
shape_data, shape=shape_data.shape, dtype=shape_data.dtype)
tf.image.resize_nearest_neighbor(
in_data, shape_data, name='resize_nearest_neighbor')
compare_tf_with_tvm(data, 'Placeholder:0', 'resize_nearest_neighbor:0')
def _test_resize_nearest_neighbor_dynamic_shape(in_shape, scale):
""" One iteration of resize nearest neighbor for graph with dynamic input shape """
data = np.random.uniform(size=in_shape).astype('float32')
with tf.Graph().as_default():
in_data = array_ops.placeholder(shape=None, dtype=data.dtype)
# multiply input shape by scale factor
new_shape = tf.shape(in_data)[1:3] * tf.constant(scale, dtype=tf.int32)
tf.image.resize_nearest_neighbor(
in_data, new_shape, name='resize_nearest_neighbor')
compare_tf_with_tvm(data, 'Placeholder:0', 'resize_nearest_neighbor:0')
def test_forward_resize():
""" Resize Bilinear, Nearest_Neighbor """
# TF default layout is NHWC
_test_resize_bilinear((4, 32, 32, 3), [50, 50], False)
_test_resize_bilinear((6, 32, 32, 3), [20, 20], True)
_test_resize_bilinear_from_tensor((4, 32, 32, 3), False)
_test_resize_bilinear_from_tensor((6, 50, 50, 3), True)
_test_resize_nearest_neighbor((6, 32, 32, 3), [20, 20])
_test_resize_nearest_neighbor_dynamic_shape((1, 16, 16, 3), scale=[2, 2])
#######################################################################
# BroadcastTo
# -----------
def _test_broadcast_to(in_shape, to_shape):
""" One iteration of broadcast_to"""
data = np.random.uniform(size=in_shape).astype('float32')
shape_data = np.array(to_shape).astype('int32')
with tf.Graph().as_default():
in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)
shape_data = constant_op.constant(
shape_data, shape=shape_data.shape, dtype=shape_data.dtype)
tf.broadcast_to(in_data, shape_data)
compare_tf_with_tvm(data, 'Placeholder:0',
'BroadcastTo:0', opt_level=0)
def _test_broadcast_to_from_tensor(in_shape):
""" One iteration of broadcast_to with unknown shape at graph build"""
data = np.random.uniform(size=in_shape).astype('float32')
with tf.Graph().as_default():
in_data = array_ops.placeholder(
shape=[None], dtype=data.dtype)
shape_data = tf.multiply(tf.shape(in_data), 32)
tf.broadcast_to(in_data, shape_data)
compare_tf_with_tvm(data, 'Placeholder:0', 'BroadcastTo:0')
def test_forward_broadcast_to():
""" Resize Bilinear """
_test_broadcast_to((4, 1, 32, 32), [4, 8, 32, 32])
_test_broadcast_to((6, 32, 32, 1), [6, 32, 32, 16])
_test_broadcast_to_from_tensor((1))
#######################################################################
# Fill
# ----
def _test_fill(in_shape):
""" Use the fill op to create a tensor of ones with non-constant shape."""
with tf.Graph().as_default():
tf.ones(shape=in_shape, dtype='float32')
compare_tf_with_tvm(in_shape, [], 'ones:0', opt_level=1)
def _test_fill_from_tensor(in_shape):
""" Use the fill op to create a tensor of ones with non-constant shape.
Some extra ops need to be added here to prevent the graph from
being fully constant and folded away."""
data = np.random.uniform(size=in_shape).astype('float32')
with tf.Graph().as_default():
in_data = array_ops.placeholder(
shape=[in_shape[0], in_shape[1], None, None], dtype=data.dtype)
x = tf.ones(shape=2*tf.shape(in_data), dtype=data.dtype)
y = tf.math.add(in_data, tf.reduce_mean(x), name='out1')
compare_tf_with_tvm(data, 'Placeholder:0', 'out1:0')
def test_forward_fill():
""" Resize Bilinear """
_test_fill((32))
_test_fill((6, 32, 64, 64))
_test_fill_from_tensor((6, 32, 64, 64))
#######################################################################
# Crop to bounding box
# --------------------
def _test_crop(in_shape, off_h, off_w, tar_h, tar_w):
""" Crop to bounding box """
data = np.random.uniform(size=in_shape).astype('float32')
with tf.Graph().as_default():
in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)
tf.image.crop_to_bounding_box(in_data, off_h, off_w, tar_h, tar_w)
compare_tf_with_tvm(data, 'Placeholder:0',
'crop_to_bounding_box/Slice:0')
def test_forward_crop():
""" Crop to bounding box """
_test_crop((1, 224, 224, 3), 20, 20, 120, 120)
#######################################################################
# CropAndResize
# -------------
def _test_forward_crop_and_resize(img_shape, boxes, box_idx, crop_size,
extrapolation_value=0.0, method='bilinear', dtype="float32"):
image = np.random.uniform(0, 10, size=img_shape).astype(dtype)
tf.reset_default_graph()
with tf.Graph().as_default():
in_data = array_ops.placeholder(dtype, image.shape, name="in_data")
tf.image.crop_and_resize(in_data, boxes=boxes, box_ind=box_idx,
crop_size=crop_size, method=method,
extrapolation_value=extrapolation_value,
name="crop_and_resize")
compare_tf_with_tvm([image], ['in_data:0'], 'crop_and_resize:0')
def test_forward_crop_and_resize():
""" CropAndResize """
_test_forward_crop_and_resize([1, 6, 6, 3], [[0, 0, 1, 1]], [0], [3, 3])
_test_forward_crop_and_resize([1, 6, 6, 3], [[0, 0, 1, 1]], [0], [3, 3], 0.2)
_test_forward_crop_and_resize([1, 6, 6, 3], [[0, 0, 1, 1]], [0], [3, 3], 0.2, 'nearest')
_test_forward_crop_and_resize([1, 11, 11, 3], [[.3, .3, 1, 1]], [0], [21, 21])
_test_forward_crop_and_resize([1, 41, 41, 3], [[.2, .4, .8, .8]], [0], [21, 11])
_test_forward_crop_and_resize([1, 100, 100, 3], [[ 0, 0, .9, .9]], [0], [30, 30])
_test_forward_crop_and_resize([1, 224, 224, 3], [[.1, .2, 1, 1]], [0], [9, 9])
_test_forward_crop_and_resize([1, 249, 249, 3], [[ 0, 0, 1, 1]], [0], [9, 9])
_test_forward_crop_and_resize([1, 201, 301, 3], [[.2, .3, .7, .8]], [0], [51, 51])
_test_forward_crop_and_resize(img_shape=[10, 11, 11, 3],
boxes=[[ 0, 0, .9, .9],
[.2, .2, .8, .8]],
box_idx=[0, 1], crop_size=[5, 5])
_test_forward_crop_and_resize(img_shape=[20, 576, 576, 3],
boxes=[[ 0, 0, 1, 1],
[ 0, 0, .8, .8],
[.1, .2, .9, 1],
[.2, 0, 1, 1]],
box_idx=[1, 0, 2, 3], crop_size=[24, 24],
extrapolation_value=0.3)
_test_forward_crop_and_resize(img_shape=[20, 229, 229, 3],
boxes=[[ 0, 0, .9, .9],
[.3, .3, 1, 1],
[.2, .1, .7, .8],
[ 0, 0, 1, 1]],
box_idx=[3, 0, 2, 1], crop_size=[58, 58],
extrapolation_value=0.2, method='nearest')
#######################################################################
# LSTM
# ----
def _test_lstm_cell(batch_size, num_hidden, num_layers, forget_bias, dtype):
""" One iteration of a LSTM cell """
tf.reset_default_graph()
input_size = num_hidden
input_data = np.full((batch_size, input_size), 1., dtype=dtype)
in_state_c = np.full(
(num_layers, batch_size, num_hidden), 0.1, dtype=dtype)
in_state_h = np.full(
(num_layers, batch_size, num_hidden), 0.1, dtype=dtype)
def _get_tensorflow_output():
with tf.Session() as sess:
with variable_scope.variable_scope(
"root", initializer=init_ops.constant_initializer(0.5)):
m0 = array_ops.zeros([batch_size, num_hidden])
m1 = array_ops.zeros([batch_size, num_hidden])
x = tf.placeholder(shape=(batch_size, input_size), dtype=dtype)
g, ((out_m0, out_m1)) = \
tensorflow.contrib.rnn.LSTMBlockCell(num_hidden,
forget_bias=forget_bias)(x, (m0, m1))
sess.run([variables.global_variables_initializer()])
res = sess.run([g, out_m0, out_m1], {
x.name: np.array([[1., 1.]]),
m0.name: 0.1 * np.ones([batch_size, num_hidden]),
m1.name: 0.1 * np.ones([batch_size, num_hidden]),
})
graph_def = sess.graph.as_graph_def(add_shapes=True)
final_graph_def = graph_util.convert_variables_to_constants(
sess,
graph_def,
['root/lstm_cell/LSTMBlockCell'])
return final_graph_def, res
graph_def, tf_out = _get_tensorflow_output()
tvm_output = run_tvm_graph(graph_def, [input_data, in_state_c, in_state_h],
['root/Placeholder', 'root/lstm_cell/LSTMBlockCell_c',
'root/lstm_cell/LSTMBlockCell_h'], num_output=2)
assert isinstance(tvm_output, list)
out = tvm_output[0]
out_state = tvm_output[1]
out_state_tup = np.split(out_state, indices_or_sections=2, axis=1)
out_state_c = np.reshape(out_state_tup[0], (batch_size, num_hidden))
out_state_h = np.reshape(out_state_tup[1], (batch_size, num_hidden))
tvm_out = [out, out_state_c, out_state_h]
tvm.testing.assert_allclose(tf_out[0], tvm_out[0], rtol=1e-3, atol=1e-3)
def test_forward_lstm():
'''test LSTM block cell'''
_test_lstm_cell(1, 2, 1, 0.5, 'float32')
#######################################################################
# Pack
# ---
def _test_pack(axis, shape, **kwargs):
a = np.arange(np.prod(shape), dtype=np.float32).reshape(shape)
b = np.arange(np.prod(shape), dtype=np.float32).reshape(shape)
with tf.Graph().as_default():
tf_a = array_ops.placeholder(shape=shape, dtype='float32', name='pl_a')
tf_b = array_ops.placeholder(shape=shape, dtype='float32', name='pl_b')
tf_c = tf.stack([tf_a, tf_b], axis=axis, **kwargs)
assert tf_c.op.op_def.name == 'Pack', "tf.stack() is expected to produce 'Pack' operation"
compare_tf_with_tvm([a, b], ['pl_a:0', 'pl_b:0'], 'stack:0')
def test_forward_pack():
for axis in range(-3, 3):
_test_pack(axis, [3, 2, 1])
for axis in range(-1, 1):
_test_pack(axis, [3])
_test_pack(0, [])
#######################################################################
# Unpack
# ------
def _test_forward_unpack(in_shape, axis, dtype):
"""test operator Unpack"""
np_data = np.random.uniform(-100, 100, size=in_shape).astype(dtype)
tf.reset_default_graph()
with tf.Graph().as_default():
in_data = tf.placeholder(dtype, in_shape, name="in_data")
tf.unstack(in_data, axis=axis, name="Unpack")
compare_tf_with_tvm([np_data], ['in_data:0'], 'Unpack:0')
def test_forward_unpack():
_test_forward_unpack((3,), 0, 'int32')
_test_forward_unpack((3,), -1, 'int16')
_test_forward_unpack((21, 23, 3), 2, 'float32')
#######################################################################
# Range
# -----
def test_forward_range():
"""test operator Range"""
tf.reset_default_graph()
with tf.Graph().as_default():
tf.range(1, 18, 3, name="range")
compare_tf_with_tvm([], [], 'range:0')
"""test type assignment for operator Range"""
tf.reset_default_graph()
with tf.Graph().as_default():
tf.range(1, 256 + 1, 1, dtype=tf.float32)
compare_tf_with_tvm([], [], 'range:0')
#######################################################################
# Pad
# ---
def _test_pad(input_shape, paddings, mode, **kwargs):
""" One iteration of pad operation with given shape"""
x = np.arange(np.prod(input_shape), dtype=np.float32).reshape(input_shape)
with tf.Graph().as_default():
in_data = array_ops.placeholder(shape=input_shape, dtype='float32')
pad_values = constant_op.constant(paddings)
pad = tf.pad(in_data, paddings=pad_values, mode=mode, **kwargs)
if mode == 'CONSTANT':
if 'constant_values' in kwargs:
out_name = 'PadV2:0'
else:
out_name = 'Pad:0'
else:
out_name = 'MirrorPad:0'
compare_tf_with_tvm(x, 'Placeholder:0', out_name)
def test_forward_pad():
""" Pad """
_test_pad((2, 3), [[1, 1], [2, 2]], mode="CONSTANT")
_test_pad((2, 3), [[1, 1], [2, 2]], mode="CONSTANT", constant_values=1.0)
_test_pad((2, 3), [[1, 1], [2, 2]], mode="SYMMETRIC")
_test_pad((2, 3), [[1, 1], [2, 2]], mode="REFLECT")
#######################################################################
# Logical operators
# --------------------
def test_logical_and():
with tf.Graph().as_default():
in1 = tf.placeholder(tf.bool, shape=[1, 4, 4, 3], name='in1')
in2 = tf.placeholder(tf.bool, shape=[1, 4, 4, 3], name='in2')
out = tf.logical_and(in1, in2, name='out')
in_data1 = np.random.choice(
a=[False, True], size=(1, 4, 4, 3)).astype('bool')
in_data2 = np.random.choice(
a=[False, True], size=(1, 4, 4, 3)).astype('bool')
compare_tf_with_tvm([in_data1, in_data2], ['in1:0', 'in2:0'], 'out:0')
def test_logical_or():
with tf.Graph().as_default():
in1 = tf.placeholder(tf.bool, shape=[1, 4, 4, 3], name='in1')
in2 = tf.placeholder(tf.bool, shape=[1, 4, 4, 3], name='in2')
out = tf.logical_or(in1, in2, name='out')
in_data1 = np.random.choice(
a=[False, True], size=(1, 4, 4, 3)).astype('bool')
in_data2 = np.random.choice(
a=[False, True], size=(1, 4, 4, 3)).astype('bool')
compare_tf_with_tvm([in_data1, in_data2], ['in1:0', 'in2:0'], 'out:0')
def test_logical_xor():
with tf.Graph().as_default():
in1 = tf.placeholder(tf.bool, shape=[1, 4, 4, 3], name='in1')
in2 = tf.placeholder(tf.bool, shape=[1, 4, 4, 3], name='in2')
out = tf.logical_xor(in1, in2, name='out')
in_data1 = np.random.choice(
a=[False, True], size=(1, 4, 4, 3)).astype('bool')
in_data2 = np.random.choice(
a=[False, True], size=(1, 4, 4, 3)).astype('bool')
compare_tf_with_tvm([in_data1, in_data2], ['in1:0', 'in2:0'], 'out:0')
def test_logical_not():
with tf.Graph().as_default():
in1 = tf.placeholder(tf.bool, shape=[1, 4, 4, 3], name='in1')
out = tf.logical_not(in1, name='out')
in_data1 = np.random.choice(
a=[False, True], size=(1, 4, 4, 3)).astype('bool')
compare_tf_with_tvm(in_data1, 'in1:0', 'out:0')
def test_forward_logical():
test_logical_and()
test_logical_or()
test_logical_xor()
test_logical_not()
#######################################################################
# Where, Select
# -------------
def test_forward_where():
''' Where: return elements depending on conditions'''
with tf.Graph().as_default():
with tf.Session() as sess:
input1 = tf.placeholder(
tf.int32, shape=[1, 4, 4, 3], name='input1')
input2 = tf.placeholder(
tf.int32, shape=[1, 4, 4, 3], name='input2')
mask = input1 > input2
tf.where(mask, input1 + 1, input2 * 2)
in_data1 = np.random.uniform(
0, 10, size=(1, 4, 4, 3)).astype("uint32")
in_data2 = np.random.uniform(
0, 10, size=(1, 4, 4, 3)).astype("uint32")
compare_tf_with_tvm([in_data1, in_data2], [
'input1:0', 'input2:0'], 'Select:0')
#######################################################################
# Inception V3
# ------------
def test_forward_inception_v3():
'''test inception V3 model'''
with tf.Graph().as_default():
graph_def = tf_testing.get_workload(
'InceptionV3/inception_v3_2016_08_28_frozen-with_shapes.pb')
# Call the utility to import the graph definition into default graph.
graph_def = tf_testing.ProcessGraphDefParam(graph_def)
data = np.random.uniform(size=(1, 299, 299, 3)).astype('float32')
with tf.Session() as sess:
tf_output = run_tf_graph(
sess, data, 'input:0', 'InceptionV3/Predictions/Reshape_1:0')
tvm_output = run_tvm_graph(graph_def, data, 'input')
tvm.testing.assert_allclose(
tf_output[0], tvm_output[0], rtol=1e-5, atol=1e-5)
#######################################################################
# Inception V1
# ------------
def test_forward_inception_v1():
'''test inception V1 model'''
with tf.Graph().as_default():
graph_def = tf_testing.get_workload(
"InceptionV1/classify_image_graph_def-with_shapes.pb")
# Call the utility to import the graph definition into default graph.
graph_def = tf_testing.ProcessGraphDefParam(graph_def)
# Build an image from random data.
from PIL import Image
from tvm.contrib import util
img_array = np.random.uniform(size=(1, 600, 600, 3)).astype("uint8")
img = Image.frombuffer(
'RGB', (600, 600), img_array.tostring(), 'raw', 'RGB', 0, 1)
temp = util.tempdir()
img_path = temp.relpath("tf-test.jpg")
img.save(img_path)
import os.path
if not tf.gfile.Exists(os.path.join(img_path)):
tf.logging.fatal('File does not exist %s', img_path)
data = tf.gfile.FastGFile(os.path.join(img_path), 'rb').read()
temp.remove()
# Extract tensorflow decoded image frame for tvm input
with tf.Session() as sess:
tvm_data = run_tf_graph(
sess, data, 'DecodeJpeg/contents:0', 'DecodeJpeg:0')
with tf.Session() as sess:
tf_output = run_tf_graph(
sess, data, 'DecodeJpeg/contents:0', 'softmax:0')
tvm_output = run_tvm_graph(
graph_def, tvm_data, 'DecodeJpeg/contents')
tvm.testing.assert_allclose(
tf_output[0], tvm_output[0], rtol=1e-5, atol=1e-5)
#######################################################################
# Mobilenet
# ---------
def test_forward_mobilenet():
'''test mobilenet model'''
# MobilenetV2
with tf.Graph().as_default():
graph_def = tf_testing.get_workload(
"https://storage.googleapis.com/mobilenet_v2/checkpoints/mobilenet_v2_1.4_224.tgz",
"mobilenet_v2_1.4_224_frozen.pb")
# Call the utility to import the graph definition into default graph.
graph_def = tf_testing.ProcessGraphDefParam(graph_def)
data = np.random.uniform(size=(1, 224, 224, 3)).astype('float32')
out_node = 'MobilenetV2/Predictions/Reshape_1'
with tf.Session() as sess:
# Add shapes to the graph.
graph_def = tf_testing.AddShapesToGraphDef(sess, out_node)
tf_output = run_tf_graph(sess, data, 'input:0', out_node + ':0')
tvm_output = run_tvm_graph(graph_def, data, 'input')
tvm.testing.assert_allclose(np.squeeze(tvm_output[0]), np.squeeze(tf_output[0]),
rtol=1e-5, atol=1e-5)
#######################################################################
# ResnetV2
# --------
def test_forward_resnetv2():
'''test resnet model'''
if is_gpu_available():
with tf.Graph().as_default():
graph_def = tf_testing.get_workload(
"ResnetV2/resnet-20180601_resnet_v2_imagenet-shapes.pb")
# Call the utility to import the graph definition into default graph.
graph_def = tf_testing.ProcessGraphDefParam(graph_def)
data = np.random.uniform(size=(128, 224, 224, 3)).astype('float32')
out_node = 'ArgMax'
with tf.Session() as sess:
tf_output = run_tf_graph(
sess, data, 'input_tensor:0', out_node + ':0')
for device in ["llvm", "cuda"]:
ctx = tvm.context(device, 0)
if not ctx.exist:
print("Skip because %s is not enabled" % device)
continue
tvm_output = run_tvm_graph(graph_def, data, 'input_tensor', len(tf_output),
target=device)
tvm.testing.assert_allclose(np.squeeze(tvm_output[0]), np.squeeze(tf_output[0]),
rtol=1e-5, atol=1e-5)
#######################################################################
# Placeholder
# -----------
def test_forward_placeholder():
'''test a simple pb with Placeholder node in the end of GraphDef'''
with tf.Graph().as_default():
graph_def = tf_testing.get_workload("Custom/placeholder.pb")
# Call the utility to import the graph definition into default graph.
graph_def = tf_testing.ProcessGraphDefParam(graph_def)
data = np.random.uniform(size=(1, 224, 224, 3)).astype('float32')
out_node = 'mul'
with tf.Session() as sess:
# Add shapes to the graph.
graph_def = tf_testing.AddShapesToGraphDef(sess, out_node)
tf_output = run_tf_graph(
sess, data, 'Placeholder:0', out_node + ':0')
tvm_output = run_tvm_graph(graph_def, data, 'Placeholder')
tvm.testing.assert_allclose(np.squeeze(tvm_output[0]), np.squeeze(tf_output[0]),
rtol=1e-5, atol=1e-5)
#######################################################################
# PTB
# ---
try:
#Load contrib for running ptb model in tf version before 2.0
import tensorflow.contrib
except:
pass
def test_forward_ptb():
'''test ptb model'''
config = tf_testing.get_config()
num_steps = config.num_steps
num_hidden = config.hidden_size
num_layers = config.num_layers
batch_size = config.batch_size
vocab_size = config.vocab_size
out_sample_shape = (batch_size, vocab_size)
out_state_shape = (num_layers, 2, batch_size, num_hidden)
# Sample input
inpt = "we have no useful information on"
cnt_sample = 20
def _pretty_print(items, is_char_model, id2word):
if not is_char_model:
return ' '.join([id2word[x] for x in items])
else:
return ''.join([id2word[x] for x in items]).replace('_', ' ')
def _get_tvm_graph_module(graph_def):
# Cell inputs 'c and 'h' consist of all layers values
shape_dict = {'Model/Placeholder': (batch_size, num_steps),
'Model/RNN/RNN/multi_rnn_cell/cell_0/lstm_cell/LSTMBlockCell_c':
(num_layers, batch_size, num_hidden),
'Model/RNN/RNN/multi_rnn_cell/cell_0/lstm_cell/LSTMBlockCell_h':
(num_layers, batch_size, num_hidden)}
mod, params = relay.frontend.from_tensorflow(
graph_def, shape=shape_dict)
dtype_dict = {'Model/Placeholder': 'int32',
'Model/RNN/RNN/multi_rnn_cell/cell_0/lstm_cell/LSTMBlockCell_c': 'float32',
'Model/RNN/RNN/multi_rnn_cell/cell_0/lstm_cell/LSTMBlockCell_h': 'float32'}
target = 'llvm'
with relay.build_config(opt_level=0):
graph, lib, params = relay.build(mod,
target,
params=params)
from tvm.contrib import graph_runtime
ctx = tvm.cpu(0)
return params, graph_runtime.create(graph, lib, ctx)
def _do_tvm_sample(model, data, in_states, params, num_samples):
"""Sampled from the model"""
samples = []
state = in_states
sample = None
def _get_sample(data, state):
input_data = np.full((batch_size, num_steps), data, dtype="int32")
in_state_tup = np.split(state, indices_or_sections=2, axis=1)
in_state_c = np.reshape(
in_state_tup[0], (num_layers, batch_size, num_hidden))
in_state_h = np.reshape(
in_state_tup[1], (num_layers, batch_size, num_hidden))
model.set_input('Model/Placeholder',
tvm.nd.array(input_data.astype("int32")))
model.set_input('Model/RNN/RNN/multi_rnn_cell/cell_0/lstm_cell/LSTMBlockCell_c',
tvm.nd.array(in_state_c.astype("float32")))
model.set_input('Model/RNN/RNN/multi_rnn_cell/cell_0/lstm_cell/LSTMBlockCell_h',
tvm.nd.array(in_state_h.astype("float32")))
model.set_input(**params)
model.run()
tvm_output = model.get_output(0, tvm.nd.empty(out_sample_shape,
"float32")).asnumpy()
state_output = model.get_output(1, tvm.nd.empty(out_state_shape,
"float32")).asnumpy()
sample = tf_testing.pick_from_weight(tvm_output[0])
return sample, state_output
for x in data:
sample, state = _get_sample(x, state)
if sample is not None:
samples.append(sample)
else:
samples.append(0)
k = 1
while k < num_samples:
sample, state = _get_sample(samples[-1], state)
samples.append(sample)
k += 1
return samples, state
with tf.Graph().as_default():
word_to_id, id_to_word, graph_def = tf_testing.get_workload_ptb()
vocab_size = len(word_to_id)
# Call the utility to import the graph definition into default graph.
graph_def = tf_testing.ProcessGraphDefParam(graph_def)
sess = tf.Session()
# TVM graph module creation
params, m = _get_tvm_graph_module(graph_def)
# Create 10 predicted statments of 20 words
cnt_stm = 0
while cnt_stm < 10:
cnt_stm += 1
in_state = np.full(
(num_layers, 2, batch_size, num_hidden), 0, dtype="float32")
seed_for_sample = inpt.split()
tvm_samples, tvm_state = _do_tvm_sample(m, [word_to_id[word]
for word in seed_for_sample],
in_state, params, cnt_sample)
tvm_sample_str = _pretty_print(tvm_samples, False, id_to_word)
tf_samples, tf_state = tf_testing.do_tf_sample(
sess,
[word_to_id[word] for word in seed_for_sample],
in_state, cnt_sample)
tf_sample_str = _pretty_print(tf_samples, False, id_to_word)
inpt = tvm_sample_str
tvm.testing.assert_allclose(
tf_samples, tvm_samples, rtol=1e-5, atol=1e-5)
assert tvm_sample_str == tf_sample_str
#######################################################################
# LRN (Local Response Normalization)
# ----------------------------------
def _test_lrn(ishape, size, axis, bias, alpha, beta):
""" testing local response normalization """
lrn_depth_radius = size / 2
inp_array = np.random.uniform(size=ishape).astype(np.float32)
with tf.Graph().as_default():
in1 = tf.placeholder(shape=inp_array.shape,
dtype=inp_array.dtype, name="lrn0_data")
nn_ops.local_response_normalization(in1,
name="lrn",
depth_radius=lrn_depth_radius,
bias=bias,
alpha=alpha,
beta=beta)
compare_tf_with_tvm(inp_array, 'lrn0_data:0', 'lrn:0')
def test_forward_lrn():
_test_lrn((1, 3, 20, 20), 3, 1, 1.0, 1.0, 0.5)
#######################################################################
# l2_normalize
# ------------
def _test_l2_normalize(ishape, eps, axis):
""" testing l2 normalize (uses max, sum, square, sqrt frontend operators)"""
inp_array = np.random.uniform(size=ishape).astype(np.float32)
with tf.Graph().as_default():
in1 = tf.placeholder(shape=inp_array.shape, dtype=inp_array.dtype)
nn.l2_normalize(in1,
axis=axis,
epsilon=eps,
name=None,
dim=None)
compare_tf_with_tvm(inp_array, 'Placeholder:0', 'l2_normalize:0')
def test_forward_l2_normalize():
_test_l2_normalize((1, 3, 20, 20), 0.001, (0,))
#######################################################################
# transpose
# ---------
def _test_forward_transpose(ishape, axes=None):
data = np.random.uniform(size=ishape).astype(np.float32)
with tf.Graph().as_default():
in1 = tf.placeholder(
shape=data.shape, dtype=data.dtype, name="transpose_data")
if axes is None:
tf.transpose(in1)
else:
tf.transpose(in1, perm=axes)
compare_tf_with_tvm(data, 'transpose_data:0', 'transpose:0')
def _test_forward_tranapose_axes_input(ishape, axes):
data = np.random.uniform(size=ishape).astype(np.float32)
axes_np = np.array(axes).astype(np.int32)
with tf.Graph().as_default():
in1 = tf.placeholder(
shape=data.shape, dtype=data.dtype, name="transpose_data")
const1 = tf.constant(axes_np, dtype=tf.int32)
# make axes an input to tf.transpose, but not an input to the graph,
# so it can be extracted with infer_value_simulated
axes = tf.reverse(const1, axis=[-1])
tf.transpose(in1, axes)
compare_tf_with_tvm([data], ['transpose_data:0'], 'transpose:0')
def test_forward_transpose():
_test_forward_transpose((2, 3, 4), (1, 2, 0))
_test_forward_transpose((2, 3, 4))
_test_forward_transpose((7, 8, 8, 10))
_test_forward_transpose((2, 3, 4), (1, 2, 0))
_test_forward_transpose((2, 3, 4), (0, 1, 2))
_test_forward_transpose((2, 3, 4, 5), (3, 0, 1, 2))
_test_forward_tranapose_axes_input((2, 3, 4), (1, 2, 0))
_test_forward_tranapose_axes_input((2, 3, 4, 5), (3, 0, 1, 2))
def _test_forward_slice_operation_input(input_value, begin_value, size_value):
input_data = np.array(input_value, dtype=np.float32)
with tf.Graph().as_default():
input_tensor = tf.placeholder(
shape=input_data.shape, dtype=input_data.dtype, name="input")
tf.slice(input_tensor, begin_value, size_value, name='slice_output')
compare_tf_with_tvm([input_data], ['input:0'], 'slice_output:0')
def test_forward_slice():
_test_forward_slice_operation_input([1, 1], [0], [2])
_test_forward_slice_operation_input([0, 1, 2, 3], [3], [-1])
_test_forward_slice_operation_input([[0, 1, 2, 3], [4, 5, 6, 7]],
begin_value=[0, 1], size_value=[-1, -1])
def test_forward_ceil():
ishape = (1, 3, 10, 10)
inp_array = np.random.uniform(size=ishape).astype(np.float32)
with tf.Graph().as_default():
in1 = tf.placeholder(shape=inp_array.shape, dtype=inp_array.dtype)
tf.ceil(in1)
compare_tf_with_tvm(inp_array, 'Placeholder:0', 'Ceil:0')
def test_forward_floor():
ishape = (1, 3, 10, 10)
inp_array = np.random.uniform(size=ishape).astype(np.float32)
with tf.Graph().as_default():
in1 = tf.placeholder(shape=inp_array.shape, dtype=inp_array.dtype)
tf.floor(in1)
compare_tf_with_tvm(inp_array, 'Placeholder:0', 'Floor:0')
def test_forward_relu():
ishape = (1, 3, 10, 10)
inp_array = np.random.uniform(-5, 5, size=ishape).astype(np.float32)
for mode in ['graph_runtime', 'vm']:
with tf.Graph().as_default():
in1 = tf.placeholder(shape=inp_array.shape, dtype=inp_array.dtype)
tf.nn.relu(in1)
compare_tf_with_tvm(inp_array, 'Placeholder:0', 'Relu:0', mode=mode)
def test_forward_leaky_relu():
ishape = (1, 3, 10, 10)
inp_array = np.random.uniform(-5, 5, size=ishape).astype(np.float32)
for mode in ['graph_runtime', 'vm']:
with tf.Graph().as_default():
in1 = tf.placeholder(shape=inp_array.shape, dtype=inp_array.dtype)
tf.nn.leaky_relu(in1, alpha=0.4)
compare_tf_with_tvm(inp_array, 'Placeholder:0', 'LeakyRelu:0', mode=mode)
def test_forward_elu():
ishape = (1, 3, 10, 10)
inp_array = np.random.uniform(-5, 5, size=ishape).astype(np.float32)
with tf.Graph().as_default():
in1 = tf.placeholder(shape=inp_array.shape, dtype=inp_array.dtype)
tf.nn.elu(in1)
compare_tf_with_tvm(inp_array, 'Placeholder:0', 'Elu:0')
def test_forward_selu():
ishape = (1, 3, 10, 10)
inp_array = np.random.uniform(-5, 5, size=ishape).astype(np.float32)
with tf.Graph().as_default():
in1 = tf.placeholder(shape=inp_array.shape, dtype=inp_array.dtype)
tf.nn.selu(in1)
compare_tf_with_tvm(inp_array, 'Placeholder:0', 'Selu:0')
def test_forward_tanh():
ishape = (1, 3, 10, 10)
inp_array = np.random.uniform(-5, 5, size=ishape).astype(np.float32)
with tf.Graph().as_default():
in1 = tf.placeholder(shape=inp_array.shape, dtype=inp_array.dtype)
tf.nn.tanh(in1)
compare_tf_with_tvm(inp_array, 'Placeholder:0', 'Tanh:0')
#######################################################################
# Softmax
# -------
def test_forward_softmax():
"""test operator Softmax """
def check_softmax(in_shape, axis, dtype):
np_data = np.random.uniform(-100, 100, size=in_shape).astype(dtype)
tf.reset_default_graph()
with tf.Graph().as_default():
in_data = tf.placeholder(dtype, in_shape, name="in_data")
tf.nn.softmax(in_data, axis=axis, name="Softmax")
compare_tf_with_tvm([np_data], ['in_data:0'], 'Softmax:0')
check_softmax((2, 3, 5), 2, "float32")
check_softmax((2, 3, 5), -1, "float32")
#######################################################################
# Tensor
# ------
def test_forward_round():
"""test Round"""
np_data = np.random.uniform(-10, 10, size=(5, 7)).astype(np.float32)
tf.reset_default_graph()
with tf.Graph().as_default():
in_data = tf.placeholder(tf.float32, (5, 7), name="in_data")
tf.round(in_data, name="round")
compare_tf_with_tvm([np_data], ['in_data:0'], 'round:0')
def test_forward_abs():
"""test operator Abs"""
np_data = np.random.uniform(1, 100, size=(9, 11)).astype(np.float32)
tf.reset_default_graph()
with tf.Graph().as_default():
in_data = tf.placeholder(tf.float32, (9, 11), name="in_data")
tf.math.abs(in_data, name="abs")
compare_tf_with_tvm([np_data], ['in_data:0'], 'abs:0')
def _test_forward_zeros_like(in_shape, dtype):
np_data = np.random.uniform(-10, 10, size=in_shape).astype(dtype)
tf.reset_default_graph()
with tf.Graph().as_default():
in_data = tf.placeholder(dtype, in_shape, name="in_data")
tf.zeros_like(in_data, name="zeros_like")
compare_tf_with_tvm([np_data], ['in_data:0'], 'zeros_like:0')
def test_forward_zeros_like():
if tf.__version__ < LooseVersion('1.2'):
_test_forward_zeros_like((2, 3), "int32")
_test_forward_zeros_like((2, 3, 5), "int8")
_test_forward_zeros_like((2, 3, 5, 7), "uint16")
_test_forward_zeros_like((2, 3, 11), "float32")
_test_forward_zeros_like((2, 3, 11), "float64")
def test_forward_erf():
ishape = (1, 3, 10, 10)
inp_array = np.random.uniform(-5, 5, size=ishape).astype(np.float32)
with tf.Graph().as_default():
in1 = tf.placeholder(shape=inp_array.shape, dtype=inp_array.dtype)
tf.math.erf(in1)
compare_tf_with_tvm(inp_array, 'Placeholder:0', 'Erf:0')
def test_forward_squared_difference():
ishape = (1, 3, 10, 14)
inp_array_a = np.random.uniform(-5, 5, size=ishape).astype(np.float32)
inp_array_b = np.random.uniform(-5, 5, size=ishape).astype(np.float32)
with tf.Graph().as_default():
in1 = tf.placeholder(shape=inp_array_a.shape,
dtype=inp_array_a.dtype, name="in1")
in2 = tf.placeholder(shape=inp_array_b.shape,
dtype=inp_array_b.dtype, name="in2")
out = tf.math.squared_difference(in1, in2)
compare_tf_with_tvm([inp_array_a, inp_array_b], [
in1.name, in2.name], out.name)
def _test_forward_reverse_v2(in_shape, axis, dtype):
np_data = np.random.uniform(-10, 10, size=in_shape).astype(dtype)
tf.reset_default_graph()
with tf.Graph().as_default():
in_data = tf.placeholder(dtype, in_shape, name="in_data")
tf.reverse(in_data, axis=[axis], name="reverse")
compare_tf_with_tvm([np_data], ['in_data:0'], 'reverse:0')
def test_forward_reverse_v2():
"""test ReverseV2"""
_test_forward_reverse_v2((2, 3), 0, "int32")
_test_forward_reverse_v2((2, 3, 5), 2, "float32")
_test_forward_reverse_v2((2, 3, 5, 7), 1, "float32")
_test_forward_reverse_v2((2, 3, 5), -1, "float64")
_test_forward_reverse_v2((2, 3, 5), -3, "float64")
def test_forward_sign():
"""test Sign"""
np_data = np.random.uniform(-10, 10, size=(5, 7, 11)).astype(np.float32)
tf.reset_default_graph()
with tf.Graph().as_default():
in_data = tf.placeholder(tf.float32, (5, 7, 11), name="in_data")
tf.sign(in_data, name="sign")
compare_tf_with_tvm([np_data], ['in_data:0'], 'sign:0')
def test_forward_square():
"""test operator Square """
np_data = np.random.uniform(1, 100, size=(2, 3, 5)).astype(np.float32)
tf.reset_default_graph()
with tf.Graph().as_default():
in_data = tf.placeholder(tf.float32, (2, 3, 5), name="in_data")
tf.square(in_data, name="square")
compare_tf_with_tvm([np_data], ['in_data:0'], 'square:0')
def test_forward_pow_exp():
"""test Pow and Exp """
np_in1 = np.random.uniform(-2, 2, size=(5, 7, 11)).astype(np.float32)
np_in2 = np.random.uniform(-2, 2, size=(5, 7, 11)).astype(np.float32)
tf.reset_default_graph()
with tf.Graph().as_default():
in1 = tf.placeholder(tf.float32, (5, 7, 11), name="in1")
in2 = tf.placeholder(tf.float32, (5, 7, 11), name="in2")
out1 = tf.pow(in1, in2, name="pow")
out = tf.exp(in1, name='exp')
compare_tf_with_tvm([np_in1, np_in2], ['in1:0', 'in2:0'], 'pow:0')
compare_tf_with_tvm([np_in1], ['in1:0'], 'exp:0')
def test_forward_log():
"""test operator Log """
np_data = np.random.uniform(1, 100, size=(2, 3, 5)).astype(np.float32)
tf.reset_default_graph()
with tf.Graph().as_default():
in_data = tf.placeholder(tf.float32, (2, 3, 5), name="in_data")
tf.log(in_data, name="log")
compare_tf_with_tvm([np_data], ['in_data:0'], 'log:0')
def test_forward_log1p():
"""test operator Log1p """
np_data = np.random.uniform(1, 100, size=(2, 3, 5)).astype(np.float32)
tf.reset_default_graph()
with tf.Graph().as_default():
in_data = tf.placeholder(tf.float32, (2, 3, 5), name="in_data")
tf.log1p(in_data, name="log1p")
compare_tf_with_tvm([np_data], ['in_data:0'], 'log1p:0')
def test_forward_cos():
"""test operator cos """
np_data = np.random.uniform(1, 100, size=(2, 3, 5)).astype(np.float32)
tf.reset_default_graph()
with tf.Graph().as_default():
in_data = tf.placeholder(tf.float32, (2, 3, 5), name="in_data")
tf.cos(in_data, name="cos")
compare_tf_with_tvm([np_data], ['in_data:0'], 'cos:0')
def test_forward_tan():
"""test operator tan """
np_data = np.random.uniform(1, 100, size=(2, 3, 5)).astype(np.float32)
tf.reset_default_graph()
in_data = tf.placeholder(tf.float32, (2, 3, 5), name="in_data")
tf.tan(in_data, name="tan")
compare_tf_with_tvm([np_data], ['in_data:0'], 'tan:0')
def test_forward_atan():
"""test operator tan """
tf.disable_eager_execution()
np_data = np.random.uniform(1, 100, size=(2, 3, 5)).astype(np.float32)
tf.reset_default_graph()
in_data = tf.placeholder(tf.float32, (2, 3, 5), name="in_data")
tf.atan(in_data, name="atan")
compare_tf_with_tvm([np_data], ['in_data:0'], 'atan:0')
def test_forward_atan2():
"""test operator tan """
tf.disable_eager_execution()
np_data_1 = np.random.uniform(1, 100, size=(2, 3, 5)).astype(np.float32)
np_data_2 = np.random.uniform(1, 100, size=(2, 3, 5)).astype(np.float32)
tf.reset_default_graph()
in_data_1 = tf.placeholder(tf.float32, (2, 3, 5), name="in_data_1")
in_data_2 = tf.placeholder(tf.float32, (2, 3, 5), name="in_data_2")
tf.atan2(in_data_1, in_data_2, name="atan2")
compare_tf_with_tvm([np_data_1, np_data_2], ['in_data_1:0', 'in_data_2:0'], 'atan2:0')
def test_forward_sin():
"""test operator sin """
np_data = np.random.uniform(1, 100, size=(2, 3, 5)).astype(np.float32)
tf.reset_default_graph()
with tf.Graph().as_default():
in_data = tf.placeholder(tf.float32, (2, 3, 5), name="in_data")
tf.sin(in_data, name="sin")
compare_tf_with_tvm([np_data], ['in_data:0'], 'sin:0')
def test_forward_negative():
"""test tf operator Neg """
np_data = np.random.uniform(-100, 255,
size=(224, 224, 3)).astype(np.float32)
tf.reset_default_graph()
with tf.Graph().as_default():
in_data = tf.placeholder(tf.float32, (224, 224, 3), name="in_data")
tf.negative(in_data, name="negative")
compare_tf_with_tvm([np_data], ['in_data:0'], 'negative:0')
def test_forward_log_softmax():
"""test operator LogSoftmax"""
np_data = np.random.uniform(1, 100, size=(9, 11)).astype(np.float32)
tf.reset_default_graph()
with tf.Graph().as_default():
in_data = tf.placeholder(tf.float32, (9, 11), name="in_data")
tf.math.log_softmax(in_data, name="LogSoftmax")
compare_tf_with_tvm([np_data], ['in_data:0'], 'LogSoftmax:0')
def test_forward_softplus():
"""test operator Softplus"""
np_data = np.random.uniform(1, 10, size=(2, 3, 5)).astype(np.float32)
tf.reset_default_graph()
with tf.Graph().as_default():
in_data = tf.placeholder(tf.float32, (2, 3, 5), name="in_data")
tf.nn.softplus(in_data, name="softplus")
compare_tf_with_tvm([np_data], ['in_data:0'], 'softplus:0')
def test_forward_rsqrt():
"""test Rsqrt """
np_data = np.random.uniform(1, 100, size=(5, 7, 11)).astype(np.float32)
tf.reset_default_graph()
with tf.Graph().as_default():
in_data = tf.placeholder(tf.float32, (5, 7, 11), name="in_data")
tf.rsqrt(in_data, name="rsqrt")
compare_tf_with_tvm([np_data], ['in_data:0'], 'rsqrt:0')
def test_forward_sqrt():
"""test Sqrt """
np_data = np.random.uniform(1, 100, size=(5, 7, 11)).astype(np.float32)
tf.reset_default_graph()
with tf.Graph().as_default():
in_data = tf.placeholder(tf.float32, (5, 7, 11), name="in_data")
tf.sqrt(in_data, name="sqrt")
compare_tf_with_tvm([np_data], ['in_data:0'], 'sqrt:0')
def _test_forward_right_shift(in_shape, dtype):
"""test operator RightShift"""
lh_data = np.random.randint(1, 3, size=in_shape).astype(dtype)
rh_data = np.random.randint(1, 8, size=in_shape).astype(dtype)
tf.reset_default_graph()
with tf.Graph().as_default():
lft_data = tf.placeholder(dtype, in_shape, name="lft_data")
rgt_data = tf.placeholder(dtype, in_shape, name="rgt_data")
tf.bitwise.right_shift(lft_data, rgt_data, name="RightShift")
compare_tf_with_tvm([lh_data, rh_data], [
'lft_data:0', 'rgt_data:0'], 'RightShift:0')
def test_forward_right_shift():
_test_forward_right_shift((7,), 'int32')
_test_forward_right_shift((3, 11), 'int16')
def _test_forward_left_shift(in_shape, dtype):
"""test operator LeftShift"""
lh_data = np.random.randint(100, 1000000, size=in_shape).astype(dtype)
rh_data = np.random.randint(1, 3, size=in_shape).astype(dtype)
tf.reset_default_graph()
with tf.Graph().as_default():
lft_data = tf.placeholder(dtype, in_shape, name="lft_data")
rgt_data = tf.placeholder(dtype, in_shape, name="rgt_data")
tf.bitwise.left_shift(lft_data, rgt_data, name="LeftShift")
compare_tf_with_tvm([lh_data, rh_data], [
'lft_data:0', 'rgt_data:0'], 'LeftShift:0')
def test_forward_left_shift():
_test_forward_left_shift((10,), 'int32')
_test_forward_left_shift((224, 224, 3), 'int16')
#######################################################################
# Mean
# ----
def test_forward_mean():
def check_mean(ishape, **kwargs):
inp_array = np.random.uniform(size=ishape).astype(np.float32)
with tf.Graph().as_default():
in1 = tf.placeholder(shape=inp_array.shape, dtype=inp_array.dtype)
tf.keras.backend.mean(in1, **kwargs)
compare_tf_with_tvm(inp_array, 'Placeholder:0',
'Mean:0', no_gpu=True)
check_mean((10, 8, 16, 32))
check_mean((10, 8, 16, 32), axis=(2, 3))
check_mean((10, 8, 16, 32), axis=(1, 2), keepdims=True)
#######################################################################
# Size
# ----
def test_forward_size():
def check_size(ishape):
np_input = np.random.uniform(size=ishape).astype(np.float32)
# if all dimensions are constant, TF will optimize away size operator into constant
tf_input_shape = list(np_input.shape)
tf_input_shape[0] = None
with tf.Graph().as_default():
input = tf.placeholder(shape=tf_input_shape,
dtype=np_input.dtype, name='input')
tf.size(input, name='size')
compare_tf_with_tvm([np_input], ['input:0'], 'size:0')
check_size((10, 8, 16, 32))
check_size((10,))
#######################################################################
# All, Any, Max, Min, Prod, variance, std, logsumexp, euclidean_norm
# ------------------------------------------------------------------
def test_forward_reduce():
def _check_op(tf_op, ishape, axis, keepdims, dtype="float32"):
tf.reset_default_graph()
if dtype == "bool":
np_data = np.random.choice([True, False], size=ishape)
else:
np_data = np.random.uniform(size=ishape).astype(dtype)
if tf_op == tf.math.reduce_prod:
axis = 1
np_data = np_data.reshape(1, -1)
with tf.Graph().as_default():
in_data = tf.placeholder(dtype, name="in_data")
reduce_op = tf_op(in_data, axis=axis,
keepdims=keepdims, name="reduce_std")
compare_tf_with_tvm([np_data], ['in_data:0'], reduce_op.name)
def _test_math_op(op, dtypes=["int32", "float32"]):
for dtype in dtypes:
_check_op(op, (3, 10), axis=(-1), keepdims=False, dtype=dtype)
_check_op(op, (8, 16, 32), axis=(-1), keepdims=False, dtype=dtype)
_check_op(op, (1, 8, 8, 3), axis=(2, 3), keepdims=True, dtype=dtype)
_check_op(op, (2, 3, 10, 10), axis=(1, 2), keepdims=True, dtype=dtype)
_test_math_op(tf.math.reduce_all, dtypes=["bool"])
_test_math_op(tf.math.reduce_any, dtypes=["bool"])
_test_math_op(tf.math.reduce_max)
_test_math_op(tf.math.reduce_min)
_test_math_op(tf.math.reduce_prod)
_test_math_op(tf.math.reduce_variance)
_test_math_op(tf.math.reduce_std, dtypes=["float32"])
_test_math_op(tf.math.reduce_logsumexp, dtypes=["float32"])
if package_version.parse(tf.VERSION) >= package_version.parse('1.15.0'):
_test_math_op(tf.math.reduce_euclidean_norm)
#######################################################################
# Relational operators
# --------------------
def _test_forward_rel_op(data, func):
with tf.Graph().as_default():
in1 = tf.placeholder(
shape=data[0].shape, dtype=data[0].dtype, name='in1')
in2 = tf.placeholder(
shape=data[1].shape, dtype=data[1].dtype, name='in2')
op = func(in1, in2, name='op')
out = tf.cast(op, tf.int32, name='out1')
compare_tf_with_tvm([data[0], data[1]], ['in1:0', 'in2:0'], 'out1:0')
def test_forward_rel_ops():
t1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
t2 = np.array([[9, 8, 7], [6, 5, 4], [3, 2, 1]])
_test_forward_rel_op([t1, t2], math_ops.less)
_test_forward_rel_op([t1, t2], math_ops.greater)
_test_forward_rel_op([t1, t2], math_ops.less_equal)
_test_forward_rel_op([t1, t2], math_ops.greater_equal)
_test_forward_rel_op([t1, t2], math_ops.equal)
_test_forward_rel_op([t1, t2], math_ops.not_equal)
#######################################################################
# ExpandDims
# ----------
def _test_forward_expand_dims(data, axis):
with tf.Graph().as_default():
in1 = tf.placeholder(shape=data.shape, dtype=data.dtype, name='in1')
out = tf.expand_dims(in1, axis)
compare_tf_with_tvm([data], [in1.name], out.name)
def test_forward_expand_dims():
_test_forward_expand_dims(np.int32(1), 0)
_test_forward_expand_dims(np.array([1]), 0)
_test_forward_expand_dims(np.array([1]), -1)
_test_forward_expand_dims(np.array([[1], [2]]), 0)
_test_forward_expand_dims(np.array([[1], [2]]), 1)
_test_forward_expand_dims(np.array([[1], [2]]), -1)
#######################################################################
# Maximum, Minimum
# ----------------
def test_forward_maximum():
"""test Op Maximum"""
def check_maximum(lh_shape, rh_shape, dtype):
tf.reset_default_graph()
lh_data = np.random.uniform(size=lh_shape).astype(dtype)
rh_data = np.random.uniform(size=rh_shape).astype(dtype)
with tf.Graph().as_default():
lft_data = tf.placeholder(dtype, name="lft_data")
rgt_data = tf.placeholder(dtype, name="rgt_data")
tf.math.maximum(lft_data, rgt_data, name="maximum")
compare_tf_with_tvm([lh_data, rh_data], [
'lft_data:0', 'rgt_data:0'], 'maximum:0')
check_maximum((10, 8, 16, 32), (1,), dtype="int32")
check_maximum((10, 8, 16, 32), (10, 8, 16, 32), dtype="float32")
def test_forward_minimum():
"""test Op Minimum"""
def check_minimum(lh_shape, rh_shape, dtype):
tf.reset_default_graph()
lh_data = np.random.uniform(size=lh_shape).astype(dtype)
rh_data = np.random.uniform(size=rh_shape).astype(dtype)
with tf.Graph().as_default():
lft_data = tf.placeholder(dtype, name="lft_data")
rgt_data = tf.placeholder(dtype, name="rgt_data")
tf.math.minimum(lft_data, rgt_data, name="minimum")
compare_tf_with_tvm([lh_data, rh_data], [
'lft_data:0', 'rgt_data:0'], 'minimum:0')
check_minimum((10, 8, 16, 32), (1,), dtype="int32")
check_minimum((10, 8, 16, 32), (10, 8, 16, 32), dtype="float32")
#######################################################################
# PlaceholderWithDefault
# ----------------------
def test_placeholder():
with tf.Graph().as_default():
in_data1 = np.random.uniform(-5, 5, size=(3, 4, 5)).astype(np.float32)
var1 = tf.Variable(in_data1, name='in1')
var2 = array_ops.placeholder_with_default(var1, None, name='place1')
in_data2 = np.random.uniform(-5, 5, size=(3, 4, 5)).astype(np.float32)
place1 = array_ops.placeholder(
shape=in_data1.shape, dtype=in_data1.dtype, name='in2')
out1 = tf.math.add(var1, var2, name='out1')
out2 = tf.math.add(out1, place1, name='out2')
compare_tf_with_tvm([in_data1, in_data2], ['place1:0', 'in2:0'], 'out2:0',
init_global_variables=True)
#######################################################################
# OneHot
# ----------------------
def _test_forward_one_hot(indices_shape, depth, on_value, off_value, axis, out_dtype):
inp_array1 = np.random.randint(0, 5, size=indices_shape)
with tf.Graph().as_default():
in1 = tf.placeholder(shape=inp_array1.shape, dtype=inp_array1.dtype)
out = tf.one_hot(in1, depth, on_value, off_value,
axis, dtype=out_dtype)
compare_tf_with_tvm(inp_array1, in1.name, out.name)
def test_forward_one_hot():
_test_forward_one_hot((3,), 3, 1, 0, -1, "int32")
_test_forward_one_hot((3,), 3, 1.0, 0.0, -1, "float32")
_test_forward_one_hot((2, 2), 5, 2, -2, 0, "int32")
_test_forward_one_hot((2, 2), 5, 0.5, -0.5, 1, "float32")
_test_forward_one_hot((3, 2, 4, 5), 6, 1, 0, 1, "int32")
_test_forward_one_hot((3, 2, 4, 5), 6, 1.0, 0.0, 0, "float32")
#######################################################################
# AddN
# ----------------------
def _test_forward_add_n(inputs):
tf.reset_default_graph()
with tf.Graph().as_default():
temp = []
for each in inputs:
temp.append(tf.placeholder(shape=each.shape, dtype=each.dtype))
output = tf.add_n(temp)
compare_tf_with_tvm([each for each in inputs], [
each.name for each in temp], output.name)
def test_forward_add_n():
x = np.random.randint(1, 100, size=(3, 3, 3), dtype=np.int32)
y = np.random.randint(1, 100, size=(3, 3, 3), dtype=np.int32)
z = np.random.randint(1, 100, size=(3, 3, 3), dtype=np.int32)
m, n, o = x.astype(np.float32), y.astype(np.float32), z.astype(np.float32)
in0 = x
in1 = [x, y]
in2 = (x, y, z)
in3 = m
in4 = [m, n]
in5 = (m, n, o)
_test_forward_add_n(in0)
_test_forward_add_n(in1)
_test_forward_add_n(in2)
_test_forward_add_n(in3)
_test_forward_add_n(in4)
_test_forward_add_n(in5)
#######################################################################
# Sharing params case
# ----------------------
def test_sharing_node():
"""Test the sharing params case."""
np_data = np.random.uniform(size=(2,2,2)).astype('float32')
with tf.Graph().as_default():
in_data = tf.placeholder(tf.float32, shape=(2, 2, 2), name='in_data')
axis = tf.constant([-1], dtype=tf.int32, name='axis')
mean0 = tf.reduce_mean(in_data, axis=axis, keepdims=False, name='mean0')
mean1 = tf.reduce_mean(in_data, axis=axis, keepdims=False, name='mean1')
out = tf.add(mean0, mean1, name='out')
compare_tf_with_tvm([np_data], ['in_data:0'], 'out:0')
#######################################################################
# Unravel Index
# ----------------------
def _test_forward_unravel_index(inputs):
tf.reset_default_graph()
with tf.Graph().as_default():
temp = []
for each in inputs:
temp.append(tf.placeholder(shape=each.shape, dtype=each.dtype))
output = tf.unravel_index(temp[0], temp[1])
compare_tf_with_tvm([each for each in inputs], [
each.name for each in temp], output.name)
def _test_forward_unravel_index_scalar(x, y, dtype="int32"):
tf.reset_default_graph()
with tf.Graph().as_default():
indices_1 = constant_op.constant(x, dtype=dtype)
dims_1 = constant_op.constant(y, dtype=dtype)
out_1 = array_ops.unravel_index(indices_1, dims_1)
compare_tf_with_tvm([], [], out_1.name)
def test_forward_unravel_index():
x = np.array([0, 1, 2, 3])
y = np.array([2, 2])
_test_forward_unravel_index([x, y])
x = np.array([0, 1, 2, 5])
y = np.array([2, 2])
_test_forward_unravel_index([x, y])
x = np.array([0, 1, 2, 5])
y = np.array([2])
_test_forward_unravel_index([x, y])
x = np.array([102, 300, 16])
y = np.array([10, 10, 9, 6])
_test_forward_unravel_index([x, y])
x = np.array([100])
y = np.array([10, 10, 9, 6])
_test_forward_unravel_index([x, y])
# Test scalar input
_test_forward_unravel_index_scalar(13, [1, 4, 5, 2])
#######################################################################
# Dilation2d
# ----------------------
def _test_dilation2d(tensor_in_sizes, filter_in_sizes,
strides, dilations, padding):
""" One iteration of dilation2d with given shapes and attributes """
total_size_1 = np.prod(tensor_in_sizes)
total_size_2 = np.prod(filter_in_sizes)
# Initializes the input tensor with array containing incrementing
# numbers from 1.
data_array = [f * 1.0 for f in range(1, total_size_1 + 1)]
filter_array = [f * 1.0 for f in range(1, total_size_2 + 1)]
with tf.Graph().as_default():
in_data = array_ops.placeholder(shape=tensor_in_sizes, dtype='float32')
in_filter = constant_op.constant(
filter_array, shape=filter_in_sizes, dtype='float32')
nn_ops.dilation2d(in_data,
in_filter,
strides=strides,
rates=dilations,
padding=padding)
compare_tf_with_tvm(np.reshape(data_array, tensor_in_sizes).astype('float32'),
'Placeholder:0', 'Dilation2D:0', no_gpu=True)
def test_forward_dilation():
_test_dilation2d([1, 18, 18, 32], [4, 4, 32], [1, 1, 1, 1], [1, 2, 1, 1], "VALID")
_test_dilation2d([1, 15, 15, 32], [4, 4, 32], [1, 1, 1, 1], [1, 2, 1, 1], "SAME")
_test_dilation2d([1, 5, 5, 1], [2, 2, 1], [1, 1, 1, 1], [1, 1, 1, 1], "VALID")
_test_dilation2d([1, 5, 5, 1], [3, 3, 1], [1, 1, 1, 1], [1, 2, 2, 1], "VALID")
_test_dilation2d([1, 5, 5, 3], [3, 3, 3], [1, 1, 1, 1], [1, 1, 1, 1], "SAME")
_test_dilation2d([1, 28, 28, 3], [5, 5, 3], [1, 2, 2, 1], [1, 1, 1, 1], "VALID")
_test_dilation2d([1, 224, 224, 10], [8, 8, 10], [1, 1, 1, 1], [1, 1, 1, 1], "VALID")
_test_dilation2d([1, 18, 18, 32], [4, 4, 32], [1, 1, 1, 1], [1, 2, 1, 1], "SAME")
_test_dilation2d([1, 15, 15, 32], [4, 4, 32], [1, 1, 1, 1], [1, 2, 1, 1], "VALID")
_test_dilation2d([1, 5, 5, 1], [7, 2, 1], [1, 3, 1, 1], [1, 1, 1, 1], "SAME")
_test_dilation2d([1, 5, 5, 1], [3, 4, 1], [1, 2, 1, 1], [1, 2, 2, 1], "SAME")
_test_dilation2d([1, 5, 5, 3], [3, 3, 3], [1, 1, 4, 1], [1, 1, 1, 1], "VALID")
_test_dilation2d([1, 28, 28, 3], [5, 6, 3], [1, 1, 2, 1], [1, 1, 1, 1], "SAME")
_test_dilation2d([1, 224, 224, 10], [8, 8, 10], [1, 3, 1, 1], [1, 1, 1, 1], "SAME")
_test_dilation2d([1, 3, 3, 1], [2, 2, 1], [1, 1, 1, 1], [1, 2, 2, 1], "SAME")
_test_dilation2d([1, 3, 3, 1], [2, 2, 1], [1, 1, 1, 1], [1, 1, 2, 1], "VALID")
#######################################################################
# infinity ops
# ------------
def _verify_infiniteness_ops(tf_op, name):
"""test operator infinity ops"""
# Only float types are allowed in Tensorflow for isfinite and isinf
# float16 is failing on cuda
tf_dtypes = ["float32", "float64"]
for tf_dtype in tf_dtypes:
shape = (8, 8)
data = np.random.uniform(size=shape).astype(tf_dtype)
data.ravel()[np.random.choice(data.size, int(data.size * 0.5), replace=False)] = np.infty
data.ravel()[np.random.choice(data.size, int(data.size * 0.5), replace=False)] = np.nan
tf.reset_default_graph()
in_data = tf.placeholder(tf_dtype, shape, name="in_data")
tf_op(in_data, name=name)
compare_tf_with_tvm([data], ['in_data:0'], '{}:0'.format(name))
def test_forward_isinf():
_verify_infiniteness_ops(tf.is_inf, "isinf")
def test_forward_isfinite():
_verify_infiniteness_ops(tf.is_finite, "isfinite")
#######################################################################
# Main
# ----
if __name__ == '__main__':
# Transforms
test_forward_slice()
test_forward_transpose()
test_forward_reshape()
test_forward_depthtospace()
test_forward_spacetodepth()
test_forward_squeeze()
test_forward_pack()
test_forward_size()
test_forward_broadcast_to()
test_forward_fill()
test_forward_crop()
test_forward_resize()
test_forward_crop_and_resize()
test_forward_pad()
test_forward_unpack()
test_forward_gather()
test_forward_gather_nd()
test_forward_stridedslice()
test_forward_split()
test_forward_unstack()
test_forward_tile()
test_forward_top_k_v2()
test_forward_clip_by_value()
test_forward_maximum()
test_forward_minimum()
test_forward_range()
test_forward_right_shift()
test_forward_left_shift()
test_forward_truncatemod()
test_forward_one_hot()
test_forward_atan()
test_forward_atan2()
# Activations
test_forward_sigmoid()
test_forward_relu()
test_forward_leaky_relu()
test_forward_elu()
test_forward_selu()
test_forward_tanh()
# Tensor
test_forward_round()
test_forward_reverse_v2()
test_forward_pow_exp()
test_forward_sign()
test_forward_log()
test_forward_log1p()
test_forward_tan()
test_forward_cos()
test_forward_sin()
test_forward_negative()
test_forward_divide()
test_forward_abs()
test_forward_softplus()
test_forward_sqrt()
test_forward_rsqrt()
test_forward_expand_dims()
test_forward_square()
test_forward_softmax()
test_forward_log_softmax()
test_forward_bias_add()
test_forward_zeros_like()
test_forward_erf()
test_forward_squared_difference()
test_forward_add_n()
test_forward_floormod()
test_forward_isfinite()
test_forward_isinf()
test_forward_unravel_index()
# Reductions
test_forward_argminmax()
test_forward_reduce()
test_forward_mean()
# General
test_forward_multi_input()
test_forward_multi_output()
test_forward_variable()
test_placeholder()
# NN
test_forward_convolution()
test_forward_pooling()
test_forward_concat_v2()
test_forward_lrn()
test_forward_l2_normalize()
test_forward_space_to_batch_nd()
test_forward_batch_to_space_nd()
test_forward_dilation()
# End to End
test_forward_inception_v3()
test_forward_inception_v1()
test_forward_mobilenet()
test_forward_resnetv2()
test_forward_placeholder()
test_forward_ptb()
# RNN
if package_version.parse(tf.VERSION) < package_version.parse('2.0.0'):
#in 2.0, tf.contrib.rnn.LSTMBlockCell is removed
test_forward_lstm()
# Elementwise
test_forward_ceil()
test_forward_floor()
# Relational ops
test_forward_rel_ops()
test_forward_logical()
test_forward_where()
test_forward_matmul()
test_forward_batch_matmul()
# Internal misc. ops
test_read_variable_op()
# Sharing params case using Mean ops
test_sharing_node()
test_forward_cumsum()
|
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'form.ui'
#
# Created by: PyQt5 UI code generator 5.15.2
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.setFixedSize(640, 480)
# initiate input validator to be only Integer
self.onlyInt = QtGui.QIntValidator(18, 99)
self.lineEdit = QtWidgets.QLineEdit(Form)
# set max length 0f input
self.lineEdit.setMaxLength(2)
self.lineEdit.setValidator(self.onlyInt)
self.lineEdit.setGeometry(QtCore.QRect(150, 60, 113, 22))
self.lineEdit.setObjectName("lineEdit")
self.comboBox = QtWidgets.QComboBox(Form)
self.comboBox.setGeometry(QtCore.QRect(150, 180, 91, 21))
self.comboBox.setObjectName("comboBox")
self.comboBox.addItem("")
self.comboBox.addItem("")
self.comboBox.addItem("")
self.comboBox.addItem("")
self.comboBox.addItem("")
self.comboBox.addItem("")
self.comboBox.addItem("")
self.comboBox.addItem("")
self.label = QtWidgets.QLabel(Form)
self.label.setGeometry(QtCore.QRect(40, 60, 91, 20))
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(Form)
self.label_2.setGeometry(QtCore.QRect(40, 120, 55, 20))
self.label_2.setObjectName("label_2")
self.label_3 = QtWidgets.QLabel(Form)
self.label_3.setGeometry(QtCore.QRect(40, 180, 101, 20))
self.label_3.setObjectName("label_3")
self.label_4 = QtWidgets.QLabel(Form)
self.label_4.setGeometry(QtCore.QRect(40, 82, 140, 20))
self.label_4.setFont(QtGui.QFont("Arial font", 6))
self.label_4.setObjectName("label_4")
self.pushButton = QtWidgets.QPushButton(Form)
self.pushButton.setGeometry(QtCore.QRect(40, 280, 93, 28))
self.pushButton.setObjectName("pushButton")
self.comboBox_2 = QtWidgets.QComboBox(Form)
self.comboBox_2.setGeometry(QtCore.QRect(150, 120, 91, 21))
self.comboBox_2.setObjectName("comboBox_2")
self.comboBox_2.addItem("")
self.comboBox_2.addItem("")
self.comboBox_2.addItem("")
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Experiment"))
Form.setStyleSheet("background-color: #4E75CF")
self.lineEdit.setStyleSheet("background-color: #8C9FC9")
self.lineEdit.setStyleSheet("border: 1px solid black;")
self.comboBox.setItemText(0, _translate("Form", "1_level"))
self.comboBox.setItemText(1, _translate("Form", "2_level"))
self.comboBox.setItemText(2, _translate("Form", "3_level"))
self.comboBox.setItemText(3, _translate("Form", "4_level"))
self.comboBox.setItemText(4, _translate("Form", "5_level"))
self.comboBox.setItemText(5, _translate("Form", "6_level"))
self.comboBox.setItemText(6, _translate("Form", "7_level"))
self.comboBox.setItemText(7, _translate("Form", "8_level"))
self.comboBox.setStyleSheet("background-color: #6997D3")
self.label.setText(_translate("Form", " Age:"))
self.label.setStyleSheet("background-color: #8C9FC9")
self.label_2.setText(_translate("Form", " Gender"))
self.label_2.setStyleSheet("background-color: #8C9FC9")
self.label_3.setText(_translate("Form", " Education level"))
self.label_3.setStyleSheet("background-color: #8C9FC9")
self.label_4.setText(_translate("Form", "(you must be over 17)"))
self.pushButton.setText(_translate("Form", "Confirm"))
self.pushButton.setStyleSheet("background-color: #6997D3")
self.comboBox_2.setItemText(0, _translate("Form", "Male"))
self.comboBox_2.setItemText(1, _translate("Form", "Female"))
self.comboBox_2.setItemText(2, _translate("Form", "Other"))
self.comboBox_2.setStyleSheet("background-color: #6997D3")
|
const TgRequestContact = require("./TgRequestContact");
const TgSendAnimation = require("./TgSendAnimation");
const TgSendAudio = require("./TgSendAudio");
const TgSendDocument = require("./TgSendDocument");
const TgSendPhoto = require("./TgSendPhoto");
const TgSendText = require("./TgSendText");
const TgSendVideo = require("./TgSendVideo");
const SendSMS = require("./SendSMS");
const WaSendText = require("./WaSendText");
const WaSendAudio = require("./WaSendAudio");
const WaSendDocument = require("./WaSendDocument");
const WaSendPhoto = require("./WaSendPhoto");
const WaSendSticker = require("./WaSendSticker");
const WaSendVideo = require("./WaSendVideo");
const WaSendContact = require("./WaSendContact");
const WaSendLocation = require("./WaSendLocation");
const WaSendTemplate = require("./WaSendTemplate");
module.exports = {
TgRequestContact,
TgSendAnimation,
TgSendAudio,
TgSendDocument,
TgSendPhoto,
TgSendText,
TgSendVideo,
SendSMS,
WaSendText,
WaSendAudio,
WaSendDocument,
WaSendPhoto,
WaSendSticker,
WaSendVideo,
WaSendContact,
WaSendLocation,
WaSendTemplate
};
|
from typing import Tuple
import torch
import torch.distributed as dist
from torch import Tensor
from .core import (get_tensor_model_parallel_group, get_tensor_model_parallel_src_rank,
get_tensor_model_parallel_world_size)
from .core import ensure_divisibility
def divide(numerator, denominator):
ensure_divisibility(numerator, denominator)
return numerator // denominator
def _reduce(tensor: Tensor) -> Tensor:
if get_tensor_model_parallel_world_size() == 1:
return tensor
dist.all_reduce(tensor,
op=dist.ReduceOp.SUM,
group=get_tensor_model_parallel_group(),
async_op=False)
return tensor
def _split(tensor: Tensor, dim: int = -1) -> Tensor:
if get_tensor_model_parallel_world_size() == 1:
return tensor
split_size = divide(tensor.shape[dim], get_tensor_model_parallel_world_size())
tensor_list = torch.split(tensor, split_size, dim=dim)
output = tensor_list[get_tensor_model_parallel_src_rank()].contiguous()
return output
def _gather(tensor: Tensor, dim: int = -1) -> Tensor:
if get_tensor_model_parallel_world_size() == 1:
return tensor
if dim == 1:
output_shape = list(tensor.shape)
output_shape[1] *= get_tensor_model_parallel_world_size()
output = torch.empty(output_shape, dtype=tensor.dtype, device=tensor.device)
tensor_list = output.chunk(get_tensor_model_parallel_world_size(), dim=1)
dist.all_gather(list(tensor_list), tensor, group=get_tensor_model_parallel_group(), async_op=False)
else:
tensor_list = [torch.ones_like(tensor) for _ in range(get_tensor_model_parallel_world_size())]
dist.all_gather(tensor_list, tensor, group=get_tensor_model_parallel_group(), async_op=False)
output = torch.cat(tensor_list, dim=dim)
return output
def copy(input: Tensor) -> Tensor:
if torch.is_grad_enabled() and input.requires_grad:
input = Copy.apply(input)
return input
class Copy(torch.autograd.Function):
@staticmethod
def forward(ctx: "Copy", input: Tensor) -> Tensor:
return input
@staticmethod
def backward(ctx: "Copy", grad_output: Tensor) -> Tensor:
return _reduce(grad_output)
def scatter(input: Tensor, dim: int = -1) -> Tensor:
if torch.is_grad_enabled() and input.requires_grad:
input = Scatter.apply(input, dim)
else:
input = _split(input, dim=dim)
return input
class Scatter(torch.autograd.Function):
@staticmethod
def forward(ctx: "Scatter", input: Tensor, dim: int = -1) -> Tensor:
ctx.save_for_backward(torch.tensor([dim]))
return _split(input, dim=dim)
@staticmethod
def backward(ctx: "Scatter", grad_output: Tensor) -> Tuple[Tensor]:
dim, = ctx.saved_tensors
return _gather(grad_output, dim=int(dim)), None
def reduce(input: Tensor) -> Tensor:
if torch.is_grad_enabled() and input.requires_grad:
input = Reduce.apply(input)
else:
input = _reduce(input)
return input
class Reduce(torch.autograd.Function):
@staticmethod
def forward(ctx: "Reduce", input: Tensor) -> Tensor:
return _reduce(input)
@staticmethod
def backward(ctx: "Reduce", grad_output: Tensor) -> Tensor:
return grad_output
def gather(input: Tensor, dim: int = -1) -> Tensor:
if torch.is_grad_enabled() and input.requires_grad:
input = Gather.apply(input, dim)
else:
input = _gather(input, dim=dim)
return input
class Gather(torch.autograd.Function):
@staticmethod
def forward(ctx: "Gather", input: Tensor, dim: int = -1) -> Tensor:
ctx.save_for_backward(torch.tensor([dim]))
return _gather(input, dim=dim)
@staticmethod
def backward(ctx: "Gather", grad_output: Tensor) -> Tuple[Tensor]:
dim, = ctx.saved_tensors
return _split(grad_output, dim=int(dim)), None
def _all_to_all(tensor: Tensor, in_dim: int = -1, out_dim: int = -1) -> Tensor:
if get_tensor_model_parallel_world_size() == 1:
return tensor
split_size = divide(tensor.shape[in_dim], get_tensor_model_parallel_world_size())
input_tensor_list = torch.split(tensor, split_size, dim=in_dim)
input_tensor_list = [tensor_.contiguous() for tensor_ in input_tensor_list]
if out_dim == 1:
output_shape = list(input_tensor_list[0].shape)
output_shape[1] *= get_tensor_model_parallel_world_size()
output = torch.empty(output_shape, dtype=tensor.dtype, device=tensor.device)
output_tensor_list = output.chunk(get_tensor_model_parallel_world_size(), dim=1)
dist.all_to_all(list(output_tensor_list),
input_tensor_list,
group=get_tensor_model_parallel_group(),
async_op=False)
else:
output_tensor_list = [torch.ones_like(tensor_) for tensor_ in input_tensor_list]
dist.all_to_all(output_tensor_list,
input_tensor_list,
group=get_tensor_model_parallel_group(),
async_op=False)
output = torch.cat(output_tensor_list, dim=out_dim)
return output
def col_to_row(input_: Tensor) -> Tensor:
if torch.is_grad_enabled() and input_.requires_grad:
input_ = All_to_All.apply(input_, 1, 2)
else:
input_ = _all_to_all(input_, in_dim=1, out_dim=2)
return input_
def row_to_col(input_: Tensor) -> Tensor:
if torch.is_grad_enabled() and input_.requires_grad:
input_ = All_to_All.apply(input_, 2, 1)
else:
input_ = _all_to_all(input_, in_dim=2, out_dim=1)
return input_
class All_to_All(torch.autograd.Function):
@staticmethod
def forward(ctx: "All_to_All", input_: Tensor, in_dim: int = -1, out_dim: int = -1) -> Tensor:
ctx.save_for_backward(torch.tensor([in_dim, out_dim]))
return _all_to_all(input_, in_dim=in_dim, out_dim=out_dim)
@staticmethod
def backward(ctx: "All_to_All", grad_output: Tensor) -> Tuple[Tensor]:
saved_tensors = ctx.saved_tensors[0]
return _all_to_all(grad_output, in_dim=int(saved_tensors[1]),
out_dim=int(saved_tensors[0])), None, None
|
import os
import flask
from flask_cors import CORS
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import Flow
from googleapiclient.discovery import build
from controllers import Connections, Profile
from conversors import (
parse_userinfo_data,
parse_connections_data,
credentials_to_dict
)
app = flask.Flask(__name__)
app.secret_key = os.environ.get("SECRET_KEY") or os.urandom(24)
cors = CORS(app, resources={r"/*": {"origins": "*"}})
# Configurações
SCOPES = [
"openid",
"https://www.googleapis.com/auth/userinfo.profile",
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/contacts"
]
SECRETS_FILE = 'credentials.json'
if not os.path.exists(SECRETS_FILE):
print(f'Error: Secrets file "{SECRETS_FILE}" not exists!')
exit(1)
DEFAULT_LOGOUT_SUCCESS_RESPONSE = {
'logged': False,
'message': 'Logged out successfully'
}
DEFAULT_LOGIN_SUCCESS_RESPONSE = {
'logged': True,
'message': 'Logged in successfully. Get data requesting /connections'
}
DEFAULT_UNLOGGED_RESPONSE = {
'logged': False,
'message': 'No Google account logged. Try to request /login'
}
# Muda o inicio de uma string pra 'https://' se ela começar com 'http://'
def force_https(url: str) -> str:
if url.startswith('http://'):
new_url = url.replace('http://', 'https://', 1)
print(f'HTTP changed to HTTPS: {url[:16]}... -> {new_url[:16]}...')
return new_url
return url
# Caso tenha uma conta Google logada no app, retorna as informações básicas do
# usuário logado somadas aos dados de contatos de email agrupados pelo domínio
# do endereço de email.
# Caso não haja login, retorna uma mensagem sugerindo acessar a rota /login.
@app.route("/connections")
def connections():
if 'credentials' not in flask.session:
return flask.jsonify(DEFAULT_UNLOGGED_RESPONSE)
credentials = Credentials(**flask.session['credentials'])
# Busca as informações básicas do usuário logado
userinfo = Profile.get_userinfo(credentials)
# Busca as informações de contatos de email agrupados por domínio do email
connections = Connections.list_contacts_by_domain(credentials)
return flask.jsonify({'logged': True, **connections, **userinfo})
# Inicia o fluxo de login usando a biblioteca de cliente oAuth2 do Google
@app.route("/login")
def login():
# Usa as credenciais do arquivo local 'credentials.json'
flow = Flow.from_client_secrets_file(SECRETS_FILE, scopes=SCOPES)
redirect_url = flask.request.base_url + "/callback"
# Se a URL de redirecionamento usar http, muda para https
redirect_url = force_https(redirect_url)
flow.redirect_uri = redirect_url
authorization_url, state = flow.authorization_url(
access_type='offline',
include_granted_scope='true'
)
#print(state)
flask.session['state'] = state
return flask.redirect(authorization_url)
# Recebe a resposta do servidor de autorização do Google e armazena as
# credenciais em uma sessão do app Flask
@app.route("/login/callback")
def callback():
state = flask.session['state']
flow = Flow.from_client_secrets_file(
SECRETS_FILE, scopes=SCOPES, state=state)
flow.redirect_uri = flask.url_for('callback', _external=True)
# Se a URL de redirecionamento usar http, muda para https
flow.redirect_uri = force_https(flow.redirect_uri)
authorization_response = flask.request.url
authorization_response = force_https(authorization_response)
flow.fetch_token(authorization_response=authorization_response)
# Armazena as informações de credenciais da sessão atual do usuário
credentials = flow.credentials
flask.session['credentials'] = credentials_to_dict(credentials)
# Redireciona o usuario para a homepage
return flask.jsonify(DEFAULT_LOGIN_SUCCESS_RESPONSE)
# return flask.redirect(flask.url_for('connections'))
@app.route("/logout")
def logout():
if 'credentials' in flask.session:
flask.session.pop('credentials', None)
return flask.jsonify(DEFAULT_LOGOUT_SUCCESS_RESPONSE)
if __name__ == "__main__":
# Permite usar HTTP inseguro para oAuth2
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = "1"
# Define o Host e Porta para rodar a aplicação
app.run('127.0.0.1', ssl_context='adhoc', debug=True)
|
#!/usr/bin/env jspm
import { dew } from './d.dew.js';
export default dew();
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'Daniel'
import tensorflow as tf
import numpy as np
# create data
x_data = np.random.rand(100).astype(np.float32)
y_data = x_data * 0.1 + 0.3
### create tensorflow structure start ###
# Weights = tf.Variable(tf.random_uniform_initializer([1], -1.0, 1.0))
# biases = tf.Variable(tf.zeros([1]))
# y = x_data * Weights + biases
# loss = tf.reduce_mean(tf.square(y-y_data))
# optimizer = tf.train.GradientDescentOptimizer(0.5)
# train = optimizer.minimize(loss)
# init = tf.initializers_all_variables()
### create tensorflow structure end ###
# sess = tf.Session()
# sess.run(init)
# for step in range(201):
# sess.run(train)
# if step%20 == 0:
# print(step, sess.run(Weights), sess.run(biases))
|
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from conf.settings import ConfigMap
# 创建数据库db
db = SQLAlchemy()
def create_app(config):
'''
工厂模式创建app
@config: 'develop': 开发环境, 'product': 生产环境, 'test': 测试环境
'''
app = Flask(__name__)
# 加载配置文件
app.config.from_object(ConfigMap[config])
# 初始化db
db.init_app(app=app)
from middleware.auth import custom_after_request
# 全局响应处理(优先api)
app.after_request(custom_after_request)
# 处理api
from apps.api import api_blueprint
app.register_blueprint(api_blueprint, url_prefix="/api/v1")
return app
|
import tkinter
root = tkinter.Tk()
#視窗名稱
root.title('109-NKUST Information Technology Club')
#視窗大小
root.geometry('480x360')
# text:要顯示的文字
# bg:背景顏色
# font:自型設定
# width, height:寬, 高
lable = tkinter.Label(root, text='12/17有活動', bg='white',
font=('Arial', 12), width=30, height=2)
lable.place(relx=0.5, rely=0.5, anchor='center')
root.mainloop()
|
let { updater } = require('@architect/utils')
let update = updater('Logs')
module.exports = function validate (/* opts*/) {
try {
if (process.env.ARC_AWS_CREDS === 'missing')
throw Error('missing or invalid AWS credentials or credentials file')
if (!process.env.AWS_REGION)
throw Error('@aws region / AWS_REGION must be configured')
}
catch (e) {
update.error(`Failed to access logs, ${e.message}`)
process.exit(1)
}
}
|
var path = require('path');
var sessionUtils = require(path.resolve(__dirname,'../business_logic/session'));
var uuid = require('node-uuid');
var async = require('async');
var exceptions = require(path.resolve(__dirname,'../utils/exceptions'));
var ObjectId = require('mongodb').ObjectID;
var dalDb = require(path.resolve(__dirname,'../dal/dalDb'));
var dalFacebook = require(path.resolve(__dirname,'../dal/dalFacebook'));
var generalUtils = require(path.resolve(__dirname,'../utils/general'));
var google = require('googleapis');
var Androidpublisher = google.androidpublisher('v2');
var jwtClient;
var PaypalObject = require('paypal-express-checkout').Paypal;
var paypal;
var paypalSettings;
PaypalObject.prototype.origParams = PaypalObject.prototype.params;
PaypalObject.prototype.params = function () {
var myParams = paypal.origParams();
myParams.SOLUTIONTYPE = 'Sole';
myParams.LANDINGPAGE = 'Billing';
myParams.VERSION = '124';
return myParams;
};
//----------------------------------------------------
// private Functions
//----------------------------------------------------
//----------------------------------------------------
// prepareClientResponse
//----------------------------------------------------
function prepareClientResponse(data) {
data.clientResponse = {};
data.clientResponse.features = data.session.features;
data.clientResponse.featurePurchased = data.featurePurchased;
data.clientResponse.nextView = generalUtils.settings.server.features[data.featurePurchased].view;
}
//---------------------------------------------------------
// analyzePaypalStatus
//
// Play with 'switches' according to the payment status
//---------------------------------------------------------
function analyzePaypalStatus(data) {
switch (data.newPurchase.status) {
//------------------------------------------------------------------------------------------------------
//-- Proceed with the payment and give the asset if it does not exist
//------------------------------------------------------------------------------------------------------
case 'Completed': //The payment has been completed, and the funds have been added successfully to your account balance.
case 'Canceled_Reversal': //A reversal has been canceled; for example, when you win a dispute and the funds for the reversal have been returned to you.
case 'Completed-Funds-Held': //The payment has been completed, and the funds have been added successfully to your pending balance.
case 'Completed_Funds_Held': //The payment has been completed, and the funds have been added successfully to your pending balance.
//See the PAYMENTINFO_n_HOLDDECISION field for more information.
data.proceedPayment = true;
break;
//------------------------------------------------------------------------------------------------------
//-- Temporary state, just write the transaction, notify client on pending - if coming from client
//------------------------------------------------------------------------------------------------------
case 'Pending': //The payment is pending. See the PendingReason field for more information.
case 'In-Progress': //The transaction has not terminated, e.g. an authorization may be awaiting completion.
data.serverErrorType = 'SERVER_ERROR_PURCHASE_IN_PROGRESS';
break;
//------------------------------------------------------------------------------------------------------
//-- Revoke the asset
//------------------------------------------------------------------------------------------------------
case 'Partially_Refunded': //The payment has been partially refunded.
case 'Refunded': //You refunded the payment.
case 'Reversed': //A payment was reversed due to a chargeback or other type of reversal. The funds have been removed from your account balance and returned to the buyer. The reason for the reversal is specified in the ReasonCode element.
data.revokeAsset = true;
data.itemCharged = true;
break;
//------------------------------------------------------------------------------------------------------
//-- Terminal state - purchase failed, money has not been recieved - just log the transaction
//------------------------------------------------------------------------------------------------------
case 'Denied': //You denied the payment. This happens only if the payment was previously pending because of possible reasons described for the PendingReason element.
case 'Expired': //the authorization period for this payment has been reached.
case 'None': //No status.
case 'Failed': //The payment has failed. This happens only if the payment was made from your buyer's bank account.
case 'Voided': //An authorization for this transaction has been voided.
data.serverErrorType = 'SERVER_ERROR_PURCHASE_FAILED';
break;
//------------------------------------------------------------------------------------------------------
//-- Just log the transaction
//------------------------------------------------------------------------------------------------------
case 'Processed': //A payment has been accepted.
break;
//------------------------------------------------------------------------------------------------------
//-- Just log the transaction
//------------------------------------------------------------------------------------------------------
default:
break;
}
}
//----------------------------------------------------
// payPalBuy
//
// data:
// input: feature, language
// output: url to surf to
//----------------------------------------------------
module.exports.payPalBuy = function (req, res, next) {
if (!paypal) {
paypalSettings = generalUtils.settings.server.payments.paypal;
//returnUrl, cancelUrl will be set just before each buy
paypal = require('paypal-express-checkout').init(paypalSettings.user, paypalSettings.password, paypalSettings.signature, '', '', paypalSettings.debug);
}
var token = req.headers.authorization;
var data = req.body;
if (!data.language) {
exceptions.ServerResponseException(res, 'Language not received during payPal buy', null, 'warn', 424);
return;
}
var operations = [
//getSession
function (callback) {
data.token = token;
sessionUtils.getSession(data, callback);
},
//Validate the payment transaction based on method
function (data, callback) {
//Invoice number will contain the product id which will be required later for validation
var invoiceNumber = uuid.v1() + '_' + data.session.userId + '_' + data.feature;
var feature = generalUtils.settings.server.features[data.feature];
if (!feature) {
exceptions.ServerResponseException(res, 'Invalid feature received during payPal buy', {'feature': data.feature}, 'warn', 424);
return;
}
var purchaseProduct = generalUtils.settings.server.payments.purchaseProducts[feature.purchaseProductId];
var purchaseProductDisplayName = purchaseProduct.displayNames[data.language];
if (!purchaseProductDisplayName) {
exceptions.ServerResponseException(res, 'Unable to find product display name during payPal buy', {'data': data}, 'warn', 424);
return;
}
var urlPrefix;
if (req.connection.encrypted) {
urlPrefix = generalUtils.settings.client.general.baseUrlSecured;
}
else {
urlPrefix = generalUtils.settings.client.general.baseUrl;
}
paypal.returnUrl = urlPrefix + paypalSettings.successUrl;
paypal.cancelUrl = urlPrefix + paypalSettings.cancelUrl;
paypal.pay(invoiceNumber,
purchaseProduct.cost,
purchaseProductDisplayName, 'USD', function (err, url) {
if (err) {
dalDb.closeDb(data);
exceptions.ServerResponseException(res, err, null, 'warn', 424);
return;
}
data.response = {'url': url};
dalDb.closeDb(data);
callback(null, data);
});
}
];
async.waterfall(operations, function (err, data) {
if (!err) {
res.json(data.response);
}
else {
res.send(err.httpStatus, err);
}
})
};
//-----------------------------------------------------------------------------------------------
// processPayment
//
// data: method (paypal, google, ios, facebook)
//
// For paypal -
// purchaseData.purchaseToken,
// purchaseData.payerId
// For facebook - 2 cases:
// - When coming from client:
// purchaseData.payment_id,
// purchaseData.amount,
// purchaseData.currency,
// purchaseData.quantity,
// purchaseData.request_id,
// purchaseData.status,
// purchaseData.signed_request
//
// - When coming from facebook server callback:
// entry[0].id is the payment id,
// entry[0].changed_fields are the fields changed that raised the call
//-----------------------------------------------------------------------------------------------
module.exports.processPayment = function (req, res, next) {
var token = req.headers.authorization;
var data = req.body;
data.token = token;
if (data.method === 'facebook') {
//For facebook payments
data.paymentId = data.purchaseData.payment_id;
}
innerProcessPayment(data, function (err, data) {
if (!err) {
res.json(data.clientResponse);
}
else if (err.httpStatus) {
res.send(err.httpStatus, err);
}
else {
if (err.message === 'DuplicatePurchase') {
//This is an intentional stop - data contains client response
//A duplicate purchase which has completed successfully by another thread
//The 'additionalInfo' of the err object is the data
res.json(err.additionalInfo.clientResponse)
}
else {
res.send(err.httpStatus, err);
}
}
});
}
//-----------------------------------------------------------------------------------------------
// innerProcessPayment
//
// like processPayment - but can also be called from Paypal IPN or facebook payments callback
// In this case - can be offline - and session is not required
//-----------------------------------------------------------------------------------------------
module.exports.innerProcessPayment = innerProcessPayment;
function innerProcessPayment(data, callback) {
var now = (new Date()).getTime();
var operations = [
function (callback) {
data.newPurchase = {'method': data.method};
switch (data.method) {
case 'paypal':
if (!data.thirdPartyServerCall) {
//comming from client
paypal.detail(data.purchaseData.purchaseToken, data.purchaseData.payerId, function (err, paypalData, invoiceNumber, amount) {
if (err) {
callback(new exceptions.ServerException('Error during DoExpressCheckoutPayment', {
'error': err,
'purchaseData': data.purchaseData
}, 'error', 403));
}
data.paymentData = paypalData;
data.newPurchase.transactionId = paypalData.PAYMENTINFO_0_TRANSACTIONID;
data.newPurchase.status = paypalData.PAYMENTINFO_0_PAYMENTSTATUS;
data.newPurchase.amount = paypalData.PAYMENTINFO_0_AMT;
data.newPurchase.currency = paypalData.PAYMENTINFO_0_CURRENCYCODE
data.newPurchase.extraData = data.paymentData;
//invoiceNumber is in the format InvoiceNumner_userId_featureName
data.featurePurchased = invoiceNumber.split('_')[2];
analyzePaypalStatus(data);
dalDb.insertPurchase(data, callback);
})
}
else {
//Server call
data.newPurchase.transactionId = data.paymentData.txn_id;
data.newPurchase.status = data.paymentData.payment_status;
data.newPurchase.amount = data.paymentData.mc_gross;
data.newPurchase.currency = data.paymentData.mc_currency;
data.newPurchase.extraData = data.paymentData;
analyzePaypalStatus(data);
var invoiceNumberParts = data.paymentData.invoice.split('_');
data.userId = invoiceNumberParts[1];
data.featurePurchased = invoiceNumberParts[2];
dalDb.insertPurchase(data, callback);
}
break;
case 'facebook':
dalFacebook.getPaymentInfo(data, function () {
data.newPurchase.transactionId = data.paymentData.id;
data.newPurchase.status = data.paymentData.status;
data.newPurchase.amount = data.paymentData.actions[0].amount;
data.newPurchase.currency = data.paymentData.actions[0].currency;
data.newPurchase.extraData = data.paymentData;
dalDb.insertPurchase(data, callback);
});
break;
case 'android':
if (!jwtClient) {
jwtClient = new google.auth.JWT(generalUtils.settings.server.google.api.auth.email, null, generalUtils.settings.server.google.api.auth.privateKey, generalUtils.settings.server.google.api.auth.scopes, null);
}
jwtClient.authorize(function(err, tokens) {
if (err) {
callback(new exceptions.ServerException('Unable to authorize to google with jwt', {'purchaseData': data.purchaseData, 'googleError' : err},'error'));
return;
}
var params = {
auth : jwtClient,
packageName: data.purchaseData.packageName,
productId: data.purchaseData.productId,
token: data.purchaseData.purchaseToken
};
Androidpublisher.purchases.products.get(params, function(purchaseError, purchaseResponse) {
// handle err and response
if (err) {
callback(new exceptions.ServerException('Unable to verify google purchase', {'purchaseData': data.purchaseData, 'googleError' : purchaseError},'error'));
return;
}
if (purchaseResponse.consumptionState !== 0) {
callback(new exceptions.ServerException('This purchase has already been consumed', {'purchaseData': data.purchaseData, 'purchaseResponse' : purchaseResponse},'error'));
return;
}
data.newPurchase.transactionId = data.purchaseData.orderId;
data.newPurchase.amount = data.extraPurchaseData.actualCost;
data.newPurchase.currency = data.extraPurchaseData.actualCurrency;
data.newPurchase.extraData = data.purchaseData;
data.featurePurchased = data.extraPurchaseData.featurePurchased;
data.paymentData = data.purchaseData;
switch (purchaseResponse.purchaseState) {
case 0: //completed
data.newPurchase.status = 'completed';
data.proceedPayment = true;
break;
case 1: //canceled
data.newPurchase.status = 'canceled';
data.revokeAsset = true;
break;
case 2: //refunded
data.newPurchase.status = 'refunded';
data.proceedPayment = true;
break;
}
dalDb.insertPurchase(data, callback);
});
});
break;
}
},
//getSession
function (data, callback) {
sessionUtils.getSession(data, callback);
},
//check for duplicate purchase (client and server occur at the same time or hacking)
function (data, callback) {
if (data.duplicatePurchase) {
dalDb.closeDb(data);
if (!data.thirdPartyServerCall) {
prepareClientResponse(data);
}
callback(new exceptions.InternalServerException('DuplicatePurchase', data));
}
else {
callback(null, data);
}
},
//Validate the payment transaction based on method
function (data, callback) {
switch (data.method) {
case 'paypal':
case 'android':
callback(null, data);
break;
case 'facebook':
//Double check - if client tries to hack without a signed request
//Make sure the purchase belongs to him
if (data.session && data.purchaseData && !data.purchaseData.signed_request && data.paymentData.user && data.paymentData.user.id !== data.session.facebookUserId) {
callback(new exceptions.ServerException('Error validating payment, payment belongs to someone else', {
'purchaseData': data.purchaseData,
'paymentData': data.paymentData,
'actualFacebookId': data.session.facebookUserId
},'error'));
return;
}
callback(null, data);
break;
default:
callback(new exceptions.ServerException('Method not supported for payment validation', {'method': data.method},'error', 403));
return;
}
},
//Store the asset at the session's level
function (data, callback) {
if ((data.proceedPayment || data.revokeAsset || (data.dispute && data.itemCharged)) &&
data.session) {
if (data.revokeAsset) {
//Revoke the asset if it has been bought within the same purchase method
if (data.session.assets && data.session.assets[data.featurePurchased] && data.session.assets[data.featurePurchased].method === data.method) {
delete data.session.assets[data.featurePurchased];
}
}
else {
//Give the asset
if (!data.session.assets) {
data.session.assets = {};
}
data.session.assets[data.featurePurchased] = {'purchaseDate': now, 'method': data.method};
data.session.features = sessionUtils.computeFeatures(data.session);
}
if (!data.thirdPartyServerCall) {
prepareClientResponse(data);
}
data.setData = {assets: data.session.assets, features: data.session.features};
dalDb.setSession(data, callback);
}
else {
callback(null, data);
}
},
//Store the asset at the user's level
function (data, callback) {
if ((data.proceedPayment || data.revokeAsset || (data.dispute && data.itemCharged))) {
if (!data.session) {
if (data.userId) {
data.setUserWhereClause = {'_id': ObjectId(data.userId)};
}
else if (data.facebookUserId) {
data.setUserWhereClause = {'facebookUserId': data.facebookUserId};
}
}
else {
data.setUserWhereClause = {'_id': ObjectId(data.session.userId)};
}
if (data.revokeAsset) {
data.unsetData = {};
data.unsetData['assets.' + data.featurePurchased] = '';
}
else {
data.setData = {};
data.setData['assets.' + data.featurePurchased] = {'purchaseDate': now, 'method': data.method};
//Update only if asset does not exist yet
data.setUserWhereClause['assets.' + data.featurePurchased] = {$exists: false};
}
dalDb.setUser(data, callback);
}
else {
callback(null, data);
}
},
//Handle facebook dispute or revoke if required
function (data, callback) {
if (data.dispute && data.method === 'facebook') {
//At this time - asset must already exist from previous steps
//Deny the dispute - currently dispute supported on facebook only
dalFacebook.denyDispute(data, callback);
}
else {
callback(null, data);
}
},
//Log the purchase and close db
function (data, callback) {
data.closeConnection = true;
data.logAction = {'action': 'payment', 'extraData': data.paymentData};
if (!data.session) {
if (data.userId) {
data.logAction.userId = data.userId;
}
else if (data.facebookUserId) {
data.logAction.facebookUserId = data.facebookUserId;
}
}
else {
data.logAction.userId = data.session.userId;
}
dalDb.logAction(data, callback);
}
];
async.waterfall(operations, callback);
};
|
#!/usr/bin/env python3
# Copyright (c) 2016-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test Hierarchical Deterministic wallet function."""
import os
import shutil
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_equal,
connect_nodes_bi,
assert_raises_rpc_error
)
class WalletHDTest(BitcoinTestFramework):
def __init__(self):
super().__init__()
self.setup_clean_chain = True
self.num_nodes = 2
self.extra_args = [[], ['-keypool=0']]
def skip_test_if_missing_module(self):
self.skip_if_no_wallet()
def run_test(self):
# Make sure we use hd, keep masterkeyid
masterkeyid = self.nodes[1].getwalletinfo()['hdseedid']
assert_equal(len(masterkeyid), 40)
# create an internal key
change_addr = self.nodes[1].getrawchangeaddress()
change_addrV= self.nodes[1].getaddressinfo(change_addr)
assert_equal(change_addrV["hdkeypath"], "m/0'/1'/0'") #first internal child key
# Import a non-HD private key in the HD wallet
non_hd_add = self.nodes[0].getnewaddress()
self.nodes[1].importprivkey(self.nodes[0].dumpprivkey(non_hd_add))
# This should be enough to keep the master key and the non-HD key
self.nodes[1].backupwallet(os.path.join(self.nodes[1].datadir, "hd.bak"))
#self.nodes[1].dumpwallet(os.path.join(self.nodes[1].datadir, "hd.dump"))
# Derive some HD addresses and remember the last
# Also send funds to each add
self.nodes[0].generate(101)
hd_add = None
NUM_HD_ADDS = 10
for i in range(NUM_HD_ADDS):
hd_add = self.nodes[1].getnewaddress()
hd_info = self.nodes[1].getaddressinfo(hd_add)
assert_equal(hd_info["hdkeypath"], "m/0'/0'/"+str(i)+"'")
assert_equal(hd_info["hdseedid"], masterkeyid)
self.nodes[0].sendtoaddress(hd_add, 1)
self.nodes[0].generate(1)
self.nodes[0].sendtoaddress(non_hd_add, 1)
self.nodes[0].generate(1)
# create an internal key (again)
change_addr = self.nodes[1].getrawchangeaddress()
change_addrV= self.nodes[1].getaddressinfo(change_addr)
assert_equal(change_addrV["hdkeypath"], "m/0'/1'/1'") #second internal child key
self.sync_all()
assert_equal(self.nodes[1].getbalance(), NUM_HD_ADDS + 1)
self.log.info("Restore backup ...")
self.stop_node(1)
# we need to delete the complete regtest directory
# otherwise node1 would auto-recover all funds in flag the keypool keys as used
shutil.rmtree(os.path.join(self.nodes[1].datadir, "regtest", "blocks"))
shutil.rmtree(os.path.join(self.nodes[1].datadir, "regtest", "chainstate"))
shutil.copyfile(os.path.join(self.nodes[1].datadir, "hd.bak"), os.path.join(self.nodes[1].datadir, "regtest", "wallets", "wallet.dat"))
self.start_node(1)
# Assert that derivation is deterministic
hd_add_2 = None
for i in range(NUM_HD_ADDS):
hd_add_2 = self.nodes[1].getnewaddress()
hd_info_2 = self.nodes[1].getaddressinfo(hd_add_2)
assert_equal(hd_info_2["hdkeypath"], "m/0'/0'/"+str(i)+"'")
assert_equal(hd_info_2["hdseedid"], masterkeyid)
assert_equal(hd_add, hd_add_2)
connect_nodes_bi(self.nodes, 0, 1)
self.sync_all()
# Needs rescan
self.stop_node(1)
self.start_node(1, extra_args=self.extra_args[1] + ['-rescan'])
assert_equal(self.nodes[1].getbalance(), NUM_HD_ADDS + 1)
# Try a RPC based rescan
self.stop_node(1)
shutil.rmtree(os.path.join(self.nodes[1].datadir, "regtest", "blocks"))
shutil.rmtree(os.path.join(self.nodes[1].datadir, "regtest", "chainstate"))
shutil.copyfile(os.path.join(self.nodes[1].datadir, "hd.bak"), os.path.join(self.nodes[1].datadir, "regtest", "wallets", "wallet.dat"))
self.start_node(1, extra_args=self.extra_args[1])
connect_nodes_bi(self.nodes, 0, 1)
self.sync_all()
# Wallet automatically scans blocks older than key on startup
assert_equal(self.nodes[1].getbalance(), NUM_HD_ADDS + 1)
out = self.nodes[1].rescanblockchain(0, 1)
assert_equal(out['start_height'], 0)
assert_equal(out['stop_height'], 1)
out = self.nodes[1].rescanblockchain()
assert_equal(out['start_height'], 0)
assert_equal(out['stop_height'], self.nodes[1].getblockcount())
assert_equal(self.nodes[1].getbalance(), NUM_HD_ADDS + 1)
# send a tx and make sure its using the internal chain for the changeoutput
txid = self.nodes[1].sendtoaddress(self.nodes[0].getnewaddress(), 1)
outs = self.nodes[1].decoderawtransaction(self.nodes[1].gettransaction(txid)['hex'])['vout']
keypath = ""
for out in outs:
if out['value'] != 1:
keypath = self.nodes[1].getaddressinfo(out['scriptPubKey']['addresses'][0])['hdkeypath']
assert_equal(keypath[0:7], "m/0'/1'")
# Generate a new HD seed on node 1 and make sure it is set
orig_masterkeyid = self.nodes[1].getwalletinfo()['hdseedid']
self.nodes[1].sethdseed()
new_masterkeyid = self.nodes[1].getwalletinfo()['hdseedid']
assert orig_masterkeyid != new_masterkeyid
addr = self.nodes[1].getnewaddress()
assert_equal(self.nodes[1].getaddressinfo(addr)['hdkeypath'], 'm/0\'/0\'/0\'') # Make sure the new address is the first from the keypool
self.nodes[1].keypoolrefill(1) # Fill keypool with 1 key
# Set a new HD seed on node 1 without flushing the keypool
new_seed = self.nodes[0].dumpprivkey(self.nodes[0].getnewaddress())
orig_masterkeyid = new_masterkeyid
self.nodes[1].sethdseed(False, new_seed)
new_masterkeyid = self.nodes[1].getwalletinfo()['hdseedid']
assert orig_masterkeyid != new_masterkeyid
addr = self.nodes[1].getnewaddress()
assert_equal(orig_masterkeyid, self.nodes[1].getaddressinfo(addr)['hdseedid'])
assert_equal(self.nodes[1].getaddressinfo(addr)['hdkeypath'], 'm/0\'/0\'/1\'') # Make sure the new address continues previous keypool
# Check that the next address is from the new seed
self.nodes[1].keypoolrefill(1)
next_addr = self.nodes[1].getnewaddress()
assert_equal(new_masterkeyid, self.nodes[1].getaddressinfo(next_addr)['hdseedid'])
assert_equal(self.nodes[1].getaddressinfo(next_addr)['hdkeypath'], 'm/0\'/0\'/0\'') # Make sure the new address is not from previous keypool
assert next_addr != addr
# Sethdseed parameter validity
assert_raises_rpc_error(-1, 'sethdseed', self.nodes[0].sethdseed, False, new_seed, 0)
assert_raises_rpc_error(-5, "Invalid private key", self.nodes[1].sethdseed, False, "not_wif")
assert_raises_rpc_error(-1, "JSON value is not a boolean as expected", self.nodes[1].sethdseed, "Not_bool")
assert_raises_rpc_error(-1, "JSON value is not a string as expected", self.nodes[1].sethdseed, False, True)
assert_raises_rpc_error(-5, "Already have this key", self.nodes[1].sethdseed, False, new_seed)
assert_raises_rpc_error(-5, "Already have this key", self.nodes[1].sethdseed, False, self.nodes[1].dumpprivkey(self.nodes[1].getnewaddress()))
if __name__ == '__main__':
WalletHDTest().main ()
|
#!/Users/localadmin/Library/Enthought/Canopy_64bit/User/bin/python2.7
import argparse
from bokeh.server.websocket import make_app
import logging
def build_parser():
parser = argparse.ArgumentParser(description="start bokeh websocket")
parser.add_argument("--url-prefix",
help="url prefix",
type=str,
default=None
)
parser.add_argument("--zmqaddr",
help="zmq url",
action='append'
)
parser.add_argument("--ws-port",
help="port for websocket worker",
default=5007,
type=int
)
return parser
def run_args(args):
#dont' know how to do default args with append and argparse
if args.zmqaddr is None:
args.zmqaddr = ["tcp://127.0.0.1:5007"]
app = make_app(args.url_prefix, args.zmqaddr, args.ws_port)
try:
app.start()
finally:
app.stop()
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG)
parser = build_parser()
args = parser.parse_args()
run_args(args)
|
/*!
* Qoopido.js library v3.3.9, 2014-6-3
* https://github.com/dlueth/qoopido.js
* (c) 2014 Dirk Lueth
* Dual licensed under MIT and GPL
*/
!function(t){window.qoopido.register("function/merge",t)}(function(t,e,n,o,r,u,f){"use strict";return function i(){var t,e,n,o,r,u=arguments[0];for(t=1;(e=arguments[t])!==f;t++)for(n in e)o=u[n],r=e[n],r!==f&&(null!==r&&"object"==typeof r?(o=r.length!==f?o&&"object"==typeof o&&o.length!==f?o:[]:o&&"object"==typeof o&&o.length===f?o:{},u[n]=i(o,r)):u[n]=r);return u}});
|
/*!
* Copyright (c) 2015-2016, Okta, Inc. and/or its affiliates. All rights reserved.
* The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (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.
*/
const INPUT = 'INPUT';
// Syntactic sugar to provide some structure to SimpleForm inputs - Just
// wraps options with { type: type, viewOptions: viewOptions, addOptions: addOptions }
const BUTTON = 'BUTTON';
const DIVIDER = 'DIVIDER';
const TOOLBAR = 'TOOLBAR';
const VIEW = 'VIEW';
function wrap(type) {
return function(viewOptions, addOptions) {
return { type: type, viewOptions: viewOptions, addOptions: addOptions };
};
}
export default {
Input: wrap(INPUT),
Button: wrap(BUTTON),
Divider: wrap(DIVIDER),
Toolbar: wrap(TOOLBAR),
View: wrap(VIEW),
INPUT: INPUT,
BUTTON: BUTTON,
DIVIDER: DIVIDER,
TOOLBAR: TOOLBAR,
VIEW: VIEW,
};
|
#!/usr/bin/env python
# coding=utf-8
import os
from subprocess import Popen, PIPE
import re
import platform
import socket
import time
import json
import threading
token = 'HPcWR7l4NJNJ'
server_ip = '192.168.47.130'
try:
import psutil
except ImportError as msg:
print(msg)
print("----------------------------------------------")
print("begining install psutil module, please waiting")
p = Popen('pip install psutil==5.2.2', stdout=PIPE, shell=True)
stdout, stderr = p.communicate()
print stdout
import psutil
try:
import schedule
except ImportError as msg:
print msg
print("------------------------------------------------")
print("begining install schedule module, please waiting")
p = Popen('pip install schedule==0.4.3', stdout=PIPE, shell=True)
stdout, stderr = p.communicate()
print stdout
import schedule
try:
import requests
except ImportError as msg:
print msg
print("------------------------------------------------")
print("begining install schedule module, please waiting")
p = Popen('pip install requests==2.17.3', stdout=PIPE, shell=True)
stdout, stderr = p.communicate()
print stdout
import requests
def get_ip():
hostname = socket.getfqdn(socket.gethostname())
ipaddr = socket.gethostbyname(hostname)
return ipaddr
def get_dmi():
p = Popen('dmidecode', stdout=PIPE, shell=True)
stdout, stderr = p.communicate()
return stdout
def parser_dmi(dmidata):
pd = {}
line_in = False
for line in dmidata.split('\n'):
if line.startswith('System Information'):
line_in = True
continue
if line.startswith('\t') and line_in:
k,v = [i.strip() for i in line.split(':')]
pd[k] = v
else:
line_in = False
return pd
"""
stdout=PIPE ,获取命令输出值
communicate方法返回值(stdout, stderr)
split() 指定分隔符对字符串进行切片;分隔符,默认为所有的空字符
vmware分配实际内存不是整数G;
"""
def get_mem_total():
cmd = "grep MemTotal /proc/meminfo"
p = Popen(cmd, stdout=PIPE, shell = True)
data = p.communicate()[0]
mem_total = data.split()[1]
memtotal = int(round(int(mem_total)/1024.0/1024.0, 0))
return memtotal
def get_cpu_model():
cmd = "cat /proc/cpuinfo"
p = Popen(cmd, stdout=PIPE, stderr = PIPE, shell = True)
stdout, stderr = p.communicate()
return stdout
def get_cpu_cores():
cpu_cores = {"physical": psutil.cpu_count(logical=False), "logical": psutil.cpu_count()}
return cpu_cores
"""
[x for x in z] 构建List;
stdout.split('\n\n')输出:
['processor\t: 0\nvendor_id\t: GenuineIntel\n……]
stdout.split('\n'):
['processor\t: 0', 'vendor_id\t: GenuineIntel',……]
-------cat /proc/cpuinfo-----
processor : 0
power management:
processor : 1
vendor_id : GenuineIntel
使用stdout.split('\n\n')按cpu核分割;
[-2] 获取倒数第二个;
"""
def parser_cpu(stdout):
groups = [i for i in stdout.split('\n\n')]
group = groups[-2]
cpu_list = [i for i in group.split('\n')]
cpu_info = {}
for x in cpu_list:
k, v = [i.strip() for i in x.split(':')]
cpu_info[k] = v
return cpu_info
"""
Popen shel=False 参数args是序列类型,第一个元素通常是可执行文件的路径;
\n 换行符;
\s 空白符;
[a-z]{1} 匹配a-z字符,{1}匹配前面字符一次;
pattern = re.compile(r'pattern')
result = re.match(pattern, string)
match函數從字符串的開始進行匹配;
search函數並不是從字符串的開始處進行匹配,而是會查找整個字符串;
re.group()/re.group(0) 整個匹配到的字符串;
smartctl -i /dev/sd[1-z]{1} 确认硬盘是否打开了SMART支持;【docker linux 报错:使用smartctl -i /dev/sda -d megaraid,0】
返回字典 {'/dev/sda': ('smartctl 6.2 2017-02-27 r4394 ........')}
"""
def get_disk_info():
ret = {}
disk_dev = re.compile(r'Disk\s/dev/sd[a-z]{1}')
disk_name = re.compile(r'/dev/sd[a-z]{1}')
pcmd = Popen(['fdisk', '-l'], shell=False,stdout=PIPE)
stdout, stderr = pcmd.communicate()
for i in stdout.split('\n'):
disk = re.match(disk_dev,i)
if disk:
dk = re.search(disk_name, disk.group()).group()
n = Popen('smartctl -i %s' % dk, shell=True, stdout=PIPE)
p = n.communicate()
ret[dk] = p
return ret
"""
dict.keys() 字典(Dictionary) keys() 函数以列表返回一个字典所有的键;
\d 匹配一个数字字符。等价于 [0-9];
\s 匹配任何空白字符,包括空格、制表符、换页符等等。等价于 [ \f\n\r\t\v]。
{n} 匹配的重复次数;{2, 4} 的含义是最少重复 2 次、最多重复 4 次。
+ 匹配前面的子表达式一次或多次。例如,'zo+' 能匹配 "zo" 以及 "zoo",但不能匹配 "z"。+ 等价于 {1,}。
strip()函数:s.strip(rm) 删除s字符串中开头、结尾处,位于 rm删除序列的字符;当rm为空时,默认删除空白符(包括'\n', '\r', '\t', ' ')
replace
"""
def parser_disk_info(diskdata):
pd = {}
disknum = diskdata.keys()
device_model = re.compile(r'(Device Model):(\s+.*)')
serial_number = re.compile(r'(Serial Number):(\s+[\d\w]{1,30})')
firmware_version = re.compile(r'(Firmware Version):(\s+[\w]{1,20})')
user_capacity = re.compile(r'(User Capacity):(\s+[\d,]{1,50})') # 正则语法不熟悉??
for num in disknum:
t = str(diskdata[num])
for line in t.split('\n'):
# ('User Capacity', ' 300,000,000,000')
user = re.search(user_capacity,line)
if user:
# user.group()[1]
# 300,000,000,000
# diskvo
# 300,000,000,000
diskvo = user.groups()[1].strip()
nums = int(diskvo.replace(',',''))
endnum = str(nums/1000/1000/1000)
pd[num] = endnum
return json.dumps(pd)
def post_data(url, data):
try:
r = requests.post(url, data)
if r.text:
print r.text
else:
print("Server return http status code: {0}".format(r.status_code))
except StandardError as msg:
print msg
return True
def asset_info():
data_info = dict()
data_info['memory'] = get_mem_total()
data_info['disk'] = parser_disk_info(get_disk_info())
cpuinfo = parser_cpu(get_cpu_model())
cpucore = get_cpu_cores()
data_info['cpu_num'] = cpucore['logical']
data_info['cpu_physical'] = cpucore['physical']
data_info['cpu_model'] = cpuinfo['model name']
data_info['ip'] = get_ip()
data_info['sn'] = parser_dmi(get_dmi())['Serial Number']
data_info['vendor'] = parser_dmi(get_dmi())['Manufacturer']
data_info['product'] = parser_dmi(get_dmi())['Version']
data_info['osver'] = platform.linux_distribution()[0] + " " + platform.linux_distribution()[1] + " " + platform.machine()
data_info['hostname'] = platform.node()
data_info['token'] = token
return json.dumps(data_info)
"""
osenv OS系统环境使用的语言('en_US.UTF-8')
"""
def asset_info_post():
osenv = os.environ["LANG"]
os.environ["LANG"] = "us_EN.UTF8"
print 'Get the hardwave infos from host:'
print asset_info()
print '----------------------------------------------------------'
post_data("http://{0}/cmdb/collect".format(server_ip), asset_info())
os.environ["LANG"] = osenv
return True
def get_sys_cpu():
sys_cpu = {}
cpu_time = psutil.cpu_times_percent(interval=1)
sys_cpu['percent'] = psutil.cpu_percent(interval=1)
sys_cpu['lcpu_percent'] = psutil.cpu_percent(interval=1, percpu=True)
sys_cpu['user'] = cpu_time.user
sys_cpu['nice'] = cpu_time.nice
sys_cpu['system'] = cpu_time.system
sys_cpu['idle'] = cpu_time.idle
sys_cpu['iowait'] = cpu_time.iowait
sys_cpu['irq'] = cpu_time.irq
sys_cpu['softirq'] = cpu_time.softirq
sys_cpu['guest'] = cpu_time.guest
return sys_cpu
def get_sys_mem():
sys_mem = {}
mem = psutil.virtual_memory()
sys_mem["total"] = mem.total/1024/1024
sys_mem["percent"] = mem.percent
sys_mem["available"] = mem.available/1024/1024
sys_mem["used"] = mem.used/1024/1024
sys_mem["free"] = mem.free/1024/1024
sys_mem["buffers"] = mem.buffers/1024/1024
sys_mem["cached"] = mem.cached/1024/1024
return sys_mem
def parser_sys_disk(mountpoint):
partitions_list = {}
d = psutil.disk_usage(mountpoint)
partitions_list['mountpoint'] = mountpoint
partitions_list['total'] = round(d.total/1024/1024/1024.0, 2)
partitions_list['free'] = round(d.free/1024/1024/1024.0, 2)
partitions_list['used'] = round(d.used/1024/1024/1024.0, 2)
partitions_list['percent'] = d.percent
return partitions_list
def get_sys_disk():
sys_disk = {}
partition_info = []
partitions = psutil.disk_partitions()
for p in partitions:
partition_info.append(parser_sys_disk(p.mountpoint))
sys_disk = partition_info
return sys_disk
# 函数获取各网卡发送、接收字节数
def get_nic():
key_info = psutil.net_io_counters(pernic=True).keys() # 获取网卡名称
recv = {}
sent = {}
for key in key_info:
recv.setdefault(key, psutil.net_io_counters(pernic=True).get(key).bytes_recv) # 各网卡接收的字节数
sent.setdefault(key, psutil.net_io_counters(pernic=True).get(key).bytes_sent) # 各网卡发送的字节数
return key_info, recv, sent
# 函数计算每秒速率
def get_nic_rate(func):
key_info, old_recv, old_sent = func() # 上一秒收集的数据
time.sleep(1)
key_info, now_recv, now_sent = func() # 当前所收集的数据
net_in = {}
net_out = {}
for key in key_info:
net_in.setdefault(key, (now_recv.get(key) - old_recv.get(key)) / 1024) # 每秒接收速率
net_out.setdefault(key, (now_sent.get(key) - old_sent.get(key)) / 1024) # 每秒发送速率
return key_info, net_in, net_out
def get_net_info():
net_info = []
key_info, net_in, net_out = get_nic_rate(get_nic)
for key in key_info:
in_data = net_in.get(key)
out_data = net_out.get(key)
net_info.append({"nic_name": key, "traffic_in": in_data, "traffic_out": out_data})
return net_info
def agg_sys_info():
print 'Get the system infos from host:'
sys_info = dict()
sys_info['hostname'] = platform.node()
sys_info['cpu'] = get_sys_cpu()
sys_info['mem'] = get_sys_mem()
sys_info['disk'] = get_sys_disk()
sys_info['net'] = get_net_info()
sys_info['token'] = token
print sys_info
json_data = json.dumps(sys_info)
print '----------------------------------------------------------'
post_data("http://{0}/monitor/received/sys/info/".format(server_ip), json_data)
return True
def run_threaded(job_func):
job_thread = threading.Thread(target=job_func)
job_thread.start()
if __name__ == "__main__":
asset_info_post()
time.sleep(1)
agg_sys_info()
schedule.every(1800).seconds.do(run_threaded, asset_info_post)
schedule.every(60).seconds.do(run_threaded, agg_sys_info)
while True:
schedule.run_pending()
time.sleep(1)
|
"""
Utilities to simplify the boilerplate for native lowering.
"""
from __future__ import print_function, absolute_import, division
import collections
import contextlib
import inspect
import functools
from enum import Enum
from .. import typing, cgutils, types, utils
from .. typing.templates import BaseRegistryLoader
class Registry(object):
"""
A registry of function and attribute implementations.
"""
def __init__(self):
self.functions = []
self.getattrs = []
self.setattrs = []
self.casts = []
self.constants = []
def lower(self, func, *argtys):
"""
Decorate an implementation of *func* for the given argument types.
*func* may be an actual global function object, or any
pseudo-function supported by Numba, such as "getitem".
The decorated implementation has the signature
(context, builder, sig, args).
"""
def decorate(impl):
self.functions.append((impl, func, argtys))
return impl
return decorate
def _decorate_attr(self, impl, ty, attr, impl_list, decorator):
real_impl = decorator(impl, ty, attr)
impl_list.append((real_impl, attr, real_impl.signature))
return impl
def lower_getattr(self, ty, attr):
"""
Decorate an implementation of __getattr__ for type *ty* and
the attribute *attr*.
The decorated implementation will have the signature
(context, builder, typ, val).
"""
def decorate(impl):
return self._decorate_attr(impl, ty, attr, self.getattrs,
_decorate_getattr)
return decorate
def lower_getattr_generic(self, ty):
"""
Decorate the fallback implementation of __getattr__ for type *ty*.
The decorated implementation will have the signature
(context, builder, typ, val, attr). The implementation is
called for attributes which haven't been explicitly registered
with lower_getattr().
"""
return self.lower_getattr(ty, None)
def lower_setattr(self, ty, attr):
"""
Decorate an implementation of __setattr__ for type *ty* and
the attribute *attr*.
The decorated implementation will have the signature
(context, builder, sig, args).
"""
def decorate(impl):
return self._decorate_attr(impl, ty, attr, self.setattrs,
_decorate_setattr)
return decorate
def lower_setattr_generic(self, ty):
"""
Decorate the fallback implementation of __setattr__ for type *ty*.
The decorated implementation will have the signature
(context, builder, sig, args, attr). The implementation is
called for attributes which haven't been explicitly registered
with lower_setattr().
"""
return self.lower_setattr(ty, None)
def lower_cast(self, fromty, toty):
"""
Decorate the implementation of implicit conversion between
*fromty* and *toty*.
The decorated implementation will have the signature
(context, builder, fromty, toty, val).
"""
def decorate(impl):
self.casts.append((impl, (fromty, toty)))
return impl
return decorate
def lower_constant(self, ty):
"""
Decorate the implementation for creating a constant of type *ty*.
The decorated implementation will have the signature
(context, builder, ty, pyval).
"""
def decorate(impl):
self.constants.append((impl, (ty,)))
return impl
return decorate
class RegistryLoader(BaseRegistryLoader):
"""
An incremental loader for a target registry.
"""
registry_items = ('functions', 'getattrs', 'setattrs', 'casts', 'constants')
# Global registry for implementations of builtin operations
# (functions, attributes, type casts)
builtin_registry = Registry()
lower_builtin = builtin_registry.lower
lower_getattr = builtin_registry.lower_getattr
lower_getattr_generic = builtin_registry.lower_getattr_generic
lower_setattr = builtin_registry.lower_setattr
lower_setattr_generic = builtin_registry.lower_setattr_generic
lower_cast = builtin_registry.lower_cast
lower_constant = builtin_registry.lower_constant
def _decorate_getattr(impl, ty, attr):
real_impl = impl
if attr is not None:
def res(context, builder, typ, value, attr):
return real_impl(context, builder, typ, value)
else:
def res(context, builder, typ, value, attr):
return real_impl(context, builder, typ, value, attr)
res.signature = (ty,)
res.attr = attr
return res
def _decorate_setattr(impl, ty, attr):
real_impl = impl
if attr is not None:
def res(context, builder, sig, args, attr):
return real_impl(context, builder, sig, args)
else:
def res(context, builder, sig, args, attr):
return real_impl(context, builder, sig, args, attr)
res.signature = (ty, types.Any)
res.attr = attr
return res
def fix_returning_optional(context, builder, sig, status, retval):
# Reconstruct optional return type
if isinstance(sig.return_type, types.Optional):
value_type = sig.return_type.type
optional_none = context.make_optional_none(builder, value_type)
retvalptr = cgutils.alloca_once_value(builder, optional_none)
with builder.if_then(builder.not_(status.is_none)):
optional_value = context.make_optional_value(
builder, value_type, retval,
)
builder.store(optional_value, retvalptr)
retval = builder.load(retvalptr)
return retval
def user_function(fndesc, libs):
"""
A wrapper inserting code calling Numba-compiled *fndesc*.
"""
def imp(context, builder, sig, args):
func = context.declare_function(builder.module, fndesc)
# env=None assumes this is a nopython function
status, retval = context.call_conv.call_function(
builder, func, fndesc.restype, fndesc.argtypes, args)
with cgutils.if_unlikely(builder, status.is_error):
context.call_conv.return_status_propagate(builder, status)
assert sig.return_type == fndesc.restype
# Reconstruct optional return type
retval = fix_returning_optional(context, builder, sig, status, retval)
# If the data representations don't match up
if retval.type != context.get_value_type(sig.return_type):
msg = "function returned {0} but expect {1}"
raise TypeError(msg.format(retval.type, sig.return_type))
return impl_ret_new_ref(context, builder, fndesc.restype, retval)
imp.signature = fndesc.argtypes
imp.libs = tuple(libs)
return imp
def user_generator(gendesc, libs):
"""
A wrapper inserting code calling Numba-compiled *gendesc*.
"""
def imp(context, builder, sig, args):
func = context.declare_function(builder.module, gendesc)
# env=None assumes this is a nopython function
status, retval = context.call_conv.call_function(
builder, func, gendesc.restype, gendesc.argtypes, args)
# Return raw status for caller to process StopIteration
return status, retval
imp.libs = tuple(libs)
return imp
def iterator_impl(iterable_type, iterator_type):
"""
Decorator a given class as implementing *iterator_type*
(by providing an `iternext()` method).
"""
def wrapper(cls):
# These are unbound methods
iternext = cls.iternext
@iternext_impl(RefType.BORROWED)
def iternext_wrapper(context, builder, sig, args, result):
(value,) = args
iterobj = cls(context, builder, value)
return iternext(iterobj, context, builder, result)
lower_builtin('iternext', iterator_type)(iternext_wrapper)
return cls
return wrapper
class _IternextResult(object):
"""
A result wrapper for iteration, passed by iternext_impl() into the
wrapped function.
"""
__slots__ = ('_context', '_builder', '_pairobj')
def __init__(self, context, builder, pairobj):
self._context = context
self._builder = builder
self._pairobj = pairobj
def set_exhausted(self):
"""
Mark the iterator as exhausted.
"""
self._pairobj.second = self._context.get_constant(types.boolean, False)
def set_valid(self, is_valid=True):
"""
Mark the iterator as valid according to *is_valid* (which must
be either a Python boolean or a LLVM inst).
"""
if is_valid in (False, True):
is_valid = self._context.get_constant(types.boolean, is_valid)
self._pairobj.second = is_valid
def yield_(self, value):
"""
Mark the iterator as yielding the given *value* (a LLVM inst).
"""
self._pairobj.first = value
def is_valid(self):
"""
Return whether the iterator is marked valid.
"""
return self._context.get_argument_value(self._builder,
types.boolean,
self._pairobj.second)
def yielded_value(self):
"""
Return the iterator's yielded value, if any.
"""
return self._pairobj.first
class RefType(Enum):
"""
Enumerate the reference type
"""
"""
A new reference
"""
NEW = 1
"""
A borrowed reference
"""
BORROWED = 2
"""
An untracked reference
"""
UNTRACKED = 3
def iternext_impl(ref_type=None):
"""
Wrap the given iternext() implementation so that it gets passed
an _IternextResult() object easing the returning of the iternext()
result pair.
ref_type: a numba.targets.imputils.RefType value, the reference type used is
that specified through the RefType enum.
The wrapped function will be called with the following signature:
(context, builder, sig, args, iternext_result)
"""
if ref_type not in [x for x in RefType]:
raise ValueError("ref_type must be an enum member of imputils.RefType")
def outer(func):
def wrapper(context, builder, sig, args):
pair_type = sig.return_type
pairobj = context.make_helper(builder, pair_type)
func(context, builder, sig, args,
_IternextResult(context, builder, pairobj))
if ref_type == RefType.NEW:
impl_ret = impl_ret_new_ref
elif ref_type == RefType.BORROWED:
impl_ret = impl_ret_borrowed
elif ref_type == RefType.UNTRACKED:
impl_ret = impl_ret_untracked
else:
raise ValueError("Unknown ref_type encountered")
return impl_ret(context, builder,
pair_type, pairobj._getvalue())
return wrapper
return outer
def call_getiter(context, builder, iterable_type, val):
"""
Call the `getiter()` implementation for the given *iterable_type*
of value *val*, and return the corresponding LLVM inst.
"""
getiter_sig = typing.signature(iterable_type.iterator_type, iterable_type)
getiter_impl = context.get_function('getiter', getiter_sig)
return getiter_impl(builder, (val,))
def call_iternext(context, builder, iterator_type, val):
"""
Call the `iternext()` implementation for the given *iterator_type*
of value *val*, and return a convenience _IternextResult() object
reflecting the results.
"""
itemty = iterator_type.yield_type
pair_type = types.Pair(itemty, types.boolean)
iternext_sig = typing.signature(pair_type, iterator_type)
iternext_impl = context.get_function('iternext', iternext_sig)
val = iternext_impl(builder, (val,))
pairobj = context.make_helper(builder, pair_type, val)
return _IternextResult(context, builder, pairobj)
def call_len(context, builder, ty, val):
"""
Call len() on the given value. Return None if len() isn't defined on
this type.
"""
try:
len_impl = context.get_function(len, typing.signature(types.intp, ty,))
except NotImplementedError:
return None
else:
return len_impl(builder, (val,))
_ForIterLoop = collections.namedtuple('_ForIterLoop',
('value', 'do_break'))
@contextlib.contextmanager
def for_iter(context, builder, iterable_type, val):
"""
Simulate a for loop on the given iterable. Yields a namedtuple with
the given members:
- `value` is the value being yielded
- `do_break` is a callable to early out of the loop
"""
iterator_type = iterable_type.iterator_type
iterval = call_getiter(context, builder, iterable_type, val)
bb_body = builder.append_basic_block('for_iter.body')
bb_end = builder.append_basic_block('for_iter.end')
def do_break():
builder.branch(bb_end)
builder.branch(bb_body)
with builder.goto_block(bb_body):
res = call_iternext(context, builder, iterator_type, iterval)
with builder.if_then(builder.not_(res.is_valid()), likely=False):
builder.branch(bb_end)
yield _ForIterLoop(res.yielded_value(), do_break)
builder.branch(bb_body)
builder.position_at_end(bb_end)
if context.enable_nrt:
context.nrt.decref(builder, iterator_type, iterval)
def impl_ret_new_ref(ctx, builder, retty, ret):
"""
The implementation returns a new reference.
"""
return ret
def impl_ret_borrowed(ctx, builder, retty, ret):
"""
The implementation returns a borrowed reference.
This function automatically incref so that the implementation is
returning a new reference.
"""
if ctx.enable_nrt:
ctx.nrt.incref(builder, retty, ret)
return ret
def impl_ret_untracked(ctx, builder, retty, ret):
"""
The return type is not a NRT object.
"""
return ret
@contextlib.contextmanager
def force_error_model(context, model_name='numpy'):
"""
Temporarily change the context's error model.
"""
from . import callconv
old_error_model = context.error_model
context.error_model = callconv.create_error_model(model_name, context)
try:
yield
finally:
context.error_model = old_error_model
def numba_typeref_ctor(*args, **kwargs):
"""A stub for use internally by Numba when a call is emitted
on a TypeRef.
"""
raise NotImplementedError("This function should not be executed.")
|
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://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.
"""Defines a Keras model and input function for training.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
def input_fn(features, labels, shuffle, num_epochs, batch_size):
"""Generates an input function to be used for model training.
Args:
features: numpy array of features used for training or inference
labels: numpy array of labels for each example
shuffle: boolean for whether to shuffle the data or not (set True for
training, False for evaluation)
num_epochs: number of epochs to provide the data for
batch_size: batch size for training
Returns:
A tf.data.Dataset that can provide data to the Keras model for training or
evaluation
"""
if labels is None:
inputs = features
else:
inputs = (features, labels)
dataset = tf.data.Dataset.from_tensor_slices(inputs)
if shuffle:
dataset = dataset.shuffle(buffer_size=len(features))
# We call repeat after shuffling, rather than before, to prevent separate
# epochs from blending together.
dataset = dataset.repeat(num_epochs)
dataset = dataset.batch(batch_size)
return dataset
def create_keras_model(input_dim, learning_rate):
"""Creates Keras Model for Binary Classification.
Args:
input_dim: How many features the input has
learning_rate: Learning rate for training
Returns:
The compiled Keras model (still needs to be trained)
"""
model = tf.keras.Sequential()
model.add(
tf.keras.layers.Dense(
100,
activation=tf.nn.relu,
kernel_initializer='uniform',
input_shape=(input_dim,)))
model.add(tf.keras.layers.Dense(75, activation=tf.nn.relu))
model.add(tf.keras.layers.Dense(50, activation=tf.nn.relu))
model.add(tf.keras.layers.Dense(25, activation=tf.nn.relu))
# The single output node and Sigmoid activation makes this a Logistic
# Regression.
model.add(tf.keras.layers.Dense(1, activation=tf.nn.sigmoid))
# Custom Optimizer:
# https://www.tensorflow.org/api_docs/python/tf/train/RMSPropOptimizer
optimizer = tf.keras.optimizers.RMSprop(
lr=learning_rate, rho=0.9, epsilon=1e-08, decay=0.0)
# Compile Keras model
model.compile(
loss='binary_crossentropy', optimizer=optimizer, metrics=['accuracy'])
return model
|
from art.estimators.classification import TensorFlowV2Classifier, PyTorchClassifier
import numpy as np
import tensorflow as tf
import torch
from typing import Union, Tuple
class Classifier:
"""`Classifier` class."""
def __init__(
self,
classifier: Union[tf.Module, torch.nn.Module],
loss: Union[tf.losses.Loss, torch.nn.modules.loss._Loss],
nb_classes: int,
input_shape: Tuple[int, ...],
):
"""Initializes a `Classifier` class.
:param classifier: The classifier. Either a Pytorch or TensorFlow classifier.
:param nb_classes: Number of classes that were used to train the classifier.
:param input_shape: Input shape of a data point of the classifier.
"""
self.loss = loss
self.nb_classes = nb_classes
self.input_shape = input_shape
self.art_classifier = self._to_art_classifier(
classifier, loss, nb_classes, input_shape
)
def predict(self, x: np.ndarray):
"""Predicts labels for given data.
:param x: Data which labels should be predicted for.
:return: Predicted labels.
"""
return self.art_classifier.predict(x)
def to_art_classifier(self):
"""Converts the classifier to an ART classifier.
:return: Converted ART classifier.
"""
return self.art_classifier
@staticmethod
def _to_art_classifier(
classifier: Union[tf.Module, torch.nn.Module],
loss: Union[tf.losses.Loss, torch.nn.modules.loss._Loss],
nb_classes: int,
input_shape: Tuple[int, ...],
) -> Union[TensorFlowV2Classifier, PyTorchClassifier]:
"""Initializes an ART classifier.
:param classifier: Original classifier, either Pytorch or TensorFlow.
:param nb_classes: Number of classes that were used to train the classifier.
:param input_shape: Shape of a input data point of the classifier.
:return: Instance of an ART classifier.
:raises TypeError: If `classifier` is of invalid type.
"""
if isinstance(classifier, torch.nn.Module):
return PyTorchClassifier(
model=classifier,
loss=loss,
nb_classes=nb_classes,
input_shape=input_shape,
)
if isinstance(classifier, tf.Module):
return TensorFlowV2Classifier(
model=classifier,
loss_object=loss,
nb_classes=nb_classes,
input_shape=input_shape,
)
else:
raise TypeError(
f"Expected `classifier` to be an instance of {str(torch.nn.Module)} or {str(tf.Module)}, received "
f"{str(type(classifier))} instead. "
)
|
#ifndef CLIENT_H
#define CLIENT_H
#include "client-state.h"
#include "user.h"
enum client_protocol {
CLIENT_PROTOCOL_IMAP = 0,
CLIENT_PROTOCOL_POP3
};
struct mailbox_source;
struct client_vfuncs {
void (*input)(struct client *client);
int (*output)(struct client *client);
void (*connected)(struct client *client);
int (*send_more_commands)(struct client *client);
void (*logout)(struct client *client);
void (*free)(struct client *client);
};
struct client {
int refcount;
struct user *user;
struct user_client *user_client;
struct client_vfuncs v;
enum client_protocol protocol;
unsigned int port;
unsigned int idx, global_id;
unsigned int cur;
int fd, rawlog_fd;
struct istream *input;
struct ostream *output;
struct ssl_iostream *ssl_iostream;
struct io *io;
struct timeout *to;
enum login_state login_state;
enum client_state state;
time_t last_io;
unsigned int delayed:1;
unsigned int disconnected:1;
unsigned int logout_sent:1;
unsigned int idling:1;
};
ARRAY_DEFINE_TYPE(client, struct client *);
extern int clients_count;
extern unsigned int total_disconnects;
extern ARRAY_TYPE(client) clients;
extern bool stalled, disconnect_clients, no_new_clients;
struct client *client_new_user(struct user *user);
struct client *client_new_random(unsigned int i, struct mailbox_source *source);
int client_init(struct client *client, unsigned int idx,
struct user *user, struct user_client *uc);
bool client_unref(struct client *client, bool reconnect);
void client_logout(struct client *client);
void client_disconnect(struct client *client);
void client_input_stop(struct client *client);
void client_input_continue(struct client *client);
void client_delay(struct client *client, unsigned int msecs);
int client_send_more_commands(struct client *client);
unsigned int clients_get_random_idx(void);
bool imaptest_has_clients(void);
void clients_init(void);
void clients_deinit(void);
#endif
|
import getpass
import os
def ensure_domain(domain):
if domain == "your-username.pythonanywhere.com":
username = getpass.getuser().lower()
pa_domain = os.environ.get("PYTHONANYWHERE_DOMAIN", "pythonanywhere.com")
return f"{username}.{pa_domain}"
else:
return domain
|
RD_VERSION = 0x00
GET_VALUE = 0x01
ERROR = -1
VCC = 65536
def getVersion(dev):
dev.send([RD_VERSION])
raw = dev.read(3)
return raw[1] + raw[2] * 256
def getValue(dev):
dev.send([GET_VALUE])
raw = dev.read(3)
if not(raw[1] == 255):
return VCC - (raw[1] + raw[2] * 256)
else:
return ERROR
|
from cv2 import cv2
import numpy as np
import math
GAUSSIAN_SMOOTH_FILTER_SIZE = (5, 5)
ADAPTIVE_THRESH_BLOCK_SIZE = 19
ADAPTIVE_THRESH_WEIGHT = 9
def preprocess(imgOriginal):
imgGrayscale = extractValue(imgOriginal)
imgMaxContrastGrayscale = maximizeContrast(imgGrayscale)
height, width = imgGrayscale.shape
imgBlurred = np.zeros((height, width, 1), np.uint8)
imgBlurred = cv2.GaussianBlur(imgMaxContrastGrayscale, GAUSSIAN_SMOOTH_FILTER_SIZE, 0)
imgThresh = cv2.adaptiveThreshold(imgBlurred, 255.0, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, ADAPTIVE_THRESH_BLOCK_SIZE, ADAPTIVE_THRESH_WEIGHT)
return imgGrayscale, imgThresh
def extractValue(imgOriginal):
height, width, numChannels = imgOriginal.shape
imgHSV = np.zeros((height, width, 3), np.uint8)
imgHSV = cv2.cvtColor(imgOriginal, cv2.COLOR_BGR2HSV)
imgHue, imgSaturation, imgValue = cv2.split(imgHSV)
return imgValue
def maximizeContrast(imgGrayscale):
height, width = imgGrayscale.shape
imgTopHat = np.zeros((height, width, 1), np.uint8)
imgBlackHat = np.zeros((height, width, 1), np.uint8)
structuringElement = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
imgTopHat = cv2.morphologyEx(imgGrayscale, cv2.MORPH_TOPHAT, structuringElement)
imgBlackHat = cv2.morphologyEx(imgGrayscale, cv2.MORPH_BLACKHAT, structuringElement)
imgGrayscalePlusTopHat = cv2.add(imgGrayscale, imgTopHat)
imgGrayscalePlusTopHatMinusBlackHat = cv2.subtract(imgGrayscalePlusTopHat, imgBlackHat)
return imgGrayscalePlusTopHatMinusBlackHat
|
import numpy as np
import pytest
from pandas._libs import (
lib,
reduction as libreduction,
)
import pandas.util._test_decorators as td
import pandas as pd
from pandas import Series
import pandas._testing as tm
def test_series_grouper():
obj = Series(np.random.randn(10))
labels = np.array([-1, -1, -1, 0, 0, 0, 1, 1, 1, 1], dtype=np.int64)
grouper = libreduction.SeriesGrouper(obj, np.mean, labels, 2)
result, counts = grouper.get_result()
expected = np.array([obj[3:6].mean(), obj[6:].mean()])
tm.assert_almost_equal(result, expected)
exp_counts = np.array([3, 4], dtype=np.int64)
tm.assert_almost_equal(counts, exp_counts)
def test_series_grouper_requires_nonempty_raises():
# GH#29500
obj = Series(np.random.randn(10))
dummy = obj.iloc[:0]
labels = np.array([-1, -1, -1, 0, 0, 0, 1, 1, 1, 1], dtype=np.int64)
with pytest.raises(ValueError, match="SeriesGrouper requires non-empty `series`"):
libreduction.SeriesGrouper(dummy, np.mean, labels, 2)
def test_series_bin_grouper():
obj = Series(np.random.randn(10))
bins = np.array([3, 6])
grouper = libreduction.SeriesBinGrouper(obj, np.mean, bins)
result, counts = grouper.get_result()
expected = np.array([obj[:3].mean(), obj[3:6].mean(), obj[6:].mean()])
tm.assert_almost_equal(result, expected)
exp_counts = np.array([3, 3, 4], dtype=np.int64)
tm.assert_almost_equal(counts, exp_counts)
def assert_block_lengths(x):
assert len(x) == len(x._mgr.blocks[0].mgr_locs)
return 0
def cumsum_max(x):
x.cumsum().max()
return 0
@pytest.mark.parametrize(
"func",
[
cumsum_max,
pytest.param(assert_block_lengths, marks=td.skip_array_manager_invalid_test),
],
)
def test_mgr_locs_updated(func):
# https://github.com/pandas-dev/pandas/issues/31802
# Some operations may require creating new blocks, which requires
# valid mgr_locs
df = pd.DataFrame({"A": ["a", "a", "a"], "B": ["a", "b", "b"], "C": [1, 1, 1]})
result = df.groupby(["A", "B"]).agg(func)
expected = pd.DataFrame(
{"C": [0, 0]},
index=pd.MultiIndex.from_product([["a"], ["a", "b"]], names=["A", "B"]),
)
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize(
"binner,closed,expected",
[
(
np.array([0, 3, 6, 9], dtype=np.int64),
"left",
np.array([2, 5, 6], dtype=np.int64),
),
(
np.array([0, 3, 6, 9], dtype=np.int64),
"right",
np.array([3, 6, 6], dtype=np.int64),
),
(np.array([0, 3, 6], dtype=np.int64), "left", np.array([2, 5], dtype=np.int64)),
(
np.array([0, 3, 6], dtype=np.int64),
"right",
np.array([3, 6], dtype=np.int64),
),
],
)
def test_generate_bins(binner, closed, expected):
values = np.array([1, 2, 3, 4, 5, 6], dtype=np.int64)
result = lib.generate_bins_dt64(values, binner, closed=closed)
tm.assert_numpy_array_equal(result, expected)
class TestMoments:
pass
|
import { g } from './basicVars.js';
import { mouseover, mousemove, mouseleave } from './hover.js'
function updateChart(continent, scales) {
const { xScale, yScale, g_xAxis, g_yAxis, xAxis, yAxis } = scales;
// Update the scales
xScale
.domain([0, d3.max(continent, (d) => d.value)]);
yScale
.domain(continent.map((d) => d.currency));
// Render the axis
g_xAxis
.call(xAxis)
.transition()
.duration(700)
.style('opacity', 1);
g_yAxis
.call(yAxis)
.transition()
.duration(700)
.style('opacity', 1);
// Join the data with rectangle elements
const rect = g.selectAll('rect')
.data(continent, (d) => d.currency)
.join(
// Create rectangle elements
(enter) => {
const rectEnter = enter.append('rect')
.attr('x', 0);
rectEnter.append('title');
return rectEnter;
},
// Update existing elements
(update) => update,
// Remove elements (not associated with data)
(exit) => exit.remove()
)
.on('mouseover', mouseover)
.on('mousemove', mousemove)
.on('mouseleave', mouseleave);
// Adding height, width and title to my rect
rect
.attr('height', yScale.bandwidth())
.attr('y', (d) => yScale(d.currency))
.transition()
.attr('width', (d) => xScale(d.value))
.duration(1500)
.ease(d3.easeCircleOut);
rect.select('title')
.text((d) => d.currency);
}
export { updateChart }
|
import os
import sys
import argparse
import numpy as np
homepath = os.path.join('..', '..')
if not homepath in sys.path:
sys.path.insert(0, homepath)
import conf_cuhk_sar as conf
# Program arguments parser
data_txt = """
The input data. 'X' stands for image, 'A' stands for attribute, and 'S' stands
for segmentation.
"""
output_txt = """
If not specified, the output data will be saved as data_sar.pkl.
Otherwise it will be saved as data_sar_name.pkl.
"""
parser = argparse.ArgumentParser(description='Prepare the data')
parser.add_argument('-d', '--dataset', nargs='+', required=True,
choices=['Mix_SAR', 'CUHK_SAR'])
parser.add_argument('-i', '--input', nargs='+', required=True,
choices=['X', 'A', 'S'], help=data_txt)
parser.add_argument('-t', '--target', nargs='+', required=True,
choices=['X', 'A', 'S'], help=data_txt)
parser.add_argument('-o', '--output', nargs='?', default=None,
metavar='name', help=output_txt)
args = parser.parse_args()
def load_rawdata(dnames):
from scipy.io import loadmat
rawdata = []
for dname in dnames:
fpath = os.path.join(homepath, 'data', 'human_sar', dname + '.mat')
matdata = loadmat(fpath)
m, n = matdata['images'].shape
for i in xrange(m):
rawdata.append([
matdata['images'][i, 0],
matdata['attributes'][i, 0].ravel(),
matdata['segmentations'][i, 0]
])
return rawdata
def create_dataset(rawdata):
from dlearn.data.dataset import Dataset
from dlearn.utils import imgproc
def imgprep(img):
if img.shape != (160, 80):
img = imgproc.resize(img, [160, 80], keep_ratio='height')
img = imgproc.subtract_luminance(img)
img = np.rollaxis(img, 2)
return (img / 100.0).astype(np.float32)
def choose_attr_uni(attr, title):
ind = conf.attr_uni_titles.index(title)
vals = conf.attr_uni[ind]
ind = [conf.attr_names.index(v) for v in vals]
return np.where(attr[ind] == 1)[0][0]
def choose_attr_mul(attr, title):
ind = conf.attr_mul_titles.index(title)
vals = conf.attr_mul[ind]
ind = [conf.attr_names.index(v) for v in vals]
return attr[ind].astype(np.float32)
def choose_seg(seg, title):
val = conf.seg_pix[title]
img = (seg == val).astype(np.float32)
img = imgproc.resize(img, [37, 17])
return img.astype(np.float32)
m = len(rawdata)
X = [0] * (2 * m)
A = [0] * (2 * m)
S = [0] * (2 * m)
i = 0
for (img, attr, seg) in rawdata:
X[i] = imgprep(img)
A[i] = choose_attr_mul(attr, 'Upper Body Colors')
S[i] = choose_seg(seg, 'Upper')
# S[i] = (seg >= 0.5).astype(np.float32)
# S[i] = imgproc.resize(S[i], [37, 17]).astype(np.float32)
# Mirror
X[i + 1] = X[i][:, :, ::-1].copy()
A[i + 1] = A[i].copy()
S[i + 1] = S[i][:, ::-1].copy()
i += 2
X = np.asarray(X)
A = np.asarray(A)
S = np.asarray(S)
X = X - X.mean(axis=0)
def parse_list(arglist):
d = {'X': X, 'A': A, 'S': S}
l = map(lambda x: d[x], arglist)
return l[0] if len(l) == 1 else l
dataset = Dataset(parse_list(args.input), parse_list(args.target))
dataset.split(0.7, 0.2)
return dataset
def save_dataset(dataset, fpath):
import cPickle
with open(fpath, 'wb') as f:
cPickle.dump(dataset, f, cPickle.HIGHEST_PROTOCOL)
if __name__ == '__main__':
rawdata = load_rawdata(args.dataset)
dataset = create_dataset(rawdata)
out_file = 'data_sar.pkl' if args.output is None else \
'data_sar_{0}.pkl'.format(args.output)
save_dataset(dataset, out_file)
|
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.base.exchange import Exchange
import hashlib
import math
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import AuthenticationError
from ccxt.base.errors import PermissionDenied
from ccxt.base.errors import ArgumentsRequired
from ccxt.base.errors import BadRequest
from ccxt.base.errors import BadSymbol
from ccxt.base.errors import InsufficientFunds
from ccxt.base.errors import InvalidOrder
from ccxt.base.errors import OrderNotFound
from ccxt.base.errors import NetworkError
from ccxt.base.errors import ExchangeNotAvailable
from ccxt.base.errors import OnMaintenance
from ccxt.base.errors import RequestTimeout
from ccxt.base.decimal_to_precision import TRUNCATE
class cdax(Exchange):
def describe(self):
return self.deep_extend(super(cdax, self).describe(), {
'id': 'cdax',
'name': 'CDAX',
'countries': ['RU'],
'rateLimit': 100,
'userAgent': self.userAgents['chrome39'],
'certified': False,
'version': 'v1',
'accounts': None,
'accountsById': None,
'hostname': 'cdax.io',
'pro': False,
'has': {
'CORS': None,
'spot': True,
'margin': None, # has but unimplemented
'swap': None,
'future': None,
'option': None,
'cancelAllOrders': True,
'cancelOrder': True,
'cancelOrders': True,
'createOrder': True,
'fetchAccounts': True,
'fetchBalance': True,
'fetchClosedOrders': True,
'fetchCurrencies': True,
'fetchDepositAddress': False,
'fetchDepositAddressesByNetwork': False,
'fetchDeposits': True,
'fetchFundingHistory': False,
'fetchFundingRate': False,
'fetchFundingRateHistory': False,
'fetchFundingRates': False,
'fetchIndexOHLCV': False,
'fetchMarkets': True,
'fetchMarkOHLCV': False,
'fetchMyTrades': True,
'fetchOHLCV': True,
'fetchOpenOrders': True,
'fetchOrder': True,
'fetchOrderBook': True,
'fetchOrders': True,
'fetchOrderTrades': True,
'fetchPremiumIndexOHLCV': False,
'fetchTicker': True,
'fetchTickers': True,
'fetchTime': True,
'fetchTrades': True,
'fetchTradingLimits': True,
'fetchWithdrawals': True,
'withdraw': True,
},
'timeframes': {
'1m': '1min',
'5m': '5min',
'15m': '15min',
'30m': '30min',
'1h': '60min',
'4h': '4hour',
'1d': '1day',
'1w': '1week',
'1M': '1mon',
'1y': '1year',
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/102157692-fd406280-3e90-11eb-8d46-4511b617cd17.jpg',
'api': {
'market': 'https://{hostname}/api',
'public': 'https://{hostname}/api',
'private': 'https://{hostname}/api',
},
'www': 'https://cdax.io',
'referral': 'https://cdax.io/invite?invite_code=esc74',
'doc': 'https://github.com/cloudapidoc/API_Docs',
'fees': 'https://cdax.io/about/fee',
},
'api': {
'market': {
'get': {
'history/kline': 1, # 获取K线数据
'detail/merged': 1, # 获取聚合行情(Ticker)
'depth': 1, # 获取 Market Depth 数据
'trade': 1, # 获取 Trade Detail 数据
'history/trade': 1, # 批量获取最近的交易记录
'detail': 1, # 获取 Market Detail 24小时成交量数据
'tickers': 1,
'etp': 1, # 获取杠杆ETP实时净值
},
},
'public': {
'get': {
'common/symbols': 1, # 查询系统支持的所有交易对
'common/currencys': 1, # 查询系统支持的所有币种
'common/timestamp': 1, # 查询系统当前时间
'common/exchange': 1, # order limits
'settings/currencys': 1, # ?language=en-US
},
},
'private': {
'get': {
'account/accounts': 0.2, # 查询当前用户的所有账户(即account-id)
'account/accounts/{id}/balance': 0.2, # 查询指定账户的余额
'account/accounts/{sub-uid}': 1,
'account/history': 4,
'cross-margin/loan-info': 1,
'margin/loan-info': 1, # 查询借币币息率及额度
'fee/fee-rate/get': 1,
'order/openOrders': 0.4,
'order/orders': 0.4,
'order/orders/{id}': 0.4, # 查询某个订单详情
'order/orders/{id}/matchresults': 0.4, # 查询某个订单的成交明细
'order/orders/getClientOrder': 0.4,
'order/history': 1, # 查询当前委托、历史委托
'order/matchresults': 1, # 查询当前成交、历史成交
# 'dw/withdraw-virtual/addresses', # 查询虚拟币提现地址(Deprecated)
'query/deposit-withdraw': 1,
# 'margin/loan-info', # duplicate
'margin/loan-orders': 0.2, # 借贷订单
'margin/accounts/balance': 0.2, # 借贷账户详情
'cross-margin/loan-orders': 1, # 查询借币订单
'cross-margin/accounts/balance': 1, # 借币账户详情
'points/actions': 1,
'points/orders': 1,
'subuser/aggregate-balance': 10,
'stable-coin/exchange_rate': 1,
'stable-coin/quote': 1,
},
'post': {
'account/transfer': 1, # 资产划转(该节点为母用户和子用户进行资产划转的通用接口。)
'futures/transfer': 1,
'order/batch-orders': 0.4,
'order/orders/place': 0.2, # 创建并执行一个新订单(一步下单, 推荐使用)
'order/orders/submitCancelClientOrder': 0.2,
'order/orders/batchCancelOpenOrders': 0.4,
# 'order/orders', # 创建一个新的订单请求 (仅创建订单,不执行下单)
# 'order/orders/{id}/place', # 执行一个订单 (仅执行已创建的订单)
'order/orders/{id}/submitcancel': 0.2, # 申请撤销一个订单请求
'order/orders/batchcancel': 0.4, # 批量撤销订单
# 'dw/balance/transfer', # 资产划转
'dw/withdraw/api/create': 1, # 申请提现虚拟币
# 'dw/withdraw-virtual/create', # 申请提现虚拟币
# 'dw/withdraw-virtual/{id}/place', # 确认申请虚拟币提现(Deprecated)
'dw/withdraw-virtual/{id}/cancel': 1, # 申请取消提现虚拟币
'dw/transfer-in/margin': 10, # 现货账户划入至借贷账户
'dw/transfer-out/margin': 10, # 借贷账户划出至现货账户
'margin/orders': 10, # 申请借贷
'margin/orders/{id}/repay': 10, # 归还借贷
'cross-margin/transfer-in': 1, # 资产划转
'cross-margin/transfer-out': 1, # 资产划转
'cross-margin/orders': 1, # 申请借币
'cross-margin/orders/{id}/repay': 1, # 归还借币
'stable-coin/exchange': 1,
'subuser/transfer': 10,
},
},
},
'fees': {
'trading': {
'feeSide': 'get',
'tierBased': False,
'percentage': True,
'maker': self.parse_number('0.002'),
'taker': self.parse_number('0.002'),
},
},
'exceptions': {
'broad': {
'contract is restricted of closing positions on API. Please contact customer service': OnMaintenance,
'maintain': OnMaintenance,
},
'exact': {
# err-code
'bad-request': BadRequest,
'base-date-limit-error': BadRequest, # {"status":"error","err-code":"base-date-limit-error","err-msg":"date less than system limit","data":null}
'api-not-support-temp-addr': PermissionDenied, # {"status":"error","err-code":"api-not-support-temp-addr","err-msg":"API withdrawal does not support temporary addresses","data":null}
'timeout': RequestTimeout, # {"ts":1571653730865,"status":"error","err-code":"timeout","err-msg":"Request Timeout"}
'gateway-internal-error': ExchangeNotAvailable, # {"status":"error","err-code":"gateway-internal-error","err-msg":"Failed to load data. Try again later.","data":null}
'account-frozen-balance-insufficient-error': InsufficientFunds, # {"status":"error","err-code":"account-frozen-balance-insufficient-error","err-msg":"trade account balance is not enough, left: `0.0027`","data":null}
'invalid-amount': InvalidOrder, # eg "Paramemter `amount` is invalid."
'order-limitorder-amount-min-error': InvalidOrder, # limit order amount error, min: `0.001`
'order-limitorder-amount-max-error': InvalidOrder, # market order amount error, max: `1000000`
'order-marketorder-amount-min-error': InvalidOrder, # market order amount error, min: `0.01`
'order-limitorder-price-min-error': InvalidOrder, # limit order price error
'order-limitorder-price-max-error': InvalidOrder, # limit order price error
'order-holding-limit-failed': InvalidOrder, # {"status":"error","err-code":"order-holding-limit-failed","err-msg":"Order failed, exceeded the holding limit of self currency","data":null}
'order-orderprice-precision-error': InvalidOrder, # {"status":"error","err-code":"order-orderprice-precision-error","err-msg":"order price precision error, scale: `4`","data":null}
'order-etp-nav-price-max-error': InvalidOrder, # {"status":"error","err-code":"order-etp-nav-price-max-error","err-msg":"Order price cannot be higher than 5% of NAV","data":null}
'order-orderstate-error': OrderNotFound, # canceling an already canceled order
'order-queryorder-invalid': OrderNotFound, # querying a non-existent order
'order-update-error': ExchangeNotAvailable, # undocumented error
'api-signature-check-failed': AuthenticationError,
'api-signature-not-valid': AuthenticationError, # {"status":"error","err-code":"api-signature-not-valid","err-msg":"Signature not valid: Incorrect Access key [Access key错误]","data":null}
'base-record-invalid': OrderNotFound, # https://github.com/ccxt/ccxt/issues/5750
'base-symbol-trade-disabled': BadSymbol, # {"status":"error","err-code":"base-symbol-trade-disabled","err-msg":"Trading is disabled for self symbol","data":null}
'base-symbol-error': BadSymbol, # {"status":"error","err-code":"base-symbol-error","err-msg":"The symbol is invalid","data":null}
'system-maintenance': OnMaintenance, # {"status": "error", "err-code": "system-maintenance", "err-msg": "System is in maintenance!", "data": null}
# err-msg
'invalid symbol': BadSymbol, # {"ts":1568813334794,"status":"error","err-code":"invalid-parameter","err-msg":"invalid symbol"}
'symbol trade not open now': BadSymbol, # {"ts":1576210479343,"status":"error","err-code":"invalid-parameter","err-msg":"symbol trade not open now"}
},
},
'options': {
'defaultNetwork': 'ERC20',
'networks': {
'ETH': 'erc20',
'TRX': 'trc20',
'HRC20': 'hrc20',
'HECO': 'hrc20',
'HT': 'hrc20',
'ALGO': 'algo',
'OMNI': '',
},
# https://github.com/ccxt/ccxt/issues/5376
'fetchOrdersByStatesMethod': 'private_get_order_orders', # 'private_get_order_history' # https://github.com/ccxt/ccxt/pull/5392
'fetchOpenOrdersMethod': 'fetch_open_orders_v1', # 'fetch_open_orders_v2' # https://github.com/ccxt/ccxt/issues/5388
'createMarketBuyOrderRequiresPrice': True,
'fetchBalanceMethod': 'privateGetAccountAccountsIdBalance',
'createOrderMethod': 'privatePostOrderOrdersPlace',
'language': 'en-US',
},
'commonCurrencies': {
# https://github.com/ccxt/ccxt/issues/6081
# https://github.com/ccxt/ccxt/issues/3365
# https://github.com/ccxt/ccxt/issues/2873
'GET': 'Themis', # conflict with GET(Guaranteed Entrance Token, GET Protocol)
'GTC': 'Game.com', # conflict with Gitcoin and Gastrocoin
'HIT': 'HitChain',
'HOT': 'Hydro Protocol', # conflict with HOT(Holo) https://github.com/ccxt/ccxt/issues/4929
# https://github.com/ccxt/ccxt/issues/7399
# https://coinmarketcap.com/currencies/pnetwork/
# https://coinmarketcap.com/currencies/penta/markets/
# https://en.cryptonomist.ch/blog/eidoo/the-edo-to-pnt-upgrade-what-you-need-to-know-updated/
'PNT': 'Penta',
'SBTC': 'Super Bitcoin',
'BIFI': 'Bitcoin File', # conflict with Beefy.Finance https://github.com/ccxt/ccxt/issues/8706
},
})
def fetch_time(self, params={}):
response = self.publicGetCommonTimestamp(params)
return self.safe_integer(response, 'data')
def fetch_trading_limits(self, symbols=None, params={}):
# self method should not be called directly, use loadTradingLimits() instead
# by default it will try load withdrawal fees of all currencies(with separate requests)
# however if you define symbols = ['ETH/BTC', 'LTC/BTC'] in args it will only load those
self.load_markets()
if symbols is None:
symbols = self.symbols
result = {}
for i in range(0, len(symbols)):
symbol = symbols[i]
result[symbol] = self.fetch_trading_limits_by_id(self.market_id(symbol), params)
return result
def fetch_trading_limits_by_id(self, id, params={}):
request = {
'symbol': id,
}
response = self.publicGetCommonExchange(self.extend(request, params))
#
# {
# status: "ok",
# data: {
# 'symbol': "aidocbtc",
# 'buy-limit-must-less-than': 1.1,
# 'sell-limit-must-greater-than': 0.9,
# 'limit-order-must-greater-than': 1,
# 'limit-order-must-less-than': 5000000,
# 'market-buy-order-must-greater-than': 0.0001,
# 'market-buy-order-must-less-than': 100,
# 'market-sell-order-must-greater-than': 1,
# 'market-sell-order-must-less-than': 500000,
# 'circuit-break-when-greater-than': 10000,
# 'circuit-break-when-less-than': 10,
# 'market-sell-order-rate-must-less-than': 0.1,
# 'market-buy-order-rate-must-less-than': 0.1
# }
# }
#
return self.parse_trading_limits(self.safe_value(response, 'data', {}))
def parse_trading_limits(self, limits, symbol=None, params={}):
#
# {
# 'symbol': "aidocbtc",
# 'buy-limit-must-less-than': 1.1,
# 'sell-limit-must-greater-than': 0.9,
# 'limit-order-must-greater-than': 1,
# 'limit-order-must-less-than': 5000000,
# 'market-buy-order-must-greater-than': 0.0001,
# 'market-buy-order-must-less-than': 100,
# 'market-sell-order-must-greater-than': 1,
# 'market-sell-order-must-less-than': 500000,
# 'circuit-break-when-greater-than': 10000,
# 'circuit-break-when-less-than': 10,
# 'market-sell-order-rate-must-less-than': 0.1,
# 'market-buy-order-rate-must-less-than': 0.1
# }
#
return {
'info': limits,
'limits': {
'amount': {
'min': self.safe_number(limits, 'limit-order-must-greater-than'),
'max': self.safe_number(limits, 'limit-order-must-less-than'),
},
},
}
def cost_to_precision(self, symbol, cost):
return self.decimal_to_precision(cost, TRUNCATE, self.markets[symbol]['precision']['cost'], self.precisionMode)
def fetch_markets(self, params={}):
response = self.publicGetCommonSymbols(params)
#
# {
# "status": "ok",
# "data": [
# {
# "base-currency": "ckb",
# "quote-currency": "usdt",
# "price-precision": 6,
# "amount-precision": 2,
# "symbol-partition": "default",
# "symbol": "ckbusdt",
# "state": "online",
# "value-precision": 8,
# "min-order-amt": 1,
# "max-order-amt": 140000000,
# "min-order-value": 5,
# "limit-order-min-order-amt": 1,
# "limit-order-max-order-amt": 140000000,
# "limit-order-max-buy-amt": 140000000,
# "limit-order-max-sell-amt": 140000000,
# "sell-market-min-order-amt": 1,
# "sell-market-max-order-amt": 14000000,
# "buy-market-max-order-value": 200000,
# "api-trading": "enabled",
# "tags": ""
# },
# ]
# }
#
markets = self.safe_value(response, 'data')
numMarkets = len(markets)
if numMarkets < 1:
raise NetworkError(self.id + ' publicGetCommonSymbols returned empty response: ' + self.json(markets))
result = []
for i in range(0, len(markets)):
market = markets[i]
baseId = self.safe_string(market, 'base-currency')
quoteId = self.safe_string(market, 'quote-currency')
base = self.safe_currency_code(baseId)
quote = self.safe_currency_code(quoteId)
state = self.safe_string(market, 'state')
result.append({
'id': baseId + quoteId,
'symbol': base + '/' + quote,
'base': base,
'quote': quote,
'settle': None,
'baseId': baseId,
'quoteId': quoteId,
'settleId': None,
'type': 'spot',
'spot': True,
'margin': None,
'swap': False,
'future': False,
'option': False,
'active': (state == 'online'),
'contract': False,
'linear': None,
'inverse': None,
'taker': 0 if (base == 'OMG') else 0.002,
'maker': 0 if (base == 'OMG') else 0.002,
'contractSize': None,
'expiry': None,
'expiryDatetime': None,
'strike': None,
'optionType': None,
'precision': {
'amount': self.safe_integer(market, 'amount-precision'),
'price': self.safe_integer(market, 'price-precision'),
'cost': self.safe_integer(market, 'value-precision'),
},
'limits': {
'leverage': {
'min': self.parse_number('1'),
'max': self.safe_number(market, 'leverage-ratio', 1),
'superMax': self.safe_number(market, 'super-margin-leverage-ratio', 1),
},
'amount': {
'min': self.safe_number(market, 'min-order-amt'),
'max': self.safe_number(market, 'max-order-amt'),
},
'price': {
'min': None,
'max': None,
},
'cost': {
'min': self.safe_number(market, 'min-order-value', 0),
'max': None,
},
},
'info': market,
})
return result
def parse_ticker(self, ticker, market=None):
#
# fetchTicker
#
# {
# "amount": 26228.672978342216,
# "open": 9078.95,
# "close": 9146.86,
# "high": 9155.41,
# "id": 209988544334,
# "count": 265846,
# "low": 8988.0,
# "version": 209988544334,
# "ask": [9146.87, 0.156134],
# "vol": 2.3822168242201668E8,
# "bid": [9146.86, 0.080758],
# }
#
# fetchTickers
# {
# symbol: "bhdht",
# open: 2.3938,
# high: 2.4151,
# low: 2.3323,
# close: 2.3909,
# amount: 628.992,
# vol: 1493.71841095,
# count: 2088,
# bid: 2.3643,
# bidSize: 0.7136,
# ask: 2.4061,
# askSize: 0.4156
# }
#
symbol = self.safe_symbol(None, market)
timestamp = self.safe_integer(ticker, 'ts')
bid = None
bidVolume = None
ask = None
askVolume = None
if 'bid' in ticker:
if isinstance(ticker['bid'], list):
bid = self.safe_string(ticker['bid'], 0)
bidVolume = self.safe_string(ticker['bid'], 1)
else:
bid = self.safe_string(ticker, 'bid')
bidVolume = self.safe_string(ticker, 'bidSize')
if 'ask' in ticker:
if isinstance(ticker['ask'], list):
ask = self.safe_string(ticker['ask'], 0)
askVolume = self.safe_string(ticker['ask'], 1)
else:
ask = self.safe_string(ticker, 'ask')
askVolume = self.safe_string(ticker, 'askSize')
open = self.safe_string(ticker, 'open')
close = self.safe_string(ticker, 'close')
baseVolume = self.safe_string(ticker, 'amount')
quoteVolume = self.safe_string(ticker, 'vol')
return self.safe_ticker({
'symbol': symbol,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': self.safe_string(ticker, 'high'),
'low': self.safe_string(ticker, 'low'),
'bid': bid,
'bidVolume': bidVolume,
'ask': ask,
'askVolume': askVolume,
'vwap': None,
'open': open,
'close': close,
'last': close,
'previousClose': None,
'change': None,
'percentage': None,
'average': None,
'baseVolume': baseVolume,
'quoteVolume': quoteVolume,
'info': ticker,
}, market, False)
def fetch_order_book(self, symbol, limit=None, params={}):
self.load_markets()
market = self.market(symbol)
request = {
'symbol': market['id'],
'type': 'step0',
}
response = self.marketGetDepth(self.extend(request, params))
#
# {
# "status": "ok",
# "ch": "market.btcusdt.depth.step0",
# "ts": 1583474832790,
# "tick": {
# "bids": [
# [9100.290000000000000000, 0.200000000000000000],
# [9099.820000000000000000, 0.200000000000000000],
# [9099.610000000000000000, 0.205000000000000000],
# ],
# "asks": [
# [9100.640000000000000000, 0.005904000000000000],
# [9101.010000000000000000, 0.287311000000000000],
# [9101.030000000000000000, 0.012121000000000000],
# ],
# "ts":1583474832008,
# "version":104999698780
# }
# }
#
if 'tick' in response:
if not response['tick']:
raise BadSymbol(self.id + ' fetchOrderBook() returned empty response: ' + self.json(response))
tick = self.safe_value(response, 'tick')
timestamp = self.safe_integer(tick, 'ts', self.safe_integer(response, 'ts'))
result = self.parse_order_book(tick, symbol, timestamp)
result['nonce'] = self.safe_integer(tick, 'version')
return result
raise ExchangeError(self.id + ' fetchOrderBook() returned unrecognized response: ' + self.json(response))
def fetch_ticker(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
request = {
'symbol': market['id'],
}
response = self.marketGetDetailMerged(self.extend(request, params))
#
# {
# "status": "ok",
# "ch": "market.btcusdt.detail.merged",
# "ts": 1583494336669,
# "tick": {
# "amount": 26228.672978342216,
# "open": 9078.95,
# "close": 9146.86,
# "high": 9155.41,
# "id": 209988544334,
# "count": 265846,
# "low": 8988.0,
# "version": 209988544334,
# "ask": [9146.87, 0.156134],
# "vol": 2.3822168242201668E8,
# "bid": [9146.86, 0.080758],
# }
# }
#
ticker = self.parse_ticker(response['tick'], market)
timestamp = self.safe_integer(response, 'ts')
ticker['timestamp'] = timestamp
ticker['datetime'] = self.iso8601(timestamp)
return ticker
def fetch_tickers(self, symbols=None, params={}):
self.load_markets()
response = self.marketGetTickers(params)
tickers = self.safe_value(response, 'data')
timestamp = self.safe_integer(response, 'ts')
result = {}
for i in range(0, len(tickers)):
marketId = self.safe_string(tickers[i], 'symbol')
market = self.safe_market(marketId)
symbol = market['symbol']
ticker = self.parse_ticker(tickers[i], market)
ticker['timestamp'] = timestamp
ticker['datetime'] = self.iso8601(timestamp)
result[symbol] = ticker
return self.filter_by_array(result, 'symbol', symbols)
def parse_trade(self, trade, market=None):
#
# fetchTrades(public)
#
# {
# "id": "112522757755423628681413936",
# "ts": "1638457111917",
# "trade-id": "100454385963",
# "amount": "13.7962",
# "price": "1.697867",
# "direction": "buy"
# }
#
# fetchMyTrades(private)
#
# {
# "symbol": "adausdt",
# "fee-currency": "usdt",
# "source": "spot-api",
# "order-id": "423628498050504",
# "created-at": "1638455779233",
# "role": "taker",
# "price": "1.672487",
# "match-id": "112521868633",
# "trade-id": "100454375614",
# "filled-amount": "6.8",
# "filled-fees": "0.0227458232",
# "filled-points": "0.0",
# "fee-deduct-currency": "",
# "fee-deduct-state": "done",
# "id": "422419583501532",
# "type": "sell-market"
# },
#
# fetchOrderTrades(private)
#
# {
# "symbol": "adausdt",
# "fee-currency": "usdt",
# "source": "spot-api",
# "match-id": "112521868633",
# "trade-id": "100454375614",
# "role": "taker",
# "order-id": "423628498050504",
# "price": "1.672487",
# "created-at": "1638455779233",
# "filled-amount": "6.8",
# "filled-fees": "0.0227458232",
# "filled-points": "0.0",
# "fee-deduct-currency": "",
# "fee-deduct-state": "done",
# "id": "422419583501532",
# "type": "sell-market"
# }
#
marketId = self.safe_string(trade, 'symbol')
symbol = self.safe_symbol(marketId, market)
timestamp = self.safe_integer_2(trade, 'ts', 'created-at')
order = self.safe_string(trade, 'order-id')
side = self.safe_string(trade, 'direction')
type = self.safe_string(trade, 'type')
if type is not None:
typeParts = type.split('-')
side = typeParts[0]
type = typeParts[1]
takerOrMaker = self.safe_string(trade, 'role')
priceString = self.safe_string(trade, 'price')
amountString = self.safe_string_2(trade, 'filled-amount', 'amount')
fee = None
feeCostString = self.safe_string(trade, 'filled-fees')
feeCurrency = self.safe_currency_code(self.safe_string(trade, 'fee-currency'))
filledPoints = self.safe_string(trade, 'filled-points')
if filledPoints is not None:
if (feeCostString is None) or (feeCostString == '0.0'):
feeCostString = filledPoints
feeCurrency = self.safe_currency_code(self.safe_string(trade, 'fee-deduct-currency'))
if feeCostString is not None:
fee = {
'cost': feeCostString,
'currency': feeCurrency,
}
tradeId = self.safe_string_2(trade, 'trade-id', 'tradeId')
id = self.safe_string(trade, 'id', tradeId)
return self.safe_trade({
'id': id,
'info': trade,
'order': order,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': symbol,
'type': type,
'side': side,
'takerOrMaker': takerOrMaker,
'price': priceString,
'amount': amountString,
'cost': None,
'fee': fee,
}, market)
def fetch_order_trades(self, id, symbol=None, since=None, limit=None, params={}):
self.load_markets()
request = {
'id': id,
}
response = self.privateGetOrderOrdersIdMatchresults(self.extend(request, params))
return self.parse_trades(response['data'], None, since, limit)
def fetch_my_trades(self, symbol=None, since=None, limit=None, params={}):
self.load_markets()
market = None
request = {}
if symbol is not None:
market = self.market(symbol)
request['symbol'] = market['id']
if limit is not None:
request['size'] = limit # 1-100 orders, default is 100
if since is not None:
request['start-time'] = since # a date within 120 days from today
# request['end-time'] = self.sum(since, 172800000) # 48 hours window
response = self.privateGetOrderMatchresults(self.extend(request, params))
return self.parse_trades(response['data'], market, since, limit)
def fetch_trades(self, symbol, since=None, limit=1000, params={}):
self.load_markets()
market = self.market(symbol)
request = {
'symbol': market['id'],
}
if limit is not None:
request['size'] = limit
response = self.marketGetHistoryTrade(self.extend(request, params))
#
# {
# "status": "ok",
# "ch": "market.btcusdt.trade.detail",
# "ts": 1583497692365,
# "data": [
# {
# "id": 105005170342,
# "ts": 1583497692182,
# "data": [
# {
# "amount": 0.010411000000000000,
# "trade-id": 102090736910,
# "ts": 1583497692182,
# "id": 10500517034273194594947,
# "price": 9096.050000000000000000,
# "direction": "sell"
# }
# ]
# },
# # ...
# ]
# }
#
data = self.safe_value(response, 'data')
result = []
for i in range(0, len(data)):
trades = self.safe_value(data[i], 'data', [])
for j in range(0, len(trades)):
trade = self.parse_trade(trades[j], market)
result.append(trade)
result = self.sort_by(result, 'timestamp')
return self.filter_by_symbol_since_limit(result, symbol, since, limit)
def parse_ohlcv(self, ohlcv, market=None):
#
# {
# "amount":1.2082,
# "open":0.025096,
# "close":0.025095,
# "high":0.025096,
# "id":1591515300,
# "count":6,
# "low":0.025095,
# "vol":0.0303205097
# }
#
return [
self.safe_timestamp(ohlcv, 'id'),
self.safe_number(ohlcv, 'open'),
self.safe_number(ohlcv, 'high'),
self.safe_number(ohlcv, 'low'),
self.safe_number(ohlcv, 'close'),
self.safe_number(ohlcv, 'amount'),
]
def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=1000, params={}):
self.load_markets()
market = self.market(symbol)
request = {
'symbol': market['id'],
'period': self.timeframes[timeframe],
}
if limit is not None:
request['size'] = limit
response = self.marketGetHistoryKline(self.extend(request, params))
#
# {
# "status":"ok",
# "ch":"market.ethbtc.kline.1min",
# "ts":1591515374371,
# "data":[
# {"amount":0.0,"open":0.025095,"close":0.025095,"high":0.025095,"id":1591515360,"count":0,"low":0.025095,"vol":0.0},
# {"amount":1.2082,"open":0.025096,"close":0.025095,"high":0.025096,"id":1591515300,"count":6,"low":0.025095,"vol":0.0303205097},
# {"amount":0.0648,"open":0.025096,"close":0.025096,"high":0.025096,"id":1591515240,"count":2,"low":0.025096,"vol":0.0016262208},
# ]
# }
#
data = self.safe_value(response, 'data', [])
return self.parse_ohlcvs(data, market, timeframe, since, limit)
def fetch_accounts(self, params={}):
self.load_markets()
response = self.privateGetAccountAccounts(params)
return response['data']
def fetch_currencies(self, params={}):
request = {
'language': self.options['language'],
}
response = self.publicGetSettingsCurrencys(self.extend(request, params))
#
# {
# "status":"ok",
# "data":[
# {
# "currency-addr-with-tag":false,
# "fast-confirms":12,
# "safe-confirms":12,
# "currency-type":"eth",
# "quote-currency":true,
# "withdraw-enable-timestamp":1609430400000,
# "deposit-enable-timestamp":1609430400000,
# "currency-partition":"all",
# "support-sites":["OTC","INSTITUTION","MINEPOOL"],
# "withdraw-precision":6,
# "visible-assets-timestamp":1508839200000,
# "deposit-min-amount":"1",
# "withdraw-min-amount":"10",
# "show-precision":"8",
# "tags":"",
# "weight":23,
# "full-name":"Tether USDT",
# "otc-enable":1,
# "visible":true,
# "white-enabled":false,
# "country-disabled":false,
# "deposit-enabled":true,
# "withdraw-enabled":true,
# "name":"usdt",
# "state":"online",
# "display-name":"USDT",
# "suspend-withdraw-desc":null,
# "withdraw-desc":"Minimum withdrawal amount: 10 USDT(ERC20). not >_<not To ensure the safety of your funds, your withdrawal request will be manually reviewed if your security strategy or password is changed. Please wait for phone calls or emails from our staff.not >_<not Please make sure that your computer and browser are secure and your information is protected from being tampered or leaked.",
# "suspend-deposit-desc":null,
# "deposit-desc":"Please don’t deposit any other digital assets except USDT to the above address. Otherwise, you may lose your assets permanently. not >_<not Depositing to the above address requires confirmations of the entire network. It will arrive after 12 confirmations, and it will be available to withdraw after 12 confirmations. not >_<not Minimum deposit amount: 1 USDT. Any deposits less than the minimum will not be credited or refunded.not >_<not Your deposit address won’t change often. If there are any changes, we will notify you via announcement or email.not >_<not Please make sure that your computer and browser are secure and your information is protected from being tampered or leaked.",
# "suspend-visible-desc":null
# }
# ]
# }
#
currencies = self.safe_value(response, 'data')
result = {}
for i in range(0, len(currencies)):
currency = currencies[i]
id = self.safe_value(currency, 'name')
precision = self.safe_integer(currency, 'withdraw-precision')
code = self.safe_currency_code(id)
depositEnabled = self.safe_value(currency, 'deposit-enabled')
withdrawEnabled = self.safe_value(currency, 'withdraw-enabled')
countryDisabled = self.safe_value(currency, 'country-disabled')
visible = self.safe_value(currency, 'visible', False)
state = self.safe_string(currency, 'state')
active = visible and depositEnabled and withdrawEnabled and (state == 'online') and not countryDisabled
name = self.safe_string(currency, 'display-name')
result[code] = {
'id': id,
'code': code,
'type': 'crypto',
# 'payin': currency['deposit-enabled'],
# 'payout': currency['withdraw-enabled'],
# 'transfer': None,
'name': name,
'active': active,
'deposit': depositEnabled,
'withdraw': withdrawEnabled,
'fee': None, # todo need to fetch from fee endpoint
'precision': precision,
'limits': {
'amount': {
'min': math.pow(10, -precision),
'max': math.pow(10, precision),
},
'deposit': {
'min': self.safe_number(currency, 'deposit-min-amount'),
'max': math.pow(10, precision),
},
'withdraw': {
'min': self.safe_number(currency, 'withdraw-min-amount'),
'max': math.pow(10, precision),
},
},
'info': currency,
}
return result
def parse_balance(self, response):
balances = self.safe_value(response['data'], 'list', [])
result = {'info': response}
for i in range(0, len(balances)):
balance = balances[i]
currencyId = self.safe_string(balance, 'currency')
code = self.safe_currency_code(currencyId)
account = None
if code in result:
account = result[code]
else:
account = self.account()
if balance['type'] == 'trade':
account['free'] = self.safe_string(balance, 'balance')
if balance['type'] == 'frozen':
account['used'] = self.safe_string(balance, 'balance')
result[code] = account
return self.safe_balance(result)
def fetch_balance(self, params={}):
self.load_markets()
self.load_accounts()
method = self.options['fetchBalanceMethod']
request = {
'id': self.accounts[0]['id'],
}
response = getattr(self, method)(self.extend(request, params))
return self.parse_balance(response)
def fetch_orders_by_states(self, states, symbol=None, since=None, limit=None, params={}):
self.load_markets()
request = {
'states': states,
}
market = None
if symbol is not None:
market = self.market(symbol)
request['symbol'] = market['id']
method = self.safe_string(self.options, 'fetchOrdersByStatesMethod', 'private_get_order_orders')
response = getattr(self, method)(self.extend(request, params))
#
# {status: "ok",
# data: [{ id: 13997833014,
# symbol: "ethbtc",
# 'account-id': 3398321,
# amount: "0.045000000000000000",
# price: "0.034014000000000000",
# 'created-at': 1545836976871,
# type: "sell-limit",
# 'field-amount': "0.045000000000000000",
# 'field-cash-amount': "0.001530630000000000",
# 'field-fees': "0.000003061260000000",
# 'finished-at': 1545837948214,
# source: "spot-api",
# state: "filled",
# 'canceled-at': 0 } ]}
#
return self.parse_orders(response['data'], market, since, limit)
def fetch_order(self, id, symbol=None, params={}):
self.load_markets()
request = {
'id': id,
}
response = self.privateGetOrderOrdersId(self.extend(request, params))
order = self.safe_value(response, 'data')
return self.parse_order(order)
def fetch_orders(self, symbol=None, since=None, limit=None, params={}):
return self.fetch_orders_by_states('pre-submitted,submitted,partial-filled,filled,partial-canceled,canceled', symbol, since, limit, params)
def fetch_open_orders(self, symbol=None, since=None, limit=None, params={}):
method = self.safe_string(self.options, 'fetchOpenOrdersMethod', 'fetch_open_orders_v1')
return getattr(self, method)(symbol, since, limit, params)
def fetch_open_orders_v1(self, symbol=None, since=None, limit=None, params={}):
if symbol is None:
raise ArgumentsRequired(self.id + ' fetchOpenOrdersV1() requires a symbol argument')
return self.fetch_orders_by_states('pre-submitted,submitted,partial-filled', symbol, since, limit, params)
def fetch_closed_orders(self, symbol=None, since=None, limit=None, params={}):
return self.fetch_orders_by_states('filled,partial-canceled,canceled', symbol, since, limit, params)
def fetch_open_orders_v2(self, symbol=None, since=None, limit=None, params={}):
self.load_markets()
request = {}
market = None
if symbol is not None:
market = self.market(symbol)
request['symbol'] = market['id']
accountId = self.safe_string(params, 'account-id')
if accountId is None:
# pick the first account
self.load_accounts()
for i in range(0, len(self.accounts)):
account = self.accounts[i]
if account['type'] == 'spot':
accountId = self.safe_string(account, 'id')
if accountId is not None:
break
request['account-id'] = accountId
if limit is not None:
request['size'] = limit
omitted = self.omit(params, 'account-id')
response = self.privateGetOrderOpenOrders(self.extend(request, omitted))
#
# {
# "status":"ok",
# "data":[
# {
# "symbol":"ethusdt",
# "source":"api",
# "amount":"0.010000000000000000",
# "account-id":1528640,
# "created-at":1561597491963,
# "price":"400.000000000000000000",
# "filled-amount":"0.0",
# "filled-cash-amount":"0.0",
# "filled-fees":"0.0",
# "id":38477101630,
# "state":"submitted",
# "type":"sell-limit"
# }
# ]
# }
#
data = self.safe_value(response, 'data', [])
return self.parse_orders(data, market, since, limit)
def parse_order_status(self, status):
statuses = {
'partial-filled': 'open',
'partial-canceled': 'canceled',
'filled': 'closed',
'canceled': 'canceled',
'submitted': 'open',
}
return self.safe_string(statuses, status, status)
def parse_order(self, order, market=None):
#
# { id: 13997833014,
# symbol: "ethbtc",
# 'account-id': 3398321,
# amount: "0.045000000000000000",
# price: "0.034014000000000000",
# 'created-at': 1545836976871,
# type: "sell-limit",
# 'field-amount': "0.045000000000000000", # they have fixed it for filled-amount
# 'field-cash-amount': "0.001530630000000000", # they have fixed it for filled-cash-amount
# 'field-fees': "0.000003061260000000", # they have fixed it for filled-fees
# 'finished-at': 1545837948214,
# source: "spot-api",
# state: "filled",
# 'canceled-at': 0 }
#
# { id: 20395337822,
# symbol: "ethbtc",
# 'account-id': 5685075,
# amount: "0.001000000000000000",
# price: "0.0",
# 'created-at': 1545831584023,
# type: "buy-market",
# 'field-amount': "0.029100000000000000", # they have fixed it for filled-amount
# 'field-cash-amount': "0.000999788700000000", # they have fixed it for filled-cash-amount
# 'field-fees': "0.000058200000000000", # they have fixed it for filled-fees
# 'finished-at': 1545831584181,
# source: "spot-api",
# state: "filled",
# 'canceled-at': 0 }
#
id = self.safe_string(order, 'id')
side = None
type = None
status = self.parse_order_status(self.safe_string(order, 'state'))
orderType = self.safe_string(order, 'type')
if orderType is not None:
parts = orderType.split('-')
side = self.safe_string(parts, 0)
type = self.safe_string(parts, 1)
marketId = self.safe_string(order, 'symbol')
market = self.safe_market(marketId, market)
timestamp = self.safe_integer(order, 'created-at')
clientOrderId = self.safe_string(order, 'client-order-id')
filledString = self.safe_string_2(order, 'filled-amount', 'field-amount') # typo in their API, filled amount
priceString = self.safe_string(order, 'price')
costString = self.safe_string_2(order, 'filled-cash-amount', 'field-cash-amount') # same typo
amountString = self.safe_string(order, 'amount')
if orderType == 'buy-market':
amountString = None
feeCostString = self.safe_string_2(order, 'filled-fees', 'field-fees') # typo in their API, filled fees
fee = None
if feeCostString is not None:
feeCurrency = market['quote'] if (side == 'sell') else market['base']
fee = {
'cost': feeCostString,
'currency': feeCurrency,
}
return self.safe_order({
'info': order,
'id': id,
'clientOrderId': clientOrderId,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'lastTradeTimestamp': None,
'symbol': market['symbol'],
'type': type,
'timeInForce': None,
'postOnly': None,
'side': side,
'price': priceString,
'stopPrice': None,
'average': None,
'cost': costString,
'amount': amountString,
'filled': filledString,
'remaining': None,
'status': status,
'fee': fee,
'trades': None,
}, market)
def create_order(self, symbol, type, side, amount, price=None, params={}):
self.load_markets()
self.load_accounts()
market = self.market(symbol)
request = {
'account-id': self.accounts[0]['id'],
'symbol': market['id'],
'type': side + '-' + type,
}
clientOrderId = self.safe_string_2(params, 'clientOrderId', 'client-order-id') # must be 64 chars max and unique within 24 hours
if clientOrderId is None:
broker = self.safe_value(self.options, 'broker', {})
brokerId = self.safe_string(broker, 'id')
request['client-order-id'] = brokerId + self.uuid()
else:
request['client-order-id'] = clientOrderId
params = self.omit(params, ['clientOrderId', 'client-order-id'])
if (type == 'market') and (side == 'buy'):
if self.options['createMarketBuyOrderRequiresPrice']:
if price is None:
raise InvalidOrder(self.id + " market buy order requires price argument to calculate cost(total amount of quote currency to spend for buying, amount * price). To switch off self warning exception and specify cost in the amount argument, set .options['createMarketBuyOrderRequiresPrice'] = False. Make sure you know what you're doing.")
else:
# despite that cost = amount * price is in quote currency and should have quote precision
# the exchange API requires the cost supplied in 'amount' to be of base precision
# more about it here:
# https://github.com/ccxt/ccxt/pull/4395
# https://github.com/ccxt/ccxt/issues/7611
# we use amountToPrecision here because the exchange requires cost in base precision
request['amount'] = self.cost_to_precision(symbol, float(amount) * float(price))
else:
request['amount'] = self.cost_to_precision(symbol, amount)
else:
request['amount'] = self.amount_to_precision(symbol, amount)
if type == 'limit' or type == 'ioc' or type == 'limit-maker' or type == 'stop-limit' or type == 'stop-limit-fok':
request['price'] = self.price_to_precision(symbol, price)
method = self.options['createOrderMethod']
response = getattr(self, method)(self.extend(request, params))
timestamp = self.milliseconds()
id = self.safe_string(response, 'data')
return {
'info': response,
'id': id,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'lastTradeTimestamp': None,
'status': None,
'symbol': symbol,
'type': type,
'side': side,
'price': price,
'amount': amount,
'filled': None,
'remaining': None,
'cost': None,
'trades': None,
'fee': None,
'clientOrderId': None,
'average': None,
}
def cancel_order(self, id, symbol=None, params={}):
response = self.privatePostOrderOrdersIdSubmitcancel({'id': id})
#
# {
# 'status': 'ok',
# 'data': '10138899000',
# }
#
return self.extend(self.parse_order(response), {
'id': id,
'status': 'canceled',
})
def cancel_orders(self, ids, symbol=None, params={}):
self.load_markets()
clientOrderIds = self.safe_value_2(params, 'clientOrderIds', 'client-order-ids')
params = self.omit(params, ['clientOrderIds', 'client-order-ids'])
request = {}
if clientOrderIds is None:
request['order-ids'] = ids
else:
request['client-order-ids'] = clientOrderIds
response = self.privatePostOrderOrdersBatchcancel(self.extend(request, params))
#
# {
# "status": "ok",
# "data": {
# "success": [
# "5983466"
# ],
# "failed": [
# {
# "err-msg": "Incorrect order state",
# "order-state": 7,
# "order-id": "",
# "err-code": "order-orderstate-error",
# "client-order-id": "first"
# },
# {
# "err-msg": "Incorrect order state",
# "order-state": 7,
# "order-id": "",
# "err-code": "order-orderstate-error",
# "client-order-id": "second"
# },
# {
# "err-msg": "The record is not found.",
# "order-id": "",
# "err-code": "base-not-found",
# "client-order-id": "third"
# }
# ]
# }
# }
#
return response
def cancel_all_orders(self, symbol=None, params={}):
self.load_markets()
request = {
# 'account-id' string False NA The account id used for self cancel Refer to GET /v1/account/accounts
# 'symbol': market['id'], # a list of comma-separated symbols, all symbols by default
# 'types' 'string', buy-market, sell-market, buy-limit, sell-limit, buy-ioc, sell-ioc, buy-stop-limit, sell-stop-limit, buy-limit-fok, sell-limit-fok, buy-stop-limit-fok, sell-stop-limit-fok
# 'side': 'buy', # or 'sell'
# 'size': 100, # the number of orders to cancel 1-100
}
market = None
if symbol is not None:
market = self.market(symbol)
request['symbol'] = market['id']
response = self.privatePostOrderOrdersBatchCancelOpenOrders(self.extend(request, params))
#
# {
# code: 200,
# data: {
# "success-count": 2,
# "failed-count": 0,
# "next-id": 5454600
# }
# }
#
return response
def currency_to_precision(self, currency, fee):
return self.decimal_to_precision(fee, 0, self.currencies[currency]['precision'])
def safe_network(self, networkId):
lastCharacterIndex = len(networkId) - 1
lastCharacter = networkId[lastCharacterIndex]
if lastCharacter == '1':
networkId = networkId[0:lastCharacterIndex]
networksById = {}
return self.safe_string(networksById, networkId, networkId)
def parse_deposit_address(self, depositAddress, currency=None):
#
# {
# currency: "usdt",
# address: "0xf7292eb9ba7bc50358e27f0e025a4d225a64127b",
# addressTag: "",
# chain: "usdterc20", # trc20usdt, hrc20usdt, usdt, algousdt
# }
#
address = self.safe_string(depositAddress, 'address')
tag = self.safe_string(depositAddress, 'addressTag')
if tag == '':
tag = None
currencyId = self.safe_string(depositAddress, 'currency')
currency = self.safe_currency(currencyId, currency)
code = self.safe_currency_code(currencyId, currency)
networkId = self.safe_string(depositAddress, 'chain')
networks = self.safe_value(currency, 'networks', {})
networksById = self.index_by(networks, 'id')
networkValue = self.safe_value(networksById, networkId, networkId)
network = self.safe_string(networkValue, 'network')
self.check_address(address)
return {
'currency': code,
'address': address,
'tag': tag,
'network': network,
'info': depositAddress,
}
def fetch_deposits(self, code=None, since=None, limit=None, params={}):
if limit is None or limit > 100:
limit = 100
self.load_markets()
currency = None
if code is not None:
currency = self.currency(code)
request = {
'type': 'deposit',
'from': 0, # From 'id' ... if you want to get results after a particular transaction id, pass the id in params.from
}
if currency is not None:
request['currency'] = currency['id']
if limit is not None:
request['size'] = limit # max 100
response = self.privateGetQueryDepositWithdraw(self.extend(request, params))
# return response
return self.parse_transactions(response['data'], currency, since, limit)
def fetch_withdrawals(self, code=None, since=None, limit=None, params={}):
if limit is None or limit > 100:
limit = 100
self.load_markets()
currency = None
if code is not None:
currency = self.currency(code)
request = {
'type': 'withdraw',
'from': 0, # From 'id' ... if you want to get results after a particular transaction id, pass the id in params.from
}
if currency is not None:
request['currency'] = currency['id']
if limit is not None:
request['size'] = limit # max 100
response = self.privateGetQueryDepositWithdraw(self.extend(request, params))
# return response
return self.parse_transactions(response['data'], currency, since, limit)
def parse_transaction(self, transaction, currency=None):
#
# fetchDeposits
#
# {
# 'id': 8211029,
# 'type': 'deposit',
# 'currency': 'eth',
# 'chain': 'eth',
# 'tx-hash': 'bd315....',
# 'amount': 0.81162421,
# 'address': '4b8b....',
# 'address-tag': '',
# 'fee': 0,
# 'state': 'safe',
# 'created-at': 1542180380965,
# 'updated-at': 1542180788077
# }
#
# fetchWithdrawals
#
# {
# 'id': 6908275,
# 'type': 'withdraw',
# 'currency': 'btc',
# 'chain': 'btc',
# 'tx-hash': 'c1a1a....',
# 'amount': 0.80257005,
# 'address': '1QR....',
# 'address-tag': '',
# 'fee': 0.0005,
# 'state': 'confirmed',
# 'created-at': 1552107295685,
# 'updated-at': 1552108032859
# }
#
timestamp = self.safe_integer(transaction, 'created-at')
updated = self.safe_integer(transaction, 'updated-at')
code = self.safe_currency_code(self.safe_string(transaction, 'currency'))
type = self.safe_string(transaction, 'type')
if type == 'withdraw':
type = 'withdrawal'
status = self.parse_transaction_status(self.safe_string(transaction, 'state'))
tag = self.safe_string(transaction, 'address-tag')
feeCost = self.safe_number(transaction, 'fee')
if feeCost is not None:
feeCost = abs(feeCost)
address = self.safe_string(transaction, 'address')
network = self.safe_string_upper(transaction, 'chain')
return {
'info': transaction,
'id': self.safe_string(transaction, 'id'),
'txid': self.safe_string(transaction, 'tx-hash'),
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'network': network,
'address': address,
'addressTo': None,
'addressFrom': None,
'tag': tag,
'tagTo': None,
'tagFrom': None,
'type': type,
'amount': self.safe_number(transaction, 'amount'),
'currency': code,
'status': status,
'updated': updated,
'fee': {
'currency': code,
'cost': feeCost,
'rate': None,
},
}
def parse_transaction_status(self, status):
statuses = {
# deposit statuses
'unknown': 'failed',
'confirming': 'pending',
'confirmed': 'ok',
'safe': 'ok',
'orphan': 'failed',
# withdrawal statuses
'submitted': 'pending',
'canceled': 'canceled',
'reexamine': 'pending',
'reject': 'failed',
'pass': 'pending',
'wallet-reject': 'failed',
# 'confirmed': 'ok', # present in deposit statuses
'confirm-error': 'failed',
'repealed': 'failed',
'wallet-transfer': 'pending',
'pre-transfer': 'pending',
}
return self.safe_string(statuses, status, status)
def withdraw(self, code, amount, address, tag=None, params={}):
tag, params = self.handle_withdraw_tag_and_params(tag, params)
self.load_markets()
self.check_address(address)
currency = self.currency(code)
request = {
'address': address, # only supports existing addresses in your withdraw address list
'amount': amount,
'currency': currency['id'].lower(),
}
if tag is not None:
request['addr-tag'] = tag # only for XRP?
networks = self.safe_value(self.options, 'networks', {})
network = self.safe_string_upper(params, 'network') # self line allows the user to specify either ERC20 or ETH
network = self.safe_string_lower(networks, network, network) # handle ETH>ERC20 alias
if network is not None:
# possible chains - usdterc20, trc20usdt, hrc20usdt, usdt, algousdt
if network == 'erc20':
request['chain'] = currency['id'] + network
else:
request['chain'] = network + currency['id']
params = self.omit(params, 'network')
response = self.privatePostDwWithdrawApiCreate(self.extend(request, params))
id = self.safe_string(response, 'data')
return {
'info': response,
'id': id,
}
def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = '/'
if api == 'market':
url += api
elif (api == 'public') or (api == 'private'):
url += self.version
elif (api == 'v2Public') or (api == 'v2Private'):
url += 'v2'
url += '/' + self.implode_params(path, params)
query = self.omit(params, self.extract_params(path))
if api == 'private' or api == 'v2Private':
self.check_required_credentials()
timestamp = self.ymdhms(self.milliseconds(), 'T')
request = {
'SignatureMethod': 'HmacSHA256',
'SignatureVersion': '2',
'AccessKeyId': self.apiKey,
'Timestamp': timestamp,
}
if method != 'POST':
request = self.extend(request, query)
request = self.keysort(request)
auth = self.urlencode(request)
# unfortunately, PHP demands double quotes for the escaped newline symbol
# eslint-disable-next-line quotes
payload = "\n".join([method, self.hostname, url, auth])
signature = self.hmac(self.encode(payload), self.encode(self.secret), hashlib.sha256, 'base64')
auth += '&' + self.urlencode({'Signature': signature})
url += '?' + auth
if method == 'POST':
body = self.json(query)
headers = {
'Content-Type': 'application/json',
}
else:
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
}
else:
if params:
url += '?' + self.urlencode(params)
url = self.implode_params(self.urls['api'][api], {
'hostname': self.hostname,
}) + url
return {'url': url, 'method': method, 'body': body, 'headers': headers}
def calculate_rate_limiter_cost(self, api, method, path, params, config={}, context={}):
return self.safe_integer(config, 'cost', 1)
def handle_errors(self, httpCode, reason, url, method, headers, body, response, requestHeaders, requestBody):
if response is None:
return # fallback to default error handler
if 'status' in response:
#
# {"status":"error","err-code":"order-limitorder-amount-min-error","err-msg":"limit order amount error, min: `0.001`","data":null}
#
status = self.safe_string(response, 'status')
if status == 'error':
code = self.safe_string(response, 'err-code')
feedback = self.id + ' ' + body
self.throw_broadly_matched_exception(self.exceptions['broad'], body, feedback)
self.throw_exactly_matched_exception(self.exceptions['exact'], code, feedback)
message = self.safe_string(response, 'err-msg')
self.throw_exactly_matched_exception(self.exceptions['exact'], message, feedback)
raise ExchangeError(feedback)
|
/**
* Copyright (c) Matthieu Jabbour. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
/* eslint-disable no-console */
/* eslint-disable import/no-unresolved */
process.env.NODE_ENV = 'development';
const fs = require('fs-extra');
const path = require('path');
const express = require('express');
const webpack = require('webpack');
const { spawn } = require('child_process');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const packageJson = require('../../../package.json');
const config = require('../config/webpack.config.dev');
const distPath = config.output.path;
const compiler = webpack(config);
const random = () => Math.floor(Math.random() * 10);
let nodeProcess = null;
// For front-end projects, we setup a dev server to leverage on HMR and Hot Reloading.
if (config.target === 'web') {
const server = express();
// Removing existing `dist` directory...
fs.remove(distPath)
// Running webpack compiler...
.then(() => {
// `webpack-dev-middleware` package enables Webpack to be run as a server in watch mode,
// for a better development experience.
// We use it instead of `webpack-dev-server` package because it offers more flexibility and
// control over the server.
const devMiddleware = webpackDevMiddleware(compiler, {
index: 'index.html',
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, PATCH, OPTIONS',
},
});
devMiddleware.waitUntilValid(() => {
console.log(`\n\x1B[0m\x1B[32m\x1B[1m ✔️ Dev server is listening at http://${config.devServer.ip}:${config.devServer.port} \x1B[0m\n`);
});
server.use(devMiddleware);
// `webpack-hot-middleware` package enables HMR, along with a dev server.
server.use(webpackHotMiddleware(compiler, {
path: '/assets/_hmr',
heartbeat: 2000,
}));
// Serves all static assets.
server.use(express.static(path.resolve(config.output.path, '..')));
// Catch-all to redirect any request to the main entry point (index.html).
server.get('*', (_request, response, next) => {
const filePath = path.resolve(config.output.path, '../index.html');
compiler.outputFileSystem.readFile(filePath, (error, content) => {
if (error !== null) {
next(error);
} else {
response.set('content-type', 'text/html');
response.send(content);
response.end();
}
});
});
server.listen(config.devServer.port, config.devServer.ip);
})
// If any error occurs...
.catch((error) => {
console.error('\x1B[0m\x1B[31m\x1B[1m ✖ Compilation failed: \x1B[0m\n');
console.error(error.message);
});
} else {
// Removing existing `dist` directory...
fs.remove(distPath)
// Running webpack compiler...
.then(() => {
compiler.watch({}, (error, stats) => {
console.log(stats.toString({
colors: true,
cached: true,
performance: true,
modules: false,
children: false,
excludeAssets: [/\.d\.ts$/i],
}));
if (!stats.hasErrors()) {
try {
// Writing distributable `package.json` file into `dist` directory...
fs.writeJsonSync(path.join(distPath, 'package.json'), {
name: packageJson.name,
main: packageJson.main,
types: packageJson.types,
bugs: packageJson.bugs,
author: packageJson.author,
// This tricks forces invalidating webpack cache and allows real-time package testing.
// See https://github.com/webpack/webpack/issues/11612.
version: [random(), random(), random()].join('.'),
engines: packageJson.engines,
license: packageJson.license,
keywords: packageJson.keywords,
homepage: packageJson.homepage,
repository: packageJson.repository,
description: packageJson.description,
contributors: packageJson.contributors,
dependencies: packageJson.dependencies,
peerDependencies: packageJson.peerDependencies,
}, { spaces: 2 });
// For back-end projects, the final bundle can be executed after each compilation.
// This is especially useful when developing a NodeJS server for instance.
if (packageJson.tsDevKitConfig.runInDev === true) {
if (nodeProcess !== null) {
nodeProcess.kill('SIGKILL');
nodeProcess = null;
}
nodeProcess = spawn('node', [path.join(distPath, packageJson.main)]);
nodeProcess.stdout.on('data', (data) => {
console.log(data.toString());
});
nodeProcess.stderr.on('data', (data) => {
console.error('\n\x1B[0m\x1B[31m\x1B[1m ✖ Error occurred in main entry: \x1B[0m\n');
console.error(data.toString());
console.error('');
});
nodeProcess.on('error', (...args) => {
console.error('\n\x1B[0m\x1B[31m\x1B[1m ✖ Could not run main entry: \x1B[0m\n');
console.error(args[0]);
console.error('');
});
}
} catch (fsError) {
console.error('\x1B[0m\x1B[31m\x1B[1m ✖ Compilation failed: \x1B[0m\n');
console.error(fsError.message);
}
}
});
})
// If any error occurs...
.catch((error) => {
console.error('\x1B[0m\x1B[31m\x1B[1m ✖ Compilation failed: \x1B[0m\n');
console.error(error.message);
});
}
|
#! /usr/bin/env python
"""A module for authenticating against and communicating with selected
parts of the Garmin Connect REST API.
"""
import json
import logging
import os
import os.path
import re
import sys
import zipfile
from datetime import timedelta, datetime
from builtins import range
from functools import wraps
from io import BytesIO
import dateutil
import dateutil.parser
import requests
from garminexport.retryer import Retryer, ExponentialBackoffDelayStrategy, MaxRetriesStopStrategy
#
# Note: For more detailed information about the API services
# used by this module, log in to your Garmin Connect account
# through the web browser and visit the API documentation page
# for the REST service of interest. For example:
# https://connect.garmin.com/proxy/activity-service-1.3/index.html
# https://connect.garmin.com/proxy/activity-search-service-1.2/index.html
#
#
# Other useful references:
# https://github.com/cpfair/tapiriik/blob/master/tapiriik/services/GarminConnect/garminconnect.py
# https://forums.garmin.com/showthread.php?72150-connect-garmin-com-signin-question/page2
#
log = logging.getLogger(__name__)
# reduce logging noise from requests library
logging.getLogger("requests").setLevel(logging.ERROR)
SSO_LOGIN_URL = "https://sso.garmin.com/sso/login"
"""Garmin Connect's Single-Sign On login URL."""
SSO_SIGNIN_URL = "https://sso.garmin.com/sso/signin"
"""The Garmin Connect Single-Sign On sign-in URL. This is where the login form
gets POSTed."""
def require_session(client_function):
"""Decorator that is used to annotate :class:`GarminClient`
methods that need an authenticated session before being called.
"""
@wraps(client_function)
def check_session(*args, **kwargs):
client_object = args[0]
if not client_object.session:
raise Exception("Attempt to use GarminClient without being connected. Call connect() before first use.'")
return client_function(*args, **kwargs)
return check_session
class GarminClient(object):
"""A client class used to authenticate with Garmin Connect and
extract data from the user account.
Since this class implements the context manager protocol, this object
can preferably be used together with the with-statement. This will
automatically take care of logging in to Garmin Connect before any
further interactions and logging out after the block completes or
a failure occurs.
Example of use: ::
with GarminClient("my.sample@sample.com", "secretpassword") as client:
ids = client.list_activities()
for activity_id in ids:
gpx = client.get_activity_gpx(activity_id[0])
"""
def __init__(self, username, password, user_agent_fn=None):
"""Initialize a :class:`GarminClient` instance.
:param username: Garmin Connect user name or email address.
:type username: str
:param password: Garmin Connect account password.
:type password: str
:keyword user_agent_fn: A function that, when called, produces a
`User-Agent` string to be used as `User-Agent` for the remainder of the
session. If set to None, the default user agent of the http request
library is used.
:type user_agent_fn: Callable[[], str]
"""
self.username = username
self.password = password
self._user_agent_fn = user_agent_fn
self.session = None
def __enter__(self):
self.connect()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.disconnect()
def connect(self):
self.session = requests.Session()
self._authenticate()
def disconnect(self):
if self.session:
self.session.close()
self.session = None
def _authenticate(self):
log.info("authenticating user ...")
form_data = {
"username": self.username,
"password": self.password,
"embed": "false",
"_csrf": self._get_csrf_token(),
}
headers = {
'origin': 'https://sso.garmin.com',
}
if self._user_agent_fn:
user_agent = self._user_agent_fn()
if not user_agent:
raise ValueError("user_agent_fn didn't produce a value")
headers['User-Agent'] = user_agent
auth_response = self.session.post(
SSO_SIGNIN_URL, headers=headers, params=self._auth_params(), data=form_data)
log.debug("got auth response: %s", auth_response.text)
if auth_response.status_code != 200:
raise ValueError("authentication failure: did you enter valid credentials?")
auth_ticket_url = self._extract_auth_ticket_url(auth_response.text)
log.debug("auth ticket url: '%s'", auth_ticket_url)
log.info("claiming auth ticket ...")
response = self.session.get(auth_ticket_url)
if response.status_code != 200:
raise RuntimeError(
"auth failure: failed to claim auth ticket: {}: {}\n{}".format(
auth_ticket_url, response.status_code, response.text))
# appears like we need to touch base with the main page to complete the
# login ceremony.
self.session.get('https://connect.garmin.com/modern')
def _get_csrf_token(self):
"""Retrieves a Cross-Site Request Forgery (CSRF) token from Garmin's login
page. The token is passed along in the login form for increased
security."""
log.info("fetching CSRF token ...")
resp = self.session.get(SSO_LOGIN_URL, params=self._auth_params())
if resp.status_code != 200:
raise ValueError("auth failure: could not load {}".format(SSO_LOGIN_URL))
# extract CSRF token
csrf_token = re.search(r'<input type="hidden" name="_csrf" value="(\w+)"',
resp.content.decode('utf-8'))
if not csrf_token:
raise ValueError("auth failure: no CSRF token in {}".format(SSO_LOGIN_URL))
return csrf_token.group(1)
def _auth_params(self):
"""A set of request query parameters that need to be present for Garmin to
accept our login attempt.
"""
return {
"service": "https://connect.garmin.com/modern/",
"gauthHost": "https://sso.garmin.com/sso",
}
@staticmethod
def _extract_auth_ticket_url(auth_response):
"""Extracts an authentication ticket URL from the response of an
authentication form submission. The auth ticket URL is typically
of form:
https://connect.garmin.com/modern?ticket=ST-0123456-aBCDefgh1iJkLmN5opQ9R-cas
:param auth_response: HTML response from an auth form submission.
"""
match = re.search(r'response_url\s*=\s*"(https:[^"]+)"', auth_response)
if not match:
raise RuntimeError(
"auth failure: unable to extract auth ticket URL. did you provide a correct username/password?")
auth_ticket_url = match.group(1).replace("\\", "")
return auth_ticket_url
@require_session
def list_activities(self, request_size=sys.maxsize):
"""Return activity ids stored by the logged in user, along
with their starting timestamps.
:param request_size: number of activities to return, default is all
:type request_size: int
:returns: The full list of activity identifiers (along with their starting timestamps).
:rtype: tuples of (int, datetime)
"""
ids = []
batch_size = 100
if request_size < batch_size:
batch_size = request_size
# fetch in batches since the API doesn't allow more than a certain
# number of activities to be retrieved on every invocation
for start_index in range(0, request_size, batch_size):
next_batch = self._fetch_activity_ids_and_ts(start_index, batch_size)
if not next_batch:
break
ids.extend(next_batch)
return ids
@require_session
def _fetch_activity_ids_and_ts(self, start_index, max_limit=100):
"""Return a sequence of activity ids (along with their starting
timestamps) starting at a given index, with index 0 being the user's
most recently registered activity.
Should the index be out of bounds or the account empty, an empty list is returned.
:param start_index: The index of the first activity to retrieve.
:type start_index: int
:param max_limit: The (maximum) number of activities to retrieve.
:type max_limit: int
:returns: A list of activity identifiers (along with their starting timestamps).
:rtype: tuples of (int, datetime)
"""
log.debug("fetching activities %d through %d ...", start_index, start_index + max_limit - 1)
response = self.session.get(
"https://connect.garmin.com/proxy/activitylist-service/activities/search/activities",
params={"start": start_index, "limit": max_limit})
if response.status_code != 200:
raise Exception(
u"failed to fetch activities {} to {} types: {}\n{}".format(
start_index, (start_index + max_limit - 1), response.status_code, response.text))
activities = json.loads(response.text)
if not activities:
# index out of bounds or empty account
return []
entries = []
for activity in activities:
id = int(activity["activityId"])
timestamp_utc = dateutil.parser.parse(activity["startTimeGMT"])
# make sure UTC timezone gets set
timestamp_utc = timestamp_utc.replace(tzinfo=dateutil.tz.tzutc())
entries.append((id, timestamp_utc))
log.debug("got %d activities.", len(entries))
return entries
@require_session
def get_activity_summary(self, activity_id):
"""Return a summary about a given activity.
The summary contains several statistics, such as duration, GPS starting
point, GPS end point, elevation gain, max heart rate, max pace, max speed, etc).
:param activity_id: Activity identifier.
:type activity_id: int
:returns: The activity summary as a JSON dict.
:rtype: dict
"""
response = self.session.get(
"https://connect.garmin.com/proxy/activity-service/activity/{}".format(activity_id))
if response.status_code != 200:
log.error(u"failed to fetch json summary for activity %s: %d\n%s",
activity_id, response.status_code, response.text)
raise Exception(u"failed to fetch json summary for activity {}: {}\n{}".format(
activity_id, response.status_code, response.text))
return json.loads(response.text)
@require_session
def get_activity_details(self, activity_id):
"""Return a JSON representation of a given activity including
available measurements such as location (longitude, latitude),
heart rate, distance, pace, speed, elevation.
:param activity_id: Activity identifier.
:type activity_id: int
:returns: The activity details as a JSON dict.
:rtype: dict
"""
# mounted at xml or json depending on result encoding
response = self.session.get(
"https://connect.garmin.com/proxy/activity-service/activity/{}/details".format(activity_id))
if response.status_code != 200:
raise Exception(u"failed to fetch json activityDetails for {}: {}\n{}".format(
activity_id, response.status_code, response.text))
return json.loads(response.text)
@require_session
def get_activity_gpx(self, activity_id):
"""Return a GPX (GPS Exchange Format) representation of a
given activity. If the activity cannot be exported to GPX
(not yet observed in practice, but that doesn't exclude the
possibility), a :obj:`None` value is returned.
:param activity_id: Activity identifier.
:type activity_id: int
:returns: The GPX representation of the activity as an XML string
or ``None`` if the activity couldn't be exported to GPX.
:rtype: str
"""
response = self.session.get(
"https://connect.garmin.com/proxy/download-service/export/gpx/activity/{}".format(activity_id))
# An alternate URL that seems to produce the same results
# and is the one used when exporting through the Garmin
# Connect web page.
# response = self.session.get("https://connect.garmin.com/proxy/activity-service-1.1/gpx/activity/{}?full=true".format(activity_id))
# A 404 (Not Found) or 204 (No Content) response are both indicators
# of a gpx file not being available for the activity. It may, for
# example be a manually entered activity without any device data.
if response.status_code in (404, 204):
return None
if response.status_code != 200:
raise Exception(u"failed to fetch GPX for activity {}: {}\n{}".format(
activity_id, response.status_code, response.text))
return response.text
@require_session
def get_activity_tcx(self, activity_id):
"""Return a TCX (Training Center XML) representation of a
given activity. If the activity doesn't have a TCX source (for
example, if it was originally uploaded in GPX format, Garmin
won't try to synthesize a TCX file) a :obj:`None` value is
returned.
:param activity_id: Activity identifier.
:type activity_id: int
:returns: The TCX representation of the activity as an XML string
or ``None`` if the activity cannot be exported to TCX.
:rtype: str
"""
response = self.session.get(
"https://connect.garmin.com/proxy/download-service/export/tcx/activity/{}".format(activity_id))
if response.status_code == 404:
return None
if response.status_code != 200:
raise Exception(u"failed to fetch TCX for activity {}: {}\n{}".format(
activity_id, response.status_code, response.text))
return response.text
def get_original_activity(self, activity_id):
"""Return the original file that was uploaded for an activity.
If the activity doesn't have any file source (for example,
if it was entered manually rather than imported from a Garmin
device) then :obj:`(None,None)` is returned.
:param activity_id: Activity identifier.
:type activity_id: int
:returns: A tuple of the file type (e.g. 'fit', 'tcx', 'gpx') and
its contents, or :obj:`(None,None)` if no file is found.
:rtype: (str, str)
"""
response = self.session.get(
"https://connect.garmin.com/proxy/download-service/files/activity/{}".format(activity_id))
# A 404 (Not Found) response is a clear indicator of a missing .fit
# file. As of lately, the endpoint appears to have started to
# respond with 500 "NullPointerException" on attempts to download a
# .fit file for an activity without one.
if response.status_code in [404, 500]:
# Manually entered activity, no file source available
return None, None
if response.status_code != 200:
raise Exception(
u"failed to get original activity file for {}: {}\n{}".format(
activity_id, response.status_code, response.text))
# return the first entry from the zip archive where the filename is
# activity_id (should be the only entry!)
zip_file = zipfile.ZipFile(BytesIO(response.content), mode="r")
for path in zip_file.namelist():
fn, ext = os.path.splitext(path)
if fn.startswith(str(activity_id)):
return ext[1:], zip_file.open(path).read()
return None, None
def get_activity_fit(self, activity_id):
"""Return a FIT representation for a given activity. If the activity
doesn't have a FIT source (for example, if it was entered manually
rather than imported from a Garmin device) a :obj:`None` value is
returned.
:param activity_id: Activity identifier.
:type activity_id: int
:returns: A string with a FIT file for the activity or :obj:`None`
if no FIT source exists for this activity (e.g., entered manually).
:rtype: str
"""
fmt, orig_file = self.get_original_activity(activity_id)
# if the file extension of the original activity file isn't 'fit',
# this activity was uploaded in a different format (e.g. gpx/tcx)
# and cannot be exported to fit
return orig_file if fmt == 'fit' else None
@require_session
def _poll_upload_completion(self, uuid, creation_date):
"""Poll for completion of an upload. If Garmin connect returns
HTTP status 202 ("Accepted") after initial upload, then we must poll
until the upload has either succeeded or failed. Raises an
:class:`Exception` if the upload has failed.
:param uuid: uploadUuid returned on initial upload.
:type uuid: str
:param creation_date: creationDate returned from initial upload (e.g.
"2020-01-01 12:34:56.789 GMT")
:type creation_date: str
:returns: Garmin's internalId for the newly-created activity, or
:obj:`None` if upload is still processing.
:rtype: int
"""
response = self.session.get("https://connect.garmin.com/proxy/activity-service/activity/status/{}/{}?_={}".format(
creation_date[:10], uuid.replace("-",""), int(datetime.now().timestamp()*1000)), headers={"nk": "NT"})
if response.status_code == 201 and response.headers["location"]:
# location should be https://connectapi.garmin.com/activity-service/activity/ACTIVITY_ID
return int(response.headers["location"].split("/")[-1])
elif response.status_code == 202:
return None # still processing
else:
response.raise_for_status()
@require_session
def upload_activity(self, file, format=None, name=None, description=None, activity_type=None, private=None):
"""Upload a GPX, TCX, or FIT file for an activity.
:param file: Path or open file
:param format: File format (gpx, tcx, or fit); guessed from filename if :obj:`None`
:type format: str
:param name: Optional name for the activity on Garmin Connect
:type name: str
:param description: Optional description for the activity on Garmin Connect
:type description: str
:param activity_type: Optional activityType key (lowercase: e.g. running, cycling)
:type activityType: str
:param private: If true, then activity will be set as private.
:type private: bool
:returns: ID of the newly-uploaded activity
:rtype: int
"""
if isinstance(file, str):
file = open(file, "rb")
# guess file type if unspecified
fn = os.path.basename(file.name)
_, ext = os.path.splitext(fn)
if format is None:
if ext.lower() in ('.gpx', '.tcx', '.fit'):
format = ext.lower()[1:]
else:
raise Exception(u"could not guess file type for {}".format(fn))
# upload it
files = dict(data=(fn, file))
response = self.session.post("https://connect.garmin.com/proxy/upload-service/upload/.{}".format(format),
files=files, headers={"nk": "NT"})
# check response and get activity ID
try:
j = response.json()["detailedImportResult"]
except (json.JSONDecodeError, KeyError):
raise Exception(u"failed to upload {} for activity: {}\n{}".format(
format, response.status_code, response.text))
# single activity, immediate success
if len(j["successes"]) == 1 and len(j["failures"]) == 0:
activity_id = j["successes"][0]["internalId"]
# duplicate of existing activity
elif len(j["failures"]) == 1 and len(j["successes"]) == 0 and response.status_code == 409:
log.info(u"duplicate activity uploaded, continuing")
activity_id = j["failures"][0]["internalId"]
# need to poll until success/failure
elif len(j["failures"]) == 0 and len(j["successes"]) == 0 and response.status_code == 202:
retryer = Retryer(
returnval_predicate=bool,
delay_strategy=ExponentialBackoffDelayStrategy(initial_delay=timedelta(seconds=1)),
stop_strategy=MaxRetriesStopStrategy(6), # wait for up to 64 seconds (2**6)
error_strategy=None
)
activity_id = retryer.call(self._poll_upload_completion, j["uploadUuid"]["uuid"], j["creationDate"])
# don't know how to handle multiple activities
elif len(j["successes"]) > 1:
raise Exception(u"uploading {} resulted in multiple activities ({})".format(
format, len(j["successes"])))
# all other errors
else:
raise Exception(u"failed to upload {} for activity: {}\n{}".format(
format, response.status_code, j["failures"]))
# add optional fields
data = {}
if name is not None:
data['activityName'] = name
if description is not None:
data['description'] = description
if activity_type is not None:
data['activityTypeDTO'] = {"typeKey": activity_type}
if private:
data['privacy'] = {"typeKey": "private"}
if data:
data['activityId'] = activity_id
encoding_headers = {"Content-Type": "application/json; charset=UTF-8"} # see Tapiriik
response = self.session.put(
"https://connect.garmin.com/proxy/activity-service/activity/{}".format(activity_id),
data=json.dumps(data), headers=encoding_headers)
if response.status_code != 204:
raise Exception(u"failed to set metadata for activity {}: {}\n{}".format(
activity_id, response.status_code, response.text))
return activity_id
|
//
// Copyright (c) articy Software GmbH & Co. KG. All rights reserved.
//
#pragma once
class UArticyImportData;
/**
*
*/
class ObjectDefinitionsGenerator
{
public:
static void GenerateCode(const UArticyImportData* Data);
private:
ObjectDefinitionsGenerator() {};
~ObjectDefinitionsGenerator() {};
};
|
/*
* Copyright Joyent, Inc. and other Node contributors.
*
* 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.
*/
'use strict';
var punycode = require('punycode');
function Url() {
this.protocol = null;
this.slashes = null;
this.auth = null;
this.host = null;
this.port = null;
this.hostname = null;
this.hash = null;
this.search = null;
this.query = null;
this.pathname = null;
this.path = null;
this.href = null;
}
// Reference: RFC 3986, RFC 1808, RFC 2396
/*
* define these here so at least they only have to be
* compiled once on the first module load.
*/
var protocolPattern = /^([a-z0-9.+-]+:)/i,
portPattern = /:[0-9]*$/,
// Special case for a simple path URL
simplePathPattern = /^(\/\/?(?!\/)[^?\s]*)(\?[^\s]*)?$/,
/*
* RFC 2396: characters reserved for delimiting URLs.
* We actually just auto-escape these.
*/
delims = [
'<', '>', '"', '`', ' ', '\r', '\n', '\t'
],
// RFC 2396: characters not allowed for various reasons.
unwise = [
'{', '}', '|', '\\', '^', '`'
].concat(delims),
// Allowed by RFCs, but cause of XSS attacks. Always escape these.
autoEscape = ['\''].concat(unwise),
/*
* Characters that are never ever allowed in a hostname.
* Note that any invalid chars are also handled, but these
* are the ones that are *expected* to be seen, so we fast-path
* them.
*/
nonHostChars = [
'%', '/', '?', ';', '#'
].concat(autoEscape),
hostEndingChars = [
'/', '?', '#'
],
hostnameMaxLen = 255,
hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
// protocols that can allow "unsafe" and "unwise" chars.
unsafeProtocol = {
javascript: true,
'javascript:': true
},
// protocols that never have a hostname.
hostlessProtocol = {
javascript: true,
'javascript:': true
},
// protocols that always contain a // bit.
slashedProtocol = {
http: true,
https: true,
ftp: true,
gopher: true,
file: true,
'http:': true,
'https:': true,
'ftp:': true,
'gopher:': true,
'file:': true
},
querystring = require('querystring');
function urlParse(url, parseQueryString, slashesDenoteHost) {
if (url && typeof url === 'object' && url instanceof Url) { return url; }
var u = new Url();
u.parse(url, parseQueryString, slashesDenoteHost);
return u;
}
Url.prototype.parse = function (url, parseQueryString, slashesDenoteHost) {
if (typeof url !== 'string') {
throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
}
/*
* Copy chrome, IE, opera backslash-handling behavior.
* Back slashes before the query string get converted to forward slashes
* See: https://code.google.com/p/chromium/issues/detail?id=25916
*/
var queryIndex = url.indexOf('?'),
splitter = queryIndex !== -1 && queryIndex < url.indexOf('#') ? '?' : '#',
uSplit = url.split(splitter),
slashRegex = /\\/g;
uSplit[0] = uSplit[0].replace(slashRegex, '/');
url = uSplit.join(splitter);
var rest = url;
/*
* trim before proceeding.
* This is to support parse stuff like " http://foo.com \n"
*/
rest = rest.trim();
if (!slashesDenoteHost && url.split('#').length === 1) {
// Try fast path regexp
var simplePath = simplePathPattern.exec(rest);
if (simplePath) {
this.path = rest;
this.href = rest;
this.pathname = simplePath[1];
if (simplePath[2]) {
this.search = simplePath[2];
if (parseQueryString) {
this.query = querystring.parse(this.search.substr(1));
} else {
this.query = this.search.substr(1);
}
} else if (parseQueryString) {
this.search = '';
this.query = {};
}
return this;
}
}
var proto = protocolPattern.exec(rest);
if (proto) {
proto = proto[0];
var lowerProto = proto.toLowerCase();
this.protocol = lowerProto;
rest = rest.substr(proto.length);
}
/*
* figure out if it's got a host
* user@server is *always* interpreted as a hostname, and url
* resolution will treat //foo/bar as host=foo,path=bar because that's
* how the browser resolves relative URLs.
*/
if (slashesDenoteHost || proto || rest.match(/^\/\/[^@/]+@[^@/]+/)) {
var slashes = rest.substr(0, 2) === '//';
if (slashes && !(proto && hostlessProtocol[proto])) {
rest = rest.substr(2);
this.slashes = true;
}
}
if (!hostlessProtocol[proto] && (slashes || (proto && !slashedProtocol[proto]))) {
/*
* there's a hostname.
* the first instance of /, ?, ;, or # ends the host.
*
* If there is an @ in the hostname, then non-host chars *are* allowed
* to the left of the last @ sign, unless some host-ending character
* comes *before* the @-sign.
* URLs are obnoxious.
*
* ex:
* http://a@b@c/ => user:a@b host:c
* http://a@b?@c => user:a host:c path:/?@c
*/
/*
* v0.12 TODO(isaacs): This is not quite how Chrome does things.
* Review our test case against browsers more comprehensively.
*/
// find the first instance of any hostEndingChars
var hostEnd = -1;
for (var i = 0; i < hostEndingChars.length; i++) {
var hec = rest.indexOf(hostEndingChars[i]);
if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) { hostEnd = hec; }
}
/*
* at this point, either we have an explicit point where the
* auth portion cannot go past, or the last @ char is the decider.
*/
var auth, atSign;
if (hostEnd === -1) {
// atSign can be anywhere.
atSign = rest.lastIndexOf('@');
} else {
/*
* atSign must be in auth portion.
* http://a@b/c@d => host:b auth:a path:/c@d
*/
atSign = rest.lastIndexOf('@', hostEnd);
}
/*
* Now we have a portion which is definitely the auth.
* Pull that off.
*/
if (atSign !== -1) {
auth = rest.slice(0, atSign);
rest = rest.slice(atSign + 1);
this.auth = decodeURIComponent(auth);
}
// the host is the remaining to the left of the first non-host char
hostEnd = -1;
for (var i = 0; i < nonHostChars.length; i++) {
var hec = rest.indexOf(nonHostChars[i]);
if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) { hostEnd = hec; }
}
// if we still have not hit it, then the entire thing is a host.
if (hostEnd === -1) { hostEnd = rest.length; }
this.host = rest.slice(0, hostEnd);
rest = rest.slice(hostEnd);
// pull out port.
this.parseHost();
/*
* we've indicated that there is a hostname,
* so even if it's empty, it has to be present.
*/
this.hostname = this.hostname || '';
/*
* if hostname begins with [ and ends with ]
* assume that it's an IPv6 address.
*/
var ipv6Hostname = this.hostname[0] === '[' && this.hostname[this.hostname.length - 1] === ']';
// validate a little.
if (!ipv6Hostname) {
var hostparts = this.hostname.split(/\./);
for (var i = 0, l = hostparts.length; i < l; i++) {
var part = hostparts[i];
if (!part) { continue; }
if (!part.match(hostnamePartPattern)) {
var newpart = '';
for (var j = 0, k = part.length; j < k; j++) {
if (part.charCodeAt(j) > 127) {
/*
* we replace non-ASCII char with a temporary placeholder
* we need this to make sure size of hostname is not
* broken by replacing non-ASCII by nothing
*/
newpart += 'x';
} else {
newpart += part[j];
}
}
// we test again with ASCII char only
if (!newpart.match(hostnamePartPattern)) {
var validParts = hostparts.slice(0, i);
var notHost = hostparts.slice(i + 1);
var bit = part.match(hostnamePartStart);
if (bit) {
validParts.push(bit[1]);
notHost.unshift(bit[2]);
}
if (notHost.length) {
rest = '/' + notHost.join('.') + rest;
}
this.hostname = validParts.join('.');
break;
}
}
}
}
if (this.hostname.length > hostnameMaxLen) {
this.hostname = '';
} else {
// hostnames are always lower case.
this.hostname = this.hostname.toLowerCase();
}
if (!ipv6Hostname) {
/*
* IDNA Support: Returns a punycoded representation of "domain".
* It only converts parts of the domain name that
* have non-ASCII characters, i.e. it doesn't matter if
* you call it with a domain that already is ASCII-only.
*/
this.hostname = punycode.toASCII(this.hostname);
}
var p = this.port ? ':' + this.port : '';
var h = this.hostname || '';
this.host = h + p;
this.href += this.host;
/*
* strip [ and ] from the hostname
* the host field still retains them, though
*/
if (ipv6Hostname) {
this.hostname = this.hostname.substr(1, this.hostname.length - 2);
if (rest[0] !== '/') {
rest = '/' + rest;
}
}
}
/*
* now rest is set to the post-host stuff.
* chop off any delim chars.
*/
if (!unsafeProtocol[lowerProto]) {
/*
* First, make 100% sure that any "autoEscape" chars get
* escaped, even if encodeURIComponent doesn't think they
* need to be.
*/
for (var i = 0, l = autoEscape.length; i < l; i++) {
var ae = autoEscape[i];
if (rest.indexOf(ae) === -1) { continue; }
var esc = encodeURIComponent(ae);
if (esc === ae) {
esc = escape(ae);
}
rest = rest.split(ae).join(esc);
}
}
// chop off from the tail first.
var hash = rest.indexOf('#');
if (hash !== -1) {
// got a fragment string.
this.hash = rest.substr(hash);
rest = rest.slice(0, hash);
}
var qm = rest.indexOf('?');
if (qm !== -1) {
this.search = rest.substr(qm);
this.query = rest.substr(qm + 1);
if (parseQueryString) {
this.query = querystring.parse(this.query);
}
rest = rest.slice(0, qm);
} else if (parseQueryString) {
// no query string, but parseQueryString still requested
this.search = '';
this.query = {};
}
if (rest) { this.pathname = rest; }
if (slashedProtocol[lowerProto] && this.hostname && !this.pathname) {
this.pathname = '/';
}
// to support http.request
if (this.pathname || this.search) {
var p = this.pathname || '';
var s = this.search || '';
this.path = p + s;
}
// finally, reconstruct the href based on what has been validated.
this.href = this.format();
return this;
};
// format a parsed object into a url string
function urlFormat(obj) {
/*
* ensure it's an object, and not a string url.
* If it's an obj, this is a no-op.
* this way, you can call url_format() on strings
* to clean up potentially wonky urls.
*/
if (typeof obj === 'string') { obj = urlParse(obj); }
if (!(obj instanceof Url)) { return Url.prototype.format.call(obj); }
return obj.format();
}
Url.prototype.format = function () {
var auth = this.auth || '';
if (auth) {
auth = encodeURIComponent(auth);
auth = auth.replace(/%3A/i, ':');
auth += '@';
}
var protocol = this.protocol || '',
pathname = this.pathname || '',
hash = this.hash || '',
host = false,
query = '';
if (this.host) {
host = auth + this.host;
} else if (this.hostname) {
host = auth + (this.hostname.indexOf(':') === -1 ? this.hostname : '[' + this.hostname + ']');
if (this.port) {
host += ':' + this.port;
}
}
if (this.query && typeof this.query === 'object' && Object.keys(this.query).length) {
query = querystring.stringify(this.query);
}
var search = this.search || (query && ('?' + query)) || '';
if (protocol && protocol.substr(-1) !== ':') { protocol += ':'; }
/*
* only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
* unless they had them to begin with.
*/
if (this.slashes || (!protocol || slashedProtocol[protocol]) && host !== false) {
host = '//' + (host || '');
if (pathname && pathname.charAt(0) !== '/') { pathname = '/' + pathname; }
} else if (!host) {
host = '';
}
if (hash && hash.charAt(0) !== '#') { hash = '#' + hash; }
if (search && search.charAt(0) !== '?') { search = '?' + search; }
pathname = pathname.replace(/[?#]/g, function (match) {
return encodeURIComponent(match);
});
search = search.replace('#', '%23');
return protocol + host + pathname + search + hash;
};
function urlResolve(source, relative) {
return urlParse(source, false, true).resolve(relative);
}
Url.prototype.resolve = function (relative) {
return this.resolveObject(urlParse(relative, false, true)).format();
};
function urlResolveObject(source, relative) {
if (!source) { return relative; }
return urlParse(source, false, true).resolveObject(relative);
}
Url.prototype.resolveObject = function (relative) {
if (typeof relative === 'string') {
var rel = new Url();
rel.parse(relative, false, true);
relative = rel;
}
var result = new Url();
var tkeys = Object.keys(this);
for (var tk = 0; tk < tkeys.length; tk++) {
var tkey = tkeys[tk];
result[tkey] = this[tkey];
}
/*
* hash is always overridden, no matter what.
* even href="" will remove it.
*/
result.hash = relative.hash;
// if the relative url is empty, then there's nothing left to do here.
if (relative.href === '') {
result.href = result.format();
return result;
}
// hrefs like //foo/bar always cut to the protocol.
if (relative.slashes && !relative.protocol) {
// take everything except the protocol from relative
var rkeys = Object.keys(relative);
for (var rk = 0; rk < rkeys.length; rk++) {
var rkey = rkeys[rk];
if (rkey !== 'protocol') { result[rkey] = relative[rkey]; }
}
// urlParse appends trailing / to urls like http://www.example.com
if (slashedProtocol[result.protocol] && result.hostname && !result.pathname) {
result.pathname = '/';
result.path = result.pathname;
}
result.href = result.format();
return result;
}
if (relative.protocol && relative.protocol !== result.protocol) {
/*
* if it's a known url protocol, then changing
* the protocol does weird things
* first, if it's not file:, then we MUST have a host,
* and if there was a path
* to begin with, then we MUST have a path.
* if it is file:, then the host is dropped,
* because that's known to be hostless.
* anything else is assumed to be absolute.
*/
if (!slashedProtocol[relative.protocol]) {
var keys = Object.keys(relative);
for (var v = 0; v < keys.length; v++) {
var k = keys[v];
result[k] = relative[k];
}
result.href = result.format();
return result;
}
result.protocol = relative.protocol;
if (!relative.host && !hostlessProtocol[relative.protocol]) {
var relPath = (relative.pathname || '').split('/');
while (relPath.length && !(relative.host = relPath.shift())) { }
if (!relative.host) { relative.host = ''; }
if (!relative.hostname) { relative.hostname = ''; }
if (relPath[0] !== '') { relPath.unshift(''); }
if (relPath.length < 2) { relPath.unshift(''); }
result.pathname = relPath.join('/');
} else {
result.pathname = relative.pathname;
}
result.search = relative.search;
result.query = relative.query;
result.host = relative.host || '';
result.auth = relative.auth;
result.hostname = relative.hostname || relative.host;
result.port = relative.port;
// to support http.request
if (result.pathname || result.search) {
var p = result.pathname || '';
var s = result.search || '';
result.path = p + s;
}
result.slashes = result.slashes || relative.slashes;
result.href = result.format();
return result;
}
var isSourceAbs = result.pathname && result.pathname.charAt(0) === '/',
isRelAbs = relative.host || relative.pathname && relative.pathname.charAt(0) === '/',
mustEndAbs = isRelAbs || isSourceAbs || (result.host && relative.pathname),
removeAllDots = mustEndAbs,
srcPath = result.pathname && result.pathname.split('/') || [],
relPath = relative.pathname && relative.pathname.split('/') || [],
psychotic = result.protocol && !slashedProtocol[result.protocol];
/*
* if the url is a non-slashed url, then relative
* links like ../.. should be able
* to crawl up to the hostname, as well. This is strange.
* result.protocol has already been set by now.
* Later on, put the first path part into the host field.
*/
if (psychotic) {
result.hostname = '';
result.port = null;
if (result.host) {
if (srcPath[0] === '') { srcPath[0] = result.host; } else { srcPath.unshift(result.host); }
}
result.host = '';
if (relative.protocol) {
relative.hostname = null;
relative.port = null;
if (relative.host) {
if (relPath[0] === '') { relPath[0] = relative.host; } else { relPath.unshift(relative.host); }
}
relative.host = null;
}
mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
}
if (isRelAbs) {
// it's absolute.
result.host = relative.host || relative.host === '' ? relative.host : result.host;
result.hostname = relative.hostname || relative.hostname === '' ? relative.hostname : result.hostname;
result.search = relative.search;
result.query = relative.query;
srcPath = relPath;
// fall through to the dot-handling below.
} else if (relPath.length) {
/*
* it's relative
* throw away the existing file, and take the new path instead.
*/
if (!srcPath) { srcPath = []; }
srcPath.pop();
srcPath = srcPath.concat(relPath);
result.search = relative.search;
result.query = relative.query;
} else if (relative.search != null) {
/*
* just pull out the search.
* like href='?foo'.
* Put this after the other two cases because it simplifies the booleans
*/
if (psychotic) {
result.host = srcPath.shift();
result.hostname = result.host;
/*
* occationaly the auth can get stuck only in host
* this especially happens in cases like
* url.resolveObject('mailto:local1@domain1', 'local2@domain2')
*/
var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false;
if (authInHost) {
result.auth = authInHost.shift();
result.hostname = authInHost.shift();
result.host = result.hostname;
}
}
result.search = relative.search;
result.query = relative.query;
// to support http.request
if (result.pathname !== null || result.search !== null) {
result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : '');
}
result.href = result.format();
return result;
}
if (!srcPath.length) {
/*
* no path at all. easy.
* we've already handled the other stuff above.
*/
result.pathname = null;
// to support http.request
if (result.search) {
result.path = '/' + result.search;
} else {
result.path = null;
}
result.href = result.format();
return result;
}
/*
* if a url ENDs in . or .., then it must get a trailing slash.
* however, if it ends in anything else non-slashy,
* then it must NOT get a trailing slash.
*/
var last = srcPath.slice(-1)[0];
var hasTrailingSlash = (result.host || relative.host || srcPath.length > 1) && (last === '.' || last === '..') || last === '';
/*
* strip single dots, resolve double dots to parent dir
* if the path tries to go above the root, `up` ends up > 0
*/
var up = 0;
for (var i = srcPath.length; i >= 0; i--) {
last = srcPath[i];
if (last === '.') {
srcPath.splice(i, 1);
} else if (last === '..') {
srcPath.splice(i, 1);
up++;
} else if (up) {
srcPath.splice(i, 1);
up--;
}
}
// if the path is allowed to go above the root, restore leading ..s
if (!mustEndAbs && !removeAllDots) {
for (; up--; up) {
srcPath.unshift('..');
}
}
if (mustEndAbs && srcPath[0] !== '' && (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
srcPath.unshift('');
}
if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
srcPath.push('');
}
var isAbsolute = srcPath[0] === '' || (srcPath[0] && srcPath[0].charAt(0) === '/');
// put the host back
if (psychotic) {
result.hostname = isAbsolute ? '' : srcPath.length ? srcPath.shift() : '';
result.host = result.hostname;
/*
* occationaly the auth can get stuck only in host
* this especially happens in cases like
* url.resolveObject('mailto:local1@domain1', 'local2@domain2')
*/
var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false;
if (authInHost) {
result.auth = authInHost.shift();
result.hostname = authInHost.shift();
result.host = result.hostname;
}
}
mustEndAbs = mustEndAbs || (result.host && srcPath.length);
if (mustEndAbs && !isAbsolute) {
srcPath.unshift('');
}
if (srcPath.length > 0) {
result.pathname = srcPath.join('/');
} else {
result.pathname = null;
result.path = null;
}
// to support request.http
if (result.pathname !== null || result.search !== null) {
result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : '');
}
result.auth = relative.auth || result.auth;
result.slashes = result.slashes || relative.slashes;
result.href = result.format();
return result;
};
Url.prototype.parseHost = function () {
var host = this.host;
var port = portPattern.exec(host);
if (port) {
port = port[0];
if (port !== ':') {
this.port = port.substr(1);
}
host = host.substr(0, host.length - port.length);
}
if (host) { this.hostname = host; }
};
exports.parse = urlParse;
exports.resolve = urlResolve;
exports.resolveObject = urlResolveObject;
exports.format = urlFormat;
exports.Url = Url;
|
# v. 1.2
# 07.09.2017
# Sergii Mamedov
"""
Gevent version.
Get metadata from all dois from a journal.
Journal`s urls: https://www.crossref.org/06members/51depositor.html
"""
import time
import json
import logging
import argparse
import requests
from tqdm import tqdm
import gevent
from gevent import monkey
# https://github.com/tqdm/tqdm/issues/404
gevent.monkey.patch_all(thread=False)
OUTPUT_LOCK = gevent.lock.Semaphore()
FORMAT = '%(asctime)s %(levelname)s %(message)s'
logging.basicConfig(format=FORMAT, level=logging.INFO)
URL_API = 'http://api.crossref.org/works/'
def connect_get(url, timeout=30, headers={}, cookies={}):
"""
get source code from page
"""
MAX_RETRIES = 5
for i in range(0, MAX_RETRIES):
html = u''
try:
conn = requests.get(url, timeout=timeout, headers=headers, cookies=cookies, verify=False)
html = conn.text
conn.raise_for_status()
break
except requests.exceptions.RequestException as err:
logging.info('RequestException\t{}'.format(err))
time.sleep(MAX_RETRIES)
return html
def get_dois_list(url):
"""
return all dois from journals
"""
raw = connect_get(url, timeout=120)
return [item.split(' ')[0] for item in raw.split('\r\n')[2:] if item.strip()]
def change_dois_list(sequence):
"""
return {'PhysRevX.01': list, 'PhysRevX.02': list}
"""
data = {}
for item in sequence:
key = item.split('.')
key = '{}.{}'.format('.'.join(key[:2]), key[2].zfill(3))
data[key] = data.get(key, []) + [item]
return data
def get_info(name, dois):
"""
write metadata of article in file
"""
name = name.split('/')[1].split('.')
name = '{}.{}.txt'.format(name[0], name[1])
with open(name, encoding='utf-8', mode='w') as f:
for doi in dois:
item = connect_get(URL_API+doi)
item = json.loads(item)
if item.get('message') and item['message'].get('type') \
and item['message']['type'] == 'journal-article':
f.write(json.dumps(item, ensure_ascii=False) + '\n')
def main():
parser = argparse.ArgumentParser()
parser.description = ('Get metadata from all dois from a journals of APS')
parser.add_argument('-t', '--thread', default=10, type=int,
help='number of thread, max - 10, defaul - 10')
parser.add_argument('-j', '--journal', help='name of a journal')
args = parser.parse_args()
journals = {'Phys. Rev. A': 'http://data.crossref.org/depositorreport?pubid=J5203',
'Phys. Rev. B': 'http://data.crossref.org/depositorreport?pubid=J5200',
'Phys. Rev. C': 'http://data.crossref.org/depositorreport?pubid=J5201',
'Phys. Rev. D': 'http://data.crossref.org/depositorreport?pubid=J5199',
'Phys. Rev. E': 'http://data.crossref.org/depositorreport?pubid=J5202',
'Phys. Rev. X': 'http://data.crossref.org/depositorreport?pubid=J140965',
'Phys. Rev. Lett': 'http://data.crossref.org/depositorreport?pubid=J5204'}
thread = args.thread
if thread > 10 or thread < 1:
thread = 10
if args.journal == 'all':
pass
elif args.journal in journals:
journals = {args.journal: journals.get(args.journal)}
else:
print('Available journals: \n\n{}'.format('; '.join(journals.keys())))
return
for journal, url in journals.items():
logging.info('Start {}'.format(journal))
dois = get_dois_list(url)
dois = change_dois_list(dois)
logging.info('Get DOIs list')
pool = gevent.pool.Pool(thread)
for name, dois_sublist in tqdm(sorted(dois.items(), key=lambda x: x)):
pool.wait_available()
pool.apply_async(get_info, args=[name, dois_sublist])
pool.join()
if __name__ == '__main__':
main()
|
from abc import abstractmethod
import re
import tensorflow as tf
import functools
from core.target_assigner import TargetAssignerExtend
from object_detection.core import box_list
from object_detection.core import box_predictor as bpredictor
from object_detection.core import model, box_list, box_list_ops, preprocessor
from object_detection.core import standard_fields as fields
from object_detection.core import target_assigner
from object_detection.utils import shape_utils
from object_detection.meta_architectures.ssd_meta_arch import SSDMetaArch
import numpy as np
slim = tf.contrib.slim
def match_and_select_feature(groundtruth_boxes, anchors, feature_maps):
""" Select features on the groundtruth box locations
Args:
groundtruth_boxes: a tensor of batch_size x 4
anchors: generated anchor Box list
feature_maps: a list of feature pyramid, each element is a
tensor of batch_size x height_i x width_i x channel
Returns:
selected_features: a tensor of batch_size x 1 x 1 x channel
"""
groundtruth_boxeslists =[box_list.BoxList(tf.expand_dims(box, 0))
for box in tf.unstack(groundtruth_boxes, axis=0)]
feature_maps = [tf.reshape(m, [m.get_shape()[0].value, -1, m.get_shape()[-1].value]) for m in feature_maps]
feature_maps = tf.unstack(tf.concat(feature_maps, axis=1), axis=0)
num_anchors_per_location = anchors.get().get_shape()[0].value / feature_maps[0].get_shape()[0].value
selected_feature = list()
for groundtruth_boxes, feature_map in zip(groundtruth_boxeslists, feature_maps):
iou = box_list_ops.iou(groundtruth_boxes, anchors)
max_ind = tf.argmax(iou, axis=1) / num_anchors_per_location
selected_feature.append(tf.gather(feature_map, max_ind))
selected_feature = tf.concat(selected_feature, axis=0)
selected_feature = tf.expand_dims(tf.expand_dims(selected_feature, axis= 1), axis=1)
return selected_feature
class MANMetaArch(SSDMetaArch):
def __init__(self,
is_training,
anchor_generator,
box_predictor,
box_coder,
feature_extractor,
matcher,
region_similarity_calculator,
image_resizer_fn,
non_max_suppression_fn,
score_conversion_fn,
classification_loss,
localization_loss,
classification_loss_weight,
localization_loss_weight,
normalize_loss_by_num_matches,
hard_example_miner,
add_summaries=True):
"""SSDMetaArch Constructor.
TODO: group NMS parameters + score converter into
a class and loss parameters into a class and write config protos for
postprocessing and losses.
Args:
is_training: A boolean indicating whether the training version of the
computation graph should be constructed.
anchor_generator: an anchor_generator.AnchorGenerator object.
box_predictor: a box_predictor.BoxPredictor object.
box_coder: a box_coder.BoxCoder object.
feature_extractor: a SSDFeatureExtractor object.
matcher: a matcher.Matcher object.
region_similarity_calculator: a
region_similarity_calculator.RegionSimilarityCalculator object.
image_resizer_fn: a callable for image resizing. This callable always
takes a rank-3 image tensor (corresponding to a single image) and
returns a rank-3 image tensor, possibly with new spatial dimensions.
See builders/image_resizer_builder.py.
non_max_suppression_fn: batch_multiclass_non_max_suppression
callable that takes `boxes`, `scores` and optional `clip_window`
inputs (with all other inputs already set) and returns a dictionary
hold tensors with keys: `detection_boxes`, `detection_scores`,
`detection_classes` and `num_detections`. See `post_processing.
batch_multiclass_non_max_suppression` for the type and shape of these
tensors.
score_conversion_fn: callable elementwise nonlinearity (that takes tensors
as inputs and returns tensors). This is usually used to convert logits
to probabilities.
classification_loss: an object_detection.core.losses.Loss object.
localization_loss: a object_detection.core.losses.Loss object.
classification_loss_weight: float
localization_loss_weight: float
normalize_loss_by_num_matches: boolean
hard_example_miner: a losses.HardExampleMiner object (can be None)
add_summaries: boolean (default: True) controlling whether summary ops
should be added to tensorflow graph.
"""
super(SSDMetaArch, self).__init__(num_classes=box_predictor.num_classes)
self._is_training = is_training
# Needed for fine-tuning from classification checkpoints whose
# variables do not have the feature extractor scope.
self._extract_features_scope = 'FeatureExtractor'
self._anchor_generator = anchor_generator
self._box_predictor = box_predictor
self._box_coder = box_coder
self._feature_extractor = feature_extractor
self._matcher = matcher
self._region_similarity_calculator = region_similarity_calculator
# TODO: handle agnostic mode and positive/negative class weights
unmatched_cls_target = None
unmatched_cls_target = tf.constant([1] + self.num_classes * [0], tf.float32)
self._target_assigner = TargetAssignerExtend(
self._region_similarity_calculator,
self._matcher,
self._box_coder,
positive_class_weight=1.0,
negative_class_weight=1.0,
unmatched_cls_target=unmatched_cls_target)
self._classification_loss = classification_loss
self._localization_loss = localization_loss
self._classification_loss_weight = classification_loss_weight
self._localization_loss_weight = localization_loss_weight
self._normalize_loss_by_num_matches = normalize_loss_by_num_matches
self._hard_example_miner = hard_example_miner
self._image_resizer_fn = image_resizer_fn
self._non_max_suppression_fn = non_max_suppression_fn
self._score_conversion_fn = score_conversion_fn
self._anchors = None
self._add_summaries = add_summaries
def _add_box_predictions_to_feature_maps(self, feature_maps,reuse=None):
"""Adds box predictors to each feature map and returns concatenated results.
Args:
feature_maps: a list of tensors where the ith tensor has shape
[batch, height_i, width_i, depth_i]
Returns:
box_encodings: 4-D float tensor of shape [batch_size, num_anchors,
box_code_dimension] containing predicted boxes.
class_predictions_with_background: 2-D float tensor of shape
[batch_size, num_anchors, num_classes+1] containing class predictions
(logits) for each of the anchors. Note that this tensor *includes*
background class predictions (at class index 0).
Raises:
RuntimeError: if the number of feature maps extracted via the
extract_features method does not match the length of the
num_anchors_per_locations list that was passed to the constructor.
RuntimeError: if box_encodings from the box_predictor does not have
shape of the form [batch_size, num_anchors, 1, code_size].
"""
num_anchors_per_location_list = (
self._anchor_generator.num_anchors_per_location())
if len(feature_maps) != len(num_anchors_per_location_list):
raise RuntimeError('the number of feature maps must match the '
'length of self.anchors.NumAnchorsPerLocation().')
box_encodings_list = []
cls_predictions_with_background_list = []
for idx, (feature_map, num_anchors_per_location
) in enumerate(zip(feature_maps, num_anchors_per_location_list)):
box_predictor_scope = 'BoxPredictor'
box_predictions = self._box_predictor.predict(feature_map,
num_anchors_per_location,
box_predictor_scope,reuse=reuse)
box_encodings = box_predictions[bpredictor.BOX_ENCODINGS]
cls_predictions_with_background = box_predictions[
bpredictor.CLASS_PREDICTIONS_WITH_BACKGROUND]
box_encodings_shape = box_encodings.get_shape().as_list()
if len(box_encodings_shape) != 4 or box_encodings_shape[2] != 1:
raise RuntimeError('box_encodings from the box_predictor must be of '
'shape `[batch_size, num_anchors, 1, code_size]`; '
'actual shape', box_encodings_shape)
box_encodings = tf.squeeze(box_encodings, axis=2)
box_encodings_list.append(box_encodings)
cls_predictions_with_background_list.append(
cls_predictions_with_background)
num_predictions = sum(
[tf.shape(box_encodings)[1] for box_encodings in box_encodings_list])
num_anchors = self.anchors.num_boxes()
anchors_assert = tf.assert_equal(num_anchors, num_predictions, [
'Mismatch: number of anchors vs number of predictions', num_anchors,
num_predictions
])
with tf.control_dependencies([anchors_assert]):
box_encodings = tf.concat(box_encodings_list, 1)
class_predictions_with_background = tf.concat(
cls_predictions_with_background_list, 1)
return box_encodings, class_predictions_with_background
def _add_sequential_box_predictions_to_feature_maps(self, init_feature_maps, feature_maps,reuse=None):
"""Adds box predictors to each feature map and returns concatenated results.
Args:
feature_maps: a list of tensors where the ith tensor has shape
[batch, seq_length, height_i, width_i, depth_i]
Returns:
box_encodings: 4-D float tensor of shape [batch_size, num_anchors,
box_code_dimension] containing predicted boxes.
class_predictions_with_background: 2-D float tensor of shape
[batch_size, num_anchors, num_classes+1] containing class predictions
(logits) for each of the anchors. Note that this tensor *includes*
background class predictions (at class index 0).
Raises:
RuntimeError: if the number of feature maps extracted via the
extract_features method does not match the length of the
num_anchors_per_locations list that was passed to the constructor.
RuntimeError: if box_encodings from the box_predictor does not have
shape of the form [batch_size, num_anchors, 1, code_size].
"""
# reshape and transpose each feature map to the size of [seq_length, batch_size, height, width, channel]
feature_maps = [tf.transpose(tf.reshape(m,
[self._batch_size,
self._seq_length,
m.get_shape()[1].value,
m.get_shape()[2].value,
m.get_shape()[3].value]), perm=[1,0,2,3,4]) for m in feature_maps]
feature_array_list = list()
for feature_map in feature_maps:
feature_array = tf.TensorArray(dtype=tf.float32, size=self._seq_length, clear_after_read=False)
feature_array = feature_array.unstack(feature_map)
feature_array_list.append(feature_array)
groundtruth_boxes = tf.transpose(self.groundtruth_lists('boxes'), [1, 0, 2]) # seq_length x batch_size x 4
# init_groundtruth_boxes = groundtruth_boxes[0]
box_reg_array = tf.TensorArray(dtype=tf.float32, size=self._seq_length)
box_cls_array = tf.TensorArray(dtype=tf.float32, size=self._seq_length)
# groundtruth_boxes_array=groundtruth_boxes_array.unstack(groundtruth_boxes[1:])
# selected_feature = init_feature_list[-1]
# selected_feature = match_and_select_feature(init_groundtruth_boxes, self.anchors, init_feature_list)
# feature_maps = [A.read(0) for A in feature_array_list]
# feature_maps = [tf.concat([m,
# tf.tile(selected_feature, [1, m.get_shape()[1].value, m.get_shape()[2].value, 1])],
# axis=3) for m in feature_maps]
# a = self._add_box_predictions_to_feature_maps(feature_maps)
def _time_step(time, box_reg_array, box_cls_array):
feature_maps = [A.read(time) for A in feature_array_list]
concate_feature_maps = list()
for m in feature_maps:
#tile_num = int(np.ceil(int(m.get_shape()[1])/ float(int(init_feature_maps.get_shape()[1]))))
tile_num = int(m.get_shape()[1])
tiled_init_feature = tf.tile(init_feature_maps,
[1,tile_num,tile_num,1])
#crop_shape = int(m.get_shape()[1])
#tiled_init_feature = tiled_init_feature[:,:crop_shape,:crop_shape,:]
tmp1 = m*tiled_init_feature
concate_feature_maps.append(tf.concat([tf.nn.l2_normalize(tmp1,dim=3)*10, tf.nn.l2_normalize(tiled_init_feature,dim=3)*10], axis=3))
reg_pre, cls_pre = self._add_box_predictions_to_feature_maps(concate_feature_maps,reuse=reuse)
box_reg_array = box_reg_array.write(time, reg_pre)
box_cls_array = box_cls_array.write(time, cls_pre)
# groundtruth_boxes = groundtruth_boxes_array.read(time)
# selected_feature = match_and_select_feature(groundtruth_boxes, self.anchors, feature_maps)
return time+1, box_reg_array, box_cls_array
_, box_reg_array, box_cls_array = tf.while_loop(
cond=lambda time, *_: time < self._seq_length,
body=_time_step,
loop_vars=(0, box_reg_array, box_cls_array),
parallel_iterations=1,
swap_memory=True)
#_, _, box_reg_array, box_cls_array = _time_step(0, selected_feature, box_reg_array, box_cls_array)
box_reg = box_reg_array.stack()
box_reg.set_shape([self._seq_length,
self._batch_size,
box_reg.get_shape()[2].value,
box_reg.get_shape()[3].value])
box_reg = tf.transpose(box_reg, [1,0,2,3])
box_reg = tf.reshape(box_reg, [self._batch_size * (self._seq_length),
box_reg.get_shape()[2].value,
box_reg.get_shape()[3].value])
box_cls = box_cls_array.stack()
box_cls.set_shape([self._seq_length,
self._batch_size,
box_cls.get_shape()[2].value,
box_cls.get_shape()[3].value])
box_cls = tf.transpose(box_cls, [1,0,2,3])
box_cls = tf.reshape(box_cls, [self._batch_size * (self._seq_length),
box_cls.get_shape()[2].value,
box_cls.get_shape()[3].value])
return box_reg, box_cls
def _assign_targets(self, groundtruth_boxes_list, groundtruth_classes_list):
"""Assign groundtruth targets.
Adds a background class to each one-hot encoding of groundtruth classes
and uses target assigner to obtain regression and classification targets.
Args:
groundtruth_boxes_list: a list of 2-D tensors of shape [num_boxes, 4]
containing coordinates of the groundtruth boxes.
Groundtruth boxes are provided in [y_min, x_min, y_max, x_max]
format and assumed to be normalized and clipped
relative to the image window with y_min <= y_max and x_min <= x_max.
groundtruth_classes_list: a list of 2-D one-hot (or k-hot) tensors of
shape [num_boxes, num_classes] containing the class targets with the 0th
index assumed to map to the first non-background class.
Returns:
batch_cls_targets: a tensor with shape [batch_size, num_anchors,
num_classes],
batch_cls_weights: a tensor with shape [batch_size, num_anchors],
batch_reg_targets: a tensor with shape [batch_size, num_anchors,
box_code_dimension]
batch_reg_weights: a tensor with shape [batch_size, num_anchors],
match_list: a list of matcher.Match objects encoding the match between
anchors and groundtruth boxes for each image of the batch,
with rows of the Match objects corresponding to groundtruth boxes
and columns corresponding to anchors.
"""
groundtruth_boxes_list = tf.reshape(groundtruth_boxes_list, [self._batch_size*(self._seq_length), -1])
groundtruth_boxes_list = tf.unstack(groundtruth_boxes_list, axis=0)
groundtruth_boxlists = [
box_list.BoxList(tf.expand_dims(boxes, axis=0)) for boxes in groundtruth_boxes_list
]
groundtruth_classes_list = tf.reshape(groundtruth_classes_list, [self._batch_size*(self._seq_length), -1])
groundtruth_classes_list = tf.unstack(groundtruth_classes_list, axis=0)
groundtruth_classes_with_background_list = [
tf.reshape(tf.one_hot(one_hot_encoding, self.num_classes+1), [1, self.num_classes+1])
for one_hot_encoding in groundtruth_classes_list
]
return target_assigner.batch_assign_targets(
self._target_assigner, self.anchors, groundtruth_boxlists,
groundtruth_classes_with_background_list)
def extract_feature(self,preprocessed_inputs):
self._batch_size, self._seq_length, self._input_size, _, _ = preprocessed_inputs.get_shape().as_list()
preprocessed_inputs = tf.reshape(preprocessed_inputs, [-1, self._input_size, self._input_size, 3])
with tf.variable_scope('FeatureExtractor'):
feature_maps = self._feature_extractor.extract_features(
preprocessed_inputs)
output_dict = {
'feature_maps0': feature_maps[0],
'feature_maps1': feature_maps[1],
# 'feature_maps2': feature_maps[2],
# 'feature_maps3': feature_maps[3],
# 'feature_maps4': feature_maps[4],
# 'feature_maps5': feature_maps[5]
}
return output_dict
def extract_init_feature(self,preprocessed_init_input):
_, _, self.init_input_size, _, _ = preprocessed_init_input.get_shape().as_list()
preprocessed_init_input = tf.reshape(preprocessed_init_input,
[-1, self.init_input_size, self.init_input_size, 3])
with tf.variable_scope('InitFeatureExtractor'):
init_feature_maps = self._feature_extractor.extract_features(
preprocessed_init_input, True)
return init_feature_maps
def predict_box_with_init(self,init_feature_maps, preprocessed_input,istraining=False):
self._batch_size, self._seq_length, self._input_size, _, _ = preprocessed_input.get_shape().as_list()
preprocessed_inputs = tf.reshape(preprocessed_input, [-1, self._input_size, self._input_size, 3])
with tf.variable_scope('FeatureExtractor'):
feature_maps = self._feature_extractor.extract_features(
preprocessed_inputs)
self._is_training = istraining
feature_map_spatial_dims = self._get_feature_map_spatial_dims(feature_maps)
self._anchors = self._anchor_generator.generate(feature_map_spatial_dims)
(box_encodings, class_predictions_with_background
) = self._add_sequential_box_predictions_to_feature_maps(init_feature_maps, feature_maps)
predictions_dict = {
'box_encodings': box_encodings,
'class_predictions_with_background': class_predictions_with_background,
'feature_maps': feature_maps
}
return predictions_dict
def predict_box(self,init_feature_maps, feature_maps,istraining=False):
self._is_training = istraining
feature_map_spatial_dims = self._get_feature_map_spatial_dims(feature_maps)
self._anchors = self._anchor_generator.generate(feature_map_spatial_dims)
(box_encodings, class_predictions_with_background
) = self._add_sequential_box_predictions_to_feature_maps(init_feature_maps, feature_maps)
predictions_dict = {
'box_encodings': box_encodings,
'class_predictions_with_background': class_predictions_with_background,
'feature_maps': feature_maps
}
return predictions_dict
def predict(self, preprocessed_init_input, preprocessed_inputs,istraining=False,reuse=None,weights_dict=None):
"""Predicts unpostprocessed tensors from input tensor.
This function takes an input batch of images and runs it through the forward
pass of the network to yield unpostprocessesed predictions.
A side effect of calling the predict method is that self._anchors is
populated with a box_list.BoxList of anchors. These anchors must be
constructed before the postprocess or loss functions can be called.
Args:
preprocessed_inputs: a [batch, height, width, channels] image tensor.
Returns:
prediction_dict: a dictionary holding "raw" prediction tensors:
1) box_encodings: 4-D float tensor of shape [batch_size, num_anchors,
box_code_dimension] containing predicted boxes.
2) class_predictions_with_background: 3-D float tensor of shape
[batch_size, num_anchors, num_classes+1] containing class predictions
(logits) for each of the anchors. Note that this tensor *includes*
background class predictions (at class index 0).
3) feature_maps: a list of tensors where the ith tensor has shape
[batch, height_i, width_i, depth_i].
"""
self._is_training = istraining
self._batch_size, self._seq_length, self._input_size, _, _ = preprocessed_inputs.get_shape().as_list()
_, _, self.init_input_size, _, _ = preprocessed_init_input.get_shape().as_list()
preprocessed_init_input = tf.reshape(preprocessed_init_input,
[-1, self.init_input_size, self.init_input_size, 3])
preprocessed_inputs = tf.reshape(preprocessed_inputs, [-1, self._input_size, self._input_size, 3])
with tf.variable_scope('InitFeatureExtractor') as scope:
if reuse:
scope.reuse_variables()
init_feature_maps = self._feature_extractor.extract_features(
preprocessed_init_input, True)
with tf.variable_scope('FeatureExtractor') as scope:
if reuse:
scope.reuse_variables()
feature_maps = self._feature_extractor.extract_features(
preprocessed_inputs)
# if weights_dict is None:
# weights_dict = dict()
# weights_dict = self._box_predictor.get_weights(weights_dict,reuse=reuse)
feature_map_spatial_dims = self._get_feature_map_spatial_dims(feature_maps)
self._anchors = self._anchor_generator.generate(feature_map_spatial_dims)
(box_encodings, class_predictions_with_background
) = self._add_sequential_box_predictions_to_feature_maps(init_feature_maps, feature_maps,reuse=reuse)
predictions_dict = {
'box_encodings': box_encodings,
'class_predictions_with_background': class_predictions_with_background,
'feature_maps': feature_maps
}
return predictions_dict
def preprocess(self, inputs, win_size=None):
"""Feature-extractor specific preprocessing.
See base class.
Args:
inputs: a [batch, height_in, width_in, channels] float tensor representing
a batch of images with values between 0 and 255.0.
Returns:
preprocessed_inputs: a [batch, height_out, width_out, channels] float
tensor representing a batch of images.
Raises:
ValueError: if inputs tensor does not have type tf.float32
"""
if inputs.dtype is not tf.float32:
raise ValueError('`preprocess` expects a tf.float32 tensor')
if win_size == None:
win_size=[300,300]
with tf.name_scope('Preprocessor'):
# TODO: revisit whether to always use batch size as the number of
# parallel iterations vs allow for dynamic batching.
_image_resizer_fn = functools.partial(preprocessor.resize_image, new_height=win_size[0], new_width=win_size[1])
resized_inputs = tf.map_fn(_image_resizer_fn,
elems=inputs,
dtype=tf.float32)
return self._feature_extractor.preprocess(resized_inputs)
def restore_map(self, from_detection_checkpoint=True):
"""Returns a map of variables to load from a foreign checkpoint.
See parent class for details.
Args:
from_detection_checkpoint: whether to restore from a full detection
checkpoint (with compatible variable names) or to restore from a
classification checkpoint for initialization prior to training.
Returns:
A dict mapping variable names (to load from a checkpoint) to variables in
the model graph.
"""
variables_to_restore = {}
for variable in tf.all_variables():
if variable.op.name.startswith(self._extract_features_scope):
var_name = variable.op.name
if not from_detection_checkpoint:
var_name = (re.split('^' + self._extract_features_scope + '/',
var_name)[-1])
variables_to_restore[var_name] = variable
return variables_to_restore
def restore_init_map(self, from_detection_checkpoint=True):
"""Returns a map of variables to load from a foreign checkpoint.
See parent class for details.
Args:
from_detection_checkpoint: whether to restore from a full detection
checkpoint (with compatible variable names) or to restore from a
classification checkpoint for initialization prior to training.
Returns:
A dict mapping variable names (to load from a checkpoint) to variables in
the model graph.
"""
variables_to_restore = {}
for variable in tf.all_variables():
if variable.op.name.startswith('InitFeatureExtractor'):
var_name = variable.op.name
if not from_detection_checkpoint:
var_name = (re.split('^' + 'InitFeatureExtractor' + '/',
var_name)[-1])
else:
var_name = (re.split('^' + 'Init',
var_name)[-1])
variables_to_restore[var_name] = variable
return variables_to_restore
|
$("#date").click(function() {
var entitySelector = $("#tb").html('');
var params = {
url: ""
};
if($("#time1").val()!="" && $("#time2").val()!=""){
params.url='http://localhost/pi_dev/web/app_dev.php/dispo/dateajax/'+$("#date").val()+'/'+$("#time1").val()+'/'+$("#time2").val();
}
else{
params.url='http://localhost/pi_dev/web/app_dev.php/dispo/dateonly/'+ $("#date").val();
}
//OVqtMx8XZc7Ky6iWBdlLnAc9A2BN8z4lSbfHUblu
//95fbfb23bf649f24b897d7b196c53369
$.ajax({
type: "GET",
// url: "{{ path('rappelrdv_ajax') }}",
url: params.url,
//dataType: "jsonp",
dataType: "text",
success: function(msg){
//we need to check if the value is the same
var result = JSON.parse(msg);
$.each(result, function(key, arr) {
$.each(arr, function(id, value) {
if (key === 'disponibilite') {
if (id !== 'error') {
entitySelector.append('<tr><td>'+value['id']+'</td><td>'+
value['adresse']+'</td><td>'+value['date']+
'</td><td>' +value['HeureDebut']+'</td><td>'+ value['HeureFin']+'</td><td>'+value['nom']+'</td> <td>'+value['tel']+'</td> <ul><li><a class="ui inverted primary button" href=\"/pi_dev/web/app_dev.php/rappelrdv/'+value['id']+'/edit\">'+'Modifier'
+' </li></a>' +' </br><li><a class="ui inverted red button" href=\"/pi_dev/web/app_dev.php/rappelrdv/'+value['id']+'/delete\">'+'Supprimer'
+'</li></ul></a></tr>'
);
} else {
Swal.fire({
type: 'error',
title: 'Oops...',
text: 'Something went wrong!',
footer: '<a href>Why do I have this issue?</a>',
timer: 1500
});
}
}
});
});
}
});
});
|
import { CommonModule } from '@angular/common';
import { ɵɵdefineInjectable, Injectable, Optional, SkipSelf, InjectionToken, EventEmitter, Directive, ChangeDetectorRef, Input, Output, Component, ChangeDetectionStrategy, ViewEncapsulation, Inject, NgModule } from '@angular/core';
import { mixinDisabled, mixinInitialized, MatCommonModule } from '@angular/material/core';
import { MatButtonModule } from '@angular/material/button';
import { MatSelectModule } from '@angular/material/select';
import { MatTooltipModule } from '@angular/material/tooltip';
import { coerceNumberProperty, coerceBooleanProperty } from '@angular/cdk/coercion';
import { Subject } from 'rxjs';
/**
* @license
* 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
*/
/**
* To modify the labels and text displayed, create a new instance of MatPaginatorIntl and
* include it in a custom provider
*/
import * as ɵngcc0 from '@angular/core';
import * as ɵngcc1 from '@angular/common';
import * as ɵngcc2 from '@angular/material/button';
import * as ɵngcc3 from '@angular/material/tooltip';
import * as ɵngcc4 from '@angular/material/form-field';
import * as ɵngcc5 from '@angular/material/select';
import * as ɵngcc6 from '@angular/material/core';
function MatPaginator_div_2_mat_form_field_3_mat_option_2_Template(rf, ctx) { if (rf & 1) {
ɵngcc0.ɵɵelementStart(0, "mat-option", 19);
ɵngcc0.ɵɵtext(1);
ɵngcc0.ɵɵelementEnd();
} if (rf & 2) {
const pageSizeOption_r6 = ctx.$implicit;
ɵngcc0.ɵɵproperty("value", pageSizeOption_r6);
ɵngcc0.ɵɵadvance(1);
ɵngcc0.ɵɵtextInterpolate1(" ", pageSizeOption_r6, " ");
} }
function MatPaginator_div_2_mat_form_field_3_Template(rf, ctx) { if (rf & 1) {
const _r8 = ɵngcc0.ɵɵgetCurrentView();
ɵngcc0.ɵɵelementStart(0, "mat-form-field", 16);
ɵngcc0.ɵɵelementStart(1, "mat-select", 17);
ɵngcc0.ɵɵlistener("selectionChange", function MatPaginator_div_2_mat_form_field_3_Template_mat_select_selectionChange_1_listener($event) { ɵngcc0.ɵɵrestoreView(_r8); const ctx_r7 = ɵngcc0.ɵɵnextContext(2); return ctx_r7._changePageSize($event.value); });
ɵngcc0.ɵɵtemplate(2, MatPaginator_div_2_mat_form_field_3_mat_option_2_Template, 2, 2, "mat-option", 18);
ɵngcc0.ɵɵelementEnd();
ɵngcc0.ɵɵelementEnd();
} if (rf & 2) {
const ctx_r3 = ɵngcc0.ɵɵnextContext(2);
ɵngcc0.ɵɵproperty("appearance", ctx_r3._formFieldAppearance)("color", ctx_r3.color);
ɵngcc0.ɵɵadvance(1);
ɵngcc0.ɵɵproperty("value", ctx_r3.pageSize)("disabled", ctx_r3.disabled)("aria-label", ctx_r3._intl.itemsPerPageLabel);
ɵngcc0.ɵɵadvance(1);
ɵngcc0.ɵɵproperty("ngForOf", ctx_r3._displayedPageSizeOptions);
} }
function MatPaginator_div_2_div_4_Template(rf, ctx) { if (rf & 1) {
ɵngcc0.ɵɵelementStart(0, "div", 20);
ɵngcc0.ɵɵtext(1);
ɵngcc0.ɵɵelementEnd();
} if (rf & 2) {
const ctx_r4 = ɵngcc0.ɵɵnextContext(2);
ɵngcc0.ɵɵadvance(1);
ɵngcc0.ɵɵtextInterpolate(ctx_r4.pageSize);
} }
function MatPaginator_div_2_Template(rf, ctx) { if (rf & 1) {
ɵngcc0.ɵɵelementStart(0, "div", 12);
ɵngcc0.ɵɵelementStart(1, "div", 13);
ɵngcc0.ɵɵtext(2);
ɵngcc0.ɵɵelementEnd();
ɵngcc0.ɵɵtemplate(3, MatPaginator_div_2_mat_form_field_3_Template, 3, 6, "mat-form-field", 14);
ɵngcc0.ɵɵtemplate(4, MatPaginator_div_2_div_4_Template, 2, 1, "div", 15);
ɵngcc0.ɵɵelementEnd();
} if (rf & 2) {
const ctx_r0 = ɵngcc0.ɵɵnextContext();
ɵngcc0.ɵɵadvance(2);
ɵngcc0.ɵɵtextInterpolate1(" ", ctx_r0._intl.itemsPerPageLabel, " ");
ɵngcc0.ɵɵadvance(1);
ɵngcc0.ɵɵproperty("ngIf", ctx_r0._displayedPageSizeOptions.length > 1);
ɵngcc0.ɵɵadvance(1);
ɵngcc0.ɵɵproperty("ngIf", ctx_r0._displayedPageSizeOptions.length <= 1);
} }
function MatPaginator_button_6_Template(rf, ctx) { if (rf & 1) {
const _r10 = ɵngcc0.ɵɵgetCurrentView();
ɵngcc0.ɵɵelementStart(0, "button", 21);
ɵngcc0.ɵɵlistener("click", function MatPaginator_button_6_Template_button_click_0_listener() { ɵngcc0.ɵɵrestoreView(_r10); const ctx_r9 = ɵngcc0.ɵɵnextContext(); return ctx_r9.firstPage(); });
ɵngcc0.ɵɵnamespaceSVG();
ɵngcc0.ɵɵelementStart(1, "svg", 7);
ɵngcc0.ɵɵelement(2, "path", 22);
ɵngcc0.ɵɵelementEnd();
ɵngcc0.ɵɵelementEnd();
} if (rf & 2) {
const ctx_r1 = ɵngcc0.ɵɵnextContext();
ɵngcc0.ɵɵproperty("matTooltip", ctx_r1._intl.firstPageLabel)("matTooltipDisabled", ctx_r1._previousButtonsDisabled())("matTooltipPosition", "above")("disabled", ctx_r1._previousButtonsDisabled());
ɵngcc0.ɵɵattribute("aria-label", ctx_r1._intl.firstPageLabel);
} }
function MatPaginator_button_13_Template(rf, ctx) { if (rf & 1) {
const _r12 = ɵngcc0.ɵɵgetCurrentView();
ɵngcc0.ɵɵnamespaceSVG();
ɵngcc0.ɵɵnamespaceHTML();
ɵngcc0.ɵɵelementStart(0, "button", 23);
ɵngcc0.ɵɵlistener("click", function MatPaginator_button_13_Template_button_click_0_listener() { ɵngcc0.ɵɵrestoreView(_r12); const ctx_r11 = ɵngcc0.ɵɵnextContext(); return ctx_r11.lastPage(); });
ɵngcc0.ɵɵnamespaceSVG();
ɵngcc0.ɵɵelementStart(1, "svg", 7);
ɵngcc0.ɵɵelement(2, "path", 24);
ɵngcc0.ɵɵelementEnd();
ɵngcc0.ɵɵelementEnd();
} if (rf & 2) {
const ctx_r2 = ɵngcc0.ɵɵnextContext();
ɵngcc0.ɵɵproperty("matTooltip", ctx_r2._intl.lastPageLabel)("matTooltipDisabled", ctx_r2._nextButtonsDisabled())("matTooltipPosition", "above")("disabled", ctx_r2._nextButtonsDisabled());
ɵngcc0.ɵɵattribute("aria-label", ctx_r2._intl.lastPageLabel);
} }
class MatPaginatorIntl {
constructor() {
/**
* Stream to emit from when labels are changed. Use this to notify components when the labels have
* changed after initialization.
*/
this.changes = new Subject();
/** A label for the page size selector. */
this.itemsPerPageLabel = 'Items per page:';
/** A label for the button that increments the current page. */
this.nextPageLabel = 'Next page';
/** A label for the button that decrements the current page. */
this.previousPageLabel = 'Previous page';
/** A label for the button that moves to the first page. */
this.firstPageLabel = 'First page';
/** A label for the button that moves to the last page. */
this.lastPageLabel = 'Last page';
/** A label for the range of items within the current page and the length of the whole list. */
this.getRangeLabel = (page, pageSize, length) => {
if (length == 0 || pageSize == 0) {
return `0 of ${length}`;
}
length = Math.max(length, 0);
const startIndex = page * pageSize;
// If the start index exceeds the list length, do not try and fix the end index to the end.
const endIndex = startIndex < length ?
Math.min(startIndex + pageSize, length) :
startIndex + pageSize;
return `${startIndex + 1} – ${endIndex} of ${length}`;
};
}
}
MatPaginatorIntl.ɵfac = function MatPaginatorIntl_Factory(t) { return new (t || MatPaginatorIntl)(); };
MatPaginatorIntl.ɵprov = ɵɵdefineInjectable({ factory: function MatPaginatorIntl_Factory() { return new MatPaginatorIntl(); }, token: MatPaginatorIntl, providedIn: "root" });
(function () { (typeof ngDevMode === "undefined" || ngDevMode) && ɵngcc0.ɵsetClassMetadata(MatPaginatorIntl, [{
type: Injectable,
args: [{ providedIn: 'root' }]
}], function () { return []; }, null); })();
/** @docs-private */
function MAT_PAGINATOR_INTL_PROVIDER_FACTORY(parentIntl) {
return parentIntl || new MatPaginatorIntl();
}
/** @docs-private */
const MAT_PAGINATOR_INTL_PROVIDER = {
// If there is already an MatPaginatorIntl available, use that. Otherwise, provide a new one.
provide: MatPaginatorIntl,
deps: [[new Optional(), new SkipSelf(), MatPaginatorIntl]],
useFactory: MAT_PAGINATOR_INTL_PROVIDER_FACTORY
};
/**
* @license
* 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
*/
/** The default page size if there is no page size and there are no provided page size options. */
const DEFAULT_PAGE_SIZE = 50;
/**
* Change event object that is emitted when the user selects a
* different page size or navigates to another page.
*/
class PageEvent {
}
/** Injection token that can be used to provide the default options for the paginator module. */
const MAT_PAGINATOR_DEFAULT_OPTIONS = new InjectionToken('MAT_PAGINATOR_DEFAULT_OPTIONS');
// Boilerplate for applying mixins to _MatPaginatorBase.
/** @docs-private */
class MatPaginatorMixinBase {
}
const _MatPaginatorMixinBase = mixinDisabled(mixinInitialized(MatPaginatorMixinBase));
/**
* Base class with all of the `MatPaginator` functionality.
* @docs-private
*/
class _MatPaginatorBase extends _MatPaginatorMixinBase {
constructor(_intl, _changeDetectorRef, defaults) {
super();
this._intl = _intl;
this._changeDetectorRef = _changeDetectorRef;
this._pageIndex = 0;
this._length = 0;
this._pageSizeOptions = [];
this._hidePageSize = false;
this._showFirstLastButtons = false;
/** Event emitted when the paginator changes the page size or page index. */
this.page = new EventEmitter();
this._intlChanges = _intl.changes.subscribe(() => this._changeDetectorRef.markForCheck());
if (defaults) {
const { pageSize, pageSizeOptions, hidePageSize, showFirstLastButtons, } = defaults;
if (pageSize != null) {
this._pageSize = pageSize;
}
if (pageSizeOptions != null) {
this._pageSizeOptions = pageSizeOptions;
}
if (hidePageSize != null) {
this._hidePageSize = hidePageSize;
}
if (showFirstLastButtons != null) {
this._showFirstLastButtons = showFirstLastButtons;
}
}
}
/** The zero-based page index of the displayed list of items. Defaulted to 0. */
get pageIndex() { return this._pageIndex; }
set pageIndex(value) {
this._pageIndex = Math.max(coerceNumberProperty(value), 0);
this._changeDetectorRef.markForCheck();
}
/** The length of the total number of items that are being paginated. Defaulted to 0. */
get length() { return this._length; }
set length(value) {
this._length = coerceNumberProperty(value);
this._changeDetectorRef.markForCheck();
}
/** Number of items to display on a page. By default set to 50. */
get pageSize() { return this._pageSize; }
set pageSize(value) {
this._pageSize = Math.max(coerceNumberProperty(value), 0);
this._updateDisplayedPageSizeOptions();
}
/** The set of provided page size options to display to the user. */
get pageSizeOptions() { return this._pageSizeOptions; }
set pageSizeOptions(value) {
this._pageSizeOptions = (value || []).map(p => coerceNumberProperty(p));
this._updateDisplayedPageSizeOptions();
}
/** Whether to hide the page size selection UI from the user. */
get hidePageSize() { return this._hidePageSize; }
set hidePageSize(value) {
this._hidePageSize = coerceBooleanProperty(value);
}
/** Whether to show the first/last buttons UI to the user. */
get showFirstLastButtons() { return this._showFirstLastButtons; }
set showFirstLastButtons(value) {
this._showFirstLastButtons = coerceBooleanProperty(value);
}
ngOnInit() {
this._initialized = true;
this._updateDisplayedPageSizeOptions();
this._markInitialized();
}
ngOnDestroy() {
this._intlChanges.unsubscribe();
}
/** Advances to the next page if it exists. */
nextPage() {
if (!this.hasNextPage()) {
return;
}
const previousPageIndex = this.pageIndex;
this.pageIndex++;
this._emitPageEvent(previousPageIndex);
}
/** Move back to the previous page if it exists. */
previousPage() {
if (!this.hasPreviousPage()) {
return;
}
const previousPageIndex = this.pageIndex;
this.pageIndex--;
this._emitPageEvent(previousPageIndex);
}
/** Move to the first page if not already there. */
firstPage() {
// hasPreviousPage being false implies at the start
if (!this.hasPreviousPage()) {
return;
}
const previousPageIndex = this.pageIndex;
this.pageIndex = 0;
this._emitPageEvent(previousPageIndex);
}
/** Move to the last page if not already there. */
lastPage() {
// hasNextPage being false implies at the end
if (!this.hasNextPage()) {
return;
}
const previousPageIndex = this.pageIndex;
this.pageIndex = this.getNumberOfPages() - 1;
this._emitPageEvent(previousPageIndex);
}
/** Whether there is a previous page. */
hasPreviousPage() {
return this.pageIndex >= 1 && this.pageSize != 0;
}
/** Whether there is a next page. */
hasNextPage() {
const maxPageIndex = this.getNumberOfPages() - 1;
return this.pageIndex < maxPageIndex && this.pageSize != 0;
}
/** Calculate the number of pages */
getNumberOfPages() {
if (!this.pageSize) {
return 0;
}
return Math.ceil(this.length / this.pageSize);
}
/**
* Changes the page size so that the first item displayed on the page will still be
* displayed using the new page size.
*
* For example, if the page size is 10 and on the second page (items indexed 10-19) then
* switching so that the page size is 5 will set the third page as the current page so
* that the 10th item will still be displayed.
*/
_changePageSize(pageSize) {
// Current page needs to be updated to reflect the new page size. Navigate to the page
// containing the previous page's first item.
const startIndex = this.pageIndex * this.pageSize;
const previousPageIndex = this.pageIndex;
this.pageIndex = Math.floor(startIndex / pageSize) || 0;
this.pageSize = pageSize;
this._emitPageEvent(previousPageIndex);
}
/** Checks whether the buttons for going forwards should be disabled. */
_nextButtonsDisabled() {
return this.disabled || !this.hasNextPage();
}
/** Checks whether the buttons for going backwards should be disabled. */
_previousButtonsDisabled() {
return this.disabled || !this.hasPreviousPage();
}
/**
* Updates the list of page size options to display to the user. Includes making sure that
* the page size is an option and that the list is sorted.
*/
_updateDisplayedPageSizeOptions() {
if (!this._initialized) {
return;
}
// If no page size is provided, use the first page size option or the default page size.
if (!this.pageSize) {
this._pageSize = this.pageSizeOptions.length != 0 ?
this.pageSizeOptions[0] :
DEFAULT_PAGE_SIZE;
}
this._displayedPageSizeOptions = this.pageSizeOptions.slice();
if (this._displayedPageSizeOptions.indexOf(this.pageSize) === -1) {
this._displayedPageSizeOptions.push(this.pageSize);
}
// Sort the numbers using a number-specific sort function.
this._displayedPageSizeOptions.sort((a, b) => a - b);
this._changeDetectorRef.markForCheck();
}
/** Emits an event notifying that a change of the paginator's properties has been triggered. */
_emitPageEvent(previousPageIndex) {
this.page.emit({
previousPageIndex,
pageIndex: this.pageIndex,
pageSize: this.pageSize,
length: this.length
});
}
}
_MatPaginatorBase.ɵfac = function _MatPaginatorBase_Factory(t) { return new (t || _MatPaginatorBase)(ɵngcc0.ɵɵdirectiveInject(MatPaginatorIntl), ɵngcc0.ɵɵdirectiveInject(ɵngcc0.ChangeDetectorRef), ɵngcc0.ɵɵdirectiveInject(undefined)); };
_MatPaginatorBase.ɵdir = ɵngcc0.ɵɵdefineDirective({ type: _MatPaginatorBase, inputs: { pageIndex: "pageIndex", length: "length", pageSize: "pageSize", pageSizeOptions: "pageSizeOptions", hidePageSize: "hidePageSize", showFirstLastButtons: "showFirstLastButtons", color: "color" }, outputs: { page: "page" }, features: [ɵngcc0.ɵɵInheritDefinitionFeature] });
_MatPaginatorBase.ctorParameters = () => [
{ type: MatPaginatorIntl },
{ type: ChangeDetectorRef },
{ type: undefined }
];
_MatPaginatorBase.propDecorators = {
color: [{ type: Input }],
pageIndex: [{ type: Input }],
length: [{ type: Input }],
pageSize: [{ type: Input }],
pageSizeOptions: [{ type: Input }],
hidePageSize: [{ type: Input }],
showFirstLastButtons: [{ type: Input }],
page: [{ type: Output }]
};
(function () { (typeof ngDevMode === "undefined" || ngDevMode) && ɵngcc0.ɵsetClassMetadata(_MatPaginatorBase, [{
type: Directive
}], function () { return [{ type: MatPaginatorIntl }, { type: ɵngcc0.ChangeDetectorRef }, { type: undefined }]; }, { page: [{
type: Output
}], pageIndex: [{
type: Input
}], length: [{
type: Input
}], pageSize: [{
type: Input
}], pageSizeOptions: [{
type: Input
}], hidePageSize: [{
type: Input
}], showFirstLastButtons: [{
type: Input
}], color: [{
type: Input
}] }); })();
/**
* Component to provide navigation between paged information. Displays the size of the current
* page, user-selectable options to change that size, what items are being shown, and
* navigational button to go to the previous or next page.
*/
class MatPaginator extends _MatPaginatorBase {
constructor(intl, changeDetectorRef, defaults) {
super(intl, changeDetectorRef, defaults);
if (defaults && defaults.formFieldAppearance != null) {
this._formFieldAppearance = defaults.formFieldAppearance;
}
}
}
MatPaginator.ɵfac = function MatPaginator_Factory(t) { return new (t || MatPaginator)(ɵngcc0.ɵɵdirectiveInject(MatPaginatorIntl), ɵngcc0.ɵɵdirectiveInject(ɵngcc0.ChangeDetectorRef), ɵngcc0.ɵɵdirectiveInject(MAT_PAGINATOR_DEFAULT_OPTIONS, 8)); };
MatPaginator.ɵcmp = ɵngcc0.ɵɵdefineComponent({ type: MatPaginator, selectors: [["mat-paginator"]], hostAttrs: [1, "mat-paginator"], inputs: { disabled: "disabled" }, exportAs: ["matPaginator"], features: [ɵngcc0.ɵɵInheritDefinitionFeature], decls: 14, vars: 14, consts: [[1, "mat-paginator-outer-container"], [1, "mat-paginator-container"], ["class", "mat-paginator-page-size", 4, "ngIf"], [1, "mat-paginator-range-actions"], [1, "mat-paginator-range-label"], ["mat-icon-button", "", "type", "button", "class", "mat-paginator-navigation-first", 3, "matTooltip", "matTooltipDisabled", "matTooltipPosition", "disabled", "click", 4, "ngIf"], ["mat-icon-button", "", "type", "button", 1, "mat-paginator-navigation-previous", 3, "matTooltip", "matTooltipDisabled", "matTooltipPosition", "disabled", "click"], ["viewBox", "0 0 24 24", "focusable", "false", 1, "mat-paginator-icon"], ["d", "M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"], ["mat-icon-button", "", "type", "button", 1, "mat-paginator-navigation-next", 3, "matTooltip", "matTooltipDisabled", "matTooltipPosition", "disabled", "click"], ["d", "M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"], ["mat-icon-button", "", "type", "button", "class", "mat-paginator-navigation-last", 3, "matTooltip", "matTooltipDisabled", "matTooltipPosition", "disabled", "click", 4, "ngIf"], [1, "mat-paginator-page-size"], [1, "mat-paginator-page-size-label"], ["class", "mat-paginator-page-size-select", 3, "appearance", "color", 4, "ngIf"], ["class", "mat-paginator-page-size-value", 4, "ngIf"], [1, "mat-paginator-page-size-select", 3, "appearance", "color"], [3, "value", "disabled", "aria-label", "selectionChange"], [3, "value", 4, "ngFor", "ngForOf"], [3, "value"], [1, "mat-paginator-page-size-value"], ["mat-icon-button", "", "type", "button", 1, "mat-paginator-navigation-first", 3, "matTooltip", "matTooltipDisabled", "matTooltipPosition", "disabled", "click"], ["d", "M18.41 16.59L13.82 12l4.59-4.59L17 6l-6 6 6 6zM6 6h2v12H6z"], ["mat-icon-button", "", "type", "button", 1, "mat-paginator-navigation-last", 3, "matTooltip", "matTooltipDisabled", "matTooltipPosition", "disabled", "click"], ["d", "M5.59 7.41L10.18 12l-4.59 4.59L7 18l6-6-6-6zM16 6h2v12h-2z"]], template: function MatPaginator_Template(rf, ctx) { if (rf & 1) {
ɵngcc0.ɵɵelementStart(0, "div", 0);
ɵngcc0.ɵɵelementStart(1, "div", 1);
ɵngcc0.ɵɵtemplate(2, MatPaginator_div_2_Template, 5, 3, "div", 2);
ɵngcc0.ɵɵelementStart(3, "div", 3);
ɵngcc0.ɵɵelementStart(4, "div", 4);
ɵngcc0.ɵɵtext(5);
ɵngcc0.ɵɵelementEnd();
ɵngcc0.ɵɵtemplate(6, MatPaginator_button_6_Template, 3, 5, "button", 5);
ɵngcc0.ɵɵelementStart(7, "button", 6);
ɵngcc0.ɵɵlistener("click", function MatPaginator_Template_button_click_7_listener() { return ctx.previousPage(); });
ɵngcc0.ɵɵnamespaceSVG();
ɵngcc0.ɵɵelementStart(8, "svg", 7);
ɵngcc0.ɵɵelement(9, "path", 8);
ɵngcc0.ɵɵelementEnd();
ɵngcc0.ɵɵelementEnd();
ɵngcc0.ɵɵnamespaceHTML();
ɵngcc0.ɵɵelementStart(10, "button", 9);
ɵngcc0.ɵɵlistener("click", function MatPaginator_Template_button_click_10_listener() { return ctx.nextPage(); });
ɵngcc0.ɵɵnamespaceSVG();
ɵngcc0.ɵɵelementStart(11, "svg", 7);
ɵngcc0.ɵɵelement(12, "path", 10);
ɵngcc0.ɵɵelementEnd();
ɵngcc0.ɵɵelementEnd();
ɵngcc0.ɵɵtemplate(13, MatPaginator_button_13_Template, 3, 5, "button", 11);
ɵngcc0.ɵɵelementEnd();
ɵngcc0.ɵɵelementEnd();
ɵngcc0.ɵɵelementEnd();
} if (rf & 2) {
ɵngcc0.ɵɵadvance(2);
ɵngcc0.ɵɵproperty("ngIf", !ctx.hidePageSize);
ɵngcc0.ɵɵadvance(3);
ɵngcc0.ɵɵtextInterpolate1(" ", ctx._intl.getRangeLabel(ctx.pageIndex, ctx.pageSize, ctx.length), " ");
ɵngcc0.ɵɵadvance(1);
ɵngcc0.ɵɵproperty("ngIf", ctx.showFirstLastButtons);
ɵngcc0.ɵɵadvance(1);
ɵngcc0.ɵɵproperty("matTooltip", ctx._intl.previousPageLabel)("matTooltipDisabled", ctx._previousButtonsDisabled())("matTooltipPosition", "above")("disabled", ctx._previousButtonsDisabled());
ɵngcc0.ɵɵattribute("aria-label", ctx._intl.previousPageLabel);
ɵngcc0.ɵɵadvance(3);
ɵngcc0.ɵɵproperty("matTooltip", ctx._intl.nextPageLabel)("matTooltipDisabled", ctx._nextButtonsDisabled())("matTooltipPosition", "above")("disabled", ctx._nextButtonsDisabled());
ɵngcc0.ɵɵattribute("aria-label", ctx._intl.nextPageLabel);
ɵngcc0.ɵɵadvance(3);
ɵngcc0.ɵɵproperty("ngIf", ctx.showFirstLastButtons);
} }, directives: [ɵngcc1.NgIf, ɵngcc2.MatButton, ɵngcc3.MatTooltip, ɵngcc4.MatFormField, ɵngcc5.MatSelect, ɵngcc1.NgForOf, ɵngcc6.MatOption], styles: [".mat-paginator{display:block}.mat-paginator-outer-container{display:flex}.mat-paginator-container{display:flex;align-items:center;justify-content:flex-end;padding:0 8px;flex-wrap:wrap-reverse;width:100%}.mat-paginator-page-size{display:flex;align-items:baseline;margin-right:8px}[dir=rtl] .mat-paginator-page-size{margin-right:0;margin-left:8px}.mat-paginator-page-size-label{margin:0 4px}.mat-paginator-page-size-select{margin:6px 4px 0 4px;width:56px}.mat-paginator-page-size-select.mat-form-field-appearance-outline{width:64px}.mat-paginator-page-size-select.mat-form-field-appearance-fill{width:64px}.mat-paginator-range-label{margin:0 32px 0 24px}.mat-paginator-range-actions{display:flex;align-items:center}.mat-paginator-icon{width:28px;fill:currentColor}[dir=rtl] .mat-paginator-icon{transform:rotate(180deg)}\n"], encapsulation: 2, changeDetection: 0 });
MatPaginator.ctorParameters = () => [
{ type: MatPaginatorIntl },
{ type: ChangeDetectorRef },
{ type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [MAT_PAGINATOR_DEFAULT_OPTIONS,] }] }
];
(function () { (typeof ngDevMode === "undefined" || ngDevMode) && ɵngcc0.ɵsetClassMetadata(MatPaginator, [{
type: Component,
args: [{
selector: 'mat-paginator',
exportAs: 'matPaginator',
template: "<div class=\"mat-paginator-outer-container\">\n <div class=\"mat-paginator-container\">\n <div class=\"mat-paginator-page-size\" *ngIf=\"!hidePageSize\">\n <div class=\"mat-paginator-page-size-label\">\n {{_intl.itemsPerPageLabel}}\n </div>\n\n <mat-form-field\n *ngIf=\"_displayedPageSizeOptions.length > 1\"\n [appearance]=\"_formFieldAppearance!\"\n [color]=\"color\"\n class=\"mat-paginator-page-size-select\">\n <mat-select\n [value]=\"pageSize\"\n [disabled]=\"disabled\"\n [aria-label]=\"_intl.itemsPerPageLabel\"\n (selectionChange)=\"_changePageSize($event.value)\">\n <mat-option *ngFor=\"let pageSizeOption of _displayedPageSizeOptions\" [value]=\"pageSizeOption\">\n {{pageSizeOption}}\n </mat-option>\n </mat-select>\n </mat-form-field>\n\n <div\n class=\"mat-paginator-page-size-value\"\n *ngIf=\"_displayedPageSizeOptions.length <= 1\">{{pageSize}}</div>\n </div>\n\n <div class=\"mat-paginator-range-actions\">\n <div class=\"mat-paginator-range-label\">\n {{_intl.getRangeLabel(pageIndex, pageSize, length)}}\n </div>\n\n <button mat-icon-button type=\"button\"\n class=\"mat-paginator-navigation-first\"\n (click)=\"firstPage()\"\n [attr.aria-label]=\"_intl.firstPageLabel\"\n [matTooltip]=\"_intl.firstPageLabel\"\n [matTooltipDisabled]=\"_previousButtonsDisabled()\"\n [matTooltipPosition]=\"'above'\"\n [disabled]=\"_previousButtonsDisabled()\"\n *ngIf=\"showFirstLastButtons\">\n <svg class=\"mat-paginator-icon\" viewBox=\"0 0 24 24\" focusable=\"false\">\n <path d=\"M18.41 16.59L13.82 12l4.59-4.59L17 6l-6 6 6 6zM6 6h2v12H6z\"/>\n </svg>\n </button>\n <button mat-icon-button type=\"button\"\n class=\"mat-paginator-navigation-previous\"\n (click)=\"previousPage()\"\n [attr.aria-label]=\"_intl.previousPageLabel\"\n [matTooltip]=\"_intl.previousPageLabel\"\n [matTooltipDisabled]=\"_previousButtonsDisabled()\"\n [matTooltipPosition]=\"'above'\"\n [disabled]=\"_previousButtonsDisabled()\">\n <svg class=\"mat-paginator-icon\" viewBox=\"0 0 24 24\" focusable=\"false\">\n <path d=\"M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z\"/>\n </svg>\n </button>\n <button mat-icon-button type=\"button\"\n class=\"mat-paginator-navigation-next\"\n (click)=\"nextPage()\"\n [attr.aria-label]=\"_intl.nextPageLabel\"\n [matTooltip]=\"_intl.nextPageLabel\"\n [matTooltipDisabled]=\"_nextButtonsDisabled()\"\n [matTooltipPosition]=\"'above'\"\n [disabled]=\"_nextButtonsDisabled()\">\n <svg class=\"mat-paginator-icon\" viewBox=\"0 0 24 24\" focusable=\"false\">\n <path d=\"M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z\"/>\n </svg>\n </button>\n <button mat-icon-button type=\"button\"\n class=\"mat-paginator-navigation-last\"\n (click)=\"lastPage()\"\n [attr.aria-label]=\"_intl.lastPageLabel\"\n [matTooltip]=\"_intl.lastPageLabel\"\n [matTooltipDisabled]=\"_nextButtonsDisabled()\"\n [matTooltipPosition]=\"'above'\"\n [disabled]=\"_nextButtonsDisabled()\"\n *ngIf=\"showFirstLastButtons\">\n <svg class=\"mat-paginator-icon\" viewBox=\"0 0 24 24\" focusable=\"false\">\n <path d=\"M5.59 7.41L10.18 12l-4.59 4.59L7 18l6-6-6-6zM16 6h2v12h-2z\"/>\n </svg>\n </button>\n </div>\n </div>\n</div>\n",
inputs: ['disabled'],
host: {
'class': 'mat-paginator'
},
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
styles: [".mat-paginator{display:block}.mat-paginator-outer-container{display:flex}.mat-paginator-container{display:flex;align-items:center;justify-content:flex-end;padding:0 8px;flex-wrap:wrap-reverse;width:100%}.mat-paginator-page-size{display:flex;align-items:baseline;margin-right:8px}[dir=rtl] .mat-paginator-page-size{margin-right:0;margin-left:8px}.mat-paginator-page-size-label{margin:0 4px}.mat-paginator-page-size-select{margin:6px 4px 0 4px;width:56px}.mat-paginator-page-size-select.mat-form-field-appearance-outline{width:64px}.mat-paginator-page-size-select.mat-form-field-appearance-fill{width:64px}.mat-paginator-range-label{margin:0 32px 0 24px}.mat-paginator-range-actions{display:flex;align-items:center}.mat-paginator-icon{width:28px;fill:currentColor}[dir=rtl] .mat-paginator-icon{transform:rotate(180deg)}\n"]
}]
}], function () { return [{ type: MatPaginatorIntl }, { type: ɵngcc0.ChangeDetectorRef }, { type: undefined, decorators: [{
type: Optional
}, {
type: Inject,
args: [MAT_PAGINATOR_DEFAULT_OPTIONS]
}] }]; }, null); })();
/**
* @license
* 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
*/
class MatPaginatorModule {
}
MatPaginatorModule.ɵfac = function MatPaginatorModule_Factory(t) { return new (t || MatPaginatorModule)(); };
MatPaginatorModule.ɵmod = ɵngcc0.ɵɵdefineNgModule({ type: MatPaginatorModule });
MatPaginatorModule.ɵinj = ɵngcc0.ɵɵdefineInjector({ providers: [MAT_PAGINATOR_INTL_PROVIDER], imports: [[
CommonModule,
MatButtonModule,
MatSelectModule,
MatTooltipModule,
MatCommonModule,
]] });
(function () { (typeof ngJitMode === "undefined" || ngJitMode) && ɵngcc0.ɵɵsetNgModuleScope(MatPaginatorModule, { declarations: function () { return [MatPaginator]; }, imports: function () { return [CommonModule,
MatButtonModule,
MatSelectModule,
MatTooltipModule,
MatCommonModule]; }, exports: function () { return [MatPaginator]; } }); })();
(function () { (typeof ngDevMode === "undefined" || ngDevMode) && ɵngcc0.ɵsetClassMetadata(MatPaginatorModule, [{
type: NgModule,
args: [{
imports: [
CommonModule,
MatButtonModule,
MatSelectModule,
MatTooltipModule,
MatCommonModule,
],
exports: [MatPaginator],
declarations: [MatPaginator],
providers: [MAT_PAGINATOR_INTL_PROVIDER]
}]
}], null, null); })();
/**
* @license
* 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
*/
/**
* Generated bundle index. Do not edit.
*/
export { MAT_PAGINATOR_DEFAULT_OPTIONS, MAT_PAGINATOR_INTL_PROVIDER, MAT_PAGINATOR_INTL_PROVIDER_FACTORY, MatPaginator, MatPaginatorIntl, MatPaginatorModule, PageEvent, _MatPaginatorBase };
//# sourceMappingURL=paginator.js.map
|
import numpy
from keras.layers import np
from keras.utils import Sequence
from utils import load_image, augment, preprocess, resize
APPLY_DATA_AUGMENTATION = True
class AutoencoderBatchGenerator(Sequence):
"""
Single image based batch generator. Generated inputs == generated labels (i.e., x == y) as required by autoencoders
"""
def __init__(self, path_to_pictures: numpy.array, anomaly_detector, data_dir: str, batch_size: int):
self.data_dir = data_dir
self.batch_size = batch_size
self.path_to_pictures = path_to_pictures
self.model = anomaly_detector
def __getitem__(self, index):
start_index = index * self.batch_size
end_index = start_index + self.batch_size
batch_paths = self.path_to_pictures[start_index:end_index]
input_shape = self.model.get_input_shape()
x_shape = (len(batch_paths),) + (input_shape)
x = np.empty(shape=x_shape)
for i, path in enumerate(batch_paths):
# apply augmentation to 60% of the images, if enabled
if APPLY_DATA_AUGMENTATION and np.random.rand() < 0.6:
# data augmentation
img = load_image(self.data_dir, path)
img = augment(img)
img = preprocess(img) # crop + resize + rgb2yuv
else:
img = load_image(self.data_dir, path)
img = resize(img)
x[i] = self.model.normalize_and_reshape(img)
return x, x
def __len__(self):
return len(self.path_to_pictures) // self.batch_size
def get_batch_size(self):
return self.batch_size
|
import React from 'react'
import {Row} from 'antd'
import Header from './components/Header'
import './style/common.less'
export default class Common extends React.Component {
render() {
return (
<div>
<Row className="simple-page">
<Header menuType="second"/>
</Row>
<Row className="content">
{this.props.children}
</Row>
</div>
)
}
}
|
/*
Lots of comments
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras ut lorem sem.
Vestibulum vehicula dolor ac elit dictum convallis. Vivamus rhoncus, neque id euismod tempor, justo nulla pellentesque nibh,
nec placerat mauris massa vel massa. Etiam cursus rutrum faucibus.
Mauris sem turpis, lacinia eget faucibus vel, vulputate et ante.
*/
cb.tools1 = {};
cb.tools1.substitute = function(str, arr) {
var i, pattern, re, n = arr.length;
for (i = 0; i < n; i++) {
pattern = "\\{" + i + "\\}";
re = new RegExp(pattern, "g");
str = str.replace(re, arr[i]);
}
return str;
};
|
// 匹配带id_start属性的Unicode字符
const unicode_id_start_regex = /^([A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEF\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7BF\uA7C2-\uA7C6\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB67\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE35\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2\uDD00-\uDD23\uDF00-\uDF1C\uDF27\uDF30-\uDF45\uDFE0-\uDFF6]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD44\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC5F\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDEB8\uDF00-\uDF1A]|\uD806[\uDC00-\uDC2B\uDCA0-\uDCDF\uDCFF\uDDA0-\uDDA7\uDDAA-\uDDD0\uDDE1\uDDE3\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE89\uDE9D\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46\uDD60-\uDD65\uDD67\uDD68\uDD6A-\uDD89\uDD98\uDEE0-\uDEF2]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDE40-\uDE7F\uDF00-\uDF4A\uDF50\uDF93-\uDF9F\uDFE0\uDFE1\uDFE3]|\uD821[\uDC00-\uDFF7]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD50-\uDD52\uDD64-\uDD67\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD838[\uDD00-\uDD2C\uDD37-\uDD3D\uDD4E\uDEC0-\uDEEB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43\uDD4B]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D])+$/
// 匹配带id_continue属性的Unicode字符 Unicode 12.0.0
const unicode_id_continue_regex = /^([0-9A-Z_a-z\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05EF-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u07FD\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D3-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u09FE\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1878\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1C90-\u1CBA\u1CBD-\u1CBF\u1CD0-\u1CD2\u1CD4-\u1CFA\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEF\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7BF\uA7C2-\uA7C6\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB67\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE35\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2\uDD00-\uDD27\uDD30-\uDD39\uDF00-\uDF1C\uDF27\uDF30-\uDF50\uDFE0-\uDFF6]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD44-\uDD46\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDC9-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3B-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC5E\uDC5F\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB8\uDEC0-\uDEC9\uDF00-\uDF1A\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDC00-\uDC3A\uDCA0-\uDCE9\uDCFF\uDDA0-\uDDA7\uDDAA-\uDDD7\uDDDA-\uDDE1\uDDE3\uDDE4\uDE00-\uDE3E\uDE47\uDE50-\uDE99\uDE9D\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59\uDD60-\uDD65\uDD67\uDD68\uDD6A-\uDD8E\uDD90\uDD91\uDD93-\uDD98\uDDA0-\uDDA9\uDEE0-\uDEF6]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDE40-\uDE7F\uDF00-\uDF4A\uDF4F-\uDF87\uDF8F-\uDF9F\uDFE0\uDFE1\uDFE3]|\uD821[\uDC00-\uDFF7]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD50-\uDD52\uDD64-\uDD67\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A\uDD00-\uDD2C\uDD30-\uDD3D\uDD40-\uDD49\uDD4E\uDEC0-\uDEF9]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4B\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF])+$/
// 关键字 ES6+
const keywords = ['await', 'break', 'case', 'class', 'const', 'continue',
'debugger', 'default', 'delete', 'do', 'else', 'export', 'extends', 'finally',
'for', 'function', 'if', 'import', 'in', 'instanceof', 'new', 'return', 'super',
'switch', 'this', 'throw', 'try', 'typeof', 'var', 'void', 'while', 'with', 'yield']
/** let和static并不是通过词法分析的时候来检测的,而是在静态语义(Static Semantics)分析的时候进行限制
* 所以let和static并不在保留字当中
*/
const ss = ['let', 'static']
// 关键字ES5
const keywordsES5 = ['break', 'do', 'instanceof', 'typeof', 'case', 'else', 'new', 'var',
'catch', 'finally', 'return', 'void', 'continue', 'for', 'switch', 'while', 'debugger',
'function', 'this', 'with', 'default', 'if', 'throw', 'delete', 'in', 'try']
// 未来保留字 ES6+
const futureReservedWords = ['enum']
// 未来保留字 ES5
const futureReservedWordsES5 = ['class', 'enum', 'extends', 'super',
'const', 'export', 'import']
// 严格模式下的未来保留字 ES6+
const strictFutureReservedWords = ['implements', 'package', 'protected', 'interface', 'private', 'public']
// 严格模式下的未来保留字 ES5
const strictFutureReservedWordsES5 = ['implements', 'let', 'private', 'public', 'yield', 'interface',
'package', 'protected', 'static']
// null字面量
const nullLiteral = ['null']
// boolean字面量
const booleanLiteral = ['true', 'false']
var ES6, ES5, ES2018
const AllVersionError = {
ES5: false,
ES6: false,
ES2018: false
}
/** 是否可以作为标识start部分 */
function isIdentifierStart (ch) {
/** 如果start能够匹配$ _ 和带有id_start属性的Unicode字符(\u1234)
* 那么这个start部分是符合ES5和ES6共同的标准
*/
if (/[$_]/.test(ch) || unicode_id_start_regex.test(ch)) {
ES5 = true
ES6 = true
ES2018 = true
return
}
/**
* 在这里需要去分辨是可以在ES6环境中运行的,还是ES2018环境中运行的
*/
if (/^\\u\{([a-fA-F0-9]{1,})\}$/.test(ch)) {
console.log('regexp', RegExp.$1)
}
return false
}
/** 是否可以作为标识part部分 */
function isIdentifierPart (ch) {
// 当part部分没有的时候,也是符合规范的,所以返回true
if (/[$]/.test(ch) || unicode_id_continue_regex.test(ch) || ch === '') {
ES5 = true
ES6 = true
}
return false
}
/** 将一个变量分割成start和part部分 [start, part]*/
function splitStartAndPart (varName) {
// 只要第一个字符不以\开头,那么start都为第一个字符
if (varName[0] !== '\\') return [varName.substr(0, 1), varName.substr(1)]
if (/^\\u[a-fA-F0-9]{4}/.test(varName)) return [varName.substr(0, 6), varName.substr(6)]
// if (/^\\u\{([a-fA-F0-9]{1,6})\}/.test(varName))
// if (/^\\u\{[a-fA-F0-9]{1,6}\}/.test(varName))
let result = []
result[1] = varName.replace(/^\\u\{([a-fA-F0-9]{1,6})\}/g, ($0) => {
result[0] = $0
ES5 = false // \u{codepoint}这个规则是ES5不支持的语法 只有ES6+支持
return ''
})
return result
}
export default function (varName) {
if (!varName) return AllVersionError
/** 根据关键字或者保留字判断ES5环境通过还是ES6环境通过检测 */
// 不能为保留字 ES6+
if (
keywords.indexOf(varName) !== -1
|| ss.indexOf(varName) !== -1
|| futureReservedWords.indexOf(varName) !== -1
|| strictFutureReservedWords.indexOf(varName) !== -1
|| nullLiteral.indexOf(varName) !== -1
|| booleanLiteral.indexOf(varName) !== -1
) {
ES6 = false
} else {
ES6 = true
ES2018 = true
}
// 不能为保留字 ES5
if (
keywordsES5.indexOf(varName) !== -1
|| futureReservedWordsES5.indexOf(varName) !== -1
|| strictFutureReservedWordsES5.indexOf(varName) !== -1
|| nullLiteral.indexOf(varName) !== -1
|| booleanLiteral.indexOf(varName) !== -1
) {
ES5 = false
} else {
ES5 = true
}
// 如果在ES5和ES6的环境上都无法通过,则直接返回全部失败
if (!ES5 && !ES6) return AllVersionError
// 匹配到了\uxxx (x的个数为0-3) 就一定不符合ES5或者ES6+ 中转义字符应该是\uxxxx的规则 也全部返回失败
if (/\\u[a-fA-F0-9]{0,3}[^a-fA-F0-9]*$/.test(varName)) return AllVersionError
/**
* \u{codepoint} 的语法是ES2018才开始有的 并且codepoint 必须小于0x10ffff
* 在ES6 - ES2017 规则为\u{HexDigits} 而HexDigits只要是16进制的数字即可,没有大小限制
* 在ES5中并没有\u{xxx} 这样的语法
*/
if (/\\u\{([a-fA-F0-9]{1,})\}/.test(varName)) {
ES5 = false
ES6 = ES2018 = true
}
var startAndPart = splitStartAndPart(varName)
isIdentifierStart(startAndPart[0])
isIdentifierPart(startAndPart[1])
let start = startAndPart[0]
let part = startAndPart[1]
console.log([start, part])
return {
ES5,
ES6
}
}
|
"""nomnom_server URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import include, path
from django.conf.urls import include
from nomnom import views
urlpatterns = [
path('api-auth/', include('nomnom.urls')),
path('admin/', admin.site.urls),
path('', views.index, name='index'),
path('assets/FontManifest.json', views.fontmanifest, name='fontmanifest'),
path('assets/AssetManifest.json', views.assetmanifest, name='assetmanifest'),
path('assets/fonts/MaterialIcons-Regular.ttf',
views.materialicons, name='materialicons'),
path('assets/packages/cupertino_icons/assets/CupertinoIcons.ttf',
views.cupertinoicons, name='cupertinoicons'),
path('assets/resources/images/nomnomlogo_book_only.png',
views.logo, name='logo'),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
|
// var phonecatAnimations = angular.module('phonecatAnimations', ['ngAnimate']);
//
// phonecatAnimations.animation('.phone', function() {
//
// var animateUp = function(element, className, done) {
// if(className != 'active') {
// return;
// }
// element.css({
// position: 'absolute',
// top: 500,
// left: 0,
// display: 'block'
// });
//
// jQuery(element).animate({
// top: 0
// }, done);
//
// return function(cancel) {
// if(cancel) {
// element.stop();
// }
// };
// }
//
// var animateDown = function(element, className, done) {
// if(className != 'active') {
// return;
// }
// element.css({
// position: 'absolute',
// left: 0,
// top: 0
// });
//
// jQuery(element).animate({
// top: -500
// }, done);
//
// return function(cancel) {
// if(cancel) {
// element.stop();
// }
// };
// }
//
// return {
// addClass: animateUp,
// removeClass: animateDown
// };
// });
|
import { useSelector, useDispatch } from "react-redux";
import * as sel from "selectors";
import * as ta from "actions/TransactionActions";
export function useHistoryTab() {
const window = useSelector(sel.mainWindow);
const tsDate = useSelector(sel.tsDate);
const currencyDisplay = useSelector(sel.currencyDisplay);
const unitDivisor = useSelector(sel.unitDivisor);
const transactions = useSelector(sel.filteredRegularTxs);
const transactionsFilter = useSelector(sel.transactionsFilter);
const noMoreTransactions = useSelector(sel.noMoreRegularTxs);
const totalBalance = useSelector(sel.totalBalance);
const dispatch = useDispatch();
const onGetTransactions = (isStake) => dispatch(ta.getTransactions(isStake));
const onChangeTransactionsFilter = (newFilter) =>
dispatch(ta.changeTransactionsFilter(newFilter));
return {
window,
tsDate,
currencyDisplay,
unitDivisor,
transactions,
transactionsFilter,
totalBalance,
noMoreTransactions,
onGetTransactions,
onChangeTransactionsFilter
};
}
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class ApplicationGatewayBackendHealthHttpSettings(Model):
"""Application gateway BackendHealthHttp settings.
:param backend_http_settings: Reference of an
ApplicationGatewayBackendHttpSettings resource.
:type backend_http_settings:
~azure.mgmt.network.v2018_11_01.models.ApplicationGatewayBackendHttpSettings
:param servers: List of ApplicationGatewayBackendHealthServer resources.
:type servers:
list[~azure.mgmt.network.v2018_11_01.models.ApplicationGatewayBackendHealthServer]
"""
_attribute_map = {
'backend_http_settings': {'key': 'backendHttpSettings', 'type': 'ApplicationGatewayBackendHttpSettings'},
'servers': {'key': 'servers', 'type': '[ApplicationGatewayBackendHealthServer]'},
}
def __init__(self, *, backend_http_settings=None, servers=None, **kwargs) -> None:
super(ApplicationGatewayBackendHealthHttpSettings, self).__init__(**kwargs)
self.backend_http_settings = backend_http_settings
self.servers = servers
|
import LinkComponent from '@ember/routing/link-component';
import layout from '../../templates/components/uk-tab/item';
export default LinkComponent.extend({
layout,
tagName: 'li',
activeClass: 'uk-active',
classNameBindings: ['disabled:uk-disabled'],
disabled: false
});
|
/**
******************************************************************************
* @file Project/Template/stm32f10x_it.h
* @author MCD Application Team
* @version V3.1.2
* @date 09/28/2009
* @brief This file contains the headers of the interrupt handlers.
******************************************************************************
* @copy
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2009 STMicroelectronics</center></h2>
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32F10x_IT_H
#define __STM32F10x_IT_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32f10x.h"
/* Exported types ------------------------------------------------------------*/
/* Exported constants --------------------------------------------------------*/
/* Exported macro ------------------------------------------------------------*/
/* Exported functions ------------------------------------------------------- */
void NMI_Handler(void);
void HardFault_Handler(void);
void MemManage_Handler(void);
void BusFault_Handler(void);
void UsageFault_Handler(void);
void SVC_Handler(void);
void DebugMon_Handler(void);
void PendSV_Handler(void);
void SysTick_Handler(void);
#ifdef __cplusplus
}
#endif
#endif /* __STM32F10x_IT_H */
/******************* (C) COPYRIGHT 2009 STMicroelectronics *****END OF FILE****/
|
import tvm
from tvm import relay
from tvm.contrib import graph_executor as runtime
from tvm.relay.transform.pattern_manager.utils import is_function_node
from tvm.relay.transform.pattern_manager.target import measure, NUM_MEASUREMENTS_PER_REPEAT, NUM_REPEATS, AUTOSCH_LOG
from tvm.relay.transform.pattern_manager.target import OPT_LEVEL
from tvm.collage.optimizer.custom_fusion_pass import *
from tvm.collage.optimizer.optimizer_utils import *
from tvm import autotvm, auto_scheduler
from measure_end_to_end import verify_network_output
from workloads.onnx_workloads import get_network_from_onnx
from workloads.torch_workloads import *
from workloads.relay_workloads import get_network_from_relay
import numpy as np
import argparse
from workloads.workloads import WORKLOADS_DIC
def build_network(net, params, mode, net_name, hw_name, batch_size):
assert is_function_node(net)
assert CustomFusionPass.has_value(mode)
net = net.with_attr("CustomFusionPass", mode)
net = net.with_attr(NETWORK_FUNC_ATTR, net_name)
net = net.with_attr(HW_FUNC_ATTR, hw_name)
net = net.with_attr(BATCH_SIZE_ATTR, batch_size)
with autotvm.apply_history_best(get_autotvm_log_path(hw_name)):
with tvm.transform.PassContext(opt_level=OPT_LEVEL.get()):
# with tvm.transform.PassContext(opt_level=OPT_LEVEL.get(), trace=print_ir):
lib = relay.build(net, "cuda", params=params)
return lib
def measure_network(lib, target_str, shape_dict):
# Create workload
dev = tvm.device(target_str, 0)
module = runtime.GraphModule(lib["default"](dev))
# Setup execution
for input_name, input_shape in shape_dict.items():
input_data = np.random.uniform(-1, 1, size=input_shape).astype("float32")
module.set_input(input_name, input_data)
ftimer = module.module.time_evaluator("run", dev, number=NUM_MEASUREMENTS_PER_REPEAT, repeat=NUM_REPEATS)
return measure(ftimer, is_net=False)
def build_network_tensorrt(mod, params):
from tvm.relay.op.contrib.tensorrt import partition_for_tensorrt
mod, config = partition_for_tensorrt(mod, params)
# print("-"*50)
# print("Expr" + "-"*30)
# print(repr(mod["main"]))
# print("config" + "-"*30)
# print(config)
# visualize_network(mod["main"], "o3_resnet_tensorrt")
target = "cuda"
with tvm.transform.PassContext(opt_level=OPT_LEVEL.get(), config={'relay.ext.tensorrt.options': config}):
lib = relay.build(mod, target=target, params=params)
printe("Built done")
lib.export_library('compiled.so')
dev = tvm.gpu(0)
loaded_lib = tvm.runtime.load_module('compiled.so')
module = tvm.contrib.graph_executor.GraphModule(loaded_lib['default'](dev))
def args_checker(args, parser):
is_missing_arg = not args.network
is_missing_arg |= not args.hw
# is_missing_arg |= not args.target
# is_missing_arg |= not args.dtype
# is_missing_arg |= not args.batch_size
if is_missing_arg:
parser.error('Make sure you input all arguments')
def get_args():
parser = argparse.ArgumentParser()
# Default type is string for argparse
parser.add_argument("-n", "--network", help="name of a neural network")
parser.add_argument("-hw", "--hw", help="target hardware")
# parser.add_argument("-t", "--target", help="target device")
# parser.add_argument("-dt", "--dtype", help="data type")
# parser.add_argument("-bs", "--batch-size", type=int, help="batch size")
args = parser.parse_args()
args_checker(args, parser)
return args
if __name__ == "__main__":
args = get_args()
# NasNet-A only works for opt_level 2 (not 3 due to the avgpool2d issue)
# if args.network == "nasneta":
# OPT_LEVEL.set(2)
# mod, params, shape_dict, _ = get_network_from_torch(args.network, 1)
# mod, params, shape_dict, _ = crop_network_from_torch(args.network, 1, 25)
mod, params = get_network_from_relay(args.network, 1)
# printe(repr(mod["main"]))
# build_network_tensorrt(mod, params)
# lib = build_network(mod["main"], params, CustomFusionPass.TWO_LEVEL_OPT, args.network, args.hw)
lib = build_network(mod["main"], params, CustomFusionPass.DP, args.network, args.hw, 1)
# lib = build_network(mod["main"], params, CustomFusionPass.USER_DEFINED_FUSION, args.network)
print(f"We successfully built the {args.network} on {args.hw}")
# Verify if the network output is same after our optimization
# verify_network_output(mod["main"], params, 'cuda', shape_dict)
# Verify if the network can be measured
# For Conv2d and conv2d+relu
# inference_time = measure_network(lib, "cuda", {"data": [1, 3, 224, 224]})
# For (conv2d+relu)x2
# inference_time = measure_network(lib, "cuda", {"data": [1, 64, 56, 56]})
# For networks from torch
# inference_time = measure_network(lib, "cuda", WORKLOADS_DIC[args.network])
# print(f"Inference time: {inference_time}")
|
# coding: utf-8
"""
Phaxio API
API Definition for Phaxio
OpenAPI spec version: 2.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class PhaxCode(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, success=None, message=None, data=None):
"""
PhaxCode - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition.
"""
self.swagger_types = {
'success': 'bool',
'message': 'str',
'data': 'PhaxCodeData'
}
self.attribute_map = {
'success': 'success',
'message': 'message',
'data': 'data'
}
self._success = success
self._message = message
self._data = data
@property
def success(self):
"""
Gets the success of this PhaxCode.
:return: The success of this PhaxCode.
:rtype: bool
"""
return self._success
@success.setter
def success(self, success):
"""
Sets the success of this PhaxCode.
:param success: The success of this PhaxCode.
:type: bool
"""
self._success = success
@property
def message(self):
"""
Gets the message of this PhaxCode.
:return: The message of this PhaxCode.
:rtype: str
"""
return self._message
@message.setter
def message(self, message):
"""
Sets the message of this PhaxCode.
:param message: The message of this PhaxCode.
:type: str
"""
self._message = message
@property
def data(self):
"""
Gets the data of this PhaxCode.
:return: The data of this PhaxCode.
:rtype: PhaxCodeData
"""
return self._data
@data.setter
def data(self, data):
"""
Sets the data of this PhaxCode.
:param data: The data of this PhaxCode.
:type: PhaxCodeData
"""
self._data = data
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
|
const expect = chai.expect;
import Vue from "vue";
import Row from "../src/grid/row.vue";
import Col from "../src/grid/col.vue";
Vue.config.devtools = false;
Vue.config.productionTip = false;
const Constructor1 = Vue.extend(Row);
const Constructor2 = Vue.extend(Col);
const init = (props, Constructor, fix) => {
const div = document.createElement("div");
document.body.appendChild(div);
const vm = new Constructor({propsData: props});
if (fix) {
const col1 = new Constructor2().$mount();
const col2 = new Constructor2().$mount();
vm.$children = [col1, col2];
}
vm.$mount(div);
vm.getEl = key => vm.$el.querySelector(key);
vm.getAllEl = key => vm.$el.querySelectorAll(key);
vm.over = () => {
vm.$el.remove();
vm.$destroy();
div.remove();
};
return vm;
};
describe(
"Row", () => {
it("存在!", function () {
expect(Row).to.exist;
});
it("gutter属性,可以设置自身的margin值。并且可以把值传递给子组件的gutter属性",
function (done) {
Vue.component("y-row", Row);
Vue.component("y-col", Col);
const html = `
<y-row gutter="20">
<y-col span="6" class="g">
<div></div>
</y-col>
<y-col span="6" class="g">
<div></div>
</y-col>
<y-col span="6" class="g">
<div></div>
</y-col>
<y-col span="6" class="g">
<div></div>
</y-col>
</y-row>
`;
const div = document.createElement("div");
div.innerHTML = html;
document.body.appendChild(div);
const vm = new Vue(
{
el: div
}
);
setTimeout(
() => {
// console.log(vm.$el);
const col = vm.$el.querySelector(".yv-col");
expect(getComputedStyle(col).paddingLeft).to.eq("10px");
expect(getComputedStyle(col).paddingRight).to.eq("10px");
const row = vm.$el.querySelector(".yv-row");
expect(getComputedStyle(row).marginLeft).to.eq("-10px");
expect(getComputedStyle(row).marginRight).to.eq("-10px");
done();
}, 1000
);
// const row = init(
// {gutter: 20}, Constructor1, true
// );
// const dom = row.$el;
// const children = row.$children;
// children.map(
// child => {
// // console.log(child.gutter);
// expect(child.gutter).to.eq(20);
// const col = child.$el;
// console.log(col.classList, getComputedStyle(col).paddingLeft);
// expect(getComputedStyle(col).paddingLeft).to.eq("10px");
// expect(getComputedStyle(col).paddingRight).to.eq("10px");
// }
// );
// const {marginLeft, marginRight} = getComputedStyle(dom);
// expect(marginLeft).to.eq("-10px");
// expect(marginRight).to.eq("-10px");
//
// row.over();
}
);
it("可以设置flex的justify-content属性值为left,right,center!", function () {
const obj = {
row0: "", row1: "", row2: ""
};
["left", "right", "center"].map(
(val, ind) => {
obj["row" + ind] = init(
{justify: val}, Constructor1
);
}
);
["flex-start", "flex-end", "center"].map(
(val, ind) => {
const vm = obj["row" + ind];
const div = vm.$el;
// console.log(div,div.getAttribute('justify-content'));
expect(getComputedStyle(div).justifyContent).to.eq(val);
vm.over();
}
);
});
it("可以设置flex的align-items属性值为up,down,center!", function () {
const obj = {
row0: "", row1: "", row2: ""
};
["up", "down", "center"].map(
(val, ind) => {
obj["row" + ind] = init(
{align: val}, Constructor1
);
}
);
["flex-start", "flex-end", "center"].map(
(val, ind) => {
const vm = obj["row" + ind];
const div = vm.$el;
// console.log(div,div.getAttribute('justify-content'));
expect(getComputedStyle(div).alignItems).to.eq(val);
vm.over();
}
);
});
}
);
describe(
"Col", () => {
it("存在!", function () {
expect(Col).to.exist;
});
it("设置span,可以设置width!", function () {
const vm = init(
{span: 10}, Constructor2
);
const div = vm.$el;
expect(div.classList.contains("col-10")).to.eq(true);
});
it("设置interval,可以设置margin-left!", function () {
const vm = init(
{interval: 10}, Constructor2
);
const div = vm.$el;
expect(div.classList.contains("interval-10")).to.eq(true);
});
it("设置gutter,可以设置padding!", function (done) {
const vm = init(
{}, Constructor2
);
// console.log(vm.gutter);
const div = vm.$el;
vm.gutter = 20;
// console.log(vm.gutter);
//这里是异步的错误!!
Vue.nextTick(
() => {
expect(getComputedStyle(div).paddingLeft).to.eq("10px");
expect(getComputedStyle(div).paddingRight).to.eq("10px");
vm.over();
done();
}
);
});
// it("可以自定义媒体查询,做到完全形式的响应式!", function (done) {
// const medias2 = [
// {
// condition: "(max-width:576px)",
// span: 12,
// },
// {
// condition: "(min-width:576px) and (max-width:768px)",
// span: 12,
// interval: 4
// },
// {
// condition: "(min-width:768px) and (max-width:992px)",
// span: 10,
// interval: 8
// },
// {
// condition: "(min-width:992px) and (max-width:1200px)",
// span: 8,
// interval: 12
// },
// {
// condition: "(min-width:1200px)",
// span: 8,
// interval: 12
// }
// ];
// const vm = init(
// {medias: medias2}, Constructor2
// );
//
//
// const evt = new Event("resize");
// [
// 150,
// 200, 300, 400, 500,
// 600, 700,
// 800, 900,
// 1000, 1100, 1200,
// 1300, 1400
// ].map(
// (val, index) => {
// let leval;
// if (val > 1200) {
// leval = 5;
// } else if (val > 992) {
// leval = 4;
// } else if (val > 768) {
// leval = 3;
// } else if (val > 576) {
// leval = 2;
// } else {
// leval = 1;
// }
// setTimeout(
// () => {
// window.innerWidth = val;
// window.outerWidth = val + 2;
// window.dispatchEvent(evt);
// window.innerWidth = val;
// window.outerWidth = val + 2;
// setTimeout(
// () => {
//
// const {span, interval} = medias2[leval-1];
// // console.log(vm.$el.classList,12121,span,interval);
//
// expect(
// vm.$el.classList.contains(
// `media-${leval }-col-${span}`
// )
// ).to.eq(true);
// interval && expect(
// vm.$el.classList.contains(
// `media-${leval }-interval-${interval}`
// )
// ).to.eq(true);
// vm.over();
// done();
// }, 1000
// );
// }, (index +0.5)* 1000
// );
// }
// );
//
//
// });
}
);
|
/*
* /MathJax/jax/output/PlainSource/jax.js
*
* Copyright (c) 2009-2018 The MathJax Consortium
*
* 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.
*/
(function(a,b,f,c){var e,g,d;c.Augment({settings:b.config.menuSettings,Config:function(){if(!this.require){this.require=[]}this.SUPER(arguments).Config.call(this);this.require.push(MathJax.OutputJax.extensionDir+"/MathEvents.js")},Startup:function(){e=MathJax.Extension.MathEvents.Event;g=MathJax.Extension.MathEvents.Touch;d=MathJax.Extension.MathEvents.Hover;this.ContextMenu=e.ContextMenu;this.Mousedown=e.AltContextMenu;this.Mouseover=d.Mouseover;this.Mouseout=d.Mouseout;this.Mousemove=d.Mousemove;return a.Styles(this.config.styles)},preTranslate:function(k){var o=k.jax[this.id],p,l=o.length,q,n,r,j,h;for(p=0;p<l;p++){q=o[p];if(!q.parentNode){continue}n=q.previousSibling;if(n&&String(n.className).match(/^MathJax(_PlainSource)?(_Display)?( MathJax_Process(ing|ed))?$/)){n.parentNode.removeChild(n)}h=q.MathJax.elementJax;if(!h){continue}h.PlainSource={display:(h.root.Get("display")==="block")};r=j=f.Element("span",{className:"MathJax_PlainSource",id:h.inputID+"-Frame",isMathJax:true,jaxID:this.id,oncontextmenu:e.Menu,onmousedown:e.Mousedown,onmouseover:e.Mouseover,onmouseout:e.Mouseout,onmousemove:e.Mousemove,onclick:e.Click,ondblclick:e.DblClick,onkeydown:e.Keydown,tabIndex:b.getTabOrder(h)},[["span"]]);if(b.Browser.noContextMenu){r.ontouchstart=g.start;r.ontouchend=g.end}if(h.PlainSource.display){j=f.Element("div",{className:"MathJax_PlainSource_Display"});j.appendChild(r)}q.parentNode.insertBefore(j,q)}},Translate:function(j,n){if(!j.parentNode){return}var i=j.MathJax.elementJax,l=i.root,k=document.getElementById(i.inputID+"-Frame");this.initPlainSource(l,k);var m=i.originalText;if(i.inputJax==="MathML"){if((i.root.data[0].data.length>0)&&(i.root.data[0].data[0].type==="semantics")){var o=i.root.data[0].data[0].data;for(var h=0;h<o.length;h++){if(o[h].attr.encoding==="application/x-tex"){m=i.root.data[0].data[0].data[h].data[0].data[0];break}if(o[h].attr.encoding==="text/x-asciimath"){m=i.root.data[0].data[0].data[h].data[0].data[0]}}}}i.PlainSource.source=m;f.addText(k.firstChild,m)},postTranslate:function(h){},getJaxFromMath:function(h){if(h.parentNode.className.match(/MathJax_PlainSource_Display/)){h=h.parentNode}do{h=h.nextSibling}while(h&&h.nodeName.toLowerCase()!=="script");return b.getJaxFor(h)},Zoom:function(i,q,p,h,n){var k=Math.round(q.parentNode.offsetWidth/2);q.style.whiteSpace="pre";f.addText(q,i.PlainSource.source);var l=p.offsetWidth,r=p.offsetHeight,o=q.offsetWidth,m=q.offsetHeight;var j=-Math.round((m+r)/2)-(i.PlainSource.display?0:k);return{mW:l,mH:r,zW:o,zH:m,Y:j}},initPlainSource:function(i,h){},Remove:function(h){var i=document.getElementById(h.inputID+"-Frame");if(i){if(h.PlainSource.display){i=i.parentNode}i.parentNode.removeChild(i)}delete h.PlainSource}});MathJax.Hub.Register.StartupHook("mml Jax Ready",function(){MathJax.Hub.Register.StartupHook("onLoad",function(){setTimeout(MathJax.Callback(["loadComplete",c,"jax.js"]),0)})});MathJax.Hub.Register.StartupHook("End Cookie",function(){if(b.config.menuSettings.zoom!=="None"){a.Require("[MathJax]/extensions/MathZoom.js")}})})(MathJax.Ajax,MathJax.Hub,MathJax.HTML,MathJax.OutputJax.PlainSource);
|
import cProfile
#------------------------------------------------------------------------------
# Debug
#------------------------------------------------------------------------------
#
# This file contains random snippets of code that I frequently use while
# developing and debugging parts of lighthouse. I don't expect any of this
# code to be active or in use for major releases.
#
#------------------------------------------------------------------------------
# Call Profiling
#------------------------------------------------------------------------------
pr = cProfile.Profile()
def profile(func):
"""
A simple function profiling decorator.
"""
def wrap(*args, **kwargs):
global pr
pr.enable()
result = func(*args, **kwargs)
pr.disable()
pr.print_stats(sort="tottime")
return result
return wrap
#------------------------------------------------------------------------------
# Function Line Profiling
#------------------------------------------------------------------------------
# from: https://gist.github.com/sibelius/3920b3eb5adab482b105
try:
from line_profiler import LineProfiler
def line_profile(func):
def profiled_func(*args, **kwargs):
try:
profiler = LineProfiler()
profiler.add_function(func)
profiler.enable_by_count()
return func(*args, **kwargs)
finally:
profiler.print_stats()
return profiled_func
except ImportError:
def line_profile(func):
def nothing(*args, **kwargs):
return func(*args, **kwargs)
return nothing
#------------------------------------------------------------------------------
# Module Line Profiling
#------------------------------------------------------------------------------
if False:
from line_profiler import LineProfiler
lpr = LineProfiler()
# change this to the target file / module to profile
import lighthouse.metadata as metadata
lpr.add_module(metadata)
# put this code somewhere to dump results:
#global lpr
#lpr.enable_by_count()
#lpr.disable_by_count()
#lpr.print_stats(stripzeros=True)
|
/*
* Copyright IBM Corp. 2004, 2010
* Interface implementation for communication with the z/VM control program
*
* Author(s): Christian Borntraeger <borntraeger@de.ibm.com>
*
* z/VMs CP offers the possibility to issue commands via the diagnose code 8
* this driver implements a character device that issues these commands and
* returns the answer of CP.
*
* The idea of this driver is based on cpint from Neale Ferguson and #CP in CMS
*/
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/compat.h>
#include <linux/kernel.h>
#include <linux/miscdevice.h>
#include <linux/slab.h>
#include <linux/export.h>
#include <asm/compat.h>
#include <asm/cpcmd.h>
#include <asm/debug.h>
#include <linux/uaccess.h>
#include "vmcp.h"
static debug_info_t *vmcp_debug;
static int vmcp_open(struct inode *inode, struct file *file)
{
struct vmcp_session *session;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
session = kmalloc(sizeof(*session), GFP_KERNEL);
if (!session)
return -ENOMEM;
session->bufsize = PAGE_SIZE;
session->response = NULL;
session->resp_size = 0;
mutex_init(&session->mutex);
file->private_data = session;
return nonseekable_open(inode, file);
}
static int vmcp_release(struct inode *inode, struct file *file)
{
struct vmcp_session *session;
session = file->private_data;
file->private_data = NULL;
free_pages((unsigned long)session->response, get_order(session->bufsize));
kfree(session);
return 0;
}
static ssize_t
vmcp_read(struct file *file, char __user *buff, size_t count, loff_t *ppos)
{
ssize_t ret;
size_t size;
struct vmcp_session *session;
session = file->private_data;
if (mutex_lock_interruptible(&session->mutex))
return -ERESTARTSYS;
if (!session->response) {
mutex_unlock(&session->mutex);
return 0;
}
size = min_t(size_t, session->resp_size, session->bufsize);
ret = simple_read_from_buffer(buff, count, ppos,
session->response, size);
mutex_unlock(&session->mutex);
return ret;
}
static ssize_t
vmcp_write(struct file *file, const char __user *buff, size_t count,
loff_t *ppos)
{
char *cmd;
struct vmcp_session *session;
if (count > 240)
return -EINVAL;
cmd = memdup_user_nul(buff, count);
if (IS_ERR(cmd))
return PTR_ERR(cmd);
session = file->private_data;
if (mutex_lock_interruptible(&session->mutex)) {
kfree(cmd);
return -ERESTARTSYS;
}
if (!session->response)
session->response = (char *)__get_free_pages(GFP_KERNEL
| __GFP_REPEAT | GFP_DMA,
get_order(session->bufsize));
if (!session->response) {
mutex_unlock(&session->mutex);
kfree(cmd);
return -ENOMEM;
}
debug_text_event(vmcp_debug, 1, cmd);
session->resp_size = cpcmd(cmd, session->response, session->bufsize,
&session->resp_code);
mutex_unlock(&session->mutex);
kfree(cmd);
*ppos = 0; /* reset the file pointer after a command */
return count;
}
/*
* These ioctls are available, as the semantics of the diagnose 8 call
* does not fit very well into a Linux call. Diagnose X'08' is described in
* CP Programming Services SC24-6084-00
*
* VMCP_GETCODE: gives the CP return code back to user space
* VMCP_SETBUF: sets the response buffer for the next write call. diagnose 8
* expects adjacent pages in real storage and to make matters worse, we
* dont know the size of the response. Therefore we default to PAGESIZE and
* let userspace to change the response size, if userspace expects a bigger
* response
*/
static long vmcp_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
struct vmcp_session *session;
int __user *argp;
int temp;
session = file->private_data;
if (is_compat_task())
argp = compat_ptr(arg);
else
argp = (int __user *)arg;
if (mutex_lock_interruptible(&session->mutex))
return -ERESTARTSYS;
switch (cmd) {
case VMCP_GETCODE:
temp = session->resp_code;
mutex_unlock(&session->mutex);
return put_user(temp, argp);
case VMCP_SETBUF:
free_pages((unsigned long)session->response,
get_order(session->bufsize));
session->response=NULL;
temp = get_user(session->bufsize, argp);
if (get_order(session->bufsize) > 8) {
session->bufsize = PAGE_SIZE;
temp = -EINVAL;
}
mutex_unlock(&session->mutex);
return temp;
case VMCP_GETSIZE:
temp = session->resp_size;
mutex_unlock(&session->mutex);
return put_user(temp, argp);
default:
mutex_unlock(&session->mutex);
return -ENOIOCTLCMD;
}
}
static const struct file_operations vmcp_fops = {
.owner = THIS_MODULE,
.open = vmcp_open,
.release = vmcp_release,
.read = vmcp_read,
.write = vmcp_write,
.unlocked_ioctl = vmcp_ioctl,
.compat_ioctl = vmcp_ioctl,
.llseek = no_llseek,
};
static struct miscdevice vmcp_dev = {
.name = "vmcp",
.minor = MISC_DYNAMIC_MINOR,
.fops = &vmcp_fops,
};
static int __init vmcp_init(void)
{
int ret;
if (!MACHINE_IS_VM)
return 0;
vmcp_debug = debug_register("vmcp", 1, 1, 240);
if (!vmcp_debug)
return -ENOMEM;
ret = debug_register_view(vmcp_debug, &debug_hex_ascii_view);
if (ret) {
debug_unregister(vmcp_debug);
return ret;
}
ret = misc_register(&vmcp_dev);
if (ret)
debug_unregister(vmcp_debug);
return ret;
}
device_initcall(vmcp_init);
|
# coding: utf-8
#
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
# except in compliance with the License. A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for
# the specific language governing permissions and limitations under the License.
#
import pprint
import re # noqa: F401
import six
import typing
from enum import Enum
if typing.TYPE_CHECKING:
from typing import Dict, List, Optional
from datetime import datetime
class Coordinate(object):
"""
An object containing the location information of the device.
:param latitude_in_degrees: A double representing the latitude in degrees of the device.
:type latitude_in_degrees: (optional) float
:param longitude_in_degrees: A double representing the longitude in degrees of the device.
:type longitude_in_degrees: (optional) float
:param accuracy_in_meters: A double representing the accuracy of geolocation data in meters.
:type accuracy_in_meters: (optional) float
"""
deserialized_types = {
'latitude_in_degrees': 'float',
'longitude_in_degrees': 'float',
'accuracy_in_meters': 'float'
} # type: Dict
attribute_map = {
'latitude_in_degrees': 'latitudeInDegrees',
'longitude_in_degrees': 'longitudeInDegrees',
'accuracy_in_meters': 'accuracyInMeters'
} # type: Dict
def __init__(self, latitude_in_degrees=None, longitude_in_degrees=None, accuracy_in_meters=None):
# type: (Optional[float], Optional[float], Optional[float]) -> None
"""An object containing the location information of the device.
:param latitude_in_degrees: A double representing the latitude in degrees of the device.
:type latitude_in_degrees: (optional) float
:param longitude_in_degrees: A double representing the longitude in degrees of the device.
:type longitude_in_degrees: (optional) float
:param accuracy_in_meters: A double representing the accuracy of geolocation data in meters.
:type accuracy_in_meters: (optional) float
"""
self.__discriminator_value = None # type: str
self.latitude_in_degrees = latitude_in_degrees
self.longitude_in_degrees = longitude_in_degrees
self.accuracy_in_meters = accuracy_in_meters
def to_dict(self):
# type: () -> Dict[str, object]
"""Returns the model properties as a dict"""
result = {} # type: Dict
for attr, _ in six.iteritems(self.deserialized_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else
x.value if isinstance(x, Enum) else x,
value
))
elif isinstance(value, Enum):
result[attr] = value.value
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else
(item[0], item[1].value)
if isinstance(item[1], Enum) else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
# type: () -> str
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
# type: () -> str
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
# type: (object) -> bool
"""Returns true if both objects are equal"""
if not isinstance(other, Coordinate):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
# type: (object) -> bool
"""Returns true if both objects are not equal"""
return not self == other
|
#!/usr/bin/python2.4
#
# Copyright 2010 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Base class for all request handlers.
Provides functionality useful to all request handlers, including extraction and
validation of request parameters.
"""
import os
import urllib2
# pylint: disable-msg=C6204
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
class Error(urllib2.HTTPError):
"""Base class for all exceptions defined in this module."""
pass
class MissingRequiredParameterError(Error):
"""Raised when the request is missing a required parameter."""
def __init__(self, parameter_name):
msg = 'Request missing required parameter: %s' % parameter_name
Error.__init__(self, code=400, msg=msg, url='', hdrs='', fp=None)
class InvalidIntValueError(Error):
"""Raised when a request parameter is expected to be an int, but it isn't."""
def __init__(self, parameter_name, parameter_value):
msg = ('The specified value for parameter "%s" is not '
'a valid int: %s' % (parameter_name, parameter_value))
Error.__init__(self, code=400, msg=msg, url='', hdrs='', fp=None)
class InvalidParameterValueError(Error):
"""Raised when a request parameter has an invalid value."""
def __init__(self, parameter_name, parameter_value):
msg = ('The specified value for parameter "%s" is not '
'valid: %s' % (parameter_name, parameter_value))
Error.__init__(self, code=400, msg=msg, url='', hdrs='', fp=None)
class BaseHandler(webapp.RequestHandler):
"""Base class for the application handlers.
Defines common functionality used by various handlers. As a rule of thumb,
most code that extracts and validates parameters from the request belongs to
this class.
If any of the validations fails, one of the exceptions defined in this module
is raised; all of which inherits from the Error class, also defined in this
module.
The most basic type of retrieval is to retrieve an optional str
argument from the request. This is accomplished by calling
GetOptionalParameter, for example:
value = self.GetOptionalParameter('optional_param_name')
value = self.GetOptionalParameter('optional_param_name', 'default_value')
If the parameter is required by the request handler, this can be enforced
by calling GetRequiredParameter, for example
value = self.GetRequiredParameter('required_param_name')
In addition to enforcing whether a parameter is required or not, there are
variations to enforce the parameter value is of a specific type. Some of
the methods we have implemented at the moment retrieve an optional int
and a required URL, for example:
# Note that 10 is just an optional default value.
value = self.GetOptionalIntParameter('int_parameter_name', 10)
"""
def GetRequiredParameter(self, parameter_name):
"""Retrieves the value of a required request parameter.
Args:
parameter_name: Name of the parameter to get from the request.
Returns:
The value of the specified parameter as a str.
Raises:
MissingRequiredParameterError: The specified parameter was not found in
the request.
"""
str_value = self.GetOptionalParameter(parameter_name)
if not str_value:
raise MissingRequiredParameterError(parameter_name)
return str_value
def GetOptionalParameter(self, parameter_name, default_value=None):
"""Retrieves the value of an optional request parameter.
Args:
parameter_name: Name of the parameter to get from the request.
default_value: Value to return if the parameter is not found.
Returns:
The value of the specified parameter as a str, or default_value
if the parameter was not present in the request.
"""
return self.request.get(parameter_name, default_value)
def GetOptionalIntParameter(self, parameter_name, default_value):
"""Retrieves the value of an optional request parameter.
Args:
parameter_name: Name of the parameter to get from the request.
default_value: Value to return if the parameter is not found.
Returns:
An int object with the value of the specified parameter as a str.
Raises:
InvalidIntValueError: The value of the specified parameter is
not a valid integer number.
"""
str_value = self.GetOptionalParameter(parameter_name)
# If the following line raises a ValueError, the calling code
# has a bug where they passed an invalid default_value. We let
# that exception propagate, causing a 500 response to client and
# sufficient error logging.
if not str_value:
return int(default_value)
try:
return int(str_value)
except ValueError:
raise InvalidIntValueError(parameter_name, str_value)
def RenderTemplate(self, name, template_args):
"""Renders the specified django template.
Assumes the hander and templates are on different folders:
- root
- handlers
- templates
Args:
name: Str name of the file template.
template_args: Dict argument passed to the template.
"""
path = os.path.join(os.path.dirname(__file__), '..', 'templates', name)
self.response.out.write(template.render(path, template_args))
# Register filter
template.register_template_library(
'filters.filters')
|
from .syncer import JsonSyncer
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
|
from rest_framework.serializers import ModelSerializer
from .models import Task
from mmetrograd.users.models import User
class TaskListSerializer(ModelSerializer):
class Meta:
model = Task
fields = "__all__"
# fields = [
# "inn",
# "id",
# ]
class TaskDetailSerializer(ModelSerializer):
class Meta:
model = Task
fields = "__all__"
class TenantListTaskSerializer(ModelSerializer):
tasks = TaskListSerializer(many=True, read_only=True)
class Meta:
model = User
fields = "__all__"
# exclude = ["tenant"]
class TenantDetailTaskSerializer(ModelSerializer):
tasks = TaskDetailSerializer(many=True, read_only=True)
class Meta:
model = User
fields = "__all__"
# exclude = ["tenant"]
|
webpackJsonp([2],{1370:function(e,t,a){"use strict";t.a={data:function(){return{plugins:[{name:"vuetify-loader",href:"https://www.npmjs.com/package/vuetify-loader"},{name:"babel-plugin-transform-imports",href:"https://www.npmjs.com/package/babel-plugin-transform-imports"}]}}}},1371:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement,a=e._self._c||t;return a("doc-view",{attrs:{id:"a-la-carte-view"}},[a("v-layout",{attrs:{row:"row",wrap:"wrap"}},[a("v-flex",{attrs:{xs12:"xs12",sm8:"sm8",xl12:"xl12"}},[a("section-def",[a("dt",{attrs:{slot:"title"},slot:"title"},[e._v("Single component importing")]),a("dd",{attrs:{slot:"desc"},slot:"desc"},[e._v("Being a component framework, Vuetify will always grow horizontally. Depending on your project requirements, "),a("strong",[e._v("package size")]),e._v(" may be heavily scrutinized and important for your particular use-case. Vuetify allows you to easily import only what you need, drastically lowering its footprint.")])])],1),a("ad")],1),a("v-alert",{staticClass:"mb-4",attrs:{value:"value",color:"warning",icon:"priority_high"}},[e._v("The implementation details for this feature will very likely change drastically in future versions. The "),a("strong",[e._v("a-la-carte")]),e._v(" feature should be considered to be in "),a("strong",[e._v("beta")])]),a("v-alert",{staticClass:"mb-4",attrs:{value:"value",color:"info",icon:"info"}},[e._v("For a pre-built project demonstrating single component imports, install the "),a("strong",[e._v("a-la-carte")]),e._v(" template from the cli, using the command "),a("code",[e._v("vue init vuetifyjs/a-la-carte")]),e._v(". Some of our other templates also include options for enabling a-la-carte components.")]),a("section",[a("section-header",[e._v("Importing components")]),a("section-text"),a("section-text",[e._v("The "),a("code",[e._v("transform-imports")]),e._v(" package is not necessary to use a-la-carte components, but simplifies the process of importing them, and is therefore highly recommended.")]),a("markup",{attrs:{lang:"bash"}},[e._v("npm install --save-dev babel-plugin-transform-imports\n# or\nyarn add --dev babel-plugin-transform-imports")]),a("section-text",[e._v("When using the "),a("code",[e._v("transform-imports")]),e._v(" package, you will need to add the following to the plugins section of your "),a("kbd",[e._v(".babelrc")]),e._v(" file.")]),a("markup",{attrs:{lang:"js"}},[e._v('["transform-imports", {\n "vuetify": {\n "transform": "vuetify/es5/components/${member}",\n "preventFullImport": true\n }\n}]')]),a("section-text",[e._v("To import and use components, use the following code in your entry point.")]),a("markup",{attrs:{lang:"js"}},[e._v("import {\n Vuetify,\n VApp,\n VNavigationDrawer,\n VFooter,\n VList,\n VBtn\n} from 'vuetify'\n\nVue.use(Vuetify, {\n components: {\n VApp,\n VNavigationDrawer,\n VFooter,\n VList,\n VBtn\n }\n})")]),a("v-alert",{staticClass:"mb-4",attrs:{value:"value",color:"info",icon:"info"}},[e._v("The options object that you pass as the second argument to "),a("code",[e._v("Vue.use")]),e._v(" can also include both a "),a("strong",[e._v("directives")]),e._v(" and a "),a("strong",[e._v("transitions")]),e._v(" property.")]),a("section-text",[e._v("If you are not using the "),a("code",[e._v("transform-imports")]),e._v(" package, you will need to import each component like this")]),a("markup",{attrs:{lang:"js"}},[e._v("import Vuetify from 'vuetify/es5/components/Vuetify'\nimport VApp from 'vuetify/es5/components/VApp'\nimport VNavigationDrawer from 'vuetify/es5/components/VNavigationDrawer'\n// etc")]),a("v-alert",{staticClass:"mb-4",attrs:{value:"value",color:"error",icon:"warning"}},[e._v("Be aware that both the "),a("code",[e._v("Vuetify")]),e._v(" and "),a("code",[e._v("VApp")]),e._v(" components are required to use Vuetify.")])],1),a("section",[a("section-header",[e._v("Required styles")]),a("section-text",[e._v("In order to obtain all the required styles, we need to import them in "),a("strong",[e._v("stylus")]),e._v(". In order for webpack to handle this, you will need to install "),a("code",[e._v("stylus")]),e._v(" and the "),a("code",[e._v("stylus-loader")]),e._v(" from npm.")]),a("markup",{attrs:{lang:"bash"}},[e._v("npm install --save-dev stylus stylus-loader\n# or\nyarn add --dev stylus stylus-loader")]),a("v-alert",{staticClass:"mb-4",attrs:{value:"value",color:"info",icon:"info"}},[e._v("For a more detailed explanation on how to setup your application to handle stylus, please navigate to the "),a("router-link",{staticClass:"white--text",attrs:{to:"/style/theme"}},[e._v("theme page")]),e._v(".")],1),a("section-text",[e._v("Now you will need to require the stylus from the entry point of your application. This is the same place where you're importing Vue and Vuetify (usually "),a("kbd",[e._v("main.js")]),e._v(" or "),a("kbd",[e._v("app.js")]),e._v("):")]),a("markup",{attrs:{lang:"js"}},[e._v("require('vuetify/src/stylus/app.styl')")])],1),a("section",[a("section-header",[e._v("Theming")]),a("section-text",[e._v("Using custom themes with a-la-carte components is done exactly the same way as described on the "),a("router-link",{attrs:{to:"/style/theme"}},[e._v("theme page")]),e._v(".")],1)],1)],1)},s=[],i={render:o,staticRenderFns:s};t.a=i},1372:function(e,t,a){var o=a(1373);"string"==typeof o&&(o=[[e.i,o,""]]),o.locals&&(e.exports=o.locals);a(198)("3931f224",o,!0)},1373:function(e,t,a){t=e.exports=a(197)(void 0),t.push([e.i,"#alert-view .alert{margin:1rem 0}",""])},1374:function(e,t,a){"use strict";t.a={name:"alerts-view",data:function(){return{doc:{component:"VAlert",edit:"AlertsView",title:"Alert",desc:"The <code>v-alert</code> component is used to convey information to the user. Designed to stand out, the alerts come in four contextual styles, success, info, warning, and error.",examples:[{header:"Contextual",file:"alerts/contextual",desc:"The <code>v-alert</code> component comes in 4 variations, <strong>success</strong>, <strong>info</strong>, <strong>warning</strong> and <strong>error</strong>. These have default icons assigned which can be changed and represent different actions."},{header:"Closable",file:"alerts/closable",desc:"Using <code>v-model</code> you can control the state of the Alert. If you don't want to assign a v-model and just display the alert, you can simply assign the prop <code>value</code>."},{header:"Custom Icon / No Icon",file:"alerts/icon",desc:"You can easily assign a custom icon or remove it all together."},{header:"Display transition",file:"alerts/transition",desc:"You can apply a custom transition to the show/hide of the alert."},{header:"Outline",file:"alerts/outline",desc:"Outline alerts inherit their borders from the current color applied."}],props:{"v-alert":{shared:["colorable","transitionable"],model:{type:["Boolean"],default:"False"},params:[["dismissible","Boolean","False","Specifies that the Alert can be closed"],["icon","String","-","Designates a specific icon"],["outline","Boolean","False","Alert will have an outline"],["type","String","null","Specify a <strong>success</strong>, <strong>info</strong>, <strong>warning</strong> or <strong>error</strong> alert. Uses the contextual color and a pre-defined icon."]]}},slots:{"v-alert":{shared:["default"]}}}}}}},1375:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement;return(e._self._c||t)("component-view",{attrs:{doc:e.doc}})},s=[],i={render:o,staticRenderFns:s};t.a=i},1376:function(e,t,a){"use strict";t.a={name:"alignment-view"}},1377:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement,a=e._self._c||t;return a("div",{staticClass:"view",attrs:{id:"spacing-view"}},[a("v-layout",{attrs:{row:"row",wrap:"wrap"}},[a("v-flex",{attrs:{xs12:"xs12",sm8:"sm8",xl12:"xl12"}},[a("section-def",[a("dt",{attrs:{slot:"title"},slot:"title"},[e._v("Alignment")]),a("dd",{attrs:{slot:"desc"},slot:"desc"},[e._v("Layouts can change when screen resolutions change. The alignment classes help you position your text based on viewport size.")])])],1),a("ad")],1),a("grid"),a("section",[a("component-example",{attrs:{header:"Examples",file:"alignment/text"}},[a("v-card",[a("v-card-text",[a("p",{staticClass:"text-lg-right"},[e._v("Right align on large viewport sizes")]),a("p",{staticClass:"text-md-center"},[e._v("Center align on medium viewport sizes")]),a("p",{staticClass:"text-sm-left"},[e._v("Left align on small viewport sizes")]),a("p",{staticClass:"text-xs-center"},[e._v("Center align on all viewport sizes")]),a("p",{staticClass:"text-xl-right"},[e._v("Right align on extra large viewport sizes")])])],1)],1),a("markup",{attrs:{lang:"html"}},[e._v('<p class="text-xs-left">...</p>\n<p class="text-xs-center">...</p>\n<p class="text-xs-right">...</p>\n \n \n<p class="text-xs-left">...</p>\n<p class="text-sm-left">...</p>\n<p class="text-md-left">...</p>\n<p class="text-lg-left">...</p>\n<p class="text-xl-right">...</p>')])],1)],1)},s=[],i={render:o,staticRenderFns:s};t.a=i},1378:function(e,t,a){var o=a(1379);"string"==typeof o&&(o=[[e.i,o,""]]),o.locals&&(e.exports=o.locals);a(198)("628f4d20",o,!0)},1379:function(e,t,a){t=e.exports=a(197)(void 0),t.push([e.i,"#alert-view .alert{margin:1rem 0}",""])},1380:function(e,t,a){"use strict";t.a={name:"alerts-view",data:function(){return{doc:{component:"VAvatar",edit:"AvatarsView",title:"Avatar",desc:"The <code>v-avatar</code> component is used to control the size and border radius of responsive images, typically used to show profile pictures.",examples:[{header:"Standard display",file:"avatars/standard",desc:"The avatar has a dynamic size that can be scaled for any situation. A <strong>tile</strong> variation is available for displaying an avatar without border radius."},{header:"Advanced usage",file:"avatars/advanced",desc:"Combining an avatar with other components allows you to build beautiful user interfaces right out of the box."},{header:"Icon and text",file:"avatars/icon-and-text",desc:"An avatar also accepts the <code>v-icon</code> component or text. Mix and match functionality to create something unique."}],props:{"v-avatar":{params:[["size","String","48px","Controls the height and width of a child <code>img</code> or <code>v-icon</code>"],["tile","Boolean","False","Removes the border radius from the avatar"]]}},slots:{"v-avatar":{shared:["default"]}}}}}}},1381:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement;return(e._self._c||t)("component-view",{attrs:{doc:e.doc}})},s=[],i={render:o,staticRenderFns:s};t.a=i},1382:function(e,t,a){"use strict";t.a={data:function(){return{doc:{title:"Badge component",edit:"BadgesView",component:"badge",desc:"The <code>v-badge</code> component can wrap any type of content to highlight information to a user or to just draw attention to a specific element.",examples:[{header:"Character",file:"badges/character",desc:"Any character can be placed with a badge."},{header:"Icon",file:"badges/icon",desc:"The icon badge type only supports Material Design icons."},{header:"Inline",file:"badges/inline",desc:"Badges can also be placed inline with text."},{header:"Visibility",file:"badges/visibility",desc:"The visibility of badges can be controlled using <code>v-model</code>."}],props:{"v-badge":{model:{type:["Boolean"],default:"False"},params:[["color","String","False","Designate a custom badge color from the MD color spec"],["left","Boolean","False","Position the badge to the left"],["bottom","Boolean","False","Position the badge to the bottom"],["transition","String","fab-transition","Transition used when enabling or disabling the badge"],["overlap","Boolean","False","Remove the added margin and allow badge to overlap designated element"]]}}}}}}},1383:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement;return(e._self._c||t)("component-view",{attrs:{doc:e.doc,id:"badges-view"}})},s=[],i={render:o,staticRenderFns:s};t.a=i},1384:function(e,t,a){var o=a(1385);"string"==typeof o&&(o=[[e.i,o,""]]),o.locals&&(e.exports=o.locals);a(198)("6f09145d",o,!0)},1385:function(e,t,a){t=e.exports=a(197)(void 0),t.push([e.i,"#bottom-navigation-view .bottom-nav{z-index:1}",""])},1386:function(e,t,a){"use strict";t.a={data:function(){return{doc:{title:"Bottom nav",edit:"BottomNavigationView",component:"VBottomNav",desc:"The <code>v-bottom-nav</code> is an alternative to the sidebar. It is primarily used on mobile and comes in two variants, icons and text, and shift.",examples:[{header:"Icons and text",file:"bottom-navigation/icons-and-text",desc:"While the bottom nav is meant to be used with the <code>vue-router</code>, you can also programmatically control the active state of the buttons by using the <code>active.sync</code> prop. You can change a button's value by using its <code>value</code> attribute."},{header:"Color & shift",file:"bottom-navigation/color-and-shift",desc:"When using a colored background, it is recommended to use the <code>light</code> prop. The <code>shift</code> prop will hide the button text until active. Keep in mind, <code>v-btn</code> text is required to be wrapped in a <code><span></code> tag."},{header:"Toggle",file:"bottom-navigation/toggle",desc:"As with other Vuetify components, you can control the display state with <code>v-model</code>."}],props:{"v-bottom-nav":{shared:["colorable"],model:{type:["Boolean"],default:"False"},params:[["absolute","Boolean","False","Change the position from fixed to absolute"],["shift","Boolean","False","Hide text of button when not active"],["active","String, Number","-","The non-reactive version of <code>active.sync</code>. This will not update your bound value when changed internally."],["active.sync","String, Number","-","Holds the value of the currently active button. If the button has no value supplied, its index will be used instead."]]}},slots:{"v-bottom-navigation":{shared:["default"]}}}}}}},1387:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement;return(e._self._c||t)("component-view",{attrs:{doc:e.doc}})},s=[],i={render:o,staticRenderFns:s};t.a=i},1388:function(e,t,a){"use strict";t.a={data:function(){return{doc:{component:"VBottomSheet",edit:"BottomSheetsView",title:"Bottom sheets",desc:"The bottom sheet is a modified <code>v-dialog</code> that slides from the bottom of the screen, similar to a <code>v-bottom-nav</code>. Whereas a bottom navigation component is for buttons and specific application level actions, a bottom sheet can contain anything.",examples:[{header:"Standard display",file:"bottom-sheets/standard",desc:"Here we display an example list of actions that could be present in an application."},{header:"Inset bottom sheets",file:"bottom-sheets/inset",desc:"Bottom sheets can be inset, reducing their maximum width on desktop to 70%. This can be further reduced manually using the <code>width</code> prop. We also showcase dynamic class binding using the Vuetify breakpoint object."}],props:{"v-bottom-sheet":{shared:["dialog"],model:{type:"Boolean",default:"False"},params:[["inset","Boolean","False","Reduces the dialog content maximum width to 70%"]]}},slots:{"v-bottom-sheets":{shared:["default"]}}}}}}},1389:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement;return(e._self._c||t)("component-view",{attrs:{doc:e.doc}})},s=[],i={render:o,staticRenderFns:s};t.a=i},1390:function(e,t,a){"use strict";t.a={data:function(){return{doc:{title:"Breadcrumbs",edit:"BreadcrumbsView",component:"VBreadcrumbs",desc:"\n <p>\n The <code>v-breadcrumbs</code> component is a navigational helper for pages. It can accept a <strong>Material Icons</strong> icon or characters as a divider. An array of objects containing the fields <em>href</em>, <em>text</em> and optional <em>disabled</em> can be passed to the <strong>items</strong> property of the component. Additionally, a regular slot exists for more control of the breadcrumbs, either utilizing <code>v-breadcrumbs-item</code> or other custom markup.\n </p>\n ",examples:[{header:"Text dividers",file:"breadcrumbs/text-dividers",desc:"By default, breadcrumbs use a text divider. This can be any string."},{header:"Icon dividers",file:"breadcrumbs/icon-dividers",desc:"For the icon variant, breadcrumbs can use any icon in Material Design Icons."}],props:{"v-breadcrumbs":{params:[["divider","String","/","Specifies the dividing character"],["large","Boolean","False","Increases the breadcrumb text size"],["justify-center","Boolean","False","Center the breadcrumbs"],["justify-end","Boolean","False","Right align the breadcrumbs"]]},"v-breadcrumbs-item":{shared:["router"],params:[]}},slots:{"v-breadcrumbs":{shared:["default"]},"v-breadcrumbs-item":{shared:["default"]}}}}}}},1391:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement;return(e._self._c||t)("component-view",{attrs:{doc:e.doc}})},s=[],i={render:o,staticRenderFns:s};t.a=i},1392:function(e,t,a){"use strict";t.a={name:"buttons-view",data:function(){return{doc:{component:"VBtn",edit:"ButtonsView",title:"Button",desc:"\n <p>\n The <code>v-btn</code> component replaces the standard html button with a material design theme and a multitude of options. Any color helper class can be used to alter the background or text color.\n </p>\n ",examples:[{header:"Flat",file:"buttons/flat",desc:""},{header:"Raised",file:"buttons/raised",desc:""},{header:"Button Dropdown Variants",file:"buttons/dropdown",desc:"Button dropdowns are regular selects with additional styling."},{header:"Button Toggle",file:"buttons/toggle",desc:"Toggle buttons are essentially styled radio or checkboxes, depending on the properties selected. This component is compatible with the <code>v-toolbar</code> component."},{header:"Icon",file:"buttons/icon",desc:"Icons can be used for the primary content of a button."},{header:"Floating",file:"buttons/floating",desc:"Floating buttons are round and usually contain an icon."},{header:"Loaders",file:"buttons/loaders",desc:"Using the loading prop, you can notify a user that there is processing taking place. The default behavior is to use a <code>v-progress-circular</code> component but this can be customized."},{header:"Sizing",file:"buttons/sizing",desc:"Buttons can be given different sizing options to fit a multitude of scenarios."},{header:"Outline",file:"buttons/outline",desc:"Outline buttons inherit their borders from the current color applied."},{header:"Round",file:"buttons/round",desc:"Rounded buttons behave the same as regular buttons but have rounded edges."},{header:"Block",file:"buttons/block",desc:"Block buttons extend the full available width."}],props:{"v-btn":{shared:["theme","colorable","contextual","router","positionable"],params:[["block","Boolean","False","Button will have 100% width"],["flat","Boolean","False","Applies the flat style"],["fab","Boolean","False","Applies the floating / round style"],["icon","Boolean","False","Designates the button as icon - round and flat"],["small","Boolean","False","Small size button"],["large","Boolean","False","Large size button"],["loading","Boolean","False","Adds a loading icon animation"],["outline","Boolean","False","Button will have an outline"],["round","Boolean","False","Button will be round on the sides"],["depressed","Boolean","True","Removes the button box shadow"],["ripple","[Boolean, Object]","True","Applies ripple effect"]]},"v-btn-toggle":{shared:["theme"],params:[["multiple","Boolean","False","Designates the toggle accepts and returns an array"],["mandatory","Boolean","False","Makes it so that at least one button must be toggle on"],["input-value","","-","Custom prop for v-model instead of <code>value</code>"]],model:{type:["Array","String","Number"],default:"-",description:"Holds the value(s) for toggled buttons. "}}},slots:{"v-btn":{default:!0,params:[["loader","Used for specifying custom loader"]]}},events:{"v-btn-toggle":{params:[["change","Array, String, Number","Selected button(s)"]]}}}}}}},1393:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement;return(e._self._c||t)("component-view",{attrs:{doc:e.doc}})},s=[],i={render:o,staticRenderFns:s};t.a=i},1394:function(e,t,a){"use strict";t.a={data:function(){return{doc:{component:"VCard",edit:"CardsView",title:"Card",desc:'The <code>v-card</code> component is a versatile component that can be used for anything from a panel to a static image. The <strong>card</strong> component has numerous helper components to make markup as easy as possible. Components that have no listed options use <strong class="green--text">Vue\'s</strong> functional component option for faster rendering and serve as markup sugar to make building easier.',examples:[{header:"Components",file:"cards/components",desc:"A card has 4 basic components, <code>v-card-media</code>, <code>v-card-title</code>, <code>v-card-text</code> and <code>v-card-actions</code>."},{header:"Media with text",file:"cards/media-with-text",desc:"Using the layout system, we can add custom text anywhere within the background."},{header:"Horizontal cards",file:"cards/horizontal",desc:"Using <code>v-flex</code>, you can create customized horizontal cards. Use the <code>contain</code> property to shrink the <code>v-card-media</code> to fit inside the container, instead of covering."},{header:"Grids",file:"cards/grids",desc:"Using grid lists, you can create beautiful layouts."},{header:"Custom actions",file:"cards/custom-actions",desc:"With a simple conditional, you can easily add supplementary text that is hidden until opened."}],props:{"v-card":{shared:["router","theme","colorable"],params:[["height","String","auto","Manually define the height of the Card"],["img","String","-","Specifies an image background"],["hover","Boolean","False","Apply a higher elevation on hover"],["raised","Boolean","False","Specifies a higher default elevation"],["flat","Boolean","False","Specifies a 0 elevation"],["tile","Boolean","False","Turn the card into a tile by removing the border radius"]]},"v-card-media":{params:[["contain","Boolean","False","Change the background-size to contain."],["src","String","-","The image to display as a background."],["height","Number, String","False","Manually set the height of the component."]]},"v-card-title":{params:[["primary-title","Boolean","False","Applies primary title specific padding."]]}},functional:{"v-card":{params:[["v-card-text",".card__text"],["v-card-actions",".card__actions"]]}}}}}}},1395:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement;return(e._self._c||t)("component-view",{attrs:{doc:e.doc}})},s=[],i={render:o,staticRenderFns:s};t.a=i},1396:function(e,t,a){"use strict";var o=a(16);a.n(o).a.component("fade",{functional:!0,render:function(e,t){var a=t.data||{};return a.props={name:"fade"},e("transition",a,t.children)}}),t.a={data:function(){return{doc:{title:"Carousel",component:"VCarousel",edit:"CarouselView",desc:"The <code>v-carousel</code> component is used to display large numbers of visual content on a rotating timer.",examples:[{header:"Default",file:"carousel/default",desc:"A carousel by default has a slide transition."},{header:"Custom transition",file:"carousel/custom-transition",desc:"You can also apply your own custom transition."},{header:"Custom delimiter",file:"carousel/custom-delimiter",desc:"You can also change the icon for the carousel delimiter."},{header:"Hide controls",file:"carousel/hide-controls",desc:"You can hide the navigation controls with the <code>hide-controls</code> prop."},{header:"Hide delimiters",file:"carousel/hide-delimiters",desc:"You can hide the bottom controls with the <code>hide-delimiters</code> prop."}],props:{"v-carousel":{shared:["theme"],model:{type:"Number"},params:[["cycle","Boolean","True","Determines if carousel should cycle through images"],["delimiter-icon","String","fiber_manual_record","Sets icon for carousel delimiter"],["hide-controls","Boolean","False","Hides the navigation controls"],["hide-delimiters","Boolean","False","Hides the panel with carousel delimiters"],["lazy","Boolean","False","Lazily load the carousel slides"],["left-control-icon","[Boolean, String]","chevron_left","Sets icon for left carousel control, false removes icon"],["right-control-icon","[Boolean, String]","chevron_right","Sets icon for right carousel control, false removes icon"],["interval","Number","6000","The duration between image cycles"]]},"v-carousel-item":{params:[["src","String","-","The image src"],["transition","String","v-tab-transition","Sets the normal transition"],["reverse-transition","String","v-tab-reverse-transition","Sets the reverse transition"]]}},slots:{"v-carousel":{shared:["default"]},"v-carousel-item":{shared:["default"]}}}}}}},1397:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement;return(e._self._c||t)("component-view",{attrs:{doc:e.doc}})},s=[],i={render:o,staticRenderFns:s};t.a=i},1398:function(e,t,a){var o=a(1399);"string"==typeof o&&(o=[[e.i,o,""]]),o.locals&&(e.exports=o.locals);a(198)("af565d22",o,!0)},1399:function(e,t,a){t=e.exports=a(197)(void 0),t.push([e.i,"#chips-view .component-example__container>div{text-align:center}#chips-view .chip{margin:1rem}",""])},1400:function(e,t,a){"use strict";t.a={data:function(){return{doc:{title:"Chip",component:"VChip",edit:"ChipsView",desc:"The <code>v-chip</code> component is used to convey small pieces of information. Using the <code>close</code> property, the chip becomes interactive, allowing user interaction.",examples:[{header:"Default",file:"chips/default",desc:"Chips come in 4 primary variations. Regular, with icon, with portrait and closeable."},{header:"Colored",file:"chips/colored",desc:"Any color from the Material Design palette can be used to change a chips color."},{header:"Icon",file:"chips/icon",desc:"Chips can use text or any icon available in the Material Icons font library."},{header:"Outline",file:"chips/outline",desc:"Outlined chips inherit their border color from the current text color."},{header:"Label",file:"chips/label",desc:"Label chips use the <code>v-card</code> border-radius."},{header:"Closable",file:"chips/closable",desc:"Closable chips can be controlled with a v-model. Listen to the <code>input</code> event if you want to know when a chip has been closed."},{header:"In selects",file:"chips/in-selects",desc:"Selects can use chips to display the selected data.",new:"0.15.3"}],props:{"v-chip":{shared:["colorable","theme"],params:[["text-color","String","null","Applies specified color to the control text"],["close","Boolean","False","Adds remove button"],["disabled","Boolean","False","Disabled the chip from being selectable"],["label","Boolean","False","Applies the chip--label class"],["outline","Boolean","False","Applies the chip--outline class"],["small","Boolean","False","Applies the chip--small class"],["selected","Boolean","False","Applies a selection color to the chip. Primarily used for displaying highlight context in <code>v-select</code>"]],model:{type:["Boolean"],default:"True"}}},slots:{"v-chip":{shared:["default"]}},events:{"v-chip":{params:[["input","Boolean: False","Chip was closed. Requires 'close' prop."]]}}}}}}},1401:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement;return(e._self._c||t)("component-view",{attrs:{doc:e.doc}})},s=[],i={render:o,staticRenderFns:s};t.a=i},1402:function(e,t,a){var o=a(1403);"string"==typeof o&&(o=[[e.i,o,""]]),o.locals&&(e.exports=o.locals);a(198)("0193588a",o,!0)},1403:function(e,t,a){t=e.exports=a(197)(void 0),t.push([e.i,"#colors-view .colors .flex{margin:1rem 0}#colors-view .colors .card{color:#fff;font-weight:500;letter-spacing:.5px;padding:1rem;border-radius:0}#colors-view .colors .card .card__text h3{color:#fff;-ms-flex-item-align:start;align-self:flex-start;font-size:1.5rem;margin:0}#colors-view .colors .card__text{padding:0}",""])},1404:function(e,t,a){"use strict";t.a={data:function(){return{doc:{title:"Colors",desc:"Included with Vuetify is the entire Material Design color library. These color classes drastically help the prototyping phase or make the need for additional color declaration not needed."},colors:["red","pink","purple","deep-purple","indigo","blue","light-blue","cyan","teal","green","light-green","lime","yellow","amber","orange","deep-orange","brown","blue-grey","grey"],types:["darken","lighten","accent"]}}}},1405:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement,a=e._self._c||t;return a("doc-view",{attrs:{id:"colors-view"}},[a("v-layout",{attrs:{row:"row",wrap:"wrap"}},[a("v-flex",{attrs:{xs12:"xs12",sm8:"sm8",xl12:"xl12"}},[a("section-def",[a("dt",{attrs:{slot:"title"},slot:"title"},[e._v(e._s(e.doc.title))]),a("dd",{attrs:{slot:"desc"},slot:"desc"},[e._v(e._s(e.doc.desc))])])],1),a("ad")],1),a("section",{staticClass:"mb-5"},[a("section-header",[e._v("Classes")]),a("section-text",[e._v("You can change a background or text color by adding a class to the element.\nFor background, use just the name, for example, "),a("code",[e._v('<div class="red">')]),e._v(".\nTo use a shade, just add the modifying type, such as, "),a("strong",[e._v("darken-3")]),e._v(".\nText is very similar, adding a modification class, "),a("strong",[e._v("red--text")]),e._v(",\nyou can change the color of text, or change the type with adding "),a("strong",[e._v("text--lighten-2")]),e._v(".\nFor some elements like the "),a("code",[e._v("v-badge")]),e._v(", you can use the "),a("em",[e._v("--after")]),e._v(" type for the background,\n"),a("code",[e._v('<span class="green--after" v-badge:5>')]),e._v(".\n"),a("br"),e._v("\nThese colors are also available as javascript variables, just "),a("code",[e._v("import colors from 'vuetify/es5/util/colors'")])]),a("div",{staticClass:"colors"},[a("v-container",{staticClass:"pa-0",attrs:{fluid:"fluid"}},[a("v-layout",{attrs:{row:"row",wrap:"wrap"}},e._l(e.colors,function(t){return a("v-flex",{key:t,attrs:{xs6:"xs6",sm6:"sm6",md4:"md4",lg3:"lg3"}},[a("v-card",{attrs:{color:t,height:"100px"}},[a("v-card-text",[a("h3",[e._v(e._s(t))])])],1),e._l([4,3,2,1],function(o){return a("v-card",{key:o,staticClass:"black--text",attrs:{color:t+" lighten-"+o}},[a("v-card-text",[e._v(e._s(t)+" lighten-"+e._s(o))])],1)}),e._l(4,function(o){return a("v-card",{key:o,attrs:{color:t+" darken-"+o}},[a("v-card-text",[e._v(e._s(t)+" darken-"+e._s(o))])],1)}),e._l(4,function(o){return-1===["grey","blue-grey","brown"].indexOf(t)?a("v-card",{key:o,staticClass:"black--text",attrs:{color:t+" accent-"+o}},[a("v-card-text",[e._v(e._s(t)+" accent-"+e._s(o))])],1):e._e()})],2)}))],1)],1)],1),a("v-divider",{staticClass:"my-5"}),a("section",{attrs:{id:"color-pack"}},[a("section-header",[e._v("Color Pack")]),a("section-text",[e._v("Vuetify comes pre-built with a Material Design Color Pack\n(thanks "),a("a",{attrs:{href:"http://materializecss.com/color.html",target:"_blank",rel:"noopener"}},[e._v("Materialize.css")]),e._v(") by default.\nWhile convenient, this also increases the css export size by ~30kb.\nThis can be disabled in both the webpack and webpack-ssr Vue cli templates.")]),a("div",{staticClass:"title pt-3 pb-3"},[e._v("Webpack")]),a("section-text",[e._v("Navigate to "),a("kbd",[e._v("src/App.vue")]),e._v(". Scroll to the style element and\nset "),a("code",[e._v("$color-pack = false")]),e._v(" above the Vuetify css import.")]),a("div",{staticClass:"title pt-3 pb-3"},[e._v("Webpack-SSR")]),a("section-text",[e._v("Navigate to "),a("kbd",[e._v("src/stylus/main.styl")]),e._v(". At the top of the file, declare "),a("code",[e._v("$color-pack = false")]),e._v(".")])],1)],1)},s=[],i={render:o,staticRenderFns:s};t.a=i},1406:function(e,t,a){var o=a(1407);"string"==typeof o&&(o=[[e.i,o,""]]),o.locals&&(e.exports=o.locals);a(198)("f9bca4c0",o,!0)},1407:function(e,t,a){t=e.exports=a(197)(void 0),t.push([e.i,"#content-view .component-example__container>div{width:100%}#content-view code{-webkit-box-shadow:none;box-shadow:none}",""])},1408:function(e,t,a){"use strict";t.a={name:"content-view",data:function(){return{doc:{title:"Content",desc:"Vuetify has custom styling for multiple standard elements."},lorem:"Lorem ipsum dolor sit amet, brute iriure accusata ne mea. Eos suavitate referrentur ad, te duo agam libris qualisque, utroque quaestio accommodare no qui. Et percipit laboramus usu, no invidunt verterem nominati mel. Dolorem ancillae an mei, ut putant invenire splendide mel, ea nec propriae adipisci. Ignota salutandi accusamus in sed, et per malis fuisset, qui id ludus appareat."}}}},1409:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement,a=e._self._c||t;return a("doc-view",{attrs:{id:"content-view"}},[a("v-layout",{attrs:{row:"row",wrap:"wrap"}},[a("v-flex",{attrs:{xs12:"xs12",sm8:"sm8",xl12:"xl12"}},[a("section-def",[a("dt",{attrs:{slot:"title"},slot:"title"},[e._v(e._s(e.doc.title))]),a("dd",{attrs:{slot:"desc"},slot:"desc"},[e._v(e._s(e.doc.desc))])])],1),a("ad")],1),a("section",[a("section-header",[e._v("Block quote")]),a("blockquote",{staticClass:"blockquote mb-5"},[e._v("Lorem ipsum dolor sit amet, brute iriure accusata ne mea. Eos suavitate referrentur ad, te duo agam libris qualisque, utroque quaestio accommodare no qui. Et percipit laboramus usu, no invidunt verterem nominati mel. Dolorem ancillae an mei, ut putant invenire splendide mel, ea nec propriae adipisci. Ignota salutandi accusamus in sed, et per malis fuisset, qui id ludus appareat.")]),a("section-header",[e._v("Paragraphs")]),a("div",{staticClass:"mb-5"},[a("p",[e._v("Lorem ipsum dolor sit amet, brute iriure accusata ne mea. Eos suavitate referrentur ad, te duo agam libris qualisque, utroque quaestio accommodare no qui. Et percipit laboramus usu, no invidunt verterem nominati mel. Dolorem ancillae an mei, ut putant invenire splendide mel, ea nec propriae adipisci. Ignota salutandi accusamus in sed, et per malis fuisset, qui id ludus appareat.")]),a("p",[e._v("Lorem ipsum dolor sit amet, brute iriure accusata ne mea. Eos suavitate referrentur ad, te duo agam libris qualisque, utroque quaestio accommodare no qui. Et percipit laboramus usu, no invidunt verterem nominati mel. Dolorem ancillae an mei, ut putant invenire splendide mel, ea nec propriae adipisci. Ignota salutandi accusamus in sed, et per malis fuisset, qui id ludus appareat.")])]),a("section-header",[e._v("Code")]),a("div",{staticClass:"mb-5"},[e._v("Example of an inline "),a("code",[e._v("<code>")]),e._v(" element.")]),a("section-header",[e._v("Variables")]),a("div",{staticClass:"mb-5"},[a("var",[e._v("v")]),e._v(" = "),a("var",[e._v("u")]),e._v(" * "),a("var",[e._v("e")])]),a("section-header",[e._v("User input")]),a("div",[e._v("To install Vuetify, type "),a("kbd",[e._v("npm install vuetify")]),e._v(" into your console. Once complete, type "),a("kbd",[e._v("cd <project name>")]),e._v(" and run "),a("kbd",[e._v("npm install")])])],1)],1)},s=[],i={render:o,staticRenderFns:s};t.a=i},1410:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement,a=e._self._c||t;return a("doc-view",[a("v-layout",{attrs:{row:"row",wrap:"wrap"}},[a("v-flex",{attrs:{xs12:"xs12",sm8:"sm8",xl12:"xl12"}},[a("section-def",[a("dt",{attrs:{slot:"title"},slot:"title"},[e._v("Be a part of something bigger!")]),a("dd",{attrs:{slot:"desc"},slot:"desc"},[e._v("Vuetify is made possible by an amazing community that submits issues, creates pull requests, and provides invaluable feedback. It is our job to enable you to create amazing applications. A lot of the time, you come across something that can be made better. Maybe you find a bug, or you have an idea for additional functionality. That's great! It's as easy as cloning the Vuetify repository to get started working in a development environment.")])])],1),a("ad")],1),a("section",{attrs:{id:"reporting-issues"}},[a("section-header",[e._v("Reporting issues")]),a("section-text",[a("ul",{staticClass:"browser-list"},[a("li",[e._v("Use the "),a("a",{attrs:{href:"https://issues.vuetifyjs.com",target:"_blank",rel:"noopener"}},[e._v("issue creator")]),e._v(" when you want to report a bug or submit a feature request.")]),a("li",[e._v("Any issues not created using the issue creator will be closed immediately.")]),a("ul",{staticClass:"browser-list"},[a("li",[e._v("For general questions, please join the "),a("a",{attrs:{href:"https://chat.vuetifyjs.com",target:"_blank",rel:"noopener"}},[e._v("community")]),e._v(".")])]),a("li",[e._v("Try to search for your issue, it may have been answered.")]),a("li",[e._v("See if the error is reproducible with the latest version.")]),a("li",[e._v("If reproducible, please provide a simple "),a("a",{attrs:{href:"https://template.vuetifyjs.com",target:"_blank",rel:"noopener"}},[e._v("codepen")]),e._v(" or repository that can be cloned to produce the expected behavior.")])])])],1),a("section",{attrs:{id:"pull-requests"}},[a("section-header",[e._v("Pull requests")]),a("section-text",[a("ul",{staticClass:"browser-list"},[a("li",[e._v("All PR's should be made to the "),a("code",[e._v("dev")]),e._v(" branch of Vuetify.")]),a("li",[e._v("For changes and feature requests, please include an example of what you are trying to solve and an example of the markup")]),a("li",[e._v("For bug fixes please reference the issue # that the PR resolves")])])])],1),a("section",{attrs:{id:"local-dev"}},[a("section-header",[e._v("Setup local dev")]),a("section-text",[e._v("Vuetify contains a local dev environment that you can bootup to test new features, functionality, and components. First, clone the repository:")]),a("markup",{attrs:{lang:"cli"}},[e._v("git clone git@github.com:vuetifyjs/vuetify")]),a("section-text",[e._v("After cloned, use your cli to "),a("kbd",[e._v("cd vuetify")]),e._v(". Once in the directory, you will need to create a new file in the "),a("kbd",[e._v("dev")]),e._v(" directory called "),a("code",[e._v("Playground.vue")]),e._v(". An example has been provided, "),a("code",[e._v("Playground.example.vue")]),e._v(", which you can rename. Keep in mind, this file is not tracked by version control. Once copied, go back to your cli and run:")]),a("markup",{attrs:{lang:"cli"}},[e._v("git checkout dev\nnpm install // or yarn\nnpm run dev")]),a("section-text",[e._v("This will start a local node server located at "),a("a",{attrs:{href:"http://localhost:8080"}},[e._v("http://localhost:8080")]),e._v(". Now from your code editor you can easily load components and test whatever you want at lightning speed!")])],1)],1)},s=[],i={render:o,staticRenderFns:s};t.a=i},1411:function(e,t,a){var o=a(1412);"string"==typeof o&&(o=[[e.i,o,""]]),o.locals&&(e.exports=o.locals);a(198)("b605072e",o,!0)},1412:function(e,t,a){t=e.exports=a(197)(void 0),t.push([e.i,"#data-tables-view{max-width:1200px}",""])},1413:function(e,t,a){"use strict";t.a={data:function(){return{doc:{component:"VDataTable",edit:"DatatablesView",title:"Data tables",id:"#data-tables-view",desc:"The <code>v-data-table</code> component is used for displaying tabular data. Features include sorting, searching, pagination, inline-editing, header tooltips, and row selection.",examples:[{header:"Standard",file:"tables/standard",desc:"The standard data-table contains data with no additional functionality. You can opt out of displaying table actions that allow you to control the pagination of information with the <code>hide-actions</code> prop."},{header:"Slots: no-data / no-results",file:"tables/noData",desc:"The <code>no-data</code> and <code>no-results</code> slots can display custom HTML when theres no data or no filtered data in the table"},{header:"Slots: items and headers",file:"tables/headers",desc:"The <code>items</code> and <code>headers</code> slots can accept either a collection of <kbd>td/th</kbd> tags, or if you want control of the entire row, a <kbd>tr</kbd> tag."},{header:"Slots: headerCell",file:"tables/headerCell",desc:"If you only want to apply some common markup or effect on each of the header cells, you can use the slot <code>headerCell</code>. In this example is has been used to apply a tooltip to each header."},{header:"Slots: footer",file:"tables/footer",desc:"There is also a <code>footer</code> slot for when you want to add some extra functionality to tables, for example per column filtering or search."},{header:"Slots: expand",file:"tables/expand",desc:"The <code>v-data-table</code> component also supports expandable rows using the <code>expand</code> slot. You can use the prop <code>expand</code> to prevent expanded rows from closing when clicking on another row."},{header:"Selectable rows",file:"tables/select",desc:"Selectable rows allow you to perform an action on specific and all rows."},{header:"Search with custom page text",file:"tables/search",desc:"The data table exposes a <code>search</code> prop that allows you to filter your data."},{header:"External pagination",file:"tables/paginate",desc:"Pagination can be controlled externally by using the <code>pagination</code> prop. Remember that you must apply the <code>.sync</code> modifier."},{header:"External sorting",file:"tables/sort",desc:"Sorting can also be controlled externally by using the <code>pagination</code> prop. Remember that you must apply the <code>.sync</code> modifier. You can also use the prop to set the default sorted column."},{header:"Paginate and sort server-side",file:"tables/server",desc:"If you're loading data from a backend and want to paginate and sort the results before displaying them, you can use the <code>total-items</code> prop. Defining this prop will disable the built-in sorting and pagination, and you will instead need to use the <code>pagination</code> prop to listen for changes. Use the <code>loading</code> prop to display a progress bar while fetching data."},{header:"Theme support",file:"tables/theme",desc:"The <code>v-data-table</code> component supports the application dark theme."},{header:"Headerless tables",file:"tables/headerless",desc:"Setting the <code>hide-headers</code> prop creates a headerless table.",new:"0.16.4"}],props:{"v-data-table":{shared:["filterable","loadable","theme"],params:[["headers","Array","[]","The array of headers"],["header-text","String","text","If using an object, the text value for the header"],["hide-actions","Boolean","False","Hide the table actions"],["hide-headers","Boolean","False","Hide the table headers"],["disable-initial-sort","Boolean","False","Disable default sorting on initial render"],["items","Array","[]","The array of table rows"],["no-results-text","String","No matching records found","Display text when there are no filtered results"],["rows-per-page-text","String","Rows per page:","The default rows per page text"],["rows-per-page-items","Array",'[5, 15, 25, { text: "All", value: -1 }]',"The default values for the rows-per-page dropdown"],["select-all","[Boolean, String]","False","Adds header row select all checkbox. Can either be a String which specifies which color is applied to the button, or a Boolean (which uses the default color)"],["item-key","String","id","Determines the item value used for identifying selected items"],["search","String","-","The search model for filtering results"],["filter","Function","(val, search) => boolean","The method used by customFilter to filter each individual item. The default function does a simple indexOf check. Should return a boolean indicating if item matches search input."],["custom-filter","Function","(items, search, filter, headers) => array","Custom search filter. A default implementation will be used if prop is not specified. Should return an array of items matching the search input."],["custom-sort","Function","-","Custom sort filter"],["must-sort","Boolean","False","Forces at least one column to always be sorted instead of toggling between <code>sorted ascending</code>/<code>sorted descending</code>/<code>unsorted</code> states"],["total-items","Number","-","Manually sets total number of row items, which disables built-in sort and pagination. Used together with pagination prop to enable server-side sort and pagination"],["pagination.sync","Object","{\n sortBy: 'column',\n page: 1,\n rowsPerPage: 5,\n descending: false,\n totalItems: 0\n }","Used to control pagination and sorting from outside the data table. Can also be used to set default sorted column"],["expand","Boolean","False","Designates the table as containing rows that are expandable"]],model:{type:["Array"],default:"",description:"Holds selected row items"}},"v-edit-dialog":{params:[["cancel-text","String","Cancel","Set's the default text for the cancel button when using the <code>large</code> prop"],["save-text","String","Save","Set's the default text for the save button when using the <code>large</code> prop"],["large","Boolean","False","Attaches a submit and cancel button to the dialog"],["lazy","Boolean","False","Lazily load the dialog contents"],["transition","String","v-slide-x-reverse-transition","The transition of the edit dialog"]]}},slots:{shared:["progress"],"v-data-table":{params:[["scope[headerCell]","The scoped slot for each individual header cell. The available prop is <code>header</code> which is the current header. Can be used to apply some markup or effect to each cell, such as a tooltip."],["scope[headers]","The scoped slot for templating the headers. Provide either a <kbd>tr</kbd> tag or <kbd>th</kbd> tags for all headers. Scope properties <code>headers</code>, <code>indeterminate</code>, and <code>all</code>."],["scope[items]","The scoped slot for templating the row display. Available props are the currently iterated <code>item</code> and its <code>index</code> within the iterated items array. Provide either a <kbd>tr</kbd> tag or <kbd>td</kbd> tags for all columns."],["scope[pageText]","The scoped slot for adding custom page text."],["no-data","Slot displayed in the table body when there is no data (see also <code>no-data-text</code> prop)"],["no-results","Slot displayed in the table body when there are no filtered results (see also <code>no-results-text</code> prop)"]]}},events:{"v-data-table":{params:[["input","Array","Array will contain selected rows"]]},"v-edit-dialog":{params:[["open","-","Edit dialog opened"],["close","-","Edit dialog closed"],["cancel","-","Cancel button was clicked"],["save","-","Save button was clicked"]]}}}}},methods:{saving:function(){console.log("I saved!")}}}},1414:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement;return(e._self._c||t)("component-view",{attrs:{doc:e.doc}})},s=[],i={render:o,staticRenderFns:s};t.a=i},1415:function(e,t,a){"use strict";t.a={name:"dialogs-view",data:function(){return{doc:{title:"Dialog",component:"VDialog",edit:"DialogsView",desc:"<p>The <code>v-dialog</code> component inform users about a specific task and may contain critical information, require decisions, or involve multiple tasks. Use dialogs sparingly because they are interruptive.</p>\n <p>If you want to programmatically open or close the dialog, you can do so by using <code>v-model</code> with a boolean value. Keep in mind, if the trigger for the opening is not contained within the <code>activator</code> slot and is done so by a click, you must <strong>stopPropagation</strong> to avoid immediately triggering a close event.</p>",examples:[{header:"Simple dialogs",file:"dialogs/simple",desc:"Choosing an option immediately commits the option and closes the menu. Touching outside of the dialog, or pressing Back, cancels the action and closes the dialog."},{header:"Without activator",file:"dialogs/without-activator",desc:"If for some reason you are unable to use the activator slot, be sure to add the <code>.stop</code> modifier to the event that triggers the dialog."},{header:"Modal",file:"dialogs/modal",desc:"Similar to a Simple Dialog, except that it's not dismissed when touching outside."},{header:"Fullscreen",file:"dialogs/fullscreen",desc:"Due to limited space, full-screen dialogs may be more appropriate for mobile devices than dialogs used on devices with larger screens."},{header:"Form",file:"dialogs/form",desc:"Just a simple example of a form in a dialog."},{header:"Scrollable",file:"dialogs/scrollable",desc:"Example of a dialog with scrollable content."},{header:"Overflowed",file:"dialogs/overflowed",desc:"Modals that do not fit within the available window space will scroll the container."}],props:{"v-dialog":{shared:["overlay","detachable","dialog"],params:[["fullscreen","Boolean","False","Changes layout for fullscreen display"],["origin","String","center center","Defines transition origin"],["transition","[Boolean, String]","v-dialog-transition","Defines show/hide transition. Set to false for no transition"]],model:{type:["Boolean"],default:"False"}}},slots:{"v-dialog":{shared:["default"],params:[["activator","The element that will activate the dialog"]]}}}}}}},1416:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement;return(e._self._c||t)("component-view",{attrs:{doc:e.doc}})},s=[],i={render:o,staticRenderFns:s};t.a=i},1417:function(e,t,a){"use strict";t.a={name:"display-view"}},1418:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement,a=e._self._c||t;return a("div",{staticClass:"view",attrs:{id:"display-view"}},[a("v-layout",{attrs:{row:"row"}},[a("v-flex",{attrs:{xs12:"xs12",sm8:"sm8",md12:"md12"}},[a("section-def",[a("dt",{attrs:{slot:"title"},slot:"title"},[e._v("Display")]),a("dd",{attrs:{slot:"desc"},slot:"desc"},[e._v("The display helpers allow you to control the display of content. This includes being conditionally visible based upon the current viewport, or the actual element display type.")])])],1),a("ad")],1),a("grid"),a("section",[a("h6",{staticClass:"subheading"},[e._v("Classes")]),e._m(0),e._m(1),a("component-example",{attrs:{header:"Hidden elements",file:"display/hidden-elements"}},[a("div",{attrs:{slot:"desc"},slot:"desc"},[e._v("The toolbar links will be hidden on small viewport devices and down")])])],1)],1)},s=[function(){var e=this,t=e.$createElement,a=e._self._c||t;return a("ul",{staticClass:"mb-3 browser-list"},[a("li",{staticClass:"subheader pl-0"},[e._v("Visibility")]),a("li",[a("code",[e._v("hidden-xs-only")]),e._v(" - hidden on extra small viewports only")]),a("li",[a("code",[e._v("hidden-sm-and-down")]),e._v(" - hidden on small viewports and down")]),a("li",[a("code",[e._v("hidden-sm-and-up")]),e._v(" - hidden on small viewports and up")]),a("li",[a("code",[e._v("hidden-md-only")]),e._v(" - hidden on medium viewports only")]),a("li",[a("code",[e._v("hidden-md-and-down")]),e._v(" - hidden on medium viewports and down")]),a("li",[a("code",[e._v("hidden-md-and-up")]),e._v(" - hidden on medium viewports and up")]),a("li",[a("code",[e._v("hidden-lg-only")]),e._v(" - hidden on large viewports only")]),a("li",[a("code",[e._v("hidden-lg-and-down")]),e._v(" - hidden on large viewports and down")]),a("li",[a("code",[e._v("hidden-lg-and-up")]),e._v(" - hidden on large viewports and up")]),a("li",[a("code",[e._v("hidden-xl-only")]),e._v(" - hidden on extra large viewports only")])])},function(){var e=this,t=e.$createElement,a=e._self._c||t;return a("ul",{staticClass:"mb-5 browser-list"},[a("li",{staticClass:"subheader pl-0"},[e._v("Display")]),a("li",[a("code",[e._v("d-flex")]),e._v(" - sets element display to flex")]),a("li",[a("code",[e._v("d-inline-flex")]),e._v(" - sets element display to inline-flex")]),a("li",[a("code",[e._v("d-block")]),e._v(" - sets element display to block")]),a("li",[a("code",[e._v("d-inline-block")]),e._v(" - sets element display to inline-block")])])}],i={render:o,staticRenderFns:s};t.a=i},1419:function(e,t,a){var o=a(1420);"string"==typeof o&&(o=[[e.i,o,""]]),o.locals&&(e.exports=o.locals);a(198)("b04b0eb6",o,!0)},1420:function(e,t,a){t=e.exports=a(197)(void 0),t.push([e.i,"#divider-view .grid{max-height:500px;overflow-y:auto}#divider-view .component-example{position:relative;z-index:1}#divider-view .component-example .card{max-width:400px;margin:0 auto}#divider-view .component-example .image{width:100%}#divider-view .toolbar{height:64px;min-height:none}",""])},1421:function(e,t,a){"use strict";t.a={data:function(){return{doc:{title:"Dividers",component:"VDivider",edit:"DividerView",desc:"The <code>v-divider</code> component is used to separate sections of lists.",examples:[{header:"Full bleed",file:"dividers/full-bleed",desc:"Full bleed dividers extend the entire content width."},{header:"Light and dark",file:"dividers/light-and-dark",desc:"Dividers have light and dark variants."},{header:"Inset dividers",file:"dividers/inset",desc:"Inset dividers are moved 72px to the right. This will cause them to line up with list items."},{header:"Subheaders and dividers",file:"dividers/subheaders",desc:"Subheaders can be lined up with inset dividers by using the same prop."}],props:{"v-divider":{shared:["theme"],params:[["inset","Boolean","False","Adds indentation (72px)"]]}}}}}}},1422:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement;return(e._self._c||t)("component-view",{attrs:{doc:e.doc}})},s=[],i={render:o,staticRenderFns:s};t.a=i},1423:function(e,t,a){var o=a(1424);"string"==typeof o&&(o=[[e.i,o,""]]),o.locals&&(e.exports=o.locals);a(198)("6c5065c3",o,!0)},1424:function(e,t,a){t=e.exports=a(197)(void 0),t.push([e.i,"#display-view .toolbar{height:64px}",""])},1425:function(e,t,a){"use strict";t.a={name:"elevation-view",data:function(){return{selected:0}}}},1426:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement,a=e._self._c||t;return a("div",{staticClass:"view",attrs:{id:"elevation-view"}},[a("v-layout",{attrs:{row:"row"}},[a("v-flex",{attrs:{xs12:"xs12",sm8:"sm8",md12:"md12"}},[a("section-def",[a("dt",{attrs:{slot:"title"},slot:"title"},[e._v("Elevation")]),a("dd",{attrs:{slot:"desc"},slot:"desc"},[e._v("The elevation helpers allow you to control relative depth, or distance, between two surfaces along the z-axis.")])])],1),a("ad")],1),a("section",[a("h6",{staticClass:"title"},[e._v("Variants")]),e._m(0),a("h6",{staticClass:"title"},[e._v("Playground")]),a("v-container",{attrs:{fluid:"fluid"}},[a("v-layout",{attrs:{row:"row"}},[a("v-flex",{attrs:{xs4:"xs4"}},[a("v-slider",{attrs:{"prepend-icon":"fa-arrows-h",min:"0",max:"24","thumb-label":"thumb-label"},model:{value:e.selected,callback:function(t){e.selected=t},expression:"selected"}})],1),a("v-flex",{attrs:{xs6:"xs6","offset-xs1":"offset-xs1"}},[a("v-card",{class:(o={},o["elevation-"+e.selected]=!0,o)},[a("v-card-text",[a("p",{staticClass:"text-xs-center ma-0"},[e._v("Elevation "+e._s(e.selected))])])],1)],1)],1)],1)],1)],1);var o},s=[function(){var e=this,t=e.$createElement,a=e._self._c||t;return a("p",{staticClass:"mb-5"},[e._v("There's a total of 25 elevation levels. You can set an element's elevation by using the class "),a("code",[e._v("elevation-N")]),e._v(", where N is a integer between 0-24 corresponding to the desired elevation.")])}],i={render:o,staticRenderFns:s};t.a=i},1427:function(e,t,a){"use strict";t.a={data:function(){return{component:null}},computed:{source:function(){return"https://github.com/vuetifyjs/docs/blob/master"+this.$route.fullPath+".vue"}},beforeRouteEnter:function(e,t,o){return a(58)("./"+e.params.example+".vue").then(function(e){o(function(t){return t.component=e.default})}).catch(function(e){o("/404")})}}},1428:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement;return(e._self._c||t)(e.component,{tag:"component",attrs:{source:e.source}})},s=[],i={render:o,staticRenderFns:s};t.a=i},1429:function(e,t,a){"use strict";t.a={data:function(){return{doc:{title:"Expansion Panel",edit:"ExpansionPanelView",component:"VExpansionPanel",desc:"The <code>v-expansion-panel</code> component is useful for reducing vertical space with large amounts of information. The default functionality of the component is to only display one expansion-panel body at a time, however, with the <code>expandable</code> property, the expansion-panel can remain open until explicitly closed.",examples:[{header:"Accordion",file:"expansion-panel/accordion",desc:"Accordion expansion panels can only have 1 panel open at a time."},{header:"Expand",file:"expansion-panel/expand",desc:"Expand expansion panels will stay open until closed."},{header:"Popout & Inset",file:"expansion-panel/popout",desc:"The expansion panel also has two alternative designs you can activate with the props <code>popout</code> and <code>inset</code>."},{header:"Focusable",file:"expansion-panel/focusable",desc:"The expansion panel headers can be made focusable with the prop <code>focusable</code>."}],props:{"v-expansion-panel":{shared:["theme"],params:[["expand","Boolean","False","Leaves expansion-panel open when selecting another"],["focusable","Boolean","False","Makes the expansion panel headers focusable"],["inset","Boolean","False","Makes the expansion panel open with an inset style"],["popout","Boolean","False","Makes the expansion panel open with a popout style"]]},"v-expansion-panel-content":{params:[["ripple","Boolean","False","Applies the ripple directive"],["hide-actions","Boolean","False","Hide the icon in the content header"],["lazy","Boolean","False","Lazily load the expansion panel contents"]],model:{type:["Boolean"],default:"False",description:"Designates whether content is expanded or not"}}},slots:{"v-expansion-panel":{shared:["default"]},"v-expansion-panel-content":{shared:["default"],params:[["header","Expansion header content"],["actions","Expansion header actions"]]}}}}}}},1430:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement;return(e._self._c||t)("component-view",{attrs:{doc:e.doc}})},s=[],i={render:o,staticRenderFns:s};t.a=i},1431:function(e,t,a){var o=a(1432);"string"==typeof o&&(o=[[e.i,o,""]]),o.locals&&(e.exports=o.locals);a(198)("766ef415",o,!0)},1432:function(e,t,a){t=e.exports=a(197)(void 0),t.push([e.i,"#fab-view .btn--floating.btn--absolute{z-index:0!important}",""])},1433:function(e,t,a){"use strict";t.a={name:"fabs-view",data:function(){return{doc:{component:"VBtn",edit:"FabsView",title:"Buttons: Floating Action Button",desc:"The <code>v-btn</code> component can be used as a Floating action button. This provides an application a main point of action. Combined with the <code>v-speed-dial</code> component, you can create a diverse set of functions available for your users.",examples:[{header:"Promoted action",file:"fabs/promoted-action",desc:"Floating action buttons can be attached to material to signify a promoted action in your application. The default size will be used in most cases, whereas the <code>small</code> variant can be used to maintain continuity with similar sized elements."},{header:"Small variant",file:"fabs/small",desc:"For better visual appeal, we use a small button to match our list avatars."},{header:"Display animation",file:"fabs/display-animation",desc:"When displaying for the first time, a floating action button should animate onto the screen. Here we use the <code>v-fab-transition</code> with v-show. You can also use any custom transition provided by Vuetify or your own."},{header:"Lateral screens",file:"fabs/lateral-screens",desc:"When changing the default action of your button, it is recommended that you display a transition to signify a change. We do this by binding the <code>key</code> prop to a piece of data that can properly signal a change in action to the Vue transition system. While you can use a custom transition for this, ensure that you set the <code>mode</code> prop to <strong>out-in</strong>."},{header:"FAB with speed-dial",file:"fabs/speed-dial",desc:"The speed-dial component has an very robust api for customizing your FAB experience exactly how you want."}],props:{"speed-dial":{shared:["positionable"],model:{type:["Boolean"],default:"False",description:"Used to link the speed-dial state to a button (fab)."},params:[["direction","String ['top', 'right', 'bottom', 'left']","top","Controls the direction that the speed dial list will open."],["hover","Boolean","False","Open the speed dial when the button is hovered over."],["transition","String","scale-transition","The default transition to be used for the list animation."]]}},slots:{"speed-dial":{shared:["default"],params:[["activator","The element that will activate the menu"]]}}}}}}},1434:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement,a=e._self._c||t;return a("component-view",{attrs:{doc:e.doc,id:"fab-view"}},[a("v-alert",{attrs:{color:"info",icon:"info",value:"value"}},[e._v("For more information on all the options available for the "),a("code",[e._v("v-btn")]),e._v(" component, please navigate to the "),a("router-link",{staticClass:"white--text",attrs:{to:"/components/buttons"}},[e._v("Button documentation")]),e._v(".")],1)],1)},s=[],i={render:o,staticRenderFns:s};t.a=i},1435:function(e,t,a){var o=a(1436);"string"==typeof o&&(o=[[e.i,o,""]]),o.locals&&(e.exports=o.locals);a(198)("815a1d9c",o,!0)},1436:function(e,t,a){t=e.exports=a(197)(void 0),t.push([e.i,"#faq-view .expansion-panel__header>div{overflow:hidden;-o-text-overflow:ellipsis;text-overflow:ellipsis;white-space:nowrap}",""])},1437:function(e,t,a){"use strict";t.a={data:function(){return{gotchas:[{q:"My code doesn't work - what should I do?",a:'\n <p>First, ensure that you\'re using the latest version of Vue.js and Vuetify. Try to reproduce it in codepen using the following template:</p>\n <a href="https://template.vuetifyjs.com/" target="_blank" rel="noopener">https://template.vuetifyjs.com</a>.\n <p>and then seek advice in the official discord server:</p>\n <a href="https://chat.vuetifyjs.com/" target="_blank" rel="noopener">https://chat.vuetifyjs.com</a>\n '},{q:"Is there a codepen template with router?",a:'Yes, <a href="https://codepen.io/zikeji/pen/ypeQNm" target="_blank" rel="noopener">https://codepen.io/zikeji/pen/ypeQNm</a>'},{q:"My application does not look correct",a:"Vuetify requires the use of the <code>v-app</code> component. It should wrap your entire application and is the center point for much of the framework functionality. If for whatever reason you cannot use this element, you can mimic it from attributes and classes. Set the <code>data-app</code> attribute to true on the highest element available (not including body), and the <strong>application application--{light|dark}</strong> classes."},{q:"The Dark or Light theme are not working.",a:'Vuetify requires a mounting point in order to perform tasks such as theme styling. Ensure that you have a <code>v-app</code> wrapping your application. In the event that this is not possible, for whatever reason, you can mimic its behavior by applying <strong>data-app</strong> and <strong>class="application application--light (or dark)</strong> to the highest element that you can within your application.'},{q:"Menu/Dialog/Navigation drawer are not opening properly.",a:"Ensure that your components are wrapped with a <code>v-app</code> element. If you are using an element to activate the component that is not placed into the <kbd>activator</kbd> slot, ensure that you stop propagation of the click event. These components utilize the <code>v-outside-click</code> directive and will immediately close."},{q:"The scrollbar is showing even though my content is not overflowing vertically.",a:"Vuetify by default turns on the html scrollbar. This is a design choice and has been debated numerous times. There are pros and cons to having and not having it and as of now, the vote is in favor of leaving it as is. If you wish to disable this functionality, simply add <code>html { overflow-y: auto }</code> to your style file."},{q:"How to center vertically?",a:"Apply the <strong>fill-height</strong> prop to <code>v-container</code>. This helper class normally only adds <strong>height: 100%</strong>, but for the container, it also looks for a child <code>v-layout</code> and applies the needed classes to vertically center the content."},{q:'My "/" link is active when I\'m on "/home" page',a:'Add the <strong>exact</strong> to the link that points to absolute /. For more information on this, you can visit the official Vue router <a href="https://router.vuejs.org/en/api/router-link.html" target="_blank" rel="noopener">documentation</a>.'},{q:"My page on mobile is not responsive",a:'Add the <code><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui"></code> to the <code><head></code> section in your index.html.'},{q:"How do I use Font Awesome Icons or Material Design Icons (mdi)?",a:'\n <p>You must add the fonts to your index.html or otherwise import them into your project.</p>\n <ul class="browser-list"><li>MDI: <a href="https://materialdesignicons.com/getting-started" target="_blank" rel="noopener">https://materialdesignicons.com/getting-started</a></li><li> FA: <a href="http://fontawesome.io/get-started/" target="blank" rel="noopener">http://fontawesome.io/get-started/</a></li></ul>\n '},{q:"My dialog closes immediately after clicking the button",a:'When not using the <strong>activator</strong> slot for <code>v-menu</code> and <code>v-dialog</code> for example, you must manually stop the <em>propagation</em> of the click event. To do this, simply add the <em>.stop</em> modifier to the click event, <code>@click.stop="myMethod"</code>.'},{q:"Relative images are not working in <code>v-card</code> components",a:"<p>Vue loader converts relative paths into require functions automatically for you. Unfortunately, this is not the case when it comes to custom components.</p><p>In order to use relative paths, you must use the <code>require</code>:</p><p><code class=\"pa-2\">methods: {<br> getImgUrl (img) {<br> return require('../../assets/img/' + img)<br> }<br>}</code></p><p>and use it in the tempate: <code>:src=\"getImgUrl('card.img')\"</code></p>"}],search:""}},computed:{faqs:function(){var e=this;return this.gotchas.filter(function(t){var a=t.a.toLowerCase(),o=t.q.toLowerCase(),s=(e.search||"").toLowerCase();return a.indexOf(s)>-1||o.indexOf(s)>-1})}},methods:{resetSearch:function(){this.search="",this.$refs.search.focus()}}}},1438:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement,a=e._self._c||t;return a("doc-view",{attrs:{id:"faq-view"}},[a("v-layout",{attrs:{row:"row",wrap:"wrap"}},[a("v-flex",{attrs:{xs12:"xs12",sm8:"sm8",xl12:"xl12"}},[a("section-def",[a("dt",{attrs:{slot:"title"},slot:"title"},[e._v("Frequently asked questions")]),a("dd",{attrs:{slot:"desc"},slot:"desc"},[e._v("Stuck on a particular problem? Check some of these common gotchas before creating a ticket. If you still cannot find what you are looking for, submit an "),a("a",{attrs:{href:"https://issues.vuetifyjs.com",target:"_blank",rel:"noopener"}},[e._v("issue")]),e._v(" on github or ask the community in "),a("a",{attrs:{href:"https://chat.vuetifyjs.com",target:"_blank",rel:"noopener"}},[e._v("discord")]),e._v(".")])])],1),a("ad")],1),a("section",{attrs:{id:"frequently-asked-questions"}},[a("v-text-field",{ref:"search",staticClass:"mb-3",attrs:{label:"Search","single-line":"single-line",clearable:"clearable","prepend-icon":"filter_list",solo:"solo"},model:{value:e.search,callback:function(t){e.search=t},expression:"search"}}),a("v-expansion-panel",{staticClass:"mb-5",attrs:{expand:"expand"}},e._l(e.faqs,function(t,o){return a("v-expansion-panel-content",{key:o},[a("div",{staticClass:"pr-5",attrs:{slot:"header"},slot:"header"},[a("strong",[e._v("Question: ")]),a("span",{domProps:{innerHTML:e._s(t.q)}})]),a("v-divider"),a("v-card",{attrs:{color:"grey lighten-4"}},[a("v-card-text",[a("strong",[e._v("Answer: ")]),a("div",{domProps:{innerHTML:e._s(t.a)}})])],1)],1)})),a("v-fade-transition",[e.faqs.length?e._e():a("div",{staticClass:"text-xs-center mb-5"},[a("h3",[e._v("No results found")]),a("v-btn",{attrs:{color:"primary",flat:"flat"},on:{click:e.resetSearch}},[e._v("Reset search")])],1)]),a("div",{staticClass:"text-xs-center"},[a("div",{staticClass:"mb-3"},[e._v("Have something that you think belongs here?")]),a("v-btn",{attrs:{outline:"outline",color:"success",round:"round",href:"https://chat.vuetifyjs.com",target:"_blank",rel:"noopener"}},[e._v("Let us know")])],1)],1)],1)},s=[],i={render:o,staticRenderFns:s};t.a=i},1439:function(e,t,a){var o=a(1440);"string"==typeof o&&(o=[[e.i,o,""]]),o.locals&&(e.exports=o.locals);a(198)("4db120f7",o,!0)},1440:function(e,t,a){t=e.exports=a(197)(void 0),t.push([e.i,"#footer-view .component-example__container>div{width:100%}#footer-view footer{min-height:36px}",""])},1441:function(e,t,a){"use strict";t.a={data:function(){return{doc:{title:"Footer",component:"VFooter",edit:"FooterView",desc:"The <code>v-footer</code> component is used for displaying general information that a user might want to access from any page within your site.",examples:[{header:"Default",file:"footer/default",desc:"The footer component is just a basic container."}],props:{"v-footer":{shared:["app","theme","colorable"],params:[["absolute","Boolean","False","Sets the position of the footer to absolute"],["fixed","Boolean","False","Sets the position of the footer to fixed"]]}},slots:{"v-footer":{shared:["default","colorable"]}}}}}}},1442:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement;return(e._self._c||t)("component-view",{attrs:{doc:e.doc,id:"footer-view"}})},s=[],i={render:o,staticRenderFns:s};t.a=i},1443:function(e,t,a){var o=a(1444);"string"==typeof o&&(o=[[e.i,o,""]]),o.locals&&(e.exports=o.locals);a(198)("4714efa7",o,!0)},1444:function(e,t,a){t=e.exports=a(197)(void 0),t.push([e.i,"",""])},1445:function(e,t,a){"use strict";t.a={data:function(){return{doc:{title:"Forms",component:"VForm",edit:"FormsView",desc:"When it comes to form validation, Vuetify has a multitude of integrations and baked in functionality. Want to use a 3rd party validation plugin? Out of the box you can use Vee-validate and Vuelidate.",examples:[{header:"VForm - Basic validation",file:"forms/basic-validation",desc:""},{header:"VForm - Validation w/ submit & clear",file:"forms/validation-with-submit-and-clear",desc:""},{header:"Vuelidate",file:"forms/vuelidate",desc:""},{header:"Vee-validate",file:"forms/vee-validate",desc:'Vee-validate is another validation plugin that allows you to check your forms. One caveat is that you must add the <strong>type="checkbox"</strong> to properly validate a <code>v-checkbox</code> when using the <strong>value</strong> prop.'}],props:{"v-form":{params:[["value","Boolean","false","Current validation state of form"],["lazy-validation","Boolean","false","If enabled, <code>value</code> will always be true unless there are visible validation errors. You can still call <code>validate()</code> to manually trigger validation"]],model:{type:"Boolean",default:"false",description:"Current validation state of form"}}},slots:{"v-form":{shared:["default"]}},events:{"v-form":{params:[["input","Boolean","Validation state changed"],["submit","-","Form has been submitted. You can use <code>@submit.prevent</code> to suppress this event and disable form submission (e.g. to avoid reloading the page)"]]}}}}}}},1446:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement;return(e._self._c||t)("component-view",{attrs:{doc:e.doc}})},s=[],i={render:o,staticRenderFns:s};t.a=i},1447:function(e,t,a){"use strict";t.a={data:function(){return{doc:{title:"Grid list",component:"VGrid",edit:"GridListView",desc:"Grid lists are an addon for the <code>v-container</code> component that add gutter control between items.",examples:[{header:"Grid lists",file:"grid-lists/default",desc:"Grid lists augment the <code>v-container</code> component to allow for greater flexibility with gutters. It comes in 5 variants, from xs to xl and can be dynamically changed."},{header:"Grid lists",file:"grid-lists/subheader",desc:"Grid lists will work seamlessly with your current grid implementation and allow you to create amazing user interfaces."}],props:{"v-container":{params:[["grid-list-{xs through xl}","Boolean","False","Sets the gutter between grid list items ranging from 2px to 24px"]]}},slots:{"v-container":{default:!0}}}}}}},1448:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement;return(e._self._c||t)("component-view",{attrs:{doc:e.doc}})},s=[],i={render:o,staticRenderFns:s};t.a=i},1449:function(e,t,a){"use strict";t.a={data:function(){return{doc:{title:"Grid",component:"VGrid",edit:"GridView",desc:"Vuetify has a 12 point grid system. Built using <kbd>flex-box</kbd>, the grid is used to layout an application's content. It contains 5 types of media breakpoints that are used for targeting specific screen sizes or orientations. The props for grid components are actually classes that are derived from their defined properties. This allows you to easily specify these helper classes as props, while still providing the classes to be used anywhere.",examples:[{header:"Grid",file:"grid/grid",desc:"The <code>v-container</code> can be used for a center focused page, or given the <code>fluid</code> prop to extend its full width. <code>v-layout</code> is used for separating sections and contains the <code>v-flex</code>. The structure of your layout will be as follows, <strong>v-container</strong> » <strong>v-layout</strong> » <strong>v-flex</strong>. Each part of the grid chain is a flex-box element. The final, <code>v-flex</code>, automatically sets its children to have <kbd>flex: 1 1 auto</kbd>."},{header:"Offset",file:"grid/offset",desc:"Offsets are useful for compensating for elements that may not be visible yet, or to control the position of content. Just as with breakpoints, you can set an offset for any available sizes. This allows you to fine tune your application layout precisely to your needs."},{header:"Order",file:"grid/order",desc:"You can control the ordering of grid items. As with offsets, you can set different orders for different sizes. Design specialized screen layouts that accommodate to any application."},{header:"Direction and Align",file:"grid/direction-and-align",desc:"Designate the direction and alignment in a variety of ways. All of the available <kbd>flex-box</kbd> api is available through intuitive helper props."},{header:"Row and column based on breakpoint",file:"grid/row-column-breakpoint",desc:"Dynamically change your layout based upon resolution. <strong>(resize your screen and watch the layout change to a <code>row</code> on small breakpoints)</strong>"},{header:"Nested grid",file:"grid/nested-grid",desc:"Grids can be nested, similar to other frameworks, in order to achieve very custom layouts."},{header:"Unique layouts",file:"grid/unique-layouts",desc:"The power and flexibility of the Vuetify grid system allows you to create amazing user interfaces."},{header:"Specific tags",file:"grid/tags",desc:"Sometimes you will want to specify a layout item as a specific tag, such as a <code>section</code> or <code>li</code> element.",new:"0.16.5"}],props:{"v-container":{params:[["fluid","Boolean","False","Removes viewport size breakpoints"],["grid-list-{xs through xl}","Boolean","False","Sets the gutter between grid list items ranging from 1px to 24px"]]},"v-flex":{params:[["xs(1-12)","Boolean","False","xs:extra small, sm:small, md:medium, lg:large, xl:extra large - 1 through 12"],["offset-[size](0-12)","Boolean","False","offset-xs:extra small, offset-sm:small, offset-md:medium, offset-lg:large, offset-xl:extra large. Example: offset-xs3"],["order-[size](1-12)","Boolean","False","order-xs:extra small, order-sm:small, order-md:medium, order-lg:large, order-xl:extra large. Example: order-xs1"]]},"v-container/v-layout/v-flex":{params:[["tag","String","div","Specify the html tag that is rendered."],["id","String","-","Sets the id for the html tag that is rendered"],["reverse","Boolean","False","Reverses the currently selected direction (column, row)."],["justify-space-around","Boolean","False","Justify content to the space around."],["justify-space-between","Boolean","False","Justify content to the space between."],["justify-center","Boolean","False","Justify content to the center.."],["justify-start","Boolean","False","Space between child elements."],["justify-end","Boolean","False","Space between child elements."],["align-center","Boolean","False","Align items to the center."],["align-baseline","Boolean","False","Align items to the baseline."],["align-start","Boolean","False","Align items to the start."],["align-end","Boolean","False","Align items to the end."],["align-content-start","Boolean","False","Align content to the start."],["align-content-end","Boolean","False","Align content to the end."],["align-content-center","Boolean","False","Align content to the center."],["align-content-space-around","Boolean","False","Align content to the space around."],["align-content-space-between","Boolean","False","Align content to the space between."],["wrap","Boolean","False","Allows children to wrap within the container if the elements use more than 100%."],["fill-height","Boolean","False","Make sure that col element height is filled with parent and child. Important for Safari/Firefox if children is column element."],["display-helpers","Boolean","False","Specify to display an element as flex/inline-flex/block etc. Syntax is <code>d-{display-type}</code>. For example <code>d-flex</code>."]]}},slots:{"v-container":{shared:["default"]},"v-layout":{shared:["default"]},"v-flex":{shared:["default"]}},functional:{grid:{params:[["v-spacer","Spacer for flexbox grids"]]}}}}}}},1450:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement,a=e._self._c||t;return a("component-view",{attrs:{doc:e.doc}},[a("v-alert",{attrs:{slot:"top",color:"info",icon:"info",value:"true"},slot:"top"},[e._v("If you are looking for "),a("strong",[e._v("Grid lists")]),e._v(", please navigate "),a("router-link",{staticClass:"white--text",attrs:{to:"/components/grid-lists"}},[e._v("here")]),e._v(".")],1),a("grid",{staticClass:"mt-5",attrs:{slot:"top"},slot:"top"}),a("v-alert",{staticClass:"mb-4",attrs:{color:"info",icon:"info",value:"value"}},[e._v("Vuetify breakpoint functionality requires the use of the "),a("code",[e._v("v-app")]),e._v(" component.")]),a("section-header",[e._v("Breakpoint object")]),a("section-text",[e._v("Vuetify converts the available breakpoints into an accessible object from within your application. This will allow you to assign/apply specific properties and attributes based upon viewport size. The object can be accessed from:")]),a("markup",{attrs:{lang:"js"}},[e._v("export default {\n mounted () {\n console.log(this.$vuetify.breakpoint)\n },\n computed: {\n imageHeight () {\n switch (this.$vuetify.breakpoint.name) {\n case 'xs': return '220px'\n case 'sm': return '400px'\n case 'md': return '500px'\n case 'lg': return '600px'\n case 'xl': return '800px'\n }\n }\n }\n}")]),a("section-text",[e._v("This object contains the same semantic properties that you are already used to using from the grid system. Let's try a real world example. You have a "),a("code",[e._v("v-dialog")]),e._v(" component that you want to convert to a "),a("strong",[e._v("full-screen")]),e._v(" dialog on mobile devices. Normally you would need to bind watchers for the viewport size, and/or check whenever the page loads.")]),a("markup",{attrs:{lang:"js"}},[e._v("export default {\n data: () => ({\n isMobile: false\n }),\n mounted () {\n this.onResize()\n window.addEventListener('resize', this.onResize, { passive: true })\n },\n beforeDestroy () {\n if (typeof window !== 'undefined') {\n window.removeEventListener('resize', this.onResize, { passive: true })\n }\n },\n methods: {\n onResize () {\n this.isMobile = window.innerWidth < 600\n }\n }\n}")]),a("section-text",[e._v("That's a lot of boilerplate to write. Even if you opt to use the built in "),a("router-link",{attrs:{to:"/directives/resizing"}},[e._v("v-resize")]),e._v(" directive, you are still going to have to define a resize method. With the "),a("strong",[e._v("breakpoint")]),e._v(" object you can completely skip this logic and get back to building your application.")],1),a("markup",{attrs:{lang:"html"}},[e._v('<v-dialog :fullscreen="$vuetify.breakpoint.xsOnly">\n ...\n</v-dialog>')])],1)},s=[],i={render:o,staticRenderFns:s};t.a=i},1451:function(e,t,a){"use strict";t.a={data:function(){return{sponsors:[{title:"LMAX Exchange",href:"https://careers.lmax.com/?utm_source=vuetify&utm_medium=logo-link&utm_campaign=lmax-careers",src:"/doc-images/backers/lmax-exchange.png"},{title:"intygrate",href:"http://intygrate.com/?ref=vuetifyjs.com",src:"/doc-images/backers/intygrate.png"},{title:"BrowserStack",href:"https://www.browserstack.com/",src:"/doc-images/browser-stack.svg"},{title:"Cloudflare",href:"https://www.cloudflare.com/",src:"/doc-images/cloudflare.svg"}],toolbar:!1}},methods:{onScroll:function(){this.toolbar=window.scrollY>300}}}},1452:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement,a=e._self._c||t;return a("div",{directives:[{name:"scroll",rawName:"v-scroll",value:e.onScroll,expression:"onScroll"}],attrs:{id:"home-view"}},[a("v-toolbar",{staticClass:"white text-xs-center",class:[e.toolbar?"toolbar--home":"hidden"],attrs:{fixed:"fixed",app:"app"}},[a("img",{attrs:{src:"/doc-images/header-logo.svg",height:"38px"}}),a("v-spacer"),a("v-toolbar-items",[a("v-btn",{staticClass:"subheading",attrs:{flat:"flat",to:"/vuetify/quick-start"}},[e._v("Documentation")]),a("v-btn",{staticClass:"hidden-xs-only subheading",attrs:{flat:"flat",href:"https://chat.vuetifyjs.com",target:"_blank",rel:"noopener"}},[e._v("Community")]),a("v-btn",{staticClass:"hidden-xs-only subheading",attrs:{flat:"flat",href:"https://github.com/vuetifyjs/vuetify/releases",target:"_blank",rel:"noopener"}},[e._v("Updates")])],1)],1),a("section",{attrs:{id:"hero"}},[a("v-container",{attrs:{"grid-list-xl":"grid-list-xl"}},[a("v-layout",{attrs:{row:"row",wrap:"wrap"}},[a("v-flex",{staticClass:"text-xs-center",attrs:{xs12:"xs12",md4:"md4"}},[a("img",{staticClass:"logo",attrs:{src:"/doc-images/logo.svg"}})]),a("v-flex",{staticClass:"text-xs-center text-md-left",attrs:{xs12:"xs12",md8:"md8"}},[a("v-layout",{class:{"justify-center":e.$vuetify.breakpoint.smAndDown},attrs:{row:"row",wrap:"wrap"}},[a("v-flex",{staticClass:"py-1",attrs:{xs12:"xs12"}},[a("h1",{staticClass:"mb-0"},[e._v("Vuetify")])]),a("v-flex",{staticClass:"py-1",attrs:{xs12:"xs12"}},[a("h2",[e._v("Material Component Framework")])]),a("v-flex",{attrs:{xs12:"xs12",sm8:"sm8",md6:"md6",lg4:"lg4"}},[a("v-btn",{attrs:{block:"block",dark:"dark",color:"blue",large:"large",to:"/vuetify/quick-start"}},[a("span",[e._v("Documentation")])])],1),a("v-flex",{attrs:{xs12:"xs12",sm8:"sm8",md6:"md6",lg4:"lg4"}},[a("v-btn",{staticClass:"primary--text",attrs:{large:"large",block:"block",color:"white",tag:"a",href:"https://github.com/vuetifyjs/vuetify",target:"_blank",rel:"noopener"}},[a("v-icon",{staticClass:"primary--text",attrs:{left:"left"}},[e._v("fa-github")]),a("span",[e._v("Github")])],1)],1)],1)],1)],1)],1)],1),a("section",{staticClass:"text-xs-center",attrs:{id:"new-release"}},[a("v-card",{attrs:{tile:"tile",flat:"flat",color:"primary",dark:"dark"}},[a("v-card-text",[a("span",{staticClass:"subheading"},[e._v("New Vuetify Shop is now live!")]),a("v-btn",{staticClass:"primary--text ml-4",attrs:{color:"white",light:"light",href:"https://next.vuetifyjs.com/en/store",target:"_blank",large:"large"}},[e._v("Take me there!")])],1)],1)],1),a("div",{attrs:{id:"section-body"}},[a("section",{staticClass:"mb-3",attrs:{id:"features"}},[a("v-container",{attrs:{"grid-list-md":"grid-list-md"}},[a("v-card",{staticClass:"elevation-2"},[a("v-card-text",{staticClass:"py-5"},[a("v-layout",{attrs:{row:"row",wrap:"wrap"}},[a("v-flex",{staticClass:"text-xs-center my-3",attrs:{xs12:"xs12",md4:"md4"}},[a("img",{attrs:{src:"/doc-images/feature1.svg"}}),a("h3",{staticClass:"mt-4 mb-3"},[e._v("Vue-CLI Templates")]),a("p",[e._v("Vuetify comes ready to go with 8 pre-made vue-cli templates. From simple html to full-blown SSR, you are ready to go in minutes.")])]),a("v-flex",{staticClass:"text-xs-center my-3",attrs:{xs12:"xs12",md4:"md4"}},[a("img",{attrs:{src:"/doc-images/feature2.svg"}}),a("h3",{staticClass:"mt-4 mb-3"},[e._v("Custom Layouts")]),a("p",[e._v("Each and every available layout from the Material design spec is at your disposal. Create unique and flexible user interfaces that fit the scope of any project.")])]),a("v-flex",{staticClass:"text-xs-center my-3",attrs:{xs12:"xs12",md4:"md4"}},[a("img",{attrs:{src:"/doc-images/feature3.svg"}}),a("h3",{staticClass:"mt-4 mb-3"},[e._v("Semantic Material Components")]),a("p",[e._v("Be prepared for an armada of specialized components at your disposal. With over 80 in total, there is a solution for any application.")])])],1)],1)],1)],1)],1),a("section",{staticClass:"mb-3",attrs:{id:"sponsors"}},[a("v-container",{attrs:{"grid-list-md":"grid-list-md"}},[a("v-card",{staticClass:"elevation-2"},[a("v-card-text",{staticClass:"py-5"},[a("h2",{staticClass:"mb-5 text-xs-center"},[e._v("Proudly sponsored by:")]),a("v-layout",{attrs:{row:"row",wrap:"wrap","align-center":"align-center","justify-center":"justify-center"}},[e._l(e.sponsors,function(e,t){return a("v-flex",{key:t,staticClass:"text-xs-center",attrs:{xs12:"xs12",md3:"md3"}},[a("a",{attrs:{href:e.href,target:"_blank",title:e.title,rel:"noopener"}},[a("img",{staticClass:"sponsor",attrs:{src:e.src}})])])}),a("v-flex",{staticClass:"text-xs-center",attrs:{xs12:"xs12"}},[a("v-btn",{staticClass:"primary--text",attrs:{to:"/vuetify/sponsors-and-backers",large:"large",color:"white"}},[e._v("Become a backer"),a("v-icon",{attrs:{right:"right"}},[e._v("fa-arrow-circle-right")])],1)],1)],2)],1)],1)],1)],1),a("section",{staticClass:"mb-3",attrs:{id:"support"}},[a("v-container",{attrs:{"grid-list-md":"grid-list-md"}},[a("v-card",{staticClass:"elevation-2"},[a("v-card-text",{staticClass:"py-5"},[a("v-layout",{staticClass:"text-xs-center",attrs:{row:"row",wrap:"wrap"}},[a("v-flex",{staticClass:"mb-5",attrs:{xs12:"xs12"}},[a("h2",[e._v("Has Vuetify helped you create an amazing application?"),a("br"),a("br",{staticClass:"hidden-md-and-up"}),e._v(" You can show your support by backing the project on Patreon or Paypal:")])]),a("v-flex",{attrs:{xs12:"xs12",sm3:"sm3","offset-sm3":"offset-sm3"}},[a("a",{attrs:{href:"https://www.patreon.com/vuetify",target:"_blank",rel:"noopener"}},[a("div",{staticClass:"display-1 my-3 primary--text"},[e._v("Patreon")]),a("img",{attrs:{src:"/doc-images/patreon.png",width:"125px"}})])]),a("v-flex",{attrs:{xs12:"xs12",sm3:"sm3"}},[a("a",{attrs:{href:"https://paypal.me/vuetify",target:"_blank",rel:"noopener"}},[a("div",{staticClass:"display-1 my-3 primary--text"},[e._v("PayPal")]),a("img",{attrs:{src:"/doc-images/paypal.png",width:"125px"}})])])],1)],1)],1)],1)],1),a("section",{staticClass:"mb-0",attrs:{id:"footer-hero"}},[a("v-container",[a("v-layout",{attrs:{row:"row",wrap:"wrap"}},[a("v-flex",{attrs:{xs12:"xs12",md8:"md8",lg10:"lg10"}},[a("img",{attrs:{src:"/doc-images/logo.svg",height:"90px"}}),a("h2",{staticClass:"mt-4 mb-5"},[e._v("Supercharge Your Development with the Power of Vue and Material Design")])])],1)],1)],1)]),a("footer",[a("v-layout",{attrs:{row:"row",wrap:"wrap"}},[a("v-flex",{staticClass:"vuetify",attrs:{xs6:"xs6",sm3:"sm3"}},[a("h5",[a("img",{attrs:{src:"/doc-images/logo.svg"}}),a("span",[e._v("Vuetify")])]),a("ul",[a("li",[a("a",{attrs:{href:"https://vuetifyjs.com/vuetify/quick-start"}},[a("span",{staticClass:"hidden-sm-only"},[e._v("Documentation")]),a("span",{staticClass:"hidden-md-and-up hidden-xs-only"},[e._v("Docs")])])]),a("li",[a("a",{attrs:{href:"https://github.com/vuetifyjs/vuetify",target:"_blank"}},[a("v-icon",{staticClass:"hidden-sm-only",attrs:{dark:""}},[e._v("fa-github")]),e._v(" GitHub")],1)]),a("li",[a("a",{attrs:{href:"https://twitter.com/vuetifyjs",target:"_blank"}},[a("v-icon",{staticClass:"hidden-sm-only",attrs:{dark:""}},[e._v("fa-twitter")]),e._v(" Twitter")],1)]),a("li",[a("a",{attrs:{href:"https://www.facebook.com/vuetifyjs",target:"_blank"}},[a("v-icon",{staticClass:"hidden-sm-only",attrs:{dark:""}},[e._v("fa-facebook")]),e._v(" Facebook")],1)])])]),a("v-flex",{attrs:{xs6:"xs6",sm3:"sm3"}},[a("h5",[e._v("Donate")]),a("ul",[a("li",[a("a",{attrs:{href:"https://www.patreon.com/vuetify",target:"_blank"}},[e._v("Patreon")])]),a("li",[a("a",{attrs:{href:"https://www.paypal.me/vuetify",target:"_blank"}},[e._v("PayPal")])])])]),a("v-flex",{attrs:{xs6:"xs6",sm3:"sm3"}},[a("h5",[e._v("Sponsors")]),a("ul",[a("li",[a("a",{attrs:{href:"https://www.browserstack.com/",target:"_blank"}},[e._v("BrowserStack")])]),a("li",[a("a",{attrs:{href:"https://www.cloudflare.com/",target:"_blank"}},[e._v("CloudFlare")])])])]),a("v-flex",{attrs:{xs6:"xs6",sm3:"sm3"}},[a("h5",[e._v("Links")]),a("ul",[a("li",[a("a",{attrs:{href:"https://vuejs.org/",target:"_blank"}},[e._v("Vue.js")])]),a("li",[a("a",{attrs:{href:"https://material.io/guidelines/",target:"_blank"}},[e._v("Material Design")])])])])],1),a("div",{staticClass:"legal-footer text-xs-center"},[a("span",[e._v("© "+e._s((new Date).getFullYear())+" Vuetify LLC. Distributed under the")]),a("a",{staticClass:"accent--text",attrs:{href:"https://opensource.org/licenses/MIT",target:"_blank"}},[e._v(" MIT License.")])])],1)],1)},s=[],i={render:o,staticRenderFns:s};t.a=i},1453:function(e,t,a){"use strict";t.a={data:function(){return{doc:{title:"Icons",component:"VIcon",edit:"IconView",desc:'The <code>v-icon</code> component provides a large set of glyphs to provide context to various aspects of your application. Vuetify icons utilize Google\'s Material Icons font library. For a list of all available icons, visit the official <a href="https://material.io/icons/" target="_blank" rel="noopener">Material Icons</a> page.',examples:[{header:"Standard",file:"icons/standard",desc:"Icons come in two themes (light and dark), and four different sizes (standard, medium, large, and x-large)."},{header:"Font Awesome",file:"icons/font-awesome",desc:'<a href="http://fontawesome.io/icons/">Font Awesome</a> is also supported. Simply use the <code>fa-</code> prefixed icon name. Please note that you still need to include the Font Awesome icons in your project.'},{header:"Material Design Icons",file:"icons/mdi",desc:'<a href="https://materialdesignicons.com/">Material Design Icons</a> is also supported. Simply use the <code>mdi-</code> prefixed icon name. Please note that you still need to include the MDI icons in your project.'},{header:"Color",file:"icons/color",desc:"Using color helpers you can change the color of an icon from the standard dark and light themes."},{header:"Buttons",file:"icons/buttons",desc:"Icons can be used inside of buttons to add emphasis to the action."}],props:{"v-icon":{shared:["colorable","theme"],params:[["disabled","Boolean","False","Disables the icon, fading the color"],["medium","Boolean","False","Medium size"],["large","Boolean","False","Large size"],["x-large","Boolean","False","Extra-Large size"],["left","Boolean","False","Places icon on the left, when used inside a button"],["right","Boolean","False","Places icon on the right, when used inside a button"],["light","Boolean","False","Applies the light theme (default dark)"]]}}}}}}},1454:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement,a=e._self._c||t;return a("component-view",{attrs:{doc:e.doc}},[a("v-alert",{attrs:{color:"warning",icon:"priority_high",value:"value"}},[a("span",[e._v("Custom font libraries such as Icomoon can overwrite the "),a("code",[e._v("icon-")]),e._v(" class and cause issues. While other icon packages can work, the only official support is for Material Icons, FontAwesome, and Material Design Icons.")])])],1)},s=[],i={render:o,staticRenderFns:s};t.a=i},1455:function(e,t,a){var o=a(1456);"string"==typeof o&&(o=[[e.i,o,""]]),o.locals&&(e.exports=o.locals);a(198)("714520f0",o,!0)},1456:function(e,t,a){t=e.exports=a(197)(void 0),t.push([e.i,"#layouts-view .component-example{position:relative;z-index:0}#layouts-view .component-example [data-app]{border:1px solid rgba(0,0,0,.1);overflow:hidden}#layouts-view .component-example [data-app] .navigation-drawer,#layouts-view .component-example [data-app] .overlay,#layouts-view .component-example [data-app] .toolbar:not(.elevation-0){position:absolute}#layouts-view .component-example [data-app] main .container{min-height:364px!important}#layouts-view .component-example [data-app] .footer{height:36px}",""])},1457:function(e,t,a){"use strict";t.a={data:function(){return{doc:{title:"Layouts",edit:"LayoutsView",component:"app",desc:"The layout system is the heart of every application. Below are the officially supported examples, ranging from desktop to mobile applications. While Vuetify.js aims to be as un-opinionated as possible, the layout structure must be <strong>explicitly</strong> followed to receive the expected results.",examples:[],props:{"v-app":{shared:["theme"],params:[["id","String","app","The id for your application"]]},"v-content":{}},slots:{"v-app":{shared:["default"]}},functional:{"v-app":{params:[["v-spacer","Spacer for flexbox grids"]]}}},layouts:[{name:"Baseline",href:"/examples/layouts/baseline"},{name:"Baseline Flipped",href:"/examples/layouts/baseline-flipped"},{name:"Complex",href:"/examples/layouts/complex"},{name:"Dark",href:"/examples/layouts/dark",dark:!0},{name:"Google Contacts",href:"/examples/layouts/google-contacts"},{name:"Google Keep",href:"/examples/layouts/google-keep"},{name:"Google Youtube",href:"/examples/layouts/google-youtube",dark:!0}]}},methods:{genSrc:function(e){return"'/doc-images/layouts/"+e.toLowerCase().replace(" ","-")+".png'"}}}},1458:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement,a=e._self._c||t;return a("component-view",{attrs:{doc:e.doc}},[a("div",{attrs:{slot:"top"},slot:"top"},[a("section",[a("h2",{staticClass:"display-1"},[e._v("Default application markup")]),a("section-text",[e._v("This is an example of the default application markup for Vuetify. You can place your layout elements anywhere, as long as you designate them with the "),a("strong",[e._v("app")]),e._v(" property. The key component in all of this is the "),a("code",[e._v("v-content")]),e._v(" element. This will be dynamically sized depending upon the structure of your designated "),a("strong",[e._v("app")]),e._v(" components. This allows you to create extremely customized solutions.")]),a("markup",{attrs:{lang:"html",xs12:"xs12",sm6:"sm6"}},[e._v("<v-app>\n <v-navigation-drawer app></v-navigation-drawer>\n <v-toolbar app></v-toolbar>\n <v-content>\n <v-container fluid>\n <router-view></router-view>\n </v-container>\n </v-content>\n <v-footer app></v-footer>\n</v-app>")]),a("markup",{attrs:{lang:"html",xs12:"xs12",sm6:"sm6"}},[e._v("<v-app>\n <v-navigation-drawer app></v-navigation-drawer>\n <v-toolbar app></v-toolbar>\n <v-content>\n <router-view>\n <v-container fluid></v-container>\n </router-view>\n </v-content>\n <v-footer app></v-footer>\n</v-app>")]),a("v-alert",{attrs:{color:"error",icon:"warning",value:"true"}},[e._v("In order for your application to work properly, you "),a("strong",[e._v("must")]),e._v(" wrap it in a "),a("code",[e._v("v-app")]),e._v(" component. This component is required for determining grid breakpoints for the layout. This can exist "),a("strong",[e._v("anywhere")]),e._v(" inside the body, but must be the parent of "),a("strong",[e._v("ALL")]),e._v(" Vuetify components.")])],1)]),a("section",{attrs:{id:"layouts"}},[a("v-container",{staticClass:"pa-0",attrs:{fluid:"fluid","grid-list-xl":"grid-list-xl"}},[a("v-layout",{attrs:{row:"row",wrap:"wrap"}},e._l(e.layouts,function(t){return a("v-flex",{key:t.name,attrs:{xs12:"xs12",sm4:"sm4"}},[a("v-card",{attrs:{hover:"hover",href:t.href,target:"_blank",rel:"noopener"}},[a("v-card-media",{attrs:{height:"300px",src:e.genSrc(t.name)}},[a("v-layout",{attrs:{"align-center":"align-center"}},[a("v-flex",{staticClass:"text-xs-center"},[a("div",{staticClass:"title",class:[t.dark?"white--text":""]},[e._v(e._s(t.name))])])],1)],1)],1)],1)}))],1)],1)])},s=[],i={render:o,staticRenderFns:s};t.a=i},1459:function(e,t,a){var o=a(1460);"string"==typeof o&&(o=[[e.i,o,""]]),o.locals&&(e.exports=o.locals);a(198)("6b5e3c56",o,!0)},1460:function(e,t,a){t=e.exports=a(197)(void 0),t.push([e.i,"#lists-view .component-example{position:relative;z-index:1}#lists-view .component-example .card{max-width:400px;margin:1rem auto}#lists-view .component-example .card .toolbar{height:auto;min-height:55px}",""])},1461:function(e,t,a){"use strict";t.a={name:"lists-view",data:function(){return{doc:{title:"List",component:"VList",edit:"ListsView",desc:"The <code>v-list</code> component is used to display information. It can contain an avatar, content, actions, subheaders and much more. Lists can contain children and are used in the sidebar.",examples:[{header:"Avatar with 2 lines",file:"lists/avatar-two-lines",desc:"Lists can take an array of list items. When given an array, the list component will figure out the classes that are needed depending on what it was given. You can also define headers or dividers within the items array."},{header:"Avatar with title and action",file:"lists/avatar-title-and-action",desc:"Lists also contain slots for a more explicit approach. If you choose this approach, remember you must provide additional props for correct spacing. In this example, we have a tile with an avatar, so we must provide an <code>avatar</code> property."},{header:"Icon with 2 lines and action",file:"lists/icon-two-lines-and-action",desc:"Lists can contain subheaders, dividers, and can contain 1 or more lines. The subtitle will overflow with ellipsis if it extends past one line."},{header:"Avatar with 3 lines",file:"lists/avatar-three-lines",desc:'For three line lists, the subtitle will clamp vertically at 2 lines and then ellipsis. If you need more than 3 lines, it is advised to use a <router-link to="/components/cards">card</router-link>.'},{header:"Avatar with title and action",file:"lists/avatar-subheader-title-and-action",desc:"When a lists slot is used, you must manually define whether it contains headers, or if the items contain an avatar. This is required to maintain proper spacing."},{header:"Subheadings and dividers",file:"lists/subheadings-and-dividers",desc:"Lists can contain multiple subheaders and dividers."},{header:"Card image with toolbar and list",file:"lists/card-list",desc:"A list can be combined with a card."},{header:"Title with sub-title, actions and action-text",file:"lists/title-subtitle-actions-and-action-text",desc:"A list can contain a stack within an action. Ripple and router props can be passed through the main v-list, to the v-list-tile or as a property in the items array."},{header:"Action with title and sub-title",file:"lists/action-with-title-and-subtitle",desc:"A list can contain up to 3 lines."},{header:"Expansion Lists",file:"lists/expansion-lists",desc:"A list can contain a group of items which will display on click. Expansion lists are also used within the <code>navigation drawer</code> component."},{header:"Dark scheme",file:"lists/dark",desc:"A list can assume the alternate scheme color of dark."}],props:{"v-list":{shared:["theme"],params:[["dense","Boolean","False","Lowers max height of list tiles"],["subheader","Boolean","False","Removes top padding. Used when previous sibling is a header"],["two-line","Boolean","False","Increases list-tile height for two lines"],["three-line","Boolean","False","Increases list-tile height for three lines"]]},"v-list-tile":{shared:["router"],params:[["inactive","Boolean","False","If set, the list tile will not be rendered as a link even if it has to/href prop or @click handler"],["avatar","Boolean","False","Used to set minimum tile height on a single-line list item"]],model:{type:["Boolean"],default:"False",description:"Toggles the list tile active state"}},"v-list-group":{params:[["group","String","False","Assign a route namespace"],["no-action","Boolean","False","Removes left padding assigned for action icons from group items"],["lazy","Boolean","False","Conditionally renders content on mounted"]],model:{type:["Boolean"],default:"False",description:"Expands / Collapse list group"}}},functional:{"v-list":{params:[["v-list-tile-action","list__tile__action--stack"],["v-list-tile-action-text","list__tile__action-text"],["v-list-tile-avatar","list__tile__avatar"],["v-list-tile-content","list__tile__content"],["v-list-tile-title","list__tile__title"],["v-list-tile-sub-title","list__tile__sub-title"]]}},slots:{"v-list":{shared:["default"]},"v-list-tile":{shared:["default"]},"v-list-tile-content":{shared:["default"]},"v-list-tile-title":{shared:["default"]},"v-list-tile-sub-title":{shared:["default"]},"v-list-tile-action":{shared:["default"]},"v-list-tile-action-text":{shared:["default"]},"v-list-tile-avatar":{shared:["default"]},"v-subheader":{shared:["default"]}}}}}}},1462:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement,a=e._self._c||t;return a("component-view",{attrs:{doc:e.doc}},[a("blockquote",[e._v("The three-line prop uses "),a("code",[e._v("-webkit-line-clamp")]),e._v(" which is not supported on all browsers. If not supported, the line will just continue to wrap.")])])},s=[],i={render:o,staticRenderFns:s};t.a=i},1463:function(e,t,a){"use strict";t.a={data:function(){return{doc:{title:"Menu",component:"VMenu",edit:"MenusView",desc:"The <code>v-menu</code> component shows a menu at the position of the element used to activate it.",examples:[{header:"Activator",file:"menus/activator",desc:"Remember to put the element that activates the menu in the <code>activator</code> slot."},{header:"Absolute position",file:"menus/absolute",desc:"Menus can also be placed absolutely on top of the activator element using the <code>absolute</code> prop. Try clicking anywhere on the image."},{header:"Absolute position without activator",file:"menus/absolute-without-activator",desc:"Menus can also be used without an activator by using <code>absolute</code> together with the props <code>position-x</code> and <code>position-y</code>. Try right-clicking anywhere on the image."},{header:"Hover",file:"menus/hover",desc:"Menus can be accessed using hover instead of clicking with the <code>open-on-hover</code> prop."},{header:"Menus",file:"menus/menus",desc:"Menus can be placed within almost any component."},{header:"Custom transitions",file:"menus/custom-transition",desc:'Vuetify comes with 3 standard transitions, <strong>scale</strong>, <strong>slide-x</strong> and <strong>slide-y</strong>. You can also create your own and pass it as the transition argument. For an example of how the stock transitions are constructed, visit <a href="https://github.com/vuetifyjs/vuetify/blob/master/src/util/helpers.js#L13" target="_blank" rel="noopener">here</a>.'},{header:"Popover menu",file:"menus/popover",desc:"A menu can be configured to be static when opened, allowing it to function as a popover. This can be useful when there are multiple interactive items within the menu contents."}],props:{"v-menu":{shared:["menu","delayable","lazy"],model:{type:["Boolean"],default:"False"},params:[["absolute","Boolean","False","Position the menu absolutely, useful for context menus"],["fixed","Boolean","False",""],["auto","Boolean","false",""],["full-width","Boolean","False","Changes the menu display to block, useful for filling available width in forms"],["offset-x","Boolean","False","Offset the menu on the x-axis. Works in conjunction with direction left/right"],["offset-y","Boolean","False","Offset the menu on the y-axis. Works in conjunction with direction top/bottom"],["disabled","Boolean","False","Disables the menu"],["max-height","[Number, String]","auto","The maximum height of the menu, will overflow-y with scroll if content is too large"],["open-on-hover","Boolean","False","Designates whether menu should open on activator hover"],["open-on-click","Boolean","True","Designates whether menu should open on activator click"],["close-on-click","Boolean","True","Designates if menu should close on outside-activator click"],["close-on-content-click","Boolean","True","Designates if menu should close when its content is clicked"],["origin","String","top left","Set the transform-origin of the transition"],["transition","String","v-menu-transition","Set the transition component"],["z-index","[Number, String]","6","Specify the z-index of the menu, useful when stacking multiple layers of components such as <code>v-dialog</code> with an inner <code>v-menu</code>"]]}},slots:{"v-menu":{shared:["default"],params:[["activator","The element that will activate the menu"]]}}}}}}},1464:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement;return(e._self._c||t)("component-view",{attrs:{doc:e.doc,id:"menus-view"}})},s=[],i={render:o,staticRenderFns:s};t.a=i},1465:function(e,t,a){var o=a(1466);"string"==typeof o&&(o=[[e.i,o,""]]),o.locals&&(e.exports=o.locals);a(198)("352cad88",o,!0)},1466:function(e,t,a){t=e.exports=a(197)(void 0),t.push([e.i,"#navigation-drawer-view .component-example .card__text{overflow:hidden}#navigation-drawer-view .navigation-drawer{-webkit-box-shadow:0 2px 4px -1px rgba(0,0,0,.2),0 4px 5px 0 rgba(0,0,0,.14),0 1px 10px 0 rgba(0,0,0,.12);box-shadow:0 2px 4px -1px rgba(0,0,0,.2),0 4px 5px 0 rgba(0,0,0,.14),0 1px 10px 0 rgba(0,0,0,.12);position:relative;z-index:0}#navigation-drawer-view .overlay{z-index:0}#navigation-drawer-view #example-8 .icon{color:#fff!important}",""])},1467:function(e,t,a){"use strict";t.a={data:function(){return{doc:{title:"Navigation drawer",edit:"NavigationDrawerView",component:"VNavigationDrawer",desc:"\nThe <code>v-navigation-drawer</code> component is what your users will utilize to navigate through the application.\nThe navigation-drawer is pre-configured to work with or without <strong>vue-router</strong> right out the box.\n<br>\nFor most application-level drawers, you will want to use either <code>absolute</code> or <code>fixed</code> to get the correct positioning.",examples:[{header:"Default",file:"navigation-drawers/permanent",desc:"The navigation drawer is primarily used to house links to the pages in your application"},{header:"Colored drawer",file:"navigation-drawers/permanent-clipped",desc:"Navigation drawers can be customized to fit any application's design. While any component can be used within a drawer, the primary ones you will use are <code>v-list</code>, all of the <strong>list</strong> children components and <code>v-divider</code>"},{header:"Permanent floating drawer",file:"navigation-drawers/permanent-floating",desc:"A navigation drawer can be placed inside of a card and float over the content background."},{header:"Avatars",file:"navigation-drawers/persistent",desc:"Since drawers support the <code>v-list</code> component, you can easily create customized dashboard solutions."},{header:"Mini",file:"navigation-drawers/mini",desc:"The navigation drawer also has a mini-variant which can be controlled using the prop <code>mini-variant.sync</code>."},{header:"Temporary",file:"navigation-drawers/temporary",desc:"A temporary drawer sits above its application and uses a scrim (overlay) to darken the background. This drawer behavior is mimicked on the persistent drawer when on mobile. Clicking outside of the drawer will cause it to close."},{header:"Dark theme",file:"navigation-drawers/dark",desc:"Vuetify also supports the dark application theme. This will not override components that have default themes so in some cases it will be necessary to manually set the dark theme accents."}],props:{"v-navigation-drawer":{shared:["app","theme","overlay"],model:{type:["Boolean"],default:"True"},params:[["absolute","Boolean","False","Sets the navigation drawer position to absolute"],["fixed","Boolean","False","Sets the navigation drawer position to fixed"],["clipped","Boolean","False","A clipped drawer rests under the application toolbar"],["disable-route-watcher","Boolean","False","Disables opening of navigation drawer when route changes"],["disable-resize-watcher","Boolean","False","Will automatically open/close drawer when resized depending if mobile or desktop."],["height","String","100%","Sets height of the navigation drawer"],["floating","Boolean","False","A floating drawer has no visible container (no border-right)"],["mini-variant","Boolean","False","Condenses navigation drawer width, also accepts the <strong>.sync</strong> modifier. With this, the drawer will re-open when clicking it"],["mini-variant-width","[Number, String]","80","Designates the width assigned when the <code>mini</code> prop is turned on"],["mobile-break-point","[Number, String]","1264","Designates the window width for the drawer to become mobile"],["permanent","Boolean","False","The drawer remains visible regardless of screen size"],["stateless","Boolean","False","Remove all automated state functionality (resize, mobile, route) and manually control the drawer state"],["right","Boolean","False","Places the navigation drawer on the right"],["temporary","Boolean","False","A temporary drawer sits above its application and uses a scrim (overlay) to darken the background"],["touchless","Boolean","False","Disable mobile touch functionality"],["width","[Number, String]","300","The width of the drawer."]]}},slots:{"v-navigation-drawer":{shared:["default"]}}}}}}},1468:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement;return(e._self._c||t)("component-view",{attrs:{doc:e.doc}})},s=[],i={render:o,staticRenderFns:s};t.a=i},1469:function(e,t,a){"use strict";t.a={name:"pagination-view",data:function(){return{doc:{component:"VPagination",edit:"PaginationView",title:"Pagination",desc:"The <code>v-pagination</code> component is used to separate long sets of data so that it is easier for a user to consume information. Depending on the length provided, the pagination component will automatically scale. To maintain the current page, simply supply a v-model attribute.",examples:[{header:"Short",file:"pagination/short",desc:"Pagination displays all pages if parent container is big enough."},{header:"Long",file:"pagination/long",desc:"When the number of page buttons exceeds the parent container, the component will truncate the list."},{header:"Limit",file:"pagination/limit",desc:"You can also manually set the maximum number of visible page buttons with the <code>total-visible</code> prop."},{header:"Round",file:"pagination/round",desc:"The alternate style for pagination is circle pages."},{header:"Disabled",file:"pagination/disabled",desc:"Pagination items can be manually deactivated."}],props:{"v-pagination":{shared:["colorable"],params:[["circle","Boolean","False","Shape pagination elements as circles"],["disabled","Boolean","False","Disables component"],["length","Number","0","The length of the paginator"],["total-visible","[Number, String]","null","Specify the max total visible pagination numbers"],["next-icon","String","chevron_right","Specify the icon to use for the next icon"],["prev-icon","String","chevron_left","Specify the icon to use for the prev icon"]],model:{type:"Number",description:"Current selected page"}}},events:{"v-pagination":{params:[["input","Number","Current page"],["next","-","Emits when the next button is clicked"],["previous","-","Emits when the previous button is clicked"]]}}}}}}},1470:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement;return(e._self._c||t)("component-view",{attrs:{doc:e.doc}})},s=[],i={render:o,staticRenderFns:s};t.a=i},1471:function(e,t,a){var o=a(1472);"string"==typeof o&&(o=[[e.i,o,""]]),o.locals&&(e.exports=o.locals);a(198)("36ff8150",o,!0)},1472:function(e,t,a){t=e.exports=a(197)(void 0),t.push([e.i,"",""])},1473:function(e,t,a){"use strict";t.a={name:"parallax-view",data:function(){return{doc:{component:"VParallax",edit:"ParallaxView",title:"Parallax",desc:"The <code>v-parallax</code> component creates a 3d effect that makes an image appear to scroll slower than the window.",examples:[{header:"Default",file:"parallax/default",desc:"A parallax causes a shift in a background image when the user scrolls the page."},{header:"With content",file:"parallax/content",desc:"You can also place any content inside of the parallax. This allows you to use the parallax as a hero image."},{header:"Custom height",file:"parallax/custom-height",desc:"You can specify a custom height on a parallax. Keep in mind this can break the parallax if your image is not sized properly"},{header:"Jumbotron",file:"parallax/jumbotron",new:"0.15.3",desc:"The parallax can have its effect disabled to be used as a standard <strong>jumbotron</strong>"}],props:{"v-parallax":{params:[["alt","String","null","Attaches an alt property to the parallax image"],["jumbotron","Boolean","False","Removes parallax effect"],["height","Number","500","The height of the parallax container"],["src","String","Required","The image to parallax"]]}}}}}}},1474:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement;return(e._self._c||t)("component-view",{attrs:{doc:e.doc}})},s=[],i={render:o,staticRenderFns:s};t.a=i},1475:function(e,t,a){var o=a(1476);"string"==typeof o&&(o=[[e.i,o,""]]),o.locals&&(e.exports=o.locals);a(198)("3c5dfbcc",o,!0)},1476:function(e,t,a){t=e.exports=a(197)(void 0),t.push([e.i,"#pickers-view{min-height:150vh}#pickers-view .component-example .col{margin:1rem auto}",""])},1477:function(e,t,a){"use strict";t.a={data:function(){return{doc:{component:"",edit:"PickersView",title:"Pickers",desc:"The <code>v-date-picker</code> and <code>v-time-picker</code> are stand-alone components that can be utilized in many existing Vuetify components. They offer the user a visual representation for selecting date and time.",examples:[{header:"Date pickers - Light",file:"pickers/date-light",desc:"Date pickers come in two orientation variations, portrait <strong>(default)</strong> and landscape."},{header:"Date pickers - Dark",file:"pickers/date-dark",desc:"Date pickers come in a dark variant which utilizes the applications primary accent color."},{header:"Date pickers - Colors",file:"pickers/date-colorable",desc:"Date picker colors can be set using the <code>color</code> and <code>header-color</code> props. If <code>header-color</code> prop is not provided header will use the <code>color</code> prop value."},{header:"Date pickers - In dialog and menu",file:"pickers/date-dialog-and-menu",desc:"<p>When integrating a picker into a <code>v-text-field</code>, it is recommended to use the <strong>readonly</strong> prop. This will prevent mobile keyboards from triggering. To save vertical space, you can also hide the picker title.</p><p>Pickers expose a scoped slot that allow you to hook into save and cancel functionality. This will maintain an old value which can be replaced if the user cancels.</p>"},{header:"Date pickers - Formatting date",file:"pickers/date-formatting",desc:"<p>You can use your own formatting function if you want to display the date in the different format than ISO 8601</p>"},{header:"Date pickers - Allowed dates",file:"pickers/date-allowed-dates",desc:"You can specify allowed dates using arrays, objects, and functions."},{header:"Date pickers - Internationalization",file:"pickers/date-internationalization",desc:"The date picker supports internationalization through the JavaScript Date object. Specify a BCP 47 language tag using the <code>locale</code> prop, and then set the first day of the week with the <code>first-day-of-week</code> prop."},{header:"Month pickers - Light",file:"pickers/month-light",desc:"Month pickers come in two orientation variations, portrait <strong>(default)</strong> and landscape."},{header:"Month pickers - Dark",file:"pickers/month-dark",desc:"Month pickers come in a dark variant which utilizes the applications primary accent color."},{header:"Month pickers - Colors",file:"pickers/month-colorable",desc:"Month picker colors can be set using the <code>color</code> and <code>header-color</code> props. If <code>header-color</code> prop is not provided header will use the <code>color</code> prop value."},{header:"Month pickers - In dialog and menu",file:"pickers/month-dialog-and-menu",desc:"<p>When integrating a picker into a <code>v-text-field</code>, it is recommended to use the <strong>readonly</strong> prop. This will prevent mobile keyboards from triggering. To save vertical space, you can also hide the picker title.</p><p>Pickers expose a scoped slot that allow you to hook into save and cancel functionality. This will maintain an old value which can be replaced if the user cancels.</p>"},{header:"Month pickers - Allowed months",file:"pickers/month-allowed-months",desc:"You can specify allowed months using arrays, objects, and functions."},{header:"Month pickers - Internationalization",file:"pickers/month-internationalization",desc:"The month picker supports internationalization through the JavaScript Date object. Specify a BCP 47 language tag using the <code>locale</code> prop, and then set the first day of the week with the <code>first-day-of-week</code> prop."},{header:"Time pickers - Light",file:"pickers/time-light",desc:"Time pickers have the light theme enabled by default."},{header:"Time pickers - Dark",file:"pickers/time-dark",desc:"An alternate dark theme can be used for dark theme applications."},{header:"Date pickers - Colors",file:"pickers/time-colorable",desc:"Time picker colors can be set using the <code>color</code> and <code>header-color</code> props. If <code>header-color</code> prop is not provided header will use the <code>color</code> prop value."},{header:"Time pickers - In dialog and menu",file:"pickers/time-dialog-and-menu",desc:"Due to the flexibility of pickers, you can really dial in the experience exactly how you want it."},{header:"Time pickers - 24h format",file:"pickers/time-24h-format",desc:"A time picker can be switched to 24hr format."},{header:"Time pickers - Allowed times",file:"pickers/time-allowed-times",desc:"You can specify allowed times using arrays, objects, and functions."}],props:{"v-date-picker":{shared:["theme","colorable"],model:{type:["String"],default:"null",description:"Controls the displayed date. Must use ISO 8601 format."},params:[["type","String","date","Determines the type of the picker - <code>'date'</code> for date picker, <code>'month'</code> for month picker"],["header-color","String","-","Defines the header color. If not specified it will use the color defined by <code>color</code> prop or the default picker color"],["actions","Boolean","True","Use this when using actions inside the picker"],["autosave","Boolean","True","Automatically save the selected value. This updates the internal previous value so if cancel is clicked, it will not revert the user changes"],["landscape","Boolean","True","Orients picker horizontal"],["no-title","Boolean","True","Hide the picker title"],["month-format","Function","Date::toLocaleDateString(locale, { month: 'short' })","Formatting function used for displaying months in the months table. Called with date (ISO 8601 string) and locale (string) arguments."],["scrollable","Boolean","False","Allows the use of the mousewheel in the picker"],["allowed-dates","Array, Object, Function","null","Restricts which dates can be selected"],["locale","String","en-US","Sets the locale. Accepts a string with a BCP 47 language tag."],["first-day-of-week","[Number, String]","0","Sets the first day of the week, starting with 0 for Sunday."],["title-date-format","Function","Date::toLocaleDateString(locale, { weekday: 'short', month: 'short', day: 'numeric' })","Allows you to customize the format of the date string that appears in the title of the date picker. Called with date (ISO 8601 string) and locale (string) arguments."],["header-date-format","Function","Date::loLocaleDateString(locale, { month: 'long', year: 'numeric' })","Allows you to customize the format of the month string that appears in the header of the calendar. Called with date (ISO 8601 string) and locale (string) arguments."],["year-format","Function","Date::loLocaleDateString(locale, { year: 'numeric' })","Allows you to customize the format of the year string that appears in the header of the calendar. Called with date (ISO 8601 string) and locale (string) arguments."],["day-format","Function","Date::loLocaleDateString(locale, { day: 'numeric' })","Allows you to customize the format of the day string that appears in the date table. Called with date (ISO 8601 string) and locale (string) arguments."],["year-icon","String","''","Generates an icon next to the year"]]},"v-time-picker":{shared:["theme","colorable"],model:{type:["String"],default:"null",description:"Controls the displayed time."},params:[["actions","Boolean","True","Use this when using actions inside the picker"],["header-color","String","-","Defines the header color. If not specified it will use the color defined by <code>color</code> prop or the default picker color"],["autosave","Boolean","True","Automatically save the selected value. This updates the internal previous value so if cancel is clicked, it will not revert the user changes"],["landscape","Boolean","True","Orients picker horizontal"],["no-title","Boolean","True","Hide the picker title"],["format","String","ampm","Available options are ['ampm', '24hr']"],["scrollable","Boolean","False","Allows the use of the mousewheel in the picker"],["allowed-hours","Array, Object, Function","null","Restricts which hours can be selected"],["allowed-minutes","Array, Object, Function","null","Restricts which minutes can be selected"]]}}}}}}},1478:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement,a=e._self._c||t;return a("component-view",{attrs:{doc:e.doc}},[a("v-alert",{staticClass:"mb-5",attrs:{slot:"top",color:"info",icon:"info",value:"true"},slot:"top"},[e._v("Date/Time pickers store internally the current value of your model and only change once saved. This can be accomplished by using the "),a("code",[e._v("actions")]),e._v(" prop in conjunction with a scopedSlot to define your buttons, or by using the "),a("code",[e._v("autosave")]),e._v(" prop.")])],1)},s=[],i={render:o,staticRenderFns:s};t.a=i},1479:function(e,t,a){"use strict";t.a={data:function(){return{templates:[{screenshot:"/doc-images/starter/vuetify-premium.jpg",title:"Startup",tag:"PREMIUM",description:"Showcase your Company or personal portfolio with this beautifully hand-crafted Material design template.",price:"25$",demoUrl:""},{screenshot:"/doc-images/starter/vuetify-parallax-starter.png",title:"Parallax",description:"This beautiful single page parallax is a great home page for any application.",sourceUrl:"vuetifyjs/parallax-starter",demoUrl:"/themes/parallax-starter"},{screenshot:"/doc-images/starter/vuetify-blog-starter.png",title:"Blog",description:"A simple template that features a clean interface for creating a blog or blog-like application.",sourceUrl:"vuetifyjs/blog-starter",demoUrl:"/themes/blog-starter"}]}}}},1480:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement,a=e._self._c||t;return a("doc-view",{attrs:{id:"themes-view"}},[a("section-def",[a("dt",{attrs:{slot:"title"},slot:"title"},[e._v("Free and Premium themes")]),a("dd",{attrs:{slot:"desc"},slot:"desc"},[e._v("Vuetify offers Free and Premium pre-made themes designed to get you started in a flash. Free themes are available to install through vue-cli or you can simply download the source.")])]),a("v-container",{attrs:{fluid:"fluid","grid-list-xl":"grid-list-xl"}},[a("v-layout",{attrs:{row:"row",wrap:"wrap"}},e._l(e.templates,function(t){return a("v-flex",{key:t.title,attrs:{xs12:"xs12",sm6:"sm6"}},[a("v-card",{attrs:{height:"100%"}},[a("v-card-media",{attrs:{src:t.screenshot,height:"350px"}}),a("v-card-title",{staticClass:"align-center"},[a("h2",{staticClass:"headline mb-0"},[e._v(e._s(t.title)),t.tag?a("v-chip",{attrs:{label:"label",small:"small",color:"indigo","text-color":"white"}},[e._v(e._s(t.tag))]):a("v-chip",{attrs:{label:"label",small:"small",color:"blue-grey","text-color":"white"}},[e._v("FREE")])],1),a("v-spacer"),t.buy?a("v-avatar",{staticClass:"green lighten-2"},[a("span",{staticClass:"white--text title"},[e._v("25$")])]):e._e()],1),a("v-divider"),a("v-card-text",[e._v(e._s(t.description))]),a("v-card-actions",[t.price?e._e():a("v-btn",{attrs:{flat:"flat",color:"success",href:t.demoUrl,target:"_blank",rel:"noopener"}},[e._v("Demo")]),a("v-spacer"),t.price?a("v-btn",{attrs:{flat:"flat",href:"javascript:;",disabled:"disabled"}},[e._v("Coming Soon")]):a("v-btn",{attrs:{flat:"flat",color:"success",href:"https://github.com/"+t.sourceUrl+"/tree/master/template",target:"_blank",rel:"noopener"}},[e._v("Source Code"),a("v-icon",{attrs:{right:"right",success:"success"}},[e._v("chevron_right")])],1)],1)],1)],1)}))],1)],1)},s=[],i={render:o,staticRenderFns:s};t.a=i},1481:function(e,t,a){"use strict";t.a={data:function(){return{doc:{component:"",edit:"ProgressView",title:"Progress",desc:"The <code>v-progress-circular</code> and <code>v-progress-linear</code> components are used to convey data visually to users. They can also represent an indeterminate amount, such as loading or processing. These components contains a slot that is centered within the component container.",examples:[{header:"Default",file:"progress-circular/default",desc:"By default, progress circular uses the applications secondary color."},{header:"Colored",file:"progress-circular/colored",desc:"Alternate colors can be applied."},{header:"Indeterminate",file:"progress-circular/indeterminate",desc:"An indeterminate progress circular animates forever."},{header:"Size & Width",file:"progress-circular/size-and-width",desc:"The progress circular component can have an altered width and size."},{header:"Rotate",file:"progress-circular/rotate",desc:"The progress origin can be rotated."},{header:"Determinate",file:"progress-linear/determinate",desc:"The progress linear component can have a determinate state modified by v-model."},{header:"Indeterminate",file:"progress-linear/indeterminate",desc:"Just as with the progress circular component, progress linear has an indeterminate state."},{header:"Buffer",file:"progress-linear/buffer",desc:"A buffer state represents two values simultaneously. The primary value is controlled by the model, whereas the buffer is controlled by the <code>buffer-value</code> prop."},{header:"Query Indeterminate and Determinate",file:"progress-linear/query-indeterminate-and-determinate",desc:"To query state is controlled by the truthiness of indeterminate with the query prop set to true."},{header:"Custom height and contextual colors",file:"progress-linear/custom-height-and-contextual-colors",desc:"A custom height or contextual color can be applied to a progress bar. The bars primary color is your applications primary color."},{header:"Custom colors",file:"progress-linear/custom-colors",desc:"You can also set the color using the props <code>color</code> and <code>background-color</code>."}],props:{"v-progress-circular":{shared:["colorable"],params:[["fill","String","[indeterminate ? 'none' : 'transparent']","Sets the fill color of the circle"],["indeterminate","Boolean","False","Never stops rotating. Use when loading progress is unknown."],["rotate","Number","0","Rotates the circle start point in deg"],["size","Number","32","Sets the diameter of the circle in pixels"],["width","Number","4","Sets the stroke of the circle in pixels"]],model:{type:["Number"],default:"0",description:"The percentage value for current progress"}},"v-progress-linear":{shared:["colorable"],params:[["background-color","String","null","Background color, set to component's color if null"],["background-opacity","[Number, String]","null","Background opacity, if null it defaults to 0.3 if background color is not specified or 1 otherwise"],["buffer-value","Number","None","The percentage value for the buffer"],["height","number","7","The height of the progress bar"],["indeterminate","Boolean","False","Sets the indeterminate state of the component. Use when loading progress is unknown"],["active","Boolean","True","When disabled, the component will shrink up"],["query","Boolean","False","Sets the query state of the component"]],model:{type:["Number"],default:"0",description:"The percentage value for current progress"}}},slots:{"v-progress-circular":{default:!0}}}}}}},1482:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement;return(e._self._c||t)("component-view",{attrs:{doc:e.doc}})},s=[],i={render:o,staticRenderFns:s};t.a=i},1483:function(e,t,a){"use strict";t.a={data:function(){return{browsers:[{icon:"internet-explorer",title:"IE9 / IE10",supported:!1},{icon:"internet-explorer",title:"IE11",supported:"Supported w/ polyfill"},{icon:"edge",title:"Edge",supported:!0},{icon:"chrome",title:"Chrome",supported:!0},{icon:"firefox",title:"Firefox",supported:!0},{icon:"safari",title:"Safari 9+",supported:!0}],copied:!1,copyTimeout:null,templates:[{icon:"landscape",title:"Simple HTML",init:"simple",desc:"This template is intended for users who want to try out Vue.js and Vuetify.js in the most simplistic way. It contains a basic index.html with no additional functionality. This is useful for developers who want to easily preview the features of the framework."},{icon:"web",title:"Webpack Simple",init:"webpack-simple",desc:"This template is intended for users who are already familiar with Vue/Webpack. It contains a very simple webpack setup and is targetted at developers creating prototype or basic applications."},{icon:"layers",title:"Webpack",init:"webpack",desc:"This template is intended for users who are looking for out of the box linting and unit testing."},{icon:"cloud_circle",title:"Webpack SSR",init:"webpack-ssr",desc:'This template is for advanced users looking to utilize the new Vue SSR (server-side rendering). Based off of the structure in the Vue.js 2 <a class="white--text" href="https://github.com/vuejs/vue-hackernews-2.0" target="_blank" rel="noopener">Hackernews</a> repository. The Vuetify.js SSR template provides next generation functionality for advanced Vue applications.'},{icon:"flash_on",title:"NUXT",init:"nuxt",desc:"Utilizing the power of NUXT, supercharge your development experience with a bootstraped version ready to go with Vuetify out of the box."},{icon:"featured_video",title:"PWA",init:"pwa",desc:"A pre-configured PWA (Progressive Web Application) template is at your disposal. Bootstraped with service workers, application manifest, and a 90+/100 Lighthouse score."},{icon:"power",title:"Electron",init:"electron",desc:"Vuetify's official Electron template for creating desktop applications."},{icon:"call_split",title:"A La Carte",init:"a-la-carte",desc:"In this template you can see an example of how to select only the components you want to use. This is useful for reducing package size with unused components."}],selectedIndex:0}},computed:{copy:function(){return"vue init vuetifyjs/"+this.selectedTemplate.init},selectedText:function(){return this.selectedTemplate.desc},selectedTemplate:function(){return this.templates[this.selectedIndex]}},watch:{copied:function(e){!e&&clearTimeout(this.copyTimeout)}},methods:{copyMarkup:function(){var e=this;clearTimeout(this.copyTimeout),this.$refs.copy.select(),document.execCommand("copy"),this.copied=!0,this.copyTimeout=setTimeout(function(){return e.copied=!1},2e3)}}}},1484:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement,a=e._self._c||t;return a("doc-view",{attrs:{id:"quick-start-view"}},[a("v-layout",{attrs:{row:"row",wrap:"wrap"}},[a("v-flex",{attrs:{xs12:"xs12",sm8:"sm8",xl12:"xl12"}},[a("section-def",[a("dt",{attrs:{slot:"title"},slot:"title"},[e._v("Getting Started")]),a("dd",{attrs:{slot:"desc"},slot:"desc"},[e._v("Use one of the Vuetify.js Vue CLI packages "),a("em",[e._v("(based on the official examples)")]),e._v(" to get your project started in no time. Vuetify.js supports "),a("strong",[e._v("SSR")]),e._v(" (server-side rendering), "),a("strong",[e._v("SPA")]),e._v(" (single page application), "),a("strong",[e._v("PWA")]),e._v(" (progressive web application) and standard "),a("strong",[e._v("HTML")]),e._v(" pages.")])])],1),a("ad")],1),a("v-alert",{staticClass:"mb-4",attrs:{color:"error",icon:"warning",value:"value"}},[e._v("In order for your application to work properly, you "),a("strong",[e._v("must")]),e._v(" wrap it in a "),a("code",[e._v("v-app")]),e._v(" component. This component is used for dynamically managing your content area and is the mounting point for many components.")]),a("v-alert",{staticClass:"mb-4",attrs:{color:"info",icon:"local_offer",value:"value"}},[a("div",[e._v("The new "),a("strong",[e._v("Vuetify Store")]),e._v(" is now live "),a("v-btn",{staticClass:"primary--text",attrs:{color:"white",href:"https://next.vuetifyjs.com/store",target:"_blank"}},[e._v("Check it out! "),a("v-icon",[e._v("chevron_right")])],1)],1)]),a("section",{attrs:{id:"cdn-install"}},[a("section-header",[e._v("CDN Install")]),a("section-text",[e._v("To test using Vuetify.js without installing a template from Vue CLI, copy the code below into your "),a("code",[e._v("index.html")]),e._v(". This will pull the latest version of Vue and Vuetify, allowing you to start playing with components. You can also use the "),a("a",{attrs:{href:"https://template.vuetifyjs.com",target:"_blank"}},[e._v("Vuetify starter")]),e._v(" on codepen.")]),a("markup",{attrs:{lang:"html"}},[e._v('<!DOCTYPE html>\n<html>\n<head>\n <link href=\'https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons\' rel="stylesheet">\n <link href="https://unpkg.com/vuetify/dist/vuetify.min.css" rel="stylesheet">\n <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">\n</head>\n<body>\n <div id="app">\n <v-app>\n <v-content>\n <v-container>Hello world</v-container>\n </v-content>\n </v-app>\n </div>\n \n <script src="https://unpkg.com/vue/dist/vue.js"><\/script>\n <script src="https://unpkg.com/vuetify/dist/vuetify.js"><\/script>\n <script>\n new Vue({ el: \'#app\' })\n <\/script>\n</body>\n</html>')])],1),a("section",{attrs:{id:"new-applications"}},[a("section-header",[e._v("New applications")]),a("section-text",[e._v("Vuetify has 8 pre-made Vue CLI templates, 3 which are forked from "),a("a",{attrs:{href:"https://github.com/vuejs-templates",target:"_blank",rel:"noopener"}},[e._v("official Vue.js templates")]),e._v(". They contain small modifications to help you get started with Vuetify even faster. These packages require "),a("code",[e._v("vue-cli")]),e._v(". For more information on vue-cli, visit the official "),a("a",{attrs:{href:"https://github.com/vuejs/vue-cli",target:"_blank",rel:"noopener"}},[e._v("Github")]),e._v(" repository. These templates are designed to get you started as fast as possible with your next project")]),a("div",{staticClass:"elevation-2"},[a("v-layout",{attrs:{wrap:"wrap"}},[a("input",{ref:"copy",style:{position:"absolute",left:"-1000px",top:"-1000px"},domProps:{value:e.copy}}),e._l(e.templates,function(t,o){return a("v-flex",{key:o,attrs:{xs12:"xs12",sm4:"sm4",md3:"md3"}},[a("div",{staticStyle:{display:"none"},domProps:{innerHTML:e._s(t.desc)}}),a("v-list",{staticClass:"pa-0",attrs:{"two-line":"two-line"}},[a("v-list-tile",{attrs:{href:"javascript:;",value:e.selectedIndex===o},on:{click:function(t){e.selectedIndex=o}}},[a("v-list-tile-action",[a("v-icon",{class:[e.selectedIndex===o?"primary--text":""],domProps:{innerHTML:e._s(t.icon)}})],1),a("v-list-tile-content",[a("v-list-tile-title",{domProps:{textContent:e._s(t.title)}}),a("v-list-tile-sub-title",[e._v("vue init vuetifyjs/"+e._s(t.init))])],1)],1)],1)],1)})],2),a("v-expansion-panel",{staticClass:"elevation-0"},[a("v-expansion-panel-content",{attrs:{value:"value"}},[a("v-card",{staticClass:"blue darken-3 hide-overflow",staticStyle:{"min-height":"75px"},attrs:{tile:"tile",flat:"flat",dark:"dark"}},[a("v-fade-transition",{attrs:{mode:"out-in"}},[a("v-layout",{key:e.selectedIndex,attrs:{row:"row","justify-space-between":"justify-space-between"}},[a("v-flex",{staticClass:"layout align-center",attrs:{xs10:"xs10"}},[a("v-card-text",{domProps:{innerHTML:e._s(e.selectedTemplate.desc)}}),a("v-snackbar",{attrs:{absolute:"absolute",top:"top",left:"left"},model:{value:e.copied,callback:function(t){e.copied=t},expression:"copied"}},[e._v("Init copied!"),a("v-btn",{attrs:{flat:"flat",color:"light-blue"},on:{click:function(t){e.copied=!e.copied}}},[e._v("close")])],1)],1),a("v-flex",{staticClass:"layout column align-end pa-3",attrs:{xs2:"xs2"}},[a("v-tooltip",{attrs:{left:"left",debounce:"300"}},[a("v-btn",{attrs:{slot:"activator",icon:"icon",dark:"dark",color:"secondary",href:"https://github.com/vuetifyjs/"+e.selectedTemplate.init,target:"_blank",rel:"noopener"},slot:"activator"},[a("v-icon",{attrs:{dark:"dark"}},[e._v("fa-github")])],1),a("span",[e._v("Github")])],1),a("v-tooltip",{attrs:{left:"left",debounce:"300"}},[a("v-btn",{attrs:{slot:"activator",icon:"icon",color:"secondary",dark:"dark"},on:{click:e.copyMarkup},slot:"activator"},[a("v-icon",{attrs:{dark:"dark"}},[e._v("content_copy")])],1),a("span",[e._v("Copy markup")])],1)],1)],1)],1)],1)],1)],1)],1)],1),a("section",{attrs:{id:"existing-applications"}},[a("section-header",[e._v("Existing applications")]),a("section-text",[e._v("To include Vuetify into an existing project, you must pull it into your node_modules. You can use either "),a("code",[e._v("npm")]),e._v(" or "),a("code",[e._v("yarn")]),e._v(" to accomplish this task. These are both package managers that allow you to control what resources are available to your application.")]),a("section-text",[e._v("For a detailed explanation of how to get "),a("code",[e._v("npm")]),e._v(" running in your environment, check out the "),a("a",{attrs:{href:"https://docs.npmjs.com/getting-started/what-is-npm",target:"_blank",rel:"noopener"}},[e._v("official documentation")]),e._v(". Alternatively, if you wish to use yarn, you can find the official documentation "),a("a",{attrs:{href:"https://yarnpkg.com/lang/en/docs/",target:"_blank",rel:"noopener"}},[e._v("here")]),e._v(". Once setup, you can run either command from your command prompt.")]),a("markup",{attrs:{lang:"cli"}},[e._v("$ npm install vuetify\n# or\n$ yarn add vuetify")]),a("section-text",[e._v("Once Vuetify has been installed, navigate to your applications main entry point. In most cases this will be "),a("code",[e._v("index.js")]),e._v(" or "),a("code",[e._v("main.js")]),e._v(". In this file you will import Vuetify and tell Vue to use it.")]),a("markup",{attrs:{lang:"js"}},[e._v("import Vue from 'vue'\nimport Vuetify from 'vuetify'\n \nVue.use(Vuetify)")]),a("section-text",[e._v("You will also need to include the Vuetify css file. Simply include the Vuetify css file in your "),a("code",[e._v("index.html")]),e._v(" or import the actual stylus file or the minified css.")]),a("markup",{attrs:{lang:"js"}},[e._v("// index.js or main.js\nimport('path/to/node_modules/vuetify/dist/vuetify.min.css') // Ensure you are using css-loader")]),a("markup",{attrs:{lang:"stylus"}},[e._v("// main.styl\n@import 'path/to/node_modules/vuetify/src/stylus/main.styl' // Ensure you are using stylus-loader\n ")]),a("section-text",[e._v("The easiest way to include the Material Design icons is to add a "),a("code",[e._v("link")]),e._v(" tag to your "),a("code",[e._v("index.html")]),e._v(" file.")]),a("markup",{attrs:{lang:"html"}},[e._v("<head>\n <link href='https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons' rel=\"stylesheet\">\n</head>")]),a("v-alert",{attrs:{color:"error",icon:"warning",value:"value"}},[e._v("Warning: While Vuetify attempts to not cause any css collision as much as possible, there is no guarantee that your custom styles will not alter your experience when integrating this framework into your existing project.")])],1),a("section",[a("section-header",[e._v("Support Browsers")]),a("section-text",[e._v("Vuetify.js is a progressive framework that attempts to push web development to the next level. In order to best accomplish this task, some sacrifices had to be made in terms of support for older versions of Internet Explorer.")]),a("v-list",{staticClass:"transparent"},[a("v-layout",{attrs:{row:"row",wrap:"wrap"}},e._l(e.browsers,function(t){return a("v-flex",{key:t.title,staticClass:"px-0",attrs:{xs12:"xs12",sm6:"sm6",md4:"md4"}},[a("v-list-tile",{attrs:{avatar:"avatar",tag:"ul"}},[a("v-list-tile-avatar",[a("v-icon",{staticClass:"primary",attrs:{dark:"dark"}},[e._v("fa-"+e._s(t.icon))])],1),a("v-list-tile-content",[a("v-list-tile-title",[e._v(e._s(t.title))]),a("v-list-tile-sub-title",[e._v(e._s(!0===t.supported?"Supported":!1===t.supported?"Not supported":t.supported))])],1),a("v-list-tile-action",[t.supported?a("v-icon",{staticClass:"success--text"},[e._v("check")]):a("v-icon",{staticClass:"error--text"},[e._v("clear")])],1)],1)],1)}))],1)],1),a("section",[a("section-header",[e._v("Internet Explorer 11 Support")]),a("section-text",[e._v("To use Vuetify.js with Internet Explorer, you must include a polyfill in your project. Vuetify.js can work with either "),a("a",{attrs:{href:"https://polyfill.io/v2/docs/",target:"_blank",rel:"noopener"}},[e._v("polyfill.io")]),e._v(" or "),a("a",{attrs:{href:"https://babeljs.io/docs/usage/polyfill/#installation",target:"_blank",rel:"noopener"}},[e._v("babel-polyfill")]),e._v(". The polyfill must be loaded before your project source code. Other polyfills may be needed to use specific features in your project. "),a("strong",[e._v("Keep in mind")]),e._v(", the CDN versions of these polyfills do not always include everything by default. It is recommended that you pull the package into your project locally and import it there.")]),a("section-text",[e._v("Due to Internet Explorer's limited support for "),a("code",[e._v("<template>")]),e._v(" tags, you must take care to send fully compiled dom elements to the browser. This can be done by either building your Vue code in advance or by creating helper components to replace the dom elements. For instance, if sent directly to IE, this will fail:")]),a("markup",{attrs:{lang:"html"}},[e._v('<template slot="items" slot-scope="props">\n <td>{{ props.item.name }}</td>\n</template>')]),a("section-text",[e._v("Using a custom component, in this example "),a("code",[e._v("<cell>")]),e._v(", we could use this markup:")]),a("markup",{attrs:{lang:"html"}},[e._v("\x3c!--Example component declaration--\x3e\nVue.component('cell', { template: '<td><slot></slot></td>' });\n \n\x3c!--Example scoped slot--\x3e\n<template slot=\"items\" slot-scope=\"props\">\n <cell>{{ props.item.name }}</cell>\n</template>")]),a("v-alert",{attrs:{value:"value",color:"warning",icon:"priority_high"}},[e._v("If you still find yourself struggling with IE11, come get help from the Vuetify "),a("a",{staticClass:"white--text",attrs:{href:"https://chat.vuetifyjs.com",target:"_blank",rel:"noopener"}},[e._v("community")]),e._v(".")])],1)],1)},s=[],i={render:o,staticRenderFns:s};t.a=i},1485:function(e,t,a){"use strict";t.a={data:function(){return{doc:{title:"Resize directive",edit:"Resize",directive:"resize",desc:"The <code>v-resize</code> directive can be used for calling specific functions when the window resizes.",props:{"v-resize":{params:[["value","Function","Required","Function to be called on window resize"]]}},examples:[{header:"Default",file:"resize/default",desc:"Resize your window and observe the values change."}]}}}}},1486:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement;return(e._self._c||t)("component-view",{attrs:{doc:e.doc}})},s=[],i={render:o,staticRenderFns:s};t.a=i},1487:function(e,t,a){"use strict";t.a={data:function(){return{doc:{title:"Ripples",desc:"The <code>v-ripple</code> directive is used to show action from a user. It can be applied to any block level element. Numerous components come with the ripple directive built in, such as the <code>v-btn</code>, <code>v-tab-item</code> and many more.",examples:[{header:"Buttons",file:"ripples/buttons",desc:'Buttons by default have ripples enabled. This can be removed with the prop <code>:ripple="false"</code>.'},{header:"Custom color",file:"ripples/custom-color",desc:"Using a helper class, you can change the color of the ripple."},{header:"Tabs",file:"ripples/tabs",desc:"Tabs by default have ripples disabled. This can be enabled with the <code>ripple</code> prop."},{header:"Navigation drawers",file:"ripples/navigation-drawers",desc:"List items by default have ripples disabled. This can be enabled with the <code>ripple</code> prop."},{header:"Toolbars",file:"ripples/toolbars",desc:"Toolbar items by default have ripples disabled. This can be enabled with the <code>ripple</code> prop."},{header:"Expansion panels",file:"ripples/expansion-panels",desc:"Expansion panels by default have ripples disabled. This can be enabled with the <code>ripple</code> prop."},{header:"Standard HTML element",file:"ripples/html-element",desc:"Add the ripple effect to a standard HTML element. This can be enabled with the <code>v-ripple</code> HTML attribute."}],props:{"v-ripple":{params:[["{ class: 'class' }","Property","","Applies a custom class to the ripple, useful for changing color"]]}}}}}}},1488:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement;return(e._self._c||t)("component-view",{attrs:{doc:e.doc}})},s=[],i={render:o,staticRenderFns:s};t.a=i},1489:function(e,t,a){"use strict";t.a={data:function(){return{cards:[{ver:"Alpha theme",sem:"THEME",rel:"January, 2018",icon:"mdi-brush",highlights:["Hand crafted pre-made Material Design theme","Theme specific components","more info coming soon..."]},{ver:"Front-end pack",sem:"COMPONENT PACK",rel:"April, 2018",icon:"mdi-package-variant-closed",highlights:["10+ new components:","File upload","Timeline","Star rating","Testimonial","Gallery","and more..."]},{ver:"Back-end pack",sem:"COMPONENT PACK",rel:"June, 2018",icon:"mdi-package-variant-closed",highlights:["10+ new components:","Report card","Charts (Chart.js integration)","and more..."]}],releases:[{ver:"v1.0.0",sem:"MAJOR RELEASE",rel:"December, 2017",icon:"cake",highlights:["New documentation","Dynamic themes","RTL & i18n support","CSS collision improvements","more to come..."]},{ver:"v1.1.0",sem:"MINOR RELEASE",rel:"February, 2018",icon:"mdi-alert-circle",highlights:["Form components refactor","more to come..."]}]}}}},1490:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement,a=e._self._c||t;return a("doc-view",{attrs:{id:"roadmap-view"}},[a("v-layout",{attrs:{row:"row",wrap:"wrap"}},[a("v-flex",{attrs:{xs12:"xs12",sm8:"sm8",xl12:"xl12"}},[a("section-def",[a("dt",{attrs:{slot:"title"},slot:"title"},[e._v("Roadmap")]),a("dd",{attrs:{slot:"desc"},slot:"desc"},[e._v("Vuetify is always under development, working to improve the existing codebase, as well as add new features and functionality that help make building applications even easier. Below is a tentative list of planned features. This is "),a("em",[e._v("not")]),e._v(" an exhaustive list and may change at any time without notice.")])])],1),a("ad")],1),a("section",{attrs:{id:"roadmap"}},[a("v-container",{staticClass:"px-0",attrs:{"grid-list-xl":"grid-list-xl",fluid:"fluid"}},[a("v-layout",{attrs:{wrap:"wrap"}},e._l([e.releases,e.cards],function(t,o){return a("v-flex",{key:o,attrs:{xs12:"xs12",md6:"md6"}},[a("v-layout",{attrs:{wrap:"wrap"}},e._l(t,function(t,o){return a("v-flex",{key:o,attrs:{xs12:"xs12","d-flex":"d-flex"}},[a("v-card",{attrs:{flat:"flat",tile:"tile"}},[a("v-toolbar",{attrs:{dark:"dark",prominent:"prominent",flat:"flat",color:"secondary"}},[a("v-list",{staticClass:"pa-0",attrs:{dark:"dark"}},[a("v-list-tile",{attrs:{avatar:"avatar"}},[a("v-list-tile-content",[a("v-list-tile-title",[a("strong",{staticClass:"title"},[e._v(e._s(t.ver))])]),a("v-list-tile-sub-title",[e._v(e._s(t.rel))])],1)],1)],1),a("v-spacer"),a("span",[e._v(e._s(t.sem))]),a("v-icon",{staticClass:"ml-3 blue--text text--lighten-2",attrs:{dark:"dark"}},[e._v(e._s(t.icon))])],1),a("v-card-text",[a("v-subheader",[e._v("Highlights")]),a("v-divider"),a("v-list",{attrs:{dense:"dense"}},e._l(t.highlights,function(t,o){return a("v-list-tile",{key:o,attrs:{inset:"inset"}},[a("v-list-tile-action",[a("v-icon",{staticClass:"mr-3 secondary--text",staticStyle:{"font-size":"10px","margin-left":"auto"}},[e._v("mdi-circle")])],1),a("v-list-tile-title",[e._v(e._s(t))])],1)}))],1)],1)],1)}))],1)}))],1)],1)],1)},s=[],i={render:o,staticRenderFns:s};t.a=i},1491:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement,a=e._self._c||t;return a("div",{staticClass:"view"},[a("v-layout",{attrs:{row:"row"}},[a("v-flex",{attrs:{xs12:"xs12",sm8:"sm8",md12:"md12"}},[a("section-def",[a("dt",{attrs:{slot:"title"},slot:"title"},[e._v("Overview")]),a("dd",{attrs:{slot:"desc"},slot:"desc"},[a("p",[e._v("This overview is designed to help you become fluent in "),a("strong",[e._v("Vuetify's")]),e._v(" Vue SSR Template. If you have not already installed the "),a("code",[e._v("webpack-ssr")]),e._v(" template, please do so "),a("router-link",{attrs:{to:"/vuetify/quick-start"}},[e._v("in the Quick start")]),e._v(".")],1)])])],1),a("ad")],1),a("section",[a("section-header",[e._v("Introduction")]),a("section-text",[e._v("This Vue CLI template was designed for performance, seo optimization and usability. This template is configured out of the box for css, sass and stylus pre-processors.")]),a("h6",[e._v("Folder Structure")]),a("markup",{attrs:{lang:"cli"}},[e._v("/ project\n / assets\n / build\n / components\n / mixins\n / pages\n / router\n / static\n / store")]),a("section-text",[a("p",[e._v("The "),a("strong",[e._v("Build")]),e._v(" folder contains all of the webpack specific build configurations for your project. "),a("strong",[e._v("Src")]),e._v(" is where all the development project files reside. Notice that the Webpack-SSR template is out-of-the-box configured to use "),a("a",{attrs:{href:"https://router.vuejs.org/en/",target:"_blank",rel:"noopener"}},[e._v("Vue Router")]),e._v(", "),a("a",{attrs:{href:"https://vuex.vuejs.org/en/intro.html",target:"_blank",rel:"noopener"}},[e._v("Vuex")]),e._v(", and the "),a("a",{attrs:{href:"https://vuejs.org/v2/guide/ssr.html",target:"_blank",rel:"noopener"}},[e._v("Vue Server Renderer")]),e._v(". This will allow you to make simple or complex applications that are not only fast/efficient, but "),a("strong",[e._v("SEO")]),e._v(" friendly.")])]),a("section-header",[e._v("Application")]),a("section-text",[e._v("Navigate to the "),a("strong",[e._v("src")]),e._v(" folder and open up "),a("code",[e._v("App.vue")]),e._v(". Vuetify is a semantic-focused framework. The code you write should be easy to remember, and easy to manage. To do this, one of the main components of Vuetify is "),a("code",[e._v("v-app")]),e._v(". This component allows you to define your application layout. This is used in conjunction with "),a("code",[e._v("v-toolbar")]),e._v(", "),a("code",[e._v("v-navigation-drawer")]),e._v(", and "),a("code",[e._v("v-footer")]),e._v(".")]),a("section-text",[e._v("The markup below tells the application that you have a "),a("code",[e._v("toolbar")]),e._v(" and "),a("code",[e._v("footer")]),e._v(". Once defined, the content area will be resized to accommodate. For more information on layouts, navigate to the "),a("router-link",{attrs:{to:"/layouts/pre-defined"}},[e._v("Layouts")]),e._v(" section.")],1),a("markup",{attrs:{lang:"html"}},[e._v("<v-app>\n <v-toolbar app>\n <v-toolbar-logo>Portfolio</v-toolbar-logo>\n </v-toolbar>\n <v-content>\n <v-container fluid>\n <router-view></router-view>\n </v-container>\n </v-content>\n <v-footer app>2017</v-footer>\n</v-app>")]),a("h5",[e._v("Static assets")]),a("section-text",[e._v("Place all statically served assets in "),a("code",[e._v("static")]),e._v(". This can be accessed by referencing "),a("code",[e._v("/picture.png")]),e._v(", for example.")]),a("h5",[e._v("Components")]),a("section-text",[e._v("The components folder is where your custom components should be placed. Edit the "),a("code",[e._v("components/_index.js")]),e._v(" file to have these files automatically bootstrapped for you.")]),a("section-header",[e._v("Routing")]),a("section-text",[e._v("The Webpack-SSR template uses the official Vue Router for controlling application flow. Located in "),a("code",[e._v("/src/router/index.js")]),e._v(", all of your application routes and route logic will be defined here. Inside you will also see a function that allows you to setup dynamically imported pages. This is not required, however, it will help break up your application and only load views that are needed, clearing up space in your eventual bundle output.")]),a("markup",{attrs:{lang:"js"}},[e._v("routes: [\n route('/', 'Welcome'),\n route('/inspire', 'Inspire')\n]")]),a("section-text",[a("p",[e._v("These routes can be accessed by creating a link to the specified path, or by using Vue Router's "),a("code",[e._v("<router-link>")]),e._v(" component. For more information, review the official Vue Router "),a("a",{attrs:{href:"https://router.vuejs.org/en/",target:"_blank",rel:"noopener"}},[e._v("documentation")]),e._v(". The default function assumes you are placing views in the "),a("kbd",[e._v("/pages")]),e._v(" folder containing "),a("strong",[e._v("View")]),e._v(" on the end of the file. Example "),a("code",[e._v("HomeView.vue")]),e._v(".")])]),a("section-header",[e._v("State Control")]),a("section-text",[a("p",[e._v("State control is managed by the official Vuex library. This Vue plugin follows Facebooks' Reflux design pattern. Navigate to "),a("code",[e._v("/store/index.js")]),e._v(". By default, Vuex is setup to prefetch data for the store before your page is initially rendered. To hook into this functionality, create a "),a("code",[e._v("preFetch")]),e._v(" method on your view component.")])]),a("markup",{attrs:{lang:"js"}},[e._v("preFetch (store) {\n store.dispatch('GET_USER', 2)\n}")]),a("section-text",[a("p",[e._v("This is useful for bootstrapping your application so that any necessary data is available before the initial render.")]),a("p",[e._v("For more information on State Control and Vuex, view the official "),a("a",{attrs:{href:"https://vuex.vuejs.org/en/intro.html",target:"_blank",rel:"noopener"}},[e._v("documentation")]),e._v(".")])]),a("section-text",[a("p",[e._v("Vuetify integrates into Vuex to allow for easy debugging and access to stored properties. You can also use watchers to hook into store states and react when they change. More information can be found "),a("a",{attrs:{href:"https://vuejs.org/v2/guide/reactivity.html",target:"_blank",rel:"noopener"}},[e._v("here")]),e._v(".")])]),a("section-header",[e._v("Meta data")]),a("section-text",[e._v("In order to ensure that page specific meta data is viewable when your pages are crawled, you can define your applications page specific information in "),a("code",[e._v("router/meta.json")]),e._v(". This will allow you to set page title, description and keywords for every route. This will automatically be applied for you on page load and change.")]),a("section-header",[e._v("Redirects")]),a("section-text",[e._v("As applications evolve, routes change. If you want to maintain the authority already garnered from bots that index your page, it is best to assign a 301 redirect to the new location. Located in "),a("code",[e._v("router/301.json")]),e._v(" you can define 301 redirects for your pages which will automatically be handled for you on page load.")])],1),a("section",[a("section-header",[e._v("Web App Support")]),a("section-text",[e._v("Vuetify SSR has support for native Web Applications on smart phones. Also known as progressive web apps, your websites can be saved on the homescreen of a device, allowing it to be usable offline and receive push notifications. For more information on Web App Manifest's, navigate to the "),a("a",{attrs:{href:"https://developer.mozilla.org/en-US/docs/Web/Manifest",target:"_blank",rel:"noopener"}},[e._v("Mozilla Developer Network")]),e._v(". To see a live example, add the Vuetify documentation on your mobile device's homescreen.")])],1)],1)},s=[],i={render:o,staticRenderFns:s};t.a=i},1492:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement,a=e._self._c||t;return a("doc-view",{attrs:{id:"sandbox-view"}},[a("v-layout",{attrs:{row:"row",wrap:"wrap"}},[a("v-flex",{attrs:{xs12:"xs12",sm8:"sm8",xl12:"xl12"}},[a("section-def",[a("dt",{attrs:{slot:"title"},slot:"title"},[e._v("Sandbox")]),a("dd",{attrs:{slot:"desc"},slot:"desc"},[e._v("This page will allow you to configure the various settings available to you when setting up a layout with Vuetify. Keep in mind, this is "),a("strong",[e._v("not")]),e._v(" an exhaustive list, but a starting point allowing you to understand what is available.")])])],1),a("ad")],1),a("section",[a("v-layout",[a("v-flex",{staticClass:"text-xs-center",attrs:{xs12:"xs12"}},[a("v-btn",{staticClass:"mt-5",attrs:{href:"/examples/layouts/sandbox",target:"_blank",color:"primary",large:"large",dark:"dark"}},[e._v("Go to Sandbox")])],1)],1)],1)],1)},s=[],i={render:o,staticRenderFns:s};t.a=i},1493:function(e,t,a){"use strict";t.a={data:function(){return{doc:{title:"Scrolling",desc:"The <code>v-scroll</code> directive allows you to provide callbacks when the window or a specifically defined element are scrolled.",props:{"v-scroll":{params:[["callback","Function","Required","The function to be called on scroll"],["target","String","window","The DOM element to bind the scroll event listener"],["options","Object","{ passive: true }","The options to be passed to the event listener of the binding target"]]}},examples:[{header:"Default",file:"scroll/default",desc:"The default behavior is to bind to the window. If no additional configuration options are needed, you can simple pass your callback function."},{header:"Scroll with options",file:"scroll/options",desc:"For a more fine tuned approach, you can designate the target to bind the scroll event listener."}]}}}}},1494:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement;return(e._self._c||t)("component-view",{attrs:{doc:e.doc}})},s=[],i={render:o,staticRenderFns:s};t.a=i},1495:function(e,t,a){var o=a(1496);"string"==typeof o&&(o=[[e.i,o,""]]),o.locals&&(e.exports=o.locals);a(198)("4df96ce2",o,!0)},1496:function(e,t,a){t=e.exports=a(197)(void 0),t.push([e.i,"#forms-view .with{min-height:0}#forms-view main{min-height:0;padding-left:0}#forms-view .toolbar{max-height:64px}#forms-view .component-example__container{-webkit-box-pack:justify;-ms-flex-pack:justify;justify-content:space-between;-ms-flex-wrap:wrap;flex-wrap:wrap}#forms-view .component-example__container>div>*{margin:2rem 0;-webkit-box-flex:1;-ms-flex:1 0 100%;flex:1 0 100%}",""])},1497:function(e,t,a){"use strict";t.a={data:function(){return{doc:{title:"Select",desc:"Select fields components are used for collecting user provided information from a list of options.",component:"VSelect",edit:"SelectView",examples:[{header:"Light theme",file:"selects/light",desc:"A standard single select has a multitude of configuration options."},{header:"Dark theme",file:"selects/dark",desc:"Selects also support theming, dark and light."},{header:"Icons",file:"selects/icons",desc:"Use a custom prepended or appended icon."},{header:"Multiple",file:"selects/multiple",desc:"A multi-select can utilize v-chip as the display for selected items."},{header:"Autocomplete",file:"selects/autocomplete",desc:"Provides type-ahead autocomplete functionality."},{header:"Scoped slots",file:"selects/scoped-slots",desc:"With the power of scoped slots, you can customize the visual output of the select. In this example we add a profile picture for both the chips and list items."},{header:"Customized item text and value",file:"selects/custom-text-and-value",desc:"You can specify the specific properties within your items array correspond to the text and value fields. By default, this is <strong>text</strong> and <strong>value</strong>. In this example we also use the <code>return-object</code> prop which will return the entire object of the selected item on selection."},{header:"Tags",new:"0.15.3",file:"selects/tags",desc:"With tags you can allow a user to create new values that may not be present in a provided items list. Keep in mind, tags only supports arrays of <strong>primitive</strong> items and cannot be used with props such as <code>item-text</code>, <code>item-value</code> for example."},{header:"Combobox",file:"selects/combobox",desc:"Combobox is the <strong>single</strong> select variant of <strong>tags</strong>"},{header:"Asynchronous items",new:"0.15.3",file:"selects/asynchronous",desc:"Sometimes you need to load data externally based upon a search query. Use the <code>search-input</code> prop with the <strong>.sync</strong> modifier when using the <code>autocomplete</code> prop. We also make use of the new <code>cache-items</code> prop. This will keep a unique list of all items that have been passed to the <code>items</code> prop and is <strong>REQUIRED</strong> when using asynchronous items and the <strong>multiple</strong> prop."}],props:{"v-select":{shared:["input","filterable","loadable","mask","colorable"],params:[["allow-overflow","Boolean","False","Removes content/window overflow detection"],["content-class","String","-","Applies a custom class to the select menu. This is useful because the menu content is moved to the end of the app and is not targettable by classes passed directly on the select component."],["deletable-chips","Boolean","False","Adds a remove icon to selected chips"],["dense","Boolean","False","Lowers max height of list items"],["open-on-clear","Boolean","False","When using the <strong>clearable</strong> prop, once cleared, the select menu will either open or stay open, depending on the current state"],["browser-autocomplete","String","on","Set the autocomplete prop for the search input when using the <code>autocomplete</code> prop"],["clearable","Boolean","False","Add input clear functionality"],["combobox","Boolean","False","The single select variant of <strong>tags</strong>"],["cache-items","Boolean","False","Keeps a local <strong>unique</strong> copy of all items that have been passed through the <code>items</code> prop."],["debounce-search","[Number, String]","200","Debounces the search input value being emitted"],["chips","Boolean","False","Changes display of selections to chips"],["hide-selected","Boolean","False","Do not display in the select menu items that are already selected"],["items","Array","[]","Can be an array of objects or array of strings. When using objects, will look for a <strong>text</strong> and <strong>value</strong> field. This can be changed using the <code>item-text</code> and <code>item-value</code> props."],["item-text","String","text","Set property of <code>items</code> will be displayed on option"],["item-value","String","value","Set property of <code>items</code> define option's value"],["item-disabled","String","disabled","Set property of <code>items</code>'s disabled value"],["item-avatar","String","avatar","Set property of <code>items</code>'s avatar value"],["max-height","Number, String","200","Sets the maximum height for the select menu"],["multiple","Boolean","False","Changes select to multiple. Accepts array for v-model"],["min-width","[Boolean, Number, String]","False","Sets the minimum width of the select, overwrites automatic determination"],["single-line","Boolean","False","Removes floating label"],["solo","Boolean","False","Changes the style of the text-field for use in toolbars"],["tags","Boolean","False","Tagging functionality, allows you to enter/navigate/delete items"],["auto","Boolean","False","Centers list on selected element"],["autocomplete","Boolean","False","Filter the items in the list based on user input"],["return-object","Boolean","False","Changes the selection behavior to return the object directly rather than the value specified with item-value"],["multi-line","Boolean","False","Causes label to float when the select component is focused or dirty"],["search-input","String","null","Bound when using the autocomplete prop. Use the .sync modifier to catch user input from the autocomplete search input"],["segmented","Boolean","False",'Creates a segmented button - <a href="https://material.io/guidelines/components/buttons.html#buttons-dropdown-buttons" rel="noopener" target="_blank">spec</a>'],["overflow","Boolean","False",'Creates an overflow button - <a href="https://material.io/guidelines/components/buttons.html#buttons-dropdown-buttons" rel="noopener" target="_blank">spec</a>'],["editable","Boolean","False",'Creates an editable button - <a href="https://material.io/guidelines/components/buttons.html#buttons-dropdown-buttons" rel="noopener" target="_blank">spec</a>']],model:{type:["Array","Object"],default:"-",description:"Single select requires model, multiple requires array"}}},slots:{"v-select":{shared:["label","progress"],params:[["no-data","Used when there are no filtered items when using autocomplete"]]}},events:{"v-select":{params:[["input","String","Selected value"]]}}}}}}},1498:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement,a=e._self._c||t;return a("component-view",{attrs:{doc:e.doc}},[a("mask-table")],1)},s=[],i={render:o,staticRenderFns:s};t.a=i},1499:function(e,t,a){var o=a(1500);"string"==typeof o&&(o=[[e.i,o,""]]),o.locals&&(e.exports=o.locals);a(198)("0cc85b4a",o,!0)},1500:function(e,t,a){t=e.exports=a(197)(void 0),t.push([e.i,"#selection-controls-view .component-example table tr{border-bottom:none!important;height:75px}#selection-controls-view .component-example table tr:hover{background:transparent!important}#selection-controls-view .component-example table td,#selection-controls-view .component-example table th{text-align:center}#selection-controls-view .component-example table td .input-group{-webkit-box-pack:center;-ms-flex-pack:center;justify-content:center}",""])},1501:function(e,t,a){"use strict";t.a={data:function(){return{test:[],test2:!1,doc:{title:"Selection controls",component:"",edit:"SelectionControlsView",desc:"Selection control components allow a user to select options. These components <strong>must</strong> be used with the <code>v-model</code> prop as they do not maintain their own state.",examples:[{header:"Checkboxes - Boolean",file:"selection-controls/checkboxes-boolean",desc:""},{header:"Checkboxes - Array",file:"selection-controls/checkboxes-array",desc:""},{header:"Checkboxes - States",file:"selection-controls/checkboxes-states",desc:""},{header:"Checkboxes - Colors",file:"selection-controls/checkboxes-colors",desc:"Checkboxes can be colored by using any of the builtin colors and contextual names using the color prop."},{header:"Radios - Default",file:"selection-controls/radios-default",desc:"Radio-groups are by default mandatory. This can be changed with the <code>mandatory</code> prop."},{header:"Radios - Direction",file:"selection-controls/radios-direction",desc:"Radio-groups can be presented either as a row or a column, using their respective props. The default is as a column."},{header:"Radios - Colors",file:"selection-controls/radios-colors",desc:"Radios can be colored by using any of the builtin colors and contextual names using the color prop."},{header:"Switches - Boolean",file:"selection-controls/switches-boolean",desc:""},{header:"Switches - Array",file:"selection-controls/switches-array",desc:""},{header:"Switches - States",file:"selection-controls/switches-states",desc:""},{header:"Switches - Colors",file:"selection-controls/switches-colors",desc:"Switches can be colored by using any of the builtin colors and contextual names using the color prop."}],props:{"v-checkbox":{shared:["colorable","input"],params:[["input-value","Array, Boolean, String","-","Sets possible input values"],["true-value","String","-","Sets value for truthy state"],["false-value","String","-","Sets value for falsy state"],["indeterminate","Boolean","False","Sets an indeterminate state for the checkbox"]],model:{type:"*",default:"None",description:"Current input value"}},"v-radio":{shared:["colorable","input"],params:[["input-value","String, Number","-","Sets the radio current input value"]],model:{type:"*",default:"None",description:"Current radio value"}},"v-radio-group":{params:[["column","Boolean","True","Displays radio buttons in column"],["row","Boolean","False","Displays radio buttons in row"]]},"v-switch":{shared:["colorable","input"],params:[["input-value","Array, Boolean, String","-","Sets possible input values"],["true-value","String","-","Sets value for truthy state"],["false-value","String","-","Sets value for falsy state"]],model:{type:"*",default:"None",description:"Current switch value"}}},slots:{"v-checkbox":{shared:["label"]},"v-radio":{shared:["label"]},"v-radio-group":{shared:["default"]},"v-switch":{shared:["label"]}},events:{"v-radio":{params:[["change","String, Number","Input value changed."]]},"v-radio-group":{params:[["change","String, Number","Input value changed."],["blur","String, Number","Last active input value."]]}}}}}}},1502:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement;return(e._self._c||t)("component-view",{attrs:{doc:e.doc}})},s=[],i={render:o,staticRenderFns:s};t.a=i},1503:function(e,t,a){var o=a(1504);"string"==typeof o&&(o=[[e.i,o,""]]),o.locals&&(e.exports=o.locals);a(198)("767a18a8",o,!0)},1504:function(e,t,a){t=e.exports=a(197)(void 0),t.push([e.i,"",""])},1505:function(e,t,a){"use strict";t.a={data:function(){return{doc:{component:"VSlider",edit:"SliderView",title:"Slider",desc:"The <code>v-slider</code> component is a better visualization of the number input. It is used for gathering numerical user data.",examples:[{header:"Continuous",file:"sliders/continuous",desc:"Continuous sliders should be used when precision is not a concern."},{header:"Discrete",file:"sliders/discrete",desc:"Discrete sliders offer a thumb label that displays the exact current amount. Using the <code>step</code> prop you can disallow selecting values outside of steps."},{header:"Icons",file:"sliders/icons",desc:"You can add icons to the slider with the <code>append-icon</code> and <code>prepend-icon</code> props."},{header:"With an editable numeric value",file:"sliders/editable-numeric-value",desc:"Sliders can be combined with other components for a better display."},{header:"Dark theme",file:"sliders/dark",desc:"Sliders also support theming."},{header:"Custom colors",file:"sliders/custom-colors",desc:"You can set the colors of the slider using the props <code>color</code>, <code>track-color</code> and <code>thumb-color</code>.",new:"0.16.0"}],props:{"v-slider":{shared:["input","theme"],params:[["color","String","-","Sets the track color"],["min","Number","0","Sets minimum value"],["max","Number","100","Sets maximum value"],["thumb-color","String","-","Sets the thumb and thumb label color"],["thumb-label","Boolean","False","Show thumb label"],["track-color","String","-","Sets the track fill color"],["ticks","Boolean","False","Displays dots at every step (defined with <code>step</code> prop)"],["step","Number","1","If greater than 0, sets step interval for ticks and makes the thumb snapping to each step"]]}},events:{"v-slider":{params:[["input",["Number","String"],"Selected value"]]}}}}}}},1506:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement;return(e._self._c||t)("component-view",{attrs:{doc:e.doc}})},s=[],i={render:o,staticRenderFns:s};t.a=i},1507:function(e,t,a){var o=a(1508);"string"==typeof o&&(o=[[e.i,o,""]]),o.locals&&(e.exports=o.locals);a(198)("a5fb6b5a",o,!0)},1508:function(e,t,a){t=e.exports=a(197)(void 0),t.push([e.i,"#snackbar-view .component-example>.card{z-index:auto!important}",""])},1509:function(e,t,a){"use strict";t.a={data:function(){return{doc:{title:"Snackbar",component:"VSnackbar",edit:"SnackbarView",desc:"The <code>v-snackbar</code> component is used to display a quick message to a user. Snackbars support positioning, removal delay and callbacks.",examples:[{header:"Position",file:"snackbars/position",desc:"The standard snackbar is useful for calling attention to some function that has just happened."},{header:"Contextual",file:"snackbars/contextual",desc:"You can also apply a color to the snackbar to better fit your implementation."}],props:{"v-snackbar":{shared:["colorable"],params:[["absolute","Boolean","False","Set the position to absolute, allowing you to place snackbar inside any container"],["bottom","Boolean","True","Position the snackbar at the bottom"],["top","Boolean","False","Position the snackbar at the top"],["left","Boolean","False","Position the snackbar on the left"],["right","Boolean","False","Position the snackbar on the right"],["multi-line","Boolean","False","Makes the snackbar higher (mobile)"],["timeout","Number","6000","Time to wait until snackbar is automatically hidden"],["vertical","Boolean","False","Stacks snackbar content vertically (mobile)"]],model:{type:["Boolean"],default:"False"}}}}}}}},1510:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement;return(e._self._c||t)("component-view",{attrs:{doc:e.doc}})},s=[],i={render:o,staticRenderFns:s};t.a=i},1511:function(e,t,a){var o=a(1512);"string"==typeof o&&(o=[[e.i,o,""]]),o.locals&&(e.exports=o.locals);a(198)("304fe63b",o,!0)},1512:function(e,t,a){t=e.exports=a(197)(void 0),t.push([e.i,"#helpers li{margin-bottom:1rem}",""])},1513:function(e,t,a){"use strict";t.a={name:"spacing-view"}},1514:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement,a=e._self._c||t;return a("doc-view",{attrs:{id:"spacing-view"}},[a("v-layout",{attrs:{row:"row"}},[a("v-flex",{attrs:{xs12:"xs12",sm8:"sm8",md12:"md12"}},[a("section-def",[a("dt",{attrs:{slot:"title"},slot:"title"},[e._v("Spacing")]),a("dd",{attrs:{slot:"desc"},slot:"desc"},[e._v("Update your layout without creating new classes. Spacing helpers are useful for modifying the padding and margin of an element.")])])],1),a("ad")],1),a("section",[a("h6",{staticClass:"subheading"},[e._v("Type")]),a("ul",{staticClass:"mb-5 browser-list"},[a("li",[a("code",[e._v("m")]),e._v(" - to set margin")]),a("li",[a("code",[e._v("p")]),e._v(" - to set padding")])]),a("h6",{staticClass:"subheading"},[e._v("Direction")]),a("ul",{staticClass:"mb-5 browser-list"},[a("li",[a("code",[e._v("t")]),e._v(" - to set top")]),a("li",[a("code",[e._v("r")]),e._v(" - to set right")]),a("li",[a("code",[e._v("b")]),e._v(" - to set bottom")]),a("li",[a("code",[e._v("l")]),e._v(" - to set left")]),a("li",[a("code",[e._v("x")]),e._v(" - to set x-axis")]),a("li",[a("code",[e._v("y")]),e._v(" - to set y-axis")]),a("li",[a("code",[e._v("a")]),e._v(" - to set all")])]),a("h6",{staticClass:"subheading"},[e._v("Size")]),a("ul",{staticClass:"mb-5 browser-list"},[a("li",[a("code",[e._v("0")]),e._v(" - removes margin or padding for specified direction")]),a("li",[a("code",[e._v("1")]),e._v(" - applies margin or padding with "),a("code",[e._v("16px * .25")])]),a("li",[a("code",[e._v("2")]),e._v(" - applies margin or padding with "),a("code",[e._v("16px * .50")])]),a("li",[a("code",[e._v("3")]),e._v(" - applies margin or padding with "),a("code",[e._v("16px")])]),a("li",[a("code",[e._v("4")]),e._v(" - applies margin or padding with "),a("code",[e._v("16px * 1.5")])]),a("li",[a("code",[e._v("5")]),e._v(" - applies margin or padding with "),a("code",[e._v("16px * 3")])])])]),a("section",[a("h6",{staticClass:"subheading"},[e._v("Example of spacers variable")]),a("markup",{attrs:{lang:"html"}},[e._v('<p class="mt-1">...</p>\n \n<li class="pb-2">...</li>\n \n<v-btn color="primary" class="ma-3">...</v-btn>')]),a("markup",{attrs:{lang:"stylus"}},[e._v("$spacer := 16px\n$spacer-x := $spacer\n$spacer-y := $spacer\n \n$spacers := {\n zero: {\n x: 0,\n y: 0\n },\n one: {\n x: ($spacer-x * .25),\n y: ($spacer-y * .25)\n },\n two: {\n x: ($spacer-x * .5),\n y: ($spacer-y * .5)\n },\n three: {\n x: $spacer-x,\n y: $spacer-y\n },\n four: {\n x: ($spacer-x * 1.5),\n y: ($spacer-y * 1.5)\n },\n five: {\n x: ($spacer-x * 3),\n y: ($spacer-y * 3)\n }\n}")])],1)],1)},s=[],i={render:o,staticRenderFns:s};t.a=i},1515:function(e,t,a){var o=a(1516);"string"==typeof o&&(o=[[e.i,o,""]]),o.locals&&(e.exports=o.locals);a(198)("0f541730",o,!0)},1516:function(e,t,a){t=e.exports=a(197)(void 0),t.push([e.i,"#sponsors-and-backers-view img{max-width:225px;width:100%}#sponsors-and-backers-view .affiliates img{width:80%}",""])},1517:function(e,t,a){"use strict";t.a={data:function(){return{sponsors:[{title:"BrowserStack",href:"https://www.browserstack.com/",src:"browser-stack.png"},{title:"Cloudflare",href:"https://www.cloudflare.com/",src:"cloudflare.svg"}],palladium:[{title:"Eikos Partners",href:"http://www.eikospartners.com/",src:"eikos-partners.webp"},{title:"rateGenius",href:"https://application.rategenius.com/",src:"rate-genius.png"},{title:"quitt",href:"https://quitt.ch/",src:"quitt.png"}],diamond:[{title:"LMAX Exchange",href:"https://careers.lmax.com/?utm_source=vuetify&utm_medium=logo-link&utm_campaign=lmax-careers",src:"lmax-exchange.png"},{title:"Intygrate",href:"http://intygrate.com/",src:"intygrate.png"}],gold:[{title:"Deister Software",href:"http://www.deister.es/",src:"deister-logo-light.png"},{title:"Cocoatech",href:"https://cocoatech.com/",src:"cocoatechlogo.png"},{title:"Cycloid",href:"https://www.cycloid.io/",src:"cycloid.png"},{title:"Live Casino",href:"https://livecasino.com/",src:"casino.webp",dark:!0},{title:"Nate Controls",href:"http://www.natecontrols.com/",src:"n8controls.png"},{title:"Trek10",href:"https://www.trek10.com/",src:"trek10.svg"}],affiliates:[{title:"VueJobs",href:"https://vuejobs.com/?utm_source=vuejobs&utm_medium=affiliates&utm_campaign=linking",noref:!0,src:"vuejobs-logo.svg"},{title:"Made with Vue.js",href:"https://madewithvuejs.com",src:"madewithvuejs.png"},{title:"Vue.js Radar",href:"https://vuejsradar.com",src:"vueradar2.png"}]}}}},1518:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement,a=e._self._c||t;return a("doc-view",{attrs:{id:"sponsors-and-backers-view"}},[a("v-layout",{attrs:{row:"row"}},[a("v-flex",{attrs:{xs12:"xs12"}},[a("section-def",[a("dt",{attrs:{slot:"title"},slot:"title"},[e._v("Support Vuetify.js development")]),a("dd",{attrs:{slot:"desc"},slot:"desc"},[e._v("Vuetify.js is an open source project under the MIT license. It is and will always be free to use. However, the amount of effort it takes to maintain the core framework and all supplementing packages is quite considerable. With the goal to continue development of additional functionality even after the completion of Material Design spec, you can help by "),a("a",{attrs:{href:"https://www.patreon.com/vuetify",target:"_blank",rel:"noreferrer"}},[e._v("backing Vuetify on Patreon")]),e._v(".")])])],1)],1),a("section",{attrs:{id:"sponsors-and-backers"}},[a("h2",{staticClass:"headline"},[e._v("Patreon backers:")]),a("v-divider"),a("v-list",{staticClass:"transparent"},[a("v-list-tile",[a("v-list-tile-title",[a("strong",[e._v("Diamond ($500/mo)")])])],1)],1),a("v-container",{staticClass:"mb-5",attrs:{fluid:"fluid","grid-list-md":"grid-list-md"}},[a("v-layout",{attrs:{row:"row",wrap:"wrap","justify-start":"justify-start","align-center":"align-center"}},e._l(e.diamond,function(e){return a("a",{key:e.title,staticClass:"text-xs-center mx-3",attrs:{href:e.href+"?ref=vuetifyjs.com",target:"_blank",title:e.title}},[a("img",{attrs:{src:"/doc-images/backers/"+e.src,alt:e.title}})])}))],1),a("v-list",{staticClass:"transparent"},[a("v-list-tile",{attrs:{tag:"div"}},[a("v-list-tile-title",[a("strong",[e._v("Palladium ($250/mo)")])])],1)],1),a("v-container",{staticClass:"mb-5",attrs:{fluid:"fluid","grid-list-md":"grid-list-md"}},[a("v-layout",{attrs:{row:"row",wrap:"wrap","justify-start":"justify-start","align-center":"align-center"}},e._l(e.palladium,function(e){return a("a",{key:e.title,staticClass:"text-xs-center mx-3",class:[e.dark?"black":""],attrs:{target:"_blank",href:e.href+"?ref=vuetifyjs.com",title:e.title}},[a("img",{attrs:{src:"/doc-images/backers/"+e.src,alt:e.title}})])}))],1),a("v-list",{staticClass:"transparent"},[a("v-list-tile",{attrs:{tag:"div"}},[a("v-list-tile-title",[a("strong",[e._v("Gold ($50/mo)")])])],1)],1),a("v-container",{staticClass:"mb-5",attrs:{fluid:"fluid","grid-list-md":"grid-list-md"}},[a("v-layout",{attrs:{row:"row",wrap:"wrap","justify-start":"justify-start","align-center":"align-center"}},e._l(e.gold,function(e){return a("a",{key:e.title,staticClass:"text-xs-center mx-3",class:[e.dark?"black":""],attrs:{target:"_blank",href:e.href+"?ref=vuetifyjs.com",title:e.title}},[a("img",{staticStyle:{"max-width":"175px"},attrs:{src:"/doc-images/backers/"+e.src,alt:e.title}})])}))],1),a("h2",{staticClass:"headline"},[e._v("Affiliates:")]),a("v-divider",{staticClass:"mb-3"}),a("v-container",{staticClass:"mb-5 affiliates",attrs:{fluid:"fluid","grid-list-md":"grid-list-md"}},[a("v-layout",{attrs:{row:"row",wrap:"wrap","justify-start":"justify-start","align-center":"align-center"}},e._l(e.affiliates,function(e){return a("a",{key:e.title,staticClass:"text-xs-center mx-3",class:[e.dark?"black":""],attrs:{target:"_blank",href:e.href+(e.noref?"":"?ref=vuetifyjs.com"),title:e.title}},[a("img",{staticStyle:{"max-width":"175px"},attrs:{src:"/doc-images/affiliates/"+e.src,alt:e.title}})])}))],1),a("h2",{staticClass:"headline"},[e._v("Service sponsors:")]),a("v-divider",{staticClass:"mb-3"}),a("v-container",{staticClass:"mb-5",attrs:{fluid:"fluid"}},[a("v-layout",{attrs:{row:"row",wrap:"wrap","justify-start":"justify-start","align-center":"align-center"}},e._l(e.sponsors,function(e){return a("a",{key:e.title,staticClass:"text-xs-center mx-3",attrs:{href:e.href+"?ref=vuetifyjs.com",target:"_blank",title:e.title}},[a("img",{attrs:{src:"/doc-images/"+e.src,alt:"sponsor.title"}})])}))],1),a("div",{staticClass:"text-xs-center"},[a("div",{staticClass:"mb-3"},[e._v("Have additional questions?")]),a("v-btn",{attrs:{outline:"outline",color:"success",round:"round",href:"mailto:john@vuetifyjs.com"}},[e._v("Contact Us")])],1)],1)],1)},s=[],i={render:o,staticRenderFns:s};t.a=i},1519:function(e,t,a){"use strict";t.a={data:function(){return{doc:{component:"VStepper",edit:"SteppersView",title:"stepper",desc:"The <code>v-stepper</code> component displays progress through numbered steps.",examples:[{header:"Example",file:"steppers/example",desc:"A stepper can be used for a multitude of scenarios, including shopping carts, record creation and more."},{header:"Editable steps",file:"steppers/editable",desc:"An editable step can be selected by a user at any point and will navigate them to that step."},{header:"Non-editable steps",file:"steppers/non-editable",desc:"Non-editable steps force a user to process linearly through your process."},{header:"Optional steps",file:"steppers/optional",desc:"An optional step can be called out with sub-text."},{header:"Horizontal steps",file:"steppers/horizontal",desc:"Horizontal steppers move users along the x-axis through the defined steps."},{header:"Vertical steppers",file:"steppers/vertical",desc:"Vertical steppers move users along the y-axis and otherwise work exactly the same as their horizontal counterpart."},{header:"Linear steppers",file:"steppers/linear",desc:"Linear steppers will always move a user through your defined path."},{header:"Non-linear steppers",file:"steppers/non-linear",desc:"Non-linear steppers allow the user to move through your process in whatever way they choose."},{header:"Alternate labels",file:"steppers/alternate-labels",desc:"Steppers also have an alternative label style which places the title under the step itself."},{header:"Multi-line error state",file:"steppers/error",desc:"An error state can be displayed to notify the user of some action that must be taken."},{header:"Alternative label multi-line error state",file:"steppers/alternative-error",desc:"The error state can also be applied to the alternative label style."},{header:"Vertical multi-line error state",file:"steppers/vertical-error",desc:"The same state also applies to Vertical steppers."},{header:"Dynamic steps",file:"steppers/dynamic",new:"0.15.3",desc:"Steppers can have their steps dynamically added or removed. If a currently active step is removed, be sure to account for this by changing the applied model."}],props:{"v-stepper":{shared:["theme"],params:[["non-linear","Boolean","False","Allow user to jump to any step"],["alt-labels","Boolean","False","Places the labels beneath the step"],["vertical","Boolean","False","Display steps vertically"]],model:{type:["Number","String"],default:"-",description:"Sets current selected step"}},"v-stepper-step":{params:[["complete","Boolean","False","Marks step as complete"],["complete-icon","String","check","Icon to display when step is marked as completed"],["edit-icon","String","edit","Icon to display when step is editable"],["error-icon","String","warning","Icon to display when step has an error"],["editable","Boolean","False","Marks step as editable"],["rules","Array","[]","If any rule is falsy, step will be marked with error"],["step","Number, String","-","Will be displayed inside the step circle"]]},"v-stepper-content":{params:[["step","Number, String","-","Sets step to associate the content to"]]}},functional:{"v-stepper-header":{params:[["v-stepper-header","Wrapper for horizontal stepper steps"]]},"v-stepper-items":{params:[["v-stepper-items","Wrapper for horizontal stepper content items"]]}},events:{"v-stepper":{params:[["input","Number, String","Current step"]]}}}}}}},1520:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement;return(e._self._c||t)("component-view",{attrs:{doc:e.doc}})},s=[],i={render:o,staticRenderFns:s};t.a=i},1521:function(e,t,a){"use strict";t.a={data:function(){return{doc:{component:"subheader",edit:"SubheaderView",title:"Subheaders",desc:"The <code>v-subheader</code> component is used to separate sections of lists.",examples:[{header:"List subheaders",file:"subheaders/list",desc:"Subheaders work great with lists for describing the information below."},{header:"Grid subheaders",file:"subheaders/grid",desc:"A subheader can add context to what a user is looking at."},{header:"Menu subheaders",file:"subheaders/menu",desc:"Using a subheader can help separate different types of actions."}],props:{"v-subheader":{shared:["theme"],params:[["inset","Boolean","False","Adds indentation (72px)"]]}}}}}}},1522:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement;return(e._self._c||t)("component-view",{attrs:{doc:e.doc}})},s=[],i={render:o,staticRenderFns:s};t.a=i},1523:function(e,t,a){var o=a(1524);"string"==typeof o&&(o=[[e.i,o,""]]),o.locals&&(e.exports=o.locals);a(198)("1a1b728a",o,!0)},1524:function(e,t,a){t=e.exports=a(197)(void 0),t.push([e.i,"#components-tabs-view .tabs{margin:1rem 0}",""])},1525:function(e,t,a){"use strict";t.a={name:"tabs-view",data:function(){return{doc:{component:"VTabs",edit:"TabsView",title:"Tabs",desc:"The <code>v-tabs</code> component is used for hiding content behind a selectable item. This can also be used as a pseudo-navigation for a page, where the tabs are links and the tab-items are the content.",examples:[{header:"Toolbar tabs",file:"tabs/toolbar",desc:"The <code>v-tabs</code> component is highly customizable to suit your needs. You can get and set the currently active tab by using the <code>v-model</code> prop on the <code>v-tabs</code> component."},{header:"Centered tabs",file:"tabs/centered",desc:"Tabs can be centered by using the <code>centered</code> prop. Here we have also applied the <code>fixed</code> prop which gives all tab items a fixed size, regardless of content."},{header:"Content",file:"tabs/content",desc:"Tabs are not the only thing you can put inside the <code>v-tabs</code> component. In this example we've also added a toolbar."},{header:"With search",file:"tabs/search",desc:"Here is another example of additional content inside the <code>v-tabs</code> component."},{header:"Icons",file:"tabs/icons",desc:"By using the <code>icons</code> prop you can add icons to each tab item."},{header:"Desktop tabs",file:"tabs/desktop"},{header:"Grow",file:"tabs/grow",desc:"The <code>grow</code> prop will make the tab items take up all available space."},{header:"Pagination",file:"tabs/pagination",desc:"If the tab items overflow their container, pagination controls will appear."},{header:"Disabled scroll",file:"tabs/disabled-scroll",desc:"You can disable the pagination controls by setting the <code>scrollable</code> prop to <code>false</code>. This also has the effect of removing the margins around the tab item container."}],props:{"v-tabs":{params:[["centered","Boolean","False","Centers the tabs"],["fixed","Boolean","False","Items have a fixed size"],["grow","Boolean","False","Items fill available space"],["icons","Boolean","False","Applies the tabs--icons class"],["scrollable","Boolean","True","Displays pagination controls when content overflows"],["mobile-break-point","[Number, String]","1280","Sets the designated mobile breakpoint"]],model:{type:["String"],default:"-",description:"Current selected tab"}},"v-tabs-bar":{shared:["theme"],params:[]},"v-tabs-items":{params:[["cycle","Boolean","False","Will go to the first or last tab when swiped at the start or end of items"],["touchless","Boolean","False","Remove touch functionality from component"]]},"v-tabs-item":{shared:["router"],params:[]},"v-tabs-content":{params:[["id","String","Required","The content id"],["transition","String","v-tab-transition","Sets the default transition"],["reverse-transition","String","v-tab-reverse-transition","Sets the reverse transition"],["lazy","Boolean","False","Will not render contents until is active for the first time"]]},"v-tabs-slider":{shared:["colorable"]}},events:{"v-tabs":{params:[["input","String","Current active tab"]]}},slots:{"v-tabs":{shared:["default"]},"v-tabs-items":{shared:["default"]},"v-tabs-bar":{shared:["default"]}}}}}}},1526:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement;return(e._self._c||t)("component-view",{attrs:{doc:e.doc}})},s=[],i={render:o,staticRenderFns:s};t.a=i},1527:function(e,t,a){var o=a(1528);"string"==typeof o&&(o=[[e.i,o,""]]),o.locals&&(e.exports=o.locals);a(198)("75aaadcc",o,!0)},1528:function(e,t,a){t=e.exports=a(197)(void 0),t.push([e.i,"#text-fields-view .container,#text-fields-view main{min-height:0}",""])},1529:function(e,t,a){"use strict";t.a={data:function(){return{doc:{title:"Text fields",desc:"Text fields components are used for collecting user provided information.",component:"VTextField",edit:"TextFieldsView",examples:[{header:"With label",file:"text-fields/label",desc:"Text-fields come in two theme options, dark and light."},{header:"Dark theme with label",file:"text-fields/label-dark",desc:"The dark theme compliments darker backgrounds."},{header:"Single line light theme",file:"text-fields/single-line",desc:"Single line text-fields do not float their label on focus or with data."},{header:"Single line dark theme",file:"text-fields/single-line-dark",desc:"A single line label mimics the display of a placeholder."},{header:"With Icon",file:"text-fields/icon",desc:"Icons can be specified as prepended or appended."},{header:"Dark theme with icon",file:"text-fields/icon-dark",desc:"The icon inherits the applications primary color on text-field focus."},{header:"Multi-Line",file:"text-fields/multi-line",desc:"A multi-line text-field is useful for larger amounts of text."},{header:"Dark theme multi-line",file:"text-fields/multi-line-dark",desc:"Multi-line text-fields can be set to autogrow allowing the field to scale with the input."},{header:"Character counter",file:"text-fields/character-counter",desc:"Use a counter to inform a user of the character limit. The counter does not perform any validation by itself. You will need to pair it with either the internal validation system, or a 3rd party library."},{header:"Password input",file:"text-fields/password",desc:"A password input can be used with an appended icon and callback to control the visibility."},{header:"Validation",file:"text-fields/validation",desc:"Vuetify includes simple validation through the <code>rules</code> prop. The prop accepts an array of callbacks. While validating rules, the current v-model value will be passed to the callback. This callback should return either <code>true</code> or a <code>String</code>, the error message."},{header:"Full-width text field with character counter",file:"text-fields/full-width-with-character-counter",desc:"Light theme"},{header:"Required fields",file:"text-fields/required-fields",desc:"In this example two of the text-fields are required. We utilize the <strong>required</strong> prop in order to apply an asterisk to the label and rules to validate the fields."},{header:"Hint text",file:"text-fields/hint",desc:"Light theme"},{header:"Prefixes & suffixes",file:"text-fields/prefixes-and-suffixes",desc:"Light theme"},{header:"Custom validation",file:"text-fields/custom-validation",desc:'While the built in <code>v-form</code> or 3rd party plugin such as <a href="https://github.com/monterail/vuelidate" target="_blank" rel="noopener">vuelidate</a> or <a href="https://github.com/logaretm/vee-validate" target="_blank" rel="noopener">vee-validation</a> can help streamline your validation process, you can choose to simply control it yourself.'},{header:"Textarea",file:"text-fields/textarea",desc:"Textarea text-fields have an alternate style."},{header:"Box style",file:"text-fields/box",desc:"Text-fields can be used with an alternative box design. Append and prepend icon props are <strong>not</strong> supported in this mode."},{header:"Custom colors",file:"text-fields/custom-colors",new:"0.16.0",desc:"You can optionally change a text-field into any color in the Material design palette. Below is an example implementation of a custom form with validation."},{header:"Masks",file:"text-fields/masks",new:"0.16.0",desc:"Text fields can validate against character masks. Using either a pre-made or custom rules, you can optionally format and validate specific character sets."},{header:"Progress bar",file:"text-fields/progress-bar",new:"0.16.0",desc:"You can display a progress bar instead of the bottom line. You can use the default indeterminate progress having same color as the text field or designate a custom one using the <code>progress</code> slot"}],props:{"v-text-field":{shared:["input","loadable","mask"],params:[["autofocus","Boolean","False","Enable autofocus"],["color","String","primary","Sets a custom theme color"],["box","Boolean","False","Applies the alternate <strong>box</strong> input style"],["clearable","Boolean","False","Add input clear functionality"],["auto-grow","Boolean","False","Auto-grows the input. This option <strong>requires</strong> the use of <code>v-model</code>"],["counter","[Boolean, Number]","False","Creates counter for input length. If no Number is specified, it defaults to 25. Does not apply any validation."],["full-width","Boolean","False","Designates input type as full-width"],["prefix","String","","Displays prefix text"],["multi-line","Boolean","False","Turns into textarea"],["readonly","Boolean","False","Disables input"],["rows","Number","5","Number of rows in textarea"],["single-line","Boolean","False","Label does not move on focus/dirty"],["solo","Boolean","False","Changes the style of the text-field for use in toolbars"],["textarea","Boolean","False","Textarea text-field with alternate style"],["suffix","String","","Displays suffix text"],["type","String","text","Sets input type"]],model:{type:["*"],default:"-",description:"Current input value"}}},slots:{"v-text-field":{shared:["label","progress"]}},events:{"v-text-field":{params:[["input","String","Current input value. Fires while typing."],["focus","-","Input gained focus."],["blur","-","Input lost focus."],["change","String","Input value was changed. Fired on blur."]]}}}}}}},1530:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement,a=e._self._c||t;return a("component-view",{attrs:{doc:e.doc}},[a("mask-table")],1)},s=[],i={render:o,staticRenderFns:s};t.a=i},1531:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement,a=e._self._c||t;return a("doc-view",[a("v-layout",{attrs:{row:"row",wrap:"wrap"}},[a("v-flex",{attrs:{xs12:"xs12",sm8:"sm8",xl12:"xl12"}},[a("section-def",[a("dt",{attrs:{slot:"title"},slot:"title"},[e._v("Theme")]),a("dd",{attrs:{slot:"desc"},slot:"desc"},[e._v("Easily change the colors of your application programmatically.")])])],1),a("ad")],1),a("section",[a("section-header",[e._v("Light and Dark")]),a("section-text",[e._v("Vuetify supports both "),a("strong",[e._v("light")]),e._v(" and "),a("strong",[e._v("dark")]),e._v(" variants of the Material Design spec. This designation starts at the root application component, "),a("code",[e._v("v-app")]),e._v(".")]),a("markup",[e._v("<v-app light>\n...\n</v-app>")]),a("section-text",[e._v("When you designate a component as light or dark, all of its children will inherit and apply the same unless otherwise specified.")])],1),a("section",[a("section-header",[e._v("Customizing")]),a("section-text",[e._v("By default, Vuetify has a standard theme applied for all components.")]),a("markup",{attrs:{lang:"javascript"}},[e._v("{\n primary: '#1976D2',\n secondary: '#424242',\n accent: '#82B1FF',\n error: '#FF5252',\n info: '#2196F3',\n success: '#4CAF50',\n warning: '#FFC107'\n}")]),a("section-text",[e._v("This can be easily changed. Simply pass a "),a("strong",[e._v("theme")]),e._v(" property to the "),a("code",[e._v("Vue.use")]),e._v(" function. You can choose to modify all or only some of the theme properties, with the remaining inheriting from the default.")]),a("markup",{attrs:{lang:"javascript"}},[e._v("Vue.use(Vuetify, {\n theme: {\n primary: '#3f51b5',\n secondary: '#b0bec5',\n accent: '#8c9eff',\n error: '#b71c1c'\n }\n})")]),a("section-text",[e._v("Under the hood, Vuetify will generate css classes based upon these values that will be accessible in the DOM. These classes will follow the same markup as other helper classes, "),a("code",[e._v("primary")]),e._v(" or "),a("code",[e._v("secondary--text")]),e._v(" for example.")]),a("section-text",[e._v("These values will also be made available on the instance "),a("strong",[e._v("$vuetify")]),e._v(" object under the "),a("strong",[e._v("theme")]),e._v(" property. This allows you to "),a("em",[e._v("dynamically")]),e._v(" modify your theme. Behind the scenes, Vuetify will regenerate and update your theme classes, seamlessly updating your application.")]),a("markup",{attrs:{lang:"javascript"}},[e._v("this.$vuetify.theme.primary = '#4caf50'")])],1)],1)},s=[],i={render:o,staticRenderFns:s};t.a=i},1532:function(e,t,a){var o=a(1533);"string"==typeof o&&(o=[[e.i,o,""]]),o.locals&&(e.exports=o.locals);a(198)("d0cf6de8",o,!0)},1533:function(e,t,a){t=e.exports=a(197)(void 0),t.push([e.i,"#toolbar-view .system-bar{position:relative;z-index:auto}#toolbar-image{height:300px;width:100%}#toolbar-image .toolbar{margin:0}",""])},1534:function(e,t,a){"use strict";var o=a(1535),s=a.n(o);t.a={data:function(){return{doc:s()({title:"Toolbar",component:"VToolbar",edit:"ToolbarsView",desc:"The <code>v-toolbar</code> component is pivotal to any gui, as it generally is the primary source of site navigation. The toolbar component works great in conjunction with a navigation drawer for hiding links and presenting an activator to open the sidebar on mobile.",examples:[{header:"Default",file:"toolbar/default",desc:"A toolbar is a flexible container that can be utilized in a number of ways. By default, the toolbar is 64px high on desktop, 56px high on mobile portrait and 48px high on mobile landscape. These can be overwritten using the <code>dense</code> and <code>prominent</code> props."},{header:"App bar",file:"toolbar/app-bar",desc:"An App bar is the primary toolbar of your application. It can contain icons, menus and more."},{header:"App bar with extension",file:"toolbar/app-bar-extension",desc:"An extension can be used that creates a much more prominent bar. If a title is placed within the extension, it will automatically be shifted to the right to match the normal location it would be at in the main bar."},{header:"Column width with hierarchy",file:"toolbar/column-width-with-hierarchy",desc:"Toolbars come in 2 variants, light and dark. Light toolbars have dark tinted buttons and dark text whereas Dark toolbars have white tinted buttons and white text."},{header:"Flexible toolbar and card toolbar",file:"toolbar/flexible-and-card",desc:"With a few custom styles, you can easily create your amazing user interfaces."},{header:"Floating with search",file:"toolbar/floating-with-search",desc:"A floating toolbar can be placed over the content that it references."},{header:"Variations",file:"toolbar/variations",desc:"An app-bar has multiple variations that can be applied with themes and helper classes. These range from light and dark themes, colored and transparent."},{header:"Prominent toolbars",file:"toolbar/prominent",desc:"Prominent toolbars add a slot where you can placed elements in the extended area. The content and extension areas will be locked to 64px in height."},{header:"Dense toolbars",file:"toolbar/dense",desc:"Dense toolbars reduce their height to 48px. This is also the default behavior for mobile landscape orientation."},{header:"Dense prominent toolbars",file:"toolbar/dense-prominent",desc:"You can combine both the prominent and dense to extend a smaller variant of the toolbar."},{header:"Scrolling techniques",file:"toolbar/scrolling",desc:"A toolbar can transition off screen when scrolling. Here we demonstrate how you can specify the scroll target (default is window). Keep in mind, for this example there is special markup that will not be required in your application."},{header:"App bar with menu",file:"toolbar/app-bar-menu",desc:"You can add menu components to a toolbar."},{header:"System bars - status/window",file:"toolbar/system-bars-status-window",desc:"System bars are useful for notification icons on mobile and desktop. For live examples of, head to the pre-defined layouts."}],props:{"v-toolbar":{shared:["app","theme","colorable"],params:[["clipped-left","Boolean","False","Designates that a <code>v-navigation-drawer</code> is clipped on the left side of the toolbar"],["clipped-right","Boolean","False","Designates that a <code>v-navigation-drawer</code> is clipped on the right side of the toolbar"],["card","Boolean","False","Inherits border radius when used within a <code>v-card</code>"],["extended","Boolean","False","Force the toolbar to generate the extension without using the slot"],["dense","Boolean","False","Reduces the height of the toolbar content and extension"],["height","[Number, String]","null","Designates a specific height for the toolbar"],["manual-scroll","Boolean","False","Manually apply the <code>scroll-off-screen</code> functionality"],["fixed","Boolean","False","Sets the position of the toolbar to fixed"],["flat","Boolean","False","Removes the toolbar box-shadow"],["absolute","Boolean","False","Sets the position of the toolbar to absolute"],["floating","Boolean","False","Makes the toolbar inline"],["prominent","Boolean","False","Increases the height of the toolbar content and extension"],["scroll-off-screen","Boolean","False","Will transition the toolbar off screen when scrolling down"],["scroll-target","String","window","Assign the scroll target for scroll-off-screen"],["scroll-threshold","Number","100","The amount of scroll distance down before the toolbar uses scroll-off-screen"]]},"v-system-bar":{shared:["app","theme","colorable"],params:[["lights-out","Boolean","False","Reduces the system bar opacity"],["status","Boolean","False","Reduces the system bar height"],["fixed","Boolean","False","Sets the position of the toolbar to fixed"],["absolute","Boolean","False","Sets the position of the toolbar to absolute"],["window","Boolean","False","Increases the system bar height"]]}},slots:{"v-toolbar":{default:!0},"v-system-bar":{default:!0}},functional:{"v-toolbar":{params:[["v-toolbar-items",".toolbar__items"],["v-toolbar-title",".toolbar__title"],["v-toolbar-side-icon",".toolbar__side-icon"]]}}},"slots",{"v-toolbar":{shared:["default"]},"v-toolbar-item":{shared:["default"]}})}}}},1535:function(e,t,a){"use strict";t.__esModule=!0;var o=a(1536),s=function(e){return e&&e.__esModule?e:{default:e}}(o);t.default=function(e,t,a){return t in e?(0,s.default)(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}},1536:function(e,t,a){e.exports={default:a(1537),__esModule:!0}},1537:function(e,t,a){a(1538);var o=a(2).Object;e.exports=function(e,t,a){return o.defineProperty(e,t,a)}},1538:function(e,t,a){var o=a(5);o(o.S+o.F*!a(7),"Object",{defineProperty:a(4).f})},1539:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement;return(e._self._c||t)("component-view",{attrs:{doc:e.doc}})},s=[],i={render:o,staticRenderFns:s};t.a=i},1540:function(e,t,a){"use strict";t.a={data:function(){return{doc:{title:"Tooltip",component:"VTooltip",edit:"TooltipsView",desc:"The <code>v-tooltip</code> component is useful for conveying information when a user hovers over an element. You can also programmatically control the display of tooltips through a <strong>v-model</strong>",props:{"v-tooltip":{shared:["delayable","menu","lazy"],model:{type:["Boolean"],default:"False"},params:[["color","String","-","Apply a custom color to the tooltip background"],["disabled","Boolean","False","Disables showing tooltip on mouse hover"],["debounce","[Number, String]","100","Duration before tooltip is shown and hidden when hovered"],["tag","String","span","The tooltip tag"],["transition","String","-","By default, this is automatically calculated depending on the position options used. Can be removed with a Boolean (false) value or changed by providing your own"],["z-index","*","99","The z-index used for the tooltip"]]}},examples:[{header:"Default",file:"tooltips/default",desc:"Tooltips can wrap any element."},{header:"Visibility",file:"tooltips/visibility",desc:"Tooltip visibility can be programmatically changed using <code>v-model</code>."}]}}}}},1541:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement;return(e._self._c||t)("component-view",{attrs:{doc:e.doc}})},s=[],i={render:o,staticRenderFns:s};t.a=i},1542:function(e,t,a){"use strict";t.a={data:function(){return{doc:{title:"Touch Support",desc:"The <code>v-touch</code> directive allows you to capture swipe gestures and apply directional callbacks.",props:{"v-touch":{params:[["[up, down, left, right]","Function","-","Assign a callback based upon a swipe direction. Pairing x-axis and y-axis callbacks is not recommended at this time."],["[move, start, end]","Function","-","Assign a callback when the touch event starts, ends, and while it is in progress"]]}},examples:[{header:"Default",file:"touch/default",desc:"On a mobile device, try swiping in various directions."}]}}}}},1543:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement;return(e._self._c||t)("component-view",{attrs:{doc:e.doc}})},s=[],i={render:o,staticRenderFns:s};t.a=i},1544:function(e,t,a){"use strict";t.a={data:function(){return{doc:{title:"Motion",edit:"TransitionsView",desc:"Smooth animations help make a UI feel great. Using Vue's transition system and re-usable functional components, you can easily control the motion of your application. Most components can have their transition altered through the <code>transition</code> prop.",examples:[{header:"Slide X transitions",file:"transitions/slide-x-transitions",desc:"Slide x transitions move along the horizontal axis."},{header:"Slide Y transitions",file:"transitions/slide-y-transitions",desc:"Animations use the applications <code>$primary-transition</code>."},{header:"Scale transition",file:"transitions/scale-transition",desc:"Many of Vuetify's components contain a <code>transition</code> prop which allows you to specify your own."},{header:"Fade transition",file:"transitions/fade-transition",desc:'Another example of the fade transition can be found on the <router-link to="/components/carousel">Carousel</router-link> component.'},{header:"Custom Origin",file:"transitions/custom-origin",desc:"Programmatically control the transition origin with a simple prop."}]}}}}},1545:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement,a=e._self._c||t;return a("component-view",{attrs:{doc:e.doc}},[a("h6",[e._v("Create your own")]),a("section-text",[e._v("You can use Vuetify's transition helper function to easily create your own custom transitions. This function will return an object that you can import into Vue. Using Vue's "),a("a",{attrs:{href:"https://vuejs.org/v2/guide/render-function.html#Functional-Components",target:"_blank",rel:"noopener"}},[e._v("functional component")]),e._v(" option will make sure your transition is as efficient as possible. Simply import the function:")]),a("markup",{attrs:{lang:"javascript"}},[e._v("import { createSimpleTransition } from '../../node_modules/vuetify/src/util/helpers'\n \nconst myTransition = createSimpleTransition('my-transition')\n \nVue.component('my-transition', myTransition)")]),a("section-text",[e._v("The "),a("code",[e._v("createSimpleTransition")]),e._v(" function accepts 1 argument, name. This will be the name that you can hook into with your style. This is an example of what "),a("code",[e._v("v-fade-transition")]),e._v(" looks like:")]),a("markup",{attrs:{lang:"stylus"}},[e._v(".fade-transition\n &-leave-active\n position: absolute\n \n &-enter-active, &-leave, &-leave-to\n transition: $primary-transition\n \n &-enter, &-leave-to\n opacity: 0")])],1)},s=[],i={render:o,staticRenderFns:s};t.a=i},1546:function(e,t,a){var o=a(1547);"string"==typeof o&&(o=[[e.i,o,""]]),o.locals&&(e.exports=o.locals);a(198)("8a563918",o,!0)},1547:function(e,t,a){t=e.exports=a(197)(void 0),t.push([e.i,'#typography-view .component-example__container>div,#typography-view .component-example__container dl{width:100%}#typography-view .component-example__container>div:after,#typography-view .component-example__container dl:after{content:"";display:table;clear:both}#typography-view .component-example__container .headings dd,#typography-view .component-example__container .headings dt{float:left}#typography-view .component-example__container .headings dt{width:32px;height:32px;border-radius:50%;text-align:center;line-height:32px;color:#fff;clear:both}#typography-view .component-example__container .headings dd{margin:0 0 3rem 2rem}#typography-view .component-example__container .headings dd>div{margin-bottom:16px}#typography-view .component-example__container .headings dd strong{margin-right:16px}',""])},1548:function(e,t,a){"use strict";t.a={name:"typography-view",data:function(){return{doc:{title:"Typography",desc:"The typography of an application is just as important as its functionality. Vuetify.js uses the Material Design spec Roboto Font. Each heading size also has a corresponding helper class to style other elements the same."},lorem:"Lorem ipsum dolor sit amet, brute iriure accusata ne mea. Eos suavitate referrentur ad, te duo agam libris qualisque, utroque quaestio accommodare no qui. Et percipit laboramus usu, no invidunt verterem nominati mel. Dolorem ancillae an mei, ut putant invenire splendide mel, ea nec propriae adipisci. Ignota salutandi accusamus in sed, et per malis fuisset, qui id ludus appareat."}}}},1549:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement,a=e._self._c||t;return a("doc-view",{attrs:{id:"typography-view"}},[a("v-layout",{attrs:{row:"row",wrap:"wrap"}},[a("v-flex",{attrs:{xs12:"xs12",sm8:"sm8",xl12:"xl12"}},[a("section-def",[a("dt",{attrs:{slot:"title"},slot:"title"},[e._v(e._s(e.doc.title))]),a("dd",{attrs:{slot:"desc"},slot:"desc"},[e._v(e._s(e.doc.desc))])])],1),a("ad")],1),a("section",[a("section-header",[e._v("Examples")]),a("div",{staticClass:"component-example"},[a("div",{staticClass:"component-example__container"},[a("dl",{staticClass:"headings"},[a("dt",{staticClass:"primary"},[e._v("h1")]),a("dd",[a("div",{staticClass:"display-4 grey--text text--darken-1"},[e._v("Light 112sp")]),a("strong",[e._v("display-4")]),a("span",[e._v("font-weight 300")])]),a("dt",{staticClass:"primary"},[e._v("h2")]),a("dd",[a("div",{staticClass:"display-3 grey--text text--darken-1"},[e._v("Regular 56sp")]),a("strong",[e._v("display-3")]),a("span",[e._v("font-weight 400")])]),a("dt",{staticClass:"primary"},[e._v("h3")]),a("dd",[a("div",{staticClass:"display-2 grey--text text--darken-1"},[e._v("Regular 45sp")]),a("strong",[e._v("display-2")]),a("span",[e._v("font-weight 400")])]),a("dt",{staticClass:"primary"},[e._v("h4")]),a("dd",[a("div",{staticClass:"display-1 grey--text text--darken-1"},[e._v("Regular 34sp")]),a("strong",[e._v("display-1")]),a("span",[e._v("font-weight 400")])]),a("dt",{staticClass:"primary"},[e._v("h5")]),a("dd",[a("div",{staticClass:"headline grey--text text--darken-1"},[e._v("Regular 24sp")]),a("strong",[e._v("headline")]),a("span",[e._v("font-weight 400")])]),a("dt",{staticClass:"primary"},[e._v("h6")]),a("dd",[a("div",{staticClass:"title grey--text text--darken-1"},[e._v("Medium 20sp")]),a("strong",[e._v("title")]),a("span",[e._v("font-weight 500")])]),a("dt"),a("dd",[a("div",{staticClass:"subheading grey--text text--darken-1"},[e._v("Regular 16sp")]),a("strong",[e._v("subheading")]),a("span",[e._v("font-weight 400")])]),a("dt"),a("dd",[a("div",{staticClass:"body-2 grey--text text--darken-1"},[e._v("Medium 14sp")]),a("strong",[e._v("body-2")]),a("span",[e._v("font-weight 500")])]),a("dt"),a("dd",[a("div",{staticClass:"body-1 grey--text text--darken-1"},[e._v("Regular 14sp")]),a("strong",[e._v("body-1")]),a("span",[e._v("font-weight 400")])]),a("dt"),a("dd",[a("div",{staticClass:"caption grey--text text--darken-1"},[e._v("Regular 12sp")]),a("strong",[e._v("caption")]),a("span",[e._v("font-weight 400")])])])])])],1)],1)},s=[],i={render:o,staticRenderFns:s};t.a=i},1550:function(e,t,a){var o=a(1551);"string"==typeof o&&(o=[[e.i,o,""]]),o.locals&&(e.exports=o.locals);a(198)("0c53e134",o,!0)},1551:function(e,t,a){t=e.exports=a(197)(void 0),t.push([e.i,"#why-vuetify .section-text{margin-bottom:24px!important}.pillars .flex{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-flex:1;-ms-flex:1 1 auto;flex:1 1 auto;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column}.pillars .flex .card{-webkit-box-flex:1;-ms-flex:1 1 auto;flex:1 1 auto}",""])},1552:function(e,t,a){"use strict";t.a={data:function(){return{comparisons:[{title:"Semantic Helper Components"},{title:"SSR and PWA Support"},{title:"8 Vue-CLI templates"},{title:"Chat Support"},{title:"Modular Component Transition System"},{title:"Blazing Fast Framework"},{title:"A La Carte components"}],list:[{check:!0,text:"Good for SEO"},{check:!0,text:"Well Documented"},{check:!0,text:"Active Community"},{check:!0,text:"Free"}],philosophies:[{img:"/vuetify_semantic.svg",title:"Semantic toolkit",caption:"Vuetify is built from the ground up to be semantic. Easy to learn, easy to remember—this means that whether you are developing your own application, or onboarding a new developer, Vuetify's <em>write-as-you-speak</em> components and properties make development a breeze."},{img:"/vuetify_sizes.svg",title:"Continuous updates",caption:"Vuetify has a consistent update cycle, allowing you to get your hands on bug fixes and enhancements more often. The development team is committed to providing you with the best experience you can have."},{img:"/vuetify_cli.svg",title:"Amazing support",caption:"When you run into a roadblock, you need assistance immediately. Vuetify offers chat support in our growing community on Discord."}]}}}},1553:function(e,t,a){"use strict";var o=function(){var e=this,t=e.$createElement,a=e._self._c||t;return a("doc-view",{attrs:{id:"why-vuetify"}},[a("section-header",[e._v("What's the difference?")]),a("v-layout",{staticClass:"mb-5",attrs:{row:"row",wrap:"wrap"}},[a("v-flex",{attrs:{xs12:"xs12"}},[a("v-container",{staticClass:"pa-0",attrs:{fluid:"fluid","grid-list-md":"grid-list-md"}},[a("v-layout",{staticClass:"pillars",attrs:{row:"row",wrap:"wrap"}},e._l(e.philosophies,function(t,o){return a("v-flex",{key:o,attrs:{xs12:"xs12",sm4:"sm4"}},[a("v-card",[a("v-layout",{staticClass:"pa-5",attrs:{"align-center":"align-center","justify-center":"justify-center"}},[a("v-avatar",{attrs:{size:"150px"}},[a("img",{staticClass:"grey darken-4",attrs:{src:t.img}})])],1),a("div",{staticClass:"px-3"},[a("v-divider",{staticClass:"indigo lighten-4"})],1),a("v-card-title",{staticClass:"headline layout justify-center",attrs:{primary:"primary"}},[a("span",{domProps:{textContent:e._s(t.title)}})]),a("v-card-text",{staticClass:"caption",domProps:{innerHTML:e._s(t.caption)}})],1)],1)}))],1)],1)],1),a("v-layout",{attrs:{row:"row",wrap:"wrap","justify-space-between":"justify-space-between"}},[a("v-flex",{attrs:{xs12:"xs12",md8:"md8"}},[a("section-text",[e._v("Choosing a framework can be a daunting task, and I'm not even talking about component frameworks. You've arrived at Vue and now it's time to start developing your next great idea. There are many options to choose from, and everyone says that they are great. So you have to decide, what are my metrics for success?")]),a("section-text",[e._v("This was me almost a year ago. There were plenty of "),a("strong",[e._v("UI toolkits")]),e._v(" to choose from, but none them had everything that I needed...yeah, you've heard that before. Often enough though, it "),a("em",[e._v("is")]),e._v(" the reason individual's attempts to create products that fill gaps, and is why I started working on Vuetify.")]),a("section-text",{staticClass:"mb-0"},[e._v("But now you are the one searching for that perfect framework, and Vuetify is another on a list of many, vying for your attention. While my opinion will be subjective, I will try to outline features that I believe will be valuable to you and/or your organization.")]),a("section-header",{staticClass:"title"},[a("v-icon",{staticClass:"mr-3 purple--text"},[e._v("brush")]),a("span",[e._v("Design principles")])],1),a("section-text",[e._v("Vuetify is developed exactly according to Material Design spec. Every component is hand crafted to bring you the best possible UI tools to your next great app. The development doesn't stop at the core components outlined in Google's spec. Through the support of community members and sponsors, additional components will be designed and made available for everyone to enjoy.")]),a("section-header",{staticClass:"title"},[a("v-icon",{staticClass:"mr-3 teal--text"},[e._v("people")]),a("span",[e._v("Vibrant community")])],1),a("section-text",[e._v("Developing with Vuetify means you will never be alone. Get help immediately from the dev team and other community members in the official Discord server. Get the opportunity to speak with talented individuals that want you to succeed in your efforts.")]),a("section-header",{staticClass:"title"},[a("v-icon",{staticClass:"mr-3 primary--text"},[e._v("apps")]),a("span",[e._v("Comparison to other Frameworks")])],1),a("section-text",[e._v("Vuetify is not the only Vue material framework out there. Plenty of other talented developers have created some amazing applications under the guise of Google's Material Design spec. Each offer their own unique take on development and process, however, here are a few things that set Vuetify apart:")]),a("v-layout",{attrs:{row:"row",wrap:"wrap"}},[a("v-flex",{attrs:{xs12:"xs12",sm8:"sm8"}},[a("v-subheader",[e._v("What you get:")]),a("v-list",{staticClass:"transparent",staticStyle:{"max-width":"400px"},attrs:{dense:"dense"}},e._l(e.comparisons,function(t,o){return a("v-list-tile",{key:t.title,class:{"grey lighten-3":o%2==0},attrs:{tag:"div",ripple:!1,avatar:"avatar"}},[a("v-list-tile-content",[a("v-list-tile-title",{staticClass:"subheading"},[e._v(e._s(t.title))])],1),a("v-list-tile-action",[a("v-icon",{staticClass:"green--text",attrs:{dark:"dark"}},[e._v("check")])],1)],1)}))],1),a("v-flex",{staticClass:"layout align-center justify-center",attrs:{xs12:"xs12",sm4:"sm4"}},[a("img",{staticClass:"my-5",attrs:{src:"/doc-images/logo.svg",alt:"Vuetify",width:"150px"}})])],1)],1),a("v-flex",{attrs:{xs12:"xs12",md3:"md3"}},[a("v-badge",{attrs:{color:"error",overlap:"overlap"}},[a("v-icon",{staticClass:"white--text",attrs:{slot:"badge",left:"left",overlap:"overlap"},slot:"badge"},[e._v("favorite")]),a("v-card",{staticClass:"red--after",attrs:{flat:"flat",tile:"tile"}},[a("v-list",[a("v-list-tile",{attrs:{avatar:"avatar",tag:"div"}},[a("v-list-tile-avatar",[a("v-avatar",[a("img",{attrs:{src:"/doc-images/john.jpg"}})])],1),a("v-list-tile-content",[a("v-list-tile-title",[e._v("John Leider")]),a("v-list-tile-sub-title",[e._v("Author of Vuetify.js")])],1),a("v-list-tile-action",[a("v-tooltip",{attrs:{left:"left"}},[a("v-btn",{attrs:{slot:"activator",icon:"icon",href:"mailto:john@vuetifyjs.com"},slot:"activator"},[a("v-icon",[e._v("mail")])],1),a("span",[e._v("Contact Me")])],1)],1)],1)],1),a("v-card-text",[e._v("I am extremely humbled that you have considered using Vuetify as your next UI Framework. A lot of care has went into forging the perfect setup for taking any idea from conception to production. I look forward to you joining the Vuetify community and am excited to see what incredible interfaces you create!")]),a("v-card-text",{staticClass:"text-xs-right"},[a("em",[e._v("—John Leider")])])],1)],1)],1)],1),a("div",{staticClass:"text-xs-center my-5"},[a("em",[e._v("Still have questions?"),a("br")]),a("v-btn",{attrs:{flat:"flat",outline:"outline",round:"round",color:"success",href:"https://chat.vuetifyjs.com",target:"_blank"}},[e._v("Ask the Community")])],1)],1)},s=[],i={render:o,staticRenderFns:s};t.a=i},765:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=a(1370),s=a(1371),i=a(0),n=i(o.a,s.a,!1,null,null,null);t.default=n.exports},766:function(e,t,a){"use strict";function o(e){a(1372)}Object.defineProperty(t,"__esModule",{value:!0});var s=a(1374),i=a(1375),n=a(0),r=o,l=n(s.a,i.a,!1,r,null,null);t.default=l.exports},767:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=a(1376),s=a(1377),i=a(0),n=i(o.a,s.a,!1,null,null,null);t.default=n.exports},768:function(e,t,a){"use strict";function o(e){a(1378)}Object.defineProperty(t,"__esModule",{value:!0});var s=a(1380),i=a(1381),n=a(0),r=o,l=n(s.a,i.a,!1,r,null,null);t.default=l.exports},769:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=a(1382),s=a(1383),i=a(0),n=i(o.a,s.a,!1,null,null,null);t.default=n.exports},770:function(e,t,a){"use strict";function o(e){a(1384)}Object.defineProperty(t,"__esModule",{value:!0});var s=a(1386),i=a(1387),n=a(0),r=o,l=n(s.a,i.a,!1,r,null,null);t.default=l.exports},771:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=a(1388),s=a(1389),i=a(0),n=i(o.a,s.a,!1,null,null,null);t.default=n.exports},772:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=a(1390),s=a(1391),i=a(0),n=i(o.a,s.a,!1,null,null,null);t.default=n.exports},773:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=a(1392),s=a(1393),i=a(0),n=i(o.a,s.a,!1,null,null,null);t.default=n.exports},774:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=a(1394),s=a(1395),i=a(0),n=i(o.a,s.a,!1,null,null,null);t.default=n.exports},775:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=a(1396),s=a(1397),i=a(0),n=i(o.a,s.a,!1,null,null,null);t.default=n.exports},776:function(e,t,a){"use strict";function o(e){a(1398)}Object.defineProperty(t,"__esModule",{value:!0});var s=a(1400),i=a(1401),n=a(0),r=o,l=n(s.a,i.a,!1,r,null,null);t.default=l.exports},777:function(e,t,a){"use strict";function o(e){a(1402)}Object.defineProperty(t,"__esModule",{value:!0});var s=a(1404),i=a(1405),n=a(0),r=o,l=n(s.a,i.a,!1,r,null,null);t.default=l.exports},778:function(e,t,a){"use strict";function o(e){a(1406)}Object.defineProperty(t,"__esModule",{value:!0});var s=a(1408),i=a(1409),n=a(0),r=o,l=n(s.a,i.a,!1,r,null,null);t.default=l.exports},779:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=a(1410),s=a(0),i=s(null,o.a,!1,null,null,null);t.default=i.exports},780:function(e,t,a){"use strict";function o(e){a(1411)}Object.defineProperty(t,"__esModule",{value:!0});var s=a(1413),i=a(1414),n=a(0),r=o,l=n(s.a,i.a,!1,r,null,null);t.default=l.exports},781:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=a(0),s=o(null,null,!1,null,null,null);t.default=s.exports},782:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=a(1415),s=a(1416),i=a(0),n=i(o.a,s.a,!1,null,null,null);t.default=n.exports},783:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=a(1417),s=a(1418),i=a(0),n=i(o.a,s.a,!1,null,null,null);t.default=n.exports},784:function(e,t,a){"use strict";function o(e){a(1419)}Object.defineProperty(t,"__esModule",{value:!0});var s=a(1421),i=a(1422),n=a(0),r=o,l=n(s.a,i.a,!1,r,null,null);t.default=l.exports},785:function(e,t,a){"use strict";function o(e){a(1423)}Object.defineProperty(t,"__esModule",{value:!0});var s=a(1425),i=a(1426),n=a(0),r=o,l=n(s.a,i.a,!1,r,null,null);t.default=l.exports},786:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=a(1427),s=a(1428),i=a(0),n=i(o.a,s.a,!1,null,null,null);t.default=n.exports},787:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=a(1429),s=a(1430),i=a(0),n=i(o.a,s.a,!1,null,null,null);t.default=n.exports},788:function(e,t,a){"use strict";function o(e){a(1431)}Object.defineProperty(t,"__esModule",{value:!0});var s=a(1433),i=a(1434),n=a(0),r=o,l=n(s.a,i.a,!1,r,null,null);t.default=l.exports},789:function(e,t,a){"use strict";function o(e){a(1435)}Object.defineProperty(t,"__esModule",{value:!0});var s=a(1437),i=a(1438),n=a(0),r=o,l=n(s.a,i.a,!1,r,null,null);t.default=l.exports},790:function(e,t,a){"use strict";function o(e){a(1439)}Object.defineProperty(t,"__esModule",{value:!0});var s=a(1441),i=a(1442),n=a(0),r=o,l=n(s.a,i.a,!1,r,null,null);t.default=l.exports},791:function(e,t,a){"use strict";function o(e){a(1443)}Object.defineProperty(t,"__esModule",{value:!0});var s=a(1445),i=a(1446),n=a(0),r=o,l=n(s.a,i.a,!1,r,null,null);t.default=l.exports},792:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=a(1447),s=a(1448),i=a(0),n=i(o.a,s.a,!1,null,null,null);t.default=n.exports},793:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=a(1449),s=a(1450),i=a(0),n=i(o.a,s.a,!1,null,null,null);t.default=n.exports},794:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=a(1451),s=a(1452),i=a(0),n=i(o.a,s.a,!1,null,null,null);t.default=n.exports},795:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=a(1453),s=a(1454),i=a(0),n=i(o.a,s.a,!1,null,null,null);t.default=n.exports},796:function(e,t,a){"use strict";function o(e){a(1455)}Object.defineProperty(t,"__esModule",{value:!0});var s=a(1457),i=a(1458),n=a(0),r=o,l=n(s.a,i.a,!1,r,null,null);t.default=l.exports},797:function(e,t,a){"use strict";function o(e){a(1459)}Object.defineProperty(t,"__esModule",{value:!0});var s=a(1461),i=a(1462),n=a(0),r=o,l=n(s.a,i.a,!1,r,null,null);t.default=l.exports},798:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=a(1463),s=a(1464),i=a(0),n=i(o.a,s.a,!1,null,null,null);t.default=n.exports},799:function(e,t,a){"use strict";function o(e){a(1465)}Object.defineProperty(t,"__esModule",{value:!0});var s=a(1467),i=a(1468),n=a(0),r=o,l=n(s.a,i.a,!1,r,null,null);t.default=l.exports},800:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=a(1469),s=a(1470),i=a(0),n=i(o.a,s.a,!1,null,null,null);t.default=n.exports},801:function(e,t,a){"use strict";function o(e){a(1471)}Object.defineProperty(t,"__esModule",{value:!0});var s=a(1473),i=a(1474),n=a(0),r=o,l=n(s.a,i.a,!1,r,null,null);t.default=l.exports},802:function(e,t,a){"use strict";function o(e){a(1475)}Object.defineProperty(t,"__esModule",{value:!0});var s=a(1477),i=a(1478),n=a(0),r=o,l=n(s.a,i.a,!1,r,null,null);t.default=l.exports},803:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=a(1479),s=a(1480),i=a(0),n=i(o.a,s.a,!1,null,null,null);t.default=n.exports},804:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=a(1481),s=a(1482),i=a(0),n=i(o.a,s.a,!1,null,null,null);t.default=n.exports},805:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=a(1483),s=a(1484),i=a(0),n=i(o.a,s.a,!1,null,null,null);t.default=n.exports},806:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=a(1485),s=a(1486),i=a(0),n=i(o.a,s.a,!1,null,null,null);t.default=n.exports},807:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=a(1487),s=a(1488),i=a(0),n=i(o.a,s.a,!1,null,null,null);t.default=n.exports},808:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=a(1489),s=a(1490),i=a(0),n=i(o.a,s.a,!1,null,null,null);t.default=n.exports},809:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=a(1491),s=a(0),i=s(null,o.a,!1,null,null,null);t.default=i.exports},810:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=a(1492),s=a(0),i=s(null,o.a,!1,null,null,null);t.default=i.exports},811:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=a(1493),s=a(1494),i=a(0),n=i(o.a,s.a,!1,null,null,null);t.default=n.exports},812:function(e,t,a){"use strict";function o(e){a(1495)}Object.defineProperty(t,"__esModule",{value:!0});var s=a(1497),i=a(1498),n=a(0),r=o,l=n(s.a,i.a,!1,r,null,null);t.default=l.exports},813:function(e,t,a){"use strict";function o(e){a(1499)}Object.defineProperty(t,"__esModule",{value:!0});var s=a(1501),i=a(1502),n=a(0),r=o,l=n(s.a,i.a,!1,r,null,null);t.default=l.exports},814:function(e,t,a){"use strict";function o(e){a(1503)}Object.defineProperty(t,"__esModule",{value:!0});var s=a(1505),i=a(1506),n=a(0),r=o,l=n(s.a,i.a,!1,r,null,null);t.default=l.exports},815:function(e,t,a){"use strict";function o(e){a(1507)}Object.defineProperty(t,"__esModule",{value:!0});var s=a(1509),i=a(1510),n=a(0),r=o,l=n(s.a,i.a,!1,r,null,null);t.default=l.exports},816:function(e,t,a){"use strict";function o(e){a(1511)}Object.defineProperty(t,"__esModule",{value:!0});var s=a(1513),i=a(1514),n=a(0),r=o,l=n(s.a,i.a,!1,r,null,null);t.default=l.exports},817:function(e,t,a){"use strict";function o(e){a(1515)}Object.defineProperty(t,"__esModule",{value:!0});var s=a(1517),i=a(1518),n=a(0),r=o,l=n(s.a,i.a,!1,r,null,null);t.default=l.exports},818:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=a(1519),s=a(1520),i=a(0),n=i(o.a,s.a,!1,null,null,null);t.default=n.exports},819:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=a(1521),s=a(1522),i=a(0),n=i(o.a,s.a,!1,null,null,null);t.default=n.exports},820:function(e,t,a){"use strict";function o(e){a(1523)}Object.defineProperty(t,"__esModule",{value:!0});var s=a(1525),i=a(1526),n=a(0),r=o,l=n(s.a,i.a,!1,r,null,null);t.default=l.exports},821:function(e,t,a){"use strict";function o(e){a(1527)}Object.defineProperty(t,"__esModule",{value:!0});var s=a(1529),i=a(1530),n=a(0),r=o,l=n(s.a,i.a,!1,r,null,null);t.default=l.exports},822:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=a(1531),s=a(0),i=s(null,o.a,!1,null,null,null);t.default=i.exports},823:function(e,t,a){"use strict";function o(e){a(1532)}Object.defineProperty(t,"__esModule",{value:!0});var s=a(1534),i=a(1539),n=a(0),r=o,l=n(s.a,i.a,!1,r,null,null);t.default=l.exports},824:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=a(1540),s=a(1541),i=a(0),n=i(o.a,s.a,!1,null,null,null);t.default=n.exports},825:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=a(1542),s=a(1543),i=a(0),n=i(o.a,s.a,!1,null,null,null);t.default=n.exports},826:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=a(1544),s=a(1545),i=a(0),n=i(o.a,s.a,!1,null,null,null);t.default=n.exports},827:function(e,t,a){"use strict";function o(e){a(1546)}Object.defineProperty(t,"__esModule",{value:!0});var s=a(1548),i=a(1549),n=a(0),r=o,l=n(s.a,i.a,!1,r,null,null);t.default=l.exports},828:function(e,t,a){"use strict";function o(e){a(1550)}Object.defineProperty(t,"__esModule",{value:!0});var s=a(1552),i=a(1553),n=a(0),r=o,l=n(s.a,i.a,!1,r,null,null);t.default=l.exports}});
|
from app import app
import random
import string
import os
def random_file(type_file):
return "".join(random.sample(string.ascii_letters + string.digits, 32)) + "." + type_file
def upload(image):
"""
Upload image to Local
"""
try:
if not os.path.isdir(app.config["UPLOAD_FOLDER"]):
os.mkdir(app.config["UPLOAD_FOLDER"])
filename = random_file(image.filename.rsplit(".", 1)[1])
while os.path.isfile(os.path.join(app.config["UPLOAD_FOLDER"], filename)):
filename = random_file()
upload_image = os.path.join(app.config["UPLOAD_FOLDER"], filename)
image.save(upload_image)
except Exception as error:
print(error)
return
return upload_image.split("/", 1)[1]
|
# 509. Fibonacci Number
# 动态规划
# Runtime: 36 ms, faster than 44.34% of Python3 online submissions for Fibonacci Number.
# Memory Usage: 13 MB, less than 5.02% of Python3 online submissions for Fibonacci Number.
class Solution:
def fib(self, N: int) -> int:
if N == 0:
return 0
if N == 1:
return 1
a = 0
b = 1
for _ in range(2, N + 1):
c = a + b
a = b
b = c
return c
|
/*
YUI 3.16.0 (build 76f0e08)
Copyright 2014 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add("lang/calendar-base_hu",function(e){e.Intl.add("calendar-base","hu",{very_short_weekdays:["V","H","K","Sze","Cs","P","Szo"],first_weekday:1,weekends:[0,6]})},"3.16.0");
|
/* money.js 0.1.2, MIT license, josscrowcroft.github.com/money.js */
(function(g,j){var b=function(a){return new i(a)};b.version="0.1.2";var c=g.fxSetup||{rates:{},base:""};b.rates=c.rates;b.base=c.base;b.settings={from:c.from||b.base,to:c.to||b.base};var h=b.convert=function(a,e){if("object"===typeof a&&a.length){for(var d=0;d<a.length;d++)a[d]=h(a[d],e);return a}e=e||{};if(!e.from)e.from=b.settings.from;if(!e.to)e.to=b.settings.to;var d=e.to,c=e.from,f=b.rates;f[b.base]=1;if(!f[d]||!f[c])throw"fx error";d=c===b.base?f[d]:d===b.base?1/f[c]:f[d]*(1/f[c]);return a*d},i=function(a){"string"===typeof a?(this._v=parseFloat(a.replace(/[^0-9-.]/g,"")),this._fx=a.replace(/([^A-Za-z])/g,"")):this._v=a},c=b.prototype=i.prototype;c.convert=function(){var a=Array.prototype.slice.call(arguments);a.unshift(this._v);return h.apply(b,a)};c.from=function(a){a=b(h(this._v,{from:a,to:b.base}));a._fx=b.base;return a};c.to=function(a){return h(this._v,{from:this._fx?this._fx:b.settings.from,to:a})};if("undefined"!==typeof exports){if("undefined"!==typeof module&&module.exports)exports=module.exports=b;exports.fx=lib}else"function"===typeof define&&define.amd?define([],function(){return b}):(b.noConflict=function(a){return function(){g.fx=a;b.noConflict=j;return b}}(g.fx),g.fx=b)})(this);
|
/* trace:example/src/style-inc.css */
define(function(require, exports, module) {
var cssContent = ".menu{width:30px}";
var moduleUri = module && module.uri;
var head = document.head || document.getElementsByTagName("head")[0];
var styleTagId = "yom-style-module-inject-tag";
var styleTag = document.getElementById(styleTagId);
if (!styleTag) {
styleTag = document.createElement("style");
styleTag.id = styleTagId;
styleTag.type = "text/css";
styleTag = head.appendChild(styleTag);
}
window._yom_style_module_injected = window._yom_style_module_injected || {};
if (!moduleUri) {
styleTag.appendChild(document.createTextNode(cssContent + "\n"));
} else if (!window._yom_style_module_injected[moduleUri]) {
styleTag.appendChild(document.createTextNode("/* " + moduleUri + " */\n" + cssContent + "\n"));
window._yom_style_module_injected[moduleUri] = 1;
}
module.exports = cssContent;
});
|
// COPYRIGHT © 2021 Esri
//
// All rights reserved under the copyright laws of the United States
// and applicable international laws, treaties, and conventions.
//
// This material is licensed for use under the Esri Master License
// Agreement (MLA), and is bound by the terms of that agreement.
// You may redistribute and use this code without modification,
// provided you adhere to the terms of the MLA and include this
// copyright notice.
//
// See use restrictions at http://www.esri.com/legal/pdfs/mla_e204_e300/english
//
// For additional information, contact:
// Environmental Systems Research Institute, Inc.
// Attn: Contracts and Legal Services Department
// 380 New York Street
// Redlands, California, USA 92373
// USA
//
// email: contracts@esri.com
//
// See http://js.arcgis.com/3.37/esri/copyright.txt for details.
define({display:{elevationProfileTitle:"Profil elevație",showMe:"arată",selectLine:"<b>Selectaţi</b> un obiect spaţial în hartă.",popupRequirement:"NOTĂ: obiectul spaţial trebuie să facă parte dintr-un strat tematic pentru care sunt activate pop-upurile.",digitizeDistanceMeasureTool:"Utilizaţi instrumentele <b>Măsurare</b>.",selectFeatureHelpUrl:"http://help.arcgis.com/ro/arcgisonline/help/010q/010q0000004s000000.htm#ESRI_SECTION1_DAA22E89DF67448E8F3682309F39BE5D",measureToolHelpUrl:"http://help.arcgis.com/ro/arcgisonline/help/index.html#//010q00000096000000",hoverOver:"Suprapuneţi indicatorul mouse-ului peste diagrama Profil elevaţie sau atingeţi această diagramă pentru a afişa elevaţiile şi locaţia pe hartă.",directionLabel:"Direcţie profil"},buttons:{measureLabel:"Măsurătoare",helpLabel:"Ajutor",profileForward:"Înainte",profileReverse:"Inversare",flipProfileTitle:"Faceţi clic pentru a întoarce direcţia profilului",aggregationShowLabel:"Afişare informaţii agregare",aggregationHideLabel:"Ascundere informaţii agregare",aggregateElevationGainForward:"Agregare câştig elevaţie înainte",aggregateElevationLossForward:"Agregare pierdere elevaţie înainte",aggregateElevationGainReverse:"Agregare câştig elevaţie înapoi",aggregateElevationLossReverse:"Agregare pierdere elevaţie înapoi"},chart:{title:"Profil elevaţie",demResolution:"Rezoluţie DEM",elevationTitleTemplate:"Elevaţie în {0}",distanceTitleTemplate:"Distanţă în {0}",gainLossTemplate:"Min.:{min} Max.:{max} Pornire:{start} Sfârşit:{end} Modificare:{gainloss}"},errors:{MissingConstructorParameters:"Lipsesc parametrii constructorului.",InvalidConfiguration:"Configuraţie nevalidă.",UnableToProcessResults:"Nu se pot procesa rezultatele analizei.",UnableToNormalizeGeometry:"Nu s-a putut normaliza geometria de intrare a poliliniei",NullGeometry:"Geometria poliliniei este nulă. Nu s-a putut actualiza profilul",InvalidProfileResults:"Lispeşte parametrul „profileResults” din ProfileChart.update(...)."}});
|
function getInfo(callback){
let timestamp = Math.floor(Date.parse(new Date())/1000)
let siteInfo
if(window.localStorage){
if(localStorage.infoTime>timestamp-3600){
siteInfo=JSON.parse(localStorage.siteInfo)
callback(siteInfo)
}else{
Vue.http.get('/api/getinfo').then(function(res){
localStorage.siteInfo=JSON.stringify(res.body)
localStorage.infoTime=timestamp
siteInfo = res.body
callback(siteInfo)
}, function(){})
}
}else{
Vue.http.get('/api/getinfo').then(function(res){
siteInfo = res.body
callback(siteInfo)
}, function(){})
}
}
function getNickName(){
let preName=['梅花','黑桃','方块','红桃']
let aftName=['A','2','3','4','5','6','7','8','9','10','J','Q','K']
return preName[Math.floor(Math.random()*(4))]+aftName[Math.floor(Math.random()*(13))]
}
var MD5 = function(d){result = M(V(Y(X(d),8*d.length)));return result.toLowerCase()};function M(d){for(var _,m="0123456789ABCDEF",f="",r=0;r<d.length;r++)_=d.charCodeAt(r),f+=m.charAt(_>>>4&15)+m.charAt(15&_);return f}function X(d){for(var _=Array(d.length>>2),m=0;m<_.length;m++)_[m]=0;for(m=0;m<8*d.length;m+=8)_[m>>5]|=(255&d.charCodeAt(m/8))<<m%32;return _}function V(d){for(var _="",m=0;m<32*d.length;m+=8)_+=String.fromCharCode(d[m>>5]>>>m%32&255);return _}function Y(d,_){d[_>>5]|=128<<_%32,d[14+(_+64>>>9<<4)]=_;for(var m=1732584193,f=-271733879,r=-1732584194,i=271733878,n=0;n<d.length;n+=16){var h=m,t=f,g=r,e=i;f=md5_ii(f=md5_ii(f=md5_ii(f=md5_ii(f=md5_hh(f=md5_hh(f=md5_hh(f=md5_hh(f=md5_gg(f=md5_gg(f=md5_gg(f=md5_gg(f=md5_ff(f=md5_ff(f=md5_ff(f=md5_ff(f,r=md5_ff(r,i=md5_ff(i,m=md5_ff(m,f,r,i,d[n+0],7,-680876936),f,r,d[n+1],12,-389564586),m,f,d[n+2],17,606105819),i,m,d[n+3],22,-1044525330),r=md5_ff(r,i=md5_ff(i,m=md5_ff(m,f,r,i,d[n+4],7,-176418897),f,r,d[n+5],12,1200080426),m,f,d[n+6],17,-1473231341),i,m,d[n+7],22,-45705983),r=md5_ff(r,i=md5_ff(i,m=md5_ff(m,f,r,i,d[n+8],7,1770035416),f,r,d[n+9],12,-1958414417),m,f,d[n+10],17,-42063),i,m,d[n+11],22,-1990404162),r=md5_ff(r,i=md5_ff(i,m=md5_ff(m,f,r,i,d[n+12],7,1804603682),f,r,d[n+13],12,-40341101),m,f,d[n+14],17,-1502002290),i,m,d[n+15],22,1236535329),r=md5_gg(r,i=md5_gg(i,m=md5_gg(m,f,r,i,d[n+1],5,-165796510),f,r,d[n+6],9,-1069501632),m,f,d[n+11],14,643717713),i,m,d[n+0],20,-373897302),r=md5_gg(r,i=md5_gg(i,m=md5_gg(m,f,r,i,d[n+5],5,-701558691),f,r,d[n+10],9,38016083),m,f,d[n+15],14,-660478335),i,m,d[n+4],20,-405537848),r=md5_gg(r,i=md5_gg(i,m=md5_gg(m,f,r,i,d[n+9],5,568446438),f,r,d[n+14],9,-1019803690),m,f,d[n+3],14,-187363961),i,m,d[n+8],20,1163531501),r=md5_gg(r,i=md5_gg(i,m=md5_gg(m,f,r,i,d[n+13],5,-1444681467),f,r,d[n+2],9,-51403784),m,f,d[n+7],14,1735328473),i,m,d[n+12],20,-1926607734),r=md5_hh(r,i=md5_hh(i,m=md5_hh(m,f,r,i,d[n+5],4,-378558),f,r,d[n+8],11,-2022574463),m,f,d[n+11],16,1839030562),i,m,d[n+14],23,-35309556),r=md5_hh(r,i=md5_hh(i,m=md5_hh(m,f,r,i,d[n+1],4,-1530992060),f,r,d[n+4],11,1272893353),m,f,d[n+7],16,-155497632),i,m,d[n+10],23,-1094730640),r=md5_hh(r,i=md5_hh(i,m=md5_hh(m,f,r,i,d[n+13],4,681279174),f,r,d[n+0],11,-358537222),m,f,d[n+3],16,-722521979),i,m,d[n+6],23,76029189),r=md5_hh(r,i=md5_hh(i,m=md5_hh(m,f,r,i,d[n+9],4,-640364487),f,r,d[n+12],11,-421815835),m,f,d[n+15],16,530742520),i,m,d[n+2],23,-995338651),r=md5_ii(r,i=md5_ii(i,m=md5_ii(m,f,r,i,d[n+0],6,-198630844),f,r,d[n+7],10,1126891415),m,f,d[n+14],15,-1416354905),i,m,d[n+5],21,-57434055),r=md5_ii(r,i=md5_ii(i,m=md5_ii(m,f,r,i,d[n+12],6,1700485571),f,r,d[n+3],10,-1894986606),m,f,d[n+10],15,-1051523),i,m,d[n+1],21,-2054922799),r=md5_ii(r,i=md5_ii(i,m=md5_ii(m,f,r,i,d[n+8],6,1873313359),f,r,d[n+15],10,-30611744),m,f,d[n+6],15,-1560198380),i,m,d[n+13],21,1309151649),r=md5_ii(r,i=md5_ii(i,m=md5_ii(m,f,r,i,d[n+4],6,-145523070),f,r,d[n+11],10,-1120210379),m,f,d[n+2],15,718787259),i,m,d[n+9],21,-343485551),m=safe_add(m,h),f=safe_add(f,t),r=safe_add(r,g),i=safe_add(i,e)}return Array(m,f,r,i)}function md5_cmn(d,_,m,f,r,i){return safe_add(bit_rol(safe_add(safe_add(_,d),safe_add(f,i)),r),m)}function md5_ff(d,_,m,f,r,i,n){return md5_cmn(_&m|~_&f,d,_,r,i,n)}function md5_gg(d,_,m,f,r,i,n){return md5_cmn(_&f|m&~f,d,_,r,i,n)}function md5_hh(d,_,m,f,r,i,n){return md5_cmn(_^m^f,d,_,r,i,n)}function md5_ii(d,_,m,f,r,i,n){return md5_cmn(m^(_|~f),d,_,r,i,n)}function safe_add(d,_){var m=(65535&d)+(65535&_);return(d>>16)+(_>>16)+(m>>16)<<16|65535&m}function bit_rol(d,_){return d<<_|d>>>32-_}
function getToken(){for(res={},res.timestamp=String(Math.floor(Date.parse(new Date)/1e3)),seed=String(Math.floor(1e6*Math.random())),key=MD5(res.timestamp).slice(0,3);MD5(seed).slice(0,3)!=key;)seed=MD5(seed);return res.md5=seed,res}
//curpage
let curPagn=window.location.pathname.split('/')
let arch=window.location.pathname.split('/')
arch.pop()
arch=arch.join('/')+'/'
if(arch.length==1){arch='/page/'}
curPagn=curPagn[curPagn.length-1]
curPagn=curPagn.split('#')[0]
//canvas
new Vue({
el: "#cvs",
methods: {
draw: function () {
let colors = ['#40E0D0','#B0C4DE','#00BFFF','#8470FF','#EEEE00','#FF8C00']
let canvas = document.getElementById("cvs")
let hei = window.innerHeight*2
let wid = window.innerWidth*2
if(canvas.getContext){
canvas.width = wid
canvas.height = hei
lst = 0.8*hei*Math.random()+0.2*hei
rst = 0.8*hei*Math.random()
let ctx = canvas.getContext("2d")
lft=2*Math.random()
rft=2*Math.random()
for (let i=0;i<5;i++){
ctx.lineWidth = 2
ctx.beginPath()
lst = lst - lft*0.2*hei*Math.random()-0.05*hei
rst = rst + rft*0.2*hei*Math.random()+0.05*hei
ctx.strokeStyle = colors[Math.floor(6*Math.random())]
ctx.moveTo(0, lst)
ctx.lineTo(wid, rst)
ctx.stroke()
ctx.closePath()
}
}
}
},
mounted(){this.draw()}
})
//navbar
new Vue({
delimiters: ['${', '}'],
el: "#nav",
data:{cates:{},tog:0},
methods: {
setCates:function(info){
this.cates=info.cates
},
toggle:function(){
this.tog=1-this.tog
document.getElementById("nav-btns").style.display=['none','block'][this.tog]
document.getElementById("nav-btns").style.opacity=this.tog
}
},
mounted(){getInfo(this.setCates)}
})
//sidebar
new Vue({
delimiters: ['${', '}'],
el: "#sidebar",
data:{sidebarData:''},
methods: {
init:function(info){
this.sidebarData=info.sidebar
}
},
mounted(){
getInfo(this.init);}
})
//footer
new Vue({
delimiters: ['${', '}'],
el: "#footer",
data:{time:''},
methods: {
onShow:function(){
window.setInterval(()=>{
let days = 3600000 * 24
let today = new Date()
let t1 = Date.UTC(2016,8,21,18,24,41)
let t2 = Date.UTC(today.getFullYear(),today.getMonth(),today.getDate(),today.getHours(),today.getMinutes(),today.getSeconds())
let diff = t2-t1
let diffDays = Math.floor((diff/days))
let diffHours = Math.floor((diff-(diffDays)*days)/3600000)
let diffMinutes = Math.floor((diff-(diffDays)*days-diffHours*3600000)/60000)
let diffSeconds = Math.floor((diff-(diffDays)*days-diffHours*3600000-diffMinutes*60000)/1000)
this.time=diffDays+" 天 "+diffHours+" 时 "+diffMinutes+" 分 "+diffSeconds+" 秒"
},1000)
}
},
mounted(){
this.onShow()
}
})
//article
let eleList = document.querySelectorAll('.artiList date')
for (let i = 0; i < eleList.length; i++) {eleList[i].innerHTML="Posted on: "+eleList[i].innerHTML.slice(0,-9);}
getInfo((info)=>{
eleList = document.querySelectorAll('file')
for (let i = 0; i < eleList.length; i++) {eleList[i].innerHTML=info.cates[eleList[i].innerHTML];}
})
eleList = document.querySelectorAll('tag')
for (let i = 0; i < eleList.length; i++) {
let temp=' '
tags=eleList[i].innerHTML.split(",")
for (let j = 0; j < tags.length; j++) {
temp+='<a href="/arch/'+tags[j]+'/1"> '+tags[j]+' </a>'
}
eleList[i].innerHTML=temp
}
//pagn
eleList = document.querySelectorAll('pagn')
if(eleList.length){
if(curPagn==""){curPagn=1;}
if(curPagn==1){document.querySelector('pagn.prev').className += " hidden";}
if(curPagn==eleList.length-2){document.querySelector('pagn.next').className += " hidden";}
document.querySelector('pagn.prev').parentElement.href=arch+String(parseInt(curPagn)-1)
document.querySelector('pagn.next').parentElement.href=arch+String(parseInt(curPagn)+1)
for (let i = 0; i < eleList.length; i++) {
eleList[i].parentElement.href=arch+String(i)
if(eleList[i].innerHTML==curPagn){
eleList[i].className += "active"
eleList[i].parentElement.href=""
}
}
}
//comments
let replyId = null;
poster=new Vue({
delimiters: ['${', '}'],
el: "#commentpost",
data:{textholder:'一句话吐槽',inputholder:'输入您的昵称或留空',text:'',author:'',lastTime:0},
methods: {
onshow: function(){},
post: function(){
var _this=this
if(this.lastTime+10>Math.floor(Date.parse(new Date)/1e3)){
_this.textholder="回复得太快了,请稍候..."
return false
}else if(this.text==''){
_this.textholder="回复内容不能为空"
return false
}
this.lastTime=Math.floor(Date.parse(new Date)/1e3)
token=getToken()
if(_this.author==''){_this.author=getNickName()}
Vue.http.post('/api/postcomment',{author:_this.author,content:_this.text,bid:curPagn,rid:replyId,timestamp:token.timestamp,md5:token.md5},{emulateJSON:true}).then(function(res){
if(res.body==1){
comments.onshow()
_this.author="";
_this.text="";
_this.textholder="一句话吐槽"
replyId=null;
}
}, function(){})
},
cancel:function(){
replyId=null
this.textholder="一句话吐槽"
}
},
mounted(){
this.onshow()
}
})
Vue.component('comment', {
delimiters: ['${', '}'],
props: ['info'],
template: '<div class="comment"><author>${ info.content.author }</author><a href="#tags"><reply v-on:click="reply"> 回复</reply></a><content>${ info.content.content }</content><date>${ info.content.date }</date><subcom v-for="subcom in info.content.subcom" v-bind:subcom="subcom"></subcom></div>',
methods:{
onshow: function(){
this.info.content.date=String(this.info.content.date).slice(0,-7)
},
reply:function(){
replyId=this.info.id
poster.textholder="回复|"+this.info.content.author+"|的评论,双击文本框可撤销"
}
},
mounted(){
this.onshow()
}
})
Vue.component('subcom', {
delimiters: ['${', '}'],
props: ['subcom'],
template: '<div class="comment"><author>${ subcom.author }</author><content>${ subcom.content }</content><date>${ subcom.date }</date></div>',
methods:{
onshow: function(){
this.subcom.date=String(this.subcom.date).slice(0,-7)
}
},
mounted(){
this.onshow()
}
})
comments=new Vue({
delimiters: ['${', '}'],
el: "#comments",
data:{infos:{}},
methods: {
onshow: function(){
let _this=this
Vue.http.post('/api/getcomment',{id:curPagn},{emulateJSON:true}).then(function(res){
let infos=[];
for (let i in res.body) {
infos.unshift({'id':i,'content':res.body[i]})
}
_this.infos=infos;
}, function(){})
}
},
mounted(){
if(arch=="/article/")this.onshow()
}
})
Vue.component('memo', {
delimiters: ['${', '}'],
props: ['info'],
template: '<div class="well"><author>${ info.content.author }</author><content>${ info.content.content }</content><date>${ info.content.date }</date></div>',
methods:{
onshow: function(){
this.info.content.date=String(this.info.content.date).slice(0,-13)
}
},
mounted(){
this.onshow()
}
})
new Vue({
delimiters: ['${', '}'],
el: "#memopost",
data:{textholder:'留下你的足迹',inputholder:'输入昵称或留空',text:'',author:'',lastTime:0,infos:{}},
methods: {
onshow: function(){
let _this=this
Vue.http.post('/api/getcomment',{id:0},{emulateJSON:true}).then(function(res){
let infos=[];
for (let i in res.body) {
infos.unshift({'id':i,'content':res.body[i]})
}
_this.infos=infos;
}, function(){})
},
post: function(){
var _this=this
if(this.lastTime+10>Math.floor(Date.parse(new Date)/1e3)){
_this.textholder="操作太快了,请稍候..."
return false
}else if(this.text==''){
_this.textholder="内容不能为空"
return false
}
this.lastTime=Math.floor(Date.parse(new Date)/1e3)
token=getToken()
if(_this.author==''){_this.author=getNickName()}
Vue.http.post('/api/postcomment',{author:_this.author,content:_this.text,bid:0,rid:null,timestamp:token.timestamp,md5:token.md5},{emulateJSON:true}).then(function(res){
if(res.body==1){
_this.onshow()
_this.author="";
_this.text="";
_this.textholder="留下你的足迹"
replyId=null;
}
}, function(){})
}
},
mounted(){
if(window.document.location.pathname=="/memo"){
this.onshow()
}
}
})
new Vue({
delimiters: ['${', '}'],
el: "#moon",
data:{textholder:'月池',inputholder:'署名',text:'',author:'',lastTime:0},
methods: {
post: function(){
var _this=this
if(this.lastTime+1000>Math.floor(Date.parse(new Date)/1e3)){return false}
this.lastTime=Math.floor(Date.parse(new Date)/1e3)
token=getToken()
if(_this.author==''){_this.author=getNickName()}
Vue.http.post('/api/postcomment',{author:_this.author,content:_this.text,bid:-1,rid:null,timestamp:token.timestamp,md5:token.md5},{emulateJSON:true}).then(function(res){
if(res.body==1){
_this.author="";
_this.text="";
_this.textholder="许愿完成,祝你好运!"
replyId=null;
}
}, function(){})
}
}
})
new Vue({
delimiters: ['${', '}'],
el: "#sun",
data:{textholder:'日池',inputholder:'署名',text:'',author:'',lastTime:0},
methods: {
post: function(){
var _this=this
if(this.lastTime+1000>Math.floor(Date.parse(new Date)/1e3)){return false}
this.lastTime=Math.floor(Date.parse(new Date)/1e3)
token=getToken()
Vue.http.post('/api/postcomment',{author:_this.author,content:_this.text,bid:-2,rid:null,timestamp:token.timestamp,md5:token.md5},{emulateJSON:true}).then(function(res){
if(res.body==1){
_this.author="";
_this.text="";
_this.textholder="许愿完成,祝你好运!"
replyId=null;
}
}, function(){})
}
}
})
|
/*
* maintenance.c:
*
* Copyright (c) 2009-2016, NIPPON TELEGRAPH AND TELEPHONE CORPORATION
*/
#include "pg_statsinfod.h"
#include <sys/types.h>
#include <sys/wait.h>
#define SQL_DELETE_SNAPSHOT "SELECT statsrepo.del_snapshot2(CAST($1 AS TIMESTAMPTZ))"
#define SQL_DELETE_REPOLOG "SELECT statsrepo.del_repolog2(CAST($1 AS TIMESTAMPTZ))"
typedef struct Maintenance
{
QueueItem base;
bool (*operation)(PGconn *conn, void *param);
time_t period;
} Maintenance;
static bool Maintenance_exec(Maintenance *maintenance, PGconn *conn, const char *instid);
static void Maintenance_free(Maintenance *maintenance);
static bool delete_snapshot(PGconn *conn, void *param);
static bool delete_repolog(PGconn *conn, void *param);
static pid_t forkexec(const char *command, int *fd_err);
/*
* maintenance of the snapshot
*/
void
maintenance_snapshot(time_t repository_keep_period)
{
Maintenance *maintenance;
maintenance = pgut_malloc(sizeof(Maintenance));
maintenance->base.type = QUEUE_MAINTENANCE;
maintenance->base.exec = (QueueItemExec) Maintenance_exec;
maintenance->base.free = (QueueItemFree) Maintenance_free;
maintenance->operation = delete_snapshot;
maintenance->period = repository_keep_period;
writer_send((QueueItem *) maintenance);
}
/*
* maintenance of the log which is in repository
*/
void
maintenance_repolog(time_t repolog_keep_period)
{
Maintenance *maintenance;
maintenance = pgut_malloc(sizeof(Maintenance));
maintenance->base.type = QUEUE_MAINTENANCE;
maintenance->base.exec = (QueueItemExec) Maintenance_exec;
maintenance->base.free = (QueueItemFree) Maintenance_free;
maintenance->operation = delete_repolog;
maintenance->period = repolog_keep_period;
writer_send((QueueItem *) maintenance);
}
/*
* maintenance of the log
*/
pid_t
maintenance_log(const char *command, int *fd_err)
{
char logMaintenanceCmd[MAXPGPATH];
char *dp;
char *endp;
const char *sp;
/* construct the log maintenance command */
dp = logMaintenanceCmd;
endp = logMaintenanceCmd + MAXPGPATH - 1;
*endp = '\0';
for (sp = log_maintenance_command; *sp; sp++)
{
if (*sp == '%')
{
switch (sp[1])
{
case 'l':
/* %l: log directory */
sp++;
if (is_absolute_path(log_directory))
StrNCpy(dp, log_directory, endp - dp);
else
join_path_components(dp, data_directory, log_directory);
dp += strlen(dp);
break;
case '%':
/* convert %% to a single % */
sp++;
if (dp < endp)
*dp++ = *sp;
break;
default:
/* otherwise treat the % as not special */
if (dp < endp)
*dp++ = *sp;
break;
}
}
else
{
if (dp < endp)
*dp++ = *sp;
}
}
*dp = '\0';
/* run the log maintenance command in background */
return forkexec(logMaintenanceCmd, fd_err);
}
#define ERROR_MESSAGE_MAXSIZE 256
/*
* check the status of log maintenance command running in background
*/
bool
check_maintenance_log(pid_t log_maintenance_pid, int fd_err)
{
int status;
switch (waitpid(log_maintenance_pid, &status, WNOHANG))
{
case -1: /* error */
elog(ERROR,
"failed to wait of the log maintenance command: %s", strerror(errno));
close(fd_err);
return true;
case 0: /* running */
elog(DEBUG2, "log maintenance command is running");
return false;
default: /* completed */
if (status != 0)
{
/* command exit value is abnormally code */
ssize_t read_size;
char errmsg[ERROR_MESSAGE_MAXSIZE];
if((read_size = read(fd_err, errmsg, sizeof(errmsg) - 1)) >= 0)
errmsg[read_size] = '\0';
else
{
elog(ERROR, "read() on self-pipe failed: %s", strerror(errno));
errmsg[0] = '\0';
}
if (WIFEXITED(status))
elog(ERROR,
"log maintenance command failed with exit code %d: %s",
WEXITSTATUS(status), errmsg);
else if (WIFSIGNALED(status))
elog(ERROR,
"log maintenance command was terminated by signal %d: %s",
WTERMSIG(status), errmsg);
else
elog(ERROR,
"log maintenance command exited with unrecognized status %d: %s",
status, errmsg);
}
close(fd_err);
return true;
}
}
static bool
delete_snapshot(PGconn *conn, void *param)
{
const char *params[1];
ExecStatusType status;
params[0] = (const char *) param;
/* exclusive control during snapshot and maintenance */
pthread_mutex_lock(&maintenance_lock);
status = pgut_command(conn, SQL_DELETE_SNAPSHOT, 1, params);
pthread_mutex_unlock(&maintenance_lock);
return status == PGRES_TUPLES_OK;
}
static bool
delete_repolog(PGconn *conn, void *param)
{
const char *params[1];
params[0] = (const char *) param;
if (pgut_command(conn, SQL_DELETE_REPOLOG, 1, params) != PGRES_TUPLES_OK)
return false;
return true;
}
static bool
Maintenance_exec(Maintenance *maintenance, PGconn *conn, const char *instid)
{
char timestamp[32];
strftime(timestamp, sizeof(timestamp),
"%Y-%m-%d %H:%M:%S", localtime(&maintenance->period));
return maintenance->operation(conn, timestamp);
}
static void
Maintenance_free(Maintenance *maintenance)
{
free(maintenance);
}
#define R (0)
#define W (1)
/*
* execute a shell command asynchronously
*/
static pid_t
forkexec(const char *command, int *fd_err)
{
pid_t cpid;
int pipe_fd_err[2];
/* create pipes */
if (pipe(pipe_fd_err) < 0)
{
elog(ERROR, "could not create pipe: %s", strerror(errno));
return -1;
}
/* invoke processs */
if ((cpid = fork()) < 0)
{
close(pipe_fd_err[R]);
close(pipe_fd_err[W]);
elog(ERROR, "fork failed: %s", strerror(errno));
return -1;
}
if (cpid == 0)
{
/* in child process */
close(pipe_fd_err[R]);
dup2(pipe_fd_err[W], STDERR_FILENO);
close(pipe_fd_err[W]);
execlp("/bin/sh", "sh", "-c", command, NULL);
_exit(127);
}
close(pipe_fd_err[W]);
*fd_err = pipe_fd_err[R];
return cpid;
}
|
import numpy as np
from astropy import units as u
from poliastro.twobody.angles import E_to_nu, nu_to_E
from poliastro.util import alinspace
@u.quantity_input(min_nu=u.rad, ecc=u.one, max_nu=u.rad)
def sample_closed(min_nu, ecc, max_nu=None, num_values=100):
"""Sample a closed orbit
If ``max_nu`` is given, the sampling interval will go
from the minimum to the maximum true anomaly in the direction of the orbit.
If not given, it will do a full revolution starting in the minimum true anomaly.
Notes
-----
First sample the eccentric anomaly uniformly,
then transform into true anomaly
to minimize error in the apocenter,
see https://apps.dtic.mil/dtic/tr/fulltext/u2/a605040.pdf
"""
# Because how nu_to_E works, we don't need to wrap the angle here!
# It will do the right thing
min_E = nu_to_E(min_nu, ecc)
# This linspace will always increase positively,
# even though it might contain out of range values
E_values = alinspace(
min_E, nu_to_E(max_nu, ecc) if max_nu is not None else None, num=num_values
)
# Because how E_to_nu works, we don't need to wrap the angles here!
# It will do the right thing
nu_values = E_to_nu(E_values, ecc)
# We wrap the angles on return
return (nu_values + np.pi * u.rad) % (2 * np.pi * u.rad) - np.pi * u.rad
|
/* -*- Mode: Javascript; indent-tabs-mode:nil; js-indent-level: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*************************************************************
*
* MathJax/extensions/TeX/mathchoice.js
*
* Implements the \mathchoice macro (rarely used)
*
* ---------------------------------------------------------------------
*
* Copyright (c) 2009-2018 The MathJax Consortium
*
* 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.
*/
MathJax.Hub.Register.StartupHook("TeX Jax Ready",function () {
var VERSION = "2.7.3";
var MML = MathJax.ElementJax.mml;
var TEX = MathJax.InputJax.TeX;
var TEXDEF = TEX.Definitions;
TEXDEF.Add({macros: {mathchoice: 'MathChoice'}},null,true);
TEX.Parse.Augment({
MathChoice: function (name) {
var D = this.ParseArg(name),
T = this.ParseArg(name),
S = this.ParseArg(name),
SS = this.ParseArg(name);
this.Push(MML.TeXmathchoice(D,T,S,SS));
}
});
MML.TeXmathchoice = MML.mbase.Subclass({
type: "TeXmathchoice", notParent: true,
choice: function () {
if (this.selection != null) return this.selection;
if (this.choosing) return 2; // prevent infinite loops: see issue #1151
this.choosing = true;
var selection = 0, values = this.getValues("displaystyle","scriptlevel");
if (values.scriptlevel > 0) {selection = Math.min(3,values.scriptlevel+1)}
else {selection = (values.displaystyle ? 0 : 1)}
// only cache the result if we are actually in place in a <math> tag.
var node = this.inherit; while (node && node.type !== "math") node = node.inherit;
if (node) this.selection = selection;
this.choosing = false;
return selection;
},
selected: function () {return this.data[this.choice()]},
setTeXclass: function (prev) {return this.selected().setTeXclass(prev)},
isSpacelike: function () {return this.selected().isSpacelike()},
isEmbellished: function () {return this.selected().isEmbellished()},
Core: function () {return this.selected()},
CoreMO: function () {return this.selected().CoreMO()},
toHTML: function (span) {
span = this.HTMLcreateSpan(span);
span.bbox = this.Core().toHTML(span).bbox;
// Firefox doesn't correctly handle a span with a negatively sized content,
// so move marginLeft to main span (this is a hack to get \iiiint to work).
// FIXME: This is a symptom of a more general problem with Firefox, and
// there probably needs to be a more general solution (e.g., modifying
// HTMLhandleSpace() to get the width and adjust the right margin to
// compensate for negative-width contents)
if (span.firstChild && span.firstChild.style.marginLeft) {
span.style.marginLeft = span.firstChild.style.marginLeft;
span.firstChild.style.marginLeft = "";
}
return span;
},
toSVG: function () {
var svg = this.Core().toSVG();
this.SVGsaveData(svg);
return svg;
},
toCommonHTML: function (node) {
node = this.CHTMLcreateNode(node);
this.CHTMLhandleStyle(node);
this.CHTMLhandleColor(node);
this.CHTMLaddChild(node,this.choice(),{});
return node;
},
toPreviewHTML: function(span) {
span = this.PHTMLcreateSpan(span);
this.PHTMLhandleStyle(span);
this.PHTMLhandleColor(span);
this.PHTMLaddChild(span,this.choice(),{});
return span;
}
});
MathJax.Hub.Startup.signal.Post("TeX mathchoice Ready");
});
MathJax.Ajax.loadComplete("[MathJax]/extensions/TeX/mathchoice.js");
|
/**
*
* \file
*
* \brief This file is a skeleton for developing Ethernet network interface
* drivers for lwIP. Add code to the low_level functions and do a
* search-and-replace for the word "ethernetif" to replace it with
* something that better describes your network interface.
*
* Copyright (c) 2013-2018 Microchip Technology Inc. and its subsidiaries.
*
* \asf_license_start
*
* \page License
*
* Subject to your compliance with these terms, you may use Microchip
* software and any derivatives exclusively with Microchip products.
* It is your responsibility to comply with third party license terms applicable
* to your use of third party software (including open source software) that
* may accompany Microchip software.
*
* THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES,
* WHETHER EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE,
* INCLUDING ANY IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY,
* AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT WILL MICROCHIP BE
* LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE, INCIDENTAL OR CONSEQUENTIAL
* LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND WHATSOEVER RELATED TO THE
* SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS BEEN ADVISED OF THE
* POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE FULLEST EXTENT
* ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN ANY WAY
* RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY,
* THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE.
*
* \asf_license_stop
*
*/
#include "lwip/opt.h"
#include "lwip/def.h"
#include "lwip/mem.h"
#include "lwip/pbuf.h"
#include "lwip/sys.h"
#include <lwip/stats.h>
#include <lwip/snmp.h>
#include "netif/etharp.h"
#include "netif/ppp_oe.h"
#include "pmc.h"
#include "gmac.h"
#include "ethernet_phy.h"
#include "netif/ethernetif.h"
#include "sysclk.h"
#include <string.h>
#include "conf_eth.h"
#include "ioport.h"
/** Define those to better describe your network interface */
#define IFNAME0 'e'
#define IFNAME1 'n'
/** Maximum transfer unit */
#define NET_MTU 1500
/** Network link speed */
#define NET_LINK_SPEED 100000000
/** Read/write buffer size for lwIP */
#define NET_RW_BUFF_SIZE 1536
/* Interrupt priorities. (lowest value = highest priority) */
/* ISRs using FreeRTOS *FromISR APIs must have priorities below or equal to */
/* configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY. */
#define INT_PRIORITY_GMAC 12
#if LWIP_STATS
/** Used to compute LwIP bandwidth */
uint32_t lwip_tx_count = 0;
uint32_t lwip_rx_count = 0;
uint32_t lwip_tx_rate = 0;
uint32_t lwip_rx_rate = 0;
uint32_t lwip_eth_tx_cur = 0;
uint32_t lwip_eth_tx_max = 0;
uint32_t lwip_eth_tx_err = 0;
uint32_t lwip_eth_rx_cur = 0;
uint32_t lwip_eth_rx_max = 0;
uint32_t lwip_eth_rx_err = 0;
#endif
/** The MAC address used for the test */
static uint8_t gs_uc_mac_address[] =
{ ETHERNET_CONF_ETHADDR0, ETHERNET_CONF_ETHADDR1, ETHERNET_CONF_ETHADDR2,
ETHERNET_CONF_ETHADDR3, ETHERNET_CONF_ETHADDR4, ETHERNET_CONF_ETHADDR5};
/** The GMAC driver instance */
static gmac_device_t gs_gmac_dev;
/**
* Helper struct to hold private data used to operate your ethernet interface.
* Keeping the ethernet address of the MAC in this struct is not necessary
* as it is already kept in the struct netif.
* But this is only an example, anyway...
*/
struct ethernetif {
struct eth_addr *ethaddr;
/* Add whatever per-interface state that is needed here. */
};
/**
* \brief GMAC interrupt handler.
*/
void GMAC_Handler(void)
{
gmac_handler(&gs_gmac_dev);
}
/**
* \brief In this function, the hardware should be initialized.
* Called from ethernetif_init().
*
* \param netif the already initialized lwip network interface structure
* for this ethernetif
*/
static void low_level_init(struct netif *netif)
{
volatile uint32_t ul_dealy;
gmac_options_t gmac_option;
#ifdef FREERTOS_USED
unsigned portBASE_TYPE uxPriority;
#endif
/* Set MAC hardware address length */
netif->hwaddr_len = sizeof(gs_uc_mac_address);
/* Set MAC hardware address */
netif->hwaddr[0] = gs_uc_mac_address[0];
netif->hwaddr[1] = gs_uc_mac_address[1];
netif->hwaddr[2] = gs_uc_mac_address[2];
netif->hwaddr[3] = gs_uc_mac_address[3];
netif->hwaddr[4] = gs_uc_mac_address[4];
netif->hwaddr[5] = gs_uc_mac_address[5];
/* Maximum transfer unit */
netif->mtu = NET_MTU;
/* device capabilities */
/* don't set NETIF_FLAG_ETHARP if this device is not an ethernet one */
netif->flags |= NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP
#if defined(DHCP_USED)
| NETIF_FLAG_DHCP
#endif
;
#ifdef FREERTOS_USED
/*
* NOTE: This routine contains code that polls status bits. If the Ethernet
* cable is not plugged in then this can take a considerable time. To prevent
* this from starving lower priority tasks of processing time we lower our
* priority prior to the call, then raise it back again once the initialization
* is complete.
*/
/* Read the priority of the current task. */
uxPriority = uxTaskPriorityGet( NULL );
/* Set the priority of the current task to the lowest possible. */
vTaskPrioritySet( NULL, tskIDLE_PRIORITY +3);
#endif
/* Wait for PHY to be ready (CAT811: Max400ms) */
ul_dealy = sysclk_get_cpu_hz() / 6;
while (ul_dealy--) {
}
/* Enable GMAC clock */
pmc_enable_periph_clk(ID_GMAC);
/* Fill in GMAC options */
gmac_option.uc_copy_all_frame = 0;
gmac_option.uc_no_boardcast = 0;
memcpy(gmac_option.uc_mac_addr, gs_uc_mac_address,
sizeof(gs_uc_mac_address));
gs_gmac_dev.p_hw = GMAC;
/* Init GMAC driver structure */
gmac_dev_init(GMAC, &gs_gmac_dev, &gmac_option);
/* Enable Interrupt */
NVIC_SetPriority(GMAC_IRQn, INT_PRIORITY_GMAC);
NVIC_EnableIRQ(GMAC_IRQn);
/* Init MAC PHY driver */
if (ethernet_phy_init(GMAC, BOARD_GMAC_PHY_ADDR, sysclk_get_cpu_hz()) != GMAC_OK) {
LWIP_DEBUGF(LWIP_DBG_TRACE, ("PHY Initialize ERROR!\r\n"));
return;
}
/* Auto Negotiate, work in RMII mode */
if (ethernet_phy_auto_negotiate(GMAC, BOARD_GMAC_PHY_ADDR) != GMAC_OK) {
LWIP_DEBUGF(LWIP_DBG_TRACE, ("Auto Negotiate ERROR!\r\n"));
return;
}
/* Establish ethernet link */
while (ethernet_phy_set_link(GMAC, BOARD_GMAC_PHY_ADDR, 1) != GMAC_OK) {
LWIP_DEBUGF(LWIP_DBG_TRACE, ("Set link ERROR!\r\n"));
}
#ifdef FREERTOS_USED
/* Restore the priority of the current task. */
vTaskPrioritySet( NULL, uxPriority );
/* Create the task that handles the GMAC input packets. */
sys_thread_new( "ETHINT", ethernetif_input, netif,
netifINTERFACE_TASK_STACK_SIZE,
netifINTERFACE_TASK_PRIORITY );
#endif
}
/**
* \brief This function should do the actual transmission of the packet. The
* packet is contained in the pbuf that is passed to the function. This pbuf
* might be chained.
* note: Returning ERR_MEM here if a DMA queue of your MAC is full can lead to
* strange results. You might consider waiting for space in the DMA queue
* to become available since the stack doesn't retry to send a packet
* dropped because of memory failure (except for the TCP timers).
*
* \param netif the lwip network interface structure for this ethernetif
* \param p the MAC packet to send (e.g. IP packet including MAC addresses and type)
*
* \return ERR_OK if the packet could be sent
* an err_t value if the packet couldn't be sent.
*/
static err_t low_level_output(struct netif *netif, struct pbuf *p)
{
struct pbuf *q = NULL;
int8_t pc_buf[NET_RW_BUFF_SIZE];
int8_t *bufptr = &pc_buf[0];
uint8_t uc_rc;
#if ETH_PAD_SIZE
pbuf_header(p, -ETH_PAD_SIZE); /* Drop the padding word */
#endif
/* Check the buffer boundary */
if (p->tot_len > NET_RW_BUFF_SIZE) {
return ERR_BUF;
}
/* Clear the output buffer */
// memset(bufptr, 0x0, NET_RW_BUFF_SIZE);
for (q = p; q != NULL; q = q->next) {
/* Send the data from the pbuf to the interface, one pbuf at a
* time. The size of the data in each pbuf is kept in the ->len
* variable. */
/* Send data from(q->payload, q->len); */
memcpy(bufptr, q->payload, q->len);
bufptr += q->len;
}
/* Signal that packet should be sent(); */
uc_rc = gmac_dev_write(&gs_gmac_dev, pc_buf, p->tot_len, NULL);
if (uc_rc != GMAC_OK) {
#if LWIP_STATS
lwip_eth_tx_err += 1;
#endif
return ERR_BUF;
}
#if LWIP_STATS
lwip_tx_count += p->tot_len;
lwip_eth_tx_cur = gmac_dev_tx_buf_used(&gs_gmac_dev);
if (lwip_eth_tx_cur > lwip_eth_tx_max)
lwip_eth_tx_max = lwip_eth_tx_cur;
#endif
#if ETH_PAD_SIZE
pbuf_header(p, ETH_PAD_SIZE); /* Reclaim the padding word */
#endif
LINK_STATS_INC(link.xmit);
return ERR_OK;
}
/**
* \brief Should allocate a pbuf and transfer the bytes of the incoming
* packet from the interface into the pbuf.
*
* \param netif the lwip network interface structure for this ethernetif.
*
* \return a pbuf filled with the received packet (including MAC header)
* NULL on memory error.
*/
static struct pbuf *low_level_input(struct netif *netif)
{
struct pbuf *p = NULL, *q = NULL;
u16_t s_len;
uint8_t pc_buf[NET_RW_BUFF_SIZE];
int8_t *bufptr = (int8_t *)&pc_buf[0];
uint32_t ul_frmlen;
uint8_t uc_rc;
(void)netif;
/* Obtain the size of the packet and put it into the "len"
* variable. */
uc_rc = gmac_dev_read(&gs_gmac_dev, pc_buf, sizeof(pc_buf), &ul_frmlen);
if (uc_rc != GMAC_OK) {
#if LWIP_STATS
if (uc_rc == GMAC_RX_ERROR)
lwip_eth_rx_err += 1;
#endif
return NULL;
}
#if LWIP_STATS
lwip_rx_count += ul_frmlen;
lwip_eth_rx_cur = gmac_dev_rx_buf_used(&gs_gmac_dev);
if (lwip_eth_rx_cur > lwip_eth_rx_max)
lwip_eth_rx_max = lwip_eth_rx_cur;
#endif
s_len = ul_frmlen;
#if ETH_PAD_SIZE
s_len += ETH_PAD_SIZE; /* allow room for Ethernet padding */
#endif
/* We allocate a pbuf chain of pbufs from the pool. */
p = pbuf_alloc(PBUF_RAW, s_len, PBUF_POOL);
if (p != NULL) {
#if ETH_PAD_SIZE
pbuf_header(p, -ETH_PAD_SIZE); /* drop the padding word */
#endif
/* Iterate over the pbuf chain until we have read the entire
* packet into the pbuf. */
for (q = p; q != NULL; q = q->next) {
/* Read enough bytes to fill this pbuf in the chain. The
* available data in the pbuf is given by the q->len
* variable. */
/* read data into(q->payload, q->len); */
memcpy(q->payload, bufptr, q->len);
bufptr += q->len;
}
/* Acknowledge that packet has been read(); */
#if ETH_PAD_SIZE
pbuf_header(p, ETH_PAD_SIZE); /* Reclaim the padding word */
#endif
LINK_STATS_INC(link.recv);
} else {
/* Drop packet(); */
LINK_STATS_INC(link.memerr);
LINK_STATS_INC(link.drop);
}
return p;
}
#ifdef FREERTOS_USED
extern xSemaphoreHandle netif_notification_semaphore;
#endif
/**
* \brief This function should be called when a packet is ready to be
* read from the interface. It uses the function low_level_input()
* that should handle the actual reception of bytes from the network
* interface. Then the type of the received packet is determined and
* the appropriate input function is called.
*
* \param pv_parameters the lwip network interface structure for this
* ethernetif.
*/
void ethernetif_input(void * pvParameters)
{
struct netif *netif = (struct netif *)pvParameters;
struct pbuf *p = NULL;
#ifdef FREERTOS_USED
for ( ;; )
{
while (p == NULL)
{
if (xSemaphoreTake(netif_notification_semaphore, portMAX_DELAY))
{
/* Move received packet into a new pbuf. */
p = low_level_input(netif);
}
}
if (ERR_OK != netif->input(p, netif))
{
pbuf_free(p);
}
/* At this point, buffer is either consumed or freed, so don't care. */
p = NULL;
}
#else
/* Move received packet into a new pbuf. */
p = low_level_input(netif);
if (p == NULL)
{
return;
}
if (ERR_OK != netif->input(p, netif))
{
pbuf_free(p);
p = NULL;
}
#endif
}
/**
* \brief Should be called at the beginning of the program to set up the
* network interface. It calls the function low_level_init() to do the
* actual setup of the hardware.
*
* This function should be passed as a parameter to netif_add().
*
* \param netif the lwip network interface structure for this ethernetif.
*
* \return ERR_OK if the loopif is initialized
* ERR_MEM if private data couldn't be allocated
* any other err_t on error.
*/
err_t ethernetif_init(struct netif *netif)
{
LWIP_ASSERT("netif != NULL", (netif != NULL));
#if LWIP_NETIF_HOSTNAME
/* Initialize interface hostname */
netif->hostname = "lwip";
#endif /* LWIP_NETIF_HOSTNAME */
/*
* Initialize the snmp variables and counters inside the struct netif.
* The last argument should be replaced with your link speed, in units
* of bits per second.
*/
#if LWIP_SNMP
NETIF_INIT_SNMP(netif, snmp_ifType_ethernet_csmacd, NET_LINK_SPEED);
#endif /* LWIP_SNMP */
netif->state = NULL;
netif->name[0] = IFNAME0;
netif->name[1] = IFNAME1;
/* We directly use etharp_output() here to save a function call.
* You can instead declare your own function an call etharp_output()
* from it if you have to do some checks before sending (e.g. if link
* is available...) */
netif->output = etharp_output;
netif->linkoutput = low_level_output;
/* Initialize the hardware */
low_level_init(netif);
return ERR_OK;
}
|
/*
* Copyright © 2019, SAS Institute Inc., Cary, NC, USA. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
import React from "react";
import SimpleTableFromJsonp from "./SimpleTableFromJsonp";
import DisplayODSp from "./DisplayODSp";
import Select from "react-select";
import queryGraphql from "../queryGraphql";
function WineAppp(props) {
const { useState } = React;
let [selections, setSelections] = useState(null);
let [reportSelection, setReportSelection] = useState(null);
let [fromYear, setFromYearSelection] = useState(null);
let [toYear, setToYearSelection] = useState(null);
let [resultValues, setResultValues] = useState(null);
let [reportValues, setReportValues] = useState(null);
let [graphqlQuery] = useState(props.graphqlQuery);
let [products] = useState(props.products);
let [showReport] = useState(props.report);
let [years] = useState(props.years);
let [productType] = useState(props.productType);
let [productTitle] = useState(props.productTitle);
let [errors, setError] = useState(null);
let { host } = props;
const report = [
{ value: "ods", label: "ODS" },
{ value: "log", label: "Log" }
];
//
// TBD:
// Get all the hard-coded product values from the server using graphql
// and make the calls using useEffect
//
const _onSelection = selectedValues => {
setSelections(selectedValues.length > 0 ? selectedValues : null);
};
const _onReportSelection = selectedValues => {
setReportSelection(selectedValues.length > 0 ? selectedValues : null);
};
const _onFromYearSelection = selectedValues => {
setFromYearSelection(selectedValues);
};
const _onToYearSelection = selectedValues => {
setToYearSelection(selectedValues);
};
const _onSubmit = () => {
if (selections === null || fromYear === null || toYear === null) {
alert("Missing Information");
return;
}
let qvars = "";
if (selections !== null) {
selections.forEach(r => {
qvars = qvars + " " + r.value;
});
}
let rvars = "";
if (reportSelection !== null) {
rvars = "report {";
reportSelection.forEach(r => {
rvars = rvars + " " + r.value;
});
rvars = rvars + " }";
}
const resultcb = (r) => {
setResultValues(r[productType]);
if (r.report != null) {
setReportValues(r.report);
}
}
let gqString = `query ${graphqlQuery}($from: Int, $to: Int){
results: ${graphqlQuery}(from: $from, to: $to) {
${productType} {
${qvars}
}
${rvars}
}
}`;
let filter = {
from: fromYear.value,
to : toYear.value
};
setReportValues(null);
setResultValues(null);
debugger;
queryGraphql(host, gqString, filter, resultcb, setError);
};
let show = (
<div className="container">
<div className="form-group form-group-sm">
<div className="col-md-6">
<div className="form-group">
<small id="fromsel"> From</small>
<Select
value={fromYear}
onChange={_onFromYearSelection}
options={years}
closeMenuOnSelect={true}
/>
</div>
<div className="form-group">
<small id="tosel"> To</small>
<Select
value={toYear}
onChange={_onToYearSelection}
options={years}
closeMenuOnSelect={true}
/>
</div>
<div className="form-group">
<small id="helpsel"> {productTitle}</small>
<Select
value={selections}
isMulti={true}
onChange={_onSelection}
options={products}
closeMenuOnSelect={false}
isOpen={true}
/>
</div>
{showReport === true ? (
<div className="form-group">
<small id="repsel"> Report Options</small>
<Select
value={reportSelection}
isMulti={true}
onChange={_onReportSelection}
options={report}
closeMenuOnSelect={false}
isOpen={true}
/>
</div>
) : null}
</div>
</div>
<button className="btn btn-primary" onClick={_onSubmit}>
Submit
</button>
<br />
{errors}
<div>
{resultValues !== null ? (
<SimpleTableFromJsonp data={resultValues} />
) : null}
</div>
<br />
<div>
{reportValues !== null && reportValues.ods !== null ? (
<DisplayODSp odsHTML={reportValues.ods}> </DisplayODSp>
) : null}
</div>
<br />
<div>
{reportValues !== null && reportValues.log !== null ? (
<DisplayODSp odsHTML={reportValues.log} />
) : null}
</div>
</div>
);
return show;
}
export default WineAppp;
|
/*global describe, it, require*/
import { File, Types } from "../lib/core/file";
let ContractsManager = require('embark-contracts-manager');
let Compiler = require('embark-compiler');
let Logger = require('embark-logger');
let TestLogger = require('../lib/utils/test_logger');
let Events = require('../lib/core/events');
let Ipc = require('../lib/core/ipc.js');
let assert = require('assert');
//let SolidityCompiler = require('../lib/modules/solidity');
let Plugins = require('../lib/core/plugins.js');
let readFile = function(file) {
return new File({filename: file, type: Types.dappFile, path: file});
};
const currentSolcVersion = require('../../package.json').dependencies.solc;
const TestEvents = {
request: (cmd, cb) => {
cb(currentSolcVersion);
},
emit: (_ev, _data) => {}
};
describe('embark.Contracts', function() {
this.timeout(0);
describe('simple', function() {
let plugins = new Plugins({
logger: new TestLogger({}),
events: TestEvents,
config: {
contractDirectories: ['app/contracts/'],
embarkConfig: {
options: {
solc: {
"optimize": true,
"optimize-runs": 200
}
}
}
}
});
let ipcObject = new Ipc({
ipcRole: 'none'
});
plugins.loadInternalPlugin('solidity', {ipc: ipcObject});
let events = new Events();
let embarkObject = {
registerAPICall: () => {},
events: events,
fs: {
existsSync: () => { return false },
dappPath: () => { return "ok" }
},
logger: plugins.logger,
embarkConfig: {
options: {
solc: {
"optimize": true,
"optimize-runs": 200
}
}
}
};
let compiler = new Compiler(embarkObject, {plugins: plugins});
let contractsConfig;
events.setCommandHandler("config:contractsConfig", function(cb) {
cb(contractsConfig);
});
events.setCommandHandler("config:contractsFiles", (cb) => {
cb([
readFile('contracts/simple_storage.sol'),
readFile('contracts/token.sol')
]);
});
events.setCommandHandler("blockchain:gasPrice", (cb) => {
cb(null, 100);
});
contractsConfig = {
"versions": {
"web3.js": "1.0.0-beta",
"solc": "0.4.17"
},
"deployment": {
"host": "localhost",
"port": 8545,
"type": "rpc"
},
"dappConnection": [
"$WEB3",
"localhost:8545"
],
"gas": "auto",
"contracts": {
"Token": {
"args": [
100
]
},
"SimpleStorage": {
"args": [
200
]
}
}
};
let embarkObj = {
registerAPICall: () => {},
fs: {
existsSync: () => { return false },
dappPath: () => { return "ok" }
},
logger: new Logger({}),
events: events
};
let contractsManager = new ContractsManager(embarkObj, {
plugins: plugins,
contractDirectories: ['app/contracts']
});
describe('#build', function() {
it('generate contracts', function(done) {
contractsManager.build(function(err, result) {
if (err) {
throw err;
}
let contracts = contractsManager.listContracts();
assert.equal(contracts.length, 2);
assert.equal(contracts[0].deploy, true);
assert.deepEqual(contracts[0].args, [100]);
assert.equal(contracts[0].className, "Token");
//assert.deepEqual(contracts[0].gas, 725000);
assert.deepEqual(contracts[0].gas, 'auto');
//assert.equal(contracts[0].gasPrice, []); // TODO: test this one
assert.equal(contracts[0].type, 'file');
//assert.equal(contracts[0].abiDefinition, '');
//assert.equal(contracts[0].code, '');
//assert.equal(contracts[0].runtimeBytecode, '');
assert.equal(contracts[1].deploy, true);
assert.deepEqual(contracts[1].args, [200]);
assert.equal(contracts[1].className, "SimpleStorage");
//assert.deepEqual(contracts[1].gas, 725000);
assert.deepEqual(contracts[1].gas, 'auto');
//assert.equal(contracts[1].gasPrice, []); // TODO: test this one
assert.equal(contracts[1].type, 'file');
//assert.equal(contracts[1].abiDefinition, '');
//assert.equal(contracts[1].code, '');
//assert.equal(contracts[1].runtimeBytecode, '');
done();
});
});
});
});
describe('config with contract instances', function() {
let plugins = new Plugins({
logger: new TestLogger({}),
events: TestEvents,
config: {
contractDirectories: ['app/contracts/'],
embarkConfig: {
options: {
solc: {
"optimize": true,
"optimize-runs": 200
}
}
}
}
});
let ipcObject = new Ipc({
ipcRole: 'none'
});
plugins.loadInternalPlugin('solidity', {ipc: ipcObject});
let events = new Events();
let compiler = new Compiler({events: events, logger: plugins.logger}, {plugins: plugins});
let contractsConfig;
events.setCommandHandler("config:contractsConfig", function(cb) {
cb(contractsConfig);
});
events.setCommandHandler("config:contractsFiles", (cb) => {
cb([
readFile('contracts/simple_storage.sol'),
readFile('contracts/token_storage.sol')
]);
});
events.setCommandHandler("blockchain:gasPrice", (cb) => {
cb(null, 100);
});
contractsConfig = {
"versions": {
"web3.js": "1.0.0-beta",
"solc": "0.4.17"
},
"deployment": {
"host": "localhost",
"port": 8545,
"type": "rpc"
},
"dappConnection": [
"$WEB3",
"localhost:8545"
],
"gas": "auto",
"contracts": {
"TokenStorage": {
"args": [
100,
"$SimpleStorage"
]
},
"MySimpleStorage": {
"instanceOf": "SimpleStorage",
"args": [
300
]
},
"SimpleStorage": {
"args": [
200
]
},
"AnotherSimpleStorage": {
"instanceOf": "SimpleStorage"
}
}
};
let embarkObj = {
registerAPICall: () => {},
fs: {
existsSync: () => { return false },
dappPath: () => { return "ok" }
},
logger: new Logger({}),
events: events
};
let contractsManager = new ContractsManager(embarkObj, {
plugins: plugins,
contractDirectories: ['app/contracts']
});
describe('#build', function() {
it('generate contracts', function(done) {
contractsManager.build(function(err, result) {
if (err) {
throw err;
}
let contracts = contractsManager.listContracts();
assert.equal(contracts.length, 4);
assert.equal(contracts[0].className, "MySimpleStorage");
assert.equal(contracts[1].className, "AnotherSimpleStorage");
assert.equal(contracts[2].className, "SimpleStorage");
assert.equal(contracts[3].className, "TokenStorage");
// TokenStorage
assert.equal(contracts[3].deploy, true);
assert.deepEqual(contracts[3].args, [100, '$SimpleStorage']);
//assert.deepEqual(contracts[3].gas, 725000);
assert.deepEqual(contracts[3].gas, 'auto');
assert.equal(contracts[3].type, 'file');
//assert.equal(contracts[3].abiDefinition, '');
//assert.equal(contracts[3].code, '');
//assert.equal(contracts[3].runtimeBytecode, '');
let parentContract = contracts[2];
//MySimpleStorage
assert.equal(contracts[0].deploy, true);
assert.deepEqual(contracts[0].args, [300]);
//assert.deepEqual(contracts[0].gas, 725000);
assert.deepEqual(contracts[0].gas, 'auto');
assert.equal(contracts[0].type, 'instance');
assert.equal(contracts[0].abiDefinition, parentContract.abiDefinition);
assert.equal(contracts[0].code, parentContract.code);
assert.equal(contracts[0].runtimeBytecode, parentContract.runtimeBytecode);
// SimpleStorage
assert.equal(contracts[2].deploy, true);
assert.deepEqual(contracts[2].args, [200]);
//assert.deepEqual(contracts[2].gas, 725000);
assert.deepEqual(contracts[2].gas, 'auto');
assert.equal(contracts[2].type, 'file');
//assert.equal(contracts[2].abiDefinition, '');
//assert.equal(contracts[2].code, '');
//assert.equal(contracts[2].runtimeBytecode, '');
// AnotherSimpleStorage
assert.equal(contracts[1].deploy, true);
assert.deepEqual(contracts[1].args, [200]);
//assert.deepEqual(contracts[1].gas, 725000);
assert.deepEqual(contracts[1].gas, 'auto');
assert.equal(contracts[1].type, 'instance');
assert.equal(contracts[1].abiDefinition, parentContract.abiDefinition);
assert.equal(contracts[1].code, parentContract.code);
assert.equal(contracts[1].runtimeBytecode, parentContract.runtimeBytecode);
done();
});
});
});
});
});
|
"""Utilities for file download and caching."""
from __future__ import absolute_import
from __future__ import print_function
import functools
import tarfile
import os
import sys
import shutil
import hashlib
from six.moves.urllib.request import urlopen
from six.moves.urllib.error import URLError
from six.moves.urllib.error import HTTPError
from ..utils.generic_utils import Progbar
if sys.version_info[0] == 2:
def urlretrieve(url, filename, reporthook=None, data=None):
"""Replacement for `urlretrive` for Python 2.
Under Python 2, `urlretrieve` relies on `FancyURLopener` from legacy
`urllib` module, known to have issues with proxy management.
# Arguments
url: url to retrieve.
filename: where to store the retrieved data locally.
reporthook: a hook function that will be called once
on establishment of the network connection and once
after each block read thereafter.
The hook will be passed three arguments;
a count of blocks transferred so far,
a block size in bytes, and the total size of the file.
data: `data` argument passed to `urlopen`.
"""
def chunk_read(response, chunk_size=8192, reporthook=None):
total_size = response.info().get('Content-Length').strip()
total_size = int(total_size)
count = 0
while 1:
chunk = response.read(chunk_size)
count += 1
if not chunk:
reporthook(count, total_size, total_size)
break
if reporthook:
reporthook(count, chunk_size, total_size)
yield chunk
response = urlopen(url, data)
with open(filename, 'wb') as fd:
for chunk in chunk_read(response, reporthook=reporthook):
fd.write(chunk)
else:
from six.moves.urllib.request import urlretrieve
def get_file(fname, origin, untar=False,
md5_hash=None, cache_subdir='datasets'):
"""Downloads a file from a URL if it not already in the cache.
Passing the MD5 hash will verify the file after download
as well as if it is already present in the cache.
# Arguments
fname: name of the file
origin: original URL of the file
untar: boolean, whether the file should be decompressed
md5_hash: MD5 hash of the file for verification
cache_subdir: directory being used as the cache
# Returns
Path to the downloaded file
"""
datadir_base = os.path.expanduser(os.path.join('~', '.keras'))
if not os.access(datadir_base, os.W_OK):
datadir_base = os.path.join('/tmp', '.keras')
datadir = os.path.join(datadir_base, cache_subdir)
if not os.path.exists(datadir):
os.makedirs(datadir)
if untar:
untar_fpath = os.path.join(datadir, fname)
fpath = untar_fpath + '.tar.gz'
else:
fpath = os.path.join(datadir, fname)
download = False
if os.path.exists(fpath):
# File found; verify integrity if a hash was provided.
if md5_hash is not None:
if not validate_file(fpath, md5_hash):
print('A local file was found, but it seems to be '
'incomplete or outdated.')
download = True
else:
download = True
if download:
print('Downloading data from', origin)
progbar = None
def dl_progress(count, block_size, total_size, progbar=None):
if progbar is None:
progbar = Progbar(total_size)
else:
progbar.update(count * block_size)
error_msg = 'URL fetch failure on {}: {} -- {}'
try:
try:
urlretrieve(origin, fpath,
functools.partial(dl_progress, progbar=progbar))
except URLError as e:
raise Exception(error_msg.format(origin, e.errno, e.reason))
except HTTPError as e:
raise Exception(error_msg.format(origin, e.code, e.msg))
except (Exception, KeyboardInterrupt) as e:
if os.path.exists(fpath):
os.remove(fpath)
raise
progbar = None
if untar:
if not os.path.exists(untar_fpath):
print('Untaring file...')
tfile = tarfile.open(fpath, 'r:gz')
try:
tfile.extractall(path=datadir)
except (Exception, KeyboardInterrupt) as e:
if os.path.exists(untar_fpath):
if os.path.isfile(untar_fpath):
os.remove(untar_fpath)
else:
shutil.rmtree(untar_fpath)
raise
tfile.close()
return untar_fpath
return fpath
def validate_file(fpath, md5_hash):
"""Validates a file against a MD5 hash.
# Arguments
fpath: path to the file being validated
md5_hash: the MD5 hash being validated against
# Returns
Whether the file is valid
"""
hasher = hashlib.md5()
with open(fpath, 'rb') as f:
buf = f.read()
hasher.update(buf)
if str(hasher.hexdigest()) == str(md5_hash):
return True
else:
return False
|
/**
* Cesium - https://github.com/AnalyticalGraphicsInc/cesium
*
* Copyright 2011-2015 Cesium 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.
*
* Columbus View (Pat. Pend.)
*
* Portions licensed separately.
* See https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md for full licensing details.
*/
(function () {
/*global define*/
define('Core/defined',[],function() {
"use strict";
/**
* Returns true if the object is defined, returns false otherwise.
*
* @exports defined
*
* @example
* if (Cesium.defined(positions)) {
* doSomething();
* } else {
* doSomethingElse();
* }
*/
var defined = function(value) {
return value !== undefined;
};
return defined;
});
/*global define*/
define('Core/freezeObject',[
'./defined'
], function(
defined) {
"use strict";
/**
* Freezes an object, using Object.freeze if available, otherwise returns
* the object unchanged. This function should be used in setup code to prevent
* errors from completely halting JavaScript execution in legacy browsers.
*
* @private
*
* @exports freezeObject
*/
var freezeObject = Object.freeze;
if (!defined(freezeObject)) {
freezeObject = function(o) {
return o;
};
}
return freezeObject;
});
/*global define*/
define('Core/defaultValue',[
'./freezeObject'
], function(
freezeObject) {
"use strict";
/**
* Returns the first parameter if not undefined, otherwise the second parameter.
* Useful for setting a default value for a parameter.
*
* @exports defaultValue
*
* @example
* param = Cesium.defaultValue(param, 'default');
*/
var defaultValue = function(a, b) {
if (a !== undefined) {
return a;
}
return b;
};
/**
* A frozen empty object that can be used as the default value for options passed as
* an object literal.
*/
defaultValue.EMPTY_OBJECT = freezeObject({});
return defaultValue;
});
/*global define*/
define('Core/DeveloperError',[
'./defined'
], function(
defined) {
"use strict";
/**
* Constructs an exception object that is thrown due to a developer error, e.g., invalid argument,
* argument out of range, etc. This exception should only be thrown during development;
* it usually indicates a bug in the calling code. This exception should never be
* caught; instead the calling code should strive not to generate it.
* <br /><br />
* On the other hand, a {@link RuntimeError} indicates an exception that may
* be thrown at runtime, e.g., out of memory, that the calling code should be prepared
* to catch.
*
* @alias DeveloperError
* @constructor
*
* @param {String} [message] The error message for this exception.
*
* @see RuntimeError
*/
var DeveloperError = function(message) {
/**
* 'DeveloperError' indicating that this exception was thrown due to a developer error.
* @type {String}
* @readonly
*/
this.name = 'DeveloperError';
/**
* The explanation for why this exception was thrown.
* @type {String}
* @readonly
*/
this.message = message;
//Browsers such as IE don't have a stack property until you actually throw the error.
var stack;
try {
throw new Error();
} catch (e) {
stack = e.stack;
}
/**
* The stack trace of this exception, if available.
* @type {String}
* @readonly
*/
this.stack = stack;
};
DeveloperError.prototype.toString = function() {
var str = this.name + ': ' + this.message;
if (defined(this.stack)) {
str += '\n' + this.stack.toString();
}
return str;
};
/**
* @private
*/
DeveloperError.throwInstantiationError = function() {
throw new DeveloperError('This function defines an interface and should not be called directly.');
};
return DeveloperError;
});
/*
I've wrapped Makoto Matsumoto and Takuji Nishimura's code in a namespace
so it's better encapsulated. Now you can have multiple random number generators
and they won't stomp all over eachother's state.
If you want to use this as a substitute for Math.random(), use the random()
method like so:
var m = new MersenneTwister();
var randomNumber = m.random();
You can also call the other genrand_{foo}() methods on the instance.
If you want to use a specific seed in order to get a repeatable random
sequence, pass an integer into the constructor:
var m = new MersenneTwister(123);
and that will always produce the same random sequence.
Sean McCullough (banksean@gmail.com)
*/
/*
A C-program for MT19937, with initialization improved 2002/1/26.
Coded by Takuji Nishimura and Makoto Matsumoto.
Before using, initialize the state by using init_genrand(seed)
or init_by_array(init_key, key_length).
*/
/**
@license
mersenne-twister.js - https://gist.github.com/banksean/300494
Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The names of its contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
Any feedback is very welcome.
http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
*/
define('ThirdParty/mersenne-twister',[],function() {
var MersenneTwister = function(seed) {
if (seed == undefined) {
seed = new Date().getTime();
}
/* Period parameters */
this.N = 624;
this.M = 397;
this.MATRIX_A = 0x9908b0df; /* constant vector a */
this.UPPER_MASK = 0x80000000; /* most significant w-r bits */
this.LOWER_MASK = 0x7fffffff; /* least significant r bits */
this.mt = new Array(this.N); /* the array for the state vector */
this.mti=this.N+1; /* mti==N+1 means mt[N] is not initialized */
this.init_genrand(seed);
}
/* initializes mt[N] with a seed */
MersenneTwister.prototype.init_genrand = function(s) {
this.mt[0] = s >>> 0;
for (this.mti=1; this.mti<this.N; this.mti++) {
var s = this.mt[this.mti-1] ^ (this.mt[this.mti-1] >>> 30);
this.mt[this.mti] = (((((s & 0xffff0000) >>> 16) * 1812433253) << 16) + (s & 0x0000ffff) * 1812433253)
+ this.mti;
/* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
/* In the previous versions, MSBs of the seed affect */
/* only MSBs of the array mt[]. */
/* 2002/01/09 modified by Makoto Matsumoto */
this.mt[this.mti] >>>= 0;
/* for >32 bit machines */
}
}
/* initialize by an array with array-length */
/* init_key is the array for initializing keys */
/* key_length is its length */
/* slight change for C++, 2004/2/26 */
//MersenneTwister.prototype.init_by_array = function(init_key, key_length) {
// var i, j, k;
// this.init_genrand(19650218);
// i=1; j=0;
// k = (this.N>key_length ? this.N : key_length);
// for (; k; k--) {
// var s = this.mt[i-1] ^ (this.mt[i-1] >>> 30)
// this.mt[i] = (this.mt[i] ^ (((((s & 0xffff0000) >>> 16) * 1664525) << 16) + ((s & 0x0000ffff) * 1664525)))
// + init_key[j] + j; /* non linear */
// this.mt[i] >>>= 0; /* for WORDSIZE > 32 machines */
// i++; j++;
// if (i>=this.N) { this.mt[0] = this.mt[this.N-1]; i=1; }
// if (j>=key_length) j=0;
// }
// for (k=this.N-1; k; k--) {
// var s = this.mt[i-1] ^ (this.mt[i-1] >>> 30);
// this.mt[i] = (this.mt[i] ^ (((((s & 0xffff0000) >>> 16) * 1566083941) << 16) + (s & 0x0000ffff) * 1566083941))
// - i; /* non linear */
// this.mt[i] >>>= 0; /* for WORDSIZE > 32 machines */
// i++;
// if (i>=this.N) { this.mt[0] = this.mt[this.N-1]; i=1; }
// }
//
// this.mt[0] = 0x80000000; /* MSB is 1; assuring non-zero initial array */
//}
/* generates a random number on [0,0xffffffff]-interval */
MersenneTwister.prototype.genrand_int32 = function() {
var y;
var mag01 = new Array(0x0, this.MATRIX_A);
/* mag01[x] = x * MATRIX_A for x=0,1 */
if (this.mti >= this.N) { /* generate N words at one time */
var kk;
if (this.mti == this.N+1) /* if init_genrand() has not been called, */
this.init_genrand(5489); /* a default initial seed is used */
for (kk=0;kk<this.N-this.M;kk++) {
y = (this.mt[kk]&this.UPPER_MASK)|(this.mt[kk+1]&this.LOWER_MASK);
this.mt[kk] = this.mt[kk+this.M] ^ (y >>> 1) ^ mag01[y & 0x1];
}
for (;kk<this.N-1;kk++) {
y = (this.mt[kk]&this.UPPER_MASK)|(this.mt[kk+1]&this.LOWER_MASK);
this.mt[kk] = this.mt[kk+(this.M-this.N)] ^ (y >>> 1) ^ mag01[y & 0x1];
}
y = (this.mt[this.N-1]&this.UPPER_MASK)|(this.mt[0]&this.LOWER_MASK);
this.mt[this.N-1] = this.mt[this.M-1] ^ (y >>> 1) ^ mag01[y & 0x1];
this.mti = 0;
}
y = this.mt[this.mti++];
/* Tempering */
y ^= (y >>> 11);
y ^= (y << 7) & 0x9d2c5680;
y ^= (y << 15) & 0xefc60000;
y ^= (y >>> 18);
return y >>> 0;
}
/* generates a random number on [0,0x7fffffff]-interval */
//MersenneTwister.prototype.genrand_int31 = function() {
// return (this.genrand_int32()>>>1);
//}
/* generates a random number on [0,1]-real-interval */
//MersenneTwister.prototype.genrand_real1 = function() {
// return this.genrand_int32()*(1.0/4294967295.0);
// /* divided by 2^32-1 */
//}
/* generates a random number on [0,1)-real-interval */
MersenneTwister.prototype.random = function() {
return this.genrand_int32()*(1.0/4294967296.0);
/* divided by 2^32 */
}
/* generates a random number on (0,1)-real-interval */
//MersenneTwister.prototype.genrand_real3 = function() {
// return (this.genrand_int32() + 0.5)*(1.0/4294967296.0);
// /* divided by 2^32 */
//}
/* generates a random number on [0,1) with 53-bit resolution*/
//MersenneTwister.prototype.genrand_res53 = function() {
// var a=this.genrand_int32()>>>5, b=this.genrand_int32()>>>6;
// return(a*67108864.0+b)*(1.0/9007199254740992.0);
//}
/* These real versions are due to Isaku Wada, 2002/01/09 added */
return MersenneTwister;
});
/*global define*/
define('Core/Math',[
'../ThirdParty/mersenne-twister',
'./defaultValue',
'./defined',
'./DeveloperError'
], function(
MersenneTwister,
defaultValue,
defined,
DeveloperError) {
"use strict";
/**
* Math functions.
*
* @namespace
* @alias CesiumMath
*/
var CesiumMath = {};
/**
* 0.1
* @type {Number}
* @constant
*/
CesiumMath.EPSILON1 = 0.1;
/**
* 0.01
* @type {Number}
* @constant
*/
CesiumMath.EPSILON2 = 0.01;
/**
* 0.001
* @type {Number}
* @constant
*/
CesiumMath.EPSILON3 = 0.001;
/**
* 0.0001
* @type {Number}
* @constant
*/
CesiumMath.EPSILON4 = 0.0001;
/**
* 0.00001
* @type {Number}
* @constant
*/
CesiumMath.EPSILON5 = 0.00001;
/**
* 0.000001
* @type {Number}
* @constant
*/
CesiumMath.EPSILON6 = 0.000001;
/**
* 0.0000001
* @type {Number}
* @constant
*/
CesiumMath.EPSILON7 = 0.0000001;
/**
* 0.00000001
* @type {Number}
* @constant
*/
CesiumMath.EPSILON8 = 0.00000001;
/**
* 0.000000001
* @type {Number}
* @constant
*/
CesiumMath.EPSILON9 = 0.000000001;
/**
* 0.0000000001
* @type {Number}
* @constant
*/
CesiumMath.EPSILON10 = 0.0000000001;
/**
* 0.00000000001
* @type {Number}
* @constant
*/
CesiumMath.EPSILON11 = 0.00000000001;
/**
* 0.000000000001
* @type {Number}
* @constant
*/
CesiumMath.EPSILON12 = 0.000000000001;
/**
* 0.0000000000001
* @type {Number}
* @constant
*/
CesiumMath.EPSILON13 = 0.0000000000001;
/**
* 0.00000000000001
* @type {Number}
* @constant
*/
CesiumMath.EPSILON14 = 0.00000000000001;
/**
* 0.000000000000001
* @type {Number}
* @constant
*/
CesiumMath.EPSILON15 = 0.000000000000001;
/**
* 0.0000000000000001
* @type {Number}
* @constant
*/
CesiumMath.EPSILON16 = 0.0000000000000001;
/**
* 0.00000000000000001
* @type {Number}
* @constant
*/
CesiumMath.EPSILON17 = 0.00000000000000001;
/**
* 0.000000000000000001
* @type {Number}
* @constant
*/
CesiumMath.EPSILON18 = 0.000000000000000001;
/**
* 0.0000000000000000001
* @type {Number}
* @constant
*/
CesiumMath.EPSILON19 = 0.0000000000000000001;
/**
* 0.00000000000000000001
* @type {Number}
* @constant
*/
CesiumMath.EPSILON20 = 0.00000000000000000001;
/**
* 3.986004418e14
* @type {Number}
* @constant
*/
CesiumMath.GRAVITATIONALPARAMETER = 3.986004418e14;
/**
* Radius of the sun in meters: 6.955e8
* @type {Number}
* @constant
*/
CesiumMath.SOLAR_RADIUS = 6.955e8;
/**
* The mean radius of the moon, according to the "Report of the IAU/IAG Working Group on
* Cartographic Coordinates and Rotational Elements of the Planets and satellites: 2000",
* Celestial Mechanics 82: 83-110, 2002.
* @type {Number}
* @constant
*/
CesiumMath.LUNAR_RADIUS = 1737400.0;
/**
* 64 * 1024
* @type {Number}
* @constant
*/
CesiumMath.SIXTY_FOUR_KILOBYTES = 64 * 1024;
/**
* Returns the sign of the value; 1 if the value is positive, -1 if the value is
* negative, or 0 if the value is 0.
*
* @param {Number} value The value to return the sign of.
* @returns {Number} The sign of value.
*/
CesiumMath.sign = function(value) {
if (value > 0) {
return 1;
}
if (value < 0) {
return -1;
}
return 0;
};
/**
* Returns 1.0 if the given value is positive or zero, and -1.0 if it is negative.
* This is similar to {@link CesiumMath#sign} except that returns 1.0 instead of
* 0.0 when the input value is 0.0.
* @param {Number} value The value to return the sign of.
* @returns {Number} The sign of value.
*/
CesiumMath.signNotZero = function(value) {
return value < 0.0 ? -1.0 : 1.0;
};
/**
* Converts a scalar value in the range [-1.0, 1.0] to a 8-bit 2's complement number.
* @param {Number} value The scalar value in the range [-1.0, 1.0]
* @returns {Number} The 8-bit 2's complement number, where 0 maps to -1.0 and 255 maps to 1.0.
*
* @see CesiumMath.fromSNorm
*/
CesiumMath.toSNorm = function(value) {
return Math.round((CesiumMath.clamp(value, -1.0, 1.0) * 0.5 + 0.5) * 255.0);
};
/**
* Converts a SNORM value in the range [0, 255] to a scalar in the range [-1.0, 1.0].
* @param {Number} value SNORM value in the range [0, 255]
* @returns {Number} Scalar in the range [-1.0, 1.0].
*
* @see CesiumMath.toSNorm
*/
CesiumMath.fromSNorm = function(value) {
return CesiumMath.clamp(value, 0.0, 255.0) / 255.0 * 2.0 - 1.0;
};
/**
* Returns the hyperbolic sine of a number.
* The hyperbolic sine of <em>value</em> is defined to be
* (<em>e<sup>x</sup> - e<sup>-x</sup></em>)/2.0
* where <i>e</i> is Euler's number, approximately 2.71828183.
*
* <p>Special cases:
* <ul>
* <li>If the argument is NaN, then the result is NaN.</li>
*
* <li>If the argument is infinite, then the result is an infinity
* with the same sign as the argument.</li>
*
* <li>If the argument is zero, then the result is a zero with the
* same sign as the argument.</li>
* </ul>
*</p>
*
* @param {Number} value The number whose hyperbolic sine is to be returned.
* @returns The hyperbolic sine of <code>value</code>.
*/
CesiumMath.sinh = function(value) {
var part1 = Math.pow(Math.E, value);
var part2 = Math.pow(Math.E, -1.0 * value);
return (part1 - part2) * 0.5;
};
/**
* Returns the hyperbolic cosine of a number.
* The hyperbolic cosine of <strong>value</strong> is defined to be
* (<em>e<sup>x</sup> + e<sup>-x</sup></em>)/2.0
* where <i>e</i> is Euler's number, approximately 2.71828183.
*
* <p>Special cases:
* <ul>
* <li>If the argument is NaN, then the result is NaN.</li>
*
* <li>If the argument is infinite, then the result is positive infinity.</li>
*
* <li>If the argument is zero, then the result is 1.0.</li>
* </ul>
*</p>
*
* @param {Number} value The number whose hyperbolic cosine is to be returned.
* @returns The hyperbolic cosine of <code>value</code>.
*/
CesiumMath.cosh = function(value) {
var part1 = Math.pow(Math.E, value);
var part2 = Math.pow(Math.E, -1.0 * value);
return (part1 + part2) * 0.5;
};
/**
* Computes the linear interpolation of two values.
*
* @param {Number} p The start value to interpolate.
* @param {Number} q The end value to interpolate.
* @param {Number} time The time of interpolation generally in the range <code>[0.0, 1.0]</code>.
* @returns {Number} The linearly interpolated value.
*
* @example
* var n = Cesium.Math.lerp(0.0, 2.0, 0.5); // returns 1.0
*/
CesiumMath.lerp = function(p, q, time) {
return ((1.0 - time) * p) + (time * q);
};
/**
* pi
*
* @type {Number}
* @constant
*/
CesiumMath.PI = Math.PI;
/**
* 1/pi
*
* @type {Number}
* @constant
*/
CesiumMath.ONE_OVER_PI = 1.0 / Math.PI;
/**
* pi/2
*
* @type {Number}
* @constant
*/
CesiumMath.PI_OVER_TWO = Math.PI * 0.5;
/**
* pi/3
*
* @type {Number}
* @constant
*/
CesiumMath.PI_OVER_THREE = Math.PI / 3.0;
/**
* pi/4
*
* @type {Number}
* @constant
*/
CesiumMath.PI_OVER_FOUR = Math.PI / 4.0;
/**
* pi/6
*
* @type {Number}
* @constant
*/
CesiumMath.PI_OVER_SIX = Math.PI / 6.0;
/**
* 3pi/2
*
* @type {Number}
* @constant
*/
CesiumMath.THREE_PI_OVER_TWO = (3.0 * Math.PI) * 0.5;
/**
* 2pi
*
* @type {Number}
* @constant
*/
CesiumMath.TWO_PI = 2.0 * Math.PI;
/**
* 1/2pi
*
* @type {Number}
* @constant
*/
CesiumMath.ONE_OVER_TWO_PI = 1.0 / (2.0 * Math.PI);
/**
* The number of radians in a degree.
*
* @type {Number}
* @constant
* @default Math.PI / 180.0
*/
CesiumMath.RADIANS_PER_DEGREE = Math.PI / 180.0;
/**
* The number of degrees in a radian.
*
* @type {Number}
* @constant
* @default 180.0 / Math.PI
*/
CesiumMath.DEGREES_PER_RADIAN = 180.0 / Math.PI;
/**
* The number of radians in an arc second.
*
* @type {Number}
* @constant
* @default {@link CesiumMath.RADIANS_PER_DEGREE} / 3600.0
*/
CesiumMath.RADIANS_PER_ARCSECOND = CesiumMath.RADIANS_PER_DEGREE / 3600.0;
/**
* Converts degrees to radians.
* @param {Number} degrees The angle to convert in degrees.
* @returns {Number} The corresponding angle in radians.
*/
CesiumMath.toRadians = function(degrees) {
if (!defined(degrees)) {
throw new DeveloperError('degrees is required.');
}
return degrees * CesiumMath.RADIANS_PER_DEGREE;
};
/**
* Converts radians to degrees.
* @param {Number} radians The angle to convert in radians.
* @returns {Number} The corresponding angle in degrees.
*/
CesiumMath.toDegrees = function(radians) {
if (!defined(radians)) {
throw new DeveloperError('radians is required.');
}
return radians * CesiumMath.DEGREES_PER_RADIAN;
};
/**
* Converts a longitude value, in radians, to the range [<code>-Math.PI</code>, <code>Math.PI</code>).
*
* @param {Number} angle The longitude value, in radians, to convert to the range [<code>-Math.PI</code>, <code>Math.PI</code>).
* @returns {Number} The equivalent longitude value in the range [<code>-Math.PI</code>, <code>Math.PI</code>).
*
* @example
* // Convert 270 degrees to -90 degrees longitude
* var longitude = Cesium.Math.convertLongitudeRange(Cesium.Math.toRadians(270.0));
*/
CesiumMath.convertLongitudeRange = function(angle) {
if (!defined(angle)) {
throw new DeveloperError('angle is required.');
}
var twoPi = CesiumMath.TWO_PI;
var simplified = angle - Math.floor(angle / twoPi) * twoPi;
if (simplified < -Math.PI) {
return simplified + twoPi;
}
if (simplified >= Math.PI) {
return simplified - twoPi;
}
return simplified;
};
/**
* Produces an angle in the range -Pi <= angle <= Pi which is equivalent to the provided angle.
*
* @param {Number} angle in radians
* @returns {Number} The angle in the range [<code>-CesiumMath.PI</code>, <code>CesiumMath.PI</code>].
*/
CesiumMath.negativePiToPi = function(x) {
if (!defined(x)) {
throw new DeveloperError('x is required.');
}
return CesiumMath.zeroToTwoPi(x + CesiumMath.PI) - CesiumMath.PI;
};
/**
* Produces an angle in the range 0 <= angle <= 2Pi which is equivalent to the provided angle.
*
* @param {Number} angle in radians
* @returns {Number} The angle in the range [0, <code>CesiumMath.TWO_PI</code>].
*/
CesiumMath.zeroToTwoPi = function(x) {
if (!defined(x)) {
throw new DeveloperError('x is required.');
}
var mod = CesiumMath.mod(x, CesiumMath.TWO_PI);
if (Math.abs(mod) < CesiumMath.EPSILON14 && Math.abs(x) > CesiumMath.EPSILON14) {
return CesiumMath.TWO_PI;
}
return mod;
};
/**
* The modulo operation that also works for negative dividends.
*
* @param {Number} m The dividend.
* @param {Number} n The divisor.
* @returns {Number} The remainder.
*/
CesiumMath.mod = function(m, n) {
if (!defined(m)) {
throw new DeveloperError('m is required.');
}
if (!defined(n)) {
throw new DeveloperError('n is required.');
}
return ((m % n) + n) % n;
};
/**
* Determines if two values are equal using an absolute or relative tolerance test. This is useful
* to avoid problems due to roundoff error when comparing floating-point values directly. The values are
* first compared using an absolute tolerance test. If that fails, a relative tolerance test is performed.
* Use this test if you are unsure of the magnitudes of left and right.
*
* @param {Number} left The first value to compare.
* @param {Number} right The other value to compare.
* @param {Number} relativeEpsilon The maximum inclusive delta between <code>left</code> and <code>right</code> for the relative tolerance test.
* @param {Number} [absoluteEpsilon=relativeEpsilon] The maximum inclusive delta between <code>left</code> and <code>right</code> for the absolute tolerance test.
* @returns {Boolean} <code>true</code> if the values are equal within the epsilon; otherwise, <code>false</code>.
*
* @example
* var a = Cesium.Math.equalsEpsilon(0.0, 0.01, Cesium.Math.EPSILON2); // true
* var b = Cesium.Math.equalsEpsilon(0.0, 0.1, Cesium.Math.EPSILON2); // false
* var c = Cesium.Math.equalsEpsilon(3699175.1634344, 3699175.2, Cesium.Math.EPSILON7); // true
* var d = Cesium.Math.equalsEpsilon(3699175.1634344, 3699175.2, Cesium.Math.EPSILON9); // false
*/
CesiumMath.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) {
if (!defined(left)) {
throw new DeveloperError('left is required.');
}
if (!defined(right)) {
throw new DeveloperError('right is required.');
}
if (!defined(relativeEpsilon)) {
throw new DeveloperError('relativeEpsilon is required.');
}
absoluteEpsilon = defaultValue(absoluteEpsilon, relativeEpsilon);
var absDiff = Math.abs(left - right);
return absDiff <= absoluteEpsilon || absDiff <= relativeEpsilon * Math.max(Math.abs(left), Math.abs(right));
};
var factorials = [1];
/**
* Computes the factorial of the provided number.
*
* @param {Number} n The number whose factorial is to be computed.
* @returns {Number} The factorial of the provided number or undefined if the number is less than 0.
*
* @exception {DeveloperError} A number greater than or equal to 0 is required.
*
* @see {@link http://en.wikipedia.org/wiki/Factorial|Factorial on Wikipedia}
*
* @example
* //Compute 7!, which is equal to 5040
* var computedFactorial = Cesium.Math.factorial(7);
*/
CesiumMath.factorial = function(n) {
if (typeof n !== 'number' || n < 0) {
throw new DeveloperError('A number greater than or equal to 0 is required.');
}
var length = factorials.length;
if (n >= length) {
var sum = factorials[length - 1];
for (var i = length; i <= n; i++) {
factorials.push(sum * i);
}
}
return factorials[n];
};
/**
* Increments a number with a wrapping to a minimum value if the number exceeds the maximum value.
*
* @param {Number} [n] The number to be incremented.
* @param {Number} [maximumValue] The maximum incremented value before rolling over to the minimum value.
* @param {Number} [minimumValue=0.0] The number reset to after the maximum value has been exceeded.
* @returns {Number} The incremented number.
*
* @exception {DeveloperError} Maximum value must be greater than minimum value.
*
* @example
* var n = Cesium.Math.incrementWrap(5, 10, 0); // returns 6
* var n = Cesium.Math.incrementWrap(10, 10, 0); // returns 0
*/
CesiumMath.incrementWrap = function(n, maximumValue, minimumValue) {
minimumValue = defaultValue(minimumValue, 0.0);
if (!defined(n)) {
throw new DeveloperError('n is required.');
}
if (maximumValue <= minimumValue) {
throw new DeveloperError('maximumValue must be greater than minimumValue.');
}
++n;
if (n > maximumValue) {
n = minimumValue;
}
return n;
};
/**
* Determines if a positive integer is a power of two.
*
* @param {Number} n The positive integer to test.
* @returns {Boolean} <code>true</code> if the number if a power of two; otherwise, <code>false</code>.
*
* @exception {DeveloperError} A number greater than or equal to 0 is required.
*
* @example
* var t = Cesium.Math.isPowerOfTwo(16); // true
* var f = Cesium.Math.isPowerOfTwo(20); // false
*/
CesiumMath.isPowerOfTwo = function(n) {
if (typeof n !== 'number' || n < 0) {
throw new DeveloperError('A number greater than or equal to 0 is required.');
}
return (n !== 0) && ((n & (n - 1)) === 0);
};
/**
* Computes the next power-of-two integer greater than or equal to the provided positive integer.
*
* @param {Number} n The positive integer to test.
* @returns {Number} The next power-of-two integer.
*
* @exception {DeveloperError} A number greater than or equal to 0 is required.
*
* @example
* var n = Cesium.Math.nextPowerOfTwo(29); // 32
* var m = Cesium.Math.nextPowerOfTwo(32); // 32
*/
CesiumMath.nextPowerOfTwo = function(n) {
if (typeof n !== 'number' || n < 0) {
throw new DeveloperError('A number greater than or equal to 0 is required.');
}
// From http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
--n;
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
++n;
return n;
};
/**
* Constraint a value to lie between two values.
*
* @param {Number} value The value to constrain.
* @param {Number} min The minimum value.
* @param {Number} max The maximum value.
* @returns {Number} The value clamped so that min <= value <= max.
*/
CesiumMath.clamp = function(value, min, max) {
if (!defined(value)) {
throw new DeveloperError('value is required');
}
if (!defined(min)) {
throw new DeveloperError('min is required.');
}
if (!defined(max)) {
throw new DeveloperError('max is required.');
}
return value < min ? min : value > max ? max : value;
};
var randomNumberGenerator = new MersenneTwister();
/**
* Sets the seed used by the random number generator
* in {@link CesiumMath#nextRandomNumber}.
*
* @param {Number} seed An integer used as the seed.
*/
CesiumMath.setRandomNumberSeed = function(seed) {
if (!defined(seed)) {
throw new DeveloperError('seed is required.');
}
randomNumberGenerator = new MersenneTwister(seed);
};
/**
* Generates a random number in the range of [0.0, 1.0)
* using a Mersenne twister.
*
* @returns {Number} A random number in the range of [0.0, 1.0).
*
* @see CesiumMath.setRandomNumberSeed
* @see {@link http://en.wikipedia.org/wiki/Mersenne_twister|Mersenne twister on Wikipedia}
*/
CesiumMath.nextRandomNumber = function() {
return randomNumberGenerator.random();
};
/**
* Computes <code>Math.acos(value)</acode>, but first clamps <code>value</code> to the range [-1.0, 1.0]
* so that the function will never return NaN.
*
* @param {Number} value The value for which to compute acos.
* @returns {Number} The acos of the value if the value is in the range [-1.0, 1.0], or the acos of -1.0 or 1.0,
* whichever is closer, if the value is outside the range.
*/
CesiumMath.acosClamped = function(value) {
if (!defined(value)) {
throw new DeveloperError('value is required.');
}
return Math.acos(CesiumMath.clamp(value, -1.0, 1.0));
};
/**
* Computes <code>Math.asin(value)</acode>, but first clamps <code>value</code> to the range [-1.0, 1.0]
* so that the function will never return NaN.
*
* @param {Number} value The value for which to compute asin.
* @returns {Number} The asin of the value if the value is in the range [-1.0, 1.0], or the asin of -1.0 or 1.0,
* whichever is closer, if the value is outside the range.
*/
CesiumMath.asinClamped = function(value) {
if (!defined(value)) {
throw new DeveloperError('value is required.');
}
return Math.asin(CesiumMath.clamp(value, -1.0, 1.0));
};
/**
* Finds the chord length between two points given the circle's radius and the angle between the points.
*
* @param {Number} angle The angle between the two points.
* @param {Number} radius The radius of the circle.
* @returns {Number} The chord length.
*/
CesiumMath.chordLength = function(angle, radius) {
if (!defined(angle)) {
throw new DeveloperError('angle is required.');
}
if (!defined(radius)) {
throw new DeveloperError('radius is required.');
}
return 2.0 * radius * Math.sin(angle * 0.5);
};
return CesiumMath;
});
/*global define*/
define('Core/Cartesian3',[
'./defaultValue',
'./defined',
'./DeveloperError',
'./freezeObject',
'./Math'
], function(
defaultValue,
defined,
DeveloperError,
freezeObject,
CesiumMath) {
"use strict";
/**
* A 3D Cartesian point.
* @alias Cartesian3
* @constructor
*
* @param {Number} [x=0.0] The X component.
* @param {Number} [y=0.0] The Y component.
* @param {Number} [z=0.0] The Z component.
*
* @see Cartesian2
* @see Cartesian4
* @see Packable
*/
var Cartesian3 = function(x, y, z) {
/**
* The X component.
* @type {Number}
* @default 0.0
*/
this.x = defaultValue(x, 0.0);
/**
* The Y component.
* @type {Number}
* @default 0.0
*/
this.y = defaultValue(y, 0.0);
/**
* The Z component.
* @type {Number}
* @default 0.0
*/
this.z = defaultValue(z, 0.0);
};
/**
* Converts the provided Spherical into Cartesian3 coordinates.
*
* @param {Spherical} spherical The Spherical to be converted to Cartesian3.
* @param {Cartesian3} [result] The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
*/
Cartesian3.fromSpherical = function(spherical, result) {
if (!defined(spherical)) {
throw new DeveloperError('spherical is required');
}
if (!defined(result)) {
result = new Cartesian3();
}
var clock = spherical.clock;
var cone = spherical.cone;
var magnitude = defaultValue(spherical.magnitude, 1.0);
var radial = magnitude * Math.sin(cone);
result.x = radial * Math.cos(clock);
result.y = radial * Math.sin(clock);
result.z = magnitude * Math.cos(cone);
return result;
};
/**
* Creates a Cartesian3 instance from x, y and z coordinates.
*
* @param {Number} x The x coordinate.
* @param {Number} y The y coordinate.
* @param {Number} z The z coordinate.
* @param {Cartesian3} [result] The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
*/
Cartesian3.fromElements = function(x, y, z, result) {
if (!defined(result)) {
return new Cartesian3(x, y, z);
}
result.x = x;
result.y = y;
result.z = z;
return result;
};
/**
* Duplicates a Cartesian3 instance.
*
* @param {Cartesian3} cartesian The Cartesian to duplicate.
* @param {Cartesian3} [result] The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided. (Returns undefined if cartesian is undefined)
*/
Cartesian3.clone = function(cartesian, result) {
if (!defined(cartesian)) {
return undefined;
}
if (!defined(result)) {
return new Cartesian3(cartesian.x, cartesian.y, cartesian.z);
}
result.x = cartesian.x;
result.y = cartesian.y;
result.z = cartesian.z;
return result;
};
/**
* Creates a Cartesian3 instance from an existing Cartesian4. This simply takes the
* x, y, and z properties of the Cartesian4 and drops w.
* @function
*
* @param {Cartesian4} cartesian The Cartesian4 instance to create a Cartesian3 instance from.
* @param {Cartesian3} [result] The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
*/
Cartesian3.fromCartesian4 = Cartesian3.clone;
/**
* The number of elements used to pack the object into an array.
* @type {Number}
*/
Cartesian3.packedLength = 3;
/**
* Stores the provided instance into the provided array.
*
* @param {Cartesian3} value The value to pack.
* @param {Number[]} array The array to pack into.
* @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
*/
Cartesian3.pack = function(value, array, startingIndex) {
if (!defined(value)) {
throw new DeveloperError('value is required');
}
if (!defined(array)) {
throw new DeveloperError('array is required');
}
startingIndex = defaultValue(startingIndex, 0);
array[startingIndex++] = value.x;
array[startingIndex++] = value.y;
array[startingIndex] = value.z;
};
/**
* Retrieves an instance from a packed array.
*
* @param {Number[]} array The packed array.
* @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
* @param {Cartesian3} [result] The object into which to store the result.
*/
Cartesian3.unpack = function(array, startingIndex, result) {
if (!defined(array)) {
throw new DeveloperError('array is required');
}
startingIndex = defaultValue(startingIndex, 0);
if (!defined(result)) {
result = new Cartesian3();
}
result.x = array[startingIndex++];
result.y = array[startingIndex++];
result.z = array[startingIndex];
return result;
};
/**
* Creates a Cartesian3 from three consecutive elements in an array.
* @function
*
* @param {Number[]} array The array whose three consecutive elements correspond to the x, y, and z components, respectively.
* @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to the x component.
* @param {Cartesian3} [result] The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
*
* @example
* // Create a Cartesian3 with (1.0, 2.0, 3.0)
* var v = [1.0, 2.0, 3.0];
* var p = Cesium.Cartesian3.fromArray(v);
*
* // Create a Cartesian3 with (1.0, 2.0, 3.0) using an offset into an array
* var v2 = [0.0, 0.0, 1.0, 2.0, 3.0];
* var p2 = Cesium.Cartesian3.fromArray(v2, 2);
*/
Cartesian3.fromArray = Cartesian3.unpack;
/**
* Computes the value of the maximum component for the supplied Cartesian.
*
* @param {Cartesian3} cartesian The cartesian to use.
* @returns {Number} The value of the maximum component.
*/
Cartesian3.maximumComponent = function(cartesian) {
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required');
}
return Math.max(cartesian.x, cartesian.y, cartesian.z);
};
/**
* Computes the value of the minimum component for the supplied Cartesian.
*
* @param {Cartesian3} cartesian The cartesian to use.
* @returns {Number} The value of the minimum component.
*/
Cartesian3.minimumComponent = function(cartesian) {
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required');
}
return Math.min(cartesian.x, cartesian.y, cartesian.z);
};
/**
* Compares two Cartesians and computes a Cartesian which contains the minimum components of the supplied Cartesians.
*
* @param {Cartesian3} first A cartesian to compare.
* @param {Cartesian3} second A cartesian to compare.
* @param {Cartesian3} result The object into which to store the result.
* @returns {Cartesian3} A cartesian with the minimum components.
*/
Cartesian3.minimumByComponent = function(first, second, result) {
if (!defined(first)) {
throw new DeveloperError('first is required.');
}
if (!defined(second)) {
throw new DeveloperError('second is required.');
}
if (!defined(result)) {
throw new DeveloperError('result is required.');
}
result.x = Math.min(first.x, second.x);
result.y = Math.min(first.y, second.y);
result.z = Math.min(first.z, second.z);
return result;
};
/**
* Compares two Cartesians and computes a Cartesian which contains the maximum components of the supplied Cartesians.
*
* @param {Cartesian3} first A cartesian to compare.
* @param {Cartesian3} second A cartesian to compare.
* @param {Cartesian3} result The object into which to store the result.
* @returns {Cartesian3} A cartesian with the maximum components.
*/
Cartesian3.maximumByComponent = function(first, second, result) {
if (!defined(first)) {
throw new DeveloperError('first is required.');
}
if (!defined(second)) {
throw new DeveloperError('second is required.');
}
if (!defined(result)) {
throw new DeveloperError('result is required.');
}
result.x = Math.max(first.x, second.x);
result.y = Math.max(first.y, second.y);
result.z = Math.max(first.z, second.z);
return result;
};
/**
* Computes the provided Cartesian's squared magnitude.
*
* @param {Cartesian3} cartesian The Cartesian instance whose squared magnitude is to be computed.
* @returns {Number} The squared magnitude.
*/
Cartesian3.magnitudeSquared = function(cartesian) {
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required');
}
return cartesian.x * cartesian.x + cartesian.y * cartesian.y + cartesian.z * cartesian.z;
};
/**
* Computes the Cartesian's magnitude (length).
*
* @param {Cartesian3} cartesian The Cartesian instance whose magnitude is to be computed.
* @returns {Number} The magnitude.
*/
Cartesian3.magnitude = function(cartesian) {
return Math.sqrt(Cartesian3.magnitudeSquared(cartesian));
};
var distanceScratch = new Cartesian3();
/**
* Computes the distance between two points.
*
* @param {Cartesian3} left The first point to compute the distance from.
* @param {Cartesian3} right The second point to compute the distance to.
* @returns {Number} The distance between two points.
*
* @example
* // Returns 1.0
* var d = Cesium.Cartesian3.distance(new Cesium.Cartesian3(1.0, 0.0, 0.0), new Cesium.Cartesian3(2.0, 0.0, 0.0));
*/
Cartesian3.distance = function(left, right) {
if (!defined(left) || !defined(right)) {
throw new DeveloperError('left and right are required.');
}
Cartesian3.subtract(left, right, distanceScratch);
return Cartesian3.magnitude(distanceScratch);
};
/**
* Computes the squared distance between two points. Comparing squared distances
* using this function is more efficient than comparing distances using {@link Cartesian3#distance}.
*
* @param {Cartesian3} left The first point to compute the distance from.
* @param {Cartesian3} right The second point to compute the distance to.
* @returns {Number} The distance between two points.
*
* @example
* // Returns 4.0, not 2.0
* var d = Cesium.Cartesian3.distance(new Cesium.Cartesian3(1.0, 0.0, 0.0), new Cesium.Cartesian3(3.0, 0.0, 0.0));
*/
Cartesian3.distanceSquared = function(left, right) {
if (!defined(left) || !defined(right)) {
throw new DeveloperError('left and right are required.');
}
Cartesian3.subtract(left, right, distanceScratch);
return Cartesian3.magnitudeSquared(distanceScratch);
};
/**
* Computes the normalized form of the supplied Cartesian.
*
* @param {Cartesian3} cartesian The Cartesian to be normalized.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*/
Cartesian3.normalize = function(cartesian, result) {
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required');
}
var magnitude = Cartesian3.magnitude(cartesian);
result.x = cartesian.x / magnitude;
result.y = cartesian.y / magnitude;
result.z = cartesian.z / magnitude;
return result;
};
/**
* Computes the dot (scalar) product of two Cartesians.
*
* @param {Cartesian3} left The first Cartesian.
* @param {Cartesian3} right The second Cartesian.
* @returns {Number} The dot product.
*/
Cartesian3.dot = function(left, right) {
if (!defined(left)) {
throw new DeveloperError('left is required');
}
if (!defined(right)) {
throw new DeveloperError('right is required');
}
return left.x * right.x + left.y * right.y + left.z * right.z;
};
/**
* Computes the componentwise product of two Cartesians.
*
* @param {Cartesian3} left The first Cartesian.
* @param {Cartesian3} right The second Cartesian.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*/
Cartesian3.multiplyComponents = function(left, right, result) {
if (!defined(left)) {
throw new DeveloperError('left is required');
}
if (!defined(right)) {
throw new DeveloperError('right is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required');
}
result.x = left.x * right.x;
result.y = left.y * right.y;
result.z = left.z * right.z;
return result;
};
/**
* Computes the componentwise sum of two Cartesians.
*
* @param {Cartesian3} left The first Cartesian.
* @param {Cartesian3} right The second Cartesian.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*/
Cartesian3.add = function(left, right, result) {
if (!defined(left)) {
throw new DeveloperError('left is required');
}
if (!defined(right)) {
throw new DeveloperError('right is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required');
}
result.x = left.x + right.x;
result.y = left.y + right.y;
result.z = left.z + right.z;
return result;
};
/**
* Computes the componentwise difference of two Cartesians.
*
* @param {Cartesian3} left The first Cartesian.
* @param {Cartesian3} right The second Cartesian.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*/
Cartesian3.subtract = function(left, right, result) {
if (!defined(left)) {
throw new DeveloperError('left is required');
}
if (!defined(right)) {
throw new DeveloperError('right is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required');
}
result.x = left.x - right.x;
result.y = left.y - right.y;
result.z = left.z - right.z;
return result;
};
/**
* Multiplies the provided Cartesian componentwise by the provided scalar.
*
* @param {Cartesian3} cartesian The Cartesian to be scaled.
* @param {Number} scalar The scalar to multiply with.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*/
Cartesian3.multiplyByScalar = function(cartesian, scalar, result) {
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required');
}
if (typeof scalar !== 'number') {
throw new DeveloperError('scalar is required and must be a number.');
}
if (!defined(result)) {
throw new DeveloperError('result is required');
}
result.x = cartesian.x * scalar;
result.y = cartesian.y * scalar;
result.z = cartesian.z * scalar;
return result;
};
/**
* Divides the provided Cartesian componentwise by the provided scalar.
*
* @param {Cartesian3} cartesian The Cartesian to be divided.
* @param {Number} scalar The scalar to divide by.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*/
Cartesian3.divideByScalar = function(cartesian, scalar, result) {
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required');
}
if (typeof scalar !== 'number') {
throw new DeveloperError('scalar is required and must be a number.');
}
if (!defined(result)) {
throw new DeveloperError('result is required');
}
result.x = cartesian.x / scalar;
result.y = cartesian.y / scalar;
result.z = cartesian.z / scalar;
return result;
};
/**
* Negates the provided Cartesian.
*
* @param {Cartesian3} cartesian The Cartesian to be negated.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*/
Cartesian3.negate = function(cartesian, result) {
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required');
}
result.x = -cartesian.x;
result.y = -cartesian.y;
result.z = -cartesian.z;
return result;
};
/**
* Computes the absolute value of the provided Cartesian.
*
* @param {Cartesian3} cartesian The Cartesian whose absolute value is to be computed.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*/
Cartesian3.abs = function(cartesian, result) {
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required');
}
result.x = Math.abs(cartesian.x);
result.y = Math.abs(cartesian.y);
result.z = Math.abs(cartesian.z);
return result;
};
var lerpScratch = new Cartesian3();
/**
* Computes the linear interpolation or extrapolation at t using the provided cartesians.
*
* @param {Cartesian3} start The value corresponding to t at 0.0.
* @param {Cartesian3} end The value corresponding to t at 1.0.
* @param {Number} t The point along t at which to interpolate.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*/
Cartesian3.lerp = function(start, end, t, result) {
if (!defined(start)) {
throw new DeveloperError('start is required.');
}
if (!defined(end)) {
throw new DeveloperError('end is required.');
}
if (typeof t !== 'number') {
throw new DeveloperError('t is required and must be a number.');
}
if (!defined(result)) {
throw new DeveloperError('result is required.');
}
Cartesian3.multiplyByScalar(end, t, lerpScratch);
result = Cartesian3.multiplyByScalar(start, 1.0 - t, result);
return Cartesian3.add(lerpScratch, result, result);
};
var angleBetweenScratch = new Cartesian3();
var angleBetweenScratch2 = new Cartesian3();
/**
* Returns the angle, in radians, between the provided Cartesians.
*
* @param {Cartesian3} left The first Cartesian.
* @param {Cartesian3} right The second Cartesian.
* @returns {Number} The angle between the Cartesians.
*/
Cartesian3.angleBetween = function(left, right) {
if (!defined(left)) {
throw new DeveloperError('left is required');
}
if (!defined(right)) {
throw new DeveloperError('right is required');
}
Cartesian3.normalize(left, angleBetweenScratch);
Cartesian3.normalize(right, angleBetweenScratch2);
var cosine = Cartesian3.dot(angleBetweenScratch, angleBetweenScratch2);
var sine = Cartesian3.magnitude(Cartesian3.cross(angleBetweenScratch, angleBetweenScratch2, angleBetweenScratch));
return Math.atan2(sine, cosine);
};
var mostOrthogonalAxisScratch = new Cartesian3();
/**
* Returns the axis that is most orthogonal to the provided Cartesian.
*
* @param {Cartesian3} cartesian The Cartesian on which to find the most orthogonal axis.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The most orthogonal axis.
*/
Cartesian3.mostOrthogonalAxis = function(cartesian, result) {
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required.');
}
if (!defined(result)) {
throw new DeveloperError('result is required.');
}
var f = Cartesian3.normalize(cartesian, mostOrthogonalAxisScratch);
Cartesian3.abs(f, f);
if (f.x <= f.y) {
if (f.x <= f.z) {
result = Cartesian3.clone(Cartesian3.UNIT_X, result);
} else {
result = Cartesian3.clone(Cartesian3.UNIT_Z, result);
}
} else {
if (f.y <= f.z) {
result = Cartesian3.clone(Cartesian3.UNIT_Y, result);
} else {
result = Cartesian3.clone(Cartesian3.UNIT_Z, result);
}
}
return result;
};
/**
* Compares the provided Cartesians componentwise and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Cartesian3} [left] The first Cartesian.
* @param {Cartesian3} [right] The second Cartesian.
* @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
Cartesian3.equals = function(left, right) {
return (left === right) ||
((defined(left)) &&
(defined(right)) &&
(left.x === right.x) &&
(left.y === right.y) &&
(left.z === right.z));
};
/**
* @private
*/
Cartesian3.equalsArray = function(cartesian, array, offset) {
return cartesian.x === array[offset] &&
cartesian.y === array[offset + 1] &&
cartesian.z === array[offset + 2];
};
/**
* Compares the provided Cartesians componentwise and returns
* <code>true</code> if they pass an absolute or relative tolerance test,
* <code>false</code> otherwise.
*
* @param {Cartesian3} [left] The first Cartesian.
* @param {Cartesian3} [right] The second Cartesian.
* @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
* @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
* @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
*/
Cartesian3.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) {
return (left === right) ||
(defined(left) &&
defined(right) &&
CesiumMath.equalsEpsilon(left.x, right.x, relativeEpsilon, absoluteEpsilon) &&
CesiumMath.equalsEpsilon(left.y, right.y, relativeEpsilon, absoluteEpsilon) &&
CesiumMath.equalsEpsilon(left.z, right.z, relativeEpsilon, absoluteEpsilon));
};
/**
* Computes the cross (outer) product of two Cartesians.
*
* @param {Cartesian3} left The first Cartesian.
* @param {Cartesian3} right The second Cartesian.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The cross product.
*/
Cartesian3.cross = function(left, right, result) {
if (!defined(left)) {
throw new DeveloperError('left is required');
}
if (!defined(right)) {
throw new DeveloperError('right is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required');
}
var leftX = left.x;
var leftY = left.y;
var leftZ = left.z;
var rightX = right.x;
var rightY = right.y;
var rightZ = right.z;
var x = leftY * rightZ - leftZ * rightY;
var y = leftZ * rightX - leftX * rightZ;
var z = leftX * rightY - leftY * rightX;
result.x = x;
result.y = y;
result.z = z;
return result;
};
/**
* Returns a Cartesian3 position from longitude and latitude values given in degrees.
*
* @param {Number} longitude The longitude, in degrees
* @param {Number} latitude The latitude, in degrees
* @param {Number} [height=0.0] The height, in meters, above the ellipsoid.
* @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the position lies.
* @param {Cartesian3} [result] The object onto which to store the result.
* @returns {Cartesian3} The position
*
* @example
* var position = Cesium.Cartesian3.fromDegrees(-115.0, 37.0);
*/
Cartesian3.fromDegrees = function(longitude, latitude, height, ellipsoid, result) {
if (!defined(longitude)) {
throw new DeveloperError('longitude is required');
}
if (!defined(latitude)) {
throw new DeveloperError('latitude is required');
}
var lon = CesiumMath.toRadians(longitude);
var lat = CesiumMath.toRadians(latitude);
return Cartesian3.fromRadians(lon, lat, height, ellipsoid, result);
};
var scratchN = new Cartesian3();
var scratchK = new Cartesian3();
var wgs84RadiiSquared = new Cartesian3(6378137.0 * 6378137.0, 6378137.0 * 6378137.0, 6356752.3142451793 * 6356752.3142451793);
/**
* Returns a Cartesian3 position from longitude and latitude values given in radians.
*
* @param {Number} longitude The longitude, in radians
* @param {Number} latitude The latitude, in radians
* @param {Number} [height=0.0] The height, in meters, above the ellipsoid.
* @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the position lies.
* @param {Cartesian3} [result] The object onto which to store the result.
* @returns {Cartesian3} The position
*
* @example
* var position = Cesium.Cartesian3.fromRadians(-2.007, 0.645);
*/
Cartesian3.fromRadians = function(longitude, latitude, height, ellipsoid, result) {
if (!defined(longitude)) {
throw new DeveloperError('longitude is required');
}
if (!defined(latitude)) {
throw new DeveloperError('latitude is required');
}
height = defaultValue(height, 0.0);
var radiiSquared = defined(ellipsoid) ? ellipsoid.radiiSquared : wgs84RadiiSquared;
var cosLatitude = Math.cos(latitude);
scratchN.x = cosLatitude * Math.cos(longitude);
scratchN.y = cosLatitude * Math.sin(longitude);
scratchN.z = Math.sin(latitude);
scratchN = Cartesian3.normalize(scratchN, scratchN);
Cartesian3.multiplyComponents(radiiSquared, scratchN, scratchK);
var gamma = Math.sqrt(Cartesian3.dot(scratchN, scratchK));
scratchK = Cartesian3.divideByScalar(scratchK, gamma, scratchK);
scratchN = Cartesian3.multiplyByScalar(scratchN, height, scratchN);
if (!defined(result)) {
result = new Cartesian3();
}
return Cartesian3.add(scratchK, scratchN, result);
};
/**
* Returns an array of Cartesian3 positions given an array of longitude and latitude values given in degrees.
*
* @param {Number[]} coordinates A list of longitude and latitude values. Values alternate [longitude, latitude, longitude, latitude...].
* @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the coordinates lie.
* @param {Cartesian3[]} [result] An array of Cartesian3 objects to store the result.
* @returns {Cartesian3[]} The array of positions.
*
* @example
* var positions = Cesium.Cartesian3.fromDegreesArray([-115.0, 37.0, -107.0, 33.0]);
*/
Cartesian3.fromDegreesArray = function(coordinates, ellipsoid, result) {
if (!defined(coordinates)) {
throw new DeveloperError('positions is required.');
}
var pos = new Array(coordinates.length);
for (var i = 0; i < coordinates.length; i++) {
pos[i] = CesiumMath.toRadians(coordinates[i]);
}
return Cartesian3.fromRadiansArray(pos, ellipsoid, result);
};
/**
* Returns an array of Cartesian3 positions given an array of longitude and latitude values given in radians.
*
* @param {Number[]} coordinates A list of longitude and latitude values. Values alternate [longitude, latitude, longitude, latitude...].
* @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the coordinates lie.
* @param {Cartesian3[]} [result] An array of Cartesian3 objects to store the result.
* @returns {Cartesian3[]} The array of positions.
*
* @example
* var positions = Cesium.Cartesian3.fromRadiansArray([-2.007, 0.645, -1.867, .575]);
*/
Cartesian3.fromRadiansArray = function(coordinates, ellipsoid, result) {
if (!defined(coordinates)) {
throw new DeveloperError('positions is required.');
}
if (coordinates.length < 2) {
throw new DeveloperError('positions length cannot be less than 2.');
}
if (coordinates.length % 2 !== 0) {
throw new DeveloperError('positions length must be a multiple of 2.');
}
var length = coordinates.length;
if (!defined(result)) {
result = new Array(length/2);
} else {
result.length = length/2;
}
for ( var i = 0; i < length; i+=2) {
var lon = coordinates[i];
var lat = coordinates[i+1];
result[i/2] = Cartesian3.fromRadians(lon, lat, 0, ellipsoid, result[i/2]);
}
return result;
};
/**
* Returns an array of Cartesian3 positions given an array of longitude, latitude and height values where longitude and latitude are given in degrees.
*
* @param {Number[]} coordinates A list of longitude, latitude and height values. Values alternate [longitude, latitude, height,, longitude, latitude, height...].
* @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the position lies.
* @param {Cartesian3[]} [result] An array of Cartesian3 objects to store the result.
* @returns {Cartesian3[]} The array of positions.
*
* @example
* var positions = Cesium.Cartesian3.fromDegreesArrayHeights([-115.0, 37.0, 100000.0, -107.0, 33.0, 150000.0]);
*/
Cartesian3.fromDegreesArrayHeights = function(coordinates, ellipsoid, result) {
if (!defined(coordinates)) {
throw new DeveloperError('positions is required.');
}
if (coordinates.length < 3) {
throw new DeveloperError('positions length cannot be less than 3.');
}
if (coordinates.length % 3 !== 0) {
throw new DeveloperError('positions length must be a multiple of 3.');
}
var pos = new Array(coordinates.length);
for (var i = 0; i < coordinates.length; i+=3) {
pos[i] = CesiumMath.toRadians(coordinates[i]);
pos[i+1] = CesiumMath.toRadians(coordinates[i+1]);
pos[i+2] = coordinates[i+2];
}
return Cartesian3.fromRadiansArrayHeights(pos, ellipsoid, result);
};
/**
* Returns an array of Cartesian3 positions given an array of longitude, latitude and height values where longitude and latitude are given in radians.
*
* @param {Number[]} coordinates A list of longitude, latitude and height values. Values alternate [longitude, latitude, height,, longitude, latitude, height...].
* @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the position lies.
* @param {Cartesian3[]} [result] An array of Cartesian3 objects to store the result.
* @returns {Cartesian3[]} The array of positions.
*
* @example
* var positions = Cesium.Cartesian3.fromRadiansArrayHeights([-2.007, 0.645, 100000.0, -1.867, .575, 150000.0]);
*/
Cartesian3.fromRadiansArrayHeights = function(coordinates, ellipsoid, result) {
if (!defined(coordinates)) {
throw new DeveloperError('positions is required.');
}
if (coordinates.length < 3) {
throw new DeveloperError('positions length cannot be less than 3.');
}
if (coordinates.length % 3 !== 0) {
throw new DeveloperError('positions length must be a multiple of 3.');
}
var length = coordinates.length;
if (!defined(result)) {
result = new Array(length/3);
} else {
result.length = length/3;
}
for ( var i = 0; i < length; i+=3) {
var lon = coordinates[i];
var lat = coordinates[i+1];
var alt = coordinates[i+2];
result[i/3] = Cartesian3.fromRadians(lon, lat, alt, ellipsoid, result[i/3]);
}
return result;
};
/**
* An immutable Cartesian3 instance initialized to (0.0, 0.0, 0.0).
*
* @type {Cartesian3}
* @constant
*/
Cartesian3.ZERO = freezeObject(new Cartesian3(0.0, 0.0, 0.0));
/**
* An immutable Cartesian3 instance initialized to (1.0, 0.0, 0.0).
*
* @type {Cartesian3}
* @constant
*/
Cartesian3.UNIT_X = freezeObject(new Cartesian3(1.0, 0.0, 0.0));
/**
* An immutable Cartesian3 instance initialized to (0.0, 1.0, 0.0).
*
* @type {Cartesian3}
* @constant
*/
Cartesian3.UNIT_Y = freezeObject(new Cartesian3(0.0, 1.0, 0.0));
/**
* An immutable Cartesian3 instance initialized to (0.0, 0.0, 1.0).
*
* @type {Cartesian3}
* @constant
*/
Cartesian3.UNIT_Z = freezeObject(new Cartesian3(0.0, 0.0, 1.0));
/**
* Duplicates this Cartesian3 instance.
*
* @param {Cartesian3} [result] The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
*/
Cartesian3.prototype.clone = function(result) {
return Cartesian3.clone(this, result);
};
/**
* Compares this Cartesian against the provided Cartesian componentwise and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Cartesian3} [right] The right hand side Cartesian.
* @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
*/
Cartesian3.prototype.equals = function(right) {
return Cartesian3.equals(this, right);
};
/**
* Compares this Cartesian against the provided Cartesian componentwise and returns
* <code>true</code> if they pass an absolute or relative tolerance test,
* <code>false</code> otherwise.
*
* @param {Cartesian3} [right] The right hand side Cartesian.
* @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
* @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
* @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
*/
Cartesian3.prototype.equalsEpsilon = function(right, relativeEpsilon, absoluteEpsilon) {
return Cartesian3.equalsEpsilon(this, right, relativeEpsilon, absoluteEpsilon);
};
/**
* Creates a string representing this Cartesian in the format '(x, y, z)'.
*
* @returns {String} A string representing this Cartesian in the format '(x, y, z)'.
*/
Cartesian3.prototype.toString = function() {
return '(' + this.x + ', ' + this.y + ', ' + this.z + ')';
};
return Cartesian3;
});
/*global define*/
define('Core/Cartographic',[
'./defaultValue',
'./defined',
'./DeveloperError',
'./freezeObject',
'./Math'
], function(
defaultValue,
defined,
DeveloperError,
freezeObject,
CesiumMath) {
"use strict";
/**
* A position defined by longitude, latitude, and height.
* @alias Cartographic
* @constructor
*
* @param {Number} [longitude=0.0] The longitude, in radians.
* @param {Number} [latitude=0.0] The latitude, in radians.
* @param {Number} [height=0.0] The height, in meters, above the ellipsoid.
*
* @see Ellipsoid
*/
var Cartographic = function(longitude, latitude, height) {
/**
* The longitude, in radians.
* @type {Number}
* @default 0.0
*/
this.longitude = defaultValue(longitude, 0.0);
/**
* The latitude, in radians.
* @type {Number}
* @default 0.0
*/
this.latitude = defaultValue(latitude, 0.0);
/**
* The height, in meters, above the ellipsoid.
* @type {Number}
* @default 0.0
*/
this.height = defaultValue(height, 0.0);
};
/**
* Creates a new Cartographic instance from longitude and latitude
* specified in radians.
*
* @param {Number} longitude The longitude, in radians.
* @param {Number} latitude The latitude, in radians.
* @param {Number} [height=0.0] The height, in meters, above the ellipsoid.
* @param {Cartographic} [result] The object onto which to store the result.
* @returns {Cartographic} The modified result parameter or a new Cartographic instance if one was not provided.
*/
Cartographic.fromRadians = function(longitude, latitude, height, result) {
if (!defined(longitude)) {
throw new DeveloperError('longitude is required.');
}
if (!defined(latitude)) {
throw new DeveloperError('latitude is required.');
}
height = defaultValue(height, 0.0);
if (!defined(result)) {
return new Cartographic(longitude, latitude, height);
}
result.longitude = longitude;
result.latitude = latitude;
result.height = height;
return result;
};
/**
* Creates a new Cartographic instance from longitude and latitude
* specified in degrees. The values in the resulting object will
* be in radians.
*
* @param {Number} longitude The longitude, in degrees.
* @param {Number} latitude The latitude, in degrees.
* @param {Number} [height=0.0] The height, in meters, above the ellipsoid.
* @param {Cartographic} [result] The object onto which to store the result.
* @returns {Cartographic} The modified result parameter or a new Cartographic instance if one was not provided.
*/
Cartographic.fromDegrees = function(longitude, latitude, height, result) {
if (!defined(longitude)) {
throw new DeveloperError('longitude is required.');
}
if (!defined(latitude)) {
throw new DeveloperError('latitude is required.');
}
longitude = CesiumMath.toRadians(longitude);
latitude = CesiumMath.toRadians(latitude);
return Cartographic.fromRadians(longitude, latitude, height, result);
};
/**
* Duplicates a Cartographic instance.
*
* @param {Cartographic} cartographic The cartographic to duplicate.
* @param {Cartographic} [result] The object onto which to store the result.
* @returns {Cartographic} The modified result parameter or a new Cartographic instance if one was not provided. (Returns undefined if cartographic is undefined)
*/
Cartographic.clone = function(cartographic, result) {
if (!defined(cartographic)) {
return undefined;
}
if (!defined(result)) {
return new Cartographic(cartographic.longitude, cartographic.latitude, cartographic.height);
}
result.longitude = cartographic.longitude;
result.latitude = cartographic.latitude;
result.height = cartographic.height;
return result;
};
/**
* Compares the provided cartographics componentwise and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Cartographic} [left] The first cartographic.
* @param {Cartographic} [right] The second cartographic.
* @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
Cartographic.equals = function(left, right) {
return (left === right) ||
((defined(left)) &&
(defined(right)) &&
(left.longitude === right.longitude) &&
(left.latitude === right.latitude) &&
(left.height === right.height));
};
/**
* Compares the provided cartographics componentwise and returns
* <code>true</code> if they are within the provided epsilon,
* <code>false</code> otherwise.
*
* @param {Cartographic} [left] The first cartographic.
* @param {Cartographic} [right] The second cartographic.
* @param {Number} epsilon The epsilon to use for equality testing.
* @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
*/
Cartographic.equalsEpsilon = function(left, right, epsilon) {
if (typeof epsilon !== 'number') {
throw new DeveloperError('epsilon is required and must be a number.');
}
return (left === right) ||
((defined(left)) &&
(defined(right)) &&
(Math.abs(left.longitude - right.longitude) <= epsilon) &&
(Math.abs(left.latitude - right.latitude) <= epsilon) &&
(Math.abs(left.height - right.height) <= epsilon));
};
/**
* An immutable Cartographic instance initialized to (0.0, 0.0, 0.0).
*
* @type {Cartographic}
* @constant
*/
Cartographic.ZERO = freezeObject(new Cartographic(0.0, 0.0, 0.0));
/**
* Duplicates this instance.
*
* @param {Cartographic} [result] The object onto which to store the result.
* @returns {Cartographic} The modified result parameter or a new Cartographic instance if one was not provided.
*/
Cartographic.prototype.clone = function(result) {
return Cartographic.clone(this, result);
};
/**
* Compares the provided against this cartographic componentwise and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Cartographic} [right] The second cartographic.
* @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
Cartographic.prototype.equals = function(right) {
return Cartographic.equals(this, right);
};
/**
* Compares the provided against this cartographic componentwise and returns
* <code>true</code> if they are within the provided epsilon,
* <code>false</code> otherwise.
*
* @param {Cartographic} [right] The second cartographic.
* @param {Number} epsilon The epsilon to use for equality testing.
* @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
*/
Cartographic.prototype.equalsEpsilon = function(right, epsilon) {
return Cartographic.equalsEpsilon(this, right, epsilon);
};
/**
* Creates a string representing this cartographic in the format '(longitude, latitude, height)'.
*
* @returns {String} A string representing the provided cartographic in the format '(longitude, latitude, height)'.
*/
Cartographic.prototype.toString = function() {
return '(' + this.longitude + ', ' + this.latitude + ', ' + this.height + ')';
};
return Cartographic;
});
/*global define*/
define('Core/defineProperties',[
'./defined'
], function(
defined) {
"use strict";
var definePropertyWorks = (function() {
try {
return 'x' in Object.defineProperty({}, 'x', {});
} catch (e) {
return false;
}
})();
/**
* Defines properties on an object, using Object.defineProperties if available,
* otherwise returns the object unchanged. This function should be used in
* setup code to prevent errors from completely halting JavaScript execution
* in legacy browsers.
*
* @private
*
* @exports defineProperties
*/
var defineProperties = Object.defineProperties;
if (!definePropertyWorks || !defined(defineProperties)) {
defineProperties = function(o) {
return o;
};
}
return defineProperties;
});
/*global define*/
define('Core/Ellipsoid',[
'./Cartesian3',
'./Cartographic',
'./defaultValue',
'./defined',
'./defineProperties',
'./DeveloperError',
'./freezeObject',
'./Math'
], function(
Cartesian3,
Cartographic,
defaultValue,
defined,
defineProperties,
DeveloperError,
freezeObject,
CesiumMath) {
"use strict";
function initialize(ellipsoid, x, y, z) {
x = defaultValue(x, 0.0);
y = defaultValue(y, 0.0);
z = defaultValue(z, 0.0);
if (x < 0.0 || y < 0.0 || z < 0.0) {
throw new DeveloperError('All radii components must be greater than or equal to zero.');
}
ellipsoid._radii = new Cartesian3(x, y, z);
ellipsoid._radiiSquared = new Cartesian3(x * x,
y * y,
z * z);
ellipsoid._radiiToTheFourth = new Cartesian3(x * x * x * x,
y * y * y * y,
z * z * z * z);
ellipsoid._oneOverRadii = new Cartesian3(x === 0.0 ? 0.0 : 1.0 / x,
y === 0.0 ? 0.0 : 1.0 / y,
z === 0.0 ? 0.0 : 1.0 / z);
ellipsoid._oneOverRadiiSquared = new Cartesian3(x === 0.0 ? 0.0 : 1.0 / (x * x),
y === 0.0 ? 0.0 : 1.0 / (y * y),
z === 0.0 ? 0.0 : 1.0 / (z * z));
ellipsoid._minimumRadius = Math.min(x, y, z);
ellipsoid._maximumRadius = Math.max(x, y, z);
ellipsoid._centerToleranceSquared = CesiumMath.EPSILON1;
}
/**
* A quadratic surface defined in Cartesian coordinates by the equation
* <code>(x / a)^2 + (y / b)^2 + (z / c)^2 = 1</code>. Primarily used
* by Cesium to represent the shape of planetary bodies.
*
* Rather than constructing this object directly, one of the provided
* constants is normally used.
* @alias Ellipsoid
* @constructor
*
* @param {Number} [x=0] The radius in the x direction.
* @param {Number} [y=0] The radius in the y direction.
* @param {Number} [z=0] The radius in the z direction.
*
* @exception {DeveloperError} All radii components must be greater than or equal to zero.
*
* @see Ellipsoid.fromCartesian3
* @see Ellipsoid.WGS84
* @see Ellipsoid.UNIT_SPHERE
*/
var Ellipsoid = function(x, y, z) {
this._radii = undefined;
this._radiiSquared = undefined;
this._radiiToTheFourth = undefined;
this._oneOverRadii = undefined;
this._oneOverRadiiSquared = undefined;
this._minimumRadius = undefined;
this._maximumRadius = undefined;
this._centerToleranceSquared = undefined;
initialize(this, x, y, z);
};
defineProperties(Ellipsoid.prototype, {
/**
* Gets the radii of the ellipsoid.
* @memberof Ellipsoid.prototype
* @type {Cartesian3}
*/
radii : {
get: function() {
return this._radii;
}
},
/**
* Gets the squared radii of the ellipsoid.
* @memberof Ellipsoid.prototype
* @type {Cartesian3}
*/
radiiSquared : {
get : function() {
return this._radiiSquared;
}
},
/**
* Gets the radii of the ellipsoid raise to the fourth power.
* @memberof Ellipsoid.prototype
* @type {Cartesian3}
*/
radiiToTheFourth : {
get : function() {
return this._radiiToTheFourth;
}
},
/**
* Gets one over the radii of the ellipsoid.
* @memberof Ellipsoid.prototype
* @type {Cartesian3}
*/
oneOverRadii : {
get : function() {
return this._oneOverRadii;
}
},
/**
* Gets one over the squared radii of the ellipsoid.
* @memberof Ellipsoid.prototype
* @type {Cartesian3}
*/
oneOverRadiiSquared : {
get : function() {
return this._oneOverRadiiSquared;
}
},
/**
* Gets the minimum radius of the ellipsoid.
* @memberof Ellipsoid.prototype
* @type {Number}
*/
minimumRadius : {
get : function() {
return this._minimumRadius;
}
},
/**
* Gets the maximum radius of the ellipsoid.
* @memberof Ellipsoid.prototype
* @type {Number}
*/
maximumRadius : {
get : function() {
return this._maximumRadius;
}
}
});
/**
* Duplicates an Ellipsoid instance.
*
* @param {Ellipsoid} ellipsoid The ellipsoid to duplicate.
* @param {Ellipsoid} [result] The object onto which to store the result, or undefined if a new
* instance should be created.
* @returns {Ellipsoid} The cloned Ellipsoid. (Returns undefined if ellipsoid is undefined)
*/
Ellipsoid.clone = function(ellipsoid, result) {
if (!defined(ellipsoid)) {
return undefined;
}
var radii = ellipsoid._radii;
if (!defined(result)) {
return new Ellipsoid(radii.x, radii.y, radii.z);
}
Cartesian3.clone(radii, result._radii);
Cartesian3.clone(ellipsoid._radiiSquared, result._radiiSquared);
Cartesian3.clone(ellipsoid._radiiToTheFourth, result._radiiToTheFourth);
Cartesian3.clone(ellipsoid._oneOverRadii, result._oneOverRadii);
Cartesian3.clone(ellipsoid._oneOverRadiiSquared, result._oneOverRadiiSquared);
result._minimumRadius = ellipsoid._minimumRadius;
result._maximumRadius = ellipsoid._maximumRadius;
result._centerToleranceSquared = ellipsoid._centerToleranceSquared;
return result;
};
/**
* Computes an Ellipsoid from a Cartesian specifying the radii in x, y, and z directions.
*
* @param {Cartesian3} [radii=Cartesian3.ZERO] The ellipsoid's radius in the x, y, and z directions.
* @returns {Ellipsoid} A new Ellipsoid instance.
*
* @exception {DeveloperError} All radii components must be greater than or equal to zero.
*
* @see Ellipsoid.WGS84
* @see Ellipsoid.UNIT_SPHERE
*/
Ellipsoid.fromCartesian3 = function(cartesian, result) {
if (!defined(result)) {
result = new Ellipsoid();
}
if (!defined(cartesian)) {
return result;
}
initialize(result, cartesian.x, cartesian.y, cartesian.z);
return result;
};
/**
* An Ellipsoid instance initialized to the WGS84 standard.
*
* @type {Ellipsoid}
* @constant
*/
Ellipsoid.WGS84 = freezeObject(new Ellipsoid(6378137.0, 6378137.0, 6356752.3142451793));
/**
* An Ellipsoid instance initialized to radii of (1.0, 1.0, 1.0).
*
* @type {Ellipsoid}
* @constant
*/
Ellipsoid.UNIT_SPHERE = freezeObject(new Ellipsoid(1.0, 1.0, 1.0));
/**
* An Ellipsoid instance initialized to a sphere with the lunar radius.
*
* @type {Ellipsoid}
* @constant
*/
Ellipsoid.MOON = freezeObject(new Ellipsoid(CesiumMath.LUNAR_RADIUS, CesiumMath.LUNAR_RADIUS, CesiumMath.LUNAR_RADIUS));
/**
* Duplicates an Ellipsoid instance.
*
* @param {Ellipsoid} [result] The object onto which to store the result, or undefined if a new
* instance should be created.
* @returns {Ellipsoid} The cloned Ellipsoid.
*/
Ellipsoid.prototype.clone = function(result) {
return Ellipsoid.clone(this, result);
};
/**
* The number of elements used to pack the object into an array.
* @type {Number}
*/
Ellipsoid.packedLength = Cartesian3.packedLength;
/**
* Stores the provided instance into the provided array.
* @function
*
* @param {Object} value The value to pack.
* @param {Number[]} array The array to pack into.
* @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
*/
Ellipsoid.pack = function(value, array, startingIndex) {
if (!defined(value)) {
throw new DeveloperError('value is required');
}
if (!defined(array)) {
throw new DeveloperError('array is required');
}
startingIndex = defaultValue(startingIndex, 0);
Cartesian3.pack(value._radii, array, startingIndex);
};
/**
* Retrieves an instance from a packed array.
*
* @param {Number[]} array The packed array.
* @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
* @param {Ellipsoid} [result] The object into which to store the result.
*/
Ellipsoid.unpack = function(array, startingIndex, result) {
if (!defined(array)) {
throw new DeveloperError('array is required');
}
startingIndex = defaultValue(startingIndex, 0);
var radii = Cartesian3.unpack(array, startingIndex);
return Ellipsoid.fromCartesian3(radii, result);
};
/**
* Computes the unit vector directed from the center of this ellipsoid toward the provided Cartesian position.
* @function
*
* @param {Cartesian3} cartesian The Cartesian for which to to determine the geocentric normal.
* @param {Cartesian3} [result] The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if none was provided.
*/
Ellipsoid.prototype.geocentricSurfaceNormal = Cartesian3.normalize;
/**
* Computes the normal of the plane tangent to the surface of the ellipsoid at the provided position.
*
* @param {Cartographic} cartographic The cartographic position for which to to determine the geodetic normal.
* @param {Cartesian3} [result] The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if none was provided.
*/
Ellipsoid.prototype.geodeticSurfaceNormalCartographic = function(cartographic, result) {
if (!defined(cartographic)) {
throw new DeveloperError('cartographic is required.');
}
var longitude = cartographic.longitude;
var latitude = cartographic.latitude;
var cosLatitude = Math.cos(latitude);
var x = cosLatitude * Math.cos(longitude);
var y = cosLatitude * Math.sin(longitude);
var z = Math.sin(latitude);
if (!defined(result)) {
result = new Cartesian3();
}
result.x = x;
result.y = y;
result.z = z;
return Cartesian3.normalize(result, result);
};
/**
* Computes the normal of the plane tangent to the surface of the ellipsoid at the provided position.
*
* @param {Cartesian3} cartesian The Cartesian position for which to to determine the surface normal.
* @param {Cartesian3} [result] The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if none was provided.
*/
Ellipsoid.prototype.geodeticSurfaceNormal = function(cartesian, result) {
if (!defined(result)) {
result = new Cartesian3();
}
result = Cartesian3.multiplyComponents(cartesian, this._oneOverRadiiSquared, result);
return Cartesian3.normalize(result, result);
};
var cartographicToCartesianNormal = new Cartesian3();
var cartographicToCartesianK = new Cartesian3();
/**
* Converts the provided cartographic to Cartesian representation.
*
* @param {Cartographic} cartographic The cartographic position.
* @param {Cartesian3} [result] The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if none was provided.
*
* @example
* //Create a Cartographic and determine it's Cartesian representation on a WGS84 ellipsoid.
* var position = new Cesium.Cartographic(Cesium.Math.toRadians(21), Cesium.Math.toRadians(78), 5000);
* var cartesianPosition = Cesium.Ellipsoid.WGS84.cartographicToCartesian(position);
*/
Ellipsoid.prototype.cartographicToCartesian = function(cartographic, result) {
//`cartographic is required` is thrown from geodeticSurfaceNormalCartographic.
var n = cartographicToCartesianNormal;
var k = cartographicToCartesianK;
this.geodeticSurfaceNormalCartographic(cartographic, n);
Cartesian3.multiplyComponents(this._radiiSquared, n, k);
var gamma = Math.sqrt(Cartesian3.dot(n, k));
Cartesian3.divideByScalar(k, gamma, k);
Cartesian3.multiplyByScalar(n, cartographic.height, n);
if (!defined(result)) {
result = new Cartesian3();
}
return Cartesian3.add(k, n, result);
};
/**
* Converts the provided array of cartographics to an array of Cartesians.
*
* @param {Cartographic[]} cartographics An array of cartographic positions.
* @param {Cartesian3[]} [result] The object onto which to store the result.
* @returns {Cartesian3[]} The modified result parameter or a new Array instance if none was provided.
*
* @example
* //Convert an array of Cartographics and determine their Cartesian representation on a WGS84 ellipsoid.
* var positions = [new Cesium.Cartographic(Cesium.Math.toRadians(21), Cesium.Math.toRadians(78), 0),
* new Cesium.Cartographic(Cesium.Math.toRadians(21.321), Cesium.Math.toRadians(78.123), 100),
* new Cesium.Cartographic(Cesium.Math.toRadians(21.645), Cesium.Math.toRadians(78.456), 250)
* var cartesianPositions = Cesium.Ellipsoid.WGS84.cartographicArrayToCartesianArray(positions);
*/
Ellipsoid.prototype.cartographicArrayToCartesianArray = function(cartographics, result) {
if (!defined(cartographics)) {
throw new DeveloperError('cartographics is required.');
}
var length = cartographics.length;
if (!defined(result)) {
result = new Array(length);
} else {
result.length = length;
}
for ( var i = 0; i < length; i++) {
result[i] = this.cartographicToCartesian(cartographics[i], result[i]);
}
return result;
};
var cartesianToCartographicN = new Cartesian3();
var cartesianToCartographicP = new Cartesian3();
var cartesianToCartographicH = new Cartesian3();
/**
* Converts the provided cartesian to cartographic representation.
* The cartesian is undefined at the center of the ellipsoid.
*
* @param {Cartesian3} cartesian The Cartesian position to convert to cartographic representation.
* @param {Cartographic} [result] The object onto which to store the result.
* @returns {Cartographic} The modified result parameter, new Cartographic instance if none was provided, or undefined if the cartesian is at the center of the ellipsoid.
*
* @example
* //Create a Cartesian and determine it's Cartographic representation on a WGS84 ellipsoid.
* var position = new Cesium.Cartesian(17832.12, 83234.52, 952313.73);
* var cartographicPosition = Cesium.Ellipsoid.WGS84.cartesianToCartographic(position);
*/
Ellipsoid.prototype.cartesianToCartographic = function(cartesian, result) {
//`cartesian is required.` is thrown from scaleToGeodeticSurface
var p = this.scaleToGeodeticSurface(cartesian, cartesianToCartographicP);
if (!defined(p)) {
return undefined;
}
var n = this.geodeticSurfaceNormal(p, cartesianToCartographicN);
var h = Cartesian3.subtract(cartesian, p, cartesianToCartographicH);
var longitude = Math.atan2(n.y, n.x);
var latitude = Math.asin(n.z);
var height = CesiumMath.sign(Cartesian3.dot(h, cartesian)) * Cartesian3.magnitude(h);
if (!defined(result)) {
return new Cartographic(longitude, latitude, height);
}
result.longitude = longitude;
result.latitude = latitude;
result.height = height;
return result;
};
/**
* Converts the provided array of cartesians to an array of cartographics.
*
* @param {Cartesian3[]} cartesians An array of Cartesian positions.
* @param {Cartographic[]} [result] The object onto which to store the result.
* @returns {Cartographic[]} The modified result parameter or a new Array instance if none was provided.
*
* @example
* //Create an array of Cartesians and determine their Cartographic representation on a WGS84 ellipsoid.
* var positions = [new Cesium.Cartesian3(17832.12, 83234.52, 952313.73),
* new Cesium.Cartesian3(17832.13, 83234.53, 952313.73),
* new Cesium.Cartesian3(17832.14, 83234.54, 952313.73)]
* var cartographicPositions = Cesium.Ellipsoid.WGS84.cartesianArrayToCartographicArray(positions);
*/
Ellipsoid.prototype.cartesianArrayToCartographicArray = function(cartesians, result) {
if (!defined(cartesians)) {
throw new DeveloperError('cartesians is required.');
}
var length = cartesians.length;
if (!defined(result)) {
result = new Array(length);
} else {
result.length = length;
}
for ( var i = 0; i < length; ++i) {
result[i] = this.cartesianToCartographic(cartesians[i], result[i]);
}
return result;
};
var scaleToGeodeticSurfaceIntersection = new Cartesian3();
var scaleToGeodeticSurfaceGradient = new Cartesian3();
/**
* Scales the provided Cartesian position along the geodetic surface normal
* so that it is on the surface of this ellipsoid. If the position is
* at the center of the ellipsoid, this function returns undefined.
*
* @param {Cartesian3} cartesian The Cartesian position to scale.
* @param {Cartesian3} [result] The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter, a new Cartesian3 instance if none was provided, or undefined if the position is at the center.
*/
Ellipsoid.prototype.scaleToGeodeticSurface = function(cartesian, result) {
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required.');
}
var positionX = cartesian.x;
var positionY = cartesian.y;
var positionZ = cartesian.z;
var oneOverRadii = this._oneOverRadii;
var oneOverRadiiX = oneOverRadii.x;
var oneOverRadiiY = oneOverRadii.y;
var oneOverRadiiZ = oneOverRadii.z;
var x2 = positionX * positionX * oneOverRadiiX * oneOverRadiiX;
var y2 = positionY * positionY * oneOverRadiiY * oneOverRadiiY;
var z2 = positionZ * positionZ * oneOverRadiiZ * oneOverRadiiZ;
// Compute the squared ellipsoid norm.
var squaredNorm = x2 + y2 + z2;
var ratio = Math.sqrt(1.0 / squaredNorm);
// As an initial approximation, assume that the radial intersection is the projection point.
var intersection = Cartesian3.multiplyByScalar(cartesian, ratio, scaleToGeodeticSurfaceIntersection);
//* If the position is near the center, the iteration will not converge.
if (squaredNorm < this._centerToleranceSquared) {
return !isFinite(ratio) ? undefined : Cartesian3.clone(intersection, result);
}
var oneOverRadiiSquared = this._oneOverRadiiSquared;
var oneOverRadiiSquaredX = oneOverRadiiSquared.x;
var oneOverRadiiSquaredY = oneOverRadiiSquared.y;
var oneOverRadiiSquaredZ = oneOverRadiiSquared.z;
// Use the gradient at the intersection point in place of the true unit normal.
// The difference in magnitude will be absorbed in the multiplier.
var gradient = scaleToGeodeticSurfaceGradient;
gradient.x = intersection.x * oneOverRadiiSquaredX * 2.0;
gradient.y = intersection.y * oneOverRadiiSquaredY * 2.0;
gradient.z = intersection.z * oneOverRadiiSquaredZ * 2.0;
// Compute the initial guess at the normal vector multiplier, lambda.
var lambda = (1.0 - ratio) * Cartesian3.magnitude(cartesian) / (0.5 * Cartesian3.magnitude(gradient));
var correction = 0.0;
var func;
var denominator;
var xMultiplier;
var yMultiplier;
var zMultiplier;
var xMultiplier2;
var yMultiplier2;
var zMultiplier2;
var xMultiplier3;
var yMultiplier3;
var zMultiplier3;
do {
lambda -= correction;
xMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredX);
yMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredY);
zMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredZ);
xMultiplier2 = xMultiplier * xMultiplier;
yMultiplier2 = yMultiplier * yMultiplier;
zMultiplier2 = zMultiplier * zMultiplier;
xMultiplier3 = xMultiplier2 * xMultiplier;
yMultiplier3 = yMultiplier2 * yMultiplier;
zMultiplier3 = zMultiplier2 * zMultiplier;
func = x2 * xMultiplier2 + y2 * yMultiplier2 + z2 * zMultiplier2 - 1.0;
// "denominator" here refers to the use of this expression in the velocity and acceleration
// computations in the sections to follow.
denominator = x2 * xMultiplier3 * oneOverRadiiSquaredX + y2 * yMultiplier3 * oneOverRadiiSquaredY + z2 * zMultiplier3 * oneOverRadiiSquaredZ;
var derivative = -2.0 * denominator;
correction = func / derivative;
} while (Math.abs(func) > CesiumMath.EPSILON12);
if (!defined(result)) {
return new Cartesian3(positionX * xMultiplier, positionY * yMultiplier, positionZ * zMultiplier);
}
result.x = positionX * xMultiplier;
result.y = positionY * yMultiplier;
result.z = positionZ * zMultiplier;
return result;
};
/**
* Scales the provided Cartesian position along the geocentric surface normal
* so that it is on the surface of this ellipsoid.
*
* @param {Cartesian3} cartesian The Cartesian position to scale.
* @param {Cartesian3} [result] The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if none was provided.
*/
Ellipsoid.prototype.scaleToGeocentricSurface = function(cartesian, result) {
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required.');
}
if (!defined(result)) {
result = new Cartesian3();
}
var positionX = cartesian.x;
var positionY = cartesian.y;
var positionZ = cartesian.z;
var oneOverRadiiSquared = this._oneOverRadiiSquared;
var beta = 1.0 / Math.sqrt((positionX * positionX) * oneOverRadiiSquared.x +
(positionY * positionY) * oneOverRadiiSquared.y +
(positionZ * positionZ) * oneOverRadiiSquared.z);
return Cartesian3.multiplyByScalar(cartesian, beta, result);
};
/**
* Transforms a Cartesian X, Y, Z position to the ellipsoid-scaled space by multiplying
* its components by the result of {@link Ellipsoid#oneOverRadii}.
*
* @param {Cartesian3} position The position to transform.
* @param {Cartesian3} [result] The position to which to copy the result, or undefined to create and
* return a new instance.
* @returns {Cartesian3} The position expressed in the scaled space. The returned instance is the
* one passed as the result parameter if it is not undefined, or a new instance of it is.
*/
Ellipsoid.prototype.transformPositionToScaledSpace = function(position, result) {
if (!defined(result)) {
result = new Cartesian3();
}
return Cartesian3.multiplyComponents(position, this._oneOverRadii, result);
};
/**
* Transforms a Cartesian X, Y, Z position from the ellipsoid-scaled space by multiplying
* its components by the result of {@link Ellipsoid#radii}.
*
* @param {Cartesian3} position The position to transform.
* @param {Cartesian3} [result] The position to which to copy the result, or undefined to create and
* return a new instance.
* @returns {Cartesian3} The position expressed in the unscaled space. The returned instance is the
* one passed as the result parameter if it is not undefined, or a new instance of it is.
*/
Ellipsoid.prototype.transformPositionFromScaledSpace = function(position, result) {
if (!defined(result)) {
result = new Cartesian3();
}
return Cartesian3.multiplyComponents(position, this._radii, result);
};
/**
* Compares this Ellipsoid against the provided Ellipsoid componentwise and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Ellipsoid} [right] The other Ellipsoid.
* @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
*/
Ellipsoid.prototype.equals = function(right) {
return (this === right) ||
(defined(right) &&
Cartesian3.equals(this._radii, right._radii));
};
/**
* Creates a string representing this Ellipsoid in the format '(radii.x, radii.y, radii.z)'.
*
* @returns {String} A string representing this ellipsoid in the format '(radii.x, radii.y, radii.z)'.
*/
Ellipsoid.prototype.toString = function() {
return this._radii.toString();
};
return Ellipsoid;
});
/*global define*/
define('Core/GeographicProjection',[
'./Cartesian3',
'./Cartographic',
'./defaultValue',
'./defined',
'./defineProperties',
'./DeveloperError',
'./Ellipsoid'
], function(
Cartesian3,
Cartographic,
defaultValue,
defined,
defineProperties,
DeveloperError,
Ellipsoid) {
"use strict";
/**
* A simple map projection where longitude and latitude are linearly mapped to X and Y by multiplying
* them by the {@link Ellipsoid#maximumRadius}. This projection
* is commonly known as geographic, equirectangular, equidistant cylindrical, or plate carrée. It
* is also known as EPSG:4326.
*
* @alias GeographicProjection
* @constructor
*
* @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid.
*
* @see WebMercatorProjection
*/
var GeographicProjection = function(ellipsoid) {
this._ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
this._semimajorAxis = this._ellipsoid.maximumRadius;
this._oneOverSemimajorAxis = 1.0 / this._semimajorAxis;
};
defineProperties(GeographicProjection.prototype, {
/**
* Gets the {@link Ellipsoid}.
*
* @memberof GeographicProjection.prototype
*
* @type {Ellipsoid}
* @readonly
*/
ellipsoid : {
get : function() {
return this._ellipsoid;
}
}
});
/**
* Projects a set of {@link Cartographic} coordinates, in radians, to map coordinates, in meters.
* X and Y are the longitude and latitude, respectively, multiplied by the maximum radius of the
* ellipsoid. Z is the unmodified height.
*
* @param {Cartographic} cartographic The coordinates to project.
* @param {Cartesian3} [result] An instance into which to copy the result. If this parameter is
* undefined, a new instance is created and returned.
* @returns {Cartesian3} The projected coordinates. If the result parameter is not undefined, the
* coordinates are copied there and that instance is returned. Otherwise, a new instance is
* created and returned.
*/
GeographicProjection.prototype.project = function(cartographic, result) {
// Actually this is the special case of equidistant cylindrical called the plate carree
var semimajorAxis = this._semimajorAxis;
var x = cartographic.longitude * semimajorAxis;
var y = cartographic.latitude * semimajorAxis;
var z = cartographic.height;
if (!defined(result)) {
return new Cartesian3(x, y, z);
}
result.x = x;
result.y = y;
result.z = z;
return result;
};
/**
* Unprojects a set of projected {@link Cartesian3} coordinates, in meters, to {@link Cartographic}
* coordinates, in radians. Longitude and Latitude are the X and Y coordinates, respectively,
* divided by the maximum radius of the ellipsoid. Height is the unmodified Z coordinate.
*
* @param {Cartesian3} cartesian The Cartesian position to unproject with height (z) in meters.
* @param {Cartographic} [result] An instance into which to copy the result. If this parameter is
* undefined, a new instance is created and returned.
* @returns {Cartographic} The unprojected coordinates. If the result parameter is not undefined, the
* coordinates are copied there and that instance is returned. Otherwise, a new instance is
* created and returned.
*/
GeographicProjection.prototype.unproject = function(cartesian, result) {
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required');
}
var oneOverEarthSemimajorAxis = this._oneOverSemimajorAxis;
var longitude = cartesian.x * oneOverEarthSemimajorAxis;
var latitude = cartesian.y * oneOverEarthSemimajorAxis;
var height = cartesian.z;
if (!defined(result)) {
return new Cartographic(longitude, latitude, height);
}
result.longitude = longitude;
result.latitude = latitude;
result.height = height;
return result;
};
return GeographicProjection;
});
/*global define*/
define('Core/Intersect',[
'./freezeObject'
], function(
freezeObject) {
"use strict";
/**
* This enumerated type is used in determining where, relative to the frustum, an
* object is located. The object can either be fully contained within the frustum (INSIDE),
* partially inside the frustum and partially outside (INTERSECTING), or somwhere entirely
* outside of the frustum's 6 planes (OUTSIDE).
*
* @namespace
* @alias Intersect
*/
var Intersect = {
/**
* Represents that an object is not contained within the frustum.
*
* @type {Number}
* @constant
*/
OUTSIDE : -1,
/**
* Represents that an object intersects one of the frustum's planes.
*
* @type {Number}
* @constant
*/
INTERSECTING : 0,
/**
* Represents that an object is fully within the frustum.
*
* @type {Number}
* @constant
*/
INSIDE : 1
};
return freezeObject(Intersect);
});
/*global define*/
define('Core/Interval',[
'./defaultValue'
], function(
defaultValue) {
"use strict";
/**
* Represents the closed interval [start, stop].
* @alias Interval
* @constructor
*
* @param {Number} [start=0.0] The beginning of the interval.
* @param {Number} [stop=0.0] The end of the interval.
*/
var Interval = function(start, stop) {
/**
* The beginning of the interval.
* @type {Number}
* @default 0.0
*/
this.start = defaultValue(start, 0.0);
/**
* The end of the interval.
* @type {Number}
* @default 0.0
*/
this.stop = defaultValue(stop, 0.0);
};
return Interval;
});
/*global define*/
define('Core/Cartesian4',[
'./defaultValue',
'./defined',
'./DeveloperError',
'./freezeObject',
'./Math'
], function(
defaultValue,
defined,
DeveloperError,
freezeObject,
CesiumMath) {
"use strict";
/**
* A 4D Cartesian point.
* @alias Cartesian4
* @constructor
*
* @param {Number} [x=0.0] The X component.
* @param {Number} [y=0.0] The Y component.
* @param {Number} [z=0.0] The Z component.
* @param {Number} [w=0.0] The W component.
*
* @see Cartesian2
* @see Cartesian3
* @see Packable
*/
var Cartesian4 = function(x, y, z, w) {
/**
* The X component.
* @type {Number}
* @default 0.0
*/
this.x = defaultValue(x, 0.0);
/**
* The Y component.
* @type {Number}
* @default 0.0
*/
this.y = defaultValue(y, 0.0);
/**
* The Z component.
* @type {Number}
* @default 0.0
*/
this.z = defaultValue(z, 0.0);
/**
* The W component.
* @type {Number}
* @default 0.0
*/
this.w = defaultValue(w, 0.0);
};
/**
* Creates a Cartesian4 instance from x, y, z and w coordinates.
*
* @param {Number} x The x coordinate.
* @param {Number} y The y coordinate.
* @param {Number} z The z coordinate.
* @param {Number} w The w coordinate.
* @param {Cartesian4} [result] The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
*/
Cartesian4.fromElements = function(x, y, z, w, result) {
if (!defined(result)) {
return new Cartesian4(x, y, z, w);
}
result.x = x;
result.y = y;
result.z = z;
result.w = w;
return result;
};
/**
* Creates a Cartesian4 instance from a {@link Color}. <code>red</code>, <code>green</code>, <code>blue</code>,
* and <code>alpha</code> map to <code>x</code>, <code>y</code>, <code>z</code>, and <code>w</code>, respectively.
*
* @param {Color} color The source color.
* @param {Cartesian4} [result] The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
*/
Cartesian4.fromColor = function(color, result) {
if (!defined(color)) {
throw new DeveloperError('color is required');
}
if (!defined(result)) {
return new Cartesian4(color.red, color.green, color.blue, color.alpha);
}
result.x = color.red;
result.y = color.green;
result.z = color.blue;
result.w = color.alpha;
return result;
};
/**
* Duplicates a Cartesian4 instance.
*
* @param {Cartesian4} cartesian The Cartesian to duplicate.
* @param {Cartesian4} [result] The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided. (Returns undefined if cartesian is undefined)
*/
Cartesian4.clone = function(cartesian, result) {
if (!defined(cartesian)) {
return undefined;
}
if (!defined(result)) {
return new Cartesian4(cartesian.x, cartesian.y, cartesian.z, cartesian.w);
}
result.x = cartesian.x;
result.y = cartesian.y;
result.z = cartesian.z;
result.w = cartesian.w;
return result;
};
/**
* The number of elements used to pack the object into an array.
* @type {Number}
*/
Cartesian4.packedLength = 4;
/**
* Stores the provided instance into the provided array.
*
* @param {Cartesian4} value The value to pack.
* @param {Number[]} array The array to pack into.
* @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
*/
Cartesian4.pack = function(value, array, startingIndex) {
if (!defined(value)) {
throw new DeveloperError('value is required');
}
if (!defined(array)) {
throw new DeveloperError('array is required');
}
startingIndex = defaultValue(startingIndex, 0);
array[startingIndex++] = value.x;
array[startingIndex++] = value.y;
array[startingIndex++] = value.z;
array[startingIndex] = value.w;
};
/**
* Retrieves an instance from a packed array.
*
* @param {Number[]} array The packed array.
* @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
* @param {Cartesian4} [result] The object into which to store the result.
* @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
*/
Cartesian4.unpack = function(array, startingIndex, result) {
if (!defined(array)) {
throw new DeveloperError('array is required');
}
startingIndex = defaultValue(startingIndex, 0);
if (!defined(result)) {
result = new Cartesian4();
}
result.x = array[startingIndex++];
result.y = array[startingIndex++];
result.z = array[startingIndex++];
result.w = array[startingIndex];
return result;
};
/**
* Creates a Cartesian4 from four consecutive elements in an array.
* @function
*
* @param {Number[]} array The array whose four consecutive elements correspond to the x, y, z, and w components, respectively.
* @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to the x component.
* @param {Cartesian4} [result] The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
*
* @example
* // Create a Cartesian4 with (1.0, 2.0, 3.0, 4.0)
* var v = [1.0, 2.0, 3.0, 4.0];
* var p = Cesium.Cartesian4.fromArray(v);
*
* // Create a Cartesian4 with (1.0, 2.0, 3.0, 4.0) using an offset into an array
* var v2 = [0.0, 0.0, 1.0, 2.0, 3.0, 4.0];
* var p2 = Cesium.Cartesian4.fromArray(v2, 2);
*/
Cartesian4.fromArray = Cartesian4.unpack;
/**
* Computes the value of the maximum component for the supplied Cartesian.
*
* @param {Cartesian4} cartesian The cartesian to use.
* @returns {Number} The value of the maximum component.
*/
Cartesian4.maximumComponent = function(cartesian) {
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required');
}
return Math.max(cartesian.x, cartesian.y, cartesian.z, cartesian.w);
};
/**
* Computes the value of the minimum component for the supplied Cartesian.
*
* @param {Cartesian4} cartesian The cartesian to use.
* @returns {Number} The value of the minimum component.
*/
Cartesian4.minimumComponent = function(cartesian) {
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required');
}
return Math.min(cartesian.x, cartesian.y, cartesian.z, cartesian.w);
};
/**
* Compares two Cartesians and computes a Cartesian which contains the minimum components of the supplied Cartesians.
*
* @param {Cartesian4} first A cartesian to compare.
* @param {Cartesian4} second A cartesian to compare.
* @param {Cartesian4} result The object into which to store the result.
* @returns {Cartesian4} A cartesian with the minimum components.
*/
Cartesian4.minimumByComponent = function(first, second, result) {
if (!defined(first)) {
throw new DeveloperError('first is required.');
}
if (!defined(second)) {
throw new DeveloperError('second is required.');
}
if (!defined(result)) {
throw new DeveloperError('result is required.');
}
result.x = Math.min(first.x, second.x);
result.y = Math.min(first.y, second.y);
result.z = Math.min(first.z, second.z);
result.w = Math.min(first.w, second.w);
return result;
};
/**
* Compares two Cartesians and computes a Cartesian which contains the maximum components of the supplied Cartesians.
*
* @param {Cartesian4} first A cartesian to compare.
* @param {Cartesian4} second A cartesian to compare.
* @param {Cartesian4} result The object into which to store the result.
* @returns {Cartesian4} A cartesian with the maximum components.
*/
Cartesian4.maximumByComponent = function(first, second, result) {
if (!defined(first)) {
throw new DeveloperError('first is required.');
}
if (!defined(second)) {
throw new DeveloperError('second is required.');
}
if (!defined(result)) {
throw new DeveloperError('result is required.');
}
result.x = Math.max(first.x, second.x);
result.y = Math.max(first.y, second.y);
result.z = Math.max(first.z, second.z);
result.w = Math.max(first.w, second.w);
return result;
};
/**
* Computes the provided Cartesian's squared magnitude.
*
* @param {Cartesian4} cartesian The Cartesian instance whose squared magnitude is to be computed.
* @returns {Number} The squared magnitude.
*/
Cartesian4.magnitudeSquared = function(cartesian) {
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required');
}
return cartesian.x * cartesian.x + cartesian.y * cartesian.y + cartesian.z * cartesian.z + cartesian.w * cartesian.w;
};
/**
* Computes the Cartesian's magnitude (length).
*
* @param {Cartesian4} cartesian The Cartesian instance whose magnitude is to be computed.
* @returns {Number} The magnitude.
*/
Cartesian4.magnitude = function(cartesian) {
return Math.sqrt(Cartesian4.magnitudeSquared(cartesian));
};
var distanceScratch = new Cartesian4();
/**
* Computes the 4-space distance between two points.
*
* @param {Cartesian4} left The first point to compute the distance from.
* @param {Cartesian4} right The second point to compute the distance to.
* @returns {Number} The distance between two points.
*
* @example
* // Returns 1.0
* var d = Cesium.Cartesian4.distance(
* new Cesium.Cartesian4(1.0, 0.0, 0.0, 0.0),
* new Cesium.Cartesian4(2.0, 0.0, 0.0, 0.0));
*/
Cartesian4.distance = function(left, right) {
if (!defined(left) || !defined(right)) {
throw new DeveloperError('left and right are required.');
}
Cartesian4.subtract(left, right, distanceScratch);
return Cartesian4.magnitude(distanceScratch);
};
/**
* Computes the squared distance between two points. Comparing squared distances
* using this function is more efficient than comparing distances using {@link Cartesian4#distance}.
*
* @param {Cartesian4} left The first point to compute the distance from.
* @param {Cartesian4} right The second point to compute the distance to.
* @returns {Number} The distance between two points.
*
* @example
* // Returns 4.0, not 2.0
* var d = Cesium.Cartesian4.distance(
* new Cesium.Cartesian4(1.0, 0.0, 0.0, 0.0),
* new Cesium.Cartesian4(3.0, 0.0, 0.0, 0.0));
*/
Cartesian4.distanceSquared = function(left, right) {
if (!defined(left) || !defined(right)) {
throw new DeveloperError('left and right are required.');
}
Cartesian4.subtract(left, right, distanceScratch);
return Cartesian4.magnitudeSquared(distanceScratch);
};
/**
* Computes the normalized form of the supplied Cartesian.
*
* @param {Cartesian4} cartesian The Cartesian to be normalized.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter.
*/
Cartesian4.normalize = function(cartesian, result) {
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required');
}
var magnitude = Cartesian4.magnitude(cartesian);
result.x = cartesian.x / magnitude;
result.y = cartesian.y / magnitude;
result.z = cartesian.z / magnitude;
result.w = cartesian.w / magnitude;
return result;
};
/**
* Computes the dot (scalar) product of two Cartesians.
*
* @param {Cartesian4} left The first Cartesian.
* @param {Cartesian4} right The second Cartesian.
* @returns {Number} The dot product.
*/
Cartesian4.dot = function(left, right) {
if (!defined(left)) {
throw new DeveloperError('left is required');
}
if (!defined(right)) {
throw new DeveloperError('right is required');
}
return left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w;
};
/**
* Computes the componentwise product of two Cartesians.
*
* @param {Cartesian4} left The first Cartesian.
* @param {Cartesian4} right The second Cartesian.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter.
*/
Cartesian4.multiplyComponents = function(left, right, result) {
if (!defined(left)) {
throw new DeveloperError('left is required');
}
if (!defined(right)) {
throw new DeveloperError('right is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required');
}
result.x = left.x * right.x;
result.y = left.y * right.y;
result.z = left.z * right.z;
result.w = left.w * right.w;
return result;
};
/**
* Computes the componentwise sum of two Cartesians.
*
* @param {Cartesian4} left The first Cartesian.
* @param {Cartesian4} right The second Cartesian.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter.
*/
Cartesian4.add = function(left, right, result) {
if (!defined(left)) {
throw new DeveloperError('left is required');
}
if (!defined(right)) {
throw new DeveloperError('right is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required');
}
result.x = left.x + right.x;
result.y = left.y + right.y;
result.z = left.z + right.z;
result.w = left.w + right.w;
return result;
};
/**
* Computes the componentwise difference of two Cartesians.
*
* @param {Cartesian4} left The first Cartesian.
* @param {Cartesian4} right The second Cartesian.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter.
*/
Cartesian4.subtract = function(left, right, result) {
if (!defined(left)) {
throw new DeveloperError('left is required');
}
if (!defined(right)) {
throw new DeveloperError('right is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required');
}
result.x = left.x - right.x;
result.y = left.y - right.y;
result.z = left.z - right.z;
result.w = left.w - right.w;
return result;
};
/**
* Multiplies the provided Cartesian componentwise by the provided scalar.
*
* @param {Cartesian4} cartesian The Cartesian to be scaled.
* @param {Number} scalar The scalar to multiply with.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter.
*/
Cartesian4.multiplyByScalar = function(cartesian, scalar, result) {
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required');
}
if (typeof scalar !== 'number') {
throw new DeveloperError('scalar is required and must be a number.');
}
if (!defined(result)) {
throw new DeveloperError('result is required');
}
result.x = cartesian.x * scalar;
result.y = cartesian.y * scalar;
result.z = cartesian.z * scalar;
result.w = cartesian.w * scalar;
return result;
};
/**
* Divides the provided Cartesian componentwise by the provided scalar.
*
* @param {Cartesian4} cartesian The Cartesian to be divided.
* @param {Number} scalar The scalar to divide by.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter.
*/
Cartesian4.divideByScalar = function(cartesian, scalar, result) {
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required');
}
if (typeof scalar !== 'number') {
throw new DeveloperError('scalar is required and must be a number.');
}
if (!defined(result)) {
throw new DeveloperError('result is required');
}
result.x = cartesian.x / scalar;
result.y = cartesian.y / scalar;
result.z = cartesian.z / scalar;
result.w = cartesian.w / scalar;
return result;
};
/**
* Negates the provided Cartesian.
*
* @param {Cartesian4} cartesian The Cartesian to be negated.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter.
*/
Cartesian4.negate = function(cartesian, result) {
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required');
}
result.x = -cartesian.x;
result.y = -cartesian.y;
result.z = -cartesian.z;
result.w = -cartesian.w;
return result;
};
/**
* Computes the absolute value of the provided Cartesian.
*
* @param {Cartesian4} cartesian The Cartesian whose absolute value is to be computed.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter.
*/
Cartesian4.abs = function(cartesian, result) {
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required');
}
result.x = Math.abs(cartesian.x);
result.y = Math.abs(cartesian.y);
result.z = Math.abs(cartesian.z);
result.w = Math.abs(cartesian.w);
return result;
};
var lerpScratch = new Cartesian4();
/**
* Computes the linear interpolation or extrapolation at t using the provided cartesians.
*
* @param {Cartesian4} start The value corresponding to t at 0.0.
* @param {Cartesian4}end The value corresponding to t at 1.0.
* @param {Number} t The point along t at which to interpolate.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter.
*/
Cartesian4.lerp = function(start, end, t, result) {
if (!defined(start)) {
throw new DeveloperError('start is required.');
}
if (!defined(end)) {
throw new DeveloperError('end is required.');
}
if (typeof t !== 'number') {
throw new DeveloperError('t is required and must be a number.');
}
if (!defined(result)) {
throw new DeveloperError('result is required.');
}
Cartesian4.multiplyByScalar(end, t, lerpScratch);
result = Cartesian4.multiplyByScalar(start, 1.0 - t, result);
return Cartesian4.add(lerpScratch, result, result);
};
var mostOrthogonalAxisScratch = new Cartesian4();
/**
* Returns the axis that is most orthogonal to the provided Cartesian.
*
* @param {Cartesian4} cartesian The Cartesian on which to find the most orthogonal axis.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The most orthogonal axis.
*/
Cartesian4.mostOrthogonalAxis = function(cartesian, result) {
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required.');
}
if (!defined(result)) {
throw new DeveloperError('result is required.');
}
var f = Cartesian4.normalize(cartesian, mostOrthogonalAxisScratch);
Cartesian4.abs(f, f);
if (f.x <= f.y) {
if (f.x <= f.z) {
if (f.x <= f.w) {
result = Cartesian4.clone(Cartesian4.UNIT_X, result);
} else {
result = Cartesian4.clone(Cartesian4.UNIT_W, result);
}
} else if (f.z <= f.w) {
result = Cartesian4.clone(Cartesian4.UNIT_Z, result);
} else {
result = Cartesian4.clone(Cartesian4.UNIT_W, result);
}
} else if (f.y <= f.z) {
if (f.y <= f.w) {
result = Cartesian4.clone(Cartesian4.UNIT_Y, result);
} else {
result = Cartesian4.clone(Cartesian4.UNIT_W, result);
}
} else if (f.z <= f.w) {
result = Cartesian4.clone(Cartesian4.UNIT_Z, result);
} else {
result = Cartesian4.clone(Cartesian4.UNIT_W, result);
}
return result;
};
/**
* Compares the provided Cartesians componentwise and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Cartesian4} [left] The first Cartesian.
* @param {Cartesian4} [right] The second Cartesian.
* @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
Cartesian4.equals = function(left, right) {
return (left === right) ||
((defined(left)) &&
(defined(right)) &&
(left.x === right.x) &&
(left.y === right.y) &&
(left.z === right.z) &&
(left.w === right.w));
};
/**
* @private
*/
Cartesian4.equalsArray = function(cartesian, array, offset) {
return cartesian.x === array[offset] &&
cartesian.y === array[offset + 1] &&
cartesian.z === array[offset + 2] &&
cartesian.w === array[offset + 3];
};
/**
* Compares the provided Cartesians componentwise and returns
* <code>true</code> if they pass an absolute or relative tolerance test,
* <code>false</code> otherwise.
*
* @param {Cartesian4} [left] The first Cartesian.
* @param {Cartesian4} [right] The second Cartesian.
* @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
* @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
* @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
*/
Cartesian4.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) {
return (left === right) ||
(defined(left) &&
defined(right) &&
CesiumMath.equalsEpsilon(left.x, right.x, relativeEpsilon, absoluteEpsilon) &&
CesiumMath.equalsEpsilon(left.y, right.y, relativeEpsilon, absoluteEpsilon) &&
CesiumMath.equalsEpsilon(left.z, right.z, relativeEpsilon, absoluteEpsilon) &&
CesiumMath.equalsEpsilon(left.w, right.w, relativeEpsilon, absoluteEpsilon));
};
/**
* An immutable Cartesian4 instance initialized to (0.0, 0.0, 0.0, 0.0).
*
* @type {Cartesian4}
* @constant
*/
Cartesian4.ZERO = freezeObject(new Cartesian4(0.0, 0.0, 0.0, 0.0));
/**
* An immutable Cartesian4 instance initialized to (1.0, 0.0, 0.0, 0.0).
*
* @type {Cartesian4}
* @constant
*/
Cartesian4.UNIT_X = freezeObject(new Cartesian4(1.0, 0.0, 0.0, 0.0));
/**
* An immutable Cartesian4 instance initialized to (0.0, 1.0, 0.0, 0.0).
*
* @type {Cartesian4}
* @constant
*/
Cartesian4.UNIT_Y = freezeObject(new Cartesian4(0.0, 1.0, 0.0, 0.0));
/**
* An immutable Cartesian4 instance initialized to (0.0, 0.0, 1.0, 0.0).
*
* @type {Cartesian4}
* @constant
*/
Cartesian4.UNIT_Z = freezeObject(new Cartesian4(0.0, 0.0, 1.0, 0.0));
/**
* An immutable Cartesian4 instance initialized to (0.0, 0.0, 0.0, 1.0).
*
* @type {Cartesian4}
* @constant
*/
Cartesian4.UNIT_W = freezeObject(new Cartesian4(0.0, 0.0, 0.0, 1.0));
/**
* Duplicates this Cartesian4 instance.
*
* @param {Cartesian4} [result] The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
*/
Cartesian4.prototype.clone = function(result) {
return Cartesian4.clone(this, result);
};
/**
* Compares this Cartesian against the provided Cartesian componentwise and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Cartesian4} [right] The right hand side Cartesian.
* @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
*/
Cartesian4.prototype.equals = function(right) {
return Cartesian4.equals(this, right);
};
/**
* Compares this Cartesian against the provided Cartesian componentwise and returns
* <code>true</code> if they pass an absolute or relative tolerance test,
* <code>false</code> otherwise.
*
* @param {Cartesian4} [right] The right hand side Cartesian.
* @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
* @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
* @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
*/
Cartesian4.prototype.equalsEpsilon = function(right, relativeEpsilon, absoluteEpsilon) {
return Cartesian4.equalsEpsilon(this, right, relativeEpsilon, absoluteEpsilon);
};
/**
* Creates a string representing this Cartesian in the format '(x, y)'.
*
* @returns {String} A string representing the provided Cartesian in the format '(x, y)'.
*/
Cartesian4.prototype.toString = function() {
return '(' + this.x + ', ' + this.y + ', ' + this.z + ', ' + this.w + ')';
};
return Cartesian4;
});
/*global define*/
define('Core/Matrix3',[
'./Cartesian3',
'./defaultValue',
'./defined',
'./DeveloperError',
'./freezeObject',
'./Math'
], function(
Cartesian3,
defaultValue,
defined,
DeveloperError,
freezeObject,
CesiumMath) {
"use strict";
/**
* A 3x3 matrix, indexable as a column-major order array.
* Constructor parameters are in row-major order for code readability.
* @alias Matrix3
* @constructor
*
* @param {Number} [column0Row0=0.0] The value for column 0, row 0.
* @param {Number} [column1Row0=0.0] The value for column 1, row 0.
* @param {Number} [column2Row0=0.0] The value for column 2, row 0.
* @param {Number} [column0Row1=0.0] The value for column 0, row 1.
* @param {Number} [column1Row1=0.0] The value for column 1, row 1.
* @param {Number} [column2Row1=0.0] The value for column 2, row 1.
* @param {Number} [column0Row2=0.0] The value for column 0, row 2.
* @param {Number} [column1Row2=0.0] The value for column 1, row 2.
* @param {Number} [column2Row2=0.0] The value for column 2, row 2.
*
* @see Matrix3.fromColumnMajorArray
* @see Matrix3.fromRowMajorArray
* @see Matrix3.fromQuaternion
* @see Matrix3.fromScale
* @see Matrix3.fromUniformScale
* @see Matrix2
* @see Matrix4
*/
var Matrix3 = function(column0Row0, column1Row0, column2Row0,
column0Row1, column1Row1, column2Row1,
column0Row2, column1Row2, column2Row2) {
this[0] = defaultValue(column0Row0, 0.0);
this[1] = defaultValue(column0Row1, 0.0);
this[2] = defaultValue(column0Row2, 0.0);
this[3] = defaultValue(column1Row0, 0.0);
this[4] = defaultValue(column1Row1, 0.0);
this[5] = defaultValue(column1Row2, 0.0);
this[6] = defaultValue(column2Row0, 0.0);
this[7] = defaultValue(column2Row1, 0.0);
this[8] = defaultValue(column2Row2, 0.0);
};
/**
* The number of elements used to pack the object into an array.
* @type {Number}
*/
Matrix3.packedLength = 9;
/**
* Stores the provided instance into the provided array.
*
* @param {Matrix3} value The value to pack.
* @param {Number[]} array The array to pack into.
* @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
*/
Matrix3.pack = function(value, array, startingIndex) {
if (!defined(value)) {
throw new DeveloperError('value is required');
}
if (!defined(array)) {
throw new DeveloperError('array is required');
}
startingIndex = defaultValue(startingIndex, 0);
array[startingIndex++] = value[0];
array[startingIndex++] = value[1];
array[startingIndex++] = value[2];
array[startingIndex++] = value[3];
array[startingIndex++] = value[4];
array[startingIndex++] = value[5];
array[startingIndex++] = value[6];
array[startingIndex++] = value[7];
array[startingIndex++] = value[8];
};
/**
* Retrieves an instance from a packed array.
*
* @param {Number[]} array The packed array.
* @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
* @param {Matrix3} [result] The object into which to store the result.
*/
Matrix3.unpack = function(array, startingIndex, result) {
if (!defined(array)) {
throw new DeveloperError('array is required');
}
startingIndex = defaultValue(startingIndex, 0);
if (!defined(result)) {
result = new Matrix3();
}
result[0] = array[startingIndex++];
result[1] = array[startingIndex++];
result[2] = array[startingIndex++];
result[3] = array[startingIndex++];
result[4] = array[startingIndex++];
result[5] = array[startingIndex++];
result[6] = array[startingIndex++];
result[7] = array[startingIndex++];
result[8] = array[startingIndex++];
return result;
};
/**
* Duplicates a Matrix3 instance.
*
* @param {Matrix3} matrix The matrix to duplicate.
* @param {Matrix3} [result] The object onto which to store the result.
* @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided. (Returns undefined if matrix is undefined)
*/
Matrix3.clone = function(values, result) {
if (!defined(values)) {
return undefined;
}
if (!defined(result)) {
return new Matrix3(values[0], values[3], values[6],
values[1], values[4], values[7],
values[2], values[5], values[8]);
}
result[0] = values[0];
result[1] = values[1];
result[2] = values[2];
result[3] = values[3];
result[4] = values[4];
result[5] = values[5];
result[6] = values[6];
result[7] = values[7];
result[8] = values[8];
return result;
};
/**
* Creates a Matrix3 from 9 consecutive elements in an array.
*
* @param {Number[]} array The array whose 9 consecutive elements correspond to the positions of the matrix. Assumes column-major order.
* @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to first column first row position in the matrix.
* @param {Matrix3} [result] The object onto which to store the result.
* @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided.
*
* @example
* // Create the Matrix3:
* // [1.0, 2.0, 3.0]
* // [1.0, 2.0, 3.0]
* // [1.0, 2.0, 3.0]
*
* var v = [1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0];
* var m = Cesium.Matrix3.fromArray(v);
*
* // Create same Matrix3 with using an offset into an array
* var v2 = [0.0, 0.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0];
* var m2 = Cesium.Matrix3.fromArray(v2, 2);
*/
Matrix3.fromArray = function(array, startingIndex, result) {
if (!defined(array)) {
throw new DeveloperError('array is required');
}
startingIndex = defaultValue(startingIndex, 0);
if (!defined(result)) {
result = new Matrix3();
}
result[0] = array[startingIndex];
result[1] = array[startingIndex + 1];
result[2] = array[startingIndex + 2];
result[3] = array[startingIndex + 3];
result[4] = array[startingIndex + 4];
result[5] = array[startingIndex + 5];
result[6] = array[startingIndex + 6];
result[7] = array[startingIndex + 7];
result[8] = array[startingIndex + 8];
return result;
};
/**
* Creates a Matrix3 instance from a column-major order array.
*
* @param {Number[]} values The column-major order array.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns The modified result parameter, or a new Matrix3 instance if one was not provided.
*/
Matrix3.fromColumnMajorArray = function(values, result) {
if (!defined(values)) {
throw new DeveloperError('values parameter is required');
}
return Matrix3.clone(values, result);
};
/**
* Creates a Matrix3 instance from a row-major order array.
* The resulting matrix will be in column-major order.
*
* @param {Number[]} values The row-major order array.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns The modified result parameter, or a new Matrix3 instance if one was not provided.
*/
Matrix3.fromRowMajorArray = function(values, result) {
if (!defined(values)) {
throw new DeveloperError('values is required.');
}
if (!defined(result)) {
return new Matrix3(values[0], values[1], values[2],
values[3], values[4], values[5],
values[6], values[7], values[8]);
}
result[0] = values[0];
result[1] = values[3];
result[2] = values[6];
result[3] = values[1];
result[4] = values[4];
result[5] = values[7];
result[6] = values[2];
result[7] = values[5];
result[8] = values[8];
return result;
};
/**
* Computes a 3x3 rotation matrix from the provided quaternion.
*
* @param {Quaternion} quaternion the quaternion to use.
* @returns {Matrix3} The 3x3 rotation matrix from this quaternion.
*/
Matrix3.fromQuaternion = function(quaternion, result) {
if (!defined(quaternion)) {
throw new DeveloperError('quaternion is required');
}
var x2 = quaternion.x * quaternion.x;
var xy = quaternion.x * quaternion.y;
var xz = quaternion.x * quaternion.z;
var xw = quaternion.x * quaternion.w;
var y2 = quaternion.y * quaternion.y;
var yz = quaternion.y * quaternion.z;
var yw = quaternion.y * quaternion.w;
var z2 = quaternion.z * quaternion.z;
var zw = quaternion.z * quaternion.w;
var w2 = quaternion.w * quaternion.w;
var m00 = x2 - y2 - z2 + w2;
var m01 = 2.0 * (xy - zw);
var m02 = 2.0 * (xz + yw);
var m10 = 2.0 * (xy + zw);
var m11 = -x2 + y2 - z2 + w2;
var m12 = 2.0 * (yz - xw);
var m20 = 2.0 * (xz - yw);
var m21 = 2.0 * (yz + xw);
var m22 = -x2 - y2 + z2 + w2;
if (!defined(result)) {
return new Matrix3(m00, m01, m02,
m10, m11, m12,
m20, m21, m22);
}
result[0] = m00;
result[1] = m10;
result[2] = m20;
result[3] = m01;
result[4] = m11;
result[5] = m21;
result[6] = m02;
result[7] = m12;
result[8] = m22;
return result;
};
/**
* Computes a Matrix3 instance representing a non-uniform scale.
*
* @param {Cartesian3} scale The x, y, and z scale factors.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns The modified result parameter, or a new Matrix3 instance if one was not provided.
*
* @example
* // Creates
* // [7.0, 0.0, 0.0]
* // [0.0, 8.0, 0.0]
* // [0.0, 0.0, 9.0]
* var m = Cesium.Matrix3.fromScale(new Cesium.Cartesian3(7.0, 8.0, 9.0));
*/
Matrix3.fromScale = function(scale, result) {
if (!defined(scale)) {
throw new DeveloperError('scale is required.');
}
if (!defined(result)) {
return new Matrix3(
scale.x, 0.0, 0.0,
0.0, scale.y, 0.0,
0.0, 0.0, scale.z);
}
result[0] = scale.x;
result[1] = 0.0;
result[2] = 0.0;
result[3] = 0.0;
result[4] = scale.y;
result[5] = 0.0;
result[6] = 0.0;
result[7] = 0.0;
result[8] = scale.z;
return result;
};
/**
* Computes a Matrix3 instance representing a uniform scale.
*
* @param {Number} scale The uniform scale factor.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns The modified result parameter, or a new Matrix3 instance if one was not provided.
*
* @example
* // Creates
* // [2.0, 0.0, 0.0]
* // [0.0, 2.0, 0.0]
* // [0.0, 0.0, 2.0]
* var m = Cesium.Matrix3.fromUniformScale(2.0);
*/
Matrix3.fromUniformScale = function(scale, result) {
if (typeof scale !== 'number') {
throw new DeveloperError('scale is required.');
}
if (!defined(result)) {
return new Matrix3(
scale, 0.0, 0.0,
0.0, scale, 0.0,
0.0, 0.0, scale);
}
result[0] = scale;
result[1] = 0.0;
result[2] = 0.0;
result[3] = 0.0;
result[4] = scale;
result[5] = 0.0;
result[6] = 0.0;
result[7] = 0.0;
result[8] = scale;
return result;
};
/**
* Computes a Matrix3 instance representing the cross product equivalent matrix of a Cartesian3 vector.
*
* @param {Cartesian3} the vector on the left hand side of the cross product operation.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns The modified result parameter, or a new Matrix3 instance if one was not provided.
*
* @example
* // Creates
* // [0.0, -9.0, 8.0]
* // [9.0, 0.0, -7.0]
* // [-8.0, 7.0, 0.0]
* var m = Cesium.Matrix3.fromCrossProduct(new Cesium.Cartesian3(7.0, 8.0, 9.0));
*/
Matrix3.fromCrossProduct = function(vector, result) {
if (!defined(vector)) {
throw new DeveloperError('vector is required.');
}
if (!defined(result)) {
return new Matrix3(
0.0, -vector.z, vector.y,
vector.z, 0.0, -vector.x,
-vector.y, vector.x, 0.0);
}
result[0] = 0.0;
result[1] = vector.z;
result[2] = -vector.y;
result[3] = -vector.z;
result[4] = 0.0;
result[5] = vector.x;
result[6] = vector.y;
result[7] = -vector.x;
result[8] = 0.0;
return result;
};
/**
* Creates a rotation matrix around the x-axis.
*
* @param {Number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns The modified result parameter, or a new Matrix3 instance if one was not provided.
*
* @example
* // Rotate a point 45 degrees counterclockwise around the x-axis.
* var p = new Cesium.Cartesian3(5, 6, 7);
* var m = Cesium.Matrix3.fromRotationX(Cesium.Math.toRadians(45.0));
* var rotated = Cesium.Matrix3.multiplyByVector(m, p, new Cesium.Cartesian3());
*/
Matrix3.fromRotationX = function(angle, result) {
if (!defined(angle)) {
throw new DeveloperError('angle is required.');
}
var cosAngle = Math.cos(angle);
var sinAngle = Math.sin(angle);
if (!defined(result)) {
return new Matrix3(
1.0, 0.0, 0.0,
0.0, cosAngle, -sinAngle,
0.0, sinAngle, cosAngle);
}
result[0] = 1.0;
result[1] = 0.0;
result[2] = 0.0;
result[3] = 0.0;
result[4] = cosAngle;
result[5] = sinAngle;
result[6] = 0.0;
result[7] = -sinAngle;
result[8] = cosAngle;
return result;
};
/**
* Creates a rotation matrix around the y-axis.
*
* @param {Number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns The modified result parameter, or a new Matrix3 instance if one was not provided.
*
* @example
* // Rotate a point 45 degrees counterclockwise around the y-axis.
* var p = new Cesium.Cartesian3(5, 6, 7);
* var m = Cesium.Matrix3.fromRotationY(Cesium.Math.toRadians(45.0));
* var rotated = Cesium.Matrix3.multiplyByVector(m, p, new Cesium.Cartesian3());
*/
Matrix3.fromRotationY = function(angle, result) {
if (!defined(angle)) {
throw new DeveloperError('angle is required.');
}
var cosAngle = Math.cos(angle);
var sinAngle = Math.sin(angle);
if (!defined(result)) {
return new Matrix3(
cosAngle, 0.0, sinAngle,
0.0, 1.0, 0.0,
-sinAngle, 0.0, cosAngle);
}
result[0] = cosAngle;
result[1] = 0.0;
result[2] = -sinAngle;
result[3] = 0.0;
result[4] = 1.0;
result[5] = 0.0;
result[6] = sinAngle;
result[7] = 0.0;
result[8] = cosAngle;
return result;
};
/**
* Creates a rotation matrix around the z-axis.
*
* @param {Number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns The modified result parameter, or a new Matrix3 instance if one was not provided.
*
* @example
* // Rotate a point 45 degrees counterclockwise around the z-axis.
* var p = new Cesium.Cartesian3(5, 6, 7);
* var m = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(45.0));
* var rotated = Cesium.Matrix3.multiplyByVector(m, p, new Cesium.Cartesian3());
*/
Matrix3.fromRotationZ = function(angle, result) {
if (!defined(angle)) {
throw new DeveloperError('angle is required.');
}
var cosAngle = Math.cos(angle);
var sinAngle = Math.sin(angle);
if (!defined(result)) {
return new Matrix3(
cosAngle, -sinAngle, 0.0,
sinAngle, cosAngle, 0.0,
0.0, 0.0, 1.0);
}
result[0] = cosAngle;
result[1] = sinAngle;
result[2] = 0.0;
result[3] = -sinAngle;
result[4] = cosAngle;
result[5] = 0.0;
result[6] = 0.0;
result[7] = 0.0;
result[8] = 1.0;
return result;
};
/**
* Creates an Array from the provided Matrix3 instance.
* The array will be in column-major order.
*
* @param {Matrix3} matrix The matrix to use..
* @param {Number[]} [result] The Array onto which to store the result.
* @returns {Number[]} The modified Array parameter or a new Array instance if one was not provided.
*/
Matrix3.toArray = function(matrix, result) {
if (!defined(matrix)) {
throw new DeveloperError('matrix is required');
}
if (!defined(result)) {
return [matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5], matrix[6], matrix[7], matrix[8]];
}
result[0] = matrix[0];
result[1] = matrix[1];
result[2] = matrix[2];
result[3] = matrix[3];
result[4] = matrix[4];
result[5] = matrix[5];
result[6] = matrix[6];
result[7] = matrix[7];
result[8] = matrix[8];
return result;
};
/**
* Computes the array index of the element at the provided row and column.
*
* @param {Number} row The zero-based index of the row.
* @param {Number} column The zero-based index of the column.
* @returns {Number} The index of the element at the provided row and column.
*
* @exception {DeveloperError} row must be 0, 1, or 2.
* @exception {DeveloperError} column must be 0, 1, or 2.
*
* @example
* var myMatrix = new Cesium.Matrix3();
* var column1Row0Index = Cesium.Matrix3.getElementIndex(1, 0);
* var column1Row0 = myMatrix[column1Row0Index]
* myMatrix[column1Row0Index] = 10.0;
*/
Matrix3.getElementIndex = function(column, row) {
if (typeof row !== 'number' || row < 0 || row > 2) {
throw new DeveloperError('row must be 0, 1, or 2.');
}
if (typeof column !== 'number' || column < 0 || column > 2) {
throw new DeveloperError('column must be 0, 1, or 2.');
}
return column * 3 + row;
};
/**
* Retrieves a copy of the matrix column at the provided index as a Cartesian3 instance.
*
* @param {Matrix3} matrix The matrix to use.
* @param {Number} index The zero-based index of the column to retrieve.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*
* @exception {DeveloperError} index must be 0, 1, or 2.
*/
Matrix3.getColumn = function(matrix, index, result) {
if (!defined(matrix)) {
throw new DeveloperError('matrix is required.');
}
if (typeof index !== 'number' || index < 0 || index > 2) {
throw new DeveloperError('index must be 0, 1, or 2.');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
var startIndex = index * 3;
var x = matrix[startIndex];
var y = matrix[startIndex + 1];
var z = matrix[startIndex + 2];
result.x = x;
result.y = y;
result.z = z;
return result;
};
/**
* Computes a new matrix that replaces the specified column in the provided matrix with the provided Cartesian3 instance.
*
* @param {Matrix3} matrix The matrix to use.
* @param {Number} index The zero-based index of the column to set.
* @param {Cartesian3} cartesian The Cartesian whose values will be assigned to the specified column.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*
* @exception {DeveloperError} index must be 0, 1, or 2.
*/
Matrix3.setColumn = function(matrix, index, cartesian, result) {
if (!defined(matrix)) {
throw new DeveloperError('matrix is required');
}
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required');
}
if (typeof index !== 'number' || index < 0 || index > 2) {
throw new DeveloperError('index must be 0, 1, or 2.');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
result = Matrix3.clone(matrix, result);
var startIndex = index * 3;
result[startIndex] = cartesian.x;
result[startIndex + 1] = cartesian.y;
result[startIndex + 2] = cartesian.z;
return result;
};
/**
* Retrieves a copy of the matrix row at the provided index as a Cartesian3 instance.
*
* @param {Matrix3} matrix The matrix to use.
* @param {Number} index The zero-based index of the row to retrieve.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*
* @exception {DeveloperError} index must be 0, 1, or 2.
*/
Matrix3.getRow = function(matrix, index, result) {
if (!defined(matrix)) {
throw new DeveloperError('matrix is required.');
}
if (typeof index !== 'number' || index < 0 || index > 2) {
throw new DeveloperError('index must be 0, 1, or 2.');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
var x = matrix[index];
var y = matrix[index + 3];
var z = matrix[index + 6];
result.x = x;
result.y = y;
result.z = z;
return result;
};
/**
* Computes a new matrix that replaces the specified row in the provided matrix with the provided Cartesian3 instance.
*
* @param {Matrix3} matrix The matrix to use.
* @param {Number} index The zero-based index of the row to set.
* @param {Cartesian3} cartesian The Cartesian whose values will be assigned to the specified row.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*
* @exception {DeveloperError} index must be 0, 1, or 2.
*/
Matrix3.setRow = function(matrix, index, cartesian, result) {
if (!defined(matrix)) {
throw new DeveloperError('matrix is required');
}
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required');
}
if (typeof index !== 'number' || index < 0 || index > 2) {
throw new DeveloperError('index must be 0, 1, or 2.');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
result = Matrix3.clone(matrix, result);
result[index] = cartesian.x;
result[index + 3] = cartesian.y;
result[index + 6] = cartesian.z;
return result;
};
var scratchColumn = new Cartesian3();
/**
* Extracts the non-uniform scale assuming the matrix is an affine transformation.
*
* @param {Matrix3} matrix The matrix.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*/
Matrix3.getScale = function(matrix, result) {
if (!defined(matrix)) {
throw new DeveloperError('matrix is required.');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
result.x = Cartesian3.magnitude(Cartesian3.fromElements(matrix[0], matrix[1], matrix[2], scratchColumn));
result.y = Cartesian3.magnitude(Cartesian3.fromElements(matrix[3], matrix[4], matrix[5], scratchColumn));
result.z = Cartesian3.magnitude(Cartesian3.fromElements(matrix[6], matrix[7], matrix[8], scratchColumn));
return result;
};
var scratchScale = new Cartesian3();
/**
* Computes the maximum scale assuming the matrix is an affine transformation.
* The maximum scale is the maximum length of the column vectors.
*
* @param {Matrix3} matrix The matrix.
* @returns {Number} The maximum scale.
*/
Matrix3.getMaximumScale = function(matrix) {
Matrix3.getScale(matrix, scratchScale);
return Cartesian3.maximumComponent(scratchScale);
};
/**
* Computes the product of two matrices.
*
* @param {Matrix3} left The first matrix.
* @param {Matrix3} right The second matrix.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*/
Matrix3.multiply = function(left, right, result) {
if (!defined(left)) {
throw new DeveloperError('left is required');
}
if (!defined(right)) {
throw new DeveloperError('right is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
var column0Row0 = left[0] * right[0] + left[3] * right[1] + left[6] * right[2];
var column0Row1 = left[1] * right[0] + left[4] * right[1] + left[7] * right[2];
var column0Row2 = left[2] * right[0] + left[5] * right[1] + left[8] * right[2];
var column1Row0 = left[0] * right[3] + left[3] * right[4] + left[6] * right[5];
var column1Row1 = left[1] * right[3] + left[4] * right[4] + left[7] * right[5];
var column1Row2 = left[2] * right[3] + left[5] * right[4] + left[8] * right[5];
var column2Row0 = left[0] * right[6] + left[3] * right[7] + left[6] * right[8];
var column2Row1 = left[1] * right[6] + left[4] * right[7] + left[7] * right[8];
var column2Row2 = left[2] * right[6] + left[5] * right[7] + left[8] * right[8];
result[0] = column0Row0;
result[1] = column0Row1;
result[2] = column0Row2;
result[3] = column1Row0;
result[4] = column1Row1;
result[5] = column1Row2;
result[6] = column2Row0;
result[7] = column2Row1;
result[8] = column2Row2;
return result;
};
/**
* Computes the sum of two matrices.
*
* @param {Matrix3} left The first matrix.
* @param {Matrix3} right The second matrix.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*/
Matrix3.add = function(left, right, result) {
if (!defined(left)) {
throw new DeveloperError('left is required');
}
if (!defined(right)) {
throw new DeveloperError('right is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
result[0] = left[0] + right[0];
result[1] = left[1] + right[1];
result[2] = left[2] + right[2];
result[3] = left[3] + right[3];
result[4] = left[4] + right[4];
result[5] = left[5] + right[5];
result[6] = left[6] + right[6];
result[7] = left[7] + right[7];
result[8] = left[8] + right[8];
return result;
};
/**
* Computes the difference of two matrices.
*
* @param {Matrix3} left The first matrix.
* @param {Matrix3} right The second matrix.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*/
Matrix3.subtract = function(left, right, result) {
if (!defined(left)) {
throw new DeveloperError('left is required');
}
if (!defined(right)) {
throw new DeveloperError('right is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
result[0] = left[0] - right[0];
result[1] = left[1] - right[1];
result[2] = left[2] - right[2];
result[3] = left[3] - right[3];
result[4] = left[4] - right[4];
result[5] = left[5] - right[5];
result[6] = left[6] - right[6];
result[7] = left[7] - right[7];
result[8] = left[8] - right[8];
return result;
};
/**
* Computes the product of a matrix and a column vector.
*
* @param {Matrix3} matrix The matrix.
* @param {Cartesian3} cartesian The column.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*/
Matrix3.multiplyByVector = function(matrix, cartesian, result) {
if (!defined(matrix)) {
throw new DeveloperError('matrix is required');
}
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
var vX = cartesian.x;
var vY = cartesian.y;
var vZ = cartesian.z;
var x = matrix[0] * vX + matrix[3] * vY + matrix[6] * vZ;
var y = matrix[1] * vX + matrix[4] * vY + matrix[7] * vZ;
var z = matrix[2] * vX + matrix[5] * vY + matrix[8] * vZ;
result.x = x;
result.y = y;
result.z = z;
return result;
};
/**
* Computes the product of a matrix and a scalar.
*
* @param {Matrix3} matrix The matrix.
* @param {Number} scalar The number to multiply by.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*/
Matrix3.multiplyByScalar = function(matrix, scalar, result) {
if (!defined(matrix)) {
throw new DeveloperError('matrix is required');
}
if (typeof scalar !== 'number') {
throw new DeveloperError('scalar must be a number');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
result[0] = matrix[0] * scalar;
result[1] = matrix[1] * scalar;
result[2] = matrix[2] * scalar;
result[3] = matrix[3] * scalar;
result[4] = matrix[4] * scalar;
result[5] = matrix[5] * scalar;
result[6] = matrix[6] * scalar;
result[7] = matrix[7] * scalar;
result[8] = matrix[8] * scalar;
return result;
};
/**
* Creates a negated copy of the provided matrix.
*
* @param {Matrix3} matrix The matrix to negate.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*/
Matrix3.negate = function(matrix, result) {
if (!defined(matrix)) {
throw new DeveloperError('matrix is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
result[0] = -matrix[0];
result[1] = -matrix[1];
result[2] = -matrix[2];
result[3] = -matrix[3];
result[4] = -matrix[4];
result[5] = -matrix[5];
result[6] = -matrix[6];
result[7] = -matrix[7];
result[8] = -matrix[8];
return result;
};
/**
* Computes the transpose of the provided matrix.
*
* @param {Matrix3} matrix The matrix to transpose.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*/
Matrix3.transpose = function(matrix, result) {
if (!defined(matrix)) {
throw new DeveloperError('matrix is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
var column0Row0 = matrix[0];
var column0Row1 = matrix[3];
var column0Row2 = matrix[6];
var column1Row0 = matrix[1];
var column1Row1 = matrix[4];
var column1Row2 = matrix[7];
var column2Row0 = matrix[2];
var column2Row1 = matrix[5];
var column2Row2 = matrix[8];
result[0] = column0Row0;
result[1] = column0Row1;
result[2] = column0Row2;
result[3] = column1Row0;
result[4] = column1Row1;
result[5] = column1Row2;
result[6] = column2Row0;
result[7] = column2Row1;
result[8] = column2Row2;
return result;
};
function computeFrobeniusNorm(matrix) {
var norm = 0.0;
for (var i = 0; i < 9; ++i) {
var temp = matrix[i];
norm += temp * temp;
}
return Math.sqrt(norm);
}
var rowVal = [1, 0, 0];
var colVal = [2, 2, 1];
function offDiagonalFrobeniusNorm(matrix) {
// Computes the "off-diagonal" Frobenius norm.
// Assumes matrix is symmetric.
var norm = 0.0;
for (var i = 0; i < 3; ++i) {
var temp = matrix[Matrix3.getElementIndex(colVal[i], rowVal[i])];
norm += 2.0 * temp * temp;
}
return Math.sqrt(norm);
}
function shurDecomposition(matrix, result) {
// This routine was created based upon Matrix Computations, 3rd ed., by Golub and Van Loan,
// section 8.4.2 The 2by2 Symmetric Schur Decomposition.
//
// The routine takes a matrix, which is assumed to be symmetric, and
// finds the largest off-diagonal term, and then creates
// a matrix (result) which can be used to help reduce it
var tolerance = CesiumMath.EPSILON15;
var maxDiagonal = 0.0;
var rotAxis = 1;
// find pivot (rotAxis) based on max diagonal of matrix
for (var i = 0; i < 3; ++i) {
var temp = Math.abs(matrix[Matrix3.getElementIndex(colVal[i], rowVal[i])]);
if (temp > maxDiagonal) {
rotAxis = i;
maxDiagonal = temp;
}
}
var c = 1.0;
var s = 0.0;
var p = rowVal[rotAxis];
var q = colVal[rotAxis];
if (Math.abs(matrix[Matrix3.getElementIndex(q, p)]) > tolerance) {
var qq = matrix[Matrix3.getElementIndex(q, q)];
var pp = matrix[Matrix3.getElementIndex(p, p)];
var qp = matrix[Matrix3.getElementIndex(q, p)];
var tau = (qq - pp) / 2.0 / qp;
var t;
if (tau < 0.0) {
t = -1.0 / (-tau + Math.sqrt(1.0 + tau * tau));
} else {
t = 1.0 / (tau + Math.sqrt(1.0 + tau * tau));
}
c = 1.0 / Math.sqrt(1.0 + t * t);
s = t * c;
}
result = Matrix3.clone(Matrix3.IDENTITY, result);
result[Matrix3.getElementIndex(p, p)] = result[Matrix3.getElementIndex(q, q)] = c;
result[Matrix3.getElementIndex(q, p)] = s;
result[Matrix3.getElementIndex(p, q)] = -s;
return result;
}
var jMatrix = new Matrix3();
var jMatrixTranspose = new Matrix3();
/**
* Computes the eigenvectors and eigenvalues of a symmetric matrix.
* <p>
* Returns a diagonal matrix and unitary matrix such that:
* <code>matrix = unitary matrix * diagonal matrix * transpose(unitary matrix)</code>
* </p>
* <p>
* The values along the diagonal of the diagonal matrix are the eigenvalues. The columns
* of the unitary matrix are the corresponding eigenvectors.
* </p>
*
* @param {Matrix3} matrix The matrix to decompose into diagonal and unitary matrix. Expected to be symmetric.
* @param {Object} [result] An object with unitary and diagonal properties which are matrices onto which to store the result.
* @returns {Object} An object with unitary and diagonal properties which are the unitary and diagonal matrices, respectively.
*
* @example
* var a = //... symetric matrix
* var result = {
* unitary : new Cesium.Matrix3(),
* diagonal : new Cesium.Matrix3()
* };
* Cesium.Matrix3.computeEigenDecomposition(a, result);
*
* var unitaryTranspose = Cesium.Matrix3.transpose(result.unitary, new Cesium.Matrix3());
* var b = Cesium.Matrix3.multiply(result.unitary, result.diagonal, new Cesium.Matrix3());
* Cesium.Matrix3.multiply(b, unitaryTranspose, b); // b is now equal to a
*
* var lambda = Cesium.Matrix3.getColumn(result.diagonal, 0, new Cesium.Cartesian3()).x; // first eigenvalue
* var v = Cesium.Matrix3.getColumn(result.unitary, 0, new Cesium.Cartesian3()); // first eigenvector
* var c = Cesium.Cartesian3.multiplyByScalar(v, lambda, new Cesium.Cartesian3()); // equal to Cesium.Matrix3.multiplyByVector(a, v)
*/
Matrix3.computeEigenDecomposition = function(matrix, result) {
if (!defined(matrix)) {
throw new DeveloperError('matrix is required.');
}
// This routine was created based upon Matrix Computations, 3rd ed., by Golub and Van Loan,
// section 8.4.3 The Classical Jacobi Algorithm
var tolerance = CesiumMath.EPSILON20;
var maxSweeps = 10;
var count = 0;
var sweep = 0;
if (!defined(result)) {
result = {};
}
var unitaryMatrix = result.unitary = Matrix3.clone(Matrix3.IDENTITY, result.unitary);
var diagMatrix = result.diagonal = Matrix3.clone(matrix, result.diagonal);
var epsilon = tolerance * computeFrobeniusNorm(diagMatrix);
while (sweep < maxSweeps && offDiagonalFrobeniusNorm(diagMatrix) > epsilon) {
shurDecomposition(diagMatrix, jMatrix);
Matrix3.transpose(jMatrix, jMatrixTranspose);
Matrix3.multiply(diagMatrix, jMatrix, diagMatrix);
Matrix3.multiply(jMatrixTranspose, diagMatrix, diagMatrix);
Matrix3.multiply(unitaryMatrix, jMatrix, unitaryMatrix);
if (++count > 2) {
++sweep;
count = 0;
}
}
return result;
};
/**
* Computes a matrix, which contains the absolute (unsigned) values of the provided matrix's elements.
*
* @param {Matrix3} matrix The matrix with signed elements.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*/
Matrix3.abs = function(matrix, result) {
if (!defined(matrix)) {
throw new DeveloperError('matrix is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
result[0] = Math.abs(matrix[0]);
result[1] = Math.abs(matrix[1]);
result[2] = Math.abs(matrix[2]);
result[3] = Math.abs(matrix[3]);
result[4] = Math.abs(matrix[4]);
result[5] = Math.abs(matrix[5]);
result[6] = Math.abs(matrix[6]);
result[7] = Math.abs(matrix[7]);
result[8] = Math.abs(matrix[8]);
return result;
};
/**
* Computes the determinant of the provided matrix.
*
* @param {Matrix3} matrix The matrix to use.
* @returns {Number} The value of the determinant of the matrix.
*/
Matrix3.determinant = function(matrix) {
if (!defined(matrix)) {
throw new DeveloperError('matrix is required');
}
var m11 = matrix[0];
var m21 = matrix[3];
var m31 = matrix[6];
var m12 = matrix[1];
var m22 = matrix[4];
var m32 = matrix[7];
var m13 = matrix[2];
var m23 = matrix[5];
var m33 = matrix[8];
return m11 * (m22 * m33 - m23 * m32) + m12 * (m23 * m31 - m21 * m33) + m13 * (m21 * m32 - m22 * m31);
};
/**
* Computes the inverse of the provided matrix.
*
* @param {Matrix3} matrix The matrix to invert.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*
* @exception {DeveloperError} matrix is not invertible.
*/
Matrix3.inverse = function(matrix, result) {
if (!defined(matrix)) {
throw new DeveloperError('matrix is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
var m11 = matrix[0];
var m21 = matrix[1];
var m31 = matrix[2];
var m12 = matrix[3];
var m22 = matrix[4];
var m32 = matrix[5];
var m13 = matrix[6];
var m23 = matrix[7];
var m33 = matrix[8];
var determinant = Matrix3.determinant(matrix);
if (Math.abs(determinant) <= CesiumMath.EPSILON15) {
throw new DeveloperError('matrix is not invertible');
}
result[0] = m22 * m33 - m23 * m32;
result[1] = m23 * m31 - m21 * m33;
result[2] = m21 * m32 - m22 * m31;
result[3] = m13 * m32 - m12 * m33;
result[4] = m11 * m33 - m13 * m31;
result[5] = m12 * m31 - m11 * m32;
result[6] = m12 * m23 - m13 * m22;
result[7] = m13 * m21 - m11 * m23;
result[8] = m11 * m22 - m12 * m21;
var scale = 1.0 / determinant;
return Matrix3.multiplyByScalar(result, scale, result);
};
/**
* Compares the provided matrices componentwise and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Matrix3} [left] The first matrix.
* @param {Matrix3} [right] The second matrix.
* @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
Matrix3.equals = function(left, right) {
return (left === right) ||
(defined(left) &&
defined(right) &&
left[0] === right[0] &&
left[1] === right[1] &&
left[2] === right[2] &&
left[3] === right[3] &&
left[4] === right[4] &&
left[5] === right[5] &&
left[6] === right[6] &&
left[7] === right[7] &&
left[8] === right[8]);
};
/**
* Compares the provided matrices componentwise and returns
* <code>true</code> if they are within the provided epsilon,
* <code>false</code> otherwise.
*
* @param {Matrix3} [left] The first matrix.
* @param {Matrix3} [right] The second matrix.
* @param {Number} epsilon The epsilon to use for equality testing.
* @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
*/
Matrix3.equalsEpsilon = function(left, right, epsilon) {
if (typeof epsilon !== 'number') {
throw new DeveloperError('epsilon must be a number');
}
return (left === right) ||
(defined(left) &&
defined(right) &&
Math.abs(left[0] - right[0]) <= epsilon &&
Math.abs(left[1] - right[1]) <= epsilon &&
Math.abs(left[2] - right[2]) <= epsilon &&
Math.abs(left[3] - right[3]) <= epsilon &&
Math.abs(left[4] - right[4]) <= epsilon &&
Math.abs(left[5] - right[5]) <= epsilon &&
Math.abs(left[6] - right[6]) <= epsilon &&
Math.abs(left[7] - right[7]) <= epsilon &&
Math.abs(left[8] - right[8]) <= epsilon);
};
/**
* An immutable Matrix3 instance initialized to the identity matrix.
*
* @type {Matrix3}
* @constant
*/
Matrix3.IDENTITY = freezeObject(new Matrix3(1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
0.0, 0.0, 1.0));
/**
* The index into Matrix3 for column 0, row 0.
*
* @type {Number}
* @constant
*/
Matrix3.COLUMN0ROW0 = 0;
/**
* The index into Matrix3 for column 0, row 1.
*
* @type {Number}
* @constant
*/
Matrix3.COLUMN0ROW1 = 1;
/**
* The index into Matrix3 for column 0, row 2.
*
* @type {Number}
* @constant
*/
Matrix3.COLUMN0ROW2 = 2;
/**
* The index into Matrix3 for column 1, row 0.
*
* @type {Number}
* @constant
*/
Matrix3.COLUMN1ROW0 = 3;
/**
* The index into Matrix3 for column 1, row 1.
*
* @type {Number}
* @constant
*/
Matrix3.COLUMN1ROW1 = 4;
/**
* The index into Matrix3 for column 1, row 2.
*
* @type {Number}
* @constant
*/
Matrix3.COLUMN1ROW2 = 5;
/**
* The index into Matrix3 for column 2, row 0.
*
* @type {Number}
* @constant
*/
Matrix3.COLUMN2ROW0 = 6;
/**
* The index into Matrix3 for column 2, row 1.
*
* @type {Number}
* @constant
*/
Matrix3.COLUMN2ROW1 = 7;
/**
* The index into Matrix3 for column 2, row 2.
*
* @type {Number}
* @constant
*/
Matrix3.COLUMN2ROW2 = 8;
/**
* Duplicates the provided Matrix3 instance.
*
* @param {Matrix3} [result] The object onto which to store the result.
* @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided.
*/
Matrix3.prototype.clone = function(result) {
return Matrix3.clone(this, result);
};
/**
* Compares this matrix to the provided matrix componentwise and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Matrix3} [right] The right hand side matrix.
* @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
*/
Matrix3.prototype.equals = function(right) {
return Matrix3.equals(this, right);
};
/**
* @private
*/
Matrix3.equalsArray = function(matrix, array, offset) {
return matrix[0] === array[offset] &&
matrix[1] === array[offset + 1] &&
matrix[2] === array[offset + 2] &&
matrix[3] === array[offset + 3] &&
matrix[4] === array[offset + 4] &&
matrix[5] === array[offset + 5] &&
matrix[6] === array[offset + 6] &&
matrix[7] === array[offset + 7] &&
matrix[8] === array[offset + 8];
};
/**
* Compares this matrix to the provided matrix componentwise and returns
* <code>true</code> if they are within the provided epsilon,
* <code>false</code> otherwise.
*
* @param {Matrix3} [right] The right hand side matrix.
* @param {Number} epsilon The epsilon to use for equality testing.
* @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
*/
Matrix3.prototype.equalsEpsilon = function(right, epsilon) {
return Matrix3.equalsEpsilon(this, right, epsilon);
};
/**
* Creates a string representing this Matrix with each row being
* on a separate line and in the format '(column0, column1, column2)'.
*
* @returns {String} A string representing the provided Matrix with each row being on a separate line and in the format '(column0, column1, column2)'.
*/
Matrix3.prototype.toString = function() {
return '(' + this[0] + ', ' + this[3] + ', ' + this[6] + ')\n' +
'(' + this[1] + ', ' + this[4] + ', ' + this[7] + ')\n' +
'(' + this[2] + ', ' + this[5] + ', ' + this[8] + ')';
};
return Matrix3;
});
/*global define*/
define('Core/RuntimeError',[
'./defined'
], function(
defined) {
"use strict";
/**
* Constructs an exception object that is thrown due to an error that can occur at runtime, e.g.,
* out of memory, could not compile shader, etc. If a function may throw this
* exception, the calling code should be prepared to catch it.
* <br /><br />
* On the other hand, a {@link DeveloperError} indicates an exception due
* to a developer error, e.g., invalid argument, that usually indicates a bug in the
* calling code.
*
* @alias RuntimeError
* @constructor
*
* @param {String} [message] The error message for this exception.
*
* @see DeveloperError
*/
var RuntimeError = function(message) {
/**
* 'RuntimeError' indicating that this exception was thrown due to a runtime error.
* @type {String}
* @readonly
*/
this.name = 'RuntimeError';
/**
* The explanation for why this exception was thrown.
* @type {String}
* @readonly
*/
this.message = message;
//Browsers such as IE don't have a stack property until you actually throw the error.
var stack;
try {
throw new Error();
} catch (e) {
stack = e.stack;
}
/**
* The stack trace of this exception, if available.
* @type {String}
* @readonly
*/
this.stack = stack;
};
RuntimeError.prototype.toString = function() {
var str = this.name + ': ' + this.message;
if (defined(this.stack)) {
str += '\n' + this.stack.toString();
}
return str;
};
return RuntimeError;
});
/*global define*/
define('Core/Matrix4',[
'./Cartesian3',
'./Cartesian4',
'./defaultValue',
'./defined',
'./DeveloperError',
'./freezeObject',
'./Math',
'./Matrix3',
'./RuntimeError'
], function(
Cartesian3,
Cartesian4,
defaultValue,
defined,
DeveloperError,
freezeObject,
CesiumMath,
Matrix3,
RuntimeError) {
"use strict";
/**
* A 4x4 matrix, indexable as a column-major order array.
* Constructor parameters are in row-major order for code readability.
* @alias Matrix4
* @constructor
*
* @param {Number} [column0Row0=0.0] The value for column 0, row 0.
* @param {Number} [column1Row0=0.0] The value for column 1, row 0.
* @param {Number} [column2Row0=0.0] The value for column 2, row 0.
* @param {Number} [column3Row0=0.0] The value for column 3, row 0.
* @param {Number} [column0Row1=0.0] The value for column 0, row 1.
* @param {Number} [column1Row1=0.0] The value for column 1, row 1.
* @param {Number} [column2Row1=0.0] The value for column 2, row 1.
* @param {Number} [column3Row1=0.0] The value for column 3, row 1.
* @param {Number} [column0Row2=0.0] The value for column 0, row 2.
* @param {Number} [column1Row2=0.0] The value for column 1, row 2.
* @param {Number} [column2Row2=0.0] The value for column 2, row 2.
* @param {Number} [column3Row2=0.0] The value for column 3, row 2.
* @param {Number} [column0Row3=0.0] The value for column 0, row 3.
* @param {Number} [column1Row3=0.0] The value for column 1, row 3.
* @param {Number} [column2Row3=0.0] The value for column 2, row 3.
* @param {Number} [column3Row3=0.0] The value for column 3, row 3.
*
* @see Matrix4.fromColumnMajorArray
* @see Matrix4.fromRowMajorArray
* @see Matrix4.fromRotationTranslation
* @see Matrix4.fromTranslationQuaternionRotationScale
* @see Matrix4.fromTranslation
* @see Matrix4.fromScale
* @see Matrix4.fromUniformScale
* @see Matrix4.fromCamera
* @see Matrix4.computePerspectiveFieldOfView
* @see Matrix4.computeOrthographicOffCenter
* @see Matrix4.computePerspectiveOffCenter
* @see Matrix4.computeInfinitePerspectiveOffCenter
* @see Matrix4.computeViewportTransformation
* @see Matrix2
* @see Matrix3
* @see Packable
*/
var Matrix4 = function(column0Row0, column1Row0, column2Row0, column3Row0,
column0Row1, column1Row1, column2Row1, column3Row1,
column0Row2, column1Row2, column2Row2, column3Row2,
column0Row3, column1Row3, column2Row3, column3Row3) {
this[0] = defaultValue(column0Row0, 0.0);
this[1] = defaultValue(column0Row1, 0.0);
this[2] = defaultValue(column0Row2, 0.0);
this[3] = defaultValue(column0Row3, 0.0);
this[4] = defaultValue(column1Row0, 0.0);
this[5] = defaultValue(column1Row1, 0.0);
this[6] = defaultValue(column1Row2, 0.0);
this[7] = defaultValue(column1Row3, 0.0);
this[8] = defaultValue(column2Row0, 0.0);
this[9] = defaultValue(column2Row1, 0.0);
this[10] = defaultValue(column2Row2, 0.0);
this[11] = defaultValue(column2Row3, 0.0);
this[12] = defaultValue(column3Row0, 0.0);
this[13] = defaultValue(column3Row1, 0.0);
this[14] = defaultValue(column3Row2, 0.0);
this[15] = defaultValue(column3Row3, 0.0);
};
/**
* The number of elements used to pack the object into an array.
* @type {Number}
*/
Matrix4.packedLength = 16;
/**
* Stores the provided instance into the provided array.
*
* @param {Matrix4} value The value to pack.
* @param {Number[]} array The array to pack into.
* @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
*/
Matrix4.pack = function(value, array, startingIndex) {
if (!defined(value)) {
throw new DeveloperError('value is required');
}
if (!defined(array)) {
throw new DeveloperError('array is required');
}
startingIndex = defaultValue(startingIndex, 0);
array[startingIndex++] = value[0];
array[startingIndex++] = value[1];
array[startingIndex++] = value[2];
array[startingIndex++] = value[3];
array[startingIndex++] = value[4];
array[startingIndex++] = value[5];
array[startingIndex++] = value[6];
array[startingIndex++] = value[7];
array[startingIndex++] = value[8];
array[startingIndex++] = value[9];
array[startingIndex++] = value[10];
array[startingIndex++] = value[11];
array[startingIndex++] = value[12];
array[startingIndex++] = value[13];
array[startingIndex++] = value[14];
array[startingIndex] = value[15];
};
/**
* Retrieves an instance from a packed array.
*
* @param {Number[]} array The packed array.
* @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
* @param {Matrix4} [result] The object into which to store the result.
*/
Matrix4.unpack = function(array, startingIndex, result) {
if (!defined(array)) {
throw new DeveloperError('array is required');
}
startingIndex = defaultValue(startingIndex, 0);
if (!defined(result)) {
result = new Matrix4();
}
result[0] = array[startingIndex++];
result[1] = array[startingIndex++];
result[2] = array[startingIndex++];
result[3] = array[startingIndex++];
result[4] = array[startingIndex++];
result[5] = array[startingIndex++];
result[6] = array[startingIndex++];
result[7] = array[startingIndex++];
result[8] = array[startingIndex++];
result[9] = array[startingIndex++];
result[10] = array[startingIndex++];
result[11] = array[startingIndex++];
result[12] = array[startingIndex++];
result[13] = array[startingIndex++];
result[14] = array[startingIndex++];
result[15] = array[startingIndex];
return result;
};
/**
* Duplicates a Matrix4 instance.
*
* @param {Matrix4} matrix The matrix to duplicate.
* @param {Matrix4} [result] The object onto which to store the result.
* @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided. (Returns undefined if matrix is undefined)
*/
Matrix4.clone = function(matrix, result) {
if (!defined(matrix)) {
return undefined;
}
if (!defined(result)) {
return new Matrix4(matrix[0], matrix[4], matrix[8], matrix[12],
matrix[1], matrix[5], matrix[9], matrix[13],
matrix[2], matrix[6], matrix[10], matrix[14],
matrix[3], matrix[7], matrix[11], matrix[15]);
}
result[0] = matrix[0];
result[1] = matrix[1];
result[2] = matrix[2];
result[3] = matrix[3];
result[4] = matrix[4];
result[5] = matrix[5];
result[6] = matrix[6];
result[7] = matrix[7];
result[8] = matrix[8];
result[9] = matrix[9];
result[10] = matrix[10];
result[11] = matrix[11];
result[12] = matrix[12];
result[13] = matrix[13];
result[14] = matrix[14];
result[15] = matrix[15];
return result;
};
/**
* Creates a Matrix4 from 16 consecutive elements in an array.
* @function
*
* @param {Number[]} array The array whose 16 consecutive elements correspond to the positions of the matrix. Assumes column-major order.
* @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to first column first row position in the matrix.
* @param {Matrix4} [result] The object onto which to store the result.
* @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided.
*
* @example
* // Create the Matrix4:
* // [1.0, 2.0, 3.0, 4.0]
* // [1.0, 2.0, 3.0, 4.0]
* // [1.0, 2.0, 3.0, 4.0]
* // [1.0, 2.0, 3.0, 4.0]
*
* var v = [1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0, 3.0, 4.0, 4.0, 4.0, 4.0];
* var m = Cesium.Matrix4.fromArray(v);
*
* // Create same Matrix4 with using an offset into an array
* var v2 = [0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0, 3.0, 4.0, 4.0, 4.0, 4.0];
* var m2 = Cesium.Matrix4.fromArray(v2, 2);
*/
Matrix4.fromArray = Matrix4.unpack;
/**
* Computes a Matrix4 instance from a column-major order array.
*
* @param {Number[]} values The column-major order array.
* @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns The modified result parameter, or a new Matrix4 instance if one was not provided.
*/
Matrix4.fromColumnMajorArray = function(values, result) {
if (!defined(values)) {
throw new DeveloperError('values is required');
}
return Matrix4.clone(values, result);
};
/**
* Computes a Matrix4 instance from a row-major order array.
* The resulting matrix will be in column-major order.
*
* @param {Number[]} values The row-major order array.
* @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns The modified result parameter, or a new Matrix4 instance if one was not provided.
*/
Matrix4.fromRowMajorArray = function(values, result) {
if (!defined(values)) {
throw new DeveloperError('values is required.');
}
if (!defined(result)) {
return new Matrix4(values[0], values[1], values[2], values[3],
values[4], values[5], values[6], values[7],
values[8], values[9], values[10], values[11],
values[12], values[13], values[14], values[15]);
}
result[0] = values[0];
result[1] = values[4];
result[2] = values[8];
result[3] = values[12];
result[4] = values[1];
result[5] = values[5];
result[6] = values[9];
result[7] = values[13];
result[8] = values[2];
result[9] = values[6];
result[10] = values[10];
result[11] = values[14];
result[12] = values[3];
result[13] = values[7];
result[14] = values[11];
result[15] = values[15];
return result;
};
/**
* Computes a Matrix4 instance from a Matrix3 representing the rotation
* and a Cartesian3 representing the translation.
*
* @param {Matrix3} rotation The upper left portion of the matrix representing the rotation.
* @param {Cartesian3} [translation=Cartesian3.ZERO] The upper right portion of the matrix representing the translation.
* @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns The modified result parameter, or a new Matrix4 instance if one was not provided.
*/
Matrix4.fromRotationTranslation = function(rotation, translation, result) {
if (!defined(rotation)) {
throw new DeveloperError('rotation is required.');
}
translation = defaultValue(translation, Cartesian3.ZERO);
if (!defined(result)) {
return new Matrix4(rotation[0], rotation[3], rotation[6], translation.x,
rotation[1], rotation[4], rotation[7], translation.y,
rotation[2], rotation[5], rotation[8], translation.z,
0.0, 0.0, 0.0, 1.0);
}
result[0] = rotation[0];
result[1] = rotation[1];
result[2] = rotation[2];
result[3] = 0.0;
result[4] = rotation[3];
result[5] = rotation[4];
result[6] = rotation[5];
result[7] = 0.0;
result[8] = rotation[6];
result[9] = rotation[7];
result[10] = rotation[8];
result[11] = 0.0;
result[12] = translation.x;
result[13] = translation.y;
result[14] = translation.z;
result[15] = 1.0;
return result;
};
/**
* Computes a Matrix4 instance from a translation, rotation, and scale (TRS)
* representation with the rotation represented as a quaternion.
*
* @param {Cartesian3} translation The translation transformation.
* @param {Quaternion} rotation The rotation transformation.
* @param {Cartesian3} scale The non-uniform scale transformation.
* @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns The modified result parameter, or a new Matrix4 instance if one was not provided.
*
* @example
* var result = Cesium.Matrix4.fromTranslationQuaternionRotationScale(
* new Cesium.Cartesian3(1.0, 2.0, 3.0), // translation
* Cesium.Quaternion.IDENTITY, // rotation
* new Cesium.Cartesian3(7.0, 8.0, 9.0), // scale
* result);
*/
Matrix4.fromTranslationQuaternionRotationScale = function(translation, rotation, scale, result) {
if (!defined(translation)) {
throw new DeveloperError('translation is required.');
}
if (!defined(rotation)) {
throw new DeveloperError('rotation is required.');
}
if (!defined(scale)) {
throw new DeveloperError('scale is required.');
}
if (!defined(result)) {
result = new Matrix4();
}
var scaleX = scale.x;
var scaleY = scale.y;
var scaleZ = scale.z;
var x2 = rotation.x * rotation.x;
var xy = rotation.x * rotation.y;
var xz = rotation.x * rotation.z;
var xw = rotation.x * rotation.w;
var y2 = rotation.y * rotation.y;
var yz = rotation.y * rotation.z;
var yw = rotation.y * rotation.w;
var z2 = rotation.z * rotation.z;
var zw = rotation.z * rotation.w;
var w2 = rotation.w * rotation.w;
var m00 = x2 - y2 - z2 + w2;
var m01 = 2.0 * (xy - zw);
var m02 = 2.0 * (xz + yw);
var m10 = 2.0 * (xy + zw);
var m11 = -x2 + y2 - z2 + w2;
var m12 = 2.0 * (yz - xw);
var m20 = 2.0 * (xz - yw);
var m21 = 2.0 * (yz + xw);
var m22 = -x2 - y2 + z2 + w2;
result[0] = m00 * scaleX;
result[1] = m10 * scaleX;
result[2] = m20 * scaleX;
result[3] = 0.0;
result[4] = m01 * scaleY;
result[5] = m11 * scaleY;
result[6] = m21 * scaleY;
result[7] = 0.0;
result[8] = m02 * scaleZ;
result[9] = m12 * scaleZ;
result[10] = m22 * scaleZ;
result[11] = 0.0;
result[12] = translation.x;
result[13] = translation.y;
result[14] = translation.z;
result[15] = 1.0;
return result;
};
/**
* Creates a Matrix4 instance from a Cartesian3 representing the translation.
*
* @param {Cartesian3} translation The upper right portion of the matrix representing the translation.
* @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns The modified result parameter, or a new Matrix4 instance if one was not provided.
*
* @see Matrix4.multiplyByTranslation
*/
Matrix4.fromTranslation = function(translation, result) {
if (!defined(translation)) {
throw new DeveloperError('translation is required.');
}
return Matrix4.fromRotationTranslation(Matrix3.IDENTITY, translation, result);
};
/**
* Computes a Matrix4 instance representing a non-uniform scale.
*
* @param {Cartesian3} scale The x, y, and z scale factors.
* @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns The modified result parameter, or a new Matrix4 instance if one was not provided.
*
* @example
* // Creates
* // [7.0, 0.0, 0.0, 0.0]
* // [0.0, 8.0, 0.0, 0.0]
* // [0.0, 0.0, 9.0, 0.0]
* // [0.0, 0.0, 0.0, 1.0]
* var m = Cesium.Matrix4.fromScale(new Cesium.Cartesian3(7.0, 8.0, 9.0));
*/
Matrix4.fromScale = function(scale, result) {
if (!defined(scale)) {
throw new DeveloperError('scale is required.');
}
if (!defined(result)) {
return new Matrix4(
scale.x, 0.0, 0.0, 0.0,
0.0, scale.y, 0.0, 0.0,
0.0, 0.0, scale.z, 0.0,
0.0, 0.0, 0.0, 1.0);
}
result[0] = scale.x;
result[1] = 0.0;
result[2] = 0.0;
result[3] = 0.0;
result[4] = 0.0;
result[5] = scale.y;
result[6] = 0.0;
result[7] = 0.0;
result[8] = 0.0;
result[9] = 0.0;
result[10] = scale.z;
result[11] = 0.0;
result[12] = 0.0;
result[13] = 0.0;
result[14] = 0.0;
result[15] = 1.0;
return result;
};
/**
* Computes a Matrix4 instance representing a uniform scale.
*
* @param {Number} scale The uniform scale factor.
* @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns The modified result parameter, or a new Matrix4 instance if one was not provided.
*
* @example
* // Creates
* // [2.0, 0.0, 0.0, 0.0]
* // [0.0, 2.0, 0.0, 0.0]
* // [0.0, 0.0, 2.0, 0.0]
* // [0.0, 0.0, 0.0, 1.0]
* var m = Cesium.Matrix4.fromUniformScale(2.0);
*/
Matrix4.fromUniformScale = function(scale, result) {
if (typeof scale !== 'number') {
throw new DeveloperError('scale is required.');
}
if (!defined(result)) {
return new Matrix4(scale, 0.0, 0.0, 0.0,
0.0, scale, 0.0, 0.0,
0.0, 0.0, scale, 0.0,
0.0, 0.0, 0.0, 1.0);
}
result[0] = scale;
result[1] = 0.0;
result[2] = 0.0;
result[3] = 0.0;
result[4] = 0.0;
result[5] = scale;
result[6] = 0.0;
result[7] = 0.0;
result[8] = 0.0;
result[9] = 0.0;
result[10] = scale;
result[11] = 0.0;
result[12] = 0.0;
result[13] = 0.0;
result[14] = 0.0;
result[15] = 1.0;
return result;
};
var fromCameraF = new Cartesian3();
var fromCameraS = new Cartesian3();
var fromCameraU = new Cartesian3();
/**
* Computes a Matrix4 instance from a Camera.
*
* @param {Camera} camera The camera to use.
* @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns The modified result parameter, or a new Matrix4 instance if one was not provided.
*/
Matrix4.fromCamera = function(camera, result) {
if (!defined(camera)) {
throw new DeveloperError('camera is required.');
}
var eye = camera.eye;
var target = camera.target;
var up = camera.up;
if (!defined(eye)) {
throw new DeveloperError('camera.eye is required.');
}
if (!defined(target)) {
throw new DeveloperError('camera.target is required.');
}
if (!defined(up)) {
throw new DeveloperError('camera.up is required.');
}
Cartesian3.normalize(Cartesian3.subtract(target, eye, fromCameraF), fromCameraF);
Cartesian3.normalize(Cartesian3.cross(fromCameraF, up, fromCameraS), fromCameraS);
Cartesian3.normalize(Cartesian3.cross(fromCameraS, fromCameraF, fromCameraU), fromCameraU);
var sX = fromCameraS.x;
var sY = fromCameraS.y;
var sZ = fromCameraS.z;
var fX = fromCameraF.x;
var fY = fromCameraF.y;
var fZ = fromCameraF.z;
var uX = fromCameraU.x;
var uY = fromCameraU.y;
var uZ = fromCameraU.z;
var eyeX = eye.x;
var eyeY = eye.y;
var eyeZ = eye.z;
var t0 = sX * -eyeX + sY * -eyeY+ sZ * -eyeZ;
var t1 = uX * -eyeX + uY * -eyeY+ uZ * -eyeZ;
var t2 = fX * eyeX + fY * eyeY + fZ * eyeZ;
//The code below this comment is an optimized
//version of the commented lines.
//Rather that create two matrices and then multiply,
//we just bake in the multiplcation as part of creation.
//var rotation = new Matrix4(
// sX, sY, sZ, 0.0,
// uX, uY, uZ, 0.0,
// -fX, -fY, -fZ, 0.0,
// 0.0, 0.0, 0.0, 1.0);
//var translation = new Matrix4(
// 1.0, 0.0, 0.0, -eye.x,
// 0.0, 1.0, 0.0, -eye.y,
// 0.0, 0.0, 1.0, -eye.z,
// 0.0, 0.0, 0.0, 1.0);
//return rotation.multiply(translation);
if (!defined(result)) {
return new Matrix4(
sX, sY, sZ, t0,
uX, uY, uZ, t1,
-fX, -fY, -fZ, t2,
0.0, 0.0, 0.0, 1.0);
}
result[0] = sX;
result[1] = uX;
result[2] = -fX;
result[3] = 0.0;
result[4] = sY;
result[5] = uY;
result[6] = -fY;
result[7] = 0.0;
result[8] = sZ;
result[9] = uZ;
result[10] = -fZ;
result[11] = 0.0;
result[12] = t0;
result[13] = t1;
result[14] = t2;
result[15] = 1.0;
return result;
};
/**
* Computes a Matrix4 instance representing a perspective transformation matrix.
*
* @param {Number} fovY The field of view along the Y axis in radians.
* @param {Number} aspectRatio The aspect ratio.
* @param {Number} near The distance to the near plane in meters.
* @param {Number} far The distance to the far plane in meters.
* @param {Matrix4} result The object in which the result will be stored.
* @returns The modified result parameter.
*
* @exception {DeveloperError} fovY must be in [0, PI).
* @exception {DeveloperError} aspectRatio must be greater than zero.
* @exception {DeveloperError} near must be greater than zero.
* @exception {DeveloperError} far must be greater than zero.
*/
Matrix4.computePerspectiveFieldOfView = function(fovY, aspectRatio, near, far, result) {
if (fovY <= 0.0 || fovY > Math.PI) {
throw new DeveloperError('fovY must be in [0, PI).');
}
if (aspectRatio <= 0.0) {
throw new DeveloperError('aspectRatio must be greater than zero.');
}
if (near <= 0.0) {
throw new DeveloperError('near must be greater than zero.');
}
if (far <= 0.0) {
throw new DeveloperError('far must be greater than zero.');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
var bottom = Math.tan(fovY * 0.5);
var column1Row1 = 1.0 / bottom;
var column0Row0 = column1Row1 / aspectRatio;
var column2Row2 = (far + near) / (near - far);
var column3Row2 = (2.0 * far * near) / (near - far);
result[0] = column0Row0;
result[1] = 0.0;
result[2] = 0.0;
result[3] = 0.0;
result[4] = 0.0;
result[5] = column1Row1;
result[6] = 0.0;
result[7] = 0.0;
result[8] = 0.0;
result[9] = 0.0;
result[10] = column2Row2;
result[11] = -1.0;
result[12] = 0.0;
result[13] = 0.0;
result[14] = column3Row2;
result[15] = 0.0;
return result;
};
/**
* Computes a Matrix4 instance representing an orthographic transformation matrix.
*
* @param {Number} left The number of meters to the left of the camera that will be in view.
* @param {Number} right The number of meters to the right of the camera that will be in view.
* @param {Number} bottom The number of meters below of the camera that will be in view.
* @param {Number} top The number of meters above of the camera that will be in view.
* @param {Number} near The distance to the near plane in meters.
* @param {Number} far The distance to the far plane in meters.
* @param {Matrix4} result The object in which the result will be stored.
* @returns The modified result parameter.
*/
Matrix4.computeOrthographicOffCenter = function(left, right, bottom, top, near, far, result) {
if (!defined(left)) {
throw new DeveloperError('left is required.');
}
if (!defined(right)) {
throw new DeveloperError('right is required.');
}
if (!defined(bottom)) {
throw new DeveloperError('bottom is required.');
}
if (!defined(top)) {
throw new DeveloperError('top is required.');
}
if (!defined(near)) {
throw new DeveloperError('near is required.');
}
if (!defined(far)) {
throw new DeveloperError('far is required.');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
var a = 1.0 / (right - left);
var b = 1.0 / (top - bottom);
var c = 1.0 / (far - near);
var tx = -(right + left) * a;
var ty = -(top + bottom) * b;
var tz = -(far + near) * c;
a *= 2.0;
b *= 2.0;
c *= -2.0;
result[0] = a;
result[1] = 0.0;
result[2] = 0.0;
result[3] = 0.0;
result[4] = 0.0;
result[5] = b;
result[6] = 0.0;
result[7] = 0.0;
result[8] = 0.0;
result[9] = 0.0;
result[10] = c;
result[11] = 0.0;
result[12] = tx;
result[13] = ty;
result[14] = tz;
result[15] = 1.0;
return result;
};
/**
* Computes a Matrix4 instance representing an off center perspective transformation.
*
* @param {Number} left The number of meters to the left of the camera that will be in view.
* @param {Number} right The number of meters to the right of the camera that will be in view.
* @param {Number} bottom The number of meters below of the camera that will be in view.
* @param {Number} top The number of meters above of the camera that will be in view.
* @param {Number} near The distance to the near plane in meters.
* @param {Number} far The distance to the far plane in meters.
* @param {Matrix4} result The object in which the result will be stored.
* @returns The modified result parameter.
*/
Matrix4.computePerspectiveOffCenter = function(left, right, bottom, top, near, far, result) {
if (!defined(left)) {
throw new DeveloperError('left is required.');
}
if (!defined(right)) {
throw new DeveloperError('right is required.');
}
if (!defined(bottom)) {
throw new DeveloperError('bottom is required.');
}
if (!defined(top)) {
throw new DeveloperError('top is required.');
}
if (!defined(near)) {
throw new DeveloperError('near is required.');
}
if (!defined(far)) {
throw new DeveloperError('far is required.');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
var column0Row0 = 2.0 * near / (right - left);
var column1Row1 = 2.0 * near / (top - bottom);
var column2Row0 = (right + left) / (right - left);
var column2Row1 = (top + bottom) / (top - bottom);
var column2Row2 = -(far + near) / (far - near);
var column2Row3 = -1.0;
var column3Row2 = -2.0 * far * near / (far - near);
result[0] = column0Row0;
result[1] = 0.0;
result[2] = 0.0;
result[3] = 0.0;
result[4] = 0.0;
result[5] = column1Row1;
result[6] = 0.0;
result[7] = 0.0;
result[8] = column2Row0;
result[9] = column2Row1;
result[10] = column2Row2;
result[11] = column2Row3;
result[12] = 0.0;
result[13] = 0.0;
result[14] = column3Row2;
result[15] = 0.0;
return result;
};
/**
* Computes a Matrix4 instance representing an infinite off center perspective transformation.
*
* @param {Number} left The number of meters to the left of the camera that will be in view.
* @param {Number} right The number of meters to the right of the camera that will be in view.
* @param {Number} bottom The number of meters below of the camera that will be in view.
* @param {Number} top The number of meters above of the camera that will be in view.
* @param {Number} near The distance to the near plane in meters.
* @param {Number} far The distance to the far plane in meters.
* @param {Matrix4} result The object in which the result will be stored.
* @returns The modified result parameter.
*/
Matrix4.computeInfinitePerspectiveOffCenter = function(left, right, bottom, top, near, result) {
if (!defined(left)) {
throw new DeveloperError('left is required.');
}
if (!defined(right)) {
throw new DeveloperError('right is required.');
}
if (!defined(bottom)) {
throw new DeveloperError('bottom is required.');
}
if (!defined(top)) {
throw new DeveloperError('top is required.');
}
if (!defined(near)) {
throw new DeveloperError('near is required.');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
var column0Row0 = 2.0 * near / (right - left);
var column1Row1 = 2.0 * near / (top - bottom);
var column2Row0 = (right + left) / (right - left);
var column2Row1 = (top + bottom) / (top - bottom);
var column2Row2 = -1.0;
var column2Row3 = -1.0;
var column3Row2 = -2.0 * near;
result[0] = column0Row0;
result[1] = 0.0;
result[2] = 0.0;
result[3] = 0.0;
result[4] = 0.0;
result[5] = column1Row1;
result[6] = 0.0;
result[7] = 0.0;
result[8] = column2Row0;
result[9] = column2Row1;
result[10] = column2Row2;
result[11] = column2Row3;
result[12] = 0.0;
result[13] = 0.0;
result[14] = column3Row2;
result[15] = 0.0;
return result;
};
/**
* Computes a Matrix4 instance that transforms from normalized device coordinates to window coordinates.
*
* @param {Object}[viewport = { x : 0.0, y : 0.0, width : 0.0, height : 0.0 }] The viewport's corners as shown in Example 1.
* @param {Number}[nearDepthRange=0.0] The near plane distance in window coordinates.
* @param {Number}[farDepthRange=1.0] The far plane distance in window coordinates.
* @param {Matrix4} result The object in which the result will be stored.
* @returns The modified result parameter.
*
* @example
* // Create viewport transformation using an explicit viewport and depth range.
* var m = Cesium.Matrix4.computeViewportTransformation({
* x : 0.0,
* y : 0.0,
* width : 1024.0,
* height : 768.0
* }, 0.0, 1.0, new Cesium.Matrix4());
*/
Matrix4.computeViewportTransformation = function(viewport, nearDepthRange, farDepthRange, result) {
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
viewport = defaultValue(viewport, defaultValue.EMPTY_OBJECT);
var x = defaultValue(viewport.x, 0.0);
var y = defaultValue(viewport.y, 0.0);
var width = defaultValue(viewport.width, 0.0);
var height = defaultValue(viewport.height, 0.0);
nearDepthRange = defaultValue(nearDepthRange, 0.0);
farDepthRange = defaultValue(farDepthRange, 1.0);
var halfWidth = width * 0.5;
var halfHeight = height * 0.5;
var halfDepth = (farDepthRange - nearDepthRange) * 0.5;
var column0Row0 = halfWidth;
var column1Row1 = halfHeight;
var column2Row2 = halfDepth;
var column3Row0 = x + halfWidth;
var column3Row1 = y + halfHeight;
var column3Row2 = nearDepthRange + halfDepth;
var column3Row3 = 1.0;
result[0] = column0Row0;
result[1] = 0.0;
result[2] = 0.0;
result[3] = 0.0;
result[4] = 0.0;
result[5] = column1Row1;
result[6] = 0.0;
result[7] = 0.0;
result[8] = 0.0;
result[9] = 0.0;
result[10] = column2Row2;
result[11] = 0.0;
result[12] = column3Row0;
result[13] = column3Row1;
result[14] = column3Row2;
result[15] = column3Row3;
return result;
};
/**
* Computes an Array from the provided Matrix4 instance.
* The array will be in column-major order.
*
* @param {Matrix4} matrix The matrix to use..
* @param {Number[]} [result] The Array onto which to store the result.
* @returns {Number[]} The modified Array parameter or a new Array instance if one was not provided.
*
* @example
* //create an array from an instance of Matrix4
* // m = [10.0, 14.0, 18.0, 22.0]
* // [11.0, 15.0, 19.0, 23.0]
* // [12.0, 16.0, 20.0, 24.0]
* // [13.0, 17.0, 21.0, 25.0]
* var a = Cesium.Matrix4.toArray(m);
*
* // m remains the same
* //creates a = [10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0, 25.0]
*/
Matrix4.toArray = function(matrix, result) {
if (!defined(matrix)) {
throw new DeveloperError('matrix is required');
}
if (!defined(result)) {
return [matrix[0], matrix[1], matrix[2], matrix[3],
matrix[4], matrix[5], matrix[6], matrix[7],
matrix[8], matrix[9], matrix[10], matrix[11],
matrix[12], matrix[13], matrix[14], matrix[15]];
}
result[0] = matrix[0];
result[1] = matrix[1];
result[2] = matrix[2];
result[3] = matrix[3];
result[4] = matrix[4];
result[5] = matrix[5];
result[6] = matrix[6];
result[7] = matrix[7];
result[8] = matrix[8];
result[9] = matrix[9];
result[10] = matrix[10];
result[11] = matrix[11];
result[12] = matrix[12];
result[13] = matrix[13];
result[14] = matrix[14];
result[15] = matrix[15];
return result;
};
/**
* Computes the array index of the element at the provided row and column.
*
* @param {Number} row The zero-based index of the row.
* @param {Number} column The zero-based index of the column.
* @returns {Number} The index of the element at the provided row and column.
*
* @exception {DeveloperError} row must be 0, 1, 2, or 3.
* @exception {DeveloperError} column must be 0, 1, 2, or 3.
*
* @example
* var myMatrix = new Cesium.Matrix4();
* var column1Row0Index = Cesium.Matrix4.getElementIndex(1, 0);
* var column1Row0 = myMatrix[column1Row0Index];
* myMatrix[column1Row0Index] = 10.0;
*/
Matrix4.getElementIndex = function(column, row) {
if (typeof row !== 'number' || row < 0 || row > 3) {
throw new DeveloperError('row must be 0, 1, 2, or 3.');
}
if (typeof column !== 'number' || column < 0 || column > 3) {
throw new DeveloperError('column must be 0, 1, 2, or 3.');
}
return column * 4 + row;
};
/**
* Retrieves a copy of the matrix column at the provided index as a Cartesian4 instance.
*
* @param {Matrix4} matrix The matrix to use.
* @param {Number} index The zero-based index of the column to retrieve.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter.
*
* @exception {DeveloperError} index must be 0, 1, 2, or 3.
*
* @example
* //returns a Cartesian4 instance with values from the specified column
* // m = [10.0, 11.0, 12.0, 13.0]
* // [14.0, 15.0, 16.0, 17.0]
* // [18.0, 19.0, 20.0, 21.0]
* // [22.0, 23.0, 24.0, 25.0]
*
* //Example 1: Creates an instance of Cartesian
* var a = Cesium.Matrix4.getColumn(m, 2, new Cesium.Cartesian4());
*
* @example
* //Example 2: Sets values for Cartesian instance
* var a = new Cesium.Cartesian4();
* Cesium.Matrix4.getColumn(m, 2, a);
*
* // a.x = 12.0; a.y = 16.0; a.z = 20.0; a.w = 24.0;
*/
Matrix4.getColumn = function(matrix, index, result) {
if (!defined(matrix)) {
throw new DeveloperError('matrix is required.');
}
if (typeof index !== 'number' || index < 0 || index > 3) {
throw new DeveloperError('index must be 0, 1, 2, or 3.');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
var startIndex = index * 4;
var x = matrix[startIndex];
var y = matrix[startIndex + 1];
var z = matrix[startIndex + 2];
var w = matrix[startIndex + 3];
result.x = x;
result.y = y;
result.z = z;
result.w = w;
return result;
};
/**
* Computes a new matrix that replaces the specified column in the provided matrix with the provided Cartesian4 instance.
*
* @param {Matrix4} matrix The matrix to use.
* @param {Number} index The zero-based index of the column to set.
* @param {Cartesian4} cartesian The Cartesian whose values will be assigned to the specified column.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
* @exception {DeveloperError} index must be 0, 1, 2, or 3.
*
* @example
* //creates a new Matrix4 instance with new column values from the Cartesian4 instance
* // m = [10.0, 11.0, 12.0, 13.0]
* // [14.0, 15.0, 16.0, 17.0]
* // [18.0, 19.0, 20.0, 21.0]
* // [22.0, 23.0, 24.0, 25.0]
*
* var a = Cesium.Matrix4.setColumn(m, 2, new Cesium.Cartesian4(99.0, 98.0, 97.0, 96.0), new Cesium.Matrix4());
*
* // m remains the same
* // a = [10.0, 11.0, 99.0, 13.0]
* // [14.0, 15.0, 98.0, 17.0]
* // [18.0, 19.0, 97.0, 21.0]
* // [22.0, 23.0, 96.0, 25.0]
*/
Matrix4.setColumn = function(matrix, index, cartesian, result) {
if (!defined(matrix)) {
throw new DeveloperError('matrix is required');
}
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required');
}
if (typeof index !== 'number' || index < 0 || index > 3) {
throw new DeveloperError('index must be 0, 1, 2, or 3.');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
result = Matrix4.clone(matrix, result);
var startIndex = index * 4;
result[startIndex] = cartesian.x;
result[startIndex + 1] = cartesian.y;
result[startIndex + 2] = cartesian.z;
result[startIndex + 3] = cartesian.w;
return result;
};
/**
* Retrieves a copy of the matrix row at the provided index as a Cartesian4 instance.
*
* @param {Matrix4} matrix The matrix to use.
* @param {Number} index The zero-based index of the row to retrieve.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter.
*
* @exception {DeveloperError} index must be 0, 1, 2, or 3.
*
* @example
* //returns a Cartesian4 instance with values from the specified column
* // m = [10.0, 11.0, 12.0, 13.0]
* // [14.0, 15.0, 16.0, 17.0]
* // [18.0, 19.0, 20.0, 21.0]
* // [22.0, 23.0, 24.0, 25.0]
*
* //Example 1: Returns an instance of Cartesian
* var a = Cesium.Matrix4.getRow(m, 2, new Cesium.Cartesian4());
*
* @example
* //Example 2: Sets values for a Cartesian instance
* var a = new Cesium.Cartesian4();
* Cesium.Matrix4.getRow(m, 2, a);
*
* // a.x = 18.0; a.y = 19.0; a.z = 20.0; a.w = 21.0;
*/
Matrix4.getRow = function(matrix, index, result) {
if (!defined(matrix)) {
throw new DeveloperError('matrix is required.');
}
if (typeof index !== 'number' || index < 0 || index > 3) {
throw new DeveloperError('index must be 0, 1, 2, or 3.');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
var x = matrix[index];
var y = matrix[index + 4];
var z = matrix[index + 8];
var w = matrix[index + 12];
result.x = x;
result.y = y;
result.z = z;
result.w = w;
return result;
};
/**
* Computes a new matrix that replaces the specified row in the provided matrix with the provided Cartesian4 instance.
*
* @param {Matrix4} matrix The matrix to use.
* @param {Number} index The zero-based index of the row to set.
* @param {Cartesian4} cartesian The Cartesian whose values will be assigned to the specified row.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
* @exception {DeveloperError} index must be 0, 1, 2, or 3.
*
* @example
* //create a new Matrix4 instance with new row values from the Cartesian4 instance
* // m = [10.0, 11.0, 12.0, 13.0]
* // [14.0, 15.0, 16.0, 17.0]
* // [18.0, 19.0, 20.0, 21.0]
* // [22.0, 23.0, 24.0, 25.0]
*
* var a = Cesium.Matrix4.setRow(m, 2, new Cesium.Cartesian4(99.0, 98.0, 97.0, 96.0), new Cesium.Matrix4());
*
* // m remains the same
* // a = [10.0, 11.0, 12.0, 13.0]
* // [14.0, 15.0, 16.0, 17.0]
* // [99.0, 98.0, 97.0, 96.0]
* // [22.0, 23.0, 24.0, 25.0]
*/
Matrix4.setRow = function(matrix, index, cartesian, result) {
if (!defined(matrix)) {
throw new DeveloperError('matrix is required');
}
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required');
}
if (typeof index !== 'number' || index < 0 || index > 3) {
throw new DeveloperError('index must be 0, 1, 2, or 3.');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
result = Matrix4.clone(matrix, result);
result[index] = cartesian.x;
result[index + 4] = cartesian.y;
result[index + 8] = cartesian.z;
result[index + 12] = cartesian.w;
return result;
};
var scratchColumn = new Cartesian3();
/**
* Extracts the non-uniform scale assuming the matrix is an affine transformation.
*
* @param {Matrix4} matrix The matrix.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter
*/
Matrix4.getScale = function(matrix, result) {
if (!defined(matrix)) {
throw new DeveloperError('matrix is required.');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
result.x = Cartesian3.magnitude(Cartesian3.fromElements(matrix[0], matrix[1], matrix[2], scratchColumn));
result.y = Cartesian3.magnitude(Cartesian3.fromElements(matrix[4], matrix[5], matrix[6], scratchColumn));
result.z = Cartesian3.magnitude(Cartesian3.fromElements(matrix[8], matrix[9], matrix[10], scratchColumn));
return result;
};
var scratchScale = new Cartesian3();
/**
* Computes the maximum scale assuming the matrix is an affine transformation.
* The maximum scale is the maximum length of the column vectors in the upper-left
* 3x3 matrix.
*
* @param {Matrix4} matrix The matrix.
* @returns {Number} The maximum scale.
*/
Matrix4.getMaximumScale = function(matrix) {
Matrix4.getScale(matrix, scratchScale);
return Cartesian3.maximumComponent(scratchScale);
};
/**
* Computes the product of two matrices.
*
* @param {Matrix4} left The first matrix.
* @param {Matrix4} right The second matrix.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*/
Matrix4.multiply = function(left, right, result) {
if (!defined(left)) {
throw new DeveloperError('left is required');
}
if (!defined(right)) {
throw new DeveloperError('right is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
var left0 = left[0];
var left1 = left[1];
var left2 = left[2];
var left3 = left[3];
var left4 = left[4];
var left5 = left[5];
var left6 = left[6];
var left7 = left[7];
var left8 = left[8];
var left9 = left[9];
var left10 = left[10];
var left11 = left[11];
var left12 = left[12];
var left13 = left[13];
var left14 = left[14];
var left15 = left[15];
var right0 = right[0];
var right1 = right[1];
var right2 = right[2];
var right3 = right[3];
var right4 = right[4];
var right5 = right[5];
var right6 = right[6];
var right7 = right[7];
var right8 = right[8];
var right9 = right[9];
var right10 = right[10];
var right11 = right[11];
var right12 = right[12];
var right13 = right[13];
var right14 = right[14];
var right15 = right[15];
var column0Row0 = left0 * right0 + left4 * right1 + left8 * right2 + left12 * right3;
var column0Row1 = left1 * right0 + left5 * right1 + left9 * right2 + left13 * right3;
var column0Row2 = left2 * right0 + left6 * right1 + left10 * right2 + left14 * right3;
var column0Row3 = left3 * right0 + left7 * right1 + left11 * right2 + left15 * right3;
var column1Row0 = left0 * right4 + left4 * right5 + left8 * right6 + left12 * right7;
var column1Row1 = left1 * right4 + left5 * right5 + left9 * right6 + left13 * right7;
var column1Row2 = left2 * right4 + left6 * right5 + left10 * right6 + left14 * right7;
var column1Row3 = left3 * right4 + left7 * right5 + left11 * right6 + left15 * right7;
var column2Row0 = left0 * right8 + left4 * right9 + left8 * right10 + left12 * right11;
var column2Row1 = left1 * right8 + left5 * right9 + left9 * right10 + left13 * right11;
var column2Row2 = left2 * right8 + left6 * right9 + left10 * right10 + left14 * right11;
var column2Row3 = left3 * right8 + left7 * right9 + left11 * right10 + left15 * right11;
var column3Row0 = left0 * right12 + left4 * right13 + left8 * right14 + left12 * right15;
var column3Row1 = left1 * right12 + left5 * right13 + left9 * right14 + left13 * right15;
var column3Row2 = left2 * right12 + left6 * right13 + left10 * right14 + left14 * right15;
var column3Row3 = left3 * right12 + left7 * right13 + left11 * right14 + left15 * right15;
result[0] = column0Row0;
result[1] = column0Row1;
result[2] = column0Row2;
result[3] = column0Row3;
result[4] = column1Row0;
result[5] = column1Row1;
result[6] = column1Row2;
result[7] = column1Row3;
result[8] = column2Row0;
result[9] = column2Row1;
result[10] = column2Row2;
result[11] = column2Row3;
result[12] = column3Row0;
result[13] = column3Row1;
result[14] = column3Row2;
result[15] = column3Row3;
return result;
};
/**
* Computes the sum of two matrices.
*
* @param {Matrix4} left The first matrix.
* @param {Matrix4} right The second matrix.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*/
Matrix4.add = function(left, right, result) {
if (!defined(left)) {
throw new DeveloperError('left is required');
}
if (!defined(right)) {
throw new DeveloperError('right is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
result[0] = left[0] + right[0];
result[1] = left[1] + right[1];
result[2] = left[2] + right[2];
result[3] = left[3] + right[3];
result[4] = left[4] + right[4];
result[5] = left[5] + right[5];
result[6] = left[6] + right[6];
result[7] = left[7] + right[7];
result[8] = left[8] + right[8];
result[9] = left[9] + right[9];
result[10] = left[10] + right[10];
result[11] = left[11] + right[11];
result[12] = left[12] + right[12];
result[13] = left[13] + right[13];
result[14] = left[14] + right[14];
result[15] = left[15] + right[15];
return result;
};
/**
* Computes the difference of two matrices.
*
* @param {Matrix4} left The first matrix.
* @param {Matrix4} right The second matrix.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*/
Matrix4.subtract = function(left, right, result) {
if (!defined(left)) {
throw new DeveloperError('left is required');
}
if (!defined(right)) {
throw new DeveloperError('right is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
result[0] = left[0] - right[0];
result[1] = left[1] - right[1];
result[2] = left[2] - right[2];
result[3] = left[3] - right[3];
result[4] = left[4] - right[4];
result[5] = left[5] - right[5];
result[6] = left[6] - right[6];
result[7] = left[7] - right[7];
result[8] = left[8] - right[8];
result[9] = left[9] - right[9];
result[10] = left[10] - right[10];
result[11] = left[11] - right[11];
result[12] = left[12] - right[12];
result[13] = left[13] - right[13];
result[14] = left[14] - right[14];
result[15] = left[15] - right[15];
return result;
};
/**
* Computes the product of two matrices assuming the matrices are
* affine transformation matrices, where the upper left 3x3 elements
* are a rotation matrix, and the upper three elements in the fourth
* column are the translation. The bottom row is assumed to be [0, 0, 0, 1].
* The matrix is not verified to be in the proper form.
* This method is faster than computing the product for general 4x4
* matrices using {@link Matrix4.multiply}.
*
* @param {Matrix4} left The first matrix.
* @param {Matrix4} right The second matrix.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
* @example
* var m1 = new Cesium.Matrix4(1.0, 6.0, 7.0, 0.0, 2.0, 5.0, 8.0, 0.0, 3.0, 4.0, 9.0, 0.0, 0.0, 0.0, 0.0, 1.0);
* var m2 = Cesium.Transforms.eastNorthUpToFixedFrame(new Cesium.Cartesian3(1.0, 1.0, 1.0));
* var m3 = Cesium.Matrix4.multiplyTransformation(m1, m2, new Cesium.Matrix4());
*/
Matrix4.multiplyTransformation = function(left, right, result) {
if (!defined(left)) {
throw new DeveloperError('left is required');
}
if (!defined(right)) {
throw new DeveloperError('right is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
var left0 = left[0];
var left1 = left[1];
var left2 = left[2];
var left4 = left[4];
var left5 = left[5];
var left6 = left[6];
var left8 = left[8];
var left9 = left[9];
var left10 = left[10];
var left12 = left[12];
var left13 = left[13];
var left14 = left[14];
var right0 = right[0];
var right1 = right[1];
var right2 = right[2];
var right4 = right[4];
var right5 = right[5];
var right6 = right[6];
var right8 = right[8];
var right9 = right[9];
var right10 = right[10];
var right12 = right[12];
var right13 = right[13];
var right14 = right[14];
var column0Row0 = left0 * right0 + left4 * right1 + left8 * right2;
var column0Row1 = left1 * right0 + left5 * right1 + left9 * right2;
var column0Row2 = left2 * right0 + left6 * right1 + left10 * right2;
var column1Row0 = left0 * right4 + left4 * right5 + left8 * right6;
var column1Row1 = left1 * right4 + left5 * right5 + left9 * right6;
var column1Row2 = left2 * right4 + left6 * right5 + left10 * right6;
var column2Row0 = left0 * right8 + left4 * right9 + left8 * right10;
var column2Row1 = left1 * right8 + left5 * right9 + left9 * right10;
var column2Row2 = left2 * right8 + left6 * right9 + left10 * right10;
var column3Row0 = left0 * right12 + left4 * right13 + left8 * right14 + left12;
var column3Row1 = left1 * right12 + left5 * right13 + left9 * right14 + left13;
var column3Row2 = left2 * right12 + left6 * right13 + left10 * right14 + left14;
result[0] = column0Row0;
result[1] = column0Row1;
result[2] = column0Row2;
result[3] = 0.0;
result[4] = column1Row0;
result[5] = column1Row1;
result[6] = column1Row2;
result[7] = 0.0;
result[8] = column2Row0;
result[9] = column2Row1;
result[10] = column2Row2;
result[11] = 0.0;
result[12] = column3Row0;
result[13] = column3Row1;
result[14] = column3Row2;
result[15] = 1.0;
return result;
};
/**
* Multiplies a transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
* by a 3x3 rotation matrix. This is an optimization
* for <code>Matrix4.multiply(m, Matrix4.fromRotationTranslation(rotation), m);</code> with less allocations and arithmetic operations.
*
* @param {Matrix4} matrix The matrix on the left-hand side.
* @param {Matrix3} rotation The 3x3 rotation matrix on the right-hand side.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
* @example
* // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromRotationTranslation(rotation), m);
* Cesium.Matrix4.multiplyByMatrix3(m, rotation, m);
*/
Matrix4.multiplyByMatrix3 = function(matrix, rotation, result) {
if (!defined(matrix)) {
throw new DeveloperError('matrix is required');
}
if (!defined(rotation)) {
throw new DeveloperError('rotation is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
var left0 = matrix[0];
var left1 = matrix[1];
var left2 = matrix[2];
var left4 = matrix[4];
var left5 = matrix[5];
var left6 = matrix[6];
var left8 = matrix[8];
var left9 = matrix[9];
var left10 = matrix[10];
var right0 = rotation[0];
var right1 = rotation[1];
var right2 = rotation[2];
var right4 = rotation[3];
var right5 = rotation[4];
var right6 = rotation[5];
var right8 = rotation[6];
var right9 = rotation[7];
var right10 = rotation[8];
var column0Row0 = left0 * right0 + left4 * right1 + left8 * right2;
var column0Row1 = left1 * right0 + left5 * right1 + left9 * right2;
var column0Row2 = left2 * right0 + left6 * right1 + left10 * right2;
var column1Row0 = left0 * right4 + left4 * right5 + left8 * right6;
var column1Row1 = left1 * right4 + left5 * right5 + left9 * right6;
var column1Row2 = left2 * right4 + left6 * right5 + left10 * right6;
var column2Row0 = left0 * right8 + left4 * right9 + left8 * right10;
var column2Row1 = left1 * right8 + left5 * right9 + left9 * right10;
var column2Row2 = left2 * right8 + left6 * right9 + left10 * right10;
result[0] = column0Row0;
result[1] = column0Row1;
result[2] = column0Row2;
result[3] = 0.0;
result[4] = column1Row0;
result[5] = column1Row1;
result[6] = column1Row2;
result[7] = 0.0;
result[8] = column2Row0;
result[9] = column2Row1;
result[10] = column2Row2;
result[11] = 0.0;
result[12] = matrix[12];
result[13] = matrix[13];
result[14] = matrix[14];
result[15] = matrix[15];
return result;
};
/**
* Multiplies a transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
* by an implicit translation matrix defined by a {@link Cartesian3}. This is an optimization
* for <code>Matrix4.multiply(m, Matrix4.fromTranslation(position), m);</code> with less allocations and arithmetic operations.
*
* @param {Matrix4} matrix The matrix on the left-hand side.
* @param {Cartesian3} translation The translation on the right-hand side.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
* @example
* // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromTranslation(position), m);
* Cesium.Matrix4.multiplyByTranslation(m, position, m);
*/
Matrix4.multiplyByTranslation = function(matrix, translation, result) {
if (!defined(matrix)) {
throw new DeveloperError('matrix is required');
}
if (!defined(translation)) {
throw new DeveloperError('translation is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
var x = translation.x;
var y = translation.y;
var z = translation.z;
var tx = (x * matrix[0]) + (y * matrix[4]) + (z * matrix[8]) + matrix[12];
var ty = (x * matrix[1]) + (y * matrix[5]) + (z * matrix[9]) + matrix[13];
var tz = (x * matrix[2]) + (y * matrix[6]) + (z * matrix[10]) + matrix[14];
result[0] = matrix[0];
result[1] = matrix[1];
result[2] = matrix[2];
result[3] = matrix[3];
result[4] = matrix[4];
result[5] = matrix[5];
result[6] = matrix[6];
result[7] = matrix[7];
result[8] = matrix[8];
result[9] = matrix[9];
result[10] = matrix[10];
result[11] = matrix[11];
result[12] = tx;
result[13] = ty;
result[14] = tz;
result[15] = matrix[15];
return result;
};
var uniformScaleScratch = new Cartesian3();
/**
* Multiplies a transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
* by an implicit uniform scale matrix. This is an optimization
* for <code>Matrix4.multiply(m, Matrix4.fromUniformScale(scale), m);</code> with less allocations and arithmetic operations.
*
* @param {Matrix4} matrix The matrix on the left-hand side.
* @param {Number} scale The uniform scale on the right-hand side.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
* @see Matrix4.fromUniformScale
* @see Matrix4.multiplyByScale
*
* @example
* // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromUniformScale(scale), m);
* Cesium.Matrix4.multiplyByUniformScale(m, scale, m);
*/
Matrix4.multiplyByUniformScale = function(matrix, scale, result) {
if (!defined(matrix)) {
throw new DeveloperError('matrix is required');
}
if (typeof scale !== 'number') {
throw new DeveloperError('scale is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
uniformScaleScratch.x = scale;
uniformScaleScratch.y = scale;
uniformScaleScratch.z = scale;
return Matrix4.multiplyByScale(matrix, uniformScaleScratch, result);
};
/**
* Multiplies a transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
* by an implicit non-uniform scale matrix. This is an optimization
* for <code>Matrix4.multiply(m, Matrix4.fromScale(scale), m);</code> with less allocations and arithmetic operations.
*
* @param {Matrix4} matrix The matrix on the left-hand side.
* @param {Cartesian3} scale The non-uniform scale on the right-hand side.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
* @see Matrix4.fromScale
* @see Matrix4.multiplyByUniformScale
*
* @example
* // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromScale(scale), m);
* Cesium.Matrix4.multiplyByScale(m, scale, m);
*/
Matrix4.multiplyByScale = function(matrix, scale, result) {
if (!defined(matrix)) {
throw new DeveloperError('matrix is required');
}
if (!defined(scale)) {
throw new DeveloperError('scale is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
var scaleX = scale.x;
var scaleY = scale.y;
var scaleZ = scale.z;
// Faster than Cartesian3.equals
if ((scaleX === 1.0) && (scaleY === 1.0) && (scaleZ === 1.0)) {
return Matrix4.clone(matrix, result);
}
result[0] = scaleX * matrix[0];
result[1] = scaleX * matrix[1];
result[2] = scaleX * matrix[2];
result[3] = 0.0;
result[4] = scaleY * matrix[4];
result[5] = scaleY * matrix[5];
result[6] = scaleY * matrix[6];
result[7] = 0.0;
result[8] = scaleZ * matrix[8];
result[9] = scaleZ * matrix[9];
result[10] = scaleZ * matrix[10];
result[11] = 0.0;
result[12] = matrix[12];
result[13] = matrix[13];
result[14] = matrix[14];
result[15] = 1.0;
return result;
};
/**
* Computes the product of a matrix and a column vector.
*
* @param {Matrix4} matrix The matrix.
* @param {Cartesian4} cartesian The vector.
* @param {Cartesian4} result The object onto which to store the result.
* @returns {Cartesian4} The modified result parameter.
*/
Matrix4.multiplyByVector = function(matrix, cartesian, result) {
if (!defined(matrix)) {
throw new DeveloperError('matrix is required');
}
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
var vX = cartesian.x;
var vY = cartesian.y;
var vZ = cartesian.z;
var vW = cartesian.w;
var x = matrix[0] * vX + matrix[4] * vY + matrix[8] * vZ + matrix[12] * vW;
var y = matrix[1] * vX + matrix[5] * vY + matrix[9] * vZ + matrix[13] * vW;
var z = matrix[2] * vX + matrix[6] * vY + matrix[10] * vZ + matrix[14] * vW;
var w = matrix[3] * vX + matrix[7] * vY + matrix[11] * vZ + matrix[15] * vW;
result.x = x;
result.y = y;
result.z = z;
result.w = w;
return result;
};
/**
* Computes the product of a matrix and a {@link Cartesian3}. This is equivalent to calling {@link Matrix4.multiplyByVector}
* with a {@link Cartesian4} with a <code>w</code> component of zero.
*
* @param {Matrix4} matrix The matrix.
* @param {Cartesian3} cartesian The point.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*
* @example
* var p = new Cesium.Cartesian3(1.0, 2.0, 3.0);
* var result = Cesium.Matrix4.multiplyByPointAsVector(matrix, p, new Cesium.Cartesian3());
* // A shortcut for
* // Cartesian3 p = ...
* // Cesium.Matrix4.multiplyByVector(matrix, new Cesium.Cartesian4(p.x, p.y, p.z, 0.0), result);
*/
Matrix4.multiplyByPointAsVector = function(matrix, cartesian, result) {
if (!defined(matrix)) {
throw new DeveloperError('matrix is required');
}
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
var vX = cartesian.x;
var vY = cartesian.y;
var vZ = cartesian.z;
var x = matrix[0] * vX + matrix[4] * vY + matrix[8] * vZ;
var y = matrix[1] * vX + matrix[5] * vY + matrix[9] * vZ;
var z = matrix[2] * vX + matrix[6] * vY + matrix[10] * vZ;
result.x = x;
result.y = y;
result.z = z;
return result;
};
/**
* Computes the product of a matrix and a {@link Cartesian3}. This is equivalent to calling {@link Matrix4.multiplyByVector}
* with a {@link Cartesian4} with a <code>w</code> component of 1, but returns a {@link Cartesian3} instead of a {@link Cartesian4}.
*
* @param {Matrix4} matrix The matrix.
* @param {Cartesian3} cartesian The point.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*
* @example
* var p = new Cesium.Cartesian3(1.0, 2.0, 3.0);
* var result = Cesium.Matrix4.multiplyByPoint(matrix, p, new Cesium.Cartesian3());
*/
Matrix4.multiplyByPoint = function(matrix, cartesian, result) {
if (!defined(matrix)) {
throw new DeveloperError('matrix is required');
}
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
var vX = cartesian.x;
var vY = cartesian.y;
var vZ = cartesian.z;
var x = matrix[0] * vX + matrix[4] * vY + matrix[8] * vZ + matrix[12];
var y = matrix[1] * vX + matrix[5] * vY + matrix[9] * vZ + matrix[13];
var z = matrix[2] * vX + matrix[6] * vY + matrix[10] * vZ + matrix[14];
result.x = x;
result.y = y;
result.z = z;
return result;
};
/**
* Computes the product of a matrix and a scalar.
*
* @param {Matrix4} matrix The matrix.
* @param {Number} scalar The number to multiply by.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
* @example
* //create a Matrix4 instance which is a scaled version of the supplied Matrix4
* // m = [10.0, 11.0, 12.0, 13.0]
* // [14.0, 15.0, 16.0, 17.0]
* // [18.0, 19.0, 20.0, 21.0]
* // [22.0, 23.0, 24.0, 25.0]
*
* var a = Cesium.Matrix4.multiplyByScalar(m, -2, new Cesium.Matrix4());
*
* // m remains the same
* // a = [-20.0, -22.0, -24.0, -26.0]
* // [-28.0, -30.0, -32.0, -34.0]
* // [-36.0, -38.0, -40.0, -42.0]
* // [-44.0, -46.0, -48.0, -50.0]
*/
Matrix4.multiplyByScalar = function(matrix, scalar, result) {
if (!defined(matrix)) {
throw new DeveloperError('matrix is required');
}
if (typeof scalar !== 'number') {
throw new DeveloperError('scalar must be a number');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
result[0] = matrix[0] * scalar;
result[1] = matrix[1] * scalar;
result[2] = matrix[2] * scalar;
result[3] = matrix[3] * scalar;
result[4] = matrix[4] * scalar;
result[5] = matrix[5] * scalar;
result[6] = matrix[6] * scalar;
result[7] = matrix[7] * scalar;
result[8] = matrix[8] * scalar;
result[9] = matrix[9] * scalar;
result[10] = matrix[10] * scalar;
result[11] = matrix[11] * scalar;
result[12] = matrix[12] * scalar;
result[13] = matrix[13] * scalar;
result[14] = matrix[14] * scalar;
result[15] = matrix[15] * scalar;
return result;
};
/**
* Computes a negated copy of the provided matrix.
*
* @param {Matrix4} matrix The matrix to negate.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
* @example
* //create a new Matrix4 instance which is a negation of a Matrix4
* // m = [10.0, 11.0, 12.0, 13.0]
* // [14.0, 15.0, 16.0, 17.0]
* // [18.0, 19.0, 20.0, 21.0]
* // [22.0, 23.0, 24.0, 25.0]
*
* var a = Cesium.Matrix4.negate(m, new Cesium.Matrix4());
*
* // m remains the same
* // a = [-10.0, -11.0, -12.0, -13.0]
* // [-14.0, -15.0, -16.0, -17.0]
* // [-18.0, -19.0, -20.0, -21.0]
* // [-22.0, -23.0, -24.0, -25.0]
*/
Matrix4.negate = function(matrix, result) {
if (!defined(matrix)) {
throw new DeveloperError('matrix is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
result[0] = -matrix[0];
result[1] = -matrix[1];
result[2] = -matrix[2];
result[3] = -matrix[3];
result[4] = -matrix[4];
result[5] = -matrix[5];
result[6] = -matrix[6];
result[7] = -matrix[7];
result[8] = -matrix[8];
result[9] = -matrix[9];
result[10] = -matrix[10];
result[11] = -matrix[11];
result[12] = -matrix[12];
result[13] = -matrix[13];
result[14] = -matrix[14];
result[15] = -matrix[15];
return result;
};
/**
* Computes the transpose of the provided matrix.
*
* @param {Matrix4} matrix The matrix to transpose.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
* @example
* //returns transpose of a Matrix4
* // m = [10.0, 11.0, 12.0, 13.0]
* // [14.0, 15.0, 16.0, 17.0]
* // [18.0, 19.0, 20.0, 21.0]
* // [22.0, 23.0, 24.0, 25.0]
*
* var a = Cesium.Matrix4.transpose(m, new Cesium.Matrix4());
*
* // m remains the same
* // a = [10.0, 14.0, 18.0, 22.0]
* // [11.0, 15.0, 19.0, 23.0]
* // [12.0, 16.0, 20.0, 24.0]
* // [13.0, 17.0, 21.0, 25.0]
*/
Matrix4.transpose = function(matrix, result) {
if (!defined(matrix)) {
throw new DeveloperError('matrix is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
var matrix1 = matrix[1];
var matrix2 = matrix[2];
var matrix3 = matrix[3];
var matrix6 = matrix[6];
var matrix7 = matrix[7];
var matrix11 = matrix[11];
result[0] = matrix[0];
result[1] = matrix[4];
result[2] = matrix[8];
result[3] = matrix[12];
result[4] = matrix1;
result[5] = matrix[5];
result[6] = matrix[9];
result[7] = matrix[13];
result[8] = matrix2;
result[9] = matrix6;
result[10] = matrix[10];
result[11] = matrix[14];
result[12] = matrix3;
result[13] = matrix7;
result[14] = matrix11;
result[15] = matrix[15];
return result;
};
/**
* Computes a matrix, which contains the absolute (unsigned) values of the provided matrix's elements.
*
* @param {Matrix4} matrix The matrix with signed elements.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*/
Matrix4.abs = function(matrix, result) {
if (!defined(matrix)) {
throw new DeveloperError('matrix is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
result[0] = Math.abs(matrix[0]);
result[1] = Math.abs(matrix[1]);
result[2] = Math.abs(matrix[2]);
result[3] = Math.abs(matrix[3]);
result[4] = Math.abs(matrix[4]);
result[5] = Math.abs(matrix[5]);
result[6] = Math.abs(matrix[6]);
result[7] = Math.abs(matrix[7]);
result[8] = Math.abs(matrix[8]);
result[9] = Math.abs(matrix[9]);
result[10] = Math.abs(matrix[10]);
result[11] = Math.abs(matrix[11]);
result[12] = Math.abs(matrix[12]);
result[13] = Math.abs(matrix[13]);
result[14] = Math.abs(matrix[14]);
result[15] = Math.abs(matrix[15]);
return result;
};
/**
* Compares the provided matrices componentwise and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Matrix4} [left] The first matrix.
* @param {Matrix4} [right] The second matrix.
* @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*
* @example
* //compares two Matrix4 instances
*
* // a = [10.0, 14.0, 18.0, 22.0]
* // [11.0, 15.0, 19.0, 23.0]
* // [12.0, 16.0, 20.0, 24.0]
* // [13.0, 17.0, 21.0, 25.0]
*
* // b = [10.0, 14.0, 18.0, 22.0]
* // [11.0, 15.0, 19.0, 23.0]
* // [12.0, 16.0, 20.0, 24.0]
* // [13.0, 17.0, 21.0, 25.0]
*
* if(Cesium.Matrix4.equals(a,b)) {
* console.log("Both matrices are equal");
* } else {
* console.log("They are not equal");
* }
*
* //Prints "Both matrices are equal" on the console
*/
Matrix4.equals = function(left, right) {
// Given that most matrices will be transformation matrices, the elements
// are tested in order such that the test is likely to fail as early
// as possible. I _think_ this is just as friendly to the L1 cache
// as testing in index order. It is certainty faster in practice.
return (left === right) ||
(defined(left) &&
defined(right) &&
// Translation
left[12] === right[12] &&
left[13] === right[13] &&
left[14] === right[14] &&
// Rotation/scale
left[0] === right[0] &&
left[1] === right[1] &&
left[2] === right[2] &&
left[4] === right[4] &&
left[5] === right[5] &&
left[6] === right[6] &&
left[8] === right[8] &&
left[9] === right[9] &&
left[10] === right[10] &&
// Bottom row
left[3] === right[3] &&
left[7] === right[7] &&
left[11] === right[11] &&
left[15] === right[15]);
};
/**
* Compares the provided matrices componentwise and returns
* <code>true</code> if they are within the provided epsilon,
* <code>false</code> otherwise.
*
* @param {Matrix4} [left] The first matrix.
* @param {Matrix4} [right] The second matrix.
* @param {Number} epsilon The epsilon to use for equality testing.
* @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
*
* @example
* //compares two Matrix4 instances
*
* // a = [10.5, 14.5, 18.5, 22.5]
* // [11.5, 15.5, 19.5, 23.5]
* // [12.5, 16.5, 20.5, 24.5]
* // [13.5, 17.5, 21.5, 25.5]
*
* // b = [10.0, 14.0, 18.0, 22.0]
* // [11.0, 15.0, 19.0, 23.0]
* // [12.0, 16.0, 20.0, 24.0]
* // [13.0, 17.0, 21.0, 25.0]
*
* if(Cesium.Matrix4.equalsEpsilon(a,b,0.1)){
* console.log("Difference between both the matrices is less than 0.1");
* } else {
* console.log("Difference between both the matrices is not less than 0.1");
* }
*
* //Prints "Difference between both the matrices is not less than 0.1" on the console
*/
Matrix4.equalsEpsilon = function(left, right, epsilon) {
if (typeof epsilon !== 'number') {
throw new DeveloperError('epsilon must be a number');
}
return (left === right) ||
(defined(left) &&
defined(right) &&
Math.abs(left[0] - right[0]) <= epsilon &&
Math.abs(left[1] - right[1]) <= epsilon &&
Math.abs(left[2] - right[2]) <= epsilon &&
Math.abs(left[3] - right[3]) <= epsilon &&
Math.abs(left[4] - right[4]) <= epsilon &&
Math.abs(left[5] - right[5]) <= epsilon &&
Math.abs(left[6] - right[6]) <= epsilon &&
Math.abs(left[7] - right[7]) <= epsilon &&
Math.abs(left[8] - right[8]) <= epsilon &&
Math.abs(left[9] - right[9]) <= epsilon &&
Math.abs(left[10] - right[10]) <= epsilon &&
Math.abs(left[11] - right[11]) <= epsilon &&
Math.abs(left[12] - right[12]) <= epsilon &&
Math.abs(left[13] - right[13]) <= epsilon &&
Math.abs(left[14] - right[14]) <= epsilon &&
Math.abs(left[15] - right[15]) <= epsilon);
};
/**
* Gets the translation portion of the provided matrix, assuming the matrix is a affine transformation matrix.
*
* @param {Matrix4} matrix The matrix to use.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*/
Matrix4.getTranslation = function(matrix, result) {
if (!defined(matrix)) {
throw new DeveloperError('matrix is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
result.x = matrix[12];
result.y = matrix[13];
result.z = matrix[14];
return result;
};
/**
* Gets the upper left 3x3 rotation matrix of the provided matrix, assuming the matrix is a affine transformation matrix.
*
* @param {Matrix4} matrix The matrix to use.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*
* @example
* // returns a Matrix3 instance from a Matrix4 instance
*
* // m = [10.0, 14.0, 18.0, 22.0]
* // [11.0, 15.0, 19.0, 23.0]
* // [12.0, 16.0, 20.0, 24.0]
* // [13.0, 17.0, 21.0, 25.0]
*
* var b = new Cesium.Matrix3();
* Cesium.Matrix4.getRotation(m,b);
*
* // b = [10.0, 14.0, 18.0]
* // [11.0, 15.0, 19.0]
* // [12.0, 16.0, 20.0]
*/
Matrix4.getRotation = function(matrix, result) {
if (!defined(matrix)) {
throw new DeveloperError('matrix is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
result[0] = matrix[0];
result[1] = matrix[1];
result[2] = matrix[2];
result[3] = matrix[4];
result[4] = matrix[5];
result[5] = matrix[6];
result[6] = matrix[8];
result[7] = matrix[9];
result[8] = matrix[10];
return result;
};
var scratchInverseRotation = new Matrix3();
var scratchMatrix3Zero = new Matrix3();
var scratchBottomRow = new Cartesian4();
var scratchExpectedBottomRow = new Cartesian4(0.0, 0.0, 0.0, 1.0);
/**
* Computes the inverse of the provided matrix using Cramers Rule.
* If the determinant is zero, the matrix can not be inverted, and an exception is thrown.
* If the matrix is an affine transformation matrix, it is more efficient
* to invert it with {@link Matrix4.inverseTransformation}.
*
* @param {Matrix4} matrix The matrix to invert.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*
* @exception {RuntimeError} matrix is not invertible because its determinate is zero.
*/
Matrix4.inverse = function(matrix, result) {
if (!defined(matrix)) {
throw new DeveloperError('matrix is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
// Special case for a zero scale matrix that can occur, for example,
// when a model's node has a [0, 0, 0] scale.
if (Matrix3.equalsEpsilon(Matrix4.getRotation(matrix, scratchInverseRotation), scratchMatrix3Zero, CesiumMath.EPSILON7) &&
Cartesian4.equals(Matrix4.getRow(matrix, 3, scratchBottomRow), scratchExpectedBottomRow)) {
result[0] = 0.0;
result[1] = 0.0;
result[2] = 0.0;
result[3] = 0.0;
result[4] = 0.0;
result[5] = 0.0;
result[6] = 0.0;
result[7] = 0.0;
result[8] = 0.0;
result[9] = 0.0;
result[10] = 0.0;
result[11] = 0.0;
result[12] = -matrix[12];
result[13] = -matrix[13];
result[14] = -matrix[14];
result[15] = 1.0;
return result;
}
//
// Ported from:
// ftp://download.intel.com/design/PentiumIII/sml/24504301.pdf
//
var src0 = matrix[0];
var src1 = matrix[4];
var src2 = matrix[8];
var src3 = matrix[12];
var src4 = matrix[1];
var src5 = matrix[5];
var src6 = matrix[9];
var src7 = matrix[13];
var src8 = matrix[2];
var src9 = matrix[6];
var src10 = matrix[10];
var src11 = matrix[14];
var src12 = matrix[3];
var src13 = matrix[7];
var src14 = matrix[11];
var src15 = matrix[15];
// calculate pairs for first 8 elements (cofactors)
var tmp0 = src10 * src15;
var tmp1 = src11 * src14;
var tmp2 = src9 * src15;
var tmp3 = src11 * src13;
var tmp4 = src9 * src14;
var tmp5 = src10 * src13;
var tmp6 = src8 * src15;
var tmp7 = src11 * src12;
var tmp8 = src8 * src14;
var tmp9 = src10 * src12;
var tmp10 = src8 * src13;
var tmp11 = src9 * src12;
// calculate first 8 elements (cofactors)
var dst0 = (tmp0 * src5 + tmp3 * src6 + tmp4 * src7) - (tmp1 * src5 + tmp2 * src6 + tmp5 * src7);
var dst1 = (tmp1 * src4 + tmp6 * src6 + tmp9 * src7) - (tmp0 * src4 + tmp7 * src6 + tmp8 * src7);
var dst2 = (tmp2 * src4 + tmp7 * src5 + tmp10 * src7) - (tmp3 * src4 + tmp6 * src5 + tmp11 * src7);
var dst3 = (tmp5 * src4 + tmp8 * src5 + tmp11 * src6) - (tmp4 * src4 + tmp9 * src5 + tmp10 * src6);
var dst4 = (tmp1 * src1 + tmp2 * src2 + tmp5 * src3) - (tmp0 * src1 + tmp3 * src2 + tmp4 * src3);
var dst5 = (tmp0 * src0 + tmp7 * src2 + tmp8 * src3) - (tmp1 * src0 + tmp6 * src2 + tmp9 * src3);
var dst6 = (tmp3 * src0 + tmp6 * src1 + tmp11 * src3) - (tmp2 * src0 + tmp7 * src1 + tmp10 * src3);
var dst7 = (tmp4 * src0 + tmp9 * src1 + tmp10 * src2) - (tmp5 * src0 + tmp8 * src1 + tmp11 * src2);
// calculate pairs for second 8 elements (cofactors)
tmp0 = src2 * src7;
tmp1 = src3 * src6;
tmp2 = src1 * src7;
tmp3 = src3 * src5;
tmp4 = src1 * src6;
tmp5 = src2 * src5;
tmp6 = src0 * src7;
tmp7 = src3 * src4;
tmp8 = src0 * src6;
tmp9 = src2 * src4;
tmp10 = src0 * src5;
tmp11 = src1 * src4;
// calculate second 8 elements (cofactors)
var dst8 = (tmp0 * src13 + tmp3 * src14 + tmp4 * src15) - (tmp1 * src13 + tmp2 * src14 + tmp5 * src15);
var dst9 = (tmp1 * src12 + tmp6 * src14 + tmp9 * src15) - (tmp0 * src12 + tmp7 * src14 + tmp8 * src15);
var dst10 = (tmp2 * src12 + tmp7 * src13 + tmp10 * src15) - (tmp3 * src12 + tmp6 * src13 + tmp11 * src15);
var dst11 = (tmp5 * src12 + tmp8 * src13 + tmp11 * src14) - (tmp4 * src12 + tmp9 * src13 + tmp10 * src14);
var dst12 = (tmp2 * src10 + tmp5 * src11 + tmp1 * src9) - (tmp4 * src11 + tmp0 * src9 + tmp3 * src10);
var dst13 = (tmp8 * src11 + tmp0 * src8 + tmp7 * src10) - (tmp6 * src10 + tmp9 * src11 + tmp1 * src8);
var dst14 = (tmp6 * src9 + tmp11 * src11 + tmp3 * src8) - (tmp10 * src11 + tmp2 * src8 + tmp7 * src9);
var dst15 = (tmp10 * src10 + tmp4 * src8 + tmp9 * src9) - (tmp8 * src9 + tmp11 * src10 + tmp5 * src8);
// calculate determinant
var det = src0 * dst0 + src1 * dst1 + src2 * dst2 + src3 * dst3;
if (Math.abs(det) < CesiumMath.EPSILON20) {
throw new RuntimeError('matrix is not invertible because its determinate is zero.');
}
// calculate matrix inverse
det = 1.0 / det;
result[0] = dst0 * det;
result[1] = dst1 * det;
result[2] = dst2 * det;
result[3] = dst3 * det;
result[4] = dst4 * det;
result[5] = dst5 * det;
result[6] = dst6 * det;
result[7] = dst7 * det;
result[8] = dst8 * det;
result[9] = dst9 * det;
result[10] = dst10 * det;
result[11] = dst11 * det;
result[12] = dst12 * det;
result[13] = dst13 * det;
result[14] = dst14 * det;
result[15] = dst15 * det;
return result;
};
/**
* Computes the inverse of the provided matrix assuming it is
* an affine transformation matrix, where the upper left 3x3 elements
* are a rotation matrix, and the upper three elements in the fourth
* column are the translation. The bottom row is assumed to be [0, 0, 0, 1].
* The matrix is not verified to be in the proper form.
* This method is faster than computing the inverse for a general 4x4
* matrix using {@link Matrix4.inverse}.
*
* @param {Matrix4} matrix The matrix to invert.
* @param {Matrix4} result The object onto which to store the result.
* @returns {Matrix4} The modified result parameter.
*/
Matrix4.inverseTransformation = function(matrix, result) {
if (!defined(matrix)) {
throw new DeveloperError('matrix is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
//This function is an optimized version of the below 4 lines.
//var rT = Matrix3.transpose(Matrix4.getRotation(matrix));
//var rTN = Matrix3.negate(rT);
//var rTT = Matrix3.multiplyByVector(rTN, Matrix4.getTranslation(matrix));
//return Matrix4.fromRotationTranslation(rT, rTT, result);
var matrix0 = matrix[0];
var matrix1 = matrix[1];
var matrix2 = matrix[2];
var matrix4 = matrix[4];
var matrix5 = matrix[5];
var matrix6 = matrix[6];
var matrix8 = matrix[8];
var matrix9 = matrix[9];
var matrix10 = matrix[10];
var vX = matrix[12];
var vY = matrix[13];
var vZ = matrix[14];
var x = -matrix0 * vX - matrix1 * vY - matrix2 * vZ;
var y = -matrix4 * vX - matrix5 * vY - matrix6 * vZ;
var z = -matrix8 * vX - matrix9 * vY - matrix10 * vZ;
result[0] = matrix0;
result[1] = matrix4;
result[2] = matrix8;
result[3] = 0.0;
result[4] = matrix1;
result[5] = matrix5;
result[6] = matrix9;
result[7] = 0.0;
result[8] = matrix2;
result[9] = matrix6;
result[10] = matrix10;
result[11] = 0.0;
result[12] = x;
result[13] = y;
result[14] = z;
result[15] = 1.0;
return result;
};
/**
* An immutable Matrix4 instance initialized to the identity matrix.
*
* @type {Matrix4}
* @constant
*/
Matrix4.IDENTITY = freezeObject(new Matrix4(1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0));
/**
* The index into Matrix4 for column 0, row 0.
*
* @type {Number}
* @constant
*/
Matrix4.COLUMN0ROW0 = 0;
/**
* The index into Matrix4 for column 0, row 1.
*
* @type {Number}
* @constant
*/
Matrix4.COLUMN0ROW1 = 1;
/**
* The index into Matrix4 for column 0, row 2.
*
* @type {Number}
* @constant
*/
Matrix4.COLUMN0ROW2 = 2;
/**
* The index into Matrix4 for column 0, row 3.
*
* @type {Number}
* @constant
*/
Matrix4.COLUMN0ROW3 = 3;
/**
* The index into Matrix4 for column 1, row 0.
*
* @type {Number}
* @constant
*/
Matrix4.COLUMN1ROW0 = 4;
/**
* The index into Matrix4 for column 1, row 1.
*
* @type {Number}
* @constant
*/
Matrix4.COLUMN1ROW1 = 5;
/**
* The index into Matrix4 for column 1, row 2.
*
* @type {Number}
* @constant
*/
Matrix4.COLUMN1ROW2 = 6;
/**
* The index into Matrix4 for column 1, row 3.
*
* @type {Number}
* @constant
*/
Matrix4.COLUMN1ROW3 = 7;
/**
* The index into Matrix4 for column 2, row 0.
*
* @type {Number}
* @constant
*/
Matrix4.COLUMN2ROW0 = 8;
/**
* The index into Matrix4 for column 2, row 1.
*
* @type {Number}
* @constant
*/
Matrix4.COLUMN2ROW1 = 9;
/**
* The index into Matrix4 for column 2, row 2.
*
* @type {Number}
* @constant
*/
Matrix4.COLUMN2ROW2 = 10;
/**
* The index into Matrix4 for column 2, row 3.
*
* @type {Number}
* @constant
*/
Matrix4.COLUMN2ROW3 = 11;
/**
* The index into Matrix4 for column 3, row 0.
*
* @type {Number}
* @constant
*/
Matrix4.COLUMN3ROW0 = 12;
/**
* The index into Matrix4 for column 3, row 1.
*
* @type {Number}
* @constant
*/
Matrix4.COLUMN3ROW1 = 13;
/**
* The index into Matrix4 for column 3, row 2.
*
* @type {Number}
* @constant
*/
Matrix4.COLUMN3ROW2 = 14;
/**
* The index into Matrix4 for column 3, row 3.
*
* @type {Number}
* @constant
*/
Matrix4.COLUMN3ROW3 = 15;
/**
* Duplicates the provided Matrix4 instance.
*
* @param {Matrix4} [result] The object onto which to store the result.
* @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided.
*/
Matrix4.prototype.clone = function(result) {
return Matrix4.clone(this, result);
};
/**
* Compares this matrix to the provided matrix componentwise and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Matrix4} [right] The right hand side matrix.
* @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
*/
Matrix4.prototype.equals = function(right) {
return Matrix4.equals(this, right);
};
/**
* @private
*/
Matrix4.equalsArray = function(matrix, array, offset) {
return matrix[0] === array[offset] &&
matrix[1] === array[offset + 1] &&
matrix[2] === array[offset + 2] &&
matrix[3] === array[offset + 3] &&
matrix[4] === array[offset + 4] &&
matrix[5] === array[offset + 5] &&
matrix[6] === array[offset + 6] &&
matrix[7] === array[offset + 7] &&
matrix[8] === array[offset + 8] &&
matrix[9] === array[offset + 9] &&
matrix[10] === array[offset + 10] &&
matrix[11] === array[offset + 11] &&
matrix[12] === array[offset + 12] &&
matrix[13] === array[offset + 13] &&
matrix[14] === array[offset + 14] &&
matrix[15] === array[offset + 15];
};
/**
* Compares this matrix to the provided matrix componentwise and returns
* <code>true</code> if they are within the provided epsilon,
* <code>false</code> otherwise.
*
* @param {Matrix4} [right] The right hand side matrix.
* @param {Number} epsilon The epsilon to use for equality testing.
* @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
*/
Matrix4.prototype.equalsEpsilon = function(right, epsilon) {
return Matrix4.equalsEpsilon(this, right, epsilon);
};
/**
* Computes a string representing this Matrix with each row being
* on a separate line and in the format '(column0, column1, column2, column3)'.
*
* @returns {String} A string representing the provided Matrix with each row being on a separate line and in the format '(column0, column1, column2, column3)'.
*/
Matrix4.prototype.toString = function() {
return '(' + this[0] + ', ' + this[4] + ', ' + this[8] + ', ' + this[12] +')\n' +
'(' + this[1] + ', ' + this[5] + ', ' + this[9] + ', ' + this[13] +')\n' +
'(' + this[2] + ', ' + this[6] + ', ' + this[10] + ', ' + this[14] +')\n' +
'(' + this[3] + ', ' + this[7] + ', ' + this[11] + ', ' + this[15] +')';
};
return Matrix4;
});
/*global define*/
define('Core/Rectangle',[
'./Cartographic',
'./defaultValue',
'./defined',
'./defineProperties',
'./DeveloperError',
'./Ellipsoid',
'./freezeObject',
'./Math'
], function(
Cartographic,
defaultValue,
defined,
defineProperties,
DeveloperError,
Ellipsoid,
freezeObject,
CesiumMath) {
"use strict";
/**
* A two dimensional region specified as longitude and latitude coordinates.
*
* @alias Rectangle
* @constructor
*
* @param {Number} [west=0.0] The westernmost longitude, in radians, in the range [-Pi, Pi].
* @param {Number} [south=0.0] The southernmost latitude, in radians, in the range [-Pi/2, Pi/2].
* @param {Number} [east=0.0] The easternmost longitude, in radians, in the range [-Pi, Pi].
* @param {Number} [north=0.0] The northernmost latitude, in radians, in the range [-Pi/2, Pi/2].
*
* @see Packable
*/
var Rectangle = function(west, south, east, north) {
/**
* The westernmost longitude in radians in the range [-Pi, Pi].
*
* @type {Number}
* @default 0.0
*/
this.west = defaultValue(west, 0.0);
/**
* The southernmost latitude in radians in the range [-Pi/2, Pi/2].
*
* @type {Number}
* @default 0.0
*/
this.south = defaultValue(south, 0.0);
/**
* The easternmost longitude in radians in the range [-Pi, Pi].
*
* @type {Number}
* @default 0.0
*/
this.east = defaultValue(east, 0.0);
/**
* The northernmost latitude in radians in the range [-Pi/2, Pi/2].
*
* @type {Number}
* @default 0.0
*/
this.north = defaultValue(north, 0.0);
};
defineProperties(Rectangle.prototype, {
/**
* Gets the width of the rectangle in radians.
* @memberof Rectangle.prototype
* @type {Number}
*/
width : {
get : function() {
return Rectangle.computeWidth(this);
}
},
/**
* Gets the height of the rectangle in radians.
* @memberof Rectangle.prototype
* @type {Number}
*/
height : {
get : function() {
return Rectangle.computeHeight(this);
}
}
});
/**
* The number of elements used to pack the object into an array.
* @type {Number}
*/
Rectangle.packedLength = 4;
/**
* Stores the provided instance into the provided array.
*
* @param {BoundingSphere} value The value to pack.
* @param {Number[]} array The array to pack into.
* @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
*/
Rectangle.pack = function(value, array, startingIndex) {
if (!defined(value)) {
throw new DeveloperError('value is required');
}
if (!defined(array)) {
throw new DeveloperError('array is required');
}
startingIndex = defaultValue(startingIndex, 0);
array[startingIndex++] = value.west;
array[startingIndex++] = value.south;
array[startingIndex++] = value.east;
array[startingIndex] = value.north;
};
/**
* Retrieves an instance from a packed array.
*
* @param {Number[]} array The packed array.
* @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
* @param {Rectangle} [result] The object into which to store the result.
*/
Rectangle.unpack = function(array, startingIndex, result) {
if (!defined(array)) {
throw new DeveloperError('array is required');
}
startingIndex = defaultValue(startingIndex, 0);
if (!defined(result)) {
result = new Rectangle();
}
result.west = array[startingIndex++];
result.south = array[startingIndex++];
result.east = array[startingIndex++];
result.north = array[startingIndex];
return result;
};
/**
* Computes the width of a rectangle in radians.
* @param {Rectangle} rectangle The rectangle to compute the width of.
* @returns {Number} The width.
*/
Rectangle.computeWidth = function(rectangle) {
if (!defined(rectangle)) {
throw new DeveloperError('rectangle is required.');
}
var east = rectangle.east;
var west = rectangle.west;
if (east < west) {
east += CesiumMath.TWO_PI;
}
return east - west;
};
/**
* Computes the height of a rectangle in radians.
* @param {Rectangle} rectangle The rectangle to compute the height of.
* @returns {Number} The height.
*/
Rectangle.computeHeight = function(rectangle) {
if (!defined(rectangle)) {
throw new DeveloperError('rectangle is required.');
}
return rectangle.north - rectangle.south;
};
/**
* Creates an rectangle given the boundary longitude and latitude in degrees.
*
* @param {Number} [west=0.0] The westernmost longitude in degrees in the range [-180.0, 180.0].
* @param {Number} [south=0.0] The southernmost latitude in degrees in the range [-90.0, 90.0].
* @param {Number} [east=0.0] The easternmost longitude in degrees in the range [-180.0, 180.0].
* @param {Number} [north=0.0] The northernmost latitude in degrees in the range [-90.0, 90.0].
* @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
* @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
*
* @example
* var rectangle = Cesium.Rectangle.fromDegrees(0.0, 20.0, 10.0, 30.0);
*/
Rectangle.fromDegrees = function(west, south, east, north, result) {
west = CesiumMath.toRadians(defaultValue(west, 0.0));
south = CesiumMath.toRadians(defaultValue(south, 0.0));
east = CesiumMath.toRadians(defaultValue(east, 0.0));
north = CesiumMath.toRadians(defaultValue(north, 0.0));
if (!defined(result)) {
return new Rectangle(west, south, east, north);
}
result.west = west;
result.south = south;
result.east = east;
result.north = north;
return result;
};
/**
* Creates the smallest possible Rectangle that encloses all positions in the provided array.
*
* @param {Cartographic[]} cartographics The list of Cartographic instances.
* @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
* @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
*/
Rectangle.fromCartographicArray = function(cartographics, result) {
if (!defined(cartographics)) {
throw new DeveloperError('cartographics is required.');
}
var minLon = Number.MAX_VALUE;
var maxLon = -Number.MAX_VALUE;
var minLat = Number.MAX_VALUE;
var maxLat = -Number.MAX_VALUE;
for ( var i = 0, len = cartographics.length; i < len; i++) {
var position = cartographics[i];
minLon = Math.min(minLon, position.longitude);
maxLon = Math.max(maxLon, position.longitude);
minLat = Math.min(minLat, position.latitude);
maxLat = Math.max(maxLat, position.latitude);
}
if (!defined(result)) {
return new Rectangle(minLon, minLat, maxLon, maxLat);
}
result.west = minLon;
result.south = minLat;
result.east = maxLon;
result.north = maxLat;
return result;
};
/**
* The number of elements used to pack the object into an array.
* @type {Number}
*/
Rectangle.packedLength = 4;
/**
* Stores the provided instance into the provided array.
*
* @param {Rectangle} value The value to pack.
* @param {Number[]} array The array to pack into.
* @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
*/
Rectangle.pack = function(value, array, startingIndex) {
if (!defined(value)) {
throw new DeveloperError('value is required');
}
if (!defined(array)) {
throw new DeveloperError('array is required');
}
startingIndex = defaultValue(startingIndex, 0);
array[startingIndex++] = value.west;
array[startingIndex++] = value.south;
array[startingIndex++] = value.east;
array[startingIndex] = value.north;
};
/**
* Retrieves an instance from a packed array.
*
* @param {Number[]} array The packed array.
* @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
* @param {Rectangle} [result] The object into which to store the result.
*/
Rectangle.unpack = function(array, startingIndex, result) {
if (!defined(array)) {
throw new DeveloperError('array is required');
}
startingIndex = defaultValue(startingIndex, 0);
if (!defined(result)) {
result = new Rectangle();
}
result.west = array[startingIndex++];
result.south = array[startingIndex++];
result.east = array[startingIndex++];
result.north = array[startingIndex];
return result;
};
/**
* Duplicates an Rectangle.
*
* @param {Rectangle} rectangle The rectangle to clone.
* @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
* @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided. (Returns undefined if rectangle is undefined)
*/
Rectangle.clone = function(rectangle, result) {
if (!defined(rectangle)) {
return undefined;
}
if (!defined(result)) {
return new Rectangle(rectangle.west, rectangle.south, rectangle.east, rectangle.north);
}
result.west = rectangle.west;
result.south = rectangle.south;
result.east = rectangle.east;
result.north = rectangle.north;
return result;
};
/**
* Duplicates this Rectangle.
*
* @param {Rectangle} [result] The object onto which to store the result.
* @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
*/
Rectangle.prototype.clone = function(result) {
return Rectangle.clone(this, result);
};
/**
* Compares the provided Rectangle with this Rectangle componentwise and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Rectangle} [other] The Rectangle to compare.
* @returns {Boolean} <code>true</code> if the Rectangles are equal, <code>false</code> otherwise.
*/
Rectangle.prototype.equals = function(other) {
return Rectangle.equals(this, other);
};
/**
* Compares the provided rectangles and returns <code>true</code> if they are equal,
* <code>false</code> otherwise.
*
* @param {Rectangle} [left] The first Rectangle.
* @param {Rectangle} [right] The second Rectangle.
* @returns {Boolean} <code>true</code> if left and right are equal; otherwise <code>false</code>.
*/
Rectangle.equals = function(left, right) {
return (left === right) ||
((defined(left)) &&
(defined(right)) &&
(left.west === right.west) &&
(left.south === right.south) &&
(left.east === right.east) &&
(left.north === right.north));
};
/**
* Compares the provided Rectangle with this Rectangle componentwise and returns
* <code>true</code> if they are within the provided epsilon,
* <code>false</code> otherwise.
*
* @param {Rectangle} [other] The Rectangle to compare.
* @param {Number} epsilon The epsilon to use for equality testing.
* @returns {Boolean} <code>true</code> if the Rectangles are within the provided epsilon, <code>false</code> otherwise.
*/
Rectangle.prototype.equalsEpsilon = function(other, epsilon) {
if (typeof epsilon !== 'number') {
throw new DeveloperError('epsilon is required and must be a number.');
}
return defined(other) &&
(Math.abs(this.west - other.west) <= epsilon) &&
(Math.abs(this.south - other.south) <= epsilon) &&
(Math.abs(this.east - other.east) <= epsilon) &&
(Math.abs(this.north - other.north) <= epsilon);
};
/**
* Checks an Rectangle's properties and throws if they are not in valid ranges.
*
* @param {Rectangle} rectangle The rectangle to validate
*
* @exception {DeveloperError} <code>north</code> must be in the interval [<code>-Pi/2</code>, <code>Pi/2</code>].
* @exception {DeveloperError} <code>south</code> must be in the interval [<code>-Pi/2</code>, <code>Pi/2</code>].
* @exception {DeveloperError} <code>east</code> must be in the interval [<code>-Pi</code>, <code>Pi</code>].
* @exception {DeveloperError} <code>west</code> must be in the interval [<code>-Pi</code>, <code>Pi</code>].
*/
Rectangle.validate = function(rectangle) {
if (!defined(rectangle)) {
throw new DeveloperError('rectangle is required');
}
var north = rectangle.north;
if (typeof north !== 'number') {
throw new DeveloperError('north is required to be a number.');
}
if (north < -CesiumMath.PI_OVER_TWO || north > CesiumMath.PI_OVER_TWO) {
throw new DeveloperError('north must be in the interval [-Pi/2, Pi/2].');
}
var south = rectangle.south;
if (typeof south !== 'number') {
throw new DeveloperError('south is required to be a number.');
}
if (south < -CesiumMath.PI_OVER_TWO || south > CesiumMath.PI_OVER_TWO) {
throw new DeveloperError('south must be in the interval [-Pi/2, Pi/2].');
}
var west = rectangle.west;
if (typeof west !== 'number') {
throw new DeveloperError('west is required to be a number.');
}
if (west < -Math.PI || west > Math.PI) {
throw new DeveloperError('west must be in the interval [-Pi, Pi].');
}
var east = rectangle.east;
if (typeof east !== 'number') {
throw new DeveloperError('east is required to be a number.');
}
if (east < -Math.PI || east > Math.PI) {
throw new DeveloperError('east must be in the interval [-Pi, Pi].');
}
};
/**
* Computes the southwest corner of an rectangle.
*
* @param {Rectangle} rectangle The rectangle for which to find the corner
* @param {Cartographic} [result] The object onto which to store the result.
* @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
*/
Rectangle.southwest = function(rectangle, result) {
if (!defined(rectangle)) {
throw new DeveloperError('rectangle is required');
}
if (!defined(result)) {
return new Cartographic(rectangle.west, rectangle.south);
}
result.longitude = rectangle.west;
result.latitude = rectangle.south;
result.height = 0.0;
return result;
};
/**
* Computes the northwest corner of an rectangle.
*
* @param {Rectangle} rectangle The rectangle for which to find the corner
* @param {Cartographic} [result] The object onto which to store the result.
* @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
*/
Rectangle.northwest = function(rectangle, result) {
if (!defined(rectangle)) {
throw new DeveloperError('rectangle is required');
}
if (!defined(result)) {
return new Cartographic(rectangle.west, rectangle.north);
}
result.longitude = rectangle.west;
result.latitude = rectangle.north;
result.height = 0.0;
return result;
};
/**
* Computes the northeast corner of an rectangle.
*
* @param {Rectangle} rectangle The rectangle for which to find the corner
* @param {Cartographic} [result] The object onto which to store the result.
* @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
*/
Rectangle.northeast = function(rectangle, result) {
if (!defined(rectangle)) {
throw new DeveloperError('rectangle is required');
}
if (!defined(result)) {
return new Cartographic(rectangle.east, rectangle.north);
}
result.longitude = rectangle.east;
result.latitude = rectangle.north;
result.height = 0.0;
return result;
};
/**
* Computes the southeast corner of an rectangle.
*
* @param {Rectangle} rectangle The rectangle for which to find the corner
* @param {Cartographic} [result] The object onto which to store the result.
* @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
*/
Rectangle.southeast = function(rectangle, result) {
if (!defined(rectangle)) {
throw new DeveloperError('rectangle is required');
}
if (!defined(result)) {
return new Cartographic(rectangle.east, rectangle.south);
}
result.longitude = rectangle.east;
result.latitude = rectangle.south;
result.height = 0.0;
return result;
};
/**
* Computes the center of an rectangle.
*
* @param {Rectangle} rectangle The rectangle for which to find the center
* @param {Cartographic} [result] The object onto which to store the result.
* @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
*/
Rectangle.center = function(rectangle, result) {
if (!defined(rectangle)) {
throw new DeveloperError('rectangle is required');
}
var east = rectangle.east;
var west = rectangle.west;
if (east < west) {
east += CesiumMath.TWO_PI;
}
var longitude = CesiumMath.negativePiToPi((west + east) * 0.5);
var latitude = (rectangle.south + rectangle.north) * 0.5;
if (!defined(result)) {
return new Cartographic(longitude, latitude);
}
result.longitude = longitude;
result.latitude = latitude;
result.height = 0.0;
return result;
};
/**
* Computes the intersection of two rectangles
*
* @param {Rectangle} rectangle On rectangle to find an intersection
* @param {Rectangle} otherRectangle Another rectangle to find an intersection
* @param {Rectangle} [result] The object onto which to store the result.
* @returns {Rectangle|undefined} The modified result parameter, a new Rectangle instance if none was provided or undefined if there is no intersection.
*/
Rectangle.intersection = function(rectangle, otherRectangle, result) {
if (!defined(rectangle)) {
throw new DeveloperError('rectangle is required');
}
if (!defined(otherRectangle)) {
throw new DeveloperError('otherRectangle is required.');
}
var rectangleEast = rectangle.east;
var rectangleWest = rectangle.west;
var otherRectangleEast = otherRectangle.east;
var otherRectangleWest = otherRectangle.west;
if (rectangleEast < rectangleWest && otherRectangleEast > 0.0) {
rectangleEast += CesiumMath.TWO_PI;
} else if (otherRectangleEast < otherRectangleWest && rectangleEast > 0.0) {
otherRectangleEast += CesiumMath.TWO_PI;
}
if (rectangleEast < rectangleWest && otherRectangleWest < 0.0) {
otherRectangleWest += CesiumMath.TWO_PI;
} else if (otherRectangleEast < otherRectangleWest && rectangleWest < 0.0) {
rectangleWest += CesiumMath.TWO_PI;
}
var west = CesiumMath.negativePiToPi(Math.max(rectangleWest, otherRectangleWest));
var east = CesiumMath.negativePiToPi(Math.min(rectangleEast, otherRectangleEast));
if ((rectangle.west < rectangle.east || otherRectangle.west < otherRectangle.east) && east <= west) {
return undefined;
}
var south = Math.max(rectangle.south, otherRectangle.south);
var north = Math.min(rectangle.north, otherRectangle.north);
if (south >= north) {
return undefined;
}
if (!defined(result)) {
return new Rectangle(west, south, east, north);
}
result.west = west;
result.south = south;
result.east = east;
result.north = north;
return result;
};
/**
* Returns true if the cartographic is on or inside the rectangle, false otherwise.
*
* @param {Rectangle} rectangle The rectangle
* @param {Cartographic} cartographic The cartographic to test.
* @returns {Boolean} true if the provided cartographic is inside the rectangle, false otherwise.
*/
Rectangle.contains = function(rectangle, cartographic) {
if (!defined(rectangle)) {
throw new DeveloperError('rectangle is required');
}
if (!defined(cartographic)) {
throw new DeveloperError('cartographic is required.');
}
var longitude = cartographic.longitude;
var latitude = cartographic.latitude;
var west = rectangle.west;
var east = rectangle.east;
if (east < west) {
east += CesiumMath.TWO_PI;
if (longitude < 0.0) {
longitude += CesiumMath.TWO_PI;
}
}
return (longitude > west || CesiumMath.equalsEpsilon(longitude, west, CesiumMath.EPSILON14)) &&
(longitude < east || CesiumMath.equalsEpsilon(longitude, east, CesiumMath.EPSILON14)) &&
latitude >= rectangle.south &&
latitude <= rectangle.north;
};
var subsampleLlaScratch = new Cartographic();
/**
* Samples an rectangle so that it includes a list of Cartesian points suitable for passing to
* {@link BoundingSphere#fromPoints}. Sampling is necessary to account
* for rectangles that cover the poles or cross the equator.
*
* @param {Rectangle} rectangle The rectangle to subsample.
* @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid to use.
* @param {Number} [surfaceHeight=0.0] The height of the rectangle above the ellipsoid.
* @param {Cartesian3[]} [result] The array of Cartesians onto which to store the result.
* @returns {Cartesian3[]} The modified result parameter or a new Array of Cartesians instances if none was provided.
*/
Rectangle.subsample = function(rectangle, ellipsoid, surfaceHeight, result) {
if (!defined(rectangle)) {
throw new DeveloperError('rectangle is required');
}
ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
surfaceHeight = defaultValue(surfaceHeight, 0.0);
if (!defined(result)) {
result = [];
}
var length = 0;
var north = rectangle.north;
var south = rectangle.south;
var east = rectangle.east;
var west = rectangle.west;
var lla = subsampleLlaScratch;
lla.height = surfaceHeight;
lla.longitude = west;
lla.latitude = north;
result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
length++;
lla.longitude = east;
result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
length++;
lla.latitude = south;
result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
length++;
lla.longitude = west;
result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
length++;
if (north < 0.0) {
lla.latitude = north;
} else if (south > 0.0) {
lla.latitude = south;
} else {
lla.latitude = 0.0;
}
for ( var i = 1; i < 8; ++i) {
lla.longitude = -Math.PI + i * CesiumMath.PI_OVER_TWO;
if (Rectangle.contains(rectangle, lla)) {
result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
length++;
}
}
if (lla.latitude === 0.0) {
lla.longitude = west;
result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
length++;
lla.longitude = east;
result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
length++;
}
result.length = length;
return result;
};
/**
* The largest possible rectangle.
*
* @type {Rectangle}
* @constant
*/
Rectangle.MAX_VALUE = freezeObject(new Rectangle(-Math.PI, -CesiumMath.PI_OVER_TWO, Math.PI, CesiumMath.PI_OVER_TWO));
return Rectangle;
});
/*global define*/
define('Core/BoundingSphere',[
'./Cartesian3',
'./Cartographic',
'./defaultValue',
'./defined',
'./DeveloperError',
'./Ellipsoid',
'./GeographicProjection',
'./Intersect',
'./Interval',
'./Matrix4',
'./Rectangle'
], function(
Cartesian3,
Cartographic,
defaultValue,
defined,
DeveloperError,
Ellipsoid,
GeographicProjection,
Intersect,
Interval,
Matrix4,
Rectangle) {
"use strict";
/**
* A bounding sphere with a center and a radius.
* @alias BoundingSphere
* @constructor
*
* @param {Cartesian3} [center=Cartesian3.ZERO] The center of the bounding sphere.
* @param {Number} [radius=0.0] The radius of the bounding sphere.
*
* @see AxisAlignedBoundingBox
* @see BoundingRectangle
* @see Packable
*/
var BoundingSphere = function(center, radius) {
/**
* The center point of the sphere.
* @type {Cartesian3}
* @default {@link Cartesian3.ZERO}
*/
this.center = Cartesian3.clone(defaultValue(center, Cartesian3.ZERO));
/**
* The radius of the sphere.
* @type {Number}
* @default 0.0
*/
this.radius = defaultValue(radius, 0.0);
};
var fromPointsXMin = new Cartesian3();
var fromPointsYMin = new Cartesian3();
var fromPointsZMin = new Cartesian3();
var fromPointsXMax = new Cartesian3();
var fromPointsYMax = new Cartesian3();
var fromPointsZMax = new Cartesian3();
var fromPointsCurrentPos = new Cartesian3();
var fromPointsScratch = new Cartesian3();
var fromPointsRitterCenter = new Cartesian3();
var fromPointsMinBoxPt = new Cartesian3();
var fromPointsMaxBoxPt = new Cartesian3();
var fromPointsNaiveCenterScratch = new Cartesian3();
/**
* Computes a tight-fitting bounding sphere enclosing a list of 3D Cartesian points.
* The bounding sphere is computed by running two algorithms, a naive algorithm and
* Ritter's algorithm. The smaller of the two spheres is used to ensure a tight fit.
*
* @param {Cartesian3[]} positions An array of points that the bounding sphere will enclose. Each point must have <code>x</code>, <code>y</code>, and <code>z</code> properties.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
*
* @see {@link http://blogs.agi.com/insight3d/index.php/2008/02/04/a-bounding/|Bounding Sphere computation article}
*/
BoundingSphere.fromPoints = function(positions, result) {
if (!defined(result)) {
result = new BoundingSphere();
}
if (!defined(positions) || positions.length === 0) {
result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
result.radius = 0.0;
return result;
}
var currentPos = Cartesian3.clone(positions[0], fromPointsCurrentPos);
var xMin = Cartesian3.clone(currentPos, fromPointsXMin);
var yMin = Cartesian3.clone(currentPos, fromPointsYMin);
var zMin = Cartesian3.clone(currentPos, fromPointsZMin);
var xMax = Cartesian3.clone(currentPos, fromPointsXMax);
var yMax = Cartesian3.clone(currentPos, fromPointsYMax);
var zMax = Cartesian3.clone(currentPos, fromPointsZMax);
var numPositions = positions.length;
for (var i = 1; i < numPositions; i++) {
Cartesian3.clone(positions[i], currentPos);
var x = currentPos.x;
var y = currentPos.y;
var z = currentPos.z;
// Store points containing the the smallest and largest components
if (x < xMin.x) {
Cartesian3.clone(currentPos, xMin);
}
if (x > xMax.x) {
Cartesian3.clone(currentPos, xMax);
}
if (y < yMin.y) {
Cartesian3.clone(currentPos, yMin);
}
if (y > yMax.y) {
Cartesian3.clone(currentPos, yMax);
}
if (z < zMin.z) {
Cartesian3.clone(currentPos, zMin);
}
if (z > zMax.z) {
Cartesian3.clone(currentPos, zMax);
}
}
// Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
var xSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(xMax, xMin, fromPointsScratch));
var ySpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(yMax, yMin, fromPointsScratch));
var zSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(zMax, zMin, fromPointsScratch));
// Set the diameter endpoints to the largest span.
var diameter1 = xMin;
var diameter2 = xMax;
var maxSpan = xSpan;
if (ySpan > maxSpan) {
maxSpan = ySpan;
diameter1 = yMin;
diameter2 = yMax;
}
if (zSpan > maxSpan) {
maxSpan = zSpan;
diameter1 = zMin;
diameter2 = zMax;
}
// Calculate the center of the initial sphere found by Ritter's algorithm
var ritterCenter = fromPointsRitterCenter;
ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
// Calculate the radius of the initial sphere found by Ritter's algorithm
var radiusSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch));
var ritterRadius = Math.sqrt(radiusSquared);
// Find the center of the sphere found using the Naive method.
var minBoxPt = fromPointsMinBoxPt;
minBoxPt.x = xMin.x;
minBoxPt.y = yMin.y;
minBoxPt.z = zMin.z;
var maxBoxPt = fromPointsMaxBoxPt;
maxBoxPt.x = xMax.x;
maxBoxPt.y = yMax.y;
maxBoxPt.z = zMax.z;
var naiveCenter = Cartesian3.multiplyByScalar(Cartesian3.add(minBoxPt, maxBoxPt, fromPointsScratch), 0.5, fromPointsNaiveCenterScratch);
// Begin 2nd pass to find naive radius and modify the ritter sphere.
var naiveRadius = 0;
for (i = 0; i < numPositions; i++) {
Cartesian3.clone(positions[i], currentPos);
// Find the furthest point from the naive center to calculate the naive radius.
var r = Cartesian3.magnitude(Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch));
if (r > naiveRadius) {
naiveRadius = r;
}
// Make adjustments to the Ritter Sphere to include all points.
var oldCenterToPointSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch));
if (oldCenterToPointSquared > radiusSquared) {
var oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
// Calculate new radius to include the point that lies outside
ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
radiusSquared = ritterRadius * ritterRadius;
// Calculate center of new Ritter sphere
var oldToNew = oldCenterToPoint - ritterRadius;
ritterCenter.x = (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) / oldCenterToPoint;
ritterCenter.y = (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) / oldCenterToPoint;
ritterCenter.z = (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) / oldCenterToPoint;
}
}
if (ritterRadius < naiveRadius) {
Cartesian3.clone(ritterCenter, result.center);
result.radius = ritterRadius;
} else {
Cartesian3.clone(naiveCenter, result.center);
result.radius = naiveRadius;
}
return result;
};
var defaultProjection = new GeographicProjection();
var fromRectangle2DLowerLeft = new Cartesian3();
var fromRectangle2DUpperRight = new Cartesian3();
var fromRectangle2DSouthwest = new Cartographic();
var fromRectangle2DNortheast = new Cartographic();
/**
* Computes a bounding sphere from an rectangle projected in 2D.
*
* @param {Rectangle} rectangle The rectangle around which to create a bounding sphere.
* @param {Object} [projection=GeographicProjection] The projection used to project the rectangle into 2D.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*/
BoundingSphere.fromRectangle2D = function(rectangle, projection, result) {
return BoundingSphere.fromRectangleWithHeights2D(rectangle, projection, 0.0, 0.0, result);
};
/**
* Computes a bounding sphere from an rectangle projected in 2D. The bounding sphere accounts for the
* object's minimum and maximum heights over the rectangle.
*
* @param {Rectangle} rectangle The rectangle around which to create a bounding sphere.
* @param {Object} [projection=GeographicProjection] The projection used to project the rectangle into 2D.
* @param {Number} [minimumHeight=0.0] The minimum height over the rectangle.
* @param {Number} [maximumHeight=0.0] The maximum height over the rectangle.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*/
BoundingSphere.fromRectangleWithHeights2D = function(rectangle, projection, minimumHeight, maximumHeight, result) {
if (!defined(result)) {
result = new BoundingSphere();
}
if (!defined(rectangle)) {
result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
result.radius = 0.0;
return result;
}
projection = defaultValue(projection, defaultProjection);
Rectangle.southwest(rectangle, fromRectangle2DSouthwest);
fromRectangle2DSouthwest.height = minimumHeight;
Rectangle.northeast(rectangle, fromRectangle2DNortheast);
fromRectangle2DNortheast.height = maximumHeight;
var lowerLeft = projection.project(fromRectangle2DSouthwest, fromRectangle2DLowerLeft);
var upperRight = projection.project(fromRectangle2DNortheast, fromRectangle2DUpperRight);
var width = upperRight.x - lowerLeft.x;
var height = upperRight.y - lowerLeft.y;
var elevation = upperRight.z - lowerLeft.z;
result.radius = Math.sqrt(width * width + height * height + elevation * elevation) * 0.5;
var center = result.center;
center.x = lowerLeft.x + width * 0.5;
center.y = lowerLeft.y + height * 0.5;
center.z = lowerLeft.z + elevation * 0.5;
return result;
};
var fromRectangle3DScratch = [];
/**
* Computes a bounding sphere from an rectangle in 3D. The bounding sphere is created using a subsample of points
* on the ellipsoid and contained in the rectangle. It may not be accurate for all rectangles on all types of ellipsoids.
*
* @param {Rectangle} rectangle The valid rectangle used to create a bounding sphere.
* @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid used to determine positions of the rectangle.
* @param {Number} [surfaceHeight=0.0] The height above the surface of the ellipsoid.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*/
BoundingSphere.fromRectangle3D = function(rectangle, ellipsoid, surfaceHeight, result) {
ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
surfaceHeight = defaultValue(surfaceHeight, 0.0);
var positions;
if (defined(rectangle)) {
positions = Rectangle.subsample(rectangle, ellipsoid, surfaceHeight, fromRectangle3DScratch);
}
return BoundingSphere.fromPoints(positions, result);
};
/**
* Computes a tight-fitting bounding sphere enclosing a list of 3D points, where the points are
* stored in a flat array in X, Y, Z, order. The bounding sphere is computed by running two
* algorithms, a naive algorithm and Ritter's algorithm. The smaller of the two spheres is used to
* ensure a tight fit.
*
* @param {Cartesian3[]} positions An array of points that the bounding sphere will enclose. Each point
* is formed from three elements in the array in the order X, Y, Z.
* @param {Cartesian3} [center=Cartesian3.ZERO] The position to which the positions are relative, which need not be the
* origin of the coordinate system. This is useful when the positions are to be used for
* relative-to-center (RTC) rendering.
* @param {Number} [stride=3] The number of array elements per vertex. It must be at least 3, but it may
* be higher. Regardless of the value of this parameter, the X coordinate of the first position
* is at array index 0, the Y coordinate is at array index 1, and the Z coordinate is at array index
* 2. When stride is 3, the X coordinate of the next position then begins at array index 3. If
* the stride is 5, however, two array elements are skipped and the next position begins at array
* index 5.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
*
* @see {@link http://blogs.agi.com/insight3d/index.php/2008/02/04/a-bounding/|Bounding Sphere computation article}
*
* @example
* // Compute the bounding sphere from 3 positions, each specified relative to a center.
* // In addition to the X, Y, and Z coordinates, the points array contains two additional
* // elements per point which are ignored for the purpose of computing the bounding sphere.
* var center = new Cesium.Cartesian3(1.0, 2.0, 3.0);
* var points = [1.0, 2.0, 3.0, 0.1, 0.2,
* 4.0, 5.0, 6.0, 0.1, 0.2,
* 7.0, 8.0, 9.0, 0.1, 0.2];
* var sphere = Cesium.BoundingSphere.fromVertices(points, center, 5);
*/
BoundingSphere.fromVertices = function(positions, center, stride, result) {
if (!defined(result)) {
result = new BoundingSphere();
}
if (!defined(positions) || positions.length === 0) {
result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
result.radius = 0.0;
return result;
}
center = defaultValue(center, Cartesian3.ZERO);
stride = defaultValue(stride, 3);
if (stride < 3) {
throw new DeveloperError('stride must be 3 or greater.');
}
var currentPos = fromPointsCurrentPos;
currentPos.x = positions[0] + center.x;
currentPos.y = positions[1] + center.y;
currentPos.z = positions[2] + center.z;
var xMin = Cartesian3.clone(currentPos, fromPointsXMin);
var yMin = Cartesian3.clone(currentPos, fromPointsYMin);
var zMin = Cartesian3.clone(currentPos, fromPointsZMin);
var xMax = Cartesian3.clone(currentPos, fromPointsXMax);
var yMax = Cartesian3.clone(currentPos, fromPointsYMax);
var zMax = Cartesian3.clone(currentPos, fromPointsZMax);
var numElements = positions.length;
for (var i = 0; i < numElements; i += stride) {
var x = positions[i] + center.x;
var y = positions[i + 1] + center.y;
var z = positions[i + 2] + center.z;
currentPos.x = x;
currentPos.y = y;
currentPos.z = z;
// Store points containing the the smallest and largest components
if (x < xMin.x) {
Cartesian3.clone(currentPos, xMin);
}
if (x > xMax.x) {
Cartesian3.clone(currentPos, xMax);
}
if (y < yMin.y) {
Cartesian3.clone(currentPos, yMin);
}
if (y > yMax.y) {
Cartesian3.clone(currentPos, yMax);
}
if (z < zMin.z) {
Cartesian3.clone(currentPos, zMin);
}
if (z > zMax.z) {
Cartesian3.clone(currentPos, zMax);
}
}
// Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
var xSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(xMax, xMin, fromPointsScratch));
var ySpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(yMax, yMin, fromPointsScratch));
var zSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(zMax, zMin, fromPointsScratch));
// Set the diameter endpoints to the largest span.
var diameter1 = xMin;
var diameter2 = xMax;
var maxSpan = xSpan;
if (ySpan > maxSpan) {
maxSpan = ySpan;
diameter1 = yMin;
diameter2 = yMax;
}
if (zSpan > maxSpan) {
maxSpan = zSpan;
diameter1 = zMin;
diameter2 = zMax;
}
// Calculate the center of the initial sphere found by Ritter's algorithm
var ritterCenter = fromPointsRitterCenter;
ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
// Calculate the radius of the initial sphere found by Ritter's algorithm
var radiusSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch));
var ritterRadius = Math.sqrt(radiusSquared);
// Find the center of the sphere found using the Naive method.
var minBoxPt = fromPointsMinBoxPt;
minBoxPt.x = xMin.x;
minBoxPt.y = yMin.y;
minBoxPt.z = zMin.z;
var maxBoxPt = fromPointsMaxBoxPt;
maxBoxPt.x = xMax.x;
maxBoxPt.y = yMax.y;
maxBoxPt.z = zMax.z;
var naiveCenter = Cartesian3.multiplyByScalar(Cartesian3.add(minBoxPt, maxBoxPt, fromPointsScratch), 0.5, fromPointsNaiveCenterScratch);
// Begin 2nd pass to find naive radius and modify the ritter sphere.
var naiveRadius = 0;
for (i = 0; i < numElements; i += stride) {
currentPos.x = positions[i] + center.x;
currentPos.y = positions[i + 1] + center.y;
currentPos.z = positions[i + 2] + center.z;
// Find the furthest point from the naive center to calculate the naive radius.
var r = Cartesian3.magnitude(Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch));
if (r > naiveRadius) {
naiveRadius = r;
}
// Make adjustments to the Ritter Sphere to include all points.
var oldCenterToPointSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch));
if (oldCenterToPointSquared > radiusSquared) {
var oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
// Calculate new radius to include the point that lies outside
ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
radiusSquared = ritterRadius * ritterRadius;
// Calculate center of new Ritter sphere
var oldToNew = oldCenterToPoint - ritterRadius;
ritterCenter.x = (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) / oldCenterToPoint;
ritterCenter.y = (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) / oldCenterToPoint;
ritterCenter.z = (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) / oldCenterToPoint;
}
}
if (ritterRadius < naiveRadius) {
Cartesian3.clone(ritterCenter, result.center);
result.radius = ritterRadius;
} else {
Cartesian3.clone(naiveCenter, result.center);
result.radius = naiveRadius;
}
return result;
};
/**
* Computes a bounding sphere from the corner points of an axis-aligned bounding box. The sphere
* tighly and fully encompases the box.
*
* @param {Number} [corner] The minimum height over the rectangle.
* @param {Number} [oppositeCorner] The maximum height over the rectangle.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*
* @example
* // Create a bounding sphere around the unit cube
* var sphere = Cesium.BoundingSphere.fromCornerPoints(new Cesium.Cartesian3(-0.5, -0.5, -0.5), new Cesium.Cartesian3(0.5, 0.5, 0.5));
*/
BoundingSphere.fromCornerPoints = function(corner, oppositeCorner, result) {
if (!defined(corner) || !defined(oppositeCorner)) {
throw new DeveloperError('corner and oppositeCorner are required.');
}
if (!defined(result)) {
result = new BoundingSphere();
}
var center = result.center;
Cartesian3.add(corner, oppositeCorner, center);
Cartesian3.multiplyByScalar(center, 0.5, center);
result.radius = Cartesian3.distance(center, oppositeCorner);
return result;
};
/**
* Creates a bounding sphere encompassing an ellipsoid.
*
* @param {Ellipsoid} ellipsoid The ellipsoid around which to create a bounding sphere.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*
* @example
* var boundingSphere = Cesium.BoundingSphere.fromEllipsoid(ellipsoid);
*/
BoundingSphere.fromEllipsoid = function(ellipsoid, result) {
if (!defined(ellipsoid)) {
throw new DeveloperError('ellipsoid is required.');
}
if (!defined(result)) {
result = new BoundingSphere();
}
Cartesian3.clone(Cartesian3.ZERO, result.center);
result.radius = ellipsoid.maximumRadius;
return result;
};
var fromBoundingSpheresScratch = new Cartesian3();
/**
* Computes a tight-fitting bounding sphere enclosing the provided array of bounding spheres.
*
* @param {BoundingSphere[]} boundingSpheres The array of bounding spheres.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*/
BoundingSphere.fromBoundingSpheres = function(boundingSpheres, result) {
if (!defined(result)) {
result = new BoundingSphere();
}
if (!defined(boundingSpheres) || boundingSpheres.length === 0) {
result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
result.radius = 0.0;
return result;
}
var length = boundingSpheres.length;
if (length === 1) {
return BoundingSphere.clone(boundingSpheres[0], result);
}
if (length === 2) {
return BoundingSphere.union(boundingSpheres[0], boundingSpheres[1], result);
}
var positions = [];
for (var i = 0; i < length; i++) {
positions.push(boundingSpheres[i].center);
}
result = BoundingSphere.fromPoints(positions, result);
var center = result.center;
var radius = result.radius;
for (i = 0; i < length; i++) {
var tmp = boundingSpheres[i];
radius = Math.max(radius, Cartesian3.distance(center, tmp.center, fromBoundingSpheresScratch) + tmp.radius);
}
result.radius = radius;
return result;
};
/**
* Duplicates a BoundingSphere instance.
*
* @param {BoundingSphere} sphere The bounding sphere to duplicate.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided. (Returns undefined if sphere is undefined)
*/
BoundingSphere.clone = function(sphere, result) {
if (!defined(sphere)) {
return undefined;
}
if (!defined(result)) {
return new BoundingSphere(sphere.center, sphere.radius);
}
result.center = Cartesian3.clone(sphere.center, result.center);
result.radius = sphere.radius;
return result;
};
/**
* The number of elements used to pack the object into an array.
* @type {Number}
*/
BoundingSphere.packedLength = 4;
/**
* Stores the provided instance into the provided array.
*
* @param {BoundingSphere} value The value to pack.
* @param {Number[]} array The array to pack into.
* @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
*/
BoundingSphere.pack = function(value, array, startingIndex) {
if (!defined(value)) {
throw new DeveloperError('value is required');
}
if (!defined(array)) {
throw new DeveloperError('array is required');
}
startingIndex = defaultValue(startingIndex, 0);
var center = value.center;
array[startingIndex++] = center.x;
array[startingIndex++] = center.y;
array[startingIndex++] = center.z;
array[startingIndex] = value.radius;
};
/**
* Retrieves an instance from a packed array.
*
* @param {Number[]} array The packed array.
* @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
* @param {BoundingSphere} [result] The object into which to store the result.
*/
BoundingSphere.unpack = function(array, startingIndex, result) {
if (!defined(array)) {
throw new DeveloperError('array is required');
}
startingIndex = defaultValue(startingIndex, 0);
if (!defined(result)) {
result = new BoundingSphere();
}
var center = result.center;
center.x = array[startingIndex++];
center.y = array[startingIndex++];
center.z = array[startingIndex++];
result.radius = array[startingIndex];
return result;
};
var unionScratch = new Cartesian3();
var unionScratchCenter = new Cartesian3();
/**
* Computes a bounding sphere that contains both the left and right bounding spheres.
*
* @param {BoundingSphere} left A sphere to enclose in a bounding sphere.
* @param {BoundingSphere} right A sphere to enclose in a bounding sphere.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*/
BoundingSphere.union = function(left, right, result) {
if (!defined(left)) {
throw new DeveloperError('left is required.');
}
if (!defined(right)) {
throw new DeveloperError('right is required.');
}
if (!defined(result)) {
result = new BoundingSphere();
}
var leftCenter = left.center;
var rightCenter = right.center;
Cartesian3.add(leftCenter, rightCenter, unionScratchCenter);
var center = Cartesian3.multiplyByScalar(unionScratchCenter, 0.5, unionScratchCenter);
var radius1 = Cartesian3.magnitude(Cartesian3.subtract(leftCenter, center, unionScratch)) + left.radius;
var radius2 = Cartesian3.magnitude(Cartesian3.subtract(rightCenter, center, unionScratch)) + right.radius;
result.radius = Math.max(radius1, radius2);
Cartesian3.clone(center, result.center);
return result;
};
var expandScratch = new Cartesian3();
/**
* Computes a bounding sphere by enlarging the provided sphere to contain the provided point.
*
* @param {BoundingSphere} sphere A sphere to expand.
* @param {Cartesian3} point A point to enclose in a bounding sphere.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*/
BoundingSphere.expand = function(sphere, point, result) {
if (!defined(sphere)) {
throw new DeveloperError('sphere is required.');
}
if (!defined(point)) {
throw new DeveloperError('point is required.');
}
result = BoundingSphere.clone(sphere, result);
var radius = Cartesian3.magnitude(Cartesian3.subtract(point, result.center, expandScratch));
if (radius > result.radius) {
result.radius = radius;
}
return result;
};
/**
* Determines which side of a plane a sphere is located.
*
* @param {BoundingSphere} sphere The bounding sphere to test.
* @param {Cartesian4} plane The coefficients of the plane in the for ax + by + cz + d = 0
* where the coefficients a, b, c, and d are the components x, y, z,
* and w of the {@link Cartesian4}, respectively.
* @returns {Intersect} {@link Intersect.INSIDE} if the entire sphere is on the side of the plane
* the normal is pointing, {@link Intersect.OUTSIDE} if the entire sphere is
* on the opposite side, and {@link Intersect.INTERSECTING} if the sphere
* intersects the plane.
*/
BoundingSphere.intersect = function(sphere, plane) {
if (!defined(sphere)) {
throw new DeveloperError('sphere is required.');
}
if (!defined(plane)) {
throw new DeveloperError('plane is required.');
}
var center = sphere.center;
var radius = sphere.radius;
var distanceToPlane = Cartesian3.dot(plane, center) + plane.w;
if (distanceToPlane < -radius) {
// The center point is negative side of the plane normal
return Intersect.OUTSIDE;
} else if (distanceToPlane < radius) {
// The center point is positive side of the plane, but radius extends beyond it; partial overlap
return Intersect.INTERSECTING;
}
return Intersect.INSIDE;
};
/**
* Applies a 4x4 affine transformation matrix to a bounding sphere.
*
* @param {BoundingSphere} sphere The bounding sphere to apply the transformation to.
* @param {Matrix4} transform The transformation matrix to apply to the bounding sphere.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*/
BoundingSphere.transform = function(sphere, transform, result) {
if (!defined(sphere)) {
throw new DeveloperError('sphere is required.');
}
if (!defined(transform)) {
throw new DeveloperError('transform is required.');
}
if (!defined(result)) {
result = new BoundingSphere();
}
result.center = Matrix4.multiplyByPoint(transform, sphere.center, result.center);
result.radius = Matrix4.getMaximumScale(transform) * sphere.radius;
return result;
};
var distanceSquaredToScratch = new Cartesian3();
/**
* Computes the estimated distance squared from the closest point on a bounding sphere to a point.
*
* @param {BoundingSphere} sphere The sphere.
* @param {Cartesian3} cartesian The point
* @returns {Number} The estimated distance squared from the bounding sphere to the point.
*
* @example
* // Sort bounding spheres from back to front
* spheres.sort(function(a, b) {
* return Cesium.BoundingSphere.distanceSquaredTo(b, camera.positionWC) - Cesium.BoundingSphere.distanceSquaredTo(a, camera.positionWC);
* });
*/
BoundingSphere.distanceSquaredTo = function(sphere, cartesian) {
if (!defined(sphere)) {
throw new DeveloperError('sphere is required.');
}
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required.');
}
var diff = Cartesian3.subtract(sphere.center, cartesian, distanceSquaredToScratch);
return Cartesian3.magnitudeSquared(diff) - sphere.radius * sphere.radius;
};
/**
* Applies a 4x4 affine transformation matrix to a bounding sphere where there is no scale
* The transformation matrix is not verified to have a uniform scale of 1.
* This method is faster than computing the general bounding sphere transform using {@link BoundingSphere.transform}.
*
* @param {BoundingSphere} sphere The bounding sphere to apply the transformation to.
* @param {Matrix4} transform The transformation matrix to apply to the bounding sphere.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*
* @example
* var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(positionOnEllipsoid);
* var boundingSphere = new Cesium.BoundingSphere();
* var newBoundingSphere = Cesium.BoundingSphere.transformWithoutScale(boundingSphere, modelMatrix);
*/
BoundingSphere.transformWithoutScale = function(sphere, transform, result) {
if (!defined(sphere)) {
throw new DeveloperError('sphere is required.');
}
if (!defined(transform)) {
throw new DeveloperError('transform is required.');
}
if (!defined(result)) {
result = new BoundingSphere();
}
result.center = Matrix4.multiplyByPoint(transform, sphere.center, result.center);
result.radius = sphere.radius;
return result;
};
var scratchCartesian3 = new Cartesian3();
/**
* The distances calculated by the vector from the center of the bounding sphere to position projected onto direction
* plus/minus the radius of the bounding sphere.
* <br>
* If you imagine the infinite number of planes with normal direction, this computes the smallest distance to the
* closest and farthest planes from position that intersect the bounding sphere.
*
* @param {BoundingSphere} sphere The bounding sphere to calculate the distance to.
* @param {Cartesian3} position The position to calculate the distance from.
* @param {Cartesian3} direction The direction from position.
* @param {Cartesian2} [result] A Cartesian2 to store the nearest and farthest distances.
* @returns {Interval} The nearest and farthest distances on the bounding sphere from position in direction.
*/
BoundingSphere.computePlaneDistances = function(sphere, position, direction, result) {
if (!defined(sphere)) {
throw new DeveloperError('sphere is required.');
}
if (!defined(position)) {
throw new DeveloperError('position is required.');
}
if (!defined(direction)) {
throw new DeveloperError('direction is required.');
}
if (!defined(result)) {
result = new Interval();
}
var toCenter = Cartesian3.subtract(sphere.center, position, scratchCartesian3);
var proj = Cartesian3.multiplyByScalar(direction, Cartesian3.dot(direction, toCenter), scratchCartesian3);
var mag = Cartesian3.magnitude(proj);
result.start = mag - sphere.radius;
result.stop = mag + sphere.radius;
return result;
};
var projectTo2DNormalScratch = new Cartesian3();
var projectTo2DEastScratch = new Cartesian3();
var projectTo2DNorthScratch = new Cartesian3();
var projectTo2DWestScratch = new Cartesian3();
var projectTo2DSouthScratch = new Cartesian3();
var projectTo2DCartographicScratch = new Cartographic();
var projectTo2DPositionsScratch = new Array(8);
for (var n = 0; n < 8; ++n) {
projectTo2DPositionsScratch[n] = new Cartesian3();
}
var projectTo2DProjection = new GeographicProjection();
/**
* Creates a bounding sphere in 2D from a bounding sphere in 3D world coordinates.
*
* @param {BoundingSphere} sphere The bounding sphere to transform to 2D.
* @param {Object} [projection=GeographicProjection] The projection to 2D.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*/
BoundingSphere.projectTo2D = function(sphere, projection, result) {
if (!defined(sphere)) {
throw new DeveloperError('sphere is required.');
}
projection = defaultValue(projection, projectTo2DProjection);
var ellipsoid = projection.ellipsoid;
var center = sphere.center;
var radius = sphere.radius;
var normal = ellipsoid.geodeticSurfaceNormal(center, projectTo2DNormalScratch);
var east = Cartesian3.cross(Cartesian3.UNIT_Z, normal, projectTo2DEastScratch);
Cartesian3.normalize(east, east);
var north = Cartesian3.cross(normal, east, projectTo2DNorthScratch);
Cartesian3.normalize(north, north);
Cartesian3.multiplyByScalar(normal, radius, normal);
Cartesian3.multiplyByScalar(north, radius, north);
Cartesian3.multiplyByScalar(east, radius, east);
var south = Cartesian3.negate(north, projectTo2DSouthScratch);
var west = Cartesian3.negate(east, projectTo2DWestScratch);
var positions = projectTo2DPositionsScratch;
// top NE corner
var corner = positions[0];
Cartesian3.add(normal, north, corner);
Cartesian3.add(corner, east, corner);
// top NW corner
corner = positions[1];
Cartesian3.add(normal, north, corner);
Cartesian3.add(corner, west, corner);
// top SW corner
corner = positions[2];
Cartesian3.add(normal, south, corner);
Cartesian3.add(corner, west, corner);
// top SE corner
corner = positions[3];
Cartesian3.add(normal, south, corner);
Cartesian3.add(corner, east, corner);
Cartesian3.negate(normal, normal);
// bottom NE corner
corner = positions[4];
Cartesian3.add(normal, north, corner);
Cartesian3.add(corner, east, corner);
// bottom NW corner
corner = positions[5];
Cartesian3.add(normal, north, corner);
Cartesian3.add(corner, west, corner);
// bottom SW corner
corner = positions[6];
Cartesian3.add(normal, south, corner);
Cartesian3.add(corner, west, corner);
// bottom SE corner
corner = positions[7];
Cartesian3.add(normal, south, corner);
Cartesian3.add(corner, east, corner);
var length = positions.length;
for (var i = 0; i < length; ++i) {
var position = positions[i];
Cartesian3.add(center, position, position);
var cartographic = ellipsoid.cartesianToCartographic(position, projectTo2DCartographicScratch);
projection.project(cartographic, position);
}
result = BoundingSphere.fromPoints(positions, result);
// swizzle center components
center = result.center;
var x = center.x;
var y = center.y;
var z = center.z;
center.x = z;
center.y = x;
center.z = y;
return result;
};
/**
* Compares the provided BoundingSphere componentwise and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {BoundingSphere} [left] The first BoundingSphere.
* @param {BoundingSphere} [right] The second BoundingSphere.
* @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
BoundingSphere.equals = function(left, right) {
return (left === right) ||
((defined(left)) &&
(defined(right)) &&
Cartesian3.equals(left.center, right.center) &&
left.radius === right.radius);
};
/**
* Determines which side of a plane the sphere is located.
*
* @param {Cartesian4} plane The coefficients of the plane in the for ax + by + cz + d = 0
* where the coefficients a, b, c, and d are the components x, y, z,
* and w of the {@link Cartesian4}, respectively.
* @returns {Intersect} {@link Intersect.INSIDE} if the entire sphere is on the side of the plane
* the normal is pointing, {@link Intersect.OUTSIDE} if the entire sphere is
* on the opposite side, and {@link Intersect.INTERSECTING} if the sphere
* intersects the plane.
*/
BoundingSphere.prototype.intersect = function(plane) {
return BoundingSphere.intersect(this, plane);
};
/**
* Compares this BoundingSphere against the provided BoundingSphere componentwise and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {BoundingSphere} [right] The right hand side BoundingSphere.
* @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
*/
BoundingSphere.prototype.equals = function(right) {
return BoundingSphere.equals(this, right);
};
/**
* Duplicates this BoundingSphere instance.
*
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*/
BoundingSphere.prototype.clone = function(result) {
return BoundingSphere.clone(this, result);
};
return BoundingSphere;
});
/*global define*/
define('Core/Cartesian2',[
'./defaultValue',
'./defined',
'./DeveloperError',
'./freezeObject',
'./Math'
], function(
defaultValue,
defined,
DeveloperError,
freezeObject,
CesiumMath) {
"use strict";
/**
* A 2D Cartesian point.
* @alias Cartesian2
* @constructor
*
* @param {Number} [x=0.0] The X component.
* @param {Number} [y=0.0] The Y component.
*
* @see Cartesian3
* @see Cartesian4
* @see Packable
*/
var Cartesian2 = function(x, y) {
/**
* The X component.
* @type {Number}
* @default 0.0
*/
this.x = defaultValue(x, 0.0);
/**
* The Y component.
* @type {Number}
* @default 0.0
*/
this.y = defaultValue(y, 0.0);
};
/**
* Creates a Cartesian2 instance from x and y coordinates.
*
* @param {Number} x The x coordinate.
* @param {Number} y The y coordinate.
* @param {Cartesian2} [result] The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
*/
Cartesian2.fromElements = function(x, y, result) {
if (!defined(result)) {
return new Cartesian2(x, y);
}
result.x = x;
result.y = y;
return result;
};
/**
* Duplicates a Cartesian2 instance.
*
* @param {Cartesian2} cartesian The Cartesian to duplicate.
* @param {Cartesian2} [result] The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided. (Returns undefined if cartesian is undefined)
*/
Cartesian2.clone = function(cartesian, result) {
if (!defined(cartesian)) {
return undefined;
}
if (!defined(result)) {
return new Cartesian2(cartesian.x, cartesian.y);
}
result.x = cartesian.x;
result.y = cartesian.y;
return result;
};
/**
* Creates a Cartesian2 instance from an existing Cartesian3. This simply takes the
* x and y properties of the Cartesian3 and drops z.
* @function
*
* @param {Cartesian3} cartesian The Cartesian3 instance to create a Cartesian2 instance from.
* @param {Cartesian2} [result] The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
*/
Cartesian2.fromCartesian3 = Cartesian2.clone;
/**
* Creates a Cartesian2 instance from an existing Cartesian4. This simply takes the
* x and y properties of the Cartesian4 and drops z and w.
* @function
*
* @param {Cartesian4} cartesian The Cartesian4 instance to create a Cartesian2 instance from.
* @param {Cartesian2} [result] The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
*/
Cartesian2.fromCartesian4 = Cartesian2.clone;
/**
* The number of elements used to pack the object into an array.
* @type {Number}
*/
Cartesian2.packedLength = 2;
/**
* Stores the provided instance into the provided array.
*
* @param {Cartesian2} value The value to pack.
* @param {Number[]} array The array to pack into.
* @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
*/
Cartesian2.pack = function(value, array, startingIndex) {
if (!defined(value)) {
throw new DeveloperError('value is required');
}
if (!defined(array)) {
throw new DeveloperError('array is required');
}
startingIndex = defaultValue(startingIndex, 0);
array[startingIndex++] = value.x;
array[startingIndex] = value.y;
};
/**
* Retrieves an instance from a packed array.
*
* @param {Number[]} array The packed array.
* @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
* @param {Cartesian2} [result] The object into which to store the result.
*/
Cartesian2.unpack = function(array, startingIndex, result) {
if (!defined(array)) {
throw new DeveloperError('array is required');
}
startingIndex = defaultValue(startingIndex, 0);
if (!defined(result)) {
result = new Cartesian2();
}
result.x = array[startingIndex++];
result.y = array[startingIndex];
return result;
};
/**
* Creates a Cartesian2 from two consecutive elements in an array.
* @function
*
* @param {Number[]} array The array whose two consecutive elements correspond to the x and y components, respectively.
* @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to the x component.
* @param {Cartesian2} [result] The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
*
* @example
* // Create a Cartesian2 with (1.0, 2.0)
* var v = [1.0, 2.0];
* var p = Cesium.Cartesian2.fromArray(v);
*
* // Create a Cartesian2 with (1.0, 2.0) using an offset into an array
* var v2 = [0.0, 0.0, 1.0, 2.0];
* var p2 = Cesium.Cartesian2.fromArray(v2, 2);
*/
Cartesian2.fromArray = Cartesian2.unpack;
/**
* Computes the value of the maximum component for the supplied Cartesian.
*
* @param {Cartesian2} cartesian The cartesian to use.
* @returns {Number} The value of the maximum component.
*/
Cartesian2.maximumComponent = function(cartesian) {
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required');
}
return Math.max(cartesian.x, cartesian.y);
};
/**
* Computes the value of the minimum component for the supplied Cartesian.
*
* @param {Cartesian2} cartesian The cartesian to use.
* @returns {Number} The value of the minimum component.
*/
Cartesian2.minimumComponent = function(cartesian) {
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required');
}
return Math.min(cartesian.x, cartesian.y);
};
/**
* Compares two Cartesians and computes a Cartesian which contains the minimum components of the supplied Cartesians.
*
* @param {Cartesian2} first A cartesian to compare.
* @param {Cartesian2} second A cartesian to compare.
* @param {Cartesian2} result The object into which to store the result.
* @returns {Cartesian2} A cartesian with the minimum components.
*/
Cartesian2.minimumByComponent = function(first, second, result) {
if (!defined(first)) {
throw new DeveloperError('first is required.');
}
if (!defined(second)) {
throw new DeveloperError('second is required.');
}
if (!defined(result)) {
throw new DeveloperError('result is required.');
}
result.x = Math.min(first.x, second.x);
result.y = Math.min(first.y, second.y);
return result;
};
/**
* Compares two Cartesians and computes a Cartesian which contains the maximum components of the supplied Cartesians.
*
* @param {Cartesian2} first A cartesian to compare.
* @param {Cartesian2} second A cartesian to compare.
* @param {Cartesian2} result The object into which to store the result.
* @returns {Cartesian2} A cartesian with the maximum components.
*/
Cartesian2.maximumByComponent = function(first, second, result) {
if (!defined(first)) {
throw new DeveloperError('first is required.');
}
if (!defined(second)) {
throw new DeveloperError('second is required.');
}
if (!defined(result)) {
throw new DeveloperError('result is required.');
}
result.x = Math.max(first.x, second.x);
result.y = Math.max(first.y, second.y);
return result;
};
/**
* Computes the provided Cartesian's squared magnitude.
*
* @param {Cartesian2} cartesian The Cartesian instance whose squared magnitude is to be computed.
* @returns {Number} The squared magnitude.
*/
Cartesian2.magnitudeSquared = function(cartesian) {
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required');
}
return cartesian.x * cartesian.x + cartesian.y * cartesian.y;
};
/**
* Computes the Cartesian's magnitude (length).
*
* @param {Cartesian2} cartesian The Cartesian instance whose magnitude is to be computed.
* @returns {Number} The magnitude.
*/
Cartesian2.magnitude = function(cartesian) {
return Math.sqrt(Cartesian2.magnitudeSquared(cartesian));
};
var distanceScratch = new Cartesian2();
/**
* Computes the distance between two points.
*
* @param {Cartesian2} left The first point to compute the distance from.
* @param {Cartesian2} right The second point to compute the distance to.
* @returns {Number} The distance between two points.
*
* @example
* // Returns 1.0
* var d = Cesium.Cartesian2.distance(new Cesium.Cartesian2(1.0, 0.0), new Cesium.Cartesian2(2.0, 0.0));
*/
Cartesian2.distance = function(left, right) {
if (!defined(left) || !defined(right)) {
throw new DeveloperError('left and right are required.');
}
Cartesian2.subtract(left, right, distanceScratch);
return Cartesian2.magnitude(distanceScratch);
};
/**
* Computes the squared distance between two points. Comparing squared distances
* using this function is more efficient than comparing distances using {@link Cartesian2#distance}.
*
* @param {Cartesian2} left The first point to compute the distance from.
* @param {Cartesian2} right The second point to compute the distance to.
* @returns {Number} The distance between two points.
*
* @example
* // Returns 4.0, not 2.0
* var d = Cesium.Cartesian2.distance(new Cesium.Cartesian2(1.0, 0.0), new Cesium.Cartesian2(3.0, 0.0));
*/
Cartesian2.distanceSquared = function(left, right) {
if (!defined(left) || !defined(right)) {
throw new DeveloperError('left and right are required.');
}
Cartesian2.subtract(left, right, distanceScratch);
return Cartesian2.magnitudeSquared(distanceScratch);
};
/**
* Computes the normalized form of the supplied Cartesian.
*
* @param {Cartesian2} cartesian The Cartesian to be normalized.
* @param {Cartesian2} result The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter.
*/
Cartesian2.normalize = function(cartesian, result) {
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required');
}
var magnitude = Cartesian2.magnitude(cartesian);
result.x = cartesian.x / magnitude;
result.y = cartesian.y / magnitude;
return result;
};
/**
* Computes the dot (scalar) product of two Cartesians.
*
* @param {Cartesian2} left The first Cartesian.
* @param {Cartesian2} right The second Cartesian.
* @returns {Number} The dot product.
*/
Cartesian2.dot = function(left, right) {
if (!defined(left)) {
throw new DeveloperError('left is required');
}
if (!defined(right)) {
throw new DeveloperError('right is required');
}
return left.x * right.x + left.y * right.y;
};
/**
* Computes the componentwise product of two Cartesians.
*
* @param {Cartesian2} left The first Cartesian.
* @param {Cartesian2} right The second Cartesian.
* @param {Cartesian2} result The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter.
*/
Cartesian2.multiplyComponents = function(left, right, result) {
if (!defined(left)) {
throw new DeveloperError('left is required');
}
if (!defined(right)) {
throw new DeveloperError('right is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required');
}
result.x = left.x * right.x;
result.y = left.y * right.y;
return result;
};
/**
* Computes the componentwise sum of two Cartesians.
*
* @param {Cartesian2} left The first Cartesian.
* @param {Cartesian2} right The second Cartesian.
* @param {Cartesian2} result The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter.
*/
Cartesian2.add = function(left, right, result) {
if (!defined(left)) {
throw new DeveloperError('left is required');
}
if (!defined(right)) {
throw new DeveloperError('right is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required');
}
result.x = left.x + right.x;
result.y = left.y + right.y;
return result;
};
/**
* Computes the componentwise difference of two Cartesians.
*
* @param {Cartesian2} left The first Cartesian.
* @param {Cartesian2} right The second Cartesian.
* @param {Cartesian2} result The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter.
*/
Cartesian2.subtract = function(left, right, result) {
if (!defined(left)) {
throw new DeveloperError('left is required');
}
if (!defined(right)) {
throw new DeveloperError('right is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required');
}
result.x = left.x - right.x;
result.y = left.y - right.y;
return result;
};
/**
* Multiplies the provided Cartesian componentwise by the provided scalar.
*
* @param {Cartesian2} cartesian The Cartesian to be scaled.
* @param {Number} scalar The scalar to multiply with.
* @param {Cartesian2} result The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter.
*/
Cartesian2.multiplyByScalar = function(cartesian, scalar, result) {
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required');
}
if (typeof scalar !== 'number') {
throw new DeveloperError('scalar is required and must be a number.');
}
if (!defined(result)) {
throw new DeveloperError('result is required');
}
result.x = cartesian.x * scalar;
result.y = cartesian.y * scalar;
return result;
};
/**
* Divides the provided Cartesian componentwise by the provided scalar.
*
* @param {Cartesian2} cartesian The Cartesian to be divided.
* @param {Number} scalar The scalar to divide by.
* @param {Cartesian2} result The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter.
*/
Cartesian2.divideByScalar = function(cartesian, scalar, result) {
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required');
}
if (typeof scalar !== 'number') {
throw new DeveloperError('scalar is required and must be a number.');
}
if (!defined(result)) {
throw new DeveloperError('result is required');
}
result.x = cartesian.x / scalar;
result.y = cartesian.y / scalar;
return result;
};
/**
* Negates the provided Cartesian.
*
* @param {Cartesian2} cartesian The Cartesian to be negated.
* @param {Cartesian2} result The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter.
*/
Cartesian2.negate = function(cartesian, result) {
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required');
}
result.x = -cartesian.x;
result.y = -cartesian.y;
return result;
};
/**
* Computes the absolute value of the provided Cartesian.
*
* @param {Cartesian2} cartesian The Cartesian whose absolute value is to be computed.
* @param {Cartesian2} result The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter.
*/
Cartesian2.abs = function(cartesian, result) {
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required');
}
result.x = Math.abs(cartesian.x);
result.y = Math.abs(cartesian.y);
return result;
};
var lerpScratch = new Cartesian2();
/**
* Computes the linear interpolation or extrapolation at t using the provided cartesians.
*
* @param {Cartesian2} start The value corresponding to t at 0.0.
* @param {Cartesian2} end The value corresponding to t at 1.0.
* @param {Number} t The point along t at which to interpolate.
* @param {Cartesian2} result The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter.
*/
Cartesian2.lerp = function(start, end, t, result) {
if (!defined(start)) {
throw new DeveloperError('start is required.');
}
if (!defined(end)) {
throw new DeveloperError('end is required.');
}
if (typeof t !== 'number') {
throw new DeveloperError('t is required and must be a number.');
}
if (!defined(result)) {
throw new DeveloperError('result is required.');
}
Cartesian2.multiplyByScalar(end, t, lerpScratch);
result = Cartesian2.multiplyByScalar(start, 1.0 - t, result);
return Cartesian2.add(lerpScratch, result, result);
};
var angleBetweenScratch = new Cartesian2();
var angleBetweenScratch2 = new Cartesian2();
/**
* Returns the angle, in radians, between the provided Cartesians.
*
* @param {Cartesian2} left The first Cartesian.
* @param {Cartesian2} right The second Cartesian.
* @returns {Number} The angle between the Cartesians.
*/
Cartesian2.angleBetween = function(left, right) {
if (!defined(left)) {
throw new DeveloperError('left is required');
}
if (!defined(right)) {
throw new DeveloperError('right is required');
}
Cartesian2.normalize(left, angleBetweenScratch);
Cartesian2.normalize(right, angleBetweenScratch2);
return CesiumMath.acosClamped(Cartesian2.dot(angleBetweenScratch, angleBetweenScratch2));
};
var mostOrthogonalAxisScratch = new Cartesian2();
/**
* Returns the axis that is most orthogonal to the provided Cartesian.
*
* @param {Cartesian2} cartesian The Cartesian on which to find the most orthogonal axis.
* @param {Cartesian2} result The object onto which to store the result.
* @returns {Cartesian2} The most orthogonal axis.
*/
Cartesian2.mostOrthogonalAxis = function(cartesian, result) {
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required.');
}
if (!defined(result)) {
throw new DeveloperError('result is required.');
}
var f = Cartesian2.normalize(cartesian, mostOrthogonalAxisScratch);
Cartesian2.abs(f, f);
if (f.x <= f.y) {
result = Cartesian2.clone(Cartesian2.UNIT_X, result);
} else {
result = Cartesian2.clone(Cartesian2.UNIT_Y, result);
}
return result;
};
/**
* Compares the provided Cartesians componentwise and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Cartesian2} [left] The first Cartesian.
* @param {Cartesian2} [right] The second Cartesian.
* @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
Cartesian2.equals = function(left, right) {
return (left === right) ||
((defined(left)) &&
(defined(right)) &&
(left.x === right.x) &&
(left.y === right.y));
};
/**
* @private
*/
Cartesian2.equalsArray = function(cartesian, array, offset) {
return cartesian.x === array[offset] &&
cartesian.y === array[offset + 1];
};
/**
* Compares the provided Cartesians componentwise and returns
* <code>true</code> if they pass an absolute or relative tolerance test,
* <code>false</code> otherwise.
*
* @param {Cartesian2} [left] The first Cartesian.
* @param {Cartesian2} [right] The second Cartesian.
* @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
* @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
* @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
*/
Cartesian2.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) {
return (left === right) ||
(defined(left) &&
defined(right) &&
CesiumMath.equalsEpsilon(left.x, right.x, relativeEpsilon, absoluteEpsilon) &&
CesiumMath.equalsEpsilon(left.y, right.y, relativeEpsilon, absoluteEpsilon));
};
/**
* An immutable Cartesian2 instance initialized to (0.0, 0.0).
*
* @type {Cartesian2}
* @constant
*/
Cartesian2.ZERO = freezeObject(new Cartesian2(0.0, 0.0));
/**
* An immutable Cartesian2 instance initialized to (1.0, 0.0).
*
* @type {Cartesian2}
* @constant
*/
Cartesian2.UNIT_X = freezeObject(new Cartesian2(1.0, 0.0));
/**
* An immutable Cartesian2 instance initialized to (0.0, 1.0).
*
* @type {Cartesian2}
* @constant
*/
Cartesian2.UNIT_Y = freezeObject(new Cartesian2(0.0, 1.0));
/**
* Duplicates this Cartesian2 instance.
*
* @param {Cartesian2} [result] The object onto which to store the result.
* @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
*/
Cartesian2.prototype.clone = function(result) {
return Cartesian2.clone(this, result);
};
/**
* Compares this Cartesian against the provided Cartesian componentwise and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Cartesian2} [right] The right hand side Cartesian.
* @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
*/
Cartesian2.prototype.equals = function(right) {
return Cartesian2.equals(this, right);
};
/**
* Compares this Cartesian against the provided Cartesian componentwise and returns
* <code>true</code> if they pass an absolute or relative tolerance test,
* <code>false</code> otherwise.
*
* @param {Cartesian2} [right] The right hand side Cartesian.
* @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
* @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
* @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
*/
Cartesian2.prototype.equalsEpsilon = function(right, relativeEpsilon, absoluteEpsilon) {
return Cartesian2.equalsEpsilon(this, right, relativeEpsilon, absoluteEpsilon);
};
/**
* Creates a string representing this Cartesian in the format '(x, y)'.
*
* @returns {String} A string representing the provided Cartesian in the format '(x, y)'.
*/
Cartesian2.prototype.toString = function() {
return '(' + this.x + ', ' + this.y + ')';
};
return Cartesian2;
});
/*global define*/
define('Core/Fullscreen',[
'./defined',
'./defineProperties'
], function(
defined,
defineProperties) {
"use strict";
var _supportsFullscreen;
var _names = {
requestFullscreen : undefined,
exitFullscreen : undefined,
fullscreenEnabled : undefined,
fullscreenElement : undefined,
fullscreenchange : undefined,
fullscreenerror : undefined
};
/**
* Browser-independent functions for working with the standard fullscreen API.
*
* @namespace
* @alias Fullscreen
*
* @see {@link http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html|W3C Fullscreen Living Specification}
*/
var Fullscreen = {};
defineProperties(Fullscreen, {
/**
* The element that is currently fullscreen, if any. To simply check if the
* browser is in fullscreen mode or not, use {@link Fullscreen#fullscreen}.
* @memberof Fullscreen
* @type {Object}
*/
element : {
get : function() {
if (!Fullscreen.supportsFullscreen()) {
return undefined;
}
return document[_names.fullscreenElement];
}
},
/**
* The name of the event on the document that is fired when fullscreen is
* entered or exited. This event name is intended for use with addEventListener.
* In your event handler, to determine if the browser is in fullscreen mode or not,
* use {@link Fullscreen#fullscreen}.
* @memberof Fullscreen
* @type {String}
*/
changeEventName : {
get : function() {
if (!Fullscreen.supportsFullscreen()) {
return undefined;
}
return _names.fullscreenchange;
}
},
/**
* The name of the event that is fired when a fullscreen error
* occurs. This event name is intended for use with addEventListener.
* @memberof Fullscreen
* @type {String}
*/
errorEventName : {
get : function() {
if (!Fullscreen.supportsFullscreen()) {
return undefined;
}
return _names.fullscreenerror;
}
},
/**
* Determine whether the browser will allow an element to be made fullscreen, or not.
* For example, by default, iframes cannot go fullscreen unless the containing page
* adds an "allowfullscreen" attribute (or prefixed equivalent).
* @memberof Fullscreen
* @type {Boolean}
*/
enabled : {
get : function() {
if (!Fullscreen.supportsFullscreen()) {
return undefined;
}
return document[_names.fullscreenEnabled];
}
},
/**
* Determines if the browser is currently in fullscreen mode.
* @memberof Fullscreen
* @type {Boolean}
*/
fullscreen : {
get : function() {
if (!Fullscreen.supportsFullscreen()) {
return undefined;
}
return Fullscreen.element !== null;
}
}
});
/**
* Detects whether the browser supports the standard fullscreen API.
*
* @returns <code>true</code> if the browser supports the standard fullscreen API,
* <code>false</code> otherwise.
*/
Fullscreen.supportsFullscreen = function() {
if (defined(_supportsFullscreen)) {
return _supportsFullscreen;
}
_supportsFullscreen = false;
var body = document.body;
if (typeof body.requestFullscreen === 'function') {
// go with the unprefixed, standard set of names
_names.requestFullscreen = 'requestFullscreen';
_names.exitFullscreen = 'exitFullscreen';
_names.fullscreenEnabled = 'fullscreenEnabled';
_names.fullscreenElement = 'fullscreenElement';
_names.fullscreenchange = 'fullscreenchange';
_names.fullscreenerror = 'fullscreenerror';
_supportsFullscreen = true;
return _supportsFullscreen;
}
//check for the correct combination of prefix plus the various names that browsers use
var prefixes = ['webkit', 'moz', 'o', 'ms', 'khtml'];
var name;
for (var i = 0, len = prefixes.length; i < len; ++i) {
var prefix = prefixes[i];
// casing of Fullscreen differs across browsers
name = prefix + 'RequestFullscreen';
if (typeof body[name] === 'function') {
_names.requestFullscreen = name;
_supportsFullscreen = true;
} else {
name = prefix + 'RequestFullScreen';
if (typeof body[name] === 'function') {
_names.requestFullscreen = name;
_supportsFullscreen = true;
}
}
// disagreement about whether it's "exit" as per spec, or "cancel"
name = prefix + 'ExitFullscreen';
if (typeof document[name] === 'function') {
_names.exitFullscreen = name;
} else {
name = prefix + 'CancelFullScreen';
if (typeof document[name] === 'function') {
_names.exitFullscreen = name;
}
}
// casing of Fullscreen differs across browsers
name = prefix + 'FullscreenEnabled';
if (defined(document[name])) {
_names.fullscreenEnabled = name;
} else {
name = prefix + 'FullScreenEnabled';
if (defined(document[name])) {
_names.fullscreenEnabled = name;
}
}
// casing of Fullscreen differs across browsers
name = prefix + 'FullscreenElement';
if (defined(document[name])) {
_names.fullscreenElement = name;
} else {
name = prefix + 'FullScreenElement';
if (defined(document[name])) {
_names.fullscreenElement = name;
}
}
// thankfully, event names are all lowercase per spec
name = prefix + 'fullscreenchange';
// event names do not have 'on' in the front, but the property on the document does
if (defined(document['on' + name])) {
//except on IE
if (prefix === 'ms') {
name = 'MSFullscreenChange';
}
_names.fullscreenchange = name;
}
name = prefix + 'fullscreenerror';
if (defined(document['on' + name])) {
//except on IE
if (prefix === 'ms') {
name = 'MSFullscreenError';
}
_names.fullscreenerror = name;
}
}
return _supportsFullscreen;
};
/**
* Asynchronously requests the browser to enter fullscreen mode on the given element.
* If fullscreen mode is not supported by the browser, does nothing.
*
* @param {Object} element The HTML element which will be placed into fullscreen mode.
*
* @example
* // Put the entire page into fullscreen.
* Cesium.Fullscreen.requestFullscreen(document.body)
*
* // Place only the Cesium canvas into fullscreen.
* Cesium.Fullscreen.requestFullscreen(scene.canvas)
*/
Fullscreen.requestFullscreen = function(element) {
if (!Fullscreen.supportsFullscreen()) {
return;
}
element[_names.requestFullscreen]();
};
/**
* Asynchronously exits fullscreen mode. If the browser is not currently
* in fullscreen, or if fullscreen mode is not supported by the browser, does nothing.
*/
Fullscreen.exitFullscreen = function() {
if (!Fullscreen.supportsFullscreen()) {
return;
}
document[_names.exitFullscreen]();
};
return Fullscreen;
});
/*global define*/
define('Core/FeatureDetection',[
'./defaultValue',
'./defined',
'./Fullscreen'
], function(
defaultValue,
defined,
Fullscreen) {
"use strict";
function extractVersion(versionString) {
var parts = versionString.split('.');
for (var i = 0, len = parts.length; i < len; ++i) {
parts[i] = parseInt(parts[i], 10);
}
return parts;
}
var isChromeResult;
var chromeVersionResult;
function isChrome() {
if (!defined(isChromeResult)) {
isChromeResult = false;
var fields = (/ Chrome\/([\.0-9]+)/).exec(navigator.userAgent);
if (fields !== null) {
isChromeResult = true;
chromeVersionResult = extractVersion(fields[1]);
}
}
return isChromeResult;
}
function chromeVersion() {
return isChrome() && chromeVersionResult;
}
var isSafariResult;
var safariVersionResult;
function isSafari() {
if (!defined(isSafariResult)) {
isSafariResult = false;
// Chrome contains Safari in the user agent too
if (!isChrome() && (/ Safari\/[\.0-9]+/).test(navigator.userAgent)) {
var fields = (/ Version\/([\.0-9]+)/).exec(navigator.userAgent);
if (fields !== null) {
isSafariResult = true;
safariVersionResult = extractVersion(fields[1]);
}
}
}
return isSafariResult;
}
function safariVersion() {
return isSafari() && safariVersionResult;
}
var isWebkitResult;
var webkitVersionResult;
function isWebkit() {
if (!defined(isWebkitResult)) {
isWebkitResult = false;
var fields = (/ AppleWebKit\/([\.0-9]+)(\+?)/).exec(navigator.userAgent);
if (fields !== null) {
isWebkitResult = true;
webkitVersionResult = extractVersion(fields[1]);
webkitVersionResult.isNightly = !!fields[2];
}
}
return isWebkitResult;
}
function webkitVersion() {
return isWebkit() && webkitVersionResult;
}
var isInternetExplorerResult;
var internetExplorerVersionResult;
function isInternetExplorer() {
if (!defined(isInternetExplorerResult)) {
isInternetExplorerResult = false;
var fields;
if (navigator.appName === 'Microsoft Internet Explorer') {
fields = /MSIE ([0-9]{1,}[\.0-9]{0,})/.exec(navigator.userAgent);
if (fields !== null) {
isInternetExplorerResult = true;
internetExplorerVersionResult = extractVersion(fields[1]);
}
} else if (navigator.appName === 'Netscape') {
fields = /Trident\/.*rv:([0-9]{1,}[\.0-9]{0,})/.exec(navigator.userAgent);
if (fields !== null) {
isInternetExplorerResult = true;
internetExplorerVersionResult = extractVersion(fields[1]);
}
}
}
return isInternetExplorerResult;
}
function internetExplorerVersion() {
return isInternetExplorer() && internetExplorerVersionResult;
}
var isFirefoxResult;
var firefoxVersionResult;
function isFirefox() {
if (!defined(isFirefoxResult)) {
isFirefoxResult = false;
var fields = /Firefox\/([\.0-9]+)/.exec(navigator.userAgent);
if (fields !== null) {
isFirefoxResult = true;
firefoxVersionResult = extractVersion(fields[1]);
}
}
return isFirefoxResult;
}
var isWindowsResult;
function isWindows() {
if (!defined(isWindowsResult)) {
isWindowsResult = /Windows/i.test(navigator.appVersion);
}
return isWindowsResult;
}
function firefoxVersion() {
return isFirefox() && firefoxVersionResult;
}
/**
* A set of functions to detect whether the current browser supports
* various features.
*
* @namespace
* @alias FeatureDetection
*/
var FeatureDetection = {
isChrome : isChrome,
chromeVersion : chromeVersion,
isSafari : isSafari,
safariVersion : safariVersion,
isWebkit : isWebkit,
webkitVersion : webkitVersion,
isInternetExplorer : isInternetExplorer,
internetExplorerVersion : internetExplorerVersion,
isFirefox : isFirefox,
firefoxVersion : firefoxVersion,
isWindows : isWindows,
hardwareConcurrency : defaultValue(navigator.hardwareConcurrency, 3)
};
/**
* Detects whether the current browser supports the full screen standard.
*
* @returns true if the browser supports the full screen standard, false if not.
*
* @see Fullscreen
* @see {@link http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html|W3C Fullscreen Living Specification}
*/
FeatureDetection.supportsFullscreen = function() {
return Fullscreen.supportsFullscreen();
};
/**
* Detects whether the current browser supports typed arrays.
*
* @returns true if the browser supports typed arrays, false if not.
*
* @see {@link http://www.khronos.org/registry/typedarray/specs/latest/|Typed Array Specification}
*/
FeatureDetection.supportsTypedArrays = function() {
return typeof ArrayBuffer !== 'undefined';
};
/**
* Detects whether the current browser supports Web Workers.
*
* @returns true if the browsers supports Web Workers, false if not.
*
* @see {@link http://www.w3.org/TR/workers/}
*/
FeatureDetection.supportsWebWorkers = function() {
return typeof Worker !== 'undefined';
};
return FeatureDetection;
});
/*global define*/
define('Core/ComponentDatatype',[
'./defaultValue',
'./defined',
'./DeveloperError',
'./FeatureDetection',
'./freezeObject'
], function(
defaultValue,
defined,
DeveloperError,
FeatureDetection,
freezeObject) {
"use strict";
// Bail out if the browser doesn't support typed arrays, to prevent the setup function
// from failing, since we won't be able to create a WebGL context anyway.
if (!FeatureDetection.supportsTypedArrays()) {
return {};
}
/**
* WebGL component datatypes. Components are intrinsics,
* which form attributes, which form vertices.
*
* @namespace
* @alias ComponentDatatype
*/
var ComponentDatatype = {
/**
* 8-bit signed byte corresponding to <code>gl.BYTE</code> and the type
* of an element in <code>Int8Array</code>.
*
* @type {Number}
* @constant
* @default 0x1400
*/
BYTE : 0x1400,
/**
* 8-bit unsigned byte corresponding to <code>UNSIGNED_BYTE</code> and the type
* of an element in <code>Uint8Array</code>.
*
* @type {Number}
* @constant
* @default 0x1401
*/
UNSIGNED_BYTE : 0x1401,
/**
* 16-bit signed short corresponding to <code>SHORT</code> and the type
* of an element in <code>Int16Array</code>.
*
* @type {Number}
* @constant
* @default 0x1402
*/
SHORT : 0x1402,
/**
* 16-bit unsigned short corresponding to <code>UNSIGNED_SHORT</code> and the type
* of an element in <code>Uint16Array</code>.
*
* @type {Number}
* @constant
* @default 0x1403
*/
UNSIGNED_SHORT : 0x1403,
/**
* 32-bit floating-point corresponding to <code>FLOAT</code> and the type
* of an element in <code>Float32Array</code>.
*
* @type {Number}
* @constant
* @default 0x1406
*/
FLOAT : 0x1406,
/**
* 64-bit floating-point corresponding to <code>gl.DOUBLE</code> (in Desktop OpenGL;
* this is not supported in WebGL, and is emulated in Cesium via {@link GeometryPipeline.encodeAttribute})
* and the type of an element in <code>Float64Array</code>.
*
* @memberOf ComponentDatatype
*
* @type {Number}
* @constant
* @default 0x140A
*/
DOUBLE : 0x140A
};
/**
* Returns the size, in bytes, of the corresponding datatype.
*
* @param {ComponentDatatype} componentDatatype The component datatype to get the size of.
* @returns {Number} The size in bytes.
*
* @exception {DeveloperError} componentDatatype is not a valid value.
*
* @example
* // Returns Int8Array.BYTES_PER_ELEMENT
* var size = Cesium.ComponentDatatype.getSizeInBytes(Cesium.ComponentDatatype.BYTE);
*/
ComponentDatatype.getSizeInBytes = function(componentDatatype){
if (!defined(componentDatatype)) {
throw new DeveloperError('value is required.');
}
switch (componentDatatype) {
case ComponentDatatype.BYTE:
return Int8Array.BYTES_PER_ELEMENT;
case ComponentDatatype.UNSIGNED_BYTE:
return Uint8Array.BYTES_PER_ELEMENT;
case ComponentDatatype.SHORT:
return Int16Array.BYTES_PER_ELEMENT;
case ComponentDatatype.UNSIGNED_SHORT:
return Uint16Array.BYTES_PER_ELEMENT;
case ComponentDatatype.FLOAT:
return Float32Array.BYTES_PER_ELEMENT;
case ComponentDatatype.DOUBLE:
return Float64Array.BYTES_PER_ELEMENT;
default:
throw new DeveloperError('componentDatatype is not a valid value.');
}
};
/**
* Gets the ComponentDatatype for the provided TypedArray instance.
*
* @param {TypedArray} array The typed array.
* @returns {ComponentDatatype} The ComponentDatatype for the provided array, or undefined if the array is not a TypedArray.
*/
ComponentDatatype.fromTypedArray = function(array) {
if (array instanceof Int8Array) {
return ComponentDatatype.BYTE;
}
if (array instanceof Uint8Array) {
return ComponentDatatype.UNSIGNED_BYTE;
}
if (array instanceof Int16Array) {
return ComponentDatatype.SHORT;
}
if (array instanceof Uint16Array) {
return ComponentDatatype.UNSIGNED_SHORT;
}
if (array instanceof Float32Array) {
return ComponentDatatype.FLOAT;
}
if (array instanceof Float64Array) {
return ComponentDatatype.DOUBLE;
}
};
/**
* Validates that the provided component datatype is a valid {@link ComponentDatatype}
*
* @param {ComponentDatatype} componentDatatype The component datatype to validate.
* @returns {Boolean} <code>true</code> if the provided component datatype is a valid value; otherwise, <code>false</code>.
*
* @example
* if (!Cesium.ComponentDatatype.validate(componentDatatype)) {
* throw new Cesium.DeveloperError('componentDatatype must be a valid value.');
* }
*/
ComponentDatatype.validate = function(componentDatatype) {
return defined(componentDatatype) &&
(componentDatatype === ComponentDatatype.BYTE ||
componentDatatype === ComponentDatatype.UNSIGNED_BYTE ||
componentDatatype === ComponentDatatype.SHORT ||
componentDatatype === ComponentDatatype.UNSIGNED_SHORT ||
componentDatatype === ComponentDatatype.FLOAT ||
componentDatatype === ComponentDatatype.DOUBLE);
};
/**
* Creates a typed array corresponding to component data type.
*
* @param {ComponentDatatype} componentDatatype The component data type.
* @param {Number|Array} valuesOrLength The length of the array to create or an array.
* @returns {Int8Array|Uint8Array|Int16Array|Uint16Array|Float32Array|Float64Array} A typed array.
*
* @exception {DeveloperError} componentDatatype is not a valid value.
*
* @example
* // creates a Float32Array with length of 100
* var typedArray = Cesium.ComponentDatatype.createTypedArray(Cesium.ComponentDatatype.FLOAT, 100);
*/
ComponentDatatype.createTypedArray = function(componentDatatype, valuesOrLength) {
if (!defined(componentDatatype)) {
throw new DeveloperError('componentDatatype is required.');
}
if (!defined(valuesOrLength)) {
throw new DeveloperError('valuesOrLength is required.');
}
switch (componentDatatype) {
case ComponentDatatype.BYTE:
return new Int8Array(valuesOrLength);
case ComponentDatatype.UNSIGNED_BYTE:
return new Uint8Array(valuesOrLength);
case ComponentDatatype.SHORT:
return new Int16Array(valuesOrLength);
case ComponentDatatype.UNSIGNED_SHORT:
return new Uint16Array(valuesOrLength);
case ComponentDatatype.FLOAT:
return new Float32Array(valuesOrLength);
case ComponentDatatype.DOUBLE:
return new Float64Array(valuesOrLength);
default:
throw new DeveloperError('componentDatatype is not a valid value.');
}
};
/**
* Creates a typed view of an array of bytes.
*
* @param {ComponentDatatype} componentDatatype The type of the view to create.
* @param {ArrayBuffer} buffer The buffer storage to use for the view.
* @param {Number} [byteOffset] The offset, in bytes, to the first element in the view.
* @param {Number} [length] The number of elements in the view.
* @returns {Int8Array|Uint8Array|Int16Array|Uint16Array|Float32Array|Float64Array} A typed array view of the buffer.
*
* @exception {DeveloperError} componentDatatype is not a valid value.
*/
ComponentDatatype.createArrayBufferView = function(componentDatatype, buffer, byteOffset, length) {
if (!defined(componentDatatype)) {
throw new DeveloperError('componentDatatype is required.');
}
if (!defined(buffer)) {
throw new DeveloperError('buffer is required.');
}
byteOffset = defaultValue(byteOffset, 0);
length = defaultValue(length, (buffer.byteLength - byteOffset) / ComponentDatatype.getSizeInBytes(componentDatatype));
switch (componentDatatype) {
case ComponentDatatype.BYTE:
return new Int8Array(buffer, byteOffset, length);
case ComponentDatatype.UNSIGNED_BYTE:
return new Uint8Array(buffer, byteOffset, length);
case ComponentDatatype.SHORT:
return new Int16Array(buffer, byteOffset, length);
case ComponentDatatype.UNSIGNED_SHORT:
return new Uint16Array(buffer, byteOffset, length);
case ComponentDatatype.FLOAT:
return new Float32Array(buffer, byteOffset, length);
case ComponentDatatype.DOUBLE:
return new Float64Array(buffer, byteOffset, length);
default:
throw new DeveloperError('componentDatatype is not a valid value.');
}
};
return freezeObject(ComponentDatatype);
});
/*global define*/
define('Core/GeometryType',[
'./freezeObject'
], function(
freezeObject) {
"use strict";
/**
* @private
*/
var GeometryType = {
NONE : 0,
TRIANGLES : 1,
LINES : 2,
POLYLINES : 3
};
return freezeObject(GeometryType);
});
/*global define*/
define('Core/PrimitiveType',[
'./freezeObject'
], function(
freezeObject) {
"use strict";
/**
* The type of a geometric primitive, i.e., points, lines, and triangles.
*
* @namespace
* @alias PrimitiveType
*/
var PrimitiveType = {
/**
* 0x0000. Points primitive where each vertex (or index) is a separate point.
*
* @type {Number}
* @constant
*/
POINTS : 0x0000,
/**
* 0x0001. Lines primitive where each two vertices (or indices) is a line segment. Line segments are not necessarily connected.
*
* @type {Number}
* @constant
*/
LINES : 0x0001,
/**
* 0x0002. Line loop primitive where each vertex (or index) after the first connects a line to
* the previous vertex, and the last vertex implicitly connects to the first.
*
* @type {Number}
* @constant
*/
LINE_LOOP : 0x0002,
/**
* 0x0003. Line strip primitive where each vertex (or index) after the first connects a line to the previous vertex.
*
* @type {Number}
* @constant
*/
LINE_STRIP : 0x0003,
/**
* 0x0004. Triangles primitive where each three vertices (or indices) is a triangle. Triangles do not necessarily share edges.
*
* @type {Number}
* @constant
*/
TRIANGLES : 0x0004,
/**
* 0x0005. Triangle strip primitive where each vertex (or index) after the first two connect to
* the previous two vertices forming a triangle. For example, this can be used to model a wall.
*
* @type {Number}
* @constant
*/
TRIANGLE_STRIP : 0x0005,
/**
* 0x0006. Triangle fan primitive where each vertex (or index) after the first two connect to
* the previous vertex and the first vertex forming a triangle. For example, this can be used
* to model a cone or circle.
*
* @type {Number}
* @constant
*/
TRIANGLE_FAN : 0x0006,
/**
* @private
*/
validate : function(primitiveType) {
return primitiveType === PrimitiveType.POINTS ||
primitiveType === PrimitiveType.LINES ||
primitiveType === PrimitiveType.LINE_LOOP ||
primitiveType === PrimitiveType.LINE_STRIP ||
primitiveType === PrimitiveType.TRIANGLES ||
primitiveType === PrimitiveType.TRIANGLE_STRIP ||
primitiveType === PrimitiveType.TRIANGLE_FAN;
}
};
return freezeObject(PrimitiveType);
});
/*global define*/
define('Core/Geometry',[
'./defaultValue',
'./defined',
'./DeveloperError',
'./GeometryType',
'./PrimitiveType'
], function(
defaultValue,
defined,
DeveloperError,
GeometryType,
PrimitiveType) {
"use strict";
/**
* A geometry representation with attributes forming vertices and optional index data
* defining primitives. Geometries and an {@link Appearance}, which describes the shading,
* can be assigned to a {@link Primitive} for visualization. A <code>Primitive</code> can
* be created from many heterogeneous - in many cases - geometries for performance.
* <p>
* Geometries can be transformed and optimized using functions in {@link GeometryPipeline}.
* </p>
*
* @alias Geometry
* @constructor
*
* @param {Object} options Object with the following properties:
* @param {GeometryAttributes} options.attributes Attributes, which make up the geometry's vertices.
* @param {PrimitiveType} [options.primitiveType=PrimitiveType.TRIANGLES] The type of primitives in the geometry.
* @param {Uint16Array|Uint32Array} [options.indices] Optional index data that determines the primitives in the geometry.
* @param {BoundingSphere} [options.boundingSphere] An optional bounding sphere that fully enclosed the geometry.
*
* @see PolygonGeometry
* @see RectangleGeometry
* @see EllipseGeometry
* @see CircleGeometry
* @see WallGeometry
* @see SimplePolylineGeometry
* @see BoxGeometry
* @see EllipsoidGeometry
*
* @demo {@link http://cesiumjs.org/Cesium/Apps/Sandcastle/index.html?src=Geometry%20and%20Appearances.html|Geometry and Appearances Demo}
*
* @example
* // Create geometry with a position attribute and indexed lines.
* var positions = new Float64Array([
* 0.0, 0.0, 0.0,
* 7500000.0, 0.0, 0.0,
* 0.0, 7500000.0, 0.0
* ]);
*
* var geometry = new Cesium.Geometry({
* attributes : {
* position : new Cesium.GeometryAttribute({
* componentDatatype : Cesium.ComponentDatatype.DOUBLE,
* componentsPerAttribute : 3,
* values : positions
* })
* },
* indices : new Uint16Array([0, 1, 1, 2, 2, 0]),
* primitiveType : Cesium.PrimitiveType.LINES,
* boundingSphere : Cesium.BoundingSphere.fromVertices(positions)
* });
*/
var Geometry = function(options) {
options = defaultValue(options, defaultValue.EMPTY_OBJECT);
if (!defined(options.attributes)) {
throw new DeveloperError('options.attributes is required.');
}
/**
* Attributes, which make up the geometry's vertices. Each property in this object corresponds to a
* {@link GeometryAttribute} containing the attribute's data.
* <p>
* Attributes are always stored non-interleaved in a Geometry.
* </p>
* <p>
* There are reserved attribute names with well-known semantics. The following attributes
* are created by a Geometry (depending on the provided {@link VertexFormat}.
* <ul>
* <li><code>position</code> - 3D vertex position. 64-bit floating-point (for precision). 3 components per attribute. See {@link VertexFormat#position}.</li>
* <li><code>normal</code> - Normal (normalized), commonly used for lighting. 32-bit floating-point. 3 components per attribute. See {@link VertexFormat#normal}.</li>
* <li><code>st</code> - 2D texture coordinate. 32-bit floating-point. 2 components per attribute. See {@link VertexFormat#st}.</li>
* <li><code>binormal</code> - Binormal (normalized), used for tangent-space effects like bump mapping. 32-bit floating-point. 3 components per attribute. See {@link VertexFormat#binormal}.</li>
* <li><code>tangent</code> - Tangent (normalized), used for tangent-space effects like bump mapping. 32-bit floating-point. 3 components per attribute. See {@link VertexFormat#tangent}.</li>
* </ul>
* </p>
* <p>
* The following attribute names are generally not created by a Geometry, but are added
* to a Geometry by a {@link Primitive} or {@link GeometryPipeline} functions to prepare
* the geometry for rendering.
* <ul>
* <li><code>position3DHigh</code> - High 32 bits for encoded 64-bit position computed with {@link GeometryPipeline.encodeAttribute}. 32-bit floating-point. 4 components per attribute.</li>
* <li><code>position3DLow</code> - Low 32 bits for encoded 64-bit position computed with {@link GeometryPipeline.encodeAttribute}. 32-bit floating-point. 4 components per attribute.</li>
* <li><code>position3DHigh</code> - High 32 bits for encoded 64-bit 2D (Columbus view) position computed with {@link GeometryPipeline.encodeAttribute}. 32-bit floating-point. 4 components per attribute.</li>
* <li><code>position2DLow</code> - Low 32 bits for encoded 64-bit 2D (Columbus view) position computed with {@link GeometryPipeline.encodeAttribute}. 32-bit floating-point. 4 components per attribute.</li>
* <li><code>color</code> - RGBA color (normalized) usually from {@link GeometryInstance#color}. 32-bit floating-point. 4 components per attribute.</li>
* <li><code>pickColor</code> - RGBA color used for picking. 32-bit floating-point. 4 components per attribute.</li>
* </ul>
* </p>
*
* @type GeometryAttributes
*
* @default undefined
*
* @see GeometryAttribute
* @see VertexFormat
*
* @example
* geometry.attributes.position = new Cesium.GeometryAttribute({
* componentDatatype : Cesium.ComponentDatatype.FLOAT,
* componentsPerAttribute : 3,
* values : new Float32Array()
* });
*/
this.attributes = options.attributes;
/**
* Optional index data that - along with {@link Geometry#primitiveType} -
* determines the primitives in the geometry.
*
* @type Array
*
* @default undefined
*/
this.indices = options.indices;
/**
* The type of primitives in the geometry. This is most often {@link PrimitiveType.TRIANGLES},
* but can varying based on the specific geometry.
*
* @type PrimitiveType
*
* @default undefined
*/
this.primitiveType = defaultValue(options.primitiveType, PrimitiveType.TRIANGLES);
/**
* An optional bounding sphere that fully encloses the geometry. This is
* commonly used for culling.
*
* @type BoundingSphere
*
* @default undefined
*/
this.boundingSphere = options.boundingSphere;
/**
* @private
*/
this.geometryType = defaultValue(options.geometryType, GeometryType.NONE);
/**
* @private
*/
this.boundingSphereCV = undefined;
};
/**
* Computes the number of vertices in a geometry. The runtime is linear with
* respect to the number of attributes in a vertex, not the number of vertices.
*
* @param {Cartesian3} geometry The geometry.
* @returns {Number} The number of vertices in the geometry.
*
* @example
* var numVertices = Cesium.Geometry.computeNumberOfVertices(geometry);
*/
Geometry.computeNumberOfVertices = function(geometry) {
if (!defined(geometry)) {
throw new DeveloperError('geometry is required.');
}
var numberOfVertices = -1;
for ( var property in geometry.attributes) {
if (geometry.attributes.hasOwnProperty(property) &&
defined(geometry.attributes[property]) &&
defined(geometry.attributes[property].values)) {
var attribute = geometry.attributes[property];
var num = attribute.values.length / attribute.componentsPerAttribute;
if ((numberOfVertices !== num) && (numberOfVertices !== -1)) {
throw new DeveloperError('All attribute lists must have the same number of attributes.');
}
numberOfVertices = num;
}
}
return numberOfVertices;
};
return Geometry;
});
/*global define*/
define('Core/GeometryAttribute',[
'./defaultValue',
'./defined',
'./DeveloperError'
], function(
defaultValue,
defined,
DeveloperError) {
"use strict";
/**
* Values and type information for geometry attributes. A {@link Geometry}
* generally contains one or more attributes. All attributes together form
* the geometry's vertices.
*
* @alias GeometryAttribute
* @constructor
*
* @param {Object} [options] Object with the following properties:
* @param {ComponentDatatype} [options.componentDatatype] The datatype of each component in the attribute, e.g., individual elements in values.
* @param {Number} [options.componentsPerAttribute] A number between 1 and 4 that defines the number of components in an attributes.
* @param {Boolean} [options.normalize=false] When <code>true</code> and <code>componentDatatype</code> is an integer format, indicate that the components should be mapped to the range [0, 1] (unsigned) or [-1, 1] (signed) when they are accessed as floating-point for rendering.
* @param {Number[]} [options.values] The values for the attributes stored in a typed array.
*
* @exception {DeveloperError} options.componentsPerAttribute must be between 1 and 4.
*
* @see Geometry
*
* @example
* var geometry = new Cesium.Geometry({
* attributes : {
* position : new Cesium.GeometryAttribute({
* componentDatatype : Cesium.ComponentDatatype.FLOAT,
* componentsPerAttribute : 3,
* values : [
* 0.0, 0.0, 0.0,
* 7500000.0, 0.0, 0.0,
* 0.0, 7500000.0, 0.0
* ]
* })
* },
* primitiveType : Cesium.PrimitiveType.LINE_LOOP
* });
*/
var GeometryAttribute = function(options) {
options = defaultValue(options, defaultValue.EMPTY_OBJECT);
if (!defined(options.componentDatatype)) {
throw new DeveloperError('options.componentDatatype is required.');
}
if (!defined(options.componentsPerAttribute)) {
throw new DeveloperError('options.componentsPerAttribute is required.');
}
if (options.componentsPerAttribute < 1 || options.componentsPerAttribute > 4) {
throw new DeveloperError('options.componentsPerAttribute must be between 1 and 4.');
}
if (!defined(options.values)) {
throw new DeveloperError('options.values is required.');
}
/**
* The datatype of each component in the attribute, e.g., individual elements in
* {@link GeometryAttribute#values}.
*
* @type ComponentDatatype
*
* @default undefined
*/
this.componentDatatype = options.componentDatatype;
/**
* A number between 1 and 4 that defines the number of components in an attributes.
* For example, a position attribute with x, y, and z components would have 3 as
* shown in the code example.
*
* @type Number
*
* @default undefined
*
* @example
* attribute.componentDatatype : Cesium.ComponentDatatype.FLOAT,
* attribute.componentsPerAttribute : 3,
* attribute.values = new Float32Array([
* 0.0, 0.0, 0.0,
* 7500000.0, 0.0, 0.0,
* 0.0, 7500000.0, 0.0
* ]);
*/
this.componentsPerAttribute = options.componentsPerAttribute;
/**
* When <code>true</code> and <code>componentDatatype</code> is an integer format,
* indicate that the components should be mapped to the range [0, 1] (unsigned)
* or [-1, 1] (signed) when they are accessed as floating-point for rendering.
* <p>
* This is commonly used when storing colors using {@link ComponentDatatype.UNSIGNED_BYTE}.
* </p>
*
* @type Boolean
*
* @default false
*
* @example
* attribute.componentDatatype : Cesium.ComponentDatatype.UNSIGNED_BYTE,
* attribute.componentsPerAttribute : 4,
* attribute.normalize = true;
* attribute.values = new Uint8Array([
* Cesium.Color.floatToByte(color.red)
* Cesium.Color.floatToByte(color.green)
* Cesium.Color.floatToByte(color.blue)
* Cesium.Color.floatToByte(color.alpha)
* ]);
*/
this.normalize = defaultValue(options.normalize, false);
/**
* The values for the attributes stored in a typed array. In the code example,
* every three elements in <code>values</code> defines one attributes since
* <code>componentsPerAttribute</code> is 3.
*
* @type Array
*
* @default undefined
*
* @example
* attribute.componentDatatype : Cesium.ComponentDatatype.FLOAT,
* attribute.componentsPerAttribute : 3,
* attribute.values = new Float32Array([
* 0.0, 0.0, 0.0,
* 7500000.0, 0.0, 0.0,
* 0.0, 7500000.0, 0.0
* ]);
*/
this.values = options.values;
};
return GeometryAttribute;
});
/*global define*/
define('Core/GeometryAttributes',[
'./defaultValue'
], function(
defaultValue) {
"use strict";
/**
* Attributes, which make up a geometry's vertices. Each property in this object corresponds to a
* {@link GeometryAttribute} containing the attribute's data.
* <p>
* Attributes are always stored non-interleaved in a Geometry.
* </p>
*
* @alias GeometryAttributes
* @constructor
*/
var GeometryAttributes = function(options) {
options = defaultValue(options, defaultValue.EMPTY_OBJECT);
/**
* The 3D position attribute.
* <p>
* 64-bit floating-point (for precision). 3 components per attribute.
* </p>
*
* @type GeometryAttribute
*
* @default undefined
*/
this.position = options.position;
/**
* The normal attribute (normalized), which is commonly used for lighting.
* <p>
* 32-bit floating-point. 3 components per attribute.
* </p>
*
* @type GeometryAttribute
*
* @default undefined
*/
this.normal = options.normal;
/**
* The 2D texture coordinate attribute.
* <p>
* 32-bit floating-point. 2 components per attribute
* </p>
*
* @type GeometryAttribute
*
* @default undefined
*/
this.st = options.st;
/**
* The binormal attribute (normalized), which is used for tangent-space effects like bump mapping.
* <p>
* 32-bit floating-point. 3 components per attribute.
* </p>
*
* @type GeometryAttribute
*
* @default undefined
*/
this.binormal = options.binormal;
/**
* The tangent attribute (normalized), which is used for tangent-space effects like bump mapping.
* <p>
* 32-bit floating-point. 3 components per attribute.
* </p>
*
* @type GeometryAttribute
*
* @default undefined
*/
this.tangent = options.tangent;
/**
* The color attribute.
* <p>
* 8-bit unsigned integer. 4 components per attribute.
* </p>
*
* @type GeometryAttribute
*
* @default undefined
*/
this.color = options.color;
};
return GeometryAttributes;
});
/*global define*/
define('Core/IndexDatatype',[
'./defined',
'./DeveloperError',
'./freezeObject',
'./Math'
], function(
defined,
DeveloperError,
freezeObject,
CesiumMath) {
"use strict";
/**
* Constants for WebGL index datatypes. These corresponds to the
* <code>type</code> parameter of {@link http://www.khronos.org/opengles/sdk/docs/man/xhtml/glDrawElements.xml|drawElements}.
*
* @namespace
* @alias IndexDatatype
*/
var IndexDatatype = {
/**
* 0x1401. 8-bit unsigned byte corresponding to <code>UNSIGNED_BYTE</code> and the type
* of an element in <code>Uint8Array</code>.
*
* @type {Number}
* @constant
*/
UNSIGNED_BYTE : 0x1401,
/**
* 0x1403. 16-bit unsigned short corresponding to <code>UNSIGNED_SHORT</code> and the type
* of an element in <code>Uint16Array</code>.
*
* @type {Number}
* @constant
*/
UNSIGNED_SHORT : 0x1403,
/**
* 0x1405. 32-bit unsigned int corresponding to <code>UNSIGNED_INT</code> and the type
* of an element in <code>Uint32Array</code>.
*
* @type {Number}
* @constant
*/
UNSIGNED_INT : 0x1405
};
/**
* Returns the size, in bytes, of the corresponding datatype.
*
* @param {IndexDatatype} indexDatatype The index datatype to get the size of.
* @returns {Number} The size in bytes.
*
* @example
* // Returns 2
* var size = Cesium.IndexDatatype.getSizeInBytes(Cesium.IndexDatatype.UNSIGNED_SHORT);
*/
IndexDatatype.getSizeInBytes = function(indexDatatype) {
switch(indexDatatype) {
case IndexDatatype.UNSIGNED_BYTE:
return Uint8Array.BYTES_PER_ELEMENT;
case IndexDatatype.UNSIGNED_SHORT:
return Uint16Array.BYTES_PER_ELEMENT;
case IndexDatatype.UNSIGNED_INT:
return Uint32Array.BYTES_PER_ELEMENT;
}
throw new DeveloperError('indexDatatype is required and must be a valid IndexDatatype constant.');
};
/**
* Validates that the provided index datatype is a valid {@link IndexDatatype}.
*
* @param {IndexDatatype} indexDatatype The index datatype to validate.
* @returns {Boolean} <code>true</code> if the provided index datatype is a valid value; otherwise, <code>false</code>.
*
* @example
* if (!Cesium.IndexDatatype.validate(indexDatatype)) {
* throw new Cesium.DeveloperError('indexDatatype must be a valid value.');
* }
*/
IndexDatatype.validate = function(indexDatatype) {
return defined(indexDatatype) &&
(indexDatatype === IndexDatatype.UNSIGNED_BYTE ||
indexDatatype === IndexDatatype.UNSIGNED_SHORT ||
indexDatatype === IndexDatatype.UNSIGNED_INT);
};
/**
* Creates a typed array that will store indices, using either <code><Uint16Array</code>
* or <code>Uint32Array</code> depending on the number of vertices.
*
* @param {Number} numberOfVertices Number of vertices that the indices will reference.
* @param {Any} indicesLengthOrArray Passed through to the typed array constructor.
* @returns {Uint16Aray|Uint32Array} A <code>Uint16Array</code> or <code>Uint32Array</code> constructed with <code>indicesLengthOrArray</code>.
*
* @example
* this.indices = Cesium.IndexDatatype.createTypedArray(positions.length / 3, numberOfIndices);
*/
IndexDatatype.createTypedArray = function(numberOfVertices, indicesLengthOrArray) {
if (!defined(numberOfVertices)) {
throw new DeveloperError('numberOfVertices is required.');
}
if (numberOfVertices > CesiumMath.SIXTY_FOUR_KILOBYTES) {
return new Uint32Array(indicesLengthOrArray);
}
return new Uint16Array(indicesLengthOrArray);
};
/**
* Creates a typed array from a source array buffer. The resulting typed array will store indices, using either <code><Uint16Array</code>
* or <code>Uint32Array</code> depending on the number of vertices.
*
* @param {Number} numberOfVertices Number of vertices that the indices will reference.
* @param {ArrayBuffer} sourceArray Passed through to the typed array constructor.
* @param {byteOffset} byteOffset Passed through to the typed array constructor.
* @param {length} length Passed through to the typed array constructor.
* @returns {Uint16Aray|Uint32Array} A <code>Uint16Array</code> or <code>Uint32Array</code> constructed with <code>sourceArray</code>, <code>byteOffset</code>, and <code>length</code>.
*
*/
IndexDatatype.createTypedArrayFromArrayBuffer = function(numberOfVertices, sourceArray, byteOffset, length) {
if (!defined(numberOfVertices)) {
throw new DeveloperError('numberOfVertices is required.');
}
if (!defined(sourceArray)) {
throw new DeveloperError('sourceArray is required.');
}
if (!defined(byteOffset)) {
throw new DeveloperError('byteOffset is required.');
}
if (numberOfVertices > CesiumMath.SIXTY_FOUR_KILOBYTES) {
return new Uint32Array(sourceArray, byteOffset, length);
}
return new Uint16Array(sourceArray, byteOffset, length);
};
return freezeObject(IndexDatatype);
});
/*global define*/
define('Core/VertexFormat',[
'./defaultValue',
'./defined',
'./DeveloperError',
'./freezeObject'
], function(
defaultValue,
defined,
DeveloperError,
freezeObject) {
"use strict";
/**
* A vertex format defines what attributes make up a vertex. A VertexFormat can be provided
* to a {@link Geometry} to request that certain properties be computed, e.g., just position,
* position and normal, etc.
*
* @param {Object} [options] An object with boolean properties corresponding to VertexFormat properties as shown in the code example.
*
* @alias VertexFormat
* @constructor
*
* @example
* // Create a vertex format with position and 2D texture coordinate attributes.
* var format = new Cesium.VertexFormat({
* position : true,
* st : true
* });
*
* @see Geometry#attributes
* @see Packable
*/
var VertexFormat = function(options) {
options = defaultValue(options, defaultValue.EMPTY_OBJECT);
/**
* When <code>true</code>, the vertex has a 3D position attribute.
* <p>
* 64-bit floating-point (for precision). 3 components per attribute.
* </p>
*
* @type Boolean
*
* @default false
*/
this.position = defaultValue(options.position, false);
/**
* When <code>true</code>, the vertex has a normal attribute (normalized), which is commonly used for lighting.
* <p>
* 32-bit floating-point. 3 components per attribute.
* </p>
*
* @type Boolean
*
* @default false
*/
this.normal = defaultValue(options.normal, false);
/**
* When <code>true</code>, the vertex has a 2D texture coordinate attribute.
* <p>
* 32-bit floating-point. 2 components per attribute
* </p>
*
* @type Boolean
*
* @default false
*/
this.st = defaultValue(options.st, false);
/**
* When <code>true</code>, the vertex has a binormal attribute (normalized), which is used for tangent-space effects like bump mapping.
* <p>
* 32-bit floating-point. 3 components per attribute.
* </p>
*
* @type Boolean
*
* @default false
*/
this.binormal = defaultValue(options.binormal, false);
/**
* When <code>true</code>, the vertex has a tangent attribute (normalized), which is used for tangent-space effects like bump mapping.
* <p>
* 32-bit floating-point. 3 components per attribute.
* </p>
*
* @type Boolean
*
* @default false
*/
this.tangent = defaultValue(options.tangent, false);
/**
* When <code>true</code>, the vertex has an RGB color attribute.
* <p>
* 8-bit unsigned byte. 3 components per attribute.
* </p>
*
* @type Boolean
*
* @default false
*/
this.color = defaultValue(options.color, false);
};
/**
* An immutable vertex format with only a position attribute.
*
* @type {VertexFormat}
* @constant
*
* @see VertexFormat#position
*/
VertexFormat.POSITION_ONLY = freezeObject(new VertexFormat({
position : true
}));
/**
* An immutable vertex format with position and normal attributes.
* This is compatible with per-instance color appearances like {@link PerInstanceColorAppearance}.
*
* @type {VertexFormat}
* @constant
*
* @see VertexFormat#position
* @see VertexFormat#normal
*/
VertexFormat.POSITION_AND_NORMAL = freezeObject(new VertexFormat({
position : true,
normal : true
}));
/**
* An immutable vertex format with position, normal, and st attributes.
* This is compatible with {@link MaterialAppearance} when {@link MaterialAppearance#materialSupport}
* is <code>TEXTURED/code>.
*
* @type {VertexFormat}
* @constant
*
* @see VertexFormat#position
* @see VertexFormat#normal
* @see VertexFormat#st
*/
VertexFormat.POSITION_NORMAL_AND_ST = freezeObject(new VertexFormat({
position : true,
normal : true,
st : true
}));
/**
* An immutable vertex format with position and st attributes.
* This is compatible with {@link EllipsoidSurfaceAppearance}.
*
* @type {VertexFormat}
* @constant
*
* @see VertexFormat#position
* @see VertexFormat#st
*/
VertexFormat.POSITION_AND_ST = freezeObject(new VertexFormat({
position : true,
st : true
}));
/**
* An immutable vertex format with position and color attributes.
*
* @type {VertexFormat}
* @constant
*
* @see VertexFormat#position
* @see VertexFormat#color
*/
VertexFormat.POSITION_AND_COLOR = freezeObject(new VertexFormat({
position : true,
color : true
}));
/**
* An immutable vertex format with well-known attributes: position, normal, st, binormal, and tangent.
*
* @type {VertexFormat}
* @constant
*
* @see VertexFormat#position
* @see VertexFormat#normal
* @see VertexFormat#st
* @see VertexFormat#binormal
* @see VertexFormat#tangent
*/
VertexFormat.ALL = freezeObject(new VertexFormat({
position : true,
normal : true,
st : true,
binormal : true,
tangent : true
}));
/**
* An immutable vertex format with position, normal, and st attributes.
* This is compatible with most appearances and materials; however
* normal and st attributes are not always required. When this is
* known in advance, another <code>VertexFormat</code> should be used.
*
* @type {VertexFormat}
* @constant
*
* @see VertexFormat#position
* @see VertexFormat#normal
*/
VertexFormat.DEFAULT = VertexFormat.POSITION_NORMAL_AND_ST;
/**
* The number of elements used to pack the object into an array.
* @type {Number}
*/
VertexFormat.packedLength = 6;
/**
* Stores the provided instance into the provided array.
* @function
*
* @param {Object} value The value to pack.
* @param {Number[]} array The array to pack into.
* @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
*/
VertexFormat.pack = function(value, array, startingIndex) {
if (!defined(value)) {
throw new DeveloperError('value is required');
}
if (!defined(array)) {
throw new DeveloperError('array is required');
}
startingIndex = defaultValue(startingIndex, 0);
array[startingIndex++] = value.position ? 1.0 : 0.0;
array[startingIndex++] = value.normal ? 1.0 : 0.0;
array[startingIndex++] = value.st ? 1.0 : 0.0;
array[startingIndex++] = value.binormal ? 1.0 : 0.0;
array[startingIndex++] = value.tangent ? 1.0 : 0.0;
array[startingIndex++] = value.color ? 1.0 : 0.0;
};
/**
* Retrieves an instance from a packed array.
*
* @param {Number[]} array The packed array.
* @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
* @param {VertexFormat} [result] The object into which to store the result.
*/
VertexFormat.unpack = function(array, startingIndex, result) {
if (!defined(array)) {
throw new DeveloperError('array is required');
}
startingIndex = defaultValue(startingIndex, 0);
if (!defined(result)) {
result = new VertexFormat();
}
result.position = array[startingIndex++] === 1.0;
result.normal = array[startingIndex++] === 1.0;
result.st = array[startingIndex++] === 1.0;
result.binormal = array[startingIndex++] === 1.0;
result.tangent = array[startingIndex++] === 1.0;
result.color = array[startingIndex++] === 1.0;
return result;
};
/**
* Duplicates a VertexFormat instance.
*
* @param {VertexFormat} cartesian The vertex format to duplicate.
* @param {VertexFormat} [result] The object onto which to store the result.
* @returns {VertexFormat} The modified result parameter or a new VertexFormat instance if one was not provided. (Returns undefined if vertexFormat is undefined)
*/
VertexFormat.clone = function(vertexFormat, result) {
if (!defined(vertexFormat)) {
return undefined;
}
if (!defined(result)) {
result = new VertexFormat();
}
result.position = vertexFormat.position;
result.normal = vertexFormat.normal;
result.st = vertexFormat.st;
result.binormal = vertexFormat.binormal;
result.tangent = vertexFormat.tangent;
result.color = vertexFormat.color;
return result;
};
return VertexFormat;
});
/*global define*/
define('Core/EllipsoidGeometry',[
'./BoundingSphere',
'./Cartesian2',
'./Cartesian3',
'./ComponentDatatype',
'./defaultValue',
'./defined',
'./DeveloperError',
'./Ellipsoid',
'./Geometry',
'./GeometryAttribute',
'./GeometryAttributes',
'./IndexDatatype',
'./Math',
'./PrimitiveType',
'./VertexFormat'
], function(
BoundingSphere,
Cartesian2,
Cartesian3,
ComponentDatatype,
defaultValue,
defined,
DeveloperError,
Ellipsoid,
Geometry,
GeometryAttribute,
GeometryAttributes,
IndexDatatype,
CesiumMath,
PrimitiveType,
VertexFormat) {
"use strict";
var scratchPosition = new Cartesian3();
var scratchNormal = new Cartesian3();
var scratchTangent = new Cartesian3();
var scratchBinormal = new Cartesian3();
var scratchNormalST = new Cartesian3();
var defaultRadii = new Cartesian3(1.0, 1.0, 1.0);
var cos = Math.cos;
var sin = Math.sin;
/**
* A description of an ellipsoid centered at the origin.
*
* @alias EllipsoidGeometry
* @constructor
*
* @param {Object} [options] Object with the following properties:
* @param {Cartesian3} [options.radii=Cartesian3(1.0, 1.0, 1.0)] The radii of the ellipsoid in the x, y, and z directions.
* @param {Number} [options.stackPartitions=64] The number of times to partition the ellipsoid into stacks.
* @param {Number} [options.slicePartitions=64] The number of times to partition the ellipsoid into radial slices.
* @param {VertexFormat} [options.vertexFormat=VertexFormat.DEFAULT] The vertex attributes to be computed.
*
* @exception {DeveloperError} options.slicePartitions cannot be less than three.
* @exception {DeveloperError} options.stackPartitions cannot be less than three.
*
* @see EllipsoidGeometry#createGeometry
*
* @demo {@link http://cesiumjs.org/Cesium/Apps/Sandcastle/index.html?src=Ellipsoid.html|Cesium Sandcastle Ellipsoid Demo}
*
* @example
* var ellipsoid = new Cesium.EllipsoidGeometry({
* vertexFormat : Cesium.VertexFormat.POSITION_ONLY,
* radii : new Cesium.Cartesian3(1000000.0, 500000.0, 500000.0)
* });
* var geometry = Cesium.EllipsoidGeometry.createGeometry(ellipsoid);
*/
var EllipsoidGeometry = function(options) {
options = defaultValue(options, defaultValue.EMPTY_OBJECT);
var radii = defaultValue(options.radii, defaultRadii);
var stackPartitions = defaultValue(options.stackPartitions, 64);
var slicePartitions = defaultValue(options.slicePartitions, 64);
var vertexFormat = defaultValue(options.vertexFormat, VertexFormat.DEFAULT);
if (slicePartitions < 3) {
throw new DeveloperError ('options.slicePartitions cannot be less than three.');
}
if (stackPartitions < 3) {
throw new DeveloperError('options.stackPartitions cannot be less than three.');
}
this._radii = Cartesian3.clone(radii);
this._stackPartitions = stackPartitions;
this._slicePartitions = slicePartitions;
this._vertexFormat = VertexFormat.clone(vertexFormat);
this._workerName = 'createEllipsoidGeometry';
};
/**
* The number of elements used to pack the object into an array.
* @type {Number}
*/
EllipsoidGeometry.packedLength = Cartesian3.packedLength + VertexFormat.packedLength + 2;
/**
* Stores the provided instance into the provided array.
* @function
*
* @param {Object} value The value to pack.
* @param {Number[]} array The array to pack into.
* @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
*/
EllipsoidGeometry.pack = function(value, array, startingIndex) {
if (!defined(value)) {
throw new DeveloperError('value is required');
}
if (!defined(array)) {
throw new DeveloperError('array is required');
}
startingIndex = defaultValue(startingIndex, 0);
Cartesian3.pack(value._radii, array, startingIndex);
startingIndex += Cartesian3.packedLength;
VertexFormat.pack(value._vertexFormat, array, startingIndex);
startingIndex += VertexFormat.packedLength;
array[startingIndex++] = value._stackPartitions;
array[startingIndex] = value._slicePartitions;
};
var scratchRadii = new Cartesian3();
var scratchVertexFormat = new VertexFormat();
var scratchOptions = {
radii : scratchRadii,
vertexFormat : scratchVertexFormat,
stackPartitions : undefined,
slicePartitions : undefined
};
/**
* Retrieves an instance from a packed array.
*
* @param {Number[]} array The packed array.
* @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
* @param {EllipsoidGeometry} [result] The object into which to store the result.
*/
EllipsoidGeometry.unpack = function(array, startingIndex, result) {
if (!defined(array)) {
throw new DeveloperError('array is required');
}
startingIndex = defaultValue(startingIndex, 0);
var radii = Cartesian3.unpack(array, startingIndex, scratchRadii);
startingIndex += Cartesian3.packedLength;
var vertexFormat = VertexFormat.unpack(array, startingIndex, scratchVertexFormat);
startingIndex += VertexFormat.packedLength;
var stackPartitions = array[startingIndex++];
var slicePartitions = array[startingIndex];
if (!defined(result)) {
scratchOptions.stackPartitions = stackPartitions;
scratchOptions.slicePartitions = slicePartitions;
return new EllipsoidGeometry(scratchOptions);
}
result._radii = Cartesian3.clone(radii, result._radii);
result._vertexFormat = VertexFormat.clone(vertexFormat, result._vertexFormat);
result._stackPartitions = stackPartitions;
result._slicePartitions = slicePartitions;
return result;
};
/**
* Computes the geometric representation of an ellipsoid, including its vertices, indices, and a bounding sphere.
*
* @param {EllipsoidGeometry} ellipsoidGeometry A description of the ellipsoid.
* @returns {Geometry} The computed vertices and indices.
*/
EllipsoidGeometry.createGeometry = function(ellipsoidGeometry) {
var radii = ellipsoidGeometry._radii;
var ellipsoid = Ellipsoid.fromCartesian3(radii);
var vertexFormat = ellipsoidGeometry._vertexFormat;
// The extra slice and stack are for duplicating points at the x axis and poles.
// We need the texture coordinates to interpolate from (2 * pi - delta) to 2 * pi instead of
// (2 * pi - delta) to 0.
var slicePartitions = ellipsoidGeometry._slicePartitions + 1;
var stackPartitions = ellipsoidGeometry._stackPartitions + 1;
var vertexCount = stackPartitions * slicePartitions;
var positions = new Float64Array(vertexCount * 3);
var numIndices = 6 * (slicePartitions - 1) * (stackPartitions - 1);
var indices = IndexDatatype.createTypedArray(vertexCount, numIndices);
var normals = (vertexFormat.normal) ? new Float32Array(vertexCount * 3) : undefined;
var tangents = (vertexFormat.tangent) ? new Float32Array(vertexCount * 3) : undefined;
var binormals = (vertexFormat.binormal) ? new Float32Array(vertexCount * 3) : undefined;
var st = (vertexFormat.st) ? new Float32Array(vertexCount * 2) : undefined;
var cosTheta = new Array(slicePartitions);
var sinTheta = new Array(slicePartitions);
var i;
var j;
var index = 0;
for (i = 0; i < slicePartitions; i++) {
var theta = CesiumMath.TWO_PI * i / (slicePartitions - 1);
cosTheta[i] = cos(theta);
sinTheta[i] = sin(theta);
// duplicate first point for correct
// texture coordinates at the north pole.
positions[index++] = 0.0;
positions[index++] = 0.0;
positions[index++] = radii.z;
}
for (i = 1; i < stackPartitions - 1; i++) {
var phi = Math.PI * i / (stackPartitions - 1);
var sinPhi = sin(phi);
var xSinPhi = radii.x * sinPhi;
var ySinPhi = radii.y * sinPhi;
var zCosPhi = radii.z * cos(phi);
for (j = 0; j < slicePartitions; j++) {
positions[index++] = cosTheta[j] * xSinPhi;
positions[index++] = sinTheta[j] * ySinPhi;
positions[index++] = zCosPhi;
}
}
for (i = 0; i < slicePartitions; i++) {
// duplicate first point for correct
// texture coordinates at the north pole.
positions[index++] = 0.0;
positions[index++] = 0.0;
positions[index++] = -radii.z;
}
var attributes = new GeometryAttributes();
if (vertexFormat.position) {
attributes.position = new GeometryAttribute({
componentDatatype : ComponentDatatype.DOUBLE,
componentsPerAttribute : 3,
values : positions
});
}
var stIndex = 0;
var normalIndex = 0;
var tangentIndex = 0;
var binormalIndex = 0;
if (vertexFormat.st || vertexFormat.normal || vertexFormat.tangent || vertexFormat.binormal) {
for( i = 0; i < vertexCount; i++) {
var position = Cartesian3.fromArray(positions, i * 3, scratchPosition);
var normal = ellipsoid.geodeticSurfaceNormal(position, scratchNormal);
if (vertexFormat.st) {
var normalST = Cartesian2.negate(normal, scratchNormalST);
// if the point is at or close to the pole, find a point along the same longitude
// close to the xy-plane for the s coordinate.
if (Cartesian2.magnitude(normalST) < CesiumMath.EPSILON6) {
index = (i + slicePartitions * Math.floor(stackPartitions * 0.5)) * 3;
if (index > positions.length) {
index = (i - slicePartitions * Math.floor(stackPartitions * 0.5)) * 3;
}
Cartesian3.fromArray(positions, index, normalST);
ellipsoid.geodeticSurfaceNormal(normalST, normalST);
Cartesian2.negate(normalST, normalST);
}
st[stIndex++] = (Math.atan2(normalST.y, normalST.x) / CesiumMath.TWO_PI) + 0.5;
st[stIndex++] = (Math.asin(normal.z) / Math.PI) + 0.5;
}
if (vertexFormat.normal) {
normals[normalIndex++] = normal.x;
normals[normalIndex++] = normal.y;
normals[normalIndex++] = normal.z;
}
if (vertexFormat.tangent || vertexFormat.binormal) {
var tangent = scratchTangent;
if (i < slicePartitions || i > vertexCount - slicePartitions - 1) {
Cartesian3.cross(Cartesian3.UNIT_X, normal, tangent);
Cartesian3.normalize(tangent, tangent);
} else {
Cartesian3.cross(Cartesian3.UNIT_Z, normal, tangent);
Cartesian3.normalize(tangent, tangent);
}
if (vertexFormat.tangent) {
tangents[tangentIndex++] = tangent.x;
tangents[tangentIndex++] = tangent.y;
tangents[tangentIndex++] = tangent.z;
}
if (vertexFormat.binormal) {
var binormal = Cartesian3.cross(normal, tangent, scratchBinormal);
Cartesian3.normalize(binormal, binormal);
binormals[binormalIndex++] = binormal.x;
binormals[binormalIndex++] = binormal.y;
binormals[binormalIndex++] = binormal.z;
}
}
}
if (vertexFormat.st) {
attributes.st = new GeometryAttribute({
componentDatatype : ComponentDatatype.FLOAT,
componentsPerAttribute : 2,
values : st
});
}
if (vertexFormat.normal) {
attributes.normal = new GeometryAttribute({
componentDatatype : ComponentDatatype.FLOAT,
componentsPerAttribute : 3,
values : normals
});
}
if (vertexFormat.tangent) {
attributes.tangent = new GeometryAttribute({
componentDatatype : ComponentDatatype.FLOAT,
componentsPerAttribute : 3,
values : tangents
});
}
if (vertexFormat.binormal) {
attributes.binormal = new GeometryAttribute({
componentDatatype : ComponentDatatype.FLOAT,
componentsPerAttribute : 3,
values : binormals
});
}
}
index = 0;
for (i = 0; i < stackPartitions; i++) {
var topOffset = i * slicePartitions;
var bottomOffset = (i + 1) * slicePartitions;
for (j = 0; j < slicePartitions - 1; j++) {
indices[index++] = bottomOffset + j;
indices[index++] = bottomOffset + j + 1;
indices[index++] = topOffset + j + 1;
indices[index++] = bottomOffset + j;
indices[index++] = topOffset + j + 1;
indices[index++] = topOffset + j;
}
}
return new Geometry({
attributes : attributes,
indices : indices,
primitiveType : PrimitiveType.TRIANGLES,
boundingSphere : BoundingSphere.fromEllipsoid(ellipsoid)
});
};
return EllipsoidGeometry;
});
/*global define*/
define('Workers/createEllipsoidGeometry',[
'../Core/defined',
'../Core/EllipsoidGeometry'
], function(
defined,
EllipsoidGeometry) {
"use strict";
return function(ellipsoidGeometry, offset) {
if (defined(offset)) {
ellipsoidGeometry = EllipsoidGeometry.unpack(ellipsoidGeometry, offset);
}
return EllipsoidGeometry.createGeometry(ellipsoidGeometry);
};
});
}());
|
/**
* pong.c - Classic Pong implementation on the Amiga
*/
#include <stdio.h>
#include <string.h>
#include <hardware/custom.h>
#include <clib/exec_protos.h>
#include <clib/intuition_protos.h>
#include <clib/graphics_protos.h>
#include <clib/alib_protos.h>
#include <devices/keyboard.h>
#include <devices/input.h>
#include <exec/execbase.h>
#include <graphics/gfxbase.h>
#include <ahpc_registers.h>
#include <SDI/SDI_compiler.h>
#include "../ptplayer/ptplayer.h"
#include <tilesheet.h>
#include "pong_defs.h"
static UWORD __chip coplist[] = {
COP_MOVE(FMODE, 0), // set fetch mode = 0
// sprites first
COP_MOVE(SPR0PTH, 0), COP_MOVE(SPR0PTL, 0),
COP_MOVE(SPR1PTH, 0), COP_MOVE(SPR1PTL, 0),
COP_MOVE(SPR2PTH, 0), COP_MOVE(SPR2PTL, 0),
COP_MOVE(SPR3PTH, 0), COP_MOVE(SPR3PTL, 0),
COP_MOVE(SPR4PTH, 0), COP_MOVE(SPR4PTL, 0),
COP_MOVE(SPR5PTH, 0), COP_MOVE(SPR5PTL, 0),
COP_MOVE(SPR6PTH, 0), COP_MOVE(SPR6PTL, 0),
COP_MOVE(SPR7PTH, 0), COP_MOVE(SPR7PTL, 0),
COP_MOVE(DDFSTRT, DDFSTRT_VALUE),
COP_MOVE(DDFSTOP, DDFSTOP_VALUE),
COP_MOVE(DIWSTRT, DIWSTRT_VALUE),
COP_MOVE(DIWSTOP, DIWSTOP_VALUE_PAL),
COP_MOVE(BPLCON0, BPLCON0_VALUE),
COP_MOVE(BPLCON2, BPLCON2_VALUE),
COP_MOVE(BPL1MOD, 0),
COP_MOVE(BPL2MOD, 0),
// set up the display colors
COP_MOVE(COLOR00, 0x000), COP_MOVE(COLOR01, 0xfff),
COP_MOVE(COLOR02, 0xfff), COP_MOVE(COLOR03, 0xfff),
COP_MOVE(COLOR04, 0xfff), COP_MOVE(COLOR05, 0xfff),
COP_MOVE(COLOR06, 0xfff), COP_MOVE(COLOR07, 0xfff),
COP_MOVE(COLOR08, 0xfff), COP_MOVE(COLOR09, 0xfff),
COP_MOVE(COLOR10, 0xfff), COP_MOVE(COLOR11, 0xfff),
COP_MOVE(COLOR12, 0xfff), COP_MOVE(COLOR13, 0xfff),
COP_MOVE(COLOR14, 0xfff), COP_MOVE(COLOR15, 0xfff),
COP_MOVE(COLOR16, 0xfff), COP_MOVE(COLOR17, 0xfff),
COP_MOVE(COLOR18, 0xfff), COP_MOVE(COLOR19, 0xfff),
COP_MOVE(COLOR20, 0xfff), COP_MOVE(COLOR21, 0xfff),
COP_MOVE(COLOR22, 0xfff), COP_MOVE(COLOR23, 0xfff),
COP_MOVE(COLOR24, 0xfff), COP_MOVE(COLOR25, 0xfff),
COP_MOVE(COLOR26, 0xfff), COP_MOVE(COLOR27, 0xfff),
COP_MOVE(COLOR28, 0xfff), COP_MOVE(COLOR29, 0xfff),
COP_MOVE(COLOR30, 0xfff), COP_MOVE(COLOR31, 0xfff),
COP_MOVE(BPL1PTH, 0), COP_MOVE(BPL1PTL, 0),
COP_WAIT_END,
COP_WAIT_END
};
static volatile ULONG *custom_vposr = (volatile ULONG *) 0xdff004;
static volatile UWORD *custom_clxdat = (volatile UWORD *) 0xdff00e;
// Wait for this position for vertical blank
// translated from http://eab.abime.net/showthread.php?t=51928
static vb_waitpos;
static void wait_vblank()
{
while (((*custom_vposr) & 0x1ff00) != (vb_waitpos<<8)) ;
}
static BOOL init_display(void)
{
LoadView(NULL); // clear display, reset hardware registers
WaitTOF(); // 2 WaitTOFs to wait for 1. long frame and
WaitTOF(); // 2. short frame copper lists to finish (if interlaced)
return (((struct GfxBase *) GfxBase)->DisplayFlags & PAL) == PAL;
}
static void reset_display(void)
{
LoadView(((struct GfxBase *) GfxBase)->ActiView);
WaitTOF();
WaitTOF();
custom.cop1lc = (ULONG) ((struct GfxBase *) GfxBase)->copinit;
RethinkDisplay();
}
static struct Ratr0TileSheet image;
// To handle input
static struct MsgPort *input_mp;
static struct IOStdReq *input_io;
static struct Interrupt handler_info;
// *******************************
// Global game state
// Game objects
struct Paddle {
UWORD x, y;
UWORD __chip *data;
};
struct Ball {
UWORD x, y;
WORD speed_x, speed_y;
UWORD __chip *data;
};
struct PlayerScore {
UWORD score;
UWORD digit0_data[DIGIT_SPRITE_WORDS], digit1_data[DIGIT_SPRITE_WORDS];
};
struct Paddle paddle_l = { PADDLE_L_INIT_X, PADDLE_INIT_Y, paddle_l_data },
paddle_r = { PADDLE_R_INIT_X, PADDLE_INIT_Y, paddle_r_data };
struct Ball ball = { BALL_INIT_X, BALL_INIT_Y, BALL_START_X_SPEED, BALL_START_Y_SPEED, ball_data};
// maximum y-positions (PAL/NTSC)
static UWORD paddle_max_y, ball_max_y;
// Player score
struct PlayerScore __chip player1, player2;
// *******************************
// To handle input
static BYTE error;
static struct MsgPort *kb_mp;
static struct IOStdReq *kb_io;
static UBYTE *kb_matrix;
#define MATRIX_SIZE (16L)
static int init_keyboard_device(void)
{
kb_mp = CreatePort(0, 0);
kb_io = (struct IOStdReq *) CreateExtIO(kb_mp, sizeof(struct IOStdReq));
error = OpenDevice("keyboard.device", 0L, (struct IORequest *) kb_io, 0);
kb_matrix = AllocMem(MATRIX_SIZE, MEMF_PUBLIC|MEMF_CLEAR);
return 1;
}
static void cleanup_keyboard_device(void)
{
if (kb_matrix) FreeMem(kb_matrix, MATRIX_SIZE);
if (kb_io) {
CloseDevice((struct IORequest *) kb_io);
DeleteExtIO((struct IORequest *) kb_io);
}
if (kb_mp) DeletePort(kb_mp);
}
static void read_keyboard(void)
{
kb_io->io_Command = KBD_READMATRIX;
kb_io->io_Data = (APTR) kb_matrix;
kb_io->io_Length = SysBase->LibNode.lib_Version >= 36 ? MATRIX_SIZE : 13;
DoIO((struct IORequest *) kb_io);
}
static int is_keydown(BYTE keycode) {
return kb_matrix[keycode / 8] & (1 << (keycode % 8));
}
static void set_sprite_pos(UWORD *sprite_data, UWORD hstart, UWORD vstart, UWORD vstop)
{
sprite_data[0] = ((vstart & 0xff) << 8) | ((hstart >> 1) & 0xff);
// vstop + high bit of vstart + low bit of hstart
sprite_data[1] = ((vstop & 0xff) << 8) | // vstop 8 low bits
((vstart >> 8) & 1) << 2 | // vstart high bit
((vstop >> 8) & 1) << 1 | // vstop high bit
(hstart & 1) | // hstart low bit
sprite_data[1] & 0x80; // preserve attach bit
}
static void cleanup(void)
{
cleanup_keyboard_device();
ratr0_free_tilesheet_data(&image);
reset_display();
mt_remove_cia(&custom);
}
/**
* Copies the data for a digit to the destination sprite.
*/
static void set_digit(UWORD *sprite, int digit)
{
memcpy(&sprite[2], &digit_data[32 * digit], 4 * 16);
}
/**
* Increments the player's score and updates the display.
*/
static void increment_score(struct PlayerScore *player)
{
player->score++;
set_digit(player->digit0_data, player->score % 10);
set_digit(player->digit1_data, player->score / 10);
}
void reset_ball(BOOL player1_adv)
{
ball.x = BALL_INIT_X;
ball.y = BALL_INIT_Y;
ball.speed_x = player1_adv ? BALL_START_X_SPEED: -BALL_START_X_SPEED;
ball.speed_y = BALL_START_Y_SPEED;
}
void update_paddle_and_ball_positions(void)
{
set_sprite_pos(paddle_l.data, paddle_l.x, paddle_l.y, paddle_l.y + PADDLE_HEIGHT);
set_sprite_pos(paddle_r.data, paddle_r.x, paddle_r.y, paddle_r.y + PADDLE_HEIGHT);
set_sprite_pos(ball.data, ball.x, ball.y, ball.y + BALL_SIZE);
}
/**
* Reads the input and updates the paddle positions.
* Return value: TRUE if the game should exit, FALSE otherwise
*/
BOOL handle_input(void)
{
// now check the keyboard status
read_keyboard();
if (is_keydown(RAW_KEY_ESCAPE)) return TRUE;
if (is_keydown(RAW_KEY_CURSOR_DOWN)) {
paddle_r.y += PADDLE_SPEED;
if (paddle_r.y > paddle_max_y) paddle_r.y = paddle_max_y;
} else if (is_keydown(RAW_KEY_CURSOR_UP)) {
paddle_r.y -= PADDLE_SPEED;
if (paddle_r.y < PADDLE_MIN_Y) paddle_r.y = PADDLE_MIN_Y;
}
if (is_keydown(RAW_KEY_S)) {
paddle_l.y += PADDLE_SPEED;
if (paddle_l.y > paddle_max_y) paddle_l.y = paddle_max_y;
} else if (is_keydown(RAW_KEY_W)) {
paddle_l.y -= PADDLE_SPEED;
if (paddle_l.y < PADDLE_MIN_Y) paddle_l.y = PADDLE_MIN_Y;
}
return FALSE;
}
// Sound effects for PTPlayer
UBYTE __chip beep_data[BEEP_BYTES];
UBYTE __chip buzz_data[BUZZ_BYTES];
static struct SfxStructure beep = { beep_data, BEEP_BYTES / 2, 0, 64, 0, 1};
static struct SfxStructure buzz = { buzz_data, BUZZ_BYTES / 2, 0, 64, 0, 1 };
static void init_sound_system(BOOL is_pal)
{
mt_install_cia(&custom, NULL, is_pal);
FILE *fp = fopen(BEEP_PATH, "r");
fread(beep_data, sizeof(UBYTE), BEEP_BYTES, fp);
fclose(fp);
fp = fopen(BUZZ_PATH, "r");
fread(buzz_data, sizeof(UBYTE), BUZZ_BYTES, fp);
fclose(fp);
beep.sfx_per = buzz.sfx_per = is_pal ? SAMPLE_PERIOD_PAL : SAMPLE_PERIOD_NTSC;
}
static BOOL initialize(void)
{
init_keyboard_device();
BOOL is_pal = init_display();
const char *bgfile = is_pal ? IMG_FILENAME_PAL : IMG_FILENAME_NTSC;
if (!ratr0_read_tilesheet(bgfile, &image)) {
puts("Could not read background image");
cleanup();
return FALSE;
}
init_sound_system(is_pal);
if (is_pal) {
coplist[COPLIST_IDX_DIWSTOP_VALUE] = DIWSTOP_VALUE_PAL;
vb_waitpos = 303;
} else {
coplist[COPLIST_IDX_DIWSTOP_VALUE] = DIWSTOP_VALUE_NTSC;
vb_waitpos = 262;
}
int img_row_bytes = image.header.width / 8;
UBYTE num_colors = 2;
// Set up copper list
// 1. background
ULONG addr = (ULONG) image.imgdata;
coplist[COPLIST_IDX_BPL1PTH_VALUE] = (addr >> 16) & 0xffff;
coplist[COPLIST_IDX_BPL1PTH_VALUE + 2] = addr & 0xffff;
// 2. sprite data pointers
// sprites 0 and 1: paddles, sprite 2: ball
coplist[COPLIST_IDX_SPR0_PTH_VALUE] = (((ULONG) paddle_l_data) >> 16) & 0xffff;
coplist[COPLIST_IDX_SPR0_PTH_VALUE + 2] = ((ULONG) paddle_l_data) & 0xffff;
coplist[COPLIST_IDX_SPR0_PTH_VALUE + 4] = (((ULONG) paddle_r_data) >> 16) & 0xffff;
coplist[COPLIST_IDX_SPR0_PTH_VALUE + 6] = ((ULONG) paddle_r_data) & 0xffff;
coplist[COPLIST_IDX_SPR0_PTH_VALUE + 8] = (((ULONG) ball_data) >> 16) & 0xffff;
coplist[COPLIST_IDX_SPR0_PTH_VALUE + 10] = ((ULONG) ball_data) & 0xffff;
// sprite 3-6: counter
coplist[COPLIST_IDX_SPR0_PTH_VALUE + 12] = (((ULONG) player1.digit0_data) >> 16) & 0xffff;
coplist[COPLIST_IDX_SPR0_PTH_VALUE + 14] = ((ULONG) player1.digit0_data) & 0xffff;
coplist[COPLIST_IDX_SPR0_PTH_VALUE + 16] = (((ULONG) player1.digit1_data) >> 16) & 0xffff;
coplist[COPLIST_IDX_SPR0_PTH_VALUE + 18] = ((ULONG) player1.digit1_data) & 0xffff;
coplist[COPLIST_IDX_SPR0_PTH_VALUE + 20] = (((ULONG) player2.digit0_data) >> 16) & 0xffff;
coplist[COPLIST_IDX_SPR0_PTH_VALUE + 22] = ((ULONG) player2.digit0_data) & 0xffff;
coplist[COPLIST_IDX_SPR0_PTH_VALUE + 24] = (((ULONG) player2.digit1_data) >> 16) & 0xffff;
coplist[COPLIST_IDX_SPR0_PTH_VALUE + 26] = ((ULONG) player2.digit1_data) & 0xffff;
// sprite 7 is unused, initialize with empty
coplist[COPLIST_IDX_SPR0_PTH_VALUE + 28] = (((ULONG) NULL_SPRITE_DATA) >> 16) & 0xffff;
coplist[COPLIST_IDX_SPR0_PTH_VALUE + 30] = ((ULONG) NULL_SPRITE_DATA) & 0xffff;
// and set the sprite position
ball_max_y = is_pal ? BALL_MAX_Y_PAL : BALL_MAX_Y_NTSC;
paddle_max_y = is_pal ? PADDLE_MAX_Y_PAL : PADDLE_MAX_Y_NTSC;
update_paddle_and_ball_positions();
set_sprite_pos(player1.digit0_data, DIGIT_L0_X, DIGIT_Y, DIGIT_Y + DIGIT_HEIGHT);
set_sprite_pos(player1.digit1_data, DIGIT_L1_X, DIGIT_Y, DIGIT_Y + DIGIT_HEIGHT);
set_sprite_pos(player2.digit0_data, DIGIT_R0_X, DIGIT_Y, DIGIT_Y + DIGIT_HEIGHT);
set_sprite_pos(player2.digit1_data, DIGIT_R1_X, DIGIT_Y, DIGIT_Y + DIGIT_HEIGHT);
// SET SPRITE DATA END
set_digit(player1.digit0_data, 0);
set_digit(player1.digit1_data, 0);
set_digit(player2.digit0_data, 0);
set_digit(player2.digit1_data, 0);
// initialize and activate the copper list
custom.cop1lc = (ULONG) coplist;
custom.clxcon = 0x1000; // include both sprite 0 and 1 in collision detection
return TRUE;
}
int main(int argc, char **argv)
{
initialize();
UWORD coll_state = *custom_clxdat; // read to clear
int frames_since_collision = 0;
// the event loop
while (TRUE) {
wait_vblank();
if (handle_input()) break;
ball.x += ball.speed_x;
ball.y += ball.speed_y;
update_paddle_and_ball_positions();
coll_state = *custom_clxdat;
if (ball.x < BALL_MIN_X) {
mt_playfx(&custom, &buzz);
increment_score(&player2);
reset_ball(FALSE);
} else if (ball.x > BALL_MAX_X) {
mt_playfx(&custom, &buzz);
increment_score(&player1);
reset_ball(TRUE);
} else if (ball.y <= BALL_MIN_Y || ball.y >= ball_max_y) {
mt_playfx(&custom, &beep);
ball.speed_y = -ball.speed_y;
} else if (coll_state & 0x200 && frames_since_collision > 10) {
// collision sprite 2 (ball) with 0 or 1 (paddles)
mt_playfx(&custom, &beep);
// where does the ball hit ? hit_y is between 0 and PADDLE_HEIGHT
int hit_y = (ball.y + BALL_SIZE / 2) - (ball.speed_x < 0 ? paddle_l.y : paddle_r.y);
// rel_y is between - PADDLE_HEIGHT / 2 and + PADDLE_HEIGHT / 2
// rel_y > 0 => in the upper part
// rel_y < 0 => in the lower part
int rel_y = PADDLE_HEIGHT / 2 - hit_y;
ball.speed_y = - (rel_y / 3);
ball.speed_x = -ball.speed_x;
frames_since_collision = 0;
}
frames_since_collision++;
}
cleanup();
return 0;
}
|
import { motion } from "framer-motion";
import Link from "next/link";
import React, { useState } from "react";
import CardanoLogo from "../../lib/icons/CardanoLogo";
const gdsEase12 = {
duration: 0.7,
ease: [0.6, 0.01, -0.05, 0.9],
};
export default function LargeCards({ colors, list }) {
return (
<div className="relative">
<div className=" relative flex justify-between">
<div className=" h-12 sm:h-14 top-0 left-0 z-0 ">
<div>
<div
role="button"
className={` relative overflow-hidden text-blue-100 flex flex-nowrap relative group relative flex items-stretch mb-10 `}
>
<Square
className={"w-8 sm:w-10 lg:w-12 xl:w-14 h-12 sm:h-14 z-30 "}
color={colors[0]}
number={list[0].number}
title={list[0].title}
>
<CardanoLogo className="w-8 text-blue-100 mb-3 ml-1" />
</Square>
<Square
className={"w-8 sm:w-10 h-12 sm:h-14"}
color={colors[1]}
number={list[1].number}
title={list[1].title}
/>
<Square
className={"w-8 sm:w-10 h-12 sm:h-14"}
color={colors[2]}
number={list[2].number}
title={list[2].title}
/>
<Square
className={"w-8 sm:w-10 h-12 sm:h-14"}
color={colors[3]}
number={list[3].number}
title={list[3].title}
/>
</div>
</div>
</div>
<div className="hidden lg:block relative z-10 ml-auto p-7 w-1/3 ">
<p>
Cardano Starter Kits are an invitation for you to start learning about how Cardano works. You can use these video explanations and documentation to move at your own pace. When you have questions or feel ready to learn more, we hope you'll let us know.
</p>
</div>
</div>
</div>
);
}
const Square = ({ color, number, title, className, children }) => {
const [localHov, setLocalHov] = useState(false);
return (
<div>
<Link href={`/pbl/csk/csk${number}`}>
<a>
<div>
<motion.div
animate={{
transition: { ...gdsEase12, duration: 0.3 },
y: localHov ? -5 : 0,
}}
layout
className={` grid ${color} z-20 ${className}`}
onMouseOver={() => setLocalHov(true)}
onMouseLeave={() => setLocalHov(false)}
>
<div className="hidden md:flex flex flex-col justify-end p-3 overflow-hidden">
<div className="flex ">
{children && <div className="">{children}</div>}
<motion.div
animate={{
transition: { ...gdsEase12 },
y: localHov ? 0 : 24,
opacity: localHov ? 1 : 0.2,
x: 32,
}}
className="text-4xl font-heading"
>
{number}
</motion.div>
<div className="inline-block transform -rotate-90 origin-center-2">
<motion.div
animate={{
transition: { ...gdsEase12 },
opacity: localHov ? 1 : 0,
y: localHov ? 32 : 64,
}}
className=" ml-6 text-2xl text-blue-200 whitespace-nowrap font-body "
>
{title}
</motion.div>
</div>
</div>
</div>
</motion.div>
</div>
</a>
</Link>
</div>
);
};
|
from talon import Context, Module, actions
ctx = Context()
mod = Module()
# Maps language mode names to the extensions that activate them. Only put things
# here which have a supported language mode; that's why there are so many
# commented out entries. TODO: make this a csv file?
language_extensions = {
# 'assembly': 'asm s',
# 'bash': 'bashbook sh',
'batch': 'bat',
'c': 'c h',
# 'cmake': 'cmake',
# 'cplusplus': 'cpp hpp',
'csharp': 'cs',
# 'css': 'css',
# 'elisp': 'el',
# 'elm': 'elm',
'gdb': 'gdb',
'go': 'go',
# 'html': 'html',
'java': 'java',
'javascript': 'js',
'javascriptreact': 'jsx',
# 'json': 'json',
# 'lua': 'lua',
'markdown': 'md',
# 'perl': 'pl',
# 'powershell': 'ps1',
'python': 'py',
'protobuf': 'proto',
'r': 'r',
# 'racket': 'rkt',
'ruby': 'rb',
'rust': 'rs',
# 'sass': 'sass',
'scala': 'scala',
# 'snippets': 'snippets',
'talon': 'talon',
'terraform': 'tf',
'typescript': 'ts',
'typescriptreact': 'tsx',
# 'vba': 'vba',
'vimscript': 'vim vimrc',
}
# Override speakable forms for language modes. If not present, a language mode's
# name is used directly.
language_name_overrides = {
"cplusplus": ["see plus plus"],
"csharp": ["see sharp"],
"css": ["c s s"],
"gdb": ["g d b"],
"go": ["go", "go lang", "go language"],
"r": ["are language"],
}
mod.list("language_mode", desc="Name of a programming language mode.")
ctx.lists["self.language_mode"] = {
name: language
for language in language_extensions
for name in language_name_overrides.get(language, [language])
}
# Maps extension to languages.
extension_lang_map = {
'.' + ext: language
for language, extensions in language_extensions.items()
for ext in extensions.split()
}
# Create a context for each defined language
for lang in language_extensions.keys():
mod.tag(lang)
mod.tag(f"{lang}_forced")
c = Context()
# Context is active if language is forced or auto language matches
c.matches = f"""
tag: user.{lang}_forced
tag: user.auto_lang
and code.language: {lang}
"""
c.tags = [f"user.{lang}"]
# Create a mode for the automated language detection. This is active when no lang is forced.
mod.tag("auto_lang")
ctx.tags = ["user.auto_lang"]
@ctx.action_class("code")
class code_actions:
def language():
result = ""
file_extension = actions.win.file_ext()
if file_extension and file_extension in extension_lang_map:
result = extension_lang_map[file_extension]
return result
@mod.action_class
class Actions:
def code_set_language_mode(language: str):
"""Sets the active language mode, and disables extension matching"""
assert language in language_extensions
ctx.tags = [f"user.{language}_forced"]
def code_clear_language_mode():
"""Clears the active language mode, and re-enables code.language: extension matching"""
ctx.tags = ["user.auto_lang"]
|
export const hello = async (event) => {
return {
statusCode: 200,
body: JSON.stringify({
message: "NODE_ENV=" + process.env.NODE_ENV,
input: event,
}),
};
};
|
from django.test import TestCase, Client
from django.contrib.auth.models import User
from django.urls import reverse
from user_profile.forms import UserUpdateForm, ProfileUpdateForm
class MetaSetUp(TestCase):
fixtures = ["test_db.json"]
def setUp(self):
self.client = Client()
self.user = User.objects.get(username="test_user")
self.client.force_login(user=self.user)
class ProfileViewTest(MetaSetUp):
def setUp(self):
super().setUp()
self.response = self.client.get('/accounts/profile/{}/'.format(
self.user.username))
def test_page(self):
self.assertEqual(self.response.status_code, 200)
class ProfileEditTest(MetaSetUp):
def setUp(self):
super().setUp()
self.url = '/accounts/profile/{}/edit/'.format(self.user.username)
self.response = self.client.get(self.url)
def test_get_page(self):
self.assertEqual(self.response.status_code, 200)
self.assertTemplateUsed(self.response, 'profile/edit_profile.html')
self.assertEqual(self.response.context['profile'], self.user.profile)
def test_forms(self):
f_user_update_data = {'first_name': 'test', 'last_name': 'usertest'}
upus = UserUpdateForm(f_user_update_data, instance=self.user)
self.assertTrue(upus.is_valid())
f_profile_data = {
'job': 'Есть',
'study': 'Всю жизнь',
'biography': 'Трудно найти, легко потерять, тяжело прокормить',
'gender': 'M',
'custom_url': self.user.profile.custom_url,
}
prfl = ProfileUpdateForm(f_profile_data, instance=self.user.profile)
self.assertTrue(prfl.is_valid())
def test_edit_profile(self):
f_user_update_data = {'first_name': 'test', 'last_name': 'usertest'}
f_profile_data = {
'job': 'Есть',
'study': 'Всю жизнь',
'biography': 'Трудно найти, легко потерять, тяжело прокормить',
'gender': 'M', # LGBTQ+ ???
'custom_url': self.user.profile.custom_url,
}
resp = self.client.post(self.url, {
**f_user_update_data,
**f_profile_data,
})
self.assertEqual(resp.status_code, 302)
upuser = User.objects.get(id=self.user.id)
self.assertEqual(upuser.profile.job, f_profile_data['job'])
self.assertEqual(upuser.last_name, f_user_update_data['last_name'])
def test_online(self):
url = '/ajax/set_online/'
resp = self.client.get(url)
self.assertEqual(resp.status_code, 404)
resp = self.client.post(url)
# такое ощущение что это не
# данные, а ссылка
# TODO: Здесь нужен нормальный тест
self.assertContains(resp, 'Success', status_code=200)
class AvatarManagingTest(MetaSetUp):
def setUp(self):
super().setUp()
self.response = self.client.get('/change_avatar/')
def test_get_page(self):
self.assertEqual(self.response.status_code, 200)
self.assertTemplateUsed(self.response, 'profile/change_avatar.html')
def test_forms(self):
self.assertTrue(True)
|
import typing
import numpy as np
def stack_delay_arr(
_arr: typing.Sequence[float], _num: int
) -> np.ndarray:
ret_list = []
for i in range(_num):
shift = i + 1
ret_list.append(_arr[_num - shift: -shift])
return np.stack(ret_list)
def stack_delay_arr_T(
_arr: np.ndarray, _num: int
) -> np.ndarray:
ret_list = []
for i in range(_num):
shift = i + 1
ret_list.append(_arr[_num - shift: -shift].T)
return np.stack(ret_list)
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE127_Buffer_Underread__char_declare_memcpy_04.c
Label Definition File: CWE127_Buffer_Underread.stack.label.xml
Template File: sources-sink-04.tmpl.c
*/
/*
* @description
* CWE: 127 Buffer Under-read
* BadSource: Set data pointer to before the allocated memory buffer
* GoodSource: Set data pointer to the allocated memory buffer
* Sink: memcpy
* BadSink : Copy data to string using memcpy
* Flow Variant: 04 Control flow: if(STATIC_CONST_TRUE) and if(STATIC_CONST_FALSE)
*
* */
#include "std_testcase.h"
#include <wchar.h>
/* The two variables below are declared "const", so a tool should
* be able to identify that reads of these will always return their
* initialized values.
*/
static const int STATIC_CONST_TRUE = 1; /* true */
static const int STATIC_CONST_FALSE = 0; /* false */
#ifndef OMITBAD
void CWE127_Buffer_Underread__char_declare_memcpy_04_bad()
{
char * data;
char dataBuffer[100];
memset(dataBuffer, 'A', 100-1);
dataBuffer[100-1] = '\0';
if(STATIC_CONST_TRUE)
{
/* FLAW: Set data pointer to before the allocated memory buffer */
data = dataBuffer - 8;
}
{
char dest[100];
memset(dest, 'C', 100-1); /* fill with 'C's */
dest[100-1] = '\0'; /* null terminate */
/* POTENTIAL FLAW: Possibly copy from a memory location located before the source buffer */
memcpy(dest, data, 100*sizeof(char));
/* Ensure null termination */
dest[100-1] = '\0';
printLine(dest);
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B1() - use goodsource and badsink by changing the STATIC_CONST_TRUE to STATIC_CONST_FALSE */
static void goodG2B1()
{
char * data;
char dataBuffer[100];
memset(dataBuffer, 'A', 100-1);
dataBuffer[100-1] = '\0';
if(STATIC_CONST_FALSE)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
/* FIX: Set data pointer to the allocated memory buffer */
data = dataBuffer;
}
{
char dest[100];
memset(dest, 'C', 100-1); /* fill with 'C's */
dest[100-1] = '\0'; /* null terminate */
/* POTENTIAL FLAW: Possibly copy from a memory location located before the source buffer */
memcpy(dest, data, 100*sizeof(char));
/* Ensure null termination */
dest[100-1] = '\0';
printLine(dest);
}
}
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */
static void goodG2B2()
{
char * data;
char dataBuffer[100];
memset(dataBuffer, 'A', 100-1);
dataBuffer[100-1] = '\0';
if(STATIC_CONST_TRUE)
{
/* FIX: Set data pointer to the allocated memory buffer */
data = dataBuffer;
}
{
char dest[100];
memset(dest, 'C', 100-1); /* fill with 'C's */
dest[100-1] = '\0'; /* null terminate */
/* POTENTIAL FLAW: Possibly copy from a memory location located before the source buffer */
memcpy(dest, data, 100*sizeof(char));
/* Ensure null termination */
dest[100-1] = '\0';
printLine(dest);
}
}
void CWE127_Buffer_Underread__char_declare_memcpy_04_good()
{
goodG2B1();
goodG2B2();
}
#endif /* OMITGOOD */
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
#ifdef INCLUDEMAIN
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
CWE127_Buffer_Underread__char_declare_memcpy_04_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE127_Buffer_Underread__char_declare_memcpy_04_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
//--------------------------------------------------------------------+
// fatfs diskio
//--------------------------------------------------------------------+
//extern "C"
#include "diskio.h"
#include "ff.h"
#ifdef __cplusplus
extern "C" {
#endif
DSTATUS disk_status ( BYTE pdrv )
{
(void) pdrv;
return 0;
}
DSTATUS disk_initialize ( BYTE pdrv )
{
(void) pdrv;
return 0;
}
DRESULT disk_read (
BYTE pdrv, /* Physical drive nmuber to identify the drive */
BYTE *buff, /* Data buffer to store read data */
DWORD sector, /* Start sector in LBA */
UINT count /* Number of sectors to read */
)
{
(void) pdrv;
return flash.readBlocks(sector, buff, count) ? RES_OK : RES_ERROR;
}
DRESULT disk_write (
BYTE pdrv, /* Physical drive nmuber to identify the drive */
const BYTE *buff, /* Data to be written */
DWORD sector, /* Start sector in LBA */
UINT count /* Number of sectors to write */
)
{
(void) pdrv;
return flash.writeBlocks(sector, buff, count) ? RES_OK : RES_ERROR;
}
DRESULT disk_ioctl (
BYTE pdrv, /* Physical drive nmuber (0..) */
BYTE cmd, /* Control code */
void *buff /* Buffer to send/receive control data */
)
{
(void) pdrv;
switch ( cmd )
{
case CTRL_SYNC:
flash.syncBlocks();
return RES_OK;
case GET_SECTOR_COUNT:
*((DWORD*) buff) = flash.size()/512;
return RES_OK;
case GET_SECTOR_SIZE:
*((WORD*) buff) = 512;
return RES_OK;
case GET_BLOCK_SIZE:
*((DWORD*) buff) = 8; // erase block size in units of sector size
return RES_OK;
default:
return RES_PARERR;
}
}
#ifdef __cplusplus
}
#endif
|
#pragma once
namespace qif191
{
namespace t
{
class CUserDataXMLType : public TypeBase
{
public:
QIF191_EXPORT CUserDataXMLType(xercesc::DOMNode* const& init);
QIF191_EXPORT CUserDataXMLType(CUserDataXMLType const& init);
void operator=(CUserDataXMLType const& other) { m_node = other.m_node; }
static altova::meta::ComplexType StaticInfo() { return altova::meta::ComplexType(types + _altova_ti_t_altova_CUserDataXMLType); }
QIF191_EXPORT void SetXsiType();
};
} // namespace t
} // namespace qif191
//#endif // _ALTOVA_INCLUDED_QIFDocument_ALTOVA_t_ALTOVA_CUserDataXMLType
|
import pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 1024 , FREQ = 'D', seed = 0, trendtype = "Lag1Trend", cycle_length = 5, transform = "BoxCox", sigma = 0.0, exog_count = 0, ar_order = 0);
|
# flake8: noqa
import abc
import sys
import pathlib
from contextlib import suppress
try:
from zipfile import Path as ZipPath # type: ignore
except ImportError:
from zipp import Path as ZipPath # type: ignore
try:
from typing import runtime_checkable # type: ignore
except ImportError:
def runtime_checkable(cls): # type: ignore
return cls
try:
from typing import Protocol # type: ignore
except ImportError:
Protocol = abc.ABC # type: ignore
class TraversableResourcesLoader:
"""
Adapt loaders to provide TraversableResources and other
compatibility.
"""
def __init__(self, spec):
self.spec = spec
@property
def path(self):
return self.spec.origin
def get_resource_reader(self, name):
from . import readers, _adapters
def _zip_reader(spec):
with suppress(AttributeError):
return readers.ZipReader(spec.loader, spec.name)
def _namespace_reader(spec):
with suppress(AttributeError, ValueError):
return readers.NamespaceReader(spec.submodule_search_locations)
def _available_reader(spec):
with suppress(AttributeError):
return spec.loader.get_resource_reader(spec.name)
def _native_reader(spec):
reader = _available_reader(spec)
return reader if hasattr(reader, 'files') else None
def _file_reader(spec):
if pathlib.Path(self.path).exists():
return readers.FileReader(self)
return (
# native reader if it supplies 'files'
_native_reader(self.spec)
or
# local ZipReader if a zip module
_zip_reader(self.spec)
or
# local NamespaceReader if a namespace module
_namespace_reader(self.spec)
or
# local FileReader
_file_reader(self.spec)
or _adapters.DegenerateFiles(self.spec)
)
def wrap_spec(package):
"""
Construct a package spec with traversable compatibility
on the spec/loader/reader.
"""
from . import _adapters
return _adapters.SpecLoaderAdapter(package.__spec__, TraversableResourcesLoader)
|
/*
Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'pastefromword', 'vi', {
confirmCleanup: 'Văn bản bạn muốn dán có kèm định dạng của Word. Bạn có muốn loại bỏ định dạng Word trước khi dán?',
error: 'Không thể để làm sạch các dữ liệu dán do một lỗi nội bộ',
title: 'Dán với định dạng Word',
toolbar: 'Dán với định dạng Word'
} );
|
# author: Fei Gao
# date: Sun Jun 1 18:45:42 2014
#
# Best Time To Buy And Sell Stock II
#
# Say you have an array for which the ith element is the price of a given stock
# on day i.
# Design an algorithm to find the maximum profit. You may complete as many
# transactions as you like (ie, buy one and sell one share of the stock
# multiple times). However, you may not engage in multiple transactions at the
# same time (ie, you must sell the stock before you buy again).
# Note: if price drops today, sell out yesterday and buy in today!
class Solution:
# @param prices, a list of integer
# @return an integer
def maxProfit(self, prices):
if prices is None or len(prices) <= 1:
return 0
win = 0
buy = prices[0]
for i in range(1, len(prices)):
if prices[i] < prices[i-1]:
# sell yesterday
win += prices[i-1] - buy
# buy today
buy = prices[i]
if prices[-1] > buy:
win += prices[-1] - buy
return win
def main():
solver = Solution()
import random
prices = [random.randrange(-5, 6) for _ in range(10)]
print(prices, solver.maxProfit(prices))
prices = list(range(10000))[::-1]
print(solver.maxProfit(prices))
pass
if __name__ == '__main__':
main()
pass
|
def convert_to_number(algo):
binstr = ''.join(['0' if char == '.' else '1' for char in algo])
return int(binstr, 2)
def enhance1(iha, input_image, empty):
num_rows = len(input_image) + 4
num_cols = len(input_image[0]) + 4
image = []
for row in input_image:
image.append([empty, empty] + list(row) + [empty, empty])
image.insert(0, [empty for i in range(num_cols)])
image.insert(0, [empty for i in range(num_cols)])
image.append([empty for i in range(num_cols)])
image.append([empty for i in range(num_cols)])
output = []
for row in range(1, num_rows - 1):
out_row = []
for col in range(1, num_cols - 1):
lookup_raw = image[row - 1][col - 1] + \
image[row - 1][col] + \
image[row - 1][col + 1] + \
image[row][col - 1] + \
image[row][col] + \
image[row][col + 1] + \
image[row + 1][col - 1] + \
image[row + 1][col] + \
image[row + 1][col + 1]
out_row.append(iha[convert_to_number(lookup_raw)])
output.append(out_row)
return output
if __name__ == '__main__':
with open('input.txt') as f:
lines = f.read().splitlines()
iha = lines[0]
out = enhance1(iha, lines[2:], '.')
zit = '#'
for i in range(49):
out = enhance1(iha, out, zit)
if zit == '#':
zit = '.'
else:
zit = '#'
count = 0
for line in out:
for char in line:
if char == '#':
count += 1
print(count)
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidHJhbnNhY3Rpb25zX2ZpbmFuY2lhbF90eXBlcy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9uZXRzdWl0ZV93ZWJzZXJ2aWNlcy8yMDE5XzIvdHJhbnNhY3Rpb25zX2ZpbmFuY2lhbF90eXBlcy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiIiwic291cmNlc0NvbnRlbnQiOlsiZXhwb3J0IHR5cGUgQnVkZ2V0QnVkZ2V0VHlwZSA9IFwiX2dsb2JhbFwiIHwgXCJfbG9jYWxcIjtcbiJdfQ==
|
module.exports = {
devServer: {
overlay: false,
},
};
|
import json
from typing import List, Tuple, Dict
import constants
import data.analysis.analysis_util as a_util
# adding comments to the number of reactions
N_REACTIONS = len(constants.FB_REACTIONS) + 1
N_BINS = 50
REACTION_NAMES = ([r.lower() for r in constants.FB_REACTIONS] + ["comment"])
def plot_histograms(n_bins: int = N_BINS) -> None:
# todo - set the max to be at like 100...
# todo - remove % plot because it's useless
labels = a_util.get_data_labels()
label_lists = [[] for _ in range(N_REACTIONS)]
for label in labels:
for index, label_list in enumerate(label_lists):
label_list.append(label[index])
for reaction, reaction_labels in zip(REACTION_NAMES, label_lists):
hist = a_util.Histogram(reaction_labels, n_bins=n_bins)
hist.plot("Histogram for %ss" % reaction)
def plot_text_char_length_histogram(n_bins: int = N_BINS, maximum_length: int = None) -> None:
texts = a_util.get_data_texts()
labels = [len(t) for t in texts if maximum_length is None or len(t) < maximum_length]
hist = a_util.Histogram(labels, n_bins=n_bins)
if maximum_length is not None:
title = "Histogram for Confession Text Length (in Characters) Up to %d Chars" % maximum_length
else:
title = "Histogram for Confession Text Length (in Characters)"
hist.plot(title)
def plot_2d_histograms(
n_bins: int = N_BINS,
min_rxn: int = None,
max_char_count: int = None,
save: bool = False) -> None:
# do char length and reaction count
all_char_lengths = [len(t) for t in a_util.get_data_texts()]
all_rxn_labels = a_util.get_data_labels()
label_lists = []
for index in range(N_REACTIONS):
char_lengths, rxn_labels = [], []
for char_length, label in zip(all_char_lengths, all_rxn_labels):
higher_than_min_rxn = (min_rxn is None or label[index] >= min_rxn)
lower_than_max_char_count = (max_char_count is None or char_length <= max_char_count)
if higher_than_min_rxn and lower_than_max_char_count:
char_lengths.append(char_length)
rxn_labels.append(label[index])
label_lists.append((char_lengths, rxn_labels))
for reaction_name, bundle in zip(REACTION_NAMES, label_lists):
char_lengths, rxn_labels = bundle
hist = a_util.Histogram2D(char_lengths, rxn_labels, n_bins=n_bins)
title = "2D Hist for chr-count (X) and %ss (Y)" % reaction_name
if min_rxn is not None:
title = "%s %s" % (title, "with min rxn %d" % min_rxn)
max_length_suffix = "" if (max_char_count is None) else "%d" % max_char_count
mix_rxn_suffix = "" if (min_rxn is None) else "%d" % min_rxn
fname = "char_count%s_v_%s%s" % (max_length_suffix, reaction_name, mix_rxn_suffix)
hist.plot(title, save=save, fname=fname)
print(fname)
if __name__ == '__main__':
# plot_histograms()
plot_2d_histograms(n_bins=100, min_rxn=5, max_char_count=400, save=True)
# plot_2d_histograms(n_bins=100, max_char_count=800, save=True)
# plot_text_char_length_histogram(100, maximum_length=1000)\
|
#ifndef _COMPILATOR_H_
#define _COMPILATOR_H_
/******************************************************************************/
// on suppose qu'il s'agit avr gcc
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/sleep.h>
#include <avr/wdt.h>
#include <avr/pgmspace.h>
// Redefinition des carateristique intrinsec au micro :
// Internal code memory
#define __CODE_MEMORY
// No default initialisation of memory variables
#define __NO_INIT
// Internal EEPROM memory
#define __EEPROM_MEMORY
// Interrupt functions
#define __ISR_FUNCTION
// Monitor function
#define __MONITOR_FUNCTION
#define __enable_interrupt() sei()
#define __disable_interrupt() cli()
#define __watchdog_reset() wdt_reset()
#define __no_operation()
#define __sleep()
#define __io
// code en flash
#define FLASH_DECLARE(x) x __attribute__((__progmem__))
/**
* @description A block of code may be made atomic by wrapping it with this
* macro. Something which is atomic cannot be interrupted by interrupts.
*/
#ifndef ATOMIC
#define ATOMIC(code) \
{ \
Int8U em_isr_state; \
em_isr_state = SREG; \
__disable_interrupt(); \
do{ code }while(0); \
SREG = em_isr_state; \
}
#endif
/******************************************************************************/
#endif // _COMPILATOR_H_
|
const express = require('express')
const router = express.Router();
const User = require('../models/user')
router.get('/', isLoggedIn, (req, res)=>{
// res.render('question.ejs',{user: req.user, questions: req.user.questions})
User.findByIdAndUpdate(req.user.id, {hasPlayed: true}, {new: true, upsert: true}, (err, user)=>{
console.log("Quiz started for>>>", user)
})
.then((user)=>{
res.redirect('/question/quiz/?number=0')
})
});
router.post('/', (req,res)=>{
var option = req.body.option,
questionNumber = req.body.question;
var answer = {
questionNumber: questionNumber,
option: option
}
User.findByIdAndUpdate(req.user._id, {$push: {answers: answer}}, {new: true, upsert: true}, (err, user)=>{
console.log(user.fullName);
})
// add to database
var nextQuestion = '/question/quiz/?number=' + (parseInt(questionNumber) + 1).toString();
res.redirect(nextQuestion);
})
router.get('/quiz', isLoggedIn, (req, res)=>{
if(parseInt(req.query.number) < 30){
var questionNumber = req.query.number,
question = req.user.questions[questionNumber];
res.render('question.ejs', {user: req.user, question: question, questionNumber: questionNumber})
}
else{
res.redirect('/score')
}
})
router.get('/rules', isLoggedIn, (req,res)=>{
res.render('rules.ejs', {user: req.user});
})
router.get('/played', isLoggedIn, (req, res)=>{
let user = req.user;
req.logout();
res.render('played.ejs', {user: user});
})
function isLoggedIn(req, res, next){
if(req.isAuthenticated())
return next();
else
{
res.redirect("/auth/login");
}
}
module.exports = router;
|
#!/usr/bin/python
import re, json, copy, sys
from main import *
### Hex to bin converter and vice versa for objects
def json_is_base(obj, base):
alpha = get_code_string(base)
if isinstance(obj, (str, unicode)):
for i in range(len(obj)):
if alpha.find(obj[i]) == -1:
return False
return True
elif isinstance(obj, (int, float, long)) or obj is None:
return True
elif isinstance(obj, list):
for i in range(len(obj)):
if not json_is_base(obj[i], base):
return False
return True
else:
for x in obj:
if not json_is_base(obj[x], base):
return False
return True
def json_changebase(obj, changer):
if isinstance(obj, (str, unicode)):
return changer(obj)
elif isinstance(obj, (int, float, long)) or obj is None:
return obj
elif isinstance(obj, list):
return [json_changebase(x, changer) for x in obj]
return dict((x, json_changebase(obj[x], changer)) for x in obj)
# Transaction serialization and deserialization
def deserialize(tx):
if re.match('^[0-9a-fA-F]*$', tx):
return json_changebase(deserialize(tx.decode('hex')),
lambda x: x.encode('hex'))
# http://stackoverflow.com/questions/4851463/python-closure-write-to-variable-in-parent-scope
# Python's scoping rules are demented, requiring me to make pos an object
# so that it is call-by-reference
pos = [0]
def read_as_int(bytez):
pos[0] += bytez
return decode(tx[pos[0]-bytez:pos[0]][::-1], 256)
def read_var_int():
pos[0] += 1
if ord(tx[pos[0]-1]) < 253:
return ord(tx[pos[0]-1])
return read_as_int(pow(2, ord(tx[pos[0]-1]) - 252))
def read_bytes(bytez):
pos[0] += bytez
return tx[pos[0]-bytez:pos[0]]
def read_var_string():
size = read_var_int()
return read_bytes(size)
obj = {"ins": [], "outs": []}
obj["version"] = read_as_int(4)
ins = read_var_int()
for i in range(ins):
obj["ins"].append({
"outpoint": {
"hash": read_bytes(32)[::-1],
"index": read_as_int(4)
},
"script": read_var_string(),
"sequence": read_as_int(4)
})
outs = read_var_int()
for i in range(outs):
obj["outs"].append({
"value": read_as_int(8),
"script": read_var_string()
})
obj["locktime"] = read_as_int(4)
return obj
def serialize(txobj):
o = []
if json_is_base(txobj, 16):
return serialize(json_changebase(txobj,
lambda x: x.decode('hex'))).encode('hex')
o.append(encode(txobj["version"], 256, 4)[::-1])
o.append(num_to_var_int(len(txobj["ins"])))
for inp in txobj["ins"]:
o.append(inp["outpoint"]["hash"][::-1])
o.append(encode(inp["outpoint"]["index"], 256, 4)[::-1])
o.append(num_to_var_int(len(inp["script"]))+inp["script"])
o.append(encode(inp["sequence"], 256, 4)[::-1])
o.append(num_to_var_int(len(txobj["outs"])))
for out in txobj["outs"]:
o.append(encode(out["value"], 256, 8)[::-1])
o.append(num_to_var_int(len(out["script"]))+out["script"])
o.append(encode(txobj["locktime"], 256, 4)[::-1])
return ''.join(o)
# Hashing transactions for signing
SIGHASH_ALL = 1
SIGHASH_NONE = 2
SIGHASH_SINGLE = 3
SIGHASH_ANYONECANPAY = 80
def signature_form(tx, i, script, hashcode = SIGHASH_ALL):
i, hashcode = int(i), int(hashcode)
if isinstance(tx, str):
return serialize(signature_form(deserialize(tx), i, script, hashcode))
newtx = copy.deepcopy(tx)
for inp in newtx["ins"]:
inp["script"] = ""
newtx["ins"][i]["script"] = script
if hashcode == SIGHASH_NONE:
newtx["outs"] = []
elif hashcode == SIGHASH_SINGLE:
newtx["outs"] = newtx["outs"][:len(newtx["ins"])]
for out in range(len(newtx["ins"]) - 1):
out.value = 2**64 - 1
out.script = ""
elif hashcode == SIGHASH_ANYONECANPAY:
newtx["ins"] = [newtx["ins"][i]]
else:
pass
return newtx
# Making the actual signatures
def der_encode_sig(v, r, s):
b1, b2 = encode(r, 256).encode('hex'), encode(s, 256).encode('hex')
if r >= 2**255:
b1 = '00' + b1
if s >= 2**255:
b2 = '00' + b2
left = '02'+encode(len(b1)/2, 16, 2)+b1
right = '02'+encode(len(b2)/2, 16, 2)+b2
return '30'+encode(len(left+right)/2, 16, 2)+left+right
def der_decode_sig(sig):
leftlen = decode(sig[6:8], 16)*2
left = sig[8:8+leftlen]
rightlen = decode(sig[10+leftlen:12+leftlen], 16)*2
right = sig[12+leftlen:12+leftlen+rightlen]
return (None,decode(left,16),decode(right,16))
def txhash(tx, hashcode=None):
if re.match('^[0-9a-fA-F]*$', tx):
tx = changebase(tx, 16, 256)
if hashcode:
return dbl_sha256(tx + encode(int(hashcode), 256, 4)[::-1])
else:
return bin_dbl_sha256(tx)[::-1].encode('hex')
def bin_txhash(tx, hashcode=None):
return txhash(tx, hashcode).decode('hex')
def ecdsa_tx_sign(tx, priv, hashcode=SIGHASH_ALL):
rawsig = ecdsa_raw_sign(bin_txhash(tx, hashcode), priv)
return der_encode_sig(*rawsig)+encode(hashcode, 16, 2)
def ecdsa_tx_verify(tx, sig, pub, hashcode=SIGHASH_ALL):
return ecdsa_raw_verify(bin_txhash(tx, hashcode), der_decode_sig(sig), pub)
def ecdsa_tx_recover(tx, sig, hashcode=SIGHASH_ALL):
z = bin_txhash(tx, hashcode)
_, r, s = der_decode_sig(sig)
left = ecdsa_raw_recover(z, (0, r, s))
right = ecdsa_raw_recover(z, (1, r, s))
return (encode_pubkey(left, 'hex'), encode_pubkey(right, 'hex'))
# Scripts
def mk_pubkey_script(addr):
# Keep the auxiliary functions around for altcoins' sake
return '76a914' + b58check_to_hex(addr) + '88ac'
def mk_scripthash_script(addr):
return 'a914' + b58check_to_hex(addr) + '87'
# Address representation to output script
def address_to_script(addr):
if addr[0] == '3' or addr[0] == '2':
return mk_scripthash_script(addr)
else:
return mk_pubkey_script(addr)
# Output script to address representation
def script_to_address(script, vbyte=0):
if re.match('^[0-9a-fA-F]*$', script):
script = script.decode('hex')
if script[:3] == '\x76\xa9\x14' and script[-2:] == '\x88\xac' and len(script) == 25:
return bin_to_b58check(script[3:-2], vbyte) # pubkey hash addresses
else:
if vbyte == 111:
# Testnet
scripthash_byte = 196
else:
scripthash_byte = 5
# BIP0016 scripthash addresses
return bin_to_b58check(script[2:-1], scripthash_byte)
def p2sh_scriptaddr(script, magicbyte=5):
if re.match('^[0-9a-fA-F]*$', script):
script = script.decode('hex')
return hex_to_b58check(hash160(script), magicbyte)
scriptaddr = p2sh_scriptaddr
def deserialize_script(script):
if re.match('^[0-9a-fA-F]*$', script):
return json_changebase(deserialize_script(script.decode('hex')),
lambda x: x.encode('hex'))
out, pos = [], 0
while pos < len(script):
code = ord(script[pos])
if code == 0:
out.append(None)
pos += 1
elif code <= 75:
out.append(script[pos+1:pos+1+code])
pos += 1 + code
elif code <= 78:
szsz = pow(2, code - 76)
sz = decode(script[pos+szsz: pos:-1], 256)
out.append(script[pos + 1 + szsz:pos + 1 + szsz + sz])
pos += 1 + szsz + sz
elif code <= 96:
out.append(code - 80)
pos += 1
else:
out.append(code)
pos += 1
return out
def serialize_script_unit(unit):
if isinstance(unit, int):
if unit < 16:
return chr(unit + 80)
else:
return chr(unit)
elif unit is None:
return '\x00'
else:
if len(unit) <= 75:
return chr(len(unit))+unit
elif len(unit) < 256:
return chr(76)+chr(len(unit))+unit
elif len(unit) < 65536:
return chr(77)+encode(len(unit), 256, 2)[::-1]+unit
else:
return chr(78)+encode(len(unit), 256, 4)[::-1]+unit
def serialize_script(script):
if json_is_base(script, 16):
return serialize_script(json_changebase(script,
lambda x: x.decode('hex'))).encode('hex')
return ''.join(map(serialize_script_unit, script))
def mk_multisig_script(*args): # [pubs],k or pub1,pub2...pub[n],k
if isinstance(args[0], list):
pubs, k = args[0], int(args[1])
else:
pubs = filter(lambda x: len(str(x)) >= 32, args)
k = args[pubs]
return serialize_script([k]+pubs+[len(pubs), 174])
# Signing and verifying
def verify_tx_input(tx, i, script, sig, pub):
if re.match('^[0-9a-fA-F]*$', tx):
tx = tx.decode('hex')
if re.match('^[0-9a-fA-F]*$', script):
script = script.decode('hex')
if not re.match('^[0-9a-fA-F]*$', sig):
sig = sig.encode('hex')
hashcode = decode(sig[-2:], 16)
modtx = signature_form(tx, int(i), script, hashcode)
return ecdsa_tx_verify(modtx, sig, pub, hashcode)
def sign(tx, i, priv):
i = int(i)
if not re.match('^[0-9a-fA-F]*$', tx):
return sign(tx.encode('hex'), i, priv).decode('hex')
if len(priv) <= 33:
priv = priv.encode('hex')
pub = privkey_to_pubkey(priv)
address = pubkey_to_address(pub)
signing_tx = signature_form(tx, i, mk_pubkey_script(address))
sig = ecdsa_tx_sign(signing_tx, priv)
txobj = deserialize(tx)
txobj["ins"][i]["script"] = serialize_script([sig, pub])
return serialize(txobj)
def signall(tx, priv):
for i in range(len(deserialize(tx)["ins"])):
tx = sign(tx, i, priv)
return tx
def multisign(tx, i, script, pk, hashcode=SIGHASH_ALL):
if re.match('^[0-9a-fA-F]*$', tx):
tx = tx.decode('hex')
if re.match('^[0-9a-fA-F]*$', script):
script = script.decode('hex')
modtx = signature_form(tx, i, script, hashcode)
return ecdsa_tx_sign(modtx, pk, hashcode)
def apply_multisignatures(*args):
# tx,i,script,sigs OR tx,i,script,sig1,sig2...,sig[n]
tx, i, script = args[0], int(args[1]), args[2]
sigs = args[3] if isinstance(args[3], list) else list(args[3:])
if re.match('^[0-9a-fA-F]*$', script):
script = script.decode('hex')
sigs = [x.decode('hex') if x[:2] == '30' else x for x in sigs]
if re.match('^[0-9a-fA-F]*$', tx):
return apply_multisignatures(tx.decode('hex'), i, script, sigs).encode('hex')
txobj = deserialize(tx)
txobj["ins"][i]["script"] = serialize_script([None]+sigs+[script])
return serialize(txobj)
def is_inp(arg):
return len(arg) > 64 or "output" in arg or "outpoint" in arg
def mktx(*args):
# [in0, in1...],[out0, out1...] or in0, in1 ... out0 out1 ...
ins, outs = [], []
for arg in args:
if isinstance(arg, list):
for a in arg: (ins if is_inp(a) else outs).append(a)
else:
(ins if is_inp(arg) else outs).append(arg)
txobj = {"locktime": 0, "version": 1, "ins": [], "outs": []}
for i in ins:
if isinstance(i, dict) and "outpoint" in i:
txobj["ins"].append(i)
else:
if isinstance(i, dict) and "output" in i:
i = i["output"]
txobj["ins"].append({
"outpoint": {"hash": i[:64], "index": int(i[65:])},
"script": "",
"sequence": 4294967295
})
for o in outs:
if isinstance(o, str):
addr = o[:o.find(':')]
val = int(o[o.find(':')+1:])
o = {}
if re.match('^[0-9a-fA-F]*$', addr):
o["script"] = addr
else:
o["address"] = addr
o["value"] = val
outobj = {}
if "address" in o:
outobj["script"] = address_to_script(o["address"])
elif "script" in o:
outobj["script"] = o["script"]
else:
raise Exception("Could not find 'address' or 'script' in output.")
outobj["value"] = o["value"]
txobj["outs"].append(outobj)
return serialize(txobj)
def select(unspent, value):
value = int(value)
high = [u for u in unspent if u["value"] >= value]
high.sort(key=lambda u: u["value"])
low = [u for u in unspent if u["value"] < value]
low.sort(key=lambda u: -u["value"])
if len(high):
return [high[0]]
i, tv = 0, 0
while tv < value and i < len(low):
tv += low[i]["value"]
i += 1
if tv < value:
raise Exception("Not enough funds")
return low[:i]
# Only takes inputs of the form { "output": blah, "value": foo }
def mksend(*args):
argz, change, fee = args[:-2], args[-2], int(args[-1])
ins, outs = [], []
for arg in argz:
if isinstance(arg, list):
for a in arg:
(ins if is_inp(a) else outs).append(a)
else:
(ins if is_inp(arg) else outs).append(arg)
isum = sum([i["value"] for i in ins])
osum, outputs2 = 0, []
for o in outs:
if isinstance(o, str):
o2 = {
"address": o[:o.find(':')],
"value": int(o[o.find(':')+1:])
}
else:
o2 = o
outputs2.append(o2)
osum += o2["value"]
if isum < osum+fee:
raise Exception("Not enough money")
elif isum > osum+fee+5430:
outputs2 += [{"address": change, "value": isum-osum-fee}]
return mktx(ins, outputs2)
|
import { combineReducers } from 'redux';
const Reducers = combineReducers({});
export default Reducers;
|
# Theory: Comparisons
# Writing code without comparing any values in it will get you
# only so far. Now, it's time to master this skill.
# 1. Comparison operators
# Comparison or relation operations let you compare two values
# and determine the relation between them. There are ten
# comparison operators in Python:
# < strictly less than
# <= less than or equal
# > strictly greater than
# >= greater than or equal
# == equal
# != not equal
# is object identity
# is not negated object identity
# in membership
# not in negated membership.
# The result of applying these operators is always bool. The
# following sections focus on the first six operators (<, <=, >,
# >=, ==, !=), but you can find more details about identity and
# membership testing in the next topics.
# 2. Comparing integers
# In this topic, we will cover only integer comparison.
a = 5
b = -10
c = 15
result_1 = a < b # False
result_2 = a == a # True
result_3 = a != b # True
result_4 = b >= c # False
# Any expression that returns an integer is a valid comparison
# operand too:
calculated_result = a == b + c # True
# Given the defined variables a, b and c, we basically check if
# 5 is equal to -10 + 15, which is true.
# Comparison chaining
# Since comparison operations return boolean values, you can
# join them using logical operators. In this case, it is important
# to know their priority, i.e. which one is executed first. All
# comparison operations have the same priority, and it is lower
# than that of any arithmetic, shifting, or bitwise operation.
x = -5
y = 10
z = 12
result = x < y and y <= z # True
# In Python, there is a fancier way to write complex comparisons.
# It is called chaining. For example, x < y <= z is almost
# equivalent to the expression you saw in the last example. The
# difference is that y is evaluated only once.
result = 10 < (100 * 100) <= 10000 # True, the multiplication is evaluated once
# Please pay attention to the fact that tools for code quality
# often recommend chaining comparisons instead of joining them.
# Comparison chaining, however, should be used carefully
# because sometimes expressions might get tricky, so the result
# would depend on the operators' order and how the parentheses
# are put. Consider this example:
a = 1
b = 2
c = 3
e = 4
f = 5
g = 6
print(b + c <= e or f + g >= e == f == 5) # False
print((b + c <= e or f + g >= e) == (f == 5)) # True
# The first expression is False because it is evaluated
# consequently: the part b + c <= e or f + g >= e is True but
# it is not equal to f, so the whole expression is already False.
# In the second case, both operands are Trueand True equals
# True, so the final expression is also True.
# 4. Logic & arithmetics
# Let's look at another interesting case. At the beginning of the
# topic, we learned that the result of applying comparison
# operators is always bool. However, if there is a logical and
# arithmetic part in an expression, we might see unusual
# behavior:
# True and-expressions return the result of the last operation:
print(b + c * f >= e and (f + g) * c) # 33
print((f + g) * c and b + c * f >= e) # True
# False and-expressions return a boolean False value:
print(b + c * f <= e and (f + g) * c) # False
print((f + g) * c and b + c * f <= e) # False
# True or-expressions return the result of the first operation:
print(b + c * f >= e or (f + g) * c) # True
print((f + g) * c or b + c * f >= e) # 33
# True-False or-expressions return the True part:
print((f + g) * c or b + c * f <= e) # 33
print(b + c * f <= e or (f + g) * c) # 33
# It might look confusing at first sight but, if you think about it,
# every printed value is perfectly legal and complies with
# common mathematical logic.
# 5. Summary
# In this topic, we familiarized ourselves with Python comparison
# operators, learned how to compare integers, and use
# comparison chaining. These basic operators will definitely be a
# great help to you in the future!
|
var PImage = require('../src/pureimage');
var fs = require('fs');
var fnt = PImage.registerFont('tests/fonts/SourceSansPro-Regular.ttf','Source Sans Pro');
// First test: render synchronously loading text
fnt.loadSync();
renderText('textSync');
// Second test: render asynchronously (font is loaded at this point so it's going to be faster)
fnt.load(function() { renderText('textAsync') });
function renderText(fileName) {
var img = PImage.make(200,200);
var ctx = img.getContext('2d');
ctx.fillStyle = "#ffff00";
ctx.fillRect(0,0,200,200);
ctx.fillStyle = '#00ff00';
ctx.font = "48pt 'Source Sans Pro'";
ctx.fillText("Hello world", 10, 60);
//ctx.USE_FONT_GLYPH_CACHING = true;
//var before = process.hrtime();
//var count = 20*1000;
//for(var i=0; i<count; i++) {
// var str = "ABCDE";
//ctx.fillStyle = '#00ff00';
//ctx.fillText(str,30,30);
//ctx.fillStyle = '#ffff00';
//ctx.fillText(str,30,60);
// ctx.save();
//ctx.translate(0,80);
//ctx.fillText(str,30,30);
//ctx.restore();
//}
//var diff = process.hrtime(before);
//console.log('with caching', diff);
//ctx.USE_FONT_GLYPH_CACHING = false;
//var before = process.hrtime();
//for(var i=0; i<count; i++) {
// var str = "ABCDE";
// ctx.fillText(str,30,30);
//}
//var diff = process.hrtime(before);
//console.log('without caching', diff);
PImage.encodePNGToStream(img, fs.createWriteStream('build/text.png')).then(()=>{
// console.log("wrote out the png file to build/text.png");
});
}
|
import matplotlib.pyplot as plt
a = input("Escribe el numero de personas que usan vehiculo: \n")
A = int(a)
while A < 0:
print("¡Ha escrito un número negativo! Inténtelo de nuevo")
a = input("Escribe el numero de personas que usan vehiculo: \n")
A = int(a)
b = input("Escribe el numero de personas que usan motocicleta: \n")
B = int(b)
while B < 0:
print("¡Ha escrito un número negativo! Inténtelo de nuevo")
b = input("Escribe el numero de personas que usan motocicletas: \n")
B = int(b)
c = input("Escribe el numero de personas que usan bicicletas: \n")
C = int(c)
while C < 0:
print("¡Ha escrito un número negativo! Inténtelo de nuevo")
c = input("Escribe el numero de personas que usan bicicletas: \n")
C = int(c)
d = input("Escribe el numero de personas que usan el metro: \n")
D = int(d)
while D < 0:
print("¡Ha escrito un número negativo! Inténtelo de nuevo")
d = input("Escribe el numero de personas que usan el metro: \n")
D = int(d)
Dato1 = float(A/(A+B+C+D)*100)
Dato2 = float(B/(A+B+C+D)*100)
Dato3 = float(C/(A+B+C+D)*100)
Dato4 = float(D/(A+B+C+D)*100)
print(Dato1, Dato2, Dato3, Dato4)
medios_transporte= "Vehiculo", "Motocicleta", "Bicicleta", "Metro"
sizes= [Dato1, Dato2,Dato3, Dato4]
fig1, ax1 =plt.subplots()
ax1.pie(sizes, labels=medios_transporte, autopct='%1.1f%%', shadow=True, startangle=90)
ax1.axis('equal')
plt.title("Principal Medio de transporte")
plt.legend()
plt.savefig('Grafica_pastel.png')
plt.show()
|
// 为组件提供 install 方法,供组件对外按需引入
import Component from './src/index'
Component.install = Vue => {
Vue.component(Component.name, Component)
}
Object.assign(Component, {
title: '竞猜组件',
icon: 'iconfont iconbiaodan',
valueType: '',
defaultStyle: {
height: 375,
width: 375,
top: 0
}
})
export default Component
|
# 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
#
# https://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.
"""Define version number here and read it from setup.py automatically"""
import sys
if sys.version_info.major == 2:
__version__ = "0.2.0.dev27" # coverage: ignore
else:
__version__ = "0.2.0.dev35"
|
/**
* This JS file allows downloading png files from svg cavas. This codes belong to: https://github.com/exupero/saveSvgAsPng
*
*/
(function () {
var out$ = typeof exports != 'undefined' && exports || typeof define != 'undefined' && {} || this;
var doctype = '<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" [<!ENTITY nbsp " ">]>';
function isElement(obj) {
return obj instanceof HTMLElement || obj instanceof SVGElement;
}
function requireDomNode(el) {
if (!isElement(el)) {
throw new Error('an HTMLElement or SVGElement is required; got ' + el);
}
}
function isExternal(url) {
return url && url.lastIndexOf('http', 0) == 0 && url.lastIndexOf(window.location.host) == -1;
}
function inlineImages(el, callback) {
requireDomNode(el);
var images = el.querySelectorAll('image'),
left = images.length,
checkDone = function () {
if (left === 0) {
callback();
}
};
checkDone();
for (var i = 0; i < images.length; i++) {
(function (image) {
var href = image.getAttributeNS("http://www.w3.org/1999/xlink", "href");
if (href) {
if (isExternal(href.value)) {
console.warn("Cannot render embedded images linking to external hosts: " + href.value);
return;
}
}
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.crossOrigin = "anonymous";
href = href || image.getAttribute('href');
if (href) {
img.src = href;
img.onload = function () {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
image.setAttributeNS("http://www.w3.org/1999/xlink", "href", canvas.toDataURL('image/png'));
left--;
checkDone();
};
img.onerror = function () {
console.log("Could not load " + href);
left--;
checkDone();
}
} else {
left--;
checkDone();
}
})(images[i]);
}
}
function styles(el, options, cssLoadedCallback) {
var selectorRemap = options.selectorRemap;
var modifyStyle = options.modifyStyle;
var css = "";
// each font that has extranl link is saved into queue, and processed
// asynchronously
var fontsQueue = [];
var sheets = document.styleSheets;
for (var i = 0; i < sheets.length; i++) {
try {
var rules = sheets[i].cssRules;
} catch (e) {
console.warn("Stylesheet could not be loaded: " + sheets[i].href);
continue;
}
if (rules != null) {
for (var j = 0, match; j < rules.length; j++, match = null) {
var rule = rules[j];
if (typeof (rule.style) != "undefined") {
var selectorText;
try {
selectorText = rule.selectorText;
} catch (err) {
console.warn('The following CSS rule has an invalid selector: "' + rule + '"', err);
}
try {
if (selectorText) {
match = el.querySelector(selectorText) || el.parentNode.querySelector(selectorText);
}
} catch (err) {
console.warn('Invalid CSS selector "' + selectorText + '"', err);
}
if (match) {
var selector = selectorRemap ? selectorRemap(rule.selectorText) : rule.selectorText;
var cssText = modifyStyle ? modifyStyle(rule.style.cssText) : rule.style.cssText;
css += selector + " { " + cssText + " }\n";
} else if (rule.cssText.match(/^@font-face/)) {
// below we are trying to find matches to external link. E.g.
// @font-face {
// // ...
// src: local('Abel'), url(https://fonts.gstatic.com/s/abel/v6/UzN-iejR1VoXU2Oc-7LsbvesZW2xOQ-xsNqO47m55DA.woff2);
// }
//
// This regex will save extrnal link into first capture group
var fontUrlRegexp = /url\(["']?(.+?)["']?\)/;
// TODO: This needs to be changed to support multiple url declarations per font.
var fontUrlMatch = rule.cssText.match(fontUrlRegexp);
var externalFontUrl = (fontUrlMatch && fontUrlMatch[1]) || '';
var fontUrlIsDataURI = externalFontUrl.match(/^data:/);
if (fontUrlIsDataURI) {
// We should ignore data uri - they are already embedded
externalFontUrl = '';
}
if (externalFontUrl === 'about:blank') {
// no point trying to load this
externalFontUrl = '';
}
if (externalFontUrl) {
// okay, we are lucky. We can fetch this font later
//handle url if relative
if (externalFontUrl.startsWith('../')) {
externalFontUrl = sheets[i].href + '/../' + externalFontUrl
} else if (externalFontUrl.startsWith('./')) {
externalFontUrl = sheets[i].href + '/.' + externalFontUrl
}
fontsQueue.push({
text: rule.cssText,
// Pass url regex, so that once font is downladed, we can run `replace()` on it
fontUrlRegexp: fontUrlRegexp,
format: getFontMimeTypeFromUrl(externalFontUrl),
url: externalFontUrl
});
} else {
// otherwise, use previous logic
css += rule.cssText + '\n';
}
}
}
}
}
}
// Now all css is processed, it's time to handle scheduled fonts
processFontQueue(fontsQueue);
function getFontMimeTypeFromUrl(fontUrl) {
var supportedFormats = {
'woff2': 'font/woff2',
'woff': 'font/woff',
'otf': 'application/x-font-opentype',
'ttf': 'application/x-font-ttf',
'eot': 'application/vnd.ms-fontobject',
'sfnt': 'application/font-sfnt',
'svg': 'image/svg+xml'
};
var extensions = Object.keys(supportedFormats);
for (var i = 0; i < extensions.length; ++i) {
var extension = extensions[i];
// TODO: This is not bullet proof, it needs to handle edge cases...
if (fontUrl.indexOf('.' + extension) > 0) {
return supportedFormats[extension];
}
}
// If you see this error message, you probably need to update code above.
console.error('Unknown font format for ' + fontUrl + '; Fonts may not be working correctly');
return 'application/octet-stream';
}
function processFontQueue(queue) {
if (queue.length > 0) {
// load fonts one by one until we have anything in the queue:
var font = queue.pop();
processNext(font);
} else {
// no more fonts to load.
cssLoadedCallback(css);
}
function processNext(font) {
// TODO: This could benefit from caching.
var oReq = new XMLHttpRequest();
oReq.addEventListener('load', fontLoaded);
oReq.addEventListener('error', transferFailed);
oReq.addEventListener('abort', transferFailed);
oReq.open('GET', font.url);
oReq.responseType = 'arraybuffer';
oReq.send();
function fontLoaded() {
// TODO: it may be also worth to wait until fonts are fully loaded before
// attempting to rasterize them. (e.g. use https://developer.mozilla.org/en-US/docs/Web/API/FontFaceSet )
var fontBits = oReq.response;
var fontInBase64 = arrayBufferToBase64(fontBits);
updateFontStyle(font, fontInBase64);
}
function transferFailed(e) {
console.warn('Failed to load font from: ' + font.url);
console.warn(e);
css += font.text + '\n';
processFontQueue(queue);
}
function updateFontStyle(font, fontInBase64) {
var dataUrl = 'url("data:' + font.format + ';base64,' + fontInBase64 + '")';
css += font.text.replace(font.fontUrlRegexp, dataUrl) + '\n';
// schedule next font download on next tick.
setTimeout(function () {
processFontQueue(queue)
}, 0);
}
}
}
function arrayBufferToBase64(buffer) {
var binary = '';
var bytes = new Uint8Array(buffer);
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return window.btoa(binary);
}
}
function getDimension(el, clone, dim) {
var v = (el.viewBox && el.viewBox.baseVal && el.viewBox.baseVal[dim]) ||
(clone.getAttribute(dim) !== null && !clone.getAttribute(dim).match(/%$/) && parseInt(clone.getAttribute(dim))) ||
el.getBoundingClientRect()[dim] ||
parseInt(clone.style[dim]) ||
parseInt(window.getComputedStyle(el).getPropertyValue(dim));
return (typeof v === 'undefined' || v === null || isNaN(parseFloat(v))) ? 0 : v;
}
function reEncode(data) {
data = encodeURIComponent(data);
data = data.replace(/%([0-9A-F]{2})/g, function (match, p1) {
var c = String.fromCharCode('0x' + p1);
return c === '%' ? '%25' : c;
});
return decodeURIComponent(data);
}
out$.prepareSvg = function (el, options, cb) {
requireDomNode(el);
options = options || {};
options.scale = options.scale || 1;
options.responsive = options.responsive || false;
var xmlns = "http://www.w3.org/2000/xmlns/";
inlineImages(el, function () {
var outer = document.createElement("div");
var clone = el.cloneNode(true);
var width, height;
if (el.tagName == 'svg') {
width = options.width || getDimension(el, clone, 'width');
height = options.height || getDimension(el, clone, 'height');
} else if (el.getBBox) {
var box = el.getBBox();
width = box.x + box.width;
height = box.y + box.height;
clone.setAttribute('transform', clone.getAttribute('transform').replace(/translate\(.*?\)/, ''));
var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.appendChild(clone);
clone = svg;
} else {
console.error('Attempted to render non-SVG element', el);
return;
}
clone.setAttribute("version", "1.1");
if (!clone.getAttribute('xmlns')) {
clone.setAttributeNS(xmlns, "xmlns", "http://www.w3.org/2000/svg");
}
if (!clone.getAttribute('xmlns:xlink')) {
clone.setAttributeNS(xmlns, "xmlns:xlink", "http://www.w3.org/1999/xlink");
}
if (options.responsive) {
clone.removeAttribute('width');
clone.removeAttribute('height');
clone.setAttribute('preserveAspectRatio', 'xMinYMin meet');
} else {
clone.setAttribute("width", width * options.scale);
clone.setAttribute("height", height * options.scale);
}
clone.setAttribute("viewBox", [
options.left || 0,
options.top || 0,
width,
height
].join(" "));
var fos = clone.querySelectorAll('foreignObject > *');
for (var i = 0; i < fos.length; i++) {
if (!fos[i].getAttribute('xmlns')) {
fos[i].setAttributeNS(xmlns, "xmlns", "http://www.w3.org/1999/xhtml");
}
}
outer.appendChild(clone);
// In case of custom fonts we need to fetch font first, and then inline
// its url into data-uri format (encode as base64). That's why style
// processing is done asynchonously. Once all inlining is finshed
// cssLoadedCallback() is called.
styles(el, options, cssLoadedCallback);
function cssLoadedCallback(css) {
// here all fonts are inlined, so that we can render them properly.
var s = document.createElement('style');
s.setAttribute('type', 'text/css');
s.innerHTML = "<![CDATA[\n" + css + "\n]]>";
var defs = document.createElement('defs');
defs.appendChild(s);
clone.insertBefore(defs, clone.firstChild);
if (cb) {
var outHtml = outer.innerHTML;
outHtml = outHtml.replace(/NS\d+:href/gi, 'xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href');
cb(outHtml, width, height);
}
}
});
};
out$.svgAsDataUri = function (el, options, cb) {
out$.prepareSvg(el, options, function (svg) {
var uri = 'data:image/svg+xml;base64,' + window.btoa(reEncode(doctype + svg));
if (cb) {
cb(uri);
}
});
};
out$.svgAsPngUri = function (el, options, cb) {
requireDomNode(el);
options = options || {};
options.encoderType = options.encoderType || 'image/png';
options.encoderOptions = options.encoderOptions || 0.8;
var convertToPng = function (src, w, h) {
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
canvas.width = w;
canvas.height = h;
if (options.canvg) {
options.canvg(canvas, src);
} else {
context.drawImage(src, 0, 0);
}
if (options.backgroundColor) {
context.globalCompositeOperation = 'destination-over';
context.fillStyle = options.backgroundColor;
context.fillRect(0, 0, canvas.width, canvas.height);
}
var png;
try {
png = canvas.toDataURL(options.encoderType, options.encoderOptions);
} catch (e) {
if ((typeof SecurityError !== 'undefined' && e instanceof SecurityError) || e.name == "SecurityError") {
console.error("Rendered SVG images cannot be downloaded in this browser.");
return;
} else {
throw e;
}
}
cb(png);
};
if (options.canvg) {
out$.prepareSvg(el, options, convertToPng);
} else {
out$.svgAsDataUri(el, options, function (uri) {
var image = new Image();
image.onload = function () {
convertToPng(image, image.width, image.height);
};
image.onerror = function () {
console.error(
'There was an error loading the data URI as an image on the following SVG\n',
window.atob(uri.slice(26)), '\n',
"Open the following link to see browser's diagnosis\n",
uri);
};
image.src = uri;
});
}
};
out$.download = function (name, uri) {
if (navigator.msSaveOrOpenBlob) {
navigator.msSaveOrOpenBlob(uriToBlob(uri), name);
} else {
var saveLink = document.createElement('a');
var downloadSupported = 'download' in saveLink;
if (downloadSupported) {
saveLink.download = name;
saveLink.style.display = 'none';
document.body.appendChild(saveLink);
try {
var blob = uriToBlob(uri);
var url = URL.createObjectURL(blob);
saveLink.href = url;
saveLink.onclick = function () {
requestAnimationFrame(function () {
URL.revokeObjectURL(url);
})
};
} catch (e) {
console.warn('This browser does not support object URLs. Falling back to string URL.');
saveLink.href = uri;
}
saveLink.click();
document.body.removeChild(saveLink);
} else {
window.open(uri, '_temp', 'menubar=no,toolbar=no,status=no');
}
}
};
function uriToBlob(uri) {
var byteString = window.atob(uri.split(',')[1]);
var mimeString = uri.split(',')[0].split(':')[1].split(';')[0];
var buffer = new ArrayBuffer(byteString.length);
var intArray = new Uint8Array(buffer);
for (var i = 0; i < byteString.length; i++) {
intArray[i] = byteString.charCodeAt(i);
}
return new Blob([buffer], {type: mimeString});
}
out$.saveSvg = function (el, name, options) {
requireDomNode(el);
options = options || {};
out$.svgAsDataUri(el, options, function (uri) {
out$.download(name, uri);
});
};
out$.saveSvgAsPng = function (el, name, options) {
requireDomNode(el);
options = options || {};
out$.svgAsPngUri(el, options, function (uri) {
out$.download(name, uri);
});
};
// if define is defined create as an AMD module
if (typeof define !== 'undefined') {
define(function () {
return out$;
});
}
})();
|
var group__DAP__Config__Timestamp__gr =
[
[ "TIMESTAMP_GET", "group__DAP__Config__Timestamp__gr.html#gaf9bdc40d3a256fc2cc4d26b295993d9c", null ]
];
|