text
stringlengths 3
1.05M
|
|---|
!function(e){function r(r){for(var n,u,i=r[0],l=r[1],p=r[2],c=0,s=[];c<i.length;c++)u=i[c],Object.prototype.hasOwnProperty.call(o,u)&&o[u]&&s.push(o[u][0]),o[u]=0;for(n in l)Object.prototype.hasOwnProperty.call(l,n)&&(e[n]=l[n]);for(f&&f(r);s.length;)s.shift()();return a.push.apply(a,p||[]),t()}function t(){for(var e,r=0;r<a.length;r++){for(var t=a[r],n=!0,i=1;i<t.length;i++){var l=t[i];0!==o[l]&&(n=!1)}n&&(a.splice(r--,1),e=u(u.s=t[0]))}return e}var n={},o={1:0},a=[];function u(r){if(n[r])return n[r].exports;var t=n[r]={i:r,l:!1,exports:{}};return e[r].call(t.exports,t,t.exports,u),t.l=!0,t.exports}u.m=e,u.c=n,u.d=function(e,r,t){u.o(e,r)||Object.defineProperty(e,r,{enumerable:!0,get:t})},u.r=function(e){"undefined"!==typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},u.t=function(e,r){if(1&r&&(e=u(e)),8&r)return e;if(4&r&&"object"===typeof e&&e&&e.__esModule)return e;var t=Object.create(null);if(u.r(t),Object.defineProperty(t,"default",{enumerable:!0,value:e}),2&r&&"string"!=typeof e)for(var n in e)u.d(t,n,function(r){return e[r]}.bind(null,n));return t},u.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return u.d(r,"a",r),r},u.o=function(e,r){return Object.prototype.hasOwnProperty.call(e,r)},u.p="/br-bad-universe-react-app/";var i=this["webpackJsonpbreaking-bad-database"]=this["webpackJsonpbreaking-bad-database"]||[],l=i.push.bind(i);i.push=r,i=i.slice();for(var p=0;p<i.length;p++)r(i[p]);var f=l;t()}([]);
//# sourceMappingURL=runtime-main.8754e8a4.js.map
|
const debug = require('debug')('eqws-router');
const error = require('debug')('eqws-router:error');
const compose = require('koa-compose');
const Protocol = require('eqws-protocol');
const C = Protocol.C;
const ApiError = Protocol.ApiError;
const Context = require('./Context');
class Router {
constructor(opts = {}) {
this._methods = {};
this._middlewares = [];
this._options = opts;
this.init = this.init.bind(this);
}
define(method, handler) {
const route = {};
if (arguments.length === 1 && 'object' === typeof method) {
route = opts;
} else if (arguments.length === 2) {
route.path = method;
route.handler = handler;
} else if (arguments.length > 2) {
let args = Array.prototype.slice.call(arguments);
route.path = args.shift();
route.handler = compose(args);
} else {
throw new Error('Invalid route define arguments');
}
debug('define method=%s', method);
this._methods[method] = { handler };
}
init(wss, opts) {
debug('open chanel');
const controller = this._controller.bind(this);
wss.on(`packet:${C.PACKET_TYPES.RPC}`, controller);
}
use(fn) {
this._middlewares.push(fn);
}
match(path) {
return this._methods[path];
}
_controller(socket, packet) {
const ctx = new Context(socket, this._options);
debug('socket=%s request=%j', socket.id, packet.data);
try {
ctx._parseRequest(packet.data);
} catch (err) {
error(err);
return ctx._onError(err);
}
const route = this.match(ctx.path);
if (!route) {
error('method=%s not defined', ctx.path);
let err = ApiError.incorrectMethod(ctx.path);
return ctx._onError(err);
}
let way = this._middlewares.concat(route.handler);
let fn = compose(way);
debug('middlewares method=%s compose', ctx.path);
fn(ctx)
.then(ctx.send.bind(ctx))
.catch(ctx._onError.bind(ctx));
}
}
module.exports = Router;
|
const { NotImplementedError } = require("../extensions/index.js");
const { Node } = require("../extensions/list-tree.js");
/**
* Implement simple binary search tree according to task description
* using Node from extensions
*/
module.exports = class BinarySearchTree {
constructor() {
this.binRoot = null;
}
root() {
// throw new NotImplementedError('Not implemented');
return this.binRoot;
// remove line with error and write your code here
}
add(data) {
// throw new NotImplementedError('Not implemented');
const node = this.binRoot;
if (node === null) {
this.binRoot = new Node(data);
return;
} else {
const binTree = function (node) {
if (data < node.data) {
if (node.left === null) {
node.left = new Node(data);
return;
} else if (node.left !== null) {
return binTree(node.left);
}
} else if (data > node.data) {
if (node.right === null) {
node.right = new Node(data);
return;
} else if (node.right !== null) {
return binTree(node.right);
}
} else {
return null;
}
};
return binTree(node);
}
// remove line with error and write your code here
}
has(data) {
// throw new NotImplementedError('Not implemented');
let current = this.binRoot;
if (current === null) return null;
while (current) {
if (data === current.data) {
return true;
}
if (data < current.data ) {
if (current.left !== null) current = current.left;
else return false;
}
if (data > current.data) {
if (current.right !== null) current = current.right;
else return false;
}
}
return false;
// remove line with error and write your code here
}
find(data) {
// throw new NotImplementedError('Not implemented');
let current = this.binRoot;
while (current.data !== data) {
if (data < current.data) {
current = current.left;
} else if (data > current.data) {
current = current.right;
}
if (current === null) {
return null;
}
}
return current;
// remove line with error and write your code here
}
minNode(node) {
if (node.left === null) return node;
else return this.findMinNode(node.left);
}
findMinNode(node) {
let tree = node;
if (tree.left === null) {
return tree;
} else {
return this.findMinNode(node.left);
}
}
remove(data) {
// throw new NotImplementedError('Not implemented');
this.binRoot = this.removeNode(this.binRoot, data);
// remove line with error and write your code here
}
removeNode(node, data) {
if (node === null) {
return null;
} else if (data < node.data) {
node.left = this.removeNode(node.left, data);
return node;
} else if (data > node.data) {
node.right = this.removeNode(node.right, data);
return node;
} else {
if (node.left === null && node.right === null) {
node = null;
return node;
}
if (node.left === null) {
node = node.right;
return node;
} else if (node.right === null) {
node = node.left;
return node;
}
let newNode = this.minNode(node.right);
node.data = newNode.data;
node.right = this.removeNode(node.right, newNode.data);
return node;
}
}
min() {
// throw new NotImplementedError('Not implemented');
let current = this.binRoot;
if (current === null) return null;
while (current.left !== null) {
current = current.left;
}
return current.data;
// remove line with error and write your code here
}
max() {
// throw new NotImplementedError('Not implemented');
let current = this.binRoot;
if (current === null) return null;
while (current.right !== null) {
current = current.right;
}
return current.data;
// remove line with error and write your code here
}
};
|
var connect = function(root) {
if (!root) return null
let q = [root]
while (q.length) {
let next = []
for (let i = 0; i < q.length; i++) {
let node = q[i]
if (node.left) next.push(node.left)
if (node.right) next.push(node.right)
if (q[i+1]) node.next = q[i+1]
}
q = next
}
return root
};
|
/*!
* FileInput Indonesian Translations
*
* This file must be loaded after 'fileinput.js'. Patterns in braces '{}', or
* any HTML markup tags in the messages must not be converted or translated.
*
* @see http://github.com/kartik-v/bootstrap-fileinput
* @author Bambang Riswanto <bamz3r@gmail.com>
*
* NOTE: this file must be saved in UTF-8 encoding.
*/
(function ($) {
"use strict";
$.fn.fileinputLocales['id'] = {
fileSingle: 'berkas',
filePlural: 'berkas',
browseLabel: 'Pilih berkas …',
removeLabel: 'Hapus',
removeTitle: 'Hapus berkas terpilih',
cancelLabel: 'Batal',
cancelTitle: 'Batalkan proses pengunggahan',
pauseLabel: 'Pause',
pauseTitle: 'Pause ongoing upload',
uploadLabel: 'Unggah',
uploadTitle: 'Unggah berkas terpilih',
msgNo: 'Tidak',
msgNoFilesSelected: '',
msgPaused: 'Paused',
msgCancelled: 'Dibatalkan',
msgPlaceholder: 'Pilih {files}...',
msgZoomModalHeading: 'Pratinjau terperinci',
msgFileRequired: 'Anda harus memilih berkas untuk diunggah.',
msgSizeTooSmall: 'Berkas "{name}" (<b>{size} KB</b>) terlalu kecil dan harus lebih besar dari <b>{minSize} KB</b>.',
msgSizeTooLarge: 'Berkas "{name}" (<b>{size} KB</b>) melebihi ukuran unggah maksimal yaitu <b>{maxSize} KB</b>.',
msgFilesTooLess: 'Anda harus memilih setidaknya <b>{n}</b> {files} untuk diunggah.',
msgFilesTooMany: '<b>({n})</b> berkas yang dipilih untuk diunggah melebihi ukuran unggah maksimal yaitu <b>{m}</b>.',
msgFileNotFound: 'Berkas "{name}" tak ditemukan!',
msgFileSecured: 'Sistem keamanan mencegah untuk membaca berkas "{name}".',
msgFileNotReadable: 'Berkas "{name}" tak dapat dibaca.',
msgFilePreviewAborted: 'Pratinjau untuk berkas "{name}" dibatalkan.',
msgFilePreviewError: 'Kesalahan saat membaca berkas "{name}".',
msgInvalidFileName: 'Karakter tidak dikenali atau tidak didukung untuk nama berkas "{name}".',
msgInvalidFileType: 'Jenis berkas "{name}" tidak sah. Hanya berkas "{types}" yang didukung.',
msgInvalidFileExtension: 'Ekstensi berkas "{name}" tidak sah. Hanya ekstensi "{extensions}" yang didukung.',
msgFileTypes: {
'image': 'image',
'html': 'HTML',
'text': 'text',
'video': 'video',
'audio': 'audio',
'flash': 'flash',
'pdf': 'PDF',
'object': 'object'
},
msgUploadAborted: 'Proses Unggah berkas dibatalkan',
msgUploadThreshold: 'Memproses...',
msgUploadBegin: 'Menyiapkan...',
msgUploadEnd: 'Selesai',
msgUploadResume: 'Resuming upload...',
msgUploadEmpty: 'Tidak ada data valid yang tersedia untuk diunggah.',
msgUploadError: 'Upload Error',
msgDeleteError: 'Delete Error',
msgProgressError: 'Kesalahan',
msgValidationError: 'Kesalahan saat memvalidasi',
msgLoading: 'Memuat {index} dari {files} berkas …',
msgProgress: 'Memuat {index} dari {files} berkas - {name} - {percent}% selesai.',
msgSelected: '{n} {files} dipilih',
msgFoldersNotAllowed: 'Hanya tahan dan lepas file saja! {n} folder diabaikan.',
msgImageWidthSmall: 'Lebar dari gambar "{name}" harus sekurangnya {size} px.',
msgImageHeightSmall: 'Tinggi dari gambar "{name}" harus sekurangnya {size} px.',
msgImageWidthLarge: 'Lebar dari gambar "{name}" tak boleh melebihi {size} px.',
msgImageHeightLarge: 'Tinggi dari gambar "{name}" tak boleh melebihi {size} px.',
msgImageResizeError: 'Tidak dapat menentukan dimensi gambar untuk mengubah ukuran.',
msgImageResizeException: 'Kesalahan saat mengubah ukuran gambar.<pre>{errors}</pre>',
msgAjaxError: 'Terjadi kesalahan ketika melakukan operasi {operation}. Silahkan coba lagi nanti!',
msgAjaxProgressError: '{operation} gagal',
msgDuplicateFile: 'File "{name}" of same size "{size} KB" has already been selected earlier. Skipping duplicate selection.',
msgResumableUploadRetriesExceeded: 'Upload aborted beyond <b>{max}</b> retries for file <b>{file}</b>! Error Details: <pre>{error}</pre>',
msgPendingTime: '{time} remaining',
msgCalculatingTime: 'calculating time remaining',
ajaxOperations: {
deleteThumb: 'Hapus berkas',
uploadThumb: 'Unggah berkas',
uploadBatch: 'Unggah banyak berkas',
uploadExtra: 'Unggah form ekstra'
},
dropZoneTitle: 'Tarik dan lepaskan berkas disini …',
dropZoneClickTitle: '<br>(atau klik untuk memilih {files})',
fileActionSettings: {
removeTitle: 'Hapus Berkas',
uploadTitle: 'Unggah Berkas',
uploadRetryTitle: 'Unggah Ulang',
downloadTitle: 'Unduh Berkas',
zoomTitle: 'Tampilkan Rincian',
dragTitle: 'Pindah atau Atur Ulang',
indicatorNewTitle: 'Belum diunggah',
indicatorSuccessTitle: 'Sudah diunggah',
indicatorErrorTitle: 'Kesalahan dalam mengungah',
indicatorPausedTitle: 'Upload Paused',
indicatorLoadingTitle: 'Mengunggah ...'
},
previewZoomButtonTitles: {
prev: 'Lihat berkas sebelumnya',
next: 'Lihat berkas selanjutnya',
toggleheader: 'Beralih ke tajuk',
fullscreen: 'Beralih ke mode penuh',
borderless: 'Beralih ke mode tanpa tepi',
close: 'Tutup pratinjau terperinci'
}
};
})(window.jQuery);
|
import React from 'react'
import Helmet from 'react-helmet'
import { StaticQuery, graphql } from 'gatsby'
import Header from '../components/header'
const Layout = ({children}) => (
<StaticQuery
query={graphql`
query SiteTitleQuery {
site {
siteMetadata {
title
description
keywords
}
}
}
`}
render={( data ) => (
<>
<Helmet
title={data.site.siteMetadata.title}
meta={[
{ name: 'description', content: data.site.siteMetadata.description },
{ name: 'keywords', content: data.site.siteMetadata.keywords },
]}
>
<html lang="en" />
</Helmet>
<Header />
{children}
</>
)}
/>
)
export default Layout
|
const webpack = require('webpack');
const path = require('path');
const WebpackPwaManifest = require('webpack-pwa-manifest');
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const TerserJSPlugin = require('terser-webpack-plugin');
const RobotstxtPlugin = require("robotstxt-webpack-plugin");
const CopyPlugin = require('copy-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const Config = require("./_config");
const MarkdownRSSGeneratorPlugin = require("markdown-rss-generator-webpack-plugin").default;
const MarkdownToJS = require("markdown-to-js-webpack-plugin").default;
const MarkdownSiteMapGeneratorPlugin = require("markdown-sitemap-generator-webpack-plugin").default;
const { GenerateSW } = require('workbox-webpack-plugin');
module.exports = {
mode: "production",
entry: [
"@babel/polyfill",
path.resolve(__dirname, 'src/index.js')
],
mode: "production",
target: 'web',
output: {
path: __dirname + '/dist',
publicPath: '/',
filename: '[name].[contenthash].js'
},
devServer: {
contentBase: path.resolve(__dirname, 'dist')
},
optimization: {
minimizer: [new TerserJSPlugin({}), new OptimizeCSSAssetsPlugin({})],
splitChunks: {
cacheGroups: {
commons: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all'
}
}
}
},
node: {
fs: 'empty'
},
module: {
rules: [
{
test: /\.(js|jsx)?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
},
{
test: /\.js$/,
loaders: ['unlazy'],
include: /node_modules\/markdown-toc/
},
{
test: /(\.css)$/,
use: [MiniCssExtractPlugin.loader, "css-loader"]
},
{
test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
use: [{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'fonts/'
}
}]
},
{
test: /\.md$/,
use: [{
loader: 'file-loader',
options: {
name: '[name].[hash].[ext]',
outputPath: 'posts/'
}
}]
}
]
},
plugins: [
new CopyPlugin(
[
{
context: __dirname + '/src',
from: 'netlify.toml',
to: '',
},
{
context: __dirname + "/posts",
from: 'images/**/*',
to: '',
}
]
),
new MarkdownSiteMapGeneratorPlugin({
host: Config.url,
links: [
"https://www.eatsomemore.com/posts/categories/%E6%B8%B8%E8%AE%B0?tags=%E8%8B%B1%E5%9B%BD&pagetype=uk-tour",
"https://www.eatsomemore.com/posts/categories/%E7%BE%8E%E9%A3%9F?tags=%E8%8B%B1%E5%9B%BD&pagetype=uk-food",
"https://www.eatsomemore.com/posts/categories/%E6%94%BB%E7%95%A5?tags=%E8%8B%B1%E5%9B%BD&pagetype=uk-play",
"https://www.eatsomemore.com/posts/categories/%E9%A2%84%E5%AE%9A?tags=%E8%8B%B1%E5%9B%BD&pagetype=uk-guide",
"https://www.eatsomemore.com/posts/categories/%E6%B8%B8%E8%AE%B0?extags=%E8%8B%B1%E5%9B%BD&pagetype=other-tour",
],
route: "/items",
outputPath: "sitemap.txt"
}),
new MarkdownRSSGeneratorPlugin({
title: Config.site,
outputPath: "rss.xml", //rss file output path
description: Config.description,
link: Config.url,
language: Config.language,
image: Config.logo,
favicon: Config.logo,
copyright: "All rights reserved " + new Date().getFullYear() + " " + Config.site,
updated: new Date(), //updated date
generator: "Sporule",
author: {
name: Config.site,
email: Config.email,
link: Config.url
},
}),
new RobotstxtPlugin({
policy: [
{
userAgent: "*",
disallow:"/404/",
allow: "/"
}
],
sitemap: Config.url + "/sitemap.txt",
host: Config.url
}),
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
inject: false,
template: 'template/index.html',
templateParameters: (compilation, assets, assetTags, options)=>{
return{
compilation,
webpackConfig: compilation.options,
htmlWebpackPlugin: {
tags: assetTags,
files: assets,
options
},
Config
}
}
}),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.optimize.ModuleConcatenationPlugin(),
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: "[name].[contenthash].css",
chunkFilename: "[id].css"
}),
new MarkdownToJS(),
new GenerateSW({
maximumFileSizeToCacheInBytes: 1e+7,
skipWaiting: true,
runtimeCaching: [{
urlPattern: new RegExp('/\.(js|css)$/i'),
// urlPattern: new RegExp('/\.(js|css|png|jpe?g|gif|svg)$/i'),
handler: 'StaleWhileRevalidate'
}],
exclude: [/\.(md|png|jpe?g|gif|xml|toml|txt|gz)$/i, /CNAME/i,/md\.js/i],
// exclude: [/\.(md|xml|toml|txt|gz)$/i, /CNAME/i,/md\.js/i],
swDest: 'sw.js'
}),
new WebpackPwaManifest({
name: Config.site,
short_name: Config.site,
description: Config.description,
display: "standalone",
start_url: ".",
crossorigin: null,
background_color: '#ffffff',
includeDirectory: true,
orientation: 'any',
crossorigin: 'anonymous', //can be null, use-credentials or anonymous
"theme_color": "#3367D6",
icons: [
{
src: path.resolve('publish_assets/logo-ios-black-512.png'),
sizes: [96, 128, 192, 256, 384, 512],
},
],
ios: {
'apple-mobile-web-app-title': Config.site,
'apple-mobile-web-app-status-bar-style': 'black-translucent'
}
})
]
}
|
Prism.languages.yaml = {
'scalar': {
pattern: /([\-:]\s*(![^\s]+)?[ \t]*[|>])[ \t]*(?:((?:\r?\n|\r)[ \t]+)[^\r\n]+(?:\3[^\r\n]+)*)/,
lookbehind: true,
alias: 'string'
},
'comment': /#.*/,
'key': {
pattern: /(\s*(?:^|[:\-,[{\r\n?])[ \t]*(![^\s]+)?[ \t]*)[^\r\n{[\]},#\s]+?(?=\s*:\s)/,
lookbehind: true,
alias: 'atrule'
},
'directive': {
pattern: /(^[ \t]*)%.+/m,
lookbehind: true,
alias: 'important'
},
'datetime': {
pattern: /([:\-,[{]\s*(![^\s]+)?[ \t]*)(\d{4}-\d\d?-\d\d?([tT]|[ \t]+)\d\d?:\d{2}:\d{2}(\.\d*)?[ \t]*(Z|[-+]\d\d?(:\d{2})?)?|\d{4}-\d{2}-\d{2}|\d\d?:\d{2}(:\d{2}(\.\d*)?)?)(?=[ \t]*($|,|]|}))/m,
lookbehind: true,
alias: 'number'
},
'boolean': {
pattern: /([:\-,[{]\s*(![^\s]+)?[ \t]*)(true|false)[ \t]*(?=$|,|]|})/im,
lookbehind: true,
alias: 'important'
},
'null': {
pattern: /([:\-,[{]\s*(![^\s]+)?[ \t]*)(null|~)[ \t]*(?=$|,|]|})/im,
lookbehind: true,
alias: 'important'
},
'string': {
pattern: /([:\-,[{]\s*(![^\s]+)?[ \t]*)("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')(?=[ \t]*($|,|]|}))/m,
lookbehind: true,
greedy: true
},
'number': {
pattern: /([:\-,[{]\s*(![^\s]+)?[ \t]*)[+\-]?(0x[\da-f]+|0o[0-7]+|(\d+\.?\d*|\.?\d+)(e[\+\-]?\d+)?|\.inf|\.nan)[ \t]*(?=$|,|]|})/im,
lookbehind: true
},
'tag': /![^\s]+/,
'important': /[&*][\w]+/,
'punctuation': /---|[:[\]{}\-,|>?]|\.\.\./
};
|
$(document).ready(function(){
// Add smooth scrolling to all links
$("a").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
// Age up-to date
$("#age").text(((new Date() - new Date('1988-01-22T00:00:00'))/1000/3600/24/365.33).toFixed(2));
// Experience up-to date
$("#exp").text(((new Date() - new Date('2012-05-01T00:00:00'))/1000/3600/24/365.33).toFixed(1));
function setupTypewriter(t) {
var HTML = t.innerHTML;
t.innerHTML = "";
var cursorPosition = 0,
tag = "",
writingTag = false,
tagOpen = false,
typeSpeed = 30,
tempTypeSpeed = 0;
var type = function() {
if (writingTag === true) {
tag += HTML[cursorPosition];
}
if (HTML[cursorPosition] === "<") {
tempTypeSpeed = 0;
if (tagOpen) {
tagOpen = false;
writingTag = true;
} else {
tag = "";
tagOpen = true;
writingTag = true;
tag += HTML[cursorPosition];
}
}
if (!writingTag && tagOpen) {
tag.innerHTML += HTML[cursorPosition];
}
if (!writingTag && !tagOpen) {
if (HTML[cursorPosition] === " ") {
tempTypeSpeed = 0;
}
else {
tempTypeSpeed = (Math.random() * typeSpeed) + 30;
}
t.innerHTML += HTML[cursorPosition];
}
if (writingTag === true && HTML[cursorPosition] === ">") {
tempTypeSpeed = (Math.random() * typeSpeed) + 30;
writingTag = false;
if (tagOpen) {
var newSpan = document.createElement("span");
t.appendChild(newSpan);
newSpan.innerHTML = tag;
tag = newSpan.firstChild;
}
}
cursorPosition += 1;
if (cursorPosition < HTML.length - 1) {
setTimeout(type, tempTypeSpeed);
}
};
return {
type: type
};
}
var typer = document.getElementById('typewriter');
var typerShown = false;
typewriter = setupTypewriter(typewriter);
window.addEventListener('scroll', function() {
var position = typer.getBoundingClientRect();
// checking whether fully visible
if(position.top >= 0 && position.bottom <= window.innerHeight && !typerShown) {
typerShown = true;
typewriter.type();
}
})
});
|
from django import template
register = template.Library()
class RepeatNode(template.Node):
def __init__(self, nodelist, count):
self.nodelist = nodelist
self.count = template.Variable(count)
def render(self, context):
output = self.nodelist.render(context)
return output * int(self.count.resolve(context))
def repeat(parser, token):
"""
Repeats the containing text a certain number of times.
Requires a single argument, an integer, to indicate the number of times to
repeat the enclosing content.
Example::
{% repeat 3 %}foo{% endrepeat %}
Yields::
foofoofoo
"""
bits = token.split_contents()
if len(bits) != 2:
raise template.TemplateSyntaxError('%r tag requires 1 argument.' % bits[0])
count = bits[1]
nodelist = parser.parse(('endrepeat',))
parser.delete_first_token()
return RepeatNode(nodelist, count)
repeat = register.tag(repeat)
|
import BaseAPI from '../baseApi';
import axios from '../../plugins/axios';
class TextAPI extends BaseAPI {
constructor() {
super('writing/texts');
}
create(item, originalId) {
return axios.post(`${this.endpoint}${originalId ? '?copy=' + originalId : ''}`, item);
}
}
export default new TextAPI();
|
/**
* @file themes tool.
*
* @author <a href='http://vanessa.b3log.org'>Liyuan Li</a>
* @version 1.0.0.1, May 28, 2019
*/
const gulp = require('gulp')
const sass = require('gulp-sass')
const rename = require('gulp-rename')
var uglify = require('gulp-uglify')
const fs = require('fs')
const browserify = require('browserify')
const source = require('vinyl-source-stream')
const buffer = require('vinyl-buffer')
function themeSassProcess () {
return gulp.src('./x/*/css/*.scss').
pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError)).
pipe(gulp.dest('./x'))
}
function themeSassProcessWatch () {
gulp.watch('./x/*/css/*.scss', themeSassProcess)
}
function baseSassProcess () {
return gulp.src('./scss/*.scss').
pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError)).
pipe(gulp.dest('./scss'))
}
function baseSassProcessWatch () {
gulp.watch('./scss/*.scss', baseSassProcess)
}
function devJSProcessWatch () {
const watcher = gulp.watch([
'./x/*/js/common.js'])
watcher.on('change', function (entry) {
browserify({entries: [entry]}).
transform('babelify', {presets: ['@babel/preset-env']}).
bundle().
on('error', function (err) { console.error(err) }).
pipe(source(entry)).
pipe(rename({suffix: '.min'})).
pipe(buffer()).
pipe(gulp.dest('.'))
console.log('[Packed] ' + entry)
})
}
gulp.task('watch',
gulp.parallel(themeSassProcessWatch, baseSassProcessWatch, devJSProcessWatch))
function updateVersion () {
// set static version
const newVersion = (new Date()).getTime()
// set pipe.json
fs.writeFileSync('../pipe.json',
fs.readFileSync('../pipe.json', 'UTF-8').
replace(/"StaticResourceVersion": "\d{13}"/,
`"StaticResourceVersion": "${newVersion}"`), 'UTF-8')
// min sw.min.js.tpl
browserify({entries: `./sw.js`}).
transform('babelify', {presets: ['@babel/preset-env']}).
bundle().
on('error', function (err) { console.error(err) }).
pipe(source('sw.min.js.tpl')).
pipe(buffer()).
pipe(uglify()).
pipe(gulp.dest('.'))
// min sw.min.js
return browserify({entries: `./sw.js`}).
transform('babelify', {presets: ['@babel/preset-env']}).
bundle().
on('error', function (err) { console.error(err) }).
pipe(source('sw.min.js')).
pipe(buffer()).
pipe(uglify()).
pipe(gulp.dest('.'))
}
function minThemeJS () {
fs.readdirSync('./x').forEach(function (file) {
const jsPath = `./x/${file}/js/`
try {
fs.statSync(`${jsPath}/common.js`)
browserify({entries: [`${jsPath}/common.js`]}).
transform('babelify', {presets: ['@babel/preset-env']}).
bundle().
on('error', function (err) { console.error(err) }).
pipe(source(`${jsPath}/common.js`)).
pipe(rename({suffix: '.min'})).
pipe(buffer()).
pipe(uglify()).
pipe(gulp.dest('.'))
} catch (e) {
}
})
// fixed gulp task return error
return gulp.src('./sw.js');
}
gulp.task('default',
gulp.series(updateVersion,
gulp.parallel(themeSassProcess, baseSassProcess, minThemeJS)))
|
/*!
* jQuery JavaScript Library v1.9.1
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2005, 2012 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2013-2-4
*/
(function (window, undefined) {
// Can't do this because several apps including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
// Support: Firefox 18+
//"use strict";
var
// The deferred used on DOM ready
readyList,
// A central reference to the root jQuery(document)
rootjQuery,
// Support: IE<9
// For `typeof node.method` instead of `node.method !== undefined`
core_strundefined = typeof undefined,
// Use the correct document accordingly with window argument (sandbox)
document = window.document,
location = window.location,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// [[Class]] -> type pairs
class2type = {},
// List of deleted data cache ids, so we can reuse them
core_deletedIds = [],
core_version = "1.9.1",
// Save a reference to some core methods
core_concat = core_deletedIds.concat,
core_push = core_deletedIds.push,
core_slice = core_deletedIds.slice,
core_indexOf = core_deletedIds.indexOf,
core_toString = class2type.toString,
core_hasOwn = class2type.hasOwnProperty,
core_trim = core_version.trim,
// Define a local copy of jQuery
jQuery = function (selector, context) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init(selector, context, rootjQuery);
},
// Used for matching numbers
core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,
// Used for splitting on whitespace
core_rnotwhite = /\S+/g,
// Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE)
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
rquickExpr = /^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function (all, letter) {
return letter.toUpperCase();
},
// The ready event handler
completed = function (event) {
// readyState === "complete" is good enough for us to call the dom ready in oldIE
if (document.addEventListener || event.type === "load" || document.readyState === "complete") {
detach();
jQuery.ready();
}
},
// Clean-up method for dom ready events
detach = function () {
if (document.addEventListener) {
document.removeEventListener("DOMContentLoaded", completed, false);
window.removeEventListener("load", completed, false);
} else {
document.detachEvent("onreadystatechange", completed);
window.detachEvent("onload", completed);
}
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: core_version,
constructor: jQuery,
init: function (selector, context, rootjQuery) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if (!selector) {
return this;
}
// Handle HTML strings
if (typeof selector === "string") {
if (selector.charAt(0) === "<" && selector.charAt(selector.length - 1) === ">" && selector.length >= 3) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec(selector);
}
// Match html or make sure no context is specified for #id
if (match && (match[1] || !context)) {
// HANDLE: $(html) -> $(array)
if (match[1]) {
context = context instanceof jQuery ? context[0] : context;
// scripts is true for back-compat
jQuery.merge(this, jQuery.parseHTML(
match[1],
context && context.nodeType ? context.ownerDocument || context : document,
true
));
// HANDLE: $(html, props)
if (rsingleTag.test(match[1]) && jQuery.isPlainObject(context)) {
for (match in context) {
// Properties of context are called as methods if possible
if (jQuery.isFunction(this[ match ])) {
this[ match ](context[ match ]);
// ...and otherwise set as attributes
} else {
this.attr(match, context[ match ]);
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById(match[2]);
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if (elem && elem.parentNode) {
// Handle the case where IE and Opera return items
// by name instead of ID
if (elem.id !== match[2]) {
return rootjQuery.find(selector);
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if (!context || context.jquery) {
return ( context || rootjQuery ).find(selector);
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor(context).find(selector);
}
// HANDLE: $(DOMElement)
} else if (selector.nodeType) {
this.context = this[0] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if (jQuery.isFunction(selector)) {
return rootjQuery.ready(selector);
}
if (selector.selector !== undefined) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray(selector, this);
},
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
// The number of elements contained in the matched element set
size: function () {
return this.length;
},
toArray: function () {
return core_slice.call(this);
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function (num) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function (elems) {
// Build a new jQuery matched element set
var ret = jQuery.merge(this.constructor(), elems);
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function (callback, args) {
return jQuery.each(this, callback, args);
},
ready: function (fn) {
// Add the callback
jQuery.ready.promise().done(fn);
return this;
},
slice: function () {
return this.pushStack(core_slice.apply(this, arguments));
},
first: function () {
return this.eq(0);
},
last: function () {
return this.eq(-1);
},
eq: function (i) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack(j >= 0 && j < len ? [ this[j] ] : []);
},
map: function (callback) {
return this.pushStack(jQuery.map(this, function (elem, i) {
return callback.call(elem, i, elem);
}));
},
end: function () {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: core_push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function () {
var src, copyIsArray, copy, name, options, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if (typeof target === "boolean") {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if (typeof target !== "object" && !jQuery.isFunction(target)) {
target = {};
}
// extend jQuery itself if only one argument is passed
if (length === i) {
target = this;
--i;
}
for (; i < length; i++) {
// Only deal with non-null/undefined values
if ((options = arguments[ i ]) != null) {
// Extend the base object
for (name in options) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if (target === copy) {
continue;
}
// Recurse if we're merging plain objects or arrays
if (deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) )) {
if (copyIsArray) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend(deep, clone, copy);
// Don't bring in undefined values
} else if (copy !== undefined) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
noConflict: function (deep) {
if (window.$ === jQuery) {
window.$ = _$;
}
if (deep && window.jQuery === jQuery) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function (hold) {
if (hold) {
jQuery.readyWait++;
} else {
jQuery.ready(true);
}
},
// Handle when the DOM is ready
ready: function (wait) {
// Abort if there are pending holds or we're already ready
if (wait === true ? --jQuery.readyWait : jQuery.isReady) {
return;
}
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if (!document.body) {
return setTimeout(jQuery.ready);
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if (wait !== true && --jQuery.readyWait > 0) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith(document, [ jQuery ]);
// Trigger any bound ready events
if (jQuery.fn.trigger) {
jQuery(document).trigger("ready").off("ready");
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function (obj) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function (obj) {
return jQuery.type(obj) === "array";
},
isWindow: function (obj) {
return obj != null && obj == obj.window;
},
isNumeric: function (obj) {
return !isNaN(parseFloat(obj)) && isFinite(obj);
},
type: function (obj) {
if (obj == null) {
return String(obj);
}
return typeof obj === "object" || typeof obj === "function" ?
class2type[ core_toString.call(obj) ] || "object" :
typeof obj;
},
isPlainObject: function (obj) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if (!obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow(obj)) {
return false;
}
try {
// Not own constructor property must be Object
if (obj.constructor && !core_hasOwn.call(obj, "constructor") && !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf")) {
return false;
}
} catch (e) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for (key in obj) {
}
return key === undefined || core_hasOwn.call(obj, key);
},
isEmptyObject: function (obj) {
var name;
for (name in obj) {
return false;
}
return true;
},
error: function (msg) {
throw new Error(msg);
},
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
parseHTML: function (data, context, keepScripts) {
if (!data || typeof data !== "string") {
return null;
}
if (typeof context === "boolean") {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec(data),
scripts = !keepScripts && [];
// Single tag
if (parsed) {
return [ context.createElement(parsed[1]) ];
}
parsed = jQuery.buildFragment([ data ], context, scripts);
if (scripts) {
jQuery(scripts).remove();
}
return jQuery.merge([], parsed.childNodes);
},
parseJSON: function (data) {
// Attempt to parse using the native JSON parser first
if (window.JSON && window.JSON.parse) {
return window.JSON.parse(data);
}
if (data === null) {
return data;
}
if (typeof data === "string") {
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim(data);
if (data) {
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if (rvalidchars.test(data.replace(rvalidescape, "@")
.replace(rvalidtokens, "]")
.replace(rvalidbraces, ""))) {
return ( new Function("return " + data) )();
}
}
}
jQuery.error("Invalid JSON: " + data);
},
// Cross-browser xml parsing
parseXML: function (data) {
var xml, tmp;
if (!data || typeof data !== "string") {
return null;
}
try {
if (window.DOMParser) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString(data, "text/xml");
} else { // IE
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = "false";
xml.loadXML(data);
}
} catch (e) {
xml = undefined;
}
if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length) {
jQuery.error("Invalid XML: " + data);
}
return xml;
},
noop: function () {
},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function (data) {
if (data && jQuery.trim(data)) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function (data) {
window[ "eval" ].call(window, data);
} )(data);
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function (string) {
return string.replace(rmsPrefix, "ms-").replace(rdashAlpha, fcamelCase);
},
nodeName: function (elem, name) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function (obj, callback, args) {
var value,
i = 0,
length = obj.length,
isArray = isArraylike(obj);
if (args) {
if (isArray) {
for (; i < length; i++) {
value = callback.apply(obj[ i ], args);
if (value === false) {
break;
}
}
} else {
for (i in obj) {
value = callback.apply(obj[ i ], args);
if (value === false) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if (isArray) {
for (; i < length; i++) {
value = callback.call(obj[ i ], i, obj[ i ]);
if (value === false) {
break;
}
}
} else {
for (i in obj) {
value = callback.call(obj[ i ], i, obj[ i ]);
if (value === false) {
break;
}
}
}
}
return obj;
},
// Use native String.trim function wherever possible
trim: core_trim && !core_trim.call("\uFEFF\xA0") ?
function (text) {
return text == null ?
"" :
core_trim.call(text);
} :
// Otherwise use our own trimming functionality
function (text) {
return text == null ?
"" :
( text + "" ).replace(rtrim, "");
},
// results is for internal usage only
makeArray: function (arr, results) {
var ret = results || [];
if (arr != null) {
if (isArraylike(Object(arr))) {
jQuery.merge(ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
core_push.call(ret, arr);
}
}
return ret;
},
inArray: function (elem, arr, i) {
var len;
if (arr) {
if (core_indexOf) {
return core_indexOf.call(arr, elem, i);
}
len = arr.length;
i = i ? i < 0 ? Math.max(0, len + i) : i : 0;
for (; i < len; i++) {
// Skip accessing in sparse arrays
if (i in arr && arr[ i ] === elem) {
return i;
}
}
}
return -1;
},
merge: function (first, second) {
var l = second.length,
i = first.length,
j = 0;
if (typeof l === "number") {
for (; j < l; j++) {
first[ i++ ] = second[ j ];
}
} else {
while (second[j] !== undefined) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function (elems, callback, inv) {
var retVal,
ret = [],
i = 0,
length = elems.length;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for (; i < length; i++) {
retVal = !!callback(elems[ i ], i);
if (inv !== retVal) {
ret.push(elems[ i ]);
}
}
return ret;
},
// arg is for internal usage only
map: function (elems, callback, arg) {
var value,
i = 0,
length = elems.length,
isArray = isArraylike(elems),
ret = [];
// Go through the array, translating each of the items to their
if (isArray) {
for (; i < length; i++) {
value = callback(elems[ i ], i, arg);
if (value != null) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for (i in elems) {
value = callback(elems[ i ], i, arg);
if (value != null) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return core_concat.apply([], ret);
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function (fn, context) {
var args, proxy, tmp;
if (typeof context === "string") {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if (!jQuery.isFunction(fn)) {
return undefined;
}
// Simulated bind
args = core_slice.call(arguments, 2);
proxy = function () {
return fn.apply(context || this, args.concat(core_slice.call(arguments)));
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
access: function (elems, fn, key, value, chainable, emptyGet, raw) {
var i = 0,
length = elems.length,
bulk = key == null;
// Sets many values
if (jQuery.type(key) === "object") {
chainable = true;
for (i in key) {
jQuery.access(elems, fn, i, key[i], true, emptyGet, raw);
}
// Sets one value
} else if (value !== undefined) {
chainable = true;
if (!jQuery.isFunction(value)) {
raw = true;
}
if (bulk) {
// Bulk operations run against the entire set
if (raw) {
fn.call(elems, value);
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function (elem, key, value) {
return bulk.call(jQuery(elem), value);
};
}
}
if (fn) {
for (; i < length; i++) {
fn(elems[i], key, raw ? value : value.call(elems[i], i, fn(elems[i], key)));
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call(elems) :
length ? fn(elems[0], key) : emptyGet;
},
now: function () {
return ( new Date() ).getTime();
}
});
jQuery.ready.promise = function (obj) {
if (!readyList) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if (document.readyState === "complete") {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout(jQuery.ready);
// Standards-based browsers support DOMContentLoaded
} else if (document.addEventListener) {
// Use the handy event callback
document.addEventListener("DOMContentLoaded", completed, false);
// A fallback to window.onload, that will always work
window.addEventListener("load", completed, false);
// If IE event model is used
} else {
// Ensure firing before onload, maybe late but safe also for iframes
document.attachEvent("onreadystatechange", completed);
// A fallback to window.onload, that will always work
window.attachEvent("onload", completed);
// If IE and not a frame
// continually check to see if the document is ready
var top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch (e) {
}
if (top && top.doScroll) {
(function doScrollCheck() {
if (!jQuery.isReady) {
try {
// Use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
top.doScroll("left");
} catch (e) {
return setTimeout(doScrollCheck, 50);
}
// detach all dom ready events
detach();
// and execute any waiting functions
jQuery.ready();
}
})();
}
}
}
return readyList.promise(obj);
};
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function (i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
function isArraylike(obj) {
var length = obj.length,
type = jQuery.type(obj);
if (jQuery.isWindow(obj)) {
return false;
}
if (obj.nodeType === 1 && length) {
return true;
}
return type === "array" || type !== "function" &&
( length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj );
}
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions(options) {
var object = optionsCache[ options ] = {};
jQuery.each(options.match(core_rnotwhite) || [], function (_, flag) {
object[ flag ] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function (options) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions(options) ) :
jQuery.extend({}, options);
var // Flag to know if list is currently firing
firing,
// Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// First callback to fire (used internally by add and fireWith)
firingStart,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function (data) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for (; list && firingIndex < firingLength; firingIndex++) {
if (list[ firingIndex ].apply(data[ 0 ], data[ 1 ]) === false && options.stopOnFalse) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if (list) {
if (stack) {
if (stack.length) {
fire(stack.shift());
}
} else if (memory) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function () {
if (list) {
// First, we save the current length
var start = list.length;
(function add(args) {
jQuery.each(args, function (_, arg) {
var type = jQuery.type(arg);
if (type === "function") {
if (!options.unique || !self.has(arg)) {
list.push(arg);
}
} else if (arg && arg.length && type !== "string") {
// Inspect recursively
add(arg);
}
});
})(arguments);
// Do we need to add the callbacks to the
// current firing batch?
if (firing) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if (memory) {
firingStart = start;
fire(memory);
}
}
return this;
},
// Remove a callback from the list
remove: function () {
if (list) {
jQuery.each(arguments, function (_, arg) {
var index;
while (( index = jQuery.inArray(arg, list, index) ) > -1) {
list.splice(index, 1);
// Handle firing indexes
if (firing) {
if (index <= firingLength) {
firingLength--;
}
if (index <= firingIndex) {
firingIndex--;
}
}
}
});
}
return this;
},
// Check if a given callback is in the list.
// If no argument is given, return whether or not list has callbacks attached.
has: function (fn) {
return fn ? jQuery.inArray(fn, list) > -1 : !!( list && list.length );
},
// Remove all callbacks from the list
empty: function () {
list = [];
return this;
},
// Have the list do nothing anymore
disable: function () {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function () {
return !list;
},
// Lock the list in its current state
lock: function () {
stack = undefined;
if (!memory) {
self.disable();
}
return this;
},
// Is it locked?
locked: function () {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function (context, args) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if (list && ( !fired || stack )) {
if (firing) {
stack.push(args);
} else {
fire(args);
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function () {
self.fireWith(this, arguments);
return this;
},
// To know if the callbacks have already been called at least once
fired: function () {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function (func) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function () {
return state;
},
always: function () {
deferred.done(arguments).fail(arguments);
return this;
},
then: function (/* fnDone, fnFail, fnProgress */) {
var fns = arguments;
return jQuery.Deferred(function (newDefer) {
jQuery.each(tuples, function (i, tuple) {
var action = tuple[ 0 ],
fn = jQuery.isFunction(fns[ i ]) && fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ](function () {
var returned = fn && fn.apply(this, arguments);
if (returned && jQuery.isFunction(returned.promise)) {
returned.promise()
.done(newDefer.resolve)
.fail(newDefer.reject)
.progress(newDefer.notify);
} else {
newDefer[ action + "With" ](this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments);
}
});
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function (obj) {
return obj != null ? jQuery.extend(obj, promise) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each(tuples, function (i, tuple) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if (stateString) {
list.add(function () {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock);
}
// deferred[ resolve | reject | notify ]
deferred[ tuple[0] ] = function () {
deferred[ tuple[0] + "With" ](this === deferred ? promise : this, arguments);
return this;
};
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise(deferred);
// Call given func if any
if (func) {
func.call(deferred, deferred);
}
// All done!
return deferred;
},
// Deferred helper
when: function (subordinate /* , ..., subordinateN */) {
var i = 0,
resolveValues = core_slice.call(arguments),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction(subordinate.promise) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function (i, contexts, values) {
return function (value) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? core_slice.call(arguments) : value;
if (values === progressValues) {
deferred.notifyWith(contexts, values);
} else if (!( --remaining )) {
deferred.resolveWith(contexts, values);
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if (length > 1) {
progressValues = new Array(length);
progressContexts = new Array(length);
resolveContexts = new Array(length);
for (; i < length; i++) {
if (resolveValues[ i ] && jQuery.isFunction(resolveValues[ i ].promise)) {
resolveValues[ i ].promise()
.done(updateFunc(i, resolveContexts, resolveValues))
.fail(deferred.reject)
.progress(updateFunc(i, progressContexts, progressValues));
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if (!remaining) {
deferred.resolveWith(resolveContexts, resolveValues);
}
return deferred.promise();
}
});
jQuery.support = (function () {
var support, all, a,
input, select, fragment,
opt, eventName, isSupported, i,
div = document.createElement("div");
// Setup
div.setAttribute("className", "t");
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
// Support tests won't run in some limited or non-browser environments
all = div.getElementsByTagName("*");
a = div.getElementsByTagName("a")[ 0 ];
if (!all || !a || !all.length) {
return {};
}
// First batch of tests
select = document.createElement("select");
opt = select.appendChild(document.createElement("option"));
input = div.getElementsByTagName("input")[ 0 ];
a.style.cssText = "top:1px;float:left;opacity:.5";
support = {
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
getSetAttribute: div.className !== "t",
// IE strips leading whitespace when .innerHTML is used
leadingWhitespace: div.firstChild.nodeType === 3,
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
tbody: !div.getElementsByTagName("tbody").length,
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
htmlSerialize: !!div.getElementsByTagName("link").length,
// Get the style information from getAttribute
// (IE uses .cssText instead)
style: /top/.test(a.getAttribute("style")),
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
hrefNormalized: a.getAttribute("href") === "/a",
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
opacity: /^0.5/.test(a.style.opacity),
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
cssFloat: !!a.style.cssFloat,
// Check the default checkbox/radio value ("" on WebKit; "on" elsewhere)
checkOn: !!input.value,
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
optSelected: opt.selected,
// Tests for enctype support on a form (#6743)
enctype: !!document.createElement("form").enctype,
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
html5Clone: document.createElement("nav").cloneNode(true).outerHTML !== "<:nav></:nav>",
// jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode
boxModel: document.compatMode === "CSS1Compat",
// Will be defined later
deleteExpando: true,
noCloneEvent: true,
inlineBlockNeedsLayout: false,
shrinkWrapBlocks: false,
reliableMarginRight: true,
boxSizingReliable: true,
pixelPosition: false
};
// Make sure checked status is properly cloned
input.checked = true;
support.noCloneChecked = input.cloneNode(true).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Support: IE<9
try {
delete div.test;
} catch (e) {
support.deleteExpando = false;
}
// Check if we can trust getAttribute("value")
input = document.createElement("input");
input.setAttribute("value", "");
support.input = input.getAttribute("value") === "";
// Check if an input maintains its value after becoming a radio
input.value = "t";
input.setAttribute("type", "radio");
support.radioValue = input.value === "t";
// #11217 - WebKit loses check when the name is after the checked attribute
input.setAttribute("checked", "t");
input.setAttribute("name", "t");
fragment = document.createDocumentFragment();
fragment.appendChild(input);
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
support.appendChecked = input.checked;
// WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode(true).cloneNode(true).lastChild.checked;
// Support: IE<9
// Opera does not clone events (and typeof div.attachEvent === undefined).
// IE9-10 clones events bound via attachEvent, but they don't trigger with .click()
if (div.attachEvent) {
div.attachEvent("onclick", function () {
support.noCloneEvent = false;
});
div.cloneNode(true).click();
}
// Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event)
// Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP), test/csp.php
for (i in { submit: true, change: true, focusin: true }) {
div.setAttribute(eventName = "on" + i, "t");
support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false;
}
div.style.backgroundClip = "content-box";
div.cloneNode(true).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
// Run tests that need a body at doc ready
jQuery(function () {
var container, marginDiv, tds,
divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",
body = document.getElementsByTagName("body")[0];
if (!body) {
// Return for frameset docs that don't have a body
return;
}
container = document.createElement("div");
container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px";
body.appendChild(container).appendChild(div);
// Support: IE8
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
tds = div.getElementsByTagName("td");
tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none";
isSupported = ( tds[ 0 ].offsetHeight === 0 );
tds[ 0 ].style.display = "";
tds[ 1 ].style.display = "none";
// Support: IE8
// Check if empty table cells still have offsetWidth/Height
support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
// Check box-sizing and margin behavior
div.innerHTML = "";
div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;";
support.boxSizing = ( div.offsetWidth === 4 );
support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 );
// Use window.getComputedStyle because jsdom on node.js will break without it.
if (window.getComputedStyle) {
support.pixelPosition = ( window.getComputedStyle(div, null) || {} ).top !== "1%";
support.boxSizingReliable = ( window.getComputedStyle(div, null) || { width: "4px" } ).width === "4px";
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. (#3333)
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
marginDiv = div.appendChild(document.createElement("div"));
marginDiv.style.cssText = div.style.cssText = divReset;
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
support.reliableMarginRight = !parseFloat(( window.getComputedStyle(marginDiv, null) || {} ).marginRight);
}
if (typeof div.style.zoom !== core_strundefined) {
// Support: IE<8
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
div.innerHTML = "";
div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1";
support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );
// Support: IE6
// Check if elements with layout shrink-wrap their children
div.style.display = "block";
div.innerHTML = "<div></div>";
div.firstChild.style.width = "5px";
support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );
if (support.inlineBlockNeedsLayout) {
// Prevent IE 6 from affecting layout for positioned elements #11048
// Prevent IE from shrinking the body in IE 7 mode #12869
// Support: IE<8
body.style.zoom = 1;
}
}
body.removeChild(container);
// Null elements to avoid leaks in IE
container = div = tds = marginDiv = null;
});
// Null elements to avoid leaks in IE
all = select = fragment = opt = a = input = null;
return support;
})();
var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
rmultiDash = /([A-Z])/g;
function internalData(elem, name, data, pvt /* Internal Use Only */) {
if (!jQuery.acceptData(elem)) {
return;
}
var thisCache, ret,
internalKey = jQuery.expando,
getByName = typeof name === "string",
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ((!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined) {
return;
}
if (!id) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if (isNode) {
elem[ internalKey ] = id = core_deletedIds.pop() || jQuery.guid++;
} else {
id = internalKey;
}
}
if (!cache[ id ]) {
cache[ id ] = {};
// Avoids exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
if (!isNode) {
cache[ id ].toJSON = jQuery.noop;
}
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if (typeof name === "object" || typeof name === "function") {
if (pvt) {
cache[ id ] = jQuery.extend(cache[ id ], name);
} else {
cache[ id ].data = jQuery.extend(cache[ id ].data, name);
}
}
thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if (!pvt) {
if (!thisCache.data) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if (data !== undefined) {
thisCache[ jQuery.camelCase(name) ] = data;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if (getByName) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if (ret == null) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase(name) ];
}
} else {
ret = thisCache;
}
return ret;
}
function internalRemoveData(elem, name, pvt) {
if (!jQuery.acceptData(elem)) {
return;
}
var i, l, thisCache,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if (!cache[ id ]) {
return;
}
if (name) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if (thisCache) {
// Support array or space separated string names for data keys
if (!jQuery.isArray(name)) {
// try the string as a key before any manipulation
if (name in thisCache) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase(name);
if (name in thisCache) {
name = [ name ];
} else {
name = name.split(" ");
}
}
} else {
// If "name" is an array of keys...
// When data is initially created, via ("key", "val") signature,
// keys will be converted to camelCase.
// Since there is no way to tell _how_ a key was added, remove
// both plain key and camelCase key. #12786
// This will only penalize the array argument path.
name = name.concat(jQuery.map(name, jQuery.camelCase));
}
for (i = 0, l = name.length; i < l; i++) {
delete thisCache[ name[i] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if (!( pvt ? isEmptyDataObject : jQuery.isEmptyObject )(thisCache)) {
return;
}
}
}
// See jQuery.data for more information
if (!pvt) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if (!isEmptyDataObject(cache[ id ])) {
return;
}
}
// Destroy the cache
if (isNode) {
jQuery.cleanData([ elem ], true);
// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
} else if (jQuery.support.deleteExpando || cache != cache.window) {
delete cache[ id ];
// When all else fails, null
} else {
cache[ id ] = null;
}
}
jQuery.extend({
cache: {},
// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( core_version + Math.random() ).replace(/\D/g, ""),
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
"applet": true
},
hasData: function (elem) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject(elem);
},
data: function (elem, name, data) {
return internalData(elem, name, data);
},
removeData: function (elem, name) {
return internalRemoveData(elem, name);
},
// For internal use only.
_data: function (elem, name, data) {
return internalData(elem, name, data, true);
},
_removeData: function (elem, name) {
return internalRemoveData(elem, name, true);
},
// A method for determining if a DOM node can handle the data expando
acceptData: function (elem) {
// Do not set data on non-element because it will not be cleared (#8335).
if (elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9) {
return false;
}
var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ];
// nodes accept data unless otherwise specified; rejection can be conditional
return !noData || noData !== true && elem.getAttribute("classid") === noData;
}
});
jQuery.fn.extend({
data: function (key, value) {
var attrs, name,
elem = this[0],
i = 0,
data = null;
// Gets all values
if (key === undefined) {
if (this.length) {
data = jQuery.data(elem);
if (elem.nodeType === 1 && !jQuery._data(elem, "parsedAttrs")) {
attrs = elem.attributes;
for (; i < attrs.length; i++) {
name = attrs[i].name;
if (!name.indexOf("data-")) {
name = jQuery.camelCase(name.slice(5));
dataAttr(elem, name, data[ name ]);
}
}
jQuery._data(elem, "parsedAttrs", true);
}
}
return data;
}
// Sets multiple values
if (typeof key === "object") {
return this.each(function () {
jQuery.data(this, key);
});
}
return jQuery.access(this, function (value) {
if (value === undefined) {
// Try to fetch any internally stored data first
return elem ? dataAttr(elem, key, jQuery.data(elem, key)) : null;
}
this.each(function () {
jQuery.data(this, key, value);
});
}, null, value, arguments.length > 1, null, true);
},
removeData: function (key) {
return this.each(function () {
jQuery.removeData(this, key);
});
}
});
function dataAttr(elem, key, data) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if (data === undefined && elem.nodeType === 1) {
var name = "data-" + key.replace(rmultiDash, "-$1").toLowerCase();
data = elem.getAttribute(name);
if (typeof data === "string") {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test(data) ? jQuery.parseJSON(data) :
data;
} catch (e) {
}
// Make sure we set the data so it isn't changed later
jQuery.data(elem, key, data);
} else {
data = undefined;
}
}
return data;
}
// checks a cache object for emptiness
function isEmptyDataObject(obj) {
var name;
for (name in obj) {
// if the public data object is empty, the private is still empty
if (name === "data" && jQuery.isEmptyObject(obj[name])) {
continue;
}
if (name !== "toJSON") {
return false;
}
}
return true;
}
jQuery.extend({
queue: function (elem, type, data) {
var queue;
if (elem) {
type = ( type || "fx" ) + "queue";
queue = jQuery._data(elem, type);
// Speed up dequeue by getting out quickly if this is just a lookup
if (data) {
if (!queue || jQuery.isArray(data)) {
queue = jQuery._data(elem, type, jQuery.makeArray(data));
} else {
queue.push(data);
}
}
return queue || [];
}
},
dequeue: function (elem, type) {
type = type || "fx";
var queue = jQuery.queue(elem, type),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks(elem, type),
next = function () {
jQuery.dequeue(elem, type);
};
// If the fx queue is dequeued, always remove the progress sentinel
if (fn === "inprogress") {
fn = queue.shift();
startLength--;
}
hooks.cur = fn;
if (fn) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if (type === "fx") {
queue.unshift("inprogress");
}
// clear up the last queue stop function
delete hooks.stop;
fn.call(elem, next, hooks);
}
if (!startLength && hooks) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function (elem, type) {
var key = type + "queueHooks";
return jQuery._data(elem, key) || jQuery._data(elem, key, {
empty: jQuery.Callbacks("once memory").add(function () {
jQuery._removeData(elem, type + "queue");
jQuery._removeData(elem, key);
})
});
}
});
jQuery.fn.extend({
queue: function (type, data) {
var setter = 2;
if (typeof type !== "string") {
data = type;
type = "fx";
setter--;
}
if (arguments.length < setter) {
return jQuery.queue(this[0], type);
}
return data === undefined ?
this :
this.each(function () {
var queue = jQuery.queue(this, type, data);
// ensure a hooks for this queue
jQuery._queueHooks(this, type);
if (type === "fx" && queue[0] !== "inprogress") {
jQuery.dequeue(this, type);
}
});
},
dequeue: function (type) {
return this.each(function () {
jQuery.dequeue(this, type);
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function (time, type) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue(type, function (next, hooks) {
var timeout = setTimeout(next, time);
hooks.stop = function () {
clearTimeout(timeout);
};
});
},
clearQueue: function (type) {
return this.queue(type || "fx", []);
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function (type, obj) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function () {
if (!( --count )) {
defer.resolveWith(elements, [ elements ]);
}
};
if (typeof type !== "string") {
obj = type;
type = undefined;
}
type = type || "fx";
while (i--) {
tmp = jQuery._data(elements[ i ], type + "queueHooks");
if (tmp && tmp.empty) {
count++;
tmp.empty.add(resolve);
}
}
resolve();
return defer.promise(obj);
}
});
var nodeHook, boolHook,
rclass = /[\t\r\n]/g,
rreturn = /\r/g,
rfocusable = /^(?:input|select|textarea|button|object)$/i,
rclickable = /^(?:a|area)$/i,
rboolean = /^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i,
ruseDefault = /^(?:checked|selected)$/i,
getSetAttribute = jQuery.support.getSetAttribute,
getSetInput = jQuery.support.input;
jQuery.fn.extend({
attr: function (name, value) {
return jQuery.access(this, jQuery.attr, name, value, arguments.length > 1);
},
removeAttr: function (name) {
return this.each(function () {
jQuery.removeAttr(this, name);
});
},
prop: function (name, value) {
return jQuery.access(this, jQuery.prop, name, value, arguments.length > 1);
},
removeProp: function (name) {
name = jQuery.propFix[ name ] || name;
return this.each(function () {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch (e) {
}
});
},
addClass: function (value) {
var classes, elem, cur, clazz, j,
i = 0,
len = this.length,
proceed = typeof value === "string" && value;
if (jQuery.isFunction(value)) {
return this.each(function (j) {
jQuery(this).addClass(value.call(this, j, this.className));
});
}
if (proceed) {
// The disjunction here is for better compressibility (see removeClass)
classes = ( value || "" ).match(core_rnotwhite) || [];
for (; i < len; i++) {
elem = this[ i ];
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace(rclass, " ") :
" "
);
if (cur) {
j = 0;
while ((clazz = classes[j++])) {
if (cur.indexOf(" " + clazz + " ") < 0) {
cur += clazz + " ";
}
}
elem.className = jQuery.trim(cur);
}
}
}
return this;
},
removeClass: function (value) {
var classes, elem, cur, clazz, j,
i = 0,
len = this.length,
proceed = arguments.length === 0 || typeof value === "string" && value;
if (jQuery.isFunction(value)) {
return this.each(function (j) {
jQuery(this).removeClass(value.call(this, j, this.className));
});
}
if (proceed) {
classes = ( value || "" ).match(core_rnotwhite) || [];
for (; i < len; i++) {
elem = this[ i ];
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace(rclass, " ") :
""
);
if (cur) {
j = 0;
while ((clazz = classes[j++])) {
// Remove *all* instances
while (cur.indexOf(" " + clazz + " ") >= 0) {
cur = cur.replace(" " + clazz + " ", " ");
}
}
elem.className = value ? jQuery.trim(cur) : "";
}
}
}
return this;
},
toggleClass: function (value, stateVal) {
var type = typeof value,
isBool = typeof stateVal === "boolean";
if (jQuery.isFunction(value)) {
return this.each(function (i) {
jQuery(this).toggleClass(value.call(this, i, this.className, stateVal), stateVal);
});
}
return this.each(function () {
if (type === "string") {
// toggle individual class names
var className,
i = 0,
self = jQuery(this),
state = stateVal,
classNames = value.match(core_rnotwhite) || [];
while ((className = classNames[ i++ ])) {
// check each className given, space separated list
state = isBool ? state : !self.hasClass(className);
self[ state ? "addClass" : "removeClass" ](className);
}
// Toggle whole class name
} else if (type === core_strundefined || type === "boolean") {
if (this.className) {
// store className if set
jQuery._data(this, "__className__", this.className);
}
// If the element has a class name or if we're passed "false",
// then remove the whole classname (if there was one, the above saved it).
// Otherwise bring back whatever was previously saved (if anything),
// falling back to the empty string if nothing was stored.
this.className = this.className || value === false ? "" : jQuery._data(this, "__className__") || "";
}
});
},
hasClass: function (selector) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for (; i < l; i++) {
if (this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf(className) >= 0) {
return true;
}
}
return false;
},
val: function (value) {
var ret, hooks, isFunction,
elem = this[0];
if (!arguments.length) {
if (elem) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if (hooks && "get" in hooks && (ret = hooks.get(elem, "value")) !== undefined) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction(value);
return this.each(function (i) {
var val,
self = jQuery(this);
if (this.nodeType !== 1) {
return;
}
if (isFunction) {
val = value.call(this, i, self.val());
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if (val == null) {
val = "";
} else if (typeof val === "number") {
val += "";
} else if (jQuery.isArray(val)) {
val = jQuery.map(val, function (value) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if (!hooks || !("set" in hooks) || hooks.set(this, val, "value") === undefined) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function (elem) {
// attributes.value is undefined in Blackberry 4.7 but
// uses .value. See #6932
var val = elem.attributes.value;
return !val || val.specified ? elem.value : elem.text;
}
},
select: {
get: function (elem) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for (; i < max; i++) {
option = options[ i ];
// oldIE doesn't update selected after form reset (#2551)
if (( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName(option.parentNode, "optgroup") )) {
// Get the specific value for the option
value = jQuery(option).val();
// We don't need an array for one selects
if (one) {
return value;
}
// Multi-Selects return an array
values.push(value);
}
}
return values;
},
set: function (elem, value) {
var values = jQuery.makeArray(value);
jQuery(elem).find("option").each(function () {
this.selected = jQuery.inArray(jQuery(this).val(), values) >= 0;
});
if (!values.length) {
elem.selectedIndex = -1;
}
return values;
}
}
},
attr: function (elem, name, value) {
var hooks, notxml, ret,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if (!elem || nType === 3 || nType === 8 || nType === 2) {
return;
}
// Fallback to prop when attributes are not supported
if (typeof elem.getAttribute === core_strundefined) {
return jQuery.prop(elem, name, value);
}
notxml = nType !== 1 || !jQuery.isXMLDoc(elem);
// All attributes are lowercase
// Grab necessary hook if one is defined
if (notxml) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] || ( rboolean.test(name) ? boolHook : nodeHook );
}
if (value !== undefined) {
if (value === null) {
jQuery.removeAttr(elem, name);
} else if (hooks && notxml && "set" in hooks && (ret = hooks.set(elem, value, name)) !== undefined) {
return ret;
} else {
elem.setAttribute(name, value + "");
return value;
}
} else if (hooks && notxml && "get" in hooks && (ret = hooks.get(elem, name)) !== null) {
return ret;
} else {
// In IE9+, Flash objects don't have .getAttribute (#12945)
// Support: IE9+
if (typeof elem.getAttribute !== core_strundefined) {
ret = elem.getAttribute(name);
}
// Non-existent attributes return null, we normalize to undefined
return ret == null ?
undefined :
ret;
}
},
removeAttr: function (elem, value) {
var name, propName,
i = 0,
attrNames = value && value.match(core_rnotwhite);
if (attrNames && elem.nodeType === 1) {
while ((name = attrNames[i++])) {
propName = jQuery.propFix[ name ] || name;
// Boolean attributes get special treatment (#10870)
if (rboolean.test(name)) {
// Set corresponding property to false for boolean attributes
// Also clear defaultChecked/defaultSelected (if appropriate) for IE<8
if (!getSetAttribute && ruseDefault.test(name)) {
elem[ jQuery.camelCase("default-" + name) ] =
elem[ propName ] = false;
} else {
elem[ propName ] = false;
}
// See #9699 for explanation of this approach (setting first, then removal)
} else {
jQuery.attr(elem, name, "");
}
elem.removeAttribute(getSetAttribute ? name : propName);
}
}
},
attrHooks: {
type: {
set: function (elem, value) {
if (!jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input")) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to default in case type is set after value during creation
var val = elem.value;
elem.setAttribute("type", value);
if (val) {
elem.value = val;
}
return value;
}
}
}
},
propFix: {
tabindex: "tabIndex",
readonly: "readOnly",
"for": "htmlFor",
"class": "className",
maxlength: "maxLength",
cellspacing: "cellSpacing",
cellpadding: "cellPadding",
rowspan: "rowSpan",
colspan: "colSpan",
usemap: "useMap",
frameborder: "frameBorder",
contenteditable: "contentEditable"
},
prop: function (elem, name, value) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if (!elem || nType === 3 || nType === 8 || nType === 2) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc(elem);
if (notxml) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if (value !== undefined) {
if (hooks && "set" in hooks && (ret = hooks.set(elem, value, name)) !== undefined) {
return ret;
} else {
return ( elem[ name ] = value );
}
} else {
if (hooks && "get" in hooks && (ret = hooks.get(elem, name)) !== null) {
return ret;
} else {
return elem[ name ];
}
}
},
propHooks: {
tabIndex: {
get: function (elem) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
var attributeNode = elem.getAttributeNode("tabindex");
return attributeNode && attributeNode.specified ?
parseInt(attributeNode.value, 10) :
rfocusable.test(elem.nodeName) || rclickable.test(elem.nodeName) && elem.href ?
0 :
undefined;
}
}
}
});
// Hook for boolean attributes
boolHook = {
get: function (elem, name) {
var
// Use .prop to determine if this attribute is understood as boolean
prop = jQuery.prop(elem, name),
// Fetch it accordingly
attr = typeof prop === "boolean" && elem.getAttribute(name),
detail = typeof prop === "boolean" ?
getSetInput && getSetAttribute ?
attr != null :
// oldIE fabricates an empty string for missing boolean attributes
// and conflates checked/selected into attroperties
ruseDefault.test(name) ?
elem[ jQuery.camelCase("default-" + name) ] :
!!attr :
// fetch an attribute node for properties not recognized as boolean
elem.getAttributeNode(name);
return detail && detail.value !== false ?
name.toLowerCase() :
undefined;
},
set: function (elem, value, name) {
if (value === false) {
// Remove boolean attributes when set to false
jQuery.removeAttr(elem, name);
} else if (getSetInput && getSetAttribute || !ruseDefault.test(name)) {
// IE<8 needs the *property* name
elem.setAttribute(!getSetAttribute && jQuery.propFix[ name ] || name, name);
// Use defaultChecked and defaultSelected for oldIE
} else {
elem[ jQuery.camelCase("default-" + name) ] = elem[ name ] = true;
}
return name;
}
};
// fix oldIE value attroperty
if (!getSetInput || !getSetAttribute) {
jQuery.attrHooks.value = {
get: function (elem, name) {
var ret = elem.getAttributeNode(name);
return jQuery.nodeName(elem, "input") ?
// Ignore the value *property* by using defaultValue
elem.defaultValue :
ret && ret.specified ? ret.value : undefined;
},
set: function (elem, value, name) {
if (jQuery.nodeName(elem, "input")) {
// Does not return so that setAttribute is also used
elem.defaultValue = value;
} else {
// Use nodeHook if defined (#1954); otherwise setAttribute is fine
return nodeHook && nodeHook.set(elem, value, name);
}
}
};
}
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if (!getSetAttribute) {
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = jQuery.valHooks.button = {
get: function (elem, name) {
var ret = elem.getAttributeNode(name);
return ret && ( name === "id" || name === "name" || name === "coords" ? ret.value !== "" : ret.specified ) ?
ret.value :
undefined;
},
set: function (elem, value, name) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode(name);
if (!ret) {
elem.setAttributeNode(
(ret = elem.ownerDocument.createAttribute(name))
);
}
ret.value = value += "";
// Break association with cloned elements by also using setAttribute (#9646)
return name === "value" || value === elem.getAttribute(name) ?
value :
undefined;
}
};
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
get: nodeHook.get,
set: function (elem, value, name) {
nodeHook.set(elem, value === "" ? false : value, name);
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function (i, name) {
jQuery.attrHooks[ name ] = jQuery.extend(jQuery.attrHooks[ name ], {
set: function (elem, value) {
if (value === "") {
elem.setAttribute(name, "auto");
return value;
}
}
});
});
}
// Some attributes require a special call on IE
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if (!jQuery.support.hrefNormalized) {
jQuery.each([ "href", "src", "width", "height" ], function (i, name) {
jQuery.attrHooks[ name ] = jQuery.extend(jQuery.attrHooks[ name ], {
get: function (elem) {
var ret = elem.getAttribute(name, 2);
return ret == null ? undefined : ret;
}
});
});
// href/src property should get the full normalized URL (#10299/#12915)
jQuery.each([ "href", "src" ], function (i, name) {
jQuery.propHooks[ name ] = {
get: function (elem) {
return elem.getAttribute(name, 4);
}
};
});
}
if (!jQuery.support.style) {
jQuery.attrHooks.style = {
get: function (elem) {
// Return undefined in the case of empty string
// Note: IE uppercases css property names, but if we were to .toLowerCase()
// .cssText, that would destroy case senstitivity in URL's, like in "background"
return elem.style.cssText || undefined;
},
set: function (elem, value) {
return ( elem.style.cssText = value + "" );
}
};
}
// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if (!jQuery.support.optSelected) {
jQuery.propHooks.selected = jQuery.extend(jQuery.propHooks.selected, {
get: function (elem) {
var parent = elem.parentNode;
if (parent) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if (parent.parentNode) {
parent.parentNode.selectedIndex;
}
}
return null;
}
});
}
// IE6/7 call enctype encoding
if (!jQuery.support.enctype) {
jQuery.propFix.enctype = "encoding";
}
// Radios and checkboxes getter/setter
if (!jQuery.support.checkOn) {
jQuery.each([ "radio", "checkbox" ], function () {
jQuery.valHooks[ this ] = {
get: function (elem) {
// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
}
};
});
}
jQuery.each([ "radio", "checkbox" ], function () {
jQuery.valHooks[ this ] = jQuery.extend(jQuery.valHooks[ this ], {
set: function (elem, value) {
if (jQuery.isArray(value)) {
return ( elem.checked = jQuery.inArray(jQuery(elem).val(), value) >= 0 );
}
}
});
});
var rformElems = /^(?:input|select|textarea)$/i,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
global: {},
add: function (elem, types, handler, data, selector) {
var tmp, events, t, handleObjIn,
special, eventHandle, handleObj,
handlers, type, namespaces, origType,
elemData = jQuery._data(elem);
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if (!elemData) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if (handler.handler) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if (!handler.guid) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
if (!(events = elemData.events)) {
events = elemData.events = {};
}
if (!(eventHandle = elemData.handle)) {
eventHandle = elemData.handle = function (e) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply(eventHandle.elem, arguments) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
types = ( types || "" ).match(core_rnotwhite) || [""];
t = types.length;
while (t--) {
tmp = rtypenamespace.exec(types[t]) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split(".").sort();
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test(selector),
namespace: namespaces.join(".")
}, handleObjIn);
// Init the event handler queue if we're the first
if (!(handlers = events[ type ])) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener/attachEvent if the special events handler returns false
if (!special.setup || special.setup.call(elem, data, namespaces, eventHandle) === false) {
// Bind the global event handler to the element
if (elem.addEventListener) {
elem.addEventListener(type, eventHandle, false);
} else if (elem.attachEvent) {
elem.attachEvent("on" + type, eventHandle);
}
}
}
if (special.add) {
special.add.call(elem, handleObj);
if (!handleObj.handler.guid) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if (selector) {
handlers.splice(handlers.delegateCount++, 0, handleObj);
} else {
handlers.push(handleObj);
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
// Detach an event or set of events from an element
remove: function (elem, types, handler, selector, mappedTypes) {
var j, handleObj, tmp,
origCount, t, events,
special, handlers, type,
namespaces, origType,
elemData = jQuery.hasData(elem) && jQuery._data(elem);
if (!elemData || !(events = elemData.events)) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match(core_rnotwhite) || [""];
t = types.length;
while (t--) {
tmp = rtypenamespace.exec(types[t]) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split(".").sort();
// Unbind all events (on this namespace, if provided) for the element
if (!type) {
for (type in events) {
jQuery.event.remove(elem, type + types[ t ], handler, selector, true);
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector ? special.delegateType : special.bindType ) || type;
handlers = events[ type ] || [];
tmp = tmp[2] && new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)");
// Remove matching events
origCount = j = handlers.length;
while (j--) {
handleObj = handlers[ j ];
if (( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !tmp || tmp.test(handleObj.namespace) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector )) {
handlers.splice(j, 1);
if (handleObj.selector) {
handlers.delegateCount--;
}
if (special.remove) {
special.remove.call(elem, handleObj);
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if (origCount && !handlers.length) {
if (!special.teardown || special.teardown.call(elem, namespaces, elemData.handle) === false) {
jQuery.removeEvent(elem, type, elemData.handle);
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if (jQuery.isEmptyObject(events)) {
delete elemData.handle;
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery._removeData(elem, "events");
}
},
trigger: function (event, data, elem, onlyHandlers) {
var handle, ontype, cur,
bubbleType, special, tmp, i,
eventPath = [ elem || document ],
type = core_hasOwn.call(event, "type") ? event.type : event,
namespaces = core_hasOwn.call(event, "namespace") ? event.namespace.split(".") : [];
cur = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if (elem.nodeType === 3 || elem.nodeType === 8) {
return;
}
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if (rfocusMorph.test(type + jQuery.event.triggered)) {
return;
}
if (type.indexOf(".") >= 0) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
ontype = type.indexOf(":") < 0 && "on" + type;
// Caller can pass in a jQuery.Event object, Object, or just an event type string
event = event[ jQuery.expando ] ?
event :
new jQuery.Event(type, typeof event === "object" && event);
event.isTrigger = true;
event.namespace = namespaces.join(".");
event.namespace_re = event.namespace ?
new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") :
null;
// Clean up the event in case it is being reused
event.result = undefined;
if (!event.target) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data == null ?
[ event ] :
jQuery.makeArray(data, [ event ]);
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if (!onlyHandlers && special.trigger && special.trigger.apply(elem, data) === false) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
if (!onlyHandlers && !special.noBubble && !jQuery.isWindow(elem)) {
bubbleType = special.delegateType || type;
if (!rfocusMorph.test(bubbleType + type)) {
cur = cur.parentNode;
}
for (; cur; cur = cur.parentNode) {
eventPath.push(cur);
tmp = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if (tmp === (elem.ownerDocument || document)) {
eventPath.push(tmp.defaultView || tmp.parentWindow || window);
}
}
// Fire handlers on the event path
i = 0;
while ((cur = eventPath[i++]) && !event.isPropagationStopped()) {
event.type = i > 1 ?
bubbleType :
special.bindType || type;
// jQuery handler
handle = ( jQuery._data(cur, "events") || {} )[ event.type ] && jQuery._data(cur, "handle");
if (handle) {
handle.apply(cur, data);
}
// Native handler
handle = ontype && cur[ ontype ];
if (handle && jQuery.acceptData(cur) && handle.apply && handle.apply(cur, data) === false) {
event.preventDefault();
}
}
event.type = type;
// If nobody prevented the default action, do it now
if (!onlyHandlers && !event.isDefaultPrevented()) {
if ((!special._default || special._default.apply(elem.ownerDocument, data) === false) && !(type === "click" && jQuery.nodeName(elem, "a")) && jQuery.acceptData(elem)) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
if (ontype && elem[ type ] && !jQuery.isWindow(elem)) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ ontype ];
if (tmp) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
try {
elem[ type ]();
} catch (e) {
// IE<9 dies on focus/blur to hidden element (#1486,#12518)
// only reproducible on winXP IE8 native, not IE9 in IE8 mode
}
jQuery.event.triggered = undefined;
if (tmp) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
dispatch: function (event) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix(event);
var i, ret, handleObj, matched, j,
handlerQueue = [],
args = core_slice.call(arguments),
handlers = ( jQuery._data(this, "events") || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if (special.preDispatch && special.preDispatch.call(this, event) === false) {
return;
}
// Determine handlers
handlerQueue = jQuery.event.handlers.call(this, event, handlers);
// Run delegates first; they may want to stop propagation beneath us
i = 0;
while ((matched = handlerQueue[ i++ ]) && !event.isPropagationStopped()) {
event.currentTarget = matched.elem;
j = 0;
while ((handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped()) {
// Triggered event must either 1) have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if (!event.namespace_re || event.namespace_re.test(handleObj.namespace)) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply(matched.elem, args);
if (ret !== undefined) {
if ((event.result = ret) === false) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if (special.postDispatch) {
special.postDispatch.call(this, event);
}
return event.result;
},
handlers: function (event, handlers) {
var sel, handleObj, matches, i,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
// Avoid non-left-click bubbling in Firefox (#3861)
if (delegateCount && cur.nodeType && (!event.button || event.type !== "click")) {
for (; cur != this; cur = cur.parentNode || this) {
// Don't check non-elements (#13208)
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if (cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click")) {
matches = [];
for (i = 0; i < delegateCount; i++) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if (matches[ sel ] === undefined) {
matches[ sel ] = handleObj.needsContext ?
jQuery(sel, this).index(cur) >= 0 :
jQuery.find(sel, this, null, [ cur ]).length;
}
if (matches[ sel ]) {
matches.push(handleObj);
}
}
if (matches.length) {
handlerQueue.push({ elem: cur, handlers: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if (delegateCount < handlers.length) {
handlerQueue.push({ elem: this, handlers: handlers.slice(delegateCount) });
}
return handlerQueue;
},
fix: function (event) {
if (event[ jQuery.expando ]) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop, copy,
type = event.type,
originalEvent = event,
fixHook = this.fixHooks[ type ];
if (!fixHook) {
this.fixHooks[ type ] = fixHook =
rmouseEvent.test(type) ? this.mouseHooks :
rkeyEvent.test(type) ? this.keyHooks :
{};
}
copy = fixHook.props ? this.props.concat(fixHook.props) : this.props;
event = new jQuery.Event(originalEvent);
i = copy.length;
while (i--) {
prop = copy[ i ];
event[ prop ] = originalEvent[ prop ];
}
// Support: IE<9
// Fix target property (#1925)
if (!event.target) {
event.target = originalEvent.srcElement || document;
}
// Support: Chrome 23+, Safari?
// Target should not be a text node (#504, #13143)
if (event.target.nodeType === 3) {
event.target = event.target.parentNode;
}
// Support: IE<9
// For mouse/key events, metaKey==false if it's undefined (#3368, #11328)
event.metaKey = !!event.metaKey;
return fixHook.filter ? fixHook.filter(event, originalEvent) : event;
},
// Includes some event props shared by KeyEvent and MouseEvent
props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function (event, original) {
// Add which for key events
if (event.which == null) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function (event, original) {
var body, eventDoc, doc,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if (event.pageX == null && original.clientX != null) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if (!event.relatedTarget && fromElement) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if (!event.which && button !== undefined) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function () {
if (jQuery.nodeName(this, "input") && this.type === "checkbox" && this.click) {
this.click();
return false;
}
}
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function () {
if (this !== document.activeElement && this.focus) {
try {
this.focus();
return false;
} catch (e) {
// Support: IE<9
// If we error on focus to hidden element (#1486, #12518),
// let .trigger() run the handlers
}
}
},
delegateType: "focusin"
},
blur: {
trigger: function () {
if (this === document.activeElement && this.blur) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
beforeunload: {
postDispatch: function (event) {
// Even when returnValue equals to undefined Firefox will still show alert
if (event.result !== undefined) {
event.originalEvent.returnValue = event.result;
}
}
}
},
simulate: function (type, elem, event, bubble) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{ type: type,
isSimulated: true,
originalEvent: {}
}
);
if (bubble) {
jQuery.event.trigger(e, null, elem);
} else {
jQuery.event.dispatch.call(elem, e);
}
if (e.isDefaultPrevented()) {
event.preventDefault();
}
}
};
jQuery.removeEvent = document.removeEventListener ?
function (elem, type, handle) {
if (elem.removeEventListener) {
elem.removeEventListener(type, handle, false);
}
} :
function (elem, type, handle) {
var name = "on" + type;
if (elem.detachEvent) {
// #8545, #7054, preventing memory leaks for custom events in IE6-8
// detachEvent needed property on element, by name of that event, to properly expose it to GC
if (typeof elem[ name ] === core_strundefined) {
elem[ name ] = null;
}
elem.detachEvent(name, handle);
}
};
jQuery.Event = function (src, props) {
// Allow instantiation without the 'new' keyword
if (!(this instanceof jQuery.Event)) {
return new jQuery.Event(src, props);
}
// Event object
if (src && src.type) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false ||
src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if (props) {
jQuery.extend(this, props);
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
preventDefault: function () {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if (!e) {
return;
}
// If preventDefault exists, run it on the original event
if (e.preventDefault) {
e.preventDefault();
// Support: IE
// Otherwise set the returnValue property of the original event to false
} else {
e.returnValue = false;
}
},
stopPropagation: function () {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if (!e) {
return;
}
// If stopPropagation exists, run it on the original event
if (e.stopPropagation) {
e.stopPropagation();
}
// Support: IE
// Set the cancelBubble property of the original event to true
e.cancelBubble = true;
},
stopImmediatePropagation: function () {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
}
};
// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function (orig, fix) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function (event) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if (!related || (related !== target && !jQuery.contains(target, related))) {
event.type = handleObj.origType;
ret = handleObj.handler.apply(this, arguments);
event.type = fix;
}
return ret;
}
};
});
// IE submit delegation
if (!jQuery.support.submitBubbles) {
jQuery.event.special.submit = {
setup: function () {
// Only need this for delegated form submit events
if (jQuery.nodeName(this, "form")) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add(this, "click._submit keypress._submit", function (e) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName(elem, "input") || jQuery.nodeName(elem, "button") ? elem.form : undefined;
if (form && !jQuery._data(form, "submitBubbles")) {
jQuery.event.add(form, "submit._submit", function (event) {
event._submit_bubble = true;
});
jQuery._data(form, "submitBubbles", true);
}
});
// return undefined since we don't need an event listener
},
postDispatch: function (event) {
// If form was submitted by the user, bubble the event up the tree
if (event._submit_bubble) {
delete event._submit_bubble;
if (this.parentNode && !event.isTrigger) {
jQuery.event.simulate("submit", this.parentNode, event, true);
}
}
},
teardown: function () {
// Only need this for delegated form submit events
if (jQuery.nodeName(this, "form")) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove(this, "._submit");
}
};
}
// IE change delegation and checkbox/radio fix
if (!jQuery.support.changeBubbles) {
jQuery.event.special.change = {
setup: function () {
if (rformElems.test(this.nodeName)) {
// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if (this.type === "checkbox" || this.type === "radio") {
jQuery.event.add(this, "propertychange._change", function (event) {
if (event.originalEvent.propertyName === "checked") {
this._just_changed = true;
}
});
jQuery.event.add(this, "click._change", function (event) {
if (this._just_changed && !event.isTrigger) {
this._just_changed = false;
}
// Allow triggered, simulated change events (#11500)
jQuery.event.simulate("change", this, event, true);
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add(this, "beforeactivate._change", function (e) {
var elem = e.target;
if (rformElems.test(elem.nodeName) && !jQuery._data(elem, "changeBubbles")) {
jQuery.event.add(elem, "change._change", function (event) {
if (this.parentNode && !event.isSimulated && !event.isTrigger) {
jQuery.event.simulate("change", this.parentNode, event, true);
}
});
jQuery._data(elem, "changeBubbles", true);
}
});
},
handle: function (event) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if (this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox")) {
return event.handleObj.handler.apply(this, arguments);
}
},
teardown: function () {
jQuery.event.remove(this, "._change");
return !rformElems.test(this.nodeName);
}
};
}
// Create "bubbling" focus and blur events
if (!jQuery.support.focusinBubbles) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function (orig, fix) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0,
handler = function (event) {
jQuery.event.simulate(fix, event.target, jQuery.event.fix(event), true);
};
jQuery.event.special[ fix ] = {
setup: function () {
if (attaches++ === 0) {
document.addEventListener(orig, handler, true);
}
},
teardown: function () {
if (--attaches === 0) {
document.removeEventListener(orig, handler, true);
}
}
};
});
}
jQuery.fn.extend({
on: function (types, selector, data, fn, /*INTERNAL*/ one) {
var type, origFn;
// Types can be a map of types/handlers
if (typeof types === "object") {
// ( types-Object, selector, data )
if (typeof selector !== "string") {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for (type in types) {
this.on(type, selector, data, types[ type ], one);
}
return this;
}
if (data == null && fn == null) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if (fn == null) {
if (typeof selector === "string") {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if (fn === false) {
fn = returnFalse;
} else if (!fn) {
return this;
}
if (one === 1) {
origFn = fn;
fn = function (event) {
// Can use an empty set, since event contains the info
jQuery().off(event);
return origFn.apply(this, arguments);
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each(function () {
jQuery.event.add(this, types, fn, data, selector);
});
},
one: function (types, selector, data, fn) {
return this.on(types, selector, data, fn, 1);
},
off: function (types, selector, fn) {
var handleObj, type;
if (types && types.preventDefault && types.handleObj) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery(types.delegateTarget).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if (typeof types === "object") {
// ( types-object [, selector] )
for (type in types) {
this.off(type, selector, types[ type ]);
}
return this;
}
if (selector === false || typeof selector === "function") {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if (fn === false) {
fn = returnFalse;
}
return this.each(function () {
jQuery.event.remove(this, types, fn, selector);
});
},
bind: function (types, data, fn) {
return this.on(types, null, data, fn);
},
unbind: function (types, fn) {
return this.off(types, null, fn);
},
delegate: function (selector, types, data, fn) {
return this.on(types, selector, data, fn);
},
undelegate: function (selector, types, fn) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off(selector, "**") : this.off(types, selector || "**", fn);
},
trigger: function (type, data) {
return this.each(function () {
jQuery.event.trigger(type, data, this);
});
},
triggerHandler: function (type, data) {
var elem = this[0];
if (elem) {
return jQuery.event.trigger(type, data, elem, true);
}
}
});
/*!
* Sizzle CSS Selector Engine
* Copyright 2012 jQuery Foundation and other contributors
* Released under the MIT license
* http://sizzlejs.com/
*/
(function (window, undefined) {
var i,
cachedruns,
Expr,
getText,
isXML,
compile,
hasDuplicate,
outermostContext,
// Local document vars
setDocument,
document,
docElem,
documentIsXML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
sortOrder,
// Instance-specific data
expando = "sizzle" + -(new Date()),
preferredDoc = window.document,
support = {},
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
// General-purpose constants
strundefined = typeof undefined,
MAX_NEGATIVE = 1 << 31,
// Array methods
arr = [],
pop = arr.pop,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf if we can't use a native one
indexOf = arr.indexOf || function (elem) {
var i = 0,
len = this.length;
for (; i < len; i++) {
if (this[i] === elem) {
return i;
}
}
return -1;
},
// Regular expressions
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace("w", "w#"),
// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
operators = "([*^$|!~]?=)",
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
"*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
// Prefer arguments quoted,
// then not containing pseudos/brackets,
// then attribute selectors/non-parenthetical expressions,
// then anything else
// These preferences are here to reduce the number of selectors
// needing tokenize in the PSEUDO preFilter
pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace(3, 8) + ")*)|.*)\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rtrim = new RegExp("^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g"),
rcomma = new RegExp("^" + whitespace + "*," + whitespace + "*"),
rcombinators = new RegExp("^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*"),
rpseudo = new RegExp(pseudos),
ridentifier = new RegExp("^" + identifier + "$"),
matchExpr = {
"ID": new RegExp("^#(" + characterEncoding + ")"),
"CLASS": new RegExp("^\\.(" + characterEncoding + ")"),
"NAME": new RegExp("^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]"),
"TAG": new RegExp("^(" + characterEncoding.replace("w", "w*") + ")"),
"ATTR": new RegExp("^" + attributes),
"PSEUDO": new RegExp("^" + pseudos),
"CHILD": new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i"),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp("^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i")
},
rsibling = /[\x20\t\r\n\f]*[+~]/,
rnative = /^[^{]+\{\s*\[native code/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rescape = /'|\\/g,
rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,
// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = /\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,
funescape = function (_, escaped) {
var high = "0x" + escaped - 0x10000;
// NaN means non-codepoint
return high !== high ?
escaped :
// BMP codepoint
high < 0 ?
String.fromCharCode(high + 0x10000) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode(high >> 10 | 0xD800, high & 0x3FF | 0xDC00);
};
// Use a stripped-down slice if we can't use a native one
try {
slice.call(preferredDoc.documentElement.childNodes, 0)[0].nodeType;
} catch (e) {
slice = function (i) {
var elem,
results = [];
while ((elem = this[i++])) {
results.push(elem);
}
return results;
};
}
/**
* For feature detection
* @param {Function} fn The function to test for native support
*/
function isNative(fn) {
return rnative.test(fn + "");
}
/**
* Create key-value caches of limited size
* @returns {Function(string, Object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
var cache,
keys = [];
return (cache = function (key, value) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if (keys.push(key += " ") > Expr.cacheLength) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return (cache[ key ] = value);
});
}
/**
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/
function markFunction(fn) {
fn[ expando ] = true;
return fn;
}
/**
* Support testing using an element
* @param {Function} fn Passed the created div and expects a boolean result
*/
function assert(fn) {
var div = document.createElement("div");
try {
return fn(div);
} catch (e) {
return false;
} finally {
// release memory in IE
div = null;
}
}
function Sizzle(selector, context, results, seed) {
var match, elem, m, nodeType,
// QSA vars
i, groups, old, nid, newContext, newSelector;
if (( context ? context.ownerDocument || context : preferredDoc ) !== document) {
setDocument(context);
}
context = context || document;
results = results || [];
if (!selector || typeof selector !== "string") {
return results;
}
if ((nodeType = context.nodeType) !== 1 && nodeType !== 9) {
return [];
}
if (!documentIsXML && !seed) {
// Shortcuts
if ((match = rquickExpr.exec(selector))) {
// Speed-up: Sizzle("#ID")
if ((m = match[1])) {
if (nodeType === 9) {
elem = context.getElementById(m);
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if (elem && elem.parentNode) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if (elem.id === m) {
results.push(elem);
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if (context.ownerDocument && (elem = context.ownerDocument.getElementById(m)) &&
contains(context, elem) && elem.id === m) {
results.push(elem);
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if (match[2]) {
push.apply(results, slice.call(context.getElementsByTagName(selector), 0));
return results;
// Speed-up: Sizzle(".CLASS")
} else if ((m = match[3]) && support.getByClassName && context.getElementsByClassName) {
push.apply(results, slice.call(context.getElementsByClassName(m), 0));
return results;
}
}
// QSA path
if (support.qsa && !rbuggyQSA.test(selector)) {
old = true;
nid = expando;
newContext = context;
newSelector = nodeType === 9 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if (nodeType === 1 && context.nodeName.toLowerCase() !== "object") {
groups = tokenize(selector);
if ((old = context.getAttribute("id"))) {
nid = old.replace(rescape, "\\$&");
} else {
context.setAttribute("id", nid);
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while (i--) {
groups[i] = nid + toSelector(groups[i]);
}
newContext = rsibling.test(selector) && context.parentNode || context;
newSelector = groups.join(",");
}
if (newSelector) {
try {
push.apply(results, slice.call(newContext.querySelectorAll(
newSelector
), 0));
return results;
} catch (qsaError) {
} finally {
if (!old) {
context.removeAttribute("id");
}
}
}
}
}
// All others
return select(selector.replace(rtrim, "$1"), context, results, seed);
}
/**
* Detect xml
* @param {Element|Object} elem An element or a document
*/
isXML = Sizzle.isXML = function (elem) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
/**
* Sets document-related variables once based on the current document
* @param {Element|Object} [doc] An element or document object to use to set the document
* @returns {Object} Returns the current document
*/
setDocument = Sizzle.setDocument = function (node) {
var doc = node ? node.ownerDocument || node : preferredDoc;
// If no document and documentElement is available, return
if (doc === document || doc.nodeType !== 9 || !doc.documentElement) {
return document;
}
// Set our document
document = doc;
docElem = doc.documentElement;
// Support tests
documentIsXML = isXML(doc);
// Check if getElementsByTagName("*") returns only elements
support.tagNameNoComments = assert(function (div) {
div.appendChild(doc.createComment(""));
return !div.getElementsByTagName("*").length;
});
// Check if attributes should be retrieved by attribute nodes
support.attributes = assert(function (div) {
div.innerHTML = "<select></select>";
var type = typeof div.lastChild.getAttribute("multiple");
// IE8 returns a string for some attributes even when not present
return type !== "boolean" && type !== "string";
});
// Check if getElementsByClassName can be trusted
support.getByClassName = assert(function (div) {
// Opera can't find a second classname (in 9.6)
div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>";
if (!div.getElementsByClassName || !div.getElementsByClassName("e").length) {
return false;
}
// Safari 3.2 caches class attributes and doesn't catch changes
div.lastChild.className = "e";
return div.getElementsByClassName("e").length === 2;
});
// Check if getElementById returns elements by name
// Check if getElementsByName privileges form controls or returns elements by ID
support.getByName = assert(function (div) {
// Inject content
div.id = expando + 0;
div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>";
docElem.insertBefore(div, docElem.firstChild);
// Test
var pass = doc.getElementsByName &&
// buggy browsers will return fewer than the correct 2
doc.getElementsByName(expando).length === 2 +
// buggy browsers will return more than the correct 0
doc.getElementsByName(expando + 0).length;
support.getIdNotName = !doc.getElementById(expando);
// Cleanup
docElem.removeChild(div);
return pass;
});
// IE6/7 return modified attributes
Expr.attrHandle = assert(function (div) {
div.innerHTML = "<a href='#'></a>";
return div.firstChild && typeof div.firstChild.getAttribute !== strundefined &&
div.firstChild.getAttribute("href") === "#";
}) ?
{} :
{
"href": function (elem) {
return elem.getAttribute("href", 2);
},
"type": function (elem) {
return elem.getAttribute("type");
}
};
// ID find and filter
if (support.getIdNotName) {
Expr.find["ID"] = function (id, context) {
if (typeof context.getElementById !== strundefined && !documentIsXML) {
var m = context.getElementById(id);
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
};
Expr.filter["ID"] = function (id) {
var attrId = id.replace(runescape, funescape);
return function (elem) {
return elem.getAttribute("id") === attrId;
};
};
} else {
Expr.find["ID"] = function (id, context) {
if (typeof context.getElementById !== strundefined && !documentIsXML) {
var m = context.getElementById(id);
return m ?
m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ?
[m] :
undefined :
[];
}
};
Expr.filter["ID"] = function (id) {
var attrId = id.replace(runescape, funescape);
return function (elem) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
}
// Tag
Expr.find["TAG"] = support.tagNameNoComments ?
function (tag, context) {
if (typeof context.getElementsByTagName !== strundefined) {
return context.getElementsByTagName(tag);
}
} :
function (tag, context) {
var elem,
tmp = [],
i = 0,
results = context.getElementsByTagName(tag);
// Filter out possible comments
if (tag === "*") {
while ((elem = results[i++])) {
if (elem.nodeType === 1) {
tmp.push(elem);
}
}
return tmp;
}
return results;
};
// Name
Expr.find["NAME"] = support.getByName && function (tag, context) {
if (typeof context.getElementsByName !== strundefined) {
return context.getElementsByName(name);
}
};
// Class
Expr.find["CLASS"] = support.getByClassName && function (className, context) {
if (typeof context.getElementsByClassName !== strundefined && !documentIsXML) {
return context.getElementsByClassName(className);
}
};
// QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [];
// qSa(:focus) reports false when true (Chrome 21),
// no need to also add to buggyMatches since matches checks buggyQSA
// A support test would require too much code (would include document ready)
rbuggyQSA = [ ":focus" ];
if ((support.qsa = isNative(doc.querySelectorAll))) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function (div) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explictly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
div.innerHTML = "<select><option selected=''></option></select>";
// IE8 - Some boolean attributes are not treated correctly
if (!div.querySelectorAll("[selected]").length) {
rbuggyQSA.push("\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)");
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here and will not see later tests
if (!div.querySelectorAll(":checked").length) {
rbuggyQSA.push(":checked");
}
});
assert(function (div) {
// Opera 10-12/IE8 - ^= $= *= and empty values
// Should not select anything
div.innerHTML = "<input type='hidden' i=''/>";
if (div.querySelectorAll("[i^='']").length) {
rbuggyQSA.push("[*^$]=" + whitespace + "*(?:\"\"|'')");
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here and will not see later tests
if (!div.querySelectorAll(":enabled").length) {
rbuggyQSA.push(":enabled", ":disabled");
}
// Opera 10-11 does not throw on post-comma invalid pseudos
div.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ((support.matchesSelector = isNative((matches = docElem.matchesSelector ||
docElem.mozMatchesSelector ||
docElem.webkitMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector)))) {
assert(function (div) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call(div, "div");
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call(div, "[s!='']:x");
rbuggyMatches.push("!=", pseudos);
});
}
rbuggyQSA = new RegExp(rbuggyQSA.join("|"));
rbuggyMatches = new RegExp(rbuggyMatches.join("|"));
// Element contains another
// Purposefully does not implement inclusive descendent
// As in, an element does not contain itself
contains = isNative(docElem.contains) || docElem.compareDocumentPosition ?
function (a, b) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains(bup) :
a.compareDocumentPosition && a.compareDocumentPosition(bup) & 16
));
} :
function (a, b) {
if (b) {
while ((b = b.parentNode)) {
if (b === a) {
return true;
}
}
}
return false;
};
// Document order sorting
sortOrder = docElem.compareDocumentPosition ?
function (a, b) {
var compare;
if (a === b) {
hasDuplicate = true;
return 0;
}
if ((compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition(b))) {
if (compare & 1 || a.parentNode && a.parentNode.nodeType === 11) {
if (a === doc || contains(preferredDoc, a)) {
return -1;
}
if (b === doc || contains(preferredDoc, b)) {
return 1;
}
return 0;
}
return compare & 4 ? -1 : 1;
}
return a.compareDocumentPosition ? -1 : 1;
} :
function (a, b) {
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ b ];
// Exit early if the nodes are identical
if (a === b) {
hasDuplicate = true;
return 0;
// Parentless nodes are either documents or disconnected
} else if (!aup || !bup) {
return a === doc ? -1 :
b === doc ? 1 :
aup ? -1 :
bup ? 1 :
0;
// If the nodes are siblings, we can do a quick check
} else if (aup === bup) {
return siblingCheck(a, b);
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while ((cur = cur.parentNode)) {
ap.unshift(cur);
}
cur = b;
while ((cur = cur.parentNode)) {
bp.unshift(cur);
}
// Walk down the tree looking for a discrepancy
while (ap[i] === bp[i]) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck(ap[i], bp[i]) :
// Otherwise nodes in our document sort first
ap[i] === preferredDoc ? -1 :
bp[i] === preferredDoc ? 1 :
0;
};
// Always assume the presence of duplicates if sort doesn't
// pass them to our comparison function (as in Google Chrome).
hasDuplicate = false;
[0, 0].sort(sortOrder);
support.detectDuplicates = hasDuplicate;
return document;
};
Sizzle.matches = function (expr, elements) {
return Sizzle(expr, null, null, elements);
};
Sizzle.matchesSelector = function (elem, expr) {
// Set document vars if needed
if (( elem.ownerDocument || elem ) !== document) {
setDocument(elem);
}
// Make sure that attribute selectors are quoted
expr = expr.replace(rattributeQuotes, "='$1']");
// rbuggyQSA always contains :focus, so no need for an existence check
if (support.matchesSelector && !documentIsXML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && !rbuggyQSA.test(expr)) {
try {
var ret = matches.call(elem, expr);
// IE 9's matchesSelector returns false on disconnected nodes
if (ret || support.disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11) {
return ret;
}
} catch (e) {
}
}
return Sizzle(expr, document, null, [elem]).length > 0;
};
Sizzle.contains = function (context, elem) {
// Set document vars if needed
if (( context.ownerDocument || context ) !== document) {
setDocument(context);
}
return contains(context, elem);
};
Sizzle.attr = function (elem, name) {
var val;
// Set document vars if needed
if (( elem.ownerDocument || elem ) !== document) {
setDocument(elem);
}
if (!documentIsXML) {
name = name.toLowerCase();
}
if ((val = Expr.attrHandle[ name ])) {
return val(elem);
}
if (documentIsXML || support.attributes) {
return elem.getAttribute(name);
}
return ( (val = elem.getAttributeNode(name)) || elem.getAttribute(name) ) && elem[ name ] === true ?
name :
val && val.specified ? val.value : null;
};
Sizzle.error = function (msg) {
throw new Error("Syntax error, unrecognized expression: " + msg);
};
// Document sorting and removing duplicates
Sizzle.uniqueSort = function (results) {
var elem,
duplicates = [],
i = 1,
j = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
results.sort(sortOrder);
if (hasDuplicate) {
for (; (elem = results[i]); i++) {
if (elem === results[ i - 1 ]) {
j = duplicates.push(i);
}
}
while (j--) {
results.splice(duplicates[ j ], 1);
}
}
return results;
};
function siblingCheck(a, b) {
var cur = b && a,
diff = cur && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE );
// Use IE sourceIndex if available on both nodes
if (diff) {
return diff;
}
// Check if b follows a
if (cur) {
while ((cur = cur.nextSibling)) {
if (cur === b) {
return -1;
}
}
}
return a ? 1 : -1;
}
// Returns a function to use in pseudos for input types
function createInputPseudo(type) {
return function (elem) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
// Returns a function to use in pseudos for buttons
function createButtonPseudo(type) {
return function (elem) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
// Returns a function to use in pseudos for positionals
function createPositionalPseudo(fn) {
return markFunction(function (argument) {
argument = +argument;
return markFunction(function (seed, matches) {
var j,
matchIndexes = fn([], seed.length, argument),
i = matchIndexes.length;
// Match elements found at the specified indexes
while (i--) {
if (seed[ (j = matchIndexes[i]) ]) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function (elem) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if (!nodeType) {
// If no nodeType, this is expected to be an array
for (; (node = elem[i]); i++) {
// Do not traverse comment nodes
ret += getText(node);
}
} else if (nodeType === 1 || nodeType === 9 || nodeType === 11) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (see #11153)
if (typeof elem.textContent === "string") {
return elem.textContent;
} else {
// Traverse its children
for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
ret += getText(elem);
}
}
} else if (nodeType === 3 || nodeType === 4) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
find: {},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function (match) {
match[1] = match[1].replace(runescape, funescape);
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[4] || match[5] || "" ).replace(runescape, funescape);
if (match[2] === "~=") {
match[3] = " " + match[3] + " ";
}
return match.slice(0, 4);
},
"CHILD": function (match) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[1] = match[1].toLowerCase();
if (match[1].slice(0, 3) === "nth") {
// nth-* requires argument
if (!match[3]) {
Sizzle.error(match[0]);
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
// other types prohibit arguments
} else if (match[3]) {
Sizzle.error(match[0]);
}
return match;
},
"PSEUDO": function (match) {
var excess,
unquoted = !match[5] && match[2];
if (matchExpr["CHILD"].test(match[0])) {
return null;
}
// Accept quoted arguments as-is
if (match[4]) {
match[2] = match[4];
// Strip excess characters from unquoted arguments
} else if (unquoted && rpseudo.test(unquoted) &&
// Get excess from tokenize (recursively)
(excess = tokenize(unquoted, true)) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf(")", unquoted.length - excess) - unquoted.length)) {
// excess is a negative index
match[0] = match[0].slice(0, excess);
match[2] = unquoted.slice(0, excess);
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice(0, 3);
}
},
filter: {
"TAG": function (nodeName) {
if (nodeName === "*") {
return function () {
return true;
};
}
nodeName = nodeName.replace(runescape, funescape).toLowerCase();
return function (elem) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function (className) {
var pattern = classCache[ className + " " ];
return pattern ||
(pattern = new RegExp("(^|" + whitespace + ")" + className + "(" + whitespace + "|$)")) &&
classCache(className, function (elem) {
return pattern.test(elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "");
});
},
"ATTR": function (name, operator, check) {
return function (elem) {
var result = Sizzle.attr(elem, name);
if (result == null) {
return operator === "!=";
}
if (!operator) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf(check) === 0 :
operator === "*=" ? check && result.indexOf(check) > -1 :
operator === "$=" ? check && result.slice(-check.length) === check :
operator === "~=" ? ( " " + result + " " ).indexOf(check) > -1 :
operator === "|=" ? result === check || result.slice(0, check.length + 1) === check + "-" :
false;
};
},
"CHILD": function (type, what, argument, first, last) {
var simple = type.slice(0, 3) !== "nth",
forward = type.slice(-4) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function (elem) {
return !!elem.parentNode;
} :
function (elem, context, xml) {
var cache, outerCache, node, diff, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType;
if (parent) {
// :(first|last|only)-(child|of-type)
if (simple) {
while (dir) {
node = elem;
while ((node = node[ dir ])) {
if (ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [ forward ? parent.firstChild : parent.lastChild ];
// non-xml :nth-child(...) stores cache data on `parent`
if (forward && useCache) {
// Seek `elem` from a previously-cached index
outerCache = parent[ expando ] || (parent[ expando ] = {});
cache = outerCache[ type ] || [];
nodeIndex = cache[0] === dirruns && cache[1];
diff = cache[0] === dirruns && cache[2];
node = nodeIndex && parent.childNodes[ nodeIndex ];
while ((node = ++nodeIndex && node && node[ dir ] ||
// Fallback to seeking `elem` from the start
(diff = nodeIndex = 0) || start.pop())) {
// When found, cache indexes on `parent` and break
if (node.nodeType === 1 && ++diff && node === elem) {
outerCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
// Use previously-cached element index if available
} else if (useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns) {
diff = cache[1];
// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
} else {
// Use the same loop as above to seek `elem` from the start
while ((node = ++nodeIndex && node && node[ dir ] ||
(diff = nodeIndex = 0) || start.pop())) {
if (( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff) {
// Cache the index of each encountered element
if (useCache) {
(node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ];
}
if (node === elem) {
break;
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
}
};
},
"PSEUDO": function (pseudo, argument) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error("unsupported pseudo: " + pseudo);
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if (fn[ expando ]) {
return fn(argument);
}
// But maintain support for old signatures
if (fn.length > 1) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty(pseudo.toLowerCase()) ?
markFunction(function (seed, matches) {
var idx,
matched = fn(seed, argument),
i = matched.length;
while (i--) {
idx = indexOf.call(seed, matched[i]);
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function (elem) {
return fn(elem, 0, args);
};
}
return fn;
}
},
pseudos: {
// Potentially complex pseudos
"not": markFunction(function (selector) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile(selector.replace(rtrim, "$1"));
return matcher[ expando ] ?
markFunction(function (seed, matches, context, xml) {
var elem,
unmatched = matcher(seed, null, xml, []),
i = seed.length;
// Match elements unmatched by `matcher`
while (i--) {
if ((elem = unmatched[i])) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function (elem, context, xml) {
input[0] = elem;
matcher(input, null, xml, results);
return !results.pop();
};
}),
"has": markFunction(function (selector) {
return function (elem) {
return Sizzle(selector, elem).length > 0;
};
}),
"contains": markFunction(function (text) {
return function (elem) {
return ( elem.textContent || elem.innerText || getText(elem) ).indexOf(text) > -1;
};
}),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
"lang": markFunction(function (lang) {
// lang value must be a valid identifider
if (!ridentifier.test(lang || "")) {
Sizzle.error("unsupported lang: " + lang);
}
lang = lang.replace(runescape, funescape).toLowerCase();
return function (elem) {
var elemLang;
do {
if ((elemLang = documentIsXML ?
elem.getAttribute("xml:lang") || elem.getAttribute("lang") :
elem.lang)) {
elemLang = elemLang.toLowerCase();
return elemLang === lang || elemLang.indexOf(lang + "-") === 0;
}
} while ((elem = elem.parentNode) && elem.nodeType === 1);
return false;
};
}),
// Miscellaneous
"target": function (elem) {
var hash = window.location && window.location.hash;
return hash && hash.slice(1) === elem.id;
},
"root": function (elem) {
return elem === docElem;
},
"focus": function (elem) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"enabled": function (elem) {
return elem.disabled === false;
},
"disabled": function (elem) {
return elem.disabled === true;
},
"checked": function (elem) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function (elem) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if (elem.parentNode) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
// Contents
"empty": function (elem) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),
// not comment, processing instructions, or others
// Thanks to Diego Perini for the nodeName shortcut
// Greater than "@" means alpha characters (specifically not starting with "#" or "?")
for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
if (elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4) {
return false;
}
}
return true;
},
"parent": function (elem) {
return !Expr.pseudos["empty"](elem);
},
// Element/input types
"header": function (elem) {
return rheader.test(elem.nodeName);
},
"input": function (elem) {
return rinputs.test(elem.nodeName);
},
"button": function (elem) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"text": function (elem) {
var attr;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" &&
elem.type === "text" &&
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type );
},
// Position-in-collection
"first": createPositionalPseudo(function () {
return [ 0 ];
}),
"last": createPositionalPseudo(function (matchIndexes, length) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function (matchIndexes, length, argument) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function (matchIndexes, length) {
var i = 0;
for (; i < length; i += 2) {
matchIndexes.push(i);
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function (matchIndexes, length) {
var i = 1;
for (; i < length; i += 2) {
matchIndexes.push(i);
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function (matchIndexes, length, argument) {
var i = argument < 0 ? argument + length : argument;
for (; --i >= 0;) {
matchIndexes.push(i);
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function (matchIndexes, length, argument) {
var i = argument < 0 ? argument + length : argument;
for (; ++i < length;) {
matchIndexes.push(i);
}
return matchIndexes;
})
}
};
// Add button/input type pseudos
for (i in { radio: true, checkbox: true, file: true, password: true, image: true }) {
Expr.pseudos[ i ] = createInputPseudo(i);
}
for (i in { submit: true, reset: true }) {
Expr.pseudos[ i ] = createButtonPseudo(i);
}
function tokenize(selector, parseOnly) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ selector + " " ];
if (cached) {
return parseOnly ? 0 : cached.slice(0);
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while (soFar) {
// Comma and first run
if (!matched || (match = rcomma.exec(soFar))) {
if (match) {
// Don't consume trailing commas as valid
soFar = soFar.slice(match[0].length) || soFar;
}
groups.push(tokens = []);
}
matched = false;
// Combinators
if ((match = rcombinators.exec(soFar))) {
matched = match.shift();
tokens.push({
value: matched,
// Cast descendant combinators to space
type: match[0].replace(rtrim, " ")
});
soFar = soFar.slice(matched.length);
}
// Filters
for (type in Expr.filter) {
if ((match = matchExpr[ type ].exec(soFar)) && (!preFilters[ type ] ||
(match = preFilters[ type ](match)))) {
matched = match.shift();
tokens.push({
value: matched,
type: type,
matches: match
});
soFar = soFar.slice(matched.length);
}
}
if (!matched) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error(selector) :
// Cache the tokens
tokenCache(selector, groups).slice(0);
}
function toSelector(tokens) {
var i = 0,
len = tokens.length,
selector = "";
for (; i < len; i++) {
selector += tokens[i].value;
}
return selector;
}
function addCombinator(matcher, combinator, base) {
var dir = combinator.dir,
checkNonElements = base && dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function (elem, context, xml) {
while ((elem = elem[ dir ])) {
if (elem.nodeType === 1 || checkNonElements) {
return matcher(elem, context, xml);
}
}
} :
// Check against all ancestor/preceding elements
function (elem, context, xml) {
var data, cache, outerCache,
dirkey = dirruns + " " + doneName;
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
if (xml) {
while ((elem = elem[ dir ])) {
if (elem.nodeType === 1 || checkNonElements) {
if (matcher(elem, context, xml)) {
return true;
}
}
}
} else {
while ((elem = elem[ dir ])) {
if (elem.nodeType === 1 || checkNonElements) {
outerCache = elem[ expando ] || (elem[ expando ] = {});
if ((cache = outerCache[ dir ]) && cache[0] === dirkey) {
if ((data = cache[1]) === true || data === cachedruns) {
return data === true;
}
} else {
cache = outerCache[ dir ] = [ dirkey ];
cache[1] = matcher(elem, context, xml) || cachedruns;
if (cache[1] === true) {
return true;
}
}
}
}
}
};
}
function elementMatcher(matchers) {
return matchers.length > 1 ?
function (elem, context, xml) {
var i = matchers.length;
while (i--) {
if (!matchers[i](elem, context, xml)) {
return false;
}
}
return true;
} :
matchers[0];
}
function condense(unmatched, map, filter, context, xml) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for (; i < len; i++) {
if ((elem = unmatched[i])) {
if (!filter || filter(elem, context, xml)) {
newUnmatched.push(elem);
if (mapped) {
map.push(i);
}
}
}
}
return newUnmatched;
}
function setMatcher(preFilter, selector, matcher, postFilter, postFinder, postSelector) {
if (postFilter && !postFilter[ expando ]) {
postFilter = setMatcher(postFilter);
}
if (postFinder && !postFinder[ expando ]) {
postFinder = setMatcher(postFinder, postSelector);
}
return markFunction(function (seed, results, context, xml) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts(selector || "*", context.nodeType ? [ context ] : context, []),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense(elems, preMap, preFilter, context, xml) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if (matcher) {
matcher(matcherIn, matcherOut, context, xml);
}
// Apply postFilter
if (postFilter) {
temp = condense(matcherOut, postMap);
postFilter(temp, [], context, xml);
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while (i--) {
if ((elem = temp[i])) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if (seed) {
if (postFinder || preFilter) {
if (postFinder) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while (i--) {
if ((elem = matcherOut[i])) {
// Restore matcherIn since elem is not yet a final match
temp.push((matcherIn[i] = elem));
}
}
postFinder(null, (matcherOut = []), temp, xml);
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while (i--) {
if ((elem = matcherOut[i]) &&
(temp = postFinder ? indexOf.call(seed, elem) : preMap[i]) > -1) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice(preexisting, matcherOut.length) :
matcherOut
);
if (postFinder) {
postFinder(null, results, matcherOut, xml);
} else {
push.apply(results, matcherOut);
}
}
});
}
function matcherFromTokens(tokens) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator(function (elem) {
return elem === checkContext;
}, implicitRelative, true),
matchAnyContext = addCombinator(function (elem) {
return indexOf.call(checkContext, elem) > -1;
}, implicitRelative, true),
matchers = [ function (elem, context, xml) {
return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext(elem, context, xml) :
matchAnyContext(elem, context, xml) );
} ];
for (; i < len; i++) {
if ((matcher = Expr.relative[ tokens[i].type ])) {
matchers = [ addCombinator(elementMatcher(matchers), matcher) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply(null, tokens[i].matches);
// Return special upon seeing a positional matcher
if (matcher[ expando ]) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for (; j < len; j++) {
if (Expr.relative[ tokens[j].type ]) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher(matchers),
i > 1 && toSelector(tokens.slice(0, i - 1)).replace(rtrim, "$1"),
matcher,
i < j && matcherFromTokens(tokens.slice(i, j)),
j < len && matcherFromTokens((tokens = tokens.slice(j))),
j < len && toSelector(tokens)
);
}
matchers.push(matcher);
}
}
return elementMatcher(matchers);
}
function matcherFromGroupMatchers(elementMatchers, setMatchers) {
// A counter to specify which element is currently being matched
var matcherCachedRuns = 0,
bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function (seed, context, xml, results, expandContext) {
var elem, j, matcher,
setMatched = [],
matchedCount = 0,
i = "0",
unmatched = seed && [],
outermost = expandContext != null,
contextBackup = outermostContext,
// We must always have either seed elements or context
elems = seed || byElement && Expr.find["TAG"]("*", expandContext && context.parentNode || context),
// Use integer dirruns iff this is the outermost matcher
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1);
if (outermost) {
outermostContext = context !== document && context;
cachedruns = matcherCachedRuns;
}
// Add elements passing elementMatchers directly to results
// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
for (; (elem = elems[i]) != null; i++) {
if (byElement && elem) {
j = 0;
while ((matcher = elementMatchers[j++])) {
if (matcher(elem, context, xml)) {
results.push(elem);
break;
}
}
if (outermost) {
dirruns = dirrunsUnique;
cachedruns = ++matcherCachedRuns;
}
}
// Track unmatched elements for set filters
if (bySet) {
// They will have gone through all possible matchers
if ((elem = !matcher && elem)) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if (seed) {
unmatched.push(elem);
}
}
}
// Apply set filters to unmatched elements
matchedCount += i;
if (bySet && i !== matchedCount) {
j = 0;
while ((matcher = setMatchers[j++])) {
matcher(unmatched, setMatched, context, xml);
}
if (seed) {
// Reintegrate element matches to eliminate the need for sorting
if (matchedCount > 0) {
while (i--) {
if (!(unmatched[i] || setMatched[i])) {
setMatched[i] = pop.call(results);
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense(setMatched);
}
// Add matches to results
push.apply(results, setMatched);
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if (outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1) {
Sizzle.uniqueSort(results);
}
}
// Override manipulation of globals by nested matchers
if (outermost) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ?
markFunction(superMatcher) :
superMatcher;
}
compile = Sizzle.compile = function (selector, group /* Internal Use Only */) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ selector + " " ];
if (!cached) {
// Generate a function of recursive functions that can be used to check each element
if (!group) {
group = tokenize(selector);
}
i = group.length;
while (i--) {
cached = matcherFromTokens(group[i]);
if (cached[ expando ]) {
setMatchers.push(cached);
} else {
elementMatchers.push(cached);
}
}
// Cache the compiled function
cached = compilerCache(selector, matcherFromGroupMatchers(elementMatchers, setMatchers));
}
return cached;
};
function multipleContexts(selector, contexts, results) {
var i = 0,
len = contexts.length;
for (; i < len; i++) {
Sizzle(selector, contexts[i], results);
}
return results;
}
function select(selector, context, results, seed) {
var i, tokens, token, type, find,
match = tokenize(selector);
if (!seed) {
// Try to minimize operations if there is only one group
if (match.length === 1) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice(0);
if (tokens.length > 2 && (token = tokens[0]).type === "ID" &&
context.nodeType === 9 && !documentIsXML &&
Expr.relative[ tokens[1].type ]) {
context = Expr.find["ID"](token.matches[0].replace(runescape, funescape), context)[0];
if (!context) {
return results;
}
selector = selector.slice(tokens.shift().value.length);
}
// Fetch a seed set for right-to-left matching
i = matchExpr["needsContext"].test(selector) ? 0 : tokens.length;
while (i--) {
token = tokens[i];
// Abort if we hit a combinator
if (Expr.relative[ (type = token.type) ]) {
break;
}
if ((find = Expr.find[ type ])) {
// Search, expanding context for leading sibling combinators
if ((seed = find(
token.matches[0].replace(runescape, funescape),
rsibling.test(tokens[0].type) && context.parentNode || context
))) {
// If seed is empty or no tokens remain, we can return early
tokens.splice(i, 1);
selector = seed.length && toSelector(tokens);
if (!selector) {
push.apply(results, slice.call(seed, 0));
return results;
}
break;
}
}
}
}
}
// Compile and execute a filtering function
// Provide `match` to avoid retokenization if we modified the selector above
compile(selector, match)(
seed,
context,
documentIsXML,
results,
rsibling.test(selector)
);
return results;
}
// Deprecated
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Easy API for creating new setFilters
function setFilters() {
}
Expr.filters = setFilters.prototype = Expr.pseudos;
Expr.setFilters = new setFilters();
// Initialize with the default document
setDocument();
// Override sizzle attribute retrieval
Sizzle.attr = jQuery.attr;
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})(window);
var runtil = /Until$/,
rparentsprev = /^(?:parents|prev(?:Until|All))/,
isSimple = /^.[^:#\[\.,]*$/,
rneedsContext = jQuery.expr.match.needsContext,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function (selector) {
var i, ret, self,
len = this.length;
if (typeof selector !== "string") {
self = this;
return this.pushStack(jQuery(selector).filter(function () {
for (i = 0; i < len; i++) {
if (jQuery.contains(self[ i ], this)) {
return true;
}
}
}));
}
ret = [];
for (i = 0; i < len; i++) {
jQuery.find(selector, this[ i ], ret);
}
// Needed because $( selector, context ) becomes $( context ).find( selector )
ret = this.pushStack(len > 1 ? jQuery.unique(ret) : ret);
ret.selector = ( this.selector ? this.selector + " " : "" ) + selector;
return ret;
},
has: function (target) {
var i,
targets = jQuery(target, this),
len = targets.length;
return this.filter(function () {
for (i = 0; i < len; i++) {
if (jQuery.contains(this, targets[i])) {
return true;
}
}
});
},
not: function (selector) {
return this.pushStack(winnow(this, selector, false));
},
filter: function (selector) {
return this.pushStack(winnow(this, selector, true));
},
is: function (selector) {
return !!selector && (
typeof selector === "string" ?
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
rneedsContext.test(selector) ?
jQuery(selector, this.context).index(this[0]) >= 0 :
jQuery.filter(selector, this).length > 0 :
this.filter(selector).length > 0 );
},
closest: function (selectors, context) {
var cur,
i = 0,
l = this.length,
ret = [],
pos = rneedsContext.test(selectors) || typeof selectors !== "string" ?
jQuery(selectors, context || this.context) :
0;
for (; i < l; i++) {
cur = this[i];
while (cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11) {
if (pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors)) {
ret.push(cur);
break;
}
cur = cur.parentNode;
}
}
return this.pushStack(ret.length > 1 ? jQuery.unique(ret) : ret);
},
// Determine the position of an element within
// the matched set of elements
index: function (elem) {
// No argument, return index in parent
if (!elem) {
return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1;
}
// index in selector
if (typeof elem === "string") {
return jQuery.inArray(this[0], jQuery(elem));
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this);
},
add: function (selector, context) {
var set = typeof selector === "string" ?
jQuery(selector, context) :
jQuery.makeArray(selector && selector.nodeType ? [ selector ] : selector),
all = jQuery.merge(this.get(), set);
return this.pushStack(jQuery.unique(all));
},
addBack: function (selector) {
return this.add(selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
jQuery.fn.andSelf = jQuery.fn.addBack;
function sibling(cur, dir) {
do {
cur = cur[ dir ];
} while (cur && cur.nodeType !== 1);
return cur;
}
jQuery.each({
parent: function (elem) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function (elem) {
return jQuery.dir(elem, "parentNode");
},
parentsUntil: function (elem, i, until) {
return jQuery.dir(elem, "parentNode", until);
},
next: function (elem) {
return sibling(elem, "nextSibling");
},
prev: function (elem) {
return sibling(elem, "previousSibling");
},
nextAll: function (elem) {
return jQuery.dir(elem, "nextSibling");
},
prevAll: function (elem) {
return jQuery.dir(elem, "previousSibling");
},
nextUntil: function (elem, i, until) {
return jQuery.dir(elem, "nextSibling", until);
},
prevUntil: function (elem, i, until) {
return jQuery.dir(elem, "previousSibling", until);
},
siblings: function (elem) {
return jQuery.sibling(( elem.parentNode || {} ).firstChild, elem);
},
children: function (elem) {
return jQuery.sibling(elem.firstChild);
},
contents: function (elem) {
return jQuery.nodeName(elem, "iframe") ?
elem.contentDocument || elem.contentWindow.document :
jQuery.merge([], elem.childNodes);
}
}, function (name, fn) {
jQuery.fn[ name ] = function (until, selector) {
var ret = jQuery.map(this, fn, until);
if (!runtil.test(name)) {
selector = until;
}
if (selector && typeof selector === "string") {
ret = jQuery.filter(selector, ret);
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique(ret) : ret;
if (this.length > 1 && rparentsprev.test(name)) {
ret = ret.reverse();
}
return this.pushStack(ret);
};
});
jQuery.extend({
filter: function (expr, elems, not) {
if (not) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 ?
jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
jQuery.find.matches(expr, elems);
},
dir: function (elem, dir, until) {
var matched = [],
cur = elem[ dir ];
while (cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery(cur).is(until))) {
if (cur.nodeType === 1) {
matched.push(cur);
}
cur = cur[dir];
}
return matched;
},
sibling: function (n, elem) {
var r = [];
for (; n; n = n.nextSibling) {
if (n.nodeType === 1 && n !== elem) {
r.push(n);
}
}
return r;
}
});
// Implement the identical functionality for filter and not
function winnow(elements, qualifier, keep) {
// Can't pass null or undefined to indexOf in Firefox 4
// Set to 0 to skip string check
qualifier = qualifier || 0;
if (jQuery.isFunction(qualifier)) {
return jQuery.grep(elements, function (elem, i) {
var retVal = !!qualifier.call(elem, i, elem);
return retVal === keep;
});
} else if (qualifier.nodeType) {
return jQuery.grep(elements, function (elem) {
return ( elem === qualifier ) === keep;
});
} else if (typeof qualifier === "string") {
var filtered = jQuery.grep(elements, function (elem) {
return elem.nodeType === 1;
});
if (isSimple.test(qualifier)) {
return jQuery.filter(qualifier, filtered, !keep);
} else {
qualifier = jQuery.filter(qualifier, filtered);
}
}
return jQuery.grep(elements, function (elem) {
return ( jQuery.inArray(elem, qualifier) >= 0 ) === keep;
});
}
function createSafeFragment(document) {
var list = nodeNames.split("|"),
safeFrag = document.createDocumentFragment();
if (safeFrag.createElement) {
while (list.length) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
manipulation_rcheckableType = /^(?:checkbox|radio)$/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /^$|\/(?:java|ecma)script/i,
rscriptTypeMasked = /^true\/(.*)/,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
// We have to close these tags to support XHTML (#13200)
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
area: [ 1, "<map>", "</map>" ],
param: [ 1, "<object>", "</object>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
// unless wrapped in a div with non-breaking characters in front of it.
_default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ]
},
safeFragment = createSafeFragment(document),
fragmentDiv = safeFragment.appendChild(document.createElement("div"));
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
jQuery.fn.extend({
text: function (value) {
return jQuery.access(this, function (value) {
return value === undefined ?
jQuery.text(this) :
this.empty().append(( this[0] && this[0].ownerDocument || document ).createTextNode(value));
}, null, value, arguments.length);
},
wrapAll: function (html) {
if (jQuery.isFunction(html)) {
return this.each(function (i) {
jQuery(this).wrapAll(html.call(this, i));
});
}
if (this[0]) {
// The elements to wrap the target around
var wrap = jQuery(html, this[0].ownerDocument).eq(0).clone(true);
if (this[0].parentNode) {
wrap.insertBefore(this[0]);
}
wrap.map(function () {
var elem = this;
while (elem.firstChild && elem.firstChild.nodeType === 1) {
elem = elem.firstChild;
}
return elem;
}).append(this);
}
return this;
},
wrapInner: function (html) {
if (jQuery.isFunction(html)) {
return this.each(function (i) {
jQuery(this).wrapInner(html.call(this, i));
});
}
return this.each(function () {
var self = jQuery(this),
contents = self.contents();
if (contents.length) {
contents.wrapAll(html);
} else {
self.append(html);
}
});
},
wrap: function (html) {
var isFunction = jQuery.isFunction(html);
return this.each(function (i) {
jQuery(this).wrapAll(isFunction ? html.call(this, i) : html);
});
},
unwrap: function () {
return this.parent().each(function () {
if (!jQuery.nodeName(this, "body")) {
jQuery(this).replaceWith(this.childNodes);
}
}).end();
},
append: function () {
return this.domManip(arguments, true, function (elem) {
if (this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9) {
this.appendChild(elem);
}
});
},
prepend: function () {
return this.domManip(arguments, true, function (elem) {
if (this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9) {
this.insertBefore(elem, this.firstChild);
}
});
},
before: function () {
return this.domManip(arguments, false, function (elem) {
if (this.parentNode) {
this.parentNode.insertBefore(elem, this);
}
});
},
after: function () {
return this.domManip(arguments, false, function (elem) {
if (this.parentNode) {
this.parentNode.insertBefore(elem, this.nextSibling);
}
});
},
// keepData is for internal use only--do not document
remove: function (selector, keepData) {
var elem,
i = 0;
for (; (elem = this[i]) != null; i++) {
if (!selector || jQuery.filter(selector, [ elem ]).length > 0) {
if (!keepData && elem.nodeType === 1) {
jQuery.cleanData(getAll(elem));
}
if (elem.parentNode) {
if (keepData && jQuery.contains(elem.ownerDocument, elem)) {
setGlobalEval(getAll(elem, "script"));
}
elem.parentNode.removeChild(elem);
}
}
}
return this;
},
empty: function () {
var elem,
i = 0;
for (; (elem = this[i]) != null; i++) {
// Remove element nodes and prevent memory leaks
if (elem.nodeType === 1) {
jQuery.cleanData(getAll(elem, false));
}
// Remove any remaining nodes
while (elem.firstChild) {
elem.removeChild(elem.firstChild);
}
// If this is a select, ensure that it displays empty (#12336)
// Support: IE<9
if (elem.options && jQuery.nodeName(elem, "select")) {
elem.options.length = 0;
}
}
return this;
},
clone: function (dataAndEvents, deepDataAndEvents) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map(function () {
return jQuery.clone(this, dataAndEvents, deepDataAndEvents);
});
},
html: function (value) {
return jQuery.access(this, function (value) {
var elem = this[0] || {},
i = 0,
l = this.length;
if (value === undefined) {
return elem.nodeType === 1 ?
elem.innerHTML.replace(rinlinejQuery, "") :
undefined;
}
// See if we can take a shortcut and just use innerHTML
if (typeof value === "string" && !rnoInnerhtml.test(value) &&
( jQuery.support.htmlSerialize || !rnoshimcache.test(value) ) &&
( jQuery.support.leadingWhitespace || !rleadingWhitespace.test(value) ) && !wrapMap[ ( rtagName.exec(value) || ["", ""] )[1].toLowerCase() ]) {
value = value.replace(rxhtmlTag, "<$1></$2>");
try {
for (; i < l; i++) {
// Remove element nodes and prevent memory leaks
elem = this[i] || {};
if (elem.nodeType === 1) {
jQuery.cleanData(getAll(elem, false));
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch (e) {
}
}
if (elem) {
this.empty().append(value);
}
}, null, value, arguments.length);
},
replaceWith: function (value) {
var isFunc = jQuery.isFunction(value);
// Make sure that the elements are removed from the DOM before they are inserted
// this can help fix replacing a parent with child elements
if (!isFunc && typeof value !== "string") {
value = jQuery(value).not(this).detach();
}
return this.domManip([ value ], true, function (elem) {
var next = this.nextSibling,
parent = this.parentNode;
if (parent) {
jQuery(this).remove();
parent.insertBefore(elem, next);
}
});
},
detach: function (selector) {
return this.remove(selector, true);
},
domManip: function (args, table, callback) {
// Flatten any nested arrays
args = core_concat.apply([], args);
var first, node, hasScripts,
scripts, doc, fragment,
i = 0,
l = this.length,
set = this,
iNoClone = l - 1,
value = args[0],
isFunction = jQuery.isFunction(value);
// We can't cloneNode fragments that contain checked, in WebKit
if (isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test(value) )) {
return this.each(function (index) {
var self = set.eq(index);
if (isFunction) {
args[0] = value.call(this, index, table ? self.html() : undefined);
}
self.domManip(args, table, callback);
});
}
if (l) {
fragment = jQuery.buildFragment(args, this[ 0 ].ownerDocument, false, this);
first = fragment.firstChild;
if (fragment.childNodes.length === 1) {
fragment = first;
}
if (first) {
table = table && jQuery.nodeName(first, "tr");
scripts = jQuery.map(getAll(fragment, "script"), disableScript);
hasScripts = scripts.length;
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
for (; i < l; i++) {
node = fragment;
if (i !== iNoClone) {
node = jQuery.clone(node, true, true);
// Keep references to cloned scripts for later restoration
if (hasScripts) {
jQuery.merge(scripts, getAll(node, "script"));
}
}
callback.call(
table && jQuery.nodeName(this[i], "table") ?
findOrAppend(this[i], "tbody") :
this[i],
node,
i
);
}
if (hasScripts) {
doc = scripts[ scripts.length - 1 ].ownerDocument;
// Reenable scripts
jQuery.map(scripts, restoreScript);
// Evaluate executable scripts on first document insertion
for (i = 0; i < hasScripts; i++) {
node = scripts[ i ];
if (rscriptType.test(node.type || "") && !jQuery._data(node, "globalEval") && jQuery.contains(doc, node)) {
if (node.src) {
// Hope ajax is available...
jQuery.ajax({
url: node.src,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
} else {
jQuery.globalEval(( node.text || node.textContent || node.innerHTML || "" ).replace(rcleanScript, ""));
}
}
}
}
// Fix #11809: Avoid leaking memory
fragment = first = null;
}
}
return this;
}
});
function findOrAppend(elem, tag) {
return elem.getElementsByTagName(tag)[0] || elem.appendChild(elem.ownerDocument.createElement(tag));
}
// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript(elem) {
var attr = elem.getAttributeNode("type");
elem.type = ( attr && attr.specified ) + "/" + elem.type;
return elem;
}
function restoreScript(elem) {
var match = rscriptTypeMasked.exec(elem.type);
if (match) {
elem.type = match[1];
} else {
elem.removeAttribute("type");
}
return elem;
}
// Mark scripts as having already been evaluated
function setGlobalEval(elems, refElements) {
var elem,
i = 0;
for (; (elem = elems[i]) != null; i++) {
jQuery._data(elem, "globalEval", !refElements || jQuery._data(refElements[i], "globalEval"));
}
}
function cloneCopyEvent(src, dest) {
if (dest.nodeType !== 1 || !jQuery.hasData(src)) {
return;
}
var type, i, l,
oldData = jQuery._data(src),
curData = jQuery._data(dest, oldData),
events = oldData.events;
if (events) {
delete curData.handle;
curData.events = {};
for (type in events) {
for (i = 0, l = events[ type ].length; i < l; i++) {
jQuery.event.add(dest, type, events[ type ][ i ]);
}
}
}
// make the cloned public data object a copy from the original
if (curData.data) {
curData.data = jQuery.extend({}, curData.data);
}
}
function fixCloneNodeIssues(src, dest) {
var nodeName, e, data;
// We do not need to do anything for non-Elements
if (dest.nodeType !== 1) {
return;
}
nodeName = dest.nodeName.toLowerCase();
// IE6-8 copies events bound via attachEvent when using cloneNode.
if (!jQuery.support.noCloneEvent && dest[ jQuery.expando ]) {
data = jQuery._data(dest);
for (e in data.events) {
jQuery.removeEvent(dest, e, data.handle);
}
// Event data gets referenced instead of copied if the expando gets copied too
dest.removeAttribute(jQuery.expando);
}
// IE blanks contents when cloning scripts, and tries to evaluate newly-set text
if (nodeName === "script" && dest.text !== src.text) {
disableScript(dest).text = src.text;
restoreScript(dest);
// IE6-10 improperly clones children of object elements using classid.
// IE10 throws NoModificationAllowedError if parent is null, #12132.
} else if (nodeName === "object") {
if (dest.parentNode) {
dest.outerHTML = src.outerHTML;
}
// This path appears unavoidable for IE9. When cloning an object
// element in IE9, the outerHTML strategy above is not sufficient.
// If the src has innerHTML and the destination does not,
// copy the src.innerHTML into the dest.innerHTML. #10324
if (jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) )) {
dest.innerHTML = src.innerHTML;
}
} else if (nodeName === "input" && manipulation_rcheckableType.test(src.type)) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
dest.defaultChecked = dest.checked = src.checked;
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if (dest.value !== src.value) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if (nodeName === "option") {
dest.defaultSelected = dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if (nodeName === "input" || nodeName === "textarea") {
dest.defaultValue = src.defaultValue;
}
}
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function (name, original) {
jQuery.fn[ name ] = function (selector) {
var elems,
i = 0,
ret = [],
insert = jQuery(selector),
last = insert.length - 1;
for (; i <= last; i++) {
elems = i === last ? this : this.clone(true);
jQuery(insert[i])[ original ](elems);
// Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get()
core_push.apply(ret, elems.get());
}
return this.pushStack(ret);
};
});
function getAll(context, tag) {
var elems, elem,
i = 0,
found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName(tag || "*") :
typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll(tag || "*") :
undefined;
if (!found) {
for (found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++) {
if (!tag || jQuery.nodeName(elem, tag)) {
found.push(elem);
} else {
jQuery.merge(found, getAll(elem, tag));
}
}
}
return tag === undefined || tag && jQuery.nodeName(context, tag) ?
jQuery.merge([ context ], found) :
found;
}
// Used in buildFragment, fixes the defaultChecked property
function fixDefaultChecked(elem) {
if (manipulation_rcheckableType.test(elem.type)) {
elem.defaultChecked = elem.checked;
}
}
jQuery.extend({
clone: function (elem, dataAndEvents, deepDataAndEvents) {
var destElements, node, clone, i, srcElements,
inPage = jQuery.contains(elem.ownerDocument, elem);
if (jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test("<" + elem.nodeName + ">")) {
clone = elem.cloneNode(true);
// IE<=8 does not properly clone detached, unknown element nodes
} else {
fragmentDiv.innerHTML = elem.outerHTML;
fragmentDiv.removeChild(clone = fragmentDiv.firstChild);
}
if ((!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem)) {
// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
destElements = getAll(clone);
srcElements = getAll(elem);
// Fix all IE cloning issues
for (i = 0; (node = srcElements[i]) != null; ++i) {
// Ensure that the destination node is not null; Fixes #9587
if (destElements[i]) {
fixCloneNodeIssues(node, destElements[i]);
}
}
}
// Copy the events from the original to the clone
if (dataAndEvents) {
if (deepDataAndEvents) {
srcElements = srcElements || getAll(elem);
destElements = destElements || getAll(clone);
for (i = 0; (node = srcElements[i]) != null; i++) {
cloneCopyEvent(node, destElements[i]);
}
} else {
cloneCopyEvent(elem, clone);
}
}
// Preserve script evaluation history
destElements = getAll(clone, "script");
if (destElements.length > 0) {
setGlobalEval(destElements, !inPage && getAll(elem, "script"));
}
destElements = srcElements = node = null;
// Return the cloned set
return clone;
},
buildFragment: function (elems, context, scripts, selection) {
var j, elem, contains,
tmp, tag, tbody, wrap,
l = elems.length,
// Ensure a safe fragment
safe = createSafeFragment(context),
nodes = [],
i = 0;
for (; i < l; i++) {
elem = elems[ i ];
if (elem || elem === 0) {
// Add nodes directly
if (jQuery.type(elem) === "object") {
jQuery.merge(nodes, elem.nodeType ? [ elem ] : elem);
// Convert non-html into a text node
} else if (!rhtml.test(elem)) {
nodes.push(context.createTextNode(elem));
// Convert html into DOM nodes
} else {
tmp = tmp || safe.appendChild(context.createElement("div"));
// Deserialize a standard representation
tag = ( rtagName.exec(elem) || ["", ""] )[1].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
tmp.innerHTML = wrap[1] + elem.replace(rxhtmlTag, "<$1></$2>") + wrap[2];
// Descend through wrappers to the right content
j = wrap[0];
while (j--) {
tmp = tmp.lastChild;
}
// Manually add leading whitespace removed by IE
if (!jQuery.support.leadingWhitespace && rleadingWhitespace.test(elem)) {
nodes.push(context.createTextNode(rleadingWhitespace.exec(elem)[0]));
}
// Remove IE's autoinserted <tbody> from table fragments
if (!jQuery.support.tbody) {
// String was a <table>, *may* have spurious <tbody>
elem = tag === "table" && !rtbody.test(elem) ?
tmp.firstChild :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !rtbody.test(elem) ?
tmp :
0;
j = elem && elem.childNodes.length;
while (j--) {
if (jQuery.nodeName((tbody = elem.childNodes[j]), "tbody") && !tbody.childNodes.length) {
elem.removeChild(tbody);
}
}
}
jQuery.merge(nodes, tmp.childNodes);
// Fix #12392 for WebKit and IE > 9
tmp.textContent = "";
// Fix #12392 for oldIE
while (tmp.firstChild) {
tmp.removeChild(tmp.firstChild);
}
// Remember the top-level container for proper cleanup
tmp = safe.lastChild;
}
}
}
// Fix #11356: Clear elements from fragment
if (tmp) {
safe.removeChild(tmp);
}
// Reset defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
if (!jQuery.support.appendChecked) {
jQuery.grep(getAll(nodes, "input"), fixDefaultChecked);
}
i = 0;
while ((elem = nodes[ i++ ])) {
// #4087 - If origin and destination elements are the same, and this is
// that element, do not do anything
if (selection && jQuery.inArray(elem, selection) !== -1) {
continue;
}
contains = jQuery.contains(elem.ownerDocument, elem);
// Append to fragment
tmp = getAll(safe.appendChild(elem), "script");
// Preserve script evaluation history
if (contains) {
setGlobalEval(tmp);
}
// Capture executables
if (scripts) {
j = 0;
while ((elem = tmp[ j++ ])) {
if (rscriptType.test(elem.type || "")) {
scripts.push(elem);
}
}
}
}
tmp = null;
return safe;
},
cleanData: function (elems, /* internal */ acceptData) {
var elem, type, id, data,
i = 0,
internalKey = jQuery.expando,
cache = jQuery.cache,
deleteExpando = jQuery.support.deleteExpando,
special = jQuery.event.special;
for (; (elem = elems[i]) != null; i++) {
if (acceptData || jQuery.acceptData(elem)) {
id = elem[ internalKey ];
data = id && cache[ id ];
if (data) {
if (data.events) {
for (type in data.events) {
if (special[ type ]) {
jQuery.event.remove(elem, type);
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent(elem, type, data.handle);
}
}
}
// Remove cache only if it was not already removed by jQuery.event.remove
if (cache[ id ]) {
delete cache[ id ];
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if (deleteExpando) {
delete elem[ internalKey ];
} else if (typeof elem.removeAttribute !== core_strundefined) {
elem.removeAttribute(internalKey);
} else {
elem[ internalKey ] = null;
}
core_deletedIds.push(id);
}
}
}
}
}
});
var iframe, getStyles, curCSS,
ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity\s*=\s*([^)]*)/,
rposition = /^(top|right|bottom|left)$/,
// swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rmargin = /^margin/,
rnumsplit = new RegExp("^(" + core_pnum + ")(.*)$", "i"),
rnumnonpx = new RegExp("^(" + core_pnum + ")(?!px)[a-z%]+$", "i"),
rrelNum = new RegExp("^([+-])=(" + core_pnum + ")", "i"),
elemdisplay = { BODY: "block" },
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: 0,
fontWeight: 400
},
cssExpand = [ "Top", "Right", "Bottom", "Left" ],
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];
// return a css property mapped to a potentially vendor prefixed property
function vendorPropName(style, name) {
// shortcut for names that are not vendor prefixed
if (name in style) {
return name;
}
// check for vendor prefixed names
var capName = name.charAt(0).toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while (i--) {
name = cssPrefixes[ i ] + capName;
if (name in style) {
return name;
}
}
return origName;
}
function isHidden(elem, el) {
// isHidden might be called from jQuery#filter function;
// in that case, element will be second argument
elem = el || elem;
return jQuery.css(elem, "display") === "none" || !jQuery.contains(elem.ownerDocument, elem);
}
function showHide(elements, show) {
var display, elem, hidden,
values = [],
index = 0,
length = elements.length;
for (; index < length; index++) {
elem = elements[ index ];
if (!elem.style) {
continue;
}
values[ index ] = jQuery._data(elem, "olddisplay");
display = elem.style.display;
if (show) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if (!values[ index ] && display === "none") {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if (elem.style.display === "" && isHidden(elem)) {
values[ index ] = jQuery._data(elem, "olddisplay", css_defaultDisplay(elem.nodeName));
}
} else {
if (!values[ index ]) {
hidden = isHidden(elem);
if (display && display !== "none" || !hidden) {
jQuery._data(elem, "olddisplay", hidden ? display : jQuery.css(elem, "display"));
}
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for (index = 0; index < length; index++) {
elem = elements[ index ];
if (!elem.style) {
continue;
}
if (!show || elem.style.display === "none" || elem.style.display === "") {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
jQuery.fn.extend({
css: function (name, value) {
return jQuery.access(this, function (elem, name, value) {
var len, styles,
map = {},
i = 0;
if (jQuery.isArray(name)) {
styles = getStyles(elem);
len = name.length;
for (; i < len; i++) {
map[ name[ i ] ] = jQuery.css(elem, name[ i ], false, styles);
}
return map;
}
return value !== undefined ?
jQuery.style(elem, name, value) :
jQuery.css(elem, name);
}, name, value, arguments.length > 1);
},
show: function () {
return showHide(this, true);
},
hide: function () {
return showHide(this);
},
toggle: function (state) {
var bool = typeof state === "boolean";
return this.each(function () {
if (bool ? state : isHidden(this)) {
jQuery(this).show();
} else {
jQuery(this).hide();
}
});
}
});
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function (elem, computed) {
if (computed) {
// We should always get a number back from opacity
var ret = curCSS(elem, "opacity");
return ret === "" ? "1" : ret;
}
}
}
},
// Exclude the following css properties to add px
cssNumber: {
"columnCount": true,
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function (elem, name, value, extra) {
// Don't set styles on text and comment nodes
if (!elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase(name),
style = elem.style;
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName(style, origName) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if (value !== undefined) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if (type === "string" && (ret = rrelNum.exec(value))) {
value = ( ret[1] + 1 ) * ret[2] + parseFloat(jQuery.css(elem, name));
// Fixes bug #9237
type = "number";
}
// Make sure that NaN and null values aren't set. See: #7116
if (value == null || type === "number" && isNaN(value)) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if (type === "number" && !jQuery.cssNumber[ origName ]) {
value += "px";
}
// Fixes #8908, it can be done more correctly by specifing setters in cssHooks,
// but it would mean to define eight (for every problematic property) identical functions
if (!jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0) {
style[ name ] = "inherit";
}
// If a hook was provided, use that value, otherwise just set the specified value
if (!hooks || !("set" in hooks) || (value = hooks.set(elem, value, extra)) !== undefined) {
// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
// Fixes bug #5509
try {
style[ name ] = value;
} catch (e) {
}
}
} else {
// If a hook was provided get the non-computed value from there
if (hooks && "get" in hooks && (ret = hooks.get(elem, false, extra)) !== undefined) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function (elem, name, extra, styles) {
var num, val, hooks,
origName = jQuery.camelCase(name);
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName(elem.style, origName) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if (hooks && "get" in hooks) {
val = hooks.get(elem, true, extra);
}
// Otherwise, if a way to get the computed value exists, use that
if (val === undefined) {
val = curCSS(elem, name, styles);
}
//convert "normal" to computed value
if (val === "normal" && name in cssNormalTransform) {
val = cssNormalTransform[ name ];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if (extra === "" || extra) {
num = parseFloat(val);
return extra === true || jQuery.isNumeric(num) ? num || 0 : val;
}
return val;
},
// A method for quickly swapping in/out CSS properties to get correct calculations
swap: function (elem, options, callback, args) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for (name in options) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.apply(elem, args || []);
// Revert the old values
for (name in options) {
elem.style[ name ] = old[ name ];
}
return ret;
}
});
// NOTE: we've included the "window" in window.getComputedStyle
// because jsdom on node.js will break without it.
if (window.getComputedStyle) {
getStyles = function (elem) {
return window.getComputedStyle(elem, null);
};
curCSS = function (elem, name, _computed) {
var width, minWidth, maxWidth,
computed = _computed || getStyles(elem),
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
ret = computed ? computed.getPropertyValue(name) || computed[ name ] : undefined,
style = elem.style;
if (computed) {
if (ret === "" && !jQuery.contains(elem.ownerDocument, elem)) {
ret = jQuery.style(elem, name);
}
// A tribute to the "awesome hack by Dean Edwards"
// Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right
// Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if (rnumnonpx.test(ret) && rmargin.test(name)) {
// Remember the original values
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
// Put in the new values to get a computed value out
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
// Revert the changed values
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
return ret;
};
} else if (document.documentElement.currentStyle) {
getStyles = function (elem) {
return elem.currentStyle;
};
curCSS = function (elem, name, _computed) {
var left, rs, rsLeft,
computed = _computed || getStyles(elem),
ret = computed ? computed[ name ] : undefined,
style = elem.style;
// Avoid setting ret to empty string here
// so we don't default to auto
if (ret == null && style && style[ name ]) {
ret = style[ name ];
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
// but not position css attributes, as those are proportional to the parent element instead
// and we can't measure the parent instead because it might trigger a "stacking dolls" problem
if (rnumnonpx.test(ret) && !rposition.test(name)) {
// Remember the original values
left = style.left;
rs = elem.runtimeStyle;
rsLeft = rs && rs.left;
// Put in the new values to get a computed value out
if (rsLeft) {
rs.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if (rsLeft) {
rs.left = rsLeft;
}
}
return ret === "" ? "auto" : ret;
};
}
function setPositiveNumber(elem, value, subtract) {
var matches = rnumsplit.exec(value);
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max(0, matches[ 1 ] - ( subtract || 0 )) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight(elem, name, extra, isBorderBox, styles) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for (; i < 4; i += 2) {
// both box models exclude margin, so add it if we want it
if (extra === "margin") {
val += jQuery.css(elem, extra + cssExpand[ i ], true, styles);
}
if (isBorderBox) {
// border-box includes padding, so remove it if we want content
if (extra === "content") {
val -= jQuery.css(elem, "padding" + cssExpand[ i ], true, styles);
}
// at this point, extra isn't border nor margin, so remove border
if (extra !== "margin") {
val -= jQuery.css(elem, "border" + cssExpand[ i ] + "Width", true, styles);
}
} else {
// at this point, extra isn't content, so add padding
val += jQuery.css(elem, "padding" + cssExpand[ i ], true, styles);
// at this point, extra isn't content nor padding, so add border
if (extra !== "padding") {
val += jQuery.css(elem, "border" + cssExpand[ i ] + "Width", true, styles);
}
}
}
return val;
}
function getWidthOrHeight(elem, name, extra) {
// Start with offset property, which is equivalent to the border-box value
var valueIsBorderBox = true,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
styles = getStyles(elem),
isBorderBox = jQuery.support.boxSizing && jQuery.css(elem, "boxSizing", false, styles) === "border-box";
// some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if (val <= 0 || val == null) {
// Fall back to computed then uncomputed css if necessary
val = curCSS(elem, name, styles);
if (val < 0 || val == null) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if (rnumnonpx.test(val)) {
return val;
}
// we need the check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] );
// Normalize "", auto, and prepare for extra
val = parseFloat(val) || 0;
}
// use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox,
styles
)
) + "px";
}
// Try to determine the default display value of an element
function css_defaultDisplay(nodeName) {
var doc = document,
display = elemdisplay[ nodeName ];
if (!display) {
display = actualDisplay(nodeName, doc);
// If the simple way fails, read from inside an iframe
if (display === "none" || !display) {
// Use the already-created iframe if possible
iframe = ( iframe ||
jQuery("<iframe frameborder='0' width='0' height='0'/>")
.css("cssText", "display:block !important")
).appendTo(doc.documentElement);
// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document;
doc.write("<!doctype html><html><body>");
doc.close();
display = actualDisplay(nodeName, doc);
iframe.detach();
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return display;
}
// Called ONLY from within css_defaultDisplay
function actualDisplay(name, doc) {
var elem = jQuery(doc.createElement(name)).appendTo(doc.body),
display = jQuery.css(elem[0], "display");
elem.remove();
return display;
}
jQuery.each([ "height", "width" ], function (i, name) {
jQuery.cssHooks[ name ] = {
get: function (elem, computed, extra) {
if (computed) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
return elem.offsetWidth === 0 && rdisplayswap.test(jQuery.css(elem, "display")) ?
jQuery.swap(elem, cssShow, function () {
return getWidthOrHeight(elem, name, extra);
}) :
getWidthOrHeight(elem, name, extra);
}
},
set: function (elem, value, extra) {
var styles = extra && getStyles(elem);
return setPositiveNumber(elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
jQuery.support.boxSizing && jQuery.css(elem, "boxSizing", false, styles) === "border-box",
styles
) : 0
);
}
};
});
if (!jQuery.support.opacity) {
jQuery.cssHooks.opacity = {
get: function (elem, computed) {
// IE uses filters for opacity
return ropacity.test((computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "") ?
( 0.01 * parseFloat(RegExp.$1) ) + "" :
computed ? "1" : "";
},
set: function (elem, value) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNumeric(value) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
// if value === "", then remove inline opacity #12685
if (( value >= 1 || value === "" ) &&
jQuery.trim(filter.replace(ralpha, "")) === "" &&
style.removeAttribute) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute("filter");
// if there is no filter style applied in a css rule or unset inline opacity, we are done
if (value === "" || currentStyle && !currentStyle.filter) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test(filter) ?
filter.replace(ralpha, opacity) :
filter + " " + opacity;
}
};
}
// These hooks cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
jQuery(function () {
if (!jQuery.support.reliableMarginRight) {
jQuery.cssHooks.marginRight = {
get: function (elem, computed) {
if (computed) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap(elem, { "display": "inline-block" },
curCSS, [ elem, "marginRight" ]);
}
}
};
}
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we just check for it here
if (!jQuery.support.pixelPosition && jQuery.fn.position) {
jQuery.each([ "top", "left" ], function (i, prop) {
jQuery.cssHooks[ prop ] = {
get: function (elem, computed) {
if (computed) {
computed = curCSS(elem, prop);
// if curCSS returns percentage, fallback to offset
return rnumnonpx.test(computed) ?
jQuery(elem).position()[ prop ] + "px" :
computed;
}
}
};
});
}
});
if (jQuery.expr && jQuery.expr.filters) {
jQuery.expr.filters.hidden = function (elem) {
// Support: Opera <= 12.12
// Opera reports offsetWidths and offsetHeights less than zero on some elements
return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 ||
(!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css(elem, "display")) === "none");
};
jQuery.expr.filters.visible = function (elem) {
return !jQuery.expr.filters.hidden(elem);
};
}
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function (prefix, suffix) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function (value) {
var i = 0,
expanded = {},
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ];
for (; i < 4; i++) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if (!rmargin.test(prefix)) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
});
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
rsubmittable = /^(?:input|select|textarea|keygen)/i;
jQuery.fn.extend({
serialize: function () {
return jQuery.param(this.serializeArray());
},
serializeArray: function () {
return this.map(function () {
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop(this, "elements");
return elements ? jQuery.makeArray(elements) : this;
})
.filter(function () {
var type = this.type;
// Use .is(":disabled") so that fieldset[disabled] works
return this.name && !jQuery(this).is(":disabled") &&
rsubmittable.test(this.nodeName) && !rsubmitterTypes.test(type) &&
( this.checked || !manipulation_rcheckableType.test(type) );
})
.map(function (i, elem) {
var val = jQuery(this).val();
return val == null ?
null :
jQuery.isArray(val) ?
jQuery.map(val, function (val) {
return { name: elem.name, value: val.replace(rCRLF, "\r\n") };
}) :
{ name: elem.name, value: val.replace(rCRLF, "\r\n") };
}).get();
}
});
//Serialize an array of form elements or a set of
//key/values into a query string
jQuery.param = function (a, traditional) {
var prefix,
s = [],
add = function (key, value) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction(value) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if (traditional === undefined) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if (jQuery.isArray(a) || ( a.jquery && !jQuery.isPlainObject(a) )) {
// Serialize the form elements
jQuery.each(a, function () {
add(this.name, this.value);
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for (prefix in a) {
buildParams(prefix, a[ prefix ], traditional, add);
}
}
// Return the resulting serialization
return s.join("&").replace(r20, "+");
};
function buildParams(prefix, obj, traditional, add) {
var name;
if (jQuery.isArray(obj)) {
// Serialize array item.
jQuery.each(obj, function (i, v) {
if (traditional || rbracket.test(prefix)) {
// Treat each array item as a scalar.
add(prefix, v);
} else {
// Item is non-scalar (array or object), encode its numeric index.
buildParams(prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add);
}
});
} else if (!traditional && jQuery.type(obj) === "object") {
// Serialize object item.
for (name in obj) {
buildParams(prefix + "[" + name + "]", obj[ name ], traditional, add);
}
} else {
// Serialize scalar item.
add(prefix, obj);
}
}
jQuery.each(("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function (i, name) {
// Handle event binding
jQuery.fn[ name ] = function (data, fn) {
return arguments.length > 0 ?
this.on(name, null, data, fn) :
this.trigger(name);
};
});
jQuery.fn.hover = function (fnOver, fnOut) {
return this.mouseenter(fnOver).mouseleave(fnOut || fnOver);
};
var
// Document location
ajaxLocParts,
ajaxLocation,
ajax_nonce = jQuery.now(),
ajax_rquery = /\?/,
rhash = /#.*$/,
rts = /([?&])_=[^&]*/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,
// Keep a copy of the old load method
_load = jQuery.fn.load,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = "*/".concat("*");
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch (e) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement("a");
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec(ajaxLocation.toLowerCase()) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports(structure) {
// dataTypeExpression is optional and defaults to "*"
return function (dataTypeExpression, func) {
if (typeof dataTypeExpression !== "string") {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType,
i = 0,
dataTypes = dataTypeExpression.toLowerCase().match(core_rnotwhite) || [];
if (jQuery.isFunction(func)) {
// For each dataType in the dataTypeExpression
while ((dataType = dataTypes[i++])) {
// Prepend if requested
if (dataType[0] === "+") {
dataType = dataType.slice(1) || "*";
(structure[ dataType ] = structure[ dataType ] || []).unshift(func);
// Otherwise append
} else {
(structure[ dataType ] = structure[ dataType ] || []).push(func);
}
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports(structure, options, originalOptions, jqXHR) {
var inspected = {},
seekingTransport = ( structure === transports );
function inspect(dataType) {
var selected;
inspected[ dataType ] = true;
jQuery.each(structure[ dataType ] || [], function (_, prefilterOrFactory) {
var dataTypeOrTransport = prefilterOrFactory(options, originalOptions, jqXHR);
if (typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ]) {
options.dataTypes.unshift(dataTypeOrTransport);
inspect(dataTypeOrTransport);
return false;
} else if (seekingTransport) {
return !( selected = dataTypeOrTransport );
}
});
return selected;
}
return inspect(options.dataTypes[ 0 ]) || !inspected[ "*" ] && inspect("*");
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend(target, src) {
var deep, key,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for (key in src) {
if (src[ key ] !== undefined) {
( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ];
}
}
if (deep) {
jQuery.extend(true, target, deep);
}
return target;
}
jQuery.fn.load = function (url, params, callback) {
if (typeof url !== "string" && _load) {
return _load.apply(this, arguments);
}
var selector, response, type,
self = this,
off = url.indexOf(" ");
if (off >= 0) {
selector = url.slice(off, url.length);
url = url.slice(0, off);
}
// If it's a function
if (jQuery.isFunction(params)) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if (params && typeof params === "object") {
type = "POST";
}
// If we have elements to modify, make the request
if (self.length > 0) {
jQuery.ajax({
url: url,
// if "type" variable is undefined, then "GET" method will be used
type: type,
dataType: "html",
data: params
}).done(function (responseText) {
// Save response for use in complete callback
response = arguments;
self.html(selector ?
// If a selector was specified, locate the right elements in a dummy div
// Exclude scripts to avoid IE 'Permission Denied' errors
jQuery("<div>").append(jQuery.parseHTML(responseText)).find(selector) :
// Otherwise use the full result
responseText);
}).complete(callback && function (jqXHR, status) {
self.each(callback, response || [ jqXHR.responseText, status, jqXHR ]);
});
}
return this;
};
// Attach a bunch of functions for handling common AJAX events
jQuery.each([ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function (i, type) {
jQuery.fn[ type ] = function (fn) {
return this.on(type, fn);
};
});
jQuery.each([ "get", "post" ], function (i, method) {
jQuery[ method ] = function (url, data, callback, type) {
// shift arguments if data argument was omitted
if (jQuery.isFunction(data)) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: method,
dataType: type,
data: data,
success: callback
});
};
});
jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {},
ajaxSettings: {
url: ajaxLocation,
type: "GET",
isLocal: rlocalProtocol.test(ajaxLocParts[ 1 ]),
global: true,
processData: true,
async: true,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
"*": allTypes,
text: "text/plain",
html: "text/html",
xml: "application/xml, text/xml",
json: "application/json, text/javascript"
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText"
},
// Data converters
// Keys separate source (or catchall "*") and destination types with a single space
converters: {
// Convert anything to text
"* text": window.String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
url: true,
context: true
}
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function (target, settings) {
return settings ?
// Building a settings object
ajaxExtend(ajaxExtend(target, jQuery.ajaxSettings), settings) :
// Extending ajaxSettings
ajaxExtend(jQuery.ajaxSettings, target);
},
ajaxPrefilter: addToPrefiltersOrTransports(prefilters),
ajaxTransport: addToPrefiltersOrTransports(transports),
// Main method
ajax: function (url, options) {
// If url is an object, simulate pre-1.5 signature
if (typeof url === "object") {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // Cross-domain detection vars
parts,
// Loop variable
i,
// URL without anti-cache param
cacheURL,
// Response headers as string
responseHeadersString,
// timeout handle
timeoutTimer,
// To know if global events are to be dispatched
fireGlobals,
transport,
// Response headers
responseHeaders,
// Create the final options object
s = jQuery.ajaxSetup({}, options),
// Callbacks context
callbackContext = s.context || s,
// Context for global events is callbackContext if it is a DOM node or jQuery collection
globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ?
jQuery(callbackContext) :
jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks("once memory"),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// The jqXHR state
state = 0,
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Builds headers hashtable if needed
getResponseHeader: function (key) {
var match;
if (state === 2) {
if (!responseHeaders) {
responseHeaders = {};
while ((match = rheaders.exec(responseHeadersString))) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match == null ? null : match;
},
// Raw string
getAllResponseHeaders: function () {
return state === 2 ? responseHeadersString : null;
},
// Caches the header
setRequestHeader: function (name, value) {
var lname = name.toLowerCase();
if (!state) {
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Overrides response content-type header
overrideMimeType: function (type) {
if (!state) {
s.mimeType = type;
}
return this;
},
// Status-dependent callbacks
statusCode: function (map) {
var code;
if (map) {
if (state < 2) {
for (code in map) {
// Lazy-add the new callback in a way that preserves old ones
statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
}
} else {
// Execute the appropriate callbacks
jqXHR.always(map[ jqXHR.status ]);
}
}
return this;
},
// Cancel the request
abort: function (statusText) {
var finalText = statusText || strAbort;
if (transport) {
transport.abort(finalText);
}
done(0, finalText);
return this;
}
};
// Attach deferreds
deferred.promise(jqXHR).complete = completeDeferred.add;
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// Handle falsy url in the settings object (#10093: consistency with old signature)
// We also use the url parameter if available
s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace(rhash, "").replace(rprotocol, ajaxLocParts[ 1 ] + "//");
// Alias method option to type as per ticket #12004
s.type = options.method || options.type || s.method || s.type;
// Extract dataTypes list
s.dataTypes = jQuery.trim(s.dataType || "*").toLowerCase().match(core_rnotwhite) || [""];
// A cross-domain request is in order when we have a protocol:host:port mismatch
if (s.crossDomain == null) {
parts = rurl.exec(s.url.toLowerCase());
s.crossDomain = !!( parts &&
( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
);
}
// Convert data if not already a string
if (s.data && s.processData && typeof s.data !== "string") {
s.data = jQuery.param(s.data, s.traditional);
}
// Apply prefilters
inspectPrefiltersOrTransports(prefilters, s, options, jqXHR);
// If request was aborted inside a prefilter, stop there
if (state === 2) {
return jqXHR;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Watch for a new set of requests
if (fireGlobals && jQuery.active++ === 0) {
jQuery.event.trigger("ajaxStart");
}
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test(s.type);
// Save the URL in case we're toying with the If-Modified-Since
// and/or If-None-Match header later on
cacheURL = s.url;
// More options handling for requests with no content
if (!s.hasContent) {
// If data is available, append data to url
if (s.data) {
cacheURL = ( s.url += ( ajax_rquery.test(cacheURL) ? "&" : "?" ) + s.data );
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Add anti-cache in url if needed
if (s.cache === false) {
s.url = rts.test(cacheURL) ?
// If there is already a '_' parameter, set its value
cacheURL.replace(rts, "$1_=" + ajax_nonce++) :
// Otherwise add one to the end
cacheURL + ( ajax_rquery.test(cacheURL) ? "&" : "?" ) + "_=" + ajax_nonce++;
}
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if (s.ifModified) {
if (jQuery.lastModified[ cacheURL ]) {
jqXHR.setRequestHeader("If-Modified-Since", jQuery.lastModified[ cacheURL ]);
}
if (jQuery.etag[ cacheURL ]) {
jqXHR.setRequestHeader("If-None-Match", jQuery.etag[ cacheURL ]);
}
}
// Set the correct header, if data is being sent
if (s.data && s.hasContent && s.contentType !== false || options.contentType) {
jqXHR.setRequestHeader("Content-Type", s.contentType);
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for (i in s.headers) {
jqXHR.setRequestHeader(i, s.headers[ i ]);
}
// Allow custom headers/mimetypes and early abort
if (s.beforeSend && ( s.beforeSend.call(callbackContext, jqXHR, s) === false || state === 2 )) {
// Abort if not done already and return
return jqXHR.abort();
}
// aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
for (i in { success: 1, error: 1, complete: 1 }) {
jqXHR[ i ](s[ i ]);
}
// Get transport
transport = inspectPrefiltersOrTransports(transports, s, options, jqXHR);
// If no transport, we auto-abort
if (!transport) {
done(-1, "No Transport");
} else {
jqXHR.readyState = 1;
// Send global event
if (fireGlobals) {
globalEventContext.trigger("ajaxSend", [ jqXHR, s ]);
}
// Timeout
if (s.async && s.timeout > 0) {
timeoutTimer = setTimeout(function () {
jqXHR.abort("timeout");
}, s.timeout);
}
try {
state = 1;
transport.send(requestHeaders, done);
} catch (e) {
// Propagate exception as error if not done
if (state < 2) {
done(-1, e);
// Simply rethrow otherwise
} else {
throw e;
}
}
}
// Callback for when everything is done
function done(status, nativeStatusText, responses, headers) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Called once
if (state === 2) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if (timeoutTimer) {
clearTimeout(timeoutTimer);
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Get response data
if (responses) {
response = ajaxHandleResponses(s, jqXHR, responses);
}
// If successful, handle type chaining
if (status >= 200 && status < 300 || status === 304) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if (s.ifModified) {
modified = jqXHR.getResponseHeader("Last-Modified");
if (modified) {
jQuery.lastModified[ cacheURL ] = modified;
}
modified = jqXHR.getResponseHeader("etag");
if (modified) {
jQuery.etag[ cacheURL ] = modified;
}
}
// if no content
if (status === 204) {
isSuccess = true;
statusText = "nocontent";
// if not modified
} else if (status === 304) {
isSuccess = true;
statusText = "notmodified";
// If we have data, let's convert it
} else {
isSuccess = ajaxConvert(s, response);
statusText = isSuccess.state;
success = isSuccess.data;
error = isSuccess.error;
isSuccess = !error;
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if (status || !statusText) {
statusText = "error";
if (status < 0) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = ( nativeStatusText || statusText ) + "";
// Success/Error
if (isSuccess) {
deferred.resolveWith(callbackContext, [ success, statusText, jqXHR ]);
} else {
deferred.rejectWith(callbackContext, [ jqXHR, statusText, error ]);
}
// Status-dependent callbacks
jqXHR.statusCode(statusCode);
statusCode = undefined;
if (fireGlobals) {
globalEventContext.trigger(isSuccess ? "ajaxSuccess" : "ajaxError",
[ jqXHR, s, isSuccess ? success : error ]);
}
// Complete
completeDeferred.fireWith(callbackContext, [ jqXHR, statusText ]);
if (fireGlobals) {
globalEventContext.trigger("ajaxComplete", [ jqXHR, s ]);
// Handle the global AJAX counter
if (!( --jQuery.active )) {
jQuery.event.trigger("ajaxStop");
}
}
}
return jqXHR;
},
getScript: function (url, callback) {
return jQuery.get(url, undefined, callback, "script");
},
getJSON: function (url, data, callback) {
return jQuery.get(url, data, callback, "json");
}
});
/* Handles responses to an ajax request:
* - sets all responseXXX fields accordingly
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses(s, jqXHR, responses) {
var firstDataType, ct, finalDataType, type,
contents = s.contents,
dataTypes = s.dataTypes,
responseFields = s.responseFields;
// Fill responseXXX fields
for (type in responseFields) {
if (type in responses) {
jqXHR[ responseFields[type] ] = responses[ type ];
}
}
// Remove auto dataType and get content-type in the process
while (dataTypes[ 0 ] === "*") {
dataTypes.shift();
if (ct === undefined) {
ct = s.mimeType || jqXHR.getResponseHeader("Content-Type");
}
}
// Check if we're dealing with a known content-type
if (ct) {
for (type in contents) {
if (contents[ type ] && contents[ type ].test(ct)) {
dataTypes.unshift(type);
break;
}
}
}
// Check to see if we have a response for the expected dataType
if (dataTypes[ 0 ] in responses) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for (type in responses) {
if (!dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ]) {
finalDataType = type;
break;
}
if (!firstDataType) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if (finalDataType) {
if (finalDataType !== dataTypes[ 0 ]) {
dataTypes.unshift(finalDataType);
}
return responses[ finalDataType ];
}
}
// Chain conversions given the request and the original response
function ajaxConvert(s, response) {
var conv2, current, conv, tmp,
converters = {},
i = 0,
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice(),
prev = dataTypes[ 0 ];
// Apply the dataFilter if provided
if (s.dataFilter) {
response = s.dataFilter(response, s.dataType);
}
// Create converters map with lowercased keys
if (dataTypes[ 1 ]) {
for (conv in s.converters) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
// Convert to each sequential dataType, tolerating list modification
for (; (current = dataTypes[++i]);) {
// There's only work to do if current dataType is non-auto
if (current !== "*") {
// Convert response if prev dataType is non-auto and differs from current
if (prev !== "*" && prev !== current) {
// Seek a direct converter
conv = converters[ prev + " " + current ] || converters[ "* " + current ];
// If none found, seek a pair
if (!conv) {
for (conv2 in converters) {
// If conv2 outputs current
tmp = conv2.split(" ");
if (tmp[ 1 ] === current) {
// If prev can be converted to accepted input
conv = converters[ prev + " " + tmp[ 0 ] ] ||
converters[ "* " + tmp[ 0 ] ];
if (conv) {
// Condense equivalence converters
if (conv === true) {
conv = converters[ conv2 ];
// Otherwise, insert the intermediate dataType
} else if (converters[ conv2 ] !== true) {
current = tmp[ 0 ];
dataTypes.splice(i--, 0, current);
}
break;
}
}
}
}
// Apply converter (if not an equivalence)
if (conv !== true) {
// Unless errors are allowed to bubble, catch and return them
if (conv && s["throws"]) {
response = conv(response);
} else {
try {
response = conv(response);
} catch (e) {
return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };
}
}
}
}
// Update prev for next iteration
prev = current;
}
}
return { state: "success", data: response };
}
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /(?:java|ecma)script/
},
converters: {
"text script": function (text) {
jQuery.globalEval(text);
return text;
}
}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter("script", function (s) {
if (s.cache === undefined) {
s.cache = false;
}
if (s.crossDomain) {
s.type = "GET";
s.global = false;
}
});
// Bind script tag hack transport
jQuery.ajaxTransport("script", function (s) {
// This transport only deals with cross domain requests
if (s.crossDomain) {
var script,
head = document.head || jQuery("head")[0] || document.documentElement;
return {
send: function (_, callback) {
script = document.createElement("script");
script.async = true;
if (s.scriptCharset) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function (_, isAbort) {
if (isAbort || !script.readyState || /loaded|complete/.test(script.readyState)) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if (script.parentNode) {
script.parentNode.removeChild(script);
}
// Dereference the script
script = null;
// Callback if not abort
if (!isAbort) {
callback(200, "success");
}
}
};
// Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending
// Use native DOM manipulation to avoid our domManip AJAX trickery
head.insertBefore(script, head.firstChild);
},
abort: function () {
if (script) {
script.onload(undefined, true);
}
}
};
}
});
var oldCallbacks = [],
rjsonp = /(=)\?(?=&|$)|\?\?/;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function () {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) );
this[ callback ] = true;
return callback;
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter("json jsonp", function (s, originalSettings, jqXHR) {
var callbackName, overwritten, responseContainer,
jsonProp = s.jsonp !== false && ( rjsonp.test(s.url) ?
"url" :
typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test(s.data) && "data"
);
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if (jsonProp || s.dataTypes[ 0 ] === "jsonp") {
// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = jQuery.isFunction(s.jsonpCallback) ?
s.jsonpCallback() :
s.jsonpCallback;
// Insert callback into url or form data
if (jsonProp) {
s[ jsonProp ] = s[ jsonProp ].replace(rjsonp, "$1" + callbackName);
} else if (s.jsonp !== false) {
s.url += ( ajax_rquery.test(s.url) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
}
// Use data converter to retrieve json after script execution
s.converters["script json"] = function () {
if (!responseContainer) {
jQuery.error(callbackName + " was not called");
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Install callback
overwritten = window[ callbackName ];
window[ callbackName ] = function () {
responseContainer = arguments;
};
// Clean-up function (fires after converters)
jqXHR.always(function () {
// Restore preexisting value
window[ callbackName ] = overwritten;
// Save back as free
if (s[ callbackName ]) {
// make sure that re-using the options doesn't screw things around
s.jsonpCallback = originalSettings.jsonpCallback;
// save the callback name for future use
oldCallbacks.push(callbackName);
}
// Call if it was a function and we have a response
if (responseContainer && jQuery.isFunction(overwritten)) {
overwritten(responseContainer[ 0 ]);
}
responseContainer = overwritten = undefined;
});
// Delegate to script
return "script";
}
});
var xhrCallbacks, xhrSupported,
xhrId = 0,
// #5280: Internet Explorer will keep connections alive if we don't abort on unload
xhrOnUnloadAbort = window.ActiveXObject && function () {
// Abort all pending requests
var key;
for (key in xhrCallbacks) {
xhrCallbacks[ key ](undefined, true);
}
};
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch (e) {
}
}
function createActiveXHR() {
try {
return new window.ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
}
}
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject ?
/* Microsoft failed to properly
* implement the XMLHttpRequest in IE7 (can't request local files),
* so we use the ActiveXObject when it is available
* Additionally XMLHttpRequest can be disabled in IE7/IE8 so
* we need a fallback.
*/
function () {
return !this.isLocal && createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
// Determine support properties
xhrSupported = jQuery.ajaxSettings.xhr();
jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
xhrSupported = jQuery.support.ajax = !!xhrSupported;
// Create transport if the browser can provide an xhr
if (xhrSupported) {
jQuery.ajaxTransport(function (s) {
// Cross domain only allowed if supported through XMLHttpRequest
if (!s.crossDomain || jQuery.support.cors) {
var callback;
return {
send: function (headers, complete) {
// Get a new xhr
var handle, i,
xhr = s.xhr();
// Open the socket
// Passing null username, generates a login popup on Opera (#2865)
if (s.username) {
xhr.open(s.type, s.url, s.async, s.username, s.password);
} else {
xhr.open(s.type, s.url, s.async);
}
// Apply custom fields if provided
if (s.xhrFields) {
for (i in s.xhrFields) {
xhr[ i ] = s.xhrFields[ i ];
}
}
// Override mime type if needed
if (s.mimeType && xhr.overrideMimeType) {
xhr.overrideMimeType(s.mimeType);
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if (!s.crossDomain && !headers["X-Requested-With"]) {
headers["X-Requested-With"] = "XMLHttpRequest";
}
// Need an extra try/catch for cross domain requests in Firefox 3
try {
for (i in headers) {
xhr.setRequestHeader(i, headers[ i ]);
}
} catch (err) {
}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send(( s.hasContent && s.data ) || null);
// Listener
callback = function (_, isAbort) {
var status, responseHeaders, statusText, responses;
// Firefox throws exceptions when accessing properties
// of an xhr when a network error occurred
// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
try {
// Was never called and is aborted or complete
if (callback && ( isAbort || xhr.readyState === 4 )) {
// Only called once
callback = undefined;
// Do not keep as active anymore
if (handle) {
xhr.onreadystatechange = jQuery.noop;
if (xhrOnUnloadAbort) {
delete xhrCallbacks[ handle ];
}
}
// If it's an abort
if (isAbort) {
// Abort it manually if needed
if (xhr.readyState !== 4) {
xhr.abort();
}
} else {
responses = {};
status = xhr.status;
responseHeaders = xhr.getAllResponseHeaders();
// When requesting binary data, IE6-9 will throw an exception
// on any attempt to access responseText (#11426)
if (typeof xhr.responseText === "string") {
responses.text = xhr.responseText;
}
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch (e) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if (!status && s.isLocal && !s.crossDomain) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if (status === 1223) {
status = 204;
}
}
}
} catch (firefoxAccessException) {
if (!isAbort) {
complete(-1, firefoxAccessException);
}
}
// Call complete if needed
if (responses) {
complete(status, statusText, responses, responseHeaders);
}
};
if (!s.async) {
// if we're in sync mode we fire the callback
callback();
} else if (xhr.readyState === 4) {
// (IE6 & IE7) if it's in cache and has been
// retrieved directly we need to fire the callback
setTimeout(callback);
} else {
handle = ++xhrId;
if (xhrOnUnloadAbort) {
// Create the active xhrs callbacks list if needed
// and attach the unload handler
if (!xhrCallbacks) {
xhrCallbacks = {};
jQuery(window).unload(xhrOnUnloadAbort);
}
// Add to list of active xhrs callbacks
xhrCallbacks[ handle ] = callback;
}
xhr.onreadystatechange = callback;
}
},
abort: function () {
if (callback) {
callback(undefined, true);
}
}
};
}
});
}
var fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = new RegExp("^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i"),
rrun = /queueHooks$/,
animationPrefilters = [ defaultPrefilter ],
tweeners = {
"*": [function (prop, value) {
var end, unit,
tween = this.createTween(prop, value),
parts = rfxnum.exec(value),
target = tween.cur(),
start = +target || 0,
scale = 1,
maxIterations = 20;
if (parts) {
end = +parts[2];
unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" );
// We need to compute starting value
if (unit !== "px" && start) {
// Iteratively approximate from a nonzero starting point
// Prefer the current property, because this process will be trivial if it uses the same units
// Fallback to end or a simple constant
start = jQuery.css(tween.elem, prop, true) || end || 1;
do {
// If previous iteration zeroed out, double until we get *something*
// Use a string for doubling factor so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
start = start / scale;
jQuery.style(tween.elem, prop, start + unit);
// Update scale, tolerating zero or NaN from tween.cur()
// And breaking the loop if scale is unchanged or perfect, or if we've just had enough
} while (scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations);
}
tween.unit = unit;
tween.start = start;
// If a +=/-= token was provided, we're doing a relative animation
tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end;
}
return tween;
}]
};
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout(function () {
fxNow = undefined;
});
return ( fxNow = jQuery.now() );
}
function createTweens(animation, props) {
jQuery.each(props, function (prop, value) {
var collection = ( tweeners[ prop ] || [] ).concat(tweeners[ "*" ]),
index = 0,
length = collection.length;
for (; index < length; index++) {
if (collection[ index ].call(animation, prop, value)) {
// we're done with this property
return;
}
}
});
}
function Animation(elem, properties, options) {
var result,
stopped,
index = 0,
length = animationPrefilters.length,
deferred = jQuery.Deferred().always(function () {
// don't match elem in the :animated selector
delete tick.elem;
}),
tick = function () {
if (stopped) {
return false;
}
var currentTime = fxNow || createFxNow(),
remaining = Math.max(0, animation.startTime + animation.duration - currentTime),
// archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497)
temp = remaining / animation.duration || 0,
percent = 1 - temp,
index = 0,
length = animation.tweens.length;
for (; index < length; index++) {
animation.tweens[ index ].run(percent);
}
deferred.notifyWith(elem, [ animation, percent, remaining ]);
if (percent < 1 && length) {
return remaining;
} else {
deferred.resolveWith(elem, [ animation ]);
return false;
}
},
animation = deferred.promise({
elem: elem,
props: jQuery.extend({}, properties),
opts: jQuery.extend(true, { specialEasing: {} }, options),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function (prop, end) {
var tween = jQuery.Tween(elem, animation.opts, prop, end,
animation.opts.specialEasing[ prop ] || animation.opts.easing);
animation.tweens.push(tween);
return tween;
},
stop: function (gotoEnd) {
var index = 0,
// if we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
if (stopped) {
return this;
}
stopped = true;
for (; index < length; index++) {
animation.tweens[ index ].run(1);
}
// resolve when we played the last frame
// otherwise, reject
if (gotoEnd) {
deferred.resolveWith(elem, [ animation, gotoEnd ]);
} else {
deferred.rejectWith(elem, [ animation, gotoEnd ]);
}
return this;
}
}),
props = animation.props;
propFilter(props, animation.opts.specialEasing);
for (; index < length; index++) {
result = animationPrefilters[ index ].call(animation, elem, props, animation.opts);
if (result) {
return result;
}
}
createTweens(animation, props);
if (jQuery.isFunction(animation.opts.start)) {
animation.opts.start.call(elem, animation);
}
jQuery.fx.timer(
jQuery.extend(tick, {
elem: elem,
anim: animation,
queue: animation.opts.queue
})
);
// attach callbacks from options
return animation.progress(animation.opts.progress)
.done(animation.opts.done, animation.opts.complete)
.fail(animation.opts.fail)
.always(animation.opts.always);
}
function propFilter(props, specialEasing) {
var value, name, index, easing, hooks;
// camelCase, specialEasing and expand cssHook pass
for (index in props) {
name = jQuery.camelCase(index);
easing = specialEasing[ name ];
value = props[ index ];
if (jQuery.isArray(value)) {
easing = value[ 1 ];
value = props[ index ] = value[ 0 ];
}
if (index !== name) {
props[ name ] = value;
delete props[ index ];
}
hooks = jQuery.cssHooks[ name ];
if (hooks && "expand" in hooks) {
value = hooks.expand(value);
delete props[ name ];
// not quite $.extend, this wont overwrite keys already present.
// also - reusing 'index' from above because we have the correct "name"
for (index in value) {
if (!( index in props )) {
props[ index ] = value[ index ];
specialEasing[ index ] = easing;
}
}
} else {
specialEasing[ name ] = easing;
}
}
}
jQuery.Animation = jQuery.extend(Animation, {
tweener: function (props, callback) {
if (jQuery.isFunction(props)) {
callback = props;
props = [ "*" ];
} else {
props = props.split(" ");
}
var prop,
index = 0,
length = props.length;
for (; index < length; index++) {
prop = props[ index ];
tweeners[ prop ] = tweeners[ prop ] || [];
tweeners[ prop ].unshift(callback);
}
},
prefilter: function (callback, prepend) {
if (prepend) {
animationPrefilters.unshift(callback);
} else {
animationPrefilters.push(callback);
}
}
});
function defaultPrefilter(elem, props, opts) {
/*jshint validthis:true */
var prop, index, length,
value, dataShow, toggle,
tween, hooks, oldfire,
anim = this,
style = elem.style,
orig = {},
handled = [],
hidden = elem.nodeType && isHidden(elem);
// handle queue: false promises
if (!opts.queue) {
hooks = jQuery._queueHooks(elem, "fx");
if (hooks.unqueued == null) {
hooks.unqueued = 0;
oldfire = hooks.empty.fire;
hooks.empty.fire = function () {
if (!hooks.unqueued) {
oldfire();
}
};
}
hooks.unqueued++;
anim.always(function () {
// doing this makes sure that the complete handler will be called
// before this completes
anim.always(function () {
hooks.unqueued--;
if (!jQuery.queue(elem, "fx").length) {
hooks.empty.fire();
}
});
});
}
// height/width overflow pass
if (elem.nodeType === 1 && ( "height" in props || "width" in props )) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
if (jQuery.css(elem, "display") === "inline" &&
jQuery.css(elem, "float") === "none") {
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if (!jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay(elem.nodeName) === "inline") {
style.display = "inline-block";
} else {
style.zoom = 1;
}
}
}
if (opts.overflow) {
style.overflow = "hidden";
if (!jQuery.support.shrinkWrapBlocks) {
anim.always(function () {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
});
}
}
// show/hide pass
for (index in props) {
value = props[ index ];
if (rfxtypes.exec(value)) {
delete props[ index ];
toggle = toggle || value === "toggle";
if (value === ( hidden ? "hide" : "show" )) {
continue;
}
handled.push(index);
}
}
length = handled.length;
if (length) {
dataShow = jQuery._data(elem, "fxshow") || jQuery._data(elem, "fxshow", {});
if ("hidden" in dataShow) {
hidden = dataShow.hidden;
}
// store state if its toggle - enables .stop().toggle() to "reverse"
if (toggle) {
dataShow.hidden = !hidden;
}
if (hidden) {
jQuery(elem).show();
} else {
anim.done(function () {
jQuery(elem).hide();
});
}
anim.done(function () {
var prop;
jQuery._removeData(elem, "fxshow");
for (prop in orig) {
jQuery.style(elem, prop, orig[ prop ]);
}
});
for (index = 0; index < length; index++) {
prop = handled[ index ];
tween = anim.createTween(prop, hidden ? dataShow[ prop ] : 0);
orig[ prop ] = dataShow[ prop ] || jQuery.style(elem, prop);
if (!( prop in dataShow )) {
dataShow[ prop ] = tween.start;
if (hidden) {
tween.end = tween.start;
tween.start = prop === "width" || prop === "height" ? 1 : 0;
}
}
}
}
}
function Tween(elem, options, prop, end, easing) {
return new Tween.prototype.init(elem, options, prop, end, easing);
}
jQuery.Tween = Tween;
Tween.prototype = {
constructor: Tween,
init: function (elem, options, prop, end, easing, unit) {
this.elem = elem;
this.prop = prop;
this.easing = easing || "swing";
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
},
cur: function () {
var hooks = Tween.propHooks[ this.prop ];
return hooks && hooks.get ?
hooks.get(this) :
Tween.propHooks._default.get(this);
},
run: function (percent) {
var eased,
hooks = Tween.propHooks[ this.prop ];
if (this.options.duration) {
this.pos = eased = jQuery.easing[ this.easing ](
percent, this.options.duration * percent, 0, 1, this.options.duration
);
} else {
this.pos = eased = percent;
}
this.now = ( this.end - this.start ) * eased + this.start;
if (this.options.step) {
this.options.step.call(this.elem, this.now, this);
}
if (hooks && hooks.set) {
hooks.set(this);
} else {
Tween.propHooks._default.set(this);
}
return this;
}
};
Tween.prototype.init.prototype = Tween.prototype;
Tween.propHooks = {
_default: {
get: function (tween) {
var result;
if (tween.elem[ tween.prop ] != null &&
(!tween.elem.style || tween.elem.style[ tween.prop ] == null)) {
return tween.elem[ tween.prop ];
}
// passing an empty string as a 3rd parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails
// so, simple values such as "10px" are parsed to Float.
// complex values such as "rotate(1rad)" are returned as is.
result = jQuery.css(tween.elem, tween.prop, "");
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function (tween) {
// use step hook for back compat - use cssHook if its there - use .style if its
// available and use plain properties where available
if (jQuery.fx.step[ tween.prop ]) {
jQuery.fx.step[ tween.prop ](tween);
} else if (tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] )) {
jQuery.style(tween.elem, tween.prop, tween.now + tween.unit);
} else {
tween.elem[ tween.prop ] = tween.now;
}
}
}
};
// Remove in 2.0 - this supports IE8's panic based approach
// to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function (tween) {
if (tween.elem.nodeType && tween.elem.parentNode) {
tween.elem[ tween.prop ] = tween.now;
}
}
};
jQuery.each([ "toggle", "show", "hide" ], function (i, name) {
var cssFn = jQuery.fn[ name ];
jQuery.fn[ name ] = function (speed, easing, callback) {
return speed == null || typeof speed === "boolean" ?
cssFn.apply(this, arguments) :
this.animate(genFx(name, true), speed, easing, callback);
};
});
jQuery.fn.extend({
fadeTo: function (speed, to, easing, callback) {
// show any hidden elements after setting opacity to 0
return this.filter(isHidden).css("opacity", 0).show()
// animate to the value specified
.end().animate({ opacity: to }, speed, easing, callback);
},
animate: function (prop, speed, easing, callback) {
var empty = jQuery.isEmptyObject(prop),
optall = jQuery.speed(speed, easing, callback),
doAnimation = function () {
// Operate on a copy of prop so per-property easing won't be lost
var anim = Animation(this, jQuery.extend({}, prop), optall);
doAnimation.finish = function () {
anim.stop(true);
};
// Empty animations, or finishing resolves immediately
if (empty || jQuery._data(this, "finish")) {
anim.stop(true);
}
};
doAnimation.finish = doAnimation;
return empty || optall.queue === false ?
this.each(doAnimation) :
this.queue(optall.queue, doAnimation);
},
stop: function (type, clearQueue, gotoEnd) {
var stopQueue = function (hooks) {
var stop = hooks.stop;
delete hooks.stop;
stop(gotoEnd);
};
if (typeof type !== "string") {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if (clearQueue && type !== false) {
this.queue(type || "fx", []);
}
return this.each(function () {
var dequeue = true,
index = type != null && type + "queueHooks",
timers = jQuery.timers,
data = jQuery._data(this);
if (index) {
if (data[ index ] && data[ index ].stop) {
stopQueue(data[ index ]);
}
} else {
for (index in data) {
if (data[ index ] && data[ index ].stop && rrun.test(index)) {
stopQueue(data[ index ]);
}
}
}
for (index = timers.length; index--;) {
if (timers[ index ].elem === this && (type == null || timers[ index ].queue === type)) {
timers[ index ].anim.stop(gotoEnd);
dequeue = false;
timers.splice(index, 1);
}
}
// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if (dequeue || !gotoEnd) {
jQuery.dequeue(this, type);
}
});
},
finish: function (type) {
if (type !== false) {
type = type || "fx";
}
return this.each(function () {
var index,
data = jQuery._data(this),
queue = data[ type + "queue" ],
hooks = data[ type + "queueHooks" ],
timers = jQuery.timers,
length = queue ? queue.length : 0;
// enable finishing flag on private data
data.finish = true;
// empty the queue first
jQuery.queue(this, type, []);
if (hooks && hooks.cur && hooks.cur.finish) {
hooks.cur.finish.call(this);
}
// look for any active animations, and finish them
for (index = timers.length; index--;) {
if (timers[ index ].elem === this && timers[ index ].queue === type) {
timers[ index ].anim.stop(true);
timers.splice(index, 1);
}
}
// look for any animations in the old queue and finish them
for (index = 0; index < length; index++) {
if (queue[ index ] && queue[ index ].finish) {
queue[ index ].finish.call(this);
}
}
// turn off finishing flag
delete data.finish;
});
}
});
// Generate parameters to create a standard animation
function genFx(type, includeWidth) {
var which,
attrs = { height: type },
i = 0;
// if we include width, step value is 1 to do all cssExpand values,
// if we don't include width, step value is 2 to skip over Left and Right
includeWidth = includeWidth ? 1 : 0;
for (; i < 4; i += 2 - includeWidth) {
which = cssExpand[ i ];
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
}
if (includeWidth) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx("show"),
slideUp: genFx("hide"),
slideToggle: genFx("toggle"),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function (name, props) {
jQuery.fn[ name ] = function (speed, easing, callback) {
return this.animate(props, speed, easing, callback);
};
});
jQuery.speed = function (speed, easing, fn) {
var opt = speed && typeof speed === "object" ? jQuery.extend({}, speed) : {
complete: fn || !fn && easing ||
jQuery.isFunction(speed) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction(easing) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
// normalize opt.queue - true/undefined/null -> "fx"
if (opt.queue == null || opt.queue === true) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function () {
if (jQuery.isFunction(opt.old)) {
opt.old.call(this);
}
if (opt.queue) {
jQuery.dequeue(this, opt.queue);
}
};
return opt;
};
jQuery.easing = {
linear: function (p) {
return p;
},
swing: function (p) {
return 0.5 - Math.cos(p * Math.PI) / 2;
}
};
jQuery.timers = [];
jQuery.fx = Tween.prototype.init;
jQuery.fx.tick = function () {
var timer,
timers = jQuery.timers,
i = 0;
fxNow = jQuery.now();
for (; i < timers.length; i++) {
timer = timers[ i ];
// Checks the timer has not already been removed
if (!timer() && timers[ i ] === timer) {
timers.splice(i--, 1);
}
}
if (!timers.length) {
jQuery.fx.stop();
}
fxNow = undefined;
};
jQuery.fx.timer = function (timer) {
if (timer() && jQuery.timers.push(timer)) {
jQuery.fx.start();
}
};
jQuery.fx.interval = 13;
jQuery.fx.start = function () {
if (!timerId) {
timerId = setInterval(jQuery.fx.tick, jQuery.fx.interval);
}
};
jQuery.fx.stop = function () {
clearInterval(timerId);
timerId = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Back Compat <1.8 extension point
jQuery.fx.step = {};
if (jQuery.expr && jQuery.expr.filters) {
jQuery.expr.filters.animated = function (elem) {
return jQuery.grep(jQuery.timers, function (fn) {
return elem === fn.elem;
}).length;
};
}
jQuery.fn.offset = function (options) {
if (arguments.length) {
return options === undefined ?
this :
this.each(function (i) {
jQuery.offset.setOffset(this, options, i);
});
}
var docElem, win,
box = { top: 0, left: 0 },
elem = this[ 0 ],
doc = elem && elem.ownerDocument;
if (!doc) {
return;
}
docElem = doc.documentElement;
// Make sure it's not a disconnected DOM node
if (!jQuery.contains(docElem, elem)) {
return box;
}
// If we don't have gBCR, just use 0,0 rather than error
// BlackBerry 5, iOS 3 (original iPhone)
if (typeof elem.getBoundingClientRect !== core_strundefined) {
box = elem.getBoundingClientRect();
}
win = getWindow(doc);
return {
top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ),
left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 )
};
};
jQuery.offset = {
setOffset: function (elem, options, i) {
var position = jQuery.css(elem, "position");
// set position first, in-case top/left are set even on static elem
if (position === "static") {
elem.style.position = "relative";
}
var curElem = jQuery(elem),
curOffset = curElem.offset(),
curCSSTop = jQuery.css(elem, "top"),
curCSSLeft = jQuery.css(elem, "left"),
calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
props = {}, curPosition = {}, curTop, curLeft;
// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if (calculatePosition) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat(curCSSTop) || 0;
curLeft = parseFloat(curCSSLeft) || 0;
}
if (jQuery.isFunction(options)) {
options = options.call(elem, i, curOffset);
}
if (options.top != null) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if (options.left != null) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ("using" in options) {
options.using.call(elem, props);
} else {
curElem.css(props);
}
}
};
jQuery.fn.extend({
position: function () {
if (!this[ 0 ]) {
return;
}
var offsetParent, offset,
parentOffset = { top: 0, left: 0 },
elem = this[ 0 ];
// fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent
if (jQuery.css(elem, "position") === "fixed") {
// we assume that getBoundingClientRect is available when computed position is fixed
offset = elem.getBoundingClientRect();
} else {
// Get *real* offsetParent
offsetParent = this.offsetParent();
// Get correct offsets
offset = this.offset();
if (!jQuery.nodeName(offsetParent[ 0 ], "html")) {
parentOffset = offsetParent.offset();
}
// Add offsetParent borders
parentOffset.top += jQuery.css(offsetParent[ 0 ], "borderTopWidth", true);
parentOffset.left += jQuery.css(offsetParent[ 0 ], "borderLeftWidth", true);
}
// Subtract parent offsets and element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
return {
top: offset.top - parentOffset.top - jQuery.css(elem, "marginTop", true),
left: offset.left - parentOffset.left - jQuery.css(elem, "marginLeft", true)
};
},
offsetParent: function () {
return this.map(function () {
var offsetParent = this.offsetParent || document.documentElement;
while (offsetParent && ( !jQuery.nodeName(offsetParent, "html") && jQuery.css(offsetParent, "position") === "static" )) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || document.documentElement;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each({scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function (method, prop) {
var top = /Y/.test(prop);
jQuery.fn[ method ] = function (val) {
return jQuery.access(this, function (elem, method, val) {
var win = getWindow(elem);
if (val === undefined) {
return win ? (prop in win) ? win[ prop ] :
win.document.documentElement[ method ] :
elem[ method ];
}
if (win) {
win.scrollTo(
!top ? val : jQuery(win).scrollLeft(),
top ? val : jQuery(win).scrollTop()
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null);
};
});
function getWindow(elem) {
return jQuery.isWindow(elem) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each({ Height: "height", Width: "width" }, function (name, type) {
jQuery.each({ padding: "inner" + name, content: type, "": "outer" + name }, function (defaultExtra, funcName) {
// margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function (margin, value) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return jQuery.access(this, function (elem, type, value) {
var doc;
if (jQuery.isWindow(elem)) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return elem.document.documentElement[ "client" + name ];
}
// Get document width or height
if (elem.nodeType === 9) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
// unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
return Math.max(
elem.body[ "scroll" + name ], doc[ "scroll" + name ],
elem.body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css(elem, type, extra) :
// Set width or height on the element
jQuery.style(elem, type, value, extra);
}, type, chainable ? margin : undefined, chainable, null);
};
});
});
// Limit scope pollution from any deprecated API
// (function() {
// })();
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
// Expose jQuery as an AMD module, but only for AMD loaders that
// understand the issues with loading multiple versions of jQuery
// in a page that all might call define(). The loader will indicate
// they have special allowances for multiple jQuery versions by
// specifying define.amd.jQuery = true. Register as a named module,
// since jQuery can be concatenated with other files that may use define,
// but not use a proper concatenation script that understands anonymous
// AMD modules. A named AMD is safest and most robust way to register.
// Lowercase jquery is used because AMD module names are derived from
// file names, and jQuery is normally delivered in a lowercase file name.
// Do this after creating the global so that if an AMD module wants to call
// noConflict to hide this version of jQuery, it will work.
if (typeof define === "function" && define.amd && define.amd.jQuery) {
define("jquery", [], function () {
return jQuery;
});
}
})(window);
|
"""
pygments.lexers.usd
~~~~~~~~~~~~~~~~~~~
The module that parses Pixar's Universal Scene Description file format.
:copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.lexer import RegexLexer, bygroups
from pygments.lexer import words as words_
from pygments.lexers._usd_builtins import COMMON_ATTRIBUTES, KEYWORDS, \
OPERATORS, SPECIAL_NAMES, TYPES
from pygments.token import Comment, Keyword, Name, Number, Operator, \
Punctuation, String, Text, Whitespace
__all__ = ["UsdLexer"]
def _keywords(words, type_):
return [(words_(words, prefix=r"\b", suffix=r"\b"), type_)]
_TYPE = r"(\w+(?:\[\])?)"
_BASE_ATTRIBUTE = r"(\w+(?:\:\w+)*)(?:(\.)(timeSamples))?"
_WHITESPACE = r"([ \t]+)"
class UsdLexer(RegexLexer):
"""
A lexer that parses Pixar's Universal Scene Description file format.
.. versionadded:: 2.6
"""
name = "USD"
aliases = ["usd", "usda"]
filenames = ["*.usd", "*.usda"]
tokens = {
"root": [
(r"(custom){_WHITESPACE}(uniform)(\s+){}(\s+){}(\s*)(=)".format(
_TYPE, _BASE_ATTRIBUTE, _WHITESPACE=_WHITESPACE),
bygroups(Keyword.Token, Whitespace, Keyword.Token, Whitespace,
Keyword.Type, Whitespace, Name.Attribute, Text,
Name.Keyword.Tokens, Whitespace, Operator)),
(r"(custom){_WHITESPACE}{}(\s+){}(\s*)(=)".format(
_TYPE, _BASE_ATTRIBUTE, _WHITESPACE=_WHITESPACE),
bygroups(Keyword.Token, Whitespace, Keyword.Type, Whitespace,
Name.Attribute, Text, Name.Keyword.Tokens, Whitespace,
Operator)),
(r"(uniform){_WHITESPACE}{}(\s+){}(\s*)(=)".format(
_TYPE, _BASE_ATTRIBUTE, _WHITESPACE=_WHITESPACE),
bygroups(Keyword.Token, Whitespace, Keyword.Type, Whitespace,
Name.Attribute, Text, Name.Keyword.Tokens, Whitespace,
Operator)),
(r"{}{_WHITESPACE}{}(\s*)(=)".format(
_TYPE, _BASE_ATTRIBUTE, _WHITESPACE=_WHITESPACE),
bygroups(Keyword.Type, Whitespace, Name.Attribute, Text,
Name.Keyword.Tokens, Whitespace, Operator)),
] +
_keywords(KEYWORDS, Keyword.Tokens) +
_keywords(SPECIAL_NAMES, Name.Builtins) +
_keywords(COMMON_ATTRIBUTES, Name.Attribute) +
[(r"\b\w+:[\w:]+\b", Name.Attribute)] +
_keywords(OPERATORS, Operator) + # more attributes
[(type_ + r"\[\]", Keyword.Type) for type_ in TYPES] +
_keywords(TYPES, Keyword.Type) +
[
(r"[(){}\[\]]", Punctuation),
("#.*?$", Comment.Single),
(",", Punctuation),
(";", Punctuation), # ";"s are allowed to combine separate metadata lines
("=", Operator),
(r"[-]*([0-9]*[.])?[0-9]+(?:e[+-]*\d+)?", Number),
(r"'''(?:.|\n)*?'''", String),
(r'"""(?:.|\n)*?"""', String),
(r"'.*?'", String),
(r'".*?"', String),
(r"<(\.\./)*([\w/]+|[\w/]+\.\w+[\w:]*)>", Name.Namespace),
(r"@.*?@", String.Interpol),
(r'\(.*"[.\\n]*".*\)', String.Doc),
(r"\A#usda .+$", Comment.Hashbang),
(r"\s+", Whitespace),
(r"\w+", Text),
(r"[_:.]+", Punctuation),
],
}
|
export default xs => [].concat(...xs);
|
/*
* Kendo UI Complete v2013.2.918 (http://kendoui.com)
* Copyright 2013 Telerik AD. All rights reserved.
*
* Kendo UI Complete commercial licenses may be obtained at
* https://www.kendoui.com/purchase/license-agreement/kendo-ui-complete-commercial.aspx
* If you do not own a commercial license, this file shall be governed by the trial license terms.
*/
!function(define){return define([],function(){!function(y){var n=y.kendo||(y.kendo={cultures:{}});n.cultures["zh-Hans"]={name:"zh-Hans",numberFormat:{pattern:["-n"],decimals:2,",":",",".":".",groupSize:[3],percent:{pattern:["-n%","n%"],decimals:2,",":",",".":".",groupSize:[3],symbol:"%"},currency:{pattern:["$-n","$n"],decimals:2,",":",",".":".",groupSize:[3],symbol:"¥"}},calendars:{standard:{days:{names:["星期日","星期一","星期二","星期三","星期四","星期五","星期六"],namesAbbr:["周日","周一","周二","周三","周四","周五","周六"],namesShort:["日","一","二","三","四","五","六"]},months:{names:["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月",""],namesAbbr:["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月",""]},AM:["上午","上午","上午"],PM:["下午","下午","下午"],patterns:{d:"yyyy/M/d",D:"yyyy'年'M'月'd'日'",F:"yyyy'年'M'月'd'日' H:mm:ss",g:"yyyy/M/d H:mm",G:"yyyy/M/d H:mm:ss",m:"M'月'd'日'",M:"M'月'd'日'",s:"yyyy'-'MM'-'dd'T'HH':'mm':'ss",t:"H:mm",T:"H:mm:ss",u:"yyyy'-'MM'-'dd HH':'mm':'ss'Z'",y:"yyyy'年'M'月'",Y:"yyyy'年'M'月'"},"/":"/",":":":",firstDay:0}}}}(this)})}("function"==typeof define&&define.amd?define:function(y,n){return n()});
|
import extend from 'lodash/extend';
export default function tableReducer(state={rows: []}, action) {
switch (action.type) {
case 'TABLE_ADD_ROW':
return extend({}, state, {rows: state.rows.concat([action.fields])});
default:
return state;
}
}
|
module.exports = {
parser: 'babel-eslint',
parserOptions: {
ecmaVersion: 6,
ecmaFeatures: {
jsx: true,
},
},
plugins: ['import', 'jsx-a11y', 'meteor', 'react', 'flowtype'],
extends: [
'eslint:recommended',
'plugin:meteor/recommended',
'plugin:react/recommended',
'plugin:flowtype/recommended',
],
env: {
es6: true,
node: true,
browser: true,
},
globals: {},
settings: {
flowtype: {
onlyFilesWithFlowAnnotation: true,
},
'import/resolver': {
alias: [['db', './src/db'], ['api', './src/api'], ['ui', './src/client']],
},
},
rules: {
'import/no-unresolved': ['error', { ignore: ['^meteor/', '^/'] }],
'no-console': 0
},
};
|
/**
* Copyright 2015 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {AmpAccessEvaluator} from '../access-expr';
describe('evaluate', () => {
let evaluator;
beforeEach(() => {
evaluator = new AmpAccessEvaluator();
});
it('should NOT allow double equal', () => {
expect(() => {
evaluator.evaluate('access == true', {});
}).to.throw(/\"\=\=\" is not allowed, use \"\=\"/);
});
it('should evaluate simple boolean expressions', () => {
expect(evaluator.evaluate('access = true', {access: true})).to.be.true;
expect(evaluator.evaluate('access = TRUE', {access: true})).to.be.true;
expect(evaluator.evaluate('access = false', {access: true})).to.be.false;
expect(evaluator.evaluate('access = FALSE', {access: true})).to.be.false;
expect(evaluator.evaluate('access != false', {access: true})).to.be.true;
expect(evaluator.evaluate('access = FALSE', {access: false})).to.be.true;
expect(evaluator.evaluate('access != TRUE', {access: false})).to.be.true;
expect(evaluator.evaluate('access = TRUE', {access: false})).to.be.false;
});
it('should evaluate boolean expressions over undefined', () => {
expect(evaluator.evaluate('access = true', {})).to.be.false;
expect(evaluator.evaluate('access != true', {})).to.be.true;
expect(evaluator.evaluate('access = false', {})).to.be.false;
expect(evaluator.evaluate('access != false', {})).to.be.true;
});
it('should evaluate simple numeric expressions', () => {
expect(evaluator.evaluate('num = 1', {num: 1})).to.be.true;
expect(evaluator.evaluate('num > 1', {num: 1})).to.be.false;
expect(evaluator.evaluate('num < 1', {num: 1})).to.be.false;
expect(evaluator.evaluate('num >= 1', {num: 1})).to.be.true;
expect(evaluator.evaluate('num <= 1', {num: 1})).to.be.true;
});
it('should evaluate negative numerics', () => {
expect(evaluator.evaluate('num = -1', {num: -1})).to.be.true;
expect(evaluator.evaluate('num = -1', {num: 0})).to.be.false;
expect(evaluator.evaluate('num < -1', {num: -1})).to.be.false;
expect(evaluator.evaluate('num < -1', {num: -2})).to.be.true;
expect(evaluator.evaluate('num > -1', {num: 0})).to.be.true;
});
it('should evaluate numeric expressions over mistamtching type', () => {
expect(evaluator.evaluate('num = 1', {})).to.be.false;
expect(evaluator.evaluate('num > 1', {})).to.be.false;
expect(evaluator.evaluate('num < 1', {})).to.be.false;
expect(evaluator.evaluate('num >= 1', {})).to.be.false;
expect(evaluator.evaluate('num <= 1', {})).to.be.false;
expect(evaluator.evaluate('num != 1', {})).to.be.true;
expect(evaluator.evaluate('num = 0', {num: 0})).to.be.true;
expect(evaluator.evaluate('num > 0', {num: 0})).to.be.false;
expect(evaluator.evaluate('num < 0', {num: 0})).to.be.false;
expect(evaluator.evaluate('num >= 0', {num: 0})).to.be.true;
expect(evaluator.evaluate('num <= 0', {num: 0})).to.be.true;
expect(evaluator.evaluate('num != 0', {num: 0})).to.be.false;
expect(evaluator.evaluate('num = 0', {})).to.be.false;
expect(evaluator.evaluate('num > 0', {})).to.be.false;
expect(evaluator.evaluate('num < 0', {})).to.be.false;
expect(evaluator.evaluate('num >= 0', {})).to.be.false;
expect(evaluator.evaluate('num <= 0', {})).to.be.false;
expect(evaluator.evaluate('num != 0', {})).to.be.true;
expect(evaluator.evaluate('num = 0', {num: false})).to.be.false;
expect(evaluator.evaluate('num > 0', {num: false})).to.be.false;
expect(evaluator.evaluate('num < 0', {num: false})).to.be.false;
expect(evaluator.evaluate('num >= 0', {num: false})).to.be.false;
expect(evaluator.evaluate('num <= 0', {num: false})).to.be.false;
expect(evaluator.evaluate('num != 0', {num: false})).to.be.true;
expect(evaluator.evaluate('num = 0', {num: ''})).to.be.false;
expect(evaluator.evaluate('num > 0', {num: ''})).to.be.false;
expect(evaluator.evaluate('num < 0', {num: ''})).to.be.false;
expect(evaluator.evaluate('num >= 0', {num: ''})).to.be.false;
expect(evaluator.evaluate('num <= 0', {num: ''})).to.be.false;
expect(evaluator.evaluate('num != 0', {num: ''})).to.be.true;
expect(evaluator.evaluate('num = 0', {num: '0'})).to.be.false;
expect(evaluator.evaluate('num > 0', {num: '0'})).to.be.false;
expect(evaluator.evaluate('num < 0', {num: '0'})).to.be.false;
expect(evaluator.evaluate('num >= 0', {num: '0'})).to.be.false;
expect(evaluator.evaluate('num <= 0', {num: '0'})).to.be.false;
expect(evaluator.evaluate('num != 0', {num: '0'})).to.be.true;
});
it('should evaluate simple string expressions', () => {
expect(evaluator.evaluate('str = "A"', {str: 'A'})).to.be.true;
expect(evaluator.evaluate("str = 'A'", {str: 'A'})).to.be.true;
expect(evaluator.evaluate('str != "A"', {str: 'A'})).to.be.false;
});
it('should evaluate string expressions with wrong type', () => {
expect(evaluator.evaluate('str = "A"', {})).to.be.false;
expect(evaluator.evaluate("str = 'A'", {})).to.be.false;
expect(evaluator.evaluate('str != "A"', {})).to.be.true;
expect(evaluator.evaluate('str = "A"', {str: 1})).to.be.false;
expect(evaluator.evaluate("str = 'A'", {str: 1})).to.be.false;
expect(evaluator.evaluate('str != "A"', {str: 1})).to.be.true;
expect(evaluator.evaluate('str = ""', {str: false})).to.be.false;
expect(evaluator.evaluate("str = ''", {str: false})).to.be.false;
expect(evaluator.evaluate('str != ""', {str: false})).to.be.true;
expect(evaluator.evaluate('str = "A"', {str: true})).to.be.false;
expect(evaluator.evaluate("str = 'A'", {str: true})).to.be.false;
expect(evaluator.evaluate('str != "A"', {str: true})).to.be.true;
});
it('should evaluate simple NULL expressions', () => {
expect(evaluator.evaluate('access = NULL', {})).to.be.true;
expect(evaluator.evaluate('access != NULL', {})).to.be.false;
expect(evaluator.evaluate('access = NULL', {access: null})).to.be.true;
expect(evaluator.evaluate('access != NULL', {access: null})).to.be.false;
});
it('should evaluate NULL expressions with wrong type', () => {
expect(evaluator.evaluate('n = NULL', {n: ''})).to.be.false;
expect(evaluator.evaluate('n != NULL', {n: ''})).to.be.true;
expect(evaluator.evaluate('n = NULL', {n: 0})).to.be.false;
expect(evaluator.evaluate('n != NULL', {n: 0})).to.be.true;
expect(evaluator.evaluate('n = NULL', {n: false})).to.be.false;
expect(evaluator.evaluate('n != NULL', {n: false})).to.be.true;
});
it('should evaluate truthy expressions', () => {
expect(evaluator.evaluate('t', {})).to.be.false;
expect(evaluator.evaluate('NOT t', {})).to.be.true;
expect(evaluator.evaluate('t', {t: null})).to.be.false;
expect(evaluator.evaluate('NOT t', {t: null})).to.be.true;
expect(evaluator.evaluate('t', {t: true})).to.be.true;
expect(evaluator.evaluate('NOT t', {t: true})).to.be.false;
expect(evaluator.evaluate('t', {t: false})).to.be.false;
expect(evaluator.evaluate('NOT t', {t: false})).to.be.true;
expect(evaluator.evaluate('t', {t: 1})).to.be.true;
expect(evaluator.evaluate('NOT t', {t: 1})).to.be.false;
expect(evaluator.evaluate('t', {t: 0})).to.be.false;
expect(evaluator.evaluate('NOT t', {t: 0})).to.be.true;
expect(evaluator.evaluate('t', {t: '1'})).to.be.true;
expect(evaluator.evaluate('NOT t', {t: '1'})).to.be.false;
expect(evaluator.evaluate('t', {t: ''})).to.be.false;
expect(evaluator.evaluate('NOT t', {t: ''})).to.be.true;
});
it('should evaluate NOT expressions', () => {
expect(evaluator.evaluate('NOT (access = true)', {})).to.be.true;
expect(evaluator.evaluate('NOT (access = true)', {access: true})).to.be
.false;
expect(evaluator.evaluate('NOT (access = true)', {access: false})).to.be
.true;
expect(evaluator.evaluate('NOT (access = 1)', {access: 1})).to.be.false;
expect(evaluator.evaluate('NOT (access = 1)', {access: 0})).to.be.true;
expect(evaluator.evaluate('NOT (access > 1)', {access: 1})).to.be.true;
expect(evaluator.evaluate('NOT (access > 0)', {access: 1})).to.be.false;
expect(evaluator.evaluate('NOT (access = "a")', {access: 'a'})).to.be.false;
expect(evaluator.evaluate('NOT (access = "b")', {access: 'a'})).to.be.true;
});
it('should evaluate AND/OR expressions', () => {
expect(evaluator.evaluate('a = 1 AND b = 2', {a: 1, b: 2})).to.be.true;
expect(evaluator.evaluate('a = 1 AND b != 2', {a: 1, b: 2})).to.be.false;
expect(evaluator.evaluate('a = 1 OR b = 2', {a: 1, b: 2})).to.be.true;
expect(evaluator.evaluate('a = 1 OR b != 2', {a: 1, b: 2})).to.be.true;
expect(evaluator.evaluate('NOT (a = 1 OR b != 2)', {a: 1, b: 2})).to.be
.false;
expect(evaluator.evaluate('a AND b = 2', {a: 1, b: 2})).to.be.true;
expect(evaluator.evaluate('a AND b', {a: 1, b: 2})).to.be.true;
expect(evaluator.evaluate('a AND c', {a: 1, b: 2})).to.be.false;
});
it('should evaluate nested expressions', () => {
const resp = {
obj: {
str: 'A',
num: 11,
bool: true,
},
};
expect(evaluator.evaluate('obj.bool = true', resp)).to.be.true;
expect(evaluator.evaluate('obj.num = 11', resp)).to.be.true;
expect(evaluator.evaluate('obj.str = "A"', resp)).to.be.true;
expect(evaluator.evaluate('obj.other = NULL', resp)).to.be.true;
expect(evaluator.evaluate('obj.str = NULL', resp)).to.be.false;
expect(evaluator.evaluate('obj.bool', resp)).to.be.true;
expect(evaluator.evaluate('obj.str', resp)).to.be.true;
expect(evaluator.evaluate('obj.num', resp)).to.be.true;
expect(evaluator.evaluate('obj.other', resp)).to.be.false;
expect(evaluator.evaluate('NOT obj.bool', resp)).to.be.false;
expect(evaluator.evaluate('NOT obj.str', resp)).to.be.false;
expect(evaluator.evaluate('NOT obj.num', resp)).to.be.false;
expect(evaluator.evaluate('NOT obj.other', resp)).to.be.true;
});
it('should shortcircuit nested expressions with missing parent', () => {
const resp = {
obj: {
str: 'A',
child: {
str: 'B',
},
},
};
expect(evaluator.evaluate('obj.str = "A"', resp)).to.be.true;
expect(evaluator.evaluate('obj.child.str = "B"', resp)).to.be.true;
expect(evaluator.evaluate('obj.child.other = NULL', resp)).to.be.true;
expect(evaluator.evaluate('obj.child2 = NULL', resp)).to.be.true;
expect(evaluator.evaluate('obj.child2.other = NULL', resp)).to.be.true;
expect(evaluator.evaluate('obj.child2.other.x = NULL', resp)).to.be.true;
expect(evaluator.evaluate('obj2.child2.other.x = NULL', resp)).to.be.true;
});
it('should evaluate nested expressions with brackets', () => {
const resp = {
obj: {
str: 'A',
'a str': 'A',
num: 11,
'a num': 11,
bool: true,
'a bool': true,
},
};
expect(evaluator.evaluate('obj["bool"] = true', resp)).to.be.true;
expect(evaluator.evaluate('obj["a bool"] = true', resp)).to.be.true;
expect(evaluator.evaluate('obj["num"] = 11', resp)).to.be.true;
expect(evaluator.evaluate('obj["a num"] = 11', resp)).to.be.true;
expect(evaluator.evaluate('obj["str"] = "A"', resp)).to.be.true;
expect(evaluator.evaluate('obj["a str"] = "A"', resp)).to.be.true;
expect(evaluator.evaluate("obj['bool'] = true", resp)).to.be.true;
expect(evaluator.evaluate("obj['a bool'] = true", resp)).to.be.true;
expect(evaluator.evaluate("obj['num'] = 11", resp)).to.be.true;
expect(evaluator.evaluate("obj['a num'] = 11", resp)).to.be.true;
expect(evaluator.evaluate("obj['str'] = 'A'", resp)).to.be.true;
expect(evaluator.evaluate("obj['a str'] = 'A'", resp)).to.be.true;
expect(evaluator.evaluate('obj["other"] = NULL', resp)).to.be.true;
expect(evaluator.evaluate('obj["a other"] = NULL', resp)).to.be.true;
expect(evaluator.evaluate('obj["str"] = NULL', resp)).to.be.false;
expect(evaluator.evaluate('obj["a str"] = NULL', resp)).to.be.false;
expect(evaluator.evaluate('obj["bool"]', resp)).to.be.true;
expect(evaluator.evaluate('obj["a bool"]', resp)).to.be.true;
expect(evaluator.evaluate('obj["str"]', resp)).to.be.true;
expect(evaluator.evaluate('obj["a str"]', resp)).to.be.true;
expect(evaluator.evaluate('obj["num"]', resp)).to.be.true;
expect(evaluator.evaluate('obj["a num"]', resp)).to.be.true;
expect(evaluator.evaluate('obj["other"]', resp)).to.be.false;
expect(evaluator.evaluate('obj["a other"]', resp)).to.be.false;
expect(evaluator.evaluate('NOT obj["bool"]', resp)).to.be.false;
expect(evaluator.evaluate('NOT obj["a bool"]', resp)).to.be.false;
expect(evaluator.evaluate('NOT obj["str"]', resp)).to.be.false;
expect(evaluator.evaluate('NOT obj["a str"]', resp)).to.be.false;
expect(evaluator.evaluate('NOT obj["num"]', resp)).to.be.false;
expect(evaluator.evaluate('NOT obj["a num"]', resp)).to.be.false;
expect(evaluator.evaluate('NOT obj["other"]', resp)).to.be.true;
expect(evaluator.evaluate('NOT obj["a other"]', resp)).to.be.true;
expect(evaluator.evaluate('obj2["bool"] = NULL', resp)).to.be.true;
});
it('should NOT evaluate nested expressions with wrong type', function() {
expect(evaluator.evaluate('obj.bool = true', {obj: true})).to.be.false;
expect(evaluator.evaluate('obj.num = 11', {obj: 11})).to.be.false;
expect(evaluator.evaluate('obj.str = "A"', {obj: 'A'})).to.be.false;
expect(evaluator.evaluate('obj.str = "A"', {})).to.be.false;
expect(evaluator.evaluate('obj.other = NULL', {obj: 11})).to.be.true;
expect(() => {
evaluator.evaluate('obj.NULL', {});
}).to.throw();
expect(() => {
evaluator.evaluate('NULL.obj', {});
}).to.throw();
expect(() => {
evaluator.evaluate('1.obj', {});
}).to.throw();
expect(() => {
evaluator.evaluate('TRUE.obj', {});
}).to.throw();
});
it('should evaluate nested expressions securely', () => {
expect(evaluator.evaluate('obj.__bool__ = NULL', {obj: {}})).to.be.true;
});
it('should accept name grammar', () => {
expect(evaluator.evaluate('num = 10', {num: 10})).to.be.true;
expect(evaluator.evaluate('num1 = 10', {num1: 10})).to.be.true;
expect(evaluator.evaluate('num_ = 10', {num_: 10})).to.be.true;
expect(evaluator.evaluate('_num = 10', {_num: 10})).to.be.true;
expect(() => {
evaluator.evaluate('1num = 10', {'1num': 10});
}).to.throw();
expect(() => {
evaluator.evaluate('num-a = 10', {'num-a': 10});
}).to.throw();
expect(() => {
evaluator.evaluate('num-1 = 10', {'num-1': 10});
}).to.throw();
});
describe('caching', () => {
beforeEach(() => {
window.sandbox.spy(evaluator, 'eval_');
});
it('first request should go through', () => {
evaluator.evaluate('access = true', {access: true});
expect(evaluator.eval_).calledOnce;
});
it('should use the cache on subsequent calls for the same expression and data', () => {
const data = {access: true};
evaluator.evaluate('access = true', data);
evaluator.evaluate('access = true', data);
expect(evaluator.eval_).calledOnce;
});
it('should not use the cache if the data is referentially unequal', () => {
evaluator.evaluate('access = true', {access: true});
evaluator.evaluate('access = true', {access: true});
expect(evaluator.eval_).calledTwice;
});
});
});
|
# Copyright 2012 by Wibowo Arindrarto. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""Tests for SearchIO BlastIO parsers."""
import os
import unittest
from Bio.SearchIO import parse
from Bio.SearchIO.BlastIO.blast_tab import _LONG_SHORT_MAP as all_fields
# test case files are in the Blast directory
TEST_DIR = 'Blast'
FMT = 'blast-tab'
def get_file(filename):
"""Return the path of a test file."""
return os.path.join(TEST_DIR, filename)
class BlastTabCases(unittest.TestCase):
"""Tests for the tab-separated BLAST parser."""
def test_tab_2228_tblastn_001(self):
"""Test parsing TBLASTN 2.2.28+ tabular output (tab_2228_tblastn_001)."""
tab_file = get_file('tab_2228_tblastn_001.txt')
qresults = list(parse(tab_file, FMT,
fields=['evalue', 'sallseqid', 'qseqid'],
comments=True))
self.assertEqual(1, len(qresults))
self.assertEqual(10, len(qresults[0].hits))
# there is one hit with an alternative ID
self.assertEqual(qresults[0]['gi|148227873|ref|NM_001095167.1|'],
qresults[0]['gi|55250552|gb|BC086280.1|'])
# check some of the HSPs
self.assertEqual(0.0, qresults[0][0][0].evalue)
self.assertEqual(8e-173, qresults[0][-1][0].evalue)
def test_tab_2228_tblastx_001(self):
"""Test parsing TBLASTX 2.2.28+ tabular output (tab_2228_tblastx_001)."""
tab_file = get_file('tab_2228_tblastx_001.txt')
qresults = list(parse(tab_file, FMT,
fields=list(all_fields.values()),
comments=True))
# this a single query, with 192 hits and 243 hsps
self.assertEqual(1, len(qresults))
self.assertEqual(192, len(qresults[0].hits))
self.assertEqual(243, sum(len(x) for x in qresults[0]))
# there is one hit with an alternative ID
self.assertEqual(qresults[0]['gi|31126987|gb|AY255526.2|'],
qresults[0]['gi|31342050|ref|NM_181083.2|'])
# only checking the new fields in 2.2.28+
hit = qresults[0][0]
self.assertEqual(['NM_001183135', 'EF059095'], hit.accession_all)
self.assertEqual(['32630', '559292'], hit.tax_ids)
self.assertEqual(['N/A', 'N/A'], hit.sci_names)
self.assertEqual(['N/A', 'N/A'], hit.com_names)
self.assertEqual(['N/A'], hit.blast_names)
self.assertEqual(['N/A'], hit.super_kingdoms)
self.assertEqual('Saccharomyces cerevisiae S288c Mon2p (MON2), mRNA', hit.title)
self.assertEqual(['Saccharomyces cerevisiae S288c Mon2p (MON2), mRNA',
'Synthetic construct Saccharomyces cerevisiae clone '
'FLH203015.01X MON2, complete sequence'], hit.title_all)
self.assertEqual('N/A', hit.strand)
self.assertEqual(100.0, hit.query_coverage)
for hsp in hit[:4]:
# shorthand ~ the values just happen to all be 99
# in other cases, they may be different
self.assertEqual(99.0, hsp.query_coverage)
self.assertEqual(73.0, hit[5].query_coverage)
self.assertEqual(12.0, hit[6].query_coverage)
def test_tab_2226_tblastn_001(self):
"""Test parsing TBLASTN 2.2.26+ tabular output (tab_2226_tblastn_001)."""
xml_file = get_file('tab_2226_tblastn_001.txt')
qresults = parse(xml_file, FMT)
counter = 0
# test first qresult
qresult = next(qresults)
counter += 1
self.assertEqual('gi|16080617|ref|NP_391444.1|', qresult.id)
self.assertEqual(3, len(qresult))
hit = qresult[0]
self.assertEqual('gi|145479850|ref|XM_001425911.1|', hit.id)
self.assertEqual('gi|16080617|ref|NP_391444.1|', hit.query_id)
self.assertEqual(1, len(hit))
hsp = hit.hsps[0]
self.assertEqual('gi|145479850|ref|XM_001425911.1|', hsp.hit_id)
self.assertEqual('gi|16080617|ref|NP_391444.1|', hsp.query_id)
self.assertEqual(34.88, hsp.ident_pct)
self.assertEqual(43, hsp.aln_span)
self.assertEqual(28, hsp.mismatch_num)
self.assertEqual(0, hsp.gapopen_num)
self.assertEqual(30, hsp.query_start)
self.assertEqual(73, hsp.query_end)
self.assertEqual(1743, hsp.hit_start)
self.assertEqual(1872, hsp.hit_end)
self.assertEqual(1e-05, hsp.evalue)
self.assertEqual(34.7, hsp.bitscore)
hit = qresult[-1]
self.assertEqual('gi|115975252|ref|XM_001180111.1|', hit.id)
self.assertEqual('gi|16080617|ref|NP_391444.1|', hit.query_id)
self.assertEqual(1, len(hit))
hsp = hit.hsps[0]
self.assertEqual('gi|115975252|ref|XM_001180111.1|', hsp.hit_id)
self.assertEqual('gi|16080617|ref|NP_391444.1|', hsp.query_id)
self.assertEqual(33.90, hsp.ident_pct)
self.assertEqual(59, hsp.aln_span)
self.assertEqual(31, hsp.mismatch_num)
self.assertEqual(1, hsp.gapopen_num)
self.assertEqual(43, hsp.query_start)
self.assertEqual(94, hsp.query_end)
self.assertEqual(1056, hsp.hit_start)
self.assertEqual(1233, hsp.hit_end)
self.assertEqual(1e-04, hsp.evalue)
self.assertEqual(31.6, hsp.bitscore)
# test last qresult
qresult = next(qresults)
counter += 1
self.assertEqual('gi|11464971:4-101', qresult.id)
self.assertEqual(5, len(qresult))
hit = qresult[0]
self.assertEqual('gi|350596019|ref|XM_003360601.2|', hit.id)
self.assertEqual('gi|11464971:4-101', hit.query_id)
self.assertEqual(2, len(hit))
hsp = hit.hsps[0]
self.assertEqual('gi|350596019|ref|XM_003360601.2|', hsp.hit_id)
self.assertEqual('gi|11464971:4-101', hsp.query_id)
self.assertEqual(95.92, hsp.ident_pct)
self.assertEqual(98, hsp.aln_span)
self.assertEqual(4, hsp.mismatch_num)
self.assertEqual(0, hsp.gapopen_num)
self.assertEqual(0, hsp.query_start)
self.assertEqual(98, hsp.query_end)
self.assertEqual(94, hsp.hit_start)
self.assertEqual(388, hsp.hit_end)
self.assertEqual(2e-67, hsp.evalue)
self.assertEqual(199, hsp.bitscore)
hsp = hit.hsps[-1]
self.assertEqual('gi|350596019|ref|XM_003360601.2|', hsp.hit_id)
self.assertEqual('gi|11464971:4-101', hsp.query_id)
self.assertEqual(29.58, hsp.ident_pct)
self.assertEqual(71, hsp.aln_span)
self.assertEqual(46, hsp.mismatch_num)
self.assertEqual(2, hsp.gapopen_num)
self.assertEqual(29, hsp.query_start)
self.assertEqual(96, hsp.query_end)
self.assertEqual(541, hsp.hit_start)
self.assertEqual(754, hsp.hit_end)
self.assertEqual(4e-05, hsp.evalue)
self.assertEqual(32.7, hsp.bitscore)
# check if we've finished iteration over qresults
self.assertRaises(StopIteration, next, qresults)
self.assertEqual(2, counter)
def test_tab_2226_tblastn_002(self):
"""Test parsing TBLASTN 2.2.26+ tabular output (tab_2226_tblastn_002)."""
xml_file = get_file('tab_2226_tblastn_002.txt')
qresults = parse(xml_file, FMT)
# check if we've finished iteration over qresults
self.assertRaises(StopIteration, next, qresults)
def test_tab_2226_tblastn_003(self):
"""Test parsing TBLASTN 2.2.26+ tabular output (tab_2226_tblastn_003)."""
xml_file = get_file('tab_2226_tblastn_003.txt')
qresults = parse(xml_file, FMT)
counter = 0
# test first qresult
qresult = next(qresults)
counter += 1
self.assertEqual('gi|16080617|ref|NP_391444.1|', qresult.id)
self.assertEqual(3, len(qresult))
hit = qresult[0]
self.assertEqual('gi|145479850|ref|XM_001425911.1|', hit.id)
self.assertEqual('gi|16080617|ref|NP_391444.1|', hit.query_id)
self.assertEqual(1, len(hit))
hsp = hit.hsps[0]
self.assertEqual('gi|145479850|ref|XM_001425911.1|', hsp.hit_id)
self.assertEqual('gi|16080617|ref|NP_391444.1|', hsp.query_id)
self.assertEqual(34.88, hsp.ident_pct)
self.assertEqual(43, hsp.aln_span)
self.assertEqual(28, hsp.mismatch_num)
self.assertEqual(0, hsp.gapopen_num)
self.assertEqual(30, hsp.query_start)
self.assertEqual(73, hsp.query_end)
self.assertEqual(1743, hsp.hit_start)
self.assertEqual(1872, hsp.hit_end)
self.assertEqual(1e-05, hsp.evalue)
self.assertEqual(34.7, hsp.bitscore)
hit = qresult[-1]
self.assertEqual('gi|115975252|ref|XM_001180111.1|', hit.id)
self.assertEqual('gi|16080617|ref|NP_391444.1|', hit.query_id)
self.assertEqual(1, len(hit))
hsp = hit.hsps[0]
self.assertEqual('gi|115975252|ref|XM_001180111.1|', hsp.hit_id)
self.assertEqual('gi|16080617|ref|NP_391444.1|', hsp.query_id)
self.assertEqual(33.90, hsp.ident_pct)
self.assertEqual(59, hsp.aln_span)
self.assertEqual(31, hsp.mismatch_num)
self.assertEqual(1, hsp.gapopen_num)
self.assertEqual(43, hsp.query_start)
self.assertEqual(94, hsp.query_end)
self.assertEqual(1056, hsp.hit_start)
self.assertEqual(1233, hsp.hit_end)
self.assertEqual(1e-04, hsp.evalue)
self.assertEqual(31.6, hsp.bitscore)
# check if we've finished iteration over qresults
self.assertRaises(StopIteration, next, qresults)
self.assertEqual(1, counter)
def test_tab_2226_tblastn_004(self):
"""Test parsing TBLASTN 2.2.26+ tabular output (tab_2226_tblastn_004)."""
xml_file = get_file('tab_2226_tblastn_004.txt')
qresults = parse(xml_file, FMT)
counter = 0
qresult = next(qresults)
counter += 1
self.assertEqual('gi|11464971:4-101', qresult.id)
self.assertEqual(5, len(qresult))
hit = qresult[0]
self.assertEqual('gi|350596019|ref|XM_003360601.2|', hit.id)
self.assertEqual('gi|11464971:4-101', hit.query_id)
self.assertEqual(2, len(hit))
hsp = hit.hsps[0]
self.assertEqual('gi|350596019|ref|XM_003360601.2|', hsp.hit_id)
self.assertEqual('gi|11464971:4-101', hsp.query_id)
self.assertEqual(95.92, hsp.ident_pct)
self.assertEqual(98, hsp.aln_span)
self.assertEqual(4, hsp.mismatch_num)
self.assertEqual(0, hsp.gapopen_num)
self.assertEqual(0, hsp.query_start)
self.assertEqual(98, hsp.query_end)
self.assertEqual(94, hsp.hit_start)
self.assertEqual(388, hsp.hit_end)
self.assertEqual(2e-67, hsp.evalue)
self.assertEqual(199, hsp.bitscore)
hsp = hit.hsps[-1]
self.assertEqual('gi|350596019|ref|XM_003360601.2|', hsp.hit_id)
self.assertEqual('gi|11464971:4-101', hsp.query_id)
self.assertEqual(29.58, hsp.ident_pct)
self.assertEqual(71, hsp.aln_span)
self.assertEqual(46, hsp.mismatch_num)
self.assertEqual(2, hsp.gapopen_num)
self.assertEqual(29, hsp.query_start)
self.assertEqual(96, hsp.query_end)
self.assertEqual(541, hsp.hit_start)
self.assertEqual(754, hsp.hit_end)
self.assertEqual(4e-05, hsp.evalue)
self.assertEqual(32.7, hsp.bitscore)
# check if we've finished iteration over qresults
self.assertRaises(StopIteration, next, qresults)
self.assertEqual(1, counter)
def test_tab_2226_tblastn_005(self):
"""Test parsing TBLASTN 2.2.26+ tabular output with comments (tab_2226_tblastn_005)."""
xml_file = get_file('tab_2226_tblastn_005.txt')
qresults = parse(xml_file, FMT, comments=True)
counter = 0
# test first qresult
qresult = next(qresults)
counter += 1
self.assertEqual('tblastn', qresult.program)
self.assertEqual('db/minirefseq_mrna', qresult.target)
self.assertEqual('2.2.26+', qresult.version)
self.assertEqual('random_s00', qresult.id)
self.assertEqual(0, len(qresult))
# test second qresult
qresult = next(qresults)
counter += 1
self.assertEqual('tblastn', qresult.program)
self.assertEqual('db/minirefseq_mrna', qresult.target)
self.assertEqual('2.2.26+', qresult.version)
self.assertEqual('gi|16080617|ref|NP_391444.1|', qresult.id)
self.assertEqual(3, len(qresult))
hit = qresult[0]
self.assertEqual('gi|145479850|ref|XM_001425911.1|', hit.id)
self.assertEqual('gi|16080617|ref|NP_391444.1|', hit.query_id)
self.assertEqual(1, len(hit))
hsp = hit.hsps[0]
self.assertEqual('gi|145479850|ref|XM_001425911.1|', hsp.hit_id)
self.assertEqual('gi|16080617|ref|NP_391444.1|', hsp.query_id)
self.assertEqual(34.88, hsp.ident_pct)
self.assertEqual(43, hsp.aln_span)
self.assertEqual(28, hsp.mismatch_num)
self.assertEqual(0, hsp.gapopen_num)
self.assertEqual(30, hsp.query_start)
self.assertEqual(73, hsp.query_end)
self.assertEqual(1743, hsp.hit_start)
self.assertEqual(1872, hsp.hit_end)
self.assertEqual(1e-05, hsp.evalue)
self.assertEqual(34.7, hsp.bitscore)
hit = qresult[-1]
self.assertEqual('gi|115975252|ref|XM_001180111.1|', hit.id)
self.assertEqual('gi|16080617|ref|NP_391444.1|', hit.query_id)
self.assertEqual(1, len(hit))
hsp = hit.hsps[0]
self.assertEqual('gi|115975252|ref|XM_001180111.1|', hsp.hit_id)
self.assertEqual('gi|16080617|ref|NP_391444.1|', hsp.query_id)
self.assertEqual(33.90, hsp.ident_pct)
self.assertEqual(59, hsp.aln_span)
self.assertEqual(31, hsp.mismatch_num)
self.assertEqual(1, hsp.gapopen_num)
self.assertEqual(43, hsp.query_start)
self.assertEqual(94, hsp.query_end)
self.assertEqual(1056, hsp.hit_start)
self.assertEqual(1233, hsp.hit_end)
self.assertEqual(1e-04, hsp.evalue)
self.assertEqual(31.6, hsp.bitscore)
# test last qresult
qresult = next(qresults)
counter += 1
self.assertEqual('tblastn', qresult.program)
self.assertEqual('db/minirefseq_mrna', qresult.target)
self.assertEqual('2.2.26+', qresult.version)
self.assertEqual('gi|11464971:4-101', qresult.id)
self.assertEqual(5, len(qresult))
hit = qresult[0]
self.assertEqual('gi|350596019|ref|XM_003360601.2|', hit.id)
self.assertEqual('gi|11464971:4-101', hit.query_id)
self.assertEqual(2, len(hit))
hsp = hit.hsps[0]
self.assertEqual('gi|350596019|ref|XM_003360601.2|', hsp.hit_id)
self.assertEqual('gi|11464971:4-101', hsp.query_id)
self.assertEqual(95.92, hsp.ident_pct)
self.assertEqual(98, hsp.aln_span)
self.assertEqual(4, hsp.mismatch_num)
self.assertEqual(0, hsp.gapopen_num)
self.assertEqual(0, hsp.query_start)
self.assertEqual(98, hsp.query_end)
self.assertEqual(94, hsp.hit_start)
self.assertEqual(388, hsp.hit_end)
self.assertEqual(2e-67, hsp.evalue)
self.assertEqual(199, hsp.bitscore)
hsp = hit.hsps[-1]
self.assertEqual('gi|350596019|ref|XM_003360601.2|', hsp.hit_id)
self.assertEqual('gi|11464971:4-101', hsp.query_id)
self.assertEqual(29.58, hsp.ident_pct)
self.assertEqual(71, hsp.aln_span)
self.assertEqual(46, hsp.mismatch_num)
self.assertEqual(2, hsp.gapopen_num)
self.assertEqual(29, hsp.query_start)
self.assertEqual(96, hsp.query_end)
self.assertEqual(541, hsp.hit_start)
self.assertEqual(754, hsp.hit_end)
self.assertEqual(4e-05, hsp.evalue)
self.assertEqual(32.7, hsp.bitscore)
# check if we've finished iteration over qresults
self.assertRaises(StopIteration, next, qresults)
self.assertEqual(3, counter)
def test_tab_2226_tblastn_005_comments_false(self):
"""Test parsing TBLASTN 2.2.26+ tabular output with comments (tab_2226_tblastn_005)."""
tab_file = get_file('tab_2226_tblastn_005.txt')
exc_msg = ("Encountered unexpected character '#' at the beginning of"
" a line. Set comments=True if the file is a commented"
" file.")
qresults = parse(tab_file, FMT)
with self.assertRaises(ValueError, msg=exc_msg):
next(qresults)
def test_tab_2226_tblastn_006(self):
"""Test parsing TBLASTN 2.2.26+ tabular output with comments (tab_2226_tblastn_006)."""
xml_file = get_file('tab_2226_tblastn_006.txt')
qresults = parse(xml_file, FMT, comments=True)
counter = 0
qresult = next(qresults)
counter += 1
self.assertEqual('tblastn', qresult.program)
self.assertEqual('db/minirefseq_mrna', qresult.target)
self.assertEqual('2.2.26+', qresult.version)
self.assertEqual('random_s00', qresult.id)
self.assertEqual(0, len(qresult))
# check if we've finished iteration over qresults
self.assertRaises(StopIteration, next, qresults)
self.assertEqual(1, counter)
def test_tab_2226_tblastn_007(self):
"""Test parsing TBLASTN 2.2.26+ tabular output with comments (tab_2226_tblastn_007)."""
xml_file = get_file('tab_2226_tblastn_007.txt')
qresults = parse(xml_file, FMT, comments=True)
counter = 0
qresult = next(qresults)
counter += 1
self.assertEqual('tblastn', qresult.program)
self.assertEqual('db/minirefseq_mrna', qresult.target)
self.assertEqual('2.2.26+', qresult.version)
self.assertEqual('gi|16080617|ref|NP_391444.1|', qresult.id)
self.assertEqual(3, len(qresult))
hit = qresult[0]
self.assertEqual('gi|145479850|ref|XM_001425911.1|', hit.id)
self.assertEqual('gi|16080617|ref|NP_391444.1|', hit.query_id)
self.assertEqual(1, len(hit))
hsp = hit.hsps[0]
self.assertEqual('gi|145479850|ref|XM_001425911.1|', hsp.hit_id)
self.assertEqual('gi|16080617|ref|NP_391444.1|', hsp.query_id)
self.assertEqual(34.88, hsp.ident_pct)
self.assertEqual(43, hsp.aln_span)
self.assertEqual(28, hsp.mismatch_num)
self.assertEqual(0, hsp.gapopen_num)
self.assertEqual(30, hsp.query_start)
self.assertEqual(73, hsp.query_end)
self.assertEqual(1743, hsp.hit_start)
self.assertEqual(1872, hsp.hit_end)
self.assertEqual(1e-05, hsp.evalue)
self.assertEqual(34.7, hsp.bitscore)
hit = qresult[-1]
self.assertEqual('gi|115975252|ref|XM_001180111.1|', hit.id)
self.assertEqual('gi|16080617|ref|NP_391444.1|', hit.query_id)
self.assertEqual(1, len(hit))
hsp = hit.hsps[0]
self.assertEqual('gi|115975252|ref|XM_001180111.1|', hsp.hit_id)
self.assertEqual('gi|16080617|ref|NP_391444.1|', hsp.query_id)
self.assertEqual(33.90, hsp.ident_pct)
self.assertEqual(59, hsp.aln_span)
self.assertEqual(31, hsp.mismatch_num)
self.assertEqual(1, hsp.gapopen_num)
self.assertEqual(43, hsp.query_start)
self.assertEqual(94, hsp.query_end)
self.assertEqual(1056, hsp.hit_start)
self.assertEqual(1233, hsp.hit_end)
self.assertEqual(1e-04, hsp.evalue)
self.assertEqual(31.6, hsp.bitscore)
# check if we've finished iteration over qresults
self.assertRaises(StopIteration, next, qresults)
self.assertEqual(1, counter)
def test_tab_2226_tblastn_008(self):
"""Test parsing TBLASTN 2.2.26+ tabular output with comments (tab_2226_tblastn_008)."""
xml_file = get_file('tab_2226_tblastn_008.txt')
qresults = parse(xml_file, FMT, comments=True)
counter = 0
qresult = next(qresults)
counter += 1
self.assertEqual('tblastn', qresult.program)
self.assertEqual('db/minirefseq_mrna', qresult.target)
self.assertEqual('2.2.26+', qresult.version)
self.assertEqual('gi|11464971:4-101', qresult.id)
self.assertEqual(5, len(qresult))
hit = qresult[0]
self.assertEqual('gi|350596019|ref|XM_003360601.2|', hit.id)
self.assertEqual('gi|11464971:4-101', hit.query_id)
self.assertEqual(2, len(hit))
hsp = hit.hsps[0]
self.assertEqual('gi|350596019|ref|XM_003360601.2|', hsp.hit_id)
self.assertEqual('gi|11464971:4-101', hsp.query_id)
self.assertEqual(95.92, hsp.ident_pct)
self.assertEqual(98, hsp.aln_span)
self.assertEqual(4, hsp.mismatch_num)
self.assertEqual(0, hsp.gapopen_num)
self.assertEqual(0, hsp.query_start)
self.assertEqual(98, hsp.query_end)
self.assertEqual(94, hsp.hit_start)
self.assertEqual(388, hsp.hit_end)
self.assertEqual(2e-67, hsp.evalue)
self.assertEqual(199, hsp.bitscore)
hsp = hit.hsps[-1]
self.assertEqual('gi|350596019|ref|XM_003360601.2|', hsp.hit_id)
self.assertEqual('gi|11464971:4-101', hsp.query_id)
self.assertEqual(29.58, hsp.ident_pct)
self.assertEqual(71, hsp.aln_span)
self.assertEqual(46, hsp.mismatch_num)
self.assertEqual(2, hsp.gapopen_num)
self.assertEqual(29, hsp.query_start)
self.assertEqual(96, hsp.query_end)
self.assertEqual(541, hsp.hit_start)
self.assertEqual(754, hsp.hit_end)
self.assertEqual(4e-05, hsp.evalue)
self.assertEqual(32.7, hsp.bitscore)
# check if we've finished iteration over qresults
self.assertRaises(StopIteration, next, qresults)
self.assertEqual(1, counter)
def test_tab_2226_tblastn_009(self):
"""Test parsing TBLASTN 2.2.26+ tabular output (tab_2226_tblastn_009)."""
xml_file = get_file('tab_2226_tblastn_009.txt')
qresults = parse(xml_file, FMT, fields=('qseqid', 'sseqid'))
counter = 0
# test first qresult
qresult = next(qresults)
counter += 1
self.assertEqual('<unknown program>', qresult.program)
self.assertEqual('<unknown target>', qresult.target)
self.assertEqual('<unknown version>', qresult.version)
self.assertEqual('gi|16080617|ref|NP_391444.1|', qresult.id)
self.assertEqual(3, len(qresult))
hit = qresult[0]
self.assertEqual('gi|145479850|ref|XM_001425911.1|', hit.id)
self.assertEqual('gi|16080617|ref|NP_391444.1|', hit.query_id)
self.assertEqual(1, len(hit))
hsp = hit[0]
self.assertEqual('gi|145479850|ref|XM_001425911.1|', hsp.hit_id)
self.assertEqual('gi|16080617|ref|NP_391444.1|', hsp.query_id)
hit = qresult[-1]
self.assertEqual('gi|115975252|ref|XM_001180111.1|', hit.id)
self.assertEqual('gi|16080617|ref|NP_391444.1|', hit.query_id)
self.assertEqual(1, len(hit))
hsp = hit[0]
self.assertEqual('gi|115975252|ref|XM_001180111.1|', hsp.hit_id)
self.assertEqual('gi|16080617|ref|NP_391444.1|', hsp.query_id)
# test last qresult
qresult = next(qresults)
counter += 1
self.assertEqual('<unknown program>', qresult.program)
self.assertEqual('<unknown target>', qresult.target)
self.assertEqual('<unknown version>', qresult.version)
self.assertEqual('gi|11464971:4-101', qresult.id)
self.assertEqual(5, len(qresult))
hit = qresult[0]
self.assertEqual('gi|350596019|ref|XM_003360601.2|', hit.id)
self.assertEqual('gi|11464971:4-101', hit.query_id)
self.assertEqual(2, len(hit))
hsp = hit[0]
self.assertEqual('gi|350596019|ref|XM_003360601.2|', hsp.hit_id)
self.assertEqual('gi|11464971:4-101', hsp.query_id)
hsp = hit[-1]
self.assertEqual('gi|350596019|ref|XM_003360601.2|', hsp.hit_id)
self.assertEqual('gi|11464971:4-101', hsp.query_id)
# check if we've finished iteration over qresults
self.assertRaises(StopIteration, next, qresults)
self.assertEqual(2, counter)
def test_tab_2226_tblastn_010(self):
"""Test parsing TBLASTN 2.2.26+ tabular output with comments (tab_2226_tblastn_010)."""
xml_file = get_file('tab_2226_tblastn_010.txt')
qresults = parse(xml_file, FMT, comments=True)
counter = 0
# test first qresult
qresult = next(qresults)
counter += 1
self.assertEqual('tblastn', qresult.program)
self.assertEqual('db/minirefseq_mrna', qresult.target)
self.assertEqual('2.2.26+', qresult.version)
self.assertEqual('random_s00', qresult.id)
self.assertEqual(0, len(qresult))
# test second qresult
qresult = next(qresults)
counter += 1
self.assertEqual('tblastn', qresult.program)
self.assertEqual('db/minirefseq_mrna', qresult.target)
self.assertEqual('2.2.26+', qresult.version)
self.assertEqual('gi|16080617|ref|NP_391444.1|', qresult.id)
self.assertEqual(3, len(qresult))
hit = qresult[0]
self.assertEqual('gi|145479850|ref|XM_001425911.1|', hit.id)
self.assertEqual('gi|16080617|ref|NP_391444.1|', hit.query_id)
self.assertEqual(1, len(hit))
hsp = hit.hsps[0]
self.assertEqual('gi|145479850|ref|XM_001425911.1|', hsp.hit_id)
self.assertEqual('gi|16080617|ref|NP_391444.1|', hsp.query_id)
self.assertEqual(1e-05, hsp.evalue)
self.assertEqual(34.7, hsp.bitscore)
hit = qresult[-1]
self.assertEqual('gi|115975252|ref|XM_001180111.1|', hit.id)
self.assertEqual('gi|16080617|ref|NP_391444.1|', hit.query_id)
self.assertEqual(1, len(hit))
hsp = hit.hsps[0]
self.assertEqual('gi|115975252|ref|XM_001180111.1|', hsp.hit_id)
self.assertEqual('gi|16080617|ref|NP_391444.1|', hsp.query_id)
self.assertEqual(1e-04, hsp.evalue)
self.assertEqual(31.6, hsp.bitscore)
# test last qresult
qresult = next(qresults)
counter += 1
self.assertEqual('tblastn', qresult.program)
self.assertEqual('db/minirefseq_mrna', qresult.target)
self.assertEqual('2.2.26+', qresult.version)
self.assertEqual('gi|11464971:4-101', qresult.id)
self.assertEqual(5, len(qresult))
hit = qresult[0]
self.assertEqual('gi|350596019|ref|XM_003360601.2|', hit.id)
self.assertEqual('gi|11464971:4-101', hit.query_id)
self.assertEqual(2, len(hit))
hsp = hit.hsps[0]
self.assertEqual('gi|350596019|ref|XM_003360601.2|', hsp.hit_id)
self.assertEqual('gi|11464971:4-101', hsp.query_id)
self.assertEqual(2e-67, hsp.evalue)
self.assertEqual(199, hsp.bitscore)
hsp = hit.hsps[-1]
self.assertEqual('gi|350596019|ref|XM_003360601.2|', hsp.hit_id)
self.assertEqual('gi|11464971:4-101', hsp.query_id)
self.assertEqual(4e-05, hsp.evalue)
self.assertEqual(32.7, hsp.bitscore)
# check if we've finished iteration over qresults
self.assertRaises(StopIteration, next, qresults)
self.assertEqual(3, counter)
def test_tab_2226_tblastn_011(self):
"""Test parsing TBLASTN 2.2.26+ tabular output with comments (tab_2226_tblastn_011)."""
xml_file = get_file('tab_2226_tblastn_011.txt')
qresults = parse(xml_file, FMT, comments=True)
counter = 0
# test first qresult
qresult = next(qresults)
counter += 1
self.assertEqual('tblastn', qresult.program)
self.assertEqual('db/minirefseq_mrna', qresult.target)
self.assertEqual('2.2.26+', qresult.version)
self.assertEqual('random_s00', qresult.id)
self.assertEqual(0, len(qresult))
# test second qresult
qresult = next(qresults)
counter += 1
self.assertEqual('tblastn', qresult.program)
self.assertEqual('db/minirefseq_mrna', qresult.target)
self.assertEqual('2.2.26+', qresult.version)
self.assertEqual('gi|16080617|ref|NP_391444.1|', qresult.id)
self.assertEqual('gi|16080617|ref|NP_391444.1|', qresult.accession)
self.assertEqual('gi|16080617|ref|NP_391444.1|', qresult.accession_version)
self.assertEqual('0', qresult.gi)
self.assertEqual(102, qresult.seq_len)
self.assertEqual(3, len(qresult))
hit = qresult[0]
self.assertEqual('gi|145479850|ref|XM_001425911.1|', hit.id)
self.assertEqual(['gi|145479850|ref|XM_001425911.1|'], hit.id_all)
self.assertEqual('gi|145479850|ref|XM_001425911.1|', hit.accession)
self.assertEqual('gi|145479850|ref|XM_001425911.1|', hit.accession_version)
self.assertEqual('0', hit.gi)
self.assertEqual('0', hit.gi_all)
self.assertEqual('gi|16080617|ref|NP_391444.1|', hit.query_id)
self.assertEqual(4632, hit.seq_len)
self.assertEqual(1, len(hit))
hsp = hit.hsps[0]
self.assertEqual('gi|145479850|ref|XM_001425911.1|', hsp.hit_id)
self.assertEqual('gi|16080617|ref|NP_391444.1|', hsp.query_id)
self.assertEqual(34.88, hsp.ident_pct)
self.assertEqual(43, hsp.aln_span)
self.assertEqual(28, hsp.mismatch_num)
self.assertEqual(0, hsp.gapopen_num)
self.assertEqual(30, hsp.query_start)
self.assertEqual(73, hsp.query_end)
self.assertEqual(1743, hsp.hit_start)
self.assertEqual(1872, hsp.hit_end)
self.assertEqual(1e-05, hsp.evalue)
self.assertEqual(34.7, hsp.bitscore)
self.assertEqual('PDSNIETKEGTYVGLADTHTIEVTVDNEPVSLDITEESTSDLD', str(hsp.query.seq))
self.assertEqual('PKTATGTKKGTIIGLLSIHTILFILTSHALSLEVKEQT*KDID', str(hsp.hit.seq))
self.assertEqual(78, hsp.bitscore_raw)
self.assertEqual(15, hsp.ident_num)
self.assertEqual(26, hsp.pos_num)
self.assertEqual(0, hsp.gap_num)
self.assertEqual(60.47, hsp.pos_pct)
self.assertEqual(0, hsp.query_frame)
self.assertEqual(1, hsp.hit_frame)
hit = qresult[-1]
self.assertEqual('gi|115975252|ref|XM_001180111.1|', hit.id)
self.assertEqual('gi|115975252|ref|XM_001180111.1|', hit.accession)
self.assertEqual('gi|115975252|ref|XM_001180111.1|', hit.accession_version)
self.assertEqual('gi|16080617|ref|NP_391444.1|', hit.query_id)
self.assertEqual(1, len(hit))
hsp = hit.hsps[0]
self.assertEqual('gi|115975252|ref|XM_001180111.1|', hsp.hit_id)
self.assertEqual('gi|16080617|ref|NP_391444.1|', hsp.query_id)
self.assertEqual(33.90, hsp.ident_pct)
self.assertEqual(59, hsp.aln_span)
self.assertEqual(31, hsp.mismatch_num)
self.assertEqual(1, hsp.gapopen_num)
self.assertEqual(43, hsp.query_start)
self.assertEqual(94, hsp.query_end)
self.assertEqual(1056, hsp.hit_start)
self.assertEqual(1233, hsp.hit_end)
self.assertEqual(1e-04, hsp.evalue)
self.assertEqual(31.6, hsp.bitscore)
self.assertEqual('GLADTHTIEVTVDNEPVSLDITEESTSDLDKFNSG--------DKVTITYEKNDEGQLL', str(hsp.query.seq))
self.assertEqual('GLVPDHTLILPVGHYQSMLDLTEEVQTELDQFKSALRKYYLSKGKTCVIYERNFRTQHL', str(hsp.hit.seq))
self.assertEqual(70.0, hsp.bitscore_raw)
self.assertEqual(20, hsp.ident_num)
self.assertEqual(29, hsp.pos_num)
self.assertEqual(8, hsp.gap_num)
self.assertEqual(49.15, hsp.pos_pct)
self.assertEqual(0, hsp.query_frame)
self.assertEqual(1, hsp.hit_frame)
# test last qresult
qresult = next(qresults)
counter += 1
self.assertEqual('tblastn', qresult.program)
self.assertEqual('db/minirefseq_mrna', qresult.target)
self.assertEqual('2.2.26+', qresult.version)
self.assertEqual('gi|11464971:4-101', qresult.id)
self.assertEqual('gi|11464971:4-101', qresult.accession)
self.assertEqual('gi|11464971:4-101', qresult.accession_version)
self.assertEqual('0', qresult.gi)
self.assertEqual(98, qresult.seq_len)
self.assertEqual(5, len(qresult))
hit = qresult[0]
self.assertEqual('gi|350596019|ref|XM_003360601.2|', hit.id)
self.assertEqual(['gi|350596019|ref|XM_003360601.2|'], hit.id_all)
self.assertEqual('gi|350596019|ref|XM_003360601.2|', hit.accession)
self.assertEqual('gi|350596019|ref|XM_003360601.2|', hit.accession_version)
self.assertEqual('0', hit.gi)
self.assertEqual('0', hit.gi_all)
self.assertEqual('gi|11464971:4-101', hit.query_id)
self.assertEqual(772, hit.seq_len)
self.assertEqual(2, len(hit))
hsp = hit.hsps[0]
self.assertEqual('gi|350596019|ref|XM_003360601.2|', hsp.hit_id)
self.assertEqual('gi|11464971:4-101', hsp.query_id)
self.assertEqual(95.92, hsp.ident_pct)
self.assertEqual(98, hsp.aln_span)
self.assertEqual(4, hsp.mismatch_num)
self.assertEqual(0, hsp.gapopen_num)
self.assertEqual(0, hsp.query_start)
self.assertEqual(98, hsp.query_end)
self.assertEqual(94, hsp.hit_start)
self.assertEqual(388, hsp.hit_end)
self.assertEqual(2e-67, hsp.evalue)
self.assertEqual(199, hsp.bitscore)
self.assertEqual('KRIREGYLVKKGSVFNTWKPMWVVLLEDGIEFYKKKSDNSPKGMIPLKGSTLTSPCQDFGKRMFVLKITTTKQQDHFFQAAFLEERDAWVRDIKKAIK', str(hsp.query.seq))
self.assertEqual('KRIREGYLVKKGSMFNTWKPMWVILLEDGIEFYKKKSDNSPKGMIPLKGSTLTSPCQDFGKRMFVFKITTTKQQDHFFQAAFLEERDGWVRDIKKAIK', str(hsp.hit.seq))
self.assertEqual(506.0, hsp.bitscore_raw)
self.assertEqual(94, hsp.ident_num)
self.assertEqual(96, hsp.pos_num)
self.assertEqual(0, hsp.gap_num)
self.assertEqual(97.96, hsp.pos_pct)
self.assertEqual(0, hsp.query_frame)
self.assertEqual(2, hsp.hit_frame)
hsp = hit.hsps[-1]
self.assertEqual('gi|350596019|ref|XM_003360601.2|', hsp.hit_id)
self.assertEqual('gi|11464971:4-101', hsp.query_id)
self.assertEqual(29.58, hsp.ident_pct)
self.assertEqual(71, hsp.aln_span)
self.assertEqual(46, hsp.mismatch_num)
self.assertEqual(2, hsp.gapopen_num)
self.assertEqual(29, hsp.query_start)
self.assertEqual(96, hsp.query_end)
self.assertEqual(541, hsp.hit_start)
self.assertEqual(754, hsp.hit_end)
self.assertEqual(4e-05, hsp.evalue)
self.assertEqual(32.7, hsp.bitscore)
self.assertEqual('IEFYKKKSDNSPKGMIPLKGSTLTS-PCQDFGKRMFVLK---ITTTKQQDHFFQAAFLEERDAWVRDIKKA', str(hsp.query.seq))
self.assertEqual('LHYYDPAGGEDPLGAIHLRGCVVTSVESNTDGKNGFLWERAXXITADEVHYFLQAANPKERTEWIKAIQVA', str(hsp.hit.seq))
self.assertEqual(73.0, hsp.bitscore_raw)
self.assertEqual(21, hsp.ident_num)
self.assertEqual(33, hsp.pos_num)
self.assertEqual(4, hsp.gap_num)
self.assertEqual(46.48, hsp.pos_pct)
self.assertEqual(0, hsp.query_frame)
self.assertEqual(2, hsp.hit_frame)
# check if we've finished iteration over qresults
self.assertRaises(StopIteration, next, qresults)
self.assertEqual(3, counter)
def test_tab_2226_tblastn_012(self):
"""Test parsing TBLASTN 2.2.26+ tabular output with comments (tab_2226_tblastn_012)."""
xml_file = get_file('tab_2226_tblastn_012.txt')
qresults = parse(xml_file, FMT, comments=True)
counter = 0
# test first qresult
qresult = next(qresults)
counter += 1
self.assertEqual('tblastn', qresult.program)
self.assertEqual('refseq_rna', qresult.target)
self.assertEqual('2.2.26+', qresult.version)
self.assertEqual('random_s00', qresult.id)
self.assertEqual('X76FDCG9016', qresult.rid)
self.assertEqual(0, len(qresult))
# test second qresult
qresult = next(qresults)
counter += 1
self.assertEqual('tblastn', qresult.program)
self.assertEqual('refseq_rna', qresult.target)
self.assertEqual('2.2.26+', qresult.version)
self.assertEqual('gi|16080617|ref|NP_391444.1|', qresult.id)
self.assertEqual('X76FDCG9016', qresult.rid)
self.assertEqual(3, len(qresult))
# test last qresult
qresult = next(qresults)
counter += 1
self.assertEqual('tblastn', qresult.program)
self.assertEqual('refseq_rna', qresult.target)
self.assertEqual('2.2.26+', qresult.version)
self.assertEqual('gi|11464971:4-101', qresult.id)
self.assertEqual('X76FDCG9016', qresult.rid)
self.assertEqual(5, len(qresult))
# check if we've finished iteration over qresults
self.assertRaises(StopIteration, next, qresults)
self.assertEqual(3, counter)
def test_tab_2226_tblastn_013(self):
"""Test parsing TBLASTN 2.2.26+ tabular output (tab_2226_tblastn_013)."""
xml_file = get_file('tab_2226_tblastn_013.txt')
qresults = parse(xml_file, FMT, fields="qseq std sseq")
counter = 0
qresult = next(qresults)
counter += 1
self.assertEqual('<unknown program>', qresult.program)
self.assertEqual('<unknown target>', qresult.target)
self.assertEqual('<unknown version>', qresult.version)
self.assertEqual(3, len(qresult))
hit = qresult[0]
self.assertEqual('gi|145479850|ref|XM_001425911.1|', hit.id)
self.assertEqual('gi|16080617|ref|NP_391444.1|', hit.query_id)
self.assertEqual(1, len(hit))
hsp = hit.hsps[0]
self.assertEqual('gi|145479850|ref|XM_001425911.1|', hsp.hit_id)
self.assertEqual('gi|16080617|ref|NP_391444.1|', hsp.query_id)
self.assertEqual(34.88, hsp.ident_pct)
self.assertEqual(43, hsp.aln_span)
self.assertEqual(28, hsp.mismatch_num)
self.assertEqual(0, hsp.gapopen_num)
self.assertEqual(30, hsp.query_start)
self.assertEqual(73, hsp.query_end)
self.assertEqual(1743, hsp.hit_start)
self.assertEqual(1872, hsp.hit_end)
self.assertEqual(1e-05, hsp.evalue)
self.assertEqual(34.7, hsp.bitscore)
self.assertEqual('PDSNIETKEGTYVGLADTHTIEVTVDNEPVSLDITEESTSDLD', str(hsp.query.seq))
self.assertEqual('PKTATGTKKGTIIGLLSIHTILFILTSHALSLEVKEQT*KDID', str(hsp.hit.seq))
hit = qresult[-1]
self.assertEqual('gi|115975252|ref|XM_001180111.1|', hit.id)
self.assertEqual('gi|16080617|ref|NP_391444.1|', hit.query_id)
self.assertEqual(1, len(hit))
hsp = hit.hsps[0]
self.assertEqual('gi|115975252|ref|XM_001180111.1|', hsp.hit_id)
self.assertEqual('gi|16080617|ref|NP_391444.1|', hsp.query_id)
self.assertEqual(33.90, hsp.ident_pct)
self.assertEqual(59, hsp.aln_span)
self.assertEqual(31, hsp.mismatch_num)
self.assertEqual(1, hsp.gapopen_num)
self.assertEqual(43, hsp.query_start)
self.assertEqual(94, hsp.query_end)
self.assertEqual(1056, hsp.hit_start)
self.assertEqual(1233, hsp.hit_end)
self.assertEqual(1e-04, hsp.evalue)
self.assertEqual(31.6, hsp.bitscore)
self.assertEqual('GLADTHTIEVTVDNEPVSLDITEESTSDLDKFNSG--------DKVTITYEKNDEGQLL', str(hsp.query.seq))
self.assertEqual('GLVPDHTLILPVGHYQSMLDLTEEVQTELDQFKSALRKYYLSKGKTCVIYERNFRTQHL', str(hsp.hit.seq))
# check if we've finished iteration over qresults
self.assertRaises(StopIteration, next, qresults)
self.assertEqual(1, counter)
if __name__ == "__main__":
runner = unittest.TextTestRunner(verbosity=2)
unittest.main(testRunner=runner)
|
"""Saver for eager mode TensorFlow."""
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import contextlib
from tensorflow.python.framework import errors
from tensorflow.python.framework import ops
from tensorflow.python.ops import resource_variable_ops
from tensorflow.python.training import checkpoint_utils
from tensorflow.python.training import saver as _saver
def _init_from_checkpoint(self, *args, **kwargs):
"""Overrides default init by loading value from checkpoint."""
self.old_init(*args, **kwargs)
# pylint: disable=protected-access
if self._shared_name not in self.ckpt_var_cache:
raise errors.NotFoundError(None, None,
"%s not found in checkpoint" % self._shared_name)
val = self.ckpt_var_cache[self._shared_name]
if val is not None:
self.assign(self.ckpt_var_cache[self._shared_name])
# Avoid assigning for the second time.
self.ckpt_var_cache[self._shared_name] = None
# pylint: enable=protected-access
@contextlib.contextmanager
def restore_variables_on_create(save_path):
"""ContextManager that restores variables on creation.
When save_path is None (e.g. No checkpoint), does nothing.
Otherwise, it preloads all values from checkpoint. When the
corresponding variable is first created, it assigns the checkpoint
value to the variable.
```python
with restore_variables_on_create(
tf.train.latest_checkpoint(checkpoint_dir)):
```
Args:
save_path: The checkpoint file prefix.
Yields:
Nothing.
Raises:
NotFoundError: If the variable is not found in checkpoint.
"""
if save_path:
ckpt_var_cache = dict()
reader = checkpoint_utils.load_checkpoint(save_path)
for k, _ in checkpoint_utils.list_variables(save_path):
ckpt_var_cache[k] = reader.get_tensor(k)
old_init = getattr(
resource_variable_ops.ResourceVariable, "_init_from_args", None)
assert old_init, "ResourceVariable misses _init_from_args method."
setattr(resource_variable_ops.ResourceVariable, "_init_from_args",
_init_from_checkpoint)
setattr(resource_variable_ops.ResourceVariable, "old_init", old_init)
setattr(resource_variable_ops.ResourceVariable, "ckpt_var_cache",
ckpt_var_cache)
try:
yield
except Exception as e:
raise e
finally:
if save_path:
setattr(resource_variable_ops.ResourceVariable, "_init_from_args",
old_init)
setattr(resource_variable_ops.ResourceVariable, "old_init", None)
setattr(resource_variable_ops.ResourceVariable, "ckpt_var_cache", None)
class Saver(object):
"""A simple tf.train.Saver adapter for eager mode.
save and restore API are similar to the tf.train.Saver, except that
session is not needed.
Args:
var_list: A list of variables.
"""
def __init__(self, var_list):
self._saver = _saver.Saver(var_list=var_list)
def save(self, save_path, global_step=None):
"""Saves variables.
Args:
save_path: See save method in tf.train.Saver.
global_step: See save method in tf.train.Saver.
Returns:
See save method in tf.train.Saver.
"""
with ops.device("/device:CPU:0"):
return self._saver.save(None, save_path, write_meta_graph=False,
global_step=global_step)
def restore(self, save_path):
"""Restores previously saved variables.
Args:
save_path: See restore method in tf.train.Saver.
"""
with ops.device("/device:CPU:0"):
self._saver.restore(None, save_path)
|
from __future__ import division, absolute_import, print_function
import os
from distutils.core import Command
from distutils.ccompiler import new_compiler
from numpy.distutils.misc_util import get_cmd
class install_clib(Command):
description = "Command to install installable C libraries"
user_options = []
def initialize_options(self):
self.install_dir = None
self.outfiles = []
def finalize_options(self):
self.set_undefined_options('install', ('install_lib', 'install_dir'))
def run (self):
build_clib_cmd = get_cmd("build_clib")
build_dir = build_clib_cmd.build_clib
# We need the compiler to get the library name -> filename association
if not build_clib_cmd.compiler:
compiler = new_compiler(compiler=None)
compiler.customize(self.distribution)
else:
compiler = build_clib_cmd.compiler
for l in self.distribution.installed_libraries:
target_dir = os.path.join(self.install_dir, l.target_dir)
name = compiler.library_filename(l.name)
source = os.path.join(build_dir, name)
self.mkpath(target_dir)
# iOS
# print("We want to copy ", source, " to ", target_dir)
self.outfiles.append(self.copy_file(source, target_dir)[0])
def get_outputs(self):
return self.outfiles
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from ansible.module_utils.openshift_common import OpenShiftAnsibleModule, OpenShiftAnsibleException
DOCUMENTATION = '''
module: openshift_v1_user_identity_mapping
short_description: OpenShift UserIdentityMapping
description:
- Manage the lifecycle of a user_identity_mapping object. Supports check mode, and
attempts to to be idempotent.
version_added: 2.3.0
author: OpenShift (@openshift)
options:
annotations:
description:
- Annotations is an unstructured key value map stored with a resource that may
be set by external tools to store and retrieve arbitrary metadata. They are
not queryable and should be preserved when modifying objects.
type: dict
api_key:
description:
- Token used to connect to the API.
cert_file:
description:
- Path to a certificate used to authenticate with the API.
type: path
context:
description:
- The name of a context found in the Kubernetes config file.
debug:
description:
- Enable debug output from the OpenShift helper. Logging info is written to KubeObjHelper.log
default: false
type: bool
force:
description:
- If set to C(True), and I(state) is C(present), an existing object will updated,
and lists will be replaced, rather than merged.
default: false
type: bool
host:
description:
- Provide a URL for acessing the Kubernetes API.
identity_api_version:
description:
- API version of the referent.
aliases:
- api_version
identity_field_path:
description:
- 'If referring to a piece of an object instead of an entire object, this string
should contain a valid JSON/Go field access statement, such as desiredState.manifest.containers[2].
For example, if the object reference is to a container within a pod, this would
take on a value like: "spec.containers{name}" (where "name" refers to the name
of the container that triggered the event) or if no container name is specified
"spec.containers[2]" (container with index 2 in this pod). This syntax is chosen
only to have some well-defined way of referencing a part of an object.'
aliases:
- field_path
identity_kind:
description:
- Kind of the referent.
aliases:
- kind
identity_name:
description:
- Name of the referent.
identity_namespace:
description:
- Namespace of the referent.
identity_resource_version:
description:
- Specific resourceVersion to which this reference is made, if any.
aliases:
- resource_version
identity_uid:
description:
- UID of the referent.
aliases:
- uid
key_file:
description:
- Path to a key file used to authenticate with the API.
type: path
kubeconfig:
description:
- Path to an existing Kubernetes config file. If not provided, and no other connection
options are provided, the openshift client will attempt to load the default
configuration file from I(~/.kube/config.json).
type: path
labels:
description:
- Map of string keys and values that can be used to organize and categorize (scope
and select) objects. May match selectors of replication controllers and services.
type: dict
name:
description:
- Name must be unique within a namespace. Is required when creating resources,
although some resources may allow a client to request the generation of an appropriate
name automatically. Name is primarily intended for creation idempotence and
configuration definition. Cannot be updated.
namespace:
description:
- Namespace defines the space within each name must be unique. An empty namespace
is equivalent to the "default" namespace, but "default" is the canonical representation.
Not all objects are required to be scoped to a namespace - the value of this
field for those objects will be empty. Must be a DNS_LABEL. Cannot be updated.
password:
description:
- Provide a password for connecting to the API. Use in conjunction with I(username).
resource_definition:
description:
- Provide the YAML definition for the object, bypassing any modules parameters
intended to define object attributes.
type: dict
src:
description:
- Provide a path to a file containing the YAML definition of the object. Mutually
exclusive with I(resource_definition).
type: path
ssl_ca_cert:
description:
- Path to a CA certificate used to authenticate with the API.
type: path
state:
description:
- Determines if an object should be created, patched, or deleted. When set to
C(present), the object will be created, if it does not exist, or patched, if
parameter values differ from the existing object's attributes, and deleted,
if set to C(absent). A patch operation results in merging lists and updating
dictionaries, with lists being merged into a unique set of values. If a list
contains a dictionary with a I(name) or I(type) attribute, a strategic merge
is performed, where individual elements with a matching I(name_) or I(type)
are merged. To force the replacement of lists, set the I(force) option to C(True).
default: present
choices:
- present
- absent
user_api_version:
description:
- API version of the referent.
user_field_path:
description:
- 'If referring to a piece of an object instead of an entire object, this string
should contain a valid JSON/Go field access statement, such as desiredState.manifest.containers[2].
For example, if the object reference is to a container within a pod, this would
take on a value like: "spec.containers{name}" (where "name" refers to the name
of the container that triggered the event) or if no container name is specified
"spec.containers[2]" (container with index 2 in this pod). This syntax is chosen
only to have some well-defined way of referencing a part of an object.'
user_kind:
description:
- Kind of the referent.
user_name:
description:
- Name of the referent.
user_namespace:
description:
- Namespace of the referent.
user_resource_version:
description:
- Specific resourceVersion to which this reference is made, if any.
user_uid:
description:
- UID of the referent.
username:
description:
- Provide a username for connecting to the API.
verify_ssl:
description:
- Whether or not to verify the API server's SSL certificates.
type: bool
requirements:
- openshift == 0.4.0.a1
'''
EXAMPLES = '''
'''
RETURN = '''
api_version:
description: Requested API version
type: string
user_identity_mapping:
type: complex
returned: when I(state) = C(present)
contains:
api_version:
description:
- APIVersion defines the versioned schema of this representation of an object.
Servers should convert recognized schemas to the latest internal value, and
may reject unrecognized values.
type: str
identity:
description:
- Identity is a reference to an identity
type: complex
kind:
description:
- Kind is a string value representing the REST resource this object represents.
Servers may infer this from the endpoint the client submits requests to. Cannot
be updated. In CamelCase.
type: str
metadata:
description:
- Standard object's metadata.
type: complex
user:
description:
- User is a reference to a user
type: complex
'''
def main():
try:
module = OpenShiftAnsibleModule('user_identity_mapping', 'v1')
except OpenShiftAnsibleException as exc:
# The helper failed to init, so there is no module object. All we can do is raise the error.
raise Exception(exc.message)
try:
module.execute_module()
except OpenShiftAnsibleException as exc:
module.fail_json(msg="Module failed!", error=str(exc))
if __name__ == '__main__':
main()
|
'use strict';
module.exports = function strnatcasecmp(a, b) {
// discuss at: http://locutus.io/php/strnatcasecmp/
// original by: Martin Pool
// reimplemented by: Pierre-Luc Paour
// reimplemented by: Kristof Coomans (SCK-CEN (Belgian Nucleair Research Centre))
// reimplemented by: Brett Zamir (http://brett-zamir.me)
// bugfixed by: Kevin van Zonneveld (http://kvz.io)
// input by: Devan Penner-Woelk
// improved by: Kevin van Zonneveld (http://kvz.io)
// reimplemented by: Rafał Kukawski
// example 1: strnatcasecmp(10, 1)
// returns 1: 1
// example 2: strnatcasecmp('1', '10')
// returns 2: -1
var strnatcmp = require('../strings/strnatcmp');
var _phpCastString = require('../_helpers/_phpCastString');
if (arguments.length !== 2) {
return null;
}
return strnatcmp(_phpCastString(a).toLowerCase(), _phpCastString(b).toLowerCase());
};
//# sourceMappingURL=strnatcasecmp.js.map
|
import info
class subinfo(info.infoclass):
def setTargets(self):
self.versionInfo.setDefaultValues()
self.description = 'a desktop planetarium'
for ver in ['3.4.3']:
self.targets[ver] = 'http://download.kde.org/stable/kstars/kstars-%s.tar.xz' % ver
self.targetInstSrc[ver] = 'kstars-%s' % ver
self.defaultTarget = '3.4.3'
self.displayName = "KStars Desktop Planetarium"
def setDependencies(self):
self.runtimeDependencies["libs/qt5/qtbase"] = None
self.runtimeDependencies["libs/qt5/qtdeclarative"] = None
self.runtimeDependencies["libs/qt5/qtquickcontrols"] = None
self.runtimeDependencies["libs/qt5/qtquickcontrols2"] = None
self.runtimeDependencies["libs/qt5/qtsvg"] = None
self.runtimeDependencies["libs/qt5/qtdatavis3d"] = None
self.runtimeDependencies["libs/qt5/qtwebsockets"] = None
self.runtimeDependencies["kde/frameworks/tier1/kconfig"] = None
self.runtimeDependencies["kde/frameworks/tier2/kdoctools"] = None
self.runtimeDependencies["kde/frameworks/tier2/kpackage"] = None
self.runtimeDependencies["kde/frameworks/tier1/kwidgetsaddons"] = None
self.runtimeDependencies["kde/frameworks/tier3/knewstuff"] = None
self.runtimeDependencies["kde/frameworks/tier1/kdbusaddons"] = None
self.runtimeDependencies["kde/frameworks/tier1/ki18n"] = None
self.runtimeDependencies["kde/frameworks/tier3/kinit"] = None
self.runtimeDependencies["kde/frameworks/tier2/kjobwidgets"] = None
self.runtimeDependencies["kde/frameworks/tier3/kio"] = None
self.runtimeDependencies["kde/frameworks/tier3/kxmlgui"] = None
self.runtimeDependencies["kde/frameworks/tier1/kplotting"] = None
self.runtimeDependencies["kde/frameworks/tier3/knotifications"] = None
self.runtimeDependencies["kde/frameworks/tier3/knotifyconfig"] = None
self.runtimeDependencies["libs/eigen3"] = None
self.runtimeDependencies["libs/cfitsio"] = None
self.runtimeDependencies["libs/wcslib"] = None
self.runtimeDependencies["libs/indiclient"] = None
self.runtimeDependencies["libs/libraw"] = None
self.runtimeDependencies["libs/gsl"] = None
self.runtimeDependencies["libs/stellarsolver"] = None
self.runtimeDependencies["qt-libs/qtkeychain"] = None
# Install proper theme
self.runtimeDependencies["kde/frameworks/tier1/breeze-icons"] = None
if not CraftCore.compiler.isMacOS:
self.runtimeDependencies["qt-libs/phonon-vlc"] = None
from Package.CMakePackageBase import *
class Package(CMakePackageBase):
def __init__(self):
CMakePackageBase.__init__(self)
self.ignoredPackages.append("binary/mysql")
self.ignoredPackages.append("libs/llvm-meta")
self.blacklist_file = ["blacklist.txt"]
def createPackage(self):
self.defines["executable"] = "bin\\kstars.exe"
#self.defines["setupname"] = "kstars-latest-win64.exe"
self.defines["icon"] = os.path.join(self.packageDir(), "kstars.ico")
# TODO: support dpi scaling
# TODO: use assets from src with the next release
#self.defines["icon_png"] = os.path.join(self.sourceDir(), "packaging", "windows", "assets", "Square150x150Logo.scale-100.png")
#self.defines["icon_png_44"] = os.path.join(self.sourceDir(), "packaging", "windows", "assets", "Square44x44Logo.scale-100.png")
#self.defines["icon_png_310x150"] = os.path.join(self.sourceDir(), "packaging", "windows", "assets", "Wide310x150Logo.scale-100.png")
#self.defines["icon_png_310x310"] = os.path.join(self.sourceDir(), "packaging", "windows", "assets", "Square310x310Logo.scale-100.png")
self.defines["icon_png"] = os.path.join(self.packageDir(), ".assets", "Square150x150Logo.scale-100.png")
self.defines["icon_png_44"] = os.path.join(self.packageDir(), ".assets", "Square44x44Logo.scale-100.png")
self.defines["icon_png_310x150"] = os.path.join(self.packageDir(), ".assets", "Wide310x150Logo.scale-100.png")
self.defines["icon_png_310x310"] = os.path.join(self.packageDir(), ".assets", "Square310x310Logo.scale-100.png")
if isinstance(self, AppxPackager):
self.defines["display_name"] = "KStars"
return TypePackager.createPackage(self)
|
const Engine = Matter.Engine;
const World = Matter.World;
const Bodies = Matter.Bodies;
const Constraint = Matter.Constraint;
var engine, world, backgroundImg;
var canvas, angle, tower, ground, cannon;
var balls = [];
var boats = [];
function preload() {
backgroundImg = loadImage("./assets/background.gif");
towerImage = loadImage("./assets/tower.png");
}
function setup() {
canvas = createCanvas(1200,600);
engine = Engine.create();
world = engine.world;
angle = -PI / 4;
ground = new Ground(0, height - 1, width * 2, 1);
tower = new Tower(150, 350, 160, 310);
cannon = new Cannon(180, 110, 100, 50, angle);
boat = new Boat(width, height - 100, 200, 200, -100);
}
function draw() {
background(189);
image(backgroundImg, 0, 0, width, height);
Engine.update(engine);
ground.display();
for (var i = 0; i < balls.length; i++) {
showCannonBalls(balls[i], i);
}
boat.display()
//Matter.Body.setVelocity(boat.body,{x:-1.0,y:0});
cannon.display();
tower.display();
showBoats();
}
function keyPressed() {
if (keyCode === DOWN_ARROW) {
var cannonBall = new CannonBall(cannon.x, cannon.y);
balls.push(cannonBall);
}
}
//function to show the ball
function showCannonBalls(ball, index) {
ball.display();
if (ball.body.position.x >= width || ball.body.position.y >= height - 50) {
Matter.World.remove(world, ball.body);
balls.splice(index, 1);
}
}
function keyReleased() {
if (keyCode === DOWN_ARROW) {
balls[balls.length - 1].shoot();
}
}
function showBoats() {
if (boats.length > 0) {
if (
boats.length < 4 &&
boats[boats.length - 1].body.position.x < width - 300
) {
var positions = [-130, -100, -120, -80];
var position = random(positions);
var boat = new Boat(width,height - 100, 200, 200, position);
boats.push(boat);
}
for (var i = 0; i < boats.length; i++) {
Matter.Body.setVelocity(boats[i].body, {
x: -0.9,
y: 0
});
boats[i].display();
}
} else {
var boat = new Boat(width, height - 100, 200, 200, -100);
boats.push(boat);
}
}
|
'use strict'
const path = require('path')
const defaultSettings = require('./src/settings.js')
const baseApi = process.env.VUE_APP_BASE_API
const baseUrl = process.env.VUE_APP_BASE_URL
function resolve(dir) {
return path.join(__dirname, dir)
}
const name = defaultSettings.title // page title
// If your port is set to 80,
// use administrator privileges to execute the command line.
// For example, Mac: sudo npm run
// You can change the port by the following methods:
// port = 9528 npm run dev OR npm run dev --port = 9528
const port = process.env.port || 8888 // dev port
// All configuration item explanations can be find in https://cli.vuejs.org/config/
module.exports = {
/**
* You will need to set publicPath if you plan to deploy your site under a sub path,
* for example GitHub Pages. If you plan to deploy your site to https://foo.github.io/bar/,
* then publicPath should be set to "/bar/".
* In most cases please use '/' !!!
* Detail: https://cli.vuejs.org/config/#publicpath
*/
publicPath: '/dptms-web',
outputDir: 'dist',
assetsDir: 'static',
productionSourceMap: false,
transpileDependencies: ['vue-echarts', 'resize-detector', 'vuex-persist'],
devServer: {
port: port,
open: false,
overlay: {
warnings: false,
errors: true
},
proxy: {
[baseApi]: {
target: baseUrl,
pathRewrite: { ['^' + baseApi]: '' }
}
}
},
configureWebpack: {
name: name,
resolve: {
alias: {
'@': resolve('src')
}
}
},
chainWebpack(config) {
config.plugins.delete('preload') // TODO: need test
config.plugins.delete('prefetch') // TODO: need test
// set svg-sprite-loader
config.module
.rule('svg')
.exclude.add(resolve('src/icons'))
.end()
config.module
.rule('icons')
.test(/\.svg$/)
.include.add(resolve('src/icons'))
.end()
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({
symbolId: 'icon-[name]'
})
.end()
// set preserveWhitespace
config.module
.rule('vue')
.use('vue-loader')
.loader('vue-loader')
.tap(options => {
options.compilerOptions.preserveWhitespace = true
return options
})
.end()
config
// https://webpack.js.org/configuration/devtool/#development
.when(process.env.NODE_ENV === 'development', config =>
config.devtool('cheap-module-source-map')
)
config.when(process.env.NODE_ENV !== 'development', config => {
config
.plugin('ScriptExtHtmlWebpackPlugin')
.after('html')
.use('script-ext-html-webpack-plugin', [
{
// `runtime` must same as runtimeChunk name. default is `runtime`
inline: /runtime\..*\.js$/
}
])
.end()
config.optimization.splitChunks({
chunks: 'all',
cacheGroups: {
libs: {
name: 'chunk-libs',
test: /[\\/]node_modules[\\/]/,
priority: 10,
chunks: 'initial' // only package third parties that are initially dependent
},
elementUI: {
name: 'chunk-elementUI', // split elementUI into a single package
priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
},
commons: {
name: 'chunk-commons',
test: resolve('src/components'), // can customize your rules
minChunks: 3, // minimum common number
priority: 5,
reuseExistingChunk: true
}
}
})
config.optimization.runtimeChunk('single')
})
}
}
|
const speechRecognition =
window.webkitSpeechRecognition ||
window.SpeechRecognition;
function startListening(){
const recog=new speechRecognition();
recog.start();
recog.onstart=console.log("Started Listening...");
recog.onresult=function(data){
handleResults(data);
};
}
function handleResults(data){
let text=data.results[0][0].transcript;
text=text.toLowerCase();
ProcessCommand(text);
}
function ProcessCommand(UserText){
if (UserText.includes("scramble")){
Speak("opening scramble game for you right away! expand your mind and improve your vocabulary");
window.open("https://buddies-hub-shm.herokuapp.com/scramble");
}
else if (UserText.includes("memory")){
Speak("opening memory game for you right away! give your 100 percent attention");
window.open("https://buddies-hub-shm.herokuapp.com/memory");
}
else if (UserText.includes("maths")){
Speak("opening maths game for you right away! Do your calculations well");
window.open("https://buddies-hub-shm.herokuapp.com/maths");
}
else if (UserText.includes("tic tac toe")){
Speak("opening tic tac toe game for you right away! Let's see if you can defeat the computer! good luck for that");
window.open("https://buddies-hub-shm.herokuapp.com/ticAI");
}
else if (UserText.includes("exit")){
Speak("going back");
window.open("https://buddies-hub-shm.herokuapp.com");
}
else if(UserText.includes("the")&& UserText.includes("time")){
Speak("The Time Is: " + getCurentTime());
}
}
function getCurentTime(){
const date=new Date();
let hour=date.getHours();
let minutes=date.getMinutes();
return `${hour} ${minutes}`;
}
function Speak(TEXT){
const utter=new SpeechSynthesisUtterance();
utter.text=TEXT;
window.speechSynthesis.speak(utter);
}
microphoneButton.addEventListener("click",startListening);
|
//@ sourceURL=pages/customize.queryview.js
//闭包执行一个立即定义的匿名函数
!function (factory) {
//factory是一个函数,下面的koExports就是他的参数
// Support three module loading scenarios
if (typeof require === 'function' && typeof exports === 'object' && typeof module === 'object') {
// [1] CommonJS/Node.js
// [1] 支持在module.exports.abc,或者直接exports.abc
var target = module['exports'] || exports; // module.exports is for Node.js
factory(target);
} else if (typeof define === 'function' && define['amd']) {
// [2] AMD anonymous module
// [2] AMD 规范
//define(['exports'],function(exports){
// exports.abc = function(){}
//});
define(['jquery'], factory);
} else {
// [3] No module loader (plain <script> tag) - put directly in global namespace
factory(window['jQuery']);
}
}(function ($) {
});
//获取表单列表
function getFormsList(entityid, $context, isRequire, callback) {
//加载forms列表
var postParams = {
type: 'forms' + entityid,
data: { entityid: entityid,loaddata:true }
}
Xms.Web.PageCache('workflow', '/customize/systemform/index', postParams, function (res) {
var resItems = res.content;
if (resItems && resItems.items) {
var _html = [];
if (isRequire == false) {
_html.push('<option data-formid="" data-solutionid="" value=""></option>');
}
$.each(resItems.items, function (i, n) {
_html.push('<option data-formid="' + n.systemformid + '" data-solutionid="' + n.solutionid + '" value="' + n.systemformid + '">' + n.name + '</option>');
});
$context.html(_html.join(''));
callback && callback();
}
}, true);
}
var AggregateType = { 'datetime': ['Max', 'Min'], 'int': ['Sum', 'Avg', 'Max', 'Min'], 'float': ['Sum', 'Avg', 'Max', 'Min'], 'money': ['Sum', 'Avg', 'Max', 'Min'] };
//打开窗口时获取是否需要统计
function getAggregateConfig(type) {
var $columnstatistical = $('#columnstatistical');
var attrtype = AggregateType[type];
if (!attrtype) {
$columnstatistical.parent().hide();
return false;
}
$columnstatistical.parent().show();
$columnstatistical.children().hide();
$columnstatistical.children('option').each(function (i, n) {
$.each(attrtype, function (ii, nn) {
if (nn == n.value) {
$(n).show();
}
});
});
$columnstatistical.children('option:first').show();
}
//打开窗口时统计de值
function setAggregateVal(name) {
var $columnstatistical = $('#columnstatistical'), $AggregateConfig = $('#AggregateConfig');
var $this = $('.selected:first', '#views');
var relationship = $this.attr('data-relationship');
var _value = $AggregateConfig.val(), tempArr = [], res = null;
if (_value != '') {
tempArr = JSON.parse(_value);
}
if (relationship) {
name = relationship.toLowerCase() + '_' + name;
}
$.each(tempArr, function (key, item) {
if (item['AttributeName'].toLowerCase() == name.toLowerCase()) {
res = item['AggregateType'];
return false
}
});
console.log(res);
$columnstatistical.children('option:first').prop('selected', true);
if (res) {
$columnstatistical.val(res);
}
}
//关闭窗口时设置统计de值
function setAggregateConfig(name, value) {
var $AggregateConfig = $('#AggregateConfig'), res = '';
var $this = $('.selected:first', '#views');
var relationship = $this.attr('data-relationship');
_value = $AggregateConfig.val(), tempArr = [];
var _flag = false;
if (relationship) {
name = relationship.toLowerCase() + '_' + name;
}
if (_value != '') {
tempArr = JSON.parse(_value);
if (value != '') {
$.each(tempArr, function (key, item) {
if (item['AttributeName'].toLowerCase() == name.toLowerCase()) {
item['AggregateType'] = value;
_flag = true;
return false
}
});
if (_flag == false) {
var _obj = {};
_obj['AttributeName'] = name;
_obj['AggregateType'] = value;
tempArr.push(_obj);
}
} else {
var temp = null;
$.each(tempArr, function (key, item) {
if (item['AttributeName'].toLowerCase() == name.toLowerCase()) {
temp = key;
_flag = true;
return false
}
});
if (_flag == true) {
tempArr.splice(temp, 1);
}
}
} else {
if (value != '') {
var _obj = {};
_obj['AttributeName'] = name;
_obj['AggregateType'] = value;
tempArr.push(_obj);
}
}
console.log(tempArr);
res = JSON.stringify(tempArr);
if (res == '[]') {
res = '';
}
$AggregateConfig.val(res);
}
function renderModityByData(data, type) {
var _html = [];
$.each(data, function (i, n) {
var flag = false;
n['rolesid'] = n['roleid'];
_html.push('<option class="list-group-item" data-entityname="type" value="' + n['rolesid'] + '" data-value="' + n['rolesid'] + '">');
_html.push(n.name);
_html.push('</option>');
});
return _html.join('');
}
function settableheaderWidth() {
var editFormTable = $("#editFormTable");
var ths = editFormTable.find('th.tableHeaderItem');
var widths = 0;
ths.each(function (key, item) {
var _w = $(item).attr('data-width') * 1;
widths += _w;
});
$('#tableheaderWidth').val(widths);
}
function resetTableWidth() {
settableheaderWidth();
var tableW = $('#tableheaderWidth').val() * 1;
var wrapW = $('#tableReWidth').width();//
console.log(tableW, wrapW);
if (tableW >= wrapW) {
$("#editFormTable").width(tableW)
} else {
$("#editFormTable").width('auto');
}
}
function resizeTableHead() {
//
$("#editFormTable").tableHdResize({
showTips: true
, onResizeEnd: function (th) {
var w = th.outerWidth();
th.attr("data-width", w);
$('#columnwidth').val(w);
resetTableWidth();
saveGridConfig();
}
, resetTableWidth: false
});
}
//判断字段是否已加入列表
function attributeIsExists(entityName, attrName, relationship) {
entityName = entityName.toLowerCase();
attrName = attrName.toLowerCase();
//是否为关联实体字段
if (relationship) {//(entityName != QueryObject.EntityName.toLowerCase()) {
//是否已存在
var le = null;
$(QueryObject.LinkEntities).each(function (ii, nn) {
if (nn.LinkToEntityName.toLowerCase() == entityName) {
le = nn;
return false;
}
});
if (le != null) {
if (~$.inArray(attrName, le.Columns.Columns)) {
if (relationship == le.EntityAlias) {
return true;
}
}
}
}
else {
if (~$.inArray(attrName, QueryObject.ColumnSet.Columns)) {
return true;
}
}
return false;
}
//加载实体,两个字段同时引用同一实体时?
function loadEntities() {
var dfd = $.Deferred();
var entityid = $('#EntityId').val();
Xms.Schema.GetEntityRelations(entityid, null, function (data) {
if (!data) return;
var _htmls = [];
$(data).each(function (i, n) {
//
var _html = '<option data-relationship="' + n.name + '" data-entityid="' + n.entityid + '" data-referencingattributelocalizedname="' + n.referencingattributelocalizedname + '" data-referencingattributename="' + n.referencingattributename + '" value="' + n.referencedentityid + '">' + n.referencingattributelocalizedname + '(' + n.referencedentitylocalizedname + ')' + '</option>';
_htmls.push(_html);
});
var entityhtml = $('#entitydefaultoption').html();
$('#entities').html(entityhtml + _htmls.join(''));
// console.log('_html',_html);
// Xms.Web.SelectedValue($('#entities'), entityid);
$('#entities').find('option:first').prop('selected', true);
dfd.resolve();
});
return dfd.promise();
}
var rowcommondAttributes = null;
//加载字段
function loadAttributes(callback) {
var entityid = Xms.Web.SelectedValue($('#entities')) || $('#EntityId').val();
var relationship = $('#entities').find('option:selected').attr('data-relationship') || '';
var referencingattributelocalizedname = $('#entities').find('option:selected').attr('data-referencingattributelocalizedname') || '';
var _html = new Array();
Xms.Schema.GetAttributesByEntityId(entityid, function (data) {
if (!data) return;
console.log('data.content.items', data);
if (rowcommondAttributes == null) {
rowcommondAttributes = data;
}
var attributename = $('#entities option:selected').attr('data-referencingattributename')
$(data).each(function (i, n) {
//console.log(n.entityname, n.name, attributeIsExists(n.entityname, n.name));
if (attributeIsExists(n.entityname, n.name, relationship) == false) {
_html.push('<li class="mutil-list-item" data-relationship="' + relationship + '" data-referencingattributelocalizedname="' + referencingattributelocalizedname + '" data-type="' + n.attributetypename + '" data-referencdentityname="' + n.referencedentityname + '" data-name="' + n.name + '" data-entityname="' + n.entityname + '" data-referencdattributename="' + (attributename || '') + '" data-entitylocalizedname="' + n.entitylocalizedname + '" data-referencedentityid="' + n.referencedentityid + '" data-attributesid="' + (n.attributeid || "") + '" data-localizedname="' + n.localizedname + '" data-optionsetid="' + (n.optionsetid || "") + '">');
_html.push('<span class="glyphicon glyphicon-screenshot"></span>');
_html.push('<span class="th-label">' + n.localizedname + '</span>');
_html.push('</li>');
}
});
$('#attributes').html(_html.join(''));
callback && callback();
});
}
//加载过滤条件字段选项
function loadFilterAttributes() {
var entityid = Xms.Web.SelectedValue($('#entities')) || $('#EntityId').val();
var _mainOptions = new Array(), _relatedOptions = new Array();
Xms.Schema.GetAttributesByEntityId(entityid, function (data) {
if (!data) return;
_mainOptions.push('<optgroup label="字段">');
console.log(data)
$(data).each(function (i, n) {
_mainOptions.push('<option value="' + n.name + '" data-entityid="' + n.entityid + '" data-entityname="' + n.entityname + '" data-type="' + n.attributetypename + '">' + n.localizedname + '</option>');
});
_mainOptions.push('</optgroup>');
Xms.Schema.GetEntityRelations(entityid, null, function (data) {
if (!data) {
$('#filternamelist').append($(_mainOptions.join('') + _relatedOptions.join('')));
$('#filterConditions > tfoot > tr:first').find('select[name=filtername]').append($(_mainOptions.join('') + _relatedOptions.join('')));
return;
}
Relationships = data;
_relatedOptions.push('<optgroup label="关联">');
$(data).each(function (ii, nn) {
_relatedOptions.push('<option value="' + nn.referencedattributename + '" data-entityname="' + nn.referencedentityname + '" data-type="' + nn.referencedattributetypename + '">' + nn.referencingattributelocalizedname + '(' + nn.referencedentitylocalizedname + ')' + '</option>');
});
_relatedOptions.push('</optgroup>');
$('#filternamelist').append($(_mainOptions.join('') + _relatedOptions.join('')));
$('#filterConditions > tfoot > tr:first').find('select[name=filtername]').append($(_mainOptions.join('') + _relatedOptions.join('')));
});
});
}
//加载操作符
function loadOperators(target, type) {
target.empty();
var operators = Xms.Fetch.ConditionOperators[type];
//操作符
var op = new Array();
$(operators).each(function (i, n) {
op.push('<option data-value="' + n[0] + '" value="' + n[1] + '">' + n[2] + '</option>');
});
target.append(op.join(''));
}
function getDdlItems(datatype) {
var items = [];
if (datatype == 'picklist') {
items = [{ value: 0, text: '已提交' }, { value: 1, text: '审核中' }];
} else if (datatype == 'state') {
items = [{ value: 0, text: '否' }, { value: 1, text: '是' }];
} else if (datatype == 'bit') {
items = [{ value: 0, text: '否' }, { value: 1, text: '是' }];
}
return items;
}
//字段选择后更改操作符
function onChangeAttribute(e) {
var $this = $(e);
var target = $this.parents('tr').find('select[name=filteroperator]');
var type = $this.find('option:selected').attr('data-type');
loadOperators(target, type);
target.change();
}
//列移动排序
function moveColumn(direction) {
var $this = $("#views").find('.selected');
if (direction == 'before' && $this.prev().length > 0) {
$this.insertBefore($this.prev());
}
else if (direction == 'after' && $this.next().length > 0) {
$this.insertAfter($this.next());
}
saveGridConfig();
}
//删除列
function removeColumn() {
var $this = $("#views").find('.selected');
var index = $this.index();
console.log(index);
var delSelf = $("#views").find('th:eq(' + index + ')');
var delOneSort = false;
var attrname = $this.attr('data-name');
var attrrelashipname = $this.attr('data-relationship');
if ($('#views').find('th').length > 1) {
if (delSelf.hasClass('shadow')) {
index = -1;
}
//还原左边列表start
var attrEntities = $('#entities').find('option:selected');
var FRelationship = attrEntities.attr('data-relationship').toLowerCase();
var TRelationship = delSelf.attr('data-relationship').toLowerCase();
for (var i = 0; i < AttributesList.length; i++) {
if (AttributesList[i].name.toLowerCase() == delSelf.attr('data-name').toLowerCase() && AttributesList[i].relationship.toLowerCase() == TRelationship.toLowerCase()) {
if (FRelationship == TRelationship) {
$(AttributesList[i].html).find('span').removeClass('hide');
$('#attributes').append(AttributesList[i].html);
}
AttributesList.splice(i, 1);
break;
}
}
//还原左边列表end
//排序设置start
if (typeof delSelf.attr('data-sorttype') != 'undefined' && typeof delSelf.attr('data-sortnum') != 'undefined' && delSelf.attr('data-sortnum') == 'one') {
delOneSort = true;
}
//排序设置end
delSelf.remove();
if (!$("#views").parents('table:first').find('tr').find('td:eq(' + index + ')').hasClass('shadow')) {
$("#views").parents('table:first').find('tr').find('td:eq(' + index + ')').remove();
}
saveGridConfig();
if ($('#views').find('th').length == 1) {
$("#views").parents('table:first').find('.shadow').removeClass('hide');
}
else {
//如果第一个排序被删除了,默认第一个排序
if (delOneSort) {
$('#views').find('th:eq(1)').attr({ 'data-sorttype': 'ascending', 'data-sortnum': 'one' });
}
}
}
if (attrrelashipname && attrrelashipname != "") {
attrname = attrrelashipname.toLowerCase() + '_' + attrname;
}
setAggregateConfig(attrname, '')
resetTableWidth();
saveGridConfig();
// addAttributeToInput();
}
//编辑列参数
function editColumnParams() {
var $this = $("#views").find('.selected');
var width = $this.attr('data-width');
var visibled = $this.attr('data-visibled');
var type = $this.attr('data-type');
var _name = $this.attr('data-name');
var attributename = $this.attr('data-localizedname');
var label = $this.attr('data-label') || $this.attr('data-localizedname');
//var sorttype = $this.attr('data-sorttype');
$('#columnModal').find('input[name=columnwidth]').val(width);
$('#columnModal').find('input[name=columnattributename]').val(attributename);
$('#columnModal').find('input[name=columnlabel]').val(label).select();
$('#columnModal').find('input[name=columnvisibled]').prop('checked', visibled);
getAggregateConfig(type);
setAggregateVal(_name);
//Xms.Web.SelectedValue($('#columnModal').find('select[name=sorttype]'), sorttype);
//$('#columnModal').modal({
// keyboard: true
//})
$('#columnModal').addClass('in');
$('#existsButtons').removeClass('in');
}
//保存列参数设置
function saveColumnParams() {
var $this = $("#views").find('.selected');
var $columnstatistical = $('#columnstatistical');
var width = $('#columnModal').find('input[name=columnwidth]').val();
var visibled = $('#columnModal').find('input[name=columnvisibled]').prop('checked');
var _name = $this.attr('data-name');
var type = $this.attr('data-type');
var label = $('#columnModal').find('input[name=columnlabel]').val();
var _assValue = $columnstatistical.val();
//var sorttype = Xms.Web.SelectedValue($('#columnModal').find('select[name=sorttype]'));
//$this.attr('data-sorttype', sorttype);
$this.attr('data-width', width);
$this.attr('data-label', label);
$this.find('.th-label').text(label);
$this.attr('data-visibled', visibled);
$this.attr('style', 'width:' + width + 'px;');
$('#columnModal').modal('hide');
$("#views").parents('table').removeClass('table');
//reset form
// $('#columnModal').find('input[name=columnwidth]').val('');
$('#columnModal').find('input[name=columnvisibled]').prop('checked', true);
Xms.Web.SelectedValue($('#columnModal').find('select[name=sorttype]'), '');
var attrtype = AggregateType[type];
if (attrtype) {
setAggregateConfig(_name, _assValue);
}
saveGridConfig();
$('#columnModal').removeClass('in');
}
//保存列表布局
function saveGridConfig() {
var $layout = $('#LayoutConfig');
try {
if ($layout.val() != "") {
var grid = JSON.parse($layout.val());
// if (!grid.SortColumns) {
//防止新增实体后默认的数据为小写
if (grid.rows) {
delete grid.rows;
}
grid.Rows = [];
// }
//if (!grid.Rows) {
grid.Rows = [];
//}
} else {
var grid = { SortColumns: [], Rows: [] };
}
} catch (e) {
console.error(e);
}
var sortColumn = { Name: '', SortAscending: false };
var row = { Name: '', Id: '', Cells: [] };
var cell = { Name: '', EntityName: '', IsHidden: false, IsSortable: false, Width: 0 };
var sortColumns = new Array(), cells = new Array(), columns = new Array(), orders = new Array();
QueryObject.LinkEntities = []; // 保存已添加到表格头的字段
$("#views").find('th:not(.shadow)').each(function (i, n) {
var column = $(n);
var name = column.attr('data-name').toLowerCase();
var entityname = column.attr('data-entityname').toLowerCase();
var visibled = column.attr('data-visibled');
var sorttype = column.attr('data-sorttype').toLowerCase();
var width = column.attr('data-width');
var label = column.attr('data-label');
var relationship = column.attr('data-relationship').toLowerCase();
//关联实体的字段名
//var referencingattributename = column.attr('data-referencingattributename')? column.attr('data-referencingattributename').toLowerCase():'';
//是否为关联实体字段
if (relationship) {//如果为关联实体
//是否已存在
var le = null;
$(QueryObject.LinkEntities).each(function (ii, nn) {
if (nn.LinkToEntityName.toLowerCase() == entityname && nn.EntityAlias == relationship) {
le = nn;
return false;
}
});
if (le != null) {
if ($.inArray(name, le.Columns.Columns) < 0) {//列名不存在
le.Columns.Columns.push(name);
}
name = le.EntityAlias + '.' + name;//cell's name
}
else {
le = new LinkEntity();//生成关联实体别名
le.LinkToEntityName = entityname;
le.EntityAlias = relationship || entityname + '_' + Xms.Utility.Guid.NewGuid().ToString('N');
le.LinkToAttributeName = entityname + 'id';
le.LinkFromEntityName = QueryObject.EntityName;
$(Relationships).each(function (ii, nn) {//from.createdby => to.userid
if (nn.name.toLowerCase() == relationship && nn.referencedattributename.toLowerCase() == entityname + 'id') {
le.LinkFromAttributeName = nn.referencingattributename.toLowerCase();
return false;
}
});
le.Columns.Columns.push(name);
QueryObject.LinkEntities.push(le);
name = le.EntityAlias + '.' + name;//cell's name
}
}
else { columns.push(name); }
cell = cell.constructor();//js对象为引用类型,所以需要NEW一个对象
cell.Name = name;
cell.EntityName = entityname;
cell.IsHidden = !visibled;
cell.IsSortable = sorttype != '';
cell.Width = width;
cell.Label = label || null;
cells.push(cell);
if (sorttype != '') {
sortColumn = sortColumn.constructor();
sortColumn.Name = name;
sortColumn.SortAscending = sorttype == 'ascending';
sortColumns.push(sortColumn);
var ord = { AttributeName: name, OrderType: sorttype == 'ascending' ? 0 : 1 };
orders.push(ord);
}
});
row.Cells = cells;
grid.SortColumns = sortColumns;
grid.Rows.push(row);
var $jslibrary = $('#jslibrary');
if ($jslibrary.val()) {
var jslibval = $jslibrary.val();
var jsarray = jslibval.split(',');
grid.ClientResources = [];
$.each(jsarray, function (i,n) {
grid.ClientResources.push(n);
});
} else {
grid.ClientResources = '';
}
//grid.RowCommand = saveRowCommandValue();
console.log('提交的grid的数据', grid);
$('#LayoutConfig').val(JSON.stringify(grid));
QueryObject.ColumnSet.Columns = columns;
//QueryObject.Orders = orders;
UpdateQueryObjectOrder();
console.log(QueryObject.LinkEntities);
QueryObject.LinkEntities = conforLink(QueryObject.LinkEntities);//合并相关实体
$('#FetchConfig').val(JSON.stringify(QueryObject));
}
//增加一行过滤条件
function addCondition(e) {
var newRow = $('#filterConditions > tfoot > tr:first').clone(true).removeClass('hide');
var fname = Xms.Web.SelectedValue($(e));
if (fname != null) {
Xms.Web.SelectedValue(newRow.find('select[name=filtername]'), fname);
}
onChangeAttribute(newRow.find('select[name=filtername]').get(0));
$('#filterConditions > tbody').append(newRow);
$('#filterConditions > tbody').find('tr:last').find('select[name=filteroperator]').change();
Xms.Web.SelectedValue($(e), '');
}
//清空过滤条件
function clearConditions() {
Xms.Web.Confirm('确认', '确定清空所有过滤条件?', function () {
$('#filterConditions tbody tr:visible').remove();
});
}
//过滤条件组合
function groupConditions(logical) {
var rows = $('#filterConditions tbody tr.active');
if (rows.length < 2) {
Xms.Web.Alert(false, '请选择2个条件以上');
return;
}
//检测
//rows.each(function (i, n) {
// if (row.is('.filterrow')) {
// //如果是组合内,则更改组合符号
// if (row.parents('tr.filtergroup').first()) {
// row.parents('tr.filtergroup').first().find('td:first').find('.dropdown-menu > li:eq(1)').trigger('click');
// }
// }
// else if (row.is('.filtergroup')) {
// removenode.push(row.parents('tr.filterrow'));
// var node = $('<tr class="filterrow"><td colspan="4"><table class="table table-condensed"><tbody></tbody></table></td></tr>');
// node.find('tbody').append(row);
// parent.find('#' + grouplistid).append(node);
// }
// //如果两个选项跨组合,或跨实体,则取消
// //...
//});
var container = new Array();
var grouplistid = 'grouplist_' + Math.round(new Date().getTime() / 1000);
var insertObj, pos;
if (rows.first().prev().length == 0) {//第一行
if (rows.last().next().length > 0) {
insertObj = rows.last().next();
pos = 'before';
}
else {
insertObj = rows.first().parent();
pos = 'append';
}
}
else {
insertObj = rows.first().prev();
pos = 'after';
}
container.push('<tr class="filterrow"><td colspan="4">');
container.push('<table class="table table-condensed"><tbody><tr class="filtergroup" data-logical="' + logical + '" data-groupid="' + grouplistid + '">');
container.push('<td class="bg-info text-primary" style="vertical-align:middle;">');
container.push('<div class="dropdown"><input type="checkbox" name="filtergroup" />');
container.push('<a class="dropdown-toggle" data-toggle="dropdown" href="#"><span name="logicaltext">' + (logical == 'and' ? '并且' : '或者') + '</span> <span class="caret"></span></a>');
container.push('<ul class="dropdown-menu">');
container.push('<li><a class="btn-link" onclick="javascript:cancelGroup(this,\'' + grouplistid + '\')">取消组合</a></li>');
container.push('<li><a class="btn-link" onclick="javascript:changeGroupLogical(this)">转换为"' + (logical != 'and' ? '并且' : '或者') + '"组合</a></li>');
container.push('</ul></div>');
container.push('</td>');
container.push('<td colspan="3">');
container.push('<table class="table table-condensed"><tbody name="grouplist" id="' + grouplistid + '">');
/********放置条件********/
container.push('</tbody></table>');
container.push('</td>');
container.push('</tr>');
container.push('</tbody></table>');
container.push('</td></tr>');
var parent = $(container.join('\n'));
var removenode = new Array();
rows.each(function (i, n) {
var row = $(n);
row.removeClass('active').find(':checkbox').prop('checked', false);
row.find('tr').removeClass('active');
if (row.is('.filterrow')) {
parent.find('#' + grouplistid).append(row.clone(true));
//if (row.parents('tr.filterrow').first()) removenode.push(row.parents('tr.filterrow').first());
row.remove();
}
else if (row.is('.filtergroup')) {
removenode.push(row.parents('tr.filterrow:first'));
var node = $('<tr class="filterrow"><td colspan="4"><table class="table table-condensed"><tbody></tbody></table></td></tr>');
node.find('tbody').empty().append(row.clone(true));
parent.find('#' + grouplistid).append(node);
row.remove();
}
});
console.log(pos);
if (insertObj.is('tr')) {
if (pos == 'before') insertObj.before(parent);
else insertObj.after(parent);
//insertObj.remove();
$(removenode).each(function (i, n) { $(n).remove(); });
}
else {
insertObj.append(parent);
//insertObj.find('.filterrow:first').remove();
}
////$(removenode).each(function (i, n) { $(n).remove(); });
}
//设置组合逻辑
function changeGroupLogical(e) {
var logical = $(e).parents('table').first().find('[data-logical]').attr('data-logical');
logical = logical == 'and' ? 'or' : 'and';
$(e).parents('table').first().find('[data-logical]').attr('data-logical', logical)
$(e).parents('td').first().find('[name=logicaltext]').text(logical == 'and' ? '并且' : '或者');
$(e).text('转换为"' + (logical != 'and' ? '并且' : '或者') + '"组合');
}
//取消组合
function cancelGroup(e, groupid) {
var g = $(e).parents('td').first();
var rows = $('#' + groupid).children();
$('#filterConditions tr.filtergroup[data-groupid=' + groupid + ']').replaceWith(rows);
g.remove();
}
//保存过滤条件
function saveFilter() {
var mainGroup = $('.form-group[data-type="Main"]').children('.andorGroup,.pilot-row').not('[data-relevant=true]');
QueryObject.Criteria = eachGroup(mainGroup, true);
var relaveList = $('.form-group[data-type="Main"]').children('.relevant-box');
var rItem = eachRelevant(relaveList, EntityName);
for (var j = QueryObject.LinkEntities.length - 1; 0 <= j; j--) {
if (QueryObject.LinkEntities[j].Columns.Columns.length > 0) {
QueryObject.LinkEntities[j].LinkCriteria = new Xms.Fetch.FilterExpression(Xms.Fetch.LogicalOperator.And);
QueryObject.LinkEntities[j].LinkEntities = [];
} else {
QueryObject.LinkEntities.splice(j, 1);
}
}
for (var i = 0; i < rItem.length; i++) {
QueryObject.LinkEntities.push(rItem[i]);
}
QueryObject.LinkEntities = conforLink(QueryObject.LinkEntities);//合并相关实体
console.log("filerResult", QueryObject);
$('#FetchConfig').val(JSON.stringify(QueryObject));
$('#filterModal').modal('hide');
}
function conforLink(linkEntity) {
var oldItem = linkEntity;
var newItem = [];
for (var i = oldItem.length - 1; 0 <= i; i--) {
if (oldItem[i].Columns.Columns.length > 0) {
newItem.push(oldItem[i]);
oldItem.splice(i, 1);
}
}
for (var j = 0; j < newItem.length; j++) {
for (var m = oldItem.length - 1; 0 <= m; m--) {
if (newItem[j].EntityAlias.toLowerCase() == oldItem[m].EntityAlias.toLowerCase()) {
newItem[j].LinkCriteria = oldItem[m].LinkCriteria;
newItem[j].LinkEntities = oldItem[m].LinkEntities;
oldItem.splice(m, 1);
}
}
}
for (var k = oldItem.length - 1; 0 <= k; k--) {
for (var p = 0; p < newItem.length; p++) {
if (newItem[p].EntityAlias.toLowerCase() == oldItem[k].EntityAlias.toLowerCase()) {
newItem.splice(p, 1);
}
}
newItem.push(oldItem[k]);
}
return newItem;
}
function openFilter() {
if ($('#pliot-page1').length > 0) {
$('#filterModal').modal('show');
var isload = $('#pliot-page1').attr('data-load');
if (typeof isload == 'undefined') {
$('#pliot-page1').attr('data-load', false);
isload = $('#pliot-page1').attr('data-load');
}
if (isload == false || isload == 'false') {
initFilter(FetchConfig, $('#pliot-page1').find('div[data-type="Main"]'));
$('#pliot-page1').attr('data-load', true);
}
}
else {
Xms.Web.Alert(false, '请等待加载完毕后再点击');
}
}
//排序设置start
function openSortModal() {
if (AttributesList.length == 0) {
Xms.Web.Alert(false, "没有可排序字段");
return false;
}
var target = $('#sortModal');
target.modal('show');
var sort1 = target.find('#sortparm1');
var sort2 = target.find('#sortparm2');
var sorttype1 = target.find('input[name="sorttype1"]');
var sorttype2 = target.find('input[name="sorttype2"]');
sort1.html('');
sort2.html('');
sort2.append('<option value="">选择</option>');
console.log('AttributesList', AttributesList);
for (var i = 0; i < AttributesList.length; i++) {
var _html = '<option data-relationship="' + AttributesList[i].relationship + '" data-name="' + AttributesList[i].name + '">' + AttributesList[i].text + '</option>';
sort1.append(_html);
sort2.append(_html);
}
var oneChoose = $('#views').find('th[data-sortnum="one"]');
var twoChoose = $('#views').find('th[data-sortnum="two"]');
if (oneChoose.length > 0) {
console.log(oneChoose.attr('data-name'))
var relationship = oneChoose.attr('data-relationship');
if (relationship && relationship != "") {
sort1.find('option[data-relationship="' + oneChoose.attr('data-relationship') + '"][data-name="' + oneChoose.attr('data-name') + '"]').attr('selected', 'selected');
} else {
sort1.find('option[data-name="' + oneChoose.attr('data-name') + '"]').attr('selected', 'selected');
}
target.find('input[name="sorttype1"][value="' + oneChoose.attr('data-sorttype').toLowerCase() + '"]').attr('checked', 'checked');
}
if (twoChoose.length > 0) {
console.log(twoChoose.attr('data-name'))
var relationship = oneChoose.attr('data-relationship');
if (relationship && relationship != "") {
sort2.find('option[data-relationship="' + twoChoose.attr('data-relationship') + '"][data-name="' + twoChoose.attr('data-name') + '"]').attr('selected', 'selected');
} else {
sort2.find('option[data-name="' + twoChoose.attr('data-name') + '"]').attr('selected', 'selected');
}
target.find('input[name="sorttype2"][value="' + twoChoose.attr('data-sorttype').toLowerCase() + '"]').attr('checked', 'checked');
}
changeSort(sort1);
changeSort(sort2);
}
function changeSort(e) {
var target = $('#sortModal');
//target.find('option').removeClass('hide');
var choose = $(e).find('option:selected');
var sibling = $(e).parents('div.form-group').siblings().find('select');
var cRelationship = choose.attr('data-relationship');
var cName = choose.attr('data-name');
sibling.find('option').removeClass('hide');
sibling.find('option[data-relationship="' + cRelationship + '"][data-name="' + cName + '"]').addClass('hide');
}
function saveSortParams() {
var target = $('#sortModal');
var sort1 = target.find('#sortparm1');
var sort2 = target.find('#sortparm2');
$('#views').find('th').attr({ 'data-sorttype': '', 'data-sortnum': '' });
target.find('option:selected').each(function (i, n) {
var relationship = $(n).attr('data-relationship');
var name = $(n).attr('data-name');
var sorttype = $(n).parent('select').parent('div').next().find('input:checked').val();
var label = $('#views').find('th[data-relationship="' + relationship + '"][data-name="' + name + '"]');
label.attr('data-sorttype', sorttype);
if ($(n).parent('select').attr('id') == 'sortparm1') {
label.attr('data-sortnum', "one");
}
else {
label.attr('data-sortnum', "two");
}
});
saveGridConfig();
target.modal('hide');
}
function UpdateQueryObjectOrder() {
var target = $('#views');
var oneSort = target.find('th[data-sortnum="one"]');
var twoSort = target.find('th[data-sortnum="two"]');
var sortColumn = { Name: '', SortAscending: false };
var orders = new Array();
var sortColumns = new Array();
if (oneSort.length > 0) {
//保存第一个筛选
var onename = oneSort.attr('data-name');
var onesorttype = oneSort.attr('data-sorttype');
var onerelationship = oneSort.attr('data-relationship');
onesorttype = onesorttype && onesorttype.toLowerCase();
sortColumn = sortColumn.constructor();
sortColumn.Name = onename;
sortColumn.SortAscending = onesorttype == 'ascending';
sortColumns.push(sortColumn);
var oneord = '';
if (onerelationship != '') {
oneord = { AttributeName: onerelationship + '.' + onename, OrderType: onesorttype == 'ascending' ? 'Ascending' : 'Descending' };
}
else {
oneord = { AttributeName: onename, OrderType: onesorttype == 'ascending' ? 'Ascending' : 'Descending' };
}
orders.push(oneord);
if (twoSort.length > 0) {
//保存第二个筛选
var twoname = twoSort.attr('data-name');
var twosorttype = twoSort.attr('data-sorttype');
var tworelationship = twoSort.attr('data-relationship');
tworelationship = tworelationship && tworelationship.toLowerCase();
sortColumn = sortColumn.constructor();
sortColumn.Name = twoname;
sortColumn.SortAscending = twosorttype == 'ascending';
sortColumns.push(sortColumn);
var twoord = '';
if (tworelationship != '') {
twoord = { AttributeName: tworelationship + '.' + twoname, OrderType: twosorttype == 'ascending' ? 'Ascending' : 'Descending' };
}
else {
twoord = { AttributeName: twoname, OrderType: twosorttype == 'ascending' ? 'Ascending' : 'Descending' };
}
orders.push(twoord);
}
}
QueryObject.Orders = orders;
}
//排序设置END
function LinkEntity() {
var self = new Object();
self.LinkFromEntityName = '';
self.LinkFromAttributeName = '';
self.LinkToEntityName = '';
self.LinkToAttributeName = '';
self.LinkCriteria = new Xms.Fetch.FilterExpression(Xms.Fetch.LogicalOperator.And);
self.JoinOperator = 1;
self.EntityAlias = '';
self.FromEntityAlias = '';
self.Columns = { Columns: [] };
return self;
}
function FilterExpression() {
var self = new Object();
self.FilterOperator = 'and';
self.Conditions = new Array();
self.Filters = new Array();
return self;
}
function ConditionExpression() {
var self = new Object();
self.AttributeName = '';
self.Operator = '';
self.Values = new Array();
return self;
}
function Save(type) {
savetype = type;
$("#savetype").val(savetype);
$("#editform").submit();
}
function Save(type) {
savetype = type;
if ($('#isShowTab').length > 0) {
if ($('#isShowTab').prop('checked')) {
var _rowConfig = $('#LayoutConfig').val();
var _rowObj = JSON.parse(_rowConfig);
_rowObj.ExtEntityTabs = getExtEntityInfo();
$('#LayoutConfig').val(JSON.stringify(_rowObj));
} else {
var _rowConfig = $('#LayoutConfig').val();
var _rowObj = JSON.parse(_rowConfig);
delete _rowObj.ExtEntityTabs;
$('#LayoutConfig').val(JSON.stringify(_rowObj));
}
}
$("#savetype").val(savetype);
$("#editform").submit();
}
function Reset() {
$("#editform").reset();
}
//过滤条件设置--行事件设置
//禁用输入框
var disabledArr = ['Last7Days', 'LastWeek', 'LastMonth', 'LastYear', 'LastYear', 'NextWeek', 'NextMonth', 'NextYear', 'ThisWeek', 'ThisMonth', 'ThisYear', 'Today', 'Tomorrow', 'Yesterday'];
//显示时间控件
var showDatepicker = ['Equal', 'NotEqual', 'GreaterThan', 'LessThan', 'GreaterEqual', 'LessEqual', 'OnOrAfter', 'OnOrBefore'];
//无需查找按钮
var noFindButton = ['BeginsWith', 'DoesNotBeginWith', 'EndsWith', 'DoesNotEndWith', 'Like', 'NotLike'];
//需要下拉 多选
var moreSelect = [];
//包含和不包含
var includeNull = ['NotNull', 'Null'];
//function initRowCommandSettings(){
// var $rowcommand = $('#rowcommand');
// var rowFirst = $rowcommand.find('.well:first');
// rowFirst.find('.EventType');
//}
function loadFilterOperators(input, type, opts) {
//操作符
if (type == 'status') {
type = 'state';
}
var _operators = Xms.Fetch.ConditionOperators[type];
var op = new Array();
op.push('<option data-value="" value="">' + LOC_FILTER_CONDITION_OPERATOR_SELECT + '</option>');
$(_operators).each(function (i, n) {
op.push('<option data-value="' + n[0] + '" value="' + n[1] + '">' + n[2] + '</option>');
});
$(input).html(op.join(''));
}
function addView() {
var view = $('.well:first', '#rowcommand').clone();
addAttributeToInput(view);
$('.well:last', '#rowcommand').after(view);
$('.well:last', '#rowcommand').show();
console.log('addView', $('.well:first .judgeView', '#rowcommand'));
view.find('.colorpicker').spectrum({
flat: false,
preferredFormat: 'rgb'
});
saveRowCommandValue();
return view;
}
function removeView(obj) {
$(obj).parent('.well').remove();
saveRowCommandValue();
}
function checkAdd(obj, isParent) {
var ddd = $('.judgeView:first', '#rowcommand>.well:first').clone();
console.log('dddddd', ddd);
if (!isParent) {
$(obj).parents('.judgeBox').find('.judgeView:last').after(ddd);
$(obj).parents('.judgeBox').find('.addMove:last').removeClass('glyphicon-plus').addClass('glyphicon-minus').attr('onclick', 'removeBox(this)');
} else {
$(obj).find('.judgeView:last').after(ddd);
$(obj).find('.addMove:last').removeClass('glyphicon-plus').addClass('glyphicon-minus').attr('onclick', 'removeBox(this)');
}
if ($(obj).parents('.judgeBox').length > 0) {
$(obj).parents('.judgeBox').css({ 'border': '1px solid #ccc', 'background': '#fff', 'border-radius': '10px' });
} else {
$(obj).find('.judgeBox').css({ 'border': '1px solid #ccc', 'background': '#fff', 'border-radius': '10px' });
}
console.log('checkAdd', $(obj));
saveRowCommandValue();
return ddd;
}
function removeBox(obj) {
$(obj).parent('.judgeView').remove();
saveRowCommandValue();
}
//加载字段
function loadRowCommondAttributes(callback) {
var entityid = $('#EntityId').val();
var $attrsInput = $('.ziduan', "#rowcommand");
if (rowcommondAttributes != null) {
var attrHtmls = [];
attrHtmls.push('<option value="">请选择</option>');
$(rowcommondAttributes).each(function (i, n) {
attrHtmls.push('<option data-relationship="' + n.relationship + '" data-type="' + n.attributetypename + '" data-referencingattributelocalizedname="' + n.referencingattributelocalizedname + '" data-name="' + n.name + '" data-entityname="' + n.entityname + '" data-referencingattributename="' + n.referencingattributename + '" data-referencedentityid="' + n.referencedentityid + '" data-entitylocalizedname="' + n.entitylocalizedname + '" value="' + n.name + '" data-optionsetid="' + (n.optionsetid || "") + '" data-attributesid="' + n.attributesid + '" >' + n.localizedname + '</option>');
});
$attrsInput.html(_html.join(''));
$attrsInput.each(function () {
var $this = $(this);
var oldValue = $this.val();
$this.html(attrHtmls.join(''));
console.log('addAttributeToInput', attrHtmls);
$this.val(oldValue);
});
saveRowCommandValue();
callback && callback();
}
}
function addAttributeToInput(_context) {
var entityid = $('#EntityId').val();
_context = _context || "#rowcommand"
var $attrsInput = $('.ziduan', _context);
if (rowcommondAttributes != null) {
var attrHtmls = [];
attrHtmls.push('<option value="">请选择</option>');
$(rowcommondAttributes).each(function (i, n) {
attrHtmls.push('<option data-relationship="' + n.relationship + '" data-type="' + n.attributetypename + '" data-referencingattributelocalizedname="' + n.referencingattributelocalizedname + '" data-name="' + n.name + '" data-entityname="' + n.entityname + '" data-referencingattributename="' + n.referencingattributename + '" data-referencedentityid="' + n.referencedentityid + '" data-entitylocalizedname="' + n.entitylocalizedname + '" value="' + n.name + '" data-optionsetid="' + (n.optionsetid || "") + '" data-attributesid="' + n.attributesid + '" >' + n.localizedname + '</option>');
});
$attrsInput.html(attrHtmls.join(''));
$attrsInput.each(function () {
var $this = $(this);
var oldValue = $this.val();
$this.html(attrHtmls.join(''));
console.log('addAttributeToInput', attrHtmls);
$this.val(oldValue);
});
saveRowCommandValue();
//callback && callback();
}
}
function rowlookupCallback(result, inputid) {
console.log(result, inputid);
$('#' + inputid).val(result[0].name);
$('#' + inputid).attr('data-value', result[0].id);
saveRowCommandValue();
}
function saveRowCommandValue() {
var $rowcommand = $("#rowcommand");
var res = [];
var flag = true;
if ($rowcommand.find('.well:gt(0)').length > 0) {
$rowcommand.find('.well:gt(0)').each(function () {
var $this = $(this);
var LogicalOperator = $this.find('.LogicalOperator').val();
var ActionType = $this.find('.ActionType').val();
var EventType = $this.find('.EventType').val();
var actions = {};
$this.find('.actionSet').each(function (i, n) {
var _key = $(this).attr('data-key');
actions[_key] = $(this).find('.ColorSite').children().val();
});
var _obj = {
"LogicalOperator": LogicalOperator,
"Conditions": [],
"ActionType": ActionType,
"Action": actions,
"EventType": EventType
}
var _condition = [];
console.log($this.find('.judgeBox>.judgeView:gt(0)'));
$this.find('.judgeBox>.judgeView').each(function (i, n) {
var $n = $(this);
var attrname = $n.find('.ziduan').val();
var attrtype = $n.find('.ziduan>option:selected').attr('data-type');
var oper = $n.find('.Operator').val();
var value = [];
console.log(' $n.find(".ziduan")', attrtype)
$n.find('.Values').each(function () {
if (attrtype == 'lookup' || attrtype == 'customer' || attrtype == 'owner') {
value.push($(this).find('input[name="value"]').attr('data-value'));
} else {
value.push($(this).find('input[name="value"]').val());
}
});
_condition.push({
"AttributeName": attrname,
"Operator": oper,
"Values": value
});
if (attrname == "" || oper == "") {
flag = false;
return false;
}
});
console.log(_condition);
_obj.Conditions = _condition;
res.push(_obj);
});
}
if (flag == true && res.length > 0) {
var _rowConfig = $('#LayoutConfig').val();
var _rowObj = JSON.parse(_rowConfig);
_rowObj.RowCommand = res;
console.log('提交的grid的数据', res);
$('#LayoutConfig').val(JSON.stringify(_rowObj));
} else if (flag == false || res.length == 0) {
var _rowConfig = $('#LayoutConfig').val();
if (_rowConfig && _rowConfig != "") {
var _rowObj = JSON.parse(_rowConfig);
delete _rowObj.RowCommand;
console.log('提交的grid的数据', res);
$('#LayoutConfig').val(JSON.stringify(_rowObj));
}
}
if (flag == true) {
return res;
} else {
return false;
}
}
function resetFilterCnName(entityid, callback, type) {
if (!type) {
var params = {
type: "queryview" + entityid,
data: { getall: true, entityid: entityid }
}
Xms.Web.PageCache('workflow', '/api/schema/attribute?__r=' + new Date().getTime(), params, function (data) {
callback && callback(data);
});
} else {
var enParam = {
type: 'referencingentityid' + entityid,
data: { referencingentityid: entityid }
}
Xms.Web.PageCache('workflow', '/api/schema/relationship/GetReferenced/' + enParam.data.referencingentityid, null, function (result) {
callback && callback(result);
});
}
}
function selectRecordCallback(result, inputid) {
var names = $.map(result, function (item, key) {
return item.name;
});
var values = $.map(result, function (item, key) {
return item.id;
});
$('#' + inputid).val(names.join(','));
var valueid = inputid.replace(/_text/, '');
$('#' + valueid).val(values.join(','));
$('#' + inputid).trigger('change');
$('#' + valueid).trigger('change');
var _LayoutConfig = $('#LayoutConfig').val();
if (_LayoutConfig != "") {
var objRowdatas = JSON.parse(_LayoutConfig);
} else {
var objRowdatas = {};
}
var jslib = $('#jslibrary');
if (result && result.length > 0) {
jslib.val(values.join(','));
objRowdatas.ClientResources = values;
$('#LayoutConfig').val(JSON.stringify(objRowdatas));
}
}
|
/**
* Cesium - https://github.com/CesiumGS/cesium
*
* Copyright 2011-2020 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/CesiumGS/cesium/blob/main/LICENSE.md for full licensing details.
*/
define(['./defaultValue-81eec7ed', './Transforms-38070b06', './Matrix2-e0921750', './RuntimeError-8952249c', './ComponentDatatype-0f8fc942', './GeometryAttribute-0fe2ec20', './GeometryAttributes-32b29525', './_commonjsHelpers-3aae1032-26891ab7', './combine-3c023bda', './WebGLConstants-508b9636'], (function (defaultValue, Transforms, Matrix2, RuntimeError, ComponentDatatype, GeometryAttribute, GeometryAttributes, _commonjsHelpers3aae1032, combine, WebGLConstants) { 'use strict';
/**
* Describes geometry representing the outline of a plane centered at the origin, with a unit width and length.
*
* @alias PlaneOutlineGeometry
* @constructor
*
*/
function PlaneOutlineGeometry() {
this._workerName = "createPlaneOutlineGeometry";
}
/**
* The number of elements used to pack the object into an array.
* @type {Number}
*/
PlaneOutlineGeometry.packedLength = 0;
/**
* Stores the provided instance into the provided array.
*
* @param {PlaneOutlineGeometry} value The value to pack.
* @param {Number[]} array The array to pack into.
*
* @returns {Number[]} The array that was packed into
*/
PlaneOutlineGeometry.pack = function (value, array) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.defined("value", value);
RuntimeError.Check.defined("array", array);
//>>includeEnd('debug');
return array;
};
/**
* 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 {PlaneOutlineGeometry} [result] The object into which to store the result.
* @returns {PlaneOutlineGeometry} The modified result parameter or a new PlaneOutlineGeometry instance if one was not provided.
*/
PlaneOutlineGeometry.unpack = function (array, startingIndex, result) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.defined("array", array);
//>>includeEnd('debug');
if (!defaultValue.defined(result)) {
return new PlaneOutlineGeometry();
}
return result;
};
const min = new Matrix2.Cartesian3(-0.5, -0.5, 0.0);
const max = new Matrix2.Cartesian3(0.5, 0.5, 0.0);
/**
* Computes the geometric representation of an outline of a plane, including its vertices, indices, and a bounding sphere.
*
* @returns {Geometry|undefined} The computed vertices and indices.
*/
PlaneOutlineGeometry.createGeometry = function () {
const attributes = new GeometryAttributes.GeometryAttributes();
const indices = new Uint16Array(4 * 2);
const positions = new Float64Array(4 * 3);
positions[0] = min.x;
positions[1] = min.y;
positions[2] = min.z;
positions[3] = max.x;
positions[4] = min.y;
positions[5] = min.z;
positions[6] = max.x;
positions[7] = max.y;
positions[8] = min.z;
positions[9] = min.x;
positions[10] = max.y;
positions[11] = min.z;
attributes.position = new GeometryAttribute.GeometryAttribute({
componentDatatype: ComponentDatatype.ComponentDatatype.DOUBLE,
componentsPerAttribute: 3,
values: positions,
});
indices[0] = 0;
indices[1] = 1;
indices[2] = 1;
indices[3] = 2;
indices[4] = 2;
indices[5] = 3;
indices[6] = 3;
indices[7] = 0;
return new GeometryAttribute.Geometry({
attributes: attributes,
indices: indices,
primitiveType: GeometryAttribute.PrimitiveType.LINES,
boundingSphere: new Transforms.BoundingSphere(Matrix2.Cartesian3.ZERO, Math.sqrt(2.0)),
});
};
function createPlaneOutlineGeometry(planeGeometry, offset) {
if (defaultValue.defined(offset)) {
planeGeometry = PlaneOutlineGeometry.unpack(planeGeometry, offset);
}
return PlaneOutlineGeometry.createGeometry(planeGeometry);
}
return createPlaneOutlineGeometry;
}));
//# sourceMappingURL=createPlaneOutlineGeometry.js.map
|
# exported from PySB model 'model'
from pysb import Model, Monomer, Parameter, Expression, Compartment, Rule, Observable, Initial, MatchOnce, Annotation, ANY, WILD
Model()
Monomer('Ligand', ['Receptor'])
Monomer('ParpU', ['C3A'])
Monomer('C8A', ['BidU', 'C3pro'])
Monomer('SmacM', ['BaxA'])
Monomer('BaxM', ['BidM', 'BaxA'])
Monomer('Apop', ['C3pro', 'Xiap'])
Monomer('Fadd', ['Receptor', 'C8pro'])
Monomer('SmacC', ['Xiap'])
Monomer('ParpC')
Monomer('Xiap', ['SmacC', 'Apop', 'C3A'])
Monomer('C9')
Monomer('C3ub')
Monomer('C8pro', ['Fadd', 'C6A'])
Monomer('Bcl2', ['BidM', 'BaxA'])
Monomer('C3pro', ['Apop', 'C8A'])
Monomer('CytoCM', ['BaxA'])
Monomer('CytoCC')
Monomer('BaxA', ['BaxM', 'Bcl2', 'BaxA_1', 'BaxA_2', 'SmacM', 'CytoCM'])
Monomer('ApafI')
Monomer('BidU', ['C8A'])
Monomer('BidT')
Monomer('C3A', ['Xiap', 'ParpU', 'C6pro'])
Monomer('ApafA')
Monomer('BidM', ['BaxM', 'Bcl2'])
Monomer('Receptor', ['Ligand', 'Fadd'])
Monomer('C6A', ['C8pro'])
Monomer('C6pro', ['C3A'])
Parameter('bind_0_Ligand_binder_Receptor_binder_target_2kf', 1.0)
Parameter('bind_0_Ligand_binder_Receptor_binder_target_1kr', 1.0)
Parameter('bind_0_Receptor_binder_Fadd_binder_target_2kf', 1.0)
Parameter('bind_0_Receptor_binder_Fadd_binder_target_1kr', 1.0)
Parameter('substrate_binding_0_Fadd_catalyzer_C8pro_substrate_2kf', 1.0)
Parameter('substrate_binding_0_Fadd_catalyzer_C8pro_substrate_1kr', 1.0)
Parameter('catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product_1kc', 1.0)
Parameter('catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_2kf', 1.0)
Parameter('catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_1kr', 1.0)
Parameter('catalysis_1_C8A_catalyzer_BidU_substrate_BidT_product_1kc', 1.0)
Parameter('conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_2kf', 1.0)
Parameter('conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_1kr', 1.0)
Parameter('inhibition_0_SmacC_inhibitor_Xiap_inh_target_2kf', 1.0)
Parameter('inhibition_0_SmacC_inhibitor_Xiap_inh_target_1kr', 1.0)
Parameter('conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_2kf', 1.0)
Parameter('conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_1kr', 1.0)
Parameter('catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_2kf', 1.0)
Parameter('catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_1kr', 1.0)
Parameter('catalysis_1_Apop_catalyzer_C3pro_substrate_C3A_product_1kc', 1.0)
Parameter('inhibition_0_Xiap_inhibitor_Apop_inh_target_2kf', 1.0)
Parameter('inhibition_0_Xiap_inhibitor_Apop_inh_target_1kr', 1.0)
Parameter('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_2kf', 1.0)
Parameter('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_1kr', 1.0)
Parameter('catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product_1kc', 1.0)
Parameter('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_2kf', 1.0)
Parameter('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_1kr', 1.0)
Parameter('catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product_1kc', 1.0)
Parameter('equilibration_0_BidT_equil_a_BidM_equil_b_1kf', 1.0)
Parameter('equilibration_0_BidT_equil_a_BidM_equil_b_1kr', 1.0)
Parameter('catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_2kf', 1.0)
Parameter('catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_1kr', 1.0)
Parameter('catalysis_1_BidM_catalyzer_BaxM_substrate_BaxA_product_1kc', 1.0)
Parameter('self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_2kf', 1.0)
Parameter('self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_1kr', 1.0)
Parameter('self_catalyze_1_BaxA_self_catalyzer_BaxM_self_substrate_1kc', 1.0)
Parameter('inhibition_0_Bcl2_inhibitor_BidM_inh_target_2df', 1.0)
Parameter('inhibition_0_Bcl2_inhibitor_BidM_inh_target_1dr', 1.0)
Parameter('inhibition_0_Bcl2_inhibitor_BaxA_inh_target_2xf', 1.0)
Parameter('inhibition_0_Bcl2_inhibitor_BaxA_inh_target_1xr', 1.0)
Parameter('pore_formation_0_BaxA_pore_2kf', 1.0)
Parameter('pore_formation_0_BaxA_pore_1kr', 1.0)
Parameter('pore_formation_1_BaxA_pore_2kf', 1.0)
Parameter('pore_formation_1_BaxA_pore_1kr', 1.0)
Parameter('pore_formation_2_BaxA_pore_2kf', 1.0)
Parameter('pore_formation_2_BaxA_pore_1kr', 1.0)
Parameter('transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_2kf', 1.0)
Parameter('transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kr', 1.0)
Parameter('transport_1_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kc', 1.0)
Parameter('transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_2kf', 1.0)
Parameter('transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kr', 1.0)
Parameter('transport_1_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kc', 1.0)
Parameter('catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_2kf', 1.0)
Parameter('catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_1kr', 1.0)
Parameter('catalysis_1_C8A_catalyzer_C3pro_substrate_C3A_product_1kc', 1.0)
Parameter('catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_2kf', 1.0)
Parameter('catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_1kr', 1.0)
Parameter('catalysis_1_C3A_catalyzer_C6pro_substrate_C6A_product_1kc', 1.0)
Parameter('catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_2kf', 1.0)
Parameter('catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_1kr', 1.0)
Parameter('catalysis_1_C6A_catalyzer_C8pro_substrate_C8A_product_1kc', 1.0)
Parameter('Ligand_0', 1000.0)
Parameter('ParpU_0', 1000000.0)
Parameter('C8A_0', 0.0)
Parameter('SmacM_0', 100000.0)
Parameter('BaxM_0', 40000.0)
Parameter('Apop_0', 0.0)
Parameter('Fadd_0', 130000.0)
Parameter('SmacC_0', 0.0)
Parameter('ParpC_0', 0.0)
Parameter('Xiap_0', 100000.0)
Parameter('C9_0', 100000.0)
Parameter('C3ub_0', 0.0)
Parameter('C8pro_0', 130000.0)
Parameter('Bcl2_0', 60000.0)
Parameter('C3pro_0', 21000.0)
Parameter('CytoCM_0', 500000.0)
Parameter('CytoCC_0', 0.0)
Parameter('BaxA_0', 0.0)
Parameter('ApafI_0', 100000.0)
Parameter('BidU_0', 171000.0)
Parameter('BidT_0', 0.0)
Parameter('C3A_0', 0.0)
Parameter('ApafA_0', 0.0)
Parameter('BidM_0', 0.0)
Parameter('Receptor_0', 100.0)
Parameter('C6A_0', 0.0)
Parameter('C6pro_0', 100.0)
Observable('Ligand_obs', Ligand())
Observable('ParpU_obs', ParpU())
Observable('C8A_obs', C8A())
Observable('SmacM_obs', SmacM())
Observable('BaxM_obs', BaxM())
Observable('Apop_obs', Apop())
Observable('Fadd_obs', Fadd())
Observable('SmacC_obs', SmacC())
Observable('ParpC_obs', ParpC())
Observable('Xiap_obs', Xiap())
Observable('C9_obs', C9())
Observable('C3ub_obs', C3ub())
Observable('C8pro_obs', C8pro())
Observable('Bcl2_obs', Bcl2())
Observable('C3pro_obs', C3pro())
Observable('CytoCM_obs', CytoCM())
Observable('CytoCC_obs', CytoCC())
Observable('BaxA_obs', BaxA())
Observable('ApafI_obs', ApafI())
Observable('BidU_obs', BidU())
Observable('BidT_obs', BidT())
Observable('C3A_obs', C3A())
Observable('ApafA_obs', ApafA())
Observable('BidM_obs', BidM())
Observable('Receptor_obs', Receptor())
Observable('C6A_obs', C6A())
Observable('C6pro_obs', C6pro())
Rule('bind_0_Ligand_binder_Receptor_binder_target', Ligand(Receptor=None) + Receptor(Ligand=None, Fadd=None) | Ligand(Receptor=1) % Receptor(Ligand=1, Fadd=None), bind_0_Ligand_binder_Receptor_binder_target_2kf, bind_0_Ligand_binder_Receptor_binder_target_1kr)
Rule('bind_0_Receptor_binder_Fadd_binder_target', Receptor(Ligand=ANY, Fadd=None) + Fadd(Receptor=None, C8pro=None) | Receptor(Ligand=ANY, Fadd=1) % Fadd(Receptor=1, C8pro=None), bind_0_Receptor_binder_Fadd_binder_target_2kf, bind_0_Receptor_binder_Fadd_binder_target_1kr)
Rule('substrate_binding_0_Fadd_catalyzer_C8pro_substrate', Fadd(Receptor=ANY, C8pro=None) + C8pro(Fadd=None, C6A=None) | Fadd(Receptor=ANY, C8pro=1) % C8pro(Fadd=1, C6A=None), substrate_binding_0_Fadd_catalyzer_C8pro_substrate_2kf, substrate_binding_0_Fadd_catalyzer_C8pro_substrate_1kr)
Rule('catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product', Fadd(Receptor=ANY, C8pro=1) % C8pro(Fadd=1, C6A=None) >> Fadd(Receptor=ANY, C8pro=None) + C8A(BidU=None, C3pro=None), catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product_1kc)
Rule('catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product', C8A(BidU=None, C3pro=None) + BidU(C8A=None) | C8A(BidU=1, C3pro=None) % BidU(C8A=1), catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_2kf, catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_1kr)
Rule('catalysis_1_C8A_catalyzer_BidU_substrate_BidT_product', C8A(BidU=1, C3pro=None) % BidU(C8A=1) >> C8A(BidU=None, C3pro=None) + BidT(), catalysis_1_C8A_catalyzer_BidU_substrate_BidT_product_1kc)
Rule('conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex', ApafI() + CytoCC() | ApafA(), conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_2kf, conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_1kr)
Rule('inhibition_0_SmacC_inhibitor_Xiap_inh_target', SmacC(Xiap=None) + Xiap(SmacC=None, Apop=None, C3A=None) | SmacC(Xiap=1) % Xiap(SmacC=1, Apop=None, C3A=None), inhibition_0_SmacC_inhibitor_Xiap_inh_target_2kf, inhibition_0_SmacC_inhibitor_Xiap_inh_target_1kr)
Rule('conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex', ApafA() + C9() | Apop(C3pro=None, Xiap=None), conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_2kf, conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_1kr)
Rule('catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product', Apop(C3pro=None, Xiap=None) + C3pro(Apop=None, C8A=None) | Apop(C3pro=1, Xiap=None) % C3pro(Apop=1, C8A=None), catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_2kf, catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_1kr)
Rule('catalysis_1_Apop_catalyzer_C3pro_substrate_C3A_product', Apop(C3pro=1, Xiap=None) % C3pro(Apop=1, C8A=None) >> Apop(C3pro=None, Xiap=None) + C3A(Xiap=None, ParpU=None, C6pro=None), catalysis_1_Apop_catalyzer_C3pro_substrate_C3A_product_1kc)
Rule('inhibition_0_Xiap_inhibitor_Apop_inh_target', Xiap(SmacC=None, Apop=None, C3A=None) + Apop(C3pro=None, Xiap=None) | Xiap(SmacC=None, Apop=1, C3A=None) % Apop(C3pro=None, Xiap=1), inhibition_0_Xiap_inhibitor_Apop_inh_target_2kf, inhibition_0_Xiap_inhibitor_Apop_inh_target_1kr)
Rule('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product', Xiap(SmacC=None, Apop=None, C3A=None) + C3A(Xiap=None, ParpU=None, C6pro=None) | Xiap(SmacC=None, Apop=None, C3A=1) % C3A(Xiap=1, ParpU=None, C6pro=None), catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_2kf, catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_1kr)
Rule('catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product', Xiap(SmacC=None, Apop=None, C3A=1) % C3A(Xiap=1, ParpU=None, C6pro=None) >> Xiap(SmacC=None, Apop=None, C3A=None) + C3ub(), catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product_1kc)
Rule('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product', C3A(Xiap=None, ParpU=None, C6pro=None) + ParpU(C3A=None) | C3A(Xiap=None, ParpU=1, C6pro=None) % ParpU(C3A=1), catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_2kf, catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_1kr)
Rule('catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product', C3A(Xiap=None, ParpU=1, C6pro=None) % ParpU(C3A=1) >> C3A(Xiap=None, ParpU=None, C6pro=None) + ParpC(), catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product_1kc)
Rule('equilibration_0_BidT_equil_a_BidM_equil_b', BidT() | BidM(BaxM=None, Bcl2=None), equilibration_0_BidT_equil_a_BidM_equil_b_1kf, equilibration_0_BidT_equil_a_BidM_equil_b_1kr)
Rule('catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product', BidM(BaxM=None, Bcl2=None) + BaxM(BidM=None, BaxA=None) | BidM(BaxM=1, Bcl2=None) % BaxM(BidM=1, BaxA=None), catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_2kf, catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_1kr)
Rule('catalysis_1_BidM_catalyzer_BaxM_substrate_BaxA_product', BidM(BaxM=1, Bcl2=None) % BaxM(BidM=1, BaxA=None) >> BidM(BaxM=None, Bcl2=None) + BaxA(BaxM=None, Bcl2=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None), catalysis_1_BidM_catalyzer_BaxM_substrate_BaxA_product_1kc)
Rule('self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate', BaxA(BaxM=None, Bcl2=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxM(BidM=None, BaxA=None) | BaxA(BaxM=1, Bcl2=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) % BaxM(BidM=None, BaxA=1), self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_2kf, self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_1kr)
Rule('self_catalyze_1_BaxA_self_catalyzer_BaxM_self_substrate', BaxA(BaxM=1, Bcl2=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) % BaxM(BidM=None, BaxA=1) >> BaxA(BaxM=None, Bcl2=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, Bcl2=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None), self_catalyze_1_BaxA_self_catalyzer_BaxM_self_substrate_1kc)
Rule('inhibition_0_Bcl2_inhibitor_BidM_inh_target', Bcl2(BidM=None, BaxA=None) + BidM(BaxM=None, Bcl2=None) | Bcl2(BidM=1, BaxA=None) % BidM(BaxM=None, Bcl2=1), inhibition_0_Bcl2_inhibitor_BidM_inh_target_2df, inhibition_0_Bcl2_inhibitor_BidM_inh_target_1dr)
Rule('inhibition_0_Bcl2_inhibitor_BaxA_inh_target', Bcl2(BidM=None, BaxA=None) + BaxA(BaxM=None, Bcl2=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) | Bcl2(BidM=None, BaxA=1) % BaxA(BaxM=None, Bcl2=1, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None), inhibition_0_Bcl2_inhibitor_BaxA_inh_target_2xf, inhibition_0_Bcl2_inhibitor_BaxA_inh_target_1xr)
Rule('pore_formation_0_BaxA_pore', BaxA(BaxM=None, Bcl2=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, Bcl2=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) | BaxA(BaxM=None, Bcl2=None, BaxA_1=None, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=1, BaxA_2=None, SmacM=None, CytoCM=None), pore_formation_0_BaxA_pore_2kf, pore_formation_0_BaxA_pore_1kr)
Rule('pore_formation_1_BaxA_pore', BaxA(BaxM=None, Bcl2=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, Bcl2=None, BaxA_1=None, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=1, BaxA_2=None, SmacM=None, CytoCM=None) | BaxA(BaxM=None, Bcl2=None, BaxA_1=3, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None), pore_formation_1_BaxA_pore_2kf, pore_formation_1_BaxA_pore_1kr)
Rule('pore_formation_2_BaxA_pore', BaxA(BaxM=None, Bcl2=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, Bcl2=None, BaxA_1=3, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) | BaxA(BaxM=None, Bcl2=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None), pore_formation_2_BaxA_pore_2kf, pore_formation_2_BaxA_pore_1kr)
Rule('transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C', BaxA(BaxM=None, Bcl2=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + SmacM(BaxA=None) | BaxA(BaxM=None, Bcl2=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=3, BaxA_2=4, SmacM=5, CytoCM=None) % SmacM(BaxA=5), transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_2kf, transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kr)
Rule('transport_1_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C', BaxA(BaxM=None, Bcl2=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=3, BaxA_2=4, SmacM=5, CytoCM=None) % SmacM(BaxA=5) >> BaxA(BaxM=None, Bcl2=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + SmacC(Xiap=None), transport_1_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kc)
Rule('transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C', BaxA(BaxM=None, Bcl2=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + CytoCM(BaxA=None) | BaxA(BaxM=None, Bcl2=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=5) % CytoCM(BaxA=5), transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_2kf, transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kr)
Rule('transport_1_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C', BaxA(BaxM=None, Bcl2=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=5) % CytoCM(BaxA=5) >> BaxA(BaxM=None, Bcl2=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, Bcl2=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + CytoCC(), transport_1_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kc)
Rule('catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product', C8A(BidU=None, C3pro=None) + C3pro(Apop=None, C8A=None) | C8A(BidU=None, C3pro=1) % C3pro(Apop=None, C8A=1), catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_2kf, catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_1kr)
Rule('catalysis_1_C8A_catalyzer_C3pro_substrate_C3A_product', C8A(BidU=None, C3pro=1) % C3pro(Apop=None, C8A=1) >> C8A(BidU=None, C3pro=None) + C3A(Xiap=None, ParpU=None, C6pro=None), catalysis_1_C8A_catalyzer_C3pro_substrate_C3A_product_1kc)
Rule('catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product', C3A(Xiap=None, ParpU=None, C6pro=None) + C6pro(C3A=None) | C3A(Xiap=None, ParpU=None, C6pro=1) % C6pro(C3A=1), catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_2kf, catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_1kr)
Rule('catalysis_1_C3A_catalyzer_C6pro_substrate_C6A_product', C3A(Xiap=None, ParpU=None, C6pro=1) % C6pro(C3A=1) >> C3A(Xiap=None, ParpU=None, C6pro=None) + C6A(C8pro=None), catalysis_1_C3A_catalyzer_C6pro_substrate_C6A_product_1kc)
Rule('catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product', C6A(C8pro=None) + C8pro(Fadd=None, C6A=None) | C6A(C8pro=1) % C8pro(Fadd=None, C6A=1), catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_2kf, catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_1kr)
Rule('catalysis_1_C6A_catalyzer_C8pro_substrate_C8A_product', C6A(C8pro=1) % C8pro(Fadd=None, C6A=1) >> C6A(C8pro=None) + C8A(BidU=None, C3pro=None), catalysis_1_C6A_catalyzer_C8pro_substrate_C8A_product_1kc)
Initial(Ligand(Receptor=None), Ligand_0)
Initial(ParpU(C3A=None), ParpU_0)
Initial(C8A(BidU=None, C3pro=None), C8A_0)
Initial(SmacM(BaxA=None), SmacM_0)
Initial(BaxM(BidM=None, BaxA=None), BaxM_0)
Initial(Apop(C3pro=None, Xiap=None), Apop_0)
Initial(Fadd(Receptor=None, C8pro=None), Fadd_0)
Initial(SmacC(Xiap=None), SmacC_0)
Initial(ParpC(), ParpC_0)
Initial(Xiap(SmacC=None, Apop=None, C3A=None), Xiap_0)
Initial(C9(), C9_0)
Initial(C3ub(), C3ub_0)
Initial(C8pro(Fadd=None, C6A=None), C8pro_0)
Initial(Bcl2(BidM=None, BaxA=None), Bcl2_0)
Initial(C3pro(Apop=None, C8A=None), C3pro_0)
Initial(CytoCM(BaxA=None), CytoCM_0)
Initial(CytoCC(), CytoCC_0)
Initial(BaxA(BaxM=None, Bcl2=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None), BaxA_0)
Initial(ApafI(), ApafI_0)
Initial(BidU(C8A=None), BidU_0)
Initial(BidT(), BidT_0)
Initial(C3A(Xiap=None, ParpU=None, C6pro=None), C3A_0)
Initial(ApafA(), ApafA_0)
Initial(BidM(BaxM=None, Bcl2=None), BidM_0)
Initial(Receptor(Ligand=None, Fadd=None), Receptor_0)
Initial(C6A(C8pro=None), C6A_0)
Initial(C6pro(C3A=None), C6pro_0)
|
// requiring dependencies, models and middlewares
const express = require('express');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const multer = require('multer');
const User = require('../models/User.model');
const auth = require('../middlewares/auth');
const {
signupValidation,
updateValidation,
loginValidation,
} = require('../middlewares/validations/user.js');
const Blog = require('../models/Blog.model');
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads/');
},
filename: function (req, file, cb) {
cb(
null,
new Date().toISOString().replace(/:/g, '-') + file.originalname
);
},
});
const fileFilter = (req, file, cb) => {
// reject a file
if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
cb(null, true);
} else {
cb(null, false);
}
};
const upload = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024 * 5,
},
fileFilter: fileFilter,
});
const router = express.Router();
// GET request for Sign Up
router.get('/sign-up', auth, async (req, res) => {
if (req.user) {
res.redirect('/');
} else {
res.render('./auth/signUp', {
error: '',
data: {
firstName: '',
lastName: '',
userName: '',
password: '',
email: '',
confirmPassword: '',
},
});
}
});
// GET request for Log In
router.get('/log-in', auth, async (req, res) => {
if (req.user) {
res.redirect('/');
} else {
res.render('./auth/logIn', {
error: '',
data: {
email: '',
password: '',
},
});
}
});
// to view own profile
router.get('/read-profile', auth, async (req, res) => {
const _id = req.user;
const user = await User.findById(_id);
res.render('./useritems/read-profile', {
user,
isAuthenticated: !!req.user,
error: '',
});
});
router.post(
'/read-profile',
upload.single('photo'),
auth,
updateValidation,
async (req, res) => {
const updates = Object.keys(req.body);
const allowedUpdates = [
'firstName',
'lastName',
'userName',
'email',
'password',
];
const isValid = updates.every((update) =>
allowedUpdates.includes(update)
);
if (!isValid) {
res.status(400).send('invalid update property');
}
if (req.file) {
updates.push('photo');
req.body.photo = req.file.path;
}
try {
const id = await req.user;
const user = await User.findById(id._id);
// eslint-disable-next-line
updates.forEach((update) => (user[update] = req.body[update]));
await user.save();
res.redirect('/');
} catch (e) {
res.status(500).send(e);
}
}
);
// POST request for sign up
router.post(
'/sign-up',
upload.single('photo'),
signupValidation,
async (req, res) => {
const {
firstName,
lastName,
userName,
email,
password,
confirmPassword,
} = req.body;
// Check if the username or email already taken
User.findOne({ $or: [{ email }, { userName }] }, () => {
User.findOne({ userName }, (err, doc) => {
if (doc) {
return res.status(401).render('./auth/logIn', {
error: 'Username already taken!',
data: {
firstName,
lastName,
userName,
password,
email,
confirmPassword,
},
});
}
let photo = '';
if (req.file) {
photo = req.file.path;
}
const newUser = new User({
firstName,
lastName,
userName,
password,
email,
photo,
});
newUser.save((err, doc) => {
if (err || !doc) {
return res.status(422).render('./auth/logIn', {
error: 'Oops something went wrong!',
data: {
firstName,
lastName,
userName,
email,
password,
},
});
}
const token = jwt.sign(
{ _id: doc._id },
process.env.SECRET_KEY
);
// Send back the token to the user as a httpOnly cookie
res.cookie('token', token, {
httpOnly: true,
});
res.redirect('/');
});
});
});
}
);
// POST request for log in
router.post('/log-in', loginValidation, async (req, res) => {
const { email, password } = req.body;
User.findOne({ email }, (err, doc) => {
if (err || !doc) {
return res.status(401).render('./auth/logIn', {
error: 'Invalid email or password!',
data: {
email,
password,
},
});
}
bcrypt.compare(password, doc.password, (err, matched) => {
if (err || !matched) {
return res.status(401).render('./auth/logIn', {
error: 'Invalid email or password!',
data: {
email,
password,
},
});
}
const token = jwt.sign(
{ _id: doc._id, email },
process.env.SECRET_KEY
);
res.cookie('token', token, {
httpOnly: true,
});
res.redirect('/');
});
});
});
// Post route for log-out
router.post('/log-out', auth, async (req, res) => {
res.clearCookie('token');
res.redirect('/');
});
//* route /author/:id
//* desc Fetch the required user's blogs
router.get('/author/:id', auth, async (req, res) => {
// If the requested author is the currently logged in user then redirect them to their dashbaord
if (req.user) {
if (req.params.id.toString() === req.user._id.toString())
return res.redirect('/dashboard');
} else {
return res.redirect('/log-in');
}
try {
try {
const user = await User.findById(req.params.id);
if (!user) return res.redirect('/error');
let toggleunfollow = false;
user.followers.forEach((item) => {
if (item.toString() === req.user._id.toString()) {
toggleunfollow = true;
}
});
const likedBlogs = await Blog.find({
_id: { $in: user.likedPosts },
status: 'Public',
});
const blogs = await Blog.find({
author: req.params.id,
status: 'Public',
})
.populate('author')
.sort({ timestamps: 'desc' })
.lean();
return res.render('./useritems/author', {
user,
toggleunfollow,
posts: blogs,
isAuthenticated: !!req.user,
likedBlogs: likedBlogs,
});
} catch (error) {
return res.redirect('/error');
}
} catch (error) {
return res.redirect('/error');
}
});
//* route /dashboard/
//* desc Fetch the logged in user's blogs
router.get('/dashboard', auth, async (req, res) => {
if (!req.user) return res.redirect('/log-in');
try {
try {
const user = await User.findById(req.user._id);
if (!user) return res.redirect('/error');
const blogs = await Blog.find({ author: req.user._id })
.populate('author')
.sort({ timestamps: 'desc' })
.lean();
const allusers = await User.find({});
const likedBlogs = await Blog.find({
_id: { $in: user.likedPosts },
});
return res.render('./useritems/dashboard', {
user,
allusers,
posts: blogs,
isAuthenticated: !!req.user,
likedBlogs: likedBlogs,
});
} catch (error) {
return res.redirect('/error');
}
} catch (error) {
return res.redirect('/error');
}
});
router.get('/follow/:id', auth, async (req, res) => {
if (!req.user) return res.redirect('/log-in');
User.findByIdAndUpdate(
req.params.id,
{
$push: { followers: req.user._id },
},
{ new: true },
(err) => {
if (err) {
return res.status(422).json({ error: err });
}
User.findByIdAndUpdate(
req.user._id,
{
$push: { following: req.params.id },
},
{ new: true }
)
.select('-password')
.then(() => res.redirect(`/author/${req.params.id}`))
.catch((err) => res.status(422).json({ error: err }));
}
);
});
router.get('/unfollow/:id', auth, async (req, res) => {
if (!req.user) return res.redirect('/log-in');
User.findByIdAndUpdate(
req.params.id,
{
$pull: { followers: req.user._id },
},
{ new: true },
(err) => {
if (err) {
return res.status(422).json({ error: err });
}
User.findByIdAndUpdate(
req.user._id,
{
$pull: { following: req.params.id },
},
{ new: true }
)
.select('-password')
.then(() => res.redirect(`/author/${req.params.id}`))
.catch((err) => res.status(422).json({ error: err }));
}
);
});
module.exports = router;
|
/* @flow */
import { no, noop, identity } from 'shared/util'
import { LIFECYCLE_HOOKS } from 'shared/constants'
export type Config = {
// user
optionMergeStrategies: { [key: string]: Function },
silent: boolean,
productionTip: boolean,
performance: boolean,
devtools: boolean,
errorHandler: ?(err: Error, vm: Component, info: string) => void,
warnHandler: ?(msg: string, vm: Component, trace: string) => void,
ignoredElements: Array<string | RegExp>,
keyCodes: { [key: string]: number | Array<number> },
// platform
isReservedTag: (x?: string) => boolean,
isReservedAttr: (x?: string) => boolean,
parsePlatformTagName: (x: string) => string,
isUnknownElement: (x?: string) => boolean,
getTagNamespace: (x?: string) => string | void,
mustUseProp: (tag: string, type: ?string, name: string) => boolean,
// private
async: boolean,
// legacy
_lifecycleHooks: Array<string>,
}
export default ({
/**
* Option merge strategies (used in core/util/options)
*/
// $flow-disable-line
optionMergeStrategies: Object.create(null),
/**
* Whether to suppress warnings.
*/
silent: false,
/**
* Show production mode tip message on boot?
*/
productionTip: process.env.NODE_ENV !== 'production',
/**
* Whether to enable devtools
*/
devtools: process.env.NODE_ENV !== 'production',
/**
* Whether to record perf
*/
performance: false,
/**
* Error handler for watcher errors
*/
errorHandler: null,
/**
* Warn handler for watcher warns
*/
warnHandler: null,
/**
* Ignore certain custom elements
*/
ignoredElements: [],
/**
* Custom user key aliases for v-on
*/
// $flow-disable-line
keyCodes: Object.create(null),
/**
* Check if a tag is reserved so that it cannot be registered as a
* component. This is platform-dependent and may be overwritten.
*/
isReservedTag: no,
/**
* Check if an attribute is reserved so that it cannot be used as a component
* prop. This is platform-dependent and may be overwritten.
*/
isReservedAttr: no,
/**
* Check if a tag is an unknown element.
* Platform-dependent.
*/
isUnknownElement: no,
/**
* Get the namespace of an element
*/
getTagNamespace: noop,
/**
* Parse the real tag name for the specific platform.
*/
parsePlatformTagName: identity,
/**
* Check if an attribute must be bound using property, e.g. value
* Platform-dependent.
*/
mustUseProp: no,
/**
* Perform updates asynchronously. Intended to be used by Vue Test Utils
* This will significantly reduce performance if set to false.
*/
async: true,
/**
* Exposed for legacy reasons
*/
_lifecycleHooks: LIFECYCLE_HOOKS,
}: Config)
|
/*
* Swagger Petstore
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
*
* Swagger Codegen version: 2.4.6-SNAPSHOT
*
* Do not edit the class manually.
*
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['ApiClient', 'model/Animal'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('../ApiClient'), require('./Animal'));
} else {
// Browser globals (root is window)
if (!root.SwaggerPetstore) {
root.SwaggerPetstore = {};
}
root.SwaggerPetstore.MixedPropertiesAndAdditionalPropertiesClass = factory(root.SwaggerPetstore.ApiClient, root.SwaggerPetstore.Animal);
}
}(this, function(ApiClient, Animal) {
'use strict';
/**
* The MixedPropertiesAndAdditionalPropertiesClass model module.
* @module model/MixedPropertiesAndAdditionalPropertiesClass
* @version 1.0.0
*/
/**
* Constructs a new <code>MixedPropertiesAndAdditionalPropertiesClass</code>.
* @alias module:model/MixedPropertiesAndAdditionalPropertiesClass
* @class
*/
var exports = function() {
};
/**
* Constructs a <code>MixedPropertiesAndAdditionalPropertiesClass</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/MixedPropertiesAndAdditionalPropertiesClass} obj Optional instance to populate.
* @return {module:model/MixedPropertiesAndAdditionalPropertiesClass} The populated <code>MixedPropertiesAndAdditionalPropertiesClass</code> instance.
*/
exports.constructFromObject = function(data, obj) {
if (data) {
obj = obj || new exports();
if (data.hasOwnProperty('uuid'))
obj.uuid = ApiClient.convertToType(data['uuid'], 'String');
if (data.hasOwnProperty('dateTime'))
obj.dateTime = ApiClient.convertToType(data['dateTime'], 'Date');
if (data.hasOwnProperty('map'))
obj.map = ApiClient.convertToType(data['map'], {'String': Animal});
}
return obj;
}
/**
* @member {String} uuid
*/
exports.prototype.uuid = undefined;
/**
* @member {Date} dateTime
*/
exports.prototype.dateTime = undefined;
/**
* @member {Object.<String, module:model/Animal>} map
*/
exports.prototype.map = undefined;
return exports;
}));
|
/**
* convertapi
* Convert API lets you effortlessly convert file formats and types.
*
* OpenAPI spec version: v1
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
*
* Swagger Codegen version: 2.4.5
*
* Do not edit the class manually.
*
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['ApiClient', 'model/DocxParagraph', 'model/DocxSection'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('../ApiClient'), require('./DocxParagraph'), require('./DocxSection'));
} else {
// Browser globals (root is window)
if (!root.CloudmersiveConvertApiClient) {
root.CloudmersiveConvertApiClient = {};
}
root.CloudmersiveConvertApiClient.DocxFooter = factory(root.CloudmersiveConvertApiClient.ApiClient, root.CloudmersiveConvertApiClient.DocxParagraph, root.CloudmersiveConvertApiClient.DocxSection);
}
}(this, function(ApiClient, DocxParagraph, DocxSection) {
'use strict';
/**
* The DocxFooter model module.
* @module model/DocxFooter
* @version 2.7.4
*/
/**
* Constructs a new <code>DocxFooter</code>.
* Footer in a Word Document (DOCX)
* @alias module:model/DocxFooter
* @class
*/
var exports = function() {
var _this = this;
};
/**
* Constructs a <code>DocxFooter</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/DocxFooter} obj Optional instance to populate.
* @return {module:model/DocxFooter} The populated <code>DocxFooter</code> instance.
*/
exports.constructFromObject = function(data, obj) {
if (data) {
obj = obj || new exports();
if (data.hasOwnProperty('Path')) {
obj['Path'] = ApiClient.convertToType(data['Path'], 'String');
}
if (data.hasOwnProperty('Paragraphs')) {
obj['Paragraphs'] = ApiClient.convertToType(data['Paragraphs'], [DocxParagraph]);
}
if (data.hasOwnProperty('SectionsWithFooter')) {
obj['SectionsWithFooter'] = ApiClient.convertToType(data['SectionsWithFooter'], [DocxSection]);
}
}
return obj;
}
/**
* The Path of the location of this object; leave blank for new tables
* @member {String} Path
*/
exports.prototype['Path'] = undefined;
/**
* Paragraphs in this footer
* @member {Array.<module:model/DocxParagraph>} Paragraphs
*/
exports.prototype['Paragraphs'] = undefined;
/**
* Sections that the footer is applied to
* @member {Array.<module:model/DocxSection>} SectionsWithFooter
*/
exports.prototype['SectionsWithFooter'] = undefined;
return exports;
}));
|
const patternMethods = ({
backend,
mergeData,
subMergeData,
token,
setLoading,
persist,
navigate,
setNotification,
translate,
showError,
account,
people,
patterns,
setAccount,
setPatterns,
setPeople
}) => {
const createPattern = (data) => {
setLoading(true)
return backend
.createPattern(data, token)
.then((res) => {
setLoading(false)
if (res.status === 200) {
updatePatterns(res.data, res.data.handle)
setNotification({
type: 'success',
msg: translate('app.created')
})
return res.data
}
})
.catch((error) => {
setLoading(false)
showError(error)
})
}
const updatePattern = (handle, data) => {
let newPatterns = { ...patterns }
newPatterns[handle] = {
...newPatterns[handle],
...data
}
setPatterns(newPatterns)
return backend
.savePattern(handle, data, token)
.then((res) => {
if (res.status === 200) {
setNotification({
type: 'success',
msg: translate('app.fieldSaved', { field: translate('app.pattern') })
})
}
})
.catch((error) => {
showError(error)
})
}
const removePattern = (handle) => {
setLoading(true)
let newPatterns = { ...patterns }
delete newPatterns[handle]
setPatterns(newPatterns)
return backend
.removePattern(handle, token)
.then((res) => {
setLoading(false)
if (res.status === 204) {
setNotification({
type: 'success',
msg: translate('app.fieldRemoved', { field: translate('app.pattern') })
})
navigate('/account/patterns/')
}
})
.catch((error) => {
setLoading(false)
showError(error)
})
}
const loadPattern = (handle) => {
return backend
.loadPattern(handle, token)
.then((res) => {
setLoading(false)
if (res.status === 200) return res.data
else return false
})
.catch((error) => false)
}
const savePattern = (data) => backend.savePattern(mergeData({}, data), token)
const updatePatterns = (value, l1, l2, l3) =>
setPatterns(mergeData(patterns, [value, l1, l2, l3]))
return {
createPattern,
updatePattern,
removePattern,
loadPattern,
savePattern,
updatePatterns
}
}
export default patternMethods
|
import * as swcHelpers from "@swc/helpers";
// @filename: file.tsx
// @jsx: preserve
// @module: amd
// @noLib: true
// @skipLibCheck: true
// @libFiles: react.d.ts,lib.d.ts
var React = require("react");
// Error
function Baz(arg1, arg2) {
var a0 = /*#__PURE__*/ React.createElement(OverloadComponent, {
a: arg1.b
});
var a2 = /*#__PURE__*/ React.createElement(OverloadComponent, swcHelpers.extends({}, arg1, {
"ignore-prop": true
})) // missing a
;
}
export { };
|
// THIS FILE IS AUTO GENERATED
var GenIcon = require('../lib').GenIcon
module.exports.FaRandom = function FaRandom (props) {
return GenIcon({"tag":"svg","attr":{"viewBox":"0 0 512 512"},"child":[{"tag":"path","attr":{"d":"M504.971 359.029c9.373 9.373 9.373 24.569 0 33.941l-80 79.984c-15.01 15.01-40.971 4.49-40.971-16.971V416h-58.785a12.004 12.004 0 0 1-8.773-3.812l-70.556-75.596 53.333-57.143L352 336h32v-39.981c0-21.438 25.943-31.998 40.971-16.971l80 79.981zM12 176h84l52.781 56.551 53.333-57.143-70.556-75.596A11.999 11.999 0 0 0 122.785 96H12c-6.627 0-12 5.373-12 12v56c0 6.627 5.373 12 12 12zm372 0v39.984c0 21.46 25.961 31.98 40.971 16.971l80-79.984c9.373-9.373 9.373-24.569 0-33.941l-80-79.981C409.943 24.021 384 34.582 384 56.019V96h-58.785a12.004 12.004 0 0 0-8.773 3.812L96 336H12c-6.627 0-12 5.373-12 12v56c0 6.627 5.373 12 12 12h110.785c3.326 0 6.503-1.381 8.773-3.812L352 176h32z"}}]})(props);
};
|
# import the definition of the steps and input files:
from Configuration.PyReleaseValidation.relval_steps import *
# here only define the workflows as a combination of the steps defined above:
workflows = Matrix()
overridesEv5={'-n':'5'}
# each workflow defines a name and a list of steps to be done.
# if no explicit name/label given for the workflow (first arg),
# the name of step1 will be used
## production tests
workflows[1] = ['', ['ProdMinBias','DIGIPROD1','RECOPROD1']]
workflows[2] = ['', ['ProdTTbar','DIGIPROD1','RECOPROD1']]
workflows[3] = ['', ['ProdQCD_Pt_3000_3500','DIGIPROD1','RECOPROD1']]
workflows.addOverride(3,overridesEv5) #######################################################
###Prod2016
#workflows[1301] = ['', ['ProdMinBias_13','DIGIUP15PROD1','RECOPRODUP15','MINIAODMCUP15']] # Re-add miniaod here, to keep event content scrutinized
workflows[1301] = ['', ['ProdMinBias_13','DIGIUP15PROD1','RECOPRODUP15']] ########################################################
workflows[1302] = ['', ['ProdTTbar_13','DIGIUP15PROD1','RECOPRODUP15']]
workflows[1303] = ['', ['ProdQCD_Pt_3000_3500_13','DIGIUP15PROD1','RECOPRODUP15']]
workflows.addOverride(1303,overridesEv5)
#####Prod2017
workflows[1301.17] = ['', ['ProdMinBias_13UP17','DIGIUP17PROD1','RECOPRODUP17']]
workflows[1302.17] = ['', ['ProdTTbar_13UP17','DIGIUP17PROD1','RECOPRODUP17']]
workflows[1303.17] = ['', ['ProdQCD_Pt_3000_3500_13UP17','DIGIUP17PROD1','RECOPRODUP17']]
workflows.addOverride(1303.17,overridesEv5)
#####Prod2018
#workflows[1301.18] = ['', ['ProdMinBias_13UP18','DIGIUP18PROD1','RECOPRODUP18']]
workflows[1302.18] = ['', ['ProdTTbar_13UP18','DIGIUP18PROD1','RECOPRODUP18','MINIAODMCUP18','NANOPRODUP18']]
#workflows[1303.18] = ['', ['ProdQCD_Pt_3000_3500_13UP18','DIGIUP18PROD1','RECOPRODUP18']]
workflows[1304.18] = ['', ['ProdZEE_13UP18','DIGIUP18PROD1','RECOPRODUP18','MINIAODMCUP18','NANOPRODUP18']]
workflows[1304.182] = ['', ['ProdZEE_13UP18','DIGIUP18PROD1bParking','RECOPRODUP18bParking','MINIAODMCUP18bParking']]
#workflows.addOverride(1303.17,overridesEv5)
#####Prod2018 with concurrentlumi
workflows[1302.181] = ['', ['ProdTTbar_13UP18ml','DIGIUP18PROD1','RECOPRODUP18','MINIAODMCUP18','NANOPRODUP18']]
workflows[1304.181] = ['', ['ProdZEE_13UP18ml','DIGIUP18PROD1','RECOPRODUP18','MINIAODMCUP18','NANOPRODUP18']]
### data ###
workflows[4.5] = ['', ['RunCosmicsA','RECOCOSD','ALCACOSD','HARVESTDC']]
#workflows[4.6] = ['', ['MinimumBias2010A','RECODR1','HARVESTDR1']]
workflows[4.6] = ['', ['MinimumBias2010A','RECOSKIMALCA','HARVESTDR1']]
#workflows[4.7] = ['', ['MinimumBias2010B','RECODR1ALCA','HARVESTDR1']]
#workflows[4.8] = ['', ['WZMuSkim2010A','RECODR1','HARVESTDR1']]
#workflows[4.9] = ['', ['WZEGSkim2010A','RECODR1','HARVESTDR1']]
#workflows[4.10] = ['', ['WZMuSkim2010B','RECODR1','HARVESTDR1']]
#workflows[4.11] = ['', ['WZEGSkim2010B','RECODR1','HARVESTDR1']]
workflows[4.12] = ['', ['RunMinBias2010B','RECODR1','HARVESTDR1']]
#workflows[4.13] = ['', ['RunMu2010B','RECODR1','HARVESTDR1']]
#workflows[4.14] = ['', ['RunElectron2010B','RECODR1','HARVESTDR1']]
#workflows[4.15] = ['', ['RunPhoton2010B','RECODR1','HARVESTDR1']]
#workflows[4.16] = ['', ['RunJet2010B','RECODR1','HARVESTDR1']]
workflows[4.17] = ['', ['RunMinBias2011A','HLTD','RECODR1reHLT','HARVESTDR1reHLT','SKIMDreHLT']]
workflows[4.18] = ['', ['RunMu2011A','RECODR1','HARVESTDR1']]
workflows[4.19] = ['', ['RunElectron2011A','RECODR1','HARVESTDR1']]
workflows[4.20] = ['', ['RunPhoton2011A','RECODR1','HARVESTDR1']]
workflows[4.21] = ['', ['RunJet2011A','RECODR1','HARVESTDR1']]
workflows[4.22] = ['', ['RunCosmics2011A','RECOCOSD','ALCACOSD','SKIMCOSD','HARVESTDC']]
workflows[4.23] = ['',['ValSkim2011A','HLTDSKIM','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.24] = ['',['WMuSkim2011A','HLTDSKIM','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.25] = ['',['WElSkim2011A','HLTDSKIM','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.26] = ['',['ZMuSkim2011A','HLTDSKIM','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.27] = ['',['ZElSkim2011A','HLTDSKIM','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.28] = ['',['HighMet2011A','HLTDSKIM','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.29] = ['', ['RunMinBias2011B','HLTD','RECODR1reHLT','HARVESTDR1reHLT','SKIMDreHLT']]
#workflows[4.291] = ['', ['RunMinBias2011B','HLTD','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.30] = ['', ['RunMu2011B','HLTD','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.31] = ['', ['RunElectron2011B','HLTD','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.32] = ['', ['RunPhoton2011B','HLTD','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.33] = ['', ['RunJet2011B','HLTD','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.34] = ['',['ValSkim2011B','HLTDSKIM','RECODR1reHLT','HARVESTDR1reHLT']]
#workflows[4.35] = ['',['WMuSkim2011B','HLTDSKIM','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.36] = ['',['WElSkim2011B','HLTDSKIM','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.37] = ['',['ZMuSkim2011B','HLTDSKIM','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.38] = ['',['ZElSkim2011B','HLTDSKIM','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.39] = ['',['HighMet2011B','HLTDSKIM','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.40] = ['',['RunMinBias2012A','HLTD','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.41] = ['',['RunTau2012A','HLTD','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.42] = ['',['RunMET2012A','HLTD','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.43] = ['',['RunMu2012A','HLTD','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.44] = ['',['RunElectron2012A','HLTD','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.45] = ['',['RunJet2012A','HLTD','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.51] = ['',['RunMinBias2012B','HLTD','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.52] = ['',['RunMu2012B','HLTD','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.53] = ['',['RunPhoton2012B','HLTD','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.54] = ['',['RunEl2012B','HLTD','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.55] = ['',['RunJet2012B','HLTD','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.56] = ['',['ZMuSkim2012B','HLTDSKIM','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.57] = ['',['ZElSkim2012B','HLTDSKIM','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.58] = ['',['WElSkim2012B','HLTDSKIM','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.61] = ['',['RunMinBias2012C','HLTD','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.62] = ['',['RunMu2012C','HLTD','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.63] = ['',['RunPhoton2012C','HLTD','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.64] = ['',['RunEl2012C','HLTD','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.65] = ['',['RunJet2012C','HLTD','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.66] = ['',['ZMuSkim2012C','HLTDSKIM','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.67] = ['',['ZElSkim2012C','HLTDSKIM','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.68] = ['',['WElSkim2012C','HLTDSKIM','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.71] = ['',['RunMinBias2012D','HLTD','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.72] = ['',['RunMu2012D','HLTD','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.73] = ['',['RunPhoton2012D','HLTD','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.74] = ['',['RunEl2012D','HLTD','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.75] = ['',['RunJet2012D','HLTD','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.76] = ['',['ZMuSkim2012D','HLTDSKIM2','RECODR1reHLT2','HARVESTDR1reHLT']]
workflows[4.77] = ['',['ZElSkim2012D','HLTDSKIM','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[4.78] = ['',['WElSkim2012D','HLTDSKIM','RECODR1reHLT','HARVESTDR1reHLT']]
workflows[140.51] = ['',['RunHI2010','REPACKHID','RECOHID11St3','HARVESTDHI']]
workflows[140.52] = ['',['RunHI2010','RECOHID10','RECOHIR10D11','HARVESTDHI']]
workflows[140.53] = ['',['RunHI2011','RECOHID11','HARVESTDHI']]
workflows[140.54] = ['',['RunPA2013','RECO_PPbData','HARVEST_PPbData']]
workflows[140.55] = ['',['RunHI2015VR','HYBRIDRepackHI2015VR','HYBRIDZSHI2015','RECOHID15','HARVESTDHI15']]
workflows[140.56] = ['',['RunHI2018','RECOHID18','HARVESTDHI18']]
workflows[140.5611] = ['',['RunHI2018AOD','REMINIAODHID18','HARVESTHI18MINIAOD']]
workflows[140.57] = ['',['RunHI2018Reduced','RECOHID18','HARVESTDHI18']]
### run2 2015B 50ns ###
workflows[134.701] = ['',['RunHLTPhy2015B','HLTDR2_50ns','RECODR2_50nsreHLT_HIPM','HARVESTDR2']]
workflows[134.702] = ['',['RunDoubleEG2015B','HLTDR2_50ns','RECODR2_50nsreHLT_HIPM','HARVESTDR2']]
workflows[134.703] = ['',['RunDoubleMuon2015B','HLTDR2_50ns','RECODR2_50nsreHLT_HIPM','HARVESTDR2']]
workflows[134.704] = ['',['RunJetHT2015B','HLTDR2_50ns','RECODR2_50nsreHLT_HIPM','HARVESTDR2']]
workflows[134.705] = ['',['RunMET2015B','HLTDR2_50ns','RECODR2_50nsreHLT_HIPM','HARVESTDR2']]
workflows[134.706] = ['',['RunMuonEG2015B','HLTDR2_50ns','RECODR2_50nsreHLT_HIPM','HARVESTDR2']]
workflows[134.707] = ['',['RunSingleEl2015B','HLTDR2_50ns','RECODR2_50nsreHLT_HIPM','HARVESTDR2']]
workflows[134.708] = ['',['RunSingleMu2015B','HLTDR2_50ns','RECODR2_50nsreHLT_HIPM','HARVESTDR2']]
workflows[134.709] = ['',['RunSinglePh2015B','HLTDR2_50ns','RECODR2_50nsreHLT_HIPM','HARVESTDR2']]
workflows[134.710] = ['',['RunZeroBias2015B','HLTDR2_50ns','RECODR2_50nsreHLT_ZB_HIPM','HARVESTDR2ZB']]
### run 2015C 25ns ###
workflows[134.801] = ['',['RunHLTPhy2015C','HLTDR2_25ns','RECODR2_25nsreHLT_HIPM','HARVESTDR2']]
workflows[134.802] = ['',['RunDoubleEG2015C','HLTDR2_25ns','RECODR2_25nsreHLT_HIPM','HARVESTDR2']]
workflows[134.803] = ['',['RunDoubleMuon2015C','HLTDR2_25ns','RECODR2_25nsreHLT_HIPM','HARVESTDR2']]
workflows[134.804] = ['',['RunJetHT2015C','HLTDR2_25ns','RECODR2_25nsreHLT_HIPM','HARVESTDR2']]
workflows[134.805] = ['',['RunMET2015C','HLTDR2_25ns','RECODR2_25nsreHLT_HIPM','HARVESTDR2']]
workflows[134.806] = ['',['RunMuonEG2015C','HLTDR2_25ns','RECODR2_25nsreHLT_HIPM','HARVESTDR2']]
workflows[134.807] = ['',['RunDoubleEGPrpt2015C','HLTDR2_25ns','RECODR2_25nsreHLT_HIPM','HARVESTDR2']]
workflows[134.808] = ['',['RunSingleMuPrpt2015C','HLTDR2_25ns','RECODR2_25nsreHLT_HIPM','HARVESTDR2']]
workflows[134.809] = ['',['RunSingleEl2015C','HLTDR2_25ns','RECODR2_25nsreHLT_HIPM','HARVESTDR2']]
workflows[134.810] = ['',['RunSingleMu2015C','HLTDR2_25ns','RECODR2_25nsreHLT_HIPM','HARVESTDR2']]
workflows[134.811] = ['',['RunSinglePh2015C','HLTDR2_25ns','RECODR2_25nsreHLT_HIPM','HARVESTDR2']]
workflows[134.812] = ['',['RunZeroBias2015C','HLTDR2_25ns','RECODR2_25nsreHLT_ZB_HIPM','HARVESTDR2ZB']]
workflows[134.813] = ['',['RunCosmics2015C','RECOCOSDRUN2','ALCACOSDRUN2','HARVESTDCRUN2']]
### run 2015D 25ns ###
workflows[134.901] = ['',['RunHLTPhy2015D','HLTDR2_25ns','RECODR2_25nsreHLT_HIPM','HARVESTDR2']]
workflows[134.902] = ['',['RunDoubleEG2015D','HLTDR2_25ns','RECODR2_25nsreHLT_HIPM','HARVESTDR2']]
workflows[134.903] = ['',['RunDoubleMuon2015D','HLTDR2_25ns','RECODR2_25nsreHLT_HIPM','HARVESTDR2']]
workflows[134.904] = ['',['RunJetHT2015D','HLTDR2_25ns','RECODR2_25nsreHLT_HIPM','HARVESTDR2']]
workflows[134.905] = ['',['RunMET2015D','HLTDR2_25ns','RECODR2_25nsreHLT_HIPM','HARVESTDR2']]
workflows[134.906] = ['',['RunMuonEG2015D','HLTDR2_25ns','RECODR2_25nsreHLT_HIPM','HARVESTDR2']]
workflows[134.907] = ['',['RunDoubleEGPrpt2015D','HLTDR2_25ns','RECODR2_25nsreHLT_HIPM','HARVESTDR2']]
workflows[134.908] = ['',['RunSingleMuPrpt2015D','HLTDR2_25ns','RECODR2_25nsreHLT_HIPM','HARVESTDR2']]
workflows[134.909] = ['',['RunSingleEl2015D','HLTDR2_25ns','RECODR2_25nsreHLT_HIPM','HARVESTDR2']]
workflows[134.910] = ['',['RunSingleMu2015D','HLTDR2_25ns','RECODR2_25nsreHLT_HIPM','HARVESTDR2']]
workflows[134.911] = ['',['RunSinglePh2015D','HLTDR2_25ns','RECODR2_25nsreHLT_HIPM','HARVESTDR2']]
workflows[134.912] = ['',['RunZeroBias2015D','HLTDR2_25ns','RECODR2_25nsreHLT_ZB_HIPM','HARVESTDR2ZB']]
### run 2016B ###
workflows[136.721] = ['',['RunHLTPhy2016B','HLTDR2_2016','RECODR2_2016reHLT_HIPM','HARVESTDR2']]
workflows[136.722] = ['',['RunDoubleEG2016B','HLTDR2_2016','RECODR2_2016reHLT_skimDoubleEG_HIPM','HARVESTDR2']]
workflows[136.723] = ['',['RunDoubleMuon2016B','HLTDR2_2016','RECODR2_2016reHLT_HIPM','HARVESTDR2']]
workflows[136.724] = ['',['RunJetHT2016B','HLTDR2_2016','RECODR2_2016reHLT_skimJetHT_HIPM','HARVESTDR2']]
workflows[136.725] = ['',['RunMET2016B','HLTDR2_2016','RECODR2_2016reHLT_skimMET_HIPM','HARVESTDR2']]
workflows[136.726] = ['',['RunMuonEG2016B','HLTDR2_2016','RECODR2_2016reHLT_skimMuonEG_HIPM','HARVESTDR2']]
workflows[136.727] = ['',['RunDoubleEGPrpt2016B','HLTDR2_2016','RECODR2_2016reHLT_HIPM','HARVESTDR2']]
workflows[136.728] = ['',['RunSingleMuPrpt2016B','HLTDR2_2016','RECODR2_2016reHLT_HIPM','HARVESTDR2']]
workflows[136.729] = ['',['RunSingleEl2016B','HLTDR2_2016','RECODR2_2016reHLT_L1TEgDQM_HIPM','HARVEST2016_L1TEgDQM']]
workflows[136.730] = ['',['RunSingleMu2016B','HLTDR2_2016','RECODR2_2016reHLT_skimSingleMu_HIPM','HARVEST2016_L1TMuDQM']]
workflows[136.731] = ['',['RunSinglePh2016B','HLTDR2_2016','RECODR2_2016reHLT_skimSinglePh_HIPM','HARVESTDR2']]
workflows[136.732] = ['',['RunZeroBias2016B','HLTDR2_2016','RECODR2_2016reHLT_ZB_HIPM','HARVESTDR2ZB']]
workflows[136.733] = ['',['RunCosmics2016B','RECOCOSDRUN2','ALCACOSDRUN2','HARVESTDCRUN2']]
workflows[136.734] = ['',['RunMuOnia2016B','HLTDR2_2016','RECODR2_2016reHLT_skimMuOnia_HIPM','HARVESTDR2']]
workflows[136.735] = ['',['RunNoBPTX2016B','HLTDR2_2016','RECODR2reHLTAlCaTkCosmics_HIPM','HARVESTDR2']]
# reminiAOD wf on 2016B input, mainly here for PPS testing
workflows[136.72411] = ['',['RunJetHT2016B_reminiaodUL','REMINIAOD_data2016UL_HIPM','HARVESTDR2_REMINIAOD_data2016UL_HIPM']]
workflows[136.72412] = ['',['RunJetHT2016B_reminiaodUL','REMININANO_data2016UL_HIPM','HARVESTDR2_REMININANO_data2016UL_HIPM']]
#workflows[136.72413] = ['',['RunJetHT2016B_reminiaodUL','REMININANO_data2016UL_HIPM_met','HARVESTDR2_REMININANO_data2016UL_HIPM_met']] #diable for now until MET is fixed.
### run 2016C ###
workflows[136.736] = ['',['RunHLTPhy2016C','HLTDR2_2016','RECODR2_2016reHLT_HIPM','HARVESTDR2']]
workflows[136.737] = ['',['RunDoubleEG2016C','HLTDR2_2016','RECODR2_2016reHLT_skimDoubleEG_HIPM','HARVESTDR2']]
workflows[136.738] = ['',['RunDoubleMuon2016C','HLTDR2_2016','RECODR2_2016reHLT_HIPM','HARVESTDR2']]
workflows[136.739] = ['',['RunJetHT2016C','HLTDR2_2016','RECODR2_2016reHLT_skimJetHT_HIPM','HARVESTDR2']]
workflows[136.740] = ['',['RunMET2016C','HLTDR2_2016','RECODR2_2016reHLT_skimMET_HIPM','HARVESTDR2']]
workflows[136.741] = ['',['RunMuonEG2016C','HLTDR2_2016','RECODR2_2016reHLT_skimMuonEG_HIPM','HARVESTDR2']]
workflows[136.742] = ['',['RunSingleEl2016C','HLTDR2_2016','RECODR2_2016reHLT_L1TEgDQM_HIPM','HARVEST2016_L1TEgDQM']]
workflows[136.743] = ['',['RunSingleMu2016C','HLTDR2_2016','RECODR2_2016reHLT_L1TMuDQM_HIPM','HARVEST2016_L1TMuDQM']]
workflows[136.744] = ['',['RunSinglePh2016C','HLTDR2_2016','RECODR2_2016reHLT_skimSinglePh_HIPM','HARVESTDR2']]
workflows[136.745] = ['',['RunZeroBias2016C','HLTDR2_2016','RECODR2_2016reHLT_ZB_HIPM','HARVESTDR2ZB']]
workflows[136.746] = ['',['RunMuOnia2016C','HLTDR2_2016','RECODR2_2016reHLT_skimMuOnia_HIPM','HARVESTDR2']]
### run 2016D ###
workflows[136.747] = ['',['RunHLTPhy2016D','HLTDR2_2016','RECODR2_2016reHLT_HIPM','HARVESTDR2']]
workflows[136.748] = ['',['RunDoubleEG2016D','HLTDR2_2016','RECODR2_2016reHLT_skimDoubleEG_HIPM','HARVESTDR2']]
workflows[136.749] = ['',['RunDoubleMuon2016D','HLTDR2_2016','RECODR2_2016reHLT_HIPM','HARVESTDR2']]
workflows[136.750] = ['',['RunJetHT2016D','HLTDR2_2016','RECODR2_2016reHLT_skimJetHT_HIPM','HARVESTDR2']]
workflows[136.751] = ['',['RunMET2016D','HLTDR2_2016','RECODR2_2016reHLT_skimMET_HIPM','HARVESTDR2']]
workflows[136.752] = ['',['RunMuonEG2016D','HLTDR2_2016','RECODR2_2016reHLT_skimMuonEG_HIPM','HARVESTDR2']]
workflows[136.753] = ['',['RunSingleEl2016D','HLTDR2_2016','RECODR2_2016reHLT_L1TEgDQM_HIPM','HARVEST2016_L1TEgDQM']]
workflows[136.754] = ['',['RunSingleMu2016D','HLTDR2_2016','RECODR2_2016reHLT_L1TMuDQM_HIPM','HARVEST2016_L1TMuDQM']]
workflows[136.755] = ['',['RunSinglePh2016D','HLTDR2_2016','RECODR2_2016reHLT_skimSinglePh_HIPM','HARVESTDR2']]
workflows[136.756] = ['',['RunZeroBias2016D','HLTDR2_2016','RECODR2_2016reHLT_ZB_HIPM','HARVESTDR2ZB']]
workflows[136.757] = ['',['RunMuOnia2016D','HLTDR2_2016','RECODR2_2016reHLT_skimMuOnia_HIPM','HARVESTDR2']]
### run 2016E ###
workflows[136.758] = ['',['RunHLTPhy2016E','HLTDR2_2016','RECODR2_2016reHLT_HIPM','HARVESTDR2']]
workflows[136.759] = ['',['RunDoubleEG2016E','HLTDR2_2016','RECODR2_2016reHLT_skimDoubleEG_HIPM','HARVESTDR2']]
workflows[136.760] = ['',['RunDoubleMuon2016E','HLTDR2_2016','RECODR2_2016reHLT_HIPM','HARVESTDR2']]
workflows[136.761] = ['',['RunJetHT2016E','HLTDR2_2016','RECODR2_2016reHLT_skimJetHT_HIPM','HARVESTDR2']]
workflows[136.762] = ['',['RunMET2016E','HLTDR2_2016','RECODR2_2016reHLT_skimMET_HIPM','HARVESTDR2']]
workflows[136.763] = ['',['RunMuonEG2016E','HLTDR2_2016','RECODR2_2016reHLT_skimMuonEG_HIPM','HARVESTDR2']]
workflows[136.764] = ['',['RunSingleEl2016E','HLTDR2_2016','RECODR2_2016reHLT_L1TEgDQM_HIPM','HARVEST2016_L1TEgDQM']]
workflows[136.765] = ['',['RunSingleMu2016E','HLTDR2_2016','RECODR2_2016reHLT_L1TMuDQM_HIPM','HARVEST2016_L1TMuDQM']]
workflows[136.766] = ['',['RunSinglePh2016E','HLTDR2_2016','RECODR2_2016reHLT_skimSinglePh_HIPM','HARVESTDR2']]
workflows[136.767] = ['',['RunZeroBias2016E','HLTDR2_2016','RECODR2_2016reHLT_ZB_HIPM','HARVESTDR2ZB']]
workflows[136.768] = ['',['RunMuOnia2016E','HLTDR2_2016','RECODR2_2016reHLT_skimMuOnia_HIPM','HARVESTDR2']]
# reminiAOD wf on 2016E input
workflows[136.7611] = ['',['RunJetHT2016E_reminiaod','REMINIAOD_data2016_HIPM','HARVESTDR2_REMINIAOD_data2016_HIPM']]
workflows[136.76111] = ['',['RunJetHT2016E_reminiaodUL','REMINIAOD_data2016UL_HIPM','HARVESTDR2_REMINIAOD_data2016UL_HIPM']]
### run 2016H ###
workflows[136.769] = ['',['RunHLTPhy2016H','HLTDR2_2016','RECODR2_2016reHLT_Prompt','HARVESTDR2']]
workflows[136.770] = ['',['RunDoubleEG2016H','HLTDR2_2016','RECODR2_2016reHLT_skimDoubleEG_Prompt','HARVESTDR2']]
workflows[136.771] = ['',['RunDoubleMuon2016H','HLTDR2_2016','RECODR2_2016reHLT_Prompt','HARVESTDR2']]
workflows[136.772] = ['',['RunJetHT2016H','HLTDR2_2016','RECODR2_2016reHLT_skimJetHT_Prompt','HARVESTDR2']]
workflows[136.773] = ['',['RunMET2016H','HLTDR2_2016','RECODR2_2016reHLT_skimMET_Prompt','HARVESTDR2']]
workflows[136.774] = ['',['RunMuonEG2016H','HLTDR2_2016','RECODR2_2016reHLT_skimMuonEG_Prompt','HARVESTDR2']]
workflows[136.775] = ['',['RunSingleEl2016H','HLTDR2_2016','RECODR2_2016reHLT_Prompt_L1TEgDQM','HARVEST2016_L1TEgDQM']]
workflows[136.776] = ['',['RunSingleMu2016H','HLTDR2_2016','RECODR2_2016reHLT_Prompt_Lumi_L1TMuDQM','HARVEST2016_L1TMuDQM']]
workflows[136.777] = ['',['RunSinglePh2016H','HLTDR2_2016','RECODR2_2016reHLT_skimSinglePh_Prompt','HARVESTDR2']]
workflows[136.778] = ['',['RunZeroBias2016H','HLTDR2_2016','RECODR2_2016reHLT_ZBPrompt','HARVESTDR2ZB']]
workflows[136.779] = ['',['RunMuOnia2016H','HLTDR2_2016','RECODR2_2016reHLT_skimMuOnia_Prompt','HARVESTDR2']]
# reminiAOD wf on 2016H input
workflows[136.7721] = ['',['RunJetHT2016H_reminiaod','REMINIAOD_data2016','HARVESTDR2_REMINIAOD_data2016']]
workflows[136.77211] = ['',['RunJetHT2016H_reminiaodUL','REMINIAOD_data2016UL','HARVESTDR2_REMINIAOD_data2016UL']]
# nanoAOD wf on 2016H 80X input
workflows[136.7722] = ['',['RunJetHT2016H_nano','NANOEDM2016_80X','HARVESTNANOAOD2016_80X']]
### run 2017B ###
workflows[136.780] = ['',['RunHLTPhy2017B','HLTDR2_2017','RECODR2_2017reHLT_Prompt','HARVEST2017']]
workflows[136.781] = ['',['RunDoubleEG2017B','HLTDR2_2017','RECODR2_2017reHLT_skimDoubleEG_Prompt','HARVEST2017']]
workflows[136.782] = ['',['RunDoubleMuon2017B','HLTDR2_2017','RECODR2_2017reHLT_Prompt','HARVEST2017']]
workflows[136.783] = ['',['RunJetHT2017B','HLTDR2_2017','RECODR2_2017reHLT_skimJetHT_Prompt','HARVEST2017']]
workflows[136.784] = ['',['RunMET2017B','HLTDR2_2017','RECODR2_2017reHLT_skimMET_Prompt','HARVEST2017']]
workflows[136.785] = ['',['RunMuonEG2017B','HLTDR2_2017','RECODR2_2017reHLT_skimMuonEG_Prompt','HARVEST2017']]
workflows[136.786] = ['',['RunSingleEl2017B','HLTDR2_2017','RECODR2_2017reHLT_Prompt_L1TEgDQM','HARVEST2017_L1TEgDQM']]
workflows[136.787] = ['',['RunSingleMu2017B','HLTDR2_2017','RECODR2_2017reHLT_skimSingleMu_Prompt_Lumi','HARVEST2017_L1TMuDQM']]
workflows[136.788] = ['',['RunSinglePh2017B','HLTDR2_2017','RECODR2_2017reHLT_skimSinglePh_Prompt','HARVEST2017']]
workflows[136.789] = ['',['RunZeroBias2017B','HLTDR2_2017','RECODR2_2017reHLT_ZBPrompt','HARVEST2017ZB']]
workflows[136.790] = ['',['RunMuOnia2017B','HLTDR2_2017','RECODR2_2017reHLT_skimMuOnia_Prompt','HARVEST2017']]
workflows[136.791] = ['',['RunNoBPTX2017B','HLTDR2_2017','RECODR2_2017reHLTAlCaTkCosmics_Prompt','HARVEST2017']]
workflows[136.7801] = ['',['RunHLTPhy2017B_AOD','DQMHLTonAOD_2017','HARVESTDQMHLTonAOD_2017']]
workflows[136.7802] = ['',['RunHLTPhy2017B_AODextra','DQMHLTonAODextra_2017','HARVESTDQMHLTonAOD_2017']]
workflows[136.7803] = ['',['RunHLTPhy2017B_RAWAOD','DQMHLTonRAWAOD_2017','HARVESTDQMHLTonAOD_2017']]
workflows[136.844] = ['',['RunCharmonium2017B','HLTDR2_2017','RECODR2_2017reHLT_skimCharmonium_Prompt','HARVEST2017']]
### run 2017C ###
workflows[136.792] = ['',['RunHLTPhy2017C','HLTDR2_2017','RECODR2_2017reHLT_Prompt','HARVEST2017']]
workflows[136.793] = ['',['RunDoubleEG2017C','HLTDR2_2017','RECODR2_2017reHLT_skimDoubleEG_Prompt','HARVEST2017']]
workflows[136.794] = ['',['RunDoubleMuon2017C','HLTDR2_2017','RECODR2_2017reHLT_Prompt','HARVEST2017']]
workflows[136.795] = ['',['RunJetHT2017C','HLTDR2_2017','RECODR2_2017reHLT_skimJetHT_Prompt','HARVEST2017']]
workflows[136.796] = ['',['RunMET2017C','HLTDR2_2017','RECODR2_2017reHLT_skimMET_Prompt','HARVEST2017']]
workflows[136.797] = ['',['RunMuonEG2017C','HLTDR2_2017','RECODR2_2017reHLT_skimMuonEG_Prompt','HARVEST2017']]
workflows[136.798] = ['',['RunSingleEl2017C','HLTDR2_2017','RECODR2_2017reHLT_Prompt_L1TEgDQM','HARVEST2017_L1TEgDQM']]
workflows[136.799] = ['',['RunSingleMu2017C','HLTDR2_2017','RECODR2_2017reHLT_skimSingleMu_Prompt_Lumi','HARVEST2017_L1TMuDQM']]
workflows[136.800] = ['',['RunSinglePh2017C','HLTDR2_2017','RECODR2_2017reHLT_skimSinglePh_Prompt','HARVEST2017']]
workflows[136.801] = ['',['RunZeroBias2017C','HLTDR2_2017','RECODR2_2017reHLT_ZBPrompt','HARVEST2017ZB']]
workflows[136.802] = ['',['RunMuOnia2017C','HLTDR2_2017','RECODR2_2017reHLT_skimMuOnia_Prompt','HARVEST2017']]
workflows[136.803] = ['',['RunNoBPTX2017C','HLTDR2_2017','RECODR2_2017reHLTAlCaTkCosmics_Prompt','HARVEST2017']]
workflows[136.840] = ['',['RunDisplacedJet2017C','HLTDR2_2017','RECODR2_2017reHLT_skimDisplacedJet_Prompt','HARVEST2017']]
workflows[136.845] = ['',['RunCharmonium2017C','HLTDR2_2017','RECODR2_2017reHLT_skimCharmonium_Prompt','HARVEST2017']]
### run 2017D ###
workflows[136.804] = ['',['RunHLTPhy2017D','HLTDR2_2017','RECODR2_2017reHLT_Prompt','HARVEST2017']]
workflows[136.805] = ['',['RunDoubleEG2017D','HLTDR2_2017','RECODR2_2017reHLT_skimDoubleEG_Prompt','HARVEST2017']]
workflows[136.806] = ['',['RunDoubleMuon2017D','HLTDR2_2017','RECODR2_2017reHLT_Prompt','HARVEST2017']]
workflows[136.807] = ['',['RunJetHT2017D','HLTDR2_2017','RECODR2_2017reHLT_skimJetHT_Prompt','HARVEST2017']]
workflows[136.808] = ['',['RunMET2017D','HLTDR2_2017','RECODR2_2017reHLT_skimMET_Prompt','HARVEST2017']]
workflows[136.809] = ['',['RunMuonEG2017D','HLTDR2_2017','RECODR2_2017reHLT_skimMuonEG_Prompt','HARVEST2017']]
workflows[136.810] = ['',['RunSingleEl2017D','HLTDR2_2017','RECODR2_2017reHLT_Prompt_L1TEgDQM','HARVEST2017_L1TEgDQM']]
workflows[136.811] = ['',['RunSingleMu2017D','HLTDR2_2017','RECODR2_2017reHLT_skimSingleMu_Prompt_Lumi','HARVEST2017_L1TMuDQM']]
workflows[136.812] = ['',['RunSinglePh2017D','HLTDR2_2017','RECODR2_2017reHLT_skimSinglePh_Prompt','HARVEST2017']]
workflows[136.813] = ['',['RunZeroBias2017D','HLTDR2_2017','RECODR2_2017reHLT_ZBPrompt','HARVEST2017ZB']]
workflows[136.814] = ['',['RunMuOnia2017D','HLTDR2_2017','RECODR2_2017reHLT_skimMuOnia_Prompt','HARVEST2017']]
workflows[136.815] = ['',['RunNoBPTX2017D','HLTDR2_2017','RECODR2_2017reHLTAlCaTkCosmics_Prompt','HARVEST2017']]
workflows[136.841] = ['',['RunDisplacedJet2017D','HLTDR2_2017','RECODR2_2017reHLT_skimDisplacedJet_Prompt','HARVEST2017']]
workflows[136.846] = ['',['RunCharmonium2017D','HLTDR2_2017','RECODR2_2017reHLT_skimCharmonium_Prompt','HARVEST2017']]
### run 2017E ###
workflows[136.816] = ['',['RunHLTPhy2017E','HLTDR2_2017','RECODR2_2017reHLT_Prompt','HARVEST2017']]
workflows[136.817] = ['',['RunDoubleEG2017E','HLTDR2_2017','RECODR2_2017reHLT_skimDoubleEG_Prompt','HARVEST2017']]
workflows[136.818] = ['',['RunDoubleMuon2017E','HLTDR2_2017','RECODR2_2017reHLT_Prompt','HARVEST2017']]
workflows[136.819] = ['',['RunJetHT2017E','HLTDR2_2017','RECODR2_2017reHLT_skimJetHT_Prompt','HARVEST2017']]
workflows[136.820] = ['',['RunMET2017E','HLTDR2_2017','RECODR2_2017reHLT_skimMET_Prompt','HARVEST2017']]
workflows[136.821] = ['',['RunMuonEG2017E','HLTDR2_2017','RECODR2_2017reHLT_skimMuonEG_Prompt','HARVEST2017']]
workflows[136.822] = ['',['RunSingleEl2017E','HLTDR2_2017','RECODR2_2017reHLT_Prompt_L1TEgDQM','HARVEST2017_L1TEgDQM']]
workflows[136.823] = ['',['RunSingleMu2017E','HLTDR2_2017','RECODR2_2017reHLT_skimSingleMu_Prompt_Lumi','HARVEST2017_L1TMuDQM']]
workflows[136.824] = ['',['RunSinglePh2017E','HLTDR2_2017','RECODR2_2017reHLT_skimSinglePh_Prompt','HARVEST2017']]
workflows[136.825] = ['',['RunZeroBias2017E','HLTDR2_2017','RECODR2_2017reHLT_ZBPrompt','HARVEST2017ZB']]
workflows[136.826] = ['',['RunMuOnia2017E','HLTDR2_2017','RECODR2_2017reHLT_skimMuOnia_Prompt','HARVEST2017']]
workflows[136.827] = ['',['RunNoBPTX2017E','HLTDR2_2017','RECODR2_2017reHLTAlCaTkCosmics_Prompt','HARVEST2017']]
workflows[136.842] = ['',['RunDisplacedJet2017E','HLTDR2_2017','RECODR2_2017reHLT_skimDisplacedJet_Prompt','HARVEST2017']]
workflows[136.847] = ['',['RunCharmonium2017E','HLTDR2_2017','RECODR2_2017reHLT_skimCharmonium_Prompt','HARVEST2017']]
### run 2017F ###
workflows[136.828] = ['',['RunHLTPhy2017F','HLTDR2_2017','RECODR2_2017reHLT_Prompt','HARVEST2017']]
workflows[136.829] = ['',['RunDoubleEG2017F','HLTDR2_2017','RECODR2_2017reHLT_skimDoubleEG_Prompt','HARVEST2017']]
workflows[136.830] = ['',['RunDoubleMuon2017F','HLTDR2_2017','RECODR2_2017reHLT_Prompt','HARVEST2017']]
workflows[136.831] = ['',['RunJetHT2017F','HLTDR2_2017','RECODR2_2017reHLT_skimJetHT_Prompt','HARVEST2017']]
workflows[136.832] = ['',['RunMET2017F','HLTDR2_2017','RECODR2_2017reHLT_skimMET_Prompt','HARVEST2017']]
workflows[136.833] = ['',['RunMuonEG2017F','HLTDR2_2017','RECODR2_2017reHLT_skimMuonEG_Prompt','HARVEST2017']]
workflows[136.834] = ['',['RunSingleEl2017F','HLTDR2_2017','RECODR2_2017reHLT_Prompt_L1TEgDQM','HARVEST2017_L1TEgDQM']]
workflows[136.835] = ['',['RunSingleMu2017F','HLTDR2_2017','RECODR2_2017reHLT_skimSingleMu_Prompt_Lumi','HARVEST2017_L1TMuDQM']]
workflows[136.836] = ['',['RunSinglePh2017F','HLTDR2_2017','RECODR2_2017reHLT_skimSinglePh_Prompt','HARVEST2017']]
workflows[136.837] = ['',['RunZeroBias2017F','HLTDR2_2017','RECODR2_2017reHLT_ZBPrompt','HARVEST2017ZB']]
workflows[136.838] = ['',['RunMuOnia2017F','HLTDR2_2017','RECODR2_2017reHLT_skimMuOnia_Prompt','HARVEST2017']]
workflows[136.839] = ['',['RunNoBPTX2017F','HLTDR2_2017','RECODR2_2017reHLTAlCaTkCosmics_Prompt','HARVEST2017']]
workflows[136.8391] = ['',['RunExpressPhy2017F','HLTDR2_2017','RECODR2_2017reHLTSiPixelCalZeroBias_Prompt','HARVEST2017']]
workflows[136.843] = ['',['RunDisplacedJet2017F','HLTDR2_2017','RECODR2_2017reHLT_skimDisplacedJet_Prompt','HARVEST2017']]
workflows[136.848] = ['',['RunCharmonium2017F','HLTDR2_2017','RECODR2_2017reHLT_skimCharmonium_Prompt','HARVEST2017']]
# reminiAOD wf on 2017F input
workflows[136.8311] = ['',['RunJetHT2017F_reminiaod','REMINIAOD_data2017','HARVEST2017_REMINIAOD_data2017']]
workflows[136.83111] = ['',['RunJetHT2017F_reminiaodUL','REMINIAOD_data2017UL','HARVEST2017_REMINIAOD_data2017UL']]
# NANOAOD wf on 2017C miniAODv2 94X input
workflows[136.7952] = ['',['RunJetHT2017C_94Xv2NanoAODINPUT','NANOEDM2017_94XMiniAODv2','HARVESTNANOAOD2017_94XMiniAODv2']]
### run 2018A ###
workflows[136.849] = ['',['RunHLTPhy2018A','HLTDR2_2018','RECODR2_2018reHLT_Offline','HARVEST2018']]
workflows[136.850] = ['',['RunEGamma2018A','HLTDR2_2018','RECODR2_2018reHLT_skimEGamma_Offline_L1TEgDQM','HARVEST2018_L1TEgDQM']]
workflows[136.851] = ['',['RunDoubleMuon2018A','HLTDR2_2018','RECODR2_2018reHLT_Offline','HARVEST2018']]
workflows[136.852] = ['',['RunJetHT2018A','HLTDR2_2018','RECODR2_2018reHLT_skimJetHT_Offline','HARVEST2018']]
workflows[136.853] = ['',['RunMET2018A','HLTDR2_2018','RECODR2_2018reHLT_skimMET_Offline','HARVEST2018']]
workflows[136.854] = ['',['RunMuonEG2018A','HLTDR2_2018','RECODR2_2018reHLT_skimMuonEG_Offline','HARVEST2018']]
workflows[136.855] = ['',['RunSingleMu2018A','HLTDR2_2018','RECODR2_2018reHLT_skimSingleMu_Offline_Lumi','HARVEST2018_L1TMuDQM']]
workflows[136.856] = ['',['RunZeroBias2018A','HLTDR2_2018','RECODR2_2018reHLT_ZBOffline','HARVEST2018ZB']]
workflows[136.857] = ['',['RunMuOnia2018A','HLTDR2_2018','RECODR2_2018reHLT_skimMuOnia_Offline','HARVEST2018']]
workflows[136.858] = ['',['RunNoBPTX2018A','HLTDR2_2018','RECODR2_2018reHLTAlCaTkCosmics_Offline','HARVEST2018']]
workflows[136.859] = ['',['RunDisplacedJet2018A','HLTDR2_2018','RECODR2_2018reHLT_skimDisplacedJet_Offline','HARVEST2018']]
workflows[136.860] = ['',['RunCharmonium2018A','HLTDR2_2018','RECODR2_2018reHLT_skimCharmonium_Offline','HARVEST2018']]
### wf to test 90 m beta* Totem run reconstruction ###
workflows[136.8501] = ['',['RunEGamma2018A','HLTDR2_2018','RECODR2_2018reHLT_skimParkingBPH_Offline','HARVEST2018']]
workflows[136.8561] = ['',['RunZeroBias_hBStarTk','HLTDR2_2018_hBStar','RECODR2_2018reHLT_Offline_hBStar','HARVEST2018_hBStar']]
workflows[136.8562] = ['',['RunZeroBias1_hBStarRP','HLTDR2_2018_hBStar','RECODR2_2018reHLT_Offline_hBStar','HARVEST2018_hBStar']]
### NANOAOD wf on 2018 prompt reco MINIADD
workflows[136.8521] = ['',['RunJetHT2018A_nano','NANOEDM2018_102Xv1','HARVESTNANOAOD2018_102Xv1']]
workflows[136.8522] = ['',['RunJetHT2018A_nanoUL','NANOEDM2018_106Xv1','HARVESTNANOAOD2018_106Xv1']]
workflows[136.8523] = ['',['RunJetHT2018C_nanoULremini','NANOEDM2018_106Xv2','HARVESTNANOAOD2018_106Xv2']]
### run 2018B ###
workflows[136.861] = ['',['RunHLTPhy2018B','HLTDR2_2018','RECODR2_2018reHLT_Offline','HARVEST2018']]
workflows[136.862] = ['',['RunEGamma2018B','HLTDR2_2018','RECODR2_2018reHLT_skimEGamma_Offline_L1TEgDQM','HARVEST2018_L1TEgDQM']]
workflows[136.863] = ['',['RunDoubleMuon2018B','HLTDR2_2018','RECODR2_2018reHLT_Offline','HARVEST2018']]
workflows[136.864] = ['',['RunJetHT2018B','HLTDR2_2018','RECODR2_2018reHLT_skimJetHT_Offline','HARVEST2018']]
workflows[136.865] = ['',['RunMET2018B','HLTDR2_2018','RECODR2_2018reHLT_skimMET_Offline','HARVEST2018']]
workflows[136.866] = ['',['RunMuonEG2018B','HLTDR2_2018','RECODR2_2018reHLT_skimMuonEG_Offline','HARVEST2018']]
workflows[136.867] = ['',['RunSingleMu2018B','HLTDR2_2018','RECODR2_2018reHLT_skimSingleMu_Offline_Lumi','HARVEST2018_L1TMuDQM']]
workflows[136.868] = ['',['RunZeroBias2018B','HLTDR2_2018','RECODR2_2018reHLT_ZBOffline','HARVEST2018ZB']]
workflows[136.869] = ['',['RunMuOnia2018B','HLTDR2_2018','RECODR2_2018reHLT_skimMuOnia_Offline','HARVEST2018']]
workflows[136.870] = ['',['RunNoBPTX2018B','HLTDR2_2018','RECODR2_2018reHLTAlCaTkCosmics_Offline','HARVEST2018']]
workflows[136.871] = ['',['RunDisplacedJet2018B','HLTDR2_2018','RECODR2_2018reHLT_skimDisplacedJet_Offline','HARVEST2018']]
workflows[136.872] = ['',['RunCharmonium2018B','HLTDR2_2018','RECODR2_2018reHLT_skimCharmonium_Offline','HARVEST2018']]
workflows[136.898] = ['',['RunParkingBPH2018B','HLTDR2_2018','RECODR2_2018reHLT_skimParkingBPH_Offline','HARVEST2018']]
workflows[136.8642] = ['',['RunJetHT2018BHEfail','HLTDR2_2018','RECODR2_2018reHLT_skimJetHT_Prompt_HEfail','HARVEST2018_HEfail']]
### run 2018C ###
workflows[136.873] = ['',['RunHLTPhy2018C','HLTDR2_2018','RECODR2_2018reHLT_Offline','HARVEST2018']]
workflows[136.874] = ['',['RunEGamma2018C','HLTDR2_2018','RECODR2_2018reHLT_skimEGamma_Offline_L1TEgDQM','HARVEST2018_L1TEgDQM']]
workflows[136.875] = ['',['RunDoubleMuon2018C','HLTDR2_2018','RECODR2_2018reHLT_Offline','HARVEST2018']]
workflows[136.876] = ['',['RunJetHT2018C','HLTDR2_2018','RECODR2_2018reHLT_skimJetHT_Offline','HARVEST2018']]
workflows[136.877] = ['',['RunMET2018C','HLTDR2_2018','RECODR2_2018reHLT_skimMET_Offline','HARVEST2018']]
workflows[136.878] = ['',['RunMuonEG2018C','HLTDR2_2018','RECODR2_2018reHLT_skimMuonEG_Offline','HARVEST2018']]
workflows[136.879] = ['',['RunSingleMu2018C','HLTDR2_2018','RECODR2_2018reHLT_skimSingleMu_Offline_Lumi','HARVEST2018_L1TMuDQM']]
workflows[136.880] = ['',['RunZeroBias2018C','HLTDR2_2018','RECODR2_2018reHLT_ZBOffline','HARVEST2018ZB']]
workflows[136.881] = ['',['RunMuOnia2018C','HLTDR2_2018','RECODR2_2018reHLT_skimMuOnia_Offline','HARVEST2018']]
workflows[136.882] = ['',['RunNoBPTX2018C','HLTDR2_2018','RECODR2_2018reHLTAlCaTkCosmics_Offline','HARVEST2018']]
workflows[136.883] = ['',['RunDisplacedJet2018C','HLTDR2_2018','RECODR2_2018reHLT_skimDisplacedJet_Offline','HARVEST2018']]
workflows[136.884] = ['',['RunCharmonium2018C','HLTDR2_2018','RECODR2_2018reHLT_skimCharmonium_Offline','HARVEST2018']]
### run 2018D ###
workflows[136.885] = ['',['RunHLTPhy2018D','HLTDR2_2018','RECODR2_2018reHLT_Prompt','HARVEST2018_Prompt']]
workflows[136.886] = ['',['RunEGamma2018D','HLTDR2_2018','RECODR2_2018reHLT_skimEGamma_Prompt_L1TEgDQM','HARVEST2018_L1TEgDQM_Prompt']]
workflows[136.887] = ['',['RunDoubleMuon2018D','HLTDR2_2018','RECODR2_2018reHLT_Prompt','HARVEST2018_Prompt']]
workflows[136.888] = ['',['RunJetHT2018D','HLTDR2_2018','RECODR2_2018reHLT_skimJetHT_Prompt','HARVEST2018_Prompt']]
workflows[136.889] = ['',['RunMET2018D','HLTDR2_2018','RECODR2_2018reHLT_skimMET_Prompt','HARVEST2018_Prompt']]
workflows[136.890] = ['',['RunMuonEG2018D','HLTDR2_2018','RECODR2_2018reHLT_skimMuonEG_Prompt','HARVEST2018_Prompt']]
workflows[136.891] = ['',['RunSingleMu2018D','HLTDR2_2018','RECODR2_2018reHLT_skimSingleMu_Prompt_Lumi','HARVEST2018_L1TMuDQM_Prompt']]
workflows[136.892] = ['',['RunZeroBias2018D','HLTDR2_2018','RECODR2_2018reHLT_ZBPrompt','HARVEST2018_PromptZB']]
workflows[136.893] = ['',['RunMuOnia2018D','HLTDR2_2018','RECODR2_2018reHLT_skimMuOnia_Prompt','HARVEST2018_Prompt']]
workflows[136.894] = ['',['RunNoBPTX2018D','HLTDR2_2018','RECODR2_2018reHLTAlCaTkCosmics_Prompt','HARVEST2018_Prompt']]
workflows[136.895] = ['',['RunDisplacedJet2018D','HLTDR2_2018','RECODR2_2018reHLT_skimDisplacedJet_Prompt','HARVEST2018_Prompt']]
workflows[136.896] = ['',['RunCharmonium2018D','HLTDR2_2018','RECODR2_2018reHLT_skimCharmonium_Prompt','HARVEST2018_Prompt']]
# reminiAOD wf on 2018D input
workflows[136.88811] = ['',['RunJetHT2018D_reminiaodUL','REMINIAOD_data2018UL','HARVEST2018_REMINIAOD_data2018UL']]
### run 2018D pixel tracks ###
workflows[136.8855] = ['',['RunHLTPhy2018D','HLTDR2_2018','RECODR2_2018reHLT_Prompt_pixelTrackingOnly','HARVEST2018_pixelTrackingOnly']]
workflows[136.885501] = ['',['RunHLTPhy2018D','HLTDR2_2018','RECODR2_2018reHLT_Patatrack_PixelOnlyCPU','HARVEST2018_pixelTrackingOnly']]
workflows[136.8885] = ['',['RunJetHT2018D','HLTDR2_2018','RECODR2_2018reHLT_Prompt_pixelTrackingOnly','HARVEST2018_pixelTrackingOnly']]
workflows[136.888501] = ['',['RunJetHT2018D','HLTDR2_2018','RECODR2_2018reHLT_Patatrack_PixelOnlyCPU','HARVEST2018_pixelTrackingOnly']]
### run 2018D ECAL-only ###
workflows[136.885511] = ['',['RunHLTPhy2018D','HLTDR2_2018','RECODR2_2018reHLT_ECALOnlyCPU','HARVEST2018_ECALOnly']]
workflows[136.888511] = ['',['RunJetHT2018D','HLTDR2_2018','RECODR2_2018reHLT_ECALOnlyCPU','HARVEST2018_ECALOnly']]
### run 2018D HCAL-only ###
workflows[136.885521] = ['',['RunHLTPhy2018D','HLTDR2_2018','RECODR2_2018reHLT_HCALOnlyCPU','HARVEST2018_HCALOnly']]
workflows[136.888521] = ['',['RunJetHT2018D','HLTDR2_2018','RECODR2_2018reHLT_HCALOnlyCPU','HARVEST2018_HCALOnly']]
### run 2021 CRUZET ###
workflows[136.897] = ['',['RunCosmics2021CRUZET','RECOCOSDRUN3','ALCACOSDRUN3','HARVESTDCRUN3']]
# multi-run harvesting
workflows[137.8] = ['',['RunEGamma2018C','HLTDR2_2018','RECODR2_2018reHLT_skimEGamma_Offline_L1TEgDQM',
'RunEGamma2018D','HLTDR2_2018','RECODR2_2018reHLT_skimEGamma_Prompt_L1TEgDQM','HARVEST2018_L1TEgDQM_MULTIRUN']]
### LS2 - MWGR ###
workflows[138.1] = ['',['RunCosmics2021','RECOCOSDPROMPTRUN3','ALCACOSDPROMPTRUN3','HARVESTDCPROMPTRUN3']]
workflows[138.2] = ['',['RunCosmics2021','RECOCOSDEXPRUN3','ALCACOSDEXPRUN3','HARVESTDCEXPRUN3']]
### 2021 Splash events
workflows[138.3] = ['',['RunMinimumBias2021Splash','COPYPASTER3', 'RECODR3Splash','HARVESTDR3']]
#### Test of lumi section boundary crossing with run2 2018D ####
workflows[136.8861] = ['',['RunEGamma2018Dml1','HLTDR2_2018ml','RECODR2_2018reHLT_skimEGamma_Prompt_L1TEgDQM','HARVEST2018_L1TEgDQM_Prompt']]
workflows[136.8862] = ['',['RunEGamma2018Dml2','HLTDR2_2018ml','RECODR2_2018reHLT_skimEGamma_Prompt_L1TEgDQM','HARVEST2018_L1TEgDQM_Prompt']]
### fastsim ###
workflows[5.1] = ['TTbar', ['TTbarFS','HARVESTFS']]
workflows[5.2] = ['SingleMuPt10', ['SingleMuPt10FS','HARVESTFS']]
workflows[5.3] = ['SingleMuPt100', ['SingleMuPt100FS','HARVESTFS']]
workflows[5.4] = ['ZEE', ['ZEEFS','HARVESTFS']]
workflows[5.5] = ['ZTT',['ZTTFS','HARVESTFS']]
workflows[5.6] = ['QCD_FlatPt_15_3000', ['QCDFlatPt153000FS','HARVESTFS']]
workflows[5.7] = ['H130GGgluonfusion', ['H130GGgluonfusionFS','HARVESTFS']]
### fastsim_13 TeV ###
workflows[135.1] = ['TTbar_13', ['TTbarFS_13','HARVESTUP15FS','MINIAODMCUP15FS']]
workflows[135.2] = ['SingleMuPt10_UP15', ['SingleMuPt10FS_UP15','HARVESTUP15FS','MINIAODMCUP15FS']]
workflows[135.3] = ['SingleMuPt100_UP15', ['SingleMuPt100FS_UP15','HARVESTUP15FS','MINIAODMCUP15FS']]
workflows[135.4] = ['ZEE_13', ['ZEEFS_13','HARVESTUP15FS','MINIAODMCUP15FS']]
workflows[135.5] = ['ZTT_13',['ZTTFS_13','HARVESTUP15FS','MINIAODMCUP15FS']]
workflows[135.6] = ['QCD_FlatPt_15_3000_13', ['QCDFlatPt153000FS_13','HARVESTUP15FS','MINIAODMCUP15FS']]
workflows[135.7] = ['H125GGgluonfusion_13', ['H125GGgluonfusionFS_13','HARVESTUP15FS','MINIAODMCUP15FS']]
workflows[135.9] = ['ZMM_13',['ZMMFS_13','HARVESTUP15FS','MINIAODMCUP15FS']]
workflows[135.11] = ['SMS-T1tttt_mGl-1500_mLSP-100_13', ['SMS-T1tttt_mGl-1500_mLSP-100FS_13','HARVESTUP15FS','MINIAODMCUP15FS']]
workflows[135.12] = ['QCD_Pt_80_120_13', ['QCD_Pt_80_120FS_13','HARVESTUP15FS','MINIAODMCUP15FS']]
workflows[135.13] = ['TTbar_13', ['TTbarFS_13_trackingOnlyValidation','HARVESTUP15FS_trackingOnly']]
### MinBias fastsim_13 TeV for mixing ###
workflows[135.8] = ['',['MinBiasFS_13_ForMixing']]
### Phase1 FastSim 13TeV ###
workflows[2017.1] = ['TTbar_13_UP17', ['TTbarFS_13_UP17','HARVESTUP17FS','MINIAODMCUP17FS']]
workflows[2017.2] = ['SingleMuPt10_UP17', ['SingleMuPt10FS_UP17','HARVESTUP17FS','MINIAODMCUP17FS']]
workflows[2017.3] = ['SingleMuPt100_UP17', ['SingleMuPt100FS_UP17','HARVESTUP17FS','MINIAODMCUP17FS']]
workflows[2017.4] = ['ZEE_13_UP17', ['ZEEFS_13_UP17','HARVESTUP17FS','MINIAODMCUP17FS']]
workflows[2017.5] = ['ZTT_13_UP17',['ZTTFS_13_UP17','HARVESTUP17FS','MINIAODMCUP17FS']]
workflows[2017.6] = ['QCD_FlatPt_15_3000_13_UP17', ['QCDFlatPt153000FS_13_UP17','HARVESTUP17FS','MINIAODMCUP17FS']]
workflows[2017.7] = ['H125GGgluonfusion_13_UP17', ['H125GGgluonfusionFS_13_UP17','HARVESTUP17FS','MINIAODMCUP17FS']]
workflows[2017.9] = ['ZMM_13_UP17',['ZMMFS_13_UP17','HARVESTUP17FS','MINIAODMCUP17FS']]
workflows[2017.11] = ['SMS-T1tttt_mGl-1500_mLSP-100_13_UP17', ['SMS-T1tttt_mGl-1500_mLSP-100FS_13_UP17','HARVESTUP17FS','MINIAODMCUP17FS']]
workflows[2017.12] = ['QCD_Pt_80_120_13_UP17', ['QCD_Pt_80_120FS_13_UP17','HARVESTUP17FS','MINIAODMCUP17FS']]
workflows[2017.13] = ['TTbar_13_UP17', ['TTbarFS_13_trackingOnlyValidation_UP17','HARVESTUP17FS_trackingOnly']]
### MinBias fastsim_13 TeV for mixing ###
workflows[2017.8] = ['',['MinBiasFS_13_UP17_ForMixing']]
### MinBias fastsim_13 TeV for mixing, 2018 ###
workflows[2018.8] = ['',['MinBiasFS_13_UP18_ForMixing']]
### Phase1 FastSim 13TeV, 2018 ###
workflows[2018.1] = ['TTbar_13_UP18', ['TTbarFS_13_UP18','HARVESTUP18FS','MINIAODMCUP18FS']]
workflows[2018.2] = ['SingleMuPt10_UP18', ['SingleMuPt10FS_UP18','HARVESTUP18FS','MINIAODMCUP18FS']]
workflows[2018.3] = ['SingleMuPt100_UP18', ['SingleMuPt100FS_UP18','HARVESTUP18FS','MINIAODMCUP18FS']]
workflows[2018.4] = ['ZEE_13_UP18', ['ZEEFS_13_UP18','HARVESTUP18FS','MINIAODMCUP18FS']]
workflows[2018.5] = ['ZTT_13_UP18',['ZTTFS_13_UP18','HARVESTUP18FS','MINIAODMCUP18FS']]
workflows[2018.6] = ['QCD_FlatPt_15_3000_13_UP18', ['QCDFlatPt153000FS_13_UP18','HARVESTUP18FS','MINIAODMCUP18FS']]
workflows[2018.7] = ['H125GGgluonfusion_13_UP18', ['H125GGgluonfusionFS_13_UP18','HARVESTUP18FS','MINIAODMCUP18FS']]
workflows[2018.9] = ['ZMM_13_UP18',['ZMMFS_13_UP18','HARVESTUP18FS','MINIAODMCUP18FS']]
workflows[2018.11] = ['SMS-T1tttt_mGl-1500_mLSP-100_13_UP18', ['SMS-T1tttt_mGl-1500_mLSP-100FS_13_UP18','HARVESTUP18FS','MINIAODMCUP18FS']]
workflows[2018.12] = ['QCD_Pt_80_120_13_UP18', ['QCD_Pt_80_120FS_13_UP18','HARVESTUP18FS','MINIAODMCUP18FS']]
workflows[2018.13] = ['TTbar_13_UP18', ['TTbarFS_13_trackingOnlyValidation_UP18','HARVESTUP18FS_trackingOnly']]
### standard set ###
## particle guns
workflows[15] = ['', ['SingleElectronPt10','DIGI','RECO','HARVEST']]
workflows[16] = ['', ['SingleElectronPt1000','DIGI','RECO','HARVEST']]
workflows[17] = ['', ['SingleElectronPt35','DIGI','RECO','HARVEST']]
workflows[18] = ['', ['SingleGammaPt10','DIGI','RECO','HARVEST']]
workflows[19] = ['', ['SingleGammaPt35','DIGI','RECO','HARVEST']]
workflows[6] = ['', ['SingleMuPt1','DIGI','RECO','HARVEST']]
workflows[20] = ['', ['SingleMuPt10','DIGI','RECO','HARVEST']]
workflows[21] = ['', ['SingleMuPt100','DIGI','RECO','HARVEST']]
workflows[22] = ['', ['SingleMuPt1000','DIGI','RECO','HARVEST']]
## particle guns postLS1
workflows[1315] = ['', ['SingleElectronPt10_UP15','DIGIUP15','RECOUP15','HARVESTUP15']]
workflows[1316] = ['', ['SingleElectronPt1000_UP15','DIGIUP15','RECOUP15','HARVESTUP15']]
workflows[1317] = ['', ['SingleElectronPt35_UP15','DIGIUP15','RECOUP15','HARVESTUP15','NANOUP15']]
workflows[1318] = ['', ['SingleGammaPt10_UP15','DIGIUP15','RECOUP15','HARVESTUP15','NANOUP15']]
workflows[1319] = ['', ['SingleGammaPt35_UP15','DIGIUP15','RECOUP15','HARVESTUP15']]
workflows[1306] = ['', ['SingleMuPt1_UP15','DIGIUP15','RECOUP15','HARVESTUP15']]
workflows[1320] = ['', ['SingleMuPt10_UP15','DIGIUP15','RECOUP15','HARVESTUP15','NANOUP15']]
workflows[1321] = ['', ['SingleMuPt100_UP15','DIGIUP15','RECOUP15','HARVESTUP15','NANOUP15']]
workflows[1322] = ['', ['SingleMuPt1000_UP15','DIGIUP15','RECOUP15','HARVESTUP15','NANOUP15']]
workflows[1323] = ['', ['NuGun_UP15','DIGIUP15','RECOUP15','HARVESTUP15']]
## 8 TeV
workflows[24] = ['', ['TTbarLepton','DIGI','RECO','HARVEST']]
workflows[35] = ['', ['Wjet_Pt_80_120','DIGI','RECO','HARVEST']]
workflows[36] = ['', ['Wjet_Pt_3000_3500','DIGI','RECO','HARVEST']]
workflows[37] = ['', ['LM1_sfts','DIGI','RECO','HARVEST']]
# the input for the following worrkflow is high statistics
workflows[38] = ['', ['QCD_FlatPt_15_3000HS','DIGI','RECO','HARVEST']]
workflows[9] = ['', ['Higgs200ChargedTaus','DIGI','RECO','HARVEST']]
workflows[13] = ['', ['QCD_Pt_3000_3500','DIGI','RECO','HARVEST']]
workflows.addOverride(13,overridesEv5)
workflows[39] = ['', ['QCD_Pt_600_800','DIGI','RECO','HARVEST']]
workflows[23] = ['', ['JpsiMM','DIGI','RECO','HARVEST']]
workflows[25] = ['', ['TTbar','DIGI','RECOAlCaCalo','HARVEST','ALCATT']]
workflows[26] = ['', ['WE','DIGI','RECOAlCaCalo','HARVEST']]
workflows[29] = ['', ['ZEE','DIGI','RECOAlCaCalo','HARVEST']]
workflows[31] = ['', ['ZTT','DIGI','RECO','HARVEST']]
workflows[32] = ['', ['H130GGgluonfusion','DIGI','RECO','HARVEST']]
workflows[33] = ['', ['PhotonJets_Pt_10','DIGI','RECO','HARVEST']]
workflows[34] = ['', ['QQH1352T','DIGI','RECO','HARVEST']]
#workflows[46] = ['', ['ZmumuJets_Pt_20_300']]
workflows[7] = ['', ['Cosmics','DIGICOS','RECOCOS','ALCACOS','HARVESTCOS']]
workflows[7.1]= ['', ['CosmicsSPLoose','DIGICOS','RECOCOS','ALCACOS','HARVESTCOS']]
workflows[7.20] = ['', ['Cosmics_UP18','DIGICOS_UP18','RECOCOS_UP18','ALCACOS_UP18','HARVESTCOS_UP18']]#2018
workflows[7.21] = ['', ['Cosmics_UP17','DIGICOS_UP17','RECOCOS_UP17','ALCACOS_UP17','HARVESTCOS_UP17']]#2017
workflows[7.22] = ['', ['Cosmics_UP16','DIGICOS_UP16','RECOCOS_UP16','ALCACOS_UP16','HARVESTCOS_UP16']]#2016
workflows[7.23] = ['', ['Cosmics_UP21','DIGICOS_UP21','RECOCOS_UP21','ALCACOS_UP21','HARVESTCOS_UP21']]#2021
workflows[7.24] = ['', ['Cosmics_UP21_0T','DIGICOS_UP21_0T','RECOCOS_UP21_0T','ALCACOS_UP21_0T','HARVESTCOS_UP21_0T']]#2021 0T
workflows[7.3] = ['', ['CosmicsSPLoose_UP18','DIGICOS_UP18','RECOCOS_UP18','ALCACOS_UP18','HARVESTCOS_UP18']]
workflows[7.4] = ['', ['Cosmics_UP18','DIGICOSPEAK_UP18','RECOCOSPEAK_UP18','ALCACOS_UP18','HARVESTCOS_UP18']]
workflows[8] = ['', ['BeamHalo','DIGICOS','RECOCOS','ALCABH','HARVESTCOS']]
workflows[8.1] = ['', ['BeamHalo_UP18','DIGICOS_UP18','RECOCOS_UP18','ALCABH_UP18','HARVESTCOS_UP18']]
workflows[8.2] = ['', ['BeamHalo_UP21','DIGICOS_UP21','RECOCOS_UP21','ALCABH_UP21','HARVESTCOS_UP21']]
workflows[11] = ['', ['MinBias','DIGI','RECOMIN','HARVEST','ALCAMIN']]
workflows[28] = ['', ['QCD_Pt_80_120','DIGI','RECO','HARVEST']]
workflows[27] = ['', ['WM','DIGI','RECO','HARVEST']]
workflows[30] = ['', ['ZMM','DIGI','RECO','HARVEST']]
workflows[10] = ['', ['ADDMonoJet_d3MD3','DIGI','RECO','HARVEST']]
workflows[12] = ['', ['ZpMM','DIGI','RECO','HARVEST']]
workflows[14] = ['', ['WpM','DIGI','RECO','HARVEST']]
workflows[43] = ['', ['ZpMM_2250_8TeV','DIGI','RECO','HARVEST']]
workflows[44] = ['', ['ZpEE_2250_8TeV','DIGI','RECO','HARVEST']]
workflows[45] = ['', ['ZpTT_1500_8TeV','DIGI','RECO','HARVEST']]
## 13 TeV and postLS1 geometry
workflows[1324] = ['', ['TTbarLepton_13','DIGIUP15','RECOUP15','HARVESTUP15']]
workflows[1335] = ['', ['Wjet_Pt_80_120_13','DIGIUP15','RECOUP15','HARVESTUP15']]
workflows[1336] = ['', ['Wjet_Pt_3000_3500_13','DIGIUP15','RECOUP15','HARVESTUP15']]
#workflows[1337] = ['', ['LM1_sfts_13','DIGIUP15','RECOUP15','HARVESTUP15']]
workflows[1337] = ['', ['SMS-T1tttt_mGl-1500_mLSP-100_13','DIGIUP15','RECOUP15','HARVESTUP15']]
workflows[1338] = ['', ['QCD_FlatPt_15_3000HS_13','DIGIUP15','RECOUP15','HARVESTUP15','NANOUP15']]
workflows[1309] = ['', ['Higgs200ChargedTaus_13','DIGIUP15','RECOUP15','HARVESTUP15']]
workflows[1313] = ['', ['QCD_Pt_3000_3500_13','DIGIUP15','RECOUP15','HARVESTUP15']]
workflows.addOverride(1313,overridesEv5)
workflows[1339] = ['', ['QCD_Pt_600_800_13','DIGIUP15','RECOUP15','HARVESTUP15']]
workflows[1347] = ['', ['Upsilon1SToMuMu_13','DIGIUP15','RECOUP15','HARVESTUP15']]
workflows[1349] = ['', ['BsToMuMu_13','DIGIUP15','RECOUP15','HARVESTUP15']]
workflows[1350] = ['', ['JpsiMuMu_Pt-8','DIGIUP15','RECOUP15','HARVESTUP15']]
workflows[1364] = ['', ['BdToMuMu_13','DIGIUP15','RECOUP15','HARVESTUP15']]
workflows[1365] = ['', ['BuToJpsiK_13','DIGIUP15','RECOUP15','HARVESTUP15']]
workflows[1366] = ['', ['BsToJpsiPhi_13','DIGIUP15','RECOUP15','HARVESTUP15']]
workflows[1325] = ['', ['TTbar_13','DIGIUP15','RECOUP15','HARVESTUP15','ALCATTUP15','NANOUP15']]
# the 3 workflows below are for tracking-specific ib test, not to be run in standard relval set.
workflows[1325.1] = ['', ['TTbar_13','DIGIUP15','RECOUP15_trackingOnly','HARVESTUP15_trackingOnly']]
workflows[1325.2] = ['', ['TTbar_13','DIGIUP15','RECOUP15_trackingLowPU','HARVESTUP15']]
workflows[1325.3] = ['', ['TTbar_13','DIGIUP15','RECOUP15_trackingOnlyLowPU','HARVESTUP15_trackingOnly']]
workflows[1325.4] = ['', ['TTbar_13','DIGIUP15','RECOUP15_HIPM','HARVESTUP15']]
# reminiaod wf on 80X MC
workflows[1325.5] = ['', ['ProdZEE_13_reminiaodINPUT','REMINIAOD_mc2016','HARVESTDR2_REMINIAOD_mc2016']]
# reminiaod wf on 94X MC
workflows[1325.51] = ['', ['TTbar_13_94XreminiaodINPUT','REMINIAOD_mc2017','HARVESTUP17_REMINIAOD_mc2017']]
# reminiaod on UL MC
workflows[1325.516] = ['', ['TTbar_13_reminiaod2016UL_preVFP_INPUT','REMINIAOD_mc2016UL_preVFP','HARVESTDR2_REMINIAOD_mc2016UL_preVFP']]
workflows[1325.5161] = ['', ['TTbar_13_reminiaod2016UL_postVFP_INPUT','REMINIAOD_mc2016UL_postVFP','HARVESTDR2_REMINIAOD_mc2016UL_postVFP']]
workflows[1325.517] = ['', ['TTbar_13_reminiaod2017UL_INPUT','REMINIAOD_mc2017UL','HARVESTUP17_REMINIAOD_mc2017UL']]
workflows[1325.518] = ['', ['TTbar_13_reminiaod2018UL_INPUT','REMINIAOD_mc2018UL','HARVESTUP18_REMINIAOD_mc2018UL']]
# nanoaod wf without intermediate EDM, starting from existing MINIAOD inputs
workflows[1325.6] = ['', ['TTbar_13_94Xv1NanoAODINPUT','NANOAODMC2017_94XMiniAODv1']]
# nanoaod wf with intermediate EDM and merge step, starting from existing MINIAOD inputs
workflows[1325.7] = ['', ['TTbar_13_94Xv2NanoAODINPUT','NANOEDMMC2017_94XMiniAODv2','HARVESTNANOAODMC2017_94XMiniAODv2']]
workflows[1325.8] = ['', ['TTbar_13_94Xv1NanoAODINPUT','NANOEDMMC2017_94XMiniAODv1','HARVESTNANOAODMC2017_94XMiniAODv1']]
# special workflow including the SiStrip APV dynamic gain simulation for 2016 MC
workflows[1325.9] = ['', ['TTbar_13','DIGIUP15APVSimu','RECOUP15','HARVESTUP15','ALCATTUP15']]
workflows[1325.91] = ['', ['TTbar_13','DIGIUP15APVSimu','RECOUP15_HIPM','HARVESTUP15','ALCATTUP15']]
# nanoaod wf without intermediate EDM, starting from existing MINIAOD inputs
workflows[1325.61] = ['', ['TTbar_13_106Xv1NanoAODINPUT','NANOAODMC2017_106XMiniAODv1']]
# nanoaod wf with intermediate EDM and merge step, starting from existing MINIAOD inputs
workflows[1325.81] = ['', ['TTbar_13_106Xv1NanoAODINPUT','NANOEDMMC2017_106XMiniAODv1','HARVESTNANOAODMC2017_106XMiniAODv1']]
#using ZEE as I cannot find TT at CERN
workflows[1329.1] = ['', ['ZEE_13_80XNanoAODINPUT','NANOEDMMC2016_80X','HARVESTNANOAODMC2016_80X']]
workflows[1326] = ['', ['WE_13','DIGIUP15','RECOUP15','HARVESTUP15']]
workflows[1329] = ['', ['ZEE_13','DIGIUP15','RECOUP15_L1TEgDQM','HARVESTUP15_L1TEgDQM','NANOUP15']]
workflows[1356] = ['', ['ZEE_13_DBLMINIAOD','DIGIUP15','RECOAODUP15','HARVESTUP15','DBLMINIAODMCUP15NODQM']]
workflows[1331] = ['', ['ZTT_13','DIGIUP15','RECOUP15','HARVESTUP15','NANOUP15']]
workflows[1332] = ['', ['H125GGgluonfusion_13','DIGIUP15','RECOUP15','HARVESTUP15']]
workflows[1333] = ['', ['PhotonJets_Pt_10_13','DIGIUP15','RECOUP15','HARVESTUP15']]
workflows[1334] = ['', ['QQH1352T_13','DIGIUP15','RECOUP15','HARVESTUP15']]
workflows[1307] = ['', ['CosmicsSPLoose_UP15','DIGICOS_UP15','RECOCOS_UP15','ALCACOS_UP15','HARVESTCOS_UP15']]
workflows[1308] = ['', ['BeamHalo_13','DIGIHAL','RECOHAL','ALCAHAL','HARVESTHAL']]
workflows[1311] = ['', ['MinBias_13','DIGIUP15','RECOMINUP15','HARVESTMINUP15','ALCAMINUP15']]
workflows[1328] = ['', ['QCD_Pt_80_120_13','DIGIUP15','RECOUP15','HARVESTUP15']]
workflows[1327] = ['', ['WM_13','DIGIUP15','RECOUP15','HARVESTUP15']]
workflows[1330] = ['', ['ZMM_13','DIGIUP15','RECOUP15_L1TMuDQM','HARVESTUP15_L1TMuDQM','NANOUP15']]
workflows[1310] = ['', ['ADDMonoJet_d3MD3_13','DIGIUP15','RECOUP15','HARVESTUP15']]
workflows[1312] = ['', ['ZpMM_13','DIGIUP15','RECOUP15','HARVESTUP15']]
workflows[1314] = ['', ['WpM_13','DIGIUP15','RECOUP15','HARVESTUP15']]
workflows[1340] = ['', ['PhiToMuMu_13','DIGIUP15','RECOUP15','HARVESTUP15']]
workflows[1341] = ['', ['RSKKGluon_m3000GeV_13','DIGIUP15','RECOUP15','HARVESTUP15']]
workflows[1343] = ['', ['ZpMM_2250_13','DIGIUP15','RECOUP15','HARVESTUP15']]
workflows[1344] = ['', ['ZpEE_2250_13','DIGIUP15','RECOUP15','HARVESTUP15']]
workflows[1345] = ['', ['ZpTT_1500_13','DIGIUP15','RECOUP15','HARVESTUP15']]
workflows[1348] = ['', ['EtaBToJpsiJpsi_13','DIGIUP15','RECOUP15','HARVESTUP15']]
workflows[1351] = ['', ['BuMixing_13','DIGIUP15','RECOUP15','HARVESTUP15']]
workflows[1352] = ['', ['HSCPstop_M_200_13','DIGIUP15','RECOUP15','HARVESTUP15']]
workflows[1353] = ['', ['RSGravitonToGaGa_13','DIGIUP15','RECOUP15','HARVESTUP15']]
workflows[1354] = ['', ['WpToENu_M-2000_13','DIGIUP15','RECOUP15','HARVESTUP15']]
workflows[1355] = ['', ['DisplacedSUSY_stopToBottom_M_300_1000mm_13','DIGIUP15','RECOUP15','HARVESTUP15']]
# fullSim 13TeV normal workflows starting from gridpacks LHE generation
workflows[1360] = ['', ['TTbar012Jets_NLO_Mad_py8_Evt_13','DIGIUP15','RECOUP15','HARVESTUP15']]
workflows[1361] = ['', ['GluGluHToZZTo4L_M125_Pow_py8_Evt_13','DIGIUP15','RECOUP15','HARVESTUP15']]
workflows[1362] = ['', ['VBFHToZZTo4Nu_M125_Pow_py8_Evt_13','DIGIUP15','RECOUP15','HARVESTUP15']]
workflows[1363] = ['', ['VBFHToBB_M125_Pow_py8_Evt_13','DIGIUP15','RECOUP15','HARVESTUP15']]
# 2017 workflows starting from gridpacks LHE generation
workflows[1361.17] = ['', ['GluGluHToZZTo4L_M125_Pow_py8_Evt_13UP17','DIGIUP17','RECOUP17','HARVESTUP17','NANOUP17']]
workflows[1362.17] = ['', ['VBFHToZZTo4Nu_M125_Pow_py8_Evt_13UP17','DIGIUP17','RECOUP17','HARVESTUP17','NANOUP17']]
workflows[1363.17] = ['', ['VBFHToBB_M125_Pow_py8_Evt_13UP17','DIGIUP17','RECOUP17','HARVESTUP17','NANOUP17']]
# 2018 workflows starting from gridpacks LHE generation
workflows[1361.18] = ['', ['GluGluHToZZTo4L_M125_Pow_py8_Evt_13UP18','DIGIUP18','RECOUP18','HARVESTUP18','NANOUP18']]
workflows[1362.18] = ['', ['VBFHToZZTo4Nu_M125_Pow_py8_Evt_13UP18','DIGIUP18','RECOUP18','HARVESTUP18','NANOUP18']]
workflows[1363.18] = ['', ['VBFHToBB_M125_Pow_py8_Evt_13UP18','DIGIUP18','RECOUP18','HARVESTUP18','NANOUP18']]
#2018 workflows starting from gridpacks LHE generation with multiple concurrent lumi sections
workflows[1361.181] = ['', ['GluGluHToZZTo4L_M125_Pow_py8_Evt_13UP18ml','DIGIUP18','RECOUP18','HARVESTUP18','NANOUP18']]
# fullSim 13TeV normal workflows starting from pLHE
workflows[1370] = ['', ['GluGluHToGG_M125_Pow_MINLO_NNLOPS_py8_13','Hadronizer_TuneCUETP8M1_13TeV_powhegEmissionVeto_2p_HToGG_M125_13','DIGIUP15','RECOUP15','HARVESTUP15','NANOUP15Had']]
# 2017 workflows starting from pLHE
workflows[1370.17] = ['', ['GluGluHToGG_M125_Pow_MINLO_NNLOPS_py8_13UP17','Hadronizer_TuneCUETP8M1_13TeV_powhegEmissionVeto_2p_HToGG_M125_13UP17','DIGIUP17','RECOUP17','HARVESTUP17','NANOUP17Had']]
# 2018 workflows starting from pLHE
workflows[1370.18] = ['', ['GluGluHToGG_M125_Pow_MINLO_NNLOPS_py8_13UP18','Hadronizer_TuneCUETP8M1_13TeV_powhegEmissionVeto_2p_HToGG_M125_13UP18','DIGIUP18','RECOUP18','HARVESTUP18','NANOUP18Had']]
### HI test ###
### Run I cond., 2011
workflows[140] = ['',['HydjetQ_B12_5020GeV_2011','DIGIHI2011','RECOHI2011','HARVESTHI2011']]
### Run II cond., 2015
workflows[145] = ['',['HydjetQ_B12_5020GeV_2015','DIGIHI2015','RECOHI2015','HARVESTHI2015']]
### Run II cond., 2017
workflows[148] = ['',['HydjetQ_MinBias_XeXe_5442GeV_2017','DIGIHI2017','RECOHI2017','HARVESTHI2017']]
### Run II cond., 2018
workflows[150] = ['',['HydjetQ_B12_5020GeV_2018','DIGIHI2018','RECOHI2018','HARVESTHI2018']]
workflows[158] = ['',['HydjetQ_B12_5020GeV_2018_ppReco','DIGIHI2018PPRECO','RECOHI2018PPRECOMB','ALCARECOHI2018PPRECO','HARVESTHI2018PPRECO']]
workflows[158.01] = ['',['HydjetQ_reminiaodPbPb2018_INPUT','REMINIAODHI2018PPRECOMB','HARVESTHI2018PPRECOMINIAOD']]
workflows[158.1] = ['',['QCD_Pt_80_120_13_HI','DIGIHI2018PPRECO','RECOHI2018PPRECO','HARVESTHI2018PPRECO']]
workflows[158.2] = ['',['PhotonJets_Pt_10_13_HI','DIGIHI2018PPRECO','RECOHI2018PPRECO','HARVESTHI2018PPRECO']]
workflows[158.3] = ['',['ZEEMM_13_HI','DIGIHI2018PPRECO','RECOHI2018PPRECO','HARVESTHI2018PPRECO']]
workflows[159] = ['',['HydjetQ_B12_5020GeV_2021_ppReco','DIGIHI2021PPRECO','RECOHI2021PPRECOMB','ALCARECOHI2021PPRECO','HARVESTHI2021PPRECO']]
workflows[159.1] = ['',['QCD_Pt_80_120_14_HI_2021','DIGIHI2021PPRECO','RECOHI2021PPRECO','HARVESTHI2021PPRECO']]
workflows[159.2] = ['',['PhotonJets_Pt_10_14_HI_2021','DIGIHI2021PPRECO','RECOHI2021PPRECO','HARVESTHI2021PPRECO']]
workflows[159.3] = ['',['ZMM_14_HI_2021','DIGIHI2021PPRECO','RECOHI2021PPRECO','HARVESTHI2021PPRECO']]
workflows[159.4] = ['',['ZEE_14_HI_2021','DIGIHI2021PPRECO','RECOHI2021PPRECO','HARVESTHI2021PPRECO']]
### pp reference test ###
workflows[149] = ['',['QCD_Pt_80_120_13_PPREF','DIGIPPREF2017','RECOPPREF2017','HARVESTPPREF2017']]
### pPb test ###
workflows[280]= ['',['AMPT_PPb_5020GeV_MinimumBias','DIGI','RECO','HARVEST']]
### pPb Run2 ###
workflows[281]= ['',['EPOS_PPb_8160GeV_MinimumBias','DIGIUP15_PPb','RECOUP15_PPb','HARVESTUP15_PPb']]
|
#
# print("What's your name?")
# name = input("> ")
#
# print("Hi " + name)
a = 60
b = 7
c = 500
if a > b:
if a > c:
print(a)
else:
print(c)
else:
if b > c:
print(b)
else:
print(c)
|
export * from './ContainerElements'
export * from './NavElements'
export * from './FooterElements'
|
import socket
import sys
if __name__=='__main__':
if len(sys.argv)<4:
print("{0} <Bind IP> <Server IP> <Message>".format(sys.argv[0]))
sys.exit()
bindIP=sys.argv[1]
serverIP=sys.argv[2]
message=sys.argv[3]
sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((bindIP, 0))
try:
sock.connect((serverIP, 5425))
#메아리 송신
sbuff=bytes(message, encoding="utf-8")
sock.send(sbuff)
print("송신 : {0}".format(message))
#메아리 수신
rbuff=sock.recv(1024)
received=str(rbuff, encoding="utf-8")
print("수신 : {0}".format(received))
finally:
sock.close()
|
# Import python libs
import os
import tempfile
# Import pop libs
import pop.hub
import idem.conf
import rend.exc
# Import third party libs
import pytest
def run_sls(sls, runtime='parallel', test=False):
'''
Pass in an sls list and run it!
'''
name = 'test'
hub = pop.hub.Hub()
hub.pop.sub.add('idem.idem', init=True)
hub.pop.sub.add('nest')
hub.pop.sub.load_subdirs(hub.nest)
hub.pop.sub.load_subdirs(hub.nest.nest)
hub.pop.sub.load_subdirs(hub.nest.nest.again)
render = 'jinja|yaml'
cache_dir = tempfile.mkdtemp()
sls_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'sls')
sls_sources = [f'file://{sls_dir}']
hub.pop.loop.start(hub.idem.init.apply(name, sls_sources, render, runtime, ['states', 'nest'], cache_dir, sls, test))
errors = hub.idem.RUNS[name]['errors']
if errors:
return errors
ret = hub.idem.RUNS[name]['running']
return ret
def test_treq():
ret = run_sls(['treq'])
assert ret['test_|-to_treq_|-to_treq_|-treq']['__run_num'] == 4
def test_ugly1():
ret = run_sls(['ugly1'])
assert ret == ['ID foo in SLS ugly1 is not a dictionary']
def test_shebang():
ret = run_sls(['bang'])
assert 'test_|-test_|-test_|-nop' in ret
def test_req_chain():
'''
Test that you can chain requisites, bug #11
'''
ret = run_sls(['recreq'])
assert ret.get('test_|-first thing_|-first thing_|-nop', {}).get('__run_num') == 1
assert ret.get('test_|-second thing_|-second thing_|-nop', {}).get('__run_num') == 2
assert ret.get('test_|-third thing_|-third thing_|-nop', {}).get('__run_num') == 3
def test_nest():
ret = run_sls(['nest'])
assert ret['nest.again.another.test_|-baz_|-baz_|-nop']['result']
assert ret['nest.again.test_|-bar_|-bar_|-nop']['result']
assert ret['nest.test_|-foo_|-foo_|-nop']['result']
# verify that the invalid state is not run
assert not ret['idem.init_|-quo_|-quo_|-create']['result']
assert ret['test_|-req_|-req_|-nop']['__run_num'] == 5
def test_basic():
'''
Test the basic funcitonality of Idem
'''
ret = run_sls(['simple'])
assert ret['test_|-happy_|-happy_|-nop']['result'] == True
assert ret['test_|-happy_|-happy_|-nop']['changes'] == {}
assert ret['test_|-happy_|-happy_|-nop']['name'] == 'happy'
assert ret['test_|-sad_|-sad_|-fail_without_changes']['result'] == False
assert ret['test_|-sad_|-sad_|-fail_without_changes']['name'] == 'sad'
assert ret['test_|-sad_|-sad_|-fail_without_changes']['changes'] == {}
def test_req():
'''
Test basic requisites
'''
ret = run_sls(['req'])
assert ret['test_|-needs_fail_|-needs_fail_|-nop']['result'] == False
assert ret['test_|-needs_fail_|-needs_fail_|-nop']['__run_num'] == 4
assert ret['test_|-needs_|-needs_|-nop']['__run_num'] == 3
assert ret['test_|-needs_|-needs_|-nop']['result'] == True
def test_req_test_mode():
'''
Test basic requisites in test mode
'''
ret = run_sls(['req'], test=True)
assert ret['test_|-needs_fail_|-needs_fail_|-nop']['result'] == False
assert ret['test_|-needs_fail_|-needs_fail_|-nop']['__run_num'] == 4
assert ret['test_|-needs_|-needs_|-nop']['__run_num'] == 3
# "needed" returned None and needs did not fail to run
assert ret['test_|-needs_|-needs_|-nop']['result'] == None
def test_watch():
'''
Test basic requisites
'''
ret = run_sls(['watch'])
assert ret['test_|-watch_changes_|-watch_changes_|-nop']['__run_num'] == 2
assert ret['test_|-watch_changes_|-watch_changes_|-nop']['comment'] == 'Watch ran!'
assert ret['test_|-watch_changes_|-watch_changes_|-nop']['result'] == True
assert ret['test_|-changes_|-changes_|-succeed_with_changes']['result'] == True
assert ret['test_|-changes_|-changes_|-succeed_with_changes']['changes']
def test_onfail():
'''
Test basic requisites
'''
ret = run_sls(['fails'])
assert ret['test_|-runs_|-runs_|-nop']['__run_num'] == 2
assert ret['test_|-runs_|-runs_|-nop']['result'] == True
assert ret['test_|-bad_|-bad_|-nop']['result'] == False
assert ret['test_|-bad_|-bad_|-nop']['__run_num'] == 3
assert ret['test_|-fails_|-fails_|-fail_without_changes']['__run_num'] == 1
assert ret['test_|-fails_|-fails_|-fail_without_changes']['result'] == False
def test_onchanges():
ret = run_sls(['changes'])
assert ret['test_|-watch_changes_|-watch_changes_|-nop']['__run_num'] == 2
assert ret['test_|-watch_changes_|-watch_changes_|-nop']['result'] == True
def test_run_name():
ret = run_sls(['update'])
assert ret['test_|-king_arthur_|-totally_extra_alls_|-nop']['__run_num'] == 2
def test_params():
ret = run_sls(['order'], runtime='serial')
assert ret['test_|-first_|-first_|-noop']['__run_num'] == 1
assert ret['test_|-second_|-second_|-noop']['__run_num'] == 2
assert ret['test_|-third_|-third_|-noop']['__run_num'] == 3
assert ret['test_|-forth_|-forth_|-noop']['__run_num'] == 4
assert ret['test_|-fifth_|-fifth_|-noop']['__run_num'] == 5
assert ret['test_|-sixth_|-sixth_|-noop']['__run_num'] == 6
assert ret['test_|-seventh_|-seventh_|-noop']['__run_num'] == 7
assert ret['test_|-eighth_|-eighth_|-noop']['__run_num'] == 8
assert ret['test_|-ninth_|-ninth_|-noop']['__run_num'] == 9
assert ret['test_|-tenth_|-tenth_|-noop']['__run_num'] == 10
def test_blocks():
ret = run_sls(['blocks'])
assert 'test_|-wow_|-wow_|-nop' in ret
def test_dup_keys():
with pytest.raises(rend.exc.RenderException):
ret = run_sls(['dupkeys'])
|
module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 15);
/******/ })
/************************************************************************/
/******/ ({
/***/ 0:
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
/* eslint-disable no-unused-vars */
/* eslint-disable camelcase */
exports.default = {
methods: {
selectComponent: function selectComponent(selector) {},
selectAllComponents: function selectAllComponents(selctor) {},
setStyle: function setStyle(styleDict) {
var onekit_styles = '';
for (var _iterator = Object.keys(styleDict), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var cssName = _ref;
onekit_styles += cssName + ':' + styleDict[cssName] + ';';
}
this.setData({ onekit_styles: onekit_styles });
},
addClass: function addClass(className) {},
removeClass: function removeClass(className) {},
hasClass: function hasClass(className) {},
getDataset: function getDataset() {},
callMethod: function callMethod(funcName, args) {},
requestAnimationFrame: function requestAnimationFrame(callback) {},
getState: function getState() {},
getComputedStyle: function getComputedStyle(cssNames) {}
}
};
/***/ }),
/***/ 1:
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.default = {
properties: {
onekitClass: '',
onekitStyle: '',
onekitId: ''
}
};
/***/ }),
/***/ 15:
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _onekit_behavior = __webpack_require__(1);
var _onekit_behavior2 = _interopRequireDefault(_onekit_behavior);
var _wxs_behavior = __webpack_require__(0);
var _wxs_behavior2 = _interopRequireDefault(_wxs_behavior);
var _weixin_behavior = __webpack_require__(2);
var _weixin_behavior2 = _interopRequireDefault(_weixin_behavior);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
Component({
behaviors: [_onekit_behavior2.default, _wxs_behavior2.default, _weixin_behavior2.default],
options: {
addGlobalClass: true
},
properties: {
longitude: {
type: Number,
value: null
},
latitude: {
type: Number,
value: null
},
scale: {
type: Number,
value: 16
},
minScale: {
type: Number,
value: 3
},
maxScale: {
type: Number,
value: 20
},
markers: {
type: Array,
value: [],
observer: function observer(markers) {
return this._getMarker(markers);
}
},
covers: {
type: Array,
value: null
},
polyline: {
type: Array,
value: []
},
circles: {
type: Array,
value: []
},
controls: {
type: Array,
value: [],
observer: function observer(controls) {
return this._getControl(controls);
}
},
includePoints: {
type: Array,
value: []
},
showLocation: {
type: Boolean,
value: false
},
polygons: {
type: Array,
value: []
},
//
subkey: {
type: String,
value: ''
},
//
layerStyle: {
type: Number,
value: 1
},
//
rotate: {
type: Number,
value: 0
},
//
skew: {
type: Boolean,
value: false
},
enable3D: {
type: Boolean,
value: false
},
showCompass: {
type: Boolean,
value: false
},
//
showScale: {
type: Boolean,
value: false
},
enableOverLooking: {
type: Boolean,
value: false
},
enableZoom: {
type: Boolean,
value: true
},
enableScroll: {
type: Boolean,
value: true
},
enableRotate: {
type: Boolean,
value: false
},
//
enableSatellite: {
type: Boolean,
value: false
},
//
enableTraffic: {
type: Boolean,
value: false
},
//
enablePoi: {
type: Boolean,
value: false
},
//
enableBuilding: {
type: Boolean,
value: false
},
//
setting: {
type: Boolean,
value: false
}
},
observers: {},
attached: function attached() {
var minScale = 3;
var maxScale = 20;
var scale = this.properties.scale;
this.properties.minScale = Math.min(minScale, scale);
this.properties.maxScale = Math.max(scale, maxScale);
//
this._getMarker(this.properties.markers);
this._getControl(this.properties.controls);
},
methods: {
map_tap: function map_tap(e) {
this.triggerEvent('Tap', e.detail);
},
map_markertap: function map_markertap(e) {
this.triggerEvent('Tap', e.detail);
},
//
_trigger_labeltap: function _trigger_labeltap(e) {
// console.warn('暂不支持!')
this.triggerEvent('Labeltap', e.detail);
},
map_controltap: function map_controltap(e) {
this.triggerEvent('Controltap', e.detail);
},
map_callouttap: function map_callouttap(e) {
this.triggerEvent('Callouttap', e.detail);
},
map_updated: function map_updated(e) {
this.triggerEvent('Updated', e.detail);
},
map_regionchange: function map_regionchange(e) {
this.triggerEvent('Regionchange', e.detail);
},
map_poitap: function map_poitap(e) {
this.triggerEvent('Poitap', e.detail);
},
//
_trigger_anchorpointtap: function _trigger_anchorpointtap(e) {
// console.warn('暂不支持!')
this.triggerEvent('Anchorpointtap', e.detail);
},
_getMarker: function _getMarker(markers) {
if (!Array.isArray(markers)) {
markers = Object.values(markers[0]);
}
// markers.map(marker => {
// marker.controlId = marker.id
// delete Object.marker.id
// return marker
// })
this.setData({
markers: markers
});
},
_getControl: function _getControl(controls) {
if (!Array.isArray(controls)) {
controls = Object.values(controls[0]);
}
// this.setData({
// controls: arr.map(control => {
// control.controlId = control.id
// delete Object.control.id
// return control
// })
// })
this.setData({
controls: controls
});
}
}
}); /* eslint-disable no-console */
/* eslint-disable camelcase */
/***/ }),
/***/ 2:
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* eslint-disable no-console */
/* eslint-disable camelcase */
module.exports = Behavior({
properties: {
animation: { type: Object }
},
methods: {
ui_tap: function ui_tap() {
this.triggerEvent('Tap');
},
ui_touchstart: function ui_touchstart() {
this.triggerEvent('Touchstart');
},
ui_touchmove: function ui_touchmove() {
this.triggerEvent('Touchmove');
},
ui_touchcancel: function ui_touchcancel() {
this.triggerEvent('Touchcancel');
},
ui_touchend: function ui_touchend() {
this.triggerEvent('Touchend');
},
ui_longpress: function ui_longpress() {
this.triggerEvent('Longpress');
},
ui_longtap: function ui_longtap() {
this.triggerEvent('Longtap');
},
ui_transitionend: function ui_transitionend() {
this.triggerEvent('Transitionend');
},
ui_animationstart: function ui_animationstart() {
this.triggerEvent('Animationstart');
},
ui_animationiteration: function ui_animationiteration() {
this.triggerEvent('Animationiteration');
},
ui_animationend: function ui_animationend() {
this.triggerEvent('Animationend');
},
ui_touchforcechange: function ui_touchforcechange() {
this.triggerEvent('Touchforcechange');
}
}
});
/***/ })
/******/ });
|
import React from 'react';
import ReactDOM from 'react-dom';
import App from '../Components/App';
import appInit from '../app-init';
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16/build/index';
import MuiThemeProvider from '@material-ui/core/styles/MuiThemeProvider';
import { BrowserRouter } from 'react-router-dom';
import {createMuiTheme} from '@material-ui/core/styles/index';
const themeDark = createMuiTheme({
palette: {
type: 'dark'
}
});
configure({ adapter: new Adapter() });
describe('Jest App Tests', function() {
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(
<MuiThemeProvider theme={themeDark}>
<BrowserRouter>
<App appInit={appInit}/>
</BrowserRouter>
</MuiThemeProvider>,
div
);
ReactDOM.unmountComponentAtNode(div);
});
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<App appInit={appInit}/>, div);
ReactDOM.unmountComponentAtNode(div);
});
});
|
import { Meteor } from 'meteor/meteor';
import { HTTP } from 'meteor/http';
import { Validators } from '/imports/api/validators/validators.js';
import { LCD } from '../../../../server/main'
const fetchFromUrl = (url) => {
try{
let res = HTTP.get(LCD + url);
if (res.statusCode == 200){
return res
};
}
catch (e){
console.log(res);
console.log(e);
}
}
Meteor.methods({
'accounts.getAccountDetail': function(address){
this.unblock();
let url = LCD + '/auth/accounts/'+ address;
try{
let available = HTTP.get(url);
if (available.statusCode == 200){
let response = JSON.parse(available.content).result;
let account;
if (response.type === 'cosmos-sdk/Account')
account = response.value;
else if (response.type === 'cosmos-sdk/DelayedVestingAccount' || response.type === 'cosmos-sdk/ContinuousVestingAccount')
account = response.value.BaseVestingAccount.BaseAccount
if (account && account.account_number != null)
return account
return null
}
}
catch (e){
console.log(url);
console.log(e)
}
},
'accounts.getBalance': function(address){
this.unblock();
let balance = {}
console.log("GET BALANCE CALLED")
// process.exit("here exited")
// get available atoms
let url = LCD + '/bank/balances/'+ address;
try{
let available = HTTP.get(url);
if (available.statusCode == 200){
balance.available = JSON.parse(available.content).result;
}
}
catch (e){
console.log(url);
console.log(e)
}
// get delegated amnounts
url = LCD + '/staking/delegators/'+address+'/delegations';
try{
let delegations = HTTP.get(url);
if (delegations.statusCode == 200){
balance.delegations = JSON.parse(delegations.content).result;
}
}
catch (e){
console.log(url);
console.log(e);
}
// get unbonding
url = LCD + '/staking/delegators/'+address+'/unbonding_delegations';
try{
let unbonding = HTTP.get(url);
if (unbonding.statusCode == 200){
balance.unbonding = JSON.parse(unbonding.content).result;
}
}
catch (e){
console.log(url);
console.log(e);
}
// get rewards
url = LCD + '/distribution/delegators/'+address+'/rewards';
try{
let rewards = HTTP.get(url);
if (rewards.statusCode == 200){
//get seperate rewards value
balance.rewards = JSON.parse(rewards.content).result.rewards;
//get total rewards value
balance.total_rewards= JSON.parse(rewards.content).result.total;
}
}
catch (e){
console.log(url);
console.log(e);
}
// get commission
let validator = Validators.findOne(
{$or: [{operator_address:address}, {delegator_address:address}, {address:address}]})
if (validator) {
let url = LCD + '/distribution/validators/' + validator.operator_address;
balance.operator_address = validator.operator_address;
try {
let rewards = HTTP.get(url);
if (rewards.statusCode == 200){
let content = JSON.parse(rewards.content).result;
if (content.val_commission && content.val_commission.length > 0)
balance.commission = content.val_commission;
}
}
catch (e){
console.log(url);
console.log(e)
}
}
return balance;
},
'accounts.getDelegation'(address, validator){
let url = `/staking/delegators/${address}/delegations/${validator}`;
let delegations = fetchFromUrl(url);
delegations = delegations && delegations.data.result;
if (delegations && delegations.shares)
delegations.shares = parseFloat(delegations.shares);
url = `/staking/redelegations?delegator=${address}&validator_to=${validator}`;
let relegations = fetchFromUrl(url);
relegations = relegations && relegations.data.result;
let completionTime;
if (relegations) {
relegations.forEach((relegation) => {
let entries = relegation.entries
let time = new Date(entries[entries.length-1].completion_time)
if (!completionTime || time > completionTime)
completionTime = time
})
delegations.redelegationCompletionTime = completionTime;
}
url = `/staking/delegators/${address}/unbonding_delegations/${validator}`;
let undelegations = fetchFromUrl(url);
undelegations = undelegations && undelegations.data.result;
if (undelegations) {
delegations.unbonding = undelegations.entries.length;
delegations.unbondingCompletionTime = undelegations.entries[0].completion_time;
}
return delegations;
},
'accounts.getAllDelegations'(address){
let url = LCD + '/staking/delegators/'+address+'/delegations';
try{
let delegations = HTTP.get(url);
if (delegations.statusCode == 200){
delegations = JSON.parse(delegations.content).result;
if (delegations && delegations.length > 0){
delegations.forEach((delegation, i) => {
if (delegations[i] && delegations[i].shares)
delegations[i].shares = parseFloat(delegations[i].shares);
})
}
return delegations;
};
}
catch (e){
console.log(url);
console.log(e);
}
},
'accounts.getAllUnbondings'(address){
let url = LCD + '/staking/delegators/'+address+'/unbonding_delegations';
try{
let unbondings = HTTP.get(url);
if (unbondings.statusCode == 200){
unbondings = JSON.parse(unbondings.content).result;
return unbondings;
};
}
catch (e){
console.log(url);
console.log(e);
}
},
'accounts.getAllRedelegations'(address, validator){
let url = `/staking/redelegations?delegator=${address}&validator_from=${validator}`;
let result = fetchFromUrl(url);
if (result && result.data) {
let redelegations = {}
result.data.forEach((redelegation) => {
let entries = redelegation.entries;
redelegations[redelegation.validator_dst_address] = {
count: entries.length,
completionTime: entries[0].completion_time
}
})
return redelegations
}
},
'accounts.getRedelegations'(address) {
let url = LCD + '/staking/redelegations?delegator=' + address;
try {
let userRedelegations = HTTP.get(url);
if (userRedelegations.statusCode == 200) {
userRedelegations = JSON.parse(userRedelegations.content).result;
return userRedelegations;
};
} catch (e) {
console.log(url);
console.log(e.response.content);
}
},
})
|
import React from 'react';
import { Router, Route, Switch } from 'react-router-dom';
import createHistory from 'history/createBrowserHistory';
import PrivateRoute from './PrivateRoute';
import PublicRoute from './PublicRoute';
import Login from 'features/auth/components/Login';
import Register from 'features/auth/components/Register';
import Dashboard from 'features/dashboard/components/Dashboard';
import NotFoundPage from 'features/notFound/components/NotFoundPage';
export const history = createHistory();
const AppRouter = () => (
<Router history={history}>
<div>
<Switch>
<PublicRoute path="/" component={Login} exact={true} />
<PublicRoute path="/register" component={Register} />
<PrivateRoute path="/dashboard" component={Dashboard} />
<Route component={NotFoundPage} />
</Switch>
</div>
</Router>
);
export default AppRouter;
|
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
import * as tslib_1 from "tslib";
import CalendarLocale from '../calendar/bg_BG';
import TimePickerLocale from '../time-picker/bg_BG';
// Merge into a locale object
var /** @type {?} */ locale = {
lang: tslib_1.__assign({ placeholder: 'Избор на дата', rangePlaceholder: ['Начална', 'Крайна'] }, CalendarLocale),
timePickerLocale: tslib_1.__assign({}, TimePickerLocale),
};
export default locale;
//# sourceMappingURL=bg_BG.js.map
|
from datetime import (time,
datetime)
from typing import Iterator
from hypothesis import strategies
from tests.utils import example
from .api import (api_base_urls,
api_keys)
from .utils import (TMDB_FOUNDATION_DATE,
load_max_movie_id)
MIN_MOVIE_ID = 2
MAX_MOVIE_ID = load_max_movie_id(api_base_url=example(api_base_urls),
api_key=example(api_keys))
MIN_PAGE_NUMBER = 1
MAX_PAGE_NUMBER = 1000
def ratings(min_movie_rating: float = 0.5,
max_movie_rating: float = 10.,
movie_rating_step: float = 0.5) -> Iterator[float]:
rating = min_movie_rating
while rating <= max_movie_rating:
yield rating
rating += movie_rating_step
movies_ids = strategies.integers(min_value=MIN_MOVIE_ID,
max_value=MAX_MOVIE_ID)
nonexistent_movies_ids = (strategies.integers(max_value=MIN_MOVIE_ID - 1)
# we're expecting
# that there will be less
# than 1_000 new records in TMDb
# while tests session is running
| strategies.integers(min_value=MAX_MOVIE_ID + 1000))
movies_changes_date_times = strategies.datetimes(
min_value=datetime.combine(TMDB_FOUNDATION_DATE, time()),
max_value=datetime.utcnow())
movies_ratings = strategies.sampled_from(list(ratings()))
pages_numbers = strategies.integers(min_value=MIN_PAGE_NUMBER,
max_value=MAX_PAGE_NUMBER)
invalid_pages_numbers = (strategies.integers(max_value=MIN_PAGE_NUMBER - 1)
| strategies.integers(min_value=MAX_PAGE_NUMBER + 1))
|
/**
* @param {string} prefix
* @constructor
*/
function Quizz() {
this.items = [
{
"type": "capital",
"options": ["Mali", "Ghana", "Ouganda", "Burundi"],
"question": "Accra",
"answer": 1
},
{
"type": "capital",
"options": ["Jordan", "Oman", "Bahrain", "Ethiopia"],
"question": "Amman",
"answer": 0
},
{
"type": "capital",
"options": ["Lithuania", "Slovenia", "Latvia", "Slovakia"],
"question": "Riga",
"answer": 2
},
{
"type": "capital",
"options": ["Philippines", "Indonesia", "Malaysia", "Madagascar"],
"question": "Manila",
"answer": 0
},
{
"type": "open",
"options": ["Quebec", "Toronto", "Ottawa", "Montreal"],
"question": "Which is capital of Canada?",
"answer": 2
},
{
"type": "open",
"options": ["250m.", "300m.", "350m.", "450m."],
"question": "How tall is the Eiffel Tower (in Meters)?",
"answer": 1
},
{
"type": "open",
"options": ["2,986km", "3,054km", "3,474km", "4,132km"],
"question": "What is the distance to Moon? (in Kilometers)",
"answer": 2
},
{
"type": "open",
"options": ["6,778km", "6,958km", "7,223km", "8.334km"],
"question": "What is the distance to Mars? (in Kilometers)",
"answer": 0
},
{
"type": "open",
"options": ["Sushma Swaraj", "Pranab Mukherjee", "Nitin Gadkari", "Ananth Kumar"],
"question": "Who is today India president?",
"answer": 1
},
{
"type": "open",
"options": ["1997", "1988", "1989", "1990"],
"question": "when did berlin wall fall?",
"answer": 2
},
{
"type": "open",
"options": ["North", "South"],
"question": "Where is Antarctica?",
"answer": 1
},
{
"type": "open",
"options": [16, 24, 29, 34],
"question": "How many countries have French as official language?",
"answer": 2
},
{
"type": "open",
"options": [48, 54, 59, 63],
"question": "How many countries in Africa?",
"answer": 1
},
{
"type": "open",
"options": ["6,147,851 km", "7,554,354 km", "8,347,458 km", "9,596,961 km"],
"question": "Surface of China?",
"answer": 3
},
{
"type": "open",
"options": ["Thomas Jefferson", "John Adams", "George Washington", "Justin Bieber"],
"question": "First president of the USA?",
"answer": 2
},
{
"type": "open",
"options": ["North", "South"],
"question": "Where is Antarctica?",
"answer": 1
},
{
"type": "open",
"options": ["Wales", "Scotland", "ireland", "Belgium"],
"question": "Which country produces Guiness beer?",
"answer": 2
},
{
"type": "open",
"options": ["Swiss", "Norway", "Bahamas", "Canada"],
"question": "How won curling event at 2012 Olympics?",
"answer": 2
},
{
"type": "open",
"options": ["Liverpool", "Manchester", "London", "Bristol"],
"question": "Native city of the Beatles?",
"answer": 0
},
{
"type": "open",
"options": ["French", "Italian", "Spanish", "Portuguese"],
"question": "Nationality of Picasso?",
"answer": 2
},
{
"type": "open",
"options": ["12 hours 45 minutes", "13 hours 17 minutes", "15 hours 26 minutes", "16 hours 5 minutes"],
"question": "Total length of 6 Star Wars episodes?",
"answer": 1
},
{
"type": "open",
"options": [14, 16, 18, 22],
"question": "How many players per australian football team?",
"answer": 2
},
{
"type": "open",
"options": [11,12,13,14],
"question": "How many players per Cricket team?",
"answer": 0
},
{
"type": "open",
"options": ["Patty", "Alcmène", "Mégara", "Gaïa"],
"question": "name of Hercules mother?",
"answer": 1
},
{
"type": "open",
"options": [11,12,13,14],
"question": "How many players per Cricket team?",
"answer": 0
},
{
"type": "open",
"options": ["Portuguese", "French", "Nobody", "Spanish"],
"question": "Who expected the spanish inquisition?",
"answer": 2
},
{
"type": "open",
"options": [11,12,13,14],
"question": "How many players per Cricket team?",
"answer": 0
},
{
"type": "open",
"options": ["Green", "Blue", "Yellow", "Red"],
"question": "What color is vermilion?",
"answer": 3
},
{
"type": "open",
"options": ["3.12s", "9.64s", "9.58s", "14.58s"],
"question": "What is Men's 100 metres world record?",
"answer": 2
},
{
"type": "open",
"options": ["6.32s", "10.49s", "10.55s", "29.58s"],
"question": "What is Women's 100 metres world record?",
"answer": 1
}
];
}
|
const path = require("path");
const process = require("process");
const { spawnSync } = require("child_process");
const { getRushSpec } = require("./index");
const parseArgs = () => {
if (process.argv.some((a) => ["-h", "--help"].includes(a.toLowerCase())) || process.argv.length < 3) {
console.error("Usage: node update-samples.js <artifact-name>");
console.error("Example: node update-samples.js azure-storage-blob");
}
const [scriptPath, artifactName] = process.argv.slice(1);
const baseDir = path.resolve(`${path.dirname(scriptPath)}/../../..`);
return [baseDir, artifactName];
};
const spawnNode = (cwd, ...args) => {
console.log(`Executing: "dev-tool ${args.join(" ")}" in ${cwd}\n\n`);
const proc = spawnSync("dev-tool", args, { cwd, shell: true, stdio: "inherit" });
console.log(`\n\process exited with code ${proc.status}`);
if (proc.status !== 0) {
process.exitCode = proc.status || 1;
}
return proc.status
};
async function main(repoRoot, artifactName) {
var rushSpec = await getRushSpec(repoRoot);
//Find project root directory using information in rush.json
const targetPackage = rushSpec.projects.find(
(packageSpec) => packageSpec.packageName.replace("@", "").replace("/", "-") == artifactName
);
if (!targetPackage) {
console.error(`Package is not found in rush.json for artifact ${artifactName}`);
return;
}
if (targetPackage.versionPolicyName == "management") {
console.error(`Skipping update samples for management package ${artifactName}`);
return;
}
console.log(`Running samples update for package ${targetPackage.packageName}`);
spawnNode(targetPackage.projectFolder, "samples publish --force");
};
const [repoRoot, artifactName] = parseArgs();
main(repoRoot, artifactName);
|
#! /usr/bin/env python3
import os
import sys
from subprocess import check_output #nosec
# add .. to PYTHONPATH
path = os.path.realpath(__file__)
basedir = os.path.dirname(os.path.dirname(path))
sys.path.append(basedir)
# add ../solver and ../util and ../plot to PATH
os.environ['PATH'] += ':' + os.path.join(basedir, 'solver')
os.environ['PATH'] += ':' + os.path.join(basedir, 'util')
os.environ['PATH'] += ':' + os.path.join(basedir, 'plot')
os.environ['DJANGO_SETTINGS_MODULE'] = 'astrometry.net.settings'
import django
django.setup()
from django.core.exceptions import MultipleObjectsReturned
import traceback
from urllib.parse import urlparse
import urllib.request, urllib.parse, urllib.error
import shutil
import multiprocessing
import time
import re
import tarfile
import gzip
import zipfile
import math
from astrometry.net import settings
settings.LOGGING['loggers'][''] = {
'handlers': ['console'],
'level': 'INFO',
'propagate': False,
}
tempdir = os.path.join(settings.TEMPDIR, 'proc-subs')
try:
os.makedirs(tempdir)
except:
pass
settings.TEMPDIR = tempdir
os.environ['TMP'] = tempdir
os.environ['TMPDIR'] = tempdir
import tempfile
from astrometry.net.tmpfile import get_temp_file
print('get_temp_file():', get_temp_file())
from astrometry.util import image2pnm
from astrometry.util.filetype import filetype_short
from astrometry.util.run_command import run_command
from astrometry.util.util import Tan
from astrometry.util import util as anutil
from astrometry.util.fits import *
from astrometry.net.models import *
from astrometry.net.log import logmsg
from django.db.models import Count
from django.db import DatabaseError
from django.db.models import Q
#import logging
#logging.basicConfig(format='%(message)s', level=logging.DEBUG)
def is_tarball(fn):
logmsg('is_tarball: %s' % fn)
types = filetype_short(fn)
logmsg('filetypes:', types)
for t in types:
if t.startswith('POSIX tar archive'):
return True
return False
def get_tarball_files(fn, tempdirs=None):
# create temp dir to extract tarfile.
tempdir = tempfile.mkdtemp()
if tempdirs is not None:
tempdirs.append(tempdir)
cmd = 'tar xvf %s -C %s' % (fn, tempdir)
print('Extracting tarball: %s' % cmd)
(rtn, out, err) = run_command(cmd)
if rtn:
print('Failed to un-tar file:\n' + err)
#bailout(submission, 'failed to extract tar file')
print('failed to extract tar file')
return None
fns = out.strip('\n').split('\n')
validpaths = []
for fn in fns:
path = os.path.join(tempdir, fn)
logmsg('Path "%s"' % path)
if not os.path.exists(path):
logmsg('Path "%s" does not exist.' % path)
continue
if os.path.islink(path):
logmsg('Path "%s" is a symlink.' % path)
continue
if os.path.isfile(path):
validpaths.append(path)
else:
logmsg('Path "%s" is not a file.' % path)
if len(validpaths) == 0:
#userlog('Tar file contains no regular files.')
#bailout(submission, "tar file contains no regular files.")
#return -1
logmsg('No real files in tar file')
return None
logmsg('Got %i paths.' % len(validpaths))
return validpaths
def run_pnmfile(fn):
""" run the pnmfile command to get image dimenensions"""
# bandit warns about security implications. We provide our own filename
# and the sysadmin has to make sure the correct pnmfile is found in the PATH
# TODO: document this for sysadmins
out = check_output(['pnmfile', fn]).decode().strip() #nosec
logdebug('pnmfile output: ' + out)
pat = re.compile(r'P(?P<pnmtype>[BGP])M .*, (?P<width>\d*) by (?P<height>\d*)( *maxval (?P<maxval>\d*))?')
match = pat.search(out)
if not match:
logmsg('pnmfile: No regex match.')
return None
w = int(match.group('width'))
h = int(match.group('height'))
pnmtype = match.group('pnmtype')
mv = match.group('maxval')
if mv is None:
maxval = 1
else:
maxval = int(mv)
logdebug('Type %s, w %i, h %i, maxval %i' % (pnmtype, w, h, maxval))
return (w, h, pnmtype, maxval)
class MyLogger(object):
def __init__(self, logger):
self.logger = logger
def debug(self, *args):
return self.logger.debug(' '.join(str(x) for x in args))
def info(self, *args):
return self.logger.info(' '.join(str(x) for x in args))
msg = info
def create_job_logger(job):
'''
Create a MyLogger object that writes to a log file within a Job directory.
'''
logmsg("getlogger")
logger = logging.getLogger('job.%i' % job.id)
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler(job.get_log_file2())
fh.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)
return MyLogger(logger)
def try_dojob(job, userimage, solve_command, solve_locally):
print('try_dojob', job, '(sub', job.user_image.submission.id, ')')
tempfiles = []
rtn = None
try:
rtn = dojob(job, userimage, solve_command=solve_command,
solve_locally=solve_locally, tempfiles=tempfiles)
print('try_dojob', job, 'completed:', rtn)
except OSError as e:
print('OSError processing job', job)
print(e)
import errno
# Too many open files
print('e.errno:', e.errno)
print('errno.EMFILE:', errno.EMFILE)
if e.errno == errno.EMFILE:
print('Too many open files -- exiting!')
#sys.exit(-1)
## Want to stop the main process, not just this pool worker process
raise e
except IOError as e:
import errno
print('Caught IOError')
print('Errno:', e.errno)
if e.errno == errno.EMFILE:
print('Too many open files!')
##sys.exit(-1)
raise e
except:
print('Caught exception while processing Job', job)
traceback.print_exc(None, sys.stdout)
# FIXME -- job.set_status()...
job.set_end_time()
job.status = 'F'
job.save()
log = create_job_logger(job)
log.msg('Caught exception while processing Job', job.id)
log.msg(traceback.format_exc(None))
for fn in tempfiles:
if os.path.exists(fn):
try:
os.remove(fn)
except OSError as e:
logmsg('Failed to delete temp file', fn, ':', e)
return rtn
def dojob(job, userimage, log=None, solve_command=None, solve_locally=None,
tempfiles=None):
print('dojob: tempdir:', tempfile.gettempdir())
jobdir = job.make_dir()
#print('Created job dir', jobdir)
#log = create_job_logger(job)
#jobdir = job.get_dir()
if log is None:
log = create_job_logger(job)
log.msg('Starting Job processing for', job)
job.set_start_time()
job.save()
#os.chdir(dirnm) - not thread safe (working directory is global)!
log.msg('Creating directory', jobdir)
axyfn = 'job.axy'
axypath = os.path.join(jobdir, axyfn)
sub = userimage.submission
log.msg('submission id', sub.id)
df = userimage.image.disk_file
img = userimage.image
# Build command-line arguments for the augment-xylist program, which
# detects sources in the image and adds processing arguments to the header
# to produce a "job.axy" file.
slo,shi = sub.get_scale_bounds()
# Note, this must match Job.get_wcs_file().
wcsfile = 'wcs.fits'
corrfile = 'corr.fits'
axyflags = []
axyargs = {
'--out': axypath,
'--scale-low': slo,
'--scale-high': shi,
'--scale-units': sub.scale_units,
'--wcs': wcsfile,
'--corr': corrfile,
'--rdls': 'rdls.fits',
'--pixel-error': sub.positional_error,
'--ra': sub.center_ra,
'--dec': sub.center_dec,
'--radius': sub.radius,
'--downsample': sub.downsample_factor,
'--objs': 1000,
# tuning-up maybe fixed; if not, turn it off with:
#'--odds-to-tune': 1e9,
# Other things we might want include...
# --invert
# -g / --guess-scale: try to guess the image scale from the FITS headers
# --crpix-x <pix>: set the WCS reference point to the given position
# --crpix-y <pix>: set the WCS reference point to the given position
# -w / --width <pixels>: specify the field width
# -e / --height <pixels>: specify the field height
# -X / --x-column <column-name>: the FITS column name
# -Y / --y-column <column-name>
}
if hasattr(img,'sourcelist'):
# image is a source list; use --xylist
axyargs['--xylist'] = img.sourcelist.get_fits_path(tempfiles=tempfiles)
w,h = img.width, img.height
if sub.image_width:
w = sub.image_width
if sub.image_height:
h = sub.image_height
axyargs['--width' ] = w
axyargs['--height'] = h
else:
axyargs['--image'] = df.get_path()
# UGLY
if sub.parity == 0:
axyargs['--parity'] = 'pos'
elif sub.parity == 1:
axyargs['--parity'] = 'neg'
if sub.tweak_order == 0:
axyflags.append('--no-tweak')
else:
axyargs['--tweak-order'] = '%i' % sub.tweak_order
if sub.use_sextractor:
axyflags.append('--use-source-extractor')
if sub.crpix_center:
axyflags.append('--crpix-center')
if sub.invert:
axyflags.append('--invert')
cmd = 'augment-xylist '
for (k,v) in list(axyargs.items()):
if v:
cmd += k + ' ' + str(v) + ' '
for k in axyflags:
cmd += k + ' '
log.msg('running: ' + cmd)
(rtn, out, err) = run_command(cmd)
if rtn:
log.msg('out: ' + out)
log.msg('err: ' + err)
logmsg('augment-xylist failed: rtn val', rtn, 'err', err)
raise Exception
log.msg('created axy file', axypath)
# shell into compute server...
logfn = job.get_log_file()
# the "tar" commands both use "-C" to chdir, and the ssh command
# and redirect uses absolute paths.
if solve_locally is not None:
cmd = (('cd %(jobdir)s && %(solvecmd)s %(jobid)s %(axyfile)s >> ' +
'%(logfile)s') %
dict(jobid='job-%s-%i' % (settings.sitename, job.id),
solvecmd=solve_locally,
axyfile=axyfn, jobdir=jobdir,
logfile=logfn))
log.msg('command:', cmd)
w = os.system(cmd)
if not os.WIFEXITED(w):
log.msg('Solver failed (sent signal?)')
logmsg('Call to solver failed for job', job.id)
raise Exception
rtn = os.WEXITSTATUS(w)
if rtn:
log.msg('Solver failed with return value %i' % rtn)
logmsg('Call to solver failed for job', job.id, 'with return val',
rtn)
raise Exception
log.msg('Solver completed successfully.')
else:
if solve_command is None:
solve_command = 'ssh -x -T %(sshconfig)s'
cmd = (('(echo %(jobid)s; '
'tar cf - --ignore-failed-read -C %(jobdir)s %(axyfile)s) | '
+ solve_command + ' 2>>%(logfile)s | '
'tar xf - --atime-preserve -m --exclude=%(axyfile)s -C %(jobdir)s '
'>>%(logfile)s 2>&1') %
dict(jobid='job-%s-%i' % (settings.sitename, job.id),
axyfile=axyfn, jobdir=jobdir,
sshconfig=settings.ssh_solver_config,
logfile=logfn))
log.msg('command:', cmd)
w = os.system(cmd)
if not os.WIFEXITED(w):
log.msg('Solver failed (sent signal?)')
logmsg('Call to solver failed for job', job.id)
raise Exception
rtn = os.WEXITSTATUS(w)
if rtn:
log.msg('Solver failed with return value %i' % rtn)
logmsg('Call to solver failed for job', job.id, 'with return val',
rtn)
raise Exception
log.msg('Solver completed successfully.')
# Solved?
wcsfn = os.path.join(jobdir, wcsfile)
log.msg('Checking for WCS file', wcsfn)
if os.path.exists(wcsfn):
log.msg('WCS file exists')
# Parse the wcs.fits file
wcs = Tan(wcsfn, 0)
# Convert to database model...
tan = TanWCS(crval1=wcs.crval[0], crval2=wcs.crval[1],
crpix1=wcs.crpix[0], crpix2=wcs.crpix[1],
cd11=wcs.cd[0], cd12=wcs.cd[1],
cd21=wcs.cd[2], cd22=wcs.cd[3],
imagew=img.width, imageh=img.height)
tan.save()
log.msg('Created TanWCS:', tan)
# Find field's healpix nside and index
ra, dec, radius = tan.get_center_radecradius()
nside = anutil.healpix_nside_for_side_length_arcmin(radius*60)
nside = int(2**round(math.log(nside, 2)))
nside = max(1, nside)
healpix = anutil.radecdegtohealpix(ra, dec, nside)
try:
sky_location, created = SkyLocation.objects.get_or_create(nside=nside, healpix=healpix)
except MultipleObjectsReturned:
log.msg('Multiple SkyLocations for nside %i, healpix %i' % (nside, healpix))
# arbitrarily take the first one.
sky_location = SkyLocation.objects.filter(nside=nside, healpix=healpix)[0]
log.msg('SkyLocation:', sky_location)
# Find bounds for the Calibration object.
r0,r1,d0,d1 = wcs.radec_bounds()
# Find cartesian coordinates
ra *= math.pi/180
dec *= math.pi/180
tempr = math.cos(dec)
x = tempr*math.cos(ra)
y = tempr*math.sin(ra)
z = math.sin(dec)
r = radius/180*math.pi
calib = Calibration(raw_tan=tan, ramin=r0, ramax=r1, decmin=d0, decmax=d1,
x=x,y=y,z=z,r=r,
sky_location=sky_location)
calib.save()
log.msg('Created Calibration', calib)
job.calibration = calib
job.save() # save calib before adding machine tags
job.status = 'S'
job.user_image.add_machine_tags(job)
job.user_image.add_sky_objects(job)
else:
job.status = 'F'
job.set_end_time()
job.save()
log.msg('Finished job', job.id)
logmsg('Finished job',job.id)
return job.id
def try_dosub(sub, max_retries):
subid = sub.id
tempfiles = []
tempdirs = []
rtn = None
try:
rtn = dosub(sub, tempfiles=tempfiles, tempdirs=tempdirs)
except DatabaseError as e:
print('Caught DatabaseError while processing Submission', sub)
traceback.print_exc(None, sys.stdout)
# Try...
django.db.connection.close()
sub = Submission.objects.get(id=subid)
if (sub.processing_retries < max_retries):
print('Retrying processing Submission %s' % str(sub))
sub.processing_retries += 1
sub.save()
rtn = try_dosub(sub, max_retries,
tempfiles=tempfiles, tempdirs=tempdirs)
else:
print('Submission retry limit reached')
sub.set_error_message(
'Caught exception while processing Submission: ' + str(sub) + '\n'
+ traceback.format_exc(None))
sub.set_processing_finished()
sub.save()
rtn = 'exception'
except:
print('Caught exception while processing Submission', sub)
traceback.print_exc(None, sys.stdout)
sub.set_error_message(
'Caught exception while processing Submission: ' + str(sub) + '\n'
+ traceback.format_exc(None))
sub.set_processing_finished()
sub.save()
logmsg('Caught exception while processing Submission ' + str(sub))
logmsg(' ' + traceback.format_exc(None))
rtn = 'exception'
for dirnm in tempdirs:
if os.path.exists(dirnm):
try:
shutil.rmtree(dirnm)
except OSError as e:
logmsg('Failed to delete temp dir', dirnm, ':', e)
for fn in tempfiles:
if os.path.exists(fn):
try:
os.remove(fn)
except OSError as e:
logmsg('Failed to delete temp file', fn, ':', e)
return rtn
def dosub(sub, tempfiles=None, tempdirs=None):
print('dosub: tempdir:', tempfile.gettempdir())
sub.set_processing_started()
sub.save()
print('Submission disk file:', sub.disk_file)
if sub.disk_file is None:
logmsg('Sub %i: retrieving URL' % (sub.id), sub.url)
(fn, headers) = urllib.request.urlretrieve(sub.url)
logmsg('Sub %i: wrote URL to file' % (sub.id), fn)
df = DiskFile.from_file(fn, Image.ORIG_COLLECTION)
logmsg('Created DiskFile', df)
# Try to split the URL into a filename component and save it
p = urlparse(sub.url)
p = p.path
if p:
s = p.split('/')
origname = s[-1]
sub.original_filename = origname
df.save()
sub.disk_file = df
sub.save()
logmsg('Saved DiskFile', df)
else:
logmsg('uploaded disk file for this submission is ' + str(sub.disk_file))
df = sub.disk_file
fn = df.get_path()
logmsg('DiskFile path ' + fn)
original_filename = sub.original_filename
# check if file is a gzipped file
try:
with gzip.open(fn) as gzip_file:
tempfn = get_temp_file(tempfiles=tempfiles)
with open(tempfn, 'wb') as f:
# should fail on the following line if not a gzip file
f.write(gzip_file.read())
df = DiskFile.from_file(tempfn, 'uploaded-gunzip')
i = original_filename.find('.gz')
if i != -1:
original_filename = original_filename[:i]
logmsg('extracted gzip file %s' % original_filename)
#fn = tempfn
fn = df.get_path()
except:
# not a gzip file
pass
is_tar = False
try:
is_tar = tarfile.is_tarfile(fn)
except:
pass
if is_tar:
logmsg('File %s: tarball' % fn)
tar = tarfile.open(fn)
dirnm = tempfile.mkdtemp()
if tempdirs is not None:
tempdirs.append(dirnm)
for tarinfo in tar.getmembers():
if tarinfo.isfile():
logmsg('extracting file %s' % tarinfo.name)
tar.extract(tarinfo, dirnm)
tempfn = os.path.join(dirnm, tarinfo.name)
df = DiskFile.from_file(tempfn, 'uploaded-untar')
# create Image object
img = get_or_create_image(df, tempfiles=tempfiles)
# create UserImage object.
if img:
create_user_image(sub, img, tarinfo.name)
tar.close()
shutil.rmtree(dirnm, ignore_errors=True)
else:
# assume file is single image
logmsg('File %s: single file' % fn)
# create Image object
img = get_or_create_image(df, tempfiles=tempfiles)
logdebug('File %s: created Image %s' % (fn, str(img)))
# create UserImage object.
if img:
uimg = create_user_image(sub, img, original_filename)
logmsg('File %s: Image id %i, UserImage id %i' % (fn, img.id, uimg.id))
sub.set_processing_finished()
sub.save()
return sub.id
def create_user_image(sub, img, original_filename):
pro = get_user_profile(sub.user)
license, created = License.objects.get_or_create(
default_license=pro.default_license,
allow_modifications = sub.license.allow_modifications,
allow_commercial_use = sub.license.allow_commercial_use,
)
comment_receiver = CommentReceiver.objects.create()
uimg,created = UserImage.objects.get_or_create(
submission=sub,
image=img,
user=sub.user,
license=license,
comment_receiver=comment_receiver,
defaults=dict(original_file_name=original_filename,
publicly_visible = sub.publicly_visible))
if sub.album:
sub.album.user_images.add(uimg)
return uimg
def get_or_create_image(df, create_thumb=True, tempfiles=None):
imgs = Image.objects.filter(disk_file=df, display_image__isnull=False, thumbnail__isnull=False)
if imgs.count():
return imgs[0]
img = create_image(df, tempfiles=tempfiles)
#logmsg('img = ' + str(img))
if img is None:
# try to create sourcelist image
img = create_source_list(df, tempfiles=tempfiles)
if img and create_thumb:
# cache
logdebug('Creating thumbnail')
img.get_thumbnail(tempfiles=tempfiles)
logdebug('Creating display-sized image')
img.get_display_image(tempfiles=tempfiles)
img.save()
elif img:
img.save()
else:
raise Exception("This file's type is not supported.")
return img
# # Is there already an Image for this DiskFile?
# try:
# except Image.MultipleObjectsReturned:
# logmsg("multiple found")
# imgs = Image.objects.filter(disk_file=df, display_image__isnull=False, thumbnail__isnull=False)
# for i in range(1,len(imgs)):
# imgs[i].delete()
# img = imgs[0]
# except Image.DoesNotExist:
# # try to create image assume disk file is an image file (png, jpg, etc)
# logmsg('Image database object does not exist; creating')
# img = create_image(df)
# logmsg('img = ' + str(img))
# if img is None:
# # try to create sourcelist image
# img = create_source_list(df)
#
# if img:
# # cache
# print('Creating thumbnail')
# img.get_thumbnail()
# print('Creating display-sized image')
# img.get_display_image()
# print('Saving image')
# img.save()
# else:
# raise Exception('This file\'s type is not supported.')
# return img
def create_image(df, tempfiles=None):
img = None
try:
img = Image(disk_file=df)
# FIXME -- move this code to Image?
# Convert file to pnm to find its size.
pnmfn = img.get_pnm_path(tempfiles=tempfiles)
x = run_pnmfile(pnmfn)
if x is None:
raise RuntimeError('Could not find image file size')
(w, h, pnmtype, maxval) = x
logdebug('Type %s, w %i, h %i' % (pnmtype, w, h))
img.width = w
img.height = h
img.save()
except:
logmsg('file is not an image file: ' + traceback.format_exc())
img = None
return img
def create_source_list(df, tempfiles=None):
img = None
fits = None
source_type = None
path = df.get_path()
print('path:', path, type(path))
try:
# see if disk file is a fits list
fits = fits_table(str(df.get_path()))
source_type = 'fits'
except:
logmsg('file is not a fits table')
# otherwise, check to see if it is a text list
try:
fitsfn = get_temp_file(tempfiles=tempfiles)
text_file = open(str(df.get_path()))
text = text_file.read()
text_file.close()
# add x y header
# potential hack, assumes it doesn't exist...
text = "# x y\n" + text
text_table = text_table_fields("", text=text)
text_table.write_to(fitsfn)
logmsg("Creating fits table from text list")
fits = fits_table(fitsfn)
source_type = 'text'
except Exception as e:
#logmsg('Traceback:\n' + traceback.format_exc())
logmsg('fitsfn: %s' % fitsfn)
logmsg(e)
logmsg('file is not a text list')
if fits:
try:
img = SourceList(disk_file=df, source_type=source_type)
# w = fits.x.max()-fits.x.min()
# h = fits.y.max()-fits.y.min()
# w = int(w)
# h = int(h)
w = int(math.ceil(fits.x.max()))
h = int(math.ceil(fits.y.max()))
logmsg('w %i, h %i' % (w, h))
if w < 1 or h < 1:
raise RuntimeError('Source list must contain POSITIVE x,y coordinates')
img.width = w
img.height = h
img.save()
except Exception as e:
logmsg(e)
img = None
raise e
return img
## DEBUG
def sub_callback(result):
print('Submission callback: Result:', result)
def job_callback(result):
print('Job callback: Result:', result)
def main(dojob_nthreads, dosub_nthreads, refresh_rate, max_sub_retries,
solve_command, solve_locally):
print('Tempdir:', tempfile.gettempdir())
from logging.config import dictConfig
dictConfig(settings.LOGGING)
# exit after a day
maxtime = 3600 * 24
# force quit after this much extra time (10 mins)
extratime = 600
t_start = time.time()
dojob_pool = None
dosub_pool = None
if dojob_nthreads > 1:
print('Processing jobs with %d threads' % dojob_nthreads)
dojob_pool = multiprocessing.Pool(processes=dojob_nthreads)
if dosub_nthreads > 1:
print('Processing submissions with %d threads' % dosub_nthreads)
dosub_pool = multiprocessing.Pool(processes=dosub_nthreads)
print('Refresh rate: %.1f seconds' % refresh_rate)
print('Submission processing retry limit: %d' % max_sub_retries)
# Find Submissions that have been started but not finished;
# reset the start times to null.
oldsubs = Submission.objects.filter(processing_started__isnull=False,
processing_finished__isnull=True)
for sub in oldsubs:
print('Resetting the processing status of', sub)
sub.processing_started = None
sub.save()
oldjobs = Job.objects.filter(Q(end_time__isnull=True),
Q(start_time__isnull=False) |
Q(queued_time__isnull=False))
#for job in oldjobs:
# #print('Resetting the processing status of', job)
# #job.start_time = None
# #job.save()
# FIXME -- really?
oldjobs.delete()
subresults = []
jobresults = []
#
me = ProcessSubmissions(pid=os.getpid())
me.set_watchdog()
me.save()
lastsubs = []
lastjobs = []
while True:
me.set_watchdog()
me.save()
print()
t_now = time.time() - t_start
quitnow = (t_now > maxtime)
#print('Checking for new Submissions')
newsubs = Submission.objects.filter(processing_started__isnull=True)
if newsubs.count():
print('Found', newsubs.count(), 'unstarted Submissions:', [s.id for s in newsubs])
print('Checking for UserImages without Jobs')
all_user_images = UserImage.objects.annotate(job_count=Count('jobs'))
newuis = all_user_images.filter(job_count=0)
if newuis.count():
#print('Found', len(newuis), 'UserImages without Jobs:', [u.id for u in newuis])
#print('Found', len(newuis), 'UserImages without Jobs.')
print('Jobs need to be started for', len(newuis), 'UserImages')
runsubs = me.subs.filter(finished=False)
if subresults != lastsubs:
print('Submissions running:', len(subresults))
lastsubs = subresults
for sid,res in subresults:
print(' Submission id', sid, 'ready:', res.ready(), end=' ')
if res.ready():
subresults.remove((sid,res))
print('success:', res.successful(), end=' ')
qs = runsubs.get(submission__id=sid)
qs.finished = True
qs.success = res.successful()
qs.save()
if res.successful():
print('result:', res.get(), end=' ')
print()
runjobs = me.jobs.filter(finished=False)
if jobresults != lastjobs:
print('Jobs running:', len(jobresults))
lastjobs = jobresults
for jid,res in jobresults:
print(' Job id', jid, 'ready:', res.ready(), end=' ')
if res.ready():
jobresults.remove((jid,res))
print('success:', res.successful())
qj = runjobs.get(job__id=jid)
qj.finished = True
qj.success = res.successful()
qj.save()
try:
job = Job.objects.get(id=jid)
print('Job:', job)
print(' status:', job.status)
print(' error message:', job.error_message)
#logfn = job.get_log_file()
print(' log file tail:')
print(job.get_log_tail(nlines=10))
except:
print('exception getting job')
if res.successful():
print('result:', res.get(),)
print()
if len(jobresults):
print('Still waiting for', len(jobresults), 'Jobs')
if quitnow:
if len(jobresults) == 0:
print('Timed out -- exiting.')
break
if t_now > (maxtime + extratime):
print('Timed out + extra time -- force quit.')
break
print('Timed out -- not launching new jobs, waiting for',
len(jobresults), 'jobs to finish')
time.sleep(refresh_rate)
continue
if (len(newsubs) + len(newuis)) == 0:
time.sleep(refresh_rate)
continue
# FIXME -- order by user, etc
## HACK -- order 'newuis' to do the newest ones first... helpful when there
# is a big backlog.
newuis = newuis.order_by('-submission__submitted_on')
for sub in newsubs:
print('Enqueuing submission:', str(sub))
sub.set_processing_started()
sub.save()
qs = QueuedSubmission(procsub=me, submission=sub)
qs.save()
if dosub_pool:
res = dosub_pool.apply_async(
try_dosub,
(sub, max_sub_retries),
callback=sub_callback
)
subresults.append((sub.id, res))
else:
try_dosub(sub, max_sub_retries)
if dojob_pool:
n_add = dojob_nthreads - len(jobresults)
if n_add <= 0:
# Already full!
continue
# Queue some new ones -- randomly select from waiting users
newuis = list(newuis)
start_newuis = []
import numpy as np
from collections import Counter
print('Need to start', n_add, 'jobs;', len(newuis), 'eligible uis')
while n_add > 0:
cusers = Counter([u.user for u in newuis])
print('Jobs queued:', len(newuis), 'by', len(cusers), 'users; top:')
for k,user in cusers.most_common(5):
try:
print(' ', k, user, user.get_profile().display_name)
except:
print(' ', k, user)
users = list(cusers.keys())
print(len(users), 'eligible users')
if len(users) == 0:
break
iu = np.random.randint(len(users))
user = users[iu]
print('Selected user', user)
for ui in newuis:
if ui.user == user:
print('Selected ui', ui)
newuis.remove(ui)
start_newuis.append(ui)
n_add -= 1
break
newuis = start_newuis
for userimage in newuis:
job = Job(user_image=userimage)
job.set_queued_time()
job.save()
userimage.has_job = True
userimage.save()
qj = QueuedJob(procsub=me, job=job)
qj.save()
if dojob_pool:
res = dojob_pool.apply_async(try_dojob, (job, userimage, solve_command, solve_locally),
callback=job_callback)
jobresults.append((job.id, res))
else:
try_dojob(job, userimage, solve_command=solve_command, solve_locally=solve_locally)
if __name__ == '__main__':
import optparse
parser = optparse.OptionParser()
parser.add_option('--jobthreads', '-j', dest='jobthreads', type='int',
default=3, help='Set the number of threads to process jobs')
parser.add_option('--subthreads', '-s', dest='subthreads', type='int',
default=2, help='Set the number of threads to process submissions')
parser.add_option('--maxsubretries', '-m', dest='maxsubretries', type='int',
default=20, help='Set the maximum number of times to retry processing a submission')
parser.add_option('--refreshrate', '-r', dest='refreshrate', type='float',
default=5, help='Set how often to check for new jobs and submissions (in seconds)')
parser.add_option('--solve-command', default=None,
help='Command to run instead of ssh to actually solve image, eg "testscript-astro"')
parser.add_option('--solve-locally',
help='Command to run astrometry-engine on this machine, not via ssh')
opt,args = parser.parse_args()
main(opt.jobthreads, opt.subthreads, opt.refreshrate, opt.maxsubretries,
opt.solve_command, opt.solve_locally)
|
let clientIP = null; // I don't use it for evil purposes, pinky promise
let prepods = null;
async function getIP()
{
const ip = await fetch("https://api.ipify.org",
{
method: "GET",
headers: { "Accept": "application/text" }
});
if (ip.ok)
{
clientIP = await ip.text();
}
}
async function putRating(prepodName, rating)
{
await fetch("/api/prepods?ip=" + clientIP + "&prepod=" + prepodName + "&rating=" + rating,
{
method: "PUT",
headers: { "Accept": "application/json" }
});
}
function appendPrepod(prepod, listElement)
{
const prepodRow = document.createElement("tr");
listElement.appendChild(prepodRow);
const prepodRowInfo = document.createElement("td");
prepodRowInfo.innerHTML = "<b>" + prepod.name + "</b> – " + prepod.desc;
prepodRow.appendChild(prepodRowInfo);
const prepodRowRating = document.createElement("td");
prepodRow.appendChild(prepodRowRating);
appendRatingStuff(prepod, prepodRowRating);
}
function appendRatingStuff(prepod, ratingDiv)
{
for (const rating of ratings)
{
const thisSelected = prepod.myRating === rating;
const ratingButton = document.createElement("input");
ratingButton.type = "radio";
ratingButton.name = prepod.name + "Rating Group";
ratingButton.id = prepod.name + " Rating " + rating;
ratingButton.value = rating;
if (thisSelected)
{
ratingButton.checked = true;
}
const ratingButtonLabel = document.createElement("label");
ratingButtonLabel.for = prepod.name + " Rating " + rating;
ratingButtonLabel.innerHTML = rating;
const separatorSpan = document.createElement("span");
separatorSpan.innerHTML = " ";
ratingDiv.appendChild(ratingButton);
ratingDiv.appendChild(ratingButtonLabel);
ratingDiv.appendChild(separatorSpan);
ratingButton.onchange = () =>
{
putRating(prepod.name, rating);
}
}
}
async function init()
{
await getIP();
prepods = await getPrepods(clientIP);
document.body.removeChild(document.getElementById("pending"));
displayPrepodsRatingTable();
}
function displayPrepodsRatingTable()
{
const contentDiv = document.getElementById("content");
const table = document.createElement("table");
table.className = "table table-hover";
table.id = "prepodList";
contentDiv.appendChild(table);
const tableHead = document.createElement("thead");
table.appendChild(tableHead);
const tableHeadRow = document.createElement("tr");
tableHead.appendChild(tableHeadRow);
const tableHeaderPrepod = document.createElement("th");
tableHeaderPrepod.scope = "col";
tableHeaderPrepod.innerHTML = "Преподаватель";
const tableHeaderRating = document.createElement("th");
tableHeaderRating.scope = "col";
tableHeaderRating.innerHTML = "Оценка";
tableHeadRow.appendChild(tableHeaderPrepod);
tableHeadRow.appendChild(tableHeaderRating);
const tableBody = document.createElement("tbody");
table.appendChild(tableBody);
prepods.forEach(prepod =>
{
appendPrepod(prepod, tableBody);
});
}
init();
|
// Fill out generic/dispatch methods for NNTP server
//
'use strict';
const _ = require('lodash');
const mongoose = require('mongoose');
const url = require('url');
const render = require('nodeca.core/lib/system/render/common');
const userInfo = require('nodeca.users/lib/user_info');
module.exports = function (N) {
let hostname = url.parse(N.config.bind?.default?.mount ?? 'http://localhost/').hostname;
N.wire.before('init:server.nntp', function init_nntp_methods(nntp) {
nntp._selectGroup = async function (session, name) {
let group = await N.models.nntp.Group.findOne()
.where('name').equals(name)
.lean(true);
if (await this._checkAccess(session, group)) {
session.group = {
_id: group._id, // internal, not used by nntp-server
type: group.type, // internal, not used by nntp-server
min_index: group.min_index,
max_index: group.max_index,
total: group.max_index - group.min_index + 1,
name: group.name,
description: '',
current_article: group.min_index
};
return true;
}
return false;
};
nntp._getGroups = async function (session, time, wildmat) {
let query = N.models.nntp.Group.find().sort('name');
if (time) {
let threshold = new mongoose.Types.ObjectId(Math.max(time.valueOf() / 1000, 0));
query = query.where('_id').gte(threshold);
}
let groups = await query.lean(true);
groups = groups.filter(group => (wildmat ? wildmat.test(group.name) : true));
let have_access = await this._checkAccess(session, groups);
groups = groups.filter((__, idx) => have_access[idx]);
return groups;
};
nntp._getArticle = async function (session, id) {
let m, article, group;
if ((m = id.match(/^<([0-9a-f]{24})@.*>$/))) {
article = await N.models.nntp.Article.findOne()
.where('source').equals(m[1])
.lean(true);
group = await N.models.nntp.Group.findById(article.group)
.lean(true);
} else if ((m = id.match(/^(\d+)$/))) {
group = session.group;
article = await N.models.nntp.Article.findOne()
.where('group').equals(group._id)
.where('index').equals(Number(m[1]))
.lean(true);
}
if (!article) return null;
return typeof this['_fetchArticleData_' + group.type] === 'function' ?
this['_fetchArticleData_' + group.type](group, article) :
null;
};
nntp._getRange = async function (session, from, to) {
let group = session.group;
let articles = await N.models.nntp.Article.find()
.where('group').equals(group._id)
.where('index').gte(from)
.where('index').lte(to)
.lean(true);
return typeof this['_fetchArticleData_' + group.type] === 'function' ?
this['_fetchArticleData_' + group.type](group, articles) :
[];
};
nntp._getNewNews = async function (session, time, wildmat) {
let groups = await N.models.nntp.Group.find().lean(true);
groups = groups.filter(group => (wildmat ? wildmat.test(group.name) : true));
if (!groups.length) return [];
let have_access = await this._checkAccess(session, groups);
groups = groups.filter((__, idx) => have_access[idx]);
if (!groups.length) return [];
let query = N.models.nntp.Article.find()
.where('group').in(groups.map(g => g._id))
.sort('_id');
if (time) {
let threshold = new mongoose.Types.ObjectId(Math.max(time.valueOf() / 1000, 0));
query = query.where('_id').gte(threshold);
}
let articles = await query.lean(true);
return articles;
};
nntp._buildHeaderField = function (session, article, field) {
switch (field) {
case 'from': return article.from;
case 'newsgroups': return article.group.name;
case 'subject': return article.subject;
case 'date': return article.date.toUTCString();
case 'message-id': return `<${article.source}@${hostname}>`;
case 'references': return article.reply_to ? (`<${article.reply_to}@${hostname}>`) : null;
case 'content-type': return 'text/html; charset=utf8';
case 'xref': return `${hostname} ${article.group.name}:${article.index}`;
case 'content-transfer-encoding': return 'base64';
default: return null;
}
};
nntp._buildHead = function (session, article) {
let fields = [
'From', 'Newsgroups', 'Subject', 'Date', 'Message-ID', 'References',
'Content-Type', 'Content-Transfer-Encoding', 'Xref'
];
let result = [];
for (let field of fields) {
let content = nntp._buildHeaderField(session, article, field.toLowerCase());
if (content === null || typeof content === 'undefined') continue;
result.push(field + ': ' + content);
}
return result;
};
nntp._buildBody = function (session, article) {
let locale = session.user_info.locale ?? N.config.locales[0];
let helpers = {};
helpers.t = (phrase, params) => N.i18n.t(locale, phrase, params);
helpers.t.exists = phrase => N.i18n.hasPhrase(locale, phrase);
helpers.link_to = (name, params) => N.router.linkTo(name, params) || '#';
helpers.asset_url = path => N.assets.asset_url(path);
helpers.asset_body = path => N.assets.asset_body(path);
let html = render(N, 'nntp.templates.' + article.type, article, helpers);
return Buffer.from(html).toString('base64').match(/.{1,76}/g);
};
nntp._authenticate = async function (session) {
let authinfo_user = session.authinfo_user;
let authinfo_pass = session.authinfo_pass;
session.authinfo_user = null;
session.authinfo_pass = null;
let user = await N.models.users.User.findOne()
.where('nick').equals(authinfo_user)
.lean(true);
if (!user) return false;
let authProvider = await N.models.users.AuthProvider.findOne()
.where('user').equals(user._id)
.where('type').equals('plain')
.where('exists').equals(true)
.lean(false);
if (!authProvider) return false;
if (!await authProvider.checkPass(authinfo_pass)) return false;
// TODO: log this login attempt somehow?
//
//await N.models.users.AuthProvider.updateOne(
// { _id: authProvider._id },
// { $set: { last_ts: Date.now(), last_ip: ??? } }
//);
session.user_info = await userInfo(N, user._id);
return true;
};
nntp._onError = function (err) {
N.logger.error('NNTP error (%s): %s', err.nntp_command, err.stack || err);
};
// Custom method used to retrieve user_info object for the current user
//
nntp._getUserInfo = async function (session) {
// lazy loading for guest sessions
session.user_info = session.user_info || await userInfo(N, null);
return session.user_info;
};
// Custom method used to check permissions for NNTP groups,
// returns a subset of the groups that allow access.
//
// Requires nntp._filterAccess_X methods to be present,
// where X is a group type (e.g. nntp._filterAccess_forum).
//
nntp._checkAccess = async function (session, groups) {
let single_group_call = false;
if (!Array.isArray(groups)) {
groups = [ groups ];
single_group_call = true;
}
let types = _.uniq(groups.map(g => g.type)).filter(type => typeof this['_filterAccess_' + type] === 'function');
let result = new Array(groups.length).fill(null);
await Promise.all(types.map(type =>
this['_filterAccess_' + type](session, groups)
.then(access_entries => access_entries.forEach((res, idx) => {
if (result[idx] === null || Boolean(result[idx]) === true) result[idx] = result[idx] || res;
}))
));
return single_group_call ? result[0] : result;
};
});
};
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.tag = void 0;
var tag = {
"viewBox": "0 0 24 24",
"children": [{
"name": "path",
"attribs": {
"d": "M9 4c1.279 0 2.559.488 3.535 1.465l3.465 3.535 5 5-7 7-5.498-5.498c-.037.033-3.037-2.967-3.037-2.967-1.953-1.953-1.953-5.119 0-7.07.976-.977 2.256-1.465 3.535-1.465m0-2c-1.87 0-3.628.729-4.949 2.051-1.322 1.32-2.051 3.078-2.051 4.948s.729 3.628 2.051 4.95l3 3c.107.107.227.201.35.279l5.187 5.186c.391.391.9.586 1.413.586s1.022-.195 1.414-.586l7-7c.78-.781.78-2.047 0-2.828l-5-5-3.45-3.521c-1.337-1.336-3.095-2.065-4.965-2.065zM9 7.498c.829 0 1.5.672 1.5 1.502s-.671 1.498-1.5 1.498-1.5-.668-1.5-1.498.671-1.502 1.5-1.502m0-1c-1.379 0-2.5 1.122-2.5 2.502 0 1.377 1.121 2.498 2.5 2.498s2.5-1.121 2.5-2.498c0-1.38-1.121-2.502-2.5-2.502z"
},
"children": []
}]
};
exports.tag = tag;
|
import Endpoints, { globalCookiePolicy } from '../../../Endpoints';
import requestAction from '../../Common/Actions/requestAction';
import {
REQUEST_SUCCESS,
COUNT_FETCHED,
REQUEST_ERROR,
} from '../../Common/Actions/Actions';
import beginFilter from '../../Common/SearchComponentGen/GenerateFilter';
/* Fetch Cancel Products */
const getBarCount = ( filterObj, isSearched ) => {
return (dispatch, getState) => {
// dispatch({ type: MAKE_REQUEST, f});
//
/* const payload = {'where': {'id': f}, 'columns': ['*']};*/
const payload = {
'columns': ['*']
};
if ( isSearched ) {
payload.where = { ...payload.where, ...filterObj };
}
const url = Endpoints.db + '/table/' + 'bars' + '/count';
const genOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'x-hasura-role': getState().loginState.highestRole},
credentials: globalCookiePolicy
};
const options = {
...genOptions,
body: JSON.stringify(payload)
};
return dispatch(requestAction(url, options, COUNT_FETCHED, REQUEST_ERROR));
};
};
const getBarData = ( page, filterObj, isSearched) => {
return (dispatch, getState) => {
// dispatch({ type: MAKE_REQUEST, f});
//
/* const payload = {'where': {'id': f}, 'columns': ['*']};*/
let offset = 0;
let limit = 0;
// const count = currentProps.count;
// limit = (page * 10) > count ? count : ((page) * 10);
// limit = ((page) * 10);
limit = 10;
offset = (page - 1) * 10;
const payload = {
'columns': [ '*', {
'name': 'addresses',
'columns': ['*'],
'order_by': '-created_at',
'limit': 1
}],
limit: limit,
offset: offset
};
if ( isSearched ) {
payload.where = { ...payload.where, ...filterObj };
}
const url = Endpoints.db + '/table/' + 'bars' + '/select';
const genOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'x-hasura-role': getState().loginState.highestRole},
credentials: globalCookiePolicy
};
const options = {
...genOptions,
body: JSON.stringify(payload),
};
return dispatch(requestAction(url, options, REQUEST_SUCCESS, REQUEST_ERROR));
};
};
const toggleBarStatus = ( id, isActive, currPage) => {
return ( dispatch, getState ) => {
const genOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'x-hasura-role': getState().loginState.highestRole},
credentials: globalCookiePolicy
};
const invUrl = Endpoints.db + '/table/bars/update';
const insertObj = {};
insertObj.values = { 'bar_status': ((isActive === 'true') ? 'false' : 'true')};
insertObj.returning = ['id'];
insertObj.where = {
'id': parseInt(id, 10)
};
const options = {
...genOptions,
body: JSON.stringify(insertObj)
};
return dispatch( requestAction( invUrl, options ) )
.then( ( resp ) => {
console.log(resp);
const filterData = getState().gen_filter_data;
const filterObj = { ...beginFilter(getState) };
dispatch(getBarData(currPage, filterObj, filterData.isSearched));
alert('Updated');
}).catch( (err) => {
console.log(err);
alert('Failed');
});
};
};
const getAllBarData = (page ) => {
const gotPage = page;
/* Dispatching first one */
return (dispatch, getState ) => {
const filterData = getState().gen_filter_data;
const filterObj = { ...beginFilter(getState) };
return Promise.all([
dispatch(getBarCount( filterObj, filterData.isSearched )),
dispatch(getBarData(gotPage, filterObj, filterData.isSearched))
]);
};
};
export {
getAllBarData,
toggleBarStatus
};
|
import React from 'react'
import { graphql } from 'gatsby'
import Layout from '../components/Layout'
import Hero from '../components/Hero'
import Container from '../components/Container'
import PageBody from '../components/PageBody'
import TagList from '../components/TagList'
import PostLinks from '../components/PostLinks'
import PostDetails from '../components/PostDetails'
import SEO from '../components/SEO'
const PostTemplate = ({ data, pageContext }) => {
const { title, metaDescription, heroImage, body, publishDate, tags } =
data.contentfulPost
const previous = pageContext.prev
const next = pageContext.next
const { basePath } = pageContext
let ogImage
try {
ogImage = heroImage.gatsbyImageData.images.fallback.src
} catch (error) {
ogImage = null
}
return (
<Layout>
<SEO
title={title}
description={
metaDescription
? metaDescription.internal.content
: body.childMarkdownRemark.excerpt
}
image={ogImage}
/>
<Hero title={title} image={heroImage} height={'50vh'} />
<Container>
{tags && <TagList tags={tags} basePath={basePath} />}
<PostDetails
date={publishDate}
timeToRead={body.childMarkdownRemark.timeToRead}
/>
<PageBody body={body} />
</Container>
<PostLinks previous={previous} next={next} basePath={basePath} />
</Layout>
)
}
export const query = graphql`
query ($slug: String!) {
contentfulPost(slug: { eq: $slug }) {
title
slug
metaDescription {
internal {
content
}
}
publishDate(formatString: "MMMM DD, YYYY")
publishDateISO: publishDate(formatString: "YYYY-MM-DD")
tags {
title
id
slug
}
heroImage {
title
gatsbyImageData(width: 1800, placeholder: BLURRED)
}
body {
childMarkdownRemark {
timeToRead
html
excerpt(pruneLength: 320)
}
}
}
}
`
export default PostTemplate
|
//给定一个包含n个整数的数组,找出其中所有的三元数组,三元数组需要
//使其中的三个元素符合a+b+c=0的条件
/**
* @param {number[]} nums
* @return {number[][]}
*/
var threeSum = function (nums) {
var ret = [];
if (nums === null || nums.length < 3) return ret;
function compare(value1, value2) {
if (value1 > value2) {
return 1;
} else if (value1 < value2) {
return -1;
} else {
return 0;
}
}
//下面的find函数需要数组是排好序的
nums.sort(compare);
var len = nums.length;
for (var i = 0; i < len - 2; i++) {
if (i > 0 && nums[i] === nums[i - 1]) continue;
//基本的思路是固定一个数字,将另外两个数字设为头尾两个指针
//依靠判断来移动前后的指针
find(nums, i + 1, len - 1, nums[i], ret);
}
return ret;
};
function find(num, begin, end, target, ret) {
var l = begin, r = end;
while (l < r) {
if (num[l] + num[r] + target === 0) {
var ans = new Array(target, num[l], num[r]);
ret.push(ans);
while (l < r && num[l] == num[l + 1]) l++;
while (l < r && num[r] == num[r - 1]) r--;
l++;
r--;
} else if (num[l] + num[r] + target < 0) {
l++;
} else {
r--;
}
}
}
|
// 配置文件
module.exports = {
// 每日说配置项(必填项)
NAME: 'A兔子', //女朋友备注姓名
NICKNAME: '嗯哼', //女朋友昵称
MEMORIAL_DAY: '2015/04/18', //你和女朋友的纪念日
CITY: '上海', //女朋友所在城市(城市名称,不要带“市”)
SENDDATE: '0 09 19 * * *', //定时发送时间 每天8点06分0秒发送,规则见 /schedule/index.js
//高级功能配置项(非必填项)
AUTOREPLY: false, //自动聊天功能 默认关闭 开启设置为: true
DEFAULTBOT: '0', //设置默认聊天机器人 0 天行机器人 1 图灵机器人 2 天行对接的图灵机器人,需要到天行机器人官网充值(50元/年,每天500次)
AUTOREPLYPERSON: ['好友1备注','好友2备注'], //指定多个好友开启机器人聊天功能 指定好友的备注,最好不要带有特殊字符
TULINGKEY: '图灵机器人apikey',//图灵机器人apikey,需要自己到图灵机器人官网申请,并且需要认证
TXAPIKEY: '天行apikey', //如设定机器人为 2 则此处须填写个人申请的天行apikey 申请地址https://www.tianapi.com/signup.html?source=474284281
}
|
import { combineReducers } from 'redux';
import about from './about/reducer';
export default combineReducers({
about,
});
|
_base_ = '../faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py'
model = dict(
neck=dict(
type='PAFPN',
in_channels=[256, 512, 1024, 2048],
out_channels=256,
num_outs=5)
)
|
#!/usr/bin/env python
import os
from setuptools import setup, find_packages
import registrasion
def read_file(filename):
"""Read a file into a string."""
path = os.path.abspath(os.path.dirname(__file__))
filepath = os.path.join(path, filename)
try:
return open(filepath).read()
except IOError:
return ''
setup(
name="registrasion",
author="Christopher Neugebauer",
author_email="_@chrisjrn.com",
version=registrasion.__version__,
description="A registration app for the Symposion conference management "
"system.",
url="http://github.com/chrisjrn/registrasion/",
packages=find_packages(),
include_package_data=True,
classifiers=(
"Development Status :: 3 - Alpha",
"Programming Language :: Python",
"Framework :: Django",
"Intended Audience :: Developers",
"Natural Language :: English",
"License :: OSI Approved :: Apache Software License",
),
install_requires=read_file("requirements/base.txt").splitlines(),
dependency_links=read_file("requirements/dependencies.txt").splitlines(),
)
|
export const provide = (lang) => {
switch (lang) {
case 'en':
return {
//the first part of the snake_case key should be the name of the related module
map_rotationButton_title: 'Reset rotation to north'
};
case 'de':
return {
//the first part of the snake_case key should be the name of the related module
map_rotationButton_title: 'Karte wieder nach Norden ausrichten'
};
default:
return {};
}
};
|
// 表单校验规则由 schema2code 生成,不建议直接修改校验规则,而建议通过 schema2code 生成, 详情: https://uniapp.dcloud.net.cn/uniCloud/schema
const validator = {
"content": {
"rules": [
{
"required": true
},
{
"format": "string"
}
],
"label": "留言内容/回复内容"
},
"imgs": {
"rules": [
{
"format": "array"
},
{
"arrayType": "file"
},
{
"maxLength": 6
}
],
"label": "图片列表"
},
"is_reply": {
"rules": [
{
"format": "bool"
}
],
"label": "是否是回复类型"
},
"feedback_id": {
"rules": [
{
"format": "string"
}
],
"label": "被回复留言ID"
},
"contact": {
"rules": [
{
"format": "string"
}
],
"label": "联系人"
},
"mobile": {
"rules": [
{
"format": "string"
},
{
"pattern": "^\\+?[0-9-]{3,20}$"
}
],
"label": "联系电话"
}
}
const enumConverter = {}
export { validator, enumConverter }
|
/**
* @module rollup.es5
* @license MIT
* @author nuintun
*/
import configure from './configure';
export default configure();
|
import { createIcon } from '../createIcon';
export const CriticalRoleIconConfig = {
name: 'CriticalRoleIcon',
height: 512,
width: 448,
svgPath: 'M225.82 0c.26.15 216.57 124.51 217.12 124.72 3 1.18 3.7 3.46 3.7 6.56q-.11 125.17 0 250.36a5.88 5.88 0 0 1-3.38 5.78c-21.37 12-207.86 118.29-218.93 124.58h-3C142 466.34 3.08 386.56 2.93 386.48a3.29 3.29 0 0 1-1.88-3.24c0-.87 0-225.94-.05-253.1a5 5 0 0 1 2.93-4.93C27.19 112.11 213.2 6 224.07 0zM215.4 20.42l-.22-.16Q118.06 75.55 21 130.87c0 .12.08.23.13.35l30.86 11.64c-7.71 6-8.32 6-10.65 5.13-.1 0-24.17-9.28-26.8-10v230.43c.88-1.41 64.07-110.91 64.13-111 1.62-2.82 3-1.92 9.12-1.52 1.4.09 1.48.22.78 1.42-41.19 71.33-36.4 63-67.48 116.94-.81 1.4-.61 1.13 1.25 1.13h186.5c1.44 0 1.69-.23 1.7-1.64v-8.88c0-1.34 2.36-.81-18.37-1-7.46-.07-14.14-3.22-21.38-12.7-7.38-9.66-14.62-19.43-21.85-29.21-2.28-3.08-3.45-2.38-16.76-2.38-1.75 0-1.78 0-1.76 1.82.29 26.21.15 25.27 1 32.66.52 4.37 2.16 4.2 9.69 4.81 3.14.26 3.88 4.08.52 4.92-1.57.39-31.6.51-33.67-.1a2.42 2.42 0 0 1 .3-4.73c3.29-.76 6.16.81 6.66-4.44 1.3-13.66 1.17-9 1.1-79.42 0-10.82-.35-12.58-5.36-13.55-1.22-.24-3.54-.16-4.69-.55-2.88-1-2-4.84 1.77-4.85 33.67 0 46.08-1.07 56.06 4.86 7.74 4.61 12 11.48 12.51 20.4.88 14.59-6.51 22.35-15 32.59a1.46 1.46 0 0 0 0 2.22c2.6 3.25 5 6.63 7.71 9.83 27.56 33.23 24.11 30.54 41.28 33.06.89.13 1-.42 1-1.15v-11c0-1 .32-1.43 1.41-1.26a72.37 72.37 0 0 0 23.58-.3c1.08-.15 1.5.2 1.48 1.33 0 .11.88 26.69.87 26.8-.05 1.52.67 1.62 1.89 1.62h186.71Q386.51 304.6 346 234.33c2.26-.66-.4 0 6.69-1.39 2-.39 2.05-.41 3.11 1.44 7.31 12.64 77.31 134 77.37 134.06V138c-1.72.5-103.3 38.72-105.76 39.68-1.08.42-1.55.2-1.91-.88-.63-1.9-1.34-3.76-2.09-5.62-.32-.79-.09-1.13.65-1.39.1 0 95.53-35.85 103-38.77-65.42-37.57-130.56-75-196-112.6l86.82 150.39-.28.33c-9.57-.9-10.46-1.6-11.8-3.94-1-1.69-73.5-127.71-82-142.16-9.1 14.67-83.56 146.21-85.37 146.32-2.93.17-5.88.08-9.25.08q43.25-74.74 86.18-149zm51.93 129.92a37.68 37.68 0 0 0 5.54-.85c1.69-.3 2.53.2 2.6 1.92 0 .11.07 19.06-.86 20.45s-1.88 1.22-2.6-.19c-5-9.69 6.22-9.66-39.12-12-.7 0-1 .23-1 .93 0 .13 3.72 122 3.73 122.11 0 .89.52 1.2 1.21 1.51a83.92 83.92 0 0 1 8.7 4.05c7.31 4.33 11.38 10.84 12.41 19.31 1.44 11.8-2.77 35.77-32.21 37.14-2.75.13-28.26 1.08-34.14-23.25-4.66-19.26 8.26-32.7 19.89-36.4a2.45 2.45 0 0 0 2-2.66c.1-5.63 3-107.1 3.71-121.35.05-1.08-.62-1.16-1.35-1.15-32.35.52-36.75-.34-40.22 8.52-2.42 6.18-4.14 1.32-3.95.23q1.59-9 3.31-18c.4-2.11 1.43-2.61 3.43-1.86 5.59 2.11 6.72 1.7 37.25 1.92 1.73 0 1.78-.08 1.82-1.85.68-27.49.58-22.59 1-29.55a2.69 2.69 0 0 0-1.63-2.8c-5.6-2.91-8.75-7.55-8.9-13.87-.35-14.81 17.72-21.67 27.38-11.51 6.84 7.19 5.8 18.91-2.45 24.15a4.35 4.35 0 0 0-2.22 4.34c0 .59-.11-4.31 1 30.05 0 .9.43 1.12 1.24 1.11.1 0 23-.09 34.47-.37zM68.27 141.7c19.84-4.51 32.68-.56 52.49 1.69 2.76.31 3.74 1.22 3.62 4-.21 5-1.16 22.33-1.24 23.15a2.65 2.65 0 0 1-1.63 2.34c-4.06 1.7-3.61-4.45-4-7.29-3.13-22.43-73.87-32.7-74.63 25.4-.31 23.92 17 53.63 54.08 50.88 27.24-2 19-20.19 24.84-20.47a2.72 2.72 0 0 1 3 3.36c-1.83 10.85-3.42 18.95-3.45 19.15-1.54 9.17-86.7 22.09-93.35-42.06-2.71-25.85 10.44-53.37 40.27-60.15zm80 87.67h-19.49a2.57 2.57 0 0 1-2.66-1.79c2.38-3.75 5.89.92 5.86-6.14-.08-25.75.21-38 .23-40.1 0-3.42-.53-4.65-3.32-4.94-7-.72-3.11-3.37-1.11-3.38 11.84-.1 22.62-.18 30.05.72 8.77 1.07 16.71 12.63 7.93 22.62-2 2.25-4 4.42-6.14 6.73.95 1.15 6.9 8.82 17.28 19.68 2.66 2.78 6.15 3.51 9.88 3.13a2.21 2.21 0 0 0 2.23-2.12c.3-3.42.26 4.73.45-40.58 0-5.65-.34-6.58-3.23-6.83-3.95-.35-4-2.26-.69-3.37l19.09-.09c.32 0 4.49.53 1 3.38 0 .05-.16 0-.24 0-3.61.26-3.94 1-4 4.62-.27 43.93.07 40.23.41 42.82.11.84.27 2.23 5.1 2.14 2.49 0 3.86 3.37 0 3.4-10.37.08-20.74 0-31.11.07-10.67 0-13.47-6.2-24.21-20.82-1.6-2.18-8.31-2.36-8.2-.37.88 16.47 0 17.78 4 17.67 4.75-.1 4.73 3.57.83 3.55zm275-10.15c-1.21 7.13.17 10.38-5.3 10.34-61.55-.42-47.82-.22-50.72-.31a18.4 18.4 0 0 1-3.63-.73c-2.53-.6 1.48-1.23-.38-5.6-1.43-3.37-2.78-6.78-4.11-10.19a1.94 1.94 0 0 0-2-1.44 138 138 0 0 0-14.58.07 2.23 2.23 0 0 0-1.62 1.06c-1.58 3.62-3.07 7.29-4.51 11-1.27 3.23 7.86 1.32 12.19 2.16 3 .57 4.53 3.72.66 3.73H322.9c-2.92 0-3.09-3.15-.74-3.21a6.3 6.3 0 0 0 5.92-3.47c1.5-3 2.8-6 4.11-9.09 18.18-42.14 17.06-40.17 18.42-41.61a1.83 1.83 0 0 1 3 0c2.93 3.34 18.4 44.71 23.62 51.92 2 2.7 5.74 2 6.36 2 3.61.13 4-1.11 4.13-4.29.09-1.87.08 1.17.07-41.24 0-4.46-2.36-3.74-5.55-4.27-.26 0-2.56-.63-.08-3.06.21-.2-.89-.24 21.7-.15 2.32 0 5.32 2.75-1.21 3.45a2.56 2.56 0 0 0-2.66 2.83c-.07 1.63-.19 38.89.29 41.21a3.06 3.06 0 0 0 3.23 2.43c13.25.43 14.92.44 16-3.41 1.67-5.78 4.13-2.52 3.73-.19zm-104.72 64.37c-4.24 0-4.42-3.39-.61-3.41 35.91-.16 28.11.38 37.19-.65 1.68-.19 2.38.24 2.25 1.89-.26 3.39-.64 6.78-1 10.16-.25 2.16-3.2 2.61-3.4-.15-.38-5.31-2.15-4.45-15.63-5.08-1.58-.07-1.64 0-1.64 1.52V304c0 1.65 0 1.6 1.62 1.47 3.12-.25 10.31.34 15.69-1.52.47-.16 3.3-1.79 3.07 1.76 0 .21-.76 10.35-1.18 11.39-.53 1.29-1.88 1.51-2.58.32-1.17-2 0-5.08-3.71-5.3-15.42-.9-12.91-2.55-12.91 6 0 12.25-.76 16.11 3.89 16.24 16.64.48 14.4 0 16.43-5.71.84-2.37 3.5-1.77 3.18.58-.44 3.21-.85 6.43-1.23 9.64 0 .36-.16 2.4-4.66 2.39-37.16-.08-34.54-.19-35.21-.31-2.72-.51-2.2-3 .22-3.45 1.1-.19 4 .54 4.16-2.56 2.44-56.22-.07-51.34-3.91-51.33zm-.41-109.52c2.46.61 3.13 1.76 2.95 4.65-.33 5.3-.34 9-.55 9.69-.66 2.23-3.15 2.12-3.34-.27-.38-4.81-3.05-7.82-7.57-9.15-26.28-7.73-32.81 15.46-27.17 30.22 5.88 15.41 22 15.92 28.86 13.78 5.92-1.85 5.88-6.5 6.91-7.58 1.23-1.3 2.25-1.84 3.12 1.1 0 .1.57 11.89-6 12.75-1.6.21-19.38 3.69-32.68-3.39-21-11.19-16.74-35.47-6.88-45.33 14-14.06 39.91-7.06 42.32-6.47zM289.8 280.14c3.28 0 3.66 3 .16 3.43-2.61.32-5-.42-5 5.46 0 2-.19 29.05.4 41.45.11 2.29 1.15 3.52 3.44 3.65 22 1.21 14.95-1.65 18.79-6.34 1.83-2.24 2.76.84 2.76 1.08.35 13.62-4 12.39-5.19 12.4l-38.16-.19c-1.93-.23-2.06-3-.42-3.38 2-.48 4.94.4 5.13-2.8 1-15.87.57-44.65.34-47.81-.27-3.77-2.8-3.27-5.68-3.71-2.47-.38-2-3.22.34-3.22 1.45-.02 17.97-.03 23.09-.02zm-31.63-57.79c.07 4.08 2.86 3.46 6 3.58 2.61.1 2.53 3.41-.07 3.43-6.48 0-13.7 0-21.61-.06-3.84 0-3.38-3.35 0-3.37 4.49 0 3.24 1.61 3.41-45.54 0-5.08-3.27-3.54-4.72-4.23-2.58-1.23-1.36-3.09.41-3.15 1.29 0 20.19-.41 21.17.21s1.87 1.65-.42 2.86c-1 .52-3.86-.28-4.15 2.47 0 .21-.82 1.63-.07 43.8zm-36.91 274.27a2.93 2.93 0 0 0 3.26 0c17-9.79 182-103.57 197.42-112.51-.14-.43 11.26-.18-181.52-.27-1.22 0-1.57.37-1.53 1.56 0 .1 1.25 44.51 1.22 50.38a28.33 28.33 0 0 1-1.36 7.71c-.55 1.83.38-.5-13.5 32.23-.73 1.72-1 2.21-2-.08-4.19-10.34-8.28-20.72-12.57-31a23.6 23.6 0 0 1-2-10.79c.16-2.46.8-16.12 1.51-48 0-1.95 0-2-2-2h-183c2.58 1.63 178.32 102.57 196 112.76zm-90.9-188.75c0 2.4.36 2.79 2.76 3 11.54 1.17 21 3.74 25.64-7.32 6-14.46 2.66-34.41-12.48-38.84-2-.59-16-2.76-15.94 1.51.05 8.04.01 11.61.02 41.65zm105.75-15.05c0 2.13 1.07 38.68 1.09 39.13.34 9.94-25.58 5.77-25.23-2.59.08-2 1.37-37.42 1.1-39.43-14.1 7.44-14.42 40.21 6.44 48.8a17.9 17.9 0 0 0 22.39-7.07c4.91-7.76 6.84-29.47-5.43-39a2.53 2.53 0 0 1-.36.12zm-12.28-198c-9.83 0-9.73 14.75-.07 14.87s10.1-14.88.07-14.91zm-80.15 103.83c0 1.8.41 2.4 2.17 2.58 13.62 1.39 12.51-11 12.16-13.36-1.69-11.22-14.38-10.2-14.35-7.81.05 4.5-.03 13.68.02 18.59zm212.32 6.4l-6.1-15.84c-2.16 5.48-4.16 10.57-6.23 15.84z',
yOffset: 0,
xOffset: 0,
transform: ''
};
export const CriticalRoleIcon = createIcon(CriticalRoleIconConfig);
export default CriticalRoleIcon;
|
/**
* Copyright 2015 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @const {!JSONType}
*/
export const NETWORKS = /** @type {!JSONType} */ ({
cloudflare: {
base: 'https://firebolt.cloudflaredemo.com',
},
adzerk: {
base: 'https://engine.betazerk.com',
},
dianomi: {
base: 'https://www.dianomi.com',
src: 'https://www.dianomi.com/smartads.pl?format=a4a',
},
});
|
import React, { useState } from "react"
import Head from "../components/head"
import Layout from "../components/layout/layout"
import TimelineEvent from "../components/timelineEvent/timelineEvent"
import timelineStyles from "../styles/timeline.module.css"
import timelineData from "../data.json"
import birth from "../images/timeline/birth.jpg"
import walking from "../images/timeline/walking.jpg"
import withCalista from "../images/timeline/withCalista.jpg"
import wedding from "../images/timeline/wedding.jpg"
import withRhi from "../images/timeline/withRhi.jpg"
import withKekoa from "../images/timeline/withKekoa.jpg"
import elementaryGrad from "../images/timeline/elementaryGrad.jpg"
import flying from "../images/timeline/flying.jpg"
import band from "../images/timeline/band.jpg"
import drumline from "../images/timeline/drumline.jpg"
import military from "../images/timeline/military.jpg"
import matthewcopy from "../images/timeline/matthewcopy.jpg"
// cool timeline inspired by https://codepen.io/Fischaela/pen/sJdqg
const Timeline = () => {
let images = [
"",
birth,
walking,
withCalista,
wedding,
withRhi,
withKekoa,
elementaryGrad,
flying,
band,
drumline,
military,
matthewcopy,
]
return (
<Layout>
<Head title="The Journey" />
<section className={timelineStyles.contentWrapper}>
<h1>This is my life</h1>
<ul className={timelineStyles.timelineList}>
{timelineData.map(value => {
images = images.slice(1)
return (
<TimelineEvent
key={value.title}
date={value.date}
title={value.title}
description={value.description}
imageUrl={images[0]}
imageAlt={value.imageAlt}
/>
)
})}
</ul>
</section>
</Layout>
)
}
export default Timeline
|
const RoleCard = require('../../rolecard.js');
class KeeperOfEarth extends RoleCard {
setupCardAbilities(ability) {
this.reaction({
title: 'Gain 1 fate',
when: {
afterConflict: (event, context) => event.conflict.elements.some(element => this.hasTrait(element)) &&
event.conflict.winner === context.player &&
event.conflict.defendingPlayer === context.player
},
gameAction: ability.actions.gainFate()
});
}
}
KeeperOfEarth.id = 'keeper-of-earth';
module.exports = KeeperOfEarth;
|
import React from "react";
export default ({ text }) => (
<header className="todo-app__header">
<h1 className="todo-app__title">{text}</h1>
</header>
)
|
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See http://js.arcgis.com/3.24/esri/copyright.txt for details.
//>>built
define("esri/tasks/GeometryService","dojo/_base/declare dojo/_base/lang dojo/_base/array dojo/_base/json dojo/_base/Deferred dojo/has ../kernel ../request ../deferredUtils ./Task ../geometry/Extent ../geometry/Polyline ../geometry/Polygon ../geometry/Multipoint ../geometry/jsonUtils".split(" "),function(v,l,t,k,n,z,A,p,q,B,x,y,w,C,r){v=v(B,{declaredClass:"esri.tasks.GeometryService",_eventMap:{"areas-and-lengths-complete":["result"],"auto-complete-complete":["geometries"],"buffer-complete":["geometries"],
"convex-hull-complete":["geometry"],"cut-complete":["result"],"densify-complete":["geometries"],"difference-complete":["geometries"],"distance-complete":["distance"],"generalize-complete":["geometries"],"intersect-complete":["geometries"],"label-points-complete":["geometries"],"lengths-complete":["result"],"offset-complete":["geometries"],"project-complete":["geometries"],"relation-complete":["relations"],"reshape-complete":["geometry"],"simplify-complete":["geometries"],"trim-extend-complete":["geometries"],
"union-complete":["geometry"]},constructor:function(a){a=l.hitch;this._projectHandler=a(this,this._projectHandler);this._simplifyHandler=a(this,this._simplifyHandler);this._bufferHandler=a(this,this._bufferHandler);this._areasAndLengthsHandler=a(this,this._areasAndLengthsHandler);this._lengthsHandler=a(this,this._lengthsHandler);this._labelPointsHandler=a(this,this._labelPointsHandler);this._relationHandler=a(this,this._relationHandler);this._convexHullHandler=a(this,this._convexHullHandler);this._unionHandler=
a(this,this._unionHandler);this._autoCompleteHandler=a(this,this._autoCompleteHandler);this._reshapeHandler=a(this,this._reshapeHandler);this._cutHandler=a(this,this._cutHandler);this._intersectHandler=a(this,this._intersectHandler);this._differenceHandler=a(this,this._differenceHandler);this._trimExtendHandler=a(this,this._trimExtendHandler);this._densifyHandler=a(this,this._densifyHandler);this._generalizeHandler=a(this,this._densifyHandler);this._offsetHandler=a(this,this._offsetHandler);this._distanceHandler=
a(this,this._distanceHandler);this._toGeoCoordinateHandler=a(this,this._toGeoCoordinateHandler);this._fromGeoCoordinateHandler=a(this,this._fromGeoCoordinateHandler);this.registerConnectEvents()},_encodeGeometries:function(a){var h=[],e,b=a.length;for(e=0;e<b;e++)h.push(a[e].toJson());return{geometryType:r.getJsonType(a[0]),geometries:h}},_decodeGeometries:function(a,h,e){var b=r.getGeometryType(h);a=a.geometries;var f=[],c={spatialReference:e.toJson()},g=l.mixin;t.forEach(a,function(a,e){f[e]=new b(g(a,
c))});return f},_toProjectGeometry:function(a){var h=a.spatialReference.toJson();return a instanceof x?new w({rings:[[[a.xmin,a.ymin],[a.xmin,a.ymax],[a.xmax,a.ymax],[a.xmax,a.ymin],[a.xmin,a.ymin]]],spatialReference:h}):new y({paths:[[].concat(a.points)],spatialReference:h})},_fromProjectedGeometry:function(a,h,e){return"esriGeometryEnvelope"===h?(a=a.rings[0],new x(a[0][0],a[0][1],a[2][0],a[2][1],e)):new C({points:a.paths[0],spatialReference:e.toJson()})},project:function(a,h,e,b){var f=l.mixin({},
this._url.query,{f:"json"}),c;a.geometries?(b=e,e=h,h=a.outSR,c=a.geometries[0],f=l.mixin(f,a.toJson())):(c=a[0],f=l.mixin(f,{outSR:h.wkid||k.toJson(h.toJson()),inSR:c.spatialReference.wkid||k.toJson(c.spatialReference.toJson()),geometries:k.toJson(this._encodeGeometries(a))}));var g=r.getJsonType(c),d=this._projectHandler,m=this._errorHandler,u=new n(q._dfdCanceller);u._pendingDfd=p({url:this._url.path+"/project",content:f,callbackParamName:"callback",load:function(a,c){d(a,c,g,h,e,b,u)},error:function(a){m(a,
b,u)}});return u},_projectHandler:function(a,h,e,b,f,c,g){try{var d=this._decodeGeometries(a,e,b);this._successHandler([d],"onProjectComplete",f,g)}catch(m){this._errorHandler(m,c,g)}},onProjectComplete:function(){},simplify:function(a,h,e){var b=a[0].spatialReference,f=l.mixin({},this._url.query,{f:"json",sr:b.wkid?b.wkid:k.toJson(b.toJson()),geometries:k.toJson(this._encodeGeometries(a))}),c=r.getJsonType(a[0]),g=this._simplifyHandler,d=this._errorHandler,m=new n(q._dfdCanceller);m._pendingDfd=
p({url:this._url.path+"/simplify",content:f,callbackParamName:"callback",load:function(a,d){g(a,d,c,b,h,e,m)},error:function(a){d(a,e,m)}});return m},_simplifyHandler:function(a,h,e,b,f,c,g){try{var d=this._decodeGeometries(a,e,b);this._successHandler([d],"onSimplifyComplete",f,g)}catch(m){this._errorHandler(m,c,g)}},onSimplifyComplete:function(){},convexHull:function(a,h,e){var b=a[0].spatialReference;a=l.mixin({},this._url.query,{f:"json",sr:k.toJson(b.toJson()),geometries:k.toJson(this._encodeGeometries(a))});
var f=this._convexHullHandler,c=this._errorHandler,g=new n(q._dfdCanceller);g._pendingDfd=p({url:this._url.path+"/convexHull",content:a,callbackParamName:"callback",load:function(a,c){f(a,c,b,h,e,g)},error:function(a){c(a,e,g)}});return g},_convexHullHandler:function(a,h,e,b,f,c){try{var g=r.fromJson(a.geometry).setSpatialReference(e);this._successHandler([g],"onConvexHullComplete",b,c)}catch(d){this._errorHandler(d,f,c)}},onConvexHullComplete:function(){},union:function(a,h,e){var b=a[0].spatialReference;
a=l.mixin({},this._url.query,{f:"json",sr:k.toJson(b.toJson()),geometries:k.toJson(this._encodeGeometries(a))});var f=this._unionHandler,c=this._errorHandler,g=new n(q._dfdCanceller);g._pendingDfd=p({url:this._url.path+"/union",content:a,callbackParamName:"callback",load:function(a,c){f(a,c,b,h,e,g)},error:function(a){c(a,e,g)}});return g},_unionHandler:function(a,h,e,b,f,c){try{var g=r.fromJson(a.geometry).setSpatialReference(e);this._successHandler([g],"onUnionComplete",b,c)}catch(d){this._errorHandler(d,
f,c)}},onUnionComplete:function(){},autoComplete:function(a,h,e,b){var f=a[0].spatialReference;a=l.mixin({},this._url.query,{f:"json",sr:k.toJson(f.toJson()),polygons:k.toJson(this._encodeGeometries(a).geometries),polylines:k.toJson(this._encodeGeometries(h).geometries)});var c=this._autoCompleteHandler,g=this._errorHandler,d=new n(q._dfdCanceller);d._pendingDfd=p({url:this._url.path+"/autoComplete",content:a,callbackParamName:"callback",load:function(a,g){c(a,g,f,e,b,d)},error:function(a){g(a,b,
d)}});return d},_autoCompleteHandler:function(a,h,e,b,f,c){try{var g=a.geometries;a=[];var d,m=g.length;for(d=0;d<m;d++)a[d]=new w({spatialReference:e,rings:g[d].rings});this._successHandler([a],"onAutoCompleteComplete",b,c)}catch(u){this._errorHandler(u,f,c)}},onAutoCompleteComplete:function(){},reshape:function(a,h,e,b){var f=a.spatialReference;a=l.mixin({},this._url.query,{f:"json",sr:k.toJson(f.toJson()),target:k.toJson({geometryType:r.getJsonType(a),geometry:a.toJson()}),reshaper:k.toJson(h.toJson())});
var c=this._reshapeHandler,g=this._errorHandler,d=new n(q._dfdCanceller);d._pendingDfd=p({url:this._url.path+"/reshape",content:a,callbackParamName:"callback",load:function(a,g){c(a,g,f,e,b,d)},error:function(a){g(a,b,d)}});return d},_reshapeHandler:function(a,h,e,b,f,c){try{var g=r.fromJson(a.geometry).setSpatialReference(e);this._successHandler([g],"onReshapeComplete",b,c)}catch(d){this._errorHandler(d,f,c)}},onReshapeComplete:function(){},cut:function(a,h,e,b){var f=a[0].spatialReference,c=t.map(a,
function(a){return a.toJson()});a=l.mixin({},this._url.query,{f:"json",sr:k.toJson(f.toJson()),target:k.toJson({geometryType:r.getJsonType(a[0]),geometries:c}),cutter:k.toJson(h.toJson())});var g=this._cutHandler,d=this._errorHandler,m=new n(q._dfdCanceller);m._pendingDfd=p({url:this._url.path+"/cut",content:a,callbackParamName:"callback",load:function(a,d){g(a,d,f,e,b,m)},error:function(a){d(a,b,m)}});return m},_cutHandler:function(a,h,e,b,f,c){try{var g=a.geometries,d={};d.cutIndexes=a.cutIndexes;
d.geometries=[];t.forEach(g,function(a){d.geometries.push(r.fromJson(a).setSpatialReference(e))});this._successHandler([d],"onCutComplete",b,c)}catch(m){this._errorHandler(m,f,c)}},onCutComplete:function(){},intersect:function(a,h,e,b){var f=a[0].spatialReference;a=l.mixin({},this._url.query,{f:"json",sr:k.toJson(f.toJson()),geometries:k.toJson(this._encodeGeometries(a)),geometry:k.toJson({geometryType:r.getJsonType(h),geometry:h.toJson()})});var c=this._intersectHandler,g=this._errorHandler,d=new n(q._dfdCanceller);
d._pendingDfd=p({url:this._url.path+"/intersect",content:a,callbackParamName:"callback",load:function(a,g){c(a,g,f,e,b,d)},error:function(a){g(a,b,d)}});return d},_intersectHandler:function(a,h,e,b,f,c){try{var g=[];t.forEach(a.geometries,function(a){g.push(r.fromJson(a).setSpatialReference(e))});this._successHandler([g],"onIntersectComplete",b,c)}catch(d){this._errorHandler(d,f,c)}},onIntersectComplete:function(){},difference:function(a,h,e,b){var f=a[0].spatialReference;a=l.mixin({},this._url.query,
{f:"json",sr:k.toJson(f.toJson()),geometries:k.toJson(this._encodeGeometries(a)),geometry:k.toJson({geometryType:r.getJsonType(h),geometry:h.toJson()})});var c=this._differenceHandler,g=this._errorHandler,d=new n(q._dfdCanceller);d._pendingDfd=p({url:this._url.path+"/difference",content:a,callbackParamName:"callback",load:function(a,g){c(a,g,f,e,b,d)},error:function(a){g(a,b,d)}});return d},_differenceHandler:function(a,h,e,b,f,c){try{var g=[];t.forEach(a.geometries,function(a){g.push(r.fromJson(a).setSpatialReference(e))});
this._successHandler([g],"onDifferenceComplete",b,c)}catch(d){this._errorHandler(d,f,c)}},onDifferenceComplete:function(){},buffer:function(a,h,e){var b=l.mixin({},this._url.query,{f:"json"},a.toJson()),f=a.outSpatialReference||a.geometries[0].spatialReference,c=this._bufferHandler,g=this._errorHandler,d=new n(q._dfdCanceller);d._pendingDfd=p({url:this._url.path+"/buffer",content:b,callbackParamName:"callback",load:function(a,b){c(a,b,f,h,e,d)},error:function(a){g(a,e,d)}});return d},_bufferHandler:function(a,
h,e,b,f,c){try{var g=a.geometries;a=[];var d,m=g.length;for(d=0;d<m;d++)a[d]=new w({spatialReference:e,rings:g[d].rings});this._successHandler([a],"onBufferComplete",b,c)}catch(u){this._errorHandler(u,f,c)}},onBufferComplete:function(){},areasAndLengths:function(a,h,e){a=l.mixin({},this._url.query,{f:"json"},a.toJson());var b=this._areasAndLengthsHandler,f=this._errorHandler,c=new n(q._dfdCanceller);c._pendingDfd=p({url:this._url.path+"/areasAndLengths",content:a,callbackParamName:"callback",load:function(a,
d){b(a,d,h,e,c)},error:function(a){f(a,e,c)}});return c},_areasAndLengthsHandler:function(a,h,e,b,f){try{this._successHandler([a],"onAreasAndLengthsComplete",e,f)}catch(c){this._errorHandler(c,b,f)}},onAreasAndLengthsComplete:function(){},lengths:function(a,h,e){a=l.mixin({},this._url.query,{f:"json"},a.toJson());var b=this._lengthsHandler,f=this._errorHandler,c=new n(q._dfdCanceller);c._pendingDfd=p({url:this._url.path+"/lengths",content:a,callbackParamName:"callback",load:function(a,d){b(a,d,h,
e,c)},error:function(a){f(a,e,c)}});return c},_lengthsHandler:function(a,h,e,b,f){try{this._successHandler([a],"onLengthsComplete",e,f)}catch(c){this._errorHandler(c,b,f)}},onLengthsComplete:function(){},labelPoints:function(a,h,e){var b=t.map(a,function(a){return a.toJson()}),f=a[0].spatialReference,b=l.mixin({},this._url.query,{f:"json",sr:f.wkid?f.wkid:k.toJson(f.toJson()),polygons:k.toJson(b)}),c=this._labelPointsHandler,g=this._errorHandler,d=new n(q._dfdCanceller);d._pendingDfd=p({url:this._url.path+
"/labelPoints",content:b,callbackParamName:"callback",load:function(b,g){c(b,g,a,f,h,e,d)},error:function(a){g(a,e,d)}});return d},_labelPointsHandler:function(a,h,e,b,f,c,g){try{var d=[];t.forEach(a.labelPoints,function(a){d.push(r.fromJson(a).setSpatialReference(b))});this._successHandler([d],"onLabelPointsComplete",f,g)}catch(m){this._errorHandler(m,c,g)}},onLabelPointsComplete:function(){},relation:function(a,h,e){a=l.mixin({},this._url.query,{f:"json"},a.toJson());var b=this._relationHandler,
f=this._errorHandler,c=new n(q._dfdCanceller);c._pendingDfd=p({url:this._url.path+"/relation",content:a,callbackParamName:"callback",load:function(a,d){b(a,d,h,e,c)},error:function(a){f(a,e,c)}});return c},_relationHandler:function(a,h,e,b,f){try{this._successHandler([a.relations],"onRelationComplete",e,f)}catch(c){this._errorHandler(c,b,f)}},onRelationComplete:function(){},trimExtend:function(a,h,e){var b=l.mixin({},this._url.query,{f:"json"},a.toJson()),f=a.sr,c=this._trimExtendHandler,g=this._errorHandler,
d=new n(q._dfdCanceller);d._pendingDfd=p({url:this._url.path+"/trimExtend",content:b,callbackParamName:"callback",load:function(a,b){c(a,b,f,h,e,d)},error:function(a){g(a,e,d)}});return d},_trimExtendHandler:function(a,h,e,b,f,c){try{var g=a.geometries;a=[];var d,m=g.length;for(d=0;d<m;d++)a[d]=new y({spatialReference:e,paths:g[d].paths});this._successHandler([a],"onTrimExtendComplete",b,c)}catch(u){this._errorHandler(u,f,c)}},onTrimExtendComplete:function(){},densify:function(a,h,e){var b=l.mixin({},
this._url.query,{f:"json"},a.toJson()),f=a.geometries[0].spatialReference,c=this._densifyHandler,g=this._errorHandler,d=new n(q._dfdCanceller);d._pendingDfd=p({url:this._url.path+"/densify",content:b,callbackParamName:"callback",load:function(a,b){c(a,b,f,h,e,d)},error:function(a){g(a,e,d)}});return d},_densifyHandler:function(a,h,e,b,f,c){try{var g=[];t.forEach(a.geometries,function(a){g.push(r.fromJson(a).setSpatialReference(e))});this._successHandler([g],"onDensifyComplete",b,c)}catch(d){this._errorHandler(d,
f,c)}},onDensifyComplete:function(){},generalize:function(a,h,e){var b=l.mixin({},this._url.query,{f:"json"},a.toJson()),f=a.geometries[0].spatialReference,c=this._generalizeHandler,g=this._errorHandler,d=new n(q._dfdCanceller);d._pendingDfd=p({url:this._url.path+"/generalize",content:b,callbackParamName:"callback",load:function(a,b){c(a,b,f,h,e,d)},error:function(a){g(a,e,d)}});return d},_generalizeHandler:function(a,h,e,b,f,c){try{var g=[];t.forEach(a.geometries,function(a){g.push(r.fromJson(a).setSpatialReference(e))});
this._successHandler([g],"onGeneralizeComplete",b,c)}catch(d){this._errorHandler(d,f,c)}},onGeneralizeComplete:function(){},offset:function(a,h,e){var b=l.mixin({},this._url.query,{f:"json"},a.toJson()),f=a.geometries[0].spatialReference,c=this._offsetHandler,g=this._errorHandler,d=new n(q._dfdCanceller);d._pendingDfd=p({url:this._url.path+"/offset",content:b,callbackParamName:"callback",load:function(a,b){c(a,b,f,h,e,d)},error:function(a){g(a,e,d)}});return d},_offsetHandler:function(a,h,e,b,f,c){try{var g=
[];t.forEach(a.geometries,function(a){g.push(r.fromJson(a).setSpatialReference(e))});this._successHandler([g],"onOffsetComplete",b,c)}catch(d){this._errorHandler(d,f,c)}},onOffsetComplete:function(){},distance:function(a,h,e){var b=l.mixin({},this._url.query,{f:"json"},a.toJson()),f=a.geometry1.spatialReference,c=this._distanceHandler,g=this._errorHandler,d=new n(q._dfdCanceller);d._pendingDfd=p({url:this._url.path+"/distance",content:b,callbackParamName:"callback",load:function(a,b){c(a,b,f,h,e,
d)},error:function(a){g(a,e,d)}});return d},_distanceHandler:function(a,h,e,b,f,c){try{a=a&&a.distance,this._successHandler([a],"onDistanceComplete",b,c)}catch(g){this._errorHandler(g,f,c)}},onDistanceComplete:function(){},toGeoCoordinateString:function(a,h,e){var b={};l.isObject(a.sr)?b.sr=a.sr.wkid||k.toJson(a.sr.toJson()):b.sr=a.sr;b.coordinates=k.toJson(a.coordinates);b.conversionType=a.conversionType||"MGRS";b.conversionMode=a.conversionMode;b.numOfDigits=a.numOfDigits;b.rounding=a.rounding;
b.addSpaces=a.addSpaces;a=l.mixin({},this._url.query,{f:"json"},b);var f=this._toGeoCoordinateHandler,c=this._errorHandler,g=new n(q._dfdCanceller);g._pendingDfd=p({url:this._url.path+"/toGeoCoordinateString",content:a,callbackParamName:"callback",load:function(a,b){f(a,b,h,e,g)},error:function(a){c(a,e,g)}});return g},_toGeoCoordinateHandler:function(a,h,e,b,f){try{this._successHandler([a.strings],"onToGeoCoordinateStringComplete",e,f)}catch(c){this._errorHandler(c,b,f)}},onToGeoCoordinateStringComplete:function(){},
fromGeoCoordinateString:function(a,h,e){var b={};l.isObject(a.sr)?b.sr=a.sr.wkid||k.toJson(a.sr.toJson()):b.sr=a.sr;b.strings=k.toJson(a.strings);b.conversionType=a.conversionType||"MGRS";b.conversionMode=a.conversionMode;a=l.mixin({},this._url.query,{f:"json"},b);var f=this._fromGeoCoordinateHandler,c=this._errorHandler,g=new n(q._dfdCanceller);g._pendingDfd=p({url:this._url.path+"/fromGeoCoordinateString",content:a,callbackParamName:"callback",load:function(a,b){f(a,b,h,e,g)},error:function(a){c(a,
e,g)}});return g},_fromGeoCoordinateHandler:function(a,h,e,b,f){try{this._successHandler([a.coordinates],"onToGeoCoordinateStringComplete",e,f)}catch(c){this._errorHandler(c,b,f)}},onFromGeoCoordinateStringComplete:function(){}});l.mixin(v,{UNIT_METER:9001,UNIT_GERMAN_METER:9031,UNIT_FOOT:9002,UNIT_SURVEY_FOOT:9003,UNIT_CLARKE_FOOT:9005,UNIT_FATHOM:9014,UNIT_NAUTICAL_MILE:9030,UNIT_SURVEY_CHAIN:9033,UNIT_SURVEY_LINK:9034,UNIT_SURVEY_MILE:9035,UNIT_KILOMETER:9036,UNIT_CLARKE_YARD:9037,UNIT_CLARKE_CHAIN:9038,
UNIT_CLARKE_LINK:9039,UNIT_SEARS_YARD:9040,UNIT_SEARS_FOOT:9041,UNIT_SEARS_CHAIN:9042,UNIT_SEARS_LINK:9043,UNIT_BENOIT_1895A_YARD:9050,UNIT_BENOIT_1895A_FOOT:9051,UNIT_BENOIT_1895A_CHAIN:9052,UNIT_BENOIT_1895A_LINK:9053,UNIT_BENOIT_1895B_YARD:9060,UNIT_BENOIT_1895B_FOOT:9061,UNIT_BENOIT_1895B_CHAIN:9062,UNIT_BENOIT_1895B_LINK:9063,UNIT_INDIAN_FOOT:9080,UNIT_INDIAN_1937_FOOT:9081,UNIT_INDIAN_1962_FOOT:9082,UNIT_INDIAN_1975_FOOT:9083,UNIT_INDIAN_YARD:9084,UNIT_INDIAN_1937_YARD:9085,UNIT_INDIAN_1962_YARD:9086,
UNIT_INDIAN_1975_YARD:9087,UNIT_FOOT_1865:9070,UNIT_RADIAN:9101,UNIT_DEGREE:9102,UNIT_ARCMINUTE:9103,UNIT_ARCSECOND:9104,UNIT_GRAD:9105,UNIT_GON:9106,UNIT_MICRORADIAN:9109,UNIT_ARCMINUTE_CENTESIMAL:9112,UNIT_ARCSECOND_CENTESIMAL:9113,UNIT_MIL6400:9114,UNIT_BRITISH_1936_FOOT:9095,UNIT_GOLDCOAST_FOOT:9094,UNIT_INTERNATIONAL_CHAIN:109003,UNIT_INTERNATIONAL_LINK:109004,UNIT_INTERNATIONAL_YARD:109001,UNIT_STATUTE_MILE:9093,UNIT_SURVEY_YARD:109002,UNIT_50KILOMETER_LENGTH:109030,UNIT_150KILOMETER_LENGTH:109031,
UNIT_DECIMETER:109005,UNIT_CENTIMETER:109006,UNIT_MILLIMETER:109007,UNIT_INTERNATIONAL_INCH:109008,UNIT_US_SURVEY_INCH:109009,UNIT_INTERNATIONAL_ROD:109010,UNIT_US_SURVEY_ROD:109011,UNIT_US_NAUTICAL_MILE:109012,UNIT_UK_NAUTICAL_MILE:109013,UNIT_SQUARE_INCHES:"esriSquareInches",UNIT_SQUARE_FEET:"esriSquareFeet",UNIT_SQUARE_YARDS:"esriSquareYards",UNIT_ACRES:"esriAcres",UNIT_SQUARE_MILES:"esriSquareMiles",UNIT_SQUARE_MILLIMETERS:"esriSquareMillimeters",UNIT_SQUARE_CENTIMETERS:"esriSquareCentimeters",
UNIT_SQUARE_DECIMETERS:"esriSquareDecimeters",UNIT_SQUARE_METERS:"esriSquareMeters",UNIT_ARES:"esriAres",UNIT_HECTARES:"esriHectares",UNIT_SQUARE_KILOMETERS:"esriSquareKilometers"});z("extend-esri")&&l.setObject("tasks.GeometryService",v,A);return v});
|
/*
* Copyright 2015 Palantir Technologies, 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.
*/
export const DISPLAYNAME_PREFIX = "Blueprint3";
/** A collection of curated prop keys used across our Components which are not valid HTMLElement props. */
const INVALID_PROPS = [
"active",
"alignText",
"asyncControl",
"containerRef",
"current",
"elementRef",
"fill",
"icon",
"inputRef",
"intent",
"inline",
"large",
"loading",
"leftElement",
"leftIcon",
"minimal",
"onRemove",
"outlined",
"panel",
"panelClassName",
"popoverProps",
"rightElement",
"rightIcon",
"round",
"small",
"text",
];
/**
* Typically applied to HTMLElements to filter out disallowed props. When applied to a Component,
* can filter props from being passed down to the children. Can also filter by a combined list of
* supplied prop keys and the denylist (only appropriate for HTMLElements).
* @param props The original props object to filter down.
* @param {string[]} invalidProps If supplied, overwrites the default denylist.
* @param {boolean} shouldMerge If true, will merge supplied invalidProps and denylist together.
*/
export function removeNonHTMLProps(props, invalidProps = INVALID_PROPS, shouldMerge = false) {
if (shouldMerge) {
invalidProps = invalidProps.concat(INVALID_PROPS);
}
return invalidProps.reduce((prev, curr) => {
// Props with hyphens (e.g. data-*) are always considered html props
if (curr.indexOf("-") !== -1) {
return prev;
}
if (prev.hasOwnProperty(curr)) {
delete prev[curr];
}
return prev;
}, { ...props });
}
//# sourceMappingURL=props.js.map
|
import React from "react";
import axios from "axios";
import DropzoneComponent from "react-dropzone-component";
import RichTextEditor from "../forms/rich-text-editor";
export default class BlogForm extends React.Component {
constructor(props) {
super(props);
this.state = {
id: "",
title: "",
blog_status: "",
content: "",
featured_image: "",
apiURL: "https://michellemarquez.devcamp.space/portfolio/portfolio_blogs",
apiAction: "post"
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleRichTextEditorChange = this.handleRichTextEditorChange.bind(
this
);
this.conponentConfig = this.componentConfig.bind(this);
this.djsConfig = this.djsConfig.bind(this);
this.handleFeaturedImageDrop = this.handleFeaturedImageDrop.bind(this);
this.deleteImage = this.deleteImage.bind(this);
this.featuredImageRef = React.createRef();
}
deleteImage(imageType) {
axios
.delete(
`https://api.devcamp.space/portfolio/delete-portfolio-blog-image/${this.props.blog.id}?image_type=${imageType}`,
{ withCredentials: true }
)
.then(response => {
this.props.handleFeaturedImageDelete();
})
.catch(error => {
console.log("deleteImage error", error);
});
}
componentWillMount() {
if (this.props.editMode) {
this.setState({
id: this.props.blog.id,
title: this.props.blog.title,
blog_status: this.props.blog.blog_status,
content: this.props.blog.content,
apiURL: `https://michellemarquez.devcamp.space/portfolio/portfolio_blogs/${this.props.blog.id}`,
apiAction: "patch"
});
}
}
componentConfig() {
return {
iconFiletypes: [".jpg", ".png"],
showFiletypeIcon: true,
postUrl: "https://httpbin.org/post"
};
}
djsConfig() {
return {
addRemoveLinks: true,
maxFiles: 1
};
}
handleFeaturedImageDrop() {
return {
addedfile: file => this.setState({ featured_image: file })
};
}
handleRichTextEditorChange(content) {
this.setState({ content });
}
buildForm() {
let formData = new FormData();
formData.append("portfolio_blog[title]", this.state.title);
formData.append("portfolio_blog[blog_status]", this.state.blog_status);
formData.append("portfolio_blog[content]", this.state.content);
if (this.state.featured_image) {
formData.append(
"portfolio_blog[featured_image]",
this.state.featured_image
);
}
return formData;
}
handleSubmit(event) {
// @ts-ignore
axios({
method: this.state.apiAction,
url: this.state.apiUrl,
data: this.buildForm(),
withCredentials: true
})
.post(this.state.apiURL, this.buildForm(), { withCredentials: true })
.then(response => {
if (this.state.featured_image) {
this.featuredImageRef.current.dropzone.removeAllFiles();
}
this.setState({
title: "",
blog_status: "",
content: "",
featured_image: ""
});
if (this.props.editMode) {
// update blog detail
this.props.handleUpdateForSubmission(response.data.portfolio_blog);
} else {
this.props.handleSuccessfullFormSubmission(
response.data.portfolio_blog
);
}
})
.catch(error => {
console.log("handleSubmit for blog error", error);
});
event.preventDefault();
}
handleChange(event) {
this.setState({
[event.target.name]: event.target.value
});
}
render() {
return (
<form onSubmit={this.handleSubmit} className="blog-form-wrapper">
<div className="two-columns">
<input
type="text"
onChange={this.handleChange}
name="title"
placeholder="Blog Title"
value={this.state.title}
/>
<input
type="text"
onChange={this.handleChange}
name="blog_status"
placeholder="Blog status"
value={this.state.blog_status}
/>
</div>
<div className="one-column">
<RichTextEditor
handleRichTextEditorChange={this.handleRichTextEditorChange}
editMode={this.props.editMode}
contentToEdit={
this.props.editMode && this.props.blog.content
? this.props.blog.content
: null
}
/>
</div>
<div className="image-uploaders">
{this.props.editMode && this.props.blog.featured_image_url ? (
<div className="manager-image-wrapper">
<img src={this.props.blog.featured_image_url} />
<div className="image-removal-link">
<a onClick={() => this.deleteImage("featured_image")}>
Remove file
</a>
</div>
</div>
) : (
<DropzoneComponent
ref={this.featuredImageRef}
config={this.componentConfig()}
djsConfig={this.djsConfig()}
eventHandlers={this.handleFeaturedImageDrop()}
>
<div className="dz-message">Featured Image</div>
</DropzoneComponent>
)}
</div>
<button className="btn">Save</button>
</form>
);
}
}
|
var callbackArguments = [];
var base_0 = [0,59,627,893]
var r_0= undefined
try {
r_0 = base_0.filter()
}
catch(e) {
r_0= "Error"
}
function serialize(array){
return array.map(function(a){
if (a === null || a == undefined) return a;
var name = a.constructor.name;
if (name==='Object' || name=='Boolean'|| name=='Array'||name=='Number'||name=='String')
return JSON.stringify(a);
return name;
});
}
setTimeout(function(){
require("fs").writeFileSync("./experiments/filter/filterRandom/test639.json",JSON.stringify({"baseObjects":serialize([base_0]),"returnObjects":serialize([r_0]),"callbackArgs":callbackArguments}))
},300)
|
module.exports = {
rules: {
'no-css-tags': require('./rules/no-css-tags'),
'no-sync-scripts': require('./rules/no-sync-scripts'),
'no-html-link-for-pages': require('./rules/no-html-link-for-pages'),
'no-img-element': require('./rules/no-img-element'),
'no-unwanted-polyfillio': require('./rules/no-unwanted-polyfillio'),
'no-page-custom-font': require('./rules/no-page-custom-font'),
'no-title-in-document-head': require('./rules/no-title-in-document-head'),
'google-font-display': require('./rules/google-font-display'),
'google-font-preconnect': require('./rules/google-font-preconnect'),
'link-passhref': require('./rules/link-passhref'),
'no-document-import-in-page': require('./rules/no-document-import-in-page'),
'no-head-import-in-document': require('./rules/no-head-import-in-document'),
'no-script-in-document': require('./rules/no-script-in-document'),
'no-script-in-head': require('./rules/no-script-in-head'),
'no-server-import-in-page': require('./rules/no-server-import-in-page'),
'no-typos': require('./rules/no-typos'),
'no-duplicate-head': require('./rules/no-duplicate-head'),
'inline-script-id': require('./rules/inline-script-id'),
'next-script-for-ga': require('./rules/next-script-for-ga'),
},
configs: {
recommended: {
plugins: ['@next/next'],
rules: {
'@next/next/no-css-tags': 1,
'@next/next/no-sync-scripts': 1,
'@next/next/no-html-link-for-pages': 1,
'@next/next/no-img-element': 1,
'@next/next/no-unwanted-polyfillio': 1,
'@next/next/no-page-custom-font': 1,
'@next/next/no-title-in-document-head': 1,
'@next/next/google-font-display': 1,
'@next/next/google-font-preconnect': 1,
'@next/next/link-passhref': 1,
'@next/next/next-script-for-ga': 1,
'@next/next/no-document-import-in-page': 2,
'@next/next/no-head-import-in-document': 2,
'@next/next/no-script-in-document': 2,
'@next/next/no-script-in-head': 2,
'@next/next/no-server-import-in-page': 2,
'@next/next/no-typos': 1,
'@next/next/no-duplicate-head': 2,
'@next/next/inline-script-id': 2,
},
},
'core-web-vitals': {
plugins: ['@next/next'],
extends: ['plugin:@next/next/recommended'],
rules: {
'@next/next/no-sync-scripts': 2,
'@next/next/no-html-link-for-pages': 2,
},
},
},
}
|
# Copyright 2019 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""test mindrecord base"""
import os
import uuid
from mindspore.mindrecord import FileWriter, FileReader, MindPage, SUCCESS
from mindspore import log as logger
from utils import get_data, get_nlp_data
FILES_NUM = 4
CV_FILE_NAME = "./imagenet.mindrecord"
CV2_FILE_NAME = "./imagenet_loop.mindrecord"
CV3_FILE_NAME = "./imagenet_append.mindrecord"
NLP_FILE_NAME = "./aclImdb.mindrecord"
def test_cv_file_writer_tutorial():
"""tutorial for cv dataset writer."""
writer = FileWriter(CV_FILE_NAME, FILES_NUM)
data = get_data("../data/mindrecord/testImageNetData/")
cv_schema_json = {"file_name": {"type": "string"},
"label": {"type": "int64"}, "data": {"type": "bytes"}}
writer.add_schema(cv_schema_json, "img_schema")
writer.add_index(["file_name", "label"])
writer.write_raw_data(data)
writer.commit()
def test_cv_file_append_writer():
"""tutorial for cv dataset append writer."""
writer = FileWriter(CV3_FILE_NAME, 4)
data = get_data("../data/mindrecord/testImageNetData/")
cv_schema_json = {"file_name": {"type": "string"},
"label": {"type": "int64"}, "data": {"type": "bytes"}}
writer.add_schema(cv_schema_json, "img_schema")
writer.add_index(["file_name", "label"])
writer.write_raw_data(data[0:5])
writer.commit()
write_append = FileWriter.open_for_append(CV3_FILE_NAME + "0")
write_append.write_raw_data(data[5:10])
write_append.commit()
reader = FileReader(CV3_FILE_NAME + "0")
count = 0
for index, x in enumerate(reader.get_next()):
assert len(x) == 3
count = count + 1
logger.info("#item{}: {}".format(index, x))
assert count == 10
reader.close()
paths = ["{}{}".format(CV3_FILE_NAME, str(x).rjust(1, '0'))
for x in range(4)]
for x in paths:
os.remove("{}".format(x))
os.remove("{}.db".format(x))
def test_cv_file_writer_loop_and_read():
"""tutorial for cv dataset loop writer."""
writer = FileWriter(CV2_FILE_NAME, FILES_NUM)
data = get_data("../data/mindrecord/testImageNetData/")
cv_schema_json = {"file_name": {"type": "string"},
"label": {"type": "int64"}, "data": {"type": "bytes"}}
writer.add_schema(cv_schema_json, "img_schema")
writer.add_index(["file_name", "label"])
for row in data:
writer.write_raw_data([row])
writer.commit()
reader = FileReader(CV2_FILE_NAME + "0")
count = 0
for index, x in enumerate(reader.get_next()):
assert len(x) == 3
count = count + 1
logger.info("#item{}: {}".format(index, x))
assert count == 10
reader.close()
paths = ["{}{}".format(CV2_FILE_NAME, str(x).rjust(1, '0'))
for x in range(FILES_NUM)]
for x in paths:
os.remove("{}".format(x))
os.remove("{}.db".format(x))
def test_cv_file_reader_tutorial():
"""tutorial for cv file reader."""
reader = FileReader(CV_FILE_NAME + "0")
count = 0
for index, x in enumerate(reader.get_next()):
assert len(x) == 3
count = count + 1
logger.info("#item{}: {}".format(index, x))
assert count == 10
reader.close()
def test_cv_file_reader_partial_tutorial():
"""tutorial for cv file partial reader."""
reader = FileReader(CV_FILE_NAME + "0")
count = 0
for index, x in enumerate(reader.get_next()):
assert len(x) == 3
count = count + 1
logger.info("#item{}: {}".format(index, x))
if count == 5:
reader.finish()
assert count == 5
def test_cv_page_reader_tutorial():
"""tutorial for cv page reader."""
reader = MindPage(CV_FILE_NAME + "0")
fields = reader.get_category_fields()
assert fields == ['file_name', 'label'],\
'failed on getting candidate category fields.'
ret = reader.set_category_field("label")
assert ret == SUCCESS, 'failed on setting category field.'
info = reader.read_category_info()
logger.info("category info: {}".format(info))
row = reader.read_at_page_by_id(0, 0, 1)
assert len(row) == 1
assert len(row[0]) == 3
assert row[0]['label'] == 13
row1 = reader.read_at_page_by_name("822", 0, 1)
assert len(row1) == 1
assert len(row1[0]) == 3
assert row1[0]['label'] == 822
paths = ["{}{}".format(CV_FILE_NAME, str(x).rjust(1, '0'))
for x in range(FILES_NUM)]
for x in paths:
os.remove("{}".format(x))
os.remove("{}.db".format(x))
def test_nlp_file_writer_tutorial():
"""tutorial for nlp file writer."""
writer = FileWriter(NLP_FILE_NAME, FILES_NUM)
data = list(get_nlp_data("../data/mindrecord/testAclImdbData/pos",
"../data/mindrecord/testAclImdbData/vocab.txt",
10))
nlp_schema_json = {"id": {"type": "string"}, "label": {"type": "int32"},
"rating": {"type": "float32"},
"input_ids": {"type": "int64",
"shape": [1, -1]},
"input_mask": {"type": "int64",
"shape": [1, -1]},
"segment_ids": {"type": "int64",
"shape": [1, -1]}
}
writer.add_schema(nlp_schema_json, "nlp_schema")
writer.add_index(["id", "rating"])
writer.write_raw_data(data)
writer.commit()
def test_nlp_file_reader_tutorial():
"""tutorial for nlp file reader."""
reader = FileReader(NLP_FILE_NAME + "0")
count = 0
for index, x in enumerate(reader.get_next()):
assert len(x) == 6
count = count + 1
logger.info("#item{}: {}".format(index, x))
assert count == 10
reader.close()
def test_nlp_page_reader_tutorial():
"""tutorial for nlp page reader."""
reader = MindPage(NLP_FILE_NAME + "0")
fields = reader.get_category_fields()
assert fields == ['id', 'rating'],\
'failed on getting candidate category fields.'
ret = reader.set_category_field("rating")
assert ret == SUCCESS, 'failed on setting category field.'
info = reader.read_category_info()
logger.info("category info: {}".format(info))
row = reader.read_at_page_by_id(0, 0, 1)
assert len(row) == 1
assert len(row[0]) == 6
logger.info("row[0]: {}".format(row[0]))
row1 = reader.read_at_page_by_name("7", 0, 1)
assert len(row1) == 1
assert len(row1[0]) == 6
logger.info("row1[0]: {}".format(row1[0]))
paths = ["{}{}".format(NLP_FILE_NAME, str(x).rjust(1, '0'))
for x in range(FILES_NUM)]
for x in paths:
os.remove("{}".format(x))
os.remove("{}.db".format(x))
def test_cv_file_writer_shard_num_1000():
"""test file writer when shard num equals 1000."""
writer = FileWriter(CV_FILE_NAME, 1000)
data = get_data("../data/mindrecord/testImageNetData/")
cv_schema_json = {"file_name": {"type": "string"},
"label": {"type": "int64"}, "data": {"type": "bytes"}}
writer.add_schema(cv_schema_json, "img_schema")
writer.add_index(["file_name", "label"])
writer.write_raw_data(data)
writer.commit()
paths = ["{}{}".format(CV_FILE_NAME, str(x).rjust(3, '0'))
for x in range(1000)]
for x in paths:
os.remove("{}".format(x))
os.remove("{}.db".format(x))
def test_cv_file_writer_absolute_path():
"""test cv file writer when file name is absolute path."""
file_name = "/tmp/" + str(uuid.uuid4())
writer = FileWriter(file_name, FILES_NUM)
data = get_data("../data/mindrecord/testImageNetData/")
cv_schema_json = {"file_name": {"type": "string"},
"label": {"type": "int64"}, "data": {"type": "bytes"}}
writer.add_schema(cv_schema_json, "img_schema")
writer.add_index(["file_name", "label"])
writer.write_raw_data(data)
writer.commit()
paths = ["{}{}".format(file_name, str(x).rjust(1, '0'))
for x in range(FILES_NUM)]
for x in paths:
os.remove("{}".format(x))
os.remove("{}.db".format(x))
def test_cv_file_writer_without_data():
"""test cv file writer without data."""
writer = FileWriter(CV_FILE_NAME, 1)
cv_schema_json = {"file_name": {"type": "string"},
"label": {"type": "int64"}, "data": {"type": "bytes"}}
writer.add_schema(cv_schema_json, "img_schema")
writer.add_index(["file_name", "label"])
writer.commit()
reader = FileReader(CV_FILE_NAME)
count = 0
for index, x in enumerate(reader.get_next()):
count = count + 1
logger.info("#item{}: {}".format(index, x))
assert count == 0
reader.close()
os.remove(CV_FILE_NAME)
os.remove("{}.db".format(CV_FILE_NAME))
def test_cv_file_writer_no_blob():
"""test cv file writer without blob data."""
writer = FileWriter(CV_FILE_NAME, 1)
data = get_data("../data/mindrecord/testImageNetData/")
cv_schema_json = {"file_name": {"type": "string"},
"label": {"type": "int64"}}
writer.add_schema(cv_schema_json, "no_blob_schema")
writer.add_index(["file_name", "label"])
writer.write_raw_data(data)
writer.commit()
reader = FileReader(CV_FILE_NAME)
count = 0
for index, x in enumerate(reader.get_next()):
count += 1
assert len(x) == 2
logger.info("#item{}: {}".format(index, x))
assert count == 10
reader.close()
os.remove(CV_FILE_NAME)
os.remove("{}.db".format(CV_FILE_NAME))
def test_cv_file_writer_no_raw():
"""test cv file writer without raw data."""
writer = FileWriter(NLP_FILE_NAME)
data = list(get_nlp_data("../data/mindrecord/testAclImdbData/pos",
"../data/mindrecord/testAclImdbData/vocab.txt",
10))
nlp_schema_json = {"input_ids": {"type": "int64",
"shape": [1, -1]},
"input_mask": {"type": "int64",
"shape": [1, -1]},
"segment_ids": {"type": "int64",
"shape": [1, -1]}
}
writer.add_schema(nlp_schema_json, "no_raw_schema")
writer.write_raw_data(data)
writer.commit()
reader = FileReader(NLP_FILE_NAME)
count = 0
for index, x in enumerate(reader.get_next()):
count += 1
assert len(x) == 3
logger.info("#item{}: {}".format(index, x))
assert count == 10
reader.close()
os.remove(NLP_FILE_NAME)
os.remove("{}.db".format(NLP_FILE_NAME))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Visualization
==================
This is module contains a simple visualizer to show event lists along with the audio.
The visualizer can show multiple event lists for the same reference audio allowing the
comparison of the reference and estimated event lists.
.. image:: visualization.png
.. autosummary::
:toctree: generated/
EventListVisualizer
EventListVisualizer.show
"""
from __future__ import print_function, absolute_import
from sed_vis.util import AudioPlayer, AudioThread
import dcase_util
import numpy
import math
import time
import scipy.fftpack
import scipy.signal
from numpy.lib.stride_tricks import as_strided
from sys import platform as _platform
import matplotlib
if _platform == "darwin":
# MAC OS X
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import matplotlib.patches as patches
import matplotlib.colors as colors
import matplotlib.cm as cm
from matplotlib.widgets import Button, SpanSelector
from matplotlib.patches import Rectangle
class EventListVisualizer(object):
"""Event List visualizer.
Examples
--------
>>> # Load audio signal first
>>> audio_container = dcase_util.containers.AudioContainer().load('data/audio.wav')
>>> # Load event lists
>>> reference_event_list = dcase_util.containers.MetaDataContainer().load('data/reference.txt')
>>> estimated_event_list = dcase_util.containers.MetaDataContainer().load('data/estimated.txt')
>>> event_lists = {'reference': reference_event_list, 'estimated': estimated_event_list}
>>> # Visualize the data
>>> vis = sed_vis.visualization.EventListVisualizer(event_lists=event_lists,audio_signal=audio_container.data,sampling_rate=audio_container.fs)
>>> vis.show()
"""
def __init__(self, *args, **kwargs):
"""Constructor
Parameters
----------
event_lists : dict of event lists
Dict of event lists
event_list_order : list
Order of event list, if None alphabetical order used
(Default value=None)
active_events : list
List of active sound event classes, if None all used.
(Default value=None)
audio_signal : np.ndarray
Audio signal
sampling_rate : int
Sampling rate [0:96000]
mode: str
Signal visualization mode ['spectrogram', 'time_domain']
(Default value = 'spectrogram')
spec_hop_size : int
Spectrogram calculation hop length in samples
(Default value=256)
spec_win_size: int ,
Spectrogram calculation window length in samples
(Default value=1024)
spec_fft_size: int
FFT length
(Default value=1024)
spec_cmap : str
Color map used for spectrogram, see examples: http://matplotlib.org/examples/color/colormaps_reference.html
(Default value='magma')
spec_interpolation : str
Matrix interpolation method for spectrogram (e.g. nearest, bilear, bicubic, quadric, gaussian)
(Default value='nearest')
event_roll_cmap : str
Color map used for spectrogram, see examples: http://matplotlib.org/examples/color/colormaps_reference.html
(Default value='rainbow')
minimum_event_length : float > 0.0
Minimum event length in seconds, shorten than given are filtered out from the output.
(Default value=None)
minimum_event_gap : float > 0.0
Minimum allowed gap between events in seconds from same event label class.
(Default value=None)
color : color hex
Main color code used in highlighting things
use_blit : bool
Use blit
(Default value=False)
publication_mode : bool
Strip visual elements, can be used to prepare figures for publications.
(Default value=False)
show_selector : bool
Show highlight selector
(Default value=True)
labels: dict
Text labels overrides
button_color : dict
Button color overrides
Returns
-------
Nothing
"""
if kwargs.get('event_lists', []):
self._event_lists = kwargs.get('event_lists', [])
if kwargs.get('event_list_order') is None:
self._event_list_order = sorted(self._event_lists.keys())
else:
self._event_list_order = kwargs.get('event_list_order')
events = dcase_util.containers.MetaDataContainer()
for event_list_label in self._event_lists:
events += self._event_lists[event_list_label]
self.event_labels = sorted(events.unique_event_labels, reverse=True)
self.event_label_count = events.event_label_count
if kwargs.get('active_events') is None:
self.active_events = self.event_labels
else:
self.active_events = sorted(kwargs.get('active_events'), reverse=True)
for name in self._event_lists:
self._event_lists[name] = self._event_lists[name].process_events(
minimum_event_length=kwargs.get('minimum_event_length'),
minimum_event_gap=kwargs.get('minimum_event_gap')
)
else:
self._event_lists = None
if kwargs.get('audio_signal') is not None and kwargs.get('sampling_rate') is not None:
audio_signal = kwargs.get('audio_signal') / numpy.max(numpy.abs(kwargs.get('audio_signal')))
self.audio = AudioPlayer(
signal=audio_signal,
sampling_rate=kwargs.get('sampling_rate')
)
if kwargs.get('mode') not in ['spectrogram', 'time_domain']:
self.mode = 'spectrogram'
else:
self.mode = kwargs.get('mode')
self.auto_play = kwargs.get('auto_play', False)
self.spec_hop_size = kwargs.get('spec_hop_size', 256)
self.spec_win_size = kwargs.get('spec_win_size', 1024)
self.spec_fft_size = kwargs.get('spec_fft_size', 1024)
self.spec_cmap = kwargs.get('spec_cmap', 'magma')
self.spec_interpolation = kwargs.get('spec_interpolation', 'nearest')
self.color = kwargs.get('color', '#339933')
self.button_color = {
'off': 'grey',
'on': 'red'
}
self.button_color.update(kwargs.get('button_color',{}))
self.labels = {
'close': 'Close',
'play': 'Play',
'stop': 'Stop',
'quit': 'Quit',
'selection': 'Selection',
'waveform': 'Waveform',
'spectrogram': 'Spectrogram',
'verification': 'Verification',
'verification_info': '',
'info': '',
}
self.labels.update(kwargs.get('labels',{}))
self.indicator_line_color = self.color
# Initialize members
self.fig = None
# Panels
self.ax1 = None
self.ax2 = None
self.ax3 = None
self.D = None
self.x = None
self.timedomain_locations = None
self.begin_time = None
self.end_time = None
self.playback_offset = 0
# Play indicators
self.animation_event_roll_panel = None
self.animation_selector_panel = None
self.animation_highlight_panel = None
self.event_panel_indicator_line = None
self.selector_panel_indicator_line = None
self.highlight_panel_indicator_line = None
self.slider_time = None
# Buttons
self.buttons = {
'play': True,
'pause': False,
'stop': True,
'close': True,
'quit': False,
'verification': False,
}
self.buttons.update(kwargs.get('buttons',{}))
self.button_play = None
self.button_pause = None
self.button_stop = None
self.button_close = None
self.use_blit = kwargs.get('use_blit', False)
self.publication_mode = kwargs.get('publication_mode', False)
self.show_selector = kwargs.get('show_selector', True)
self.panel_title_font_size = 14
self.legend_font_size = 12
self.event_roll_label_font_size = 14
self.event_roll_time_font_size = 10
self.waveform_selector_point_hop = kwargs.get('waveform_selector_point_hop', 1000)
self.waveform_highlight_point_hop = 100
self.waveform_highlight_color = self.color
self.selector_panel_height = 10
self.highlight_panel_height = 25
self.event_roll_panel_height = 50
self.selector_panel_loc = 0
self.highlight_panel_loc = 17
self.event_roll_panel_loc = 45
self.event_roll_item_opacity = 0.5
self.fig_shape = (14, 6)
self._quit = False
if self.publication_mode:
self.panel_title_font_size = 14
self.legend_font_size = 16
self.event_roll_time_font_size = 12
self.spec_cmap = 'magma_r'
self.spec_interpolation = 'bicubic'
if not self.waveform_selector_point_hop:
self.waveform_selector_point_hop = 5000
self.waveform_highlight_point_hop = 500
self.waveform_highlight_color = 'black'
if self.show_selector:
if self.mode == 'time_domain':
self.fig_shape = (30, 4)
elif self.mode == 'spectrogram':
self.fig_shape = (20, 5)
if self._event_lists:
if self.event_label_count == 1:
self.selector_panel_height = 10
self.highlight_panel_height = 33
self.event_roll_panel_height = 33
self.selector_panel_loc = 0
self.highlight_panel_loc = 17
self.event_roll_panel_loc = 53
self.event_roll_time_font_size = 16
else:
self.selector_panel_height = 10
self.highlight_panel_height = 15
self.event_roll_panel_height = 60
self.selector_panel_loc = 0
self.highlight_panel_loc = 17
self.event_roll_panel_loc = 35
else:
self.selector_panel_height = 30
self.highlight_panel_height = 66
self.event_roll_panel_height = 0
self.selector_panel_loc = 0
self.highlight_panel_loc = 37
self.event_roll_panel_loc = 0
self.event_roll_time_font_size = 16
else:
if self.mode == 'time_domain':
self.fig_shape = (30, 4)
elif self.mode == 'spectrogram':
self.fig_shape = (20, 4)
self.selector_panel_height = 0
self.highlight_panel_height = 15
self.event_roll_panel_height = 75
self.selector_panel_loc = 0
self.highlight_panel_loc = 0
self.event_roll_panel_loc = 17
self.event_roll_item_opacity = 1.0
self.label_colormap = cm.get_cmap(name=kwargs.get('event_roll_cmap','rainbow'))
def generate_GUI(self):
"""Generates the visualizer GUI.
Parameters
----------
Nothing
Returns
-------
Nothing
"""
self.fig = plt.figure(figsize=self.fig_shape)
# Selector panel
# ====================================
if self.show_selector:
self.ax1 = plt.subplot2grid(shape=(100, 1), loc=(self.selector_panel_loc, 0), rowspan=self.selector_panel_height, colspan=1)
self.timedomain_locations = numpy.arange(0, self.audio.signal.shape[0])
self.ax1.fill_between(
self.timedomain_locations[::self.waveform_selector_point_hop],
self.audio.signal[::self.waveform_selector_point_hop],
-self.audio.signal[::self.waveform_selector_point_hop],
color='0.5'
)
plt.yticks([])
plt.axis('tight')
self.ax1.set_xlim(self.timedomain_locations[0], self.timedomain_locations[-1])
self.ax1.set_ylim(-1, 1)
self.time_ticks(
locations=self.timedomain_locations,
n_ticks=10,
sampling_rate=self.audio.fs
)
self.ax1.yaxis.grid(False, which='major')
self.ax1.yaxis.grid(False, which='minor')
self.ax1.xaxis.grid(True, which='major')
self.ax1.xaxis.grid(True, which='minor')
self.ax1.yaxis.set_label_position("right")
plt.title(self.labels['selection'], fontsize=self.panel_title_font_size)
# Highlight panel
# ====================================
self.ax2 = plt.subplot2grid(shape=(100, 1), loc=(self.highlight_panel_loc, 0), rowspan=self.highlight_panel_height, colspan=1)
self.x = numpy.arange(0, self.audio.duration_samples)
self.begin_time = self.x[0] / float(self.audio.fs)
self.end_time = self.x[-1] / float(self.audio.fs)
if self.mode == 'spectrogram':
self.D = self.get_spectrogram(
audio=self.audio.signal,
n_fft=self.spec_fft_size,
win_length=self.spec_win_size,
hop_length=self.spec_hop_size
)
self.plot_spectrogram(
self.D,
sampling_rate=self.audio.fs,
interpolation=self.spec_interpolation,
cmap=self.spec_cmap
)
if not self.publication_mode:
self.ax2.yaxis.grid(False, which='major')
self.ax2.yaxis.grid(False, which='minor')
self.ax2.xaxis.grid(False, which='major')
self.ax2.xaxis.grid(False, which='minor')
plt.ylabel(self.labels['spectrogram'], fontsize=self.panel_title_font_size)
else:
self.ax2.get_yaxis().set_visible(False)
elif self.mode == 'time_domain':
self.ax2.fill_between(
self.x[::self.waveform_highlight_point_hop], self.audio.signal[::self.waveform_highlight_point_hop], -self.audio.signal[::self.waveform_highlight_point_hop],
color=self.waveform_highlight_color
)
self.ax2.set_ylim(-1, 1)
self.ax2.set_xlim(self.x[0], self.x[-1])
segment_begin = self.x[0] / float(self.audio.fs)
segment_end = self.x[-1] / float(self.audio.fs)
locs = numpy.arange(segment_begin, segment_end)
plt.xlim([locs[0], locs[-1]])
self.time_ticks(locations=locs, n_ticks=20)
plt.yticks([])
plt.xticks([])
self.ax2.yaxis.grid(False, which='major')
self.ax2.yaxis.grid(False, which='minor')
self.ax2.xaxis.grid(True, which='major')
self.ax2.xaxis.grid(True, which='minor')
if not self.publication_mode:
plt.ylabel(self.labels['waveform'], fontsize=self.panel_title_font_size)
self.ax2.set_xlim(self.timedomain_locations[0], self.timedomain_locations[-1])
self.ax2.yaxis.set_label_position("right")
# Event roll panel
# ====================================
if self._event_lists:
event_list_count = len(self._event_lists)
self.begin_time = 0
self.end_time = self.audio.duration_seconds
if event_list_count == 1:
norm = colors.Normalize(
vmin=0,
vmax=self.event_label_count
)
self.ax3 = plt.subplot2grid(
shape=(100, 1),
loc=(self.event_roll_panel_loc, 0),
rowspan=self.event_roll_panel_height+10,
colspan=1
)
else:
norm = colors.Normalize(
vmin=0,
vmax=event_list_count
)
self.ax3 = plt.subplot2grid(
shape=(100, 1),
loc=(self.event_roll_panel_loc, 0),
rowspan=self.event_roll_panel_height,
colspan=1
)
m = cm.ScalarMappable(norm=norm, cmap=self.label_colormap)
line_margin = 0.1
y = 0
annotation_height = (1.0-line_margin*2)/event_list_count
for label in self.active_events:
for event_list_id, event_list_label in enumerate(self._event_list_order):
offset = (len(self._event_list_order)-1-event_list_id) * annotation_height
event_y = y - 0.5 + line_margin + offset
# grid line
line = plt.Rectangle(
(0, y-0.5),
height=0.001,
width=self.end_time,
edgecolor='black',
facecolor='black'
)
plt.gca().add_patch(line)
for event in self._event_lists[event_list_label]:
if event['event_label'] == label:
event_length = event['offset'] - event['onset']
if 'probability' in event:
if event_list_count == 1:
color = m.to_rgba(x=y + offset, alpha=event['probability'])
else:
color = m.to_rgba(x=event_list_id, alpha=event['probability'])
rectangle = plt.Rectangle(
(event['onset'], event_y),
height=annotation_height,
width=event_length,
edgecolor='black',
facecolor=color,
linewidth=0,
picker=5
)
else:
if event_list_count == 1:
color = m.to_rgba(x=y + offset)
else:
color = m.to_rgba(x=event_list_id)
rectangle = plt.Rectangle(
(event['onset'], event_y),
height=annotation_height,
width=event_length,
edgecolor='black',
facecolor=color,
linewidth=0,
alpha=self.event_roll_item_opacity,
picker=5
)
plt.gca().add_patch(rectangle)
y += 1
# grid line
line = plt.Rectangle((0, y - 0.5),
height=0.001,
width=self.end_time,
edgecolor='black',
facecolor='black')
plt.gca().add_patch(line)
# Axis
plt.axis([0, self.audio.duration_seconds, -0.5, len(self.active_events) + 0.5])
locs = numpy.arange(0, self.audio.duration_seconds, 0.00001)
plt.xlim([locs[0], locs[-1]])
plt.axis('tight')
# X axis
self.ax3.xaxis.grid(True, which='major')
self.ax3.xaxis.grid(True, which='minor')
plt.tick_params(axis='x', which='major', labelsize=self.event_roll_time_font_size)
# Y axis
plt.yticks(
numpy.arange(len(self.active_events)),
self.active_events,
fontsize=self.event_roll_label_font_size
)
plt.ylabel('Event Roll', fontsize=self.panel_title_font_size)
self.ax3.yaxis.set_label_position('right')
self.ax3.yaxis.grid(False, which='major')
self.ax3.yaxis.grid(False, which='minor')
# Set event list legends panel
self.ax3.set_xlim(self.begin_time, self.end_time)
if event_list_count > 1:
span = 0
for event_list_id, event_list_label in enumerate(self._event_list_order):
ax_legend_color = plt.axes([0.225+span, 0.02, 0.02, 0.02])
Button(
ax_legend_color,
'',
color=m.to_rgba(event_list_id),
hovercolor=m.to_rgba(event_list_id)
)
ax_legend_label = plt.axes([0.225+0.025+span, 0.02, 0.10, 0.04])
ax_legend_label.axis('off')
ax_legend_label.text(0, 0, event_list_label, fontsize=self.legend_font_size)
span += 0.15
if self.show_selector:
self.slider_time = SpanSelector(
ax=self.ax1,
onselect=self.on_select,
minspan=None,
direction='horizontal',
span_stays=True,
useblit=self.use_blit,
onmove_callback=None,
rectprops=dict(alpha=0.15, facecolor=self.color)
)
if not self.publication_mode:
ax_legend_label = plt.axes([0.92, 0.02, 0.10, 0.04])
ax_legend_label.axis('off')
ax_legend_label.text(0, 0, 'sed_vis', fontsize=16)
# Buttons
# ====================================
ax_play = plt.axes([0.125, 0.93, 0.07, 0.04])
ax_stop = plt.axes([0.205, 0.93, 0.07, 0.04])
ax_close = plt.axes([0.92, 0.93, 0.07, 0.04])
self.button_play = Button(
ax_play,
self.labels['play'],
color=self.button_color['off'],
hovercolor=self.button_color['on']
)
self.button_stop = Button(
ax_stop,
self.labels['stop'],
color=self.button_color['off'],
hovercolor=self.button_color['on']
)
self.button_close = Button(
ax_close,
self.labels['close'],
color=self.button_color['off'],
hovercolor=self.button_color['on']
)
self.button_play.on_clicked(self.on_play)
self.button_stop.on_clicked(self.on_stop)
self.button_close.on_clicked(self.on_close_window)
self.fig.canvas.mpl_connect('pick_event', self.on_pick)
else:
plt.subplots_adjust(left=0.12, bottom=0.05, right=.97, top=0.95, wspace=0, hspace=0)
if self.auto_play:
self.on_play(None)
def show(self):
"""Shows the visualizer.
Parameters
----------
Nothing
Returns
-------
Nothing
"""
self.generate_GUI()
plt.show()
def save(self, filename=None):
if filename:
self.generate_GUI()
plt.savefig(filename, bbox_inches='tight')
def on_close_window(self, event):
if self.audio.playing:
self.audio.stop()
self.audio = None
plt.close(self.fig)
def on_pick(self, event):
if isinstance(event.artist, Rectangle):
if self.audio.playing:
self.audio.stop() # Stop current playback
try:
self.event_panel_indicator_line.set_visible(False)
self.event_panel_indicator_line.remove()
except:
pass
if self.animation_event_roll_panel is not None:
self.animation_event_roll_panel._stop()
self.animation_event_roll_panel = None
try:
self.selector_panel_indicator_line.set_visible(False)
self.selector_panel_indicator_line.remove()
except:
pass
if self.animation_selector_panel is not None:
self.animation_selector_panel._stop()
self.animation_selector_panel = None
try:
self.highlight_panel_indicator_line.set_visible(False)
self.highlight_panel_indicator_line.remove()
except:
pass
if self.animation_highlight_panel is not None:
self.animation_highlight_panel._stop()
self.animation_highlight_panel = None
self.fig.canvas.draw()
time.sleep(0.25) # Wait until playback has stopped
self.playback_offset = event.artist.get_x()
self.audio.play(
offset=event.artist.get_x(),
duration=event.artist.get_width()
)
# Set up play indicators animations
self.animation_event_roll_panel = animation.FuncAnimation(
self.fig,
self.event_roll_panel_play_indicator_update,
init_func=self.event_roll_panel_play_indicator_init,
interval=10,
blit=self.use_blit,
repeat=False
)
self.animation_selector_panel = animation.FuncAnimation(
self.fig,
self.selector_panel_play_indicator_update,
init_func=self.selector_panel_play_indicator_init,
interval=10,
blit=self.use_blit,
repeat=False
)
self.animation_highlight_panel = animation.FuncAnimation(
self.fig,
self.highlight_panel_play_indicator_update,
init_func=self.highlight_panel_play_indicator_init,
interval=10,
blit=self.use_blit,
repeat=False
)
self.fig.canvas.draw()
def on_select(self, x_min, x_max):
x_min = int(x_min)
x_max = int(x_max)
if math.fabs(x_min-x_max) < 10:
# Reset highlight
self.begin_time = self.x[0] / float(self.audio.fs)
self.end_time = self.x[-1] / float(self.audio.fs)
if self.ax3:
self.ax3.set_xlim(self.begin_time, self.end_time)
# Set signal highlight panel
if self.mode == 'spectrogram':
self.ax2.set_xlim(0, self.D.shape[1])
elif self.mode == 'time_domain':
self.ax2.set_xlim(self.timedomain_locations[0], self.timedomain_locations[-1])
self.slider_time.stay_rect.set_visible(False)
else:
# Set annotation panel
self.begin_time = float(x_min) / self.audio.fs
self.end_time = float(x_max) / self.audio.fs
if self.ax3:
self.ax3.set_xlim(self.begin_time, self.end_time)
# Set signal highlight panel
if self.mode == 'spectrogram':
spec_min = int(x_min / float(self.spec_hop_size))
spec_max = int(x_max / float(self.spec_hop_size))
self.ax2.set_xlim(spec_min, spec_max)
elif self.mode == 'time_domain':
index_min, index_max = numpy.searchsorted(self.x, (x_min, x_max))
index_max = min(len(self.x) - 1, index_max)
this_x = self.timedomain_locations[index_min:index_max]
self.ax2.set_xlim(this_x[0], this_x[-1])
self.slider_time.stay_rect.set_visible(True)
self.fig.canvas.draw()
def on_play(self, event):
if self.audio.playing:
self.audio.stop() # Stop current playback
try:
self.event_panel_indicator_line.set_visible(False)
self.event_panel_indicator_line.remove()
except:
pass
if self.animation_event_roll_panel is not None:
self.animation_event_roll_panel._stop()
self.animation_event_roll_panel = None
try:
self.selector_panel_indicator_line.set_visible(False)
self.selector_panel_indicator_line.remove()
except:
pass
if self.animation_selector_panel is not None:
self.animation_selector_panel._stop()
self.animation_selector_panel = None
try:
self.highlight_panel_indicator_line.set_visible(False)
self.highlight_panel_indicator_line.remove()
except:
pass
if self.animation_highlight_panel is not None:
self.animation_highlight_panel._stop()
self.animation_highlight_panel = None
self.fig.canvas.draw()
time.sleep(0.25) # Wait until playback has stopped
self.audio.play(
offset=self.begin_time,
duration=self.end_time-self.begin_time
)
self.button_play.color = self.button_color['on']
self.button_play.hovercolor = self.button_color['on']
self.button_stop.color = self.button_color['off']
self.button_stop.hovercolor = self.button_color['off']
self.playback_offset = self.begin_time
self.animation_event_roll_panel = animation.FuncAnimation(
self.fig,
self.event_roll_panel_play_indicator_update,
init_func=self.event_roll_panel_play_indicator_init,
interval=50,
blit=self.use_blit,
repeat=False
)
self.animation_selector_panel = animation.FuncAnimation(
self.fig,
self.selector_panel_play_indicator_update,
init_func=self.selector_panel_play_indicator_init,
interval=50,
blit=self.use_blit,
repeat=False
)
self.animation_highlight_panel = animation.FuncAnimation(
self.fig,
self.highlight_panel_play_indicator_update,
init_func=self.highlight_panel_play_indicator_init,
interval=50,
blit=self.use_blit,
repeat=False
)
self.fig.canvas.draw()
def on_pause(self, event):
self.audio.pause()
self.button_play.color = self.button_color['off']
self.button_play.hovercolor = self.button_color['off']
self.button_stop.color = self.button_color['off']
self.button_stop.hovercolor = self.button_color['off']
self.fig.canvas.draw()
def on_stop(self, event):
self.audio.stop()
self.button_play.color = self.button_color['off']
self.button_play.hovercolor = self.button_color['off']
self.button_stop.color = self.button_color['off']
self.button_stop.hovercolor = self.button_color['off']
self.fig.canvas.draw()
def on_quit(self, event):
self._quit = True
self.on_close_window(event=event)
@property
def quit(self):
return self._quit
def event_roll_panel_play_indicator_init(self):
indicator_width = (self.end_time-self.begin_time) / 1000
if indicator_width > 0.5:
indicator_width = 0.5
self.event_panel_indicator_line = patches.Rectangle(
(self.playback_offset + self.audio.get_time(), -0.5),
height=self.event_label_count,
width=indicator_width,
edgecolor=self.indicator_line_color,
facecolor=self.indicator_line_color,
alpha=0.8
)
self.ax3.add_patch(self.event_panel_indicator_line)
return self.event_panel_indicator_line,
def event_roll_panel_play_indicator_update(self, i):
if self.audio.playing:
self.event_panel_indicator_line.set_x(self.playback_offset + self.audio.get_time())
else:
self.event_panel_indicator_line.set_visible(False)
if self.animation_event_roll_panel is not None:
self.animation_event_roll_panel.event_source.stop()
self.animation_event_roll_panel = None
self.fig.canvas.draw()
return self.event_panel_indicator_line,
def selector_panel_play_indicator_init(self):
self.selector_panel_indicator_line = patches.Rectangle(
(0, -1),
height=2,
width=0.5,
edgecolor=self.indicator_line_color,
facecolor=self.indicator_line_color,
alpha=0.8
)
self.ax1.add_patch(self.selector_panel_indicator_line)
return self.selector_panel_indicator_line,
def selector_panel_play_indicator_update(self, i):
if self.audio.playing:
self.selector_panel_indicator_line.set_x((self.playback_offset + self.audio.get_time())*self.audio.fs)
else:
self.selector_panel_indicator_line.set_visible(False)
if self.animation_selector_panel is not None:
self.animation_selector_panel.event_source.stop()
self.animation_selector_panel = None
return self.selector_panel_indicator_line,
def highlight_panel_play_indicator_init(self):
indicator_width = 0.5
if self.mode == 'spectrogram':
indicator_height = self.spec_fft_size
indicator_y = 0
elif self.mode == 'time_domain':
indicator_height = 2
indicator_y = -1
else:
indicator_height = 2
indicator_y = -1
self.highlight_panel_indicator_line = patches.Rectangle(
(0, indicator_y),
height=indicator_height,
width=indicator_width,
edgecolor=self.indicator_line_color,
facecolor=self.indicator_line_color,
alpha=0.8
)
self.ax2.add_patch(self.highlight_panel_indicator_line)
return self.highlight_panel_indicator_line,
def highlight_panel_play_indicator_update(self, i):
if self.audio.playing:
if self.mode == 'spectrogram':
self.highlight_panel_indicator_line.set_x(
(self.playback_offset + self.audio.get_time()) * self.audio.fs / float(self.spec_hop_size)
)
elif self.mode == 'time_domain':
self.highlight_panel_indicator_line.set_x(
(self.playback_offset + self.audio.get_time()) * self.audio.fs
)
else:
self.highlight_panel_indicator_line.set_visible(False)
if self.animation_highlight_panel is not None:
self.animation_highlight_panel.event_source.stop()
self.animation_highlight_panel = None
return self.highlight_panel_indicator_line,
def time_ticks(self, locations, n_ticks=10, sampling_rate=44100):
times = self.samples_to_time(locations, sampling_rate=sampling_rate)
positions = numpy.linspace(0, len(locations)-1, n_ticks, endpoint=True).astype(int)
locations = locations[positions]
times = times[positions]
times = ['{:0.2f}s'.format(t) for t in times]
return plt.xticks(locations, times)
@staticmethod
def time_to_samples(time, sampling_rate=44100):
return (numpy.atleast_1d(time) * sampling_rate).astype(int)
@staticmethod
def samples_to_time(samples, sampling_rate=44100):
return numpy.atleast_1d(samples) / float(sampling_rate)
@staticmethod
def get_spectrogram(audio, n_fft=256, win_length=1024, hop_length=1024):
fft_window = scipy.signal.hann(win_length, sym=False).reshape((-1, 1))
audio = numpy.pad(array=audio,
pad_width=int(n_fft // 2),
mode='reflect')
n_frames = 1 + int((len(audio) - n_fft) / hop_length)
y_frames = as_strided(x=audio,
shape=(n_fft, n_frames),
strides=(audio.itemsize, int(hop_length * audio.itemsize)))
S = numpy.empty((int(1 + n_fft // 2), y_frames.shape[1]), dtype=numpy.complex64, order='F')
max_memory_block = 2**8 * 2**10
n_columns = int(max_memory_block / (S.shape[0] * S.itemsize))
for bl_s in range(0, S.shape[1], n_columns):
bl_t = min(bl_s + n_columns, S.shape[1])
# RFFT and Conjugate here to match phase from DPWE code
S[:, bl_s:bl_t] = scipy.fftpack.fft(fft_window * y_frames[:, bl_s:bl_t], axis=0)[:S.shape[0]].conj()
magnitude = numpy.abs(S) ** 2
ref = numpy.max(magnitude)
amin=1e-10
top_db = 80.0
log_spec = 10.0 * numpy.log10(numpy.maximum(amin, magnitude))
log_spec -= 10.0 * numpy.log10(numpy.maximum(amin, ref))
log_spec = numpy.maximum(log_spec, log_spec.max() - top_db)
return log_spec
@staticmethod
def plot_spectrogram(data, sampling_rate=44100, n_yticks=5, interpolation='nearest', cmap='magma'):
axes = plt.imshow(data, aspect='auto', origin='lower', interpolation=interpolation, cmap=plt.get_cmap(cmap))
# X axis
plt.xticks([])
# Y axis
positions = numpy.linspace(0, data.shape[0]-1, n_yticks, endpoint=True).astype(int)
values = numpy.linspace(0, 0.5 * sampling_rate, data.shape[0], endpoint=True).astype(int)
t_log = (data.shape[0] * (1 - numpy.logspace(-numpy.log2(data.shape[0]), 0, data.shape[0], base=2, endpoint=True))[::-1]).astype(int)
t_inv = numpy.arange(len(t_log))
for i in range(len(t_log)-1):
t_inv[t_log[i]:t_log[i+1]] = i
plt.yticks(positions, values[t_inv[positions]])
return axes
class EventListVerifier(EventListVisualizer):
def __init__(self, *args, **kwargs):
super(EventListVerifier, self).__init__(*args, **kwargs)
self.verification_answer_id = None
self.verification_answer_value = None
self.verification_values = kwargs.get('verification_values', [
'A',
'B',
'C'
])
self.verification_button_colors = kwargs.get('verification_button_colors',[
{
'off': '#AAAAAA',
'on':'#b32400',
},
{
'off': '#AAAAAA',
'on': '#996600',
},
{
'off': '#AAAAAA',
'on': '#009933',
},
])
self.button_color = kwargs.get('button_color', {
'off': '#AAAAAA',
'on': '#666666'
})
self.button_verification = {}
self.button_verification_axis = {}
if self.buttons['verification']:
# Verification panel
# ====================================
self.selector_panel_loc = 20
self.highlight_panel_loc = 37
self.event_roll_panel_loc = 75
self.selector_panel_height = 10
self.highlight_panel_height = 35
self.event_roll_panel_height = 20
def generate_GUI(self):
"""Generates the visualizer GUI."""
self.fig = plt.figure(figsize=self.fig_shape)
# Selector panel
# ====================================
if self.show_selector:
self.ax1 = plt.subplot2grid(
shape=(100, 1),
loc=(self.selector_panel_loc, 0),
rowspan=self.selector_panel_height,
colspan=1
)
self.timedomain_locations = numpy.arange(0, self.audio.signal.shape[0])
self.ax1.fill_between(
self.timedomain_locations[::self.waveform_selector_point_hop],
self.audio.signal[::self.waveform_selector_point_hop],
-self.audio.signal[::self.waveform_selector_point_hop],
color='0.5'
)
plt.yticks([])
plt.axis('tight')
self.ax1.set_xlim(self.timedomain_locations[0], self.timedomain_locations[-1])
self.ax1.set_ylim(-1, 1)
self.time_ticks(
locations=self.timedomain_locations,
n_ticks=10,
sampling_rate=self.audio.fs
)
self.ax1.yaxis.grid(False, which='major')
self.ax1.yaxis.grid(False, which='minor')
self.ax1.xaxis.grid(True, which='major')
self.ax1.xaxis.grid(True, which='minor')
self.ax1.yaxis.set_label_position("right")
plt.title(self.labels['selection'], fontsize=self.panel_title_font_size)
# Highlight panel
# ====================================
self.ax2 = plt.subplot2grid(
shape=(100, 1),
loc=(self.highlight_panel_loc, 0),
rowspan=self.highlight_panel_height,
colspan=1
)
self.x = numpy.arange(0, self.audio.duration_samples)
self.begin_time = float(self.x[0]) / self.audio.fs
self.end_time = float(self.x[-1]) / self.audio.fs
if self.mode == 'spectrogram':
self.D = self.get_spectrogram(
audio=self.audio.signal,
n_fft=self.spec_fft_size,
win_length=self.spec_win_size,
hop_length=self.spec_hop_size
)
self.plot_spectrogram(
self.D,
sampling_rate=self.audio.fs,
interpolation=self.spec_interpolation,
cmap=self.spec_cmap
)
if not self.publication_mode:
self.ax2.yaxis.grid(False, which='major')
self.ax2.yaxis.grid(False, which='minor')
self.ax2.xaxis.grid(False, which='major')
self.ax2.xaxis.grid(False, which='minor')
plt.ylabel(self.labels['spectrogram'], fontsize=self.panel_title_font_size)
else:
self.ax2.get_yaxis().set_visible(False)
elif self.mode == 'time_domain':
self.ax2.fill_between(
self.x[::self.waveform_highlight_point_hop],
self.audio.signal[::self.waveform_highlight_point_hop],
-self.audio.signal[::self.waveform_highlight_point_hop],
color=self.waveform_highlight_color
)
self.ax2.set_ylim(-1, 1)
self.ax2.set_xlim(self.x[0], self.x[-1])
segment_begin = self.time_to_samples(time=0, sampling_rate=self.audio.fs)
segment_end = self.time_to_samples(time=self.audio.duration_seconds, sampling_rate=self.audio.fs)
locs = numpy.arange(segment_begin, segment_end)
plt.xlim([locs[0], locs[-1]])
self.time_ticks(locations=locs, n_ticks=20)
plt.yticks([])
plt.xticks([])
self.ax2.yaxis.grid(False, which='major')
self.ax2.yaxis.grid(False, which='minor')
self.ax2.xaxis.grid(True, which='major')
self.ax2.xaxis.grid(True, which='minor')
if not self.publication_mode:
plt.ylabel(self.labels['waveform'], fontsize=self.panel_title_font_size)
self.ax2.yaxis.set_label_position("right")
plt.axis('tight')
# Event roll panel
# ====================================
if self._event_lists:
event_list_count = len(self._event_lists)
self.begin_time = 0
self.end_time = self.audio.duration_seconds
if event_list_count == 1:
norm = colors.Normalize(
vmin=0,
vmax=self.event_label_count
)
self.ax3 = plt.subplot2grid(
shape=(100, 1),
loc=(self.event_roll_panel_loc, 0),
rowspan=self.event_roll_panel_height+10,
colspan=1
)
else:
norm = colors.Normalize(
vmin=0,
vmax=event_list_count
)
self.ax3 = plt.subplot2grid(
shape=(100, 1),
loc=(self.event_roll_panel_loc, 0),
rowspan=self.event_roll_panel_height,
colspan=1
)
m = cm.ScalarMappable(
norm=norm,
cmap=self.label_colormap
)
line_margin = 0.1
y = 0
annotation_height = (1.0-line_margin*2)/event_list_count
for label in self.active_events:
for event_list_id, event_list_label in enumerate(self._event_list_order):
offset = (len(self._event_list_order)-1-event_list_id) * annotation_height
event_y = y - 0.5 + line_margin + offset
# grid line
line = plt.Rectangle(
(0, y-0.5),
height=0.001,
width=self.end_time,
edgecolor='black',
facecolor='black'
)
plt.gca().add_patch(line)
for event in self._event_lists[event_list_label]:
if event['event_label'] == label:
event_length = event['offset'] - event['onset']
if event_list_count == 1:
color = m.to_rgba(y + offset)
else:
color = m.to_rgba(event_list_id)
rectangle = plt.Rectangle(
(event['onset'], event_y),
height=annotation_height,
width=event_length,
edgecolor='black',
facecolor=color,
linewidth=0,
alpha=self.event_roll_item_opacity,
picker=5
)
plt.gca().add_patch(rectangle)
y += 1
# Grid line
line = plt.Rectangle(
(0, y - 0.5),
height=0.001,
width=self.end_time,
edgecolor='black',
facecolor='black'
)
plt.gca().add_patch(line)
# Axis
plt.axis([0, self.audio.duration_seconds, -0.5, len(self.active_events) + 0.5])
locs = numpy.arange(0, self.audio.duration_seconds, 0.00001)
plt.xlim([locs[0], locs[-1]])
plt.axis('tight')
# X axis
self.ax3.xaxis.grid(True, which='major')
self.ax3.xaxis.grid(True, which='minor')
plt.tick_params(
axis='x',
which='major',
labelsize=self.event_roll_time_font_size
)
# Y axis
plt.yticks(
numpy.arange(len(self.active_events)),
self.active_events,
fontsize=self.event_roll_label_font_size
)
plt.ylabel('Event Roll', fontsize=self.panel_title_font_size)
self.ax3.yaxis.set_label_position('right')
self.ax3.yaxis.grid(False, which='major')
self.ax3.yaxis.grid(False, which='minor')
# Set event list legends panel
self.ax3.set_xlim(self.begin_time, self.end_time)
if event_list_count > 1:
span = 0
for event_list_id, event_list_label in enumerate(self._event_list_order):
ax_legend_color = plt.axes([0.225+span, 0.02, 0.02, 0.02])
Button(
ax_legend_color,
'',
color=m.to_rgba(event_list_id),
hovercolor=m.to_rgba(event_list_id)
)
ax_legend_label = plt.axes([0.225+0.025+span, 0.02, 0.10, 0.04])
ax_legend_label.axis('off')
ax_legend_label.text(0, 0, event_list_label, fontsize=self.legend_font_size)
span += 0.15
if self.show_selector:
self.slider_time = SpanSelector(
ax=self.ax1,
onselect=self.on_select,
minspan=None,
direction='horizontal',
span_stays=True,
useblit=self.use_blit,
onmove_callback=None,
rectprops=dict(alpha=0.15, facecolor=self.color)
)
if not self.publication_mode:
ax_legend_label = plt.axes([0.92, 0.02, 0.10, 0.04])
ax_legend_label.axis('off')
ax_legend_label.text(0, 0, 'sed_vis', fontsize=16)
# Buttons
# ====================================
if self.buttons['play']:
ax_play = plt.axes([0.125, 0.93, 0.07, 0.04])
self.button_play = Button(
ax_play,
self.labels['play'],
color=self.button_color['off'],
hovercolor=self.button_color['on']
)
self.button_play.on_clicked(self.on_play)
if self.buttons['stop']:
ax_stop = plt.axes([0.205, 0.93, 0.07, 0.04])
self.button_stop = Button(
ax_stop,
self.labels['stop'],
color=self.button_color['off'],
hovercolor=self.button_color['on']
)
self.button_stop.on_clicked(self.on_stop)
if self.buttons['close']:
ax_close = plt.axes([0.92, 0.93, 0.07, 0.04])
self.button_close = Button(
ax_close,
self.labels['close'],
color=self.button_color['off'],
hovercolor=self.button_color['on']
)
self.button_close.on_clicked(self.on_close_window)
if self.buttons['quit']:
ax_quit = plt.axes([0.78, 0.93, 0.07, 0.04])
self.button_quit = Button(
ax_quit,
self.labels['quit'],
color=self.button_color['off'],
hovercolor=self.button_color['on']
)
self.button_quit.on_clicked(self.on_quit)
if self.buttons['verification']:
start_x = 0.125 + 0.2 #25
end_x = 0.125+0.775 -0.2 #1 - start_x
width = (end_x - start_x)
spacing = width / float(len(self.verification_values))
# Verification text
plt.axes([0.125, 0.88, 0.775, 0.04], frameon=False)
plt.xticks([])
plt.yticks([])
plt.text(
0.5, 0.5,
self.labels['verification'],
fontsize=14,
horizontalalignment='center',
verticalalignment='center'
)
# Verification-info text
plt.axes([0.00, 0.80, 0.125 + 0.18, 0.08], frameon=False)
plt.xticks([])
plt.yticks([])
plt.text(
1, 0.5,
self.labels['verification_info'],
fontsize=18,
horizontalalignment='right',
verticalalignment='center'
)
for i, label in enumerate(self.verification_values):
self.button_verification_axis[i] = plt.axes([start_x+(i*spacing), 0.80, 0.12, 0.08])
self.button_verification[i] = Button(
self.button_verification_axis[i],
label,
color=self.verification_button_colors[i]['off'],
hovercolor=self.verification_button_colors[i]['off']
)
self.button_verification[i].label.set_fontsize(12)
self.button_verification[i].on_clicked(self.on_verification)
# Info text
plt.axes([start_x, 0.02, width, 0.04], frameon=False)
plt.xticks([])
plt.yticks([])
plt.text(0.5, 0.5,
self.labels['info'],
fontsize=12,
horizontalalignment='center',
verticalalignment='center'
)
self.fig.canvas.mpl_connect('pick_event', self.on_pick)
else:
plt.subplots_adjust(
left=0.12,
bottom=0.05,
right=.97,
top=0.95,
wspace=0,
hspace=0
)
if self.auto_play:
self.on_play(None)
def on_verification(self, event):
for i in self.button_verification:
if event.inaxes == self.button_verification_axis[i]:
self.button_verification[i].color = self.verification_button_colors[i]['on']
self.button_verification[i].hovercolor = self.verification_button_colors[i]['on']
self.verification_answer_id =i
self.verification_answer_value = self.verification_values[i]
else:
self.button_verification[i].color = self.verification_button_colors[i]['off']
self.button_verification[i].hovercolor = self.verification_button_colors[i]['off']
def get_answer(self):
return self.verification_answer_id, self.verification_answer_value
|
// Copyright (c) WarnerMedia Direct, LLC. All rights reserved. Licensed under the MIT license.
// See the LICENSE file for license information.
//
// Copyright 2012-2015, Yahoo Inc.
// Copyrights licensed under the New BSD License. See the accompanying ThirdPartyNotices.txt file for terms.
const coverage = require('istanbul-lib-coverage');
const { BaseNode, BaseTree } = require('./tree');
const Path = require('./path');
class ReportNode extends BaseNode {
constructor(path, fileCoverage) {
super();
this.path = path;
this.parent = null;
this.fileCoverage = fileCoverage;
this.children = [];
}
static createRoot(children) {
const root = new ReportNode(new Path([]));
children.forEach(child => {
root.addChild(child);
});
return root;
}
addChild(child) {
child.parent = this;
this.children.push(child);
}
asRelative(p) {
if (p.substring(0, 1) === '/') {
return p.substring(1);
}
return p;
}
getQualifiedName() {
return this.asRelative(this.path.toString());
}
getRelativeName() {
const parent = this.getParent();
const myPath = this.path;
let relPath;
let i;
const parentPath = parent ? parent.path : new Path([]);
if (parentPath.ancestorOf(myPath)) {
relPath = new Path(myPath.elements());
for (i = 0; i < parentPath.length; i += 1) {
relPath.shift();
}
return this.asRelative(relPath.toString());
}
return this.asRelative(this.path.toString());
}
getParent() {
return this.parent;
}
getChildren() {
return this.children;
}
isSummary() {
return !this.fileCoverage;
}
getFileCoverage() {
return this.fileCoverage;
}
getCoverageSummary(filesOnly) {
const cacheProp = `c_${filesOnly ? 'files' : 'full'}`;
let summary;
if (Object.prototype.hasOwnProperty.call(this, cacheProp)) {
return this[cacheProp];
}
if (!this.isSummary()) {
summary = this.getFileCoverage().toSummary();
} else {
let count = 0;
summary = coverage.createCoverageSummary();
this.getChildren().forEach(child => {
if (filesOnly && child.isSummary()) {
return;
}
count += 1;
summary.merge(child.getCoverageSummary(filesOnly));
});
if (count === 0 && filesOnly) {
summary = null;
}
}
this[cacheProp] = summary;
return summary;
}
}
class ReportTree extends BaseTree {
constructor(root, childPrefix) {
super(root);
const maybePrefix = node => {
if (childPrefix && !node.isRoot()) {
node.path.unshift(childPrefix);
}
};
this.visit({
onDetail: maybePrefix,
onSummary(node) {
maybePrefix(node);
node.children.sort((a, b) => {
const astr = a.path.toString();
const bstr = b.path.toString();
return astr < bstr
? -1
: astr > bstr
? 1
: /* istanbul ignore next */ 0;
});
}
});
}
}
function findOrCreateParent(parentPath, nodeMap, created = () => {}) {
let parent = nodeMap[parentPath.toString()];
if (!parent) {
parent = new ReportNode(parentPath);
nodeMap[parentPath.toString()] = parent;
created(parentPath, parent);
}
return parent;
}
module.exports = {
ReportNode,
ReportTree,
findOrCreateParent
};
|
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth import (
login as django_login,
logout as django_logout
)
from django.core.exceptions import ObjectDoesNotExist
from django.utils.decorators import method_decorator
from django.utils.translation import ugettext_lazy as _
from django.views.decorators.debug import sensitive_post_parameters
from rest_framework import status
from rest_framework.generics import GenericAPIView, RetrieveUpdateAPIView
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.response import Response
from rest_framework.views import APIView
from .app_settings import (
TokenSerializer, UserDetailsSerializer, LoginSerializer,
PasswordResetSerializer, PasswordResetConfirmSerializer,
PasswordChangeSerializer, JWTSerializer, create_token
)
from .models import TokenModel
from .utils import jwt_encode
sensitive_post_parameters_m = method_decorator(
sensitive_post_parameters(
'password', 'old_password', 'new_password1', 'new_password2'
)
)
class LoginView(GenericAPIView):
"""
Check the credentials and return the REST Token
if the credentials are valid and authenticated.
Calls Django Auth login method to register User ID
in Django session framework
Accept the following POST parameters: username, password
Return the REST Framework Token Object's key.
"""
permission_classes = (AllowAny,)
serializer_class = LoginSerializer
token_model = TokenModel
@sensitive_post_parameters_m
def dispatch(self, *args, **kwargs):
return super(LoginView, self).dispatch(*args, **kwargs)
def process_login(self):
django_login(self.request, self.user)
def get_response_serializer(self):
if getattr(settings, 'REST_USE_JWT', False):
response_serializer = JWTSerializer
else:
response_serializer = TokenSerializer
return response_serializer
def login(self):
self.user = self.serializer.validated_data['user']
if getattr(settings, 'REST_USE_JWT', False):
self.token = jwt_encode(self.user)
else:
self.token = create_token(self.token_model, self.user,
self.serializer)
if getattr(settings, 'REST_SESSION_LOGIN', True):
self.process_login()
def get_response(self):
serializer_class = self.get_response_serializer()
if getattr(settings, 'REST_USE_JWT', False):
data = {
'user': self.user,
'token': self.token
}
serializer = serializer_class(instance=data,
context={'request': self.request})
else:
serializer = serializer_class(instance=self.token,
context={'request': self.request})
response = Response(serializer.data, status=status.HTTP_200_OK)
if getattr(settings, 'REST_USE_JWT', False):
from rest_framework_jwt.settings import api_settings as jwt_settings
if jwt_settings.JWT_AUTH_COOKIE:
from datetime import datetime
expiration = (datetime.utcnow() + jwt_settings.JWT_EXPIRATION_DELTA)
response.set_cookie(jwt_settings.JWT_AUTH_COOKIE,
self.token,
expires=expiration,
httponly=True)
return response
def post(self, request, *args, **kwargs):
self.request = request
self.serializer = self.get_serializer(data=self.request.data,
context={'request': request})
self.serializer.is_valid(raise_exception=True)
self.login()
return self.get_response()
class LogoutView(APIView):
"""
Calls Django logout method and delete the Token object
assigned to the current User object.
Accepts/Returns nothing.
"""
permission_classes = (AllowAny,)
def get(self, request, *args, **kwargs):
if getattr(settings, 'ACCOUNT_LOGOUT_ON_GET', False):
response = self.logout(request)
else:
response = self.http_method_not_allowed(request, *args, **kwargs)
return self.finalize_response(request, response, *args, **kwargs)
def post(self, request, *args, **kwargs):
return self.logout(request)
def logout(self, request):
try:
request.user.auth_token.delete()
except (AttributeError, ObjectDoesNotExist):
pass
if getattr(settings, 'REST_SESSION_LOGIN', True):
django_logout(request)
response = Response({"detail": _("Successfully logged out.")},
status=status.HTTP_200_OK)
if getattr(settings, 'REST_USE_JWT', False):
from rest_framework_jwt.settings import api_settings as jwt_settings
if jwt_settings.JWT_AUTH_COOKIE:
response.delete_cookie(jwt_settings.JWT_AUTH_COOKIE)
return response
class UserDetailsView(RetrieveUpdateAPIView):
"""
Reads and updates UserModel fields
Accepts GET, PUT, PATCH methods.
Default accepted fields: username, first_name, last_name
Default display fields: pk, username, email, first_name, last_name
Read-only fields: pk, email
Returns UserModel fields.
"""
serializer_class = UserDetailsSerializer
permission_classes = (IsAuthenticated,)
def get_object(self):
return self.request.user
def get_queryset(self):
"""
Adding this method since it is sometimes called when using
django-rest-swagger
https://github.com/Tivix/django-rest-auth/issues/275
"""
return get_user_model().objects.none()
class PasswordResetView(GenericAPIView):
"""
Calls Django Auth PasswordResetForm save method.
Accepts the following POST parameters: email
Returns the success/fail message.
"""
serializer_class = PasswordResetSerializer
permission_classes = (AllowAny,)
def post(self, request, *args, **kwargs):
# Create a serializer with request.data
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
# Return the success message with OK HTTP status
return Response(
{"detail": _("Password reset e-mail has been sent.")},
status=status.HTTP_200_OK
)
class PasswordResetConfirmView(GenericAPIView):
"""
Password reset e-mail link is confirmed, therefore
this resets the user's password.
Accepts the following POST parameters: token, uid,
new_password1, new_password2
Returns the success/fail message.
"""
serializer_class = PasswordResetConfirmSerializer
permission_classes = (AllowAny,)
@sensitive_post_parameters_m
def dispatch(self, *args, **kwargs):
return super(PasswordResetConfirmView, self).dispatch(*args, **kwargs)
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(
{"detail": _("Password has been reset with the new password.")}
)
class PasswordChangeView(GenericAPIView):
"""
Calls Django Auth SetPasswordForm save method.
Accepts the following POST parameters: new_password1, new_password2
Returns the success/fail message.
"""
serializer_class = PasswordChangeSerializer
permission_classes = (IsAuthenticated,)
@sensitive_post_parameters_m
def dispatch(self, *args, **kwargs):
return super(PasswordChangeView, self).dispatch(*args, **kwargs)
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response({"detail": _("New password has been saved.")})
|
from floodsystem.stationdata import build_station_list
import floodsystem.geo as geo
from floodsystem.station import MonitoringStation
from haversine import haversine, Unit
def test_stations_by_distance():
stations = build_station_list()
centre=(0,0)
StationDistance = geo.stations_by_distance(stations, centre)
assert len(StationDistance) >0 #ensures that the distances are being added to the list
for i in range (1, len(StationDistance)):
assert StationDistance[i][2] >= StationDistance[i-1][2] # As the fucntion requires the stations to be sorted from clostest to furthers, this test for every value that the ditnace in the next tuple is greater than the one before
def test_stations_within_radius():
s_id = "test-s-id"
m_id = "test-m-id"
label = "some station"
coord = (-2.0, 4.0)
trange = (-2.3, 3.4445)
river = "River X"
town = "My Town"
s = MonitoringStation(s_id, m_id, label, coord, trange, river, town)
coord = (5.0,5.0)
s1 = MonitoringStation(s_id, m_id, label, coord, trange, river, town)
coord = (10.0,10.0)
s2 = MonitoringStation(s_id, m_id, label, coord, trange, river, town)
coord = (180,0.0)
s3 = MonitoringStation(s_id, m_id, label, coord, trange, river, town)
centre = (0.0,0.0)
#Created 4 different stations with different distnaces, station S3 is built out of range of the radius to ensure on the stations within the radius r is added to the list, therefore only 3 stations should be in the list
stations = [s,s1,s2,s3]
r = haversine(centre, s2.coord, Unit.KILOMETERS) + 1
WithinRadius = geo.stations_within_radius(stations, centre, r)
assert len(WithinRadius) > 0
assert len(WithinRadius) == 3
def test_river_with_station():
s_id = "test-s-id"
m_id = "test-m-id"
label = "some station"
coord = (-2.0, 4.0)
trange = (-2.3, 3.4445)
river = "River X"
town = "My Town"
s = MonitoringStation(s_id, m_id, label, coord, trange, river, town)
river = "River Aire"
s1 = MonitoringStation(s_id, m_id, label, coord, trange, river, town)
river = "River Thames"
s2 = MonitoringStation(s_id, m_id, label, coord, trange, river, town)
stations = [s,s1,s2]
rivers = geo.rivers_with_stations(stations)
#Created a fake station list and checked if a river with a sation exits, the total length of the rivers with station is corresponding to the stations list and then whether the rivers exist in that list
assert river is not None
assert len(rivers) == 3
assert "River Aire" in rivers
assert "River Thames" in rivers
def test_stations_by_river():
s_id = "test-s-id"
m_id = "test-m-id"
label = "Station1"
coord = (-2.0, 4.0)
trange = (-2.3, 3.4445)
river = "River X"
town = "My Town"
s = MonitoringStation(s_id, m_id, label, coord, trange, river, town)
label = "Station2"
s1 = MonitoringStation(s_id, m_id, label, coord, trange, river, town)
label = "Station3"
s2 = MonitoringStation(s_id, m_id, label, coord, trange, river, town)
label = "Station4"
s3 = MonitoringStation(s_id, m_id, label, coord, trange, river, town)
#Produced 4 stations that are allocted to one river, the function should add on 4 stations to the key - River X and the thus the length ofthe value to the key is 4
stations = [s,s1,s2,s3]
SBR = geo.stations_by_river(stations)
assert len(SBR["River X"]) == 4
def test_rivers_by_station_number():
stations = build_station_list()
N = 3
result = geo.rivers_by_station_number(stations, N)
#using the database for the stations and N as 3 the lsit should have the top 4 rivers with the most stations
assert len(result) == 4
for i in range(1, len(result)):
assert result[i][1] <= result[i-1][1]
assert result[0][0] == "River Thames"
#speciffically asserted river thames as its has the highest numbe rof stations and have signifcanlt more than any other station
#so it can be used a reliable river to test whether the list is sorted is descending order
|
# 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.
import tvm
def nop():
return tvm.stmt.Evaluate(0)
def test_remove_no_op():
i = tvm.var('i')
j = tvm.var('j')
k = tvm.var('k')
m = tvm.var('m')
n = tvm.var('n')
dtype = 'int64'
Ab = tvm.decl_buffer((n, ), dtype)
stmt = tvm.make.For(
i, 0, 4, 0, 0,
tvm.make.For(
j, 0, n, 0, 0,
tvm.make.For(
k, 0, m, 0, 0,
tvm.make.IfThenElse(
(i*m+j+k < n), tvm.make.Evaluate(m), tvm.make.Evaluate(n)))))
ret = tvm.ir_pass.RemoveNoOp(stmt)
assert(isinstance(ret, tvm.stmt.Evaluate))
store = tvm.make.Store(Ab.data,
tvm.make.Load(dtype, Ab.data, i) + 1,
i + 1)
stmt2 = tvm.stmt.SeqStmt([nop(), tvm.stmt.SeqStmt([store, nop()])])
assert(tvm.ir_pass.RemoveNoOp(stmt2) == store)
# remove zero extent loop
stmt3 = tvm.make.For(i, 0, 0, 0, 0, store)
ret = tvm.ir_pass.RemoveNoOp(stmt3)
assert(isinstance(ret, tvm.stmt.Evaluate))
if __name__ == "__main__":
test_remove_no_op()
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M7 5h10v14H7z",
opacity: ".3"
}, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M17 1.01 7 1c-1.1 0-1.99.9-1.99 2v18c0 1.1.89 2 1.99 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-1.99-2-1.99zM17 19H7V5h10v14z"
}, "1")], 'StayPrimaryPortraitTwoTone');
exports.default = _default;
|
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
mode: process.env.NODE_ENV,
entry: {
index: './lib/index.tsx'
},
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx']
},
output: {
path: path.resolve(__dirname, 'dist/lib'),
library: 'FUI',
libraryTarget: 'umd',
},
module: {
rules: [
{
test: /\.tsx?$/,
loader: 'awesome-typescript-loader'
},
{
test: /\.svg$/,
loader: 'svg-sprite-loader'
},
{
test: /\.scss$/,
use: ['style-loader', 'css-loader', 'sass-loader']
},
{
test: /\.(png|jpg|jpeg|gif)$/,
use: ['file-loader']
}
]
},
}
|
const bleno = require('@abandonware/bleno')
class HeartrateCharacteristic extends bleno.Characteristic {
constructor() {
super({
uuid: '2A37',
properties: ['read', 'notify'],
})
this.buffer = Buffer.alloc(2, 0)
}
update(heartRate) {
this.buffer[1] = heartRate
}
onReadRequest(offset, callback) {
console.log('bleno: HeartrateCharacteristic readRequest')
if (offset) {
callback(this.RESULT_ATTR_NOT_LONG, null)
} else {
callback(this.RESULT_SUCCESS, this.buffer)
}
}
onSubscribe(maxValueSize, updateValueCallback) {
console.log('bleno: HeartrateCharacteristic subscribe')
this.notifyInterval = setInterval(function () {
console.log('bleno: HeartrateCharacteristic update')
updateValueCallback(this.buffer)
}.bind(this), 1000)
}
onUnsubscribe() {
console.log('bleno: HeartrateCharacteristic unsubscribe')
if (this.notifyInterval) {
clearInterval(this.notifyInterval)
this.notifyInterval = null
}
}
}
module.exports = HeartrateCharacteristic
|
var Clay = require('pebble-clay');
var clayConfig = require('./config');
var clay = new Clay(clayConfig);
/*Pebble.addEventListener('ready', function() {
console.log('PebbleKit JS ready!');
});
Pebble.addEventListener('showConfiguration', function() {
var url = 'https://torerikk.github.io/simple_analog_pebbleface/config/index.html';
Pebble.openURL(url);
});
Pebble.addEventListener('webviewclosed', function(e) {
var configData = JSON.parse(decodeURIComponent(e.response));
console.log('Configuration page returned: ' + JSON.stringify(configData));
if (configData.backgroundColor) {
Pebble.sendAppMessage({
backgroundColor: parseInt(configData.backgroundColor, 16),
clockfaceColor: parseInt(configData.clockfaceColor, 16),
clockStrokeColor: parseInt(configData.clockStrokeColor, 16),
disconnectWarning: configData.disconnectWarning
}, function() {
console.log('Send successful!');
}, function() {
console.log('Send failed!');
});
}
});*/
|
# Copyright 2021 StreamSets Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest
import string
import logging
import json
from datetime import datetime, timedelta
from streamsets.testframework.decorators import stub
from streamsets.testframework.utils import get_random_string
from streamsets.testframework.markers import sdc_min_version
logger = logging.getLogger(__name__)
@stub
@pytest.mark.parametrize('stage_attributes', [{'avro_compression_codec': 'BZIP2', 'data_format': 'AVRO'},
{'avro_compression_codec': 'DEFLATE', 'data_format': 'AVRO'},
{'avro_compression_codec': 'NULL', 'data_format': 'AVRO'},
{'avro_compression_codec': 'SNAPPY', 'data_format': 'AVRO'}])
def test_avro_compression_codec(sdc_builder, sdc_executor, stage_attributes):
pass
@stub
@pytest.mark.parametrize('stage_attributes', [{'avro_schema_location': 'INLINE', 'data_format': 'AVRO'}])
def test_avro_schema(sdc_builder, sdc_executor, stage_attributes):
pass
@stub
@pytest.mark.parametrize('stage_attributes', [{'avro_schema_location': 'HEADER', 'data_format': 'AVRO'},
{'avro_schema_location': 'INLINE', 'data_format': 'AVRO'},
{'avro_schema_location': 'REGISTRY', 'data_format': 'AVRO'}])
def test_avro_schema_location(sdc_builder, sdc_executor, stage_attributes):
pass
@stub
@pytest.mark.parametrize('stage_attributes', [{'data_format': 'BINARY'}])
def test_binary_field_path(sdc_builder, sdc_executor, stage_attributes):
pass
@stub
def test_charset(sdc_builder, sdc_executor):
pass
@stub
@pytest.mark.parametrize('stage_attributes', [{'checksum_algorithm': 'MD5',
'data_format': 'WHOLE_FILE',
'include_checksum_in_events': True},
{'checksum_algorithm': 'MURMUR3_128',
'data_format': 'WHOLE_FILE',
'include_checksum_in_events': True},
{'checksum_algorithm': 'MURMUR3_32',
'data_format': 'WHOLE_FILE',
'include_checksum_in_events': True},
{'checksum_algorithm': 'SHA1',
'data_format': 'WHOLE_FILE',
'include_checksum_in_events': True},
{'checksum_algorithm': 'SHA256',
'data_format': 'WHOLE_FILE',
'include_checksum_in_events': True},
{'checksum_algorithm': 'SHA512',
'data_format': 'WHOLE_FILE',
'include_checksum_in_events': True}])
def test_checksum_algorithm(sdc_builder, sdc_executor, stage_attributes):
pass
@stub
@pytest.mark.parametrize('stage_attributes', [{'compression_codec': 'BZIP2', 'file_type': 'SEQUENCE_FILE'},
{'compression_codec': 'GZIP', 'file_type': 'SEQUENCE_FILE'},
{'compression_codec': 'LZ4', 'file_type': 'SEQUENCE_FILE'},
{'compression_codec': 'NONE', 'file_type': 'SEQUENCE_FILE'},
{'compression_codec': 'OTHER', 'file_type': 'SEQUENCE_FILE'},
{'compression_codec': 'SNAPPY', 'file_type': 'SEQUENCE_FILE'},
{'compression_codec': 'BZIP2', 'file_type': 'TEXT'},
{'compression_codec': 'GZIP', 'file_type': 'TEXT'},
{'compression_codec': 'LZ4', 'file_type': 'TEXT'},
{'compression_codec': 'NONE', 'file_type': 'TEXT'},
{'compression_codec': 'OTHER', 'file_type': 'TEXT'},
{'compression_codec': 'SNAPPY', 'file_type': 'TEXT'}])
def test_compression_codec(sdc_builder, sdc_executor, stage_attributes):
pass
@stub
@pytest.mark.parametrize('stage_attributes', [{'compression_codec': 'OTHER', 'file_type': 'SEQUENCE_FILE'},
{'compression_codec': 'OTHER', 'file_type': 'TEXT'}])
def test_compression_codec_class(sdc_builder, sdc_executor, stage_attributes):
pass
@stub
@pytest.mark.parametrize('stage_attributes', [{'data_format': 'AVRO'},
{'data_format': 'BINARY'},
{'data_format': 'DELIMITED'},
{'data_format': 'JSON'},
{'data_format': 'PROTOBUF'},
{'data_format': 'SDC_JSON'},
{'data_format': 'TEXT'},
{'data_format': 'WHOLE_FILE'}])
def test_data_format(sdc_builder, sdc_executor, stage_attributes):
pass
@stub
def test_data_time_zone(sdc_builder, sdc_executor):
pass
@stub
@pytest.mark.parametrize('stage_attributes', [{'data_format': 'DELIMITED', 'delimiter_format': 'CUSTOM'}])
def test_delimiter_character(sdc_builder, sdc_executor, stage_attributes):
pass
@stub
@pytest.mark.parametrize('stage_attributes', [{'data_format': 'DELIMITED', 'delimiter_format': 'CSV'},
{'data_format': 'DELIMITED', 'delimiter_format': 'CUSTOM'},
{'data_format': 'DELIMITED', 'delimiter_format': 'EXCEL'},
{'data_format': 'DELIMITED', 'delimiter_format': 'MULTI_CHARACTER'},
{'data_format': 'DELIMITED', 'delimiter_format': 'MYSQL'},
{'data_format': 'DELIMITED', 'delimiter_format': 'POSTGRES_CSV'},
{'data_format': 'DELIMITED', 'delimiter_format': 'POSTGRES_TEXT'},
{'data_format': 'DELIMITED', 'delimiter_format': 'RFC4180'},
{'data_format': 'DELIMITED', 'delimiter_format': 'TDF'}])
def test_delimiter_format(sdc_builder, sdc_executor, stage_attributes):
pass
@stub
@pytest.mark.parametrize('stage_attributes', [{'directory_in_header': False}, {'directory_in_header': True}])
def test_directory_in_header(sdc_builder, sdc_executor, stage_attributes):
pass
@sdc_min_version('4.0.0')
def test_directory_template(sdc_builder, sdc_executor):
"""Test Directory Template. Two pipelines are started, each one generating a _tmp_sdc file. Their paths are similar
but use different parameters. While they are running, we check that starting the second pipeline did not rename the
_tmp_sdc file of the first pipeline.
The pipelines look like:
dev_data_generator >> local_fs
"""
# Create first pipeline
tmp_directory_1 = '/tmp/out/${directory1}'
pipeline_builder = sdc_builder.get_pipeline_builder()
dev_data_generator = pipeline_builder.add_stage('Dev Data Generator')
local_fs = pipeline_builder.add_stage('Local FS', type='destination')
local_fs.set_attributes(directory_template=tmp_directory_1,
data_format='JSON')
dev_data_generator >> local_fs
pipeline1 = pipeline_builder.build().configure_for_environment()
pipeline1.add_parameters(directory1='test1')
sdc_executor.add_pipeline(pipeline1)
# Create second pipeline
tmp_directory_2 = '/tmp/out/${directory2}'
pipeline_builder = sdc_builder.get_pipeline_builder()
dev_data_generator = pipeline_builder.add_stage('Dev Data Generator')
local_fs = pipeline_builder.add_stage('Local FS', type='destination')
local_fs.set_attributes(directory_template=tmp_directory_2,
data_format='JSON')
dev_data_generator >> local_fs
pipeline2 = pipeline_builder.build().configure_for_environment()
pipeline2.add_parameters(directory2='test2')
sdc_executor.add_pipeline(pipeline2)
try:
sdc_executor.start_pipeline(pipeline1).wait_for_pipeline_batch_count(5)
sdc_executor.start_pipeline(pipeline2).wait_for_pipeline_batch_count(5)
final_tmp_directory_1 = '/tmp/out/test1'
final_tmp_directory_2 = '/tmp/out/test2'
num_tmp_files_1 = int(sdc_executor.execute_shell(f'ls {final_tmp_directory_1} | grep _tmp_ | wc -l').stdout)
num_tmp_files_2 = int(sdc_executor.execute_shell(f'ls {final_tmp_directory_2} | grep _tmp_ | wc -l').stdout)
assert num_tmp_files_1 == 1
assert num_tmp_files_2 == 1
finally:
sdc_executor.stop_pipeline(pipeline1)
sdc_executor.stop_pipeline(pipeline2)
logger.info('Deleting files created by Local FS in %s ...', tmp_directory_1)
sdc_executor.execute_shell(f'rm -R {tmp_directory_1} ')
logger.info('Deleting files created by Local FS in %s ...', tmp_directory_2)
sdc_executor.execute_shell(f'rm -R {tmp_directory_2} ')
@stub
@pytest.mark.parametrize('stage_attributes', [{'data_format': 'DELIMITED', 'delimiter_format': 'CUSTOM'}])
def test_escape_character(sdc_builder, sdc_executor, stage_attributes):
pass
@stub
@pytest.mark.parametrize('stage_attributes', [{'data_format': 'WHOLE_FILE', 'file_exists': 'OVERWRITE'},
{'data_format': 'WHOLE_FILE', 'file_exists': 'TO_ERROR'}])
def test_file_exists(sdc_builder, sdc_executor, stage_attributes):
pass
@stub
@pytest.mark.parametrize('stage_attributes', [{'data_format': 'WHOLE_FILE'}])
def test_file_name_expression(sdc_builder, sdc_executor, stage_attributes):
pass
@stub
@pytest.mark.parametrize('stage_attributes', [{'file_type': 'SEQUENCE_FILE'},
{'file_type': 'TEXT'},
{'file_type': 'WHOLE_FILE'}])
def test_file_type(sdc_builder, sdc_executor, stage_attributes):
pass
@stub
def test_files_prefix(sdc_builder, sdc_executor):
pass
@stub
@pytest.mark.parametrize('stage_attributes', [{'file_type': 'SEQUENCE_FILE'}, {'file_type': 'TEXT'}])
def test_files_suffix(sdc_builder, sdc_executor, stage_attributes):
pass
@stub
@pytest.mark.parametrize('stage_attributes', [{'data_format': 'DELIMITED', 'header_line': 'IGNORE_HEADER'},
{'data_format': 'DELIMITED', 'header_line': 'NO_HEADER'},
{'data_format': 'DELIMITED', 'header_line': 'WITH_HEADER'}])
def test_header_line(sdc_builder, sdc_executor, stage_attributes):
pass
@pytest.mark.parametrize('idle_timeout, expected_num_files', [('${1 * SECONDS}', 5), ('${3 * SECONDS}', 1)])
def test_idle_timeout(sdc_builder, sdc_executor, idle_timeout, expected_num_files):
"""Test Idle Timeout. The pipeline test how many files are created when we write 5 batches if the Idle Timeout
are lower and higher than the the delay between batches.
Pipeline looks like:
dev_data_generator >> local_fs
"""
tmp_directory = '/tmp/out/{}'.format(get_random_string(string.ascii_letters, 10))
pipeline_builder = sdc_builder.get_pipeline_builder()
dev_data_generator = pipeline_builder.add_stage('Dev Data Generator')
dev_data_generator.set_attributes(batch_size=100,
delay_between_batches=2000,
fields_to_generate=[{'field': 'a', 'type': 'STRING'},
{'field': 'b', 'type': 'STRING'},
{'field': 'c', 'type': 'STRING'}])
local_fs = pipeline_builder.add_stage('Local FS', type='destination')
local_fs.set_attributes(data_format='DELIMITED',
directory_template=tmp_directory,
idle_timeout=idle_timeout)
dev_data_generator >> local_fs
pipeline = pipeline_builder.build().configure_for_environment()
sdc_executor.add_pipeline(pipeline)
try:
sdc_executor.start_pipeline(pipeline).wait_for_pipeline_batch_count(5)
sdc_executor.stop_pipeline(pipeline)
num_created_files = int(sdc_executor.execute_shell(f'ls {tmp_directory} | wc -l').stdout)
assert num_created_files == expected_num_files
finally:
logger.info('Deleting files created by Local FS in %s ...', tmp_directory)
sdc_executor.execute_shell(f'rm -R {tmp_directory} ')
@stub
@pytest.mark.parametrize('stage_attributes', [{'data_format': 'WHOLE_FILE', 'include_checksum_in_events': False},
{'data_format': 'WHOLE_FILE', 'include_checksum_in_events': True}])
def test_include_checksum_in_events(sdc_builder, sdc_executor, stage_attributes):
pass
@stub
@pytest.mark.parametrize('stage_attributes', [{'data_format': 'TEXT',
'insert_record_separator_if_no_text': False,
'on_missing_field': 'IGNORE'},
{'data_format': 'TEXT',
'insert_record_separator_if_no_text': True,
'on_missing_field': 'IGNORE'}])
def test_insert_record_separator_if_no_text(sdc_builder, sdc_executor, stage_attributes):
pass
@stub
@pytest.mark.parametrize('stage_attributes', [{'data_format': 'JSON', 'json_content': 'ARRAY_OBJECTS'},
{'data_format': 'JSON', 'json_content': 'MULTIPLE_OBJECTS'}])
def test_json_content(sdc_builder, sdc_executor, stage_attributes):
pass
@stub
@pytest.mark.parametrize('stage_attributes', [{'late_record_handling': 'SEND_TO_LATE_RECORDS_FILE'}])
def test_late_record_directory_template(sdc_builder, sdc_executor, stage_attributes):
pass
@stub
@pytest.mark.parametrize('stage_attributes', [{'late_record_handling': 'SEND_TO_ERROR'},
{'late_record_handling': 'SEND_TO_LATE_RECORDS_FILE'}])
def test_late_record_handling(sdc_builder, sdc_executor, stage_attributes):
pass
@pytest.mark.parametrize('late_records_time, expected_late_records', [
('${1 * SECONDS}', True),
('${2 * HOURS}', False)
])
def test_late_record_time_limit_in_secs(sdc_builder, sdc_executor, late_records_time, expected_late_records):
"""Test Late Records Time Limit (secs). We had 2 records and only second record had a 30 seconds delay. The
pipeline test how many files are created with different Late Records Time Limit.
Pipeline looks like:
dev_data_generator >> field_type_converter >> delay >> local_fs
"""
tmp_directory_prefix = '/tmp/out'
tmp_directory = '/${YYYY()}-${MM()}-${DD()}-${hh()}-${mm()}'
tmp_late_directory = '/tmp/late/{}'.format(get_random_string(string.ascii_letters, 10))
timestamp = datetime.now() - timedelta(hours=1)
raw_data = [{'id': 1, 'timestamp': str(timestamp)},
{'id': 2, 'timestamp': str(timestamp)}]
field_type_converter_configs = [
{
'fields': ['/timestamp'],
'targetType': 'DATE',
'dateFormat': 'YYYY_MM_DD_HH_MM_SS'
}]
pipeline_builder = sdc_builder.get_pipeline_builder()
dev_raw_data_source = pipeline_builder.add_stage('Dev Raw Data Source')
dev_raw_data_source.set_attributes(data_format='JSON',
raw_data='\n'.join(json.dumps(rec) for rec in raw_data),
stop_after_first_batch=False)
field_type_converter_fields = pipeline_builder.add_stage('Field Type Converter')
field_type_converter_fields.set_attributes(conversion_method='BY_FIELD',
field_type_converter_configs=field_type_converter_configs)
delay = pipeline_builder.add_stage('Delay')
delay.set_attributes(delay_between_batches=10000) # 30 seconds
local_fs = pipeline_builder.add_stage('Local FS', type='destination')
local_fs.set_attributes(data_format='JSON',
directory_template=tmp_directory_prefix + tmp_directory,
time_basis='${record:value("/timestamp")}',
late_record_time_limit_in_secs=late_records_time,
late_record_handling='SEND_TO_LATE_RECORDS_FILE',
late_record_directory_template=tmp_late_directory)
dev_raw_data_source >> field_type_converter_fields >> delay >> local_fs
pipeline = pipeline_builder.build().configure_for_environment()
sdc_executor.add_pipeline(pipeline)
try:
sdc_executor.start_pipeline(pipeline).wait_for_pipeline_batch_count(5)
sdc_executor.stop_pipeline(pipeline)
num_created_files = int(sdc_executor.execute_shell(f'ls {tmp_late_directory} | wc -l').stdout)
if expected_late_records:
assert num_created_files > 0
else:
assert num_created_files == 0
finally:
logger.info('Deleting files created by Local FS in %s and %s ...', tmp_directory_prefix, tmp_late_directory)
sdc_executor.execute_shell(f'rm -R {tmp_directory_prefix} ')
sdc_executor.execute_shell(f'rm -R {tmp_late_directory} ')
@stub
@pytest.mark.parametrize('stage_attributes', [{'avro_schema_location': 'REGISTRY',
'data_format': 'AVRO',
'lookup_schema_by': 'ID'},
{'avro_schema_location': 'REGISTRY',
'data_format': 'AVRO',
'lookup_schema_by': 'SUBJECT'}])
def test_lookup_schema_by(sdc_builder, sdc_executor, stage_attributes):
pass
@pytest.mark.parametrize('max_file_size, expected_num_files', [(0, 1), (1, 2)])
def test_max_file_size_in_mb(sdc_builder, sdc_executor, max_file_size, expected_num_files):
"""Test Max File Size in MB. The pipeline test how many files are created when we write 15k records (more than 1MB)
if the Max File Size are lower and higher than the number of records.
Pipeline looks like:
dev_data_generator >> local_fs
"""
tmp_directory = '/tmp/out/{}'.format(get_random_string(string.ascii_letters, 10))
pipeline_builder = sdc_builder.get_pipeline_builder()
dev_data_generator = pipeline_builder.add_stage('Dev Data Generator')
dev_data_generator.set_attributes(batch_size=10000,
delay_between_batches=100,
root_field_type='LIST_MAP',
fields_to_generate=[{'field': 'a', 'type': 'STRING'},
{'field': 'b', 'type': 'STRING'},
{'field': 'c', 'type': 'STRING'}])
local_fs = pipeline_builder.add_stage('Local FS', type='destination')
local_fs.set_attributes(data_format='DELIMITED',
directory_template=tmp_directory,
max_file_size_in_mb=max_file_size)
dev_data_generator >> local_fs
pipeline = pipeline_builder.build().configure_for_environment()
sdc_executor.add_pipeline(pipeline)
try:
sdc_executor.start_pipeline(pipeline).wait_for_pipeline_batch_count(10)
sdc_executor.stop_pipeline(pipeline)
num_created_files = int(sdc_executor.execute_shell(f'ls {tmp_directory} | wc -l').stdout)
assert num_created_files == expected_num_files
finally:
logger.info('Deleting files created by Local FS in %s ...', tmp_directory)
sdc_executor.execute_shell(f'rm -R {tmp_directory} ')
@pytest.mark.parametrize('max_records_in_file, expected_num_files', [(10, 10), (100, 1)])
def test_max_records_in_file(sdc_builder, sdc_executor, max_records_in_file, expected_num_files):
"""Test Max Records in File. The pipeline test how many files are created when we write 100 records if
the Max Records in File are lower and higher than the number of records.
Pipeline looks like:
dev_data_generator >> local_fs
"""
tmp_directory = '/tmp/out/{}'.format(get_random_string(string.ascii_letters, 10))
pipeline_builder = sdc_builder.get_pipeline_builder()
dev_data_generator = pipeline_builder.add_stage('Dev Data Generator')
dev_data_generator.set_attributes(batch_size=100,
delay_between_batches=1000,
root_field_type='LIST_MAP',
fields_to_generate=[{'field': 'a', 'type': 'STRING'},
{'field': 'b', 'type': 'STRING'},
{'field': 'c', 'type': 'STRING'}])
local_fs = pipeline_builder.add_stage('Local FS', type='destination')
local_fs.set_attributes(data_format='DELIMITED',
directory_template=tmp_directory,
max_records_in_file=max_records_in_file)
dev_data_generator >> local_fs
pipeline = pipeline_builder.build().configure_for_environment()
sdc_executor.add_pipeline(pipeline)
try:
sdc_executor.start_pipeline(pipeline).wait_for_pipeline_batch_count(1)
sdc_executor.stop_pipeline(pipeline)
num_created_files = int(sdc_executor.execute_shell(f'ls {tmp_directory} | wc -l').stdout)
assert num_created_files == expected_num_files
finally:
logger.info('Deleting files created by Local FS in %s ...', tmp_directory)
sdc_executor.execute_shell(f'rm -R {tmp_directory} ')
@stub
@pytest.mark.parametrize('stage_attributes', [{'data_format': 'PROTOBUF'}])
def test_message_type(sdc_builder, sdc_executor, stage_attributes):
pass
@stub
@pytest.mark.parametrize('stage_attributes', [{'data_format': 'DELIMITED', 'replace_new_line_characters': True}])
def test_new_line_character_replacement(sdc_builder, sdc_executor, stage_attributes):
pass
@stub
@pytest.mark.parametrize('stage_attributes', [{'data_format': 'TEXT', 'on_missing_field': 'ERROR'},
{'data_format': 'TEXT', 'on_missing_field': 'IGNORE'}])
def test_on_missing_field(sdc_builder, sdc_executor, stage_attributes):
pass
@stub
@pytest.mark.parametrize('stage_attributes', [{'on_record_error': 'DISCARD'},
{'on_record_error': 'STOP_PIPELINE'},
{'on_record_error': 'TO_ERROR'}])
def test_on_record_error(sdc_builder, sdc_executor, stage_attributes):
pass
@stub
@pytest.mark.parametrize('stage_attributes', [{'data_format': 'WHOLE_FILE'}])
def test_permissions_expression(sdc_builder, sdc_executor, stage_attributes):
pass
@stub
def test_preconditions(sdc_builder, sdc_executor):
pass
@stub
@pytest.mark.parametrize('stage_attributes', [{'data_format': 'XML', 'pretty_format': False},
{'data_format': 'XML', 'pretty_format': True}])
def test_pretty_format(sdc_builder, sdc_executor, stage_attributes):
pass
@stub
@pytest.mark.parametrize('stage_attributes', [{'data_format': 'PROTOBUF'}])
def test_protobuf_descriptor_file(sdc_builder, sdc_executor, stage_attributes):
pass
@stub
@pytest.mark.parametrize('stage_attributes', [{'data_format': 'DELIMITED', 'delimiter_format': 'CUSTOM'}])
def test_quote_character(sdc_builder, sdc_executor, stage_attributes):
pass
@stub
@pytest.mark.parametrize('stage_attributes', [{'data_format': 'DELIMITED',
'delimiter_format': 'CUSTOM',
'quote_mode': 'ALL'},
{'data_format': 'DELIMITED',
'delimiter_format': 'CUSTOM',
'quote_mode': 'MINIMAL'},
{'data_format': 'DELIMITED',
'delimiter_format': 'CUSTOM',
'quote_mode': 'NONE'}])
def test_quote_mode(sdc_builder, sdc_executor, stage_attributes):
pass
@stub
@pytest.mark.parametrize('stage_attributes', [{'data_format': 'TEXT'}])
def test_record_separator(sdc_builder, sdc_executor, stage_attributes):
pass
@stub
@pytest.mark.parametrize('stage_attributes', [{'avro_schema_location': 'HEADER',
'data_format': 'AVRO',
'register_schema': False},
{'avro_schema_location': 'HEADER',
'data_format': 'AVRO',
'register_schema': True},
{'avro_schema_location': 'INLINE',
'data_format': 'AVRO',
'register_schema': False},
{'avro_schema_location': 'INLINE',
'data_format': 'AVRO',
'register_schema': True}])
def test_register_schema(sdc_builder, sdc_executor, stage_attributes):
pass
@stub
@pytest.mark.parametrize('stage_attributes', [{'data_format': 'DELIMITED', 'replace_new_line_characters': False},
{'data_format': 'DELIMITED', 'replace_new_line_characters': True}])
def test_replace_new_line_characters(sdc_builder, sdc_executor, stage_attributes):
pass
@stub
def test_required_fields(sdc_builder, sdc_executor):
pass
@stub
@pytest.mark.parametrize('stage_attributes', [{'use_roll_attribute': True}])
def test_roll_attribute_name(sdc_builder, sdc_executor, stage_attributes):
pass
@stub
@pytest.mark.parametrize('stage_attributes', [{'avro_schema_location': 'REGISTRY',
'data_format': 'AVRO',
'lookup_schema_by': 'ID'}])
def test_schema_id(sdc_builder, sdc_executor, stage_attributes):
pass
@stub
@pytest.mark.parametrize('stage_attributes', [{'avro_schema_location': 'HEADER',
'data_format': 'AVRO',
'register_schema': True},
{'avro_schema_location': 'INLINE',
'data_format': 'AVRO',
'register_schema': True},
{'avro_schema_location': 'REGISTRY', 'data_format': 'AVRO'}])
def test_schema_registry_urls(sdc_builder, sdc_executor, stage_attributes):
pass
@stub
@pytest.mark.parametrize('stage_attributes', [{'avro_schema_location': 'REGISTRY',
'data_format': 'AVRO',
'lookup_schema_by': 'SUBJECT'},
{'avro_schema_location': 'HEADER',
'data_format': 'AVRO',
'register_schema': True},
{'avro_schema_location': 'INLINE',
'data_format': 'AVRO',
'register_schema': True}])
def test_schema_subject(sdc_builder, sdc_executor, stage_attributes):
pass
@stub
@pytest.mark.parametrize('stage_attributes', [{'file_type': 'SEQUENCE_FILE'}])
def test_sequence_file_key(sdc_builder, sdc_executor, stage_attributes):
pass
@stub
@pytest.mark.parametrize('stage_attributes', [{'skip_file_recovery': False}, {'skip_file_recovery': True}])
def test_skip_file_recovery(sdc_builder, sdc_executor, stage_attributes):
pass
@stub
@pytest.mark.parametrize('stage_attributes', [{'data_format': 'TEXT'}])
def test_text_field_path(sdc_builder, sdc_executor, stage_attributes):
pass
@stub
def test_time_basis(sdc_builder, sdc_executor):
pass
@stub
@pytest.mark.parametrize('stage_attributes', [{'use_roll_attribute': False}, {'use_roll_attribute': True}])
def test_use_roll_attribute(sdc_builder, sdc_executor, stage_attributes):
pass
@stub
@pytest.mark.parametrize('stage_attributes', [{'validate_permissions': False}, {'validate_permissions': True}])
def test_validate_permissions(sdc_builder, sdc_executor, stage_attributes):
pass
@stub
@pytest.mark.parametrize('stage_attributes', [{'data_format': 'XML', 'validate_schema': False},
{'data_format': 'XML', 'validate_schema': True}])
def test_validate_schema(sdc_builder, sdc_executor, stage_attributes):
pass
@stub
@pytest.mark.parametrize('stage_attributes', [{'data_format': 'XML', 'validate_schema': True}])
def test_xml_schema(sdc_builder, sdc_executor, stage_attributes):
pass
|
import os
import re
from setuptools import setup
base_dir = os.path.dirname(__file__)
DUNDER_ASSIGN_RE = re.compile(r"""^__\w+__\s*=\s*['"].+['"]$""")
about = {}
with open(os.path.join(base_dir, 'pypercard', '__init__.py'),
encoding='utf8') as f:
for line in f:
if DUNDER_ASSIGN_RE.search(line):
exec(line, about)
with open(os.path.join(base_dir, 'README.md'), encoding='utf8') as f:
readme = f.read()
with open(os.path.join(base_dir, 'CHANGES.md'), encoding='utf8') as f:
changes = f.read()
install_requires = [
"Kivy==1.11.1",
"Kivy-Garden==0.1.4",
'docutils;platform_system == "Windows"',
'pygments;platform_system == "Windows"',
'pypiwin32;platform_system == "Windows"',
'kivy_deps.sdl2==0.1.22;platform_system == "Windows"',
'kivy_deps.glew==0.1.12;platform_system == "Windows"',
'kivy_deps.angle==0.1.9;platform_system == "Windows"',
]
extras_require = {
'tests': [
'pytest',
'pytest-cov',
'pytest-random-order>=1.0.0',
'pytest-faulthandler',
'coverage',
'pycodestyle',
'pyflakes',
'black',
],
'docs': [
'sphinx',
],
'package': [
# Wheel building and PyPI uploading
'wheel',
'twine',
],
}
extras_require['dev'] = (
extras_require['tests'] +
extras_require['docs'] +
extras_require['package']
)
extras_require['all'] = list({
req
for extra, reqs in extras_require.items()
for req in reqs
})
setup(
name=about['__title__'],
version=about['__version__'],
description=about['__description__'],
long_description='{}\n\n{}'.format(readme, changes),
long_description_content_type='text/markdown',
author=about['__author__'],
author_email=about['__email__'],
url=about['__url__'],
license=about['__license__'],
packages=['pypercard', ],
install_requires=install_requires,
extras_require=extras_require,
include_package_data=True,
zip_safe=False,
classifiers=[
"Development Status :: 3 - Alpha",
"Environment :: MacOS X",
"Environment :: Win32 (MS Windows)",
"Environment :: X11 Applications",
"Intended Audience :: Developers",
"Intended Audience :: Education",
"Intended Audience :: End Users/Desktop",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Operating System :: Android",
"Operating System :: iOS",
"Operating System :: MacOS",
"Operating System :: Microsoft :: Windows :: Windows 10",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python :: 3 :: Only",
"Topic :: Education",
"Topic :: Software Development",
"Topic :: Software Development :: Libraries :: Application Frameworks",
"Topic :: Software Development :: User Interfaces",
"Topic :: Software Development :: Widget Sets",
"Topic :: System :: Software Distribution",
]
)
|
import Router from "./Router";
function App() {
return Router;
}
export default App;
|
#!/usr/bin/env node
const commander = require('commander');
commander
.command('query', 'run a query against all datatypes')
.command('run', 'run a brainlife app')
.command('wait', 'wait for a running app task to finish');
commander.parse(process.argv);
|
Search.setIndex({docnames:["about","auth","basic_usage","changelog","conversations","faq","index","metadata","real_time_messaging"],envversion:{"sphinx.domains.c":1,"sphinx.domains.changeset":1,"sphinx.domains.citation":1,"sphinx.domains.cpp":1,"sphinx.domains.javascript":1,"sphinx.domains.math":2,"sphinx.domains.python":1,"sphinx.domains.rst":1,"sphinx.domains.std":1,sphinx:56},filenames:["about.rst","auth.rst","basic_usage.rst","changelog.rst","conversations.rst","faq.rst","index.rst","metadata.rst","real_time_messaging.rst"],objects:{},objnames:{},objtypes:{},terms:{"0cb4bcd6e887b428e27e8059b6278b86ee661aaa":3,"1046cc2375a85a22e94573e2aad954ba7287c886":3,"1920s":2,"7d01515cebc80918a29100b0e4793790eb83e7b9":3,"boolean":4,"break":[3,5],"case":[3,5],"class":3,"default":[2,3,4,8],"final":1,"function":[1,3,8],"import":[1,2,3,4,8],"int":2,"long":2,"new":[1,2,3,4,5,6],"public":4,"return":[1,2,3,4],"short":[2,3],"super":5,"switch":3,"true":[2,3,4],"while":[2,5,8],Added:3,Adding:3,But:5,For:[1,2,4],IDs:4,IMs:2,One:2,That:5,The:[1,2,3,4,6,8],Then:1,These:[3,6],UIs:6,Use:[3,4,6],__eq__:3,__name__:1,aadd:3,abc:1,abhishekjiitr:3,abil:[1,3,8],abl:1,about:[1,2,3,4,5,6,8],acair:3,accept:1,access:[0,1,2,3,6],access_token:1,accessori:2,accid:2,acquir:6,act:[1,3],action:3,action_id:2,actual:2,adaptor:8,add:[1,2,3,5],added:[3,5],addit:[1,2,4],admin:3,after:[1,2,3],agent:3,agre:1,agreement:0,aim:5,aiodn:3,aiohttp:3,all:[1,2,4,5,6],allow:[2,3,6,8],along:[3,8],alreadi:[2,4],already_in_channel:2,also:[2,6,8],alt_text:2,alwai:[5,6],ambiti:5,ani:[1,2,6,8],anoth:[2,3],anyon:6,aoberoi:3,api:[0,1,3,6],api_cal:3,app:[0,1,2,3,4,6,8],app_home_open:8,appear:2,appli:1,applic:[1,2,3,6],appropri:5,architectur:8,archiv:2,aren:8,arg:[1,3],argument:2,around:5,arrai:4,articl:2,asherf:3,assign:2,assist:6,async:3,attach:2,attempt:3,attribut:[2,3],auth:[1,3],auth_cod:1,authent:[2,3],author:1,auto_reconnect:3,automat:3,avail:[1,2],avanderm:3,averag:2,avoid:1,axe:2,back:8,backend:6,bad:3,base:8,basic:[3,8],becaus:[3,6],becom:2,been:[1,2,3],befor:[2,3,6],begin:1,begin_auth:1,behalf:1,below:8,benoitlavign:3,best:[2,6],better:3,between:2,bite:5,block:3,blockattach:3,bond:6,bot:[1,2],bot_access_token:1,box:2,broadcast:2,bug:[3,6],bugfix:3,build:[0,1,2,3,6],builder:[2,3],built:[1,3,6],burst:2,busi:2,button:[1,2,3],c031415926:4,c0xxxxxx:2,c0xxxxxxx:2,c0xxxxxxy:2,c16180339:4,c27182818:4,c3ukjtqac:2,cach:3,call:[1,2,3,4,6,8],callback:[3,8],callback_id:2,can:[1,2,3,5,6,8],cannot:2,capabilit:6,care:6,caus:3,cclauss:3,chang:[1,2,3],changelog:5,channel:[3,8],channel_id:8,channels_info:2,channels_join:2,channels_leav:2,channels_list:2,channnel:3,charact:4,chat:2,chat_delet:2,chat_postephemer:2,chat_postmessag:[2,8],chat_upd:2,check:[1,2,3],clavin:3,clean:3,click:1,client:[1,2,3,4,8],client_id:1,client_secret:1,clone:6,close:3,code:[0,1,3,5,6],collect:2,com:[1,2,3,6],combin:2,comma:4,comment:[2,3],commit:3,commun:[3,6,8],comparison:3,compat:3,compex:[],complet:[1,3,5,8],complex:[2,6],compos:2,concept:6,concret:5,conduct:0,configur:[1,3,6],connect:3,connect_method:8,consid:6,consider:2,construct:3,consum:3,contain:[1,2,4,8],content:[3,5],context:2,continu:[2,3,5],contribut:[0,3],contributor:[0,3,5],convers:[2,8],conversations_cr:4,conversations_info:4,conversations_leav:4,conversations_list:4,conversations_memb:4,conversations_open:4,convert:3,copyright:3,correspond:[1,3,8],could:5,counter:3,coupl:[3,5],cours:6,coverag:5,creat:3,createchild:3,credenti:[1,3],current:6,custom:[2,3],d45285d2f1025899dcd65e259624ee73771f94bb:3,dai:5,danni:2,data:[1,2,4,6,8],databas:1,deal:2,decod:3,decomposit:3,def:[1,2,8],defin:[1,6],delai:2,demonstr:5,depend:[1,4],descend:2,describ:3,detail:[2,8],determin:1,develop:2,differ:2,direct:[1,2],directli:[2,6],discuss:5,displai:2,doc:[3,4,5,8],docstr:3,document:[1,2,3],doesn:3,don:[1,5],done:[5,6],door:2,driven:8,due:3,duplic:3,dynam:2,each:[2,3],easi:3,easier:6,edit:5,effect:1,either:[2,4],element:[2,3],elif:2,email:3,empti:1,enabl:3,encod:3,encount:4,endpoint:[1,6],enforc:3,ensur:[3,5],entir:[1,3],environ:[1,2,3,4,5,8],environment:1,ephemer:2,error:[2,3],establish:8,event:[3,6],everi:1,everyon:3,exampl:[1,2,8],exce:2,excel:5,except:3,exchang:[1,2],excit:[2,5],exclud:2,exclude_archiv:2,execut:8,exist:[2,4],expand:6,expect:5,expir:3,expos:3,extend:6,extras_requir:3,f7bb8889580cc34471ba1ddc05afc34d1a5efa23:3,facilit:1,fail:[2,3],fallback:2,fals:2,far:2,featur:[1,3,6],feedback:5,feel:[2,5],fellow:6,felt:2,fetch:2,few:3,fewer:4,field:[2,3],file:[3,5],file_com:2,files_upload:2,find:2,finish:2,finish_auth:1,first:5,fix:[3,5],flask:1,flow:1,flyte:3,focu:3,focus:[2,3],folder:5,follow:[2,3,5,6],forget:[1,5],fork:2,format:3,found:1,framework:6,from:[0,1,2,3,6,8],full:[1,2,6],fulli:2,fun:2,futur:5,gener:[5,6],german:2,get:[1,3],git:6,github:[3,6],give:[3,8],given:5,good:5,grace:2,grant:1,great:[5,6],greater:2,griffith:3,group:[2,3,4],guest:2,guid:[3,6],guidelin:[3,5],had:2,handl:[1,2,3],happen:6,harlowja:3,has:[1,2,6],haunt:2,have:[2,3,5,6],header:[2,3],hello:[2,8],help:[3,5],helper:3,here:[2,3,6],higher:6,hint:3,hit:2,hole:2,hop:2,hotel:2,how:[1,2,3],howev:2,href:1,http:[1,2,3,6,8],hub:2,hyphen:4,identifi:3,imag:2,image_url:2,importantli:5,improv:3,includ:[1,2,3,4,5],include_local:4,include_num_memb:4,incorpor:5,incorrectli:3,increas:5,inde:2,indent:3,index:3,indic:2,industri:1,info:[3,4],inform:[1,2,3,8],initi:1,input:2,insid:[2,5,8],install_requir:3,instanti:8,instead:[1,2,3,8],integr:[2,3,6],intend:1,interact:[2,6],interest:4,interfac:[2,4],intern:3,introduc:3,invalid:3,invit:2,is_priv:4,isn:6,issu:[3,5,6,8],item:[2,5],iter:3,its:[3,5,8],itself:2,jayalan:3,joakimnordl:3,join:3,jpeg:2,json:[1,2,3],just:[1,2,5,6],kamushaden:3,kei:[1,2],kelvintaywl:3,kind:2,kit:3,know:[1,5],kt5356:3,label:2,lack:3,languag:6,larg:3,larger:8,later:1,layout:2,learn:6,least:1,left:2,length:3,less:3,let:[0,1,2,5,6],letter:4,librari:3,licens:[0,3],like:[3,4,6,8],limit:3,linear:2,link:[1,3,8],lint:3,list:[1,3,8],liter:2,live:3,load:3,local:[3,4],locat:3,lock:3,log:3,login:3,longer:2,look:[2,5],love:5,made:3,mai:[2,3,4],maintain:0,make:[1,2,4,5,6],mani:[2,5],mark:3,match:3,mayb:2,messag:[3,6],metadata:4,method:[1,2,3,4],might:[2,6],migrat:3,miss:3,modifi:3,more:[1,2,5,8],most:[2,8],move:3,mpdm:3,mpim:[3,4],mrkdwn:2,much:5,multi:4,must:[1,2,4],myapp:1,name:[2,3,4],nearli:2,need:[1,2,5,6],newest:4,node:1,non:3,note:[2,4,5,8],notif:2,now:3,number:[2,4],oauth:[1,2,3,6],oauth_access:1,oauth_scop:1,object:[2,3],occur:[3,8],off:2,onc:[1,2],one:[1,2,5],onli:[2,4],onto:2,open:[3,4,6],option:[2,3,4,8],order:1,origin:[2,3],other:[1,2,3],our:[1,2,3,4,5,6,8],out:[1,2,3],over:[2,3],overlook:2,own:2,packag:3,page:[1,6],param:[1,3,4],paramet:[1,2,3,4],parent:[2,3],parti:4,particularli:5,pass:[1,2,3,8],password:[1,6],paul:3,payload:[1,8],pdf:2,peopl:[2,4,6],pep:3,per:2,period:2,permiss:[1,6],persist:1,person:[2,4],pexel:2,photo:2,ping:3,pip:6,place:[2,6],plain_text:2,plain_text_input:2,platform:[0,8],pleas:[1,3,5],point:[2,3],possibl:[3,6],post:[1,2,6,8],post_instal:1,postephemer:2,postmessag:2,potenti:[1,6],practic:2,pre:1,pre_instal:1,prefer:[3,8],prevent:3,previou:2,previous:3,primari:2,print:2,privat:[3,4],private_channel:4,program:5,programm:6,project:[3,5,6],properli:3,properti:[2,3],propos:5,protoco:1,prototyp:2,proudli:0,provid:[1,2,3,4,6,8],proxi:3,public_channel:4,publish:1,pull:[5,6],purpos:[2,6],push:8,pypi:6,python:[1,2,3,8],queri:1,quickli:[2,6],rate:3,rather:[3,5,8],react:3,reactions_add:2,reactions_remov:2,read:[1,6,8],readm:3,rebuild:5,receiv:[3,8],reciev:[3,8],recommend:[1,5,6,8],reconnect:3,redesign:3,redirect:1,refer:2,reflect:2,refresh:3,refus:1,regular:2,reinstal:1,releas:3,releg:2,remot:3,remov:[2,3],repli:[2,3],reply_broadcast:2,report:6,request:[1,2,3,4,5,6],requir:[1,2,3,4,6],respond:[2,6],respons:[1,2,3,4,8],responseparseerror:3,restructuredtext:5,result:[2,3],resum:4,retri:2,retriev:[1,3,4],review:[1,2],rfc:3,roach:3,room:2,rout:1,rowdi:2,rst:[3,5],rtm:3,rtm_client:8,rtm_connect:3,rtm_send_messag:3,rtmclient:[3,8],run:5,run_on:[3,8],runtim:1,sai:[2,8],same:[2,4],sampart:3,sampl:5,save:[1,2],say_hello:8,schedul:3,schlueter:3,scope:1,sdk:6,search:3,second:2,secret:1,section:[1,2,3,5],see:[1,2,4,8],semver:3,send:[3,8],send_messag:3,send_slack_messag:2,sent:2,separ:4,seratch:3,server:3,set:[1,2,3,4,6,8],setup:1,shanedewael:3,share:[1,4],should:[2,6],show:2,silent:2,simpl:[1,2],simpli:[2,8],singl:[2,4],site:2,slack:[1,2,3,4,8],slack_api_token:[2,4,8],slack_bot_scop:1,slack_bot_token:1,slack_client_id:1,slack_client_secret:1,slack_token:[2,4,8],slack_user_token:1,slackapi:[3,6],slackapierror:3,slackclient:[3,6],slackclienterror:3,slackrespons:3,sleep:2,slightli:2,slow:8,smaeda:3,snippet:3,social:2,some:[2,3,8],someth:5,sometim:2,sorri:3,sourc:[1,6],special:2,specif:[2,6],specifi:[2,4],sphinx:5,splinterif:3,split:3,src:5,standard:1,star:2,start:[1,2,5,6],stasfilin:3,state:2,staticdev:3,statu:2,step:5,store:1,str:2,string:[1,3,4],stuck:[2,6],submit:5,subsequ:4,succeed:[1,2],success:1,successfulli:2,suppli:4,support:[3,8],sure:[1,2,5],surfac:2,tada:2,take:[1,2],target:6,team:[0,1,3,6,8],tell:[2,3],temp:3,test:[2,3,5],text:[2,8],than:[2,3,4],thank:[3,5],thei:[2,3,5,6],them:[1,2],therefor:2,thi:[1,2,3,4,5,6,8],thing:[2,3,4,5,6],think:5,those:2,though:2,thought:5,thread:3,thread_t:[2,8],through:[3,6],thumbsup:2,tidi:3,time:2,timelin:2,timeout:3,timestamp:2,timfeirg:3,titl:2,togeth:2,token:[2,3,6,8],too:2,tool:0,torrenc:2,total:5,tox:[3,5],traceback:3,tracker:[5,6],transform:3,transmit:3,travi:3,treat:[1,6],trigger_id:2,two:[3,5],txt:6,type:[2,3,4,8],typo:3,u023becgf:8,u0xxxxxxx:2,u987654321:4,underscor:4,unifi:4,unit:5,unreli:8,until:2,unus:3,updat:[3,5],upload:3,url:[3,8],urllib:3,usag:1,use:[1,2,3,4,5,6,8],used:[1,2],useful:4,user:[1,2,3,4,5,8],users_list:2,uses:[2,8],using:[2,3,6,8],v123401:2,valid:[1,3,4],valu:[3,4],value_indentifi:2,variabl:1,veri:2,version:[3,6],via:1,view:[2,3],view_id:2,view_identifi:2,views_open:2,views_upd:2,virtualenv:5,visibl:2,visit:6,vote:2,vpetersson:3,vscode:3,w123456789:4,wai:[2,6],wait:2,want:[2,5],watch:8,web:[0,1,3,8],web_client:8,webclient:[1,2,3,4],webserv:1,websocket:[3,8],well:[2,6],what:[2,5],when:[1,2,3,8],where:[1,3,6],which:[1,2,3,4,8],who:[1,3],whole:2,why:5,wiki:[],wish:[1,4],without:3,won:2,word:3,work:[1,2,3,4,5,6],workspac:[4,6],would:[1,3,6],wrapper:2,write:[1,5,6],written:5,xoxb:1,xoxp:1,yield:1,you:[0,1,2,3,4,5,6,8],your:[0,1,2,3,4,5,6,8],yourself:5},titles:["About","Tokens & Authentication","Basic Usage","Changelog","Conversations API","Frequently Asked Questions","Slack Developer Kit for Python","<no title>","Real Time Messaging (RTM)"],titleterms:{There:5,about:0,api:[2,4,8],ask:5,authent:1,basic:[2,6],block:2,bug:5,changelog:3,channel:[2,4],compil:5,connect:8,contribut:5,convers:4,creat:4,delet:2,develop:[0,6],direct:4,document:5,emoji:2,event:8,featur:5,file:2,format:2,found:5,frequent:5,get:[2,4,6],help:6,how:5,info:2,inform:4,instal:[1,6],join:2,keep:1,kit:[0,2,6],leav:[2,4],limit:2,list:[2,4],member:[2,4],messag:[2,4,8],miss:5,modal:2,more:4,multipl:1,open:2,platform:6,push:2,python:[0,6],question:5,rate:2,reaction:2,real:8,rtm:8,safe:1,send:2,singl:1,slack:[0,6],start:8,team:2,thread:2,time:8,token:1,updat:2,upload:2,usag:2,web:2,workspac:1}})
|
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.Callback = void 0;
var _1 = require("./");
/**
* Callback provides an actor that will successfully process one and only one
* message before exiting.
*
* Unmatched messages are ignored.
*/
var Callback = /** @class */ (function (_super) {
__extends(Callback, _super);
function Callback() {
return _super !== null && _super.apply(this, arguments) || this;
}
return Callback;
}(_1.Immutable));
exports.Callback = Callback;
//# sourceMappingURL=callback.js.map
|
import React, { Component } from 'react'
import { Button, StyleSheet, View, TextInput, Text, Image } from 'react-native'
//import { getPixels } from './mnist'
import { SketchCanvas } from '@terrylinla/react-native-sketch-canvas'
//import ImageResizer from 'react-native-image-resizer'
var net = require('react-native-tcp');
//var client = net.createConnection(12345);
export default class example extends Component {
state = {
detectedDigit: null,
drawnImage: 'data:image/jpg;base64,'
}
tcpserver = {
host:'192.168.43.247',//10.0.1.1',
port: 9999
}
maxScore(obj) {
let maxKey = 0
let maxValue = 0
Object.entries(obj).forEach(entry => {
const value = entry[1]
if (value > maxValue) {
maxValue = value
maxKey = parseInt(entry[0], 10)
}
})
return maxKey
}
grabPixels = () => {
this.canvas.getBase64('jpg', false, true, false, false, (err, result) => {
const resultImage = `data:image/jpg;base64,${result}`
this.setState({ drawnImage: resultImage })
console.log(result)
// let server = net.createServer((socket) => {
// this.updateChatter('server connected on ' + JSON.stringify(socket.address()));
// socket.on('data', (data) => {
// this.updateChatter('Server Received: ' + data);
// socket.write('Echo server\r\n');
// });
// });
// ImageResizer.createResizedImage(resultImage, 28, 28, "JPEG", 80)
//.then(drawnImage => {
//RNFetchBlob.fs
//.readFile(responseImage.path, "base64")
// .then(resizeImage => {
// this.setState({ drawnImage : resizeImage });
// console.log(drawnImage)
// })
// .catch(err => {
// console.log(err);
// });
})
}
// getPixels(resultImage)
// .then(values => {
// console.log(values)
// //const detection = net.run(values)
// //this.setState({ detectedDigit:1 })
// })
// .catch(console.error)
clear = () => {
this.canvas.clear()
this.setState({ detectedDigit: null, drawnImage: 'data:image/jpg;base64,' })
}
printResults = () => {
return (
<View style={styles.rows}>
<Text>28x28 version the computer sees =</Text>
<Image
style={styles.previewImage}
source={{ uri: this.state.drawnImage }}
/>
{/* <Text style={styles.resultNumber}>{`${this.state.detectedDigit}`}</Text> */}
</View>
)
}
onsend = () =>{
// var ws = new WebSocket('ws://192.168.0.106');
// console.log(this.state.drawnImage)
// let client = net.createConnection(this.tcpserver.host, () => {
// //this.updateChatter('opened client on ' + JSON.stringify(client.host()));
// console.log(this.tcpserver)
// client.write('Hello, server! Love, Client.');
// })
// net.connect{
// this.tcpserver.host,
// this.tcpserver.port
// }
var client = net.createConnection(this.tcpserver.port, this.tcpserver.host);
var imagesend = this.state.drawnImage
client.on('data', function(data) {
// Log the response from the HTTP server.
console.log('RESPONSE: ' + data);
}).on('connect', function() {
// Manually write an HTTP request.
client.write(imagesend);
console.log('Image : ' + imagesend)
//console.log('CONNECTED : ' + tcpserver.host + ' ' + tcpserver.port);
}).on('end', function() {
console.log('DONE');
client.close();
});
};
// ws.onopen = () => {
// // connection opened
// ws.send('stome'); // send a message
// };
// ws.onmessage = (e) => {
// // a message was received
// console.log(e.data);
// this.setState({detectedDigit: e.data})
// };
// ws.onerror = (e) => {
// // an error occurred
// console.log(e.message);
// };
// ws.onclose = (e) => {
// // connection closed
// console.log(e.code, e.reason);
// };
render() {
return (
<View style={styles.container}>
<View style={{ flex: 1 }}>
<SketchCanvas
ref={ref => (this.canvas = ref)}
style={{
width: 280,
height: 280,
borderColor: 'black',
marginTop: 30,
//borderWidth: 1
}}
strokeColor={'#000000'}
strokeWidth={28}
onStrokeEnd={this.grabPixels}
/>
<Button title="Hapus" onPress={this.clear} />
<Button title="Kirim" onPress={this.onsend} />
{this.printResults()}
</View>
</View>
)
};
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'space-around',
alignItems: 'center',
backgroundColor: '#F5FCFF'
},
previewImage: {
width: 28,
height: 28
},
rows: {
flexDirection: 'row'
},
resultSentence: {
textAlign: 'center',
fontSize: 24
},
resultNumber: {
textAlign: 'center',
fontSize: 128
},
functionButton: {
width: 280, height: 140, borderRadius: 15,
}
})
|
import { DCFUtility } from './dcf-utility';
const overlayMatch = 'dcf-notice-overlay';
const overlayHeader = 'dcf-header';
const overlayMaincontent = 'dcf-main';
const typeInfo = 'dcf-notice-info';
const typeSuccess = 'dcf-notice-success';
const typeWarning = 'dcf-notice-warning';
const typeDanger = 'dcf-notice-danger';
const overlayHeaderElement = document.getElementById(overlayHeader);
const overlayMaincontentElement = document.getElementById(overlayMaincontent);
export class DCFNoticeTheme {
constructor() {
// Defaults
/* eslint-disable */
this.noticeContainerClassList = [ 'dcf-d-grid', 'dcf-ai-start', 'dcf-w-max-xl', 'dcf-ml-auto', 'dcf-mr-auto', 'dcf-mb-6', 'dcf-rounded' ];
this.closeNoticeInfoIconInnerHTML = '<svg class="dcf-h-100% dcf-w-100%" aria-hidden="true" focusable="false" height="24" width="24" viewBox="0 0 24 24"><path fill="#fefdfa" d="M12 0C5.4 0 0 5.4 0 12s5.4 12 12 12 12-5.4 12-12S18.6 0 12 0zm-.5 4.8c.7 0 1.2.6 1.2 1.2s-.6 1.2-1.2 1.2-1.3-.5-1.3-1.2.6-1.2 1.3-1.2zM15 19.2H9c-.4 0-.8-.3-.8-.8s.3-.8.8-.8h2.2v-7.5H10c-.4 0-.8-.3-.8-.8s.4-.5.8-.5h2c.2 0 .4.1.5.2.1.1.2.3.2.5v8.2H15c.4 0 .8.3.8.8s-.4.7-.8.7z"/></svg>';
this.closeNoticeSuccessIconInnerHTML = '<svg class="dcf-h-100% dcf-w-100%" aria-hidden="true" focusable="false" height="24" width="24" viewBox="0 0 24 24"><path fill="#fefdfa" d="M12 0C5.4 0 0 5.4 0 12s5.4 12 12 12 12-5.4 12-12S18.6 0 12 0zm5.5 9L10 16c-.1.1-.3.2-.5.2s-.4-.1-.5-.2l-2.5-2.5c-.1-.1-.2-.3-.2-.5s.1-.4.2-.5c.3-.3.8-.3 1.1 0l2 2 7-6.5c.1-.1.3-.2.5-.2s.4.1.5.2c.2.3.2.8-.1 1z"/></svg>';
this.closeNoticeWarningIconInnerHTML = '<svg class="dcf-h-100% dcf-w-100%" aria-hidden="true" focusable="false" height="24" width="24" viewBox="0 0 24 24"><path fill="#fefdfa" d="M22.9 22.3l-11-22c-.2-.3-.7-.3-.9 0l-11 22c-.1.3.1.7.5.7h22c.4 0 .6-.4.4-.7zM10.8 8.1c0-.4.3-.7.8-.7.2 0 .4.1.5.2.1.1.2.3.2.5v7.7c0 .2-.1.4-.2.5-.1.1-.3.2-.5.2-.4 0-.7-.3-.8-.7V8.1zm.7 12.2c-.7 0-1.2-.5-1.2-1.2s.5-1.2 1.2-1.2 1.2.5 1.2 1.2-.5 1.2-1.2 1.2z"/></svg>';
this.closeNoticeDangerIconInnerHTML = '<svg class="dcf-h-100% dcf-w-100%" aria-hidden="true" focusable="false" height="24" width="24" viewBox="0 0 24 24"><path fill="#fefdfa" d="M23.9 7L17.1.2c-.1-.1-.3-.2-.4-.2H7.2c-.1 0-.2.1-.3.1L.1 7c0 .1-.1.2-.1.3v9.5c0 .1.1.3.1.4l6.7 6.7c.2 0 .3.1.4.1h9.5c.1 0 .3-.1.4-.1l6.8-6.7c.1-.1.1-.2.1-.4V7.3c0-.1-.1-.2-.1-.3zM17 16c.3.3.3.8 0 1.1-.1.1-.3.2-.5.2s-.4-.1-.5-.3l-4-4-4 4c-.3.3-.8.3-1.1 0-.3-.3-.3-.8 0-1.1l4-4L7 8c-.2-.1-.2-.3-.2-.5s0-.4.2-.5c.3-.3.7-.3 1 0l4 4 4-4c.3-.3.8-.3 1.1 0 .1.1.2.3.2.5s-.1.4-.2.5l-4 4 3.9 4z"/></svg>';
this.closeNoticeBtnClassList = [ 'dcf-btn', 'dcf-btn-inverse-tertiary', 'dcf-lh-1' ];
this.closeNoticeBtnInnerHTML = '<span class="dcf-sr-only">Close this notice</span><svg class="dcf-fill-current" aria-hidden="true" focusable="false" height="16" width="16" viewBox="0 0 24 24"><path d="M23.707 22.293L13.414 12 23.706 1.707A.999.999 0 1022.292.293L12 10.586 1.706.292A1 1 0 00.292 1.706L10.586 12 .292 22.294a1 1 0 101.414 1.414L12 13.414l10.293 10.292a.999.999 0 101.414-1.413z"/><path fill="none" d="M0 0h24v24H0z"/></svg>';
/* eslint-enable */
}
setThemeVariable(themeVariableName, value) {
switch (themeVariableName) {
case 'noticeContainerClassList':
if (Array.isArray(value)) {
this.noticeContainerClassList = value;
}
break;
case 'closeNoticeInfoIconInnerHTML':
if (typeof value === 'string') {
this.closeNoticeInfoIconInnerHTML = value;
}
break;
case 'closeNoticeSuccessIconInnerHTML':
if (typeof value === 'string') {
this.closeNoticeSuccessIconInnerHTML = value;
}
break;
case 'closeNoticeWarningIconInnerHTML':
if (typeof value === 'string') {
this.closeNoticeWarningIconInnerHTML = value;
}
break;
case 'closeNoticeDangerIconInnerHTML':
if (typeof value === 'string') {
this.closeNoticeDangerIconInnerHTML = value;
}
break;
case 'closeNoticeBtnClassList':
if (Array.isArray(value)) {
this.closeNoticeBtnClassList = value;
}
break;
case 'closeNoticeBtnInnerHTML':
if (typeof value === 'string') {
this.closeNoticeBtnInnerHTML = value;
}
break;
default:
// Invalid variable so ignore
break;
}
}
}
export class DCFNotice {
constructor(theme) {
if (theme instanceof DCFNoticeTheme) {
this.theme = theme;
} else {
this.theme = new DCFNoticeTheme();
}
}
initialize() {
const notices = document.getElementsByClassName('dcf-notice');
Array.prototype.forEach.call(notices, (notice) => {
this.initNotice(notice);
});
}
appendNotice(parent, heading, message, type = typeInfo, overlay = '') {
let notice = false;
if (parent instanceof Element) {
notice = this.createNotice(heading, message, type, overlay);
parent.append(notice);
}
return notice;
}
prependNotice(parent, heading, message, type = typeInfo, overlay = '') {
let notice = false;
if (parent instanceof Element) {
notice = this.createNotice(heading, message, type, overlay);
parent.prepend(notice);
}
return notice;
}
createNotice(heading, message, type = typeInfo, overlay = '') {
let noticeHeading = document.createElement('h2');
noticeHeading.innerText = heading;
let noticeMsg = document.createElement('div');
noticeMsg.innerHTML = message;
let notice = document.createElement('div');
notice.classList.add('dcf-notice');
if (type === typeInfo || type === typeSuccess || type === typeWarning || type === typeDanger) {
notice.classList.add(type);
} else {
notice.classList.add(typeInfo);
}
if (overlay === overlayHeader || overlay === overlayMaincontent) {
notice.setAttribute('data-overlay', overlay);
}
notice.append(noticeHeading);
notice.append(noticeMsg);
this.initNotice(notice);
return notice;
}
getNoticeIconContent(notice) {
let iconContent = this.theme.closeNoticeInfoIconInnerHTML;
if (notice.classList.contains(typeSuccess)) {
iconContent = this.theme.closeNoticeSuccessIconInnerHTML;
} else if (notice.classList.contains(typeWarning)) {
iconContent = this.theme.closeNoticeWarningIconInnerHTML;
} else if (notice.classList.contains(typeDanger)) {
iconContent = this.theme.closeNoticeDangerIconInnerHTML;
}
return iconContent;
}
initNotice(notice) {
if (!notice.classList.contains('dcf-notice') || notice.classList.contains('dcf-notice-initialized')) {
return;
}
const int0 = 0;
// Get or Set notice id info
const idPrefix = 'dcf-notice-';
notice.setAttribute('id', DCFUtility.checkSetElementId(notice, idPrefix.concat(DCFUtility.uuidv4())));
const headingId = `${notice.getAttribute('id')}-heading`;
// Add other notice attributes
notice.setAttribute('role', 'alertdialog');
notice.setAttribute('aria-labelledby', headingId);
if (!notice.classList.contains(typeInfo) && !notice.classList.contains(typeSuccess) &&
!notice.classList.contains(typeWarning) && !notice.classList.contains(typeDanger)) {
notice.classList.add(typeInfo);
}
if (this.theme.noticeContainerClassList) {
notice.classList.add(...this.theme.noticeContainerClassList);
}
// set notice icon
const noticeIcon = document.createElement('div');
noticeIcon.classList.add('dcf-notice-icon');
noticeIcon.innerHTML = this.getNoticeIconContent(notice);
// set notice heading
const headings = notice.getElementsByTagName('h2');
const heading = headings[int0] || document.createElement('h2');
heading.classList.add('dcf-notice-heading', 'dcf-txt-h6', 'dcf-mb-0');
heading.setAttribute('id', headingId);
// set notice message
const messages = notice.getElementsByTagName('div');
let message = document.createElement('div');
if (messages[int0]) {
message = messages[int0].cloneNode(true);
}
message.classList.add('dcf-notice-message', 'dcf-txt-sm');
// build notice body
const noticeBody = document.createElement('div');
noticeBody.classList.add('dcf-notice-body');
noticeBody.append(heading);
noticeBody.append(message);
// set notice icon and body
notice.innerHTML = '';
notice.append(noticeIcon);
notice.append(noticeBody);
let isOverlay = false;
let overlayClass = `${overlayMatch}-${overlayHeader}`;
if (notice.dataset.overlay === overlayHeader || notice.classList.contains(overlayClass)) {
isOverlay = true;
notice.classList.add('dcf-absolute');
notice.classList.add(overlayMatch);
notice.classList.remove(overlayClass);
overlayHeaderElement.append(notice);
}
overlayClass = `${overlayMatch}-${overlayMaincontent}`;
if (!isOverlay && (notice.dataset.overlay === overlayMaincontent || notice.classList.contains(overlayClass))) {
isOverlay = true;
notice.classList.add('dcf-absolute');
notice.classList.add(overlayMatch);
notice.classList.remove(overlayClass);
overlayMaincontentElement.prepend(notice);
}
/* eslint func-style: ["error", "declaration", { "allowArrowFunctions": true }] */
const handleNoticeClose = () => {
notice.remove();
};
// Add close button unless data-no-close-button exists
if (notice.dataset.noCloseButton === undefined) {
let closeButton = document.createElement('button');
if (this.theme.closeNoticeBtnClassList) {
closeButton.classList.add(...this.theme.closeNoticeBtnClassList);
}
if (this.theme.closeNoticeBtnInnerHTML) {
closeButton.innerHTML = this.theme.closeNoticeBtnInnerHTML;
}
closeButton.removeEventListener('click', handleNoticeClose);
closeButton.addEventListener('click', handleNoticeClose);
let closeNotice = document.createElement('div');
closeNotice.classList.add('dcf-notice-close');
closeNotice.append(closeButton);
notice.append(closeNotice);
}
notice.classList.add('dcf-notice-initialized');
notice.removeAttribute('hidden');
}
}
|
/**
* FilterContent.js
*
* Released under LGPL License.
* Copyright (c) 1999-2017 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
define(
'tinymce.plugins.image.core.FilterContent',
[
'tinymce.core.util.Tools'
],
function (Tools) {
var hasImageClass = function (node) {
var className = node.attr('class');
return className && /\bimage\b/.test(className);
};
var toggleContentEditableState = function (state) {
return function (nodes) {
var i = nodes.length, node;
var toggleContentEditable = function (node) {
node.attr('contenteditable', state ? 'true' : null);
};
while (i--) {
node = nodes[i];
if (hasImageClass(node)) {
node.attr('contenteditable', state ? 'false' : null);
Tools.each(node.getAll('figcaption'), toggleContentEditable);
}
}
};
};
var setup = function (editor) {
editor.on('preInit', function () {
editor.parser.addNodeFilter('figure', toggleContentEditableState(true));
editor.serializer.addNodeFilter('figure', toggleContentEditableState(false));
});
};
return {
setup: setup
};
}
);
|
const Discord = require('discord.js');
const client = new Discord.Client();
const ytdl = require('ytdl-core');
const request = require('request');
const fs = require('fs');
require('dotenv').config();
let config = require('./settings.json');
const botToken = process.env.BOT_TOKEN;
const youtubeAPIKey = process.env.YOUTUBE_API_KEY;
const botMaster = process.env.BOT_MASTER;
const prefix = config.prefix;
const role = config.role;
let guilds = {};
client.on('ready', function () {
console.log(`Logged in as ${client.user.username}#${client.user.discriminator}`);
clientUser = client.user;
clientUser.setActivity('some sick Tunes!', { type: 'PLAYING' });
});
client.on('message', function (message) {
const member = message.member;
const msg = message.content.toLowerCase();
const args = message.content.split(' ').slice(1).join(' ');
if (!guilds[message.guild.id]) {
guilds[message.guild.id] = {
queue: [],
queueNames: [],
isPlaying: false,
dispatcher: null,
voiceChannel: null,
skipReq: 0,
skippers: [],
playedTracks: []
};
}
if (message.author.equals(client.user) || message.author.bot) return;
if (msg.startsWith(prefix + 'play')) {
if (member.voice.channel || guilds[message.guild.id].voiceChannel != null) {
if (guilds[message.guild.id].queue.length > 0 || guilds[message.guild.id].isPlaying) {
getID(args, function (id) {
addToQueue(id, message);
getVideoInfo(id, function (videoInfo) {
guilds[message.guild.id].queueNames.push(videoInfo.videoDetails.title);
addToPlayedTracks(message, videoInfo, message.author);
message.reply('the song: **' + videoInfo.videoDetails.title + '** has been added to the queue.');
});
});
} else {
guilds[message.guild.id].isPlaying = true;
getID(args, function (id) {
guilds[message.guild.id].queue.push(id);
playMusic(id, message);
getVideoInfo(id, function (videoInfo) {
guilds[message.guild.id].queueNames.push(videoInfo.videoDetails.title);
addToPlayedTracks(message, videoInfo, message.author);
message.reply('the song: **' + videoInfo.videoDetails.title + '** is now playing!');
});
});
}
} else if (member.voice.channel === false) {
message.reply('you have to be in a voice channel to play music!');
} else {
message.reply('you have to be in a voice channel to play music!');
}
} else if (msg.startsWith(prefix + 'skip')) {
if (guilds[message.guild.id].skippers.indexOf(message.author.id) === -1) {
guilds[message.guild.id].skippers.push(message.author.id);
guilds[message.guild.id].skipReq++;
if (guilds[message.guild.id].skipReq >=
Math.ceil((guilds[message.guild.id].voiceChannel.members.size - 1) / 2) || message.guild.member(message.author.id).roles.cache.find(roles => roles.name === role)) {
skipMusic(message);
message.reply('your skip request has been accepted. The current song will be skipped!');
} else {
message.reply('your skip request has been accepted. You need **' +
(Math.ceil((guilds[message.guild.id].voiceChannel.members.size - 1) / 2) -
guilds[message.guild.id].skipReq) + '** more skip request(s)!');
}
} else {
message.reply('you already submitted a skip request.');
}
} else if (msg.startsWith(prefix + 'queue')) {
var codeblock = '```';
for (let i = 0; i < guilds[message.guild.id].queueNames.length; i++) {
let temp = (i + 1) + '. ' + guilds[message.guild.id].queueNames[i] +
(i === 0 ? ' **(Current Song)**' : '') + '\n';
if ((codeblock + temp).length <= 2000 - 3) {
codeblock += temp;
} else {
codeblock += '```';
message.channel.send(codeblock);
codeblock = '```';
}
}
codeblock += '```';
message.channel.send(codeblock);
} else if (msg.startsWith(prefix + 'stop')) {
if (guilds[message.guild.id].isPlaying === false) {
message.reply('no music is playing!');
return;
}
if (message.guild.member(message.author.id).roles.cache.find(roles => roles.name === role)) {
message.reply('stopping the music...');
guilds[message.guild.id].queue = [];
guilds[message.guild.id].queueNames = [];
guilds[message.guild.id].isPlaying = false;
guilds[message.guild.id].dispatcher.end();
guilds[message.guild.id].voiceChannel.leave();
} else {
message.reply("nice try, but only " + role + "s can stop me!");
}
} else if (msg.startsWith(prefix + 'history')){
let defaultTrackCount = 30;
argArr = args.split(' ');
let includeUsers = argArr.some(val => val != null && val.toLowerCase().indexOf('user') >= 0);
let includeTimes = argArr.some(val => val != null && val.toLowerCase().indexOf('time') >= 0);
let historyTxt = getPlayedTracksText(message, tryParseInt(args, defaultTrackCount), includeUsers, includeTimes);
let historyMsgs = splitTextByLines(historyTxt);
for (let i = 0; i < historyMsgs.length; i++){
message.reply(historyMsgs[i]);
}
}
});
function isYoutube(str) {
return str.toLowerCase().indexOf('youtube.com') > -1;
}
function searchVideo(query, callback) {
request('https://www.googleapis.com/youtube/v3/search?part=id&type=video&q=' +
encodeURIComponent(query) + '&key=' + youtubeAPIKey,
function (error, response, body) {
var json = JSON.parse(body);
if (!json.items[0]) {
callback('5FjWe31S_0g');
} else {
callback(json.items[0].id.videoId);
}
});
}
function getID(str, callback) {
if (isYoutube(str)) {
callback(ytdl.getURLVideoID(str));
} else {
searchVideo(str, function (id) {
callback(id);
});
}
}
async function getVideoInfo(id, callback) {
callback(await ytdl.getInfo(id));
}
function addToQueue(strID, message) {
if (isYoutube(strID)) {
guilds[message.guild.id].queue.push(ytdl.getURLVideoID(strID));
} else {
guilds[message.guild.id].queue.push(strID);
}
}
function playMusic(id, message) {
guilds[message.guild.id].voiceChannel = message.member.voice.channel;
guilds[message.guild.id].voiceChannel.join().then(function (connection) {
stream = ytdl('https://www.youtube.com/watch?v=' + id, {
filter: 'audioonly',
dlChunkSize: 0
});
guilds[message.guild.id].skipReq = 0;
guilds[message.guild.id].skippers = [];
guilds[message.guild.id].dispatcher = connection.play(stream);
guilds[message.guild.id].dispatcher.on('end', function () {
guilds[message.guild.id].skipReq = 0;
guilds[message.guild.id].skippers = [];
guilds[message.guild.id].queue.shift();
guilds[message.guild.id].queueNames.shift();
if (guilds[message.guild.id].queue.length === 0) {
guilds[message.guild.id].queue = [];
guilds[message.guild.id].queueNames = [];
guilds[message.guild.id].isPlaying = false;
} else {
setTimeout(function () {
playMusic(guilds[message.guild.id].queue[0], message);
}, 500);
}
});
});
}
function skipMusic(message) {
guilds[message.guild.id].dispatcher.end();
}
function addToPlayedTracks(message, videoInfo, user){
let trackInfo = {
title: videoInfo.videoDetails.title,
url: videoInfo.videoDetails.video_url,
dateVal: Date.now(),
username: user.username
};
guilds[message.guild.id].playedTracks.push(trackInfo);
if (guilds[message.guild.id].playedTracks.length > 100){
guilds[message.guild.id].playedTracks.shift();
}
}
function getPlayedTracksText(message, trackCount, includeUsers, includeTimes){
const playedTracks = guilds[message.guild.id].playedTracks;
if (trackCount == undefined){
trackCount = playedTracks.length;
}
const startIndex = trackCount >= playedTracks.length ? 0 : playedTracks.length - trackCount;
let tracksText = '';
for (let i = startIndex; i < playedTracks.length; i++){
const trackNum = i - startIndex + 1;
tracksText += `${trackNum}: ${playedTracks[i].title} (<${playedTracks[i].url}>)${(includeUsers ? ' by ' + playedTracks[i].username : '')}${(includeTimes ? ' at ' + formatDate(playedTracks[i].dateVal) : '')}\n`;
}
return tracksText.trim();
}
function splitTextByLines(text, maxCharsPerText){
if (text == undefined || text.length == 0){
return [];
}
if (maxCharsPerText == undefined){
maxCharsPerText = 2000;
}
const lines = text.split('\n');
let messages = [''];
let charCount = 0;
let messageIndex = 0;
for (let i = 0; i < lines.length; i++){
const line = lines[i] + '\n';
charCount += line.length;
if (charCount <= maxCharsPerText){
messages[messageIndex] += line;
} else {
let lineTextRemaining = line;
while (charCount > maxCharsPerText){
let currentLineText = lineTextRemaining.substr(0, maxCharsPerText);
messages.push(currentLineText);
messageIndex++;
charCount -= maxCharsPerText;
if (charCount > 0){
let startSplitIndex = maxCharsPerText <= lineTextRemaining.length ? maxCharsPerText : lineTextRemaining.length - 1;
lineTextRemaining = lineTextRemaining.substring(startSplitIndex, lineTextRemaining.length);
} else {
charCount = 0
}
}
}
}
for (let i = 0; i < messages.length; i++){
messages[i] = messages[i].trim();
}
return messages;
}
function tryParseInt(arg, defaultVal){
if (defaultVal == undefined){
defaultVal = 0;
}
try {
let argNum = parseInt(arg);
if (!isNaN(argNum)){
return argNum;
}
return defaultVal;
} catch (parseException){
return defaultVal;
}
}
//YYYY-MM-DD hh:mm:ss UTC
function formatDate(dateValue){
const date = new Date(dateValue);
return `${date.getUTCFullYear()}-${padTo2DigitInt(date.getUTCMonth() + 1)}-${padTo2DigitInt(date.getUTCDate())} ${padTo2DigitInt(date.getUTCHours())}:${padTo2DigitInt(date.getUTCMinutes())}:${padTo2DigitInt(date.getUTCSeconds())} UTC`;
}
function padTo2DigitInt(intValue){
return intValue > 9 ? '' + intValue: '0' + intValue;
}
client.login(botToken);
|
# onnx_to_tensorrt.py
#
# Copyright 1993-2019 NVIDIA Corporation. All rights reserved.
#
# NOTICE TO LICENSEE:
#
# This source code and/or documentation ("Licensed Deliverables") are
# subject to NVIDIA intellectual property rights under U.S. and
# international Copyright laws.
#
# These Licensed Deliverables contained herein is PROPRIETARY and
# CONFIDENTIAL to NVIDIA and is being provided under the terms and
# conditions of a form of NVIDIA software license agreement by and
# between NVIDIA and Licensee ("License Agreement") or electronically
# accepted by Licensee. Notwithstanding any terms or conditions to
# the contrary in the License Agreement, reproduction or disclosure
# of the Licensed Deliverables to any third party without the express
# written consent of NVIDIA is prohibited.
#
# NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
# LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE
# SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS
# PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
# NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED
# DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
# NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
# NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
# LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY
# SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY
# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
# OF THESE LICENSED DELIVERABLES.
#
# U.S. Government End Users. These Licensed Deliverables are a
# "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT
# 1995), consisting of "commercial computer software" and "commercial
# computer software documentation" as such terms are used in 48
# C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government
# only as a commercial end item. Consistent with 48 C.F.R.12.212 and
# 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all
# U.S. Government End Users acquire the Licensed Deliverables with
# only those rights set forth herein.
#
# Any use of the Licensed Deliverables in individual and commercial
# software must include, in the user documentation and internal
# comments to the code, the above Disclaimer and U.S. Government End
# Users Notice.
#
from __future__ import print_function
import os
import argparse
import tensorrt as trt
MAX_BATCH_SIZE = 2
def get_input_wh(model_name):
input_dim = model_name.split('_')[-1]
if 'x' in input_dim:
dim_split = input_dim.split('x')
if len(dim_split) != 2:
raise SystemExit('ERROR: bad input_dim (%s)!' % input_dim)
w, h = int(dim_split[0]), int(dim_split[1])
else :
print("W, H parsing error")
return w, h
def load_onnx(source):
"""Read the ONNX file."""
if not os.path.isfile(source):
print('ERROR: file (%s) not found!' % source)
return None
else:
with open(source, 'rb') as f:
return f.read()
def set_net_batch(network, batch_size):
"""Set network input batch size.
The ONNX file might have been generated with a different batch size,
say, 64.
"""
if trt.__version__[0] >= '7':
shape = list(network.get_input(0).shape)
shape[0] = batch_size
network.get_input(0).shape = shape
return network
def build_engine(model_name, source, do_fp16, do_int8, dla_core, verbose=False):
"""Build a TensorRT engine from ONNX using the older API."""
net_w, net_h = get_input_wh(model_name)
print('Loading the ONNX file...')
onnx_data = load_onnx(source)
if onnx_data is None:
return None
TRT_LOGGER = trt.Logger(trt.Logger.VERBOSE) if verbose else trt.Logger()
EXPLICIT_BATCH = [] if trt.__version__[0] < '7' else \
[1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)]
with trt.Builder(TRT_LOGGER) as builder, builder.create_network(*EXPLICIT_BATCH) as network, trt.OnnxParser(network, TRT_LOGGER) as parser:
#if do_int8 and not builder.platform_has_fast_int8:
#raise RuntimeError('INT8 not supported on this platform')
if not parser.parse(onnx_data):
print('ERROR: Failed to parse the ONNX file.')
for error in range(parser.num_errors):
print(parser.get_error(error))
return None
network = set_net_batch(network, MAX_BATCH_SIZE)
print('Building an engine. This would take a while...')
print('(Use "--verbose" or "-v" to enable verbose logging.)')
if trt.__version__[0] < '7': # older API: build_cuda_engine()
if dla_core >= 0:
raise RuntimeError('DLA core not supported by old API')
builder.max_batch_size = MAX_BATCH_SIZE
builder.max_workspace_size = 1 << 30
if do_fp16:
builder.fp16_mode = True # alternative: builder.platform_has_fast_fp16
if do_int8:
from utils.calibrator import YOLOEntropyCalibrator
builder.int8_mode = True
builder.int8_calibrator = YOLOEntropyCalibrator(
'calib_images', (net_h, net_w), 'calib_%s.bin' % model_name)
engine = builder.build_cuda_engine(network)
else: # new API: build_engine() with builder config
builder.max_batch_size = 1
config = builder.create_builder_config()
config.max_workspace_size = 1 << 30
config.set_flag(trt.BuilderFlag.GPU_FALLBACK)
if do_fp16:
config.set_flag(trt.BuilderFlag.FP16)
'''
profile = builder.create_optimization_profile()
profile.set_shape(
'000_net', # input tensor name
(1, 3, net_h, net_w), # min shape
(1, 3, net_h, net_w), # opt shape
(1, 3, net_h, net_w)) # max shape
config.add_optimization_profile(profile)
'''
if do_int8:
from utils.calibrator import YOLOEntropyCalibrator
config.set_flag(trt.BuilderFlag.INT8)
config.int8_calibrator = YOLOEntropyCalibrator(
'calib_images', (net_h, net_w),
'calib_%s.bin' % model_name)
config.set_calibration_profile(profile)
if dla_core >= 0:
config.default_device_type = trt.DeviceType.DLA
config.DLA_core = dla_core
config.set_flag(trt.BuilderFlag.STRICT_TYPES)
print('Using DLA core %d.' % dla_core)
engine = builder.build_engine(network, config)
if engine is not None:
print('Completed creating engine.')
return engine
def main():
"""Create a TensorRT engine for ONNX-based POSE."""
parser = argparse.ArgumentParser()
parser.add_argument(
'-v', '--verbose', action='store_true',
help='enable verbose output (for debugging)')
parser.add_argument(
'-m', '--model', type=str, required=True,
help='onnx model path')
parser.add_argument(
'-o', '--outputDir', type=str, required=True,
help='output directory')
parser.add_argument(
'--fp16', action='store_true',
help='build Float16 TensorRT engine')
parser.add_argument(
'--int8', action='store_true',
help='build INT8 TensorRT engine')
parser.add_argument(
'--dla_core', type=int, default=-1,
help='id of DLA core for inference (0 ~ N-1)')
args = parser.parse_args()
model_name = args.model.split(".")[0]
model_name = model_name.split("/")[-1]
if os.path.exists(args.outputDir+'%s.trt' % model_name) == False:
engine = build_engine(
model_name, args.model, args.fp16, args.int8, args.dla_core, args.verbose)
if engine is None:
raise SystemExit('ERROR: failed to build the TensorRT engine!')
else:
print(args.outputDir + '%s.trt' % model_name, "already exists")
exit()
engine_path = args.outputDir + '%s.trt' % model_name
with open(engine_path, 'wb') as f:
f.write(engine.serialize())
print('Serialized the TensorRT engine to file: %s' % engine_path)
if __name__ == '__main__':
main()
|
/**
* @ngdoc service
* @name app.modal.alertModalFactory
* @description < description placeholder >
*/
(function(){
'use strict';
angular
.module('app.modal')
.factory('modalFactory', modalFactory);
/* @ngInject */
function modalFactory($uibModal){
return {
alertModal: alertModal,
changePassword: changePassword
};
////////////////////
/**
* @ngdoc
* @name app.modal.alertModalFactory#testFunction
* @methodOf app.modal.alertModalFactory
*
* @description < description placeholder >
* @example
* <pre>
* alertModalFactory.testFunction(id);
* </pre>
* @param {int} entity id
*/
function changePassword(userId){
var modalInstance = $uibModal.open({
animation: true,
templateUrl: 'src/setup/changePassword/changePassword.template.html',
controller: 'ChangePasswordModal as vm',
size: 'md',
windowClass: 'marginTopPlus150px',
resolve:{
userId: function(){
return userId;
}
}
});
}
function alertModal(name, type, action){
var modalInstance = $uibModal.open({
animation: true,
templateUrl: 'src/modal/alertmodal.template.html',
controller: 'AlertModal as vm',
size: 'sm',
windowClass: 'marginTopPlus150px',
resolve: {
name: function () {
return name;
},
type: function(){
return type
},
action: function(){
return action
}
}
});
return modalInstance.result.then(function (confirm) {
return confirm;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
}
}
}());
|
'use strict';
var $ = require('jquery');
var { API_URL } = require('ozp-react-commons/OzoneConfig');
var ProfileApi = {
getStewards: function() {
return $.getJSON(API_URL + '/api/profile?role=ORG_STEWARD');
}
};
module.exports = ProfileApi;
|
const path = require('path');
const host = require('./host');
const faker = require('faker');
const firstName = faker.name.findName();
const lastName = faker.name.findName();
const newLastName = faker.name.findName();
const email = faker.internet.email();
const newEmail = faker.internet.email();
const text = faker.lorem.text();
const newText = faker.lorem.text();
const title = faker.name.title();
const newTitle = faker.name.title();
const words = faker.lorem.words();
const imagePath = path.resolve('/Users/andeladeveloper/Desktop/more-recipes/More-Recipes/client/images/recipe7.jpg');
module.exports = {
'Sign up a new user': client =>
client
.url(host.url)
.waitForElementVisible('body', 1000)
.pause(1000)
.waitForElementVisible('div#mainContainer', 1000)
.pause(1000)
.click('#signupLink')
.pause(1000)
.setValue('input[name=firstName]', firstName)
.pause(1000)
.setValue('input[name=lastName]', lastName)
.pause(1000)
.setValue('input[name=email]', email)
.pause(1000)
.setValue('input[name=password]', '123456')
.pause(1000)
.setValue('input[name=confirmPassword]', '123456')
.pause(1000)
.click('#registerbutton')
.pause(1000)
.click('.nav-link.dropdown-toggle')
.pause(1000)
.click('#signoutLink')
.pause(1000)
.waitForElementVisible('.container-fluid.main-login-container', 1000)
.pause(1000),
'sign in': client =>
client
.waitForElementVisible('body', 1000)
.pause(1000)
.waitForElementVisible('div#mainContainer', 1000)
.pause(1000)
.setValue('input[name=email]', email)
.pause(1000)
.setValue('input[name=password]', '123456')
.pause(1000)
.click('#signinButton')
.pause(1000),
'View all recipes': client =>
client
.waitForElementVisible('body', 2000)
.pause(1000)
.waitForElementVisible('div#mainContainer', 2000)
.pause(1000)
.click('#catalogue')
.pause(1000),
'Search recipes': client =>
client
.waitForElementVisible('body', 2000)
.pause(1000)
.waitForElementVisible('div#mainContainer', 2000)
.pause(1000)
.setValue('input[ type="search"]', 'milk')
.pause(2000)
.clearValue('input[type=search]')
.pause(2000)
.setValue('input[ type="search"]', 'asdf')
.pause(2000)
.clearValue('input[type=search]')
.pause(2000)
.setValue('input[ type="search"]', 'pepper')
.pause(2000),
'Sort Recipe': client =>
client
.waitForElementVisible('#sortButton', 2000)
.pause(1000)
.click('#sortButton')
.pause(1000)
.click('#downvotes')
.pause(1000),
'Order Recipe': client =>
client
.click('#orderButton')
.pause(1000)
.click('#desc')
.pause(1000),
'View single recipe': client =>
client
.assert.visible('#viewDetails')
.assert
.containsText('#viewDetails', 'view details')
.pause(1000)
.execute(function () {
document.querySelector('#viewDetails').scrollIntoView();
}, ['#viewDetails'])
.pause(1000)
.click('#viewDetails')
.pause(1000)
.assert.visible('#recipeDetails')
.pause(1000),
'upvote recipe': client =>
client
.waitForElementVisible('body', 1000)
.pause(1000)
.waitForElementVisible('div#mainContainer', 1000)
.pause(1000)
.click('#upvote')
.pause(1000),
'downvote recipe': client =>
client
.waitForElementVisible('#downvote', 1000)
.pause(1000)
.assert.visible('#downvote')
.click('#downvote')
.pause(2000),
'favourite a recipe': client =>
client
.waitForElementVisible('#favourite', 7000)
.pause(1000)
.assert.visible('#favourite')
.pause(1000)
.waitForElementPresent('#favourite', 5000)
.pause(1000)
.assert.elementPresent('#favourite')
.click('#favourite')
.pause(1000),
'Add review': client =>
client
.waitForElementVisible('#addReview', 2000)
.pause(1000)
.assert.visible('#addReview')
.setValue('#review', 'some review to test this recipe')
.pause(1000)
.click('#addReview')
.pause(2000),
'Add Recipe Action': client =>
client
.click('.nav-link.dropdown-toggle')
.pause(1000)
.click('#addRecipe')
.pause(1000)
.waitForElementVisible('body', 5000)
.pause(5000)
.waitForElementVisible('div#mainContainer', 5000)
.pause(5000)
.click('input[type=submit]')
.pause(1000)
.setValue('input[type="file"]', imagePath)
.pause(1000)
.setValue('input[name=title]', title)
.pause(1000)
.setValue('input[name=ingredients]', words)
.pause(1000)
.setValue('#instructions', text)
.pause(1000)
.click('input[type=submit]')
.pause(1000),
'Favourite Recipe Action': client =>
client
.waitForElementVisible('#userRecipePage', 20000)
.pause(1000)
.click('.nav-link.dropdown-toggle')
.pause(1000)
.click('#favouriteRecipe')
.pause(1000)
.waitForElementVisible('body', 1000)
.pause(1000)
.waitForElementVisible('div#mainContainer', 1000)
.pause(1000)
.click('.btn.btn-outline-info.ml-2')
.pause(1000)
.click('.react-confirm-alert-button-group > button:nth-child(2)')
.pause(1000),
'Edit Recipe Action': client =>
client
.click('.nav-link.dropdown-toggle')
.pause(1000)
.click('#addRecipe')
.pause(1000)
.waitForElementVisible('#instructions', 1000)
.pause(1000)
.setValue('input[type="file"]', imagePath)
.pause(1000)
.setValue('input[name=title]', newTitle)
.pause(1000)
.setValue('input[name=ingredients]', words)
.pause(1000)
.setValue('#instructions', newText)
.pause(1000)
.click('input[type=submit]')
.pause(1000)
.waitForElementVisible('#editRecipe', 20000)
.click('#editRecipe')
.pause(1000)
.click('input[type=submit]')
.pause(1000),
'Edit User Profile Action': client =>
client
.click('.nav-link.dropdown-toggle')
.pause(1000)
.click('#editProfile')
.pause(1000)
.waitForElementVisible('body', 1000)
.pause(1000)
.waitForElementVisible('div#mainContainer', 1000)
.pause(1000)
.clearValue('input[name=firstName]')
.pause(1000)
.clearValue('input[name=firstName]')
.pause(1000)
.setValue('input[name=lastName]', newLastName)
.pause(1000)
.click('input[type=submit]')
.pause(1000),
'Edit Password': client =>
client
.click('.nav-link.dropdown-toggle')
.pause(1000)
.click('#editPassword')
.pause(1000)
.waitForElementVisible('body', 1000)
.pause(1000)
.waitForElementVisible('div#mainContainer', 1000)
.pause(1000)
.clearValue('input[name=password]')
.pause(1000)
.clearValue('input[name=confirmPassword]')
.pause(1000)
.setValue('input[name=password]', '456789')
.pause(1000)
.setValue('input[name=confirmPassword]', '456789')
.pause(1000)
.click('input[type=submit]')
.pause(1000)
.click('.nav-link.dropdown-toggle')
.pause(1000)
.click('#signoutLink')
.pause(1000),
'redirect unauthenticated user to signin page': client =>
client
.waitForElementVisible('body', 1000)
.pause(1000)
.waitForElementVisible('div#mainContainer', 1000)
.pause(1000)
.waitForElementVisible('#catalogue', 1000)
.pause(1000)
.click('#catalogue')
.pause(1000)
.execute(function () {
document.querySelector('#viewDetails').scrollIntoView();
}, ['#viewDetails'])
.click('#viewDetails')
.pause(1000)
.click('#upvote')
.pause(1000),
'validate user input on sign up': client =>
client
.url(host.url)
.waitForElementVisible('body', 1000)
.pause(1000)
.waitForElementVisible('div#mainContainer', 1000)
.pause(1000)
.click('#signupLink')
.pause(1000)
.setValue('input[name=firstName]', firstName)
.pause(1000)
.setValue('input[name=lastName]', lastName)
.pause(1000)
.click('#registerbutton')
.pause(1000)
.setValue('input[name=email]', email)
.pause(1000)
.click('#registerbutton')
.pause(1000)
.setValue('input[name=password]', '123456')
.pause(1000)
.click('#registerbutton')
.pause(1000)
.setValue('input[name=confirmPassword]', '123456')
.pause(1000)
.click('#registerbutton')
.pause(1000)
.clearValue('input[name=email]')
.pause(1000)
.setValue('input[name=email]', newEmail)
.pause(1000)
.click('#registerbutton')
.pause(1000)
.click('.nav-link.dropdown-toggle')
.pause(1000)
.click('#signoutLink')
.pause(1000)
.waitForElementVisible('.container-fluid.main-login-container', 1000)
.pause(1000),
'validate user input on sign in': client =>
client
.waitForElementVisible('body', 1000)
.pause(1000)
.waitForElementVisible('div#mainContainer', 2000)
.pause(1000)
.setValue('input[name=email]', email)
.pause(1000)
.click('#signinButton')
.pause(1000)
.setValue('input[name=password]', '123456')
.pause(1000)
.click('#signinButton')
.pause(1000)
.clearValue('input[name=password]')
.pause(1000)
.setValue('input[name=password]', '456789')
.click('#signinButton')
.pause(2000)
.end()
};
|
// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
'use strict';
lib.rtdep('lib.f');
/**
* This file contains the support required to make connections to Google's
* HTTP-to-SSH relay.
*
* See Also: nassh_stream_google_relay.js, which defines the hterm stream class
* for this relay mechanism.
*
* The relay is only available within Google at the moment. If you'd like
* to create one of your own though, you could follow the same conventions
* and have a client ready to go.
*
* The connection looks like this...
*
* +------+ +-------+ +---------------+
* | USER | | PROXY | | COOKIE_SERVER |
* +------+ +-------+ +---------------+
*
* +-----------+
* | SSH_RELAY |
* +-----------+
*
* 1. User specifies that they'd like to make their ssh connection through a
* web server. In this code, that web server is called the 'proxy', since
* it happens to be an HTTP proxy.
*
* 2. We redirect to the 'http://HOST:8022/cookie?ext=RETURN_TO'.
*
* HOST is the user-specified hostname for the proxy. Port 8022 on the
* proxy is assumed to be the cookie server.
*
* RETURN_TO is the location that the cookie server should redirect to
* when the cookie server is satisfied.
*
* This connects us to the 'cookie server', which can initiate a
* single-sign-on flow if necessary. It's also responsible for telling us
* which SSH_RELAY server we should talk to for the actual ssh read/write
* operations.
*
* 3. When the cookie server is done with its business it redirects to
* /html/google_relay.html#USER@RELAY_HOST.
*
* The RELAY_HOST is the host that we should use as the socket relay.
* This allows the cookie server to choose a relay server from a
* pool of hosts. This is *just* the host name, it's up to clients to
* know the uri scheme and port number.
*
* The RELAY_HOST is expected to respond to requests for /proxy, /write,
* and /read.
*
* 4. We send a request to /proxy, which establishes the ssh session with
* a remote host.
*
* 5. We establish a hanging GET on /read. If the read completes with a
* HTTP 200 OK then we consider the response entity as web-safe base 64
* encoded data. If the read completes with an HTTP 401 GONE, we assume
* the relay has discarded the ssh session. Any other responses are
* ignored. The /read request is reestablished for anything other than
* 401.
*
* 6. Writes are queued up and sent to /write.
*/
nassh.GoogleRelay = function(io, optionString, relayLocation, relayStorage) {
this.io = io;
this.options = nassh.GoogleRelay.parseOptionString(optionString);
this.proxyHost = this.options['--proxy-host'];
this.proxyPort = this.options['--proxy-port'] || 8022;
this.useSecure = this.options['--use-ssl'];
this.useWebsocket = !this.options['--use-xhr'];
this.reportAckLatency = this.options['--report-ack-latency'];
this.reportConnectAttempts = this.options['--report-connect-attempts'];
this.relayProtocol = this.options['--relay-protocol'];
this.relayServer = null;
this.relayServerSocket = null;
this.location = relayLocation;
this.storage = relayStorage;
};
nassh.GoogleRelay.parseOptionString = function(optionString) {
var rv = {};
var optionList = optionString.trim().split(/\s+/g);
for (var i = 0; i < optionList.length; i++) {
// Make sure it's a long option first.
const option = optionList[i];
if (!option.startsWith('--'))
throw Error(option);
// Split apart the option if there is an = in it.
let flag, value;
const pos = option.indexOf('=');
if (pos == -1) {
// If there is no = then it's a boolean flag (which --no- disables).
value = !option.startsWith('--no-');
flag = option.slice(value ? 2 : 5);
} else {
flag = option.slice(2, pos);
value = option.slice(pos + 1);
}
// Verify it's an option we support.
if (!nassh.GoogleRelay.parseOptionString.validOptions_.includes(flag))
throw Error(option);
rv[`--${flag}`] = value;
}
if (rv['--config'] == 'google') {
rv['auth-agent-forward'] = true;
if (!('--proxy-host' in rv))
rv['--proxy-host'] = 'ssh-relay.corp.google.com';
if (!('--proxy-port' in rv))
rv['--proxy-port'] = '443';
if (!('--use-ssl' in rv))
rv['--use-ssl'] = true;
if (!('--report-ack-latency' in rv))
rv['--report-ack-latency'] = true;
if (!('--report-connect-attempts' in rv))
rv['--report-connect-attempts'] = true;
if (!('--relay-protocol' in rv))
rv['--relay-protocol'] = 'v2';
if (!('--ssh-agent' in rv))
rv['--ssh-agent'] = nassh.GoogleRelay.defaultGnubbyExtension;
}
return rv;
};
/**
* All possible flags that may show up in the relay options.
* Currently this covers all options even non-Google relay ones.
*
* Note: Keep this in sync with nassh_connect_dialog.html.
*/
nassh.GoogleRelay.parseOptionString.validOptions_ = [
'config',
'proxy-host',
'proxy-port',
'relay-prefix-field',
'relay-protocol',
'report-ack-latency',
'report-connect-attempts',
'ssh-agent',
'ssh-client-version',
'use-ssl',
'use-xhr',
];
/**
* Returns the pattern for the cookie server URL.
*/
nassh.GoogleRelay.prototype.cookieServerPattern = function() {
var template = '%(protocol)://%(host):%(port)/cookie' +
'?ext=%encodeURIComponent(return_to)' +
'&path=html/nassh_google_relay.html';
if (this.relayProtocol == 'v2') {
template += '&version=2&method=js-redirect';
}
return template;
};
/**
* The pattern for XHR relay server's url.
*
* We'll be appending 'proxy', 'read' and 'write' to this as necessary.
*/
nassh.GoogleRelay.prototype.relayServerPattern =
'%(protocol)://%(host):%(port)/';
nassh.GoogleRelay.prototype.redirect = function(opt_resumePath) {
var resumePath = opt_resumePath ||
this.location.href.substr(this.location.origin.length);
// Save off our destination in session storage before we leave for the
// proxy page.
this.storage.setItem('googleRelay.resumePath', resumePath);
this.location.href = lib.f.replaceVars(
this.cookieServerPattern(),
{ host: this.proxyHost,
port: this.proxyPort,
protocol: this.useSecure ? 'https' : 'http',
// This returns us to nassh_google_relay.html so we can pick the relay
// host out of the reply. From there we continue on to the resumePath.
return_to: this.location.host
});
};
/**
* Initialize this relay object.
*
* If we haven't just come back from the cookie server, then this function
* will redirect to the cookie server and return false.
*
* If we have just come back from the cookie server, then we'll return true.
*/
nassh.GoogleRelay.prototype.init = function(opt_resumePath) {
var resumePath = opt_resumePath ||
this.location.href.substr(this.location.origin.length);
// This session storage item is created by /html/nassh_google_relay.html
// if we succeed at finding a relay host.
var relayHost = this.storage.getItem('googleRelay.relayHost');
var relayPort = this.storage.getItem('googleRelay.relayPort') ||
this.proxyPort;
if (relayHost) {
var relayPrefixField = parseInt(this.options['--relay-prefix-field']);
if (relayPrefixField) {
// If this option is set, we're supposed to assume the relayHost is a
// '.' delimited list of fields (like a hostname), isolate the field
// at the 1-based relayPrefixField position, and create the actual
// relayHost by prepending this field to the original proxyHost.
//
// TODO(rginda): Yes, this is a kludge. Returning the correct hostname
// from the proxy is sometimes difficult, for a reason unknown to me.
var relayPrefix = relayHost.split(/\./g)[relayPrefixField - 1];
if (relayPrefix) {
if (this.proxyHost.substr(0, relayPrefix.length + 1) !=
relayPrefix + '.') {
// Only add the prefix if the proxyHost doesn't already include it.
relayHost = relayPrefix + '.' + this.proxyHost;
} else {
relayHost = this.proxyHost;
}
} else {
console.warn('Error getting relay prefix field: ' + relayPrefixField +
' from: ' + relayHost);
this.relayHost = null;
}
}
var expectedResumePath =
this.storage.getItem('googleRelay.resumePath');
if (expectedResumePath == resumePath) {
var protocol = this.useSecure ? 'https' : 'http';
var pattern = this.relayServerPattern;
this.relayServer = lib.f.replaceVars(pattern,
{host: relayHost, port: relayPort, protocol: protocol});
if (!this.useXHR) {
protocol = this.useSecure ? 'wss' : 'ws';
this.relayServerSocket = lib.f.replaceVars(pattern,
{host: relayHost, port: relayPort, protocol: protocol});
}
// If we made it this far, we're probably not stuck in a redirect loop.
sessionStorage.removeItem('googleRelay.redirectCount');
} else {
// If everything is ok, this should be the second time we've been asked
// to do the same init. (The first time would have redirected.) If this
// init specifies a different resumePath, then something is probably
// wrong.
console.warn('Destination mismatch: ' + expectedResumePath + ' != ' +
resumePath);
this.relayServer = null;
}
}
this.storage.removeItem('googleRelay.relayHost');
this.storage.removeItem('googleRelay.relayPort');
this.storage.removeItem('googleRelay.resumePath');
if (this.relayServer) {
this.io.println(nassh.msg('FOUND_RELAY', [this.relayServer]));
return true;
}
return false;
};
/**
* Return an nassh.Stream object that will handle the socket stream
* for this relay.
*/
nassh.GoogleRelay.prototype.openSocket = function(fd, host, port, streams,
onOpen) {
var streamClass = this.useWebsocket ? nassh.Stream.GoogleRelayWS :
nassh.Stream.GoogleRelayXHR;
return streams.openStream(streamClass,
fd, {relay: this, host: host, port: port}, onOpen);
};
/**
* Find a usable gnubby extension.
*/
nassh.GoogleRelay.findGnubbyExtension = function() {
const appId = 'beknehfpfkghjoafdifaflglpjkojoco';
const extId = 'lkjlajklkdhaneeelolkfgbpikkgnkpk';
// Ping the extension to see if it's alive.
const check = (id) => new Promise((resolve, reject) => {
chrome.runtime.sendMessage(id, {'type': 'HELLO'}, (result) => {
if (result !== undefined && result['rc'] == 0)
resolve(id);
});
});
// Pick a default in case neither is installed.
nassh.GoogleRelay.defaultGnubbyExtension = extId;
// We don't care which one is available, so go with the first response.
Promise.race([
check(appId),
check(extId),
new Promise((resolve, reject) => setTimeout(resolve, 1000)),
]).then((foundId) => {
if (foundId)
nassh.GoogleRelay.defaultGnubbyExtension = foundId;
});
};
/**
* Register gnubby extension probing.
*
* This could take time to resolve, so do it as part of start up.
* It resolves using promises in the background, so this is OK.
*/
lib.registerInit('gnubby probe', function(onInit) {
nassh.GoogleRelay.findGnubbyExtension();
onInit();
});
|