text
stringlengths
2
1.05M
/** * Configures a Keystone app in encapsulated mode, but does not start it. * * Connects to the database and runs updates and then calls back. * * This is the code-path to use if you'd like to mount the keystone app as a sub-app in another express application. * * var app = express(); * * //...do your normal express setup stuff, add middleware and routes (but not static content or error handling middleware yet) * * keystone.mount('/content', app, function() { * //put your app's static content and error handling middleware here and start your server * }); * * Events are fired during initialisation to allow customisation, including: * * - onMount * * If the events argument is a function, it is assumed to be the mounted event. * * * ####Options: * * Keystone supports the following options specifically for running in encapsulated mode (with no embedded server): * * - name * - port * - views * - view engine * - compress * - favico * - less * - static * - headless * - logger * - cookie secret * - session * - 404 * - 500 * - routes * - locals * - auto update * * * @api public */ var _ = require('underscore'); var debug = require('debug')('keystone:core:mount'); var P = require('bluebird'); var express = require('express'); var path = require('path'); var utils = require('keystone-utils'); var favicon = require('serve-favicon'); var morgan = require('morgan'); var methodOverride = require('method-override'); var session = require('express-session'); var multer = require('multer'); var bodyParser = require('body-parser'); var cookieParser = require('cookie-parser'); var compression = require('compression'); var dashes = '\n------------------------------------------------\n'; function mount(mountPath, parentApp, events) { debug('mounting'); // Validate the express app instance if (!this.app) { console.error('\nKeystoneJS Initialisaton Error:\n\napp must be initialised. Call keystone.init() or keystone.connect(new Express()) first.\n'); process.exit(1); } // Localise references to this for closures var keystone = this; var app = this.app; // this.nativeApp indicates keystone has been mounted natively // (not as part of a custom middleware stack) // this.nativeApp = true; // Initialise the mongo connection url if (!this.get('mongo')) { var dbName = this.get('db name') || utils.slug(this.get('name')); var dbUrl = process.env.MONGO_URI || process.env.MONGO_URL || process.env.MONGODB_URL || process.env.MONGOLAB_URI || process.env.MONGOLAB_URL || (process.env.OPENSHIFT_MONGODB_DB_URL || 'mongodb://localhost/') + dbName; debug('setting DB URI to : ' + dbUrl); this.set('mongo', dbUrl); } // Initialise and validate session options if (!this.get('cookie secret')) { console.error('\nKeystoneJS Configuration Error:\n\nPlease provide a `cookie secret` value for session encryption.\n'); process.exit(1); } var sessionOptions = this.get('session options'); if (!_.isObject(sessionOptions)) { sessionOptions = {}; } if (!sessionOptions.key) { sessionOptions.key = 'keystone.sid'; } _.defaults(sessionOptions, { resave: false, secret: this.get('cookie secret'), saveUninitialized: false }); sessionOptions.cookieParser = cookieParser(this.get('cookie secret')); var sessionStore = this.get('session store'); var sessionStorePromise; if (typeof sessionStore === 'function') { sessionOptions.store = sessionStore(session); } else if (sessionStore) { var sessionStoreOptions = this.get('session store options') || {}; // Perform any session store specific configuration or exit on an unsupported session store if (sessionStore === 'mongo') { sessionStore = 'connect-mongo'; } else if (sessionStore === 'redis') { sessionStore = 'connect-redis'; } switch (sessionStore) { case 'connect-mongo': debug('using mongo for session store'); _.defaults(sessionStoreOptions, { collection: 'app_sessions', url: this.get('mongo') }); break; case 'connect-mongostore': debug('using connect-mongostore for session store'); _.defaults(sessionStoreOptions, { collection: 'app_sessions' }); if (!sessionStoreOptions.db) { console.error( '\nERROR: connect-mongostore requires `session store options` to be set.' + '\n' + '\nSee http://keystonejs.com/docs/configuration#options-database for details.' + '\n'); process.exit(1); } break; case 'connect-redis': debug('using redis for session store'); break; default: console.error( '\nERROR: unsupported session store ' + sessionStore + '.' + '\n' + '\nSee http://keystonejs.com/docs/configuration#options-database for details.' + '\n'); process.exit(1); break; } // Initialize the session store try { var SessionStore = require(sessionStore)(session); sessionStorePromise = new P(function(resolve) { sessionOptions.store = new SessionStore(sessionStoreOptions, resolve); sessionOptions.store.on('connect', resolve); sessionOptions.store.on('connected', resolve); sessionOptions.store.on('disconnect', function() { console.error( '\nThere was an error connecting to the ' + sessionStore + ' session store.' + '\n'); process.exit(1); }); }); } catch(e) { if (e.code === 'MODULE_NOT_FOUND') { console.error( '\n' + e.toString() + '\nTo use ' + this.get('session store') + ' as a `session store` option, run:' + '\nnpm install ' + sessionStore + ' --save' + '\n'); process.exit(1); } else { throw e; } } } // expose initialised session and options this.set('session options', sessionOptions); this.set('express session', session(sessionOptions)); // wrangle arguments if (arguments.length === 1) { events = arguments[0]; mountPath = null; } if ('function' === typeof events) { events = { onMount: events }; } if (!events) events = {}; /* Express sub-app mounting to external app at a mount point (if specified) */ if (mountPath) { //fix root-relative keystone urls for assets (gets around having to re-write all the keystone templates) parentApp.all(/^\/keystone($|\/.*)/, function(req, res, next) { req.url = mountPath + req.url; next(); }); parentApp.use(mountPath, app); } /* Keystone's encapsulated Express App Setup */ // Allow usage of custom view engines if (this.get('custom engine')) { app.engine(this.get('view engine'), this.get('custom engine')); } // Set location of view templates and view engine app.set('views', this.getPath('views') || path.sep + 'views'); app.set('view engine', this.get('view engine')); // Apply locals if (utils.isObject(this.get('locals'))) { _.extend(app.locals, this.get('locals')); } // Indent HTML everywhere, except production if (this.get('env') !== 'production') { app.locals.pretty = true; } // Default view caching logic app.set('view cache', this.get('env') === 'production' ? true : false); // Setup view caching from app settings if (this.get('view cache') !== undefined) { app.set('view cache', this.get('view cache')); } // Serve static assets if (this.get('compress')) { app.use(compression()); } if (this.get('favico')) { app.use(favicon(this.getPath('favico'))); } // unless the headless option is set (which disables the Admin UI), // add the Admin UI's Static Router for public resources if (!this.get('headless')) { app.use('/keystone', require('../../admin/app/static')); } // the less option can be a single path, or array of paths // when set, we configure the less middleware var lessPaths = this.get('less'); var lessOptions = this.get('less options') || {}; if (_.isString(lessPaths)) { lessPaths = [lessPaths]; } if (_.isArray(lessPaths)) { _.each(lessPaths, function(value) { app.use(require('less-middleware')(this.expandPath(value), lessOptions)); }, this); } // the sass option can be a single path, or array of paths // when set, we configure the node-sass middleware var sassPaths = this.get('sass'), sassOptions = this.get('sass options') || {}; if (_.isString(sassPaths)) { sassPaths = [sassPaths]; } if (_.isArray(sassPaths)) { var sassMiddleware; try { debug('adding sass'); sassMiddleware = require('node-sass-middleware'); } catch(e) { if (e.code === 'MODULE_NOT_FOUND') { console.error( '\nERROR: node-sass not found.\n' + '\nPlease install the node-sass-middleware from npm to use the `sass` option.' + '\nYou can do this by running "npm install node-sass-middleware --save".\n' ); process.exit(1); } else { throw e; } } _.each(sassPaths, function(value) { app.use(sassMiddleware(_.extend({ src: this.expandPath(value), dest: this.expandPath(value), outputStyle: this.get('env') === 'production' ? 'compressed' : 'nested' }, sassOptions))); }, this); } // the static option can be a single path, or array of paths // when set, we configure the express static middleware var staticPaths = this.get('static'); var staticOptions = this.get('static options'); if (_.isString(staticPaths)) { staticPaths = [staticPaths]; } if (_.isArray(staticPaths)) { _.each(staticPaths, function(value) { app.use(express.static(this.expandPath(value), staticOptions)); }, this); } // Handle dynamic requests if (this.get('logger')) { debug('adding request logger'); app.use(morgan(this.get('logger'), this.get('logger options'))); } var bodyParserParams = {}; if (this.get('file limit')) { debug('adding file limit'); bodyParserParams.limit = this.get('file limit'); } debug('adding standard middleware'); app.use(bodyParser.json(bodyParserParams)); bodyParserParams.extended = true; app.use(bodyParser.urlencoded(bodyParserParams)); app.use(methodOverride()); app.use(sessionOptions.cookieParser); app.use(this.get('express session')); app.use(multer({ includeEmptyFields: true })); app.use(require('connect-flash')()); if (this.get('session') === true) { app.use(this.session.persist); } else if ('function' === typeof this.get('session')) { app.use(this.get('session')); } // Add 'X-Frame-Options' to response header for ClickJacking protection if (this.get('frame guard')) { debug('enabling frame guard'); app.use(require('../security/frameGuard')(this)); } // Process 'X-Forwarded-For' request header if (this.get('trust proxy') === true) { debug('enabling trusted proxy'); app.enable('trust proxy'); } else { app.disable('trust proxy'); } // Check for IP range restrictions if (this.get('allowed ip ranges')) { if (!app.get('trust proxy')) { console.log( 'KeystoneJS Initialisaton Error:\n\n' + 'to set IP range restrictions the "trust proxy" setting must be enabled.\n\n' ); process.exit(1); } debug('adding IP ranges', this.get('allowed ip ranges')); var ipRangeMiddleware = require('../security/ipRangeRestrict')( this.get('allowed ip ranges'), this.wrapHTMLError ); this.pre('routes', ipRangeMiddleware); } // Pre-route middleware app.use(function(req, res, next){ debug('adding pre-route middlewares'); keystone.callHook('pre:routes', req, res, next); }); // unless the headless option is set (which disables the Admin UI), // include the Admin UI route handlers if (!this.get('headless')) { debug('adding keystone routes to express app'); this.routes(app); } // Configure application routes if ('function' === typeof this.get('routes')) { debug('configuring app routes'); this.get('routes')(app); } //prepare the error handlers; they should be called last var setHandlers = function () { // Handle redirects before 404s if (Object.keys(keystone._redirects).length) { app.use(function(req, res, next) { if (keystone._redirects[req.path]) { res.redirect(keystone._redirects[req.path]); } else { next(); } }); } // Handle 404 (no route matched) errors var default404Handler = function(req, res, next) {// eslint-disable-line no-unused-vars res.status(404).send(keystone.wrapHTMLError('Sorry, no page could be found at this address (404)')); }; app.use(function(req, res, next) { var err404 = keystone.get('404'); if (err404) { try { if ('function' === typeof err404) { err404(req, res, next); } else if ('string' === typeof err404) { res.status(404).render(err404); } else { if (keystone.get('logger')) { console.log(dashes + 'Error handling 404 (not found): Invalid type (' + (typeof err404) + ') for 404 setting.' + dashes); } default404Handler(req, res, next); } } catch(e) { if (keystone.get('logger')) { console.log(dashes + 'Error handling 404 (not found):'); console.log(e); console.log(dashes); } default404Handler(req, res, next); } } else { default404Handler(req, res, next); } }); // Handle other errors var default500Handler = function(err, req, res, next) {// eslint-disable-line no-unused-vars if (keystone.get('logger')) { if (err instanceof Error) { console.log((err.type ? err.type + ' ' : '') + 'Error thrown for request: ' + req.url); } else { console.log('Error thrown for request: ' + req.url); } console.log(err.stack || err); } var msg = ''; if (keystone.get('env') === 'development') { if (err instanceof Error) { if (err.type) { msg += '<h2>' + err.type + '</h2>'; } msg += utils.textToHTML(err.message); } else if ('object' === typeof err) { msg += '<code>' + JSON.stringify(err) + '</code>'; } else if (err) { msg += err; } } res.status(500).send(keystone.wrapHTMLError('Sorry, an error occurred loading the page (500)', msg)); }; app.use(function(err, req, res, next) { var err500 = keystone.get('500'); if (err500) { try { if ('function' === typeof err500) { err500(err, req, res, next); } else if ('string' === typeof err500) { res.locals.err = err; res.status(500).render(err500); } else { if (keystone.get('logger')) { console.log(dashes + 'Error handling 500 (error): Invalid type (' + (typeof err500) + ') for 500 setting.' + dashes); } default500Handler(err, req, res, next); } } catch(e) { if (keystone.get('logger')) { console.log(dashes + 'Error handling 500 (error):'); console.log(e); console.log(dashes); } default500Handler(err, req, res, next); } } else { default500Handler(err, req, res, next); } }); }; // Connect to database var mongoConnectionOpen = false; // support replica sets for mongoose if (this.get('mongo replica set')){ debug('setting up mongo replica set'); var replicaData = this.get('mongo replica set'); var replica = ''; var credentials = (replicaData.username && replicaData.password) ? replicaData.username + ':' + replicaData.password + '@' : ''; replicaData.db.servers.forEach(function (server) { replica += 'mongodb://' + credentials + server.host + ':' + server.port + '/' + replicaData.db.name + ','; }); var options = { auth: { authSource: replicaData.authSource }, replset: { rs_name: replicaData.db.replicaSetOptions.rs_name, readPreference: replicaData.db.replicaSetOptions.readPreference } }; debug('connecting to replicate set'); this.mongoose.connect(replica, options); } else { debug('connecting to mongo'); this.mongoose.connect(this.get('mongo')); } this.mongoose.connection.on('error', function(err) { if (keystone.get('logger')) { console.log('------------------------------------------------'); console.log('Mongo Error:\n'); console.log(err); } if (mongoConnectionOpen) { if (err.name === 'ValidationError') return; throw err; } else { throw new Error('KeystoneJS (' + keystone.get('name') + ') failed to start'); } }).on('open', function() { debug('mongo connection open'); mongoConnectionOpen = true; var mounted = function() { events.onMount && events.onMount();// eslint-disable-line no-unused-expressions setHandlers(); }; var connected = function() { if (keystone.get('auto update')) { debug('applying auto update'); keystone.applyUpdates(mounted); } else { mounted(); } }; if (sessionStorePromise) { sessionStorePromise.then(connected); } else { connected(); } }); } module.exports = mount;
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.intersect_ = exports.memoize = void 0; /** * @since 2.2.0 */ function memoize(f) { var cache = new Map(); return function (a) { if (!cache.has(a)) { var b = f(a); cache.set(a, b); return b; } return cache.get(a); }; } exports.memoize = memoize; // ------------------------------------------------------------------------------------- // utils // ------------------------------------------------------------------------------------- var typeOf = function (x) { return (x === null ? 'null' : typeof x); }; /** * @internal */ var intersect_ = function (a, b) { if (a !== undefined && b !== undefined) { var tx = typeOf(a); var ty = typeOf(b); if (tx === 'object' || ty === 'object') { return Object.assign({}, a, b); } } return b; }; exports.intersect_ = intersect_;
const db = require("../config/mySQL"); const bcrypt = require("bcrypt"); const jwt = require("jsonwebtoken"); const otp = require("otp-generator"); const nodemailer = require("nodemailer"); module.exports = { postNewUser: (body) => { return new Promise((resolve, reject) => { const email = body.email; const queryCheckEmail = "SELECT email FROM users WHERE email=?"; db.query(queryCheckEmail, email, (err, data) => { if (!data[0]) { const saltRounds = 10; bcrypt.genSalt(saltRounds, (err, salt) => { if (err) { reject(err); } bcrypt.hash(body.password, salt, (err, hashedPassword) => { if (err) { reject(err); } const newBody = { ...body, password: hashedPassword, }; const queryString = "INSERT INTO users SET ?"; db.query(queryString, newBody, (err, data) => { if (!err) { resolve(data); } else { reject(err); } }); }); }); } else { reject({ message: "Email is already exists!", status: 403, }); } }); }); }, postLogin: (body) => { return new Promise((resolve, reject) => { const { email, password } = body; const queryString = "SELECT id, level_id, email, full_name, password FROM users where email = ?"; db.query(queryString, email, (err, data) => { if (err) { reject({ msg: "Error SQL", status: 500, err, }); } // Handle User Not Found"," if (!data[0]) { reject({ msg: "User Not Found", status: 404, }); } else { // console.log(data); bcrypt.compare(password, data[0].password, (err, result) => { if (err) { reject({ msg: "Hash Error", status: 500, err, }); } if (!result) { reject({ msg: "Wrong Password", status: 401, }); } else { const payload = { level_id: data[0].level_id, id: data[0].id, email: data[0].email, }; const secret = process.env.SECRET_KEY; // const token = jwt.sign({email: data[0].email, level_id : data[0].level_id} , secret); const token = jwt.sign(payload, secret, { expiresIn: "1d" }); resolve({ token, full_name: data[0].full_name, email: data[0].email, user_id: data[0].id, level: data[0].level_id, }); console.log(resolve); } }); } }); }); }, postLogout: (whitelisttoken) => { return new Promise((resolve, reject) => { const queryString = "DELETE FROM token_whitelist WHERE token=?"; db.query(queryString, whitelisttoken, (err, data) => { if (data.affectedRows === 0) { reject({ status: 404, msg: "token tidak ditemukan, login gagal", }); } if (!err) { resolve({ msg: `Logout berhasil`, }); } else { reject({ msg: `Logout gagal`, }); } }); }); }, // send otp forgotPass: (email) => { return new Promise((resolve, reject) => { const getUser = `SELECT email FROM users WHERE email = ?`; db.query(getUser, email, (err, data) => { if (!err) { if (data[0]) { const delOtp = `DELETE FROM otp_reset WHERE email = ?`; db.query(delOtp, email, (err, data) => { if (!err) { const otpCode = otp.generate(6, { alphabets: true, upperCase: true, specialChars: false, }); const dataResend = { email: email, otp: otpCode, }; const queryString = `INSERT INTO otp_reset SET ?`; db.query(queryString, dataResend, (err, data) => { if (!err) { let transporter = nodemailer.createTransport({ service: "gmail", host: "smtp.gmail.com", port: 578, secure: false, auth: { user: process.env.USER_EMAIL, pass: process.env.PASS_EMAIL, }, }); let mailOptions = { from: "Blanja Team <blanja@arkademy.mail.com>", to: email, subject: "OTP Code Reset Password", html: ` <h1> OTP CODE from blanja Team </h1> <p> Hello, this is you OTP code</p> <h2><strong>${otpCode}</strong></h2> <p> Use it to reset Password </p> `, }; transporter.sendMail(mailOptions, (err, data) => { if (err) { console.log("its error: ", err); } else { console.log("success sent"); resolve({ status: 200, message: `Kode OTP telah dikirim ke email anda`, }); } }); } else { reject({ status: 500, message: `Internal server err`, details: err, }); } }); } else { reject({ status: 404, message: `Email not found`, }); } }); } else { reject({ status: 500, message: `Internal server err`, details: err, }); } } }); }); }, //check OTP checkOTP: (email, otp) => { return new Promise((resolve, reject) => { const queryString = `SELECT * FROM otp_reset WHERE email = ? AND otp = ?`; db.query(queryString, [email, otp], (err, data) => { if (!err) { if (data[0]) { const qs = `DELETE FROM otp_reset WHERE email = ? and otp = ?`; db.query(qs, [email, otp], (err, data) => { if (!err) { resolve({ status: 200, message: `reset your password`, email: email, }); } else { reject({ status: 500, message: `Internal server error`, details: err, }); } }); } else { reject({ status: 404, message: `OTP code not match`, }); } } else { reject({ status: 500, message: `Internal server error`, details: err, }); } }); }); }, resetPassword: (body) => { return new Promise((resolve, reject) => { const saltRounds = Math.floor(Math.random() * 10) + 1; bcrypt.hash(body.password, saltRounds, (err, hashedPassword) => { const queryString = `UPDATE users SET password = ? WHERE email = ?`; db.query(queryString, [hashedPassword, body.email], (err, data) => { if (!err) { resolve({ status: 200, message: "Password successfully change", }); } else { reject({ status: 500, message: "Internal server err", details: err, }); } }); }); }); }, getProfile: (id) => { return new Promise((resolve, reject) => { const queryString = "SELECT * FROM users WHERE id = ?"; db.query(queryString, id, (err, data) => { if (!err) { resolve(data); } else { reject(err); } }); }); }, updateProfile: (body, id) => { return new Promise((resolve, reject) => { const { old_password } = body; const queryOldPassword = "SELECT password FROM users WHERE id = ?"; db.query(queryOldPassword, id, (err, data) => { if (err) { reject({ msg: "Error SQL", status: 500, err, }); } else { bcrypt.compare(old_password, data[0].password, (err, result) => { if (err) { reject({ msg: "Hash Error", status: 500, err, }); } if (!result) { reject({ msg: "Wrong Password", status: 401, }); } else { const queryUpdateUser = "UPDATE users SET ? WHERE id = ?"; const { new_password, confirm_new_password } = body; if ( new_password !== undefined || confirm_new_password !== undefined ) { console.log("Ana Password Anyar"); if (new_password === confirm_new_password) { const saltRounds = 10; bcrypt.genSalt(saltRounds, (err, salt) => { if (err) { reject(err); } bcrypt.hash( body.new_password, salt, (err, hashedPassword) => { if (err) { reject(err); } delete body.new_password; delete body.confirm_new_password; delete body.old_password; const newBody = { ...body, password: hashedPassword, }; db.query( queryUpdateUser, [newBody, id], (err, data) => { if (!err) { resolve({ msg: "Update profile is successful", status: 200, data: data, }); } else { reject({ msg: "Error", status: 500, error: err, }); } } ); } ); }); } else { reject({ msg: "Passwort isn't same", status: 401, }); } } else { delete body.old_password; const newBody = { ...body, }; db.query(queryUpdateUser, [newBody, id], (err, data) => { if (!err) { resolve({ msg: "Update profile is successful", status: 200, data: data, }); } else { reject({ msg: "Error", status: 500, error: err, }); } }); } // console.log(password); } }); } }); }); }, };
import { Chip } from '@material-ui/core'; import Table from '@material-ui/core/Table'; import TableBody from '@material-ui/core/TableBody'; import TableCell from '@material-ui/core/TableCell'; import TableContainer from '@material-ui/core/TableContainer'; import TableHead from '@material-ui/core/TableHead'; import TablePagination from '@material-ui/core/TablePagination'; import TableRow from '@material-ui/core/TableRow'; import PropTypes from 'prop-types'; import React, { memo } from 'react'; import { USER_TYPE_ADMIN } from 'utils/constants'; import { UsersTableWrapper } from './styles'; const columns = [ { name: 'id', title: 'کد' }, { name: 'name', title: 'نام' }, { name: 'mobile', title: 'موبایل', dir: 'ltr' }, { name: 'email', title: 'ایمیل' }, { name: 'type', title: 'نوع کاربری', cast: v => ( <Chip label={v === USER_TYPE_ADMIN ? 'مدیر' : 'کاربر'} color={v === USER_TYPE_ADMIN ? 'secondary' : 'default'} /> ), }, { name: 'created_at', title: 'تاریخ ثبت نام', dir: 'ltr', cast: v => v }, { name: 'verified_at', title: 'وضعیت', cast: v => v ? 'تایید شده' : <b style={{ color: '#f50057' }}>تایید نشده</b>, }, ]; // eslint-disable-next-line no-unused-vars function UsersTable({ users, page, size, total, onChangePage, onRowClick }) { function handleChangePage(e, newPage) { onChangePage(newPage + 1, size); } function handleChangeRowsPerPage(e) { onChangePage(1, parseInt(e.target.value, 10)); } return ( <UsersTableWrapper> <TableContainer> <Table stickyHeader aria-label="sticky table"> <TableHead> <TableRow> {columns.map(column => ( <TableCell key={column.name} align={column.align} style={{ minWidth: column.minWidth }} > {column.title} </TableCell> ))} </TableRow> </TableHead> <TableBody> {users.map(user => ( <TableRow hover role="checkbox" tabIndex={-1} key={user.id} onClick={() => onRowClick(user)} > {columns.map(column => { const value = user[column.name]; return ( <TableCell key={column.name} align={column.align} dir={column.dir} > {column.cast ? column.cast(value) : value} </TableCell> ); })} </TableRow> ))} </TableBody> </Table> </TableContainer> <TablePagination rowsPerPageOptions={[10, 25, 50]} component="div" count={total} rowsPerPage={size} page={page - 1} labelRowsPerPage="" labelDisplayedRows={() => `صفحه ${page}`} onChangePage={handleChangePage} onChangeRowsPerPage={handleChangeRowsPerPage} /> </UsersTableWrapper> ); } UsersTable.propTypes = { users: PropTypes.arrayOf(PropTypes.object).isRequired, page: PropTypes.number.isRequired, size: PropTypes.number.isRequired, total: PropTypes.number.isRequired, onChangePage: PropTypes.func.isRequired, onRowClick: PropTypes.func.isRequired, }; export default memo(UsersTable);
mycallback( {"CONTRIBUTOR OCCUPATION": "Diagnostic Radiologist", "CONTRIBUTION AMOUNT (F3L Bundled)": "250.00", "ELECTION CODE": "", "MEMO CODE": "", "CONTRIBUTOR EMPLOYER": "X-Ray Physicians of Shelbyville", "DONOR CANDIDATE STATE": "", "CONTRIBUTOR STREET 1": "X-Ray Physicians of Shelbyville", "CONTRIBUTOR MIDDLE NAME": "", "DONOR CANDIDATE FEC ID": "", "DONOR CANDIDATE MIDDLE NAME": "", "CONTRIBUTOR STATE": "IN", "DONOR CANDIDATE FIRST NAME": "", "CONTRIBUTOR FIRST NAME": "Scott", "BACK REFERENCE SCHED NAME": "", "DONOR CANDIDATE DISTRICT": "", "CONTRIBUTION DATE": "20110322", "DONOR COMMITTEE NAME": "", "MEMO TEXT/DESCRIPTION": "", "Reference to SI or SL system code that identifies the Account": "", "FILER COMMITTEE ID NUMBER": "C00343459", "DONOR CANDIDATE LAST NAME": "", "CONTRIBUTOR LAST NAME": "Miller", "_record_type": "fec.version.v7_0.SA", "CONDUIT STREET2": "", "CONDUIT STREET1": "", "DONOR COMMITTEE FEC ID": "", "CONTRIBUTION PURPOSE DESCRIP": "", "CONTRIBUTOR ZIP": "461761236", "CONTRIBUTOR STREET 2": "150 W Washington St", "CONDUIT CITY": "", "ENTITY TYPE": "IND", "CONTRIBUTOR CITY": "Shelbyville", "CONTRIBUTOR SUFFIX": "", "TRANSACTION ID": "39292256", "DONOR CANDIDATE SUFFIX": "", "DONOR CANDIDATE OFFICE": "", "CONTRIBUTION PURPOSE CODE": "15", "ELECTION OTHER DESCRIPTION": "", "_src_file": "2011/20110504/727357.fec_1.yml", "CONDUIT STATE": "", "CONTRIBUTOR ORGANIZATION NAME": "", "BACK REFERENCE TRAN ID NUMBER": "", "DONOR CANDIDATE PREFIX": "", "CONTRIBUTOR PREFIX": "Dr.", "CONDUIT ZIP": "", "CONDUIT NAME": "", "CONTRIBUTION AGGREGATE F3L Semi-annual Bundled": "250.00", "FORM TYPE": "SA11ai"}); mycallback( {"CONTRIBUTOR OCCUPATION": "Diagnostic Radiologist", "CONTRIBUTION AMOUNT (F3L Bundled)": "250.00", "ELECTION CODE": "", "MEMO CODE": "", "CONTRIBUTOR EMPLOYER": "X-Ray Physicians of Shelbyville", "DONOR CANDIDATE STATE": "", "CONTRIBUTOR STREET 1": "X-Ray Physicians of Shelbyville", "CONTRIBUTOR MIDDLE NAME": "", "DONOR CANDIDATE FEC ID": "", "DONOR CANDIDATE MIDDLE NAME": "", "CONTRIBUTOR STATE": "IN", "DONOR CANDIDATE FIRST NAME": "", "CONTRIBUTOR FIRST NAME": "Scott", "BACK REFERENCE SCHED NAME": "", "DONOR CANDIDATE DISTRICT": "", "CONTRIBUTION DATE": "20110322", "DONOR COMMITTEE NAME": "", "MEMO TEXT/DESCRIPTION": "", "Reference to SI or SL system code that identifies the Account": "", "FILER COMMITTEE ID NUMBER": "C00343459", "DONOR CANDIDATE LAST NAME": "", "CONTRIBUTOR LAST NAME": "Miller", "_record_type": "fec.version.v7_0.SA", "CONDUIT STREET2": "", "CONDUIT STREET1": "", "DONOR COMMITTEE FEC ID": "", "CONTRIBUTION PURPOSE DESCRIP": "", "CONTRIBUTOR ZIP": "461761236", "CONTRIBUTOR STREET 2": "150 W Washington St", "CONDUIT CITY": "", "ENTITY TYPE": "IND", "CONTRIBUTOR CITY": "Shelbyville", "CONTRIBUTOR SUFFIX": "", "TRANSACTION ID": "39292256", "DONOR CANDIDATE SUFFIX": "", "DONOR CANDIDATE OFFICE": "", "CONTRIBUTION PURPOSE CODE": "15", "ELECTION OTHER DESCRIPTION": "", "_src_file": "2011/20110504/727357.fec_1.yml", "CONDUIT STATE": "", "CONTRIBUTOR ORGANIZATION NAME": "", "BACK REFERENCE TRAN ID NUMBER": "", "DONOR CANDIDATE PREFIX": "", "CONTRIBUTOR PREFIX": "Dr.", "CONDUIT ZIP": "", "CONDUIT NAME": "", "CONTRIBUTION AGGREGATE F3L Semi-annual Bundled": "250.00", "FORM TYPE": "SA11ai"});
// Contains sample contact data // Profile images import ImgBatman from './batman.jpg'; import ImgMickeyMouse from './mickey-mouse.png'; import ImgProfile from './profile.png'; import ImgSimpsonBart from './simpson-bart.png'; import ImgSimpsonHomer from './simpson-homer.jpg'; import ImgSpiderman from './spiderman.jpg'; export const DefaultProfileImg = ImgProfile; // Array of contacts export const CONTACTS = [ { id: 'waynebruce0', first: 'Bruce', last: 'Wayne', email: 'batman@xyz.com', phone: '1234567890', photo: ImgBatman, }, { id: 'mousemickey0', first: 'Mickey', last: 'Mouse', email: 'mickey@xyz.com', phone: '1234567890', photo: ImgMickeyMouse, }, { id: 'simpsonbart0', first: 'Bart', last: 'Simpson', email: 'bart@xyz.com', phone: '1234567890', photo: ImgSimpsonBart, }, { id: 'simpsonhomer0', first: 'Homer', last: 'Simpson', email: 'homer@xyz.com', phone: '1234567890', photo: ImgSimpsonHomer, }, { id: 'parkerpeter0', first: 'Peter', last: 'Parker', email: 'spiderman@xyz.com', phone: '1234567890', photo: ImgSpiderman, }, ];
import Component from '@ember/component'; import { computed } from '@ember/object'; import layout from '../../templates/components/github-card/stars'; export default Component.extend({ layout, tagName: '', stars: 0, formattedStars: computed('stars', function() { const stars = this.stars; if (stars > 1000) { return Math.round((stars / 1000) * 100) / 100 + 'k'; } return stars; }) });
// @link https://schemas.tmz.com/json-schema/tmz/iam/node/twitter-app/1-0-0.json# import Fb from '@gdbots/pbj/FieldBuilder'; import GdbotsIamTwitterAppV1Mixin from '@gdbots/schemas/gdbots/iam/mixin/twitter-app/TwitterAppV1Mixin'; import GdbotsNcrNodeV1Mixin from '@gdbots/schemas/gdbots/ncr/mixin/node/NodeV1Mixin'; import Message from '@gdbots/pbj/Message'; import NodeStatus from '@gdbots/schemas/gdbots/ncr/enums/NodeStatus'; import Schema from '@gdbots/pbj/Schema'; import T from '@gdbots/pbj/types'; import UuidIdentifier from '@gdbots/pbj/well-known/UuidIdentifier'; export default class TwitterAppV1 extends Message { /** * @private * * @returns {Schema} */ static defineSchema() { return new Schema(this.SCHEMA_ID, this, [ /* * The "_id" value: * - MUST NOT change for the life of the node. * - SHOULD be globally unique * - SHOULD be generated by the app (ideally in default value closure... e.g. UuidIdentifier::generate()) */ Fb.create('_id', T.IdentifierType.create()) .required() .withDefault(() => UuidIdentifier.generate()) .classProto(UuidIdentifier) .overridable(true) .build(), Fb.create('status', T.StringEnumType.create()) .withDefault("draft") .classProto(NodeStatus) .build(), Fb.create('etag', T.StringType.create()) .maxLength(100) .pattern('^[\\w\\.:-]+$') .build(), Fb.create('created_at', T.MicrotimeType.create()) .build(), /* * A fully qualified reference to what created this node. This is intentionally a message-ref * and not a user id because it is often a program that creates nodes, not a user. */ Fb.create('creator_ref', T.MessageRefType.create()) .build(), Fb.create('updated_at', T.MicrotimeType.create()) .useTypeDefault(false) .build(), /* * A fully qualified reference to what updated this node. This is intentionally a message-ref * and not a user id because it is often a program that updates nodes, not a user. * E.g. "acme:iam:node:app:cli-scheduler" or "acme:iam:node:user:60c71df0-fda8-11e5-bfb9-30342d363854" */ Fb.create('updater_ref', T.MessageRefType.create()) .build(), /* * A reference to the last event that changed the state of this node. * E.g. "acme:blog:event:article-published:60c71df0-fda8-11e5-bfb9-30342d363854" */ Fb.create('last_event_ref', T.MessageRefType.create()) .build(), Fb.create('title', T.StringType.create()) .build(), /* * The roles determine what permissions this app will have when using the system. * The role itself is a node which has a set of "allow" and "deny" rules. */ Fb.create('roles', T.NodeRefType.create()) .asASet() .build(), /* * Equivalent to username of your Twitter developer app when making API requests. * @link https://developer.twitter.com/en/docs/authentication/oauth-1-0a */ Fb.create('oauth_consumer_key', T.StringType.create()) .pattern('^[\\w-]+$') .build(), /* * Equivalent to password of your Twitter developer app when making API requests. * The "oauth_consumer_secret" should be encrypted and never stored in plain text. * @link https://developer.twitter.com/en/docs/authentication/oauth-1-0a */ Fb.create('oauth_consumer_secret', T.TextType.create()) .build(), /* * An oauth token is a user-specific credentials used to authenticate OAuth 1.0a API requests. * It specifies the Twitter account the request is made on behalf of. * @link https://developer.twitter.com/en/docs/authentication/oauth-1-0a */ Fb.create('oauth_token', T.StringType.create()) .pattern('^[\\w-]+$') .build(), /* * An oauth token secret is a user-specific credentials used to authenticate OAuth 1.0a API requests. * It specifies the Twitter account the request is made on behalf of. * The "oauth_token_secret" should be encrypted and never stored in plain text. * @link https://developer.twitter.com/en/docs/authentication/oauth-1-0a */ Fb.create('oauth_token_secret', T.TextType.create()) .build(), ], this.MIXINS, ); } } const M = TwitterAppV1; M.prototype.SCHEMA_ID = M.SCHEMA_ID = 'pbj:tmz:iam:node:twitter-app:1-0-0'; M.prototype.SCHEMA_CURIE = M.SCHEMA_CURIE = 'tmz:iam:node:twitter-app'; M.prototype.SCHEMA_CURIE_MAJOR = M.SCHEMA_CURIE_MAJOR = 'tmz:iam:node:twitter-app:v1'; M.prototype.MIXINS = M.MIXINS = [ 'gdbots:ncr:mixin:node:v1', 'gdbots:ncr:mixin:node', 'gdbots:iam:mixin:app:v1', 'gdbots:iam:mixin:app', 'gdbots:iam:mixin:twitter-app:v1', 'gdbots:iam:mixin:twitter-app', ]; GdbotsNcrNodeV1Mixin(M); GdbotsIamTwitterAppV1Mixin(M); Object.freeze(M); Object.freeze(M.prototype);
"use strict" /** * Poll Editor */ const { View } = require("@kisbox/browser") const { LiveArray } = require("@kisbox/model") const { remove } = require("@cosmic-plus/helpers") const chevronRightSvg = require("feather-icons/dist/icons/chevron-right.svg") const chevronDownSvg = require("feather-icons/dist/icons/chevron-down.svg") /* Definition */ class PollEditor extends View { constructor (params) { super(` <form class="PollEditor"> <fieldset> <legend $hint="The Stellar network where the poll is to be posted."> Network </legend> <input type="radio" $group="network" value="public" $label="Stellar Public"> <input type="radio" $group="network" value="test" $label="Stellar Test"> </fieldset> <fieldset> <legend $hint="A short, descriptive title for your poll."> Title </legend> <input type="text" value=%title maxlength="56" placeholder="Short Title"> </fieldset> <fieldset> <legend $hint="Candidates' names, one entry minimum."> Candidates </legend> %toCandidate:...members <input type="text" value=%newMember maxlength="28" onkeydown=%addMember placeholder="New Candidate"> <button type="button" onclick=%addMember>+</button> </fieldset> <fieldset> <legend $hint="Whether your poll should be listed under the 'Browse' tab."> Listing </legend> <input type="radio" $group="destination" value="" checked $label="No Public Listing"> <input type="radio" $group="destination" value="list*cosmic.vote" $label="List on Cosmic.vote"> </fieldset> <nav> <a onclick=%switchVotersFiltering data-switcher=%showVotersFiltering> <span hidden=%showVotersFiltering>${chevronRightSvg}</span> <span hidden=%not:showVotersFiltering>${chevronDownSvg}</span> Voters Filtering </a> <a onclick=%switchAdvancedSettings data-switcher=%showAdvancedSettings> <span hidden=%showAdvancedSettings>${chevronRightSvg}</span> <span hidden=%not:showAdvancedSettings>${chevronDownSvg}</span> Advanced Settings </a> </nav> <div hidden=%not:showVotersFiltering> <fieldset> <legend $hint="Set how much of an asset voters have to hold at vote creation time, for their vote to count. Set the amount to 0 to filter by trustline. (Optional)"> Hold Asset </legend> <div class="group"> <input type="number" value=%hodlAmount step="0.0000001" min="0" placeHolder="Asset amount"> <input type="text" value=%hodlAsset placeHolder="Asset ID (code:issuer)"> </div> </fieldset> <fieldset> <legend $hint="Set a date from which the 'Hold Asset' requirement has to be valid. (Optional)"> Hold Since </legend> <div class="group"> <input type="date" value=%hodlDate> <input type="time" value=%hodlTime> </div> </fieldset> </div> <div hidden=%not:showAdvancedSettings> <fieldset> <legend $hint="The local date & time at which your poll will end. (optional)"> Closing Time </legend> <div class="group"> <input type="date" value=%closingDate> <input type="time" value=%closingTime> </div> </fieldset> <fieldset> <legend $hint="Allow users to edit their vote while the poll is still open."> Vote Editing </legend> <input type="radio" $group="noEdit" value="" $label="Allow Edits"> <input type="radio" $group="noEdit" value="true" $label="Forbid Edits"> </fieldset> </div> </form> `) /* Defaults */ this.members = new LiveArray() this.closingTime = "00:00" this.showVotersFiltering = false this.voterHodl = null this.hodlAsset = "native" this.hodlAmount = 0 this.hodlDate = null this.hodlTime = "00:00" this.showAdvancedSettings = false this.noEdit = "" /* Imports */ this.$import(params, ["members", "title", "destination"]) this.$import(params, ["network"], (x) => x.id) } switchVotersFiltering () { this.showAdvancedSettings = false this.showVotersFiltering = !this.showVotersFiltering } switchAdvancedSettings () { this.showVotersFiltering = false this.showAdvancedSettings = !this.showAdvancedSettings } addMember (event = {}) { if (event.keyCode && event.keyCode !== 13) return if (!this.newMember) return // Keep member id unique remove(this.members, this.newMember) this.members.push(this.newMember) this.newMember = null } normalize () { if (this.newMember) { this.addMember() } } } /* Computations */ const proto = PollEditor.prototype proto.$define( "voterHodl", ["hodlAsset", "hodlAmount", "hodlSince"], function () { if ( (!this.hodlAsset || this.hodlAsset === "native") && !this.hodlAmount && !this.hodlSince ) { return null } else { return { assetId: this.hodlAsset, amount: this.hodlAmount, since: this.hodlSince } } } ) proto.$define("hodlSince", ["hodlDate", "hodlTime"], function () { if (!this.hodlDate || !this.hodlTime) return null const isoDate = `${this.hodlDate}T${this.hodlTime}` const timestamp = Number(new Date(isoDate)) return timestamp }) proto.$on("hodlAmount", function () { this.hodlAmount = Number(this.hodlAmount) .toFixed(7) .replace(/\.?0+$/, "") }) proto.$define("maxTime", ["closingDate", "closingTime"], function () { if (!this.closingDate || !this.closingTime) return const isoDate = `${this.closingDate}T${this.closingTime}` const timestamp = Number(new Date(isoDate)) return timestamp }) /* Helpers */ const helpers = PollEditor.helpers helpers.toCandidate = function (id) { const view = new PollEditor.Candidate({ id }) view.$on("delete", () => remove(this.members, id)) view.$on("id", (current, previous) => { const index = this.members.indexOf(previous) this.members[index] = current }) return view } /* Export */ PollEditor.Candidate = require("./poll-editor.candidate") module.exports = PollEditor
const DiscordReconciliation = require('../../discordReconciliation') module.exports = async (client, oldPresence) => { try { client.logs.discord.info(`Discord event: guildMemberUpdate - ${oldPresence.user.id}`) if (client.config.discord.admins.includes(oldPresence.user.id)) return if (oldPresence.user.bot) return const dr = new DiscordReconciliation(oldPresence.client, client.logs.log, client.config, client.query, client.dts) await dr.reconcileSingleUser(oldPresence.user.id, client.config.reconciliation.discord.removeInvalidUsers) } catch (e) { client.logs.discord.error('Role based registration errored', e) } }
/* * MIT License * * Copyright (c) 2017 Barracks Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import { checkStatus, parseJSON } from 'utils/fetchUtils' const AUTHENTICATION_ENDPOINT = '/api/auth/login' const REGISTER_ENDPOINT = '/api/auth/register' const CURRENT_USER_ENDPOINT = '/api/auth/me' const RESET_PASSWORD_ENDPOINT = '/api/auth/password/reset' const SET_PASSWORD_ENDPOINT = '/api/auth/password/set' const CONFIRM_PASSWORD_ENDPOINT = '/api/auth/password/reset/confirm' const CREATE_SUBSCRIPTION_ACCOUNT_ENDPOINT = '/api/subscription/customers' const VERIFY_SUBSCRIPTION_ACCOUNT_ENDPOINT = '/api/subscription/customers/verify' function setToken (token) { localStorage.setItem('authToken', token) } function getToken () { return localStorage.getItem('authToken') } function removeToken () { localStorage.removeItem('authToken') } export default { authenticate: (username, password) => new Promise((resolve, reject) => { const requestParams = { method: 'post', headers: { 'Accept': 'application/json', 'Content-type': 'application/json' }, body: JSON.stringify({ username, password }) } fetch(AUTHENTICATION_ENDPOINT, requestParams) .then(checkStatus) .then(function (response) { const token = response.headers.get('X-Auth-Token') setToken(token) return parseJSON(response) }) .then(function (json) { resolve(json) }).catch(function (err) { reject(err) }) }), resetPassword: (email) => new Promise((resolve, reject) => { const requestParams = { method: 'post', headers: { 'Accept': 'application/json', 'Content-type': 'application/json' }, body: JSON.stringify({ email }) } fetch(RESET_PASSWORD_ENDPOINT, requestParams) .then(checkStatus) .then(function (message) { resolve(message) }).catch(function (err) { reject(err) }) }), setPassword: (email) => new Promise((resolve, reject) => { const requestParams = { method: 'post', headers: { 'Accept': 'application/json', 'Content-type': 'application/json' }, body: JSON.stringify({ email }) } fetch(SET_PASSWORD_ENDPOINT, requestParams) .then(checkStatus) .then(function (message) { resolve(message) }).catch(function (err) { reject(err) }) }), confirmPassword: (credentials) => new Promise((resolve, reject) => { const requestParams = { method: 'post', headers: { 'Accept': 'application/json', 'Content-type': 'application/json' }, body: JSON.stringify({ email: credentials.email, password: credentials.password, token: credentials.token }) } fetch(CONFIRM_PASSWORD_ENDPOINT, requestParams) .then(checkStatus) .then(function (message) { resolve(message) }).catch(function (err) { reject(err) }) }), signup: (user) => new Promise((resolve, reject) => { const requestParams = { method: 'post', headers: { 'Accept': 'application/json', 'Content-type': 'application/json' }, body: JSON.stringify({ firstName: user.firstName, lastName: user.lastName, email: user.email, phone: user.phone, company: user.company }) } fetch(REGISTER_ENDPOINT, requestParams) .then(checkStatus) .then(parseJSON) .then(function (message) { resolve(message) }).catch(function (err) { reject(err) }) }), createSubscriptionAccount: (billingMethod, billingInfo) => new Promise((resolve, reject) => { const endpoint = CREATE_SUBSCRIPTION_ACCOUNT_ENDPOINT + '?method=' + billingMethod const requestParams = { method: 'post', headers: { 'Accept': 'application/json', 'Content-type': 'application/json', 'X-Auth-Token': getToken() }, body: JSON.stringify(billingInfo) } fetch(endpoint, requestParams) .then(checkStatus) .then(parseJSON) .then(function (user) { resolve(user) }).catch(function (err) { reject(err) }) }), verifySubscriptionAccount: () => new Promise((resolve, reject) => { const requestParams = { method: 'get', headers: { 'Accept': 'application/json', 'Content-type': 'application/json', 'X-Auth-Token': getToken() } } fetch(VERIFY_SUBSCRIPTION_ACCOUNT_ENDPOINT, requestParams) .then(checkStatus) .then(parseJSON) .then(function (result) { resolve(result) }).catch(function (err) { reject(err) }) }), getCurrentUser: () => new Promise((resolve, reject) => { const requestParams = { method: 'get', headers: { 'Accept': 'application/json', 'Content-type': 'application/json', 'X-Auth-Token': getToken() } } fetch(CURRENT_USER_ENDPOINT, requestParams) .then(checkStatus) .then(parseJSON) .then(function (user) { resolve(user) }).catch(function (err) { reject(err) }) }), getToken, isConnected: () => !!getToken(), logout: () => removeToken() }
module.exports = { preset: '../../../../jest.preset.js', coverageDirectory: '../../../../coverage/libs/geoservices/core/ngx', snapshotSerializers: [ 'jest-preset-angular/build/AngularNoNgAttributesSnapshotSerializer.js', 'jest-preset-angular/build/AngularSnapshotSerializer.js', 'jest-preset-angular/build/HTMLCommentSerializer.js' ], setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'], globals: { 'ts-jest': { tsConfig: '<rootDir>/tsconfig.spec.json', stringifyContentPathRegex: '\\.(html|svg)$', astTransformers: { before: ['jest-preset-angular/build/InlineFilesTransformer', 'jest-preset-angular/build/StripStylesTransformer'] } } }, displayName: 'geoservices-core-ngx' };
const express = require('express'); const app = express(); app.use(express.static('./public/przykladStatyczne/')); app.get('/manual/route', (req, res) => { res.send('To jest odpowiedź zwrócona nie z pliku, a z manualnie ustalonej ścieżki.'); }); app.listen(3000, () => { console.log('Serwer uruchomiony na porcie 3000'); });
import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from 'material-ui/styles'; import ExpansionPanel, { ExpansionPanelSummary, ExpansionPanelDetails, } from 'material-ui/ExpansionPanel'; import H3 from '../H3/index'; import P from '../P/index'; import ExpandIcon from './ExpandIcon'; const styles = () => ({ root: { width: '80vw', maxWidth: '600px', }, }); const Idea = ({ classes, idea }) => ( <ExpansionPanel className={classes.root}> <ExpansionPanelSummary expandIcon={ExpandIcon()}> <H3>{idea.subject}</H3> </ExpansionPanelSummary> <ExpansionPanelDetails> <P>{idea.text}</P> </ExpansionPanelDetails> </ExpansionPanel> ); Idea.propTypes = { classes: PropTypes.object.isRequired, idea: PropTypes.object.isRequired, }; export default withStyles(styles)(Idea);
// $(function(){ $(function() { var testing; if ( typeof WebSocket === "undefined") { $("#grid").html('The application requires Web Sockets and HTML5 support. Please update your Browser. /></a>'); return; } /* Setup the websocket connection, need to decided weather to use secure or standard socket */ var loc = window.location; var wsUriVPCA; if (loc.protocol === "https:") { wsUriVPCA = "wss:"; } else { wsUriVPCA = "ws:"; } wsUriVPCA += loc.host + "/VPCA"; var ws = new WebSocket(wsUriVPCA); /* Define the parameters we will use on this page These numbers match the parameter ID in VPCA database */ // var Engine_RPM = 101; // var Accelerator_Position = 102; // var Engine_Load = 103; // var Trip_Distance = 104; // var Total_Distance = 105; // var Engine_Coolent_Temperture = 106; // var Engine_Oil_Pressure = 107; // var Vehicle_Speed = 108; // var Engine_Fuel_Rate = 109; // var Engine_Instantaneous_Fuel_Rate = 110; // var Engine_Air_Intake_Pressure = 111; // var Engine_Air_Intake_Temperture = 112; // var Battery_Voltage = 113; // var Key_Voltage = 114; // var Transmission_Oil_Temperture = 115; // var Fuel_Level = 116; // bobbyS_vars1.title=100; var power2 = 0; var powerin = 0; var Port1_Frequency = 1; var Port1_LineVoltage = 3; var Port1_Current = 4; var Port1_Power = 5; var Port2_Frequency = 11; var Port2_LineVoltage = 13; var Port2_Current = 14; var Port2_Power = 15; var Port3_Frequency = 21; var Port3_LineVoltage = 23; var Port3_Current = 24; var Port3_Power = 25; var Port4_Frequency = 31; var Port4_LineVoltage = 33; var Port4_Current = 34; var Port4_Power = 35; var Port5_Frequency = 41; var Port5_LineVoltage = 43; var Port5_Current = 44; var Port5_Power = 45; var Port6_Frequency = 51; var Port6_LineVoltage = 53; var Port6_Current = 54; var Port6_Power = 55; var Port7_Frequency = 61; var Port7_LineVoltage = 63; var Port7_Current = 64; var Port7_Power = 65; var Port8_Frequency = 71; var Port8_LineVoltage = 73; var Port8_Current = 74; var Port8_Power = 75; var Port9_Frequency = 81; var Port9_LineVoltage = 83; var Port9_Current = 84; var Port9_Power = 85; var Port10_Frequency = 91; var Port10_LineVoltage = 93; var Port10_Current = 94; var Port10_Power = 95; var P4_Priority = 102; var P5_Priority = 103; var P6_Priority = 104; var P7_Priority = 105; var P8_Priority = 106; var P9_Priority = 107; var P10_Priority = 108; /* All above parameters are in this group*/ /*var J1939_Data_Group ="J1939_Data"; */ var J1939_Data_Group = "PortsData"; /* Defines for the state machine enumeration on the system master controller */ var var_Off = 0; var var_On_Transition = 1; var var_On = 2; var var_Off_Transition = 3; var string = ""; //Bind the grid when the socket connects ws.onopen = function() { sendrequestformetadata(); // send request for the parameters meta data we want on this page }; //Close the socket when the browser window is closed. window.onbeforeunload = closedownsocket; function closedownsocket() { request = { "WPUSHC" : "" }; // clear the push requests //Send the data to the server side application VCPA ws.send(JSON.stringify(request)); console.log("clear push request sent"); ws.close(); // close the socket } // this function sends data through the socket and calls the callback function to process the returned data function send(ws, request, callback) { if (ws.readyState != 1) { return; } //Listen to the "message" event to get server response ws.addEventListener("message", function(e) { try { var result = JSON.parse(e.data); //Check if the response is for the meta data request if (result.MGPMG == J1939_Data_Group) { //Stop listening we will no longer look for the meta data ws.removeEventListener("message", arguments.callee); //Invoke the callback with the result var_gotmetadataresponse(result); } else { //Invoke the callback with the result var_callbackgotresponse(result); var_callbackgotresponse1(result); } } catch (Exception) { console.log(Exception.message); } }); //Send the data to the server side application VCPA ws.send(JSON.stringify(request)); } // this function requests the meta data for the group and sets the callback function for the returned data function sendrequestformetadata() { request = { WGPMG : J1939_Data_Group }; send(ws, request, var_gotmetadataresponse); console.log("meta data requests sent"); /* TODO, turn off for development only*/ } var var_gotmetadataresponse = function gotmetadataresponse(result) { console.log("call back reached"); /* TODO, turn off for development only*/ console.log(result); /* TODO, turn off for development only*/ // Loop through each of the results values array and consume the appropriate information // for ( i = 0; i < result.Values.length; i++) { try { switch(result.Values[i].MGPM.MGPMID) { // case Port1_Frequency : // document.getElementById("j1939_table").rows[1].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[1].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Port1_LineVoltage : // document.getElementById("j1939_table").rows[1].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[1].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Port1_Current : // document.getElementById("j1939_table").rows[1].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[1].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Port1_Power : // document.getElementById("j1939_table").rows[1].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[1].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Port2_Frequency : // document.getElementById("j1939_table").rows[1].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[1].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Port2_LineVoltage : // document.getElementById("j1939_table").rows[1].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[1].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Port2_Current : // document.getElementById("j1939_table").rows[1].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[1].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Port2_Power : // document.getElementById("j1939_table").rows[1].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[1].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Port3_Frequency : // document.getElementById("j1939_table").rows[1].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[1].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Port3_LineVoltage : // document.getElementById("j1939_table").rows[1].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[1].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Port3_Current : // document.getElementById("j1939_table").rows[1].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[1].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Port3_Power : // document.getElementById("j1939_table").rows[1].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[1].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Port4_Frequency : // document.getElementById("j1939_table").rows[1].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[1].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Port4_LineVoltage : // document.getElementById("j1939_table").rows[1].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[1].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Port4_Current : // document.getElementById("j1939_table").rows[1].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[1].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Port4_Power : // document.getElementById("j1939_table").rows[1].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[1].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Port5_Frequency : // document.getElementById("j1939_table").rows[1].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[1].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Port5_LineVoltage : // document.getElementById("j1939_table").rows[1].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[1].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Port5_Current : // document.getElementById("j1939_table").rows[1].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[1].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Port5_Power : // document.getElementById("j1939_table").rows[1].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[1].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Port6_Frequency : // document.getElementById("j1939_table").rows[1].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[1].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Port6_LineVoltage : // document.getElementById("j1939_table").rows[1].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[1].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Port6_Current : // document.getElementById("j1939_table").rows[1].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[1].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Port6_Power : // document.getElementById("j1939_table").rows[1].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[1].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Port7_Frequency : // document.getElementById("j1939_table").rows[1].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[1].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Port7_LineVoltage : // document.getElementById("j1939_table").rows[1].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[1].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Port7_Current : // document.getElementById("j1939_table").rows[1].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[1].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Port7_Power : // document.getElementById("j1939_table").rows[1].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[1].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Port8_Frequency : // document.getElementById("j1939_table").rows[1].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[1].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Port8_LineVoltage : // document.getElementById("j1939_table").rows[1].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[1].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Port8_Current : // document.getElementById("j1939_table").rows[1].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[1].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Port8_Power : // document.getElementById("j1939_table").rows[1].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[1].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Port9_Frequency : // document.getElementById("j1939_table").rows[1].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[1].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Port9_LineVoltage : // document.getElementById("j1939_table").rows[1].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[1].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Port9_Current : // document.getElementById("j1939_table").rows[1].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[1].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Port9_Power : // document.getElementById("j1939_table").rows[1].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[1].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Port10_Frequency : // document.getElementById("j1939_table").rows[1].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[1].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Port10_LineVoltage : // document.getElementById("j1939_table").rows[1].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[1].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Port10_Current : // document.getElementById("j1939_table").rows[1].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[1].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Port10_Power : // document.getElementById("j1939_table").rows[1].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[1].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Engine_Oil_Pressure: // // document.getElementById("j1939_table").rows[11].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[11].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Transmission_Oil_Temperture: // // document.getElementById("j1939_table").rows[12].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[12].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Trip_Distance: // // document.getElementById("j1939_table").rows[13].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[13].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Total_Distance: // // document.getElementById("j1939_table").rows[14].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[14].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Battery_Voltage: // // document.getElementById("j1939_table").rows[15].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[15].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; // // case Key_Voltage: // // document.getElementById("j1939_table").rows[16].cells[0].innerHTML = result.Values[i].MGPM.MGPMName; // document.getElementById("j1939_table").rows[16].cells[2].innerHTML = result.Values[i].MGPM.UnitsStr; // // break; } /* end of switch case statement */ } catch (Exception) { console.log(Exception.message); } }/* end of for loop */ sendrequestparametervalues(); // send the push request for the parameters we want on this page and set the call back function to parse the returned message sendrequestparametervalues2(); }; /* end of got parameter meta data function */ // this function requests the runtime data for the group and sets the callback function for the returned data function sendrequestparametervalues() { request = { WPUSHG : { WPUSHGID : "PortsData", Maxrate : 50, Minrate : 5000 } }; send(ws, request, var_callbackgotresponse); console.log("group parameter push request sent"); /* TODO, turn off for development only*/ } var timestampHistory; var commcounter = 0; var timesub; var var_callbackgotresponse = function callbackgotresponse(result) { console.log("call back reached"); /* TODO, turn off for development only*/ console.log(result); /* TODO, turn off for development only*/ timesub = result.MGP.Timestamp.substr(0, 18); //clear the values if there is no update if (timestampHistory == timesub) { commcounter = 1 + commcounter; } else { timestampHistory = result.MGP.Timestamp.substr(0, 18); //"2016-06-21 15:26:30:181108" commcounter = 0; } if (commcounter > 200) { result.MGP.ParamVal = 9999; } // handle the display for the state of the image, based on the state reported by the system master controller // try { switch(result.MGP.MGPID) { case Port1_Frequency : document.getElementById("table_1").rows[2].cells[1].innerHTML = result.MGP.ParamVal * 1 + " Hz"; break; case Port1_LineVoltage : document.getElementById("table_1").rows[2].cells[2].innerHTML = result.MGP.ParamVal * 1 + " V"; document.getElementById("circule_batterychargepower").innerHTML = result.MGP.ParamVal * 1; break; case Port1_Current : document.getElementById("table_1").rows[2].cells[3].innerHTML = result.MGP.ParamVal * 1 + " A"; document.getElementById("circule_batterychargepower").innerHTML = result.MGP.ParamVal * 1; break; case Port1_Power : document.getElementById("table_1").rows[2].cells[4].innerHTML = result.MGP.ParamVal * 1 / 1000 + " kW"; // document.getElementById("table_1").rows[2].cells[5].innerHTML = ( Math.round(result.MGP.ParamVal /700)) + " %";//70kw max window.Power_chart1.Port1P = result.MGP.ParamVal * 1 / 1000; PortPowerpercent(); // //change color of table cel // if (window.Power_chart1.Port1P >0){ // document.getElementById("table_1").rows[2].cells[4].className = "w3-blue"; // } // else { // document.getElementById("table_1").rows[2].cells[4].className += "w3-red"; // } break; case Port2_Frequency : document.getElementById("table_1").rows[3].cells[1].innerHTML = result.MGP.ParamVal * 1 + " Hz"; break; case Port2_LineVoltage : document.getElementById("table_1").rows[3].cells[2].innerHTML = result.MGP.ParamVal * 1 + " V"; break; case Port2_Current : document.getElementById("table_1").rows[3].cells[3].innerHTML = result.MGP.ParamVal * 1 + " A"; break; case Port2_Power : document.getElementById("table_1").rows[3].cells[4].innerHTML = result.MGP.ParamVal * 1 / 1000 + " kW"; //document.getElementById("table_1").rows[3].cells[5].innerHTML = ( Math.round(result.MGP.ParamVal /700)) + " %";//70kw max window.Power_chart1.Port2P = result.MGP.ParamVal * 1 / 1000; PortPowerpercent(); break; case Port3_Frequency : document.getElementById("table_1").rows[4].cells[1].innerHTML = result.MGP.ParamVal * 1 + " Hz"; break; case Port3_LineVoltage : document.getElementById("table_1").rows[4].cells[2].innerHTML = result.MGP.ParamVal * 1 + " V"; break; case Port3_Current : document.getElementById("table_1").rows[4].cells[3].innerHTML = result.MGP.ParamVal * 1 + " A"; break; case Port3_Power : document.getElementById("table_1").rows[4].cells[4].innerHTML = result.MGP.ParamVal * 1 / 1000 + " kW"; //document.getElementById("table_1").rows[4].cells[5].innerHTML = ( Math.round(result.MGP.ParamVal /700)) + " %";//70kw max window.Power_chart1.Port3P = result.MGP.ParamVal * 1 / 1000; PortPowerpercent(); break; case Port4_Frequency : document.getElementById("table_2").rows[2].cells[1].innerHTML = result.MGP.ParamVal * 1 + " Hz"; break; case Port4_LineVoltage : document.getElementById("table_2").rows[2].cells[2].innerHTML = result.MGP.ParamVal * 1 + " V"; break; case Port4_Current : document.getElementById("table_2").rows[2].cells[3].innerHTML = result.MGP.ParamVal * 1 + " A"; break; case Port4_Power : document.getElementById("table_2").rows[2].cells[4].innerHTML = result.MGP.ParamVal * 1 / 1000 + " kW"; //document.getElementById("table_2").rows[2].cells[5].innerHTML = ( Math.round(result.MGP.ParamVal /700)) + " %";//70kw max window.Power_chart1.Port4P = result.MGP.ParamVal * 1 / 1000; PortPowerpercent(); break; case Port5_Frequency : document.getElementById("table_2").rows[3].cells[1].innerHTML = result.MGP.ParamVal * 1 + " Hz"; break; case Port5_LineVoltage : document.getElementById("table_2").rows[3].cells[2].innerHTML = result.MGP.ParamVal * 1 + " V"; break; case Port5_Current : document.getElementById("table_2").rows[3].cells[3].innerHTML = result.MGP.ParamVal * 1 + " A"; break; case Port5_Power : document.getElementById("table_2").rows[3].cells[4].innerHTML = result.MGP.ParamVal * 1 / 1000 + " kW"; //document.getElementById("table_2").rows[3].cells[5].innerHTML = ( Math.round(result.MGP.ParamVal /350)) + " %";//35kw max window.Power_chart1.Port5P = result.MGP.ParamVal * 1 / 1000; PortPowerpercent(); break; case Port6_Frequency : document.getElementById("table_2").rows[4].cells[1].innerHTML = result.MGP.ParamVal * 1 + " Hz"; break; case Port6_LineVoltage : document.getElementById("table_2").rows[4].cells[2].innerHTML = result.MGP.ParamVal * 1 + " V"; break; case Port6_Current : document.getElementById("table_2").rows[4].cells[3].innerHTML = result.MGP.ParamVal * 1 + " A"; break; case Port6_Power : document.getElementById("table_2").rows[4].cells[4].innerHTML = result.MGP.ParamVal * 1 / 1000 + " kW"; // document.getElementById("table_2").rows[4].cells[5].innerHTML = ( Math.round(result.MGP.ParamVal /210)) + " %";//21kw max window.Power_chart1.Port6P = result.MGP.ParamVal * 1 / 1000; PortPowerpercent(); break; case Port7_Frequency : document.getElementById("table_2").rows[5].cells[1].innerHTML = result.MGP.ParamVal * 1 + " Hz"; break; case Port7_LineVoltage : document.getElementById("table_2").rows[5].cells[2].innerHTML = result.MGP.ParamVal * 1 + " V"; break; case Port7_Current : document.getElementById("table_2").rows[5].cells[3].innerHTML = result.MGP.ParamVal * 1 + " A"; break; case Port7_Power : document.getElementById("table_2").rows[5].cells[4].innerHTML = result.MGP.ParamVal * 1 / 1000 + " kW"; //document.getElementById("table_2").rows[5].cells[5].innerHTML = ( Math.round(result.MGP.ParamVal /210)) + " %";//21kw max window.Power_chart1.Port7P = result.MGP.ParamVal * 1 / 1000; PortPowerpercent(); break; case Port8_Frequency : document.getElementById("table_2").rows[7].cells[1].innerHTML = result.MGP.ParamVal * 1 + " Hz"; break; case Port8_LineVoltage : document.getElementById("table_2").rows[7].cells[2].innerHTML = result.MGP.ParamVal * 1 + " V"; break; case Port8_Current : document.getElementById("table_2").rows[7].cells[3].innerHTML = result.MGP.ParamVal * 1 + " A"; break; case Port8_Power : document.getElementById("table_2").rows[7].cells[4].innerHTML = result.MGP.ParamVal * 1 / 1000 + " kW"; // document.getElementById("table_2").rows[6].cells[5].innerHTML = ( Math.round(result.MGP.ParamVal /350)) + " %";//35kw max window.Power_chart1.Port8P = result.MGP.ParamVal * 1 / 1000; PortPowerpercent(); break; case Port9_Frequency : document.getElementById("table_2").rows[8].cells[1].innerHTML = result.MGP.ParamVal * 1 + " Hz"; break; case Port9_LineVoltage : document.getElementById("table_2").rows[8].cells[2].innerHTML = result.MGP.ParamVal * 1 + " V"; break; case Port9_Current : document.getElementById("table_2").rows[8].cells[3].innerHTML = result.MGP.ParamVal * 1 + " A"; break; case Port9_Power : document.getElementById("table_2").rows[8].cells[4].innerHTML = result.MGP.ParamVal * 1 / 1000 + " kW"; // document.getElementById("table_2").rows[7].cells[5].innerHTML = ( Math.round(result.MGP.ParamVal /210)) + " %";//21kw max window.Power_chart1.Port9P = result.MGP.ParamVal * 1 / 1000; PortPowerpercent(); break; case Port10_Frequency : document.getElementById("table_2").rows[9].cells[1].innerHTML = result.MGP.ParamVal * 1 + " Hz"; break; case Port10_LineVoltage : document.getElementById("table_2").rows[9].cells[2].innerHTML = result.MGP.ParamVal * 1 + " V"; break; case Port10_Current : document.getElementById("table_2").rows[9].cells[3].innerHTML = result.MGP.ParamVal * 1 + " A"; break; case Port10_Power : document.getElementById("table_2").rows[9].cells[4].innerHTML = result.MGP.ParamVal * 1 / 1000 + " kW"; // document.getElementById("table_2").rows[8].cells[5].innerHTML = ( Math.round(result.MGP.ParamVal /210)) + " %";//21kw max window.Power_chart1.Port10P = result.MGP.ParamVal * 1 / 1000; PortPowerpercent(); break; //output ports priority case P4_Priority : document.getElementById("table_2").rows[2].cells[6].innerHTML = MGP_Parmval(result.MGP.ParamVal); break; case P5_Priority : document.getElementById("table_2").rows[3].cells[6].innerHTML = MGP_Parmval(result.MGP.ParamVal); break; case P6_Priority : document.getElementById("table_2").rows[4].cells[6].innerHTML = MGP_Parmval(result.MGP.ParamVal); break; case P7_Priority : document.getElementById("table_2").rows[5].cells[6].innerHTML = MGP_Parmval(result.MGP.ParamVal); break; case P8_Priority : document.getElementById("table_2").rows[7].cells[6].innerHTML = MGP_Parmval(result.MGP.ParamVal); break; case P9_Priority : document.getElementById("table_2").rows[8].cells[6].innerHTML = MGP_Parmval(result.MGP.ParamVal); break; case P10_Priority : document.getElementById("table_2").rows[9].cells[6].innerHTML = MGP_Parmval(result.MGP.ParamVal); break; case 109 : //p1 con 0=NA 1=open 2=closed 3=fault ContactorStatus(1, result.MGP.ParamVal); break; case 110 : //p2 con 0=NA 1=open 2=closed 3=fault ContactorStatus(2, result.MGP.ParamVal); break; case 111 : //p3 con 0=NA 1=open 2=closed 3=fault ContactorStatus(3, result.MGP.ParamVal); break; case 112 : //p4 con 0=NA 1=open 2=closed 3=fault ContactorStatus(4, result.MGP.ParamVal); break; case 113 : //p5 con 0=NA 1=open 2=closed 3=fault ContactorStatus(5, result.MGP.ParamVal); break; case 114 : //p6 con 0=NA 1=open 2=closed 3=fault ContactorStatus(6, result.MGP.ParamVal); break; case 115 : //p7 con 0=NA 1=open 2=closed 3=fault ContactorStatus(7, result.MGP.ParamVal); break; case 116 : //p8 con 0=NA 1=open 2=closed 3=fault ContactorStatus(8, result.MGP.ParamVal); break; case 117 : //p9 con 0=NA 1=open 2=closed 3=fault ContactorStatus(9, result.MGP.ParamVal); break; case 118 : //p10 con 0=NA 1=open 2=closed 3=fault ContactorStatus(10, result.MGP.ParamVal); break; case 119 : //TIE-Bus con 0=NA 1=open 2=closed 3=fault ContactorStatus(11, result.MGP.ParamVal); break; case 120 : //generator timer seconds window.Power_chart1.gentimer_sec = result.MGP.ParamVal; generator_timer(); break; case 121 : //generaor timer minutes window.Power_chart1.gentimer_minut = result.MGP.ParamVal; generator_timer(); break; case 122 : //generaor timer minutes document.getElementById("table_1").rows[2].cells[6].innerHTML = result.MGP.ParamVal * 1 + " kW"; break; case 123 : //generaor timer minutes document.getElementById("table_1").rows[3].cells[6].innerHTML = result.MGP.ParamVal * 1 + " kW"; break; case 124 : //generaor timer minutes document.getElementById("table_1").rows[4].cells[6].innerHTML = result.MGP.ParamVal * 1 + " kW"; break; case 125 : //generaor timer minutes document.getElementById("Mode_status").innerHTML = result.MGP.ParamVal; if (result.MGP.ParamVal == 0) { document.getElementById("Mode_status").innerHTML = "PMM Mode: NA" } if (result.MGP.ParamVal == 1) { document.getElementById("Mode_status").innerHTML = "PMM Mode: Off" } if (result.MGP.ParamVal == 2) { document.getElementById("Mode_status").innerHTML = "PMM Mode: Bypass" } if (result.MGP.ParamVal == 3) { document.getElementById("Mode_status").innerHTML = "PMM Mode: Auto" } //data for the evse case 1: document.getElementById("batterydailychargeenergy").innerHTML = result.MGP.ParamVal; break; break; } /* end of switch case statement */ } catch (Exception) { console.log(Exception.message); } }; /* end of got parameter value response function */ //second call // function sendrequestparametervalues2 () // { // request = {WPUSHG:{WPUSHGID:"PortsData2",Maxrate:50,Minrate:5000}}; // send(ws, request, var_callbackgotresponse1); // console.log("group parameter push request sent");/* TODO, turn off for development only*/ // } // // var timestampHistory1; // var commcounter1=0; // var timesub1; // var var_callbackgotresponse1 = function callbackgotresponse (result) { // console.log("call back reached");/* TODO, turn off for development only*/ // console.log(result);/* TODO, turn off for development only*/ // timesub1= result.MGP.Timestamp.substr(0,18); // if(timestampHistory1 == timesub1){ // commcounter1=1 + commcounter1; // } // else // { // timestampHistory1 = result.MGP.Timestamp.substr(0,18);//"2016-06-21 15:26:30:181108" // commcounter1=0; // } // if(commcounter1 > 100){ // result.MGP.ParamVal=0; // // } // // // handle the display for the state of the image, based on the state reported by the system master controller // // try { // switch(result.MGP.MGPID) // { // // //output ports priority // // // // } /* end of switch case statement */ // // } catch (Exception) // // { // console.log(Exception.message); // } // // }; /* end of got parameter value response function */ }); /* end of main function */ var Power_chart1 = { Port1P : 0, Port2P : 0, Port3P : 0, Port4P : 0, Port5P : 0, Port6P : 0, Port7P : 0, Port8P : 0, Port9P : 0, Port10P : 0, TIECon : 0, Con2Status : 0, gentimer_sec : 0, gentimer_minut : 0, TotalOutputPower : 0 }; // Function returns the product of a and b function MGP_Parmval(MGPvalue) { var string1; switch(MGPvalue) { case "0": string1 = "OFF"; break; case "1": string1 = "LOW"; break; case "2": string1 = "Medium"; break; case "3": string1 = "HIGH"; break; case "4": string1 = "ON"; break; } return string1; } function PortPowerpercent() { document.getElementById("port1pp").value = window.Power_chart1.Port1P; document.getElementById("port1pa").innerHTML = Math.round((window.Power_chart1.Port1P / 60) * 100) + "% of 60kW"; //( Math.round(result.MGP.ParamVal /700)) document.getElementById("port2pp").value = window.Power_chart1.Port2P; document.getElementById("port2pa").innerHTML = Math.round((window.Power_chart1.Port2P / 60) * 100) + "% of 60kW"; document.getElementById("port3pp").value = window.Power_chart1.Port3P; document.getElementById("port3pa").innerHTML = Math.round((window.Power_chart1.Port3P / 60) * 100) + "% of 60kW"; document.getElementById("port4p").value = window.Power_chart1.Port4P; document.getElementById("port4pa").innerHTML = Math.round((window.Power_chart1.Port4P / 60) * 100) + "% of 60kW"; document.getElementById("port5p").value = window.Power_chart1.Port5P; document.getElementById("port5pa").innerHTML = Math.round((window.Power_chart1.Port5P / 30) * 100) + "% of 30kW"; document.getElementById("port6p").value = window.Power_chart1.Port6P; document.getElementById("port6pa").innerHTML = Math.round((window.Power_chart1.Port6P / 30) * 100) + "% of 30kW"; document.getElementById("port7p").value = window.Power_chart1.Port7P; document.getElementById("port7pa").innerHTML = Math.round((window.Power_chart1.Port7P / 20) * 100) + "% of 20kW"; document.getElementById("port8p").value = window.Power_chart1.Port8P; document.getElementById("port8pa").innerHTML = Math.round((window.Power_chart1.Port8P / 30) * 100) + "% of 30kW"; document.getElementById("port9p").value = window.Power_chart1.Port9P; document.getElementById("port9pa").innerHTML = Math.round((window.Power_chart1.Port9P / 20) * 100) + "% of 20kW"; document.getElementById("port10p").value = window.Power_chart1.Port10P; document.getElementById("port10pa").innerHTML = Math.round((window.Power_chart1.Port10P / 20) * 100) + "% of 20kW"; // total_output_power document.getElementById("total_output_power").innerHTML = "Total Output Power: " + ((window.Power_chart1.Port4P + window.Power_chart1.Port5P + window.Power_chart1.Port6P + window.Power_chart1.Port7P + window.Power_chart1.Port8P + window.Power_chart1.Port9P + window.Power_chart1.Port10P)).toFixed(2) + " kW"; window.Power_chart1.TotalOutputPower = ((window.Power_chart1.Port4P + window.Power_chart1.Port5P + window.Power_chart1.Port6P + window.Power_chart1.Port7P + window.Power_chart1.Port8P + window.Power_chart1.Port9P + window.Power_chart1.Port10P)).toFixed(2); } function ContactorStatus(ConNum, ConStatus) { //input ports color if (ConNum <= 3) { var jloop = 0; while (jloop < 5) { //change color of table cel switch(ConStatus) {//0=NA 1=open 2=closed 3=fault case "0": document.getElementById("table_1").rows[1+ConNum].cells[1 + jloop].className = "w3-white"; break; case "1": document.getElementById("table_1").rows[1+ConNum].cells[1 + jloop].className = "w3-grey"; break; case "2": document.getElementById("table_1").rows[1+ConNum].cells[1 + jloop].className = "w3-white"; break; case "3": document.getElementById("table_1").rows[1+ConNum].cells[1 + jloop].className = "w3-red"; break; } jloop++; } } // if contactor 13 is closed and primary bus is connected to secodnay if (ConNum == 11) { if (ConStatus == "2") { window.Power_chart1.TIECon = 1; /// is closed document.getElementById("table_2").rows[6].cells[0].className = "w3-blue"; document.getElementById("table_2").rows[6].cells[1].className = "w3-white"; document.getElementById("table_2").rows[6].cells[2].className = "w3-white"; document.getElementById("table_2").rows[6].cells[3].className = "w3-white"; document.getElementById("table_2").rows[6].cells[4].className = "w3-white"; document.getElementById("table_2").rows[6].cells[5].className = "w3-white"; document.getElementById("table_2").rows[6].cells[6].className = "w3-white"; document.getElementById("table_2").rows[6].style = "display:none;"; } else { window.Power_chart1.TIECon = 0; // is open document.getElementById("table_2").rows[6].cells[0].className = "w3-black"; document.getElementById("table_2").rows[6].cells[1].className = "w3-black"; document.getElementById("table_2").rows[6].cells[2].className = "w3-black"; document.getElementById("table_2").rows[6].cells[3].className = "w3-black"; document.getElementById("table_2").rows[6].cells[4].className = "w3-black"; document.getElementById("table_2").rows[6].cells[5].className = "w3-black"; document.getElementById("table_2").rows[6].cells[6].className = "w3-black"; document.getElementById("table_2").rows[6].style = "display: table-row;"; } } if (ConNum == 2) { if (ConStatus == "2") { window.Power_chart1.Con2Status = 1; } else { window.Power_chart1.Con2Status = 0; } } /// if contactor 13 is closed, make them same color var colorClosed; if (window.Power_chart1.TIECon == 0 && ConNum >= 8) { colorClosed = "w3-white"; } else if (window.Power_chart1.TIECon == 1 && window.Power_chart1.Con2Status == 1) {//tie is closed and con 2 closed colorClosed = "w3-white"; } else { colorClosed = "w3-white"; } // table 2 have empty row after port 7 var rownumAdjust = 0; if (ConNum >= 8) { rownumAdjust = -1; } if (ConNum >= 4 && ConNum <= 7) { rownumAdjust = -2; } // output ports color if (ConNum >= 4 && ConNum <= 10) { var jloop = 0; while (jloop < 6) { //change color of table cel switch (ConStatus) {//0=NA 1=open 2=closed 3=fault case "0": document.getElementById("table_2").rows[rownumAdjust + ConNum].cells[1 + jloop].className = "w3-white"; break; case "1": document.getElementById("table_2").rows[rownumAdjust + ConNum].cells[1 + jloop].className = "w3-grey"; break; case "2": document.getElementById("table_2").rows[rownumAdjust + ConNum].cells[1 + jloop].className = colorClosed; break; case "3": document.getElementById("table_2").rows[rownumAdjust + ConNum].cells[1 + jloop].className = "w3-red"; break; } jloop++; } } } function generator_timer() { // function pad(n) { // return (n < 10) ? ("0" + n) : n; // } document.getElementById("gen_timer").innerHTML = "Reset Timer: " + window.Power_chart1.gentimer_minut + ":" + ((window.Power_chart1.gentimer_sec < 10) ? ("0" + window.Power_chart1.gentimer_sec) : window.Power_chart1.gentimer_sec); }
import { Meteor } from 'meteor/meteor' import { withTracker } from 'meteor/react-meteor-data' import { ReactiveVar } from 'meteor/reactive-var' import Eventlogs from '/imports/api/eventlogs' import Assessments from '/imports/api/assessments/schema' import Jobs from '/imports/api/jobs/schema' import Members from '/imports/api/members/schema' import JobCardList from '/imports/ui/jobs/assessment-job-card-list' import { JOB_STATUS_ALL, JOB_STATUS_READABLE, } from '/imports/api/constants' const searchVar = new ReactiveVar('') const statusVar = new ReactiveVar('') // currently opened assessment Id // so that we can dynamically subscribe to logs const selectedaId = new ReactiveVar('') export default withTracker((props) => { const jobSub = Meteor.subscribe('jobs.current') const membersSub = Meteor.subscribe('all.members') const logSub = Meteor.subscribe('jobs.eventlogs', selectedaId.get()) const loading = !jobSub.ready() && !membersSub.ready() && !logSub.ready() function changeAssId(aId) { selectedaId.set(aId) } const logs = Eventlogs.find({ objectId: selectedaId.get() }).fetch() const searchFind = (search) => { resetStatus() searchVar.set(search) } const statusFilter = (status) => { let statusValue if (status === 'all') { statusValue = JOB_STATUS_ALL } else { statusValue = Object.keys(JOB_STATUS_READABLE) // [ "1","2","3","4","5" ] .filter((key) => key === status.key) // ["1"] .map((value) => parseInt(value)) // [1] } statusVar.set(statusValue) } const resetStatus = () => { statusVar.set(JOB_STATUS_ALL) } const updateStatus = (jobId, updatedStatus) => { Meteor.call('job.updateJobStatus', jobId, updatedStatus) } const updatePaid = (jobId) => { Meteor.call('job.updatePaid', jobId) } const completeJob = (jobId) => { Meteor.call('job.completeJob', jobId) } const renderJob = () => { const search = searchVar.get() const status = statusVar.get() if (status == '') { return Jobs .find // { // search: { // $regex: search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), // $options: 'i', // }, // }, // { sort: { createdAt: -1 } } () .fetch() } return Jobs.find( { // search: { // $regex: search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), // $options: 'i', // }, status: { $in: status }, }, { sort: { createdAt: -1 } } ).fetch() } return { loading, jobs: renderJob(), members: Members.find( {}, { fields: { name: 1 }, sort: { name: 1 } } ).fetch(), searchFind, statusFilter, updateStatus, updatePaid, completeJob, resetStatus, logs, selectedaId: selectedaId.get(), changeAssId, } })(JobCardList)
// @ts-check /** @type {import("webpack").RuleSetRule[]} */ const mainRules = [ { // We're specifying native_modules in the test because the asset relocator loader generates a // "fake" .node file which is really a cjs file. test: /native_modules\/.+\.node$/, use: 'node-loader', }, { test: /\.(m?js|node)$/, parser: { amd: false }, use: { loader: '@vercel/webpack-asset-relocator-loader', options: { outputAssetBase: 'native_modules', }, }, }, { test: /\.tsx?$/, include: /src/, use: [{ loader: 'ts-loader', options: /** @type {import("ts-loader").Options} */({ transpileOnly: true, onlyCompileBundledFiles: true }) }] }]; /** @type {import("webpack").RuleSetRule[]} */ const rendererRules = [...mainRules, { oneOf: [ { test: /\.css$/, use: [ { loader: "style-loader" }, { loader: "css-loader" }, ], }, ] }]; /** @type {(target: "main" | "renderer") => import("webpack").RuleSetRule[]} */ module.exports = target => target === "main" ? mainRules : rendererRules;
// NOTE: Once the next KaTeX release is out, we'll include this as an npm module // However, we need this for features that are not yet available. import Katex from './katex.min.js' import State from './RenderingState' import classStateMapping from './classStateMapping' import styleStateMapping from './styleStateMapping' import { SvgNode, TextNode, HPaddingNode, VerticalListRow } from './virtualCanvasNodes' const IDENTIFIER_CLASS = 'enclosing' /** * NodeData represents the data returned from the build method */ class NodeData { constructor (rootNode, attributes) { this.rootNode = rootNode this.attributes = attributes } } /** * The NodeBuilder represents the entry point for all renderers. * The only method public method available is the "build method". */ export default class VirtualNodeBuilder { /** * Constructor * * @param {String} latex - Sets the initial latex expression * @param {Object} options - Any options to apply to the expression */ constructor (latex, options) { this._latex = latex this._options = options } /** * Builds all the Virtual Nodes and retrieves the appropriate attributes * for the given latex/options. This is the entry point for any renderer * implementation. * * @return {NodeData} */ build () { this._state = new State(State.defaultOptions(this._options)) const row = new VerticalListRow() this._state.vlist.addRow(row) this._classIndexes = {} const virtualDomTree = Katex.__renderToHTMLTree(this._latex, this._options).children[0] this._createRenderingState(virtualDomTree) const rootNode = this._state.vlist rootNode.align() const attributes = this._getNodeAttributes(virtualDomTree, rootNode) const nodeData = new NodeData(rootNode, attributes) return nodeData } _getNodeAttributes (virtualDomTree, root) { const attributes = {} const strutBounds = root.getStrutBounds() attributes.baselineHeight = strutBounds.height - (virtualDomTree.depth * this._state.em) attributes.strutBounds = strutBounds return attributes } _createRenderingState (node) { const parentState = this._state this._getGlyphDataFromNode(node) if (node.children) { node.children.forEach(child => this._createRenderingState(child)) } this._resetState(parentState) } _resetState (parentState) { const vlist = this._state.vlist const parentVlist = parentState.vlist if (vlist !== parentVlist) { vlist.setStretchyWidths() vlist.align() parentVlist.addCell(vlist) } if (this._state.classes !== parentState.classes) { this._state.classes.forEach((classData) => { if (!(classData in parentState.classes)) { this._classIndexes[classData.name]++ } }) } if (this._state.pstrut) { parentState = parentState.withYShift(this._state.pstrut) .withResetMargin() } this._state = parentState } _getGlyphDataFromNode (node) { this._extractClassDataFromNode(node) this._extractStyleDataFromNode(node) this._createMSpace() this._createSvgNode(node) this._createTextNode(node) this._createItalicNode(node) } _extractClassDataFromNode (node) { const classes = node.classes || [] let nextClassIsLatexClass = false classes.forEach((name) => { if (name === IDENTIFIER_CLASS) { nextClassIsLatexClass = true } else if (nextClassIsLatexClass) { nextClassIsLatexClass = false this._classIndexes[name] = this._classIndexes[name] || 0 this._state = this._state.withClass({ name, index: this._classIndexes[name] }) } else { const camelName = this._toCamelCase(name) if (classStateMapping[camelName]) { this._state = classStateMapping[camelName](this._state, node, this._options) } } }) } _toCamelCase (str) { return str.replace(/-([a-z])/g, function (g) { return g[1].toUpperCase() }) } _createMSpace () { if (this._state.mspace) { const mspace = new HPaddingNode(this._state.classes) mspace.setPosition(this._state.nextX, this._state.y) mspace.bounds.set({ width: this._state.mspace * this._state.em }) this._state.vlist.addCell(mspace) this._state = this._state.withResetMargin() } } _extractStyleDataFromNode (node) { if (!node.style) return Object.keys(node.style).forEach((key) => { const value = node.style[key] if (styleStateMapping[key]) { this._state = styleStateMapping[key](this._state, value, node) } }) } _createSvgNode (node) { if (node instanceof Katex.__domTree.svgNode) { const virtualSvg = node const state = this._state const height = (+virtualSvg.attributes.height.replace('em', '')) * this._state.em if (virtualSvg.attributes.style) { // for `\oiint`, the width gets specified in a style="xx.xxem" attribute // however this causes it to become rendered vert small as em isn't // scaled properly; we can either remove the style attribute and let // the externally-set height determine the bounds, or we can scale the // em similar to what is done to the height earlier in this function. // We do the former, while adding a console warning in case another // (unexpected) condition is encountered - in which case the developer // should handle this new case accordingly. if (!/^width:[+-]?(?:[0-9]*[.])?[0-9]+em$/.test(virtualSvg.attributes.style)) { console.warn('Unsupported SVG node explicit style attribute', virtualSvg.attributes.style) } else { // width will be determined by height delete virtualSvg.attributes.style } } virtualSvg.attributes.height = height virtualSvg.attributes.fill = this._state.color const svgNode = new SvgNode(virtualSvg, state.minWidth, state.classes) svgNode.setPosition(state.nextX, state.y) svgNode.bounds.set({ height }) svgNode.margin.set({ left: state.marginLeft, right: state.marginRight }) this._state.vlist.addCell(svgNode) this._state = this._state.withResetMargin() } } _createTextNode (node) { // The '' is NOT an empty string. It's some invisible character (U+200B) aka ZERO-WIDTH Space const isNonZeroWidthSpaceText = node.value && node.value !== '​' if (isNonZeroWidthSpaceText) { const state = this._state const textNode = new TextNode(node.value, state.font, state.color, state.classes) textNode.setPosition(state.nextX, state.y) textNode.margin.set({ left: state.marginLeft, right: state.marginRight }) this._state.vlist.addCell(textNode) this._state = this._state.withResetMargin() } } _createItalicNode (node) { if (node.italic) { const italic = this._state.em * node.italic const italicNode = new HPaddingNode(this._state.classes) italicNode.setPosition(this._state.nextX, 0) italicNode.bounds.set({ width: italic }) this._state.vlist.addCell(italicNode) this._state = this._state.withResetMargin() } } }
import { Spinner, SpinnerSize } from '@fluentui/react'; import PropTypes from 'prop-types'; import React from 'react'; import styled from 'styled-components'; const StyledOverlay = styled.div` background-color: rgba(0, 0, 0, 0.1); display: flex; align-items: center; justify-content: center; color: white; min-height: calc(100vh - 3.2rem); width: 100%; position: absolute; span { font-weight: bold; font-size: 2rem; } `; export default function LoadingOverlay({ message = 'Loading...' }) { return ( <StyledOverlay> <Spinner size={SpinnerSize.large} label={message} /> </StyledOverlay> ); } LoadingOverlay.propTypes = { message: PropTypes.string, };
/* * @license * Your First PWA Codelab (https://g.co/codelabs/pwa) * Copyright 2019 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ 'use strict'; const weatherApp = { selectedLocations: {}, addDialogContainer: document.getElementById('addDialogContainer'), }; /** * Toggles the visibility of the add location dialog box. */ function toggleAddDialog() { weatherApp.addDialogContainer.classList.toggle('visible'); } /** * Event handler for butDialogAdd, adds the selected location to the list. */ function addLocation() { // Hide the dialog toggleAddDialog(); // Get the selected city const select = document.getElementById('selectCityToAdd'); const selected = select.options[select.selectedIndex]; const geo = selected.value; const label = selected.textContent; const location = {label: label, geo: geo}; // Create a new card & get the weather data from the server const card = getForecastCard(location); getForecastFromNetwork(geo).then((forecast) => { renderForecast(card, forecast); }); // Save the updated list of selected cities. weatherApp.selectedLocations[geo] = location; saveLocationList(weatherApp.selectedLocations); } /** * Event handler for .remove-city, removes a location from the list. * * @param {Event} evt */ function removeLocation(evt) { const parent = evt.srcElement.parentElement; parent.setAttribute('hidden', true); if (weatherApp.selectedLocations[parent.id]) { delete weatherApp.selectedLocations[parent.id]; saveLocationList(weatherApp.selectedLocations); } } /** * Renders the forecast data into the card element. * * @param {Element} card The card element to update. * @param {Object} data Weather forecast data to update the element with. */ function renderForecast(card, data) { if (!data) { // There's no data, skip the update. return; } // Find out when the element was last updated. const cardLastUpdatedElem = card.querySelector('.card-last-updated'); const cardLastUpdated = cardLastUpdatedElem.textContent; const lastUpdated = parseInt(cardLastUpdated); // If the data on the element is newer, skip the update. if (lastUpdated >= data.currently.time) { return; } cardLastUpdatedElem.textContent = data.currently.time; // Render the forecast data into the card. card.querySelector('.description').textContent = data.currently.summary; const forecastFrom = luxon.DateTime .fromSeconds(data.currently.time) .setZone(data.timezone) .toFormat('DDDD t'); card.querySelector('.date').textContent = forecastFrom; card.querySelector('.current .icon') .className = `icon ${data.currently.icon}`; card.querySelector('.current .temperature .value') .textContent = Math.round(data.currently.temperature); card.querySelector('.current .humidity .value') .textContent = Math.round(data.currently.humidity * 100); card.querySelector('.current .wind .value') .textContent = Math.round(data.currently.windSpeed); card.querySelector('.current .wind .direction') .textContent = Math.round(data.currently.windBearing); const sunrise = luxon.DateTime .fromSeconds(data.daily.data[0].sunriseTime) .setZone(data.timezone) .toFormat('t'); card.querySelector('.current .sunrise .value').textContent = sunrise; const sunset = luxon.DateTime .fromSeconds(data.daily.data[0].sunsetTime) .setZone(data.timezone) .toFormat('t'); card.querySelector('.current .sunset .value').textContent = sunset; card.querySelector('.current .precip-prob .value').textContent = Math.round(data.currently.precipProbability * 100) + '%'; card.querySelector('.feels .value').textContent = Math.round(data.currently.apparentTemperature); // Render the next 7 days. const futureTiles = card.querySelectorAll('.future .oneday'); futureTiles.forEach((tile, index) => { const forecast = data.daily.data[index + 1]; const forecastFor = luxon.DateTime .fromSeconds(forecast.time) .setZone(data.timezone) .toFormat('ccc'); tile.querySelector('.date').textContent = forecastFor; tile.querySelector('.icon').className = `icon ${forecast.icon}`; tile.querySelector('.temp-high .value') .textContent = Math.round(forecast.temperatureHigh); tile.querySelector('.temp-low .value') .textContent = Math.round(forecast.temperatureLow); tile.querySelector('.precip-prob .value') .textContent = Math.round(forecast.precipProbability * 100); }); // If the loading spinner is still visible, remove it. const spinner = card.querySelector('.card-spinner'); if (spinner) { card.removeChild(spinner); } } /** * Get's the latest forecast data from the network. * * @param {string} coords Location object to. * @return {Object} The weather forecast, if the request fails, return null. */ function getForecastFromNetwork(coords) { return fetch(`/forecast/${coords}`) .then((response) => { return response.json(); }) .catch(() => { return null; }); } /** * Get's the cached forecast data from the caches object. * * @param {string} coords Location object to. * @return {Object} The weather forecast, if the request fails, return null. */ function getForecastFromCache(coords) { // CODELAB: Add code to get weather forecast from the caches object. } /** * Get's the HTML element for the weather forecast, or clones the template * and adds it to the DOM if we're adding a new item. * * @param {Object} location Location object * @return {Element} The element for the weather forecast. */ function getForecastCard(location) { const id = location.geo; const card = document.getElementById(id); if (card) { return card; } const newCard = document.getElementById('weather-template').cloneNode(true); newCard.querySelector('.location').textContent = location.label; newCard.setAttribute('id', id); newCard.querySelector('.remove-city') .addEventListener('click', removeLocation); document.querySelector('main').appendChild(newCard); newCard.removeAttribute('hidden'); return newCard; } /** * Gets the latest weather forecast data and updates each card with the * new data. */ function updateData() { Object.keys(weatherApp.selectedLocations).forEach((key) => { const location = weatherApp.selectedLocations[key]; const card = getForecastCard(location); // CODELAB: Add code to call getForecastFromCache // Get the forecast data from the network. getForecastFromNetwork(location.geo) .then((forecast) => { renderForecast(card, forecast); }); }); } /** * Saves the list of locations. * * @param {Object} locations The list of locations to save. */ function saveLocationList(locations) { const data = JSON.stringify(locations); localStorage.setItem('locationList', data); } /** * Loads the list of saved location. * * @return {Array} */ function loadLocationList() { let locations = localStorage.getItem('locationList'); if (locations) { try { locations = JSON.parse(locations); } catch (ex) { locations = {}; } } if (!locations || Object.keys(locations).length === 0) { const key = '40.7720232,-73.9732319'; locations = {}; locations[key] = {label: 'New York City', geo: '40.7720232,-73.9732319'}; } return locations; } /** * Initialize the app, gets the list of locations from local storage, then * renders the initial data. */ function init() { // Get the location list, and update the UI. weatherApp.selectedLocations = loadLocationList(); updateData(); // Set up the event handlers for all of the buttons. document.getElementById('butRefresh').addEventListener('click', updateData); document.getElementById('butAdd').addEventListener('click', toggleAddDialog); document.getElementById('butDialogCancel') .addEventListener('click', toggleAddDialog); document.getElementById('butDialogAdd') .addEventListener('click', addLocation); } init();
module.exports = function (api) { process.env.NODE_ENV === "development" ? api.cache(false) : api.cache(true); const presets = [ [ "@babel/preset-env", { targets: { node: "current", }, }, ], "@babel/preset-typescript", ]; const plugins = []; return { presets, plugins, }; };
// Export Constants export const TOGGLE_ADD_POST = "TOGGLE_ADD_POST"; export const TOGGLE_EDIT_POST = "TOGGLE_EDIT_POST"; // Export Actions export function toggleAddPost() { return { type: TOGGLE_ADD_POST }; } export function toggleEditPost() { return { type: TOGGLE_EDIT_POST }; }
var presencia = (function (window, undefined) { var workers = {}; var eventos = function() { $('#checador').submit(function(e){ e.preventDefault(); }); $('#serial').on('keyup', function(e) { if(e.which === 13) { e.preventDefault(); var ahora = moment(moment().format('HH:mm'),'HH:mm'); var diferencia = moment.duration(ahora - limite)._milliseconds/60000; var clase = 'neutral'; var referencia = $(this).val(); var mandar = false; if(referencia.length > 0) { var resultado = { 'res' : false, 'id' : 0, 'nombre' : 'Usuario no encontrado', 'avatar' : 'assets/images/users/avatar.jpg', 'clase' : 'fallo', 'tiempo' : ahora.format('HH:mm') }; if(personal[referencia]) { mandar = true; if(personal[referencia].registros == 0) { if(diferencia < 0) { clase = 'atiempo'; } else { clase = 'tarde'; } } resultado = { 'res' : true, 'id' : personal[referencia].id, 'nombre' : personal[referencia].name, 'avatar' : personal[referencia].foto, 'clase' : clase, 'tiempo' : ahora.format('HH:mm') }; } else if(personal[referencia] == undefined) { for(key in personal) { if(personal[key].clave == referencia) { mandar = true; if(personal[key].registros == 0) { if(diferencia < 0) { clase = 'atiempo'; } else { clase = 'tarde'; } } resultado = { 'res' : true, 'id' : personal[key].id, 'nombre' : personal[key].name, 'avatar' : personal[key].foto, 'clase' : clase, 'tiempo' : ahora.format('HH:mm') }; } } } if(mandar) { crearWorker(referencia); } $(this).val('').focus(); mostrar(resultado); } } }); }; var crearWorker = function(referencia) { workers[referencia] = new Worker('/js/presencia.worker.js'); workers[referencia].addEventListener('message', function(e) { var resultado = JSON.parse(e.data); }); $.get('/tokenpresencia', function(data, status) { workers[referencia].postMessage({ clave : referencia, _token : data._token }); }); }; var mostrar = function(data) { var tarjeta = '<div id="t'+data.id+'" class="tarjeta oculto '+data.clase+'">\ <div class="imagen">\ <img src="images/usuarios/'+data.avatar+'" />\ </div>\ <div class="contenido">\ <h3>'+data.nombre+'</h3>\ <h2 class="mt-1">'+data.tiempo+'</h2>\ </div>\ </div>'; $('.usuarios').append(tarjeta); $('#t'+data.id).addClass('visible'); setTimeout(function() { $('#t'+data.id).removeClass('visible'); setTimeout(function() { $('#t'+data.id).remove(); }, 1200); }, 3000); }; var checkPageFocus = function() { let body = document.querySelector('body'); if (document.hasFocus()) { $('.logo').removeClass('sleeping').find('img').attr('src', '/assets/images/logo.png'); $('#serial').focus(); } else { //$('.logo').addClass('sleeping').find('img').attr('src', '/img/sleeping.png'); } } var personal = {}; var limite = null; var setPersonal = function(datos) { datos.forEach(function(value) { personal[value.serial] = value; }); }; return { form : function(datos, entrada) { limite = moment(entrada,'HH:mm'); setPersonal(datos); eventos(); }, checkPageFocus : function() { checkPageFocus(); }, renewToken : function() { }, actualizaPersonal : function() { $.get('/getpersonal', function(data, status) { setPersonal(data); }); } }; })(window, undefined); setInterval(presencia.checkPageFocus, 1000); //1 segundo setInterval(presencia.actualizaPersonal, 600000); //10 minutos
import getBase64 from '../getBase64' describe('#getBase64', () => { it('should get a value from base64 string', () => { expect(getBase64('Zm9v')).toBe('foo') }); })
function area(largura, altura) { const area = largura * altura; if (area > 20) { console.log(`O valor acima do permitido: ${area}m2.`); } else { return area; } } let resultado = area(5, 5); if (resultado != undefined) console.log(resultado); console.log(area(5, 5) + 1); resultado = area(4, 5); if (resultado != undefined) console.log(resultado); //https://pt.stackoverflow.com/q/474321/101
var searchData= [ ['scan_5factive_5fdwell_5ftime_5fper_5fchannel_5fms',['scan_active_dwell_time_per_channel_ms',['../structwhd__scan__extended__params__t.html#addbd186dd08b75e5de298a3d8dbb76a1',1,'whd_scan_extended_params_t']]], ['scan_5fhome_5fchannel_5fdwell_5ftime_5fbetween_5fchannels_5fms',['scan_home_channel_dwell_time_between_channels_ms',['../structwhd__scan__extended__params__t.html#a325bae58ff955b428047edab0a2f0799',1,'whd_scan_extended_params_t']]], ['scan_5fint',['scan_int',['../structwhd__btc__lescan__params.html#ab9fbbe93d8ab19fa81bebf4ade2deddd',1,'whd_btc_lescan_params']]], ['scan_5fpassive_5fdwell_5ftime_5fper_5fchannel_5fms',['scan_passive_dwell_time_per_channel_ms',['../structwhd__scan__extended__params__t.html#afe48c256e4f4f14eb202d51dd8348818',1,'whd_scan_extended_params_t']]], ['scan_5fwin',['scan_win',['../structwhd__btc__lescan__params.html#a02d72a917cfb65e36cd0527ed472bf8f',1,'whd_btc_lescan_params']]], ['sdio_5f1bit_5fmode',['sdio_1bit_mode',['../structwhd__sdio__config.html#aaf50e6ef7ee9717f104ced9db86efd6a',1,'whd_sdio_config']]], ['sdpcm_5fheader',['SDPCM_HEADER',['../whd__types_8h.html#aaf73ac170e07969ed067a6cd5088044f',1,'whd_types.h']]], ['security',['security',['../structwhd__scan__result.html#ae8d5baabacdabe6d3590465572849754',1,'whd_scan_result::security()'],['../structwhd__simple__scan__result.html#ae8d5baabacdabe6d3590465572849754',1,'whd_simple_scan_result::security()'],['../structwhd__ap__info.html#ae8d5baabacdabe6d3590465572849754',1,'whd_ap_info::security()']]], ['shared_5fenabled',['SHARED_ENABLED',['../whd__types_8h.html#a4d4a4586c264fe8e4acb0bf7169b7b0f',1,'whd_types.h']]], ['signal_5fstrength',['signal_strength',['../structwhd__scan__result.html#ac303b69da3c469c92299a6ff260e2859',1,'whd_scan_result::signal_strength()'],['../structwhd__simple__scan__result.html#ac303b69da3c469c92299a6ff260e2859',1,'whd_simple_scan_result::signal_strength()'],['../structwhd__ap__info.html#ac303b69da3c469c92299a6ff260e2859',1,'whd_ap_info::signal_strength()']]], ['snr',['SNR',['../structwl__bss__info__struct.html#abcbf8106d506ba6a33c01411d5ec3e99',1,'wl_bss_info_struct']]], ['source_5faddress',['source_address',['../structwhd__event__ether__header.html#aceb7473ccdf9d41c5b6aee7a0264972a',1,'whd_event_ether_header']]], ['ssid',['SSID',['../structwhd__scan__result.html#ae3940d431c3c3ed25294eb70a02c330b',1,'whd_scan_result::SSID()'],['../structwhd__simple__scan__result.html#ae3940d431c3c3ed25294eb70a02c330b',1,'whd_simple_scan_result::SSID()'],['../structwl__bss__info__struct.html#a337a4a90b9c8cb320d1232cf9f88fa90',1,'wl_bss_info_struct::SSID()'],['../structwhd__ap__info.html#ae3940d431c3c3ed25294eb70a02c330b',1,'whd_ap_info::SSID()']]], ['ssid_5flen',['SSID_len',['../structwl__bss__info__struct.html#a7eafb3bd3419add91d9d532df5dcf63e',1,'wl_bss_info_struct']]], ['ssid_5fname_5fsize',['SSID_NAME_SIZE',['../whd__types_8h.html#a9ee2fe056ad3787e30bb8da7248592c7',1,'whd_types.h']]], ['status',['status',['../structwhd__event__msg.html#ade20423e91627f07e610924cb0081623',1,'whd_event_msg']]], ['subtype',['subtype',['../structwhd__event__eth__hdr.html#ac5d9ab8403fb9ca24facc32b821dd53b',1,'whd_event_eth_hdr']]], ['sup_5fauth_5fstatus',['sup_auth_status',['../whd__events_8h.html#aba9543ff6a1542d81c7adc66bb339c4c',1,'whd_events.h']]], ['sup_5fauth_5fstatus_5ft',['sup_auth_status_t',['../whd__events_8h.html#a4c17ec19ca52ebe4bbad3ea977108d0b',1,'whd_events.h']]] ];
import React, {useEffect, useState} from 'react' import styled from 'styled-components' import {useMutation, useApolloClient,gql} from '@apollo/client' import UserForm from '../components/UserForm' const SIGNUP_USER = gql` mutation signUp($email: String!, $username: String!, $password: String!){ signUp(email: $email, username: $username, password: $password) } ` const SignUp = props => { // Apollo client const client = useApolloClient() // Mutation Hook // mutation hook const [signUp,{loading,error}] = useMutation(SIGNUP_USER,{ onCompleted: data => { // store the token localStorage.setItem('token', data.signUp) // update the local cache client.writeData({data:{isLoggedIn: true}}) // redirect the user to the homepage props.history.push('/') } }) // change page title useEffect(() => { document.title = 'Sign up - Notedly' }) return ( <React.Fragment> <UserForm action={signUp} formType='signup'/> {/* if the data is loading, display a loading message */} {loading && <p>Loading...</p>} {/* if there is an error, display an error message */} {error && <p>Error creating an account!</p>} </React.Fragment> ) } export default SignUp
import { PostHogFeatureFlags } from '../posthog-featureflags' describe('featureflags', () => { given('properties', () => ({ $override_feature_flags: false, $active_feature_flags: ['beta-feature'] })) given('instance', () => ({ get_property: (key) => given.properties[key], capture: () => {}, })) given('feature_flags', () => new PostHogFeatureFlags(given.instance)) beforeEach(() => { jest.spyOn(given.instance, 'capture').mockReturnValue() }) it('should return the right feature flag and call capture', () => { expect(given.feature_flags.getFlags()).toEqual(['beta-feature']) expect(given.feature_flags.isFeatureEnabled('beta-feature')).toEqual(true) expect(given.feature_flags.isFeatureEnabled('random')).toEqual(false) expect(given.instance.capture).toHaveBeenCalled() }) it('should return the right feature flag and not call capture', () => { expect(given.feature_flags.isFeatureEnabled('beta-feature', { send_event: false })).toEqual(true) expect(given.instance.capture).not.toHaveBeenCalled() }) })
/** * Created by liulin on 2017/1/7. */ ES.MapView.MapLive = L.MapLib.MapMaster.MapOpr.extend({ /* 为构造函数 @oParent 为父级页面对象 @oOption 为参数,设置当前的参数 */ initialize: function (oParent, oOption,oMap) { L.MapLib.MapMaster.MapOpr.prototype.initialize.call(this, oParent, oOption, oMap); // 添加图层 this._loadLayerGroup(); // 注册监听事件 this._initOn(); this.devNo = oOption.devNo || "-1"; this.cId = null; }, setOption: function(oGpsInfo) { if(oGpsInfo.hasOwnProperty('vehNo')){ delete oGpsInfo.vehNo; } return ES.extend(this.options, oGpsInfo); }, // 初始化监听事件 _initOn: function () { this._oMap.on("moveend", this._mapMoveHandler, this); // 画实时点 this._oParent.on("MV:Real.drawLiveTrack", this.drawLiveTrack, this); // 判断是否显示弹出层 this._oParent.on("MV:Real.showVecMarkerPop", this._showVecMarkerPop, this); // 放大实时监控点 this._oParent.on("MV:Real.setLiveZoomIn", this.setLiveZoomIn, this); // 清除实时跟踪的点、历史点、轨迹线 this._oParent.on("MV:Real.clearLiveTrack", this.clearLiveTrack, this); this._oParent.on("MapView:MapLive.setZoomIn", this.setZoomIn, this); }, // 实现地图放大 setZoomIn:function(oData) { if (!oData || !oData.oGpsInfo) { return; } var oGpsInfo = oData.oGpsInfo; var oLayer = this.findLayer(this._oLivePosGroup, oGpsInfo.devNo); if (!oLayer) { return; } var oLatLng = oLayer.getLatLng(); this.flyTo(oLatLng, {zoom: 16}); // 打开popup层显示车辆数据 oLayer.openPopup(); }, // 关闭事件 offEven: function () { this._oMap.off("moveend", this._mapMoveHandler, this); // 画实时点 this._oParent.off("MV:Real.drawLiveTrack", this.drawLiveTrack, this); //解决聚合和实时同时存在问题 this._oParent.off("MV:Real.unVisibleMarker"); // 判断是否显示弹出层 this._oParent.off("MV:Real.showVecMarkerPop", this._showVecMarkerPop, this); // 放大实时监控点 this._oParent.off("MV:Real.setLiveZoomIn", this.setLiveZoomIn, this); // 清楚实时跟踪的点、历史点、轨迹线 this._oParent.off("MV:Real.clearLiveTrack", this.clearLiveTrack, this); }, //添加实时跟踪状态数据 _loadLayerGroup: function () { //线路 this._oLineGroup = L.featureGroup(); this._oMap.addLayer(this._oLineGroup); //轨迹点 this._oTrackGroup = L.featureGroup(); this._oMap.addLayer(this._oTrackGroup); //实时跟踪点 this._oLivePosGroup = L.featureGroup(); this._oMap.addLayer(this._oLivePosGroup); }, //判断弹出层是否应该弹出,如果地图为当前获得页,就弹出层,否则不弹出 //对地图进行了放大缩小操作 _showVecMarkerPop: function (oData) { if (!this._oLivePosGroup) return; var bActive = $("#Map").hasClass("active"); var oGpsInfo = oData.oGpsInfo; this._oLivePosGroup.eachLayer(function (oLayer) { if (oGpsInfo.cDevId != oLayer.cId) { oLayer.closePopup(); return; } if (bActive) { this._oMap.setView(oLayer.getLatLng(), 17); oGpsInfo.bOpenBubble ? oLayer.openPopup() : oLayer.closePopup(); } else { oLayer.closePopup(); } }, this) }, //修改弹出层样式错误, _updateVecMarkerPop: function (oLivePosLayer, cHtml) { if (!oLivePosLayer) return; oLivePosLayer.setPopupContent(cHtml); }, //画布,实时跟踪绘制,如线,轨迹点等,oPosInfo,为当前点信息 _drawLiveHis: function (oPosInfo) { var oPrePosInfo = null; var oLineLayer = this.findLayer(this._oLineGroup, oPosInfo.devNo); if (!oLineLayer) { //创建线图层 var oPloyLine = L.polyline([oPosInfo.latLng], ES.MapView.oConfig.oLiveLineConfig); oPloyLine.cId = oPosInfo.devNo; oPloyLine.oPrePosInfo = oPosInfo; oPloyLine.addTo(this._oLineGroup); } else { oPrePosInfo = oLineLayer.oPrePosInfo; oLineLayer.oPrePosInfo = oPosInfo; oLineLayer.addLatLng(oPosInfo.latLng); } //创建轨迹图层 if (oPrePosInfo) { var oTrackLayer = L.circleMarker(oPrePosInfo.latLng, ES.MapView.oConfig.oLiveCircleMarkerConfig); var cHTML = this._oParent._getVecMarkerHtml(oPrePosInfo); oTrackLayer.bindPopup(cHTML, this.oPopOption); var oPopup = oTrackLayer.getPopup(); oPopup.oGpsInfo = oPosInfo; // 设置对象的弹出层 this.initPopEven(oPopup); oTrackLayer.addTo(this._oTrackGroup); } }, // 创建实时跟踪点 _createLive: function (oPosInfo) { this._oParent.fire("MV:Real.unVisibleMarker", oPosInfo); this._oParent.fire("MapView:MapVehMark.updataMarker", oPosInfo); this.selectLi(oPosInfo); var oLatLng = oPosInfo.latLng; var oLayer = L.Marker.movingMarker([oLatLng], [], { icon: this._getPosIconInfo(oPosInfo, { nWidth: 30, nHeight:40, nInitDir: 180 }) }); oLayer.cId = oPosInfo.devNo; oLayer.cVehNo = oPosInfo.vehNo; oLayer.nW = 10; oLayer.oData = oPosInfo; var oOption = L.extend({radius: 50}, ES.MapView.oConfig.oLiveCircleConfig); //var oCircle = L.circle(oLatLng, oOption).addTo(this._oLivePosGroup); //把矢量点添加到地图上 oLayer.addTo(this._oLivePosGroup); //oLayer.oCircle = oCircle; return oLayer; }, // 在地图上绘制实时跟踪的点 _drawLive: function (oPosInfo) { if (!this._oLivePosGroup) { return; } var oLayer = this.findLayer(this._oLivePosGroup, oPosInfo.devNo); var oLatLng = oPosInfo.latLng; var cHtml = this._oParent._getVecMarkerHtml(oPosInfo); if (!oLayer) { this.clearLiveTrack(); this.oLayer = oLayer = this._createLive(oPosInfo); //当弹出层弹出时,界面初始化公司信息,注册按钮事件 oLayer.bindPopup(cHtml, this.oPopOption); var oPopup = oLayer.getPopup(); oPopup.oGpsInfo = oPosInfo; this.initPopEven(oPopup); if (oPosInfo.bOpenBubble) { oLayer.openPopup(); } this._setHeading(oPosInfo, 180); } else { this._oParent.fire("MV:Real.unVisibleMarker", oPosInfo); this._oParent.fire("MapView:MapVehMark.updataMarker", oPosInfo); this._setHeading(oPosInfo, 180); this.selectLi(oPosInfo); oLayer.moveTo(oLatLng,5000); if (oLayer.oCircle) { oLayer.oCircle.setLatLng(oLatLng); } //更新弹出层的信息,修改的目的是防止注册2次点击事件 var oPopup = oLayer.getPopup(); // 在次注册事件 oPopup.oGpsInfo = oPosInfo; oPopup._content = cHtml; oPosInfo.bOpenBubble ? oLayer.openPopup() : oLayer.closePopup(); } oLayer._bringToFront(); this._oMap.fitBounds( this._oLivePosGroup.getBounds()); //删除实时车辆数据 //this._oParent.fire("MV:Real.clearVehicle", oPosInfo); return oLayer; }, //WQ通过class获取li selectLi: function (oPosInfo) { var cId = oPosInfo.devNo; var oLi = $(".ex-layout-carlist-content").find("li"); for (var i = 0; i < oLi.length; i++) { var oLiData = $(oLi[i]).data("data"); if (oLiData.devNo == cId) { $(oLi[i]).removeData("data"); $(oLi[i]).data("data", oPosInfo) } } }, // 地图监控移动设置 _mapMoveHandler: function () { if (!this._oLivePosGroup) return; this._oLivePosGroup.eachLayer(function (oLayer) { if (!oLayer._bringToFront) return; oLayer._bringToFront(); }, this); }, // 清除实时跟踪的点 clearLiveTrack: function () { this._oLivePosGroup.clearLayers(); this._oLineGroup.clearLayers(); this._oTrackGroup.clearLayers(); //如果字不为空,就返回 //if (!this.oLayer || !this.oLayer.oData) return; //if (this.oLayer.oData.text) return; //this._oParent.fire("MV:RegionDraw.addMarker", { oLayer: this.oLayer }); }, // 画实时跟踪轨迹数据 drawLiveTrack: function (oData) { if (!oData.oGpsInfo.latLng) { return; } this._drawLiveHis(oData.oGpsInfo); this._drawLive(oData.oGpsInfo); //this._oParent.fire("MV:Real.reComerVehMarker", oData.oGpsInfo); }, // 放大地图,放大 setLiveZoomIn: function () { var aoLayer = this._oLivePosGroup.getLayers(); if (!aoLayer || aoLayer.length <= 0) { return; } if (!aoLayer[0].getLatLng) { return; } var oLatLng = aoLayer[0].getLatLng(); var nMaxZoom = this._oMap.getMaxZoom(); this._oMap.setView(oLatLng, nMaxZoom - 1); }, }); // 车辆实时跟踪的基本操作 ES.MapView.MapLive.include({ // 设置弹出层的位置 oPopOption: { maxWidth: 450 ,autoPan: false}, // 获得实时跟踪点, 地图统计点数据 _getPosIconInfo: function (oItem, oOption) { oItem.nDir = oItem.direction + oOption.nInitDir; return new L.DivIcon({ html: ES.template(this._getIconHtml(), oItem), className: 'ex-monitor-mapicon-truck-state online ', iconSize: L.point(oOption.nWidth, oOption.nHeight), popupAnchor: L.point(-0, -20), }); }, _getIconHtml: function () { var cHtml = '<div cid="{devNo}" class="car-body" style="transform:rotateZ({nDir}deg);-webkit-transform: rotate({nDir}deg);"></div>' + ' <div class="pin-tip " style="display: none;">' + ' <div class="pin-dome"><b></b><c></c><d></d></div>' + ' <div class="pin-number">{vehNo}</div>' + ' <div class="pin-state">' + //' <i class="o-earth"></i>' + //' <i class="cover"></i>' + ' </div>' + '</div>'; return cHtml; }, // 设置车辆的角度 _setHeading: function (oPosInfo, nInitDir) { if (!oPosInfo) { return; } if (!nInitDir) { nInitDir = 0; } oPosInfo.nDir = oPosInfo.direction + nInitDir; $('div[cId="' + oPosInfo.devNo + '"]').attr('style',ES.template( 'transform: rotate({nDir}deg);-webkit-transform: rotate({nDir}deg);',oPosInfo)); }, //根据告警类型,生成告警样式 alarmToCls: function (oGpsInfo) { // 获得车辆的样式 和 车辆告警样式 var oClass = { cAlarm: "" }; oGpsInfo.cClsLight = "green"; // 车灯要修改 if (!oGpsInfo) return oClass; if (oGpsInfo.Speed > 60) { oClass.cAlarm = "car-state speed"; } return oClass; }, }); // 弹出层的事件操作 ES.MapView.MapLive.include({ // 注册弹出层事件,弹出层绑定对象,每次不是最新oGpsInfo数据,不能用匿名的函数,需要注销 initPopEven: function (oPopup) { var self = this; if (!oPopup) return; oPopup.self = this; oPopup.on("contentupdate", function (){ // 车辆详情按钮 var oBtnDetail = $(".leaflet-popup").find("i.ec-icon-truck").parent(); // 车辆轨迹按钮 var oBtnTrack = $(".leaflet-popup").find("i.ec-icon-exchange").parent(); var oMeassageClick = $(".leaflet-popup").find("i.ec-icon-commenting").parent(); var oGpsInfo = this.oGpsInfo; // 绑定事件 oBtnDetail.bind("click", function () { ES.aWarn('系统正在开发过程!'); }) oBtnTrack.bind("click", function () { // 单独的页面打开 window.open("/MapView/TrackViewV2.html?PhoneNum=" + oGpsInfo.devNo + "&VehicleNo=" + oGpsInfo.vehNo); }) // 发送消息 oMeassageClick.bind("click", function () { ES.aWarn('系统正在开发过程!'); //devcmd.sendMsg(oGpsInfo.VehicleNo, oGpsInfo.PhoneNum); }) //设置状态,设置工地状态 self.setMobileInfo(oGpsInfo); }, oPopup); }, // 设置车辆gps信息 和 网络信息 setMobileInfo: function (oGpsInfo) { //去掉on状态 var $_oIMobile = $(".ex-icon-mobile"); var $_oIBD = $(".ex-icon-bd"); $_oIMobile.removeClass("on").removeClass("off"); $_oIBD.removeClass("on").removeClass("off"); //判断当前位置信息 if (oGpsInfo.VehicleStatus == "行驶" || oGpsInfo.VehicleStatus == "停车" || oGpsInfo.VehicleStatus == "熄火") { $_oIMobile.addClass("on"); $_oIBD.addClass("on"); } else if (oGpsInfo.VehicleStatus == "通讯中断") { $_oIMobile.addClass("l-mobile-off"); $_oIBD.addClass("l-bd-off"); } else if (oGpsInfo.VehicleStatus == "定位失败") { $_oIMobile.addClass("on"); $_oIBD.addClass("off"); } else { $_oIMobile.addClass("off"); $_oIBD.addClass("off"); } }, })
module.exports={A:{A:{"1":"A B","2":"I F E D hB"},B:{"1":"C O U P H J K VB JB N IB"},C:{"1":"0 1 2 3 4 5 6 7 8 9 H J K W X Y Z a b c d e f g h i j k l m n o p q r s t u v w Q y z UB BB FB DB CB AB T x R M KB LB MB NB OB PB QB RB SB TB","2":"rB GB oB","33":"G V I F E D A B C O U P gB"},D:{"1":"0 1 2 3 4 5 6 7 8 9 d e f g h i j k l m n o p q r s t u v w Q y z UB BB FB DB CB AB T x R M KB LB MB NB OB PB QB RB SB TB VB JB N IB fB aB ZB","2":"G V I F E D","33":"A B C O U P H J K W X Y Z a b c"},E:{"1":"F E D A B C O cB dB eB WB L S iB jB","2":"G V yB XB","33":"I bB"},F:{"1":"0 1 2 3 4 5 6 7 8 9 P H J K W X Y Z a b c d e f g h i j k l m n o p q r s t u v w Q y z BB DB CB AB T x R M S","2":"D B kB lB mB nB","33":"C pB","36":"L EB"},G:{"1":"E uB vB wB xB YB zB 0B 1B 2B 3B 4B 5B 6B 7B","2":"XB qB HB","33":"sB tB"},H:{"2":"8B"},I:{"1":"N DC EC","2":"GB 9B AC BC","33":"G CC HB"},J:{"1":"A","2":"F"},K:{"1":"Q S","2":"A B","33":"C","36":"L EB"},L:{"1":"N"},M:{"1":"M"},N:{"1":"A B"},O:{"1":"FC"},P:{"1":"G GC HC IC JC KC WB L"},Q:{"1":"LC"},R:{"1":"MC"},S:{"1":"NC"}},B:4,C:"CSS Repeating Gradients"};
"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 __()); }; })(); var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; Object.defineProperty(exports, "__esModule", { value: true }); var React = require("react"); var kendo_react_popup_1 = require("@progress/kendo-react-popup"); /** * @hidden */ var ListContainer = /** @class */ (function (_super) { __extends(ListContainer, _super); function ListContainer() { return _super !== null && _super.apply(this, arguments) || this; } ListContainer.prototype.render = function () { var _a = this.props, children = _a.children, width = _a.width, dir = _a.dir, itemsCount = _a.itemsCount, popupSettings = _a.popupSettings; return (React.createElement(kendo_react_popup_1.Popup, __assign({ style: { width: width, direction: dir }, contentKey: itemsCount }, popupSettings), children)); }; return ListContainer; }(React.Component)); exports.default = ListContainer; //# sourceMappingURL=ListContainer.js.map
"use strict"; //# sourceMappingURL=App.vue.js.map
function HandleMngr(url, auth, auth_cb) { this.url = url; var _url = url; var deprecationWarningSent = false; function deprecationWarning() { if (!deprecationWarningSent) { deprecationWarningSent = true; if (!window.console) return; console.log( "DEPRECATION WARNING: '*_async' method names will be removed", "in a future version. Please use the identical methods without", "the'_async' suffix."); } } var _auth = auth ? auth : { 'token' : '', 'user_id' : ''}; var _auth_cb = auth_cb; this.is_readable = function (token, nodeurl, _callback, _errorCallback) { return json_call_ajax("HandleMngr.is_readable", [token, nodeurl], 1, _callback, _errorCallback); }; this.is_readable_async = function (token, nodeurl, _callback, _error_callback) { deprecationWarning(); return json_call_ajax("HandleMngr.is_readable", [token, nodeurl], 1, _callback, _error_callback); }; this.add_read_acl = function (hids, username, _callback, _errorCallback) { return json_call_ajax("HandleMngr.add_read_acl", [hids, username], 0, _callback, _errorCallback); }; this.add_read_acl_async = function (hids, username, _callback, _error_callback) { deprecationWarning(); return json_call_ajax("HandleMngr.add_read_acl", [hids, username], 0, _callback, _error_callback); }; /* * JSON call using jQuery method. */ function json_call_ajax(method, params, numRets, callback, errorCallback) { var deferred = $.Deferred(); if (typeof callback === 'function') { deferred.done(callback); } if (typeof errorCallback === 'function') { deferred.fail(errorCallback); } var rpc = { params : params, method : method, version: "1.1", id: String(Math.random()).slice(2), }; var beforeSend = null; var token = (_auth_cb && typeof _auth_cb === 'function') ? _auth_cb() : (_auth.token ? _auth.token : null); if (token != null) { beforeSend = function (xhr) { xhr.setRequestHeader("Authorization", token); } } var xhr = jQuery.ajax({ url: _url, dataType: "text", type: 'POST', processData: false, data: JSON.stringify(rpc), beforeSend: beforeSend, success: function (data, status, xhr) { var result; try { var resp = JSON.parse(data); result = (numRets === 1 ? resp.result[0] : resp.result); } catch (err) { deferred.reject({ status: 503, error: err, url: _url, resp: data }); return; } deferred.resolve(result); }, error: function (xhr, textStatus, errorThrown) { var error; if (xhr.responseText) { try { var resp = JSON.parse(xhr.responseText); error = resp.error; } catch (err) { // Not JSON error = "Unknown error - " + xhr.responseText; } } else { error = "Unknown Error"; } deferred.reject({ status: 500, error: error }); } }); var promise = deferred.promise(); promise.xhr = xhr; return promise; } }
const path = require('path') module.exports = (env) => { const plugins = []; if (env === 'report') { const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin; plugins.push(new BundleAnalyzerPlugin()) } return { entry: { test: './src/index.js' }, mode: 'production', output: { path: path.join(__dirname, 'lib'), filename: '[name].js', libraryTarget: 'umd', library: '[name]' }, externals: { jquery: 'jQuery' }, resolve:{ alias:{ '@': './alias' } }, module: { rules: [ { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ } ] }, plugins: plugins } }
/* eslint react/require-default-props: 0 */ /* eslint arrow-body-style: 0 */ import cs from 'classnames'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import pageResolver from './page-resolver'; import SizePerPageDropDown from './size-per-page-dropdown'; import PaginationList from './pagination-list'; import Const from './const'; class Pagination extends pageResolver(Component) { constructor(props) { super(props); this.closeDropDown = this.closeDropDown.bind(this); this.toggleDropDown = this.toggleDropDown.bind(this); this.handleChangePage = this.handleChangePage.bind(this); this.handleChangeSizePerPage = this.handleChangeSizePerPage.bind(this); this.state = this.initialState(); } componentWillReceiveProps(nextProps) { const { dataSize, currSizePerPage } = nextProps; if (currSizePerPage !== this.props.currSizePerPage || dataSize !== this.props.dataSize) { const totalPages = this.calculateTotalPage(currSizePerPage, dataSize); const lastPage = this.calculateLastPage(totalPages); this.setState({ totalPages, lastPage }); } } toggleDropDown() { const dropdownOpen = !this.state.dropdownOpen; this.setState(() => { return { dropdownOpen }; }); } closeDropDown() { this.setState(() => { return { dropdownOpen: false }; }); } handleChangeSizePerPage(sizePerPage) { const { currSizePerPage, onSizePerPageChange } = this.props; const selectedSize = typeof sizePerPage === 'string' ? parseInt(sizePerPage, 10) : sizePerPage; let { currPage } = this.props; if (selectedSize !== currSizePerPage) { const newTotalPages = this.calculateTotalPage(selectedSize); const newLastPage = this.calculateLastPage(newTotalPages); if (currPage > newLastPage) currPage = newLastPage; onSizePerPageChange(selectedSize, currPage); } this.closeDropDown(); } handleChangePage(newPage) { let page; const { currPage, pageStartIndex, prePageText, nextPageText, lastPageText, firstPageText, onPageChange // keepSizePerPageState } = this.props; const { lastPage } = this.state; if (newPage === prePageText) { page = this.backToPrevPage(); } else if (newPage === nextPageText) { page = (currPage + 1) > lastPage ? lastPage : currPage + 1; } else if (newPage === lastPageText) { page = lastPage; } else if (newPage === firstPageText) { page = pageStartIndex; } else { page = parseInt(newPage, 10); } // if (keepSizePerPageState) { this.closeDropDown(); } if (page !== currPage) { onPageChange(page); } } render() { const { totalPages, lastPage, dropdownOpen: open } = this.state; const { sizePerPageList, currSizePerPage, hideSizePerPage, hidePageListOnlyOnePage } = this.props; const pages = this.calculatePageStatus(this.calculatePages(totalPages), lastPage); const pageListClass = cs( 'react-bootstrap-table-pagination-list', 'col-md-6 col-xs-6 col-sm-6 col-lg-6', { 'react-bootstrap-table-pagination-list-hidden': (hidePageListOnlyOnePage && totalPages === 1) }); const style = this.props.style ? this.props.style : {}; return ( <div style={ style } className="row react-bootstrap-table-pagination"> <div className="col-md-6 col-xs-6 col-sm-6 col-lg-6"> { sizePerPageList.length > 1 && !hideSizePerPage ? ( <SizePerPageDropDown currSizePerPage={ `${currSizePerPage}` } options={ this.calculateSizePerPageStatus() } onSizePerPageChange={ this.handleChangeSizePerPage } onClick={ this.toggleDropDown } onBlur={ this.closeDropDown } open={ open } /> ) : null } </div> <div className={ pageListClass }> <PaginationList pages={ pages } onPageChange={ this.handleChangePage }/> </div> </div> ); } } Pagination.propTypes = { style: PropTypes.object, dataSize: PropTypes.number.isRequired, sizePerPageList: PropTypes.array.isRequired, currPage: PropTypes.number.isRequired, currSizePerPage: PropTypes.number.isRequired, onPageChange: PropTypes.func.isRequired, onSizePerPageChange: PropTypes.func.isRequired, pageStartIndex: PropTypes.number, paginationSize: PropTypes.number, firstPageText: PropTypes.string, prePageText: PropTypes.string, nextPageText: PropTypes.string, lastPageText: PropTypes.string, nextPageTitle: PropTypes.string, prePageTitle: PropTypes.string, firstPageTitle: PropTypes.string, lastPageTitle: PropTypes.string, withFirstAndLast: PropTypes.bool, alwaysShowAllBtns: PropTypes.bool, hideSizePerPage: PropTypes.bool, hidePageListOnlyOnePage: PropTypes.bool }; Pagination.defaultProps = { pageStartIndex: Const.PAGE_START_INDEX, paginationSize: Const.PAGINATION_SIZE, withFirstAndLast: Const.With_FIRST_AND_LAST, alwaysShowAllBtns: Const.SHOW_ALL_PAGE_BTNS, firstPageText: Const.FIRST_PAGE_TEXT, prePageText: Const.PRE_PAGE_TEXT, nextPageText: Const.NEXT_PAGE_TEXT, lastPageText: Const.LAST_PAGE_TEXT, sizePerPageList: Const.SIZE_PER_PAGE_LIST, nextPageTitle: Const.NEXT_PAGE_TITLE, prePageTitle: Const.PRE_PAGE_TITLE, firstPageTitle: Const.FIRST_PAGE_TITLE, lastPageTitle: Const.LAST_PAGE_TITLE, hideSizePerPage: Const.HIDE_SIZE_PER_PAGE, hidePageListOnlyOnePage: Const.HIDE_PAGE_LIST_ONLY_ONE_PAGE }; export default Pagination;
'use strict'; var {Let, assocIn, dissoc, get, identity, matchKeys, pick, pluck, uniq, updateIn} = require('../underscore_ext'); var {make, mount, compose} = require('./utils'); var {cohortSummary, datasetMetadata, datasetSamplesExamples, datasetFieldN, datasetFieldExamples, fieldCodes, datasetField, datasetFetch, datasetList, datasetSamples, sparseDataExamples, segmentDataExamples} = require('../xenaQuery'); var {servers: {localHub}} = require('../defaultServers'); var {delete: deleteDataset} = require('../xenaAdmin'); var {userServers} = require('./common'); var {ignoredType} = require('../models/dataType'); var Rx = require('../rx'); import {defaultHost} from '../urlParams'; import cohortMetaData from '../cohortMetaData'; import query from './query'; var hubsToAdd = ({hubs, addHub}) => (hubs || []).concat(addHub || []); var hubsToRemove = ({removeHub}) => removeHub || []; var removeHubs = (state, params) => hubsToRemove(params).reduce( (state, hub) => assocIn(state, ['servers', hub, 'user'], false), state); var addHubs = (state, params) => hubsToAdd(params).reduce( (state, hub) => assocIn(state, ['servers', hub, 'user'], true), state); var setHubs = (state, params) => removeHubs(addHubs(state, params), params); var {ajax, of, zip, zipArray} = Rx.Observable; var ajaxGet = url => ajax({url, crossDomain: true, method: 'GET', responseType: 'text'}); var hostToGitURL = host => `${cohortMetaData}/hub_${host.replace(/https?:\/\//, '')}/info.mdown`; var hubMeta = host => ajaxGet(hostToGitURL(host)).catch(() => ajaxGet(`${host}/download/meta/info.mdown`)).map(r => r.response) .catch(() => of({error: 'not available'})); var cohortMeta = cohort => ajaxGet(`${cohortMetaData}/cohort_${cohort}/info.mdown`).map(r => r.response) .catch(() => of({error: 'not available'})); var datasetDescription = dataset => ajaxGet(`${cohortMetaData}/dataset/${dataset}/info.mdown`).map(r => r.response) .catch(() => of({error: 'not available'})); var getMarkDown = url => ajaxGet(url).map(r => r.response) .catch(() => of({error: 'not available'})); // emit url if HEAD request succeeds var head = url => ajax({url, crossDomain: true, method: 'HEAD'}).map(() => url); // Check for dataset download link. If not there, try the link with '.gz' // suffix. If not there, return undefined. var checkDownload = (host, dataset) => { var link = `${host}/download/${dataset}`, gzlink = `${link}.gz`, dl = head(link), gzdl = head(gzlink), nodl = of(undefined); return dl.catch(() => gzdl).catch(() => nodl); }; var noSnippets = () => of(undefined); function fetchMatrixDataSnippets(host, dataset, meta, nProbes = 10, nSamples = 10) { var samplesQ = datasetSamplesExamples(host, dataset, nSamples).share(), fieldQ = datasetFieldExamples(host, dataset, nProbes).share(), codeQ = fieldQ.mergeMap(probes => fieldCodes(host, dataset, probes)), dataQ = zipArray(samplesQ, fieldQ) .mergeMap(([samples, fields]) => datasetFetch(host, dataset, samples, fields)); return zipArray(samplesQ, fieldQ, codeQ, dataQ) .map(([samples, fields, codes, data]) => ({samples, fields, codes, data})) .catch(noSnippets); } var mutationAttrs = ({rows}) => ({ chrom: pluck(rows.position, 'chrom'), chromstart: pluck(rows.position, 'chromstart'), chromend: pluck(rows.position, 'chromend'), ...pick(rows, 'sampleID', 'ref', 'alt', 'effect', 'amino-acid', 'gene') }); var fetchMutationDataSnippets = (host, dataset, nProbes = 10) => sparseDataExamples(host, dataset, nProbes).map(mutationAttrs) .catch(noSnippets); var segmentAttrs = ({rows}) => ({ chrom: pluck(rows.position, 'chrom'), chromstart: pluck(rows.position, 'chromstart'), chromend: pluck(rows.position, 'chromend'), ...pick(rows, 'sampleID', 'value') }); var fetchSegmentedDataSnippets = (host, dataset, nProbes = 10) => segmentDataExamples(host, dataset, nProbes).map(segmentAttrs) .catch(noSnippets); var snippetMethod = ({type = 'genomicMatrix'} = {}) => type === 'clinicalMatrix' ? fetchMatrixDataSnippets : type === 'genomicMatrix' ? fetchMatrixDataSnippets : type === 'mutationVector' ? fetchMutationDataSnippets : type === 'genomicSegment' ? fetchSegmentedDataSnippets : noSnippets; var noProbeCount = () => of(undefined); var probeCountMethod = ({type = 'genomicMatrix'} = {}) => type === 'clinicalMatrix' ? datasetFieldN : type === 'genomicMatrix' ? datasetFieldN : noProbeCount; var datasetMetaAndLinks = (host, dataset) => { var metaQ = datasetMetadata(host, dataset).map(m => m[0]).share(), downloadQ = checkDownload(host, dataset), dataQ = metaQ.mergeMap(meta => snippetMethod(meta)(host, dataset)), probeCountQ = metaQ.mergeMap(meta => probeCountMethod(meta)(host, dataset)), probemapQ = metaQ.mergeMap(meta => get(meta, 'probeMap') ? checkDownload(host, meta.probeMap) : of(undefined)); return zip(metaQ, dataQ, probeCountQ, downloadQ, probemapQ, (meta, data, probeCount, downloadLink, probemapLink) => ({meta, data, probeCount, downloadLink, probemapLink})); }; var spreadsheetControls = { 'init': (state, pathname = '/', params) => setHubs(state, params), 'add-host': (state, host) => assocIn(state, ['servers', host], {user: true}), 'remove-host': (state, host) => updateIn(state, ['servers'], s => dissoc(s, host)), 'enable-host': (state, host, list) => assocIn(state, ['servers', host, list], true), 'disable-host': (state, host, list) => assocIn(state, ['servers', host, list], false), }; var linkedHub = state => state.params.host ? [state.params.host] : []; var getSection = ({dataset, host, cohort, allIdentifiers, allSamples, markdown}) => markdown ? 'markdown' : allSamples ? 'samples' : allIdentifiers ? 'identifiers' : dataset && host ? 'dataset' : host ? 'hub' : cohort ? 'cohort' : 'summary'; var sectionDataMethods = { samples: ({params: {host, dataset}}) => [['samples', host, dataset]], identifiers: ({params: {host, dataset}}) => [['identifiers', host, dataset]], dataset: ({params: {host, dataset}}) => [ ['dataset', host, dataset], ['datasetDescription', dataset]], markdown: ({params: {markdown}}) => [['markdown', markdown]], cohort: ({params: {cohort}, spreadsheet}) => [ ['cohort', cohort], ...Let((servers = userServers(spreadsheet)) => servers.map(server => ['cohortDatasets', cohort, server]))], summary: state => Let((servers = uniq(userServers(state.spreadsheet).concat(linkedHub(state)))) => servers.map(server => ['cohorts', server])), hub: ({params}) => Let(({host} = defaultHost(params)) => [ ['hubMeta', host], ['cohorts', host]]) }; var sectionData = state => state.page !== 'datapages' ? [] : Let((method = sectionDataMethods[getSection(defaultHost(state.params))]) => method ? method(state) : []); var fetchMethods = { samples: (host, dataset) => datasetSamples(host, dataset, null), identifiers: datasetField, dataset: datasetMetaAndLinks, datasetDescription: datasetDescription, markdown: getMarkDown, cohort: cohortMeta, // XXX Note that this will cache lists from hubs that the user has // recently disabled. We only clear cache when the cohort is changed. // OTOH it will fetch any recently enabled hubs. So, the view should // iterate over the userServer list, not this cache. cohortDatasets: (cohort, server) => datasetList(server, [cohort]).catch(() => of([])), cohorts: server => cohortSummary(server, ignoredType).catch(() => of([])), hubMeta: hubMeta }; var cachePolicy = { // cache all hosts cohorts: identity, // cache a single key: the last one updated. // XXX Doesn't work correctly for [host, dataset] paths, as it will accumulate // values until host changes. Should change this so we don't hold on to // multiple probe sets, for example. default: (state, path) => updateIn(state, ['datapages', path[0]], item => pick(item, path[1])) }; var {controller: fetchController, invalidatePath} = query(fetchMethods, sectionData, cachePolicy, 'datapages'); // ['cohorts', localHub] // ['hubMeta', localHub] // ['samples', localHub, *] // ['identifiers', localHub, *] // ['dataset', localHub, *] // ['cohortDatasets', *, localHub] var invalidateLocalHub = Let(({any} = matchKeys) => function (state) { var datapages = get(state, 'datapages', {}); invalidatePath(datapages, ['cohorts', localHub]); invalidatePath(datapages, ['hubMeta', localHub]); invalidatePath(datapages, ['samples', localHub, any]); invalidatePath(datapages, ['identifiers', localHub, any]); invalidatePath(datapages, ['dataset', localHub, any]); invalidatePath(datapages, ['cohortDatasets', any, localHub]); }); function hubChangePost(serverBus, state, newState) { invalidateLocalHub(newState); } var controls = { 'localStatus-post!': hubChangePost, 'localQueue-post!': hubChangePost, 'delete-dataset-post!': (serverBus, state, newState, host, name) => serverBus.next(['dataset-deleted', deleteDataset(host, name)]), }; module.exports = compose( fetchController, mount(make(spreadsheetControls), ['spreadsheet']), make(controls));
import connect from 'STORE/connect' import PageParam from './PageParam' export default connect( state => ({ }), {}, PageParam )
// <Create a chat client> import { ChatClient, ChatThreadClient } from '@azure/communication-chat'; import { AzureCommunicationTokenCredential } from '@azure/communication-common'; let endpointUrl = 'https://<RESOURCE_NAME>.communication.azure.com'; let userAccessToken = '<USER_ACCESS_TOKEN>'; let chatClient = new ChatClient(endpointUrl, new AzureCommunicationTokenCredential(userAccessToken)); console.log('Azure Communication Chat client created!'); // <Start a chat thread> async function createChatThread() { const createChatThreadRequest = { topic: "Calling Application" }; const createChatThreadOptions = { participants: [ { id: { communicationUserId: '<USER_ID>' }, displayName: '<USER_DISPLAY_NAME>' } ] }; const createChatThreadResult = await chatClient.createChatThread( createChatThreadRequest, createChatThreadOptions ); const threadId = createChatThreadResult.chatThread.id; return threadId; } createChatThread().then(async threadId => { console.log(`Thread created:${threadId}`); // <Get a chat thread client> let chatThreadClient = chatClient.getChatThreadClient(threadId); console.log(`Chat Thread client for threadId:${threadId}`); // <List all chat threads> const threads = chatClient.listChatThreads(); for await (const thread of threads) { console.log(`Chat Thread item:${thread.id}`); } // <Receive chat messages from a chat thread> chatClient.startRealtimeNotifications(); chatClient.on("chatMessageReceived", async (e) => { console.log("Notification chatMessageReceived!"); }); // <Send a message to a chat thread> const sendMessageRequest = { content: 'Hello Geeta! Can you share the deck for the conference?' }; let sendMessageOptions = { senderDisplayName: 'Jack', type: 'text' }; const sendChatMessageResult = await chatThreadClient.sendMessage(sendMessageRequest, sendMessageOptions); const messageId = sendChatMessageResult.id; // <LIST MESSAGES IN A CHAT THREAD> const messages = chatThreadClient.listMessages(); for await (const message of messages) { console.log(`Chat Thread message id:${message.id}`); } // <Add a user as a participant to the chat thread> const addParticipantsRequest = { participants: [ { id: { communicationUserId: '<NEW_PARTICIPANT_USER_ID>' }, displayName: 'Jane' } ] }; await chatThreadClient.addParticipants(addParticipantsRequest); // <List users in a chat thread> const participants = chatThreadClient.listParticipants(); for await (const participant of participants) { console.log(`participants in thread:${participant.id.communicationUserId}`); } // <Remove user from a chat thread> await chatThreadClient.removeParticipant({ communicationUserId: '<NEW_PARTICIPANT_USER_ID>' }); const users = chatThreadClient.listParticipants(); for await (const user of users) { console.log(`participants in thread available:${user.id.communicationUserId}`); } });
export const INITIAL = { searchData: '', selected: [], dataset: [ { id: 1, primary: 'Vanilla', accent: 'MobX' }, { id: 2, primary: 'Angular', accent: 'NGXS' }, { id: 3, primary: 'React', accent: 'Redux' }, { id: 4, primary: 'Vue', accent: 'Vuex' }, ], addData: {}, editData: {}, viewData: {}, deleteData: {}, dialogs: { add: false, edit: false, view: false, delete: false, }, }; export const ADD_ITEM = '[crudOperations/basic] ADD_ITEM'; export const EDIT_ITEM = '[crudOperations/basic] EDIT_ITEM'; export const DELETE_ITEM = '[crudOperations/basic] DELETE_ITEM'; export const SET_DATA = '[crudOperations/basic] SET_DATA';
/** * VexFlow - Music Key Management Tests * Copyright Mohit Muthanna 2010 <mohit@muthanna.com> */ const KeyManagerTests = (function () { var KeyManager = { Start: function () { QUnit.module('KeyManager'); test('Valid Notes', VF.Test.KeyManager.works); test('Select Notes', VF.Test.KeyManager.selectNotes); }, works: function () { // expect(1); var manager = new VF.KeyManager('g'); equal(manager.getAccidental('f').accidental, '#'); manager.setKey('a'); equal(manager.getAccidental('c').accidental, '#'); equal(manager.getAccidental('a').accidental, null); equal(manager.getAccidental('f').accidental, '#'); manager.setKey('A'); equal(manager.getAccidental('c').accidental, '#'); equal(manager.getAccidental('a').accidental, null); equal(manager.getAccidental('f').accidental, '#'); }, selectNotes: function () { var manager = new VF.KeyManager('f'); equal(manager.selectNote('bb').note, 'bb'); equal(manager.selectNote('bb').accidental, 'b'); equal(manager.selectNote('g').note, 'g'); equal(manager.selectNote('g').accidental, null); equal(manager.selectNote('b').note, 'b'); equal(manager.selectNote('b').accidental, null); equal(manager.selectNote('a#').note, 'bb'); equal(manager.selectNote('g#').note, 'g#'); // Changes have no effect? equal(manager.selectNote('g#').note, 'g#'); equal(manager.selectNote('bb').note, 'bb'); equal(manager.selectNote('bb').accidental, 'b'); equal(manager.selectNote('g').note, 'g'); equal(manager.selectNote('g').accidental, null); equal(manager.selectNote('b').note, 'b'); equal(manager.selectNote('b').accidental, null); equal(manager.selectNote('a#').note, 'bb'); equal(manager.selectNote('g#').note, 'g#'); // Changes should propagate manager.reset(); equal(manager.selectNote('g#').change, true); equal(manager.selectNote('g#').change, false); equal(manager.selectNote('g').change, true); equal(manager.selectNote('g').change, false); equal(manager.selectNote('g#').change, true); manager.reset(); var note = manager.selectNote('bb'); equal(note.change, false); equal(note.accidental, 'b'); note = manager.selectNote('g'); equal(note.change, false); equal(note.accidental, null); note = manager.selectNote('g#'); equal(note.change, true); equal(note.accidental, '#'); note = manager.selectNote('g'); equal(note.change, true); equal(note.accidental, null); note = manager.selectNote('g'); equal(note.change, false); equal(note.accidental, null); note = manager.selectNote('g#'); equal(note.change, true); equal(note.accidental, '#'); }, }; return KeyManager; })(); VF.Test.KeyManager = KeyManagerTests; export { KeyManagerTests };
import Component from '@ember/component'; import { inject } from '@ember/service'; export default Component.extend({ upload: inject('upload'), classNames: ['file-upload-image-selector'], input: null, inputContainer: null, didInsertElement() { this._super(...arguments); const element = this.get('element'); const input = element.querySelector('.input-file'); this.set( 'inputContainer', element.querySelector('.input-file-inp-container') ); this.set('input', input); this.setInputEvents(); }, resetInput() { const input = this.get('input'); input.value = null; const element = this.get('inputContainer'); element.innerHTML = ''; element.appendChild(input.cloneNode(true)); this.setInputEvents(); }, setInputEvents() { this.get('element') .querySelector('.input-file') .addEventListener('change', (event)=> { this.onChangeInputFile(event); }); }, onChangeInputFile(r) { if (r.target.files && r.target.files && r.target.files.length) { for (let i = 0; i < r.target.files.length; i++) { this.get('upload').addImageToUpload(r.target.files[i]); } } this.resetInput(); }, });
const tape = require('tape'); const { getOptions, buildFetchCb, } = require('../helper.js'); const _ = require('../tools.js'); const Vue = require('vue'); // require('jsdom-global')(); // const { JSDOM } = require('jsdom'); const createApp = Vue.createApp; const SelecticFile = require('../../dist/selectic.common.js'); const Selectic = SelecticFile.default; function buildDom() { return document.createElement('div'); } tape.skip('change props', (subT) => { subT.test('"value"', (sTest) => { sTest.test('should change automatically internalValue', async (t) => { const propOptions = getOptions(10); let hasChanged = false; let SelecticGetValue; const selectic = createApp(Selectic, { options: propOptions, _on: (event) => { if (event ==='change') { hasChanged = true; } }, _getMethods: ({getValue}) => SelecticGetValue = getValue, }); const el = buildDom(); selectic.mount(el); await _.nextVueTick(selectic, _.sleep(0)); t.is(getValue(), 0); t.is(hasChanged, true); t.end(); }); sTest.test('should change internalValue but not hasChanged at start', async (t) => { const propOptions = getOptions(10); let hasChanged = false; const selectic = new Selectic({ propsData: { options: propOptions, params: { allowClearSelection: true, }, $on: (event) => { if (event ==='change') { hasChanged = true; } }, }, }); selectic.value = 5; await _.nextVueTick(selectic, _.sleep(0)); t.is(selectic.getValue(), 5); /* When value is changed during creation the change event should not been triggered */ t.is(hasChanged, false); selectic.value = 2; await _.nextVueTick(selectic, _.sleep(0)); t.is(selectic.getValue(), 2); t.is(hasChanged, true); hasChanged = false; selectic.value = 3; await _.nextVueTick(selectic, _.sleep(0)); t.is(selectic.getValue(), 3); t.is(hasChanged, true); hasChanged = false; selectic.value = null; await _.nextVueTick(selectic, _.sleep(0)); t.is(selectic.getValue(), null); t.is(hasChanged, true); t.end(); }); }); });
function main() { let v2 = "__lookupSetter__"; function v3(v4,v5,v6,v7) { function v8(v9,v10,v11,v12,v13) { 'use strict' function v14(v15,v16,v17,v18) { let v21 = 0; let v22 = v16; } } const v24 = [13.37,13.37,13.37,v8,13.37]; const v26 = parseInt(v24); } for (let v31 = 0; v31 < 100; v31++) { const v32 = v3(v2,Function,13.37); } } %NeverOptimizeFunction(main); main();
let alumnos = [ { id: 1, nombre: "Miguel", cal: 10 }, { id: 2, nombre: "Juan", cal: 5 }, { id: 3, nombre: "Antonio", cal: 3 } ]; let getCalificacion = (id, callback) =>{ let calificacion = alumnos.find((calificaciones) =>{ return calificaciones.id === id; }); if(!calificacion){ callback(`La calificacion con el id ${id} no ha sido encontrada`, null); }else{ callback(null, calificacion); } } getCalificacion(4,(err, calificacion)=>{ if(err) return console.log(err); console.log(calificacion); });
"use strict"; import Reflux from "reflux"; const Cart = { AddToCart: Reflux.createAction("AddToCart"), RemoveFromCart: Reflux.createAction("RemoveFromCart"), ClearCart: Reflux.createAction("ClearCart") }; module.exports = Cart;
var pathlib = require('path') liedbase.controller('BijbelController', function ($sce, $scope, $http, log, dbFactory) { var verseText; var bibleBaseDir = './app/assets/bible/'; var readBibleBook = function(path) { } $scope.grab = function () { require('node-dir').files(bibleBaseDir, function(err, files) { processBook(files, 0); }); } var processBook = function(files, index) { path = files[index] console.log('processing: ' + path) if(path.indexOf('bible') > -1) { var pathparts = path.split(pathlib.sep) var vertaling = pathparts[pathparts.length - 2] var book = pathparts[pathparts.length - 1].substring(0, pathparts[pathparts.length - 1].indexOf('.')) var heading = "" var chapter = "" var data = fs.readFileSync(path, 'utf8'); var lines = data.split(/\r?\n/g) var counter = lines.length; console.log('linecounter: ' + counter); for(var i=0; i<lines.length; i++) { var line = lines[i]; if(line == "") { counter -= 1; console.log('linecounter: ' + counter); continue; } if(line.startsWith("=")) { heading += line.substring(1) + "\n" counter -= 1; console.log('linecounter: ' + counter); continue; } if(line.startsWith("#")) { chapter = line.substring(1) counter -= 1; console.log('linecounter: ' + counter); continue; } lineparts = line.split(/(\d+)(?=[a-zA-Z])/) counter += lineparts.length; console.log('linepartscounter: ' + counter + ': ' + line); for(var p=2; p<lineparts.length; p+=2) { dbFactory.put({ "_id": vertaling + "_" + book + "_" + chapter + "_" + lineparts[p-1], "translation": vertaling, "book": book, "chapter": parseInt(chapter), "verse": parseInt(lineparts[p-1]), "text": lineparts[p], "heading": heading }).then(function (response) { console.log('suc. counter: ' + counter); counter -= 4; if(counter == 0 && index < files.length) { processBook(files, index+1); } }).catch(function (err) { console.log('err. counter: ' + counter); counter -= 4; if(counter == 0 && index < files.length-1) { processBook(files, index+1); } }); heading = "" } } } else { processBook(files, index+1); } } })
/*\ title: $:/plugins/<%- github %>/<%- plugin %>/startup/<%- startupModule.name %>.js type: application/javascript module-type: startup This is an startup module. Please put here a comment about what it does and why. For more info just visit: http://tiddlywiki.com/dev/#StartupMechanism @preserve \*/ /*jslint node: true, browser: true */ /*global $tw: false */ // Export name and synchronous status exports.name = '<%- plugin %>-<%- startupModule.name %>'; /* You MUST export at least one startup order, so uncomment at least one Usually you want to run your module after the startup module but that varies depending on your intentions. choose wisely... */ // exports.before = ["startup"]; exports.after = [ 'startup' ]; // Allowed options are browser, node or both exports.platforms = [ 'browser' ]; // If you are doing asyncrhonous tasks change this to false exports.synchronous = true; /** * @module config-startup */ exports.startup = function () { // Put your startup logic here! console.log( '<%- plugin %> has executed one startup module!!!' ); };
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); class NgerCompilerWeappStyle { async run(config) { } } exports.NgerCompilerWeappStyle = NgerCompilerWeappStyle;
var submitEl = document.querySelector("#submit"); var nameInput = document.querySelector("#name"); var emailInput = document.querySelector("#email"); var submissionResponseEl = document.querySelector("#response"); // Action to be performed on click store in named function function showResponse(event) { // Prevent default action event.preventDefault(); console.log(event); var response = "Thank you for your submission " + nameInput.value + "! We will reach out to you at " + emailInput.value + "."; submissionResponseEl.textContent = response; } // Add listener to submit element submitEl.addEventListener("click", showResponse);
'use strict'; require('../../style/index.css'); require('./index.css'); require('../../checkbox/style/css'); require('../../pagination/style/css');
/* YUI 3.17.0 (build ce55cc9) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('handlebars-compiler', function (Y, NAME) { /*! Handlebars.js - Copyright (C) 2011 Yehuda Katz https://raw.github.com/wycats/handlebars.js/master/LICENSE */ // This file contains code that will be inserted at the beginning of the // handlebars-compiler module. // This is necessary because the Y.Handlebars object is created in the // handlebars-base module, but the native Handlebars code expects to use a local // Handlebars reference. var Handlebars = Y.Handlebars; /* THIS FILE IS GENERATED BY A BUILD SCRIPT - DO NOT EDIT! */ /* Jison generated parser */ var handlebars = (function(){ var parser = {trace: function trace() { }, yy: {}, symbols_: {"error":2,"root":3,"program":4,"EOF":5,"simpleInverse":6,"statements":7,"statement":8,"openInverse":9,"closeBlock":10,"openBlock":11,"mustache":12,"partial":13,"CONTENT":14,"COMMENT":15,"OPEN_BLOCK":16,"inMustache":17,"CLOSE":18,"OPEN_INVERSE":19,"OPEN_ENDBLOCK":20,"path":21,"OPEN":22,"OPEN_UNESCAPED":23,"CLOSE_UNESCAPED":24,"OPEN_PARTIAL":25,"partialName":26,"params":27,"hash":28,"dataName":29,"param":30,"STRING":31,"INTEGER":32,"BOOLEAN":33,"hashSegments":34,"hashSegment":35,"ID":36,"EQUALS":37,"DATA":38,"pathSegments":39,"SEP":40,"$accept":0,"$end":1}, terminals_: {2:"error",5:"EOF",14:"CONTENT",15:"COMMENT",16:"OPEN_BLOCK",18:"CLOSE",19:"OPEN_INVERSE",20:"OPEN_ENDBLOCK",22:"OPEN",23:"OPEN_UNESCAPED",24:"CLOSE_UNESCAPED",25:"OPEN_PARTIAL",31:"STRING",32:"INTEGER",33:"BOOLEAN",36:"ID",37:"EQUALS",38:"DATA",40:"SEP"}, productions_: [0,[3,2],[4,2],[4,3],[4,2],[4,1],[4,1],[4,0],[7,1],[7,2],[8,3],[8,3],[8,1],[8,1],[8,1],[8,1],[11,3],[9,3],[10,3],[12,3],[12,3],[13,3],[13,4],[6,2],[17,3],[17,2],[17,2],[17,1],[17,1],[27,2],[27,1],[30,1],[30,1],[30,1],[30,1],[30,1],[28,1],[34,2],[34,1],[35,3],[35,3],[35,3],[35,3],[35,3],[26,1],[26,1],[26,1],[29,2],[21,1],[39,3],[39,1]], performAction: function anonymous(yytext,yyleng,yylineno,yy,yystate,$$,_$) { var $0 = $$.length - 1; switch (yystate) { case 1: return $$[$0-1]; break; case 2: this.$ = new yy.ProgramNode([], $$[$0]); break; case 3: this.$ = new yy.ProgramNode($$[$0-2], $$[$0]); break; case 4: this.$ = new yy.ProgramNode($$[$0-1], []); break; case 5: this.$ = new yy.ProgramNode($$[$0]); break; case 6: this.$ = new yy.ProgramNode([], []); break; case 7: this.$ = new yy.ProgramNode([]); break; case 8: this.$ = [$$[$0]]; break; case 9: $$[$0-1].push($$[$0]); this.$ = $$[$0-1]; break; case 10: this.$ = new yy.BlockNode($$[$0-2], $$[$0-1].inverse, $$[$0-1], $$[$0]); break; case 11: this.$ = new yy.BlockNode($$[$0-2], $$[$0-1], $$[$0-1].inverse, $$[$0]); break; case 12: this.$ = $$[$0]; break; case 13: this.$ = $$[$0]; break; case 14: this.$ = new yy.ContentNode($$[$0]); break; case 15: this.$ = new yy.CommentNode($$[$0]); break; case 16: this.$ = new yy.MustacheNode($$[$0-1][0], $$[$0-1][1]); break; case 17: this.$ = new yy.MustacheNode($$[$0-1][0], $$[$0-1][1]); break; case 18: this.$ = $$[$0-1]; break; case 19: // Parsing out the '&' escape token at this level saves ~500 bytes after min due to the removal of one parser node. this.$ = new yy.MustacheNode($$[$0-1][0], $$[$0-1][1], $$[$0-2][2] === '&'); break; case 20: this.$ = new yy.MustacheNode($$[$0-1][0], $$[$0-1][1], true); break; case 21: this.$ = new yy.PartialNode($$[$0-1]); break; case 22: this.$ = new yy.PartialNode($$[$0-2], $$[$0-1]); break; case 23: break; case 24: this.$ = [[$$[$0-2]].concat($$[$0-1]), $$[$0]]; break; case 25: this.$ = [[$$[$0-1]].concat($$[$0]), null]; break; case 26: this.$ = [[$$[$0-1]], $$[$0]]; break; case 27: this.$ = [[$$[$0]], null]; break; case 28: this.$ = [[$$[$0]], null]; break; case 29: $$[$0-1].push($$[$0]); this.$ = $$[$0-1]; break; case 30: this.$ = [$$[$0]]; break; case 31: this.$ = $$[$0]; break; case 32: this.$ = new yy.StringNode($$[$0]); break; case 33: this.$ = new yy.IntegerNode($$[$0]); break; case 34: this.$ = new yy.BooleanNode($$[$0]); break; case 35: this.$ = $$[$0]; break; case 36: this.$ = new yy.HashNode($$[$0]); break; case 37: $$[$0-1].push($$[$0]); this.$ = $$[$0-1]; break; case 38: this.$ = [$$[$0]]; break; case 39: this.$ = [$$[$0-2], $$[$0]]; break; case 40: this.$ = [$$[$0-2], new yy.StringNode($$[$0])]; break; case 41: this.$ = [$$[$0-2], new yy.IntegerNode($$[$0])]; break; case 42: this.$ = [$$[$0-2], new yy.BooleanNode($$[$0])]; break; case 43: this.$ = [$$[$0-2], $$[$0]]; break; case 44: this.$ = new yy.PartialNameNode($$[$0]); break; case 45: this.$ = new yy.PartialNameNode(new yy.StringNode($$[$0])); break; case 46: this.$ = new yy.PartialNameNode(new yy.IntegerNode($$[$0])); break; case 47: this.$ = new yy.DataNode($$[$0]); break; case 48: this.$ = new yy.IdNode($$[$0]); break; case 49: $$[$0-2].push({part: $$[$0], separator: $$[$0-1]}); this.$ = $$[$0-2]; break; case 50: this.$ = [{part: $$[$0]}]; break; } }, table: [{3:1,4:2,5:[2,7],6:3,7:4,8:6,9:7,11:8,12:9,13:10,14:[1,11],15:[1,12],16:[1,13],19:[1,5],22:[1,14],23:[1,15],25:[1,16]},{1:[3]},{5:[1,17]},{5:[2,6],7:18,8:6,9:7,11:8,12:9,13:10,14:[1,11],15:[1,12],16:[1,13],19:[1,19],20:[2,6],22:[1,14],23:[1,15],25:[1,16]},{5:[2,5],6:20,8:21,9:7,11:8,12:9,13:10,14:[1,11],15:[1,12],16:[1,13],19:[1,5],20:[2,5],22:[1,14],23:[1,15],25:[1,16]},{17:23,18:[1,22],21:24,29:25,36:[1,28],38:[1,27],39:26},{5:[2,8],14:[2,8],15:[2,8],16:[2,8],19:[2,8],20:[2,8],22:[2,8],23:[2,8],25:[2,8]},{4:29,6:3,7:4,8:6,9:7,11:8,12:9,13:10,14:[1,11],15:[1,12],16:[1,13],19:[1,5],20:[2,7],22:[1,14],23:[1,15],25:[1,16]},{4:30,6:3,7:4,8:6,9:7,11:8,12:9,13:10,14:[1,11],15:[1,12],16:[1,13],19:[1,5],20:[2,7],22:[1,14],23:[1,15],25:[1,16]},{5:[2,12],14:[2,12],15:[2,12],16:[2,12],19:[2,12],20:[2,12],22:[2,12],23:[2,12],25:[2,12]},{5:[2,13],14:[2,13],15:[2,13],16:[2,13],19:[2,13],20:[2,13],22:[2,13],23:[2,13],25:[2,13]},{5:[2,14],14:[2,14],15:[2,14],16:[2,14],19:[2,14],20:[2,14],22:[2,14],23:[2,14],25:[2,14]},{5:[2,15],14:[2,15],15:[2,15],16:[2,15],19:[2,15],20:[2,15],22:[2,15],23:[2,15],25:[2,15]},{17:31,21:24,29:25,36:[1,28],38:[1,27],39:26},{17:32,21:24,29:25,36:[1,28],38:[1,27],39:26},{17:33,21:24,29:25,36:[1,28],38:[1,27],39:26},{21:35,26:34,31:[1,36],32:[1,37],36:[1,28],39:26},{1:[2,1]},{5:[2,2],8:21,9:7,11:8,12:9,13:10,14:[1,11],15:[1,12],16:[1,13],19:[1,19],20:[2,2],22:[1,14],23:[1,15],25:[1,16]},{17:23,21:24,29:25,36:[1,28],38:[1,27],39:26},{5:[2,4],7:38,8:6,9:7,11:8,12:9,13:10,14:[1,11],15:[1,12],16:[1,13],19:[1,19],20:[2,4],22:[1,14],23:[1,15],25:[1,16]},{5:[2,9],14:[2,9],15:[2,9],16:[2,9],19:[2,9],20:[2,9],22:[2,9],23:[2,9],25:[2,9]},{5:[2,23],14:[2,23],15:[2,23],16:[2,23],19:[2,23],20:[2,23],22:[2,23],23:[2,23],25:[2,23]},{18:[1,39]},{18:[2,27],21:44,24:[2,27],27:40,28:41,29:48,30:42,31:[1,45],32:[1,46],33:[1,47],34:43,35:49,36:[1,50],38:[1,27],39:26},{18:[2,28],24:[2,28]},{18:[2,48],24:[2,48],31:[2,48],32:[2,48],33:[2,48],36:[2,48],38:[2,48],40:[1,51]},{21:52,36:[1,28],39:26},{18:[2,50],24:[2,50],31:[2,50],32:[2,50],33:[2,50],36:[2,50],38:[2,50],40:[2,50]},{10:53,20:[1,54]},{10:55,20:[1,54]},{18:[1,56]},{18:[1,57]},{24:[1,58]},{18:[1,59],21:60,36:[1,28],39:26},{18:[2,44],36:[2,44]},{18:[2,45],36:[2,45]},{18:[2,46],36:[2,46]},{5:[2,3],8:21,9:7,11:8,12:9,13:10,14:[1,11],15:[1,12],16:[1,13],19:[1,19],20:[2,3],22:[1,14],23:[1,15],25:[1,16]},{14:[2,17],15:[2,17],16:[2,17],19:[2,17],20:[2,17],22:[2,17],23:[2,17],25:[2,17]},{18:[2,25],21:44,24:[2,25],28:61,29:48,30:62,31:[1,45],32:[1,46],33:[1,47],34:43,35:49,36:[1,50],38:[1,27],39:26},{18:[2,26],24:[2,26]},{18:[2,30],24:[2,30],31:[2,30],32:[2,30],33:[2,30],36:[2,30],38:[2,30]},{18:[2,36],24:[2,36],35:63,36:[1,64]},{18:[2,31],24:[2,31],31:[2,31],32:[2,31],33:[2,31],36:[2,31],38:[2,31]},{18:[2,32],24:[2,32],31:[2,32],32:[2,32],33:[2,32],36:[2,32],38:[2,32]},{18:[2,33],24:[2,33],31:[2,33],32:[2,33],33:[2,33],36:[2,33],38:[2,33]},{18:[2,34],24:[2,34],31:[2,34],32:[2,34],33:[2,34],36:[2,34],38:[2,34]},{18:[2,35],24:[2,35],31:[2,35],32:[2,35],33:[2,35],36:[2,35],38:[2,35]},{18:[2,38],24:[2,38],36:[2,38]},{18:[2,50],24:[2,50],31:[2,50],32:[2,50],33:[2,50],36:[2,50],37:[1,65],38:[2,50],40:[2,50]},{36:[1,66]},{18:[2,47],24:[2,47],31:[2,47],32:[2,47],33:[2,47],36:[2,47],38:[2,47]},{5:[2,10],14:[2,10],15:[2,10],16:[2,10],19:[2,10],20:[2,10],22:[2,10],23:[2,10],25:[2,10]},{21:67,36:[1,28],39:26},{5:[2,11],14:[2,11],15:[2,11],16:[2,11],19:[2,11],20:[2,11],22:[2,11],23:[2,11],25:[2,11]},{14:[2,16],15:[2,16],16:[2,16],19:[2,16],20:[2,16],22:[2,16],23:[2,16],25:[2,16]},{5:[2,19],14:[2,19],15:[2,19],16:[2,19],19:[2,19],20:[2,19],22:[2,19],23:[2,19],25:[2,19]},{5:[2,20],14:[2,20],15:[2,20],16:[2,20],19:[2,20],20:[2,20],22:[2,20],23:[2,20],25:[2,20]},{5:[2,21],14:[2,21],15:[2,21],16:[2,21],19:[2,21],20:[2,21],22:[2,21],23:[2,21],25:[2,21]},{18:[1,68]},{18:[2,24],24:[2,24]},{18:[2,29],24:[2,29],31:[2,29],32:[2,29],33:[2,29],36:[2,29],38:[2,29]},{18:[2,37],24:[2,37],36:[2,37]},{37:[1,65]},{21:69,29:73,31:[1,70],32:[1,71],33:[1,72],36:[1,28],38:[1,27],39:26},{18:[2,49],24:[2,49],31:[2,49],32:[2,49],33:[2,49],36:[2,49],38:[2,49],40:[2,49]},{18:[1,74]},{5:[2,22],14:[2,22],15:[2,22],16:[2,22],19:[2,22],20:[2,22],22:[2,22],23:[2,22],25:[2,22]},{18:[2,39],24:[2,39],36:[2,39]},{18:[2,40],24:[2,40],36:[2,40]},{18:[2,41],24:[2,41],36:[2,41]},{18:[2,42],24:[2,42],36:[2,42]},{18:[2,43],24:[2,43],36:[2,43]},{5:[2,18],14:[2,18],15:[2,18],16:[2,18],19:[2,18],20:[2,18],22:[2,18],23:[2,18],25:[2,18]}], defaultActions: {17:[2,1]}, parseError: function parseError(str, hash) { throw new Error(str); }, parse: function parse(input) { var self = this, stack = [0], vstack = [null], lstack = [], table = this.table, yytext = "", yylineno = 0, yyleng = 0, recovering = 0, TERROR = 2, EOF = 1; this.lexer.setInput(input); this.lexer.yy = this.yy; this.yy.lexer = this.lexer; this.yy.parser = this; if (typeof this.lexer.yylloc == "undefined") this.lexer.yylloc = {}; var yyloc = this.lexer.yylloc; lstack.push(yyloc); var ranges = this.lexer.options && this.lexer.options.ranges; if (typeof this.yy.parseError === "function") this.parseError = this.yy.parseError; function popStack(n) { stack.length = stack.length - 2 * n; vstack.length = vstack.length - n; lstack.length = lstack.length - n; } function lex() { var token; token = self.lexer.lex() || 1; if (typeof token !== "number") { token = self.symbols_[token] || token; } return token; } var symbol, preErrorSymbol, state, action, a, r, yyval = {}, p, len, newState, expected; while (true) { state = stack[stack.length - 1]; if (this.defaultActions[state]) { action = this.defaultActions[state]; } else { if (symbol === null || typeof symbol == "undefined") { symbol = lex(); } action = table[state] && table[state][symbol]; } if (typeof action === "undefined" || !action.length || !action[0]) { var errStr = ""; if (!recovering) { expected = []; for (p in table[state]) if (this.terminals_[p] && p > 2) { expected.push("'" + this.terminals_[p] + "'"); } if (this.lexer.showPosition) { errStr = "Parse error on line " + (yylineno + 1) + ":\n" + this.lexer.showPosition() + "\nExpecting " + expected.join(", ") + ", got '" + (this.terminals_[symbol] || symbol) + "'"; } else { errStr = "Parse error on line " + (yylineno + 1) + ": Unexpected " + (symbol == 1?"end of input":"'" + (this.terminals_[symbol] || symbol) + "'"); } this.parseError(errStr, {text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected}); } } if (action[0] instanceof Array && action.length > 1) { throw new Error("Parse Error: multiple actions possible at state: " + state + ", token: " + symbol); } switch (action[0]) { case 1: stack.push(symbol); vstack.push(this.lexer.yytext); lstack.push(this.lexer.yylloc); stack.push(action[1]); symbol = null; if (!preErrorSymbol) { yyleng = this.lexer.yyleng; yytext = this.lexer.yytext; yylineno = this.lexer.yylineno; yyloc = this.lexer.yylloc; if (recovering > 0) recovering--; } else { symbol = preErrorSymbol; preErrorSymbol = null; } break; case 2: len = this.productions_[action[1]][1]; yyval.$ = vstack[vstack.length - len]; yyval._$ = {first_line: lstack[lstack.length - (len || 1)].first_line, last_line: lstack[lstack.length - 1].last_line, first_column: lstack[lstack.length - (len || 1)].first_column, last_column: lstack[lstack.length - 1].last_column}; if (ranges) { yyval._$.range = [lstack[lstack.length - (len || 1)].range[0], lstack[lstack.length - 1].range[1]]; } r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack); if (typeof r !== "undefined") { return r; } if (len) { stack = stack.slice(0, -1 * len * 2); vstack = vstack.slice(0, -1 * len); lstack = lstack.slice(0, -1 * len); } stack.push(this.productions_[action[1]][0]); vstack.push(yyval.$); lstack.push(yyval._$); newState = table[stack[stack.length - 2]][stack[stack.length - 1]]; stack.push(newState); break; case 3: return true; } } return true; } }; /* Jison generated lexer */ var lexer = (function(){ var lexer = ({EOF:1, parseError:function parseError(str, hash) { if (this.yy.parser) { this.yy.parser.parseError(str, hash); } else { throw new Error(str); } }, setInput:function (input) { this._input = input; this._more = this._less = this.done = false; this.yylineno = this.yyleng = 0; this.yytext = this.matched = this.match = ''; this.conditionStack = ['INITIAL']; this.yylloc = {first_line:1,first_column:0,last_line:1,last_column:0}; if (this.options.ranges) this.yylloc.range = [0,0]; this.offset = 0; return this; }, input:function () { var ch = this._input[0]; this.yytext += ch; this.yyleng++; this.offset++; this.match += ch; this.matched += ch; var lines = ch.match(/(?:\r\n?|\n).*/g); if (lines) { this.yylineno++; this.yylloc.last_line++; } else { this.yylloc.last_column++; } if (this.options.ranges) this.yylloc.range[1]++; this._input = this._input.slice(1); return ch; }, unput:function (ch) { var len = ch.length; var lines = ch.split(/(?:\r\n?|\n)/g); this._input = ch + this._input; this.yytext = this.yytext.substr(0, this.yytext.length-len-1); //this.yyleng -= len; this.offset -= len; var oldLines = this.match.split(/(?:\r\n?|\n)/g); this.match = this.match.substr(0, this.match.length-1); this.matched = this.matched.substr(0, this.matched.length-1); if (lines.length-1) this.yylineno -= lines.length-1; var r = this.yylloc.range; this.yylloc = {first_line: this.yylloc.first_line, last_line: this.yylineno+1, first_column: this.yylloc.first_column, last_column: lines ? (lines.length === oldLines.length ? this.yylloc.first_column : 0) + oldLines[oldLines.length - lines.length].length - lines[0].length: this.yylloc.first_column - len }; if (this.options.ranges) { this.yylloc.range = [r[0], r[0] + this.yyleng - len]; } return this; }, more:function () { this._more = true; return this; }, less:function (n) { this.unput(this.match.slice(n)); }, pastInput:function () { var past = this.matched.substr(0, this.matched.length - this.match.length); return (past.length > 20 ? '...':'') + past.substr(-20).replace(/\n/g, ""); }, upcomingInput:function () { var next = this.match; if (next.length < 20) { next += this._input.substr(0, 20-next.length); } return (next.substr(0,20)+(next.length > 20 ? '...':'')).replace(/\n/g, ""); }, showPosition:function () { var pre = this.pastInput(); var c = new Array(pre.length + 1).join("-"); return pre + this.upcomingInput() + "\n" + c+"^"; }, next:function () { if (this.done) { return this.EOF; } if (!this._input) this.done = true; var token, match, tempMatch, index, col, lines; if (!this._more) { this.yytext = ''; this.match = ''; } var rules = this._currentRules(); for (var i=0;i < rules.length; i++) { tempMatch = this._input.match(this.rules[rules[i]]); if (tempMatch && (!match || tempMatch[0].length > match[0].length)) { match = tempMatch; index = i; if (!this.options.flex) break; } } if (match) { lines = match[0].match(/(?:\r\n?|\n).*/g); if (lines) this.yylineno += lines.length; this.yylloc = {first_line: this.yylloc.last_line, last_line: this.yylineno+1, first_column: this.yylloc.last_column, last_column: lines ? lines[lines.length-1].length-lines[lines.length-1].match(/\r?\n?/)[0].length : this.yylloc.last_column + match[0].length}; this.yytext += match[0]; this.match += match[0]; this.matches = match; this.yyleng = this.yytext.length; if (this.options.ranges) { this.yylloc.range = [this.offset, this.offset += this.yyleng]; } this._more = false; this._input = this._input.slice(match[0].length); this.matched += match[0]; token = this.performAction.call(this, this.yy, this, rules[index],this.conditionStack[this.conditionStack.length-1]); if (this.done && this._input) this.done = false; if (token) return token; else return; } if (this._input === "") { return this.EOF; } else { return this.parseError('Lexical error on line '+(this.yylineno+1)+'. Unrecognized text.\n'+this.showPosition(), {text: "", token: null, line: this.yylineno}); } }, lex:function lex() { var r = this.next(); if (typeof r !== 'undefined') { return r; } else { return this.lex(); } }, begin:function begin(condition) { this.conditionStack.push(condition); }, popState:function popState() { return this.conditionStack.pop(); }, _currentRules:function _currentRules() { return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules; }, topState:function () { return this.conditionStack[this.conditionStack.length-2]; }, pushState:function begin(condition) { this.begin(condition); }}); lexer.options = {}; lexer.performAction = function anonymous(yy,yy_,$avoiding_name_collisions,YY_START) { var YYSTATE=YY_START switch($avoiding_name_collisions) { case 0: yy_.yytext = "\\"; return 14; break; case 1: if(yy_.yytext.slice(-1) !== "\\") this.begin("mu"); if(yy_.yytext.slice(-1) === "\\") yy_.yytext = yy_.yytext.substr(0,yy_.yyleng-1), this.begin("emu"); if(yy_.yytext) return 14; break; case 2: return 14; break; case 3: if(yy_.yytext.slice(-1) !== "\\") this.popState(); if(yy_.yytext.slice(-1) === "\\") yy_.yytext = yy_.yytext.substr(0,yy_.yyleng-1); return 14; break; case 4: yy_.yytext = yy_.yytext.substr(0, yy_.yyleng-4); this.popState(); return 15; break; case 5: return 25; break; case 6: return 16; break; case 7: return 20; break; case 8: return 19; break; case 9: return 19; break; case 10: return 23; break; case 11: return 22; break; case 12: this.popState(); this.begin('com'); break; case 13: yy_.yytext = yy_.yytext.substr(3,yy_.yyleng-5); this.popState(); return 15; break; case 14: return 22; break; case 15: return 37; break; case 16: return 36; break; case 17: return 36; break; case 18: return 40; break; case 19: /*ignore whitespace*/ break; case 20: this.popState(); return 24; break; case 21: this.popState(); return 18; break; case 22: yy_.yytext = yy_.yytext.substr(1,yy_.yyleng-2).replace(/\\"/g,'"'); return 31; break; case 23: yy_.yytext = yy_.yytext.substr(1,yy_.yyleng-2).replace(/\\'/g,"'"); return 31; break; case 24: return 38; break; case 25: return 33; break; case 26: return 33; break; case 27: return 32; break; case 28: return 36; break; case 29: yy_.yytext = yy_.yytext.substr(1, yy_.yyleng-2); return 36; break; case 30: return 'INVALID'; break; case 31: return 5; break; } }; lexer.rules = [/^(?:\\\\(?=(\{\{)))/,/^(?:[^\x00]*?(?=(\{\{)))/,/^(?:[^\x00]+)/,/^(?:[^\x00]{2,}?(?=(\{\{|$)))/,/^(?:[\s\S]*?--\}\})/,/^(?:\{\{>)/,/^(?:\{\{#)/,/^(?:\{\{\/)/,/^(?:\{\{\^)/,/^(?:\{\{\s*else\b)/,/^(?:\{\{\{)/,/^(?:\{\{&)/,/^(?:\{\{!--)/,/^(?:\{\{![\s\S]*?\}\})/,/^(?:\{\{)/,/^(?:=)/,/^(?:\.(?=[}\/ ]))/,/^(?:\.\.)/,/^(?:[\/.])/,/^(?:\s+)/,/^(?:\}\}\})/,/^(?:\}\})/,/^(?:"(\\["]|[^"])*")/,/^(?:'(\\[']|[^'])*')/,/^(?:@)/,/^(?:true(?=[}\s]))/,/^(?:false(?=[}\s]))/,/^(?:-?[0-9]+(?=[}\s]))/,/^(?:[^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=[=}\s\/.]))/,/^(?:\[[^\]]*\])/,/^(?:.)/,/^(?:$)/]; lexer.conditions = {"mu":{"rules":[5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31],"inclusive":false},"emu":{"rules":[3],"inclusive":false},"com":{"rules":[4],"inclusive":false},"INITIAL":{"rules":[0,1,2,31],"inclusive":true}}; return lexer;})() parser.lexer = lexer; function Parser () { this.yy = {}; }Parser.prototype = parser;parser.Parser = Parser; return new Parser; })(); /* THIS FILE IS GENERATED BY A BUILD SCRIPT - DO NOT EDIT! */ Handlebars.Parser = handlebars; Handlebars.parse = function(input) { // Just return if an already-compile AST was passed in. if(input.constructor === Handlebars.AST.ProgramNode) { return input; } Handlebars.Parser.yy = Handlebars.AST; return Handlebars.Parser.parse(input); }; /* THIS FILE IS GENERATED BY A BUILD SCRIPT - DO NOT EDIT! */ Handlebars.AST = {}; Handlebars.AST.ProgramNode = function(statements, inverse) { this.type = "program"; this.statements = statements; if(inverse) { this.inverse = new Handlebars.AST.ProgramNode(inverse); } }; Handlebars.AST.MustacheNode = function(rawParams, hash, unescaped) { this.type = "mustache"; this.escaped = !unescaped; this.hash = hash; var id = this.id = rawParams[0]; var params = this.params = rawParams.slice(1); // a mustache is an eligible helper if: // * its id is simple (a single part, not `this` or `..`) var eligibleHelper = this.eligibleHelper = id.isSimple; // a mustache is definitely a helper if: // * it is an eligible helper, and // * it has at least one parameter or hash segment this.isHelper = eligibleHelper && (params.length || hash); // if a mustache is an eligible helper but not a definite // helper, it is ambiguous, and will be resolved in a later // pass or at runtime. }; Handlebars.AST.PartialNode = function(partialName, context) { this.type = "partial"; this.partialName = partialName; this.context = context; }; Handlebars.AST.BlockNode = function(mustache, program, inverse, close) { var verifyMatch = function(open, close) { if(open.original !== close.original) { throw new Handlebars.Exception(open.original + " doesn't match " + close.original); } }; verifyMatch(mustache.id, close); this.type = "block"; this.mustache = mustache; this.program = program; this.inverse = inverse; if (this.inverse && !this.program) { this.isInverse = true; } }; Handlebars.AST.ContentNode = function(string) { this.type = "content"; this.string = string; }; Handlebars.AST.HashNode = function(pairs) { this.type = "hash"; this.pairs = pairs; }; Handlebars.AST.IdNode = function(parts) { this.type = "ID"; var original = "", dig = [], depth = 0; for(var i=0,l=parts.length; i<l; i++) { var part = parts[i].part; original += (parts[i].separator || '') + part; if (part === ".." || part === "." || part === "this") { if (dig.length > 0) { throw new Handlebars.Exception("Invalid path: " + original); } else if (part === "..") { depth++; } else { this.isScoped = true; } } else { dig.push(part); } } this.original = original; this.parts = dig; this.string = dig.join('.'); this.depth = depth; // an ID is simple if it only has one part, and that part is not // `..` or `this`. this.isSimple = parts.length === 1 && !this.isScoped && depth === 0; this.stringModeValue = this.string; }; Handlebars.AST.PartialNameNode = function(name) { this.type = "PARTIAL_NAME"; this.name = name.original; }; Handlebars.AST.DataNode = function(id) { this.type = "DATA"; this.id = id; }; Handlebars.AST.StringNode = function(string) { this.type = "STRING"; this.original = this.string = this.stringModeValue = string; }; Handlebars.AST.IntegerNode = function(integer) { this.type = "INTEGER"; this.original = this.integer = integer; this.stringModeValue = Number(integer); }; Handlebars.AST.BooleanNode = function(bool) { this.type = "BOOLEAN"; this.bool = bool; this.stringModeValue = bool === "true"; }; Handlebars.AST.CommentNode = function(comment) { this.type = "comment"; this.comment = comment; }; /* THIS FILE IS GENERATED BY A BUILD SCRIPT - DO NOT EDIT! */ /*jshint eqnull:true*/ var Compiler = Handlebars.Compiler = function() {}; var JavaScriptCompiler = Handlebars.JavaScriptCompiler = function() {}; // the foundHelper register will disambiguate helper lookup from finding a // function in a context. This is necessary for mustache compatibility, which // requires that context functions in blocks are evaluated by blockHelperMissing, // and then proceed as if the resulting value was provided to blockHelperMissing. Compiler.prototype = { compiler: Compiler, disassemble: function() { var opcodes = this.opcodes, opcode, out = [], params, param; for (var i=0, l=opcodes.length; i<l; i++) { opcode = opcodes[i]; if (opcode.opcode === 'DECLARE') { out.push("DECLARE " + opcode.name + "=" + opcode.value); } else { params = []; for (var j=0; j<opcode.args.length; j++) { param = opcode.args[j]; if (typeof param === "string") { param = "\"" + param.replace("\n", "\\n") + "\""; } params.push(param); } out.push(opcode.opcode + " " + params.join(" ")); } } return out.join("\n"); }, equals: function(other) { var len = this.opcodes.length; if (other.opcodes.length !== len) { return false; } for (var i = 0; i < len; i++) { var opcode = this.opcodes[i], otherOpcode = other.opcodes[i]; if (opcode.opcode !== otherOpcode.opcode || opcode.args.length !== otherOpcode.args.length) { return false; } for (var j = 0; j < opcode.args.length; j++) { if (opcode.args[j] !== otherOpcode.args[j]) { return false; } } } len = this.children.length; if (other.children.length !== len) { return false; } for (i = 0; i < len; i++) { if (!this.children[i].equals(other.children[i])) { return false; } } return true; }, guid: 0, compile: function(program, options) { this.children = []; this.depths = {list: []}; this.options = options; // These changes will propagate to the other compiler components var knownHelpers = this.options.knownHelpers; this.options.knownHelpers = { 'helperMissing': true, 'blockHelperMissing': true, 'each': true, 'if': true, 'unless': true, 'with': true, 'log': true }; if (knownHelpers) { for (var name in knownHelpers) { this.options.knownHelpers[name] = knownHelpers[name]; } } return this.program(program); }, accept: function(node) { return this[node.type](node); }, program: function(program) { var statements = program.statements, statement; this.opcodes = []; for(var i=0, l=statements.length; i<l; i++) { statement = statements[i]; this[statement.type](statement); } this.isSimple = l === 1; this.depths.list = this.depths.list.sort(function(a, b) { return a - b; }); return this; }, compileProgram: function(program) { var result = new this.compiler().compile(program, this.options); var guid = this.guid++, depth; this.usePartial = this.usePartial || result.usePartial; this.children[guid] = result; for(var i=0, l=result.depths.list.length; i<l; i++) { depth = result.depths.list[i]; if(depth < 2) { continue; } else { this.addDepth(depth - 1); } } return guid; }, block: function(block) { var mustache = block.mustache, program = block.program, inverse = block.inverse; if (program) { program = this.compileProgram(program); } if (inverse) { inverse = this.compileProgram(inverse); } var type = this.classifyMustache(mustache); if (type === "helper") { this.helperMustache(mustache, program, inverse); } else if (type === "simple") { this.simpleMustache(mustache); // now that the simple mustache is resolved, we need to // evaluate it by executing `blockHelperMissing` this.opcode('pushProgram', program); this.opcode('pushProgram', inverse); this.opcode('emptyHash'); this.opcode('blockValue'); } else { this.ambiguousMustache(mustache, program, inverse); // now that the simple mustache is resolved, we need to // evaluate it by executing `blockHelperMissing` this.opcode('pushProgram', program); this.opcode('pushProgram', inverse); this.opcode('emptyHash'); this.opcode('ambiguousBlockValue'); } this.opcode('append'); }, hash: function(hash) { var pairs = hash.pairs, pair, val; this.opcode('pushHash'); for(var i=0, l=pairs.length; i<l; i++) { pair = pairs[i]; val = pair[1]; if (this.options.stringParams) { if(val.depth) { this.addDepth(val.depth); } this.opcode('getContext', val.depth || 0); this.opcode('pushStringParam', val.stringModeValue, val.type); } else { this.accept(val); } this.opcode('assignToHash', pair[0]); } this.opcode('popHash'); }, partial: function(partial) { var partialName = partial.partialName; this.usePartial = true; if(partial.context) { this.ID(partial.context); } else { this.opcode('push', 'depth0'); } this.opcode('invokePartial', partialName.name); this.opcode('append'); }, content: function(content) { this.opcode('appendContent', content.string); }, mustache: function(mustache) { var options = this.options; var type = this.classifyMustache(mustache); if (type === "simple") { this.simpleMustache(mustache); } else if (type === "helper") { this.helperMustache(mustache); } else { this.ambiguousMustache(mustache); } if(mustache.escaped && !options.noEscape) { this.opcode('appendEscaped'); } else { this.opcode('append'); } }, ambiguousMustache: function(mustache, program, inverse) { var id = mustache.id, name = id.parts[0], isBlock = program != null || inverse != null; this.opcode('getContext', id.depth); this.opcode('pushProgram', program); this.opcode('pushProgram', inverse); this.opcode('invokeAmbiguous', name, isBlock); }, simpleMustache: function(mustache) { var id = mustache.id; if (id.type === 'DATA') { this.DATA(id); } else if (id.parts.length) { this.ID(id); } else { // Simplified ID for `this` this.addDepth(id.depth); this.opcode('getContext', id.depth); this.opcode('pushContext'); } this.opcode('resolvePossibleLambda'); }, helperMustache: function(mustache, program, inverse) { var params = this.setupFullMustacheParams(mustache, program, inverse), name = mustache.id.parts[0]; if (this.options.knownHelpers[name]) { this.opcode('invokeKnownHelper', params.length, name); } else if (this.options.knownHelpersOnly) { throw new Error("You specified knownHelpersOnly, but used the unknown helper " + name); } else { this.opcode('invokeHelper', params.length, name); } }, ID: function(id) { this.addDepth(id.depth); this.opcode('getContext', id.depth); var name = id.parts[0]; if (!name) { this.opcode('pushContext'); } else { this.opcode('lookupOnContext', id.parts[0]); } for(var i=1, l=id.parts.length; i<l; i++) { this.opcode('lookup', id.parts[i]); } }, DATA: function(data) { this.options.data = true; if (data.id.isScoped || data.id.depth) { throw new Handlebars.Exception('Scoped data references are not supported: ' + data.original); } this.opcode('lookupData'); var parts = data.id.parts; for(var i=0, l=parts.length; i<l; i++) { this.opcode('lookup', parts[i]); } }, STRING: function(string) { this.opcode('pushString', string.string); }, INTEGER: function(integer) { this.opcode('pushLiteral', integer.integer); }, BOOLEAN: function(bool) { this.opcode('pushLiteral', bool.bool); }, comment: function() {}, // HELPERS opcode: function(name) { this.opcodes.push({ opcode: name, args: [].slice.call(arguments, 1) }); }, declare: function(name, value) { this.opcodes.push({ opcode: 'DECLARE', name: name, value: value }); }, addDepth: function(depth) { if(isNaN(depth)) { throw new Error("EWOT"); } if(depth === 0) { return; } if(!this.depths[depth]) { this.depths[depth] = true; this.depths.list.push(depth); } }, classifyMustache: function(mustache) { var isHelper = mustache.isHelper; var isEligible = mustache.eligibleHelper; var options = this.options; // if ambiguous, we can possibly resolve the ambiguity now if (isEligible && !isHelper) { var name = mustache.id.parts[0]; if (options.knownHelpers[name]) { isHelper = true; } else if (options.knownHelpersOnly) { isEligible = false; } } if (isHelper) { return "helper"; } else if (isEligible) { return "ambiguous"; } else { return "simple"; } }, pushParams: function(params) { var i = params.length, param; while(i--) { param = params[i]; if(this.options.stringParams) { if(param.depth) { this.addDepth(param.depth); } this.opcode('getContext', param.depth || 0); this.opcode('pushStringParam', param.stringModeValue, param.type); } else { this[param.type](param); } } }, setupMustacheParams: function(mustache) { var params = mustache.params; this.pushParams(params); if(mustache.hash) { this.hash(mustache.hash); } else { this.opcode('emptyHash'); } return params; }, // this will replace setupMustacheParams when we're done setupFullMustacheParams: function(mustache, program, inverse) { var params = mustache.params; this.pushParams(params); this.opcode('pushProgram', program); this.opcode('pushProgram', inverse); if(mustache.hash) { this.hash(mustache.hash); } else { this.opcode('emptyHash'); } return params; } }; var Literal = function(value) { this.value = value; }; JavaScriptCompiler.prototype = { // PUBLIC API: You can override these methods in a subclass to provide // alternative compiled forms for name lookup and buffering semantics nameLookup: function(parent, name /* , type*/) { if (/^[0-9]+$/.test(name)) { return parent + "[" + name + "]"; } else if (JavaScriptCompiler.isValidJavaScriptVariableName(name)) { return parent + "." + name; } else { return parent + "['" + name + "']"; } }, appendToBuffer: function(string) { if (this.environment.isSimple) { return "return " + string + ";"; } else { return { appendToBuffer: true, content: string, toString: function() { return "buffer += " + string + ";"; } }; } }, initializeBuffer: function() { return this.quotedString(""); }, namespace: "Handlebars", // END PUBLIC API compile: function(environment, options, context, asObject) { this.environment = environment; this.options = options || {}; Handlebars.log(Handlebars.logger.DEBUG, this.environment.disassemble() + "\n\n"); this.name = this.environment.name; this.isChild = !!context; this.context = context || { programs: [], environments: [], aliases: { } }; this.preamble(); this.stackSlot = 0; this.stackVars = []; this.registers = { list: [] }; this.compileStack = []; this.inlineStack = []; this.compileChildren(environment, options); var opcodes = environment.opcodes, opcode; this.i = 0; for(l=opcodes.length; this.i<l; this.i++) { opcode = opcodes[this.i]; if(opcode.opcode === 'DECLARE') { this[opcode.name] = opcode.value; } else { this[opcode.opcode].apply(this, opcode.args); } } return this.createFunctionContext(asObject); }, nextOpcode: function() { var opcodes = this.environment.opcodes; return opcodes[this.i + 1]; }, eat: function() { this.i = this.i + 1; }, preamble: function() { var out = []; if (!this.isChild) { var namespace = this.namespace; var copies = "helpers = this.merge(helpers, " + namespace + ".helpers);"; if (this.environment.usePartial) { copies = copies + " partials = this.merge(partials, " + namespace + ".partials);"; } if (this.options.data) { copies = copies + " data = data || {};"; } out.push(copies); } else { out.push(''); } if (!this.environment.isSimple) { out.push(", buffer = " + this.initializeBuffer()); } else { out.push(""); } // track the last context pushed into place to allow skipping the // getContext opcode when it would be a noop this.lastContext = 0; this.source = out; }, createFunctionContext: function(asObject) { var locals = this.stackVars.concat(this.registers.list); if(locals.length > 0) { this.source[1] = this.source[1] + ", " + locals.join(", "); } // Generate minimizer alias mappings if (!this.isChild) { for (var alias in this.context.aliases) { if (this.context.aliases.hasOwnProperty(alias)) { this.source[1] = this.source[1] + ', ' + alias + '=' + this.context.aliases[alias]; } } } if (this.source[1]) { this.source[1] = "var " + this.source[1].substring(2) + ";"; } // Merge children if (!this.isChild) { this.source[1] += '\n' + this.context.programs.join('\n') + '\n'; } if (!this.environment.isSimple) { this.source.push("return buffer;"); } var params = this.isChild ? ["depth0", "data"] : ["Handlebars", "depth0", "helpers", "partials", "data"]; for(var i=0, l=this.environment.depths.list.length; i<l; i++) { params.push("depth" + this.environment.depths.list[i]); } // Perform a second pass over the output to merge content when possible var source = this.mergeSource(); if (!this.isChild) { var revision = Handlebars.COMPILER_REVISION, versions = Handlebars.REVISION_CHANGES[revision]; source = "this.compilerInfo = ["+revision+",'"+versions+"'];\n"+source; } if (asObject) { params.push(source); return Function.apply(this, params); } else { var functionSource = 'function ' + (this.name || '') + '(' + params.join(',') + ') {\n ' + source + '}'; Handlebars.log(Handlebars.logger.DEBUG, functionSource + "\n\n"); return functionSource; } }, mergeSource: function() { // WARN: We are not handling the case where buffer is still populated as the source should // not have buffer append operations as their final action. var source = '', buffer; for (var i = 0, len = this.source.length; i < len; i++) { var line = this.source[i]; if (line.appendToBuffer) { if (buffer) { buffer = buffer + '\n + ' + line.content; } else { buffer = line.content; } } else { if (buffer) { source += 'buffer += ' + buffer + ';\n '; buffer = undefined; } source += line + '\n '; } } return source; }, // [blockValue] // // On stack, before: hash, inverse, program, value // On stack, after: return value of blockHelperMissing // // The purpose of this opcode is to take a block of the form // `{{#foo}}...{{/foo}}`, resolve the value of `foo`, and // replace it on the stack with the result of properly // invoking blockHelperMissing. blockValue: function() { this.context.aliases.blockHelperMissing = 'helpers.blockHelperMissing'; var params = ["depth0"]; this.setupParams(0, params); this.replaceStack(function(current) { params.splice(1, 0, current); return "blockHelperMissing.call(" + params.join(", ") + ")"; }); }, // [ambiguousBlockValue] // // On stack, before: hash, inverse, program, value // Compiler value, before: lastHelper=value of last found helper, if any // On stack, after, if no lastHelper: same as [blockValue] // On stack, after, if lastHelper: value ambiguousBlockValue: function() { this.context.aliases.blockHelperMissing = 'helpers.blockHelperMissing'; var params = ["depth0"]; this.setupParams(0, params); var current = this.topStack(); params.splice(1, 0, current); // Use the options value generated from the invocation params[params.length-1] = 'options'; this.source.push("if (!" + this.lastHelper + ") { " + current + " = blockHelperMissing.call(" + params.join(", ") + "); }"); }, // [appendContent] // // On stack, before: ... // On stack, after: ... // // Appends the string value of `content` to the current buffer appendContent: function(content) { this.source.push(this.appendToBuffer(this.quotedString(content))); }, // [append] // // On stack, before: value, ... // On stack, after: ... // // Coerces `value` to a String and appends it to the current buffer. // // If `value` is truthy, or 0, it is coerced into a string and appended // Otherwise, the empty string is appended append: function() { // Force anything that is inlined onto the stack so we don't have duplication // when we examine local this.flushInline(); var local = this.popStack(); this.source.push("if(" + local + " || " + local + " === 0) { " + this.appendToBuffer(local) + " }"); if (this.environment.isSimple) { this.source.push("else { " + this.appendToBuffer("''") + " }"); } }, // [appendEscaped] // // On stack, before: value, ... // On stack, after: ... // // Escape `value` and append it to the buffer appendEscaped: function() { this.context.aliases.escapeExpression = 'this.escapeExpression'; this.source.push(this.appendToBuffer("escapeExpression(" + this.popStack() + ")")); }, // [getContext] // // On stack, before: ... // On stack, after: ... // Compiler value, after: lastContext=depth // // Set the value of the `lastContext` compiler value to the depth getContext: function(depth) { if(this.lastContext !== depth) { this.lastContext = depth; } }, // [lookupOnContext] // // On stack, before: ... // On stack, after: currentContext[name], ... // // Looks up the value of `name` on the current context and pushes // it onto the stack. lookupOnContext: function(name) { this.push(this.nameLookup('depth' + this.lastContext, name, 'context')); }, // [pushContext] // // On stack, before: ... // On stack, after: currentContext, ... // // Pushes the value of the current context onto the stack. pushContext: function() { this.pushStackLiteral('depth' + this.lastContext); }, // [resolvePossibleLambda] // // On stack, before: value, ... // On stack, after: resolved value, ... // // If the `value` is a lambda, replace it on the stack by // the return value of the lambda resolvePossibleLambda: function() { this.context.aliases.functionType = '"function"'; this.replaceStack(function(current) { return "typeof " + current + " === functionType ? " + current + ".apply(depth0) : " + current; }); }, // [lookup] // // On stack, before: value, ... // On stack, after: value[name], ... // // Replace the value on the stack with the result of looking // up `name` on `value` lookup: function(name) { this.replaceStack(function(current) { return current + " == null || " + current + " === false ? " + current + " : " + this.nameLookup(current, name, 'context'); }); }, // [lookupData] // // On stack, before: ... // On stack, after: data[id], ... // // Push the result of looking up `id` on the current data lookupData: function(id) { this.push('data'); }, // [pushStringParam] // // On stack, before: ... // On stack, after: string, currentContext, ... // // This opcode is designed for use in string mode, which // provides the string value of a parameter along with its // depth rather than resolving it immediately. pushStringParam: function(string, type) { this.pushStackLiteral('depth' + this.lastContext); this.pushString(type); if (typeof string === 'string') { this.pushString(string); } else { this.pushStackLiteral(string); } }, emptyHash: function() { this.pushStackLiteral('{}'); if (this.options.stringParams) { this.register('hashTypes', '{}'); this.register('hashContexts', '{}'); } }, pushHash: function() { this.hash = {values: [], types: [], contexts: []}; }, popHash: function() { var hash = this.hash; this.hash = undefined; if (this.options.stringParams) { this.register('hashContexts', '{' + hash.contexts.join(',') + '}'); this.register('hashTypes', '{' + hash.types.join(',') + '}'); } this.push('{\n ' + hash.values.join(',\n ') + '\n }'); }, // [pushString] // // On stack, before: ... // On stack, after: quotedString(string), ... // // Push a quoted version of `string` onto the stack pushString: function(string) { this.pushStackLiteral(this.quotedString(string)); }, // [push] // // On stack, before: ... // On stack, after: expr, ... // // Push an expression onto the stack push: function(expr) { this.inlineStack.push(expr); return expr; }, // [pushLiteral] // // On stack, before: ... // On stack, after: value, ... // // Pushes a value onto the stack. This operation prevents // the compiler from creating a temporary variable to hold // it. pushLiteral: function(value) { this.pushStackLiteral(value); }, // [pushProgram] // // On stack, before: ... // On stack, after: program(guid), ... // // Push a program expression onto the stack. This takes // a compile-time guid and converts it into a runtime-accessible // expression. pushProgram: function(guid) { if (guid != null) { this.pushStackLiteral(this.programExpression(guid)); } else { this.pushStackLiteral(null); } }, // [invokeHelper] // // On stack, before: hash, inverse, program, params..., ... // On stack, after: result of helper invocation // // Pops off the helper's parameters, invokes the helper, // and pushes the helper's return value onto the stack. // // If the helper is not found, `helperMissing` is called. invokeHelper: function(paramSize, name) { this.context.aliases.helperMissing = 'helpers.helperMissing'; var helper = this.lastHelper = this.setupHelper(paramSize, name, true); var nonHelper = this.nameLookup('depth' + this.lastContext, name, 'context'); this.push(helper.name + ' || ' + nonHelper); this.replaceStack(function(name) { return name + ' ? ' + name + '.call(' + helper.callParams + ") " + ": helperMissing.call(" + helper.helperMissingParams + ")"; }); }, // [invokeKnownHelper] // // On stack, before: hash, inverse, program, params..., ... // On stack, after: result of helper invocation // // This operation is used when the helper is known to exist, // so a `helperMissing` fallback is not required. invokeKnownHelper: function(paramSize, name) { var helper = this.setupHelper(paramSize, name); this.push(helper.name + ".call(" + helper.callParams + ")"); }, // [invokeAmbiguous] // // On stack, before: hash, inverse, program, params..., ... // On stack, after: result of disambiguation // // This operation is used when an expression like `{{foo}}` // is provided, but we don't know at compile-time whether it // is a helper or a path. // // This operation emits more code than the other options, // and can be avoided by passing the `knownHelpers` and // `knownHelpersOnly` flags at compile-time. invokeAmbiguous: function(name, helperCall) { this.context.aliases.functionType = '"function"'; this.pushStackLiteral('{}'); // Hash value var helper = this.setupHelper(0, name, helperCall); var helperName = this.lastHelper = this.nameLookup('helpers', name, 'helper'); var nonHelper = this.nameLookup('depth' + this.lastContext, name, 'context'); var nextStack = this.nextStack(); this.source.push('if (' + nextStack + ' = ' + helperName + ') { ' + nextStack + ' = ' + nextStack + '.call(' + helper.callParams + '); }'); this.source.push('else { ' + nextStack + ' = ' + nonHelper + '; ' + nextStack + ' = typeof ' + nextStack + ' === functionType ? ' + nextStack + '.apply(depth0) : ' + nextStack + '; }'); }, // [invokePartial] // // On stack, before: context, ... // On stack after: result of partial invocation // // This operation pops off a context, invokes a partial with that context, // and pushes the result of the invocation back. invokePartial: function(name) { var params = [this.nameLookup('partials', name, 'partial'), "'" + name + "'", this.popStack(), "helpers", "partials"]; if (this.options.data) { params.push("data"); } this.context.aliases.self = "this"; this.push("self.invokePartial(" + params.join(", ") + ")"); }, // [assignToHash] // // On stack, before: value, hash, ... // On stack, after: hash, ... // // Pops a value and hash off the stack, assigns `hash[key] = value` // and pushes the hash back onto the stack. assignToHash: function(key) { var value = this.popStack(), context, type; if (this.options.stringParams) { type = this.popStack(); context = this.popStack(); } var hash = this.hash; if (context) { hash.contexts.push("'" + key + "': " + context); } if (type) { hash.types.push("'" + key + "': " + type); } hash.values.push("'" + key + "': (" + value + ")"); }, // HELPERS compiler: JavaScriptCompiler, compileChildren: function(environment, options) { var children = environment.children, child, compiler; for(var i=0, l=children.length; i<l; i++) { child = children[i]; compiler = new this.compiler(); var index = this.matchExistingProgram(child); if (index == null) { this.context.programs.push(''); // Placeholder to prevent name conflicts for nested children index = this.context.programs.length; child.index = index; child.name = 'program' + index; this.context.programs[index] = compiler.compile(child, options, this.context); this.context.environments[index] = child; } else { child.index = index; child.name = 'program' + index; } } }, matchExistingProgram: function(child) { for (var i = 0, len = this.context.environments.length; i < len; i++) { var environment = this.context.environments[i]; if (environment && environment.equals(child)) { return i; } } }, programExpression: function(guid) { this.context.aliases.self = "this"; if(guid == null) { return "self.noop"; } var child = this.environment.children[guid], depths = child.depths.list, depth; var programParams = [child.index, child.name, "data"]; for(var i=0, l = depths.length; i<l; i++) { depth = depths[i]; if(depth === 1) { programParams.push("depth0"); } else { programParams.push("depth" + (depth - 1)); } } return (depths.length === 0 ? "self.program(" : "self.programWithDepth(") + programParams.join(", ") + ")"; }, register: function(name, val) { this.useRegister(name); this.source.push(name + " = " + val + ";"); }, useRegister: function(name) { if(!this.registers[name]) { this.registers[name] = true; this.registers.list.push(name); } }, pushStackLiteral: function(item) { return this.push(new Literal(item)); }, pushStack: function(item) { this.flushInline(); var stack = this.incrStack(); if (item) { this.source.push(stack + " = " + item + ";"); } this.compileStack.push(stack); return stack; }, replaceStack: function(callback) { var prefix = '', inline = this.isInline(), stack; // If we are currently inline then we want to merge the inline statement into the // replacement statement via ',' if (inline) { var top = this.popStack(true); if (top instanceof Literal) { // Literals do not need to be inlined stack = top.value; } else { // Get or create the current stack name for use by the inline var name = this.stackSlot ? this.topStackName() : this.incrStack(); prefix = '(' + this.push(name) + ' = ' + top + '),'; stack = this.topStack(); } } else { stack = this.topStack(); } var item = callback.call(this, stack); if (inline) { if (this.inlineStack.length || this.compileStack.length) { this.popStack(); } this.push('(' + prefix + item + ')'); } else { // Prevent modification of the context depth variable. Through replaceStack if (!/^stack/.test(stack)) { stack = this.nextStack(); } this.source.push(stack + " = (" + prefix + item + ");"); } return stack; }, nextStack: function() { return this.pushStack(); }, incrStack: function() { this.stackSlot++; if(this.stackSlot > this.stackVars.length) { this.stackVars.push("stack" + this.stackSlot); } return this.topStackName(); }, topStackName: function() { return "stack" + this.stackSlot; }, flushInline: function() { var inlineStack = this.inlineStack; if (inlineStack.length) { this.inlineStack = []; for (var i = 0, len = inlineStack.length; i < len; i++) { var entry = inlineStack[i]; if (entry instanceof Literal) { this.compileStack.push(entry); } else { this.pushStack(entry); } } } }, isInline: function() { return this.inlineStack.length; }, popStack: function(wrapped) { var inline = this.isInline(), item = (inline ? this.inlineStack : this.compileStack).pop(); if (!wrapped && (item instanceof Literal)) { return item.value; } else { if (!inline) { this.stackSlot--; } return item; } }, topStack: function(wrapped) { var stack = (this.isInline() ? this.inlineStack : this.compileStack), item = stack[stack.length - 1]; if (!wrapped && (item instanceof Literal)) { return item.value; } else { return item; } }, quotedString: function(str) { return '"' + str .replace(/\\/g, '\\\\') .replace(/"/g, '\\"') .replace(/\n/g, '\\n') .replace(/\r/g, '\\r') .replace(/\u2028/g, '\\u2028') // Per Ecma-262 7.3 + 7.8.4 .replace(/\u2029/g, '\\u2029') + '"'; }, setupHelper: function(paramSize, name, missingParams) { var params = []; this.setupParams(paramSize, params, missingParams); var foundHelper = this.nameLookup('helpers', name, 'helper'); return { params: params, name: foundHelper, callParams: ["depth0"].concat(params).join(", "), helperMissingParams: missingParams && ["depth0", this.quotedString(name)].concat(params).join(", ") }; }, // the params and contexts arguments are passed in arrays // to fill in setupParams: function(paramSize, params, useRegister) { var options = [], contexts = [], types = [], param, inverse, program; options.push("hash:" + this.popStack()); inverse = this.popStack(); program = this.popStack(); // Avoid setting fn and inverse if neither are set. This allows // helpers to do a check for `if (options.fn)` if (program || inverse) { if (!program) { this.context.aliases.self = "this"; program = "self.noop"; } if (!inverse) { this.context.aliases.self = "this"; inverse = "self.noop"; } options.push("inverse:" + inverse); options.push("fn:" + program); } for(var i=0; i<paramSize; i++) { param = this.popStack(); params.push(param); if(this.options.stringParams) { types.push(this.popStack()); contexts.push(this.popStack()); } } if (this.options.stringParams) { options.push("contexts:[" + contexts.join(",") + "]"); options.push("types:[" + types.join(",") + "]"); options.push("hashContexts:hashContexts"); options.push("hashTypes:hashTypes"); } if(this.options.data) { options.push("data:data"); } options = "{" + options.join(",") + "}"; if (useRegister) { this.register('options', options); params.push('options'); } else { params.push(options); } return params.join(", "); } }; var reservedWords = ( "break else new var" + " case finally return void" + " catch for switch while" + " continue function this with" + " default if throw" + " delete in try" + " do instanceof typeof" + " abstract enum int short" + " boolean export interface static" + " byte extends long super" + " char final native synchronized" + " class float package throws" + " const goto private transient" + " debugger implements protected volatile" + " double import public let yield" ).split(" "); var compilerWords = JavaScriptCompiler.RESERVED_WORDS = {}; for(var i=0, l=reservedWords.length; i<l; i++) { compilerWords[reservedWords[i]] = true; } JavaScriptCompiler.isValidJavaScriptVariableName = function(name) { if(!JavaScriptCompiler.RESERVED_WORDS[name] && /^[a-zA-Z_$][0-9a-zA-Z_$]+$/.test(name)) { return true; } return false; }; Handlebars.precompile = function(input, options) { if (input == null || (typeof input !== 'string' && input.constructor !== Handlebars.AST.ProgramNode)) { throw new Handlebars.Exception("You must pass a string or Handlebars AST to Handlebars.precompile. You passed " + input); } options = options || {}; if (!('data' in options)) { options.data = true; } var ast = Handlebars.parse(input); var environment = new Compiler().compile(ast, options); return new JavaScriptCompiler().compile(environment, options); }; Handlebars.compile = function(input, options) { if (input == null || (typeof input !== 'string' && input.constructor !== Handlebars.AST.ProgramNode)) { throw new Handlebars.Exception("You must pass a string or Handlebars AST to Handlebars.compile. You passed " + input); } options = options || {}; if (!('data' in options)) { options.data = true; } var compiled; function compile() { var ast = Handlebars.parse(input); var environment = new Compiler().compile(ast, options); var templateSpec = new JavaScriptCompiler().compile(environment, options, undefined, true); return Handlebars.template(templateSpec); } // Template is only compiled on first use and cached after that point. return function(context, options) { if (!compiled) { compiled = compile(); } return compiled.call(this, context, options); }; }; // This file contains YUI-specific wrapper code and overrides for the // handlebars-compiler module. /** Handlebars parser and compiler. Use this module when you need to compile Handlebars templates. @module handlebars @submodule handlebars-compiler */ var levels = ['debug', 'info', 'warn', 'error']; /** Logs a debugging message. Note that messages will only be logged when the handlebars module is loaded in "debug" mode. @method log @param {String} level Log level for this message. Supported levels are "debug", "info", "warn", and "error". @param {String} message Message to log. @for Handlebars */ Handlebars.logger.log = function (level, message) { }; /** Compiles and renders a Handlebars template string in a single step. If you'll be using a template more than once, it's more efficient to compile it into a function once using `compile()`, and then render it whenever you need to by simply executing the compiled function. However, if you only need to compile and render a template once, `render()` is a handy shortcut for doing both in a single step. @example Y.Handlebars.render('The pie of the day is {{pie}}!', { pie: 'Maple Custard' }); // => "The pie of the day is Maple Custard!" @method render @param {String} string Handlebars template string to render. @param {Object} context Context object to pass to the template. @param {Object} [options] Compile/render options. @param {Object} [options.helpers] Helper functions. @param {Object} [options.partials] Partials. @param {Object} [options.data] Data. @return {String} Rendered template string. */ Handlebars.render = function (string, context, options) { return Handlebars.compile(string)(context, options); }; // The rest of this file is just API docs for methods defined in Handlebars // itself. /** Compiles a Handlebars template string into a function. To render the template, call the function and pass in a context object. @example var template = Y.Handlebars.compile('The pie of the day is {{pie}}!.'); template({pie: 'Pecan'}); // => "The pie of the day is Pecan!" @method compile @param {String} string Handlebars template string to compile. @param {Object} [options] Compiler options. @return {Function} Compiled template function. */ /** Precompiles a Handlebars template string into a string of JavaScript code. This can be used to precompile a template at build time or on the server, and the resulting template can then be rendered at runtime or on the client without needing to go through a compile step. To render a precompiled template, evaluate the code and then pass the resulting function to `Y.Handlebars.template()` to get back an executable template function. @method precompile @param {String} string Handlebars template string to compile. @param {Object} [options] Compiler options. @return {String} Precompiled template code. */ }, '3.17.0', {"requires": ["handlebars-base"]});
import React from 'react' import PropTypes from 'prop-types' // Components import { Link, graphql } from 'gatsby' import Layout from '../components/Layout' const Tags = ({ pageContext, data }) => { const { tag } = pageContext const { edges, totalCount } = data.allMarkdownRemark const { title } = data.site.siteMetadata return ( <Layout title={title}> <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '2.625rem', }} > <h2 style={{ margin: 0 }}> {tag}{' '} <span style={{ fontSize: '13px', padding: '8px' }}> <Link to="/tags">all tags</Link> </span> </h2> <span>{totalCount} Posts</span> </div> <div style={{ display: 'grid' }}> {edges.map(({ node }) => { const { slug } = node.fields const { title } = node.frontmatter return ( <div key={slug}> <Link to={slug}>{title}</Link> <p>{node.excerpt}</p> </div> ) })} </div> </Layout> ) } Tags.propTypes = { pageContext: PropTypes.shape({ tag: PropTypes.string.isRequired, }), data: PropTypes.shape({ allMarkdownRemark: PropTypes.shape({ totalCount: PropTypes.number.isRequired, edges: PropTypes.arrayOf( PropTypes.shape({ node: PropTypes.shape({ frontmatter: PropTypes.shape({ title: PropTypes.string.isRequired, }), fields: PropTypes.shape({ slug: PropTypes.string.isRequired, }), excerpt: PropTypes.string.isRequired, }), }).isRequired ), }), }), } export default Tags export const pageQuery = graphql` query($tag: String) { site { siteMetadata { title } } allMarkdownRemark( limit: 2000 sort: { fields: [frontmatter___date], order: DESC } filter: { frontmatter: { tags: { in: [$tag] } } } ) { totalCount edges { node { excerpt fields { slug } frontmatter { title } } } } } `
import Directory from '@ascend-media/package-directory/browser'; import Inquiry from '@parameter1/base-cms-marko-web-inquiry/browser'; const PaginationPageNumberInput = () => import(/* webpackChunkName: "minexpo-pagination-page-number-input" */ './pagination-page-number-input.vue'); export default (Browser) => { Directory(Browser); Inquiry(Browser); Browser.registerComponent('PaginationPageNumberInput', PaginationPageNumberInput); };
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),t=require("primereact/utils"),r=require("primereact/csstransition");function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var o=n(e);function a(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function i(e){if(Array.isArray(e))return a(e)}function s(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}function l(e,t){if(e){if("string"==typeof e)return a(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?a(e,t):void 0}}function c(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function u(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function p(e,t,r){return t&&u(e.prototype,t),r&&u(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function d(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function f(e,t){return f=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},f(e,t)}function h(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&f(e,t)}function b(e){return b="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},b(e)}function y(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function m(e,t){if(t&&("object"===b(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return y(e)}function v(e){return v=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},v(e)}function O(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function g(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function T(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?g(Object(r),!0).forEach((function(t){O(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):g(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function j(e){var t=S();return function(){var r,n=v(e);if(t){var o=v(this).constructor;r=Reflect.construct(n,arguments,o)}else r=n.apply(this,arguments);return m(this,r)}}function S(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}var C=function(t){h(n,e.Component);var r=j(n);function n(){return d(this,n),r.apply(this,arguments)}return p(n)}();O(C,"defaultProps",{header:null,disabled:!1,style:null,className:null,headerStyle:null,headerClassName:null,headerTemplate:null,contentStyle:null,contentClassName:null});var w=function(n){h(u,e.Component);var a=j(u);function u(e){var t;d(this,u);var r={id:(t=a.call(this,e)).props.id};return t.props.onTabChange||(r=T(T({},r),{},{activeIndex:e.activeIndex})),t.state=r,t}return p(u,[{key:"shouldTabRender",value:function(e){return e&&e.type===C}},{key:"onTabHeaderClick",value:function(e,t,r){if(!t.props.disabled){var n=this.isSelected(r),o=null;if(this.props.multiple){var a=(this.props.onTabChange?this.props.activeIndex:this.state.activeIndex)||[];o=a=n?a.filter((function(e){return e!==r})):[].concat(i(p=a)||s(p)||l(p)||c(),[r])}else o=n?null:r;var u=n?this.props.onTabClose:this.props.onTabOpen;u&&u({originalEvent:e,index:r}),this.props.onTabChange?this.props.onTabChange({originalEvent:e,index:o}):this.setState({activeIndex:o})}var p;e.preventDefault()}},{key:"isSelected",value:function(e){var t=this.props.onTabChange?this.props.activeIndex:this.state.activeIndex;return this.props.multiple?t&&t.indexOf(e)>=0:t===e}},{key:"componentDidMount",value:function(){this.state.id||this.setState({id:t.UniqueComponentId()})}},{key:"renderTabHeader",value:function(e,r,n){var a=this,i=T(T({},e.props.headerStyle||{}),e.props.style||{}),s=t.classNames("p-accordion-header",{"p-highlight":r,"p-disabled":e.props.disabled},e.props.headerClassName,e.props.className),l=this.state.id+"_header_"+n,c=this.state.id+"_content_"+n,u=e.props.disabled?-1:null,p=e.props.headerTemplate?t.ObjectUtils.getJSXElement(e.props.headerTemplate,e.props):o.default.createElement("span",{className:"p-accordion-header-text"},e.props.header);return o.default.createElement("div",{className:s,style:i},o.default.createElement("a",{href:"#"+c,id:l,className:"p-accordion-header-link","aria-controls":c,role:"tab","aria-expanded":r,onClick:function(t){return a.onTabHeaderClick(t,e,n)},tabIndex:u},t.IconUtils.getJSXIcon(r?this.props.collapseIcon:this.props.expandIcon,{className:"p-accordion-toggle-icon"},{props:this.props,selected:r}),p))}},{key:"renderTabContent",value:function(e,n,a){var i=T(T({},e.props.contentStyle||{}),e.props.style||{}),s=t.classNames("p-toggleable-content",e.props.contentClassName,e.props.className),l=this.state.id+"_content_"+a,c=o.default.createRef();return o.default.createElement(r.CSSTransition,{nodeRef:c,classNames:"p-toggleable-content",timeout:{enter:1e3,exit:450},in:n,unmountOnExit:!0,options:this.props.transitionOptions},o.default.createElement("div",{ref:c,id:l,className:s,style:i,role:"region","aria-labelledby":this.state.id+"_header_"+a},o.default.createElement("div",{className:"p-accordion-content"},e.props.children)))}},{key:"renderTab",value:function(e,r){var n=this.isSelected(r),a=this.renderTabHeader(e,n,r),i=this.renderTabContent(e,n,r),s=t.classNames("p-accordion-tab",{"p-accordion-tab-active":n});return o.default.createElement("div",{key:e.props.header,className:s},a,i)}},{key:"renderTabs",value:function(){var e=this;return o.default.Children.map(this.props.children,(function(t,r){if(e.shouldTabRender(t))return e.renderTab(t,r)}))}},{key:"render",value:function(){var e=this,r=t.classNames("p-accordion p-component",this.props.className),n=this.renderTabs();return o.default.createElement("div",{ref:function(t){return e.container=t},id:this.state.id,className:r,style:this.props.style},n)}}]),u}();O(w,"defaultProps",{id:null,activeIndex:null,className:null,style:null,multiple:!1,expandIcon:"pi pi-chevron-right",collapseIcon:"pi pi-chevron-down",transitionOptions:null,onTabOpen:null,onTabClose:null,onTabChange:null}),exports.Accordion=w,exports.AccordionTab=C;
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var prefix = 'fab'; var iconName = 'discord'; var width = 640; var height = 512; var aliases = []; var unicode = 'f392'; var svgPathData = 'M524.5 69.84a1.5 1.5 0 0 0 -.764-.7A485.1 485.1 0 0 0 404.1 32.03a1.816 1.816 0 0 0 -1.923 .91 337.5 337.5 0 0 0 -14.9 30.6 447.8 447.8 0 0 0 -134.4 0 309.5 309.5 0 0 0 -15.14-30.6 1.89 1.89 0 0 0 -1.924-.91A483.7 483.7 0 0 0 116.1 69.14a1.712 1.712 0 0 0 -.788 .676C39.07 183.7 18.19 294.7 28.43 404.4a2.016 2.016 0 0 0 .765 1.375A487.7 487.7 0 0 0 176 479.9a1.9 1.9 0 0 0 2.063-.676A348.2 348.2 0 0 0 208.1 430.4a1.86 1.86 0 0 0 -1.019-2.588 321.2 321.2 0 0 1 -45.87-21.85 1.885 1.885 0 0 1 -.185-3.126c3.082-2.309 6.166-4.711 9.109-7.137a1.819 1.819 0 0 1 1.9-.256c96.23 43.92 200.4 43.92 295.5 0a1.812 1.812 0 0 1 1.924 .233c2.944 2.426 6.027 4.851 9.132 7.16a1.884 1.884 0 0 1 -.162 3.126 301.4 301.4 0 0 1 -45.89 21.83 1.875 1.875 0 0 0 -1 2.611 391.1 391.1 0 0 0 30.01 48.81 1.864 1.864 0 0 0 2.063 .7A486 486 0 0 0 610.7 405.7a1.882 1.882 0 0 0 .765-1.352C623.7 277.6 590.9 167.5 524.5 69.84zM222.5 337.6c-28.97 0-52.84-26.59-52.84-59.24S193.1 219.1 222.5 219.1c29.67 0 53.31 26.82 52.84 59.24C275.3 310.1 251.9 337.6 222.5 337.6zm195.4 0c-28.97 0-52.84-26.59-52.84-59.24S388.4 219.1 417.9 219.1c29.67 0 53.31 26.82 52.84 59.24C470.7 310.1 447.5 337.6 417.9 337.6z'; exports.definition = { prefix: prefix, iconName: iconName, icon: [ width, height, aliases, unicode, svgPathData ]}; exports.faDiscord = exports.definition; exports.prefix = prefix; exports.iconName = iconName; exports.width = width; exports.height = height; exports.ligatures = aliases; exports.unicode = unicode; exports.svgPathData = svgPathData; exports.aliases = aliases;
//// [objectLiteralReferencingInternalProperties.ts] var a = { b: 10, c: b }; // Should give error for attempting to reference b. //// [objectLiteralReferencingInternalProperties.js] var a = { b: 10, c: b }; // Should give error for attempting to reference b.
// DO NOT EDIT! This test has been generated by /offscreen-canvas/tools/gentest.py. // OffscreenCanvas test in a worker:2d.text.align.invalid // Description: // Note: importScripts("/resources/testharness.js"); importScripts("/2dcontext/resources/canvas-tests.js"); var t = async_test(""); var t_pass = t.done.bind(t); var t_fail = t.step_func(function(reason) { throw reason; }); t.step(function() { var offscreenCanvas = new OffscreenCanvas(100, 50); var ctx = offscreenCanvas.getContext('2d'); ctx.textAlign = 'start'; ctx.textAlign = 'bogus'; _assertSame(ctx.textAlign, 'start', "ctx.textAlign", "'start'"); ctx.textAlign = 'start'; ctx.textAlign = 'END'; _assertSame(ctx.textAlign, 'start', "ctx.textAlign", "'start'"); ctx.textAlign = 'start'; ctx.textAlign = 'end '; _assertSame(ctx.textAlign, 'start', "ctx.textAlign", "'start'"); ctx.textAlign = 'start'; ctx.textAlign = 'end\0'; _assertSame(ctx.textAlign, 'start', "ctx.textAlign", "'start'"); t.done(); }); done();
'use strict'; app.controller('statisticaBoundController', ['$scope', '$http', '$state','$location','$filter','$stateParams','infoService','formatDate','arrDate', function($scope, $http, $state,$location,$filter,$stateParams,infoService,formatDate,arrDate) { $("#dtBox").DateTimePicker({ language:'zh-CN', defaultDate: new Date(), animationDuration:200, buttonsToDisplay: [ "SetButton", "ClearButton"], clearButtonContent: "取消" }); var Stime=arrDate.get($stateParams.type).substring(0,20); var Etime=arrDate.get($stateParams.type).substring(20); $scope.txt='新增绑定统计'; $scope.go=function(){ $location.path('app/index'); }; $scope.select={ status : 1, //1为正常 page_no : 1, //当前页 page_size : 10000, //每页显示条数 } //加载场馆 $scope.load1=function(){ $http({ method: 'POST', url:window.base_url+'/manager/shop/search', data: { limit : 0 } }).success(function(data){ if(data.code==200){ $scope.shopList=data.data; }else{ layer.msg(data.message, {icon: 2}); } }).error( function(data){ layer.msg('服务器访问失败!', {icon: 2}); }); }; $scope.load1(); $scope.parmList={ phone : '', //手机号查询 shop_id : '', //查询场馆 type : 6, //1会员卡,3私教课 pay_type : '', //[] 数组,不传所有。['CASH'] 代购,['WXPAY','ALIPAY','SITEPAY'] 线上 start_time : Stime, //开始时间 end_time : Etime, //结束时间 page_no : 1, //当前页 page_size : 12, //每页显示条数 order : 'a.pay_time desc', //排序 a.pay_time desc(降序) or asc(升序) a.price desc or as start_day : '', end_day : '', start_hour : '', end_hour : '' } //分页 $scope.maxSize=5; $scope.pages=function(){ $scope.load(); } //加载 $scope.load=function(){ if($scope.parmList.pay_type==''){ delete $scope.parmList.pay_type; } if($scope.parmList.start_time==''){ delete $scope.parmList.start_time; } if($scope.parmList.end_time==''){ delete $scope.parmList.end_time; } $http({ method: 'POST', url:window.base_url+'/manager/order/reportlist', data: { phone : $scope.parmList.phone, shop_id : $scope.parmList.shop_id, type : $scope.parmList.type, pay_type : $scope.parmList.pay_type, start_time : $scope.parmList.start_time, end_time : $scope.parmList.end_time, page_no : $scope.parmList.page_no, page_size : $scope.parmList.page_size, order : $scope.parmList.order, } }).success(function(data){ if(data.code==200){ $scope.statisticaBoundList=data.data; if($scope.statisticaBoundList.list.length == 'undefined' || $scope.statisticaBoundList.list.length == undefined){ $scope.statisticaBoundList.list = []; } }else{ layer.msg(data.message, {icon: 2}); } }).error( function(data){ layer.msg('服务器访问失败!', {icon: 2}); }); } $scope.load(); //编辑模态框 $scope.editModal_open=function(item){ $('#memberModal').modal('show'); }; $scope.editModal_close=function(){ $('#memberModal').modal('hide'); }; }]);
(function($) { $.ManifestListItem = function(options) { jQuery.extend(true, this, { element: null, appendTo: null, manifest: null, loadStatus: null, thumbHeight: 80, urlHeight: 150, resultsWidth: 0, // based on screen width maxPreviewImagesWidth: 0, repoWidth: 80, metadataWidth: 450, margin: 15, remainingWidth: 20, imagesTotalWidth: 0, tplData: null, allImages: [], remaining: 0, forcedIndex: null, state: null, eventEmitter: null }, options); this.init(); }; $.ManifestListItem.prototype = { init: function() { var _this = this; //need a better way of calculating this because JS can't get width and margin of hidden elements, so must manually set that info //ultimately use 95% of space available, since sometimes it still displays too many images this.maxPreviewImagesWidth = this.resultsWidth - (this.repoWidth + this.margin + this.metadataWidth + this.margin + this.remainingWidth); this.maxPreviewImagesWidth = this.maxPreviewImagesWidth * 0.95; $.Handlebars.registerHelper('pluralize', function(count, singular, plural) { if (count === 1) { return singular; } else { return plural; } }); this.fetchTplData(this.manifestId); if (this.forcedIndex !== null) { this.tplData.index = this.forcedIndex; } if (_this.state.getStateProperty('preserveManifestOrder')) { if (this.appendTo.children().length === 0) { this.element = jQuery(this.template(this.tplData)).prependTo(this.appendTo).hide().fadeIn('slow'); } else { var liList = _this.appendTo.find('li'); jQuery.each(liList, function(index, item) { var prev = parseFloat(jQuery(item).attr('data-index-number')); var next = parseFloat(jQuery(liList[index+1]).attr('data-index-number')); var current = _this.tplData.index; if (current <= prev && (next > current || isNaN(next)) ) { _this.element = jQuery(_this.template(_this.tplData)).insertBefore(jQuery(item)).hide().fadeIn('slow'); return false; } else if (current > prev && (current < next || isNaN(next))) { _this.element = jQuery(_this.template(_this.tplData)).insertAfter(jQuery(item)).hide().fadeIn('slow'); return false; } }); } } else { this.element = jQuery(this.template(this.tplData)).prependTo(this.appendTo).hide().fadeIn('slow'); } this.bindEvents(); this.listenForActions(); }, fetchTplData: function() { var _this = this, location = _this.manifest.location, manifest = _this.manifest.jsonLd; this.tplData = { label: $.JsonLd.getTextValue(manifest.label), repository: location, canvasCount: manifest.sequences[0].canvases.length, images: [], index: _this.state.getManifestIndex(manifest['@id']) }; this.tplData.repoImage = (function() { var repo = _this.tplData.repository; if (manifest.logo) { if (typeof manifest.logo === "string") return manifest.logo; if (typeof manifest.logo['@id'] !== 'undefined') return manifest.logo['@id']; } return ''; })(); for ( var i=0; i < manifest.sequences[0].canvases.length; i++) { var canvas = manifest.sequences[0].canvases[i]; if (canvas.width === 0) { continue; } var aspectRatio = canvas.height/canvas.width, width = (_this.thumbHeight/aspectRatio); url = _this.manifest.getThumbnailForCanvas(canvas, width); _this.allImages.push({ url: url, width: width, height: _this.thumbHeight, id: canvas['@id'], index: i }); } jQuery.each(_this.allImages, function(index, value) { var width = value.width; _this.imagesTotalWidth += (width + _this.margin); if (_this.imagesTotalWidth >= _this.maxPreviewImagesWidth) { // outsized image will inherited if (value.width > _this.maxPreviewImagesWidth) { _this.tplData.images.push(value); } _this.imagesTotalWidth -= (width + _this.margin); return false; } _this.tplData.images.push(value); }); _this.remaining = this.tplData.remaining = (function() { var remaining = _this.allImages.length - _this.tplData.images.length; if (remaining > 0) { return remaining; } })(); }, render: function() { }, listenForActions: function() { var _this = this; _this.eventEmitter.subscribe('manifestPanelWidthChanged', function(event, newWidth){ _this.updateDisplay(newWidth); }); }, bindEvents: function() { var _this = this; this.element.find('img').on('load', function() { //if img width is not equal to the width in the html, change height jQuery(this).hide().fadeIn(600); }); this.element.on('click', function() { var windowConfig = { manifest: _this.manifest, canvasID: null, viewType: 'ThumbnailsView' }; _this.eventEmitter.publish('ADD_WINDOW', windowConfig); }); this.element.find('.preview-image').on('click', function(e) { e.stopPropagation(); var windowConfig = { manifest: _this.manifest, canvasID: jQuery(this).attr('data-image-id'), viewType: _this.state.getStateProperty('windowSettings').viewType //get the view type from settings rather than always defaulting to ImageView }; _this.eventEmitter.publish('ADD_WINDOW', windowConfig); }); }, updateDisplay: function(newWidth) { var _this = this, newMaxPreviewWidth = newWidth - (_this.repoWidth + _this.margin + _this.metadataWidth + _this.margin + _this.remainingWidth); newMaxPreviewWidth = newMaxPreviewWidth * 0.95; var image = null; //width of browser window has been made smaller if (newMaxPreviewWidth < _this.maxPreviewImagesWidth ) { while (_this.imagesTotalWidth >= newMaxPreviewWidth) { image = _this.tplData.images.pop(); if (image) { _this.imagesTotalWidth -= (image.width + _this.margin); //remove image from dom _this.element.find('img[data-image-id="'+image.id+'"]').remove(); } else { break; } } //check if need to add ellipsis if (_this.remaining === 0 && _this.allImages.length - _this.tplData.images.length > 0) { _this.element.find('.preview-images').after('<i class="fa fa fa-ellipsis-h remaining"></i>'); } _this.remaining = _this.allImages.length - _this.tplData.images.length; } else if (newMaxPreviewWidth > _this.maxPreviewImagesWidth) { //width of browser window has been made larger var currentLastImage = _this.tplData.images[_this.tplData.images.length-1], index = currentLastImage ? currentLastImage.index+1 : 0; image = _this.allImages[index]; if (image) { while (_this.imagesTotalWidth + image.width + _this.margin < newMaxPreviewWidth) { _this.tplData.images.push(image); _this.imagesTotalWidth += (image.width + _this.margin); //add image to dom _this.element.find('.preview-images').append('<img src="'+image.url+'" width="'+image.width+'" height="'+image.height+'" class="preview-image flash" data-image-id="'+image.id+'">'); //get next image index++; image = _this.allImages[index]; if (!image) { break; } } //check if need to remove ellipsis if (_this.remaining > 0 && _this.allImages.length - _this.tplData.images.length === 0) { _this.element.find('.remaining').remove(); } _this.remaining = _this.allImages.length - _this.tplData.images.length; } } _this.maxPreviewImagesWidth = newMaxPreviewWidth; _this.eventEmitter.publish('manifestListItemRendered'); }, hide: function() { var _this = this; }, show: function() { var _this = this; }, template: $.Handlebars.compile([ '<li data-index-number={{index}}>', '<div class="repo-image">', '{{#if repoImage}}', '<img src="{{repoImage}}" alt="repoImg">', '{{else}}', '<span class="default-logo"></span>', '{{/if}}', '</div>', '<div class="select-metadata">', '<div class="manifest-title">', '<h3 title="{{{label}}}">{{{label}}}</h3>', '</div>', '<div class="item-info">', '<div class="item-info-row">', '{{#if repository}}', '<div class="repo-label">{{repository}}</div>', '{{/if}}', '<div class="canvas-count">{{canvasCount}} {{pluralize canvasCount (t "item") (t "items")}}</div>', '</div>', '</div>', '</div>', '<div class="preview-thumb">', '<div class="preview-images">', '{{#each images}}', '<img src="{{url}}" width="{{width}}" height="{{height}}" class="preview-image flash" data-image-id="{{id}}">', '{{/each}}', '</div>', '{{#if remaining}}', '<i class="fa fa fa-ellipsis-h remaining"></i>', '{{/if}}', '</div>', '</li>' ].join('')) }; }(Mirador));
import {AiFillGithub} from 'react-icons/ai' import {Badge} from 'react-bootstrap' import React from 'react' function ProjectList({ProjectListVal}) { return ( <div> {ProjectListVal && ProjectListVal.sort((a, b) => { if (a.title > b.title) return 1 if (a.title < b.title) return -1 return 0 }).map((Obj, index) => { return ( <a href={Obj.projectRoute} key={`project-list-item-${index}`} className='project_list_item_link'> <div style={{ background: `linear-gradient(120deg,` + Obj.initialColor + `,` + Obj.finalColor + `)`, }} className='project_list_item'> <h3> {Obj.title} {Obj.githubUrl && ( <a href={Obj.githubUrl}> <AiFillGithub className='projectGithubIcon' /> </a> )} </h3> {Object.keys(Obj.badgeTitle).map((item, index) => { return ( <Badge pill variant='primary' className='chip' key={index}> {Obj.badgeTitle[item]} </Badge> ) })} <p>{Obj.description}</p> </div> </a> ) })} </div> ) } export default ProjectList
var app = angular.module('siswa', ['ui.bootstrap','blockUI'], function($interpolateProvider) { $interpolateProvider.startSymbol('<%'); $interpolateProvider.endSymbol('%>'); }); app.factory('myHttpInterceptor', function($q, $window, blockUI) { return function(promise) { return promise.then(function(response) { // do something on success // todo hide the spinner blockUI.stop(); return response; }, function(response) { // do something on error // todo hide the spinner blockUI.stop(); return $q.reject(response); }); }; }) app.factory('baseURL', function($location) { return { url: function(url) { return base_url + '/' + url; } }; }); app.filter('_uriseg', function($location, baseURL) { return function(segment) { var query = $location.absUrl().replace(baseURL.url(), ""); var data = query.split("/"); if (data[segment - 1]) { return data[segment - 1]; } return false; } }); angular.module('siswa').controller('kelas', function($scope, $http, $filter, $timeout, baseURL) { $scope.kelas = {}; $scope.data = {}; $scope.show = false; $http.get(baseURL.url('api/kelasdropdown')).success(function(data) { $scope.kelas = data; }); $scope.submit = function() { $scope.show = true; $http.get(baseURL.url('api/ambilsiswa/' + $scope.data['id_kelas'])).success(function(e) { $scope.telo = e; }) } }); angular.module('siswa').controller('absensi', function($scope, $http, $filter, $timeout, baseURL) { $scope.data = {}; $scope.show = false; $scope.telo = {}; $scope.kelas = {}; $scope.date = []; $scope.tahun = []; $scope.bulan = [ {'id': 1, 'label': 'Januari'}, {'id': 2, 'label': 'Februari'}, {'id': 3, 'label': 'Maret'}, {'id': 4, 'label': 'April'}, {'id': 5, 'label': 'Mei'}, {'id': 6, 'label': 'Juni'}, {'id': 7, 'label': 'July'}, {'id': 8, 'label': 'Agustus'}, {'id': 9, 'label': 'September'}, {'id': 10, 'label': 'Oktober'}, {'id': 11, 'label': 'November'}, {'id': 12, 'label': 'Desember'}, ]; var dateobj = new Date(); $scope.data['kelas'] = 1; $scope.data['bulan'] = dateobj.getMonth() + 1; // 3 (0 = January, 3 = April) $scope.data['tahun'] = dateobj.getFullYear(); // 6 for (var t = dateobj.getFullYear() - 5; t <= dateobj.getFullYear(); t++) { var tahun = {'id': t, 'label': t}; $scope.tahun.push(tahun); } $http.get(baseURL.url('api/kelasdropdown')).success(function(data) { $scope.kelas = data; }); $scope.submit = function() { $http.post(baseURL.url('api/showabsensi'), $scope.data).success(function(e) { $scope.show = true; $scope.telo = e; }); } });
(window.webpackJsonp=window.webpackJsonp||[]).push([[3],{324:function(t,e,n){},353:function(t,e,n){"use strict";var i=n(324);n.n(i).a},363:function(t,e,n){"use strict";n.r(e);var i={functional:!0,props:{type:{type:String,default:"tip"},text:String,vertical:{type:String,default:"top"}},render:function(t,e){var n=e.props,i=e.slots;return t("span",{class:["badge",n.type],style:{verticalAlign:n.vertical}},n.text||i().default)}},r=(n(353),n(25)),a=Object(r.a)(i,void 0,void 0,!1,null,"15b7b770",null);e.default=a.exports}}]);
//? include("../Utils/$jsilcore.InitResizableArray.js"); //? include("../Utils/JSIL.$WrapIComparer.js"); $jsilcore.$ListExternals = function ($, T, type) { var mscorlib = JSIL.GetCorlib(); if (typeof (T) === "undefined") JSIL.RuntimeError("Invalid use of $ListExternals"); var getT; switch (type) { case "ArrayList": case "ObjectCollection": getT = function () { return System.Object; } break; default: getT = function (self) { return self.T; } break; } $.Method({ Static: false, Public: true }, ".ctor", JSIL.MethodSignature.Void, function () { $jsilcore.InitResizableArray(this, getT(this), 16); this._size = 0; } ); $.Method({ Static: false, Public: true }, ".ctor", new JSIL.MethodSignature(null, [mscorlib.TypeRef("System.Int32")], []), function (size) { $jsilcore.InitResizableArray(this, getT(this), size); this._size = 0; } ); $.Method({ Static: false, Public: true }, ".ctor", new JSIL.MethodSignature(null, [mscorlib.TypeRef("System.Collections.Generic.IEnumerable`1", [T])], []), function (values) { this._items = JSIL.EnumerableToArray(values, this.T); this._capacity = this._items.length; this._size = this._items.length; } ); var indexOfImpl = function List_IndexOf(value) { return JSIL.Array.IndexOf(this._items, 0, this._size, value); }; var findIndexImpl = function List_FindIndex(predicate) { for (var i = 0, l = this._size; i < l; i++) { if (predicate(this._items[i])) return i; } return -1; }; var addImpl = function (item) { this.InsertItem(this._size, item); return this._size; }; var rangeCheckImpl = function (index, size) { return (index >= 0) && (size > index); } var getItemImpl = function (index) { if (rangeCheckImpl(index, this._size)) return this._items[index]; else throw new System.ArgumentOutOfRangeException("index"); }; var removeImpl = function (item) { var index = JSIL.Array.IndexOf(this._items, 0, this._size, item); if (index === -1) return false; this.RemoveAt(index); return true; }; var getEnumeratorType = function (self) { if (self.$enumeratorType) return self.$enumeratorType; var T = getT(self); return self.$enumeratorType = System.Collections.Generic.List$b1_Enumerator.Of(T); }; var getEnumeratorImpl = function () { var enumeratorType = getEnumeratorType(this); return new enumeratorType(this); }; switch (type) { case "ArrayList": case "ObjectCollection": $.Method({ Static: false, Public: true }, "Add", new JSIL.MethodSignature($.Int32, [T], []), addImpl ); break; default: $.Method({ Static: false, Public: true }, "Add", new JSIL.MethodSignature(null, [T], []), addImpl ); break; } $.Method({ Static: false, Public: true }, "AddRange", new JSIL.MethodSignature(null, [mscorlib.TypeRef("System.Collections.Generic.IEnumerable`1", [T])], []), function (items) { var e = JSIL.GetEnumerator(items, this.T); var moveNext = $jsilcore.System.Collections.IEnumerator.MoveNext; var getCurrent = $jsilcore.System.Collections.IEnumerator.get_Current; try { while (moveNext.Call(e)) this.Add(getCurrent.Call(e)); } finally { JSIL.Dispose(e); } } ); $.Method({ Static: false, Public: true }, "AsReadOnly", new JSIL.MethodSignature(mscorlib.TypeRef("System.Collections.ObjectModel.ReadOnlyCollection`1", [T]), [], []), function () { // FIXME if (typeof (this.tReadOnlyCollection) === "undefined") { this.tReadOnlyCollection = System.Collections.ObjectModel.ReadOnlyCollection$b1.Of(this.T).__Type__; } return JSIL.CreateInstanceOfType(this.tReadOnlyCollection, "$listCtor", [this]); } ); $.Method({ Static: false, Public: true }, "Clear", JSIL.MethodSignature.Void, function () { this.ClearItems(); } ); $.Method({ Static: false, Public: true }, "set_Capacity", new JSIL.MethodSignature(null, [$.Int32], []), function List_set_Capacity(value) { // FIXME return; } ); $.Method({ Static: false, Public: true }, "Contains", new JSIL.MethodSignature(mscorlib.TypeRef("System.Boolean"), [T], []), function List_Contains(value) { return this.IndexOf(value) >= 0; } ); $.Method({ Static: false, Public: true }, "Exists", new JSIL.MethodSignature(mscorlib.TypeRef("System.Boolean"), [mscorlib.TypeRef("System.Predicate`1", [T])], []), function List_Exists(predicate) { return this.FindIndex(predicate) >= 0; } ); $.Method({ Static: false, Public: true }, "ForEach", new JSIL.MethodSignature(null, [$jsilcore.TypeRef("System.Action`1", [T])], []), function ForEach(action) { for (var i = 0, sz = this._size; i < sz; i++) { var item = this._items[i]; action(item); } } ); $.Method({ Static: false, Public: true }, "Find", new JSIL.MethodSignature(T, [mscorlib.TypeRef("System.Predicate`1", [T])], []), function List_Find(predicate) { var index = this.FindIndex(predicate); if (index >= 0) return this._items[index]; else return JSIL.DefaultValue(this.T); } ); $.Method({ Static: false, Public: true }, "FindAll", new JSIL.MethodSignature(mscorlib.TypeRef("System.Collections.Generic.List`1", [T]), [mscorlib.TypeRef("System.Predicate`1", [T])], []), function (predicate) { var thisType = this.GetType(); // Manually initialize the result since we don't want to hassle with overloaded ctors var result = JSIL.CreateInstanceOfType(thisType, null); result._items = []; for (var i = 0, sz = this._size; i < sz; i++) { var item = this._items[i]; if (predicate(item)) result._items.push(item); } result._capacity = result._size = result._items.length; return result; } ); $.Method({ Static: false, Public: true }, "FindIndex", new JSIL.MethodSignature(mscorlib.TypeRef("System.Int32"), [mscorlib.TypeRef("System.Predicate`1", [T])], []), findIndexImpl ); $.Method({ Static: false, Public: true }, "get_Capacity", new JSIL.MethodSignature(mscorlib.TypeRef("System.Int32"), [], []), function () { return this._items.length; } ); $.Method({ Static: false, Public: true }, "get_Count", new JSIL.MethodSignature(mscorlib.TypeRef("System.Int32"), [], []), function () { return this._size; } ); $.Method({ Static: false, Public: true }, "get_Item", new JSIL.MethodSignature(T, [mscorlib.TypeRef("System.Int32")], []), getItemImpl ); if (type != "ArrayList") { $.Method( { Static: false, Public: false }, null, new JSIL.MethodSignature($.Int32, [$.Object], []), addImpl ).Overrides("System.Collections.IList", "Add"); $.Method({ Static: false, Public: true }, null, new JSIL.MethodSignature($.Object, [mscorlib.TypeRef("System.Int32")], []), getItemImpl ) .Overrides("System.Collections.IList", "get_Item"); $.Method({ Static: false, Public: true }, null, new JSIL.MethodSignature(null, [mscorlib.TypeRef("System.Int32"), $.Object], []), function (index, value) { if (rangeCheckImpl(index, this._size)) this.SetItem(index, this.T.$Cast(value)); else throw new System.ArgumentOutOfRangeException("index"); } ) .Overrides("System.Collections.IList", "set_Item"); $.Method({ Static: false, Public: false }, null, new JSIL.MethodSignature(null, [$.Int32, $.Object], []), function (index, item) { this.InsertItem(index, item); } ).Overrides("System.Collections.IList", "Insert"); $.Method({ Static: false, Public: false }, null, new JSIL.MethodSignature($.Int32, [$.Object], []), indexOfImpl ).Overrides("System.Collections.IList", "IndexOf"); $.Method({ Static: false, Public: false }, null, new JSIL.MethodSignature(null, [$.Object], []), removeImpl ).Overrides("System.Collections.IList", "Remove"); $.Method({ Static: false, Public: true }, "InsertRange", new JSIL.MethodSignature(null, [$.Int32, mscorlib.TypeRef("System.Collections.Generic.IEnumerable`1", [T])], []), function (index, items) { var e = JSIL.GetEnumerator(items, this.T); var moveNext = $jsilcore.System.Collections.IEnumerator.MoveNext; var getCurrent = $jsilcore.System.Collections.IEnumerator.get_Current; try { var i = index; while (moveNext.Call(e)) this.InsertItem(i++, getCurrent.Call(e)); } finally { JSIL.Dispose(e); } } ); var reverseImpl = function (index, count) { if (arguments.length < 2) { index = 0; count = this._size | 0; } else { index |= 0; count |= 0; } if (count < 1) return; for (var i = index, l = (index + count - 1) | 0; i < l; i++, l--) { var a = this._items[i]; var b = this._items[l]; this._items[i] = b; this._items[l] = a; } } $.Method({ Static: false, Public: true }, "Reverse", new JSIL.MethodSignature(null, [], []), reverseImpl ); $.Method({ Static: false, Public: true }, "Reverse", new JSIL.MethodSignature(null, [$.Int32, $.Int32], []), reverseImpl ); } $.Method({ Static: false, Public: true }, "set_Item", new JSIL.MethodSignature(null, [mscorlib.TypeRef("System.Int32"), T], []), function (index, value) { if (rangeCheckImpl(index, this._size)) this.SetItem(index, value); else throw new System.ArgumentOutOfRangeException("index"); } ); switch (type) { case "List": $.Method({ Static: false, Public: true }, "GetEnumerator", (new JSIL.MethodSignature(mscorlib.TypeRef("System.Collections.Generic.List`1+Enumerator", [T]), [], [])), getEnumeratorImpl ); $.Method({ Static: false, Public: true }, null, new JSIL.MethodSignature(mscorlib.TypeRef("System.Collections.Generic.IEnumerator`1", [T]), [], []), getEnumeratorImpl ) .Overrides("System.Collections.Generic.IEnumerable`1", "GetEnumerator"); break; case "ArrayList": break; default: $.Method({ Static: false, Public: true }, "GetEnumerator", new JSIL.MethodSignature(mscorlib.TypeRef("System.Collections.Generic.IEnumerator`1", [T]), [], []), getEnumeratorImpl ) .Overrides("System.Collections.Generic.IEnumerable`1", "GetEnumerator"); break; } $.Method({ Static: false, Public: false }, null, new JSIL.MethodSignature(mscorlib.TypeRef("System.Collections.IEnumerator"), [], []), getEnumeratorImpl ) .Overrides("System.Collections.IEnumerable", "GetEnumerator"); $.RawMethod(false, "$GetEnumerator", getEnumeratorImpl); $.Method({ Static: false, Public: true }, "Insert", (new JSIL.MethodSignature(null, [$.Int32, T], [])), function Insert(index, item) { this.InsertItem(index, item); } ); $.Method({ Static: false, Public: true }, "IndexOf", new JSIL.MethodSignature(mscorlib.TypeRef("System.Int32"), [T], []), indexOfImpl ); switch (type) { case "ArrayList": case "ObjectCollection": $.Method({ Static: false, Public: true }, "Remove", new JSIL.MethodSignature(null, [T], []), removeImpl ); break; default: $.Method({ Static: false, Public: true }, "Remove", new JSIL.MethodSignature(mscorlib.TypeRef("System.Boolean"), [T], []), removeImpl ); break; } $.Method({ Static: false, Public: true }, "RemoveAll", new JSIL.MethodSignature(mscorlib.TypeRef("System.Int32"), [mscorlib.TypeRef("System.Predicate`1", [T])], []), function (predicate) { var result = 0; for (var i = 0; i < this._size; i++) { var item = this._items[i]; if (predicate(item)) { this.RemoveItem(i); i -= 1; result += 1; } } return result; } ); $.Method({ Static: false, Public: true }, "RemoveAt", new JSIL.MethodSignature(null, [mscorlib.TypeRef("System.Int32")], []), function (index) { if (!rangeCheckImpl(index, this._size)) throw new System.ArgumentOutOfRangeException("index"); this.RemoveItem(index); } ); $.Method({ Static: false, Public: true }, "RemoveRange", new JSIL.MethodSignature(null, [mscorlib.TypeRef("System.Int32"), mscorlib.TypeRef("System.Int32")], []), function (index, count) { if (index < 0) throw new System.ArgumentOutOfRangeException("index"); else if (count < 0) throw new System.ArgumentOutOfRangeException("count"); else if (!rangeCheckImpl(index, this._size)) throw new System.ArgumentException(); else if (!rangeCheckImpl(index + count - 1, this._size)) throw new System.ArgumentException(); this._items.splice(index, count); this._size -= count; } ); $.Method({ Static: false, Public: true }, "Sort", JSIL.MethodSignature.Void, function () { this._items.length = this._size; this._items.sort(JSIL.CompareValues); } ); $.Method({ Static: false, Public: true }, "Sort", new JSIL.MethodSignature(null, [mscorlib.TypeRef("System.Comparison`1", [T])], []), function (comparison) { this._items.length = this._size; this._items.sort(comparison); } ); $.Method({ Static: false, Public: true }, "Sort", (new JSIL.MethodSignature(null, [$jsilcore.TypeRef("System.Collections.IComparer")], [])), function Sort(comparer) { this._items.length = this._size; this._items.sort(JSIL.$WrapIComparer(null, comparer)); } ); $.Method({ Static: false, Public: true }, "Sort", (new JSIL.MethodSignature(null, [$jsilcore.TypeRef("System.Collections.Generic.IComparer`1", [T])], [])), function Sort(comparer) { this._items.length = this._size; this._items.sort(JSIL.$WrapIComparer(this.T, comparer)); } ); $.Method({ Static: false, Public: true }, "BinarySearch", (new JSIL.MethodSignature($.Int32, [ $.Int32, $.Int32, T, $jsilcore.TypeRef("System.Collections.Generic.IComparer`1", [T]) ], [])), function BinarySearch(index, count, item, comparer) { return JSIL.BinarySearch( this.T, this._items, index, count, item, comparer ); } ); $.Method({ Static: false, Public: true }, "BinarySearch", (new JSIL.MethodSignature($.Int32, [T], [])), function BinarySearch(item) { return JSIL.BinarySearch( this.T, this._items, 0, this._size, item, null ); } ); $.Method({ Static: false, Public: true }, "BinarySearch", (new JSIL.MethodSignature($.Int32, [ T, $jsilcore.TypeRef("System.Collections.Generic.IComparer`1", [T]) ], [])), function BinarySearch(item, comparer) { return JSIL.BinarySearch( this.T, this._items, 0, this._size, item, comparer ); } ); $.Method({ Static: false, Public: true }, "ToArray", new JSIL.MethodSignature($jsilcore.TypeRef("System.Array", [T]), [], []), function () { var result = JSIL.Array.New(this.T, this._size); for (var i = 0, l = this._size, items = this._items; i < l; i++) { result[i] = items[i]; } return result; } ); $.Method({ Static: false, Public: true }, "TrueForAll", new JSIL.MethodSignature(mscorlib.TypeRef("System.Boolean"), [mscorlib.TypeRef("System.Predicate`1", [T])], []), function (predicate) { for (var i = 0; i < this._size; i++) { var item = this._items[i]; if (!predicate(item)) return false; } return true; } ); $.Method({ Static: false, Public: false, Virtual: true }, "ClearItems", JSIL.MethodSignature.Void, function ClearItems() { // Necessary to clear any element values. var oldLength = this._items.length; this._items.length = 0; this._items.length = oldLength; this._size = 0; } ); $.Method({ Static: false, Public: false, Virtual: true }, "InsertItem", new JSIL.MethodSignature(null, [$.Int32, new JSIL.GenericParameter("T", "System.Collections.ObjectModel.Collection`1")], []), function InsertItem(index, item) { index = index | 0; if (index >= this._items.length) { this._items.push(item); } else if (index >= this._size) { this._items[index] = item; } else { this._items.splice(index, 0, item); } this._size += 1; if (this.$OnItemAdded) this.$OnItemAdded(item); } ); $.Method({ Static: false, Public: false, Virtual: true }, "RemoveItem", new JSIL.MethodSignature(null, [$.Int32], []), function RemoveItem(index) { this._items.splice(index, 1); this._size -= 1; } ); $.Method({ Static: false, Public: false, Virtual: true }, "SetItem", new JSIL.MethodSignature(null, [$.Int32, new JSIL.GenericParameter("T", "System.Collections.ObjectModel.Collection`1")], []), function SetItem(index, item) { this._items[index] = item; } ); };
import Ext_Base from '../../Ext/Base.js'; export default class Ext_route_Router extends Ext_Base { static PROPERTIES() { return [ 'hashBang', 'multipleToken', 'queueRoutes', ]}; static EVENTS() { return [ {name:'ready', parameters:'cmd,cmdAll'} ]}; static getProperties(properties) { properties = properties.concat(Ext_route_Router.PROPERTIES()); return Ext_Base.getProperties(properties); } static getEvents(events) { events = events.concat(Ext_route_Router.EVENTS()); return Ext_Base.getEvents(events); } static get observedAttributes() { var attrs = super.observedAttributes Ext_route_Router.PROPERTIES().forEach(function (property, index, array) { attrs.push(property) }) Ext_route_Router.EVENTS().forEach(function (eventparameter, index, array) { attrs.push('on' + eventparameter.name) }) return attrs } constructor(properties, events) { super ( properties.concat(Ext_route_Router.PROPERTIES()), events.concat(Ext_route_Router.EVENTS()) ) } connectedCallback() { super.connectedCallback() } attributeChangedCallback(attrName, oldVal, newVal) { super.attributeChangedCallback(attrName, oldVal, newVal) } }
// vue.config.js module.exports = { lintOnSave: true, pwa: { workboxOptions: { importScripts: ['sw-push-notifications.js'] } }, pluginOptions: { quasar: { treeShake: true } }, devServer: { host: '127.0.0.1' }, transpileDependencies: [ /[\\\/]node_modules[\\\/]quasar[\\\/]/ ] }
const yaml = require('js-yaml') , fs = require('fs') , { promisify } = require('util') , readAsync = promisify(fs.readFile) , existsAsync = promisify(fs.exists) , writeAsync = promisify(fs.writeFile) async function pm2yaml(dat) { const info = dat.info delete info._postman_id delete info.schema const steps = [] dat.item.map(item => { // TODO: handle folder const evt = {} if (item.event) item.event.map(e => { const s = e.script.exec.join('\n').replace(/\r/g, '') if (s.trim().length) evt[e.listen] = s }) delete item.event const o = {} , req = { ...item.request } delete item.request if (item.response && item.response.length < 1) delete item.response const headers = req.header.reduce((p, c) => { p[c.key] = c.value return p }, {}) delete req.body.mode const fdata = req.body.formdata let body = req.body.raw if (body) { if (isJsonContent(headers)) { req.body.raw = JSON.stringify(JSON.parse(body), null, 2) } else req.body.raw = body.replace(/[\r\t]/g, ' ') } else if (Array.isArray(fdata)) { // remove empty formdata entries req.body.formdata = fdata.filter(r => r.key.length) } o[item.name] = { [req.method]: req.url.raw || req.url, headers, body: req.body, ...evt, ...item } delete o[item.name].name steps.push(o) }) return makeYaml({ ...info, steps }) } function makeYaml({ name, description, steps }) { const out = { name, description: description || '', ver: '1.0.0', steps } return yaml.dump(out) } const rxSchema = /\/v2.[0-9].0\/collection.json/g async function loadJson(fn) { let t = await readAsync(fn) try { const pm = JSON.parse(t) let ok = pm.info && pm.info.schema && rxSchema.test(pm.info.schema) if (ok) ok = Array.isArray(pm.item) && pm.item.length if (ok) ok = pm.item[0].request || pm.item[0].item if (ok) { const dat = await pm2yaml(pm) const newfn = `${fn.substr(0, fn.length - 5)}.yaml` await writeAsync(newfn, dat) console.log(`👍 ${newfn} saved`) } else console.error(fn, 'Expected Postman ver 2.1.0 collection') } catch (err) { console.error(fn, err.stack) } } async function loadYaml(fn, isRun) { const { processInclude, setVars } = require('./macros') let t = await readAsync(fn) try { const dat = yaml.load(t) , { name, description } = dat , pm = { info: { name, description, schema: 'https://schema.getpostman.com/json/collection/v2.1.0/collection.json' }, item: [], } , vars = {} dat.steps.map(step => { if (typeof step === 'string') { if (setVars(step, vars)) return // include(file, [step, step]) return processInclude(step, pm) } makeStep(step, pm, vars) }) // const fn2 = `${isRun ? `${fn}_${+new Date()}` : fn.substr(0, fn.length - 5)}.json` let fn2 = `${fn.substr(0, fn.length - 5)}.json` if (await existsAsync(fn2)) fn2 = `${fn.substr(0, fn.length - 5)}_${+new Date()}.json` await writeAsync(fn2, JSON.stringify(pm, null, 2)) return fn2 } catch (err) { console.error(fn, ':', err.stack) } return null } function makeStep(step, pm, vars) { const det = Object.values(step)[0] det.body = det.body || {} const fdata = det.body.formdata delete det.body.mode det.body.mode = Object.keys(det.body)[0] if (Array.isArray(fdata)) { det.body.formdata = fdata.map(r => { if (typeof f !== 'string') return r return processFile(r) }).filter(r => r) } const request = { header: Object.keys(det.headers).map(key => ({ key, type: 'text', value: det.headers[key] })), body: det.body } if (vars) { const presets = [] Object.keys(vars).map(k => { let v = vars[k] if (typeof v === 'string') v = `'${v}'` presets.push(`pm.variables.set('${k}', ${v});`) }) if (presets.length) det.prerequest = `${presets.join('\n')}\n${det.prerequest || ''}` } const event = [] addEvent('prerequest', event, det) addEvent('test', event, det) // console.log('event', det.prequest, event) const VERBS = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'TRACE', 'OPTIONS', 'COPY', 'LINK', 'UNLINK', 'PURGE', 'LOCK', 'UNLOCK', 'PROPFIND', 'VIEW'] VERBS.map(v => { if (!det[v]) return const url = det[v].split('/') request.method = v request.url = { raw: det[v], host: [url[0]], path: url.slice(1) } }) const name = Object.keys(step)[0] // console.log('>>', name) pm.item.push({ name, event, protocolProfileBehavior: det.protocolProfileBehavior, request, response: det.response }) } function addEvent(key, events, det) { // console.log('addevent', key, det[key] !== undefined) if (!det[key]) return events.push({ listen: key, script: { exec: det[key].split('\n'), type: "text/javascript" } }) } const rxFile = /file\(([A-Za-z,._\-0-9\ \/\=]*)\)/gm async function processFile(text) { const m = rxFile.exec(text) const file = m[1] if (!file) return null return { key: 'file', description: file, type: 'file', src: file } } function isJsonContent(headers) { const mime = 'application/json' return headers['content-type'] === mime || headers['Content-Type'] === mime } module.exports = { loadJson, loadYaml, isJsonContent, makeYaml, makeStep }
module.exports = { token: 'NjkzNTM5NjQ0Mzk0MTc2NTQz.Xn_6jA.I6_VD2fPrNwII5n_fuYvD-Thr_w', clockchannel: '693533177414811730', timezone: 'Asia/Kolkata', format: 'HH:mm (z)', updateinterval: 60000, }
<!-- Web script --> $(document).ready(function(){ // Add smooth scrolling to all links in navbar + footer link $(".navbar a, footer a[href='#myPage']").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 (900) specifies the number of milliseconds it takes to scroll to the specified area $('html, body').animate({ scrollTop: $(hash).offset().top }, 900, function(){ // Add hash (#) to URL when done scrolling (default click behavior) window.location.hash = hash; }); } // End if }); $(window).scroll(function() { $(".slideanim").each(function(){ var pos = $(this).offset().top; var winTop = $(window).scrollTop(); if (pos < winTop + 600) { $(this).addClass("slide"); } }); }); })
/* 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 React from "react"; import { render, fireEvent } from "@testing-library/react"; import ChordToolbar from "./chordToolbar"; it("renders a ChordToolbar", () => { const routerName = "testRouterName"; const props = { isRate: true, byAddress: true, handleAddNotification: () => {}, handleChangeOption: () => {}, addresses: { testAddress: true }, chordColors: { testAddress: "#EAEAEA" }, arcColors: { testRouterName: "#EBAEBA" }, handleChangeAddress: () => {}, handleHoverAddress: () => {}, handleHoverRouter: () => {} }; const { getByLabelText, getByText, getByTestId } = render(<ChordToolbar {...props} />); // the toolbar should be present expect(getByTestId("chord-toolbar")).toBeInTheDocument(); // the options drowdown button should be present const optionsButton = getByLabelText("button-for-Options"); expect(optionsButton).toBeInTheDocument(); fireEvent.click(optionsButton); // clicking on the options buttons should show the address panel const showByAddressCheckbox = getByLabelText("show by address"); expect(showByAddressCheckbox).toBeInTheDocument(); expect(getByText("testAddress")).toBeInTheDocument(); // the options drowdown button should be present const routersButton = getByLabelText("button-for-Routers"); expect(routersButton).toBeInTheDocument(); fireEvent.click(routersButton); // clicking on the Routers buttons should show the list of routers expect(getByText(routerName)).toBeInTheDocument(); });
module.exports = function ( grunt ) { /** * Load required Grunt tasks. These are installed based on the versions listed * in `package.json` when you do `npm install` in this directory. */ grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-coffee'); grunt.loadNpmTasks('grunt-contrib-less'); grunt.loadNpmTasks('grunt-conventional-changelog'); grunt.loadNpmTasks('grunt-bump'); grunt.loadNpmTasks('grunt-coffeelint'); grunt.loadNpmTasks('grunt-karma'); grunt.loadNpmTasks('grunt-ngmin'); grunt.loadNpmTasks('grunt-html2js'); /** * Load in our build configuration file. */ var userConfig = require( './build.config.js' ); /** * This is the configuration object Grunt uses to give each plugin its * instructions. */ var taskConfig = { /** * We read in our `package.json` file so we can access the package name and * version. It's already there, so we don't repeat ourselves here. */ pkg: grunt.file.readJSON("package.json"), /** * The banner is the comment that is placed at the top of our compiled * source files. It is first processed as a Grunt template, where the `<%=` * pairs are evaluated based on this very configuration object. */ meta: { banner: '/**\n' + ' * <%= pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %>\n' + ' * <%= pkg.homepage %>\n' + ' *\n' + ' * Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author %>\n' + ' * Licensed <%= pkg.licenses.type %> <<%= pkg.licenses.url %>>\n' + ' */\n' }, /** * Creates a changelog on a new version. */ changelog: { options: { dest: 'CHANGELOG.md', template: 'changelog.tpl' } }, /** * Increments the version number, etc. */ bump: { options: { files: [ "package.json", "bower.json" ], commit: false, commitMessage: 'chore(release): v%VERSION%', commitFiles: [ "package.json", "client/bower.json" ], createTag: false, tagName: 'v%VERSION%', tagMessage: 'Version %VERSION%', push: false, pushTo: 'origin' } }, /** * The directories to delete when `grunt clean` is executed. */ clean: [ '<%= build_dir %>', '<%= compile_dir %>' ], /** * The `copy` task just copies files from A to B. We use it here to copy * our project assets (images, fonts, etc.) and javascripts into * `build_dir`, and then to copy the assets to `compile_dir`. */ copy: { build_app_assets: { files: [ { src: [ '**' ], dest: '<%= build_dir %>/assets/', cwd: 'src/assets', expand: true } ] }, build_vendor_assets: { files: [ { src: [ '<%= vendor_files.assets %>' ], dest: '<%= build_dir %>/assets/', cwd: '.', expand: true, flatten: true } ] }, build_appjs: { files: [ { src: [ '<%= app_files.js %>' ], dest: '<%= build_dir %>/', cwd: '.', expand: true } ] }, build_vendorjs: { files: [ { src: [ '<%= vendor_files.js %>' ], dest: '<%= build_dir %>/', cwd: '.', expand: true } ] }, compile_assets: { files: [ { src: [ '**' ], dest: '<%= compile_dir %>/assets', cwd: '<%= build_dir %>/assets', expand: true } ] } }, /** * `grunt concat` concatenates multiple source files into a single file. */ concat: { /** * The `build_css` target concatenates compiled CSS and vendor CSS * together. */ build_css: { src: [ '<%= vendor_files.css %>', '<%= build_dir %>/assets/<%= pkg.name %>-<%= pkg.version %>.css' ], dest: '<%= build_dir %>/assets/<%= pkg.name %>-<%= pkg.version %>.css' }, /** * The `compile_js` target is the concatenation of our application source * code and all specified vendor source code into a single file. */ compile_js: { options: { banner: '<%= meta.banner %>' }, src: [ '<%= vendor_files.js %>', 'module.prefix', '<%= build_dir %>/src/**/*.js', '<%= html2js.app.dest %>', '<%= html2js.common.dest %>', 'module.suffix' ], dest: '<%= compile_dir %>/assets/<%= pkg.name %>-<%= pkg.version %>.js' } }, /** * `grunt coffee` compiles the CoffeeScript sources. To work well with the * rest of the build, we have a separate compilation task for sources and * specs so they can go to different places. For example, we need the * sources to live with the rest of the copied JavaScript so we can include * it in the final build, but we don't want to include our specs there. */ coffee: { source: { options: { bare: true }, expand: true, cwd: '.', src: [ '<%= app_files.coffee %>' ], dest: '<%= build_dir %>', ext: '.js' } }, /** * `ng-min` annotates the sources before minifying. That is, it allows us * to code without the array syntax. */ ngmin: { compile: { files: [ { src: [ '<%= app_files.js %>' ], cwd: '<%= build_dir %>', dest: '<%= build_dir %>', expand: true } ] } }, /** * Minify the sources! */ uglify: { compile: { options: { banner: '<%= meta.banner %>' }, files: { '<%= concat.compile_js.dest %>': '<%= concat.compile_js.dest %>' } } }, /** * `grunt-contrib-less` handles our LESS compilation and uglification automatically. * Only our `main.less` file is included in compilation; all other files * must be imported from this file. */ less: { build: { files: { '<%= build_dir %>/assets/<%= pkg.name %>-<%= pkg.version %>.css': '<%= app_files.less %>' } }, compile: { files: { '<%= build_dir %>/assets/<%= pkg.name %>-<%= pkg.version %>.css': '<%= app_files.less %>' }, options: { cleancss: true, compress: true } } }, /** * `jshint` defines the rules of our linter as well as which files we * should check. This file, all javascript sources, and all our unit tests * are linted based on the policies listed in `options`. But we can also * specify exclusionary patterns by prefixing them with an exclamation * point (!); this is useful when code comes from a third party but is * nonetheless inside `src/`. */ jshint: { src: [ '<%= app_files.js %>' ], test: [ '<%= app_files.jsunit %>' ], gruntfile: [ 'Gruntfile.js' ], options: { curly: true, immed: true, newcap: true, noarg: true, sub: true, boss: true, eqnull: true }, globals: {} }, /** * `coffeelint` does the same as `jshint`, but for CoffeeScript. * CoffeeScript is not the default in ngBoilerplate, so we're just using * the defaults here. */ coffeelint: { src: { files: { src: [ '<%= app_files.coffee %>' ] } }, test: { files: { src: [ '<%= app_files.coffeeunit %>' ] } } }, /** * HTML2JS is a Grunt plugin that takes all of your template files and * places them into JavaScript files as strings that are added to * AngularJS's template cache. This means that the templates too become * part of the initial payload as one JavaScript file. Neat! */ html2js: { /** * These are the templates from `src/app`. */ app: { options: { base: 'src/app' }, src: [ '<%= app_files.atpl %>' ], dest: '<%= build_dir %>/templates-app.js' }, /** * These are the templates from `src/common`. */ common: { options: { base: 'src/common' }, src: [ '<%= app_files.ctpl %>' ], dest: '<%= build_dir %>/templates-common.js' } }, /** * The Karma configurations. */ karma: { options: { configFile: '<%= build_dir %>/karma-unit.js' }, unit: { port: 9019, background: true }, continuous: { singleRun: true } }, /** * The `index` task compiles the `index.html` file as a Grunt template. CSS * and JS files co-exist here but they get split apart later. */ index: { /** * During development, we don't want to have wait for compilation, * concatenation, minification, etc. So to avoid these steps, we simply * add all script files directly to the `<head>` of `index.html`. The * `src` property contains the list of included files. */ build: { dir: '<%= build_dir %>', src: [ '<%= vendor_files.js %>', '<%= build_dir %>/src/**/*.js', '<%= html2js.common.dest %>', '<%= html2js.app.dest %>', '<%= vendor_files.css %>', '<%= build_dir %>/assets/<%= pkg.name %>-<%= pkg.version %>.css' ] }, /** * When it is time to have a completely compiled application, we can * alter the above to include only a single JavaScript and a single CSS * file. Now we're back! */ compile: { dir: '<%= compile_dir %>', src: [ '<%= concat.compile_js.dest %>', '<%= vendor_files.css %>', '<%= build_dir %>/assets/<%= pkg.name %>-<%= pkg.version %>.css' ] } }, /** * This task compiles the karma template so that changes to its file array * don't have to be managed manually. */ karmaconfig: { unit: { dir: '<%= build_dir %>', src: [ '<%= vendor_files.js %>', '<%= html2js.app.dest %>', '<%= html2js.common.dest %>', '<%= test_files.js %>' ] } }, /** * And for rapid development, we have a watch set up that checks to see if * any of the files listed below change, and then to execute the listed * tasks when they do. This just saves us from having to type "grunt" into * the command-line every time we want to see what we're working on; we can * instead just leave "grunt watch" running in a background terminal. Set it * and forget it, as Ron Popeil used to tell us. * * But we don't need the same thing to happen for all the files. */ delta: { /** * By default, we want the Live Reload to work for all tasks; this is * overridden in some tasks (like this file) where browser resources are * unaffected. It runs by default on port 35729, which your browser * plugin should auto-detect. */ options: { livereload: true }, /** * When the Gruntfile changes, we just want to lint it. In fact, when * your Gruntfile changes, it will automatically be reloaded! */ gruntfile: { files: 'Gruntfile.js', tasks: [ 'jshint:gruntfile' ], options: { livereload: false } }, /** * When our JavaScript source files change, we want to run lint them and * run our unit tests. */ jssrc: { files: [ '<%= app_files.js %>' ], tasks: [ 'jshint:src', 'karma:unit:run', 'copy:build_appjs' ] }, /** * When our CoffeeScript source files change, we want to run lint them and * run our unit tests. */ coffeesrc: { files: [ '<%= app_files.coffee %>' ], tasks: [ 'coffeelint:src', 'coffee:source', 'karma:unit:run', 'copy:build_appjs' ] }, /** * When assets are changed, copy them. Note that this will *not* copy new * files, so this is probably not very useful. */ assets: { files: [ 'src/assets/**/*' ], tasks: [ 'copy:build_app_assets', 'copy:build_vendor_assets' ] }, /** * When index.html changes, we need to compile it. */ html: { files: [ '<%= app_files.html %>' ], tasks: [ 'index:build' ] }, /** * When our templates change, we only rewrite the template cache. */ tpls: { files: [ '<%= app_files.atpl %>', '<%= app_files.ctpl %>' ], tasks: [ 'html2js' ] }, /** * When the CSS files change, we need to compile and minify them. */ less: { files: [ 'src/**/*.less' ], tasks: [ 'less:build' ] }, /** * When a JavaScript unit test file changes, we only want to lint it and * run the unit tests. We don't want to do any live reloading. */ jsunit: { files: [ '<%= app_files.jsunit %>' ], tasks: [ 'jshint:test', 'karma:unit:run' ], options: { livereload: false } }, /** * When a CoffeeScript unit test file changes, we only want to lint it and * run the unit tests. We don't want to do any live reloading. */ coffeeunit: { files: [ '<%= app_files.coffeeunit %>' ], tasks: [ 'coffeelint:test', 'karma:unit:run' ], options: { livereload: false } } } }; grunt.initConfig( grunt.util._.extend( taskConfig, userConfig ) ); /** * In order to make it safe to just compile or copy *only* what was changed, * we need to ensure we are starting from a clean, fresh build. So we rename * the `watch` task to `delta` (that's why the configuration var above is * `delta`) and then add a new task called `watch` that does a clean build * before watching for changes. */ grunt.renameTask( 'watch', 'delta' ); grunt.registerTask( 'watch', [ 'build', 'karma:unit', 'delta' ] ); /** * The default task is to build and compile. */ grunt.registerTask( 'default', [ 'build', 'compile' ] ); /** * The `build` task gets your app ready to run for development and testing. */ grunt.registerTask( 'build', [ 'clean', 'html2js', 'jshint', 'coffeelint', 'coffee', 'less:build', 'concat:build_css', 'copy:build_app_assets', 'copy:build_vendor_assets', 'copy:build_appjs', 'copy:build_vendorjs', 'index:build', 'karmaconfig', 'karma:continuous' ]); /** * The `compile` task gets your app ready for deployment by concatenating and * minifying your code. */ grunt.registerTask( 'compile', [ 'less:compile', 'copy:compile_assets', 'ngmin', 'concat:compile_js', 'uglify', 'index:compile' ]); /** * A utility function to get all app JavaScript sources. */ function filterForJS ( files ) { return files.filter( function ( file ) { return file.match( /\.js$/ ); }); } /** * A utility function to get all app CSS sources. */ function filterForCSS ( files ) { return files.filter( function ( file ) { return file.match( /\.css$/ ); }); } /** * The index.html template includes the stylesheet and javascript sources * based on dynamic names calculated in this Gruntfile. This task assembles * the list into variables for the template to use and then runs the * compilation. */ grunt.registerMultiTask( 'index', 'Process index.html template', function () { var dirRE = new RegExp( '^('+grunt.config('build_dir')+'|'+grunt.config('compile_dir')+')\/', 'g' ); var jsFiles = filterForJS( this.filesSrc ).map( function ( file ) { return file.replace( dirRE, '' ); }); var cssFiles = filterForCSS( this.filesSrc ).map( function ( file ) { return file.replace( dirRE, '' ); }); grunt.file.copy('src/index.html', this.data.dir + '/index.html', { process: function ( contents, path ) { return grunt.template.process( contents, { data: { scripts: jsFiles, styles: cssFiles, version: grunt.config( 'pkg.version' ) } }); } }); }); /** * In order to avoid having to specify manually the files needed for karma to * run, we use grunt to manage the list for us. The `karma/*` files are * compiled as grunt templates for use by Karma. Yay! */ grunt.registerMultiTask( 'karmaconfig', 'Process karma config templates', function () { var jsFiles = filterForJS( this.filesSrc ); grunt.file.copy( 'karma/karma-unit.tpl.js', grunt.config( 'build_dir' ) + '/karma-unit.js', { process: function ( contents, path ) { return grunt.template.process( contents, { data: { scripts: jsFiles } }); } }); }); };
const mix = require('laravel-mix'); /* |-------------------------------------------------------------------------- | Mix Asset Management |-------------------------------------------------------------------------- | | Mix provides a clean, fluent API for defining some Webpack build steps | for your Laravel application. By default, we are compiling the Sass | file for the application as well as bundling up all the JS files. | */ mix .styles([ 'resources/vendor/fontawesome-free-5.15.1-web/css/all.min.css', 'resources/css/adminlte.css', ],'public/css/app.css') .js('resources/js/app.js', 'public/js') .scripts([ 'resources/vendor/jquery/jquery.min.js', 'resources/vendor/bootstrap/js/bootstrap.bundle.min.js', ],'public/js/vendor.js') .copy('resources/vendor/fontawesome-free-5.15.1-web/webfonts','public/webfonts') .copy('resources/img','public/img') // .sass('resources/sass/app.scss', 'public/css'); .version() ;
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.NullLanguageService = undefined; var _rxjs = require('rxjs'); // An implementation of LanguageService which always returns no results. // Useful for implementing aggregate language services. /** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * * @format */ class NullLanguageService { getDiagnostics(fileVersion) { return Promise.resolve(null); } observeDiagnostics() { return _rxjs.Observable.empty().publish(); } getAutocompleteSuggestions(fileVersion, position, request) { return Promise.resolve(null); } getDefinition(fileVersion, position) { return Promise.resolve(null); } findReferences(fileVersion, position) { return _rxjs.Observable.of(null).publish(); } getCoverage(filePath) { return Promise.resolve(null); } getOutline(fileVersion) { return Promise.resolve(null); } getAdditionalLogFiles(deadline) { return Promise.resolve([]); } getCodeActions(fileVersion, range, diagnostics) { return Promise.resolve([]); } typeHint(fileVersion, position) { return Promise.resolve(null); } highlight(fileVersion, position) { return Promise.resolve(null); } formatSource(fileVersion, range, options) { return Promise.resolve(null); } formatEntireFile(fileVersion, range, options) { return Promise.resolve(null); } formatAtPosition(fileVersion, position, triggerCharacter, options) { return Promise.resolve(null); } getEvaluationExpression(fileVersion, position) { return Promise.resolve(null); } supportsSymbolSearch(directories) { return Promise.resolve(false); } symbolSearch(query, directories) { return Promise.resolve(null); } getProjectRoot(fileUri) { return Promise.resolve(null); } isFileInProject(fileUri) { return Promise.resolve(false); } getExpandedSelectionRange(fileVersion, currentSelection) { return Promise.resolve(null); } getCollapsedSelectionRange(fileVersion, currentSelection, originalCursorPosition) { return Promise.resolve(null); } dispose() {} } exports.NullLanguageService = NullLanguageService; // Assert that NullLanguageService satisifes the LanguageService interface: null; //# sourceMappingURL=NullLanguageService.js.map
'use strict'; module.exports = forEach; function forEach(fn, indexes, store) { var rawIndexes = []; for (var i = 0; i < indexes.length; i++) { rawIndexes[indexes[i]] = i; } _forEach(fn, store, rawIndexes, [], 0); } function _forEach(fn, store, indexes, values, i) { if (i >= indexes.length) { values[0] = null; values[0] = store; return fn.apply(null, values); } var nextI = i + 1; var valueIndex = indexes[i] + 1; for (var v in store) { if (store.hasOwnProperty(v)) { values[valueIndex] = v; _forEach(fn, store[v], indexes, values, nextI); } } }
let handler = async (m, { conn, command, text }) => { conn.reply(m.chat, ` *Pertanyaan:* ${command} ${text} *Jawaban:* ${pickRandom(['Ya','Mungkin iya','Mungkin','Mungkin tidak','Tidak','Tidak mungkin'])} `.trim(), m, m.mentionedJid ? { contextInfo: { mentionedJid: m.mentionedJid } } : {}) } handler.help = ['apakah <pertanyaan>'] handler.tags = ['kerang'] handler.command = /^apakah/i handler.owner = false handler.mods = false handler.premium = false handler.group = false handler.private = false handler.admin = false handler.botAdmin = false handler.fail = null module.exports = handler function pickRandom(list) { return list[Math.floor(Math.random() * list.length)] }
import React from 'react'; import { Link } from 'react-router-dom'; export default function Button(props) { const { text, link, className } = props; return ( <Link to={link}><button className={className}>{text}</button></Link> ) }
const { site } = require("./config"); const https = require("https"); const crypto = require("crypto"); const moment = require("moment"); const { toTitleCase } = require("../../lib/stringUtil"); module.exports = async function GetAvailableAppointments() { console.log(`${site.name} starting.`); const webData = await ScrapeWebsiteData(); const individualLocationData = Object.values(webData).map( (responseLocation) => { let hasAvailability = false; const availability = {}; if (responseLocation && responseLocation.visibleTimeSlots) { hasAvailability = !!responseLocation.visibleTimeSlots.length; for (const timeSlot of responseLocation.visibleTimeSlots) { //strip time so we group by date, but then force midnight local time zone to avoid UTC dateline issues const date = new Date( `${timeSlot.time.split("T")[0]}T00:00` ); const formattedDate = `${ date.getMonth() + 1 }/${date.getDate()}/${date.getFullYear()}`; if (!availability[formattedDate]) { availability[formattedDate] = { hasAvailability: true, numberAvailableAppointments: 0, }; } availability[ formattedDate ].numberAvailableAppointments += 1; } } return { name: responseLocation.name, street: toTitleCase(responseLocation.address1), city: toTitleCase(responseLocation.city), state: responseLocation.state, zip: responseLocation.zipCode, hasAvailability, availability, signUpLink: site.signUpLink, }; } ); console.log(`${site.name} done.`); return { parentLocationName: "Health Mart Pharmacy", isChain: true, individualLocationData, timestamp: moment().format(), }; }; function md5HashString(string) { return crypto.createHash("md5").update(string).digest("hex"); } async function ScrapeWebsiteData() { const rawData = {}; for (const zip of site.zips) { const url = [site.websiteRoot, zip].join("/") + "?state=MA"; const getUrl = new Promise((resolve) => { let response = ""; https.get(url, { rejectUnauthorized: false }, (res) => { let body = ""; res.on("data", (chunk) => (body += chunk)); res.on("end", () => { response = JSON.parse(body); resolve(response); }); }); }); const responseJson = await getUrl; responseJson.map((responseLoc) => { const responseLocHash = md5HashString( responseLoc.address1 + responseLoc.city ); rawData[responseLocHash] = responseLoc; }); } return rawData; }
module.exports = function (request) { return require('../data/job-details/job-details' + request.params.id + '.json'); };
require("dotenv").config(); module.exports = { siteMetadata: { title: '424', }, plugins: [ 'gatsby-plugin-react-helmet', `gatsby-plugin-styled-components`, { resolve: `gatsby-source-contentful`, options: { spaceId: process.env.SPACE_ID, accessToken: process.env.ACCESS_TOKEN, }, }, { resolve: `gatsby-plugin-favicon`, options: { logo: "./src/favicon.png", // WebApp Manifest Configuration appName: null, // Inferred with your package.json appDescription: null, developerName: null, developerURL: null, dir: 'auto', lang: 'en-US', background: '#fff', theme_color: '#fff', display: 'standalone', orientation: 'any', start_url: '/?homescreen=1', version: '1.0', icons: { android: true, appleIcon: true, appleStartup: true, coast: false, favicons: true, firefox: true, opengraph: false, twitter: false, yandex: false, windows: false } } }, { resolve: `gatsby-plugin-google-analytics`, options: { trackingId: "UA-59794852-1", head: false, } } ], }
import { Link } from "gatsby" import PropTypes from "prop-types" import React from "react" import netlifyIdentity from "netlify-identity-widget" import gatsbyLogo from "../images/gatsby-icon.png" const isActive = ({ isCurrent }) => { return { className: isCurrent ? "active" : "navlink" } } const NavLink = props => <Link getProps={isActive} {...props} /> class Header extends React.Component { componentDidMount() { netlifyIdentity.init() } render() { const { siteTitle } = this.props return ( <header style={{ background: `rebeccapurple`, marginBottom: `1.45rem`, }} > <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", margin: `0 auto`, maxWidth: 960, padding: `1.45rem 1.0875rem`, }} > <span style={{ display: "flex", alignItems: "center" }}> <img src={gatsbyLogo} alt="Gatsby Logo" style={{ margin: "0 5px", border: "3px solid orange", borderRadius: "50%", width: "50px", }} /> <h1 style={{ margin: 0 }}> <NavLink to="/">{siteTitle}</NavLink> </h1> </span> <NavLink to="/blog">Blog</NavLink> <NavLink to="/products">Store</NavLink> <div data-netlify-identity-menu></div> <div style={{ color: "white", cursor: "pointer" }} className="snipcart-summary snipcart-checkout" > <div> <strong>MyCart</strong> </div> <div> <span style={{ fontWeight: "bold" }} className="snipcart-total-items" ></span>{" "} Items in Cart </div> <div> Total price <span className="snipcart-total-price"></span> </div> </div> </div> </header> ) } } Header.propTypes = { siteTitle: PropTypes.string, } Header.defaultProps = { siteTitle: ``, } export default Header
const { execSync } = require('child_process') const fs = require('fs') const path = require('path') const LRU = require('lru-cache') const semver = require('semver') let _hasYarn const _yarnProjects = new LRU({ max: 10, maxAge: 1000 }) let _hasGit const _gitProjects = new LRU({ max: 10, maxAge: 1000 }) // env detection exports.hasYarn = () => { if (process.env.VUE_CLI_TEST) { return true } if (_hasYarn != null) { return _hasYarn } try { execSync('yarn --version', { stdio: 'ignore' }) return (_hasYarn = true) } catch (e) { return (_hasYarn = false) } } exports.hasProjectYarn = (cwd) => { if (_yarnProjects.has(cwd)) { return checkYarn(_yarnProjects.get(cwd)) } const lockFile = path.join(cwd, 'yarn.lock') const result = fs.existsSync(lockFile) _yarnProjects.set(cwd, result) return checkYarn(result) } function checkYarn (result) { if (result && !exports.hasYarn()) throw new Error(`The project seems to require yarn but it's not installed.`) return result } exports.hasGit = () => { if (process.env.VUE_CLI_TEST) { return true } if (_hasGit != null) { return _hasGit } try { execSync('git --version', { stdio: 'ignore' }) return (_hasGit = true) } catch (e) { return (_hasGit = false) } } exports.hasProjectGit = (cwd) => { if (_gitProjects.has(cwd)) { return _gitProjects.get(cwd) } let result try { execSync('git status', { stdio: 'ignore', cwd }) result = true } catch (e) { result = false } _gitProjects.set(cwd, result) return result } let _hasPnpm let _pnpmVersion const _pnpmProjects = new LRU({ max: 10, maxAge: 1000 }) function getPnpmVersion () { if (_pnpmVersion != null) { return _pnpmVersion } try { _pnpmVersion = execSync('pnpm --version', { stdio: ['pipe', 'pipe', 'ignore'] }).toString() // there's a critical bug in pnpm 2 // https://github.com/pnpm/pnpm/issues/1678#issuecomment-469981972 // so we only support pnpm >= 3.0.0 _hasPnpm = true } catch (e) {} return _pnpmVersion || '0.0.0' } exports.hasPnpmVersionOrLater = (version) => { if (process.env.VUE_CLI_TEST) { return true } return semver.gte(getPnpmVersion(), version) } exports.hasPnpm3OrLater = () => { return this.hasPnpmVersionOrLater('3.0.0') } exports.hasProjectPnpm = (cwd) => { if (_pnpmProjects.has(cwd)) { return checkPnpm(_pnpmProjects.get(cwd)) } const lockFile = path.join(cwd, 'pnpm-lock.yaml') const result = fs.existsSync(lockFile) _pnpmProjects.set(cwd, result) return checkPnpm(result) } function checkPnpm (result) { if (result && !exports.hasPnpm3OrLater()) { throw new Error(`The project seems to require pnpm${_hasPnpm ? ' >= 3' : ''} but it's not installed.`) } return result } const _npmProjects = new LRU({ max: 10, maxAge: 1000 }) exports.hasProjectNpm = (cwd) => { if (_npmProjects.has(cwd)) { return _npmProjects.get(cwd) } const lockFile = path.join(cwd, 'package-lock.json') const result = fs.existsSync(lockFile) _npmProjects.set(cwd, result) return result } // OS exports.isWindows = process.platform === 'win32' exports.isMacintosh = process.platform === 'darwin' exports.isLinux = process.platform === 'linux' const browsers = {} let hasCheckedBrowsers = false function tryRun (cmd) { try { return execSync(cmd, { stdio: [0, 'pipe', 'ignore'], timeout: 10000 }).toString().trim() } catch (e) { return '' } } function getLinuxAppVersion (binary) { return tryRun(`${binary} --version`).replace(/^.* ([^ ]*)/g, '$1') } function getMacAppVersion (bundleIdentifier) { const bundlePath = tryRun(`mdfind "kMDItemCFBundleIdentifier=='${bundleIdentifier}'"`) if (bundlePath) { return tryRun(`/usr/libexec/PlistBuddy -c Print:CFBundleShortVersionString ${ bundlePath.replace(/(\s)/g, '\\ ') }/Contents/Info.plist`) } } exports.getInstalledBrowsers = () => { if (hasCheckedBrowsers) { return browsers } hasCheckedBrowsers = true if (exports.isLinux) { browsers.chrome = getLinuxAppVersion('google-chrome') browsers.firefox = getLinuxAppVersion('firefox') } else if (exports.isMacintosh) { browsers.chrome = getMacAppVersion('com.google.Chrome') browsers.firefox = getMacAppVersion('org.mozilla.firefox') } else if (exports.isWindows) { // get chrome stable version // https://stackoverflow.com/a/51773107/2302258 const chromeQueryResult = tryRun( 'reg query "HKLM\\Software\\Google\\Update\\Clients\\{8A69D345-D564-463c-AFF1-A69D9E530F96}" /v pv /reg:32' ) || tryRun( 'reg query "HKCU\\Software\\Google\\Update\\Clients\\{8A69D345-D564-463c-AFF1-A69D9E530F96}" /v pv /reg:32' ) if (chromeQueryResult) { const matched = chromeQueryResult.match(/REG_SZ\s+(\S*)$/) browsers.chrome = matched && matched[1] } // get firefox version // https://community.spiceworks.com/topic/111518-how-to-determine-version-of-installed-firefox-in-windows-batchscript const ffQueryResult = tryRun( 'reg query "HKLM\\Software\\Mozilla\\Mozilla Firefox" /v CurrentVersion' ) if (ffQueryResult) { const matched = ffQueryResult.match(/REG_SZ\s+(\S*)$/) browsers.firefox = matched && matched[1] } } return browsers }
import requestEdit from './requestEdit.js' import requestParseErrors from './requestParseErrors.js' export default function getPaginationRequestAction(target) { switch (target) { case 'parseErrors': return requestParseErrors() default: return requestEdit(target) } }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ic_voicemail = void 0; var ic_voicemail = { "viewBox": "0 0 24 24", "children": [{ "name": "path", "attribs": { "d": "M0 0h24v24H0z", "fill": "none" }, "children": [] }, { "name": "path", "attribs": { "d": "M18.5 6C15.46 6 13 8.46 13 11.5c0 1.33.47 2.55 1.26 3.5H9.74c.79-.95 1.26-2.17 1.26-3.5C11 8.46 8.54 6 5.5 6S0 8.46 0 11.5 2.46 17 5.5 17h13c3.04 0 5.5-2.46 5.5-5.5S21.54 6 18.5 6zm-13 9C3.57 15 2 13.43 2 11.5S3.57 8 5.5 8 9 9.57 9 11.5 7.43 15 5.5 15zm13 0c-1.93 0-3.5-1.57-3.5-3.5S16.57 8 18.5 8 22 9.57 22 11.5 20.43 15 18.5 15z" }, "children": [] }] }; exports.ic_voicemail = ic_voicemail;
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _isFunction2 = require('lodash/isFunction'); var _isFunction3 = _interopRequireDefault(_isFunction2); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _class, _temp; /** * @fileOverview Cartesian Axis */ var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _propTypes = require('prop-types'); var _propTypes2 = _interopRequireDefault(_propTypes); var _classnames = require('classnames'); var _classnames2 = _interopRequireDefault(_classnames); var _PureRender = require('../util/PureRender'); var _DOMUtils = require('../util/DOMUtils'); var _Layer = require('../container/Layer'); var _Layer2 = _interopRequireDefault(_Layer); var _Text = require('../component/Text'); var _Text2 = _interopRequireDefault(_Text); var _Label = require('../component/Label'); var _Label2 = _interopRequireDefault(_Label); var _ReactUtils = require('../util/ReactUtils'); var _DataUtils = require('../util/DataUtils'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var CartesianAxis = (_temp = _class = function (_Component) { _inherits(CartesianAxis, _Component); function CartesianAxis() { _classCallCheck(this, CartesianAxis); return _possibleConstructorReturn(this, (CartesianAxis.__proto__ || Object.getPrototypeOf(CartesianAxis)).apply(this, arguments)); } _createClass(CartesianAxis, [{ key: 'shouldComponentUpdate', value: function shouldComponentUpdate(_ref, state) { var viewBox = _ref.viewBox, restProps = _objectWithoutProperties(_ref, ['viewBox']); // props.viewBox is sometimes generated every time - // check that specially as object equality is likely to fail var _props = this.props, viewBoxOld = _props.viewBox, restPropsOld = _objectWithoutProperties(_props, ['viewBox']); return !(0, _PureRender.shallowEqual)(viewBox, viewBoxOld) || !(0, _PureRender.shallowEqual)(restProps, restPropsOld) || !(0, _PureRender.shallowEqual)(state, this.state); } /** * Calculate the coordinates of endpoints in ticks * @param {Object} data The data of a simple tick * @return {Object} (x1, y1): The coordinate of endpoint close to tick text * (x2, y2): The coordinate of endpoint close to axis */ }, { key: 'getTickLineCoord', value: function getTickLineCoord(data) { var _props2 = this.props, x = _props2.x, y = _props2.y, width = _props2.width, height = _props2.height, orientation = _props2.orientation, tickSize = _props2.tickSize, mirror = _props2.mirror, tickMargin = _props2.tickMargin; var x1 = void 0, x2 = void 0, y1 = void 0, y2 = void 0, tx = void 0, ty = void 0; var sign = mirror ? -1 : 1; var finalTickSize = data.tickSize || tickSize; var tickCoord = (0, _DataUtils.isNumber)(data.tickCoord) ? data.tickCoord : data.coordinate; switch (orientation) { case 'top': x1 = x2 = data.coordinate; y2 = y + !mirror * height; y1 = y2 - sign * finalTickSize; ty = y1 - sign * tickMargin; tx = tickCoord; break; case 'left': y1 = y2 = data.coordinate; x2 = x + !mirror * width; x1 = x2 - sign * finalTickSize; tx = x1 - sign * tickMargin; ty = tickCoord; break; case 'right': y1 = y2 = data.coordinate; x2 = x + mirror * width; x1 = x2 + sign * finalTickSize; tx = x1 + sign * tickMargin; ty = tickCoord; break; default: x1 = x2 = data.coordinate; y2 = y + mirror * height; y1 = y2 + sign * finalTickSize; ty = y1 + sign * tickMargin; tx = tickCoord; break; } return { line: { x1: x1, y1: y1, x2: x2, y2: y2 }, tick: { x: tx, y: ty } }; } }, { key: 'getTickTextAnchor', value: function getTickTextAnchor() { var _props3 = this.props, orientation = _props3.orientation, mirror = _props3.mirror; var textAnchor = void 0; switch (orientation) { case 'left': textAnchor = mirror ? 'start' : 'end'; break; case 'right': textAnchor = mirror ? 'end' : 'start'; break; default: textAnchor = 'middle'; break; } return textAnchor; } }, { key: 'getTickVerticalAnchor', value: function getTickVerticalAnchor() { var _props4 = this.props, orientation = _props4.orientation, mirror = _props4.mirror; var verticalAnchor = 'end'; switch (orientation) { case 'left': case 'right': verticalAnchor = 'middle'; break; case 'top': verticalAnchor = mirror ? 'start' : 'end'; break; default: verticalAnchor = mirror ? 'end' : 'start'; break; } return verticalAnchor; } }, { key: 'renderAxisLine', value: function renderAxisLine() { var _props5 = this.props, x = _props5.x, y = _props5.y, width = _props5.width, height = _props5.height, orientation = _props5.orientation, axisLine = _props5.axisLine, mirror = _props5.mirror; var props = _extends({}, (0, _ReactUtils.getPresentationAttributes)(this.props), { fill: 'none' }, (0, _ReactUtils.getPresentationAttributes)(axisLine)); if (orientation === 'top' || orientation === 'bottom') { var needHeight = orientation === 'top' && !mirror || orientation === 'bottom' && mirror; props = _extends({}, props, { x1: x, y1: y + needHeight * height, x2: x + width, y2: y + needHeight * height }); } else { var needWidth = orientation === 'left' && !mirror || orientation === 'right' && mirror; props = _extends({}, props, { x1: x + needWidth * width, y1: y, x2: x + needWidth * width, y2: y + height }); } return _react2.default.createElement('line', _extends({ className: 'recharts-cartesian-axis-line' }, props)); } }, { key: 'renderTickItem', value: function renderTickItem(option, props, value) { var tickItem = void 0; if (_react2.default.isValidElement(option)) { tickItem = _react2.default.cloneElement(option, props); } else if ((0, _isFunction3.default)(option)) { tickItem = option(props); } else { tickItem = _react2.default.createElement( _Text2.default, _extends({}, props, { className: 'recharts-cartesian-axis-tick-value' }), value ); } return tickItem; } /** * render the ticks * @param {Array} ticks The ticks to actually render (overrides what was passed in props) * @return {ReactComponent} renderedTicks */ }, { key: 'renderTicks', value: function renderTicks(ticks) { var _this2 = this; var _props6 = this.props, tickLine = _props6.tickLine, stroke = _props6.stroke, tick = _props6.tick, tickFormatter = _props6.tickFormatter, unit = _props6.unit; var finalTicks = CartesianAxis.getTicks(_extends({}, this.props, { ticks: ticks })); var textAnchor = this.getTickTextAnchor(); var verticalAnchor = this.getTickVerticalAnchor(); var axisProps = (0, _ReactUtils.getPresentationAttributes)(this.props); var customTickProps = (0, _ReactUtils.getPresentationAttributes)(tick); var tickLineProps = _extends({}, axisProps, { fill: 'none' }, (0, _ReactUtils.getPresentationAttributes)(tickLine)); var items = finalTicks.map(function (entry, i) { var _getTickLineCoord = _this2.getTickLineCoord(entry), lineCoord = _getTickLineCoord.line, tickCoord = _getTickLineCoord.tick; var tickProps = _extends({ textAnchor: textAnchor, verticalAnchor: verticalAnchor }, axisProps, { stroke: 'none', fill: stroke }, customTickProps, tickCoord, { index: i, payload: entry }); return _react2.default.createElement( _Layer2.default, _extends({ className: 'recharts-cartesian-axis-tick', key: 'tick-' + i }, (0, _ReactUtils.filterEventsOfChild)(_this2.props, entry, i)), tickLine && _react2.default.createElement('line', _extends({ className: 'recharts-cartesian-axis-tick-line' }, tickLineProps, lineCoord)), tick && _this2.renderTickItem(tick, tickProps, '' + ((0, _isFunction3.default)(tickFormatter) ? tickFormatter(entry.value) : entry.value) + (unit || '')) ); }); return _react2.default.createElement( 'g', { className: 'recharts-cartesian-axis-ticks' }, items ); } }, { key: 'render', value: function render() { var _props7 = this.props, axisLine = _props7.axisLine, width = _props7.width, height = _props7.height, ticksGenerator = _props7.ticksGenerator, className = _props7.className, hide = _props7.hide; if (hide) { return null; } var _props8 = this.props, ticks = _props8.ticks, noTicksProps = _objectWithoutProperties(_props8, ['ticks']); var finalTicks = ticks; if ((0, _isFunction3.default)(ticksGenerator)) { finalTicks = ticks && ticks.length > 0 ? ticksGenerator(this.props) : ticksGenerator(noTicksProps); } if (width <= 0 || height <= 0 || !finalTicks || !finalTicks.length) { return null; } return _react2.default.createElement( _Layer2.default, { className: (0, _classnames2.default)('recharts-cartesian-axis', className) }, axisLine && this.renderAxisLine(), this.renderTicks(finalTicks), _Label2.default.renderCallByParent(this.props) ); } }], [{ key: 'getTicks', value: function getTicks(props) { var tick = props.tick, ticks = props.ticks, viewBox = props.viewBox, minTickGap = props.minTickGap, orientation = props.orientation, interval = props.interval, tickFormatter = props.tickFormatter, unit = props.unit; if (!ticks || !ticks.length || !tick) { return []; } if ((0, _DataUtils.isNumber)(interval) || (0, _ReactUtils.isSsr)()) { return CartesianAxis.getNumberIntervalTicks(ticks, (0, _DataUtils.isNumber)(interval) ? interval : 0); } if (interval === 'preserveStartEnd') { return CartesianAxis.getTicksStart({ ticks: ticks, tickFormatter: tickFormatter, viewBox: viewBox, orientation: orientation, minTickGap: minTickGap, unit: unit }, true); } else if (interval === 'preserveStart') { return CartesianAxis.getTicksStart({ ticks: ticks, tickFormatter: tickFormatter, viewBox: viewBox, orientation: orientation, minTickGap: minTickGap, unit: unit }); } return CartesianAxis.getTicksEnd({ ticks: ticks, tickFormatter: tickFormatter, viewBox: viewBox, orientation: orientation, minTickGap: minTickGap, unit: unit }); } }, { key: 'getNumberIntervalTicks', value: function getNumberIntervalTicks(ticks, interval) { return ticks.filter(function (entry, i) { return i % (interval + 1) === 0; }); } }, { key: 'getTicksStart', value: function getTicksStart(_ref2, preserveEnd) { var ticks = _ref2.ticks, tickFormatter = _ref2.tickFormatter, viewBox = _ref2.viewBox, orientation = _ref2.orientation, minTickGap = _ref2.minTickGap, unit = _ref2.unit; var x = viewBox.x, y = viewBox.y, width = viewBox.width, height = viewBox.height; var sizeKey = orientation === 'top' || orientation === 'bottom' ? 'width' : 'height'; var result = (ticks || []).slice(); var unitSize = unit ? (0, _DOMUtils.getStringSize)(unit)[sizeKey] : 0; var len = result.length; var sign = len >= 2 ? (0, _DataUtils.mathSign)(result[1].coordinate - result[0].coordinate) : 1; var start = void 0, end = void 0; if (sign === 1) { start = sizeKey === 'width' ? x : y; end = sizeKey === 'width' ? x + width : y + height; } else { start = sizeKey === 'width' ? x + width : y + height; end = sizeKey === 'width' ? x : y; } if (preserveEnd) { // Try to guarantee the tail to be displayed var tail = ticks[len - 1]; var tailContent = (0, _isFunction3.default)(tickFormatter) ? tickFormatter(tail.value) : tail.value; var tailSize = (0, _DOMUtils.getStringSize)(tailContent)[sizeKey] + unitSize; var tailGap = sign * (tail.coordinate + sign * tailSize / 2 - end); result[len - 1] = tail = _extends({}, tail, { tickCoord: tailGap > 0 ? tail.coordinate - tailGap * sign : tail.coordinate }); var isTailShow = sign * (tail.tickCoord - sign * tailSize / 2 - start) >= 0 && sign * (tail.tickCoord + sign * tailSize / 2 - end) <= 0; if (isTailShow) { end = tail.tickCoord - sign * (tailSize / 2 + minTickGap); result[len - 1] = _extends({}, tail, { isShow: true }); } } var count = preserveEnd ? len - 1 : len; for (var i = 0; i < count; i++) { var entry = result[i]; var content = (0, _isFunction3.default)(tickFormatter) ? tickFormatter(entry.value) : entry.value; var size = (0, _DOMUtils.getStringSize)(content)[sizeKey] + unitSize; if (i === 0) { var gap = sign * (entry.coordinate - sign * size / 2 - start); result[i] = entry = _extends({}, entry, { tickCoord: gap < 0 ? entry.coordinate - gap * sign : entry.coordinate }); } else { result[i] = entry = _extends({}, entry, { tickCoord: entry.coordinate }); } var isShow = sign * (entry.tickCoord - sign * size / 2 - start) >= 0 && sign * (entry.tickCoord + sign * size / 2 - end) <= 0; if (isShow) { start = entry.tickCoord + sign * (size / 2 + minTickGap); result[i] = _extends({}, entry, { isShow: true }); } } return result.filter(function (entry) { return entry.isShow; }); } }, { key: 'getTicksEnd', value: function getTicksEnd(_ref3) { var ticks = _ref3.ticks, tickFormatter = _ref3.tickFormatter, viewBox = _ref3.viewBox, orientation = _ref3.orientation, minTickGap = _ref3.minTickGap, unit = _ref3.unit; var x = viewBox.x, y = viewBox.y, width = viewBox.width, height = viewBox.height; var sizeKey = orientation === 'top' || orientation === 'bottom' ? 'width' : 'height'; var unitSize = unit ? (0, _DOMUtils.getStringSize)(unit)[sizeKey] : 0; var result = (ticks || []).slice(); var len = result.length; var sign = len >= 2 ? (0, _DataUtils.mathSign)(result[1].coordinate - result[0].coordinate) : 1; var start = void 0, end = void 0; if (sign === 1) { start = sizeKey === 'width' ? x : y; end = sizeKey === 'width' ? x + width : y + height; } else { start = sizeKey === 'width' ? x + width : y + height; end = sizeKey === 'width' ? x : y; } for (var i = len - 1; i >= 0; i--) { var entry = result[i]; var content = (0, _isFunction3.default)(tickFormatter) ? tickFormatter(entry.value) : entry.value; var size = (0, _DOMUtils.getStringSize)(content)[sizeKey] + unitSize; if (i === len - 1) { var gap = sign * (entry.coordinate + sign * size / 2 - end); result[i] = entry = _extends({}, entry, { tickCoord: gap > 0 ? entry.coordinate - gap * sign : entry.coordinate }); } else { result[i] = entry = _extends({}, entry, { tickCoord: entry.coordinate }); } var isShow = sign * (entry.tickCoord - sign * size / 2 - start) >= 0 && sign * (entry.tickCoord + sign * size / 2 - end) <= 0; if (isShow) { end = entry.tickCoord - sign * (size / 2 + minTickGap); result[i] = _extends({}, entry, { isShow: true }); } } return result.filter(function (entry) { return entry.isShow; }); } }]); return CartesianAxis; }(_react.Component), _class.displayName = 'CartesianAxis', _class.propTypes = _extends({}, _ReactUtils.PRESENTATION_ATTRIBUTES, _ReactUtils.EVENT_ATTRIBUTES, { className: _propTypes2.default.string, x: _propTypes2.default.number, y: _propTypes2.default.number, width: _propTypes2.default.number, height: _propTypes2.default.number, orientation: _propTypes2.default.oneOf(['top', 'bottom', 'left', 'right']), // The viewBox of svg viewBox: _propTypes2.default.shape({ x: _propTypes2.default.number, y: _propTypes2.default.number, width: _propTypes2.default.number, height: _propTypes2.default.number }), tick: _propTypes2.default.oneOfType([_propTypes2.default.bool, _propTypes2.default.func, _propTypes2.default.object, _propTypes2.default.element]), axisLine: _propTypes2.default.oneOfType([_propTypes2.default.bool, _propTypes2.default.object]), tickLine: _propTypes2.default.oneOfType([_propTypes2.default.bool, _propTypes2.default.object]), mirror: _propTypes2.default.bool, tickMargin: _propTypes2.default.number.isRequired, minTickGap: _propTypes2.default.number, ticks: _propTypes2.default.array, tickSize: _propTypes2.default.number, stroke: _propTypes2.default.string, tickFormatter: _propTypes2.default.func, ticksGenerator: _propTypes2.default.func, interval: _propTypes2.default.oneOfType([_propTypes2.default.number, _propTypes2.default.oneOf(['preserveStart', 'preserveEnd', 'preserveStartEnd'])]) }), _class.defaultProps = { x: 0, y: 0, width: 0, height: 0, viewBox: { x: 0, y: 0, width: 0, height: 0 }, // The orientation of axis orientation: 'bottom', // The ticks ticks: [], stroke: '#666', tickLine: true, axisLine: true, tick: true, mirror: false, minTickGap: 5, // The width or height of tick tickSize: 6, tickMargin: 2, interval: 'preserveEnd' }, _temp); exports.default = CartesianAxis;
var options = { manager: require("../../../src/managers/garment-purchasing/purchase-order-external-manager"), model: require("dl-models").garmentPurchasing.GarmentPurchaseOrderExternal, util: require("../../data-util/garment-purchasing/purchase-order-external-data-util"), validator: require("dl-models").validator.garmentPurchasing.garmentPurchaseOrderExternal, createDuplicate: false, keys: ["no"] }; var basicTest = require("../../basic-test-factory"); basicTest(options);
import { Link, navigate } from "gatsby" import PropTypes from "prop-types" import React, { useContext } from "react" import { FirebaseContext } from './Firebase'; import styled from 'styled-components'; const LogoutLink = styled.span` color: white; cursor:pointer; &:hover{ text-decoration: underline; } ` const HeaderWrapper = styled.header` background: rebeccapurple; margin-bottom: 1.45rem; ` const HeaderContent = styled.div` margin: 0 auto; max-width: 960px; padding: 1.45rem 1.0875rem; display: flex; >h1{ margin: 0; flex-grow:1; >a{ color: white; text-decoration: none; } } >div{ margin: auto 0; } ` const UserInfo = styled.div` text-align: right; color: white; ` const LoginLink = styled.div` margin: auto 0; a{ color:white; } ` const Divider = styled.span` margin: 0 8px; padding-right: 1px; background: #ddd; ` const AdminLink = styled.span` a{ color: white; } ` const Header = ({ siteTitle }) => { const {firebase, user} = useContext(FirebaseContext); console.log(user) function handleLogoutClick(){ firebase.logout().then(() => navigate('/login')) } return ( <HeaderWrapper> <HeaderContent> <h1> <Link to="/">{siteTitle}</Link> </h1> <div> {!!user && !!user.email && <UserInfo> Hello, {user.username || user.email} <div> {!!user.isAdmin && <> <AdminLink> <Link to="/add-cook">Add Cook</Link> </AdminLink> <Divider /> <AdminLink> <Link to="/add-recipe">Add Recipe</Link> </AdminLink> <Divider /> </> } <LogoutLink onClick={handleLogoutClick}> Logout </LogoutLink> </div> </UserInfo> } {(!user || !user.email) && <LoginLink> <Link to="/login"> Login </Link> <Divider /> <Link to="/register"> Register </Link> </LoginLink> } </div> </HeaderContent> </HeaderWrapper> ) } Header.propTypes = { siteTitle: PropTypes.string, } Header.defaultProps = { siteTitle: ``, } export default Header
function showNome(){ document.getElementById('divNOME').style.display = 'inline-table'; document.getElementById('divRG').style.display = 'none'; document.getElementById('rgPaciente').value = ''; } function showRG(){ document.getElementById('divNOME').style.display ='none'; document.getElementById('divRG').style.display ='inline-table'; document.getElementById('nomePaciente').value = ''; }
import { Observable } from '../../Observable'; import { sequenceEqual } from '../../operator/sequenceEqual'; Observable.prototype.sequenceEqual = sequenceEqual;
const React = require('react'); class Footer extends React.Component { render() { const currentYear = new Date().getFullYear(); return ( <footer className="nav-footer" id="footer"> <section className="sitemap"> <a href={this.props.config.baseUrl} className="nav-home"> <img src={this.props.config.baseUrl + this.props.config.footerIcon} alt={this.props.config.title} width="66" height="58" /> </a> <div> <h5>Docs</h5> <a href={this.props.config.baseUrl + 'docs/overview.html'}>Overview</a> <a href={this.props.config.baseUrl + 'docs/concepts.html'}>Concepts</a> <a href={this.props.config.baseUrl + 'api/index.html'}>API Reference</a> </div> <div> <h5>More</h5> <a href="https://github.com/">GitHub</a> <a className="github-button" href={this.props.config.repoUrl} data-icon="octicon-star" data-count-href="/arez/arez/stargazers" data-show-count={true} data-count-aria-label="# stargazers on GitHub" aria-label="Star this project on GitHub"> Star </a> </div> </section> <section className="copyright"> Copyright &copy; {currentYear} the Arez Project. </section> </footer> ); } } module.exports = Footer;
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format * @flow strict-local */ 'use strict'; import type {Node} from 'React'; import {ActivityIndicator, StyleSheet, View} from 'react-native'; import React, {Component} from 'react'; type State = {|animating: boolean|}; type Props = $ReadOnly<{||}>; type Timer = TimeoutID; class ToggleAnimatingActivityIndicator extends Component<Props, State> { _timer: Timer; constructor(props: Props) { super(props); this.state = { animating: true, }; } componentDidMount() { this.setToggleTimeout(); } componentWillUnmount() { clearTimeout(this._timer); } setToggleTimeout() { this._timer = setTimeout(() => { this.setState({animating: !this.state.animating}); this.setToggleTimeout(); }, 2000); } render(): Node { return ( <ActivityIndicator animating={this.state.animating} style={[styles.centering, {height: 80}]} size="large" /> ); } } const styles = StyleSheet.create({ centering: { alignItems: 'center', justifyContent: 'center', padding: 8, }, gray: { backgroundColor: '#cccccc', }, horizontal: { flexDirection: 'row', justifyContent: 'space-around', padding: 8, }, }); exports.displayName = (undefined: ?string); exports.category = 'UI'; exports.framework = 'React'; exports.title = 'ActivityIndicator'; exports.documentationURL = 'https://reactnative.dev/docs/activityindicator'; exports.description = 'Animated loading indicators.'; exports.examples = [ { title: 'Default (small, white)', render(): Node { return ( <ActivityIndicator style={[styles.centering, styles.gray]} color="white" /> ); }, }, { title: 'Gray', render(): Node { return ( <View> <ActivityIndicator style={[styles.centering]} /> <ActivityIndicator style={[styles.centering, styles.gray]} /> </View> ); }, }, { title: 'Custom colors', render(): Node { return ( <View style={styles.horizontal}> <ActivityIndicator color="#0000ff" /> <ActivityIndicator color="#aa00aa" /> <ActivityIndicator color="#aa3300" /> <ActivityIndicator color="#00aa00" /> </View> ); }, }, { title: 'Large', render(): Node { return ( <ActivityIndicator style={[styles.centering, styles.gray]} size="large" color="white" /> ); }, }, { title: 'Large, custom colors', render(): Node { return ( <View style={styles.horizontal}> <ActivityIndicator size="large" color="#0000ff" /> <ActivityIndicator size="large" color="#aa00aa" /> <ActivityIndicator size="large" color="#aa3300" /> <ActivityIndicator size="large" color="#00aa00" /> </View> ); }, }, { title: 'Start/stop', render(): Node { return <ToggleAnimatingActivityIndicator />; }, }, { title: 'Custom size', render(): Node { return ( <ActivityIndicator style={[styles.centering, {transform: [{scale: 1.5}]}]} size="large" /> ); }, }, { platform: 'android', title: 'Custom size (size: 75)', render(): Node { return <ActivityIndicator style={styles.centering} size={75} />; }, }, ];
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _react = _interopRequireDefault(require("react")); var _propTypes = _interopRequireDefault(require("prop-types")); var _Collapse = _interopRequireDefault(require("react-bootstrap/lib/Collapse")); var _index = require("../index"); var _index2 = require("../NotificationDrawer/index"); var _Icon = require("../../Icon"); var _Button = require("../../Button"); var _MenuItem = require("../../MenuItem"); var _helpers = require("../../../common/helpers"); var _Icon2 = _interopRequireDefault(require("./Icon.consts")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var NotificationDrawerPanelWrapper = function NotificationDrawerPanelWrapper(_ref) { var panelkey = _ref.panelkey, panelName = _ref.panelName, className = _ref.className, notifications = _ref.notifications, isExpanded = _ref.isExpanded, togglePanel = _ref.togglePanel, onNotificationClick = _ref.onNotificationClick, onNotificationAsRead = _ref.onNotificationAsRead, onNotificationHide = _ref.onNotificationHide, onMarkPanelAsRead = _ref.onMarkPanelAsRead, onClickedLink = _ref.onClickedLink, onMarkPanelAsClear = _ref.onMarkPanelAsClear, showLoading = _ref.showLoading, translations = _ref.translations; var unreadCount = notifications.filter(function (notification) { return !notification.seen; }).length; var getUnread = function getUnread() { if (unreadCount !== 1) { return "".concat(unreadCount, " ").concat(translations.unreadEvents); } return "1 ".concat(translations.unreadEvent); }; var notificationClickHandler = function notificationClickHandler(panel, notification, seen) { onNotificationClick(panel, notification); if (!seen) { onNotificationAsRead(panel, notification); } }; var notificationsMap = notifications.map(function (notification, i) { return _react["default"].createElement(_index.Notification, { key: i, seen: notification.seen, onClick: function onClick() { return notificationClickHandler(panelkey, notification.id, notification.seen); } }, notification.actions ? Object.keys(notification.actions).length > 0 && _react["default"].createElement(_index2.NotificationDrawer.Dropdown, { pullRight: true, id: i }, notification.actions.links.map(function (link, j) { return _react["default"].createElement(_MenuItem.MenuItem, { key: j, id: "notification-kebab-".concat(j), onClick: function onClick() { return onClickedLink(link); } }, link.title); }), _react["default"].createElement(_MenuItem.MenuItem, { divider: true }), _react["default"].createElement(_MenuItem.MenuItem, { id: "notification-kebab-hide", onClick: function onClick() { return onNotificationHide(panelkey, notification.id); } }, translations.deleteNotification)) : null, _react["default"].createElement(_Icon.Icon, { className: "pull-left", type: "pf", name: (0, _Icon2["default"])(notification.level) }), _react["default"].createElement(_index.Notification.Content, null, _react["default"].createElement(_index.Notification.Message, null, notification.text), notification.created_at && _react["default"].createElement(_index.Notification.Info, { leftText: new Date(notification.created_at).toLocaleDateString(), rightText: new Date(notification.created_at).toLocaleTimeString() }))); }); var renderNotifications = _react["default"].createElement(_index2.NotificationDrawer.PanelBody, { key: "containsNotifications" }, showLoading ? [notificationsMap, _react["default"].createElement(_index.Notification, { key: "loading", type: "loading" })] : notificationsMap); var renderClearReadButtons = _react["default"].createElement(_index2.NotificationDrawer.PanelAction, { key: panelkey }, unreadCount > 0 && _react["default"].createElement(_index2.NotificationDrawer.PanelActionLink, { className: "drawer-pf-action-link", "data-toggle": "mark-all-read" }, _react["default"].createElement(_Button.Button, { bsStyle: "link", onClick: function onClick() { return onMarkPanelAsRead(panelkey); } }, translations.readAll)), _react["default"].createElement(_index2.NotificationDrawer.PanelActionLink, { "data-toggle": "clear-all" }, _react["default"].createElement(_Button.Button, { bsStyle: "link", onClick: function onClick() { return onMarkPanelAsClear(panelkey); } }, _react["default"].createElement(_Icon.Icon, { type: "pf", name: "close" }), translations.clearAll))); var noNotificationsMessage = _react["default"].createElement(_index2.NotificationDrawer.EmptyState, { title: translations.emptyState }); return _react["default"].createElement(_index2.NotificationDrawer.Panel, { className: className, expanded: isExpanded }, _react["default"].createElement(_index2.NotificationDrawer.PanelHeading, { onClick: function onClick() { return togglePanel(panelkey); } }, _react["default"].createElement(_index2.NotificationDrawer.PanelTitle, null, _react["default"].createElement("a", { className: isExpanded ? '' : 'collapsed' }, panelName)), _react["default"].createElement(_index2.NotificationDrawer.PanelCounter, { text: getUnread() })), _react["default"].createElement(_Collapse["default"], { "in": isExpanded }, _react["default"].createElement(_index2.NotificationDrawer.PanelCollapse, { id: panelkey }, notifications.length > 0 ? [renderNotifications, renderClearReadButtons] : noNotificationsMessage))); }; NotificationDrawerPanelWrapper.propTypes = { /** Panel Key,Name */ panelkey: _propTypes["default"].string, panelName: _propTypes["default"].string, className: _propTypes["default"].string, /** Notification Panels Array */ notifications: _propTypes["default"].array, /** is Expanded Bool */ isExpanded: _propTypes["default"].bool, /** function(panelkey, notificationkey) on Notification Click */ onNotificationClick: _propTypes["default"].func, /** function(panelkey, notificationkey) on Notification Mark as Read Click */ onNotificationAsRead: _propTypes["default"].func, /** on function(panelkey) Panel Read All Click */ onMarkPanelAsRead: _propTypes["default"].func, /** function(url) on Dropdown Link Click */ onClickedLink: _propTypes["default"].func, /** function(panelkey, notificationkey) on Notification Hide Click */ onNotificationHide: _propTypes["default"].func, /** function(panelkey) Panel Clear All Click */ onMarkPanelAsClear: _propTypes["default"].func, /** function() togglePanel Click */ togglePanel: _propTypes["default"].func, /** show Loading notification Bool */ showLoading: _propTypes["default"].bool, /** translations for Title, EmptyState, Read/Clear */ translations: _propTypes["default"].shape({ title: _propTypes["default"].string, unreadEvent: _propTypes["default"].string, unreadEvents: _propTypes["default"].string, emptyState: _propTypes["default"].string, readAll: _propTypes["default"].string, clearAll: _propTypes["default"].string, deleteNotification: _propTypes["default"].string }) }; NotificationDrawerPanelWrapper.defaultProps = { panelkey: '1', notifications: _propTypes["default"].array, isExpanded: false, className: null, panelName: null, onNotificationClick: _helpers.noop, onNotificationAsRead: _helpers.noop, onMarkPanelAsRead: _helpers.noop, onClickedLink: _helpers.noop, onNotificationHide: _helpers.noop, onMarkPanelAsClear: _helpers.noop, togglePanel: _helpers.noop, showLoading: false, translations: { title: 'Notifications', unreadEvent: 'Unread Event', unreadEvents: 'Unread Events', emptyState: 'No Notifications Available', readAll: 'Mark All Read', clearAll: 'Clear All', deleteNotification: 'Hide this notification' } }; var _default = NotificationDrawerPanelWrapper; exports["default"] = _default;
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require("tslib"); tslib_1.__exportStar(require("@styled-icons/boxicons-regular/DockBottom"), exports);
import styled from 'react-emotion'; export { Button, Title, Container, ButtonGroup, Description } from '../Styles'; export const Warning = styled.span ` flex: 1 1 100%; font-size: 12px; `
// Heavily inspirated by easymidi // Anyhow, I want to have direct access to the stream // which is not offered for so far by easymidi. const midi = require('midi') const EventEmitter = require('events').EventEmitter const swap = (obj) => Object.entries(obj).reduce((acc, [key, value]) => { acc[value] = key return acc }, {}) const INPUT_TYPES = { 0x08: 'noteoff', 0x09: 'noteon', 0x0a: 'poly aftertouch', 0x0b: 'cc', 0x0c: 'program', 0x0d: 'channel aftertouch', 0x0e: 'pitch', } const INPUT_EXTENDED_TYPES = { 0xf0: 'sysex', 0xf1: 'mtc', 0xf2: 'position', 0xf3: 'select', 0xf6: 'tune', 0xf7: 'sysex end', 0xf8: 'clock', 0xfa: 'start', 0xfb: 'continue', 0xfc: 'stop', 0xfe: 'activesense', 0xff: 'reset', } const OUTPUT_TYPES = swap(INPUT_TYPES) const OUTPUT_EXTENDED_TYPES = swap(INPUT_EXTENDED_TYPES) class Input extends EventEmitter { constructor(name, virtual) { super() this._input = new midi.input() this._input.ignoreTypes(false, false, false) this._pendingSysex = false this._sysex = [] this.name = name if (virtual) { this._input.openVirtualPort(name) } else { const numInputs = this._input.getPortCount() let found = false for (let i = 0; i < numInputs; i++) { if (name === this._input.getPortName(i)) { found = true this._input.openPort(i) } } if (!found) { throw new Error('No MIDI input found with name: ' + name) } } this._input.on('message', (deltaTime, bytes) => { // a long sysex can be sent in multiple chunks, depending on the RtMidi buffer size let proceed = true if (this._pendingSysex && bytes.length > 0) { if (bytes[0] < 0x80) { this._sysex = this._sysex.concat(bytes) if (bytes[bytes.length - 1] === 0xf7) { const msg = { _type: 'sysex', bytes: this._sysex } this.emit('sysex', msg) this.emit('message', msg) //sysex = [] this._pendingSysex = false } proceed = false } else { // ignore invalid sysex messages this._sysex = [] this._pendingSysex = false } } if (proceed) { const data = this.parseMessage(bytes) if (data.type === 'sysex' && bytes[bytes.length - 1] !== 0xf7) { this._sysex = [...bytes] this._pendingSysex = true } else { data.msg._type = data.type // easy access to message type this.emit(data.type, data.msg) // also emit "message" event, to allow easy monitoring of all messages this.emit('message', data.msg) if (data.type === 'mtc') { this.parseMtc(data.msg) } } } }) } getReadStream() { return midi.createReadStream(this._input) } close() { this._input.closePort() } isPortOpen() { this._input.isPortOpen() } parseMtc(data) { const byteNumber = data.type let value = data.value const smpte = [] let smpteMessageCounter = 0 let smpteType if (byteNumber === 7) { const bits = [] for (let i = 3; i >= 0; i--) { const bit = value & (1 << i) ? 1 : 0 bits.push(bit) } value = bits[3] smpteType = bits[1] * 2 + bits[2] } smpte[byteNumber] = value if (smpteMessageCounter !== 7) { smpteMessageCounter++ return } if (byteNumber === 7) { const smpteFormatted = (smpte[7] * 16 + smpte[6]).toString().padStart(2, '0') + ':' + (smpte[5] * 16 + smpte[4]).toString().padStart(2, '0') + ':' + (smpte[3] * 16 + smpte[2]).toString().padStart(2, '0') + ':' + (smpte[1] * 16 + smpte[0]).toString().padStart(2, '0') this.emit('smpte', { smpte: smpteFormatted, smpteType, }) } } parseMessage(bytes) { const msg = {} let type = 'unknown' if (bytes[0] >= 0xf0) { type = INPUT_EXTENDED_TYPES[bytes[0]] } else { type = INPUT_TYPES[bytes[0] >> 4] msg.channel = bytes[0] & 0xf } if (type === 'noteoff' || type === 'noteon') { msg.note = bytes[1] msg.velocity = bytes[2] } if (type === 'cc') { msg.controller = bytes[1] msg.value = bytes[2] } if (type === 'poly aftertouch') { msg.note = bytes[1] msg.pressure = bytes[2] } if (type === 'channel aftertouch') { msg.pressure = bytes[1] } if (type === 'program') { msg.number = bytes[1] } if (type === 'pitch' || type === 'position') { msg.value = bytes[1] + bytes[2] * 128 } if (type === 'sysex') { msg.bytes = bytes } if (type === 'select') { msg.song = bytes[1] } if (type === 'mtc') { msg.type = (bytes[1] >> 4) & 0x07 msg.value = bytes[1] & 0x0f } return { type, msg, } } } class Output { constructor(name, virtual) { this._output = new midi.output() this.name = name if (virtual) { this._output.openVirtualPort(name) } else { const numOutputs = this._output.getPortCount() let found = false for (let i = 0; i < numOutputs; i++) { if (name === this._output.getPortName(i)) { found = true this._output.openPort(i) } } if (!found) { throw new Error('No MIDI output found with name: ' + name) } } } getWriteStream() { return midi.createWriteStream(this._output) } close() { this._output.closePort() } isPortOpen() { this._output.isPortOpen() } send(type, args) { this._output.sendMessage(this.parseMessage(type, args)) } parseMessage(type, args) { const bytes = [] if (OUTPUT_TYPES[type]) { args.channel = args.channel || 0 bytes.push((OUTPUT_TYPES[type] << 4) + args.channel) } else if (OUTPUT_EXTENDED_TYPES[type]) { bytes.push(OUTPUT_EXTENDED_TYPES[type]) } else { throw new Error('Unknown midi message type: ' + type) } if (type === 'noteoff' || type === 'noteon') { bytes.push(args.note) bytes.push(args.velocity) } if (type === 'cc') { bytes.push(args.controller) bytes.push(args.value) } if (type === 'poly aftertouch') { bytes.push(args.note) bytes.push(args.pressure) } if (type === 'channel aftertouch') { bytes.push(args.pressure) } if (type === 'program') { bytes.push(args.number) } if (type === 'pitch' || type === 'position') { bytes.push(args.value & 0x7f) // lsb bytes.push((args.value & 0x3f80) >> 7) // msb } if (type === 'mtc') { bytes.push((args.type << 4) + args.value) } if (type === 'select') { bytes.push(args.song) } if (type === 'sysex') { // sysex commands should start with 0xf0 and end with 0xf7. Throw an error if it doesn't. if ( args.length <= 3 || args[0] !== 0xf0 || args[args.length - 1] !== 0xf7 ) { // throw new Error( 'sysex commands should be an array that starts with 0xf0 and end with 0xf7' ) } args.slice(1).forEach((arg) => bytes.push(arg)) // 0xf0 was already added at the beginning of parseMessage. } return bytes } } // utilities const getInputs = () => { const input = new midi.input() const inputs = [] for (let i = 0; i < input.getPortCount(); i++) { inputs.push(input.getPortName(i)) } input.closePort() return inputs } const getOutputs = () => { const output = new midi.output() const outputs = [] for (let i = 0; i < output.getPortCount(); i++) { outputs.push(output.getPortName(i)) } output.closePort() return outputs } module.exports = { Input, getInputs, Output, getOutputs, }
import '../../../stylus/components/_date-picker-table.styl' // Directives import Touch from '../../../directives/touch' // Utils import isDateAllowed from '.././util/isDateAllowed' export default { directives: { Touch }, data () { return { defaultColor: 'accent', isReversing: false } }, props: { allowedDates: Function, current: String, disabled: Boolean, format: { type: Function, default: null }, locale: { type: String, default: 'en-us' }, min: String, max: String, scrollable: Boolean, tableDate: { type: String, required: true }, value: { type: String, required: false } }, computed: { computedTransition () { return this.isReversing ? 'tab-reverse-transition' : 'tab-transition' }, displayedMonth () { return this.tableDate.split('-')[1] - 1 }, displayedYear () { return this.tableDate.split('-')[0] * 1 } }, watch: { tableDate (newVal, oldVal) { this.isReversing = newVal < oldVal } }, methods: { genButtonClasses (value, isAllowed, isFloating) { const isSelected = value === this.value const isCurrent = value === this.current const classes = { 'v-btn--active': isSelected, 'v-btn--flat': !isSelected, 'v-btn--icon': isSelected && isAllowed && isFloating, 'v-btn--floating': isFloating, 'v-btn--depressed': !isFloating && isSelected, 'v-btn--disabled': !isAllowed || (this.disabled && isSelected), 'v-btn--outline': isCurrent && !isSelected, ...this.themeClasses } if (isSelected) return this.addBackgroundColorClassChecks(classes) if (isCurrent) return this.addTextColorClassChecks(classes) return classes }, genButton (value, isFloating) { const isAllowed = isDateAllowed(value, this.min, this.max, this.allowedDates) return this.$createElement('button', { staticClass: 'v-btn', 'class': this.genButtonClasses(value, isAllowed, isFloating), attrs: { type: 'button' }, domProps: { disabled: !isAllowed, innerHTML: `<div class="v-btn__content">${this.formatter(value)}</div>` }, on: (this.disabled || !isAllowed) ? {} : { click: () => this.$emit('input', value) } }) }, wheel (e) { e.preventDefault() this.$emit('tableDate', this.calculateTableDate(e.deltaY)) }, touch (value) { this.$emit('tableDate', this.calculateTableDate(value)) }, genTable (staticClass, children) { const transition = this.$createElement('transition', { props: { name: this.computedTransition } }, [this.$createElement('table', { key: this.tableDate }, children)]) const touchDirective = { name: 'touch', value: { left: e => (e.offsetX < -15) && this.touch(1), right: e => (e.offsetX > 15) && this.touch(-1) } } return this.$createElement('div', { staticClass, class: { ...this.themeClasses }, on: this.scrollable ? { wheel: this.wheel } : undefined, directives: [touchDirective] }, [transition]) } } }
import { getProperty, map, range } from 'moltres' import { setupTestAdminContext, setupTestServiceAccountContext, tearDownTestAdminContext, tearDownTestServiceAccountContext } from '../../../test' import { User, createUser, deleteUser } from '../../user' import deleteEntityStats from './deleteEntityStats' import findOrCreateEntityStats from './findOrCreateEntityStats' import updateStatsShard from './updateStatsShard' const spec = describe('updateStatsShard', () => { describe('ServiceAccount', () => { let adminContext let context let entityStats let user beforeEach(async () => { adminContext = await setupTestAdminContext(spec) context = await setupTestServiceAccountContext(adminContext) user = await createUser(adminContext, { name: 'test-user', state: 'pending' }) entityStats = await findOrCreateEntityStats(context, { entityId: user.id, entityType: User.name }) }, 20000) afterEach(async () => { try { if (user) { await deleteUser(adminContext, getProperty('id', user)) } } catch (error) { context.logger.error(error) } try { if (entityStats) { await deleteEntityStats(adminContext, getProperty('id', entityStats)) } } catch (error) { context.logger.error(error) } context = await tearDownTestServiceAccountContext(context) adminContext = await tearDownTestAdminContext(adminContext) }, 20000) it('update StatsShard at speed', async () => { const shardIndex = 0 const increment = context.firebase.firestore.FieldValue.increment(1) const results = await Promise.all( map(async () => { return await updateStatsShard(context, [entityStats.id, shardIndex], { 'data.foo': increment }) }, range(0, 100)) ) expect(results[99]).toEqual({ createdAt: expect.any(context.firebase.firestore.Timestamp), data: { foo: 100 }, id: '0', index: 0, removedAt: null, updatedAt: expect.any(context.firebase.firestore.Timestamp) }) }, 20000) }) })
import React from "react" import { Link, graphql, useStaticQuery } from "gatsby" import headerStyle from "./header.module.scss" const Header = () => { const data = useStaticQuery(graphql` query { site { siteMetadata { title } } } `) return ( <header className={headerStyle.header}> <Link className={headerStyle.title} to="/"> {data.site.siteMetadata.title} </Link> <nav> <ul className={headerStyle.navLink}> <li> <Link className={headerStyle.navItem} activeClassName={headerStyle.activeNavItem} to="/" > Home </Link> </li> <li> <Link className={headerStyle.navItem} activeClassName={headerStyle.activeNavItem} to="/contact" > Contact </Link> </li> <li> <Link className={headerStyle.navItem} activeClassName={headerStyle.activeNavItem} to="/about" > About </Link> </li> <li> <Link className={headerStyle.navItem} activeClassName={headerStyle.activeNavItem} to="/blog" > Blog </Link> </li> </ul> </nav> </header> ) } export default Header
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2020 Photon Storm Ltd. * @license {@link https://opensource.org/licenses/MIT|MIT License} */ var ALIGN_CONST = require('../../display/align/const'); var Axes = require('./lib/geometry/Axes'); var Bodies = require('./lib/factory/Bodies'); var Body = require('./lib/body/Body'); var BodyBounds = require('./BodyBounds'); var Bounds = require('./lib/geometry/Bounds'); var Class = require('../../utils/Class'); var Collision = require('./lib/collision/Collision'); var Common = require('./lib/core/Common'); var Composite = require('./lib/body/Composite'); var Composites = require('./lib/factory/Composites'); var Constraint = require('./lib/constraint/Constraint'); var Detector = require('./lib/collision/Detector'); var DistanceBetween = require('../../math/distance/DistanceBetween'); var Factory = require('./Factory'); var GetFastValue = require('../../utils/object/GetFastValue'); var GetValue = require('../../utils/object/GetValue'); var MatterAttractors = require('./lib/plugins/MatterAttractors'); var MatterCollisionEvents = require('./lib/plugins/MatterCollisionEvents'); var MatterLib = require('./lib/core/Matter'); var MatterWrap = require('./lib/plugins/MatterWrap'); var Merge = require('../../utils/object/Merge'); var Pair = require('./lib/collision/Pair'); var Pairs = require('./lib/collision/Pairs'); var Plugin = require('./lib/core/Plugin'); var PluginCache = require('../../plugins/PluginCache'); var Query = require('./lib/collision/Query'); var Resolver = require('./lib/collision/Resolver'); var SceneEvents = require('../../scene/events'); var Svg = require('./lib/geometry/Svg'); var Vector = require('./lib/geometry/Vector'); var Vertices = require('./lib/geometry/Vertices'); var World = require('./World'); Common.setDecomp(require('./poly-decomp')); /** * @classdesc * The Phaser Matter plugin provides the ability to use the Matter JS Physics Engine within your Phaser games. * * Unlike Arcade Physics, the other physics system provided with Phaser, Matter JS is a full-body physics system. * It features: * * * Rigid bodies * * Compound bodies * * Composite bodies * * Concave and convex hulls * * Physical properties (mass, area, density etc.) * * Restitution (elastic and inelastic collisions) * * Collisions (broad-phase, mid-phase and narrow-phase) * * Stable stacking and resting * * Conservation of momentum * * Friction and resistance * * Constraints * * Gravity * * Sleeping and static bodies * * Rounded corners (chamfering) * * Views (translate, zoom) * * Collision queries (raycasting, region tests) * * Time scaling (slow-mo, speed-up) * * Configuration of Matter is handled via the Matter World Config object, which can be passed in either the * Phaser Game Config, or Phaser Scene Config. Here is a basic example: * * ```js * physics: { * default: 'matter', * matter: { * enableSleeping: true, * gravity: { * y: 0 * }, * debug: { * showBody: true, * showStaticBody: true * } * } * } * ``` * * This class acts as an interface between a Phaser Scene and a single instance of the Matter Engine. * * Use it to access the most common Matter features and helper functions. * * You can find details, documentation and examples on the Matter JS website: https://brm.io/matter-js/ * * @class MatterPhysics * @memberof Phaser.Physics.Matter * @constructor * @since 3.0.0 * * @param {Phaser.Scene} scene - The Phaser Scene that owns this Matter Physics instance. */ var MatterPhysics = new Class({ initialize: function MatterPhysics (scene) { /** * The Phaser Scene that owns this Matter Physics instance * * @name Phaser.Physics.Matter.MatterPhysics#scene * @type {Phaser.Scene} * @since 3.0.0 */ this.scene = scene; /** * A reference to the Scene Systems that belong to the Scene owning this Matter Physics instance. * * @name Phaser.Physics.Matter.MatterPhysics#systems * @type {Phaser.Scenes.Systems} * @since 3.0.0 */ this.systems = scene.sys; /** * The parsed Matter Configuration object. * * @name Phaser.Physics.Matter.MatterPhysics#config * @type {Phaser.Types.Physics.Matter.MatterWorldConfig} * @since 3.0.0 */ this.config = this.getConfig(); /** * An instance of the Matter World class. This class is responsible for the updating of the * Matter Physics world, as well as handling debug drawing functions. * * @name Phaser.Physics.Matter.MatterPhysics#world * @type {Phaser.Physics.Matter.World} * @since 3.0.0 */ this.world; /** * An instance of the Matter Factory. This class provides lots of functions for creating a * wide variety of physics objects and adds them automatically to the Matter World. * * You can use this class to cut-down on the amount of code required in your game, however, * use of the Factory is entirely optional and should be seen as a development aid. It's * perfectly possible to create and add components to the Matter world without using it. * * @name Phaser.Physics.Matter.MatterPhysics#add * @type {Phaser.Physics.Matter.Factory} * @since 3.0.0 */ this.add; /** * An instance of the Body Bounds class. This class contains functions used for getting the * world position from various points around the bounds of a physics body. * * @name Phaser.Physics.Matter.MatterPhysics#bodyBounds * @type {Phaser.Physics.Matter.BodyBounds} * @since 3.22.0 */ this.bodyBounds; // Body /** * A reference to the `Matter.Body` module. * * The `Matter.Body` module contains methods for creating and manipulating body models. * A `Matter.Body` is a rigid body that can be simulated by a `Matter.Engine`. * Factories for commonly used body configurations (such as rectangles, circles and other polygons) can be found in the `Bodies` module. * * @name Phaser.Physics.Matter.MatterPhysics#body * @type {MatterJS.BodyFactory} * @since 3.18.0 */ this.body = Body; /** * A reference to the `Matter.Composite` module. * * The `Matter.Composite` module contains methods for creating and manipulating composite bodies. * A composite body is a collection of `Matter.Body`, `Matter.Constraint` and other `Matter.Composite`, therefore composites form a tree structure. * It is important to use the functions in this module to modify composites, rather than directly modifying their properties. * Note that the `Matter.World` object is also a type of `Matter.Composite` and as such all composite methods here can also operate on a `Matter.World`. * * @name Phaser.Physics.Matter.MatterPhysics#composite * @type {MatterJS.CompositeFactory} * @since 3.22.0 */ this.composite = Composite; // Collision: /** * A reference to the `Matter.Collision` module. * * The `Matter.Collision` module contains methods for detecting collisions between a given pair of bodies. * * For efficient detection between a list of bodies, see `Matter.Detector` and `Matter.Query`. * * @name Phaser.Physics.Matter.MatterPhysics#collision * @type {MatterJS.Collision} * @since 3.60.0 */ this.collision = Collision; /** * A reference to the `Matter.Detector` module. * * The `Matter.Detector` module contains methods for detecting collisions given a set of pairs. * * @name Phaser.Physics.Matter.MatterPhysics#detector * @type {MatterJS.DetectorFactory} * @since 3.22.0 */ this.detector = Detector; /** * A reference to the `Matter.Pair` module. * * The `Matter.Pair` module contains methods for creating and manipulating collision pairs. * * @name Phaser.Physics.Matter.MatterPhysics#pair * @type {MatterJS.PairFactory} * @since 3.22.0 */ this.pair = Pair; /** * A reference to the `Matter.Pairs` module. * * The `Matter.Pairs` module contains methods for creating and manipulating collision pair sets. * * @name Phaser.Physics.Matter.MatterPhysics#pairs * @type {MatterJS.PairsFactory} * @since 3.22.0 */ this.pairs = Pairs; /** * A reference to the `Matter.Query` module. * * The `Matter.Query` module contains methods for performing collision queries. * * @name Phaser.Physics.Matter.MatterPhysics#query * @type {MatterJS.QueryFactory} * @since 3.22.0 */ this.query = Query; /** * A reference to the `Matter.Resolver` module. * * The `Matter.Resolver` module contains methods for resolving collision pairs. * * @name Phaser.Physics.Matter.MatterPhysics#resolver * @type {MatterJS.ResolverFactory} * @since 3.22.0 */ this.resolver = Resolver; // Constraint /** * A reference to the `Matter.Constraint` module. * * The `Matter.Constraint` module contains methods for creating and manipulating constraints. * Constraints are used for specifying that a fixed distance must be maintained between two bodies (or a body and a fixed world-space position). * The stiffness of constraints can be modified to create springs or elastic. * * @name Phaser.Physics.Matter.MatterPhysics#constraint * @type {MatterJS.ConstraintFactory} * @since 3.22.0 */ this.constraint = Constraint; // Factory /** * A reference to the `Matter.Bodies` module. * * The `Matter.Bodies` module contains factory methods for creating rigid bodies * with commonly used body configurations (such as rectangles, circles and other polygons). * * @name Phaser.Physics.Matter.MatterPhysics#bodies * @type {MatterJS.BodiesFactory} * @since 3.18.0 */ this.bodies = Bodies; /** * A reference to the `Matter.Composites` module. * * The `Matter.Composites` module contains factory methods for creating composite bodies * with commonly used configurations (such as stacks and chains). * * @name Phaser.Physics.Matter.MatterPhysics#composites * @type {MatterJS.CompositesFactory} * @since 3.22.0 */ this.composites = Composites; // Geometry /** * A reference to the `Matter.Axes` module. * * The `Matter.Axes` module contains methods for creating and manipulating sets of axes. * * @name Phaser.Physics.Matter.MatterPhysics#axes * @type {MatterJS.AxesFactory} * @since 3.22.0 */ this.axes = Axes; /** * A reference to the `Matter.Bounds` module. * * The `Matter.Bounds` module contains methods for creating and manipulating axis-aligned bounding boxes (AABB). * * @name Phaser.Physics.Matter.MatterPhysics#bounds * @type {MatterJS.BoundsFactory} * @since 3.22.0 */ this.bounds = Bounds; /** * A reference to the `Matter.Svg` module. * * The `Matter.Svg` module contains methods for converting SVG images into an array of vector points. * * To use this module you also need the SVGPathSeg polyfill: https://github.com/progers/pathseg * * @name Phaser.Physics.Matter.MatterPhysics#svg * @type {MatterJS.SvgFactory} * @since 3.22.0 */ this.svg = Svg; /** * A reference to the `Matter.Vector` module. * * The `Matter.Vector` module contains methods for creating and manipulating vectors. * Vectors are the basis of all the geometry related operations in the engine. * A `Matter.Vector` object is of the form `{ x: 0, y: 0 }`. * * @name Phaser.Physics.Matter.MatterPhysics#vector * @type {MatterJS.VectorFactory} * @since 3.22.0 */ this.vector = Vector; /** * A reference to the `Matter.Vertices` module. * * The `Matter.Vertices` module contains methods for creating and manipulating sets of vertices. * A set of vertices is an array of `Matter.Vector` with additional indexing properties inserted by `Vertices.create`. * A `Matter.Body` maintains a set of vertices to represent the shape of the object (its convex hull). * * @name Phaser.Physics.Matter.MatterPhysics#vertices * @type {MatterJS.VerticesFactory} * @since 3.22.0 */ this.vertices = Vertices; /** * A reference to the `Matter.Vertices` module. * * The `Matter.Vertices` module contains methods for creating and manipulating sets of vertices. * A set of vertices is an array of `Matter.Vector` with additional indexing properties inserted by `Vertices.create`. * A `Matter.Body` maintains a set of vertices to represent the shape of the object (its convex hull). * * @name Phaser.Physics.Matter.MatterPhysics#verts * @type {MatterJS.VerticesFactory} * @since 3.14.0 */ this.verts = Vertices; /** * An internal temp vector used for velocity and force calculations. * * @name Phaser.Physics.Matter.MatterPhysics#_tempVec2 * @type {MatterJS.Vector} * @private * @since 3.22.0 */ this._tempVec2 = Vector.create(); // Matter plugins if (GetValue(this.config, 'plugins.collisionevents', true)) { this.enableCollisionEventsPlugin(); } if (GetValue(this.config, 'plugins.attractors', false)) { this.enableAttractorPlugin(); } if (GetValue(this.config, 'plugins.wrap', false)) { this.enableWrapPlugin(); } Resolver._restingThresh = GetValue(this.config, 'restingThresh', 4); Resolver._restingThreshTangent = GetValue(this.config, 'restingThreshTangent', 6); Resolver._positionDampen = GetValue(this.config, 'positionDampen', 0.9); Resolver._positionWarming = GetValue(this.config, 'positionWarming', 0.8); Resolver._frictionNormalMultiplier = GetValue(this.config, 'frictionNormalMultiplier', 5); scene.sys.events.once(SceneEvents.BOOT, this.boot, this); scene.sys.events.on(SceneEvents.START, this.start, this); }, /** * This method is called automatically, only once, when the Scene is first created. * Do not invoke it directly. * * @method Phaser.Physics.Matter.MatterPhysics#boot * @private * @since 3.5.1 */ boot: function () { this.world = new World(this.scene, this.config); this.add = new Factory(this.world); this.bodyBounds = new BodyBounds(); this.systems.events.once(SceneEvents.DESTROY, this.destroy, this); }, /** * This method is called automatically by the Scene when it is starting up. * It is responsible for creating local systems, properties and listening for Scene events. * Do not invoke it directly. * * @method Phaser.Physics.Matter.MatterPhysics#start * @private * @since 3.5.0 */ start: function () { if (!this.world) { this.world = new World(this.scene, this.config); this.add = new Factory(this.world); } var eventEmitter = this.systems.events; eventEmitter.on(SceneEvents.UPDATE, this.world.update, this.world); eventEmitter.on(SceneEvents.POST_UPDATE, this.world.postUpdate, this.world); eventEmitter.once(SceneEvents.SHUTDOWN, this.shutdown, this); }, /** * This internal method is called when this class starts and retrieves the final Matter World Config. * * @method Phaser.Physics.Matter.MatterPhysics#getConfig * @since 3.0.0 * * @return {Phaser.Types.Physics.Matter.MatterWorldConfig} The Matter World Config. */ getConfig: function () { var gameConfig = this.systems.game.config.physics; var sceneConfig = this.systems.settings.physics; var config = Merge( GetFastValue(sceneConfig, 'matter', {}), GetFastValue(gameConfig, 'matter', {}) ); return config; }, /** * Enables the Matter Attractors Plugin. * * The attractors plugin that makes it easy to apply continual forces on bodies. * It's possible to simulate effects such as wind, gravity and magnetism. * * https://github.com/liabru/matter-attractors * * This method is called automatically if `plugins.attractors` is set in the Matter World Config. * However, you can also call it directly from within your game. * * @method Phaser.Physics.Matter.MatterPhysics#enableAttractorPlugin * @since 3.0.0 * * @return {this} This Matter Physics instance. */ enableAttractorPlugin: function () { Plugin.register(MatterAttractors); Plugin.use(MatterLib, MatterAttractors); return this; }, /** * Enables the Matter Wrap Plugin. * * The coordinate wrapping plugin that automatically wraps the position of bodies such that they always stay * within the given bounds. Upon crossing a boundary the body will appear on the opposite side of the bounds, * while maintaining its velocity. * * https://github.com/liabru/matter-wrap * * This method is called automatically if `plugins.wrap` is set in the Matter World Config. * However, you can also call it directly from within your game. * * @method Phaser.Physics.Matter.MatterPhysics#enableWrapPlugin * @since 3.0.0 * * @return {this} This Matter Physics instance. */ enableWrapPlugin: function () { Plugin.register(MatterWrap); Plugin.use(MatterLib, MatterWrap); return this; }, /** * Enables the Matter Collision Events Plugin. * * Note that this plugin is enabled by default. So you should only ever need to call this * method if you have specifically disabled the plugin in your Matter World Config. * You can disable it by setting `plugins.collisionevents: false` in your Matter World Config. * * This plugin triggers three new events on Matter.Body: * * 1. `onCollide` * 2. `onCollideEnd` * 3. `onCollideActive` * * These events correspond to the Matter.js events `collisionStart`, `collisionActive` and `collisionEnd`, respectively. * You can listen to these events via Matter.Events or they will also be emitted from the Matter World. * * This plugin also extends Matter.Body with three convenience functions: * * `Matter.Body.setOnCollide(callback)` * `Matter.Body.setOnCollideEnd(callback)` * `Matter.Body.setOnCollideActive(callback)` * * You can register event callbacks by providing a function of type (pair: Matter.Pair) => void * * https://github.com/dxu/matter-collision-events * * @method Phaser.Physics.Matter.MatterPhysics#enableCollisionEventsPlugin * @since 3.22.0 * * @return {this} This Matter Physics instance. */ enableCollisionEventsPlugin: function () { Plugin.register(MatterCollisionEvents); Plugin.use(MatterLib, MatterCollisionEvents); return this; }, /** * Pauses the Matter World instance and sets `enabled` to `false`. * * A paused world will not run any simulations for the duration it is paused. * * @method Phaser.Physics.Matter.MatterPhysics#pause * @fires Phaser.Physics.Matter.Events#PAUSE * @since 3.0.0 * * @return {Phaser.Physics.Matter.World} The Matter World object. */ pause: function () { return this.world.pause(); }, /** * Resumes this Matter World instance from a paused state and sets `enabled` to `true`. * * @method Phaser.Physics.Matter.MatterPhysics#resume * @since 3.0.0 * * @return {Phaser.Physics.Matter.World} The Matter World object. */ resume: function () { return this.world.resume(); }, /** * Sets the Matter Engine to run at fixed timestep of 60Hz and enables `autoUpdate`. * If you have set a custom `getDelta` function then this will override it. * * @method Phaser.Physics.Matter.MatterPhysics#set60Hz * @since 3.4.0 * * @return {this} This Matter Physics instance. */ set60Hz: function () { this.world.getDelta = this.world.update60Hz; this.world.autoUpdate = true; return this; }, /** * Sets the Matter Engine to run at fixed timestep of 30Hz and enables `autoUpdate`. * If you have set a custom `getDelta` function then this will override it. * * @method Phaser.Physics.Matter.MatterPhysics#set30Hz * @since 3.4.0 * * @return {this} This Matter Physics instance. */ set30Hz: function () { this.world.getDelta = this.world.update30Hz; this.world.autoUpdate = true; return this; }, /** * Manually advances the physics simulation by one iteration. * * You can optionally pass in the `delta` and `correction` values to be used by Engine.update. * If undefined they use the Matter defaults of 60Hz and no correction. * * Calling `step` directly bypasses any checks of `enabled` or `autoUpdate`. * * It also ignores any custom `getDelta` functions, as you should be passing the delta * value in to this call. * * You can adjust the number of iterations that Engine.update performs internally. * Use the Scene Matter Physics config object to set the following properties: * * positionIterations (defaults to 6) * velocityIterations (defaults to 4) * constraintIterations (defaults to 2) * * Adjusting these values can help performance in certain situations, depending on the physics requirements * of your game. * * @method Phaser.Physics.Matter.MatterPhysics#step * @since 3.4.0 * * @param {number} [delta=16.666] - The delta value. * @param {number} [correction=1] - Optional delta correction value. */ step: function (delta, correction) { this.world.step(delta, correction); }, /** * Checks if the vertices of the given body, or an array of bodies, contains the given point, or not. * * You can pass in either a single body, or an array of bodies to be checked. This method will * return `true` if _any_ of the bodies in the array contain the point. See the `intersectPoint` method if you need * to get a list of intersecting bodies. * * The point should be transformed into the Matter World coordinate system in advance. This happens by * default with Input Pointers, but if you wish to use points from another system you may need to * transform them before passing them. * * @method Phaser.Physics.Matter.MatterPhysics#containsPoint * @since 3.22.0 * * @param {(Phaser.Types.Physics.Matter.MatterBody|Phaser.Types.Physics.Matter.MatterBody[])} body - The body, or an array of bodies, to check against the point. * @param {number} x - The horizontal coordinate of the point. * @param {number} y - The vertical coordinate of the point. * * @return {boolean} `true` if the point is within one of the bodies given, otherwise `false`. */ containsPoint: function (body, x, y) { body = this.getMatterBodies(body); var position = Vector.create(x, y); var result = Query.point(body, position); return (result.length > 0) ? true : false; }, /** * Checks the given coordinates to see if any vertices of the given bodies contain it. * * If no bodies are provided it will search all bodies in the Matter World, including within Composites. * * The coordinates should be transformed into the Matter World coordinate system in advance. This happens by * default with Input Pointers, but if you wish to use coordinates from another system you may need to * transform them before passing them. * * @method Phaser.Physics.Matter.MatterPhysics#intersectPoint * @since 3.22.0 * * @param {number} x - The horizontal coordinate of the point. * @param {number} y - The vertical coordinate of the point. * @param {Phaser.Types.Physics.Matter.MatterBody[]} [bodies] - An array of bodies to check. If not provided it will search all bodies in the world. * * @return {Phaser.Types.Physics.Matter.MatterBody[]} An array of bodies which contain the given point. */ intersectPoint: function (x, y, bodies) { bodies = this.getMatterBodies(bodies); var position = Vector.create(x, y); var output = []; var result = Query.point(bodies, position); result.forEach(function (body) { if (output.indexOf(body) === -1) { output.push(body); } }); return output; }, /** * Checks the given rectangular area to see if any vertices of the given bodies intersect with it. * Or, if the `outside` parameter is set to `true`, it checks to see which bodies do not * intersect with it. * * If no bodies are provided it will search all bodies in the Matter World, including within Composites. * * @method Phaser.Physics.Matter.MatterPhysics#intersectRect * @since 3.22.0 * * @param {number} x - The horizontal coordinate of the top-left of the area. * @param {number} y - The vertical coordinate of the top-left of the area. * @param {number} width - The width of the area. * @param {number} height - The height of the area. * @param {boolean} [outside=false] - If `false` it checks for vertices inside the area, if `true` it checks for vertices outside the area. * @param {Phaser.Types.Physics.Matter.MatterBody[]} [bodies] - An array of bodies to check. If not provided it will search all bodies in the world. * * @return {Phaser.Types.Physics.Matter.MatterBody[]} An array of bodies that intersect with the given area. */ intersectRect: function (x, y, width, height, outside, bodies) { if (outside === undefined) { outside = false; } bodies = this.getMatterBodies(bodies); var bounds = { min: { x: x, y: y }, max: { x: x + width, y: y + height } }; var output = []; var result = Query.region(bodies, bounds, outside); result.forEach(function (body) { if (output.indexOf(body) === -1) { output.push(body); } }); return output; }, /** * Checks the given ray segment to see if any vertices of the given bodies intersect with it. * * If no bodies are provided it will search all bodies in the Matter World. * * The width of the ray can be specified via the `rayWidth` parameter. * * @method Phaser.Physics.Matter.MatterPhysics#intersectRay * @since 3.22.0 * * @param {number} x1 - The horizontal coordinate of the start of the ray segment. * @param {number} y1 - The vertical coordinate of the start of the ray segment. * @param {number} x2 - The horizontal coordinate of the end of the ray segment. * @param {number} y2 - The vertical coordinate of the end of the ray segment. * @param {number} [rayWidth=1] - The width of the ray segment. * @param {Phaser.Types.Physics.Matter.MatterBody[]} [bodies] - An array of bodies to check. If not provided it will search all bodies in the world. * * @return {Phaser.Types.Physics.Matter.MatterBody[]} An array of bodies whos vertices intersect with the ray segment. */ intersectRay: function (x1, y1, x2, y2, rayWidth, bodies) { if (rayWidth === undefined) { rayWidth = 1; } bodies = this.getMatterBodies(bodies); var result = []; var collisions = Query.ray(bodies, Vector.create(x1, y1), Vector.create(x2, y2), rayWidth); for (var i = 0; i < collisions.length; i++) { result.push(collisions[i].body); } return result; }, /** * Checks the given Matter Body to see if it intersects with any of the given bodies. * * If no bodies are provided it will check against all bodies in the Matter World. * * @method Phaser.Physics.Matter.MatterPhysics#intersectBody * @since 3.22.0 * * @param {Phaser.Types.Physics.Matter.MatterBody} body - The target body. * @param {Phaser.Types.Physics.Matter.MatterBody[]} [bodies] - An array of bodies to check the target body against. If not provided it will search all bodies in the world. * * @return {Phaser.Types.Physics.Matter.MatterBody[]} An array of bodies whos vertices intersect with target body. */ intersectBody: function (body, bodies) { bodies = this.getMatterBodies(bodies); var result = []; var collisions = Query.collides(body, bodies); for (var i = 0; i < collisions.length; i++) { var pair = collisions[i]; if (pair.bodyA === body) { result.push(pair.bodyB); } else { result.push(pair.bodyA); } } return result; }, /** * Checks to see if the target body, or an array of target bodies, intersects with any of the given bodies. * * If intersection occurs this method will return `true` and, if provided, invoke the callbacks. * * If no bodies are provided for the second parameter the target will check again all bodies in the Matter World. * * Note that bodies can only overlap if they are in non-colliding collision groups or categories. * * If you provide a `processCallback` then the two bodies that overlap are sent to it. This callback * must return a boolean and is used to allow you to perform additional processing tests before a final * outcome is decided. If it returns `true` then the bodies are finally passed to the `overlapCallback`, if set. * * If you provide an `overlapCallback` then the matching pairs of overlapping bodies will be sent to it. * * Both callbacks have the following signature: `function (bodyA, bodyB, collisionInfo)` where `bodyA` is always * the target body. The `collisionInfo` object contains additional data, such as the angle and depth of penetration. * * @method Phaser.Physics.Matter.MatterPhysics#overlap * @since 3.22.0 * * @param {(Phaser.Types.Physics.Matter.MatterBody|Phaser.Types.Physics.Matter.MatterBody[])} target - The target body, or array of target bodies, to check. * @param {Phaser.Types.Physics.Matter.MatterBody[]} [bodies] - The second body, or array of bodies, to check. If falsey it will check against all bodies in the world. * @param {ArcadePhysicsCallback} [overlapCallback] - An optional callback function that is called if the bodies overlap. * @param {ArcadePhysicsCallback} [processCallback] - An optional callback function that lets you perform additional checks against the two bodies if they overlap. If this is set then `overlapCallback` will only be invoked if this callback returns `true`. * @param {*} [callbackContext] - The context, or scope, in which to run the callbacks. * * @return {boolean} `true` if the target body intersects with _any_ of the bodies given, otherwise `false`. */ overlap: function (target, bodies, overlapCallback, processCallback, callbackContext) { if (overlapCallback === undefined) { overlapCallback = null; } if (processCallback === undefined) { processCallback = null; } if (callbackContext === undefined) { callbackContext = overlapCallback; } if (!Array.isArray(target)) { target = [ target ]; } target = this.getMatterBodies(target); bodies = this.getMatterBodies(bodies); var match = false; for (var i = 0; i < target.length; i++) { var entry = target[i]; var collisions = Query.collides(entry, bodies); for (var c = 0; c < collisions.length; c++) { var info = collisions[c]; var bodyB = (info.bodyA.id === entry.id) ? info.bodyB : info.bodyA; if (!processCallback || processCallback.call(callbackContext, entry, bodyB, info)) { match = true; if (overlapCallback) { overlapCallback.call(callbackContext, entry, bodyB, info); } else if (!processCallback) { // If there are no callbacks we don't need to test every body, just exit when the first is found return true; } } } } return match; }, /** * Sets the collision filter category of all given Matter Bodies to the given value. * * This number must be a power of two between 2^0 (= 1) and 2^31. * * Bodies with different collision groups (see {@link #setCollisionGroup}) will only collide if their collision * categories are included in their collision masks (see {@link #setCollidesWith}). * * @method Phaser.Physics.Matter.MatterPhysics#setCollisionCategory * @since 3.22.0 * * @param {Phaser.Types.Physics.Matter.MatterBody[]} bodies - An array of bodies to update. If falsey it will use all bodies in the world. * @param {number} value - Unique category bitfield. * * @return {this} This Matter Physics instance. */ setCollisionCategory: function (bodies, value) { bodies = this.getMatterBodies(bodies); bodies.forEach(function (body) { body.collisionFilter.category = value; }); return this; }, /** * Sets the collision filter group of all given Matter Bodies to the given value. * * If the group value is zero, or if two Matter Bodies have different group values, * they will collide according to the usual collision filter rules (see {@link #setCollisionCategory} and {@link #setCollisionGroup}). * * If two Matter Bodies have the same positive group value, they will always collide; * if they have the same negative group value they will never collide. * * @method Phaser.Physics.Matter.MatterPhysics#setCollisionGroup * @since 3.22.0 * * @param {Phaser.Types.Physics.Matter.MatterBody[]} bodies - An array of bodies to update. If falsey it will use all bodies in the world. * @param {number} value - Unique group index. * * @return {this} This Matter Physics instance. */ setCollisionGroup: function (bodies, value) { bodies = this.getMatterBodies(bodies); bodies.forEach(function (body) { body.collisionFilter.group = value; }); return this; }, /** * Sets the collision filter mask of all given Matter Bodies to the given value. * * Two Matter Bodies with different collision groups will only collide if each one includes the others * category in its mask based on a bitwise AND operation: `(categoryA & maskB) !== 0` and * `(categoryB & maskA) !== 0` are both true. * * @method Phaser.Physics.Matter.MatterPhysics#setCollidesWith * @since 3.22.0 * * @param {Phaser.Types.Physics.Matter.MatterBody[]} bodies - An array of bodies to update. If falsey it will use all bodies in the world. * @param {(number|number[])} categories - A unique category bitfield, or an array of them. * * @return {this} This Matter Physics instance. */ setCollidesWith: function (bodies, categories) { bodies = this.getMatterBodies(bodies); var flags = 0; if (!Array.isArray(categories)) { flags = categories; } else { for (var i = 0; i < categories.length; i++) { flags |= categories[i]; } } bodies.forEach(function (body) { body.collisionFilter.mask = flags; }); return this; }, /** * Takes an array and returns a new array made from all of the Matter Bodies found in the original array. * * For example, passing in Matter Game Objects, such as a bunch of Matter Sprites, to this method, would * return an array containing all of their native Matter Body objects. * * If the `bodies` argument is falsey, it will return all bodies in the world. * * @method Phaser.Physics.Matter.MatterPhysics#getMatterBodies * @since 3.22.0 * * @param {array} [bodies] - An array of objects to extract the bodies from. If falsey, it will return all bodies in the world. * * @return {MatterJS.BodyType[]} An array of native Matter Body objects. */ getMatterBodies: function (bodies) { if (!bodies) { return this.world.getAllBodies(); } if (!Array.isArray(bodies)) { bodies = [ bodies ]; } var output = []; for (var i = 0; i < bodies.length; i++) { var body = (bodies[i].hasOwnProperty('body')) ? bodies[i].body : bodies[i]; output.push(body); } return output; }, /** * Sets both the horizontal and vertical linear velocity of the physics bodies. * * @method Phaser.Physics.Matter.MatterPhysics#setVelocity * @since 3.22.0 * * @param {(Phaser.Types.Physics.Matter.MatterBody|Phaser.Types.Physics.Matter.MatterBody[])} bodies - Either a single Body, or an array of bodies to update. If falsey it will use all bodies in the world. * @param {number} x - The horizontal linear velocity value. * @param {number} y - The vertical linear velocity value. * * @return {this} This Matter Physics instance. */ setVelocity: function (bodies, x, y) { bodies = this.getMatterBodies(bodies); var vec2 = this._tempVec2; vec2.x = x; vec2.y = y; bodies.forEach(function (body) { Body.setVelocity(body, vec2); }); return this; }, /** * Sets just the horizontal linear velocity of the physics bodies. * The vertical velocity of the body is unchanged. * * @method Phaser.Physics.Matter.MatterPhysics#setVelocityX * @since 3.22.0 * * @param {(Phaser.Types.Physics.Matter.MatterBody|Phaser.Types.Physics.Matter.MatterBody[])} bodies - Either a single Body, or an array of bodies to update. If falsey it will use all bodies in the world. * @param {number} x - The horizontal linear velocity value. * * @return {this} This Matter Physics instance. */ setVelocityX: function (bodies, x) { bodies = this.getMatterBodies(bodies); var vec2 = this._tempVec2; vec2.x = x; bodies.forEach(function (body) { vec2.y = body.velocity.y; Body.setVelocity(body, vec2); }); return this; }, /** * Sets just the vertical linear velocity of the physics bodies. * The horizontal velocity of the body is unchanged. * * @method Phaser.Physics.Matter.MatterPhysics#setVelocityY * @since 3.22.0 * * @param {(Phaser.Types.Physics.Matter.MatterBody|Phaser.Types.Physics.Matter.MatterBody[])} bodies - Either a single Body, or an array of bodies to update. If falsey it will use all bodies in the world. * @param {number} y - The vertical linear velocity value. * * @return {this} This Matter Physics instance. */ setVelocityY: function (bodies, y) { bodies = this.getMatterBodies(bodies); var vec2 = this._tempVec2; vec2.y = y; bodies.forEach(function (body) { vec2.x = body.velocity.x; Body.setVelocity(body, vec2); }); return this; }, /** * Sets the angular velocity of the bodies instantly. * Position, angle, force etc. are unchanged. * * @method Phaser.Physics.Matter.MatterPhysics#setAngularVelocity * @since 3.22.0 * * @param {(Phaser.Types.Physics.Matter.MatterBody|Phaser.Types.Physics.Matter.MatterBody[])} bodies - Either a single Body, or an array of bodies to update. If falsey it will use all bodies in the world. * @param {number} value - The angular velocity. * * @return {this} This Matter Physics instance. */ setAngularVelocity: function (bodies, value) { bodies = this.getMatterBodies(bodies); bodies.forEach(function (body) { Body.setAngularVelocity(body, value); }); return this; }, /** * Applies a force to a body, at the bodies current position, including resulting torque. * * @method Phaser.Physics.Matter.MatterPhysics#applyForce * @since 3.22.0 * * @param {(Phaser.Types.Physics.Matter.MatterBody|Phaser.Types.Physics.Matter.MatterBody[])} bodies - Either a single Body, or an array of bodies to update. If falsey it will use all bodies in the world. * @param {Phaser.Types.Math.Vector2Like} force - A Vector that specifies the force to apply. * * @return {this} This Matter Physics instance. */ applyForce: function (bodies, force) { bodies = this.getMatterBodies(bodies); var vec2 = this._tempVec2; bodies.forEach(function (body) { vec2.x = body.position.x; vec2.y = body.position.y; Body.applyForce(body, vec2, force); }); return this; }, /** * Applies a force to a body, from the given world position, including resulting torque. * If no angle is given, the current body angle is used. * * Use very small speed values, such as 0.1, depending on the mass and required velocity. * * @method Phaser.Physics.Matter.MatterPhysics#applyForceFromPosition * @since 3.22.0 * * @param {(Phaser.Types.Physics.Matter.MatterBody|Phaser.Types.Physics.Matter.MatterBody[])} bodies - Either a single Body, or an array of bodies to update. If falsey it will use all bodies in the world. * @param {Phaser.Types.Math.Vector2Like} position - A Vector that specifies the world-space position to apply the force at. * @param {number} speed - A speed value to be applied to a directional force. * @param {number} [angle] - The angle, in radians, to apply the force from. Leave undefined to use the current body angle. * * @return {this} This Matter Physics instance. */ applyForceFromPosition: function (bodies, position, speed, angle) { bodies = this.getMatterBodies(bodies); var vec2 = this._tempVec2; bodies.forEach(function (body) { if (angle === undefined) { angle = body.angle; } vec2.x = speed * Math.cos(angle); vec2.y = speed * Math.sin(angle); Body.applyForce(body, position, vec2); }); return this; }, /** * Apply a force to a body based on the given angle and speed. * If no angle is given, the current body angle is used. * * Use very small speed values, such as 0.1, depending on the mass and required velocity. * * @method Phaser.Physics.Matter.MatterPhysics#applyForceFromAngle * @since 3.22.0 * * @param {(Phaser.Types.Physics.Matter.MatterBody|Phaser.Types.Physics.Matter.MatterBody[])} bodies - Either a single Body, or an array of bodies to update. If falsey it will use all bodies in the world. * @param {number} speed - A speed value to be applied to a directional force. * @param {number} [angle] - The angle, in radians, to apply the force from. Leave undefined to use the current body angle. * * @return {this} This Matter Physics instance. */ applyForceFromAngle: function (bodies, speed, angle) { bodies = this.getMatterBodies(bodies); var vec2 = this._tempVec2; bodies.forEach(function (body) { if (angle === undefined) { angle = body.angle; } vec2.x = speed * Math.cos(angle); vec2.y = speed * Math.sin(angle); Body.applyForce(body, { x: body.position.x, y: body.position.y }, vec2); }); return this; }, /** * Returns the length of the given constraint, which is the distance between the two points. * * @method Phaser.Physics.Matter.MatterPhysics#getConstraintLength * @since 3.22.0 * * @param {MatterJS.ConstraintType} constraint - The constraint to get the length from. * * @return {number} The length of the constraint. */ getConstraintLength: function (constraint) { var aX = constraint.pointA.x; var aY = constraint.pointA.y; var bX = constraint.pointB.x; var bY = constraint.pointB.y; if (constraint.bodyA) { aX += constraint.bodyA.position.x; aY += constraint.bodyA.position.y; } if (constraint.bodyB) { bX += constraint.bodyB.position.x; bY += constraint.bodyB.position.y; } return DistanceBetween(aX, aY, bX, bY); }, /** * Aligns a Body, or Matter Game Object, against the given coordinates. * * The alignment takes place using the body bounds, which take into consideration things * like body scale and rotation. * * Although a Body has a `position` property, it is based on the center of mass for the body, * not a dimension based center. This makes aligning bodies difficult, especially if they have * rotated or scaled. This method will derive the correct position based on the body bounds and * its center of mass offset, in order to align the body with the given coordinate. * * For example, if you wanted to align a body so it sat in the bottom-center of the * Scene, and the world was 800 x 600 in size: * * ```javascript * this.matter.alignBody(body, 400, 600, Phaser.Display.Align.BOTTOM_CENTER); * ``` * * You pass in 400 for the x coordinate, because that is the center of the world, and 600 for * the y coordinate, as that is the base of the world. * * @method Phaser.Physics.Matter.MatterPhysics#alignBody * @since 3.22.0 * * @param {Phaser.Types.Physics.Matter.MatterBody} body - The Body to align. * @param {number} x - The horizontal position to align the body to. * @param {number} y - The vertical position to align the body to. * @param {number} align - One of the `Phaser.Display.Align` constants, such as `Phaser.Display.Align.TOP_LEFT`. * * @return {this} This Matter Physics instance. */ alignBody: function (body, x, y, align) { body = (body.hasOwnProperty('body')) ? body.body : body; var pos; switch (align) { case ALIGN_CONST.TOP_LEFT: case ALIGN_CONST.LEFT_TOP: pos = this.bodyBounds.getTopLeft(body, x, y); break; case ALIGN_CONST.TOP_CENTER: pos = this.bodyBounds.getTopCenter(body, x, y); break; case ALIGN_CONST.TOP_RIGHT: case ALIGN_CONST.RIGHT_TOP: pos = this.bodyBounds.getTopRight(body, x, y); break; case ALIGN_CONST.LEFT_CENTER: pos = this.bodyBounds.getLeftCenter(body, x, y); break; case ALIGN_CONST.CENTER: pos = this.bodyBounds.getCenter(body, x, y); break; case ALIGN_CONST.RIGHT_CENTER: pos = this.bodyBounds.getRightCenter(body, x, y); break; case ALIGN_CONST.LEFT_BOTTOM: case ALIGN_CONST.BOTTOM_LEFT: pos = this.bodyBounds.getBottomLeft(body, x, y); break; case ALIGN_CONST.BOTTOM_CENTER: pos = this.bodyBounds.getBottomCenter(body, x, y); break; case ALIGN_CONST.BOTTOM_RIGHT: case ALIGN_CONST.RIGHT_BOTTOM: pos = this.bodyBounds.getBottomRight(body, x, y); break; } if (pos) { Body.setPosition(body, pos); } return this; }, /** * The Scene that owns this plugin is shutting down. * We need to kill and reset all internal properties as well as stop listening to Scene events. * * @method Phaser.Physics.Matter.MatterPhysics#shutdown * @private * @since 3.0.0 */ shutdown: function () { var eventEmitter = this.systems.events; if (this.world) { eventEmitter.off(SceneEvents.UPDATE, this.world.update, this.world); eventEmitter.off(SceneEvents.POST_UPDATE, this.world.postUpdate, this.world); } eventEmitter.off(SceneEvents.SHUTDOWN, this.shutdown, this); if (this.add) { this.add.destroy(); } if (this.world) { this.world.destroy(); } this.add = null; this.world = null; }, /** * The Scene that owns this plugin is being destroyed. * We need to shutdown and then kill off all external references. * * @method Phaser.Physics.Matter.MatterPhysics#destroy * @private * @since 3.0.0 */ destroy: function () { this.shutdown(); this.scene.sys.events.off(SceneEvents.START, this.start, this); this.scene = null; this.systems = null; } }); PluginCache.register('MatterPhysics', MatterPhysics, 'matterPhysics'); module.exports = MatterPhysics;
/* ***** BEGIN LICENSE BLOCK ***** * Distributed under the BSD license: * * Copyright (c) 2010, Ajax.org B.V. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Ajax.org B.V. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ***** END LICENSE BLOCK ***** */ ace.define('ace/ext/static_highlight', ['require', 'exports', 'module' , 'ace/edit_session', 'ace/layer/text', 'ace/config'], function(require, exports, module) { var EditSession = require("../edit_session").EditSession; var TextLayer = require("../layer/text").Text; var baseStyles = ".ace_static_highlight {\ font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', 'Droid Sans Mono', monospace;\ font-size: 12px;\ }\ .ace_static_highlight .ace_gutter {\ width: 25px !important;\ display: block;\ float: left;\ text-align: right;\ padding: 0 3px 0 0;\ margin-right: 3px;\ position: static !important;\ }\ .ace_static_highlight .ace_line { clear: both; }\ .ace_static_highlight .ace_gutter-cell {\ -moz-user-select: -moz-none;\ -khtml-user-select: none;\ -webkit-user-select: none;\ user-select: none;\ }"; var config = require("../config"); exports.render = function(input, mode, theme, lineStart, disableGutter, callback) { var waiting = 0; var modeCache = EditSession.prototype.$modes; if (typeof theme == "string") { waiting++; config.loadModule(['theme', theme], function(m) { theme = m; --waiting || done(); }); } if (typeof mode == "string") { waiting++; config.loadModule(['mode', mode], function(m) { if (!modeCache[mode]) modeCache[mode] = new m.Mode(); mode = modeCache[mode]; --waiting || done(); }); } function done() { var result = exports.renderSync(input, mode, theme, lineStart, disableGutter); return callback ? callback(result) : result; } return waiting || done(); }; exports.renderSync = function(input, mode, theme, lineStart, disableGutter) { lineStart = parseInt(lineStart || 1, 10); var session = new EditSession(""); session.setUseWorker(false); session.setMode(mode); var textLayer = new TextLayer(document.createElement("div")); textLayer.setSession(session); textLayer.config = { characterWidth: 10, lineHeight: 20 }; session.setValue(input); var stringBuilder = []; var length = session.getLength(); for(var ix = 0; ix < length; ix++) { stringBuilder.push("<div class='ace_line'>"); if (!disableGutter) stringBuilder.push("<span class='ace_gutter ace_gutter-cell' unselectable='on'>" + (ix + lineStart) + "</span>"); textLayer.$renderLine(stringBuilder, ix, true, false); stringBuilder.push("</div>"); } var html = "<div class='" + theme.cssClass + "'>" + "<div class='ace_static_highlight'>" + stringBuilder.join("") + "</div>" + "</div>"; textLayer.destroy(); return { css: baseStyles + theme.cssText, html: html }; }; });
/** * Created by zhongfan on 2017/11/1. */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; import Icon from 'react-weui/build/packages'; import classNames from 'classnames'; import deprecationWarning from 'react-weui/build/packages'; /** * weui style uploader * */ export default class Uploader extends Component { static propTypes = { /** * title of uploader * */ title: PropTypes.string, /** * max amount of allow file * */ maxCount: PropTypes.number, /** * maxWidth of image for uploader to compress * */ maxWidth: PropTypes.number, /** * when file change, pass property `(event, file)` * */ onChange: PropTypes.func, /** * when there is error, pass property `msg` * */ onError: PropTypes.func, /** * array of photos thumbnails to indicator status, include property `url`, `status`, `error` * */ files: PropTypes.array, /** * languages object, with property `maxError` * */ lang: PropTypes.object }; static defaultProps = { title: '图片上传', maxCount: 4, maxWidth: 500, files: [], onChange: undefined, onError: undefined, lang: { maxError: maxCount => `最多只能上传${maxCount}张图片` } }; /** * Detecting vertical squash in loaded image. * Fixes a bug which squash image vertically while drawing into canvas for some images. * This is a bug in iOS6 devices. This function from https://github.com/stomita/ios-imagefile-megapixel * With react fix by n7best */ detectVerticalSquash(img) { let data; let ih = img.naturalHeight; let canvas = document.createElement('canvas'); canvas.width = 1; canvas.height = ih; let ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0); try { // Prevent cross origin error data = ctx.getImageData(0, 0, 1, ih).data; } catch (err) { // hopeless, assume the image is well and good. console.log('Cannot check verticalSquash: CORS?'); return 1; } // search image edge pixel position in case it is squashed vertically. let sy = 0; let ey = ih; let py = ih; while (py > sy) { let alpha = data[(py - 1) * 4 + 3]; if (alpha === 0) { ey = py; } else { sy = py; } py = (ey + sy) >> 1; } let ratio = (py / ih); return (ratio === 0) ? 1 : ratio; } handleFile(file, cb) { let reader; if (typeof FileReader !== 'undefined') { reader = new FileReader(); } else { if (window.FileReader) reader = new window.FileReader(); } reader.onload = e => { let img; if (typeof Image !== 'undefined') { img = new Image(); } else { if (window.Image) img = new window.Image(); } img.onload = ()=>{ let w = Math.min(this.props.maxWidth, img.width); let h = img.height * (w / img.width); let canvas = document.createElement('canvas'); let ctx = canvas.getContext('2d'); //check canvas support, for test if (ctx){ //patch subsampling bug //http://jsfiddle.net/gWY2a/24/ let drawImage = ctx.drawImage; ctx.drawImage = (_img, sx, sy, sw, sh, dx, dy, dw, dh) => { let vertSquashRatio = 1; // Detect if img param is indeed image if (!!_img && _img.nodeName === 'IMG') { vertSquashRatio = this.detectVerticalSquash(_img); if (typeof sw === 'undefined') (sw = _img.naturalWidth); if (typeof sh === 'undefined') (sh = _img.naturalHeight); } // Execute several cases (Firefox does not handle undefined as no param) // by call (apply is bad performance) if (arguments.length === 9) drawImage.call(ctx, _img, sx, sy, sw, sh, dx, dy, dw, dh / vertSquashRatio); else if (typeof sw !== 'undefined') drawImage.call(ctx, _img, sx, sy, sw, sh / vertSquashRatio); else drawImage.call(ctx, _img, sx, sy); }; canvas.width = w; canvas.height = h; ctx.drawImage(img, 0, 0, w, h); let base64 = canvas.toDataURL('image/png'); cb({ nativeFile: file, lastModified: file.lastModified, lastModifiedDate: file.lastModifiedDate, name: file.name, size: file.size, type: file.type, data: base64 }, e); } else { cb(file, e); } }; img.src = e.target.result; }; reader.readAsDataURL(file); } handleChange(e) { const langs = this.props.lang; let _files = e.target.files; if (_files.length === 0) return; if (this.props.files.length >= this.props.maxCount) { this.props.onError(langs.maxError(this.props.maxCount)); return; } for (let key in _files) { if (!_files.hasOwnProperty(key)) continue; let file = _files[key]; this.handleFile(file, (_file, _e)=>{ if (this.props.onChange) this.props.onChange(_file, _e); ReactDOM.findDOMNode(this.refs.uploader).value = ''; }, e); } } renderFiles(){ return this.props.files.map((file, idx)=>{ let {url, error, status, onClick, ...others} = file; let fileStyle = { backgroundImage: `url(${url})` }; let cls = classNames({ 'weui-uploader__file': true, 'weui-uploader__file_status': error || status }); if (onClick){ deprecationWarning('File onClick', 'Uploader onFileClick'); } let handleFileClick = onClick ? onClick : e => { if (this.props.onFileClick) this.props.onFileClick(e, file, idx); }; return ( <li className={cls} key={idx} style={fileStyle} onClick={handleFileClick} {...others}> { error || status ? <div className="weui-uploader__file-content"> { error ? <Icon value="warn" /> : status } </div> : false } </li> ); }); } render(){ const { className, title, maxCount, files, onChange, onFileClick, ...others } = this.props; const inputProps = Object.assign({}, others); delete inputProps.lang; delete inputProps.onError; delete inputProps.maxWidth; const cls = classNames({ 'weui-uploader': true, [className]: className }); return ( <div className={cls}> <div className="weui-uploader__hd"> <p className="weui-uploader__title">{title}</p> <div className="weui-uploader__info">{files.length}/{maxCount}</div> </div> <div className="weui-uploader__bd"> <ul className="weui-uploader__files"> {this.renderFiles()} </ul> <div className="weui-uploader__input-box"> <input ref="uploader"//let react to reset after onchange className="weui-uploader__input" type="file" accept="image/*" onChange={this.handleChange.bind(this)} {...inputProps} /> </div> </div> </div> ); } };
// 页面初始化 $(function(){ //var DOCU_content_store; init(); getDeclareCode(); set_cqp_info(); query_cqp_record_url(); }); //保存或修改报关单 function add_declare(){ /*changeStatusToSure($("#dec-ctn-content")); changeStatusToSure($("#doc-content"));*/ var options = { url : '/declare/addDeclareMain.action', type : 'POST', dataType:'json', beforeSubmit : before_submit, success: show_result, error : show_error }; $("#form1").ajaxSubmit(options); var nums = $("#packagesNum").val(); var price = $("#price_total .t_price").text(); //var cnName = $("#businessCompany").val(); $("#numbers_2").val() || $("#numbers_2").val(nums); $("#price_2").val() || $("#price_2").val(price); //$("#businessCompany_2").val() || $("#businessCompany_2").val(cnName); return false; } function before_submit(){ if($("#businessCompany").val().length > 15){ alert("经营单位中文名不能超过15位"); return false; } if($("#productionCompany").val().length > 15){ alert("发货单位中文名不能超过15位"); return false; } if($("#declareCompany").val().length > 15){ alert("申请单位中文名不能超过15位"); return false; } if($("#businessCompanyCode").val().length != 10){ alert("经营单位代码只能是10位"); return false; } if($("#productionCompanyCode").val().length != 10){ alert("发货单位代码只能是10位"); return false; } if($("#declareCompanyCode").val().length != 10){ alert("申请单位代码只能是10位"); return false; } } function show_result(data){ if(data.flag == 1){ var cloudQpId = data.cloudQpId; $("#cqp_id").val(cloudQpId) query_cqp_record(cloudQpId); alert("保存成功"); }else{ alert("error"); } } function show_error(){ alert("error"); } //把表格里的未确认的数据自动置为确认状态 function changeStatusToSure($container){ var $container_list = $($container).find("ul"); $container_list.each(function(){ var el = $(this).find(".dec-ok"); var li = el.parents("ul").find(".input_li"); if(el.text()=="确定") { el.text("修改"); li.each(function(){ var div = $(this).find("div"); var inputText = div.find("input[type=text]"); var select = div.find("select"); var selected = select.find("option:selected"); var inputHid = $(this).find("input[type=hidden]"); var addClass = $(this).find(".sum").size()&&$(this).find(".sum").val()!=""?"add_sum add_div":"add_div"; div.html(inputText.val() || selected.text()).addClass(addClass); inputText.remove(); select.hide(); inputHid.val(inputText.val()||selected.val()); }) } }) } //查询报关单记录 function query_cqp_record(cloudQpId){ if(cloudQpId == null || cloudQpId == "" || cloudQpId == undefined){ cloudQpId = $("#cqp_id").val() } if(cloudQpId == ""){ alert("流水号不能为空"); return false; } clearAllData(); $.ajax({ type : "post" , url : "/declare/queryDfgCtn.action?cloudQpId="+cloudQpId, dataType : "json" , async:false, success : function(data){ if(data.flag == "1"){ var result = eval(data.result); if(result != null){ //第一个TAB页赋值(还差 类型、企业性质) $("#cloudQpId").val(result.declareMain.cloudQpId); if (result.declareReceipt != null) { $("#receiptDes").text(result.declareReceipt.receiptNote); } else { $("#receiptDes").text(""); } $("#ieFlag").val(result.declareMain.ieFlag); $("#status").val(result.declareMain.status); $("#eportNo").val(result.declareMain.eportNo); $("#customNo").val(result.declareMain.customNo); $("#preentryNo").val(result.declareMain.preentryNo); $("#declareLocation_v").val((result.declareMain.declareLocationCode||"")==""?"":(result.declareMain.declareLocationCode+" "+result.declareMain.declareLocation)); $("#declareLocation").val(result.declareMain.declareLocation); $("#declareLocationCode").val(result.declareMain.declareLocationCode); $("#exportLocation_v").val((result.declareMain.exportLocationCode||"")==""?"":(result.declareMain.exportLocationCode+" "+result.declareMain.exportLocation)); $("#exportLocation").val(result.declareMain.exportLocation); $("#exportLocationCode").val(result.declareMain.exportLocationCode); $("#enrolNo").val(result.declareMain.enrolNo); $("#exportDate").val(result.declareMain.exportDate); $("#declareDate").val(result.declareMain.declareDate); $("#businessCompanyCode").val(result.declareMain.businessCompanyCode); $("#businessCompany").val(result.declareMain.businessCompany); $("#transportMode_v").val((result.declareMain.transportModeCode||"")==""?"":(result.declareMain.transportModeCode+" "+result.declareMain.transportMode)); $("#transportMode").val(result.declareMain.transportMode); $("#transportModeCode").val(result.declareMain.transportModeCode||""); $("#transportName").val(result.declareMain.transportName); $("#transportId").val(result.declareMain.transportId); $("#billNo").val(result.declareMain.billNo); $("#productionCompanyCode").val(result.declareMain.productionCompanyCode); $("#productionCompany").val(result.declareMain.productionCompany); $("#tradeMode_v").val((result.declareMain.tradeModeCode||"")==""?"":(result.declareMain.tradeModeCode+" "+result.declareMain.tradeMode)); $("#tradeMode").val(result.declareMain.tradeMode); $("#tradeModeCode").val(result.declareMain.tradeModeCode||""); $("#cutMode_v").val((result.declareMain.cutModeCode||"")==""?"":(result.declareMain.cutModeCode+" "+result.declareMain.cutMode)); $("#cutMode").val(result.declareMain.cutMode); $("#cutModeCode").val(result.declareMain.cutModeCode||""); $("#payMode_v").val(result.declareMain.payModeCode==""?"":(result.declareMain.payModeCode+" "+result.declareMain.payMode)); $("#payMode").val(result.declareMain.payMode); $("#payModeCode").val(result.declareMain.payModeCode); $("#declareCompany").val(result.declareMain.declareCompany); $("#declareCompanyCode").val(result.declareMain.declareCompanyCode); $("#arrivedCountry_v").val(result.declareMain.arrivedCountryCode==""?"":(result.declareMain.arrivedCountryCode+" "+result.declareMain.arrivedCountry)); $("#arrivedCountry").val(result.declareMain.arrivedCountry); $("#arrivedCountryCode").val(result.declareMain.arrivedCountryCode); $("#arrivedPort_v").val(result.declareMain.arrivedPortCode==""?"":(result.declareMain.arrivedPortCode+" "+result.declareMain.arrivedPort)); $("#arrivedPort").val(result.declareMain.arrivedPort); $("#arrivedPortCode").val(result.declareMain.arrivedPortCode); $("#goodsSource_v").val(result.declareMain.goodsSourceCode==""?"":(result.declareMain.goodsSourceCode+" "+result.declareMain.goodsSource)); $("#goodsSource").val(result.declareMain.goodsSource); $("#goodsSourceCode").val(result.declareMain.goodsSourceCode); $("#tradingCountry_v").val(result.declareMain.tradingCountryCode==""?"":(result.declareMain.tradingCountryCode+" "+result.declareMain.tradingCountry)); $("#tradingCountry").val(result.declareMain.tradingCountry); $("#tradingCountryCode").val(result.declareMain.tradingCountryCode); $("#transactionMode_v").val((result.declareMain.transactionModeCode||"")==""?"":(result.declareMain.transactionModeCode+" "+result.declareMain.transactionMode)); $("#transactionMode").val(result.declareMain.transactionMode); $("#transactionModeCode").val(result.declareMain.transactionModeCode||""); $("#freightMark_v").val((result.declareMain.freightMark||"")==""?"":(result.declareMain.freightMark+" "+result.declareMain.freightMarkChn)); $("#freightMark").val(result.declareMain.freightMark||""); $("#freightMarkChn").val(result.declareMain.freightMarkChn); $("#freightRate").val(result.declareMain.freightRate||""); $("#freightCurrency_v").val(result.declareMain.freightCurrency==""?"":(result.declareMain.freightCurrency+" "+result.declareMain.freightCurrencyChn)); $("#freightCurrency").val(result.declareMain.freightCurrency); $("#freightCurrencyChn").val(result.declareMain.freightCurrencyChn); $("#insuranceMark_v").val((result.declareMain.insuranceMark||"")==""?"":(result.declareMain.insuranceMark+" "+result.declareMain.insuranceMarkChn)); $("#insuranceMark").val(result.declareMain.insuranceMark||""); $("#insuranceMarkChn").val(result.declareMain.insuranceMarkChn); $("#insuranceRate").val(result.declareMain.insuranceRate||""); $("#insuranceCurrency_v").val(result.declareMain.insuranceCurrency==""?"":(result.declareMain.insuranceCurrency+" "+result.declareMain.insuranceCurrencyChn)); $("#insuranceCurrency").val(result.declareMain.insuranceCurrency); $("#insuranceCurrencyChn").val(result.declareMain.insuranceCurrencyChn); $("#extrasMark_v").val((result.declareMain.extrasMark||"")==""?"":(result.declareMain.extrasMark+" "+result.declareMain.extrasMarkChn)); $("#extrasMark").val(result.declareMain.extrasMark||""); $("#extrasMarkChn").val(result.declareMain.extrasMarkChn); $("#extrasRate").val(result.declareMain.extrasRate||""); $("#extrasCurrency_v").val(result.declareMain.extrasCurrency==""?"":(result.declareMain.extrasCurrency+" "+result.declareMain.extrasCurrencyChn)); $("#extrasCurrency").val(result.declareMain.extrasCurrency); $("#extrasCurrencyChn").val(result.declareMain.extrasCurrencyChn); $("#packagesNum").val(result.declareMain.packagesNum||""); $("#packingType_v").val((result.declareMain.packingTypeCode||"")==""?"":(result.declareMain.packingTypeCode+" "+result.declareMain.packingType)); $("#packingType").val(result.declareMain.packingType); $("#packingTypeCode").val(result.declareMain.packingTypeCode||""); $("#grossWeight").val(result.declareMain.grossWeight||""); $("#netWeight").val(result.declareMain.netWeight||""); $("#remark").val(result.declareMain.remark); $("#contractNo").val(result.declareMain.contractNo); $("#entryType_v").val(result.declareMain.entryTypeCode==""?"":(result.declareMain.entryTypeCode+" "+result.declareMain.entryType)); $("#entryType").val(result.declareMain.entryType); $("#entryTypeCode").val(result.declareMain.entryTypeCode); $("#taxCorporationType").val(result.declareMain.taxCorporationType); $("#licenseNo").val(result.declareMain.licenseNo); //$("#approvalNo").val(result.declareMain.approvalNo); $("#relativeEntryNo").val(result.declareMain.relativeEntryNo); $("#relativeEnrolNo").val(result.declareMain.relativeEnrolNo); $("#warehouseNo").val(result.declareMain.warehouseNo); $("#cyNo").val(result.declareMain.cyNo); $("#vouchFlag").val(result.declareMain.vouchFlag); if(result.declareMain.vouchFlag == "Y"){ $("#vouchFlag").prop("checked", "checked"); }else{ $("#vouchFlag").prop("checked", ""); } //第一个TAB页表格的数据 $(result.declareCtnList).each(function(index, obj){ table2.append([ { name:"ctn_no", value:index+1, hiddenName: "declareCtnList["+index+"].ctn_no" }, { name:"containerNo", value:obj.containerNo || "", hiddenName: "declareCtnList["+index+"].containerNo" }, { name:"containerSize", value:obj.containerSize || "", hiddenName: "declareCtnList["+index+"].containerSize" }, { name:"containerWeight", value:obj.containerWeight || "", hiddenName: "declareCtnList["+index+"].containerWeight" }, { name:"declareCtnId", value:obj.declareCtnId, hiddenName: "declareCtnList["+index+"].declareCtnId" } ]); /*ctnContent += "<ul class='clearfix' data-no="+index+">"+ " <li class='ctn-1 input_li' upper='Y'>"+ " <div>"+ " <input type='text' name='' id='' value='"+obj.containerNo+"' onkeyup='Convert(this)'/>"+ " </div>"+ " <input type='hidden' name='declareCtnList["+index+"].containerNo' value='"+obj.containerNo+"'/>"+ " </li>"+ " <li class='ctn-2 input_li'>"+ " <div>"+ " <input type='text' name='' id='' value='"+obj.containerSize+"'/>"+ " </div>"+ " <input type='hidden' name='declareCtnList["+index+"].containerSize' value='"+obj.containerSize+"'/>"+ " </li>"+ " <li class='ctn-3 input_li' onlyNum='Y'>"+ " <div>"+ " <input type='text' name='' id='' value='"+(obj.containerWeight||"")+"' onkeyup=\"value=value.replace(/[^\\d\\.]/g,'')\"/>"+ " </div>"+ " <input type='hidden' name='declareCtnList["+index+"].containerWeight' value='"+(obj.containerWeight||"")+"'/>"+ " </li>"+ " <li class='ctn-4 input_li no_width'>"+ " <div style='display:none'>"+ " <input type='text' name='' id='' value='"+obj.declareCtnId+"'/>"+ " </div>"+ " <input type='hidden' name='declareCtnList["+index+"].declareCtnId' value='"+obj.declareCtnId+"'/>"+ " </li>"+ " <li class='ctn-5'><a href='javascript:;' class='dec-ok'>确定</a><a href='javascript:;' class='dec-del'>删除</a></li>"+ "</ul>"*/ }) //$("#dec-ctn-content").html(ctnContent); //第二个TAB页表格的数据 //var docContent = "" $(result.declareDocList).each(function(index, obj){ table3.append([ { name:"att_no", value:index+1, hiddenName: "declareDocList["+index+"].att_no" }, { name:"docAttachedCode", value:obj.docAttachedCode+" "+obj.docAttached, hiddenName: "declareDocList["+index+"].docAttachedCode" }, { name:"docAttachedNo", value:obj.docAttachedNo, hiddenName: "declareDocList["+index+"].docAttachedNo" }, { name:"declareDocId", value:obj.declareDocId, hiddenName: "declareDocList["+index+"].declareDocId" } ]); /*docContent += "<ul class='clearfix' data-no="+index+">"+ " <li class='doc-1 input_li'>"+ " <div>"+ " <input type='text' name='' id='' value='"+obj.docAttachedCode+" "+obj.docAttached+"'/>"+ " </div>"+ " <input type='hidden' name='declareDocList["+index+"].docAttachedCode' value='"+obj.docAttachedCode+" "+obj.docAttached+"'/>"+ " </li>"+ " <li class='doc-2 input_li'>"+ " <div>"+ " <input type='text' name='' id='' value='"+obj.docAttachedNo+"'/>"+ " </div>"+ " <input type='hidden' name='declareDocList["+index+"].docAttachedNo' value='"+obj.docAttachedNo+"'/>"+ " </li>"+ " <li class='doc-3 input_li no_width'>"+ " <div style='display:none'>"+ " <input type='text' name='' id='' value='"+obj.declareDocId+"'/>"+ " </div>"+ " <input type='hidden' name='declareDocList["+index+"].declareDocId' value='"+obj.declareDocId+"'/>"+ " </li>"+ " <li class='doc-4'><a href='javascript:;' class='dec-ok'>确定</a><a href='javascript:;' class='dec-del'>删除</a></li>"+ "</ul>"*/ }) //$("#doc-content").html(docContent); //第三个TAB页表格的数据 //var goodsContent = "" $(result.declareGoodsList).each(function(index, obj){ table1.append([ { name:"goodsSeq", value:(obj.goodsSeq||""), hiddenName: "declareGoodsList["+index+"].goodsSeq" }, { name:"hsCode", value:obj.hsCode.substring(0,8), hiddenName: "declareGoodsList["+index+"].hsCode" }, { name:"enrolNo", value:(obj.enrolNo||""), hiddenName: "declareGoodsList["+index+"].enrolNo" }, { name:"goodsName", value:obj.goodsName, hiddenName: "declareGoodsList["+index+"].goodsName" }, { name:"arrivalCountry", value:(obj.arrivalCountryCode == ""?"":(obj.arrivalCountryCode+" "+obj.arrivalCountry)), hiddenName: "declareGoodsList["+index+"].arrivalCountry" }, { name:"quantity", value:(obj.quantity||""), hiddenName: "declareGoodsList["+index+"].quantity" }, { name:"quantityUnit", value:(obj.quantityUnit==""?"":(obj.quantityUnit+" "+obj.quantityUnitChn)), hiddenName: "declareGoodsList["+index+"].quantityUnit" }, { name:"unitPrice", value:(obj.unitPrice||""), hiddenName: "declareGoodsList["+index+"].unitPrice" }, { name:"sum", value:(obj.totalPrice||""), hiddenName: "declareGoodsList["+index+"].totalPrice" }, { name:"currency", value:(obj.currency==""?"":(obj.currency+" "+obj.currencyChn)), hiddenName: "declareGoodsList["+index+"].currency" }, { name:"dutyMode", value:(obj.dutyMode==""?"":(obj.dutyMode+" "+obj.dutyModeChn)), hiddenName: "declareGoodsList["+index+"].dutyMode" }, { name:"extraNo", value:obj.extraNo, hiddenName: "declareGoodsList["+index+"].extraNo" }, { name:"goodsVersion", value:(obj.goodsVersion||""), hiddenName: "declareGoodsList["+index+"].goodsVersion" }, { name:"goodsNo", value:obj.goodsNo, hiddenName: "declareGoodsList["+index+"].goodsNo" }, { name:"use", value:obj.use, hiddenName: "declareGoodsList["+index+"].use" }, { name:"model", value:obj.model, hiddenName: "declareGoodsList["+index+"].model" }, { name:"firstQuantity", value:(obj.firstQuantity||""), hiddenName: "declareGoodsList["+index+"].firstQuantity" }, { name:"firstUnit", value:(obj.firstUnit==""?"":(obj.firstUnit+" "+obj.firstUnitChn)), hiddenName: "declareGoodsList["+index+"].firstUnit" }, { name:"secondQuantity", value:(obj.secondQuantity||""), hiddenName: "declareGoodsList["+index+"].secondQuantity" }, { name:"secondUnit", value:(obj.secondUnit==""?"":(obj.secondUnit+" "+obj.secondUnitChn)), hiddenName: "declareGoodsList["+index+"].secondUnit" }, { name:"processingCharges", value:(obj.processingCharges||""), hiddenName: "declareGoodsList["+index+"].processingCharges" }, { name:"declareGoodsId", value:obj.declareGoodsId, hiddenName: "declareGoodsList["+index+"].declareGoodsId" } ]); /*goodsContent += "<ul class='clearfix' data-no="+index+">"+ " <li class='d-li11 input_li'>"+ " <div class='add_div' data-index='goodsSeq'>"+(obj.goodsSeq||"")+"</div>"+ " <input type='hidden' name='declareGoodsList["+index+"].goodsSeq' value='"+(obj.goodsSeq||"")+"'/>"+ " </li>"+ " <li class='d-li1 input_li'>"+ " <div class='add_div' data-index='hsCode'>"+(obj.hsCode.substring(0,8))+"</div>"+ " <input type='hidden' name='declareGoodsList["+index+"].hsCode' value='"+(obj.hsCode.substring(0,8))+"'/>"+ " </li>"+ " <li class='d-li2 input_li'>"+ " <div class='add_div' data-index='enrolNo'>"+(obj.enrolNo||"")+"</div>"+ " <input type='hidden' name='declareGoodsList["+index+"].enrolNo' value='"+(obj.enrolNo||"")+"'/>"+ " </li>"+ " <li class='d-li3 input_li'>"+ " <div class='add_div' data-index='goodsName'>"+obj.goodsName+"</div>"+ " <input type='hidden' name='declareGoodsList["+index+"].goodsName' value='"+obj.goodsName+"'/>"+ " </li>"+ " <li class='d-li4 input_li'>"+ " <div class='add_div' data-index='arrivalCountry'>"+obj.arrivalCountryCode+" "+obj.arrivalCountry+"</div>"+ " <input type='hidden' name='declareGoodsList["+index+"].arrivalCountry' value='"+(obj.arrivalCountryCode == ""?"":(obj.arrivalCountryCode+" "+obj.arrivalCountry))+"'/>"+ " </li>"+ " <li class='d-li5 input_li'>"+ " <div class='add_div' data-index='quantity'>"+(obj.quantity||"")+"</div>"+ " <input type='hidden' name='declareGoodsList["+index+"].quantity' value='"+(obj.quantity||"")+"'/>"+ " </li>"+ " <li class='d-li6 input_li'>"+ " <div class='add_div' data-index='quantityUnit'>"+obj.quantityUnit+" "+obj.quantityUnitChn+"</div>"+ " <input type='hidden' name='declareGoodsList["+index+"].quantityUnit' value='"+(obj.quantityUnit==""?"":(obj.quantityUnit+" "+obj.quantityUnitChn))+"'/>"+ " </li>"+ " <li class='d-li7 input_li'>"+ " <div class='add_div' data-index='unitPrice'>"+(obj.unitPrice||"")+"</div>"+ " <input type='hidden' name='declareGoodsList["+index+"].unitPrice' value='"+(obj.unitPrice||"")+"'/>"+ " </li>"+ " <li class='d-li8 input_li'>"+ " <div class='add_sum add_div' data-index='sum'>"+(obj.totalPrice||"")+"</div>"+ " <input type='hidden' name='declareGoodsList["+index+"].totalPrice' value='"+(obj.totalPrice||"")+"'/>"+ " </li>"+ " <li class='d-li9 input_li'>"+ " <div class='add_div' data-index='currency'>"+obj.currency+" "+obj.currencyChn+"</div>"+ " <input type='hidden' name='declareGoodsList["+index+"].currency' value='"+(obj.currency==""?"":(obj.currency+" "+obj.currencyChn))+"'/>"+ " </li>"+ " <li class='d-li10 input_li'>"+ " <div class='add_div' data-index='dutyMode'>"+obj.dutyMode+" "+obj.dutyModeChn+"</div>"+ " <input type='hidden' name='declareGoodsList["+index+"].dutyMode' value='"+(obj.dutyMode==""?"":(obj.dutyMode+" "+obj.dutyModeChn))+"'/>"+ " </li>"+ " <li class='d-li12 input_li no_width'>"+ " <div class='add_div' data-index='extraNo' style='display:none'>"+obj.extraNo+"</div>"+ " <input type='hidden' name='declareGoodsList["+index+"].extraNo' value='"+obj.extraNo+"'/>"+ " </li>"+ " <li class='d-li13 input_li no_width'>"+ " <div class='add_div' data-index='goodsVersion' style='display:none'>"+(obj.goodsVersion||"")+"</div>"+ " <input type='hidden' name='declareGoodsList["+index+"].goodsVersion' value='"+(obj.goodsVersion||"")+"'/>"+ " </li>"+ " <li class='d-li14 input_li no_width'>"+ " <div class='add_div' data-index='goodsNo' style='display:none'>"+obj.goodsNo+"</div>"+ " <input type='hidden' name='declareGoodsList["+index+"].goodsNo' value='"+obj.goodsNo+"'/>"+ " </li>"+ " <li class='d-li15 input_li no_width'>"+ " <div class='add_div' data-index='use' style='display:none'>"+obj.use+"</div>"+ " <input type='hidden' name='declareGoodsList["+index+"].use' value='"+obj.use+"'/>"+ " </li>"+ " <li class='d-li16 input_li no_width'>"+ " <div class='add_div' data-index='model' style='display:none'>"+obj.model+"</div>"+ " <input type='hidden' name='declareGoodsList["+index+"].model' value='"+obj.model+"'/>"+ " </li>"+ " <li class='d-li17 input_li no_width'>"+ " <div class='add_div' data-index='firstQuantity' style='display:none'>"+(obj.firstQuantity||"")+"</div>"+ " <input type='hidden' name='declareGoodsList["+index+"].firstQuantity' value='"+(obj.firstQuantity||"")+"'/>"+ " </li>"+ " <li class='d-li18 input_li no_width'>"+ " <div class='add_div' data-index='firstUnit' style='display:none'>"+obj.firstUnit+" "+obj.firstUnitChn+"</div>"+ " <input type='hidden' name='declareGoodsList["+index+"].firstUnit' value='"+(obj.firstUnit==""?"":(obj.firstUnit+" "+obj.firstUnitChn))+"'/>"+ " </li>"+ " <li class='d-li19 input_li no_width'>"+ " <div class='add_div' data-index='secondQuantity' style='display:none'>"+(obj.secondQuantity||"")+"</div>"+ " <input type='hidden' name='declareGoodsList["+index+"].secondQuantity' value='"+(obj.secondQuantity||"")+"'/>"+ " </li>"+ " <li class='d-li20 input_li no_width'>"+ " <div class='add_div' data-index='secondUnit' style='display:none'>"+(!obj.secondUnit?"":(obj.secondUnit+" "+obj.secondUnitChn))+"</div>"+ " <input type='hidden' name='declareGoodsList["+index+"].secondUnit' value='"+(obj.secondUnit==""?"":(obj.secondUnit+" "+obj.secondUnitChn))+"'/>"+ " </li>"+ " <li class='d-li21 input_li no_width'>"+ " <div class='add_div' data-index='processingCharges' style='display:none'>"+(obj.processingCharges||"")+"</div>"+ " <input type='hidden' name='declareGoodsList["+index+"].processingCharges' value='"+(obj.processingCharges||"")+"'/>"+ " </li>"+ " <li class='d-li22 input_li no_width'>"+ " <div class='add_div' data-index='declareGoodsId' style='display:none'>"+obj.declareGoodsId+"</div>"+ " <input type='hidden' name='declareGoodsList["+index+"].declareGoodsId' value='"+obj.declareGoodsId+"'/>"+ " </li>"+ " <li class='d-li23'>"+ " <a href='javascript:;' class='dec-del'>删除</a>&nbsp;<a href='javascript:;' class='dec-copy'>复制</a>"+ " </li>"+ "</ul>"*/ }) //$("#goods-content").html(goodsContent); sum(); //第二个TAB页数据 if(result.declareOther != null){ $("#invoiceNo_2").val(result.declareOther.invoiceNo); $("#numbers_2").val(result.declareOther.numbers); $("#unit_2").val(result.declareOther.unit); $("#creditNo_2").val(result.declareOther.creditNo); $("#invoiceSigner_2").val(result.declareOther.invoiceSigner); $("#price_2").val(result.declareOther.price); $("#currency_2").val(result.declareOther.currency); $("#businessCompany_2").val(result.declareOther.businessCompany); $("#businessCompanyEn_2").val(result.declareOther.businessCompanyEn); $("#businessCompanyAddr_2").val(result.declareOther.businessCompanyAddr); $("#customCompamy_2").val(result.declareOther.customCompamy); $("#customTel_2").val(result.declareOther.customTel); $("#customCompamyAddr_2").val(result.declareOther.customCompamyAddr); $("#customsBroker_2").val(result.declareOther.customsBroker); $("#rmbRate_2").val(result.declareOther.rmbRate); $("#usdRate_2").val(result.declareOther.usdRate); $("#tax_2").val(result.declareOther.tax); } sum(); uploadLogo("edocFile_1", "00000001", result.declareMain.cloudQpId); uploadLogo("edocFile_2", "00000002", result.declareMain.cloudQpId); uploadLogo("edocFile_3", "00000003", result.declareMain.cloudQpId); uploadLogo("edocFile_4", "00000004", result.declareMain.cloudQpId); uploadLogo("edocFile_5", "00000005", result.declareMain.cloudQpId); uploadLogo("edocFile_6", "00000006", result.declareMain.cloudQpId); uploadLogo("edocFile_7", "00000007", result.declareMain.cloudQpId); uploadLogo("edocFile_8", "00000008", result.declareMain.cloudQpId); //uploadLogo("edocFile_9", "10000001", result.declareMain.cloudQpId); uploadLogo("edocFile_10", "10000002", result.declareMain.cloudQpId); $("#edocFile_9").attr("cloudQpId", result.declareMain.cloudQpId); $(result.declareEdocList).each(function(index, obj){ if(obj.edocCode == "10000001"){ $("#edocFile_9").val(obj.edocId) } }) } }else if(data.flag == '0'){ alert("请先登陆") }else if(data.flag == '3'){ alert("未查询到数据") }else{ alert("对不起,查询异常,请稍后再试") } }, error : function(data){ } }); } //查询报关单记录 function copy_cqp_record(cloudQpId){ if(cloudQpId == null || cloudQpId == "" || cloudQpId == undefined){ cloudQpId = $("#cqp_id").val() } if(cloudQpId == ""){ alert("流水号不能为空"); return false; } clearAllData(); $.ajax({ type : "post" , url : "/declare/queryDfgCtn.action?cloudQpId="+cloudQpId, dataType : "json" , async:false, success : function(data){ if(data.flag == "1"){ var result = eval(data.result); if(result != null){ //第一个TAB页赋值(还差 类型、企业性质) //$("#cloudQpId").val(result.declareMain.cloudQpId); $("#ieFlag").val(result.declareMain.ieFlag); $("#status").val(result.declareMain.status); $("#eportNo").val(result.declareMain.eportNo); $("#customNo").val(result.declareMain.customNo); $("#preentryNo").val(result.declareMain.preentryNo); $("#declareLocation_v").val((result.declareMain.declareLocationCode||"")==""?"":(result.declareMain.declareLocationCode+" "+result.declareMain.declareLocation)); $("#declareLocation").val(result.declareMain.declareLocation); $("#declareLocationCode").val(result.declareMain.declareLocationCode); $("#exportLocation_v").val((result.declareMain.exportLocationCode||"")==""?"":(result.declareMain.exportLocationCode+" "+result.declareMain.exportLocation)); $("#exportLocation").val(result.declareMain.exportLocation); $("#exportLocationCode").val(result.declareMain.exportLocationCode); $("#enrolNo").val(result.declareMain.enrolNo); $("#exportDate").val(result.declareMain.exportDate); $("#declareDate").val(result.declareMain.declareDate); $("#businessCompanyCode").val(result.declareMain.businessCompanyCode); $("#businessCompany").val(result.declareMain.businessCompany); $("#transportMode_v").val((result.declareMain.transportModeCode||"")==""?"":(result.declareMain.transportModeCode+" "+result.declareMain.transportMode)); $("#transportMode").val(result.declareMain.transportMode); $("#transportModeCode").val(result.declareMain.transportModeCode||""); $("#transportName").val(result.declareMain.transportName); $("#transportId").val(result.declareMain.transportId); $("#billNo").val(result.declareMain.billNo); $("#productionCompanyCode").val(result.declareMain.productionCompanyCode); $("#productionCompany").val(result.declareMain.productionCompany); $("#tradeMode_v").val((result.declareMain.tradeModeCode||"")==""?"":(result.declareMain.tradeModeCode+" "+result.declareMain.tradeMode)); $("#tradeMode").val(result.declareMain.tradeMode); $("#tradeModeCode").val(result.declareMain.tradeModeCode||""); $("#cutMode_v").val((result.declareMain.cutModeCode||"")==""?"":(result.declareMain.cutModeCode+" "+result.declareMain.cutMode)); $("#cutMode").val(result.declareMain.cutMode); $("#cutModeCode").val(result.declareMain.cutModeCode||""); $("#payMode_v").val(result.declareMain.payModeCode==""?"":(result.declareMain.payModeCode+" "+result.declareMain.payMode)); $("#payMode").val(result.declareMain.payMode); $("#payModeCode").val(result.declareMain.payModeCode); $("#declareCompany").val(result.declareMain.declareCompany); $("#declareCompanyCode").val(result.declareMain.declareCompanyCode); $("#arrivedCountry_v").val(result.declareMain.arrivedCountryCode==""?"":(result.declareMain.arrivedCountryCode+" "+result.declareMain.arrivedCountry)); $("#arrivedCountry").val(result.declareMain.arrivedCountry); $("#arrivedCountryCode").val(result.declareMain.arrivedCountryCode); $("#arrivedPort_v").val(result.declareMain.arrivedPortCode==""?"":(result.declareMain.arrivedPortCode+" "+result.declareMain.arrivedPort)); $("#arrivedPort").val(result.declareMain.arrivedPort); $("#arrivedPortCode").val(result.declareMain.arrivedPortCode); $("#goodsSource_v").val(result.declareMain.goodsSourceCode==""?"":(result.declareMain.goodsSourceCode+" "+result.declareMain.goodsSource)); $("#goodsSource").val(result.declareMain.goodsSource); $("#goodsSourceCode").val(result.declareMain.goodsSourceCode); $("#tradingCountry_v").val(result.declareMain.tradingCountryCode==""?"":(result.declareMain.tradingCountryCode+" "+result.declareMain.tradingCountry)); $("#tradingCountry").val(result.declareMain.tradingCountry); $("#tradingCountryCode").val(result.declareMain.tradingCountryCode); $("#transactionMode_v").val((result.declareMain.transactionModeCode||"")==""?"":(result.declareMain.transactionModeCode+" "+result.declareMain.transactionMode)); $("#transactionMode").val(result.declareMain.transactionMode); $("#transactionModeCode").val(result.declareMain.transactionModeCode||""); $("#freightMark_v").val((result.declareMain.freightMark||"")==""?"":(result.declareMain.freightMark+" "+result.declareMain.freightMarkChn)); $("#freightMark").val(result.declareMain.freightMark||""); $("#freightMarkChn").val(result.declareMain.freightMarkChn); $("#freightRate").val(result.declareMain.freightRate||""); $("#freightCurrency_v").val(result.declareMain.freightCurrency==""?"":(result.declareMain.freightCurrency+" "+result.declareMain.freightCurrencyChn)); $("#freightCurrency").val(result.declareMain.freightCurrency); $("#freightCurrencyChn").val(result.declareMain.freightCurrencyChn); $("#insuranceMark_v").val((result.declareMain.insuranceMark||"")==""?"":(result.declareMain.insuranceMark+" "+result.declareMain.insuranceMarkChn)); $("#insuranceMark").val(result.declareMain.insuranceMark||""); $("#insuranceMarkChn").val(result.declareMain.insuranceMarkChn); $("#insuranceRate").val(result.declareMain.insuranceRate||""); $("#insuranceCurrency_v").val(result.declareMain.insuranceCurrency==""?"":(result.declareMain.insuranceCurrency+" "+result.declareMain.insuranceCurrencyChn)); $("#insuranceCurrency").val(result.declareMain.insuranceCurrency); $("#insuranceCurrencyChn").val(result.declareMain.insuranceCurrencyChn); $("#extrasMark_v").val((result.declareMain.extrasMark||"")==""?"":(result.declareMain.extrasMark+" "+result.declareMain.extrasMarkChn)); $("#extrasMark").val(result.declareMain.extrasMark||""); $("#extrasMarkChn").val(result.declareMain.extrasMarkChn); $("#extrasRate").val(result.declareMain.extrasRate||""); $("#extrasCurrency_v").val(result.declareMain.extrasCurrency==""?"":(result.declareMain.extrasCurrency+" "+result.declareMain.extrasCurrencyChn)); $("#extrasCurrency").val(result.declareMain.extrasCurrency); $("#extrasCurrencyChn").val(result.declareMain.extrasCurrencyChn); $("#packagesNum").val(result.declareMain.packagesNum||""); $("#packingType_v").val((result.declareMain.packingTypeCode||"")==""?"":(result.declareMain.packingTypeCode+" "+result.declareMain.packingType)); $("#packingType").val(result.declareMain.packingType); $("#packingTypeCode").val(result.declareMain.packingTypeCode||""); $("#grossWeight").val(result.declareMain.grossWeight||""); $("#netWeight").val(result.declareMain.netWeight||""); $("#remark").val(result.declareMain.remark); $("#contractNo").val(result.declareMain.contractNo); $("#entryType_v").val(result.declareMain.entryTypeCode==""?"":(result.declareMain.entryTypeCode+" "+result.declareMain.entryType)); $("#entryType").val(result.declareMain.entryType); $("#entryTypeCode").val(result.declareMain.entryTypeCode); $("#taxCorporationType").val(result.declareMain.taxCorporationType); $("#licenseNo").val(result.declareMain.licenseNo); //$("#approvalNo").val(result.declareMain.approvalNo); $("#relativeEntryNo").val(result.declareMain.relativeEntryNo); $("#relativeEnrolNo").val(result.declareMain.relativeEnrolNo); $("#warehouseNo").val(result.declareMain.warehouseNo); $("#cyNo").val(result.declareMain.cyNo); $("#vouchFlag").val(result.declareMain.vouchFlag); if(result.declareMain.vouchFlag == "Y"){ $("#vouchFlag").prop("checked", "checked"); }else{ $("#vouchFlag").prop("checked", ""); } //第一个TAB页表格的数据 //var ctnContent = "" $(result.declareCtnList).each(function(index, obj){ table2.append([ { name:"ctn_no", value:index+1, hiddenName: "declareCtnList["+index+"].ctn_no" }, { name:"containerNo", value:obj.containerNo || "", hiddenName: "declareCtnList["+index+"].containerNo" }, { name:"containerSize", value:obj.containerSize || "", hiddenName: "declareCtnList["+index+"].containerSize" }, { name:"containerWeight", value:obj.containerWeight || "", hiddenName: "declareCtnList["+index+"].containerWeight" }, { name:"declareCtnId", value:obj.declareCtnId, hiddenName: "declareCtnList["+index+"].declareCtnId" } ]) }) //$("#dec-ctn-content").html(ctnContent); //第二个TAB页表格的数据 //var docContent = "" $(result.declareDocList).each(function(index, obj){ table3.append([ { name:"att_no", value:index+1, hiddenName: "declareDocList["+index+"].att_no" }, { name:"docAttachedCode", value:obj.docAttachedCode+" "+obj.docAttached, hiddenName: "declareDocList["+index+"].docAttachedCode" }, { name:"docAttachedNo", value:obj.docAttachedNo, hiddenName: "declareDocList["+index+"].docAttachedNo" }, { name:"declareDocId", value:obj.declareDocId, hiddenName: "declareDocList["+index+"].declareDocId" } ]); }) //$("#doc-content").html(docContent); //第三个TAB页表格的数据 //var goodsContent = "" $(result.declareGoodsList).each(function(index, obj){ table1.append([ { name:"goodsSeq", value:(obj.goodsSeq||""), hiddenName: "declareGoodsList["+index+"].goodsSeq" }, { name:"hsCode", value:obj.hsCode.substring(0,8), hiddenName: "declareGoodsList["+index+"].hsCode" }, { name:"enrolNo", value:(obj.enrolNo||""), hiddenName: "declareGoodsList["+index+"].enrolNo" }, { name:"goodsName", value:obj.goodsName, hiddenName: "declareGoodsList["+index+"].goodsName" }, { name:"arrivalCountry", value:(obj.arrivalCountryCode == ""?"":(obj.arrivalCountryCode+" "+obj.arrivalCountry)), hiddenName: "declareGoodsList["+index+"].arrivalCountry" }, { name:"quantity", value:(obj.quantity||""), hiddenName: "declareGoodsList["+index+"].quantity" }, { name:"quantityUnit", value:(obj.quantityUnit==""?"":(obj.quantityUnit+" "+obj.quantityUnitChn)), hiddenName: "declareGoodsList["+index+"].quantityUnit" }, { name:"unitPrice", value:(obj.unitPrice||""), hiddenName: "declareGoodsList["+index+"].unitPrice" }, { name:"sum", value:(obj.totalPrice||""), hiddenName: "declareGoodsList["+index+"].totalPrice" }, { name:"currency", value:(obj.currency==""?"":(obj.currency+" "+obj.currencyChn)), hiddenName: "declareGoodsList["+index+"].currency" }, { name:"dutyMode", value:(obj.dutyMode==""?"":(obj.dutyMode+" "+obj.dutyModeChn)), hiddenName: "declareGoodsList["+index+"].dutyMode" }, { name:"extraNo", value:obj.extraNo, hiddenName: "declareGoodsList["+index+"].extraNo" }, { name:"goodsVersion", value:(obj.goodsVersion||""), hiddenName: "declareGoodsList["+index+"].goodsVersion" }, { name:"goodsNo", value:obj.goodsNo, hiddenName: "declareGoodsList["+index+"].goodsNo" }, { name:"use", value:obj.use, hiddenName: "declareGoodsList["+index+"].use" }, { name:"model", value:obj.model, hiddenName: "declareGoodsList["+index+"].model" }, { name:"firstQuantity", value:(obj.firstQuantity||""), hiddenName: "declareGoodsList["+index+"].firstQuantity" }, { name:"firstUnit", value:(obj.firstUnit==""?"":(obj.firstUnit+" "+obj.firstUnitChn)), hiddenName: "declareGoodsList["+index+"].firstUnit" }, { name:"secondQuantity", value:(obj.secondQuantity||""), hiddenName: "declareGoodsList["+index+"].secondQuantity" }, { name:"secondUnit", value:(obj.secondUnit==""?"":(obj.secondUnit+" "+obj.secondUnitChn)), hiddenName: "declareGoodsList["+index+"].secondUnit" }, { name:"processingCharges", value:(obj.processingCharges||""), hiddenName: "declareGoodsList["+index+"].processingCharges" }, { name:"declareGoodsId", value:obj.declareGoodsId, hiddenName: "declareGoodsList["+index+"].declareGoodsId" } ]); }) //$("#goods-content").html(goodsContent); sum(); //第二个TAB页数据 if(result.declareOther != null){ $("#invoiceNo_2").val(result.declareOther.invoiceNo); $("#numbers_2").val(result.declareOther.numbers); $("#unit_2").val(result.declareOther.unit); $("#creditNo_2").val(result.declareOther.creditNo); $("#invoiceSigner_2").val(result.declareOther.invoiceSigner); $("#price_2").val(result.declareOther.price); $("#currency_2").val(result.declareOther.currency); $("#businessCompany_2").val(result.declareOther.businessCompany); $("#businessCompanyEn_2").val(result.declareOther.businessCompanyEn); $("#businessCompanyAddr_2").val(result.declareOther.businessCompanyAddr); $("#customCompamy_2").val(result.declareOther.customCompamy); $("#customTel_2").val(result.declareOther.customTel); $("#customCompamyAddr_2").val(result.declareOther.customCompamyAddr); $("#customsBroker_2").val(result.declareOther.customsBroker); $("#rmbRate_2").val(result.declareOther.rmbRate); $("#usdRate_2").val(result.declareOther.usdRate); $("#tax_2").val(result.declareOther.tax); } sum(); uploadLogo("edocFile_1", "00000001", result.declareMain.cloudQpId); uploadLogo("edocFile_2", "00000002", result.declareMain.cloudQpId); uploadLogo("edocFile_3", "00000003", result.declareMain.cloudQpId); uploadLogo("edocFile_4", "00000004", result.declareMain.cloudQpId); uploadLogo("edocFile_5", "00000005", result.declareMain.cloudQpId); uploadLogo("edocFile_6", "00000006", result.declareMain.cloudQpId); uploadLogo("edocFile_7", "00000007", result.declareMain.cloudQpId); uploadLogo("edocFile_8", "00000008", result.declareMain.cloudQpId); //uploadLogo("edocFile_9", "10000001", result.declareMain.cloudQpId); uploadLogo("edocFile_10", "10000002", result.declareMain.cloudQpId); $("#edocFile_9").attr("cloudQpId", result.declareMain.cloudQpId); $(result.declareEdocList).each(function(index, obj){ if(obj.edocCode == "10000001"){ $("#edocFile_9").val(obj.edocId) } }) } alert("复制"+cloudQpId+"成功,请按需修改后保存"); }else if(data.flag == '0'){ alert("请先登陆") }else if(data.flag == '3'){ alert("未查询到数据") }else{ alert("对不起,查询异常,请稍后再试") } }, error : function(data){ } }); } //查询报关单记录(通过URL传递的密文) function query_cqp_record_url(){ var cloudQpId = getQuery("cloudQpId"); if(cloudQpId == null || cloudQpId == "" || cloudQpId == undefined){ return false; } $.ajax({ type : "post" , url : "/declare/queryAesDfgCtn.action?cloudQpId="+cloudQpId, dataType : "json" , async:false, success : function(data){ if(data.flag == "1"){ var result = eval(data.result); if(result != null){ //第一个TAB页赋值(还差 类型、企业性质) $("#cqp_id").val(result.declareMain.cloudQpId); $("#cloudQpId").val(result.declareMain.cloudQpId); if (result.declareReceipt != null) { $("#receiptDes").text(result.declareReceipt.receiptNote); } else { $("#receiptDes").text(""); } $("#ieFlag").val(result.declareMain.ieFlag); $("#status").val(result.declareMain.status); $("#eportNo").val(result.declareMain.eportNo); $("#customNo").val(result.declareMain.customNo); $("#preentryNo").val(result.declareMain.preentryNo); $("#declareLocation_v").val((result.declareMain.declareLocationCode||"")==""?"":(result.declareMain.declareLocationCode+" "+result.declareMain.declareLocation)); $("#declareLocation").val(result.declareMain.declareLocation); $("#declareLocationCode").val(result.declareMain.declareLocationCode); $("#exportLocation_v").val((result.declareMain.exportLocationCode||"")==""?"":(result.declareMain.exportLocationCode+" "+result.declareMain.exportLocation)); $("#exportLocation").val(result.declareMain.exportLocation); $("#exportLocationCode").val(result.declareMain.exportLocationCode); $("#enrolNo").val(result.declareMain.enrolNo); $("#exportDate").val(result.declareMain.exportDate); $("#declareDate").val(result.declareMain.declareDate); $("#businessCompanyCode").val(result.declareMain.businessCompanyCode); $("#businessCompany").val(result.declareMain.businessCompany); $("#transportMode_v").val((result.declareMain.transportModeCode||"")==""?"":(result.declareMain.transportModeCode+" "+result.declareMain.transportMode)); $("#transportMode").val(result.declareMain.transportMode); $("#transportModeCode").val(result.declareMain.transportModeCode||""); $("#transportName").val(result.declareMain.transportName); $("#transportId").val(result.declareMain.transportId); $("#billNo").val(result.declareMain.billNo); $("#productionCompanyCode").val(result.declareMain.productionCompanyCode); $("#productionCompany").val(result.declareMain.productionCompany); $("#tradeMode_v").val((result.declareMain.tradeModeCode||"")==""?"":(result.declareMain.tradeModeCode+" "+result.declareMain.tradeMode)); $("#tradeMode").val(result.declareMain.tradeMode); $("#tradeModeCode").val(result.declareMain.tradeModeCode||""); $("#cutMode_v").val((result.declareMain.cutModeCode||"")==""?"":(result.declareMain.cutModeCode+" "+result.declareMain.cutMode)); $("#cutMode").val(result.declareMain.cutMode); $("#cutModeCode").val(result.declareMain.cutModeCode||""); $("#payMode_v").val(result.declareMain.payModeCode==""?"":(result.declareMain.payModeCode+" "+result.declareMain.payMode)); $("#payMode").val(result.declareMain.payMode); $("#payModeCode").val(result.declareMain.payModeCode); $("#declareCompany").val(result.declareMain.declareCompany); $("#declareCompanyCode").val(result.declareMain.declareCompanyCode); $("#arrivedCountry_v").val(result.declareMain.arrivedCountryCode==""?"":(result.declareMain.arrivedCountryCode+" "+result.declareMain.arrivedCountry)); $("#arrivedCountry").val(result.declareMain.arrivedCountry); $("#arrivedCountryCode").val(result.declareMain.arrivedCountryCode); $("#arrivedPort_v").val(result.declareMain.arrivedPortCode==""?"":(result.declareMain.arrivedPortCode+" "+result.declareMain.arrivedPort)); $("#arrivedPort").val(result.declareMain.arrivedPort); $("#arrivedPortCode").val(result.declareMain.arrivedPortCode); $("#goodsSource_v").val(result.declareMain.goodsSourceCode==""?"":(result.declareMain.goodsSourceCode+" "+result.declareMain.goodsSource)); $("#goodsSource").val(result.declareMain.goodsSource); $("#goodsSourceCode").val(result.declareMain.goodsSourceCode); $("#tradingCountry_v").val(result.declareMain.tradingCountryCode==""?"":(result.declareMain.tradingCountryCode+" "+result.declareMain.tradingCountry)); $("#tradingCountry").val(result.declareMain.tradingCountry); $("#tradingCountryCode").val(result.declareMain.tradingCountryCode); $("#transactionMode_v").val((result.declareMain.transactionModeCode||"")==""?"":(result.declareMain.transactionModeCode+" "+result.declareMain.transactionMode)); $("#transactionMode").val(result.declareMain.transactionMode); $("#transactionModeCode").val(result.declareMain.transactionModeCode||""); $("#freightMark_v").val((result.declareMain.freightMark||"")==""?"":(result.declareMain.freightMark+" "+result.declareMain.freightMarkChn)); $("#freightMark").val(result.declareMain.freightMark||""); $("#freightMarkChn").val(result.declareMain.freightMarkChn); $("#freightRate").val(result.declareMain.freightRate||""); $("#freightCurrency_v").val(result.declareMain.freightCurrency==""?"":(result.declareMain.freightCurrency+" "+result.declareMain.freightCurrencyChn)); $("#freightCurrency").val(result.declareMain.freightCurrency); $("#freightCurrencyChn").val(result.declareMain.freightCurrencyChn); $("#insuranceMark_v").val((result.declareMain.insuranceMark||"")==""?"":(result.declareMain.insuranceMark+" "+result.declareMain.insuranceMarkChn)); $("#insuranceMark").val(result.declareMain.insuranceMark||""); $("#insuranceMarkChn").val(result.declareMain.insuranceMarkChn); $("#insuranceRate").val(result.declareMain.insuranceRate||""); $("#insuranceCurrency_v").val(result.declareMain.insuranceCurrency==""?"":(result.declareMain.insuranceCurrency+" "+result.declareMain.insuranceCurrencyChn)); $("#insuranceCurrency").val(result.declareMain.insuranceCurrency); $("#insuranceCurrencyChn").val(result.declareMain.insuranceCurrencyChn); $("#extrasMark_v").val((result.declareMain.extrasMark||"")==""?"":(result.declareMain.extrasMark+" "+result.declareMain.extrasMarkChn)); $("#extrasMark").val(result.declareMain.extrasMark||""); $("#extrasMarkChn").val(result.declareMain.extrasMarkChn); $("#extrasRate").val(result.declareMain.extrasRate||""); $("#extrasCurrency_v").val(result.declareMain.extrasCurrency==""?"":(result.declareMain.extrasCurrency+" "+result.declareMain.extrasCurrencyChn)); $("#extrasCurrency").val(result.declareMain.extrasCurrency); $("#extrasCurrencyChn").val(result.declareMain.extrasCurrencyChn); $("#packagesNum").val(result.declareMain.packagesNum||""); $("#packingType_v").val((result.declareMain.packingTypeCode||"")==""?"":(result.declareMain.packingTypeCode+" "+result.declareMain.packingType)); $("#packingType").val(result.declareMain.packingType); $("#packingTypeCode").val(result.declareMain.packingTypeCode||""); $("#grossWeight").val(result.declareMain.grossWeight||""); $("#netWeight").val(result.declareMain.netWeight||""); $("#remark").val(result.declareMain.remark); $("#contractNo").val(result.declareMain.contractNo); $("#entryType_v").val(result.declareMain.entryTypeCode==""?"":(result.declareMain.entryTypeCode+" "+result.declareMain.entryType)); $("#entryType").val(result.declareMain.entryType); $("#entryTypeCode").val(result.declareMain.entryTypeCode); $("#taxCorporationType").val(result.declareMain.taxCorporationType); $("#licenseNo").val(result.declareMain.licenseNo); //$("#approvalNo").val(result.declareMain.approvalNo); $("#relativeEntryNo").val(result.declareMain.relativeEntryNo); $("#relativeEnrolNo").val(result.declareMain.relativeEnrolNo); $("#warehouseNo").val(result.declareMain.warehouseNo); $("#cyNo").val(result.declareMain.cyNo); $("#vouchFlag").val(result.declareMain.vouchFlag); if(result.declareMain.vouchFlag == "Y"){ $("#vouchFlag").prop("checked", "checked"); }else{ $("#vouchFlag").prop("checked", ""); } //第一个TAB页表格的数据 //var ctnContent = "" $(result.declareCtnList).each(function(index, obj){ table2.append([ { name:"ctn_no", value:index+1, hiddenName: "declareCtnList["+index+"].ctn_no" }, { name:"containerNo", value:obj.containerNo || "", hiddenName: "declareCtnList["+index+"].containerNo" }, { name:"containerSize", value:obj.containerSize || "", hiddenName: "declareCtnList["+index+"].containerSize" }, { name:"containerWeight", value:obj.containerWeight || "", hiddenName: "declareCtnList["+index+"].containerWeight" }, { name:"declareCtnId", value:obj.declareCtnId, hiddenName: "declareCtnList["+index+"].declareCtnId" } ]) }) //$("#dec-ctn-content").html(ctnContent); //第二个TAB页表格的数据 //var docContent = "" $(result.declareDocList).each(function(index, obj){ table3.append([ { name:"att_no", value:index+1, hiddenName: "declareDocList["+index+"].att_no" }, { name:"docAttachedCode", value:obj.docAttachedCode+" "+obj.docAttached, hiddenName: "declareDocList["+index+"].docAttachedCode" }, { name:"docAttachedNo", value:obj.docAttachedNo, hiddenName: "declareDocList["+index+"].docAttachedNo" }, { name:"declareDocId", value:obj.declareDocId, hiddenName: "declareDocList["+index+"].declareDocId" } ]); }) //$("#doc-content").html(docContent); //第三个TAB页表格的数据 //var goodsContent = "" $(result.declareGoodsList).each(function(index, obj){ table1.append([ { name:"goodsSeq", value:(obj.goodsSeq||""), hiddenName: "declareGoodsList["+index+"].goodsSeq" }, { name:"hsCode", value:obj.hsCode.substring(0,8), hiddenName: "declareGoodsList["+index+"].hsCode" }, { name:"enrolNo", value:(obj.enrolNo||""), hiddenName: "declareGoodsList["+index+"].enrolNo" }, { name:"goodsName", value:obj.goodsName, hiddenName: "declareGoodsList["+index+"].goodsName" }, { name:"arrivalCountry", value:(obj.arrivalCountryCode == ""?"":(obj.arrivalCountryCode+" "+obj.arrivalCountry)), hiddenName: "declareGoodsList["+index+"].arrivalCountry" }, { name:"quantity", value:(obj.quantity||""), hiddenName: "declareGoodsList["+index+"].quantity" }, { name:"quantityUnit", value:(obj.quantityUnit==""?"":(obj.quantityUnit+" "+obj.quantityUnitChn)), hiddenName: "declareGoodsList["+index+"].quantityUnit" }, { name:"unitPrice", value:(obj.unitPrice||""), hiddenName: "declareGoodsList["+index+"].unitPrice" }, { name:"sum", value:(obj.totalPrice||""), hiddenName: "declareGoodsList["+index+"].totalPrice" }, { name:"currency", value:(obj.currency==""?"":(obj.currency+" "+obj.currencyChn)), hiddenName: "declareGoodsList["+index+"].currency" }, { name:"dutyMode", value:(obj.dutyMode==""?"":(obj.dutyMode+" "+obj.dutyModeChn)), hiddenName: "declareGoodsList["+index+"].dutyMode" }, { name:"extraNo", value:obj.hsCode.slice(-2), hiddenName: "declareGoodsList["+index+"].extraNo" }, { name:"goodsVersion", value:(obj.goodsVersion||""), hiddenName: "declareGoodsList["+index+"].goodsVersion" }, { name:"goodsNo", value:obj.goodsNo, hiddenName: "declareGoodsList["+index+"].goodsNo" }, { name:"use", value:obj.use, hiddenName: "declareGoodsList["+index+"].use" }, { name:"model", value:obj.model, hiddenName: "declareGoodsList["+index+"].model" }, { name:"firstQuantity", value:(obj.firstQuantity||""), hiddenName: "declareGoodsList["+index+"].firstQuantity" }, { name:"firstUnit", value:(obj.firstUnit==""?"":(obj.firstUnit+" "+obj.firstUnitChn)), hiddenName: "declareGoodsList["+index+"].firstUnit" }, { name:"secondQuantity", value:(obj.secondQuantity||""), hiddenName: "declareGoodsList["+index+"].secondQuantity" }, { name:"secondUnit", value:(obj.secondUnit==""?"":(obj.secondUnit+" "+obj.secondUnitChn)), hiddenName: "declareGoodsList["+index+"].secondUnit" }, { name:"processingCharges", value:(obj.processingCharges||""), hiddenName: "declareGoodsList["+index+"].processingCharges" }, { name:"declareGoodsId", value:obj.declareGoodsId, hiddenName: "declareGoodsList["+index+"].declareGoodsId" } ]); }) //$("#goods-content").html(goodsContent); sum(); //第二个TAB页数据 if(result.declareOther != null){ $("#invoiceNo_2").val(result.declareOther.invoiceNo); $("#numbers_2").val(result.declareOther.numbers); $("#unit_2").val(result.declareOther.unit); $("#creditNo_2").val(result.declareOther.creditNo); $("#invoiceSigner_2").val(result.declareOther.invoiceSigner); $("#price_2").val(result.declareOther.price); $("#currency_2").val(result.declareOther.currency); $("#businessCompany_2").val(result.declareOther.businessCompany); $("#businessCompanyEn_2").val(result.declareOther.businessCompanyEn); $("#businessCompanyAddr_2").val(result.declareOther.businessCompanyAddr); $("#customCompamy_2").val(result.declareOther.customCompamy); $("#customTel_2").val(result.declareOther.customTel); $("#customCompamyAddr_2").val(result.declareOther.customCompamyAddr); $("#customsBroker_2").val(result.declareOther.customsBroker); $("#rmbRate_2").val(result.declareOther.rmbRate); $("#usdRate_2").val(result.declareOther.usdRate); $("#tax_2").val(result.declareOther.tax); } uploadLogo("edocFile_1", "00000001", result.declareMain.cloudQpId); uploadLogo("edocFile_2", "00000002", result.declareMain.cloudQpId); uploadLogo("edocFile_3", "00000003", result.declareMain.cloudQpId); uploadLogo("edocFile_4", "00000004", result.declareMain.cloudQpId); uploadLogo("edocFile_5", "00000005", result.declareMain.cloudQpId); uploadLogo("edocFile_6", "00000006", result.declareMain.cloudQpId); uploadLogo("edocFile_7", "00000007", result.declareMain.cloudQpId); uploadLogo("edocFile_8", "00000008", result.declareMain.cloudQpId); //uploadLogo("edocFile_9", "10000001", result.declareMain.cloudQpId); uploadLogo("edocFile_10", "10000002", result.declareMain.cloudQpId); $("#edocFile_9").attr("cloudQpId", result.declareMain.cloudQpId); $(result.declareEdocList).each(function(index, obj){ if(obj.edocCode == "10000001"){ $("#edocFile_9").val(obj.edocId) } }) } }else if(data.flag == '0'){ alert("请先登陆") }else if(data.flag == '3'){ alert("未查询到数据") }else{ alert("对不起,查询异常,请稍后再试") } }, error : function(data){ } }); } //根据URL参数设置页面内容 function set_cqp_info(){ var vessel = getQuery("vessel"); var voyage = getQuery("voyage"); var bill = getQuery("bill"); if(vessel == null || vessel == "" || vessel == undefined){ return false; } if (vessel != "") $("#transportName").val(decodeURI(vessel)); if (voyage != "") $("#transportId").val(voyage); if (bill != "") $("#billNo").val(bill); } function export_cqp_record(){ var cloudQpId = $("#cqp_id").val(); if(cloudQpId == null || cloudQpId == ""){ alert("没有数据可导出"); return false; } window.location.href = "/declare/exportDfgCtn.action?cloudQpId="+cloudQpId; } function export_cqp_record2(){ var cloudQpId = $("#cqp_id").val(); if(cloudQpId == null || cloudQpId == ""){ alert("没有数据可导出"); return false; } if($("#pdfFlag").is(":checked")) { window.location.href = "/declare/exportDfgCtnEx.action?cloudQpId="+cloudQpId + "&pdfFlag=" + $("#pdfFlag").val(); } else { window.location.href = "/declare/exportDfgCtnEx.action?cloudQpId="+cloudQpId; } } function upload_cqp_record2(){ var cloudQpId = $("#cqp_id").val(); if(cloudQpId == null || cloudQpId == ""){ alert("没有数据可导出"); return false; } var uploadUrl = "/declare/uploadDfgCtnEx.action?cloudQpId="+cloudQpId; if($("#pdfFlag").is(":checked")) { uploadUrl = uploadUrl + "&pdfFlag=" + $("#pdfFlag").val(); } $.ajax({ type : "post" , url : uploadUrl, dataType : "json" , async:false, success : function(data){ if (data.flag == "1") { alert("上传成功,请稍候查看报关单暂存状态"); } else { alert("上传失败"); } }, error : function(data){ alert("报文上传异常"); } }); } //flash上传方式 $('#analyzeDeclareExcel').uploadify({ "formData":{}, 'swf' : '/upload/uploadify.swf', 'uploader' : "/declare/analyzeDeclareExcel.action", 'fileTypeExts' : '*.xls; *.XLS; *.XLSX; *.xlsx', 'buttonText': "解析报关单", "fileDesc":"请选择报关单execl文件", 'fileObjName':'declareExcelFile', "width":100, "height":30, 'buttonClass':"rmb submit up_ico qb", "removeTimeout" : 1, "multi":true, "queueID":"upload_body", "itemTemplate":'<div class="dialog up_dialog" id="@[fileID]">\ <div class="up_content" id="up_content">\ <div class="up">\ <b class="up_wait_t">@[fileName] 上传中...</b>\ <div class="uploadify-progress">\ <div class="data-info"><span class="fileName">@[fileSize]</span><span class="data"></span></div>\ <div class="uploadify-progress-bar"></div>\ </div>\ <ul>\ <li>禁止上传任何违法,侵权或无法审查内容的文件,上传即代表接受<a href="###">上传协议</a>。</li>\ <li>易步通有义务配合有关部门将上传违规文件的用户信息保留,并进行提交。 </li>\ <li>文件大小请勿超过50M。</li>\ </ul>\ </div>\ </div>\ </div>', "queueSizeLimit":50, "onSelect":function(){ //$.eport.bar({start:0,pause:75,total:450}); }, 'onUploadStart' : function() { //$.eport.bar({start:75,pause:231,total:450}); }, 'onUploadSuccess':function(file, data, response){ data = $.parseJSON(data); if(data.flag==0) { alert("您的登陆状态已过期,请重新登录!"); window.location.href="/login.jsp" }else if(data.flag==2){ alert(data.dataError); }else if(data.flag == 1){ var decHeadContext = data.declareInfo.ResponseData.HedContext; //清空内容 clearAllData(); //第一个TAB页赋值(还差 类型、企业性质) $("#ieFlag").val("E"); //$("#status").val(result.declareMain.status); //$("#eportNo").val(result.declareMain.eportNo); //$("#customNo").val(result.declareMain.customNo); //$("#preentryNo").val(result.declareMain.preentryNo); $("#declareLocation_v").val(""); $("#declareLocation").val(""); $("#declareLocationCode").val(""); var decIEPortName = getDeclareCodeName(decHeadContext.IEPort, eval(CUST_content_store)); $("#exportLocation_v").val(decHeadContext.IEPort + " " + decIEPortName); $("#exportLocation").val(decIEPortName); $("#exportLocationCode").val(decHeadContext.IEPort); //$("#enrolNo").val(result.declareMain.enrolNo); //$("#exportDate").val(result.declareMain.exportDate); //$("#declareDate").val(""); $("#businessCompanyCode").val(decHeadContext.TradeCode); $("#businessCompany").val(decHeadContext.TradeName); var decTransfTypeName = getDeclareCodeName(decHeadContext.TransfType, eval(TRAF_content_store)); $("#transportMode_v").val(decHeadContext.TransfType + " " + decTransfTypeName); $("#transportMode").val(decTransfTypeName); $("#transportModeCode").val(decHeadContext.TransfType); //$("#transportName").val(result.declareMain.transportName); //$("#transportId").val(result.declareMain.transportId); $("#billNo").val(""); $("#productionCompanyCode").val(decHeadContext.OwnerCode); $("#productionCompany").val(decHeadContext.OwnerName); var decTradeModeName = getDeclareCodeName(decHeadContext.TradeMode, eval(TRADE_content_store)); $("#tradeMode_v").val(decHeadContext.TradeMode + " " + decTradeModeName); $("#tradeMode").val(decTradeModeName); $("#tradeModeCode").val(decHeadContext.TradeMode); var decCutModeName = getDeclareCodeName(decHeadContext.CutMode, eval(CUT_content_store)); $("#cutMode_v").val(decHeadContext.CutMode + " " + decCutModeName); $("#cutMode").val(decCutModeName); $("#cutModeCode").val(decHeadContext.CutMode); var decPayWayName = getDeclareCodeName(decHeadContext.PayWay, eval(PAY_content_store)); $("#payMode_v").val(decHeadContext.PayWay + " " + decPayWayName); $("#payMode").val(decPayWayName); $("#payModeCode").val(decHeadContext.PayWay); //$("#declareCompany").val(result.declareMain.declareCompany); //$("#declareCompanyCode").val(result.declareMain.declareCompanyCode); var decTradeCountryName = getDeclareCodeName(decHeadContext.TradeCountry, eval(COUNTRY_content_store)); $("#arrivedCountry_v").val(decHeadContext.TradeCountry + " " + decTradeCountryName); $("#arrivedCountry").val(decTradeCountryName); $("#arrivedCountryCode").val(decHeadContext.TradeCountry); $("#arrivedPort_v").val(decHeadContext.DestinationPort); $("#arrivedPort").val(""); $("#arrivedPortCode").val(decHeadContext.DestinationPort); $("#goodsSource_v").val(""); $("#goodsSource").val(decHeadContext.GSource); $("#goodsSourceCode").val(""); var decTradingCountryName = getDeclareCodeName(decHeadContext.TradingCountry, eval(COUNTRY_content_store)); $("#tradingCountry_v").val(decHeadContext.TradingCountry + " " + decTradingCountryName); $("#tradingCountry").val(decTradingCountryName); $("#tradingCountryCode").val(decHeadContext.TradingCountry); var decTransModeName = getDeclareCodeName(decHeadContext.TransMode, eval(TRANS_content_store)); $("#transactionMode_v").val(decHeadContext.TransMode + " " + decTransModeName); $("#transactionMode").val(decTransModeName); $("#transactionModeCode").val(decHeadContext.TransMode); $("#freightMark_v").val(""); $("#freightMark").val(""); $("#freightMarkChn").val(""); $("#freightRate").val(decHeadContext.TransfFee); $("#freightCurrency_v").val(""); $("#freightCurrency").val(""); $("#freightCurrencyChn").val(""); $("#insuranceMark_v").val(""); $("#insuranceMark").val(""); $("#insuranceMarkChn").val(""); $("#insuranceRate").val(decHeadContext.InsurFee); $("#insuranceCurrency_v").val(""); $("#insuranceCurrency").val(""); $("#insuranceCurrencyChn").val(""); $("#extrasMark_v").val(""); $("#extrasMark").val(""); $("#extrasMarkChn").val(""); $("#extrasRate").val(decHeadContext.OtherFee); $("#extrasCurrency_v").val(""); $("#extrasCurrency").val(""); $("#extrasCurrencyChn").val(""); $("#packagesNum").val(decHeadContext.PackNo); var decWrapTypeName = getDeclareCodeName(decHeadContext.WrapType, eval(WARP_content_store)); $("#packingType_v").val(decHeadContext.WrapType + " " + decWrapTypeName); $("#packingType").val(decWrapTypeName); $("#packingTypeCode").val(decHeadContext.WrapType); $("#grossWeight").val(decHeadContext.GrossWt); $("#netWeight").val(decHeadContext.NetWt); //$("#remark").val(result.declareMain.remark); $("#contractNo").val(decHeadContext.ContrNo); //$("#entryType_v").val(result.declareMain.entryTypeCode==""?"":(result.declareMain.entryTypeCode+" "+result.declareMain.entryType)); //$("#entryType").val(result.declareMain.entryType); //$("#entryTypeCode").val(result.declareMain.entryTypeCode); //$("#taxCorporationType").val(result.declareMain.taxCorporationType); //$("#licenseNo").val(result.declareMain.licenseNo); //$("#approvalNo").val(result.declareMain.approvalNo); //$("#relativeEntryNo").val(result.declareMain.relativeEntryNo); //$("#relativeEnrolNo").val(result.declareMain.relativeEnrolNo); //$("#warehouseNo").val(result.declareMain.warehouseNo); //$("#cyNo").val(result.declareMain.cyNo); //$("#vouchFlag").val(result.declareMain.vouchFlag); //if(result.declareMain.vouchFlag == "Y"){ // $("#vouchFlag").prop("checked", "checked"); //}else{ // $("#vouchFlag").prop("checked", ""); //} //第三个TAB页表格的数据 //var goodsContent = "" $(data.declareInfo.ResponseData.LstContexts).each(function(index, obj){ var decGUnitName = getDeclareCodeName(obj.GUnit, eval(UNIT_content_store)); var decGCurrName = getDeclareCodeName(obj.Curr, eval(CURR_content_store)); var decGCountryName = getDeclareCodeName(obj.Country, eval(COUNTRY_content_store)); var decGDutyModeName = getDeclareCodeName(obj.DutyMode, eval(DUTY_content_store)); table1.append([ { name:"goodsSeq", value:(obj.goodsSeq||""), hiddenName: "declareGoodsList["+index+"].goodsSeq" }, { name:"hsCode", value:obj.CodeTs.substring(0,8), hiddenName: "declareGoodsList["+index+"].hsCode" }, { name:"enrolNo", value:(obj.enrolNo||""), hiddenName: "declareGoodsList["+index+"].enrolNo" }, { name:"goodsName", value:obj.GName, hiddenName: "declareGoodsList["+index+"].goodsName" }, { name:"arrivalCountry", value:obj.Country+" "+decGCountryName, hiddenName: "declareGoodsList["+index+"].arrivalCountry" }, { name:"quantity", value:(obj.GQty||""), hiddenName: "declareGoodsList["+index+"].quantity" }, { name:"quantityUnit", value:obj.GUnit+" "+decGUnitName, hiddenName: "declareGoodsList["+index+"].quantityUnit" }, { name:"unitPrice", value:(obj.DeclPrice||""), hiddenName: "declareGoodsList["+index+"].unitPrice" }, { name:"sum", value:(obj.TotalPrice||""), hiddenName: "declareGoodsList["+index+"].totalPrice" }, { name:"currency", value:obj.Curr+" "+decGCurrName, hiddenName: "declareGoodsList["+index+"].currency" }, { name:"dutyMode", value:obj.DutyMode+" "+decGDutyModeName, hiddenName: "declareGoodsList["+index+"].dutyMode" }, { name:"extraNo", value:obj.CodeTs.substring(8,10), hiddenName: "declareGoodsList["+index+"].extraNo" }, { name:"goodsVersion", value:(obj.goodsVersion||""), hiddenName: "declareGoodsList["+index+"].goodsVersion" }, { name:"goodsNo", value:obj.goodsNo || "", hiddenName: "declareGoodsList["+index+"].goodsNo" }, { name:"use", value:obj.use || "", hiddenName: "declareGoodsList["+index+"].use" }, { name:"model", value:obj.model || "", hiddenName: "declareGoodsList["+index+"].model" }, { name:"firstQuantity", value:(obj.firstQuantity||""), hiddenName: "declareGoodsList["+index+"].firstQuantity" }, { name:"firstUnit", value:(obj.firstUnit==""?"":(obj.firstUnit+" "+obj.firstUnitChn)), hiddenName: "declareGoodsList["+index+"].firstUnit" }, { name:"secondQuantity", value:(obj.secondQuantity||""), hiddenName: "declareGoodsList["+index+"].secondQuantity" }, { name:"secondUnit", value:(obj.secondUnit==""?"":(obj.secondUnit+" "+obj.secondUnitChn)), hiddenName: "declareGoodsList["+index+"].secondUnit" }, { name:"processingCharges", value:(obj.processingCharges||""), hiddenName: "declareGoodsList["+index+"].processingCharges" }, { name:"declareGoodsId", value:obj.declareGoodsId || "", hiddenName: "declareGoodsList["+index+"].declareGoodsId" } ]); }) //$("#goods-content").html(goodsContent); sum(); }else{ alert("对不起,您没有解析报关单EXCEL的权限"); } }, "onUploadError":function(file, errorCode, errorMsg, errorString){ $("div.data-info").css("color","red").text("内部错误,解析失败。请稍后再试") $.eport.dialog({ element :".error_dialog", state:"open" }); $("#error_txt").val("内部错误,解析失败。请稍后再试"); } }); //上传附件 function uploadEdoc(id, edocCode){ var options = { url : '/declare/uploadEdoc.action?edocCode='+edocCode, type : 'POST', dataType:'json', beforeSubmit : before_submit_1, success: show_result_1 }; $("#edocFile_1_form").ajaxSubmit(options); return false; } function before_submit_1(){ //alert("b") } function show_result_1(data){ } //预览附件 function previewEdoc(edocCode){ if ($("#cloudQpId").val() != "") { $.ajax({ type : "post" , url : "/declare/getEdocContent.action?cloudQpId="+$("#cloudQpId").val() + "&edocCode=" + edocCode, dataType : "json" , async:false, success : function(data){ $("#previewEdoc").html('<embed style="width:100%;height:100%" src="data:application/pdf;base64,'+data.result+'"></embed>') }, error : function(data){ alert("附件显示异常"); } }); } } //预览附件URL方式 function previewEdocUrl(edocCode){ if ($("#cloudQpId").val() != "") { $.ajax({ type : "post" , url : "/declare/getEdocFileUrl.action?cloudQpId="+$("#cloudQpId").val() + "&edocCode=" + edocCode, dataType : "json" , async:false, success : function(data){ $("#previewEdoc").html('<embed style="width:100%;height:100%" src="/'+data.result+'"></embed>') }, error : function(data){ alert("附件显示异常"); } }); } } var CUST_content_store; var TRAF_content_store; var TRADE_content_store; var CUT_content_store; var PAY_content_store; var DIST_content_store; var TRANS_content_store; var WARP_content_store; var DOCU_content_store; var UNIT_content_store; var CURR_content_store; var DUTY_content_store; var COUNTRY_content_store; function getDeclareCode(){ $.ajax({ type : "post" , url : "/declare/getDeclareCode.action", dataType : "json" , async : false, success : function(data){ if(data.flag == 1){ var codeSimpleCodeList = eval(data.codeSimpleCodeList); var CUST_content = "["; var TRAF_content = "["; var TRADE_content = "["; var CUT_content = "["; var PAY_content = "["; var DIST_content = "["; var TRANS_content = "["; var WARP_content = "["; var DOCU_content = "["; var UNIT_content = "["; var CURR_content = "["; var DUTY_content = "["; var COUNTRY_content = "["; $(codeSimpleCodeList).each(function(index, obj){ var $html = "{label:\""+obj.code+" "+obj.chnDesc+"\"}"; if(obj.codeType == "CUST")CUST_content += $html+","; if(obj.codeType == "TRAF")TRAF_content += $html+","; if(obj.codeType == "TRADE")TRADE_content += $html+","; if(obj.codeType == "CUT")CUT_content += $html+","; if(obj.codeType == "PAY")PAY_content += $html+","; if(obj.codeType == "DIST")DIST_content += $html+","; if(obj.codeType == "TRANS")TRANS_content += $html+","; if(obj.codeType == "WARP")WARP_content += $html+","; if(obj.codeType == "DOCU")DOCU_content += $html+","; if(obj.codeType == "UNIT")UNIT_content += $html+","; if(obj.codeType == "CURR")CURR_content += $html+","; if(obj.codeType == "DUTY")DUTY_content += $html+","; if(obj.codeType == "COUNTRY")COUNTRY_content += $html+","; }) if (CUST_content.length > 1){CUST_content = CUST_content.substring(0, CUST_content.length-1)+"]";}else{CUST_content += "]";} if (TRAF_content.length > 1){TRAF_content = TRAF_content.substring(0, TRAF_content.length-1)+"]";}else{TRAF_content += "]";} if (TRADE_content.length > 1){TRADE_content = TRADE_content.substring(0, TRADE_content.length-1)+"]";}else{TRADE_content += "]";} if (CUT_content.length > 1){CUT_content = CUT_content.substring(0, CUT_content.length-1)+"]";}else{CUT_content += "]";} if (PAY_content.length > 1){PAY_content = PAY_content.substring(0, PAY_content.length-1)+"]";}else{PAY_content += "]";} if (DIST_content.length > 1){DIST_content = DIST_content.substring(0, DIST_content.length-1)+"]";}else{DIST_content += "]";} if (TRANS_content.length > 1){TRANS_content = TRANS_content.substring(0, TRANS_content.length-1)+"]";}else{TRANS_content += "]";} if (WARP_content.length > 1){WARP_content = WARP_content.substring(0, WARP_content.length-1)+"]";}else{WARP_content += "]";} if (DOCU_content.length > 1){DOCU_content = DOCU_content.substring(0, DOCU_content.length-1)+"]";}else{DOCU_content += "]";} if (UNIT_content.length > 1){UNIT_content = UNIT_content.substring(0, UNIT_content.length-1)+"]";}else{UNIT_content += "]";} if (CURR_content.length > 1){CURR_content = CURR_content.substring(0, CURR_content.length-1)+"]";}else{CURR_content += "]";} if (DUTY_content.length > 1){DUTY_content = DUTY_content.substring(0, DUTY_content.length-1)+"]";}else{DUTY_content += "]";} if (COUNTRY_content.length > 1){COUNTRY_content = COUNTRY_content.substring(0, COUNTRY_content.length-1)+"]";}else{COUNTRY_content += "]";} CUST_content_store = CUST_content; TRAF_content_store = TRAF_content; TRADE_content_store = TRADE_content; CUT_content_store = CUT_content; PAY_content_store = PAY_content; DIST_content_store = DIST_content; TRANS_content_store = TRANS_content; WARP_content_store = WARP_content; DOCU_content_store = DOCU_content; UNIT_content_store = UNIT_content; CURR_content_store = CURR_content; DUTY_content_store = DUTY_content; COUNTRY_content_store = COUNTRY_content; $("#docAttachedCode").autocomplete({ source : eval(DOCU_content_store), autoFocus : true, select : function(event,ui){} }); $("#declareLocation_v").autocomplete({ source : eval(CUST_content), autoFocus : true, select : function(event,ui){ var temp = ui.item.label; var list = temp.split(" "); if(list.length == 2){ $("#declareLocationCode").val(list[0]); $("#declareLocation").val(list[1]); } } }); $("#exportLocation_v").autocomplete({ source : eval(CUST_content), autoFocus : true, select : function(event,ui){ var temp = ui.item.label; var list = temp.split(" "); if(list.length == 2){ $("#exportLocationCode").val(list[0]); $("#exportLocation").val(list[1]); } } }); $("#transportMode_v").autocomplete({ source : eval(TRAF_content), autoFocus : true, select : function(event,ui){ var temp = ui.item.label; var list = temp.split(" "); if(list.length == 2){ $("#transportModeCode").val(list[0]); $("#transportMode").val(list[1]); } } }); $("#tradeMode_v").autocomplete({ source : eval(TRADE_content), autoFocus : true, select : function(event,ui){ var temp = ui.item.label; var list = temp.split(" "); if(list.length == 2){ $("#tradeModeCode").val(list[0]); $("#tradeMode").val(list[1]); } } }); $("#cutMode_v").autocomplete({ source : eval(CUT_content), autoFocus : true, select : function(event,ui){ var temp = ui.item.label; var list = temp.split(" "); if(list.length == 2){ $("#cutModeCode").val(list[0]); $("#cutMode").val(list[1]); } } }); $("#payMode_v").autocomplete({ source : eval(PAY_content), autoFocus : true, select : function(event,ui){ var temp = ui.item.label; var list = temp.split(" "); if(list.length == 2){ $("#payModeCode").val(list[0]); $("#payMode").val(list[1]); } } }); $("#arrivedCountry_v").autocomplete({ source : eval(COUNTRY_content), autoFocus : true, select : function(event,ui){ var temp = ui.item.label; var list = temp.split(" "); if(list.length == 2){ $("#arrivedCountryCode").val(list[0]); $("#arrivedCountry").val(list[1]); } } }); $("#goodsSource_v").autocomplete({ source : eval(DIST_content), autoFocus : true, appendTo: null, select : function(event,ui){ var temp = ui.item.label; var list = temp.split(" "); if(list.length == 2){ $("#goodsSourceCode").val(list[0]); $("#goodsSource").val(list[1]); } event.stopPropagation(); } }); $("#tradingCountry_v").autocomplete({ source : eval(COUNTRY_content), autoFocus : true, select : function(event,ui){ var temp = ui.item.label; var list = temp.split(" "); if(list.length == 2){ $("#tradingCountryCode").val(list[0]); $("#tradingCountry").val(list[1]); } } }); $("#transactionMode_v").autocomplete({ source : eval(TRANS_content), autoFocus : true, select : function(event,ui){ var temp = ui.item.label; var list = temp.split(" "); var val = list[1]; if($("#ieFlag").val() == "E" && val == "FOB"){ $("#freightMark_v").removeClass("qp_key_ipt").addClass("qp_readonly").attr("readonly",true).val(""); $("#freightRate").removeClass("qp_key_ipt").addClass("qp_readonly").attr("readonly",true).val(""); $("#freightCurrency_v").removeClass("qp_key_ipt").addClass("qp_readonly").attr("readonly",true).val(""); $("#insuranceMark_v").removeClass("qp_key_ipt").addClass("qp_readonly").attr("readonly",true).val(""); $("#insuranceRate").removeClass("qp_key_ipt").addClass("qp_readonly").attr("readonly",true).val(""); $("#insuranceCurrency_v").removeClass("qp_key_ipt").addClass("qp_readonly").attr("readonly",true).val(""); }else if($("#ieFlag").val() == "E" && val == "C&F"){ $("#insuranceMark_v").removeClass("qp_key_ipt").addClass("qp_readonly").attr("readonly",true).val(""); $("#insuranceRate").removeClass("qp_key_ipt").addClass("qp_readonly").attr("readonly",true).val(""); $("#insuranceCurrency_v").removeClass("qp_key_ipt").addClass("qp_readonly").attr("readonly",true).val(""); if(!$("#freightMark_v").hasClass("qp_key_ipt"))$("#freightMark_v").removeClass("qp_readonly").addClass("qp_key_ipt").attr("readonly",false); if(!$("#freightRate").hasClass("qp_key_ipt"))$("#freightRate").removeClass("qp_readonly").addClass("qp_key_ipt").attr("readonly",false); if(!$("#freightCurrency_v").hasClass("qp_key_ipt"))$("#freightCurrency_v").removeClass("qp_readonly").addClass("qp_key_ipt").attr("readonly",false); }else{ if(!$("#freightMark_v").hasClass("qp_key_ipt"))$("#freightMark_v").removeClass("qp_readonly").addClass("qp_key_ipt").attr("readonly",false); if(!$("#freightRate").hasClass("qp_key_ipt"))$("#freightRate").removeClass("qp_readonly").addClass("qp_key_ipt").attr("readonly",false); if(!$("#freightCurrency_v").hasClass("qp_key_ipt"))$("#freightCurrency_v").removeClass("qp_readonly").addClass("qp_key_ipt").attr("readonly",false); if(!$("#insuranceMark_v").hasClass("qp_key_ipt"))$("#insuranceMark_v").removeClass("qp_readonly").addClass("qp_key_ipt").attr("readonly",false); if(!$("#insuranceRate").hasClass("qp_key_ipt"))$("#insuranceRate").removeClass("qp_readonly").addClass("qp_key_ipt").attr("readonly",false); if(!$("#insuranceCurrency_v").hasClass("qp_key_ipt"))$("#insuranceCurrency_v").removeClass("qp_readonly").addClass("qp_key_ipt").attr("readonly",false); } if(list.length == 2){ $("#transactionModeCode").val(list[0]); $("#transactionMode").val(list[1]); } } }); $("#packingType_v").autocomplete({ source : eval(WARP_content), autoFocus : true, select : function(event,ui){ var temp = ui.item.label; var list = temp.split(" "); if(list.length == 2){ $("#packingTypeCode").val(list[0]); $("#packingType").val(list[1]); } } }); var entry_type_code = '[{label:"001 普通报关"},{label:"002 带清单普通报关"},{label:"003 无纸报关"},{label:"004 带清单无纸报关"}]'; $("#entryType_v").autocomplete({ source : eval(entry_type_code), autoFocus : true, select : function(event,ui){ var temp = ui.item.label; var list = temp.split(" "); if(list.length == 2){ $("#entryTypeCode").val(list[0]); $("#entryType").val(list[1]); } } }); var freightMark = '[{label:"1 费率"},{label:"2 单价"},{label:"3 总价"}]'; $("#freightMark_v").autocomplete({ source : eval(freightMark), autoFocus : true, select : function(event,ui){ var temp = ui.item.label; var list = temp.split(" "); if(list.length == 2){ $("#freightMark").val(list[0]); $("#freightMarkChn").val(list[1]); } } }); $("#insuranceMark_v").autocomplete({ source : eval(freightMark), autoFocus : true, select : function(event,ui){ var temp = ui.item.label; var list = temp.split(" "); if(list.length == 2){ $("#insuranceMark").val(list[0]); $("#insuranceMarkChn").val(list[1]); } } }); $("#extrasMark_v").autocomplete({ source : eval(freightMark), autoFocus : true, select : function(event,ui){ var temp = ui.item.label; var list = temp.split(" "); if(list.length == 2){ $("#extrasMark").val(list[0]); $("#extrasMarkChn").val(list[1]); } } }); $("#freightCurrency_v").autocomplete({ source : eval(CURR_content), autoFocus : true, select : function(event,ui){ var temp = ui.item.label; var list = temp.split(" "); if(list.length == 2){ $("#freightCurrency").val(list[0]); $("#freightCurrencyChn").val(list[1]); } } }); $("#insuranceCurrency_v").autocomplete({ source : eval(CURR_content), autoFocus : true, select : function(event,ui){ var temp = ui.item.label; var list = temp.split(" "); if(list.length == 2){ $("#insuranceCurrency").val(list[0]); $("#insuranceCurrencyChn").val(list[1]); } } }); $("#extrasCurrency_v").autocomplete({ source : eval(CURR_content), autoFocus : true, select : function(event,ui){ var temp = ui.item.label; var list = temp.split(" "); if(list.length == 2){ $("#extrasCurrency").val(list[0]); $("#extrasCurrencyChn").val(list[1]); } } }); $("#quantityUnit_goods").autocomplete({ source : eval(UNIT_content), autoFocus : true, select : function(event,ui){} }); $("#firstUnit_goods").autocomplete({ source : eval(UNIT_content), autoFocus : true, select : function(event,ui){} }); $("#secondUnit_goods").autocomplete({ source : eval(UNIT_content), autoFocus : true, select : function(event,ui){} }); $("#currency_goods").autocomplete({ source : eval(CURR_content), autoFocus : true, select : function(event,ui){} }); $("#dutyMode_goods").autocomplete({ source : eval(DUTY_content), autoFocus : true, select : function(event,ui){} }); $("#arrivalCountry_goods").autocomplete({ source : eval(COUNTRY_content), autoFocus : true, select : function(event,ui){} }); }else{ alert("获取下拉选择数据异常"); } }, error : function(data){ } }); } function getDeclareCodeName(code, declareCodeList){ for(var i=0; i<declareCodeList.length; i++) { if(declareCodeList[i]["label"].indexOf(code) == 0) { return declareCodeList[i]["label"].substring(code.length + 1); } } return ""; } function init(){ $("#search-dialog").on("dblclick", ".db", function(e){ var list = eval(hscode_search_result_store.hsCodeList); var hscode = list[$(this).attr("index")]; $("#hsCode_goods").val(hscode.codeHscode.hscode.substring(0,8)); $("#extraNo_goods").val(hscode.codeHscode.hscode.substring(8,10)); //$("#goodsName_goods").val(hscode.codeHscode.chnName); $("#quantityUnit_goods").val(hscode.codeHscode.unit1+" "+hscode.unit1Chn); $("#firstUnit_goods").val(hscode.codeHscode.unit1+" "+hscode.unit1Chn); $("#secondUnit_goods").val(hscode.codeHscode.unit2==""?"":(hscode.codeHscode.unit2+" "+hscode.unit2Chn)); $("#search-dialog").dialog("close"); $("#hsCode_goods").blur(); $("#extraNo_goods").blur(); $("#goodsName_goods").blur(); $("#quantityUnit_goods").blur(); $("#firstUnit_goods").blur(); $("#secondUnit_goods").blur(); var html = '<tr><th>1.品名</th><td>'+hscode.codeHscode.chnName+'</td></tr>'; $.ajax({ type : "post" , url : "/declare/getMerchElement.action?hscode="+hscode.codeHscode.hscode, dataType : "json" , async : false, success : function(data){ if(data.flag == 1){ var list = eval(data.list); $(list).each(function(index, obj){ html += '<tr><th>'+Number(index+2)+'.'+obj.element+'</th><td><input type="text" class="inp2"/></td></tr>' }); } }, error : function(data){ } }); $("#result-dialog_hscode").html(hscode.codeHscode.hscode.substring(0,8)); $("#result-dialog-table tbody").html(html); guigeJump(); $("#result-dialog").dialog("open"); }).on("click", ".db", function(e){ $(".db").removeClass("c-act"); $(this).addClass("c-act"); }); $("#search-arrivePort-dialog").on("dblclick", ".db", function(e){ var portCode = $(this).attr("portCode"); var portCName = $(this).attr("portCName"); var countryCode = $(this).attr("countryCode"); var countryName = $(this).attr("countryName"); $("#search-arrivePort-dialog").dialog("close"); $("#arrivedPort_v").val(portCode+" "+portCName); $("#arrivedPortCode").val(portCode); $("#arrivedPort").val(portCName); if($("#arrivedCountry_v").val() == ""){ $("#arrivedCountryCode").val(countryCode); $("#arrivedCountry_v").val(countryCode+" "+countryName); $("#arrivedCountry").val(countryName); } $("#goodsSource_v").focus(); }).on("click", ".db", function(e){ $(".db").removeClass("c-act"); $(this).addClass("c-act"); }) } var hscode_search_result_store; function hscode_search(pageNo){ $.ajax({ type : "post" , url : "/declare/getDeclareHsCode.action?hscode="+encodeURI(encodeURI($("#hscode_search_content").val()))+"&gotoPage="+pageNo, dataType : "json" , beforeSend : function(){ $("#hscode_result_table tbody").html( '<tr class="db">'+ '<td colspan="4"><image src="/images/loading.gif"></td>'+ '</tr>' ); }, success : function(data){ if(data.flag == 1){ var list = eval(data.hsCodeList); var html = ""; $(list).each(function(index, obj){ html += '<tr class="db" index="'+index+'">'+ ' <td>'+obj.codeHscode.hscode+'</td>'+ ' <td>'+obj.codeHscode.chnName+'</td>'+ ' <td>'+obj.unit1Chn+'</td>'+ ' <td>'+obj.unit2Chn+'</td>'+ '</tr>' }) $("#hscode_result_table tbody").html(html); hscode_search_result_store = data; ajaxLoadPage(data, "pages_hscode_result_table"); }else{ $("#hscode_result_table tbody").html("对不起,查询异常"); } }, error : function(data){ $("#hscode_result_table tbody").html( '<tr class="db">'+ '<td colspan="4">对不起,查询异常</td>'+ '</tr>' ); } }) } function hscode_confirm(){ var list = eval(hscode_search_result_store.hsCodeList); var hscode; if($("#hscode_result_table tbody").find(".c-act").length == 0){ alert("请先选择一条数据"); }else{ $("#hscode_result_table tbody").find(".c-act").each(function(){ hscode = list[$(this).attr("index")]; }); $("#hsCode_goods").val(hscode.codeHscode.hscode.substring(0,8)); $("#extraNo_goods").val(hscode.codeHscode.hscode.substring(8,10)); //$("#goodsName_goods").val(hscode.codeHscode.chnName); $("#quantityUnit_goods").val(hscode.codeHscode.unit1+" "+hscode.unit1Chn); $("#firstUnit_goods").val(hscode.codeHscode.unit1+" "+hscode.unit1Chn); $("#secondUnit_goods").val(hscode.codeHscode.unit2==""?"":(hscode.codeHscode.unit2+" "+hscode.unit2Chn)); $("#search-dialog").dialog("close"); $("#hsCode_goods").blur(); $("#extraNo_goods").blur(); $("#goodsName_goods").blur(); $("#quantityUnit_goods").blur(); $("#firstUnit_goods").blur(); $("#secondUnit_goods").blur(); var html = '<tr><th>1.品名</th><td>'+hscode.codeHscode.chnName+'</td></tr>'; $.ajax({ type : "post" , url : "/declare/getMerchElement.action?hscode="+hscode.codeHscode.hscode, dataType : "json" , async : false, success : function(data){ if(data.flag == 1){ var list = eval(data.list); $(list).each(function(index, obj){ html += '<tr><th>'+Number(index+2)+'.'+obj.element+'</th><td><input type="text" class="inp2"/></td></tr>' }); } }, error : function(data){ } }); $("#result-dialog_hscode").html(hscode.codeHscode.hscode.substring(0,8)); $("#result-dialog-table tbody").html(html); guigeJump(); $("#result-dialog").dialog("open"); } } function result_dialog_yes(){ var guige = ""; $("#result-dialog-table").find("input").each(function(){ guige += $(this).val() + "|"; }) guige = guige.substring(0, guige.length - 1);//先去掉最后一个斜杠 if(guige.substring(guige.length - 1, guige.length) == "|"){ $("#model_goods").val(guige.substring(0, guige.length - 1));//如果其他为空,再删掉最后一个斜杠 }else{ $("#model_goods").val(guige);//如果其他不为空 } $("#model_goods").blur(); $("#result-dialog").dialog("close"); $("#quantity_goods").focus() } function result_dialog_no(){ $("#result-dialog").dialog("close"); $("#hsCode_goods").focus(); } function arrivePort_search(pageNo){ $.ajax({ type : "post" , url : "/declare/getArrivePort.action?arrivePort="+encodeURI(encodeURI($("#arrivePort_search_content").val()))+"&gotoPage="+pageNo, dataType : "json" , beforeSend : function(){ $("#arrivePort_result_table tbody").html( '<tr class="db">'+ '<td colspan="2"><image src="/images/loading.gif"></td>'+ '</tr>' ); }, success : function(data){ if(data.flag == 1){ var list = eval(data.portList); var html = ""; if($(list).length == 1){ port_data = $(list)[0]; //如果只有一条,则直接关闭查询框,直接赋值 $("#search-arrivePort-dialog").dialog("close"); $("#arrivedPort_v").val(port_data.codePort.portCode+" "+port_data.codePort.portCName); $("#arrivedPortCode").val(port_data.codePort.portCode); $("#arrivedPort").val(port_data.codePort.portCName); $("#arrivedCountryCode").val(port_data.codePort.countryCode); $("#arrivedCountry_v").val(port_data.codePort.countryCode+" "+port_data.countryName); $("#arrivedCountry").val(port_data.countryName); $("#goodsSource_v").focus(); return false; } $(list).each(function(index, obj){ html += '<tr class="db" portCode="'+obj.codePort.portCode+'" portCName="'+obj.codePort.portCName+'" countryCode="'+obj.codePort.countryCode+'" countryName="'+obj.countryName+'">'+ ' <td>'+obj.codePort.portCode+'</td>'+ ' <td>'+obj.codePort.portCName+'</td>'+ '</tr>' }) $("#arrivePort_result_table tbody").html(html); ajaxLoadPage(data, "pages_arrivePort_result_table"); }else{ $("#arrivePort_result_table tbody").html( '<tr class="db">'+ '<td colspan="2">对不起,查询异常</td>'+ '</tr>' ); } }, error : function(data){ $("#arrivePort_result_table tbody").html( '<tr class="db">'+ '<td colspan="2">对不起,查询异常</td>'+ '</tr>' ); } }); } function getQuery(name) { var search = window.location.search ? window.location.search.substring(1).split("&") : ""; var item = []; for(var i=0, l=search.length; i<l; i++) { item[i] = search[i].split("="); if(name === item[i][0]) { return item[i][1]; } } return ""; } function guigeJump(){ var j = 0; $(".inp2").each(function(index){ $(this).keydown(function(e){ if(e.keyCode == 13){ if(j == $(".inp2").length){ result_dialog_yes(); }else{ $(".inp2")[j].focus(); } } e.stopPropagation(); }); $(this).focus(function(){ j = index + 1; }); }); } $("#model_goods").on("dblclick", function(e){ if($("#hsCode_goods").val().length != 8 || $("#extraNo_goods").val().length != 2){ alert("请先填写正确的HSCODE"); return false; } var elements = $("#model_goods").val(); var temp = elements.split("|"); var html = '<tr><th>1.品名</th><td>'+$("#goodsName_goods").val()+'</td></tr>'; $.ajax({ type : "post" , url : "/declare/getMerchElement.action?hscode="+$("#hsCode_goods").val()+$("#extraNo_goods").val(), dataType : "json" , async : false, success : function(data){ if(data.flag == 1){ var list = eval(data.list); // if($(list).length == (temp.length)){ $(list).each(function(index, obj){ html += '<tr><th>'+Number(index+2)+'.'+obj.element+'</th><td><input type="text" class="inp2" value="'+(temp[index]||'')+'"/></td></tr>' }); $("#result-dialog-table tbody").html(html); guigeJump(); $("#result-dialog").dialog("open"); // }else{ // alert("HSCODE错误"); // } } }, error : function(data){ } }); }) function companyRecord_search(pageNo){ $.ajax({ type : "post" , url : "/declare/getBusinessCompanyRecord.action?companyName="+encodeURI(encodeURI($("#companyRecord_search_content").val()))+"&gotoPage="+pageNo+"&type="+$("#companyRecord_type").val(), dataType : "json" , beforeSend : function(){ $("#companyRecord_result_table tbody").html( '<tr class="db">'+ '<td colspan="3"><image src="/images/loading.gif"></td>'+ '</tr>' ); }, success : function(data){ if(data.flag == 1){ var list = eval(data.list); var html = ""; $(list).each(function(index, obj){ html += '<tr class="db" companyCode="'+obj.companyCode+'" companyChn="'+obj.companyChn+'" >'+ ' <td>'+obj.companyCode+'</td>'+ ' <td>'+obj.companyChn+'</td>'+ ' <td><a href="javascript:;" onclick="companyRecord_del(\''+obj.id+'\')">删除</a></td>'+ '</tr>' }) $("#companyRecord_result_table tbody").html(html); ajaxLoadPage(data, "pages_companyRecord_result_table"); }else{ $("#companyRecord_result_table tbody").html( '<tr class="db">'+ '<td colspan="3">对不起,查询异常</td>'+ '</tr>' ); } }, error : function(data){ $("#companyRecord_result_table tbody").html( '<tr class="db">'+ '<td colspan="3">对不起,查询异常</td>'+ '</tr>' ); } }); } //删除经营单位记录 function companyRecord_del(id){ $.ajax({ type : "post" , url : "/declare/delBusinessCompanyRecord.action?id="+id, dataType : "json" , success : function(data){ if(data.flag == "1"){ alert("删除成功"); companyRecord_search(1); }else{ alert("对不起,删除失败,请稍后再试"); } }, error : function(){ alert("对不起,删除失败,请稍后再试"); } }); } function companyRecord_add(){ $("#add_business_company_code").val(""); $("#add_business_company_chn").val(""); $("#add-companyRecord-dialog").dialog("open"); } function add_companyRecord_yes(){ $.ajax({ type : "post" , url : "/declare/addBusinessCompanyRecord.action?id=&companyCode="+$("#add_business_company_code").val()+ "&companyChn="+encodeURI(encodeURI($("#add_business_company_chn").val()))+"&type="+$("#companyRecord_type").val(), dataType : "json" , success : function(data){ if(data.flag == "1"){ alert("新增成功"); $("#add-companyRecord-dialog").dialog("close"); $("#company-record-dialog").dialog("close"); if($("#companyRecord_type").val() == "1"){ $("#businessCompanyCode").val($("#add_business_company_code").val()); $("#businessCompany").val($("#add_business_company_chn").val()); $("#transportMode_v").focus(); }else{ $("#productionCompanyCode").val($("#add_business_company_code").val()); $("#productionCompany").val($("#add_business_company_chn").val()); $("#tradeMode_v").focus(); } }else{ alert("对不起,新增失败,请稍后再试"); } }, error : function(data){ alert("对不起,新增失败,请稍后再试"); } }) } function add_companyRecord_no(){ $("#add-companyRecord-dialog").dialog("close"); } $("#company-record-dialog").on("dblclick", ".db", function(e){ $("#company-record-dialog").dialog("close"); var bussinessCompanyCode = $(this).attr("companyCode"); var bussinessCompanyCnh = $(this).attr("companyChn"); if($("#companyRecord_type").val() == "1"){ $("#businessCompanyCode").val(bussinessCompanyCode); $("#businessCompany").val(bussinessCompanyCnh); $("#transportMode_v").focus(); }else{ $("#productionCompanyCode").val(bussinessCompanyCode); $("#productionCompany").val(bussinessCompanyCnh); $("#tradeMode_v").focus(); } }).on("click", ".db", function(e){ $(".db").removeClass("c-act"); $(this).addClass("c-act"); }) //保存电子委托协议号 function edocIdSave(){ if($("#edocFile_9").attr("cloudQpId") == null || $("#edocFile_9").attr("cloudQpId") == "" || $("#edocFile_9").attr("cloudQpId") == undefined){ alert("请先保存报关单信息F1之后再保存电子委托协议号"); $("#edocFile_9").val("电子代理报关委托编号") return false; }else{ $.ajax({ type : "post" , url : "/declare/edocIdSave.action?cloudQpId="+$("#edocFile_9").attr("cloudQpId")+"&edocId="+ $("#edocFile_9").val()+"&edocCode="+$("#edocFile_9").attr("edocType"), dataType : "json" , beforeSend : function(){ $(".dec-save").val("保存中··") }, success : function(data){ if(data.flag == "1"){ alert("保存成功"); }else{ $("#edocFile_9").val("电子代理报关委托编号") alert("对不起,保存失败,请稍后再试"); } $(".dec-save").val("保存") }, error : function(data){ $(".dec-save").val("保存") $("#edocFile_9").val("电子代理报关委托编号") alert("对不起,保存失败,请稍后再试"); } }) } } function clearAllData(){ //第一个TAB页赋值(还差 类型、企业性质) $("#cloudQpId").val(""); $("#receiptDes").text(""); $("#ieFlag").val(""); $("#status").val(""); $("#eportNo").val(""); $("#customNo").val(""); $("#preentryNo").val(""); $("#declareLocation_v").val(""); $("#declareLocation").val(""); $("#declareLocationCode").val(""); $("#exportLocation_v").val(""); $("#exportLocation").val(""); $("#exportLocationCode").val(""); $("#enrolNo").val(""); $("#exportDate").val(""); $("#declareDate").val(""); $("#businessCompanyCode").val(""); $("#businessCompany").val(""); $("#transportMode_v").val(""); $("#transportMode").val(""); $("#transportModeCode").val(""); $("#transportName").val(""); $("#transportId").val(""); $("#billNo").val(""); $("#productionCompanyCode").val(""); $("#productionCompany").val(""); $("#tradeMode_v").val(""); $("#tradeMode").val(""); $("#tradeModeCode").val(""); $("#cutMode_v").val(""); $("#cutMode").val(""); $("#cutModeCode").val(""); $("#payMode_v").val(""); $("#payMode").val(""); $("#payModeCode").val(""); $("#declareCompany").val(""); $("#declareCompanyCode").val(""); $("#arrivedCountry_v").val(""); $("#arrivedCountry").val(""); $("#arrivedCountryCode").val(""); $("#arrivedPort_v").val(""); $("#arrivedPort").val(""); $("#arrivedPortCode").val(""); $("#goodsSource_v").val(""); $("#goodsSource").val(""); $("#goodsSourceCode").val(""); $("#tradingCountry_v").val(""); $("#tradingCountry").val(""); $("#tradingCountryCode").val(""); $("#transactionMode_v").val(""); $("#transactionMode").val(""); $("#transactionModeCode").val(""); $("#freightMark_v").val(""); $("#freightMark").val(""); $("#freightMarkChn").val(""); $("#freightRate").val(""); $("#freightCurrency_v").val(""); $("#freightCurrency").val(""); $("#freightCurrencyChn").val(""); $("#insuranceMark_v").val(""); $("#insuranceMark").val(""); $("#insuranceMarkChn").val(""); $("#insuranceRate").val(""); $("#insuranceCurrency_v").val(""); $("#insuranceCurrency").val(""); $("#insuranceCurrencyChn").val(""); $("#extrasMark_v").val(""); $("#extrasMark").val(""); $("#extrasMarkChn").val(""); $("#extrasRate").val(""); $("#extrasCurrency_v").val(""); $("#extrasCurrency").val(""); $("#extrasCurrencyChn").val(""); $("#packagesNum").val(""); $("#packingType_v").val(""); $("#packingType").val(""); $("#packingTypeCode").val(""); $("#grossWeight").val(""); $("#netWeight").val(""); $("#remark").val(""); $("#contractNo").val(""); $("#entryType_v").val(""); $("#entryType").val(""); $("#entryTypeCode").val(""); $("#taxCorporationType").val(""); $("#licenseNo").val(""); //$("#approvalNo").val(""); $("#relativeEntryNo").val(""); $("#relativeEnrolNo").val(""); $("#warehouseNo").val(""); $("#cyNo").val(""); $("#vouchFlag").val(""); $("#vouchFlag").prop("checked", ""); //表格的数据 table1.refresh(); table2.refresh(); table3.refresh(); sum(); //第二个TAB页数据 $("#invoiceNo_2").val(""); $("#numbers_2").val(""); $("#unit_2").val(""); $("#creditNo_2").val(""); $("#invoiceSigner_2").val(""); $("#price_2").val(""); $("#currency_2").val(""); $("#businessCompany_2").val(""); $("#businessCompanyEn_2").val(""); $("#businessCompanyAddr_2").val(""); $("#customCompamy_2").val(""); $("#customTel_2").val(""); $("#customCompamyAddr_2").val(""); $("#customsBroker_2").val(""); $("#rmbRate_2").val(""); $("#usdRate_2").val(""); $("#tax_2").val(""); //第三个TAB页数据 uploadLogo("edocFile_1", "00000001", ""); uploadLogo("edocFile_2", "00000002", ""); uploadLogo("edocFile_3", "00000003", ""); uploadLogo("edocFile_4", "00000004", ""); uploadLogo("edocFile_5", "00000005", ""); uploadLogo("edocFile_6", "00000006", ""); uploadLogo("edocFile_7", "00000007", ""); uploadLogo("edocFile_8", "00000008", ""); //uploadLogo("edocFile_9", "10000001", ""); uploadLogo("edocFile_10", "10000002", ""); //第一页下面用于输入的框清空 $("#goodsSeq_goods").val(""); $("#enrolNo_goods").val(""); $("#hsCode_goods").val(""); $("#extraNo_goods").val(""); $("#goodsName_goods").val(""); $("#goodsVersion_goods").val(""); $("#goodsNo_goods").val(""); $("#use_goods").val(""); $("#model_goods").val(""); $("#quantity_goods").val(""); $("#quantityUnit_goods").val(""); $("#unitPrice_goods").val(""); $("#sum_goods").val(""); $("#currency_goods").val(""); $("#arrivalCountry_goods").val(""); $("#firstQuantity_goods").val(""); $("#firstUnit_goods").val(""); $("#secondQuantity_goods").val(""); $("#secondUnit_goods").val(""); $("#dutyMode_goods").val(""); $("#processingCharges_goods").val(""); //电子委托协议号清空 $("#edocFile_9").val("电子代理报关委托编号"); $("#edocFile_9").attr("cloudQpId",""); } function getDataFromCLPByBillNo(){ var billNo = $("#billNo").val(); if(billNo == ""){ alert("请先填写提单号"); return false; } $.ajax({ type : "post" , url : "/declare/getDataFromCLPByBillNo.action?billNo="+billNo, dataType : "json" , beforeSend : function(){ $("#getDataFromCLPByBillNo_btn").val("查询中··") }, success : function(data){ $("#getDataFromCLPByBillNo_btn").val("查询") $("#transportName").val(""); $("#transportId").val(""); $("#packagesNum").val("") $("#grossWeight").val("") //$("#netWeight").val("") table2.refresh(); if(data.flag == "0"){ alert("未查询到数据"); }else if(data.flag == "2"){ alert("对不起,查询异常,请稍后再试!"); }else if(data.flag == "100"){ alert("对不起,您没有权限,请联系管理员!"); }else{ //如果有数据,运输方式选择水路运输 //console.log(data); var jsonData = eval(data); var clpRecordList = eval(jsonData.CLPRecord); if(clpRecordList[0].costcoBlDeoList.length == 0){ alert("未查询到数据"); return false; } $("#transportMode_v").val("2 水路运输"); $("#transportModeCode").val("2"); $("#transportMode").val("水路运输"); $("#transportName").val(clpRecordList[0].costcoMainDeo.vessel); $("#transportId").val((clpRecordList[0].costcoMainDeo.voyage).substring(0,(clpRecordList[0].costcoMainDeo.voyage).length-1)); var js = 0; var mz = 0; //var jz = 0; //var ctnContent = "" $(clpRecordList).each(function(index, obj){ //件数,毛重,净重累加 $(obj.costcoBlDeoList).each(function(index1, obj1){ if(obj1.blNo == billNo){ js += +(obj1.ctnPackageNum); mz += +(obj1.grossWeight); } }) //js += +(obj.costcoBlDeoList[0].ctnPackageNum); //mz += +(obj.costcoBlDeoList[0].grossWeight); //jz += +(obj.costcoBlDeoList[0].ctnNetWeight); //填写箱信息 //第一个TAB页表格的数据 var ctnSizeType = obj.costcoMainDeo.sizetype; if(ctnSizeType.substring(0,1) == "2"){ ctnSizeType = "S"; }else{ ctnSizeType = "L"; } table2.append([ { name:"ctn_no", value:index+1, hiddenName: "declareCtnList["+index+"].ctn_no" }, { name:"containerNo", value:obj.costcoMainDeo.ctnNo || "", hiddenName: "declareCtnList["+index+"].containerNo" }, { name:"containerSize", value:ctnSizeType || "", hiddenName: "declareCtnList["+index+"].containerSize" }, { name:"containerWeight", value:"", hiddenName: "declareCtnList["+index+"].containerWeight" }, { name:"declareCtnId", value:"", hiddenName: "declareCtnList["+index+"].declareCtnId" } ]) }) $("#packagesNum").val(js) $("#grossWeight").val(mz) //$("#netWeight").val(jz) //$("#dec-ctn-content").html(ctnContent); // 判断海关预配数据是否与港区一致 var cusJs = 0; var cusMz = 0; var manifestRecord = eval("(" + jsonData.ManifestRecord + ")"); if(manifestRecord.Result == 1 && manifestRecord.Data.length > 0){ cusJs = manifestRecord.Data[0].PackNo; cusMz = manifestRecord.Data[0].GrossWT; if (js == cusJs && mz == cusMz) { alert("运抵与预配数据件数、毛重一致!"); } else { alert("运抵与预配件数、毛重不一致!预配数据为:件数 " + cusJs + " 毛重 " + cusMz); } } else { alert("海关预配信息为空"); } } }, error : function(data){ $("#getDataFromCLPByBillNo_btn").val("查询") alert("对不起,查询异常,请稍后再试!"); } }) } //-----------------附件上传START----------------------------------------- function uploadLogo(id, edocCode, cloudQpId){ $('#'+id).uploadify({ 'debug':false, 'fileSizeLimit' : '5000', 'formData':{'cloudQpId':cloudQpId||''}, 'swf' : 'QP/upload/uploadify.swf', 'uploader' : '/declare/uploadEdoc.action?edocCode='+edocCode, 'fileTypeExts' : '*.pdf; *.xls; *.xlsx; *.doc; *.docx', 'fileDesc':"上传", 'fileObjName':'edocFile', 'width':65, 'height':30, 'buttonText':"点击上传", 'buttonClass':"dec", 'removeTimeout' : 0.1, 'multi':false, "onSelect":function(file){ $('#'+id).uploadify('settings','formData',{'cloudQpId':cloudQpId||'', 'fileName':file.name}); }, 'onUploadStart' : function() { }, 'onUploadSuccess' : function(file, data, response){ var obj = $.parseJSON(data); if(obj.flag == "1"){ alert("上传成功"); }else if(obj.flag == "2"){ alert("上传失败:"+obj.desc); }else{ alert("上传异常"); } }, "onUploadError":function(file, errorCode, errorMsg, errorString){ alert("上传失败"); } }); } uploadLogo("edocFile_1", "00000001"); uploadLogo("edocFile_2", "00000002"); uploadLogo("edocFile_3", "00000003"); uploadLogo("edocFile_4", "00000004"); uploadLogo("edocFile_5", "00000005"); uploadLogo("edocFile_6", "00000006"); uploadLogo("edocFile_7", "00000007"); uploadLogo("edocFile_8", "00000008"); //uploadLogo("edocFile_9", "10000001"); uploadLogo("edocFile_10", "10000002"); //-----------------附件上传END-------------------------------------------